Several changes from Debian package 3.0.12 to 3.0.19-1.
[privoxy.git] / pcrs.c
1 const char pcrs_rcs[] = "$Id: pcrs.c,v 1.37 2011/04/19 13:00:47 fabiankeil Exp $";
2 /*********************************************************************
3  *
4  * File        :  $Source: /cvsroot/ijbswa/current/pcrs.c,v $
5  *
6  * Purpose     :  pcrs is a supplement to the pcre library by Philip Hazel
7  *                <ph10@cam.ac.uk> and adds Perl-style substitution. That
8  *                is, it mimics Perl's 's' operator. See pcrs(3) for details.
9  *
10  *                WARNING: This file contains additional functions and bug
11  *                fixes that aren't part of the latest official pcrs package
12  *                (which apparently is no longer maintained).
13  *
14  * Copyright   :  Written and Copyright (C) 2000, 2001 by Andreas S. Oesterhelt
15  *                <andreas@oesterhelt.org>
16  *
17  *                Copyright (C) 2006, 2007 Fabian Keil <fk@fabiankeil.de>
18  *
19  *                This program is free software; you can redistribute it
20  *                and/or modify it under the terms of the GNU Lesser
21  *                General Public License (LGPL), version 2.1, which  should
22  *                be included in this distribution (see LICENSE.txt), with
23  *                the exception that the permission to replace that license
24  *                with the GNU General Public License (GPL) given in section
25  *                3 is restricted to version 2 of the GPL.
26  *
27  *                This program is distributed in the hope that it will
28  *                be useful, but WITHOUT ANY WARRANTY; without even the
29  *                implied warranty of MERCHANTABILITY or FITNESS FOR A
30  *                PARTICULAR PURPOSE.  See the license for more details.
31  *
32  *                The GNU Lesser General Public License should be included
33  *                with this file.  If not, you can view it at
34  *                http://www.gnu.org/licenses/lgpl.html
35  *                or write to the Free Software Foundation, Inc., 59
36  *                Temple Place - Suite 330, Boston, MA  02111-1307, USA.
37  *
38  *********************************************************************/
39
40
41 #include <string.h>
42 #include <ctype.h>
43 #include <assert.h>
44
45 /*
46  * Include project.h just so that the right pcre.h gets
47  * included from there
48  */
49 #include "project.h"
50
51 /* For snprintf only */
52 #include "miscutil.h"
53 /* For xtoi */
54 #include "encode.h"
55
56 #include "pcrs.h"
57
58 const char pcrs_h_rcs[] = PCRS_H_VERSION;
59
60 /*
61  * Internal prototypes
62  */
63
64 static int              pcrs_parse_perl_options(const char *optstring, int *flags);
65 static pcrs_substitute *pcrs_compile_replacement(const char *replacement, int trivialflag,
66                         int capturecount, int *errptr);
67 static int              is_hex_sequence(const char *sequence);
68
69 /*********************************************************************
70  *
71  * Function    :  pcrs_strerror
72  *
73  * Description :  Return a string describing a given error code.
74  *
75  * Parameters  :
76  *          1  :  error = the error code
77  *
78  * Returns     :  char * to the descriptive string
79  *
80  *********************************************************************/
81 const char *pcrs_strerror(const int error)
82 {
83    if (error != 0)
84    {
85       switch (error)
86       {
87          /* Passed-through PCRE error: */
88          case PCRE_ERROR_NOMEMORY:     return "(pcre:) No memory";
89
90          /* Shouldn't happen unless PCRE or PCRS bug, or user messed with compiled job: */
91          case PCRE_ERROR_NULL:         return "(pcre:) NULL code or subject or ovector";
92          case PCRE_ERROR_BADOPTION:    return "(pcre:) Unrecognized option bit";
93          case PCRE_ERROR_BADMAGIC:     return "(pcre:) Bad magic number in code";
94          case PCRE_ERROR_UNKNOWN_NODE: return "(pcre:) Bad node in pattern";
95
96          /* Can't happen / not passed: */
97          case PCRE_ERROR_NOSUBSTRING:  return "(pcre:) Fire in power supply";
98          case PCRE_ERROR_NOMATCH:      return "(pcre:) Water in power supply";
99
100 #ifdef PCRE_ERROR_MATCHLIMIT
101          /*
102           * Only reported by PCRE versions newer than our own.
103           */
104          case PCRE_ERROR_MATCHLIMIT:   return "(pcre:) Match limit reached";
105 #endif /* def PCRE_ERROR_MATCHLIMIT */
106
107          /* PCRS errors: */
108          case PCRS_ERR_NOMEM:          return "(pcrs:) No memory";
109          case PCRS_ERR_CMDSYNTAX:      return "(pcrs:) Syntax error while parsing command";
110          case PCRS_ERR_STUDY:          return "(pcrs:) PCRE error while studying the pattern";
111          case PCRS_ERR_BADJOB:         return "(pcrs:) Bad job - NULL job, pattern or substitute";
112          case PCRS_WARN_BADREF:        return "(pcrs:) Backreference out of range";
113          case PCRS_WARN_TRUNCATION:
114             return "(pcrs:) At least one variable was too big and has been truncated before compilation";
115
116          /*
117           * XXX: With the exception of PCRE_ERROR_MATCHLIMIT we
118           * only catch PCRE errors that can happen with our internal
119           * version. If Privoxy is linked against a newer
120           * PCRE version all bets are off ...
121           */
122          default:  return "Unknown error. Privoxy out of sync with PCRE?";
123       }
124    }
125    /* error >= 0: No error */
126    return "(pcrs:) Everything's just fine. Thanks for asking.";
127
128 }
129
130
131 /*********************************************************************
132  *
133  * Function    :  pcrs_parse_perl_options
134  *
135  * Description :  This function parses a string containing the options to
136  *                Perl's s/// operator. It returns an integer that is the
137  *                pcre equivalent of the symbolic optstring.
138  *                Since pcre doesn't know about Perl's 'g' (global) or pcrs',
139  *                'T' (trivial) options but pcrs needs them, the corresponding
140  *                flags are set if 'g'or 'T' is encountered.
141  *                Note: The 'T' and 'U' options do not conform to Perl.
142  *
143  * Parameters  :
144  *          1  :  optstring = string with options in perl syntax
145  *          2  :  flags = see description
146  *
147  * Returns     :  option integer suitable for pcre
148  *
149  *********************************************************************/
150 static int pcrs_parse_perl_options(const char *optstring, int *flags)
151 {
152    size_t i;
153    int rc = 0;
154    *flags = 0;
155
156    if (NULL == optstring) return 0;
157
158    for (i = 0; i < strlen(optstring); i++)
159    {
160       switch(optstring[i])
161       {
162          case 'e': break; /* ToDo ;-) */
163          case 'g': *flags |= PCRS_GLOBAL; break;
164          case 'i': rc |= PCRE_CASELESS; break;
165          case 'm': rc |= PCRE_MULTILINE; break;
166          case 'o': break;
167          case 's': rc |= PCRE_DOTALL; break;
168          case 'x': rc |= PCRE_EXTENDED; break;
169          case 'U': rc |= PCRE_UNGREEDY; break;
170          case 'T': *flags |= PCRS_TRIVIAL; break;
171          default: break;
172       }
173    }
174    return rc;
175
176 }
177
178
179 /*********************************************************************
180  *
181  * Function    :  pcrs_compile_replacement
182  *
183  * Description :  This function takes a Perl-style replacement (2nd argument
184  *                to the s/// operator and returns a compiled pcrs_substitute,
185  *                or NULL if memory allocation for the substitute structure
186  *                fails.
187  *
188  * Parameters  :
189  *          1  :  replacement = replacement part of s/// operator
190  *                              in perl syntax
191  *          2  :  trivialflag = Flag that causes backreferences to be
192  *                              ignored.
193  *          3  :  capturecount = Number of capturing subpatterns in
194  *                               the pattern. Needed for $+ handling.
195  *          4  :  errptr = pointer to an integer in which error
196  *                         conditions can be returned.
197  *
198  * Returns     :  pcrs_substitute data structure, or NULL if an
199  *                error is encountered. In that case, *errptr has
200  *                the reason.
201  *
202  *********************************************************************/
203 static pcrs_substitute *pcrs_compile_replacement(const char *replacement, int trivialflag, int capturecount, int *errptr)
204 {
205    int i, k, l, quoted;
206    size_t length;
207    char *text;
208    pcrs_substitute *r;
209
210    i = k = l = quoted = 0;
211
212    /*
213     * Sanity check
214     */
215    if (NULL == replacement)
216    {
217       replacement = "";
218    }
219
220    /*
221     * Get memory or fail
222     */
223    if (NULL == (r = (pcrs_substitute *)malloc(sizeof(pcrs_substitute))))
224    {
225       *errptr = PCRS_ERR_NOMEM;
226       return NULL;
227    }
228    memset(r, '\0', sizeof(pcrs_substitute));
229
230    length = strlen(replacement);
231
232    if (NULL == (text = (char *)malloc(length + 1)))
233    {
234       free(r);
235       *errptr = PCRS_ERR_NOMEM;
236       return NULL;
237    }
238    memset(text, '\0', length + 1);
239
240
241    /*
242     * In trivial mode, just copy the substitute text
243     */
244    if (trivialflag)
245    {
246       text = strncpy(text, replacement, length + 1);
247       k = (int)length;
248    }
249
250    /*
251     * Else, parse, cut out and record all backreferences
252     */
253    else
254    {
255       while (i < (int)length)
256       {
257          /* Quoting */
258          if (replacement[i] == '\\')
259          {
260             if (quoted)
261             {
262                text[k++] = replacement[i++];
263                quoted = 0;
264             }
265             else
266             {
267                if (replacement[i+1] && strchr("tnrfae0", replacement[i+1]))
268                {
269                   switch (replacement[++i])
270                   {
271                   case 't':
272                      text[k++] = '\t';
273                      break;
274                   case 'n':
275                      text[k++] = '\n';
276                      break;
277                   case 'r':
278                      text[k++] = '\r';
279                      break;
280                   case 'f':
281                      text[k++] = '\f';
282                      break;
283                   case 'a':
284                      text[k++] = 7;
285                      break;
286                   case 'e':
287                      text[k++] = 27;
288                      break;
289                   case '0':
290                      text[k++] = '\0';
291                      break;
292                   }
293                   i++;
294                }
295                else if (is_hex_sequence(&replacement[i]))
296                {
297                   /*
298                    * Replace a hex sequence with a single
299                    * character with the sequence's ascii value.
300                    * e.g.: '\x7e' => '~'
301                    */
302                   const int ascii_value = xtoi(&replacement[i+2]);
303
304                   assert(ascii_value > 0);
305                   assert(ascii_value < 256);
306                   text[k++] = (char)ascii_value;
307                   i += 4;
308                }
309                else
310                {
311                   quoted = 1;
312                   i++;
313                }
314             }
315             continue;
316          }
317
318          /* Backreferences */
319          if (replacement[i] == '$' && !quoted && i < (int)(length - 1))
320          {
321             char *symbol, symbols[] = "'`+&";
322             r->block_length[l] = (size_t)(k - r->block_offset[l]);
323
324             /* Numerical backreferences */
325             if (isdigit((int)replacement[i + 1]))
326             {
327                while (i < (int)length && isdigit((int)replacement[++i]))
328                {
329                   r->backref[l] = r->backref[l] * 10 + replacement[i] - 48;
330                }
331                if (r->backref[l] > capturecount)
332                {
333                   *errptr = PCRS_WARN_BADREF;
334                }
335             }
336
337             /* Symbolic backreferences: */
338             else if (NULL != (symbol = strchr(symbols, replacement[i + 1])))
339             {
340
341                if (symbol - symbols == 2) /* $+ */
342                {
343                   r->backref[l] = capturecount;
344                }
345                else if (symbol - symbols == 3) /* $& */
346                {
347                   r->backref[l] = 0;
348                }
349                else /* $' or $` */
350                {
351                   r->backref[l] = (int)(PCRS_MAX_SUBMATCHES + 1 - (symbol - symbols));
352                }
353                i += 2;
354             }
355
356             /* Invalid backref -> plain '$' */
357             else
358             {
359                goto plainchar;
360             }
361
362             /* Valid and in range? -> record */
363             if (r->backref[l] < PCRS_MAX_SUBMATCHES + 2)
364             {
365                r->backref_count[r->backref[l]] += 1;
366                r->block_offset[++l] = k;
367             }
368             else
369             {
370                *errptr = PCRS_WARN_BADREF;
371             }
372             continue;
373          }
374
375 plainchar:
376          /* Plain chars are copied */
377          text[k++] = replacement[i++];
378          quoted = 0;
379       }
380    } /* -END- if (!trivialflag) */
381
382    /*
383     * Finish & return
384     */
385    r->text = text;
386    r->backrefs = l;
387    r->length = (size_t)k;
388    r->block_length[l] = (size_t)(k - r->block_offset[l]);
389
390    return r;
391
392 }
393
394
395 /*********************************************************************
396  *
397  * Function    :  pcrs_free_job
398  *
399  * Description :  Frees the memory used by a pcrs_job struct and its
400  *                dependent structures.
401  *
402  * Parameters  :
403  *          1  :  job = pointer to the pcrs_job structure to be freed
404  *
405  * Returns     :  a pointer to the next job, if there was any, or
406  *                NULL otherwise.
407  *
408  *********************************************************************/
409 pcrs_job *pcrs_free_job(pcrs_job *job)
410 {
411    pcrs_job *next;
412
413    if (job == NULL)
414    {
415       return NULL;
416    }
417    else
418    {
419       next = job->next;
420       if (job->pattern != NULL) free(job->pattern);
421       if (job->hints != NULL) free(job->hints);
422       if (job->substitute != NULL)
423       {
424          if (job->substitute->text != NULL) free(job->substitute->text);
425          free(job->substitute);
426       }
427       free(job);
428    }
429    return next;
430
431 }
432
433
434 /*********************************************************************
435  *
436  * Function    :  pcrs_free_joblist
437  *
438  * Description :  Iterates through a chained list of pcrs_job's and
439  *                frees them using pcrs_free_job.
440  *
441  * Parameters  :
442  *          1  :  joblist = pointer to the first pcrs_job structure to
443  *                be freed
444  *
445  * Returns     :  N/A
446  *
447  *********************************************************************/
448 void pcrs_free_joblist(pcrs_job *joblist)
449 {
450    while ( NULL != (joblist = pcrs_free_job(joblist)) ) {};
451
452    return;
453
454 }
455
456
457 /*********************************************************************
458  *
459  * Function    :  pcrs_compile_command
460  *
461  * Description :  Parses a string with a Perl-style s/// command,
462  *                calls pcrs_compile, and returns a corresponding
463  *                pcrs_job, or NULL if parsing or compiling the job
464  *                fails.
465  *
466  * Parameters  :
467  *          1  :  command = string with perl-style s/// command
468  *          2  :  errptr = pointer to an integer in which error
469  *                         conditions can be returned.
470  *
471  * Returns     :  a corresponding pcrs_job data structure, or NULL
472  *                if an error was encountered. In that case, *errptr
473  *                has the reason.
474  *
475  *********************************************************************/
476 pcrs_job *pcrs_compile_command(const char *command, int *errptr)
477 {
478    int i, k, l, quoted = FALSE;
479    size_t limit;
480    char delimiter;
481    char *tokens[4];
482    pcrs_job *newjob;
483
484    k = l = 0;
485
486    /*
487     * Tokenize the perl command
488     */
489    limit = strlen(command);
490    if (limit < 4)
491    {
492       *errptr = PCRS_ERR_CMDSYNTAX;
493       return NULL;
494    }
495    else
496    {
497       delimiter = command[1];
498    }
499
500    tokens[l] = (char *) malloc(limit + 1);
501
502    for (i = 0; i <= (int)limit; i++)
503    {
504
505       if (command[i] == delimiter && !quoted)
506       {
507          if (l == 3)
508          {
509             l = -1;
510             break;
511          }
512          tokens[0][k++] = '\0';
513          tokens[++l] = tokens[0] + k;
514          continue;
515       }
516
517       else if (command[i] == '\\' && !quoted)
518       {
519          quoted = TRUE;
520          if (command[i+1] == delimiter) continue;
521       }
522       else
523       {
524          quoted = FALSE;
525       }
526       tokens[0][k++] = command[i];
527    }
528
529    /*
530     * Syntax error ?
531     */
532    if (l != 3)
533    {
534       *errptr = PCRS_ERR_CMDSYNTAX;
535       free(tokens[0]);
536       return NULL;
537    }
538
539    newjob = pcrs_compile(tokens[1], tokens[2], tokens[3], errptr);
540    free(tokens[0]);
541    return newjob;
542
543 }
544
545
546 /*********************************************************************
547  *
548  * Function    :  pcrs_compile
549  *
550  * Description :  Takes the three arguments to a perl s/// command
551  *                and compiles a pcrs_job structure from them.
552  *
553  * Parameters  :
554  *          1  :  pattern = string with perl-style pattern
555  *          2  :  substitute = string with perl-style substitute
556  *          3  :  options = string with perl-style options
557  *          4  :  errptr = pointer to an integer in which error
558  *                         conditions can be returned.
559  *
560  * Returns     :  a corresponding pcrs_job data structure, or NULL
561  *                if an error was encountered. In that case, *errptr
562  *                has the reason.
563  *
564  *********************************************************************/
565 pcrs_job *pcrs_compile(const char *pattern, const char *substitute, const char *options, int *errptr)
566 {
567    pcrs_job *newjob;
568    int flags;
569    int capturecount;
570    const char *error;
571
572    *errptr = 0;
573
574    /*
575     * Handle NULL arguments
576     */
577    if (pattern == NULL) pattern = "";
578    if (substitute == NULL) substitute = "";
579
580
581    /*
582     * Get and init memory
583     */
584    if (NULL == (newjob = (pcrs_job *)malloc(sizeof(pcrs_job))))
585    {
586       *errptr = PCRS_ERR_NOMEM;
587       return NULL;
588    }
589    memset(newjob, '\0', sizeof(pcrs_job));
590
591
592    /*
593     * Evaluate the options
594     */
595    newjob->options = pcrs_parse_perl_options(options, &flags);
596    newjob->flags = flags;
597
598
599    /*
600     * Compile the pattern
601     */
602    newjob->pattern = pcre_compile(pattern, newjob->options, &error, errptr, NULL);
603    if (newjob->pattern == NULL)
604    {
605       pcrs_free_job(newjob);
606       return NULL;
607    }
608
609
610    /*
611     * Generate hints. This has little overhead, since the
612     * hints will be NULL for a boring pattern anyway.
613     */
614    newjob->hints = pcre_study(newjob->pattern, 0, &error);
615    if (error != NULL)
616    {
617       *errptr = PCRS_ERR_STUDY;
618       pcrs_free_job(newjob);
619       return NULL;
620    }
621
622
623    /*
624     * Determine the number of capturing subpatterns.
625     * This is needed for handling $+ in the substitute.
626     */
627    if (0 > (*errptr = pcre_fullinfo(newjob->pattern, newjob->hints, PCRE_INFO_CAPTURECOUNT, &capturecount)))
628    {
629       pcrs_free_job(newjob);
630       return NULL;
631    }
632
633
634    /*
635     * Compile the substitute
636     */
637    if (NULL == (newjob->substitute = pcrs_compile_replacement(substitute, newjob->flags & PCRS_TRIVIAL, capturecount, errptr)))
638    {
639       pcrs_free_job(newjob);
640       return NULL;
641    }
642
643    return newjob;
644
645 }
646
647
648 /*********************************************************************
649  *
650  * Function    :  pcrs_execute_list
651  *
652  * Description :  This is a multiple job wrapper for pcrs_execute().
653  *                Apply the regular substitutions defined by the jobs in
654  *                the joblist to the subject.
655  *                The subject itself is left untouched, memory for the result
656  *                is malloc()ed and it is the caller's responsibility to free
657  *                the result when it's no longer needed.
658  *
659  *                Note: For convenient string handling, a null byte is
660  *                      appended to the result. It does not count towards the
661  *                      result_length, though.
662  *
663  *
664  * Parameters  :
665  *          1  :  joblist = the chained list of pcrs_jobs to be executed
666  *          2  :  subject = the subject string
667  *          3  :  subject_length = the subject's length
668  *          4  :  result = char** for returning  the result
669  *          5  :  result_length = size_t* for returning the result's length
670  *
671  * Returns     :  On success, the number of substitutions that were made.
672  *                 May be > 1 if job->flags contained PCRS_GLOBAL
673  *                On failure, the (negative) pcre error code describing the
674  *                 failure, which may be translated to text using pcrs_strerror().
675  *
676  *********************************************************************/
677 int pcrs_execute_list(pcrs_job *joblist, char *subject, size_t subject_length, char **result, size_t *result_length)
678 {
679    pcrs_job *job;
680    char *old, *new = NULL;
681    int hits, total_hits;
682
683    old = subject;
684    *result_length = subject_length;
685    total_hits = 0;
686
687    for (job = joblist; job != NULL; job = job->next)
688    {
689       hits = pcrs_execute(job, old, *result_length, &new, result_length);
690
691       if (old != subject) free(old);
692
693       if (hits < 0)
694       {
695          return(hits);
696       }
697       else
698       {
699          total_hits += hits;
700          old = new;
701       }
702    }
703
704    *result = new;
705    return(total_hits);
706
707 }
708
709
710 /*********************************************************************
711  *
712  * Function    :  pcrs_execute
713  *
714  * Description :  Apply the regular substitution defined by the job to the
715  *                subject.
716  *                The subject itself is left untouched, memory for the result
717  *                is malloc()ed and it is the caller's responsibility to free
718  *                the result when it's no longer needed.
719  *
720  *                Note: For convenient string handling, a null byte is
721  *                      appended to the result. It does not count towards the
722  *                      result_length, though.
723  *
724  * Parameters  :
725  *          1  :  job = the pcrs_job to be executed
726  *          2  :  subject = the subject (== original) string
727  *          3  :  subject_length = the subject's length
728  *          4  :  result = char** for returning  the result
729  *          5  :  result_length = size_t* for returning the result's length
730  *
731  * Returns     :  On success, the number of substitutions that were made.
732  *                 May be > 1 if job->flags contained PCRS_GLOBAL
733  *                On failure, the (negative) pcre error code describing the
734  *                 failure, which may be translated to text using pcrs_strerror().
735  *
736  *********************************************************************/
737 int pcrs_execute(pcrs_job *job, const char *subject, size_t subject_length, char **result, size_t *result_length)
738 {
739    int offsets[3 * PCRS_MAX_SUBMATCHES],
740        offset,
741        i, k,
742        matches_found,
743        submatches,
744        max_matches = PCRS_MAX_MATCH_INIT;
745    size_t newsize;
746    pcrs_match *matches, *dummy;
747    char *result_offset;
748
749    offset = i = 0;
750
751    /*
752     * Sanity check & memory allocation
753     */
754    if (job == NULL || job->pattern == NULL || job->substitute == NULL || NULL == subject)
755    {
756       *result = NULL;
757       return(PCRS_ERR_BADJOB);
758    }
759
760    if (NULL == (matches = (pcrs_match *)malloc((size_t)max_matches * sizeof(pcrs_match))))
761    {
762       *result = NULL;
763       return(PCRS_ERR_NOMEM);
764    }
765    memset(matches, '\0', (size_t)max_matches * sizeof(pcrs_match));
766
767
768    /*
769     * Find the pattern and calculate the space
770     * requirements for the result
771     */
772    newsize = subject_length;
773
774    while ((submatches = pcre_exec(job->pattern, job->hints, subject, (int)subject_length, offset, 0, offsets, 3 * PCRS_MAX_SUBMATCHES)) > 0)
775    {
776       job->flags |= PCRS_SUCCESS;
777       matches[i].submatches = submatches;
778
779       for (k = 0; k < submatches; k++)
780       {
781          matches[i].submatch_offset[k] = offsets[2 * k];
782
783          /* Note: Non-found optional submatches have length -1-(-1)==0 */
784          matches[i].submatch_length[k] = (size_t)(offsets[2 * k + 1] - offsets[2 * k]);
785
786          /* reserve mem for each submatch as often as it is ref'd */
787          newsize += matches[i].submatch_length[k] * (size_t)job->substitute->backref_count[k];
788       }
789       /* plus replacement text size minus match text size */
790       newsize += job->substitute->length - matches[i].submatch_length[0];
791
792       /* chunk before match */
793       matches[i].submatch_offset[PCRS_MAX_SUBMATCHES] = 0;
794       matches[i].submatch_length[PCRS_MAX_SUBMATCHES] = (size_t)offsets[0];
795       newsize += (size_t)offsets[0] * (size_t)job->substitute->backref_count[PCRS_MAX_SUBMATCHES];
796
797       /* chunk after match */
798       matches[i].submatch_offset[PCRS_MAX_SUBMATCHES + 1] = offsets[1];
799       matches[i].submatch_length[PCRS_MAX_SUBMATCHES + 1] = subject_length - (size_t)offsets[1] - 1;
800       newsize += (subject_length - (size_t)offsets[1]) * (size_t)job->substitute->backref_count[PCRS_MAX_SUBMATCHES + 1];
801
802       /* Storage for matches exhausted? -> Extend! */
803       if (++i >= max_matches)
804       {
805          max_matches = (int)(max_matches * PCRS_MAX_MATCH_GROW);
806          if (NULL == (dummy = (pcrs_match *)realloc(matches, (size_t)max_matches * sizeof(pcrs_match))))
807          {
808             free(matches);
809             *result = NULL;
810             return(PCRS_ERR_NOMEM);
811          }
812          matches = dummy;
813       }
814
815       /* Non-global search or limit reached? */
816       if (!(job->flags & PCRS_GLOBAL)) break;
817
818       /* Don't loop on empty matches */
819       if (offsets[1] == offset)
820          if ((size_t)offset < subject_length)
821             offset++;
822          else
823             break;
824       /* Go find the next one */
825       else
826          offset = offsets[1];
827    }
828    /* Pass pcre error through if (bad) failiure */
829    if (submatches < PCRE_ERROR_NOMATCH)
830    {
831       free(matches);
832       return submatches;
833    }
834    matches_found = i;
835
836
837    /*
838     * Get memory for the result (must be freed by caller!)
839     * and append terminating null byte.
840     */
841    if ((*result = (char *)malloc(newsize + 1)) == NULL)
842    {
843       free(matches);
844       return PCRS_ERR_NOMEM;
845    }
846    else
847    {
848       (*result)[newsize] = '\0';
849    }
850
851
852    /*
853     * Replace
854     */
855    offset = 0;
856    result_offset = *result;
857
858    for (i = 0; i < matches_found; i++)
859    {
860       /* copy the chunk preceding the match */
861       memcpy(result_offset, subject + offset, (size_t)(matches[i].submatch_offset[0] - offset));
862       result_offset += matches[i].submatch_offset[0] - offset;
863
864       /* For every segment of the substitute.. */
865       for (k = 0; k <= job->substitute->backrefs; k++)
866       {
867          /* ...copy its text.. */
868          memcpy(result_offset, job->substitute->text + job->substitute->block_offset[k], job->substitute->block_length[k]);
869          result_offset += job->substitute->block_length[k];
870
871          /* ..plus, if it's not the last chunk, i.e.: There *is* a backref.. */
872          if (k != job->substitute->backrefs
873              /* ..in legal range.. */
874              && job->substitute->backref[k] < PCRS_MAX_SUBMATCHES + 2
875              /* ..and referencing a real submatch.. */
876              && job->substitute->backref[k] < matches[i].submatches
877              /* ..that is nonempty.. */
878              && matches[i].submatch_length[job->substitute->backref[k]] > 0)
879          {
880             /* ..copy the submatch that is ref'd. */
881             memcpy(
882                result_offset,
883                subject + matches[i].submatch_offset[job->substitute->backref[k]],
884                matches[i].submatch_length[job->substitute->backref[k]]
885             );
886             result_offset += matches[i].submatch_length[job->substitute->backref[k]];
887          }
888       }
889       offset =  matches[i].submatch_offset[0] + (int)matches[i].submatch_length[0];
890    }
891
892    /* Copy the rest. */
893    memcpy(result_offset, subject + offset, subject_length - (size_t)offset);
894
895    *result_length = newsize;
896    free(matches);
897    return matches_found;
898
899 }
900
901
902 #define is_hex_digit(x) ((x) && strchr("0123456789ABCDEF", toupper(x)))
903
904 /*********************************************************************
905  *
906  * Function    :  is_hex_sequence
907  *
908  * Description :  Checks the first four characters of a string
909  *                and decides if they are a valid hex sequence
910  *                (like '\x40').
911  *
912  * Parameters  :
913  *          1  :  sequence = The string to check
914  *
915  * Returns     :  Non-zero if it's valid sequence, or
916  *                Zero if it isn't.
917  *
918  *********************************************************************/
919 static int is_hex_sequence(const char *sequence)
920 {
921    return (sequence[0] == '\\' &&
922            sequence[1] == 'x'  &&
923            is_hex_digit(sequence[2]) &&
924            is_hex_digit(sequence[3]));
925 }
926
927
928 /*
929  * Functions below this line are only part of the pcrs version
930  * included in Privoxy. If you use any of them you should not
931  * try to dynamically link against external pcrs versions.
932  */
933
934 /*********************************************************************
935  *
936  * Function    :  pcrs_job_is_dynamic
937  *
938  * Description :  Checks if a job has the "D" (dynamic) option set.
939  *
940  * Parameters  :
941  *          1  :  job = The job to check
942  *
943  * Returns     :  TRUE if the job is indeed dynamic, otherwise
944  *                FALSE
945  *
946  *********************************************************************/
947 int pcrs_job_is_dynamic (char *job)
948 {
949    const char delimiter = job[1];
950    const size_t length = strlen(job);
951    char *option;
952
953    if (length < 5)
954    {
955       /*
956        * The shortest valid (but useless)
957        * dynamic pattern is "s@@@D"
958        */
959       return FALSE;
960    }
961
962    /*
963     * Everything between the last character
964     * and the last delimiter is an option ...
965     */
966    for (option = job + length; *option != delimiter; option--)
967    {
968       if (*option == 'D')
969       {
970          /*
971           * ... and if said option is 'D' the job is dynamic.
972           */
973          return TRUE;
974       }
975    }
976    return FALSE;
977
978 }
979
980
981 /*********************************************************************
982  *
983  * Function    :  pcrs_get_delimiter
984  *
985  * Description :  Tries to find a character that is safe to
986  *                be used as a pcrs delimiter for a certain string.
987  *
988  * Parameters  :
989  *          1  :  string = The string to search in
990  *
991  * Returns     :  A safe delimiter if one was found, otherwise '\0'.
992  *
993  *********************************************************************/
994 char pcrs_get_delimiter(const char *string)
995 {
996    /*
997     * Some characters that are unlikely to
998     * be part of pcrs replacement strings.
999     */
1000    char delimiters[] = "><§#+*~%^°-:;µ!@";
1001    char *d = delimiters;
1002
1003    /* Take the first delimiter that isn't part of the string */
1004    while (*d && NULL != strchr(string, *d))
1005    {
1006       d++;
1007    }
1008    return *d;
1009
1010 }
1011
1012
1013 /*********************************************************************
1014  *
1015  * Function    :  pcrs_execute_single_command
1016  *
1017  * Description :  Apply single pcrs command to the subject.
1018  *                The subject itself is left untouched, memory for the result
1019  *                is malloc()ed and it is the caller's responsibility to free
1020  *                the result when it's no longer needed.
1021  *
1022  * Parameters  :
1023  *          1  :  subject = the subject (== original) string
1024  *          2  :  pcrs_command = the pcrs command as string (s@foo@bar@)
1025  *          3  :  hits = int* for returning  the number of modifications
1026  *
1027  * Returns     :  NULL in case of errors, otherwise the
1028  *                result of the pcrs command.
1029  *
1030  *********************************************************************/
1031 char *pcrs_execute_single_command(const char *subject, const char *pcrs_command, int *hits)
1032 {
1033    size_t size;
1034    char *result = NULL;
1035    pcrs_job *job;
1036
1037    assert(subject);
1038    assert(pcrs_command);
1039
1040    *hits = 0;
1041    size = strlen(subject);
1042
1043    job = pcrs_compile_command(pcrs_command, hits);
1044    if (NULL != job)
1045    {
1046       *hits = pcrs_execute(job, subject, size, &result, &size);
1047       if (*hits < 0)
1048       {
1049          freez(result);
1050       }
1051       pcrs_free_job(job);
1052    }
1053    return result;
1054
1055 }
1056
1057
1058 static const char warning[] = "... [too long, truncated]";
1059 /*********************************************************************
1060  *
1061  * Function    :  pcrs_compile_dynamic_command
1062  *
1063  * Description :  Takes a dynamic pcrs command, fills in the
1064  *                values of the variables and compiles it.
1065  *
1066  * Parameters  :
1067  *          1  :  pcrs_command = The dynamic pcrs command to compile
1068  *          2  :  v = NULL terminated array of variables and their values.
1069  *          3  :  error = pcrs error code
1070  *
1071  * Returns     :  NULL in case of hard errors, otherwise the
1072  *                compiled pcrs job.
1073  *
1074  *********************************************************************/
1075 pcrs_job *pcrs_compile_dynamic_command(char *pcrs_command, const struct pcrs_variable v[], int *error)
1076 {
1077    char buf[PCRS_BUFFER_SIZE];
1078    const char *original_pcrs_command = pcrs_command;
1079    char *pcrs_command_tmp = NULL;
1080    pcrs_job *job = NULL;
1081    int truncation = 0;
1082    char d;
1083    int ret;
1084
1085    while ((NULL != v->name) && (NULL != pcrs_command))
1086    {
1087       assert(NULL != v->value);
1088
1089       if (NULL == strstr(pcrs_command, v->name))
1090       {
1091          /*
1092           * Skip the substitution if the variable
1093           * name isn't part of the pattern.
1094           */
1095          v++;
1096          continue;
1097       }
1098
1099       /* Use pcrs to replace the variable with its value. */
1100       d = pcrs_get_delimiter(v->value);
1101       if ('\0' == d)
1102       {
1103          /* No proper delimiter found */
1104          *error = PCRS_ERR_CMDSYNTAX;
1105          return NULL;
1106       }
1107
1108       /*
1109        * Variable names are supposed to contain alpha
1110        * numerical characters plus '_' only.
1111        */
1112       assert(NULL == strchr(v->name, d));
1113
1114       ret = snprintf(buf, sizeof(buf), "s%c\\$%s%c%s%cgT", d, v->name, d, v->value, d);
1115       assert(ret >= 0);
1116       if (ret >= sizeof(buf))
1117       {
1118          /*
1119           * Value didn't completely fit into buffer,
1120           * overwrite the end of the substitution text
1121           * with a truncation message and close the pattern
1122           * properly.
1123           */
1124          const size_t trailer_size = sizeof(warning) + 3; /* 3 for d + "gT" */
1125          char *trailer_start = buf + sizeof(buf) - trailer_size;
1126
1127          ret = snprintf(trailer_start, trailer_size, "%s%cgT", warning, d);
1128          assert(ret == trailer_size - 1);
1129          assert(sizeof(buf) == strlen(buf) + 1);
1130          truncation = 1;
1131       }
1132
1133       pcrs_command_tmp = pcrs_execute_single_command(pcrs_command, buf, error);
1134       if (NULL == pcrs_command_tmp)
1135       {
1136          return NULL;
1137       }
1138
1139       if (pcrs_command != original_pcrs_command)
1140       {
1141          freez(pcrs_command);
1142       }
1143       pcrs_command = pcrs_command_tmp;
1144
1145       v++;
1146    }
1147
1148    job = pcrs_compile_command(pcrs_command, error);
1149    if (pcrs_command != original_pcrs_command)
1150    {
1151       freez(pcrs_command);
1152    }
1153
1154    if (truncation)
1155    {
1156       *error = PCRS_WARN_TRUNCATION;
1157    }
1158
1159    return job;
1160
1161 }
1162
1163
1164 /*
1165   Local Variables:
1166   tab-width: 3
1167   end:
1168 */