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