automate process of uploading new releases
[privoxy.git] / pcrs.c
1 const char pcrs_rcs[] = "$Id: pcrs.c,v 1.14 2001/09/09 21:41:57 oes Exp $";
2
3 /*********************************************************************
4  *
5  * File        :  $Source: /cvsroot/ijbswa/current/pcrs.c,v $
6  *
7  * Purpose     :  pcrs is a supplement to the pcre library by Philip Hazel
8  *                <ph10@cam.ac.uk> and adds Perl-style substitution. That
9  *                is, it mimics Perl's 's' operator. See pcrs(3) for details.
10  *
11  *
12  * Copyright   :  Written and Copyright (C) 2000, 2001 by Andreas S. Oesterhelt
13  *                <andreas@oesterhelt.org>
14  *
15  *                This program is free software; you can redistribute it 
16  *                and/or modify it under the terms of the GNU Lesser
17  *                General Public License (LGPL), version 2.1, which  should
18  *                be included in this distribution (see LICENSE.txt), with
19  *                the exception that the permission to replace that license
20  *                with the GNU General Public License (GPL) given in section
21  *                3 is restricted to version 2 of the GPL.
22  *
23  *                This program is distributed in the hope that it will
24  *                be useful, but WITHOUT ANY WARRANTY; without even the
25  *                implied warranty of MERCHANTABILITY or FITNESS FOR A
26  *                PARTICULAR PURPOSE.  See the license for more details.
27  *
28  *                The GNU Lesser General Public License should be included
29  *                with this file.  If not, you can view it at
30  *                http://www.gnu.org/licenses/lgpl.html
31  *                or write to the Free Software Foundation, Inc., 59
32  *                Temple Place - Suite 330, Boston, MA  02111-1307, USA.
33  *
34  * Revisions   :
35  *    $Log: pcrs.c,v $
36  *    Revision 1.14  2001/09/09 21:41:57  oes
37  *    Fixing yet another silly bug
38  *
39  *    Revision 1.13  2001/09/06 14:05:59  oes
40  *    Fixed silly bug
41  *
42  *    Revision 1.12  2001/08/18 11:35:00  oes
43  *    - Introduced pcrs_strerror()
44  *    - made some NULL arguments non-fatal
45  *    - added support for \n \r \e \b \t \f \a \0 in substitute
46  *    - made quoting adhere to standard rules
47  *    - added warning for bad backrefs
48  *    - added pcrs_execute_list()
49  *    - fixed comments
50  *    - bugfix & cosmetics
51  *
52  *    Revision 1.11  2001/08/15 15:32:03  oes
53  *     - Added support for Perl's special variables $+, $' and $`
54  *     - Improved the substitute parser
55  *     - Replaced the hard limit for the maximum number of matches
56  *       by dynamic reallocation
57  *
58  *    Revision 1.10  2001/08/05 13:13:11  jongfoster
59  *    Making parameters "const" where possible.
60  *
61  *    Revision 1.9  2001/07/18 17:27:00  oes
62  *    Changed interface; Cosmetics
63  *
64  *    Revision 1.8  2001/06/29 21:45:41  oes
65  *    Indentation, CRLF->LF, Tab-> Space
66  *
67  *    Revision 1.7  2001/06/29 13:33:04  oes
68  *    - Cleaned up, renamed and reordered functions,
69  *      improved comments
70  *    - Removed my_strsep
71  *    - Replaced globalflag with a general flags int
72  *      that holds PCRS_GLOBAL, PCRS_SUCCESS, and PCRS_TRIVIAL
73  *    - Introduced trivial option that will prevent pcrs
74  *      from honouring backreferences in the substitute,
75  *      which is useful for large substitutes that are
76  *      red in from somewhere and saves the pain of escaping
77  *      the backrefs
78  *    - Introduced convenience function pcrs_free_joblist()
79  *    - Split pcrs_make_job() into pcrs_compile(), which still
80  *      takes a complete s/// comand as argument and parses it,
81  *      and a new function pcrs_make_job, which takes the
82  *      three separate components. This should make for a
83  *      much friendlier frontend.
84  *    - Removed create_pcrs_job() which was useless
85  *    - Fixed a bug in pcrs_execute
86  *    - Success flag is now handled by pcrs instead of user
87  *
88  *    Revision 1.6  2001/06/03 19:12:45  oes
89  *    added FIXME
90  *
91  *    Revision 1.5  2001/05/29 09:50:24  jongfoster
92  *    (Fixed one int -> size_t)
93  *
94  *    Revision 1.4  2001/05/25 14:12:40  oes
95  *    Fixed bug: Empty substitutes now detected
96  *
97  *    Revision 1.3  2001/05/25 11:03:55  oes
98  *    Added sanity check for NULL jobs to pcrs_exec_substitution
99  *
100  *    Revision 1.2  2001/05/22 18:46:04  oes
101  *
102  *      Added support for PCRE_UNGREEDY behaviour to pcrs,
103  *      which is selected by the (nonstandard and therefore
104  *      capital) letter 'U' in the option string.
105  *      It causes the quantifiers to be ungreedy by default.
106  *      Appending a ? turns back to greedy (!).
107  *
108  *    Revision 1.1.1.1  2001/05/15 13:59:02  oes
109  *    Initial import of version 2.9.3 source tree
110  *
111  *
112  *********************************************************************/
113 \f
114
115 #include <pcre.h>
116 #include <string.h>
117 #include <ctype.h>
118
119 #include "pcrs.h"
120
121 const char pcrs_h_rcs[] = PCRS_H_VERSION;
122
123 /*********************************************************************
124  *
125  * Function    :  pcrs_strerror
126  *
127  * Description :  Return a string describing a given error code.
128  *             
129  * Parameters  :
130  *          1  :  error = the error code
131  *
132  * Returns     :  char * to the descriptive string
133  *
134  *********************************************************************/
135 const char *pcrs_strerror(const int error)
136 {
137    if (error < 0)
138    {
139       switch (error)
140       {
141          /* Passed-through PCRE error: */
142          case PCRE_ERROR_NOMEMORY:     return "(pcre:) No memory";
143
144          /* Shouldn't happen unless PCRE or PCRS bug, or user messed with compiled job: */
145          case PCRE_ERROR_NULL:         return "(pcre:) NULL code or subject or ovector";
146          case PCRE_ERROR_BADOPTION:    return "(pcre:) Unrecognized option bit";
147          case PCRE_ERROR_BADMAGIC:     return "(pcre:) Bad magic number in code";
148          case PCRE_ERROR_UNKNOWN_NODE: return "(pcre:) Bad node in pattern";
149
150          /* Can't happen / not passed: */
151          case PCRE_ERROR_NOSUBSTRING:  return "(pcre:) Fire in power supply"; 
152          case PCRE_ERROR_NOMATCH:      return "(pcre:) Water in power supply";
153
154          /* PCRS errors: */
155          case PCRS_ERR_NOMEM:          return "(pcrs:) No memory";
156          case PCRS_ERR_CMDSYNTAX:      return "(pcrs:) Syntax error while parsing command";
157          case PCRS_ERR_STUDY:          return "(pcrs:) PCRE error while studying the pattern";
158          case PCRS_ERR_BADJOB:         return "(pcrs:) Bad job - NULL job, pattern or substitute";
159          case PCRS_WARN_BADREF:        return "(pcrs:) Backreference out of range";
160
161          /* What's that? */
162          default:  return "Unknown error";
163       }
164    }
165    /* error >= 0: No error */
166    return "(pcrs:) Everything's just fine. Thanks for asking.";
167
168 }
169
170
171 /*********************************************************************
172  *
173  * Function    :  pcrs_parse_perl_options
174  *
175  * Description :  This function parses a string containing the options to
176  *                Perl's s/// operator. It returns an integer that is the
177  *                pcre equivalent of the symbolic optstring.
178  *                Since pcre doesn't know about Perl's 'g' (global) or pcrs',
179  *                'T' (trivial) options but pcrs needs them, the corresponding
180  *                flags are set if 'g'or 'T' is encountered.
181  *                Note: The 'T' and 'U' options do not conform to Perl.
182  *             
183  * Parameters  :
184  *          1  :  optstring = string with options in perl syntax
185  *          2  :  flags = see description
186  *
187  * Returns     :  option integer suitable for pcre 
188  *
189  *********************************************************************/
190 int pcrs_parse_perl_options(const char *optstring, int *flags)
191 {
192    size_t i;
193    int rc = 0;
194    *flags = 0;
195
196    if (NULL == optstring) return 0;
197
198    for (i=0; i < strlen(optstring); i++)
199    {
200       switch(optstring[i])
201       {
202          case 'e': break; /* ToDo ;-) */
203          case 'g': *flags |= PCRS_GLOBAL; break;
204          case 'i': rc |= PCRE_CASELESS; break;
205          case 'm': rc |= PCRE_MULTILINE; break;
206          case 'o': break;
207          case 's': rc |= PCRE_DOTALL; break;
208          case 'x': rc |= PCRE_EXTENDED; break;
209          case 'U': rc |= PCRE_UNGREEDY; break;
210            case 'T': *flags |= PCRS_TRIVIAL; break;
211          default: break;
212       }
213    }
214    return rc;
215
216 }
217
218
219 /*********************************************************************
220  *
221  * Function    :  pcrs_compile_replacement
222  *
223  * Description :  This function takes a Perl-style replacement (2nd argument
224  *                to the s/// operator and returns a compiled pcrs_substitute,
225  *                or NULL if memory allocation for the substitute structure
226  *                fails.
227  *
228  * Parameters  :
229  *          1  :  replacement = replacement part of s/// operator
230  *                              in perl syntax
231  *          2  :  trivialflag = Flag that causes backreferences to be
232  *                              ignored.
233  *          3  :  capturecount = Number of capturing subpatterns in
234  *                               the pattern. Needed for $+ handling.
235  *          4  :  errptr = pointer to an integer in which error
236  *                         conditions can be returned.
237  *
238  * Returns     :  pcrs_substitute data structure, or NULL if an
239  *                error is encountered. In that case, *errptr has
240  *                the reason.
241  *
242  *********************************************************************/
243 pcrs_substitute *pcrs_compile_replacement(const char *replacement, int trivialflag, int capturecount, int *errptr)
244 {
245    int length, i, k, l, quoted;
246    char *text;
247    pcrs_substitute *r;
248
249    i = k = l = quoted = 0;
250
251    /*
252     * Sanity check
253     */
254    if (NULL == replacement)
255    {
256       replacement = "";
257    }
258
259    /*
260     * Get memory or fail
261     */
262    if (NULL == (r = (pcrs_substitute *)malloc(sizeof(pcrs_substitute))))
263    {
264       *errptr = PCRS_ERR_NOMEM;
265       return NULL;
266    }
267    memset(r, '\0', sizeof(pcrs_substitute));
268
269    length = strlen(replacement);
270
271    if (NULL == (text = (char *)malloc(length + 1)))
272    {
273       free(r);
274       *errptr = PCRS_ERR_NOMEM;
275       return NULL;
276    }
277    memset(text, '\0', length + 1);
278    
279
280    /*
281     * In trivial mode, just copy the substitute text
282     */
283    if (trivialflag)
284    {
285       text = strncpy(text, replacement, length + 1);
286       k = length;
287    }
288
289    /*
290     * Else, parse, cut out and record all backreferences
291     */
292    else
293    {
294       while(i < length)
295       {
296          /* Quoting */
297          if (replacement[i] == '\\')
298          {
299             if (quoted)
300             {
301                text[k++] = replacement[i++];
302                quoted = 0;
303             }
304             else
305             {
306                if (replacement[i+1] && strchr("tnrfae0", replacement[i+1]))
307                {
308                   switch(replacement[++i])
309                   {
310                   case 't':
311                      text[k++] = '\t';
312                      break;
313                   case 'n':
314                      text[k++] = '\n';
315                      break;
316                   case 'r':
317                      text[k++] = '\r';
318                      break;
319                   case 'f':
320                      text[k++] = '\f';
321                      break;
322                   case 'a':
323                      text[k++] = '\a';
324                      break;
325                   case 'e':
326                      text[k++] = 27;
327                      break;
328                   case '0':
329                      text[k++] = '\0';
330                      break;
331                   }
332                   i++;
333                }
334                else
335                {
336                   quoted = 1;
337                   i++;
338                }
339             }
340             continue;
341          }
342
343          /* Backreferences */
344          if (replacement[i] == '$' && !quoted && i < length - 1)
345          {
346             char *symbol, symbols[] = "'`+&";
347             r->block_length[l] = k - r->block_offset[l];
348
349             /* Numerical backreferences */
350             if (isdigit((int) replacement[i + 1]))
351             {
352                while (i < length && isdigit((int) replacement[++i]))
353                {
354                   r->backref[l] = r->backref[l] * 10 + replacement[i] - 48;
355                }
356                if (r->backref[l] > capturecount)
357                {
358                   *errptr = PCRS_WARN_BADREF;
359                }
360             }
361
362             /* Symbolic backreferences: */
363             else if (NULL != (symbol = strchr(symbols, replacement[i + 1])))
364             {
365                
366                if (symbol - symbols == 2) /* $+ */
367                {
368                   r->backref[l] = capturecount;
369                }
370                else if (symbol - symbols == 3) /* $& */
371                {
372                   r->backref[l] = 0;
373                }
374                else /* $' or $` */
375                {
376                   r->backref[l] = PCRS_MAX_SUBMATCHES + 1 - (symbol - symbols);
377                }
378                i += 2;
379             }
380
381             /* Invalid backref -> plain '$' */
382             else
383             {
384                goto plainchar;
385             }
386
387             /* Valid and in range? -> record */
388             if (r->backref[l] < PCRS_MAX_SUBMATCHES + 2)
389             {
390                r->backref_count[r->backref[l]] += 1;
391                r->block_offset[++l] = k;
392             }
393             else
394             {
395                *errptr = PCRS_WARN_BADREF;
396             }   
397             continue;
398          }
399          
400 plainchar:
401          /* Plain chars are copied */
402          text[k++] = replacement[i++];
403          quoted = 0;
404       }
405    } /* -END- if (!trivialflag) */
406
407    /*
408     * Finish & return
409     */
410    r->text = text;
411    r->backrefs = l;
412    r->block_length[l] = k - r->block_offset[l];
413
414    return r;
415
416 }
417
418
419 /*********************************************************************
420  *
421  * Function    :  pcrs_free_job
422  *
423  * Description :  Frees the memory used by a pcrs_job struct and its
424  *                dependant structures.
425  *
426  * Parameters  :
427  *          1  :  job = pointer to the pcrs_job structure to be freed
428  *
429  * Returns     :  a pointer to the next job, if there was any, or
430  *                NULL otherwise. 
431  *
432  *********************************************************************/
433 pcrs_job *pcrs_free_job(pcrs_job *job)
434 {
435    pcrs_job *next;
436
437    if (job == NULL)
438    {
439       return NULL;
440    }
441    else
442    {
443       next = job->next;
444       if (job->pattern != NULL) free(job->pattern);
445       if (job->hints != NULL) free(job->hints);
446       if (job->substitute != NULL)
447       {
448          if (job->substitute->text != NULL) free(job->substitute->text);
449          free(job->substitute);
450       }
451       free(job);
452    }
453    return next;
454
455 }
456
457
458 /*********************************************************************
459  *
460  * Function    :  pcrs_free_joblist
461  *
462  * Description :  Iterates through a chained list of pcrs_job's and
463  *                frees them using pcrs_free_job.
464  *
465  * Parameters  :
466  *          1  :  joblist = pointer to the first pcrs_job structure to
467  *                be freed
468  *
469  * Returns     :  N/A
470  *
471  *********************************************************************/
472 void pcrs_free_joblist(pcrs_job *joblist)
473 {
474    while ( NULL != (joblist = pcrs_free_job(joblist)) ) {};
475
476    return;
477
478 }
479
480
481 /*********************************************************************
482  *
483  * Function    :  pcrs_compile_command
484  *
485  * Description :  Parses a string with a Perl-style s/// command, 
486  *                calls pcrs_compile, and returns a corresponding
487  *                pcrs_job, or NULL if parsing or compiling the job
488  *                fails.
489  *
490  * Parameters  :
491  *          1  :  command = string with perl-style s/// command
492  *          2  :  errptr = pointer to an integer in which error
493  *                         conditions can be returned.
494  *
495  * Returns     :  a corresponding pcrs_job data structure, or NULL
496  *                if an error was encountered. In that case, *errptr
497  *                has the reason.
498  *
499  *********************************************************************/
500 pcrs_job *pcrs_compile_command(const char *command, int *errptr)
501 {
502    int i, k, l, limit, quoted = FALSE;
503    char delimiter;
504    char *tokens[4];   
505    pcrs_job *newjob;
506    
507    i = k = l = 0;
508    
509    /*
510     * Tokenize the perl command
511     */
512    limit = strlen(command);
513    if (limit < 4)
514    {
515       *errptr = PCRS_ERR_CMDSYNTAX;
516       return NULL;
517    }
518    else
519    {
520       delimiter = command[1];
521    }
522
523    tokens[l] = (char *) malloc(limit + 1);
524
525    for (i=0; i <= limit; i++)
526    {
527       
528       if (command[i] == delimiter && !quoted)
529       {
530          if (l == 3)
531          {
532             l = -1;
533             break;
534          }
535          tokens[0][k++] = '\0';
536          tokens[++l] = tokens[0] + k;
537          continue;
538       }
539       
540       else if (command[i] == '\\' && !quoted)
541       {
542          quoted = TRUE;
543          if (command[i+1] == delimiter) continue;
544       }
545       else
546       {
547          quoted = FALSE;
548       }
549       tokens[0][k++] = command[i];
550    }
551
552    /*
553     * Syntax error ?
554     */
555    if (l != 3)
556    {
557       *errptr = PCRS_ERR_CMDSYNTAX;
558       free(tokens[0]);
559       return NULL;
560    }
561    
562    newjob = pcrs_compile(tokens[1], tokens[2], tokens[3], errptr);
563    free(tokens[0]);
564    return newjob;
565    
566 }
567
568
569 /*********************************************************************
570  *
571  * Function    :  pcrs_compile
572  *
573  * Description :  Takes the three arguments to a perl s/// command
574  *                and compiles a pcrs_job structure from them.
575  *
576  * Parameters  :
577  *          1  :  pattern = string with perl-style pattern
578  *          2  :  substitute = string with perl-style substitute
579  *          3  :  options = string with perl-style options
580  *          4  :  errptr = pointer to an integer in which error
581  *                         conditions can be returned.
582  *
583  * Returns     :  a corresponding pcrs_job data structure, or NULL
584  *                if an error was encountered. In that case, *errptr
585  *                has the reason.
586  *
587  *********************************************************************/
588 pcrs_job *pcrs_compile(const char *pattern, const char *substitute, const char *options, int *errptr)
589 {
590    pcrs_job *newjob;
591    int flags;
592    int capturecount;
593    const char *error;
594
595    *errptr = 0;
596
597    /* 
598     * Handle NULL arguments
599     */
600    if (pattern == NULL) pattern = "";
601    if (substitute == NULL) substitute = "";
602
603
604    /* 
605     * Get and init memory
606     */
607    if (NULL == (newjob = (pcrs_job *)malloc(sizeof(pcrs_job))))
608    {
609       *errptr = PCRS_ERR_NOMEM;
610       return NULL;
611    }
612    memset(newjob, '\0', sizeof(pcrs_job));
613
614
615    /*
616     * Evaluate the options
617     */
618    newjob->options = pcrs_parse_perl_options(options, &flags);
619    newjob->flags = flags;
620
621
622    /*
623     * Compile the pattern
624     */
625    newjob->pattern = pcre_compile(pattern, newjob->options, &error, errptr, NULL);
626    if (newjob->pattern == NULL)
627    {
628       pcrs_free_job(newjob);
629       return NULL;
630    }
631
632
633    /*
634     * Generate hints. This has little overhead, since the
635     * hints will be NULL for a boring pattern anyway.
636     */
637    newjob->hints = pcre_study(newjob->pattern, 0, &error);
638    if (error != NULL)
639    {
640       *errptr = PCRS_ERR_STUDY;
641       pcrs_free_job(newjob);
642       return NULL;
643    }
644  
645
646    /* 
647     * Determine the number of capturing subpatterns. 
648     * This is needed for handling $+ in the substitute.
649     */
650    if (0 > (*errptr = pcre_fullinfo(newjob->pattern, newjob->hints, PCRE_INFO_CAPTURECOUNT, &capturecount)))
651    {
652       pcrs_free_job(newjob);
653       return NULL;
654    }
655  
656
657    /*
658     * Compile the substitute
659     */
660    if (NULL == (newjob->substitute = pcrs_compile_replacement(substitute, newjob->flags & PCRS_TRIVIAL, capturecount, errptr)))
661    {
662       pcrs_free_job(newjob);
663       return NULL;
664    }
665  
666    return newjob;
667
668 }
669
670
671 /*********************************************************************
672  *
673  * Function    :  pcrs_execute_list
674  *
675  * Description :  This is a multiple job wrapper for pcrs_execute().
676  *                Apply the regular substitutions defined by the jobs in
677  *                the joblist to the subject.
678  *                The subject itself is left untouched, memory for the result
679  *                is malloc()ed and it is the caller's responsibility to free
680  *                the result when it's no longer needed.
681  *
682  * Parameters  :
683  *          1  :  joblist = the chained list of pcrs_jobs to be executed
684  *          2  :  subject = the subject string
685  *          3  :  subject_length = the subject's length 
686  *                INCLUDING the terminating zero, if string!
687  *          4  :  result = char** for returning  the result 
688  *          5  :  result_length = size_t* for returning the result's length
689  *
690  * Returns     :  On success, the number of substitutions that were made.
691  *                 May be > 1 if job->flags contained PCRS_GLOBAL
692  *                On failiure, the (negative) pcre error code describing the
693  *                 failiure, which may be translated to text using pcrs_strerror().
694  *
695  *********************************************************************/
696 int pcrs_execute_list(pcrs_job *joblist, char *subject, size_t subject_length, char **result, size_t *result_length)
697 {
698    pcrs_job *job;
699    char *old, *new;
700    int hits, total_hits;
701  
702    old = subject;
703    *result_length = subject_length;
704    hits = total_hits = 0;
705
706    for (job = joblist; job != NULL; job = job->next)
707    {
708       hits = pcrs_execute(job, old, *result_length, &new, result_length);
709
710       if (old != subject) free(old);
711
712       if (hits < 0)
713       {
714          return(hits);
715       }
716       else
717       {
718          total_hits += hits;
719          old = new;
720       }
721    }
722
723    *result = new;
724    return(total_hits);
725
726 }
727
728
729 /*********************************************************************
730  *
731  * Function    :  pcrs_execute
732  *
733  * Description :  Apply the regular substitution defined by the job to the
734  *                subject.
735  *                The subject itself is left untouched, memory for the result
736  *                is malloc()ed and it is the caller's responsibility to free
737  *                the result when it's no longer needed.
738  *
739  * Parameters  :
740  *          1  :  job = the pcrs_job to be executed
741  *          2  :  subject = the subject (== original) string
742  *          3  :  subject_length = the subject's length 
743  *                INCLUDING the terminating zero, if string!
744  *          4  :  result = char** for returning  the result 
745  *          5  :  result_length = size_t* for returning the result's length
746  *
747  * Returns     :  On success, the number of substitutions that were made.
748  *                 May be > 1 if job->flags contained PCRS_GLOBAL
749  *                On failiure, the (negative) pcre error code describing the
750  *                 failiure, which may be translated to text using pcrs_strerror().
751  *
752  *********************************************************************/
753 int pcrs_execute(pcrs_job *job, char *subject, size_t subject_length, char **result, size_t *result_length)
754 {
755    int offsets[3 * PCRS_MAX_SUBMATCHES],
756        offset, i, k,
757        matches_found,
758        newsize,
759        submatches,
760        max_matches = PCRS_MAX_MATCH_INIT;
761    pcrs_match *matches, *dummy;
762    char *result_offset;
763
764    offset = i = k = 0;
765
766    /* 
767     * Sanity check & memory allocation
768     */
769    if (job == NULL || job->pattern == NULL || job->substitute == NULL)
770    {
771       *result = NULL;
772       return(PCRS_ERR_BADJOB);
773    }
774
775    if (NULL == (matches = (pcrs_match *)malloc(max_matches * sizeof(pcrs_match))))
776    {
777       *result = NULL;
778       return(PCRS_ERR_NOMEM);
779    }
780    memset(matches, '\0', max_matches * sizeof(pcrs_match));
781
782
783    /*
784     * Find the pattern and calculate the space
785     * requirements for the result
786     */
787    newsize=subject_length;
788
789    while ((submatches = pcre_exec(job->pattern, job->hints, subject, subject_length, offset, 0, offsets, 3 * PCRS_MAX_SUBMATCHES)) > 0)
790    {
791       job->flags |= PCRS_SUCCESS;
792       matches[i].submatches = submatches;
793
794       for (k=0; k < submatches; k++)
795       {
796          matches[i].submatch_offset[k] = offsets[2 * k];
797
798          /* Note: Non-found optional submatches have length -1-(-1)==0 */
799          matches[i].submatch_length[k] = offsets[2 * k + 1] - offsets[2 * k]; 
800
801          /* reserve mem for each submatch as often as it is ref'd */
802          newsize += matches[i].submatch_length[k] * job->substitute->backref_count[k]; 
803       }
804       /* plus replacement text size minus match text size */
805       newsize += strlen(job->substitute->text) - matches[i].submatch_length[0]; 
806
807       /* chunk before match */
808       matches[i].submatch_offset[PCRS_MAX_SUBMATCHES] = 0;
809       matches[i].submatch_length[PCRS_MAX_SUBMATCHES] = offsets[0];
810       newsize += offsets[0] * job->substitute->backref_count[PCRS_MAX_SUBMATCHES];
811
812       /* chunk after match */
813       matches[i].submatch_offset[PCRS_MAX_SUBMATCHES + 1] = offsets[1];
814       matches[i].submatch_length[PCRS_MAX_SUBMATCHES + 1] = subject_length - offsets[1] - 1;
815       newsize += (subject_length - offsets[1]) * job->substitute->backref_count[PCRS_MAX_SUBMATCHES + 1];
816
817       /* Storage for matches exhausted? -> Extend! */
818       if (++i >= max_matches)
819       {
820          max_matches *= PCRS_MAX_MATCH_GROW;
821          if (NULL == (dummy = (pcrs_match *)realloc(matches, max_matches * sizeof(pcrs_match))))
822          {
823             free(matches);
824             *result = NULL;
825             return(PCRS_ERR_NOMEM);
826          }
827          matches = dummy;
828       }
829
830       /* Non-global search or limit reached? */
831       if (!(job->flags & PCRS_GLOBAL)) break;
832
833       /* Don't loop on empty matches */
834       if (offsets[1] == offset)
835          if (offset < subject_length)
836             offset++;
837          else
838             break;
839       /* Go find the next one */
840       else
841          offset = offsets[1];
842    }
843    /* Pass pcre error through if (bad) failiure */
844    if (submatches < PCRE_ERROR_NOMATCH)
845    {
846       free(matches);
847       return submatches;   
848    }
849    matches_found = i;
850
851
852    /* 
853     * Get memory for the result
854     */
855    if ((*result = (char *)malloc(newsize)) == NULL)   /* must be free()d by caller */
856    {
857       free(matches);
858       return PCRS_ERR_NOMEM;
859    }
860
861
862    /* 
863     * Replace
864     */
865    offset = 0;
866    result_offset = *result;
867
868    for (i=0; i < matches_found; i++)
869    {
870       /* copy the chunk preceding the match */
871       memcpy(result_offset, subject + offset, matches[i].submatch_offset[0] - offset); 
872       result_offset += matches[i].submatch_offset[0] - offset;
873
874       /* For every segment of the substitute.. */
875       for (k=0; k <= job->substitute->backrefs; k++)
876       {
877          /* ...copy its text.. */
878          memcpy(result_offset, job->substitute->text + job->substitute->block_offset[k], job->substitute->block_length[k]);
879          result_offset += job->substitute->block_length[k];
880
881          /* ..plus, if it's not the last chunk, i.e.: There *is* a backref.. */
882          if (k != job->substitute->backrefs
883              /* ..in legal range.. */
884              && job->substitute->backref[k] < PCRS_MAX_SUBMATCHES + 2
885              /* ..and referencing a nonempty match.. */
886              && matches[i].submatch_length[job->substitute->backref[k]] > 0)
887          {
888             /* ..copy the submatch that is ref'd. */
889             memcpy(
890                result_offset,
891                subject + matches[i].submatch_offset[job->substitute->backref[k]],
892                matches[i].submatch_length[job->substitute->backref[k]]
893             );
894             result_offset += matches[i].submatch_length[job->substitute->backref[k]];
895          }
896       }
897       offset =  matches[i].submatch_offset[0] + matches[i].submatch_length[0];
898    }
899
900    /* Copy the rest. */
901    memcpy(result_offset, subject + offset, subject_length - offset);
902
903    *result_length = newsize;
904    free(matches);
905    return matches_found;
906
907 }
908
909
910 /*
911   Local Variables:
912   tab-width: 3
913   end:
914 */