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