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