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