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