4d112271a08a71f63d622f0ad72c8d684fccf21d
[privoxy.git] / pcrs.c
1 const char pcrs_rcs[] = "$Id: pcrs.c,v 1.46 2014/11/14 10:40:10 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             if (l >= PCRS_MAX_SUBMATCHES)
323             {
324                freez(text);
325                freez(r);
326                *errptr = PCRS_WARN_BADREF;
327                return NULL;
328             }
329             r->block_length[l] = (size_t)(k - r->block_offset[l]);
330
331             /* Numerical backreferences */
332             if (isdigit((int)replacement[i + 1]))
333             {
334                while (i < (int)length && isdigit((int)replacement[++i]))
335                {
336                   r->backref[l] = r->backref[l] * 10 + replacement[i] - 48;
337                }
338                if (r->backref[l] > capturecount)
339                {
340                   freez(text);
341                   freez(r);
342                   *errptr = PCRS_WARN_BADREF;
343                   return NULL;
344                }
345             }
346
347             /* Symbolic backreferences: */
348             else if (NULL != (symbol = strchr(symbols, replacement[i + 1])))
349             {
350
351                if (symbol - symbols == 2) /* $+ */
352                {
353                   r->backref[l] = capturecount;
354                }
355                else if (symbol - symbols == 3) /* $& */
356                {
357                   r->backref[l] = 0;
358                }
359                else /* $' or $` */
360                {
361                   r->backref[l] = (int)(PCRS_MAX_SUBMATCHES + 1 - (symbol - symbols));
362                }
363                i += 2;
364             }
365
366             /* Invalid backref -> plain '$' */
367             else
368             {
369                goto plainchar;
370             }
371
372             /* Valid and in range? -> record */
373             if (0 <= r->backref[l] && r->backref[l] < PCRS_MAX_SUBMATCHES + 2)
374             {
375                r->backref_count[r->backref[l]] += 1;
376                r->block_offset[++l] = k;
377             }
378             else
379             {
380                freez(text);
381                freez(r);
382                *errptr = PCRS_WARN_BADREF;
383                return NULL;
384             }
385             continue;
386          }
387
388 plainchar:
389          /* Plain chars are copied */
390          text[k++] = replacement[i++];
391          quoted = 0;
392       }
393    } /* -END- if (!trivialflag) */
394
395    /*
396     * Finish & return
397     */
398    r->text = text;
399    r->backrefs = l;
400    r->length = (size_t)k;
401    r->block_length[l] = (size_t)(k - r->block_offset[l]);
402
403    return r;
404
405 }
406
407
408 /*********************************************************************
409  *
410  * Function    :  pcrs_free_job
411  *
412  * Description :  Frees the memory used by a pcrs_job struct and its
413  *                dependent structures.
414  *
415  * Parameters  :
416  *          1  :  job = pointer to the pcrs_job structure to be freed
417  *
418  * Returns     :  a pointer to the next job, if there was any, or
419  *                NULL otherwise.
420  *
421  *********************************************************************/
422 pcrs_job *pcrs_free_job(pcrs_job *job)
423 {
424    pcrs_job *next;
425
426    if (job == NULL)
427    {
428       return NULL;
429    }
430    else
431    {
432       next = job->next;
433       if (job->pattern != NULL) free(job->pattern);
434       if (job->hints != NULL) free(job->hints);
435       if (job->substitute != NULL)
436       {
437          if (job->substitute->text != NULL) free(job->substitute->text);
438          free(job->substitute);
439       }
440       free(job);
441    }
442    return next;
443
444 }
445
446
447 /*********************************************************************
448  *
449  * Function    :  pcrs_free_joblist
450  *
451  * Description :  Iterates through a chained list of pcrs_job's and
452  *                frees them using pcrs_free_job.
453  *
454  * Parameters  :
455  *          1  :  joblist = pointer to the first pcrs_job structure to
456  *                be freed
457  *
458  * Returns     :  N/A
459  *
460  *********************************************************************/
461 void pcrs_free_joblist(pcrs_job *joblist)
462 {
463    while (NULL != (joblist = pcrs_free_job(joblist))) {};
464
465    return;
466
467 }
468
469
470 /*********************************************************************
471  *
472  * Function    :  pcrs_compile_command
473  *
474  * Description :  Parses a string with a Perl-style s/// command,
475  *                calls pcrs_compile, and returns a corresponding
476  *                pcrs_job, or NULL if parsing or compiling the job
477  *                fails.
478  *
479  * Parameters  :
480  *          1  :  command = string with perl-style s/// command
481  *          2  :  errptr = pointer to an integer in which error
482  *                         conditions can be returned.
483  *
484  * Returns     :  a corresponding pcrs_job data structure, or NULL
485  *                if an error was encountered. In that case, *errptr
486  *                has the reason.
487  *
488  *********************************************************************/
489 pcrs_job *pcrs_compile_command(const char *command, int *errptr)
490 {
491    int i, k, l, quoted = FALSE;
492    size_t limit;
493    char delimiter;
494    char *tokens[4];
495    pcrs_job *newjob;
496
497    k = l = 0;
498
499    /*
500     * Tokenize the perl command
501     */
502    limit = strlen(command);
503    if (limit < 4)
504    {
505       *errptr = PCRS_ERR_CMDSYNTAX;
506       return NULL;
507    }
508    else
509    {
510       delimiter = command[1];
511    }
512
513    tokens[l] = (char *) malloc(limit + 1);
514
515    for (i = 0; i <= (int)limit; i++)
516    {
517
518       if (command[i] == delimiter && !quoted)
519       {
520          if (l == 3)
521          {
522             l = -1;
523             break;
524          }
525          tokens[0][k++] = '\0';
526          tokens[++l] = tokens[0] + k;
527          continue;
528       }
529
530       else if (command[i] == '\\' && !quoted)
531       {
532          quoted = TRUE;
533          if (command[i+1] == delimiter) continue;
534       }
535       else
536       {
537          quoted = FALSE;
538       }
539       tokens[0][k++] = command[i];
540    }
541
542    /*
543     * Syntax error ?
544     */
545    if (l != 3)
546    {
547       *errptr = PCRS_ERR_CMDSYNTAX;
548       free(tokens[0]);
549       return NULL;
550    }
551
552    newjob = pcrs_compile(tokens[1], tokens[2], tokens[3], errptr);
553    free(tokens[0]);
554    return newjob;
555
556 }
557
558
559 /*********************************************************************
560  *
561  * Function    :  pcrs_compile
562  *
563  * Description :  Takes the three arguments to a perl s/// command
564  *                and compiles a pcrs_job structure from them.
565  *
566  * Parameters  :
567  *          1  :  pattern = string with perl-style pattern
568  *          2  :  substitute = string with perl-style substitute
569  *          3  :  options = string with perl-style options
570  *          4  :  errptr = pointer to an integer in which error
571  *                         conditions can be returned.
572  *
573  * Returns     :  a corresponding pcrs_job data structure, or NULL
574  *                if an error was encountered. In that case, *errptr
575  *                has the reason.
576  *
577  *********************************************************************/
578 pcrs_job *pcrs_compile(const char *pattern, const char *substitute, const char *options, int *errptr)
579 {
580    pcrs_job *newjob;
581    int flags;
582    int capturecount;
583    const char *error;
584
585    *errptr = 0;
586
587    /*
588     * Handle NULL arguments
589     */
590    if (pattern == NULL) pattern = "";
591    if (substitute == NULL) substitute = "";
592
593
594    /*
595     * Get and init memory
596     */
597    if (NULL == (newjob = (pcrs_job *)malloc(sizeof(pcrs_job))))
598    {
599       *errptr = PCRS_ERR_NOMEM;
600       return NULL;
601    }
602    memset(newjob, '\0', sizeof(pcrs_job));
603
604
605    /*
606     * Evaluate the options
607     */
608    newjob->options = pcrs_parse_perl_options(options, &flags);
609    newjob->flags = flags;
610
611
612    /*
613     * Compile the pattern
614     */
615    newjob->pattern = pcre_compile(pattern, newjob->options, &error, errptr, NULL);
616    if (newjob->pattern == NULL)
617    {
618       pcrs_free_job(newjob);
619       return NULL;
620    }
621
622
623    /*
624     * Generate hints. This has little overhead, since the
625     * hints will be NULL for a boring pattern anyway.
626     */
627    newjob->hints = pcre_study(newjob->pattern, 0, &error);
628    if (error != NULL)
629    {
630       *errptr = PCRS_ERR_STUDY;
631       pcrs_free_job(newjob);
632       return NULL;
633    }
634
635
636    /*
637     * Determine the number of capturing subpatterns.
638     * This is needed for handling $+ in the substitute.
639     */
640    if (0 > (*errptr = pcre_fullinfo(newjob->pattern, newjob->hints, PCRE_INFO_CAPTURECOUNT, &capturecount)))
641    {
642       pcrs_free_job(newjob);
643       return NULL;
644    }
645
646
647    /*
648     * Compile the substitute
649     */
650    if (NULL == (newjob->substitute = pcrs_compile_replacement(substitute, newjob->flags & PCRS_TRIVIAL, capturecount, errptr)))
651    {
652       pcrs_free_job(newjob);
653       return NULL;
654    }
655
656    return newjob;
657
658 }
659
660
661 /*********************************************************************
662  *
663  * Function    :  pcrs_execute_list
664  *
665  * Description :  This is a multiple job wrapper for pcrs_execute().
666  *                Apply the regular substitutions defined by the jobs in
667  *                the joblist to the subject.
668  *                The subject itself is left untouched, memory for the result
669  *                is malloc()ed and it is the caller's responsibility to free
670  *                the result when it's no longer needed.
671  *
672  *                Note: For convenient string handling, a null byte is
673  *                      appended to the result. It does not count towards the
674  *                      result_length, though.
675  *
676  *
677  * Parameters  :
678  *          1  :  joblist = the chained list of pcrs_jobs to be executed
679  *          2  :  subject = the subject string
680  *          3  :  subject_length = the subject's length
681  *          4  :  result = char** for returning  the result
682  *          5  :  result_length = size_t* for returning the result's length
683  *
684  * Returns     :  On success, the number of substitutions that were made.
685  *                 May be > 1 if job->flags contained PCRS_GLOBAL
686  *                On failure, the (negative) pcre error code describing the
687  *                 failure, which may be translated to text using pcrs_strerror().
688  *
689  *********************************************************************/
690 int pcrs_execute_list(pcrs_job *joblist, char *subject, size_t subject_length, char **result, size_t *result_length)
691 {
692    pcrs_job *job;
693    char *old, *new = NULL;
694    int hits, total_hits;
695
696    old = subject;
697    *result_length = subject_length;
698    total_hits = 0;
699
700    for (job = joblist; job != NULL; job = job->next)
701    {
702       hits = pcrs_execute(job, old, *result_length, &new, result_length);
703
704       if (old != subject) free(old);
705
706       if (hits < 0)
707       {
708          return(hits);
709       }
710       else
711       {
712          total_hits += hits;
713          old = new;
714       }
715    }
716
717    *result = new;
718    return(total_hits);
719
720 }
721
722
723 /*********************************************************************
724  *
725  * Function    :  pcrs_execute
726  *
727  * Description :  Apply the regular substitution defined by the job to the
728  *                subject.
729  *                The subject itself is left untouched, memory for the result
730  *                is malloc()ed and it is the caller's responsibility to free
731  *                the result when it's no longer needed.
732  *
733  *                Note: For convenient string handling, a null byte is
734  *                      appended to the result. It does not count towards the
735  *                      result_length, though.
736  *
737  * Parameters  :
738  *          1  :  job = the pcrs_job to be executed
739  *          2  :  subject = the subject (== original) string
740  *          3  :  subject_length = the subject's length
741  *          4  :  result = char** for returning the result (NULL on error)
742  *          5  :  result_length = size_t* for returning the result's length
743  *
744  * Returns     :  On success, the number of substitutions that were made.
745  *                 May be > 1 if job->flags contained PCRS_GLOBAL
746  *                On failure, the (negative) pcre error code describing the
747  *                 failure, which may be translated to text using pcrs_strerror().
748  *
749  *********************************************************************/
750 int pcrs_execute(pcrs_job *job, const char *subject, size_t subject_length, char **result, size_t *result_length)
751 {
752    int offsets[3 * PCRS_MAX_SUBMATCHES],
753        offset,
754        i, k,
755        matches_found,
756        submatches,
757        max_matches = PCRS_MAX_MATCH_INIT;
758    size_t newsize;
759    pcrs_match *matches, *dummy;
760    char *result_offset;
761
762    offset = i = 0;
763    *result = NULL;
764
765    /*
766     * Sanity check & memory allocation
767     */
768    if (job == NULL || job->pattern == NULL || job->substitute == NULL || NULL == subject)
769    {
770       return(PCRS_ERR_BADJOB);
771    }
772
773    if (NULL == (matches = (pcrs_match *)malloc((size_t)max_matches * sizeof(pcrs_match))))
774    {
775       return(PCRS_ERR_NOMEM);
776    }
777    memset(matches, '\0', (size_t)max_matches * sizeof(pcrs_match));
778
779
780    /*
781     * Find the pattern and calculate the space
782     * requirements for the result
783     */
784    newsize = subject_length;
785
786    while ((submatches = pcre_exec(job->pattern, job->hints, subject, (int)subject_length, offset, 0, offsets, 3 * PCRS_MAX_SUBMATCHES)) > 0)
787    {
788       job->flags |= PCRS_SUCCESS;
789       matches[i].submatches = submatches;
790
791       for (k = 0; k < submatches; k++)
792       {
793          matches[i].submatch_offset[k] = offsets[2 * k];
794
795          /* Note: Non-found optional submatches have length -1-(-1)==0 */
796          matches[i].submatch_length[k] = (size_t)(offsets[2 * k + 1] - offsets[2 * k]);
797
798          /* reserve mem for each submatch as often as it is ref'd */
799          newsize += matches[i].submatch_length[k] * (size_t)job->substitute->backref_count[k];
800       }
801       /* plus replacement text size minus match text size */
802       newsize += job->substitute->length - matches[i].submatch_length[0];
803
804       /* chunk before match */
805       matches[i].submatch_offset[PCRS_MAX_SUBMATCHES] = 0;
806       matches[i].submatch_length[PCRS_MAX_SUBMATCHES] = (size_t)offsets[0];
807       newsize += (size_t)offsets[0] * (size_t)job->substitute->backref_count[PCRS_MAX_SUBMATCHES];
808
809       /* chunk after match */
810       matches[i].submatch_offset[PCRS_MAX_SUBMATCHES + 1] = offsets[1];
811       matches[i].submatch_length[PCRS_MAX_SUBMATCHES + 1] = subject_length - (size_t)offsets[1] - 1;
812       newsize += (subject_length - (size_t)offsets[1]) * (size_t)job->substitute->backref_count[PCRS_MAX_SUBMATCHES + 1];
813
814       /* Storage for matches exhausted? -> Extend! */
815       if (++i >= max_matches)
816       {
817          max_matches = (int)(max_matches * PCRS_MAX_MATCH_GROW);
818          if (NULL == (dummy = (pcrs_match *)realloc(matches, (size_t)max_matches * sizeof(pcrs_match))))
819          {
820             free(matches);
821             return(PCRS_ERR_NOMEM);
822          }
823          matches = dummy;
824       }
825
826       /* Non-global search or limit reached? */
827       if (!(job->flags & PCRS_GLOBAL)) break;
828
829       /* Don't loop on empty matches */
830       if (offsets[1] == offset)
831          if ((size_t)offset < subject_length)
832             offset++;
833          else
834             break;
835       /* Go find the next one */
836       else
837          offset = offsets[1];
838    }
839    /* Pass pcre error through if (bad) failure */
840    if (submatches < PCRE_ERROR_NOMATCH)
841    {
842       free(matches);
843       return submatches;
844    }
845    matches_found = i;
846
847
848    /*
849     * Get memory for the result (must be freed by caller!)
850     * and append terminating null byte.
851     */
852    if ((*result = (char *)malloc(newsize + 1)) == NULL)
853    {
854       free(matches);
855       return PCRS_ERR_NOMEM;
856    }
857    else
858    {
859       (*result)[newsize] = '\0';
860    }
861
862
863    /*
864     * Replace
865     */
866    offset = 0;
867    result_offset = *result;
868
869    for (i = 0; i < matches_found; i++)
870    {
871       /* copy the chunk preceding the match */
872       memcpy(result_offset, subject + offset, (size_t)(matches[i].submatch_offset[0] - offset));
873       result_offset += matches[i].submatch_offset[0] - offset;
874
875       /* For every segment of the substitute.. */
876       for (k = 0; k <= job->substitute->backrefs; k++)
877       {
878          /* ...copy its text.. */
879          memcpy(result_offset, job->substitute->text + job->substitute->block_offset[k], job->substitute->block_length[k]);
880          result_offset += job->substitute->block_length[k];
881
882          /* ..plus, if it's not the last chunk, i.e.: There *is* a backref.. */
883          if (k != job->substitute->backrefs
884              /* ..in legal range.. */
885              && job->substitute->backref[k] < PCRS_MAX_SUBMATCHES + 2
886              /* ..and referencing a real submatch.. */
887              && job->substitute->backref[k] < matches[i].submatches
888              /* ..that is nonempty.. */
889              && matches[i].submatch_length[job->substitute->backref[k]] > 0)
890          {
891             /* ..copy the submatch that is ref'd. */
892             memcpy(
893                result_offset,
894                subject + matches[i].submatch_offset[job->substitute->backref[k]],
895                matches[i].submatch_length[job->substitute->backref[k]]
896             );
897             result_offset += matches[i].submatch_length[job->substitute->backref[k]];
898          }
899       }
900       offset =  matches[i].submatch_offset[0] + (int)matches[i].submatch_length[0];
901    }
902
903    /* Copy the rest. */
904    memcpy(result_offset, subject + offset, subject_length - (size_t)offset);
905
906    *result_length = newsize;
907    free(matches);
908    return matches_found;
909
910 }
911
912
913 #define is_hex_digit(x) ((x) && strchr("0123456789ABCDEF", toupper(x)))
914
915 /*********************************************************************
916  *
917  * Function    :  is_hex_sequence
918  *
919  * Description :  Checks the first four characters of a string
920  *                and decides if they are a valid hex sequence
921  *                (like '\x40').
922  *
923  * Parameters  :
924  *          1  :  sequence = The string to check
925  *
926  * Returns     :  Non-zero if it's valid sequence, or
927  *                Zero if it isn't.
928  *
929  *********************************************************************/
930 static int is_hex_sequence(const char *sequence)
931 {
932    return (sequence[0] == '\\' &&
933            sequence[1] == 'x'  &&
934            is_hex_digit(sequence[2]) &&
935            is_hex_digit(sequence[3]));
936 }
937
938
939 /*
940  * Functions below this line are only part of the pcrs version
941  * included in Privoxy. If you use any of them you should not
942  * try to dynamically link against external pcrs versions.
943  */
944
945 /*********************************************************************
946  *
947  * Function    :  pcrs_job_is_dynamic
948  *
949  * Description :  Checks if a job has the "D" (dynamic) option set.
950  *
951  * Parameters  :
952  *          1  :  job = The job to check
953  *
954  * Returns     :  TRUE if the job is indeed dynamic, otherwise
955  *                FALSE
956  *
957  *********************************************************************/
958 int pcrs_job_is_dynamic (char *job)
959 {
960    const char delimiter = job[1];
961    const size_t length = strlen(job);
962    char *option;
963
964    if (length < 5)
965    {
966       /*
967        * The shortest valid (but useless)
968        * dynamic pattern is "s@@@D"
969        */
970       return FALSE;
971    }
972
973    /*
974     * Everything between the last character
975     * and the last delimiter is an option ...
976     */
977    for (option = job + length; *option != delimiter; option--)
978    {
979       if (*option == 'D')
980       {
981          /*
982           * ... and if said option is 'D' the job is dynamic.
983           */
984          return TRUE;
985       }
986    }
987    return FALSE;
988
989 }
990
991
992 /*********************************************************************
993  *
994  * Function    :  pcrs_get_delimiter
995  *
996  * Description :  Tries to find a character that is safe to
997  *                be used as a pcrs delimiter for a certain string.
998  *
999  * Parameters  :
1000  *          1  :  string = The string to search in
1001  *
1002  * Returns     :  A safe delimiter if one was found, otherwise '\0'.
1003  *
1004  *********************************************************************/
1005 char pcrs_get_delimiter(const char *string)
1006 {
1007    /*
1008     * Some characters that are unlikely to
1009     * be part of pcrs replacement strings.
1010     */
1011    static const char delimiters[] = "><#+*~%^-:;!@";
1012    const char *d = delimiters;
1013
1014    /* Take the first delimiter that isn't part of the string */
1015    while (*d && NULL != strchr(string, *d))
1016    {
1017       d++;
1018    }
1019    return *d;
1020
1021 }
1022
1023
1024 /*********************************************************************
1025  *
1026  * Function    :  pcrs_execute_single_command
1027  *
1028  * Description :  Apply single pcrs command to the subject.
1029  *                The subject itself is left untouched, memory for the result
1030  *                is malloc()ed and it is the caller's responsibility to free
1031  *                the result when it's no longer needed.
1032  *
1033  * Parameters  :
1034  *          1  :  subject = the subject (== original) string
1035  *          2  :  pcrs_command = the pcrs command as string (s@foo@bar@)
1036  *          3  :  hits = int* for returning  the number of modifications
1037  *
1038  * Returns     :  NULL in case of errors, otherwise the
1039  *                result of the pcrs command.
1040  *
1041  *********************************************************************/
1042 char *pcrs_execute_single_command(const char *subject, const char *pcrs_command, int *hits)
1043 {
1044    size_t size;
1045    char *result = NULL;
1046    pcrs_job *job;
1047
1048    assert(subject);
1049    assert(pcrs_command);
1050
1051    *hits = 0;
1052    size = strlen(subject);
1053
1054    job = pcrs_compile_command(pcrs_command, hits);
1055    if (NULL != job)
1056    {
1057       *hits = pcrs_execute(job, subject, size, &result, &size);
1058       if (*hits < 0)
1059       {
1060          freez(result);
1061       }
1062       pcrs_free_job(job);
1063    }
1064    return result;
1065
1066 }
1067
1068
1069 static const char warning[] = "... [too long, truncated]";
1070 /*********************************************************************
1071  *
1072  * Function    :  pcrs_compile_dynamic_command
1073  *
1074  * Description :  Takes a dynamic pcrs command, fills in the
1075  *                values of the variables and compiles it.
1076  *
1077  * Parameters  :
1078  *          1  :  pcrs_command = The dynamic pcrs command to compile
1079  *          2  :  v = NULL terminated array of variables and their values.
1080  *          3  :  error = pcrs error code
1081  *
1082  * Returns     :  NULL in case of hard errors, otherwise the
1083  *                compiled pcrs job.
1084  *
1085  *********************************************************************/
1086 pcrs_job *pcrs_compile_dynamic_command(char *pcrs_command, const struct pcrs_variable v[], int *error)
1087 {
1088    char buf[PCRS_BUFFER_SIZE];
1089    const char *original_pcrs_command = pcrs_command;
1090    char *pcrs_command_tmp = NULL;
1091    pcrs_job *job = NULL;
1092    int truncation = 0;
1093    char d;
1094    int ret;
1095
1096    while ((NULL != v->name) && (NULL != pcrs_command))
1097    {
1098       assert(NULL != v->value);
1099
1100       if (NULL == strstr(pcrs_command, v->name))
1101       {
1102          /*
1103           * Skip the substitution if the variable
1104           * name isn't part of the pattern.
1105           */
1106          v++;
1107          continue;
1108       }
1109
1110       /* Use pcrs to replace the variable with its value. */
1111       d = pcrs_get_delimiter(v->value);
1112       if ('\0' == d)
1113       {
1114          /* No proper delimiter found */
1115          *error = PCRS_ERR_CMDSYNTAX;
1116          freez(pcrs_command_tmp);
1117          return NULL;
1118       }
1119
1120       /*
1121        * Variable names are supposed to contain alpha
1122        * numerical characters plus '_' only.
1123        */
1124       assert(NULL == strchr(v->name, d));
1125
1126       ret = snprintf(buf, sizeof(buf), "s%c\\$%s%c%s%cgT", d, v->name, d, v->value, d);
1127       assert(ret >= 0);
1128       if (ret >= sizeof(buf))
1129       {
1130          /*
1131           * Value didn't completely fit into buffer,
1132           * overwrite the end of the substitution text
1133           * with a truncation message and close the pattern
1134           * properly.
1135           */
1136          const size_t trailer_size = sizeof(warning) + 3; /* 3 for d + "gT" */
1137          char *trailer_start = buf + sizeof(buf) - trailer_size;
1138
1139          ret = snprintf(trailer_start, trailer_size, "%s%cgT", warning, d);
1140          assert(ret == trailer_size - 1);
1141          assert(sizeof(buf) == strlen(buf) + 1);
1142          truncation = 1;
1143       }
1144
1145       pcrs_command_tmp = pcrs_execute_single_command(pcrs_command, buf, error);
1146       if (NULL == pcrs_command_tmp)
1147       {
1148          return NULL;
1149       }
1150
1151       if (pcrs_command != original_pcrs_command)
1152       {
1153          freez(pcrs_command);
1154       }
1155       pcrs_command = pcrs_command_tmp;
1156
1157       v++;
1158    }
1159
1160    job = pcrs_compile_command(pcrs_command, error);
1161    if (pcrs_command != original_pcrs_command)
1162    {
1163       freez(pcrs_command);
1164    }
1165
1166    if (truncation)
1167    {
1168       *error = PCRS_WARN_TRUNCATION;
1169    }
1170
1171    return job;
1172
1173 }
1174
1175
1176 /*
1177   Local Variables:
1178   tab-width: 3
1179   end:
1180 */