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