1 const char pcrs_rcs[] = "$Id: pcrs.c,v 1.25 2007/04/30 15:02:18 fabiankeil Exp $";
3 /*********************************************************************
5 * File : $Source: /cvsroot/ijbswa/current/pcrs.c,v $
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.
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).
15 * Copyright : Written and Copyright (C) 2000, 2001 by Andreas S. Oesterhelt
16 * <andreas@oesterhelt.org>
18 * Copyright (C) 2006, 2007 Fabian Keil <fk@fabiankeil.de>
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.
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.
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.
41 * Revision 1.25 2007/04/30 15:02:18 fabiankeil
42 * Introduce dynamic pcrs jobs that can resolve variables.
44 * Revision 1.24 2007/01/05 15:46:12 fabiankeil
45 * Don't use strlen() to calculate the length of
46 * the pcrs substitutes. They don't have to be valid C
47 * strings and getting their length wrong can result in
48 * user-controlled memory corruption.
50 * Thanks to Felix Gröbert for reporting the problem
51 * and providing the fix [#1627140].
53 * Revision 1.23 2006/12/29 17:53:05 fabiankeil
54 * Fixed gcc43 conversion warnings.
56 * Revision 1.22 2006/12/24 17:34:20 fabiankeil
57 * Add pcrs_strerror() message for PCRE_ERROR_MATCHLIMIT
58 * and give a hint why an error code might be unknown.
60 * Catch NULL subjects early in pcrs_execute().
62 * Revision 1.21 2006/07/18 14:48:47 david__schmidt
63 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
64 * with what was really the latest development (the v_3_0_branch branch)
66 * Revision 1.19.2.4 2005/05/07 21:50:55 david__schmidt
67 * A few memory leaks plugged (mostly on error paths)
69 * Revision 1.19.2.3 2003/12/04 12:32:45 oes
70 * Append a trailing nullbyte to result to facilitate string processing
72 * Revision 1.19.2.2 2002/10/08 16:22:28 oes
73 * Bugfix: Need to check validity of backreferences explicitly,
74 * because when max_matches are reached and matches is expanded,
75 * realloc() does not zero the memory. Fixes Bug # 606227
77 * Revision 1.19.2.1 2002/08/10 11:23:40 oes
78 * Include prce.h via project.h, where the appropriate
79 * source will have been selected
81 * Revision 1.19 2002/03/08 14:47:48 oes
84 * Revision 1.18 2002/03/08 14:17:14 oes
85 * Fixing -Wconversion warnings
87 * Revision 1.17 2002/03/08 13:45:48 oes
88 * Hiding internal functions
90 * Revision 1.16 2001/11/30 21:32:14 jongfoster
91 * Fixing signed/unsigned comparison (Andreas please check this!)
94 * Revision 1.15 2001/09/20 16:11:06 steudten
96 * Add casting for some string functions.
98 * Revision 1.14 2001/09/09 21:41:57 oes
99 * Fixing yet another silly bug
101 * Revision 1.13 2001/09/06 14:05:59 oes
104 * Revision 1.12 2001/08/18 11:35:00 oes
105 * - Introduced pcrs_strerror()
106 * - made some NULL arguments non-fatal
107 * - added support for \n \r \e \b \t \f \a \0 in substitute
108 * - made quoting adhere to standard rules
109 * - added warning for bad backrefs
110 * - added pcrs_execute_list()
112 * - bugfix & cosmetics
114 * Revision 1.11 2001/08/15 15:32:03 oes
115 * - Added support for Perl's special variables $+, $' and $`
116 * - Improved the substitute parser
117 * - Replaced the hard limit for the maximum number of matches
118 * by dynamic reallocation
120 * Revision 1.10 2001/08/05 13:13:11 jongfoster
121 * Making parameters "const" where possible.
123 * Revision 1.9 2001/07/18 17:27:00 oes
124 * Changed interface; Cosmetics
126 * Revision 1.8 2001/06/29 21:45:41 oes
127 * Indentation, CRLF->LF, Tab-> Space
129 * Revision 1.7 2001/06/29 13:33:04 oes
130 * - Cleaned up, renamed and reordered functions,
132 * - Removed my_strsep
133 * - Replaced globalflag with a general flags int
134 * that holds PCRS_GLOBAL, PCRS_SUCCESS, and PCRS_TRIVIAL
135 * - Introduced trivial option that will prevent pcrs
136 * from honouring backreferences in the substitute,
137 * which is useful for large substitutes that are
138 * red in from somewhere and saves the pain of escaping
140 * - Introduced convenience function pcrs_free_joblist()
141 * - Split pcrs_make_job() into pcrs_compile(), which still
142 * takes a complete s/// comand as argument and parses it,
143 * and a new function pcrs_make_job, which takes the
144 * three separate components. This should make for a
145 * much friendlier frontend.
146 * - Removed create_pcrs_job() which was useless
147 * - Fixed a bug in pcrs_execute
148 * - Success flag is now handled by pcrs instead of user
150 * Revision 1.6 2001/06/03 19:12:45 oes
153 * Revision 1.5 2001/05/29 09:50:24 jongfoster
154 * (Fixed one int -> size_t)
156 * Revision 1.4 2001/05/25 14:12:40 oes
157 * Fixed bug: Empty substitutes now detected
159 * Revision 1.3 2001/05/25 11:03:55 oes
160 * Added sanity check for NULL jobs to pcrs_exec_substitution
162 * Revision 1.2 2001/05/22 18:46:04 oes
164 * Added support for PCRE_UNGREEDY behaviour to pcrs,
165 * which is selected by the (nonstandard and therefore
166 * capital) letter 'U' in the option string.
167 * It causes the quantifiers to be ungreedy by default.
168 * Appending a ? turns back to greedy (!).
170 * Revision 1.1.1.1 2001/05/15 13:59:02 oes
171 * Initial import of version 2.9.3 source tree
174 *********************************************************************/
178 * Include project.h just so that the right pcre.h gets
179 * included from there
183 /* For snprintf only */
184 #include "miscutil.h"
192 const char pcrs_h_rcs[] = PCRS_H_VERSION;
195 * Internal prototypes
198 static int pcrs_parse_perl_options(const char *optstring, int *flags);
199 static pcrs_substitute *pcrs_compile_replacement(const char *replacement, int trivialflag,
200 int capturecount, int *errptr);
201 static int is_hex_sequence(const char *sequence);
202 static char hex_to_byte(const char *sequence);
204 /*********************************************************************
206 * Function : pcrs_strerror
208 * Description : Return a string describing a given error code.
211 * 1 : error = the error code
213 * Returns : char * to the descriptive string
215 *********************************************************************/
216 const char *pcrs_strerror(const int error)
222 /* Passed-through PCRE error: */
223 case PCRE_ERROR_NOMEMORY: return "(pcre:) No memory";
225 /* Shouldn't happen unless PCRE or PCRS bug, or user messed with compiled job: */
226 case PCRE_ERROR_NULL: return "(pcre:) NULL code or subject or ovector";
227 case PCRE_ERROR_BADOPTION: return "(pcre:) Unrecognized option bit";
228 case PCRE_ERROR_BADMAGIC: return "(pcre:) Bad magic number in code";
229 case PCRE_ERROR_UNKNOWN_NODE: return "(pcre:) Bad node in pattern";
231 /* Can't happen / not passed: */
232 case PCRE_ERROR_NOSUBSTRING: return "(pcre:) Fire in power supply";
233 case PCRE_ERROR_NOMATCH: return "(pcre:) Water in power supply";
235 #ifdef PCRE_ERROR_MATCHLIMIT
237 * Only reported by PCRE versions newer than our own.
239 case PCRE_ERROR_MATCHLIMIT: return "(pcre:) Match limit reached";
240 #endif /* def PCRE_ERROR_MATCHLIMIT */
243 case PCRS_ERR_NOMEM: return "(pcrs:) No memory";
244 case PCRS_ERR_CMDSYNTAX: return "(pcrs:) Syntax error while parsing command";
245 case PCRS_ERR_STUDY: return "(pcrs:) PCRE error while studying the pattern";
246 case PCRS_ERR_BADJOB: return "(pcrs:) Bad job - NULL job, pattern or substitute";
247 case PCRS_WARN_BADREF: return "(pcrs:) Backreference out of range";
248 case PCRS_WARN_TRUNCATION:
249 return "(pcrs:) At least one variable was too big and has been truncated before compilation";
252 * XXX: With the exception of PCRE_ERROR_MATCHLIMIT we
253 * only catch PCRE errors that can happen with our internal
254 * version. If Privoxy is linked against a newer
255 * PCRE version all bets are off ...
257 default: return "Unknown error. Privoxy out of sync with PCRE?";
260 /* error >= 0: No error */
261 return "(pcrs:) Everything's just fine. Thanks for asking.";
266 /*********************************************************************
268 * Function : pcrs_parse_perl_options
270 * Description : This function parses a string containing the options to
271 * Perl's s/// operator. It returns an integer that is the
272 * pcre equivalent of the symbolic optstring.
273 * Since pcre doesn't know about Perl's 'g' (global) or pcrs',
274 * 'T' (trivial) options but pcrs needs them, the corresponding
275 * flags are set if 'g'or 'T' is encountered.
276 * Note: The 'T' and 'U' options do not conform to Perl.
279 * 1 : optstring = string with options in perl syntax
280 * 2 : flags = see description
282 * Returns : option integer suitable for pcre
284 *********************************************************************/
285 static int pcrs_parse_perl_options(const char *optstring, int *flags)
291 if (NULL == optstring) return 0;
293 for (i = 0; i < strlen(optstring); i++)
297 case 'e': break; /* ToDo ;-) */
298 case 'g': *flags |= PCRS_GLOBAL; break;
299 case 'i': rc |= PCRE_CASELESS; break;
300 case 'm': rc |= PCRE_MULTILINE; break;
302 case 's': rc |= PCRE_DOTALL; break;
303 case 'x': rc |= PCRE_EXTENDED; break;
304 case 'U': rc |= PCRE_UNGREEDY; break;
305 case 'T': *flags |= PCRS_TRIVIAL; break;
314 /*********************************************************************
316 * Function : pcrs_compile_replacement
318 * Description : This function takes a Perl-style replacement (2nd argument
319 * to the s/// operator and returns a compiled pcrs_substitute,
320 * or NULL if memory allocation for the substitute structure
324 * 1 : replacement = replacement part of s/// operator
326 * 2 : trivialflag = Flag that causes backreferences to be
328 * 3 : capturecount = Number of capturing subpatterns in
329 * the pattern. Needed for $+ handling.
330 * 4 : errptr = pointer to an integer in which error
331 * conditions can be returned.
333 * Returns : pcrs_substitute data structure, or NULL if an
334 * error is encountered. In that case, *errptr has
337 *********************************************************************/
338 static pcrs_substitute *pcrs_compile_replacement(const char *replacement, int trivialflag, int capturecount, int *errptr)
345 i = k = l = quoted = 0;
350 if (NULL == replacement)
358 if (NULL == (r = (pcrs_substitute *)malloc(sizeof(pcrs_substitute))))
360 *errptr = PCRS_ERR_NOMEM;
363 memset(r, '\0', sizeof(pcrs_substitute));
365 length = strlen(replacement);
367 if (NULL == (text = (char *)malloc(length + 1)))
370 *errptr = PCRS_ERR_NOMEM;
373 memset(text, '\0', length + 1);
377 * In trivial mode, just copy the substitute text
381 text = strncpy(text, replacement, length + 1);
386 * Else, parse, cut out and record all backreferences
390 while (i < (int)length)
393 if (replacement[i] == '\\')
397 text[k++] = replacement[i++];
402 if (replacement[i+1] && strchr("tnrfae0", replacement[i+1]))
404 switch (replacement[++i])
430 else if (is_hex_sequence(&replacement[i]))
432 text[k++] = hex_to_byte(&replacement[i+2]);
445 if (replacement[i] == '$' && !quoted && i < (int)(length - 1))
447 char *symbol, symbols[] = "'`+&";
448 r->block_length[l] = (size_t)(k - r->block_offset[l]);
450 /* Numerical backreferences */
451 if (isdigit((int)replacement[i + 1]))
453 while (i < (int)length && isdigit((int)replacement[++i]))
455 r->backref[l] = r->backref[l] * 10 + replacement[i] - 48;
457 if (r->backref[l] > capturecount)
459 *errptr = PCRS_WARN_BADREF;
463 /* Symbolic backreferences: */
464 else if (NULL != (symbol = strchr(symbols, replacement[i + 1])))
467 if (symbol - symbols == 2) /* $+ */
469 r->backref[l] = capturecount;
471 else if (symbol - symbols == 3) /* $& */
477 r->backref[l] = PCRS_MAX_SUBMATCHES + 1 - (symbol - symbols);
482 /* Invalid backref -> plain '$' */
488 /* Valid and in range? -> record */
489 if (r->backref[l] < PCRS_MAX_SUBMATCHES + 2)
491 r->backref_count[r->backref[l]] += 1;
492 r->block_offset[++l] = k;
496 *errptr = PCRS_WARN_BADREF;
502 /* Plain chars are copied */
503 text[k++] = replacement[i++];
506 } /* -END- if (!trivialflag) */
513 r->length = (size_t)k;
514 r->block_length[l] = (size_t)(k - r->block_offset[l]);
521 /*********************************************************************
523 * Function : pcrs_free_job
525 * Description : Frees the memory used by a pcrs_job struct and its
526 * dependant structures.
529 * 1 : job = pointer to the pcrs_job structure to be freed
531 * Returns : a pointer to the next job, if there was any, or
534 *********************************************************************/
535 pcrs_job *pcrs_free_job(pcrs_job *job)
546 if (job->pattern != NULL) free(job->pattern);
547 if (job->hints != NULL) free(job->hints);
548 if (job->substitute != NULL)
550 if (job->substitute->text != NULL) free(job->substitute->text);
551 free(job->substitute);
560 /*********************************************************************
562 * Function : pcrs_free_joblist
564 * Description : Iterates through a chained list of pcrs_job's and
565 * frees them using pcrs_free_job.
568 * 1 : joblist = pointer to the first pcrs_job structure to
573 *********************************************************************/
574 void pcrs_free_joblist(pcrs_job *joblist)
576 while ( NULL != (joblist = pcrs_free_job(joblist)) ) {};
583 /*********************************************************************
585 * Function : pcrs_compile_command
587 * Description : Parses a string with a Perl-style s/// command,
588 * calls pcrs_compile, and returns a corresponding
589 * pcrs_job, or NULL if parsing or compiling the job
593 * 1 : command = string with perl-style s/// command
594 * 2 : errptr = pointer to an integer in which error
595 * conditions can be returned.
597 * Returns : a corresponding pcrs_job data structure, or NULL
598 * if an error was encountered. In that case, *errptr
601 *********************************************************************/
602 pcrs_job *pcrs_compile_command(const char *command, int *errptr)
604 int i, k, l, quoted = FALSE;
613 * Tokenize the perl command
615 limit = strlen(command);
618 *errptr = PCRS_ERR_CMDSYNTAX;
623 delimiter = command[1];
626 tokens[l] = (char *) malloc(limit + 1);
628 for (i = 0; i <= (int)limit; i++)
631 if (command[i] == delimiter && !quoted)
638 tokens[0][k++] = '\0';
639 tokens[++l] = tokens[0] + k;
643 else if (command[i] == '\\' && !quoted)
646 if (command[i+1] == delimiter) continue;
652 tokens[0][k++] = command[i];
660 *errptr = PCRS_ERR_CMDSYNTAX;
665 newjob = pcrs_compile(tokens[1], tokens[2], tokens[3], errptr);
672 /*********************************************************************
674 * Function : pcrs_compile
676 * Description : Takes the three arguments to a perl s/// command
677 * and compiles a pcrs_job structure from them.
680 * 1 : pattern = string with perl-style pattern
681 * 2 : substitute = string with perl-style substitute
682 * 3 : options = string with perl-style options
683 * 4 : errptr = pointer to an integer in which error
684 * conditions can be returned.
686 * Returns : a corresponding pcrs_job data structure, or NULL
687 * if an error was encountered. In that case, *errptr
690 *********************************************************************/
691 pcrs_job *pcrs_compile(const char *pattern, const char *substitute, const char *options, int *errptr)
701 * Handle NULL arguments
703 if (pattern == NULL) pattern = "";
704 if (substitute == NULL) substitute = "";
708 * Get and init memory
710 if (NULL == (newjob = (pcrs_job *)malloc(sizeof(pcrs_job))))
712 *errptr = PCRS_ERR_NOMEM;
715 memset(newjob, '\0', sizeof(pcrs_job));
719 * Evaluate the options
721 newjob->options = pcrs_parse_perl_options(options, &flags);
722 newjob->flags = flags;
726 * Compile the pattern
728 newjob->pattern = pcre_compile(pattern, newjob->options, &error, errptr, NULL);
729 if (newjob->pattern == NULL)
731 pcrs_free_job(newjob);
737 * Generate hints. This has little overhead, since the
738 * hints will be NULL for a boring pattern anyway.
740 newjob->hints = pcre_study(newjob->pattern, 0, &error);
743 *errptr = PCRS_ERR_STUDY;
744 pcrs_free_job(newjob);
750 * Determine the number of capturing subpatterns.
751 * This is needed for handling $+ in the substitute.
753 if (0 > (*errptr = pcre_fullinfo(newjob->pattern, newjob->hints, PCRE_INFO_CAPTURECOUNT, &capturecount)))
755 pcrs_free_job(newjob);
761 * Compile the substitute
763 if (NULL == (newjob->substitute = pcrs_compile_replacement(substitute, newjob->flags & PCRS_TRIVIAL, capturecount, errptr)))
765 pcrs_free_job(newjob);
774 /*********************************************************************
776 * Function : pcrs_execute_list
778 * Description : This is a multiple job wrapper for pcrs_execute().
779 * Apply the regular substitutions defined by the jobs in
780 * the joblist to the subject.
781 * The subject itself is left untouched, memory for the result
782 * is malloc()ed and it is the caller's responsibility to free
783 * the result when it's no longer needed.
785 * Note: For convenient string handling, a null byte is
786 * appended to the result. It does not count towards the
787 * result_length, though.
791 * 1 : joblist = the chained list of pcrs_jobs to be executed
792 * 2 : subject = the subject string
793 * 3 : subject_length = the subject's length
794 * 4 : result = char** for returning the result
795 * 5 : result_length = size_t* for returning the result's length
797 * Returns : On success, the number of substitutions that were made.
798 * May be > 1 if job->flags contained PCRS_GLOBAL
799 * On failure, the (negative) pcre error code describing the
800 * failure, which may be translated to text using pcrs_strerror().
802 *********************************************************************/
803 int pcrs_execute_list(pcrs_job *joblist, char *subject, size_t subject_length, char **result, size_t *result_length)
806 char *old, *new = NULL;
807 int hits, total_hits;
810 *result_length = subject_length;
811 hits = total_hits = 0;
813 for (job = joblist; job != NULL; job = job->next)
815 hits = pcrs_execute(job, old, *result_length, &new, result_length);
817 if (old != subject) free(old);
836 /*********************************************************************
838 * Function : pcrs_execute
840 * Description : Apply the regular substitution defined by the job to the
842 * The subject itself is left untouched, memory for the result
843 * is malloc()ed and it is the caller's responsibility to free
844 * the result when it's no longer needed.
846 * Note: For convenient string handling, a null byte is
847 * appended to the result. It does not count towards the
848 * result_length, though.
851 * 1 : job = the pcrs_job to be executed
852 * 2 : subject = the subject (== original) string
853 * 3 : subject_length = the subject's length
854 * 4 : result = char** for returning the result
855 * 5 : result_length = size_t* for returning the result's length
857 * Returns : On success, the number of substitutions that were made.
858 * May be > 1 if job->flags contained PCRS_GLOBAL
859 * On failure, the (negative) pcre error code describing the
860 * failure, which may be translated to text using pcrs_strerror().
862 *********************************************************************/
863 int pcrs_execute(pcrs_job *job, const char *subject, size_t subject_length, char **result, size_t *result_length)
865 int offsets[3 * PCRS_MAX_SUBMATCHES],
870 max_matches = PCRS_MAX_MATCH_INIT;
872 pcrs_match *matches, *dummy;
878 * Sanity check & memory allocation
880 if (job == NULL || job->pattern == NULL || job->substitute == NULL || NULL == subject)
883 return(PCRS_ERR_BADJOB);
886 if (NULL == (matches = (pcrs_match *)malloc((size_t)max_matches * sizeof(pcrs_match))))
889 return(PCRS_ERR_NOMEM);
891 memset(matches, '\0', (size_t)max_matches * sizeof(pcrs_match));
895 * Find the pattern and calculate the space
896 * requirements for the result
898 newsize = subject_length;
900 while ((submatches = pcre_exec(job->pattern, job->hints, subject, (int)subject_length, offset, 0, offsets, 3 * PCRS_MAX_SUBMATCHES)) > 0)
902 job->flags |= PCRS_SUCCESS;
903 matches[i].submatches = submatches;
905 for (k = 0; k < submatches; k++)
907 matches[i].submatch_offset[k] = offsets[2 * k];
909 /* Note: Non-found optional submatches have length -1-(-1)==0 */
910 matches[i].submatch_length[k] = (size_t)(offsets[2 * k + 1] - offsets[2 * k]);
912 /* reserve mem for each submatch as often as it is ref'd */
913 newsize += matches[i].submatch_length[k] * (size_t)job->substitute->backref_count[k];
915 /* plus replacement text size minus match text size */
916 newsize += job->substitute->length - matches[i].submatch_length[0];
918 /* chunk before match */
919 matches[i].submatch_offset[PCRS_MAX_SUBMATCHES] = 0;
920 matches[i].submatch_length[PCRS_MAX_SUBMATCHES] = (size_t)offsets[0];
921 newsize += (size_t)offsets[0] * (size_t)job->substitute->backref_count[PCRS_MAX_SUBMATCHES];
923 /* chunk after match */
924 matches[i].submatch_offset[PCRS_MAX_SUBMATCHES + 1] = offsets[1];
925 matches[i].submatch_length[PCRS_MAX_SUBMATCHES + 1] = subject_length - (size_t)offsets[1] - 1;
926 newsize += (subject_length - (size_t)offsets[1]) * (size_t)job->substitute->backref_count[PCRS_MAX_SUBMATCHES + 1];
928 /* Storage for matches exhausted? -> Extend! */
929 if (++i >= max_matches)
931 max_matches = (int)(max_matches * PCRS_MAX_MATCH_GROW);
932 if (NULL == (dummy = (pcrs_match *)realloc(matches, (size_t)max_matches * sizeof(pcrs_match))))
936 return(PCRS_ERR_NOMEM);
941 /* Non-global search or limit reached? */
942 if (!(job->flags & PCRS_GLOBAL)) break;
944 /* Don't loop on empty matches */
945 if (offsets[1] == offset)
946 if ((size_t)offset < subject_length)
950 /* Go find the next one */
954 /* Pass pcre error through if (bad) failiure */
955 if (submatches < PCRE_ERROR_NOMATCH)
964 * Get memory for the result (must be freed by caller!)
965 * and append terminating null byte.
967 if ((*result = (char *)malloc(newsize + 1)) == NULL)
970 return PCRS_ERR_NOMEM;
974 (*result)[newsize] = '\0';
982 result_offset = *result;
984 for (i = 0; i < matches_found; i++)
986 /* copy the chunk preceding the match */
987 memcpy(result_offset, subject + offset, (size_t)(matches[i].submatch_offset[0] - offset));
988 result_offset += matches[i].submatch_offset[0] - offset;
990 /* For every segment of the substitute.. */
991 for (k = 0; k <= job->substitute->backrefs; k++)
993 /* ...copy its text.. */
994 memcpy(result_offset, job->substitute->text + job->substitute->block_offset[k], job->substitute->block_length[k]);
995 result_offset += job->substitute->block_length[k];
997 /* ..plus, if it's not the last chunk, i.e.: There *is* a backref.. */
998 if (k != job->substitute->backrefs
999 /* ..in legal range.. */
1000 && job->substitute->backref[k] < PCRS_MAX_SUBMATCHES + 2
1001 /* ..and referencing a real submatch.. */
1002 && job->substitute->backref[k] < matches[i].submatches
1003 /* ..that is nonempty.. */
1004 && matches[i].submatch_length[job->substitute->backref[k]] > 0)
1006 /* ..copy the submatch that is ref'd. */
1009 subject + matches[i].submatch_offset[job->substitute->backref[k]],
1010 matches[i].submatch_length[job->substitute->backref[k]]
1012 result_offset += matches[i].submatch_length[job->substitute->backref[k]];
1015 offset = matches[i].submatch_offset[0] + (int)matches[i].submatch_length[0];
1018 /* Copy the rest. */
1019 memcpy(result_offset, subject + offset, subject_length - (size_t)offset);
1021 *result_length = newsize;
1023 return matches_found;
1028 #define is_hex_digit(x) ((x) && strchr("0123456789ABCDEF", toupper(x)))
1030 /*********************************************************************
1032 * Function : is_hex_sequence
1034 * Description : Checks the first four characters of a string
1035 * and decides if they are a valid hex sequence
1039 * 1 : sequence = The string to check
1041 * Returns : Non-zero if it's valid sequence, or
1044 *********************************************************************/
1045 static int is_hex_sequence(const char *sequence)
1047 return (sequence[0] == '\\' &&
1048 sequence[1] == 'x' &&
1049 is_hex_digit(sequence[2]) &&
1050 is_hex_digit(sequence[3]));
1054 /*********************************************************************
1056 * Function : hex_to_byte
1058 * Description : Converts two bytes in hex into a single byte
1059 * with that value. For example '40' is converted
1062 * Based on Werner Koch's _gpgme_hextobyte()
1063 * in gpgme's conversion.c.
1066 * 1 : hex_sequence = Pointer to the two bytes to convert.
1068 * Returns : The byte value.
1070 *********************************************************************/
1071 static char hex_to_byte(const char *hex_sequence)
1073 const char *current_position = hex_sequence;
1078 const char current_digit = (char)toupper(*current_position);
1080 if ((current_digit >= '0') && (current_digit <= '9'))
1082 value += current_digit - '0';
1084 else if ((current_digit >= 'A') && (current_digit <= 'F'))
1086 value += current_digit - 'A' + 10; /* + 10 for the hex offset */
1089 if (current_position == hex_sequence)
1092 * As 0xNM is N * 16**1 + M * 16**0, the value
1093 * of the first byte has to be multiplied.
1098 } while (current_position++ < hex_sequence + 1);
1106 * Functions below this line are only part of the pcrs version
1107 * included in Privoxy. If you use any of them you should not
1108 * try to dynamically link against external pcrs versions.
1111 /*********************************************************************
1113 * Function : pcrs_job_is_dynamic
1115 * Description : Checks if a job has the "D" (dynamic) option set.
1118 * 1 : job = The job to check
1120 * Returns : TRUE if the job is indeed dynamic, otherwise
1123 *********************************************************************/
1124 int pcrs_job_is_dynamic (char *job)
1126 const char delimiter = job[1];
1127 const size_t length = strlen(job);
1133 * The shortest valid (but useless)
1134 * dynamic pattern is "s@@@D"
1140 * Everything between the last character
1141 * and the last delimiter is an option ...
1143 for (option = job + length; *option != delimiter; option--)
1148 * ... and if said option is 'D' the job is dynamic.
1158 /*********************************************************************
1160 * Function : pcrs_get_delimiter
1162 * Description : Tries to find a character that is safe to
1163 * be used as a pcrs delimiter for a certain string.
1166 * 1 : string = The string to search in
1168 * Returns : A safe delimiter if one was found, otherwise '\0'.
1170 *********************************************************************/
1171 char pcrs_get_delimiter(const char *string)
1174 * Some characters that are unlikely to
1175 * be part of pcrs replacement strings.
1177 char delimiters[] = "><§#+*~%^°-:;µ!@";
1178 char *d = delimiters;
1180 /* Take the first delimiter that isn't part of the string */
1181 while (*d && NULL != strchr(string, *d))
1190 /*********************************************************************
1192 * Function : pcrs_execute_single_command
1194 * Description : Apply single pcrs command to the subject.
1195 * The subject itself is left untouched, memory for the result
1196 * is malloc()ed and it is the caller's responsibility to free
1197 * the result when it's no longer needed.
1200 * 1 : subject = the subject (== original) string
1201 * 2 : pcrs_command = the pcrs command as string (s@foo@bar@)
1202 * 3 : hits = int* for returning the number of modifications
1204 * Returns : NULL in case of errors, otherwise the
1205 * result of the pcrs command.
1207 *********************************************************************/
1208 char *pcrs_execute_single_command(const char *subject, const char *pcrs_command, int *hits)
1211 char *result = NULL;
1215 assert(pcrs_command);
1218 size = strlen(subject);
1220 job = pcrs_compile_command(pcrs_command, hits);
1223 *hits = pcrs_execute(job, subject, size, &result, &size);
1235 const static char warning[] = "... [too long, truncated]";
1236 /*********************************************************************
1238 * Function : pcrs_compile_dynamic_command
1240 * Description : Takes a dynamic pcrs command, fills in the
1241 * values of the variables and compiles it.
1244 * 1 : csp = Current client state (buffers, headers, etc...)
1245 * 2 : pcrs_command = The dynamic pcrs command to compile
1246 * 3 : v = NULL terminated array of variables and their values.
1247 * 4 : error = pcrs error code
1249 * Returns : NULL in case of hard errors, otherwise the
1250 * compiled pcrs job.
1252 *********************************************************************/
1253 pcrs_job *pcrs_compile_dynamic_command(char *pcrs_command, const struct pcrs_variable v[], int *error)
1255 char buf[PCRS_BUFFER_SIZE];
1256 const char *original_pcrs_command = pcrs_command;
1257 char *pcrs_command_tmp = NULL;
1258 pcrs_job *job = NULL;
1263 while ((NULL != v->name) && (NULL != pcrs_command))
1265 assert(NULL != v->value);
1267 if (NULL == strstr(pcrs_command, v->name))
1270 * Skip the substitution if the variable
1271 * name isn't part of the pattern.
1277 /* Use pcrs to replace the variable with its value. */
1278 d = pcrs_get_delimiter(v->value);
1281 /* No proper delimiter found */
1282 *error = PCRS_ERR_CMDSYNTAX;
1287 * Variable names are supposed to contain alpha
1288 * numerical characters plus '_' only.
1290 assert(NULL == strchr(v->name, d));
1292 ret = snprintf(buf, sizeof(buf), "s%c\\$%s%c%s%cgT", d, v->name, d, v->value, d);
1294 if (ret >= sizeof(buf))
1297 * Value didn't completely fit into buffer,
1298 * overwrite the end of the substitution text
1299 * with a truncation message and close the pattern
1302 const size_t trailer_size = sizeof(warning) + 3; /* 3 for d + "gT" */
1303 char *trailer_start = buf + sizeof(buf) - trailer_size;
1305 ret = snprintf(trailer_start, trailer_size, "%s%cgT", warning, d);
1306 assert(ret == trailer_size - 1);
1307 assert(sizeof(buf) == strlen(buf) + 1);
1311 pcrs_command_tmp = pcrs_execute_single_command(pcrs_command, buf, error);
1312 if (NULL == pcrs_command_tmp)
1317 if (pcrs_command != original_pcrs_command)
1319 freez(pcrs_command);
1321 pcrs_command = pcrs_command_tmp;
1326 job = pcrs_compile_command(pcrs_command, error);
1327 if (pcrs_command != original_pcrs_command)
1329 freez(pcrs_command);
1334 *error = PCRS_WARN_TRUNCATION;