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