1 const char pcrs_rcs[] = "$Id: pcrs.c,v 1.28 2007/08/18 14:37:27 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/pcrs.c,v $
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.
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).
14 * Copyright : Written and Copyright (C) 2000, 2001 by Andreas S. Oesterhelt
15 * <andreas@oesterhelt.org>
17 * Copyright (C) 2006, 2007 Fabian Keil <fk@fabiankeil.de>
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.
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.
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.
40 * Revision 1.28 2007/08/18 14:37:27 fabiankeil
41 * Ditch hex_to_byte() in favour of xtoi().
43 * Revision 1.27 2007/08/05 13:47:04 fabiankeil
44 * #1763173 from Stefan Huehner: s@const static@static const@.
46 * Revision 1.26 2007/07/01 13:29:54 fabiankeil
47 * Add limited hex notation support for the PCRS
48 * substitution text ('\x7e' = '~'). Closes #1627140.
50 * Revision 1.25 2007/04/30 15:02:18 fabiankeil
51 * Introduce dynamic pcrs jobs that can resolve variables.
53 * Revision 1.24 2007/01/05 15:46:12 fabiankeil
54 * Don't use strlen() to calculate the length of
55 * the pcrs substitutes. They don't have to be valid C
56 * strings and getting their length wrong can result in
57 * user-controlled memory corruption.
59 * Thanks to Felix Gröbert for reporting the problem
60 * and providing the fix [#1627140].
62 * Revision 1.23 2006/12/29 17:53:05 fabiankeil
63 * Fixed gcc43 conversion warnings.
65 * Revision 1.22 2006/12/24 17:34:20 fabiankeil
66 * Add pcrs_strerror() message for PCRE_ERROR_MATCHLIMIT
67 * and give a hint why an error code might be unknown.
69 * Catch NULL subjects early in pcrs_execute().
71 * Revision 1.21 2006/07/18 14:48:47 david__schmidt
72 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
73 * with what was really the latest development (the v_3_0_branch branch)
75 * Revision 1.19.2.4 2005/05/07 21:50:55 david__schmidt
76 * A few memory leaks plugged (mostly on error paths)
78 * Revision 1.19.2.3 2003/12/04 12:32:45 oes
79 * Append a trailing nullbyte to result to facilitate string processing
81 * Revision 1.19.2.2 2002/10/08 16:22:28 oes
82 * Bugfix: Need to check validity of backreferences explicitly,
83 * because when max_matches are reached and matches is expanded,
84 * realloc() does not zero the memory. Fixes Bug # 606227
86 * Revision 1.19.2.1 2002/08/10 11:23:40 oes
87 * Include prce.h via project.h, where the appropriate
88 * source will have been selected
90 * Revision 1.19 2002/03/08 14:47:48 oes
93 * Revision 1.18 2002/03/08 14:17:14 oes
94 * Fixing -Wconversion warnings
96 * Revision 1.17 2002/03/08 13:45:48 oes
97 * Hiding internal functions
99 * Revision 1.16 2001/11/30 21:32:14 jongfoster
100 * Fixing signed/unsigned comparison (Andreas please check this!)
103 * Revision 1.15 2001/09/20 16:11:06 steudten
105 * Add casting for some string functions.
107 * Revision 1.14 2001/09/09 21:41:57 oes
108 * Fixing yet another silly bug
110 * Revision 1.13 2001/09/06 14:05:59 oes
113 * Revision 1.12 2001/08/18 11:35:00 oes
114 * - Introduced pcrs_strerror()
115 * - made some NULL arguments non-fatal
116 * - added support for \n \r \e \b \t \f \a \0 in substitute
117 * - made quoting adhere to standard rules
118 * - added warning for bad backrefs
119 * - added pcrs_execute_list()
121 * - bugfix & cosmetics
123 * Revision 1.11 2001/08/15 15:32:03 oes
124 * - Added support for Perl's special variables $+, $' and $`
125 * - Improved the substitute parser
126 * - Replaced the hard limit for the maximum number of matches
127 * by dynamic reallocation
129 * Revision 1.10 2001/08/05 13:13:11 jongfoster
130 * Making parameters "const" where possible.
132 * Revision 1.9 2001/07/18 17:27:00 oes
133 * Changed interface; Cosmetics
135 * Revision 1.8 2001/06/29 21:45:41 oes
136 * Indentation, CRLF->LF, Tab-> Space
138 * Revision 1.7 2001/06/29 13:33:04 oes
139 * - Cleaned up, renamed and reordered functions,
141 * - Removed my_strsep
142 * - Replaced globalflag with a general flags int
143 * that holds PCRS_GLOBAL, PCRS_SUCCESS, and PCRS_TRIVIAL
144 * - Introduced trivial option that will prevent pcrs
145 * from honouring backreferences in the substitute,
146 * which is useful for large substitutes that are
147 * red in from somewhere and saves the pain of escaping
149 * - Introduced convenience function pcrs_free_joblist()
150 * - Split pcrs_make_job() into pcrs_compile(), which still
151 * takes a complete s/// comand as argument and parses it,
152 * and a new function pcrs_make_job, which takes the
153 * three separate components. This should make for a
154 * much friendlier frontend.
155 * - Removed create_pcrs_job() which was useless
156 * - Fixed a bug in pcrs_execute
157 * - Success flag is now handled by pcrs instead of user
159 * Revision 1.6 2001/06/03 19:12:45 oes
162 * Revision 1.5 2001/05/29 09:50:24 jongfoster
163 * (Fixed one int -> size_t)
165 * Revision 1.4 2001/05/25 14:12:40 oes
166 * Fixed bug: Empty substitutes now detected
168 * Revision 1.3 2001/05/25 11:03:55 oes
169 * Added sanity check for NULL jobs to pcrs_exec_substitution
171 * Revision 1.2 2001/05/22 18:46:04 oes
173 * Added support for PCRE_UNGREEDY behaviour to pcrs,
174 * which is selected by the (nonstandard and therefore
175 * capital) letter 'U' in the option string.
176 * It causes the quantifiers to be ungreedy by default.
177 * Appending a ? turns back to greedy (!).
179 * Revision 1.1.1.1 2001/05/15 13:59:02 oes
180 * Initial import of version 2.9.3 source tree
183 *********************************************************************/
191 * Include project.h just so that the right pcre.h gets
192 * included from there
196 /* For snprintf only */
197 #include "miscutil.h"
203 const char pcrs_h_rcs[] = PCRS_H_VERSION;
206 * Internal prototypes
209 static int pcrs_parse_perl_options(const char *optstring, int *flags);
210 static pcrs_substitute *pcrs_compile_replacement(const char *replacement, int trivialflag,
211 int capturecount, int *errptr);
212 static int is_hex_sequence(const char *sequence);
214 /*********************************************************************
216 * Function : pcrs_strerror
218 * Description : Return a string describing a given error code.
221 * 1 : error = the error code
223 * Returns : char * to the descriptive string
225 *********************************************************************/
226 const char *pcrs_strerror(const int error)
232 /* Passed-through PCRE error: */
233 case PCRE_ERROR_NOMEMORY: return "(pcre:) No memory";
235 /* Shouldn't happen unless PCRE or PCRS bug, or user messed with compiled job: */
236 case PCRE_ERROR_NULL: return "(pcre:) NULL code or subject or ovector";
237 case PCRE_ERROR_BADOPTION: return "(pcre:) Unrecognized option bit";
238 case PCRE_ERROR_BADMAGIC: return "(pcre:) Bad magic number in code";
239 case PCRE_ERROR_UNKNOWN_NODE: return "(pcre:) Bad node in pattern";
241 /* Can't happen / not passed: */
242 case PCRE_ERROR_NOSUBSTRING: return "(pcre:) Fire in power supply";
243 case PCRE_ERROR_NOMATCH: return "(pcre:) Water in power supply";
245 #ifdef PCRE_ERROR_MATCHLIMIT
247 * Only reported by PCRE versions newer than our own.
249 case PCRE_ERROR_MATCHLIMIT: return "(pcre:) Match limit reached";
250 #endif /* def PCRE_ERROR_MATCHLIMIT */
253 case PCRS_ERR_NOMEM: return "(pcrs:) No memory";
254 case PCRS_ERR_CMDSYNTAX: return "(pcrs:) Syntax error while parsing command";
255 case PCRS_ERR_STUDY: return "(pcrs:) PCRE error while studying the pattern";
256 case PCRS_ERR_BADJOB: return "(pcrs:) Bad job - NULL job, pattern or substitute";
257 case PCRS_WARN_BADREF: return "(pcrs:) Backreference out of range";
258 case PCRS_WARN_TRUNCATION:
259 return "(pcrs:) At least one variable was too big and has been truncated before compilation";
262 * XXX: With the exception of PCRE_ERROR_MATCHLIMIT we
263 * only catch PCRE errors that can happen with our internal
264 * version. If Privoxy is linked against a newer
265 * PCRE version all bets are off ...
267 default: return "Unknown error. Privoxy out of sync with PCRE?";
270 /* error >= 0: No error */
271 return "(pcrs:) Everything's just fine. Thanks for asking.";
276 /*********************************************************************
278 * Function : pcrs_parse_perl_options
280 * Description : This function parses a string containing the options to
281 * Perl's s/// operator. It returns an integer that is the
282 * pcre equivalent of the symbolic optstring.
283 * Since pcre doesn't know about Perl's 'g' (global) or pcrs',
284 * 'T' (trivial) options but pcrs needs them, the corresponding
285 * flags are set if 'g'or 'T' is encountered.
286 * Note: The 'T' and 'U' options do not conform to Perl.
289 * 1 : optstring = string with options in perl syntax
290 * 2 : flags = see description
292 * Returns : option integer suitable for pcre
294 *********************************************************************/
295 static int pcrs_parse_perl_options(const char *optstring, int *flags)
301 if (NULL == optstring) return 0;
303 for (i = 0; i < strlen(optstring); i++)
307 case 'e': break; /* ToDo ;-) */
308 case 'g': *flags |= PCRS_GLOBAL; break;
309 case 'i': rc |= PCRE_CASELESS; break;
310 case 'm': rc |= PCRE_MULTILINE; break;
312 case 's': rc |= PCRE_DOTALL; break;
313 case 'x': rc |= PCRE_EXTENDED; break;
314 case 'U': rc |= PCRE_UNGREEDY; break;
315 case 'T': *flags |= PCRS_TRIVIAL; break;
324 /*********************************************************************
326 * Function : pcrs_compile_replacement
328 * Description : This function takes a Perl-style replacement (2nd argument
329 * to the s/// operator and returns a compiled pcrs_substitute,
330 * or NULL if memory allocation for the substitute structure
334 * 1 : replacement = replacement part of s/// operator
336 * 2 : trivialflag = Flag that causes backreferences to be
338 * 3 : capturecount = Number of capturing subpatterns in
339 * the pattern. Needed for $+ handling.
340 * 4 : errptr = pointer to an integer in which error
341 * conditions can be returned.
343 * Returns : pcrs_substitute data structure, or NULL if an
344 * error is encountered. In that case, *errptr has
347 *********************************************************************/
348 static pcrs_substitute *pcrs_compile_replacement(const char *replacement, int trivialflag, int capturecount, int *errptr)
355 i = k = l = quoted = 0;
360 if (NULL == replacement)
368 if (NULL == (r = (pcrs_substitute *)malloc(sizeof(pcrs_substitute))))
370 *errptr = PCRS_ERR_NOMEM;
373 memset(r, '\0', sizeof(pcrs_substitute));
375 length = strlen(replacement);
377 if (NULL == (text = (char *)malloc(length + 1)))
380 *errptr = PCRS_ERR_NOMEM;
383 memset(text, '\0', length + 1);
387 * In trivial mode, just copy the substitute text
391 text = strncpy(text, replacement, length + 1);
396 * Else, parse, cut out and record all backreferences
400 while (i < (int)length)
403 if (replacement[i] == '\\')
407 text[k++] = replacement[i++];
412 if (replacement[i+1] && strchr("tnrfae0", replacement[i+1]))
414 switch (replacement[++i])
440 else if (is_hex_sequence(&replacement[i]))
443 * Replace a hex sequence with a single
444 * character with the sequence's ascii value.
445 * e.g.: '\x7e' => '~'
447 const int ascii_value = xtoi(&replacement[i+2]);
449 assert(ascii_value > 0);
450 assert(ascii_value < 256);
451 text[k++] = (char)ascii_value;
464 if (replacement[i] == '$' && !quoted && i < (int)(length - 1))
466 char *symbol, symbols[] = "'`+&";
467 r->block_length[l] = (size_t)(k - r->block_offset[l]);
469 /* Numerical backreferences */
470 if (isdigit((int)replacement[i + 1]))
472 while (i < (int)length && isdigit((int)replacement[++i]))
474 r->backref[l] = r->backref[l] * 10 + replacement[i] - 48;
476 if (r->backref[l] > capturecount)
478 *errptr = PCRS_WARN_BADREF;
482 /* Symbolic backreferences: */
483 else if (NULL != (symbol = strchr(symbols, replacement[i + 1])))
486 if (symbol - symbols == 2) /* $+ */
488 r->backref[l] = capturecount;
490 else if (symbol - symbols == 3) /* $& */
496 r->backref[l] = PCRS_MAX_SUBMATCHES + 1 - (symbol - symbols);
501 /* Invalid backref -> plain '$' */
507 /* Valid and in range? -> record */
508 if (r->backref[l] < PCRS_MAX_SUBMATCHES + 2)
510 r->backref_count[r->backref[l]] += 1;
511 r->block_offset[++l] = k;
515 *errptr = PCRS_WARN_BADREF;
521 /* Plain chars are copied */
522 text[k++] = replacement[i++];
525 } /* -END- if (!trivialflag) */
532 r->length = (size_t)k;
533 r->block_length[l] = (size_t)(k - r->block_offset[l]);
540 /*********************************************************************
542 * Function : pcrs_free_job
544 * Description : Frees the memory used by a pcrs_job struct and its
545 * dependant structures.
548 * 1 : job = pointer to the pcrs_job structure to be freed
550 * Returns : a pointer to the next job, if there was any, or
553 *********************************************************************/
554 pcrs_job *pcrs_free_job(pcrs_job *job)
565 if (job->pattern != NULL) free(job->pattern);
566 if (job->hints != NULL) free(job->hints);
567 if (job->substitute != NULL)
569 if (job->substitute->text != NULL) free(job->substitute->text);
570 free(job->substitute);
579 /*********************************************************************
581 * Function : pcrs_free_joblist
583 * Description : Iterates through a chained list of pcrs_job's and
584 * frees them using pcrs_free_job.
587 * 1 : joblist = pointer to the first pcrs_job structure to
592 *********************************************************************/
593 void pcrs_free_joblist(pcrs_job *joblist)
595 while ( NULL != (joblist = pcrs_free_job(joblist)) ) {};
602 /*********************************************************************
604 * Function : pcrs_compile_command
606 * Description : Parses a string with a Perl-style s/// command,
607 * calls pcrs_compile, and returns a corresponding
608 * pcrs_job, or NULL if parsing or compiling the job
612 * 1 : command = string with perl-style s/// command
613 * 2 : errptr = pointer to an integer in which error
614 * conditions can be returned.
616 * Returns : a corresponding pcrs_job data structure, or NULL
617 * if an error was encountered. In that case, *errptr
620 *********************************************************************/
621 pcrs_job *pcrs_compile_command(const char *command, int *errptr)
623 int i, k, l, quoted = FALSE;
632 * Tokenize the perl command
634 limit = strlen(command);
637 *errptr = PCRS_ERR_CMDSYNTAX;
642 delimiter = command[1];
645 tokens[l] = (char *) malloc(limit + 1);
647 for (i = 0; i <= (int)limit; i++)
650 if (command[i] == delimiter && !quoted)
657 tokens[0][k++] = '\0';
658 tokens[++l] = tokens[0] + k;
662 else if (command[i] == '\\' && !quoted)
665 if (command[i+1] == delimiter) continue;
671 tokens[0][k++] = command[i];
679 *errptr = PCRS_ERR_CMDSYNTAX;
684 newjob = pcrs_compile(tokens[1], tokens[2], tokens[3], errptr);
691 /*********************************************************************
693 * Function : pcrs_compile
695 * Description : Takes the three arguments to a perl s/// command
696 * and compiles a pcrs_job structure from them.
699 * 1 : pattern = string with perl-style pattern
700 * 2 : substitute = string with perl-style substitute
701 * 3 : options = string with perl-style options
702 * 4 : errptr = pointer to an integer in which error
703 * conditions can be returned.
705 * Returns : a corresponding pcrs_job data structure, or NULL
706 * if an error was encountered. In that case, *errptr
709 *********************************************************************/
710 pcrs_job *pcrs_compile(const char *pattern, const char *substitute, const char *options, int *errptr)
720 * Handle NULL arguments
722 if (pattern == NULL) pattern = "";
723 if (substitute == NULL) substitute = "";
727 * Get and init memory
729 if (NULL == (newjob = (pcrs_job *)malloc(sizeof(pcrs_job))))
731 *errptr = PCRS_ERR_NOMEM;
734 memset(newjob, '\0', sizeof(pcrs_job));
738 * Evaluate the options
740 newjob->options = pcrs_parse_perl_options(options, &flags);
741 newjob->flags = flags;
745 * Compile the pattern
747 newjob->pattern = pcre_compile(pattern, newjob->options, &error, errptr, NULL);
748 if (newjob->pattern == NULL)
750 pcrs_free_job(newjob);
756 * Generate hints. This has little overhead, since the
757 * hints will be NULL for a boring pattern anyway.
759 newjob->hints = pcre_study(newjob->pattern, 0, &error);
762 *errptr = PCRS_ERR_STUDY;
763 pcrs_free_job(newjob);
769 * Determine the number of capturing subpatterns.
770 * This is needed for handling $+ in the substitute.
772 if (0 > (*errptr = pcre_fullinfo(newjob->pattern, newjob->hints, PCRE_INFO_CAPTURECOUNT, &capturecount)))
774 pcrs_free_job(newjob);
780 * Compile the substitute
782 if (NULL == (newjob->substitute = pcrs_compile_replacement(substitute, newjob->flags & PCRS_TRIVIAL, capturecount, errptr)))
784 pcrs_free_job(newjob);
793 /*********************************************************************
795 * Function : pcrs_execute_list
797 * Description : This is a multiple job wrapper for pcrs_execute().
798 * Apply the regular substitutions defined by the jobs in
799 * the joblist to the subject.
800 * The subject itself is left untouched, memory for the result
801 * is malloc()ed and it is the caller's responsibility to free
802 * the result when it's no longer needed.
804 * Note: For convenient string handling, a null byte is
805 * appended to the result. It does not count towards the
806 * result_length, though.
810 * 1 : joblist = the chained list of pcrs_jobs to be executed
811 * 2 : subject = the subject string
812 * 3 : subject_length = the subject's length
813 * 4 : result = char** for returning the result
814 * 5 : result_length = size_t* for returning the result's length
816 * Returns : On success, the number of substitutions that were made.
817 * May be > 1 if job->flags contained PCRS_GLOBAL
818 * On failure, the (negative) pcre error code describing the
819 * failure, which may be translated to text using pcrs_strerror().
821 *********************************************************************/
822 int pcrs_execute_list(pcrs_job *joblist, char *subject, size_t subject_length, char **result, size_t *result_length)
825 char *old, *new = NULL;
826 int hits, total_hits;
829 *result_length = subject_length;
830 hits = total_hits = 0;
832 for (job = joblist; job != NULL; job = job->next)
834 hits = pcrs_execute(job, old, *result_length, &new, result_length);
836 if (old != subject) free(old);
855 /*********************************************************************
857 * Function : pcrs_execute
859 * Description : Apply the regular substitution defined by the job to the
861 * The subject itself is left untouched, memory for the result
862 * is malloc()ed and it is the caller's responsibility to free
863 * the result when it's no longer needed.
865 * Note: For convenient string handling, a null byte is
866 * appended to the result. It does not count towards the
867 * result_length, though.
870 * 1 : job = the pcrs_job to be executed
871 * 2 : subject = the subject (== original) string
872 * 3 : subject_length = the subject's length
873 * 4 : result = char** for returning the result
874 * 5 : result_length = size_t* for returning the result's length
876 * Returns : On success, the number of substitutions that were made.
877 * May be > 1 if job->flags contained PCRS_GLOBAL
878 * On failure, the (negative) pcre error code describing the
879 * failure, which may be translated to text using pcrs_strerror().
881 *********************************************************************/
882 int pcrs_execute(pcrs_job *job, const char *subject, size_t subject_length, char **result, size_t *result_length)
884 int offsets[3 * PCRS_MAX_SUBMATCHES],
889 max_matches = PCRS_MAX_MATCH_INIT;
891 pcrs_match *matches, *dummy;
897 * Sanity check & memory allocation
899 if (job == NULL || job->pattern == NULL || job->substitute == NULL || NULL == subject)
902 return(PCRS_ERR_BADJOB);
905 if (NULL == (matches = (pcrs_match *)malloc((size_t)max_matches * sizeof(pcrs_match))))
908 return(PCRS_ERR_NOMEM);
910 memset(matches, '\0', (size_t)max_matches * sizeof(pcrs_match));
914 * Find the pattern and calculate the space
915 * requirements for the result
917 newsize = subject_length;
919 while ((submatches = pcre_exec(job->pattern, job->hints, subject, (int)subject_length, offset, 0, offsets, 3 * PCRS_MAX_SUBMATCHES)) > 0)
921 job->flags |= PCRS_SUCCESS;
922 matches[i].submatches = submatches;
924 for (k = 0; k < submatches; k++)
926 matches[i].submatch_offset[k] = offsets[2 * k];
928 /* Note: Non-found optional submatches have length -1-(-1)==0 */
929 matches[i].submatch_length[k] = (size_t)(offsets[2 * k + 1] - offsets[2 * k]);
931 /* reserve mem for each submatch as often as it is ref'd */
932 newsize += matches[i].submatch_length[k] * (size_t)job->substitute->backref_count[k];
934 /* plus replacement text size minus match text size */
935 newsize += job->substitute->length - matches[i].submatch_length[0];
937 /* chunk before match */
938 matches[i].submatch_offset[PCRS_MAX_SUBMATCHES] = 0;
939 matches[i].submatch_length[PCRS_MAX_SUBMATCHES] = (size_t)offsets[0];
940 newsize += (size_t)offsets[0] * (size_t)job->substitute->backref_count[PCRS_MAX_SUBMATCHES];
942 /* chunk after match */
943 matches[i].submatch_offset[PCRS_MAX_SUBMATCHES + 1] = offsets[1];
944 matches[i].submatch_length[PCRS_MAX_SUBMATCHES + 1] = subject_length - (size_t)offsets[1] - 1;
945 newsize += (subject_length - (size_t)offsets[1]) * (size_t)job->substitute->backref_count[PCRS_MAX_SUBMATCHES + 1];
947 /* Storage for matches exhausted? -> Extend! */
948 if (++i >= max_matches)
950 max_matches = (int)(max_matches * PCRS_MAX_MATCH_GROW);
951 if (NULL == (dummy = (pcrs_match *)realloc(matches, (size_t)max_matches * sizeof(pcrs_match))))
955 return(PCRS_ERR_NOMEM);
960 /* Non-global search or limit reached? */
961 if (!(job->flags & PCRS_GLOBAL)) break;
963 /* Don't loop on empty matches */
964 if (offsets[1] == offset)
965 if ((size_t)offset < subject_length)
969 /* Go find the next one */
973 /* Pass pcre error through if (bad) failiure */
974 if (submatches < PCRE_ERROR_NOMATCH)
983 * Get memory for the result (must be freed by caller!)
984 * and append terminating null byte.
986 if ((*result = (char *)malloc(newsize + 1)) == NULL)
989 return PCRS_ERR_NOMEM;
993 (*result)[newsize] = '\0';
1001 result_offset = *result;
1003 for (i = 0; i < matches_found; i++)
1005 /* copy the chunk preceding the match */
1006 memcpy(result_offset, subject + offset, (size_t)(matches[i].submatch_offset[0] - offset));
1007 result_offset += matches[i].submatch_offset[0] - offset;
1009 /* For every segment of the substitute.. */
1010 for (k = 0; k <= job->substitute->backrefs; k++)
1012 /* ...copy its text.. */
1013 memcpy(result_offset, job->substitute->text + job->substitute->block_offset[k], job->substitute->block_length[k]);
1014 result_offset += job->substitute->block_length[k];
1016 /* ..plus, if it's not the last chunk, i.e.: There *is* a backref.. */
1017 if (k != job->substitute->backrefs
1018 /* ..in legal range.. */
1019 && job->substitute->backref[k] < PCRS_MAX_SUBMATCHES + 2
1020 /* ..and referencing a real submatch.. */
1021 && job->substitute->backref[k] < matches[i].submatches
1022 /* ..that is nonempty.. */
1023 && matches[i].submatch_length[job->substitute->backref[k]] > 0)
1025 /* ..copy the submatch that is ref'd. */
1028 subject + matches[i].submatch_offset[job->substitute->backref[k]],
1029 matches[i].submatch_length[job->substitute->backref[k]]
1031 result_offset += matches[i].submatch_length[job->substitute->backref[k]];
1034 offset = matches[i].submatch_offset[0] + (int)matches[i].submatch_length[0];
1037 /* Copy the rest. */
1038 memcpy(result_offset, subject + offset, subject_length - (size_t)offset);
1040 *result_length = newsize;
1042 return matches_found;
1047 #define is_hex_digit(x) ((x) && strchr("0123456789ABCDEF", toupper(x)))
1049 /*********************************************************************
1051 * Function : is_hex_sequence
1053 * Description : Checks the first four characters of a string
1054 * and decides if they are a valid hex sequence
1058 * 1 : sequence = The string to check
1060 * Returns : Non-zero if it's valid sequence, or
1063 *********************************************************************/
1064 static int is_hex_sequence(const char *sequence)
1066 return (sequence[0] == '\\' &&
1067 sequence[1] == 'x' &&
1068 is_hex_digit(sequence[2]) &&
1069 is_hex_digit(sequence[3]));
1074 * Functions below this line are only part of the pcrs version
1075 * included in Privoxy. If you use any of them you should not
1076 * try to dynamically link against external pcrs versions.
1079 /*********************************************************************
1081 * Function : pcrs_job_is_dynamic
1083 * Description : Checks if a job has the "D" (dynamic) option set.
1086 * 1 : job = The job to check
1088 * Returns : TRUE if the job is indeed dynamic, otherwise
1091 *********************************************************************/
1092 int pcrs_job_is_dynamic (char *job)
1094 const char delimiter = job[1];
1095 const size_t length = strlen(job);
1101 * The shortest valid (but useless)
1102 * dynamic pattern is "s@@@D"
1108 * Everything between the last character
1109 * and the last delimiter is an option ...
1111 for (option = job + length; *option != delimiter; option--)
1116 * ... and if said option is 'D' the job is dynamic.
1126 /*********************************************************************
1128 * Function : pcrs_get_delimiter
1130 * Description : Tries to find a character that is safe to
1131 * be used as a pcrs delimiter for a certain string.
1134 * 1 : string = The string to search in
1136 * Returns : A safe delimiter if one was found, otherwise '\0'.
1138 *********************************************************************/
1139 char pcrs_get_delimiter(const char *string)
1142 * Some characters that are unlikely to
1143 * be part of pcrs replacement strings.
1145 char delimiters[] = "><§#+*~%^°-:;µ!@";
1146 char *d = delimiters;
1148 /* Take the first delimiter that isn't part of the string */
1149 while (*d && NULL != strchr(string, *d))
1158 /*********************************************************************
1160 * Function : pcrs_execute_single_command
1162 * Description : Apply single pcrs command to the subject.
1163 * The subject itself is left untouched, memory for the result
1164 * is malloc()ed and it is the caller's responsibility to free
1165 * the result when it's no longer needed.
1168 * 1 : subject = the subject (== original) string
1169 * 2 : pcrs_command = the pcrs command as string (s@foo@bar@)
1170 * 3 : hits = int* for returning the number of modifications
1172 * Returns : NULL in case of errors, otherwise the
1173 * result of the pcrs command.
1175 *********************************************************************/
1176 char *pcrs_execute_single_command(const char *subject, const char *pcrs_command, int *hits)
1179 char *result = NULL;
1183 assert(pcrs_command);
1186 size = strlen(subject);
1188 job = pcrs_compile_command(pcrs_command, hits);
1191 *hits = pcrs_execute(job, subject, size, &result, &size);
1203 static const char warning[] = "... [too long, truncated]";
1204 /*********************************************************************
1206 * Function : pcrs_compile_dynamic_command
1208 * Description : Takes a dynamic pcrs command, fills in the
1209 * values of the variables and compiles it.
1212 * 1 : csp = Current client state (buffers, headers, etc...)
1213 * 2 : pcrs_command = The dynamic pcrs command to compile
1214 * 3 : v = NULL terminated array of variables and their values.
1215 * 4 : error = pcrs error code
1217 * Returns : NULL in case of hard errors, otherwise the
1218 * compiled pcrs job.
1220 *********************************************************************/
1221 pcrs_job *pcrs_compile_dynamic_command(char *pcrs_command, const struct pcrs_variable v[], int *error)
1223 char buf[PCRS_BUFFER_SIZE];
1224 const char *original_pcrs_command = pcrs_command;
1225 char *pcrs_command_tmp = NULL;
1226 pcrs_job *job = NULL;
1231 while ((NULL != v->name) && (NULL != pcrs_command))
1233 assert(NULL != v->value);
1235 if (NULL == strstr(pcrs_command, v->name))
1238 * Skip the substitution if the variable
1239 * name isn't part of the pattern.
1245 /* Use pcrs to replace the variable with its value. */
1246 d = pcrs_get_delimiter(v->value);
1249 /* No proper delimiter found */
1250 *error = PCRS_ERR_CMDSYNTAX;
1255 * Variable names are supposed to contain alpha
1256 * numerical characters plus '_' only.
1258 assert(NULL == strchr(v->name, d));
1260 ret = snprintf(buf, sizeof(buf), "s%c\\$%s%c%s%cgT", d, v->name, d, v->value, d);
1262 if (ret >= sizeof(buf))
1265 * Value didn't completely fit into buffer,
1266 * overwrite the end of the substitution text
1267 * with a truncation message and close the pattern
1270 const size_t trailer_size = sizeof(warning) + 3; /* 3 for d + "gT" */
1271 char *trailer_start = buf + sizeof(buf) - trailer_size;
1273 ret = snprintf(trailer_start, trailer_size, "%s%cgT", warning, d);
1274 assert(ret == trailer_size - 1);
1275 assert(sizeof(buf) == strlen(buf) + 1);
1279 pcrs_command_tmp = pcrs_execute_single_command(pcrs_command, buf, error);
1280 if (NULL == pcrs_command_tmp)
1285 if (pcrs_command != original_pcrs_command)
1287 freez(pcrs_command);
1289 pcrs_command = pcrs_command_tmp;
1294 job = pcrs_compile_command(pcrs_command, error);
1295 if (pcrs_command != original_pcrs_command)
1297 freez(pcrs_command);
1302 *error = PCRS_WARN_TRUNCATION;