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