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