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