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