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