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