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