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