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