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