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