1 const char pcrs_rcs[] = "$Id: pcrs.c,v 1.26 2007/07/01 13:29:54 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.26 2007/07/01 13:29:54 fabiankeil
42 * Add limited hex notation support for the PCRS
43 * substitution text ('\x7e' = '~'). Closes #1627140.
45 * Revision 1.25 2007/04/30 15:02:18 fabiankeil
46 * Introduce dynamic pcrs jobs that can resolve variables.
48 * Revision 1.24 2007/01/05 15:46:12 fabiankeil
49 * Don't use strlen() to calculate the length of
50 * the pcrs substitutes. They don't have to be valid C
51 * strings and getting their length wrong can result in
52 * user-controlled memory corruption.
54 * Thanks to Felix Gröbert for reporting the problem
55 * and providing the fix [#1627140].
57 * Revision 1.23 2006/12/29 17:53:05 fabiankeil
58 * Fixed gcc43 conversion warnings.
60 * Revision 1.22 2006/12/24 17:34:20 fabiankeil
61 * Add pcrs_strerror() message for PCRE_ERROR_MATCHLIMIT
62 * and give a hint why an error code might be unknown.
64 * Catch NULL subjects early in pcrs_execute().
66 * Revision 1.21 2006/07/18 14:48:47 david__schmidt
67 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
68 * with what was really the latest development (the v_3_0_branch branch)
70 * Revision 1.19.2.4 2005/05/07 21:50:55 david__schmidt
71 * A few memory leaks plugged (mostly on error paths)
73 * Revision 1.19.2.3 2003/12/04 12:32:45 oes
74 * Append a trailing nullbyte to result to facilitate string processing
76 * Revision 1.19.2.2 2002/10/08 16:22:28 oes
77 * Bugfix: Need to check validity of backreferences explicitly,
78 * because when max_matches are reached and matches is expanded,
79 * realloc() does not zero the memory. Fixes Bug # 606227
81 * Revision 1.19.2.1 2002/08/10 11:23:40 oes
82 * Include prce.h via project.h, where the appropriate
83 * source will have been selected
85 * Revision 1.19 2002/03/08 14:47:48 oes
88 * Revision 1.18 2002/03/08 14:17:14 oes
89 * Fixing -Wconversion warnings
91 * Revision 1.17 2002/03/08 13:45:48 oes
92 * Hiding internal functions
94 * Revision 1.16 2001/11/30 21:32:14 jongfoster
95 * Fixing signed/unsigned comparison (Andreas please check this!)
98 * Revision 1.15 2001/09/20 16:11:06 steudten
100 * Add casting for some string functions.
102 * Revision 1.14 2001/09/09 21:41:57 oes
103 * Fixing yet another silly bug
105 * Revision 1.13 2001/09/06 14:05:59 oes
108 * Revision 1.12 2001/08/18 11:35:00 oes
109 * - Introduced pcrs_strerror()
110 * - made some NULL arguments non-fatal
111 * - added support for \n \r \e \b \t \f \a \0 in substitute
112 * - made quoting adhere to standard rules
113 * - added warning for bad backrefs
114 * - added pcrs_execute_list()
116 * - bugfix & cosmetics
118 * Revision 1.11 2001/08/15 15:32:03 oes
119 * - Added support for Perl's special variables $+, $' and $`
120 * - Improved the substitute parser
121 * - Replaced the hard limit for the maximum number of matches
122 * by dynamic reallocation
124 * Revision 1.10 2001/08/05 13:13:11 jongfoster
125 * Making parameters "const" where possible.
127 * Revision 1.9 2001/07/18 17:27:00 oes
128 * Changed interface; Cosmetics
130 * Revision 1.8 2001/06/29 21:45:41 oes
131 * Indentation, CRLF->LF, Tab-> Space
133 * Revision 1.7 2001/06/29 13:33:04 oes
134 * - Cleaned up, renamed and reordered functions,
136 * - Removed my_strsep
137 * - Replaced globalflag with a general flags int
138 * that holds PCRS_GLOBAL, PCRS_SUCCESS, and PCRS_TRIVIAL
139 * - Introduced trivial option that will prevent pcrs
140 * from honouring backreferences in the substitute,
141 * which is useful for large substitutes that are
142 * red in from somewhere and saves the pain of escaping
144 * - Introduced convenience function pcrs_free_joblist()
145 * - Split pcrs_make_job() into pcrs_compile(), which still
146 * takes a complete s/// comand as argument and parses it,
147 * and a new function pcrs_make_job, which takes the
148 * three separate components. This should make for a
149 * much friendlier frontend.
150 * - Removed create_pcrs_job() which was useless
151 * - Fixed a bug in pcrs_execute
152 * - Success flag is now handled by pcrs instead of user
154 * Revision 1.6 2001/06/03 19:12:45 oes
157 * Revision 1.5 2001/05/29 09:50:24 jongfoster
158 * (Fixed one int -> size_t)
160 * Revision 1.4 2001/05/25 14:12:40 oes
161 * Fixed bug: Empty substitutes now detected
163 * Revision 1.3 2001/05/25 11:03:55 oes
164 * Added sanity check for NULL jobs to pcrs_exec_substitution
166 * Revision 1.2 2001/05/22 18:46:04 oes
168 * Added support for PCRE_UNGREEDY behaviour to pcrs,
169 * which is selected by the (nonstandard and therefore
170 * capital) letter 'U' in the option string.
171 * It causes the quantifiers to be ungreedy by default.
172 * Appending a ? turns back to greedy (!).
174 * Revision 1.1.1.1 2001/05/15 13:59:02 oes
175 * Initial import of version 2.9.3 source tree
178 *********************************************************************/
182 * Include project.h just so that the right pcre.h gets
183 * included from there
187 /* For snprintf only */
188 #include "miscutil.h"
196 const char pcrs_h_rcs[] = PCRS_H_VERSION;
199 * Internal prototypes
202 static int pcrs_parse_perl_options(const char *optstring, int *flags);
203 static pcrs_substitute *pcrs_compile_replacement(const char *replacement, int trivialflag,
204 int capturecount, int *errptr);
205 static int is_hex_sequence(const char *sequence);
206 static char hex_to_byte(const char *sequence);
208 /*********************************************************************
210 * Function : pcrs_strerror
212 * Description : Return a string describing a given error code.
215 * 1 : error = the error code
217 * Returns : char * to the descriptive string
219 *********************************************************************/
220 const char *pcrs_strerror(const int error)
226 /* Passed-through PCRE error: */
227 case PCRE_ERROR_NOMEMORY: return "(pcre:) No memory";
229 /* Shouldn't happen unless PCRE or PCRS bug, or user messed with compiled job: */
230 case PCRE_ERROR_NULL: return "(pcre:) NULL code or subject or ovector";
231 case PCRE_ERROR_BADOPTION: return "(pcre:) Unrecognized option bit";
232 case PCRE_ERROR_BADMAGIC: return "(pcre:) Bad magic number in code";
233 case PCRE_ERROR_UNKNOWN_NODE: return "(pcre:) Bad node in pattern";
235 /* Can't happen / not passed: */
236 case PCRE_ERROR_NOSUBSTRING: return "(pcre:) Fire in power supply";
237 case PCRE_ERROR_NOMATCH: return "(pcre:) Water in power supply";
239 #ifdef PCRE_ERROR_MATCHLIMIT
241 * Only reported by PCRE versions newer than our own.
243 case PCRE_ERROR_MATCHLIMIT: return "(pcre:) Match limit reached";
244 #endif /* def PCRE_ERROR_MATCHLIMIT */
247 case PCRS_ERR_NOMEM: return "(pcrs:) No memory";
248 case PCRS_ERR_CMDSYNTAX: return "(pcrs:) Syntax error while parsing command";
249 case PCRS_ERR_STUDY: return "(pcrs:) PCRE error while studying the pattern";
250 case PCRS_ERR_BADJOB: return "(pcrs:) Bad job - NULL job, pattern or substitute";
251 case PCRS_WARN_BADREF: return "(pcrs:) Backreference out of range";
252 case PCRS_WARN_TRUNCATION:
253 return "(pcrs:) At least one variable was too big and has been truncated before compilation";
256 * XXX: With the exception of PCRE_ERROR_MATCHLIMIT we
257 * only catch PCRE errors that can happen with our internal
258 * version. If Privoxy is linked against a newer
259 * PCRE version all bets are off ...
261 default: return "Unknown error. Privoxy out of sync with PCRE?";
264 /* error >= 0: No error */
265 return "(pcrs:) Everything's just fine. Thanks for asking.";
270 /*********************************************************************
272 * Function : pcrs_parse_perl_options
274 * Description : This function parses a string containing the options to
275 * Perl's s/// operator. It returns an integer that is the
276 * pcre equivalent of the symbolic optstring.
277 * Since pcre doesn't know about Perl's 'g' (global) or pcrs',
278 * 'T' (trivial) options but pcrs needs them, the corresponding
279 * flags are set if 'g'or 'T' is encountered.
280 * Note: The 'T' and 'U' options do not conform to Perl.
283 * 1 : optstring = string with options in perl syntax
284 * 2 : flags = see description
286 * Returns : option integer suitable for pcre
288 *********************************************************************/
289 static int pcrs_parse_perl_options(const char *optstring, int *flags)
295 if (NULL == optstring) return 0;
297 for (i = 0; i < strlen(optstring); i++)
301 case 'e': break; /* ToDo ;-) */
302 case 'g': *flags |= PCRS_GLOBAL; break;
303 case 'i': rc |= PCRE_CASELESS; break;
304 case 'm': rc |= PCRE_MULTILINE; break;
306 case 's': rc |= PCRE_DOTALL; break;
307 case 'x': rc |= PCRE_EXTENDED; break;
308 case 'U': rc |= PCRE_UNGREEDY; break;
309 case 'T': *flags |= PCRS_TRIVIAL; break;
318 /*********************************************************************
320 * Function : pcrs_compile_replacement
322 * Description : This function takes a Perl-style replacement (2nd argument
323 * to the s/// operator and returns a compiled pcrs_substitute,
324 * or NULL if memory allocation for the substitute structure
328 * 1 : replacement = replacement part of s/// operator
330 * 2 : trivialflag = Flag that causes backreferences to be
332 * 3 : capturecount = Number of capturing subpatterns in
333 * the pattern. Needed for $+ handling.
334 * 4 : errptr = pointer to an integer in which error
335 * conditions can be returned.
337 * Returns : pcrs_substitute data structure, or NULL if an
338 * error is encountered. In that case, *errptr has
341 *********************************************************************/
342 static pcrs_substitute *pcrs_compile_replacement(const char *replacement, int trivialflag, int capturecount, int *errptr)
349 i = k = l = quoted = 0;
354 if (NULL == replacement)
362 if (NULL == (r = (pcrs_substitute *)malloc(sizeof(pcrs_substitute))))
364 *errptr = PCRS_ERR_NOMEM;
367 memset(r, '\0', sizeof(pcrs_substitute));
369 length = strlen(replacement);
371 if (NULL == (text = (char *)malloc(length + 1)))
374 *errptr = PCRS_ERR_NOMEM;
377 memset(text, '\0', length + 1);
381 * In trivial mode, just copy the substitute text
385 text = strncpy(text, replacement, length + 1);
390 * Else, parse, cut out and record all backreferences
394 while (i < (int)length)
397 if (replacement[i] == '\\')
401 text[k++] = replacement[i++];
406 if (replacement[i+1] && strchr("tnrfae0", replacement[i+1]))
408 switch (replacement[++i])
434 else if (is_hex_sequence(&replacement[i]))
436 text[k++] = hex_to_byte(&replacement[i+2]);
449 if (replacement[i] == '$' && !quoted && i < (int)(length - 1))
451 char *symbol, symbols[] = "'`+&";
452 r->block_length[l] = (size_t)(k - r->block_offset[l]);
454 /* Numerical backreferences */
455 if (isdigit((int)replacement[i + 1]))
457 while (i < (int)length && isdigit((int)replacement[++i]))
459 r->backref[l] = r->backref[l] * 10 + replacement[i] - 48;
461 if (r->backref[l] > capturecount)
463 *errptr = PCRS_WARN_BADREF;
467 /* Symbolic backreferences: */
468 else if (NULL != (symbol = strchr(symbols, replacement[i + 1])))
471 if (symbol - symbols == 2) /* $+ */
473 r->backref[l] = capturecount;
475 else if (symbol - symbols == 3) /* $& */
481 r->backref[l] = PCRS_MAX_SUBMATCHES + 1 - (symbol - symbols);
486 /* Invalid backref -> plain '$' */
492 /* Valid and in range? -> record */
493 if (r->backref[l] < PCRS_MAX_SUBMATCHES + 2)
495 r->backref_count[r->backref[l]] += 1;
496 r->block_offset[++l] = k;
500 *errptr = PCRS_WARN_BADREF;
506 /* Plain chars are copied */
507 text[k++] = replacement[i++];
510 } /* -END- if (!trivialflag) */
517 r->length = (size_t)k;
518 r->block_length[l] = (size_t)(k - r->block_offset[l]);
525 /*********************************************************************
527 * Function : pcrs_free_job
529 * Description : Frees the memory used by a pcrs_job struct and its
530 * dependant structures.
533 * 1 : job = pointer to the pcrs_job structure to be freed
535 * Returns : a pointer to the next job, if there was any, or
538 *********************************************************************/
539 pcrs_job *pcrs_free_job(pcrs_job *job)
550 if (job->pattern != NULL) free(job->pattern);
551 if (job->hints != NULL) free(job->hints);
552 if (job->substitute != NULL)
554 if (job->substitute->text != NULL) free(job->substitute->text);
555 free(job->substitute);
564 /*********************************************************************
566 * Function : pcrs_free_joblist
568 * Description : Iterates through a chained list of pcrs_job's and
569 * frees them using pcrs_free_job.
572 * 1 : joblist = pointer to the first pcrs_job structure to
577 *********************************************************************/
578 void pcrs_free_joblist(pcrs_job *joblist)
580 while ( NULL != (joblist = pcrs_free_job(joblist)) ) {};
587 /*********************************************************************
589 * Function : pcrs_compile_command
591 * Description : Parses a string with a Perl-style s/// command,
592 * calls pcrs_compile, and returns a corresponding
593 * pcrs_job, or NULL if parsing or compiling the job
597 * 1 : command = string with perl-style s/// command
598 * 2 : errptr = pointer to an integer in which error
599 * conditions can be returned.
601 * Returns : a corresponding pcrs_job data structure, or NULL
602 * if an error was encountered. In that case, *errptr
605 *********************************************************************/
606 pcrs_job *pcrs_compile_command(const char *command, int *errptr)
608 int i, k, l, quoted = FALSE;
617 * Tokenize the perl command
619 limit = strlen(command);
622 *errptr = PCRS_ERR_CMDSYNTAX;
627 delimiter = command[1];
630 tokens[l] = (char *) malloc(limit + 1);
632 for (i = 0; i <= (int)limit; i++)
635 if (command[i] == delimiter && !quoted)
642 tokens[0][k++] = '\0';
643 tokens[++l] = tokens[0] + k;
647 else if (command[i] == '\\' && !quoted)
650 if (command[i+1] == delimiter) continue;
656 tokens[0][k++] = command[i];
664 *errptr = PCRS_ERR_CMDSYNTAX;
669 newjob = pcrs_compile(tokens[1], tokens[2], tokens[3], errptr);
676 /*********************************************************************
678 * Function : pcrs_compile
680 * Description : Takes the three arguments to a perl s/// command
681 * and compiles a pcrs_job structure from them.
684 * 1 : pattern = string with perl-style pattern
685 * 2 : substitute = string with perl-style substitute
686 * 3 : options = string with perl-style options
687 * 4 : errptr = pointer to an integer in which error
688 * conditions can be returned.
690 * Returns : a corresponding pcrs_job data structure, or NULL
691 * if an error was encountered. In that case, *errptr
694 *********************************************************************/
695 pcrs_job *pcrs_compile(const char *pattern, const char *substitute, const char *options, int *errptr)
705 * Handle NULL arguments
707 if (pattern == NULL) pattern = "";
708 if (substitute == NULL) substitute = "";
712 * Get and init memory
714 if (NULL == (newjob = (pcrs_job *)malloc(sizeof(pcrs_job))))
716 *errptr = PCRS_ERR_NOMEM;
719 memset(newjob, '\0', sizeof(pcrs_job));
723 * Evaluate the options
725 newjob->options = pcrs_parse_perl_options(options, &flags);
726 newjob->flags = flags;
730 * Compile the pattern
732 newjob->pattern = pcre_compile(pattern, newjob->options, &error, errptr, NULL);
733 if (newjob->pattern == NULL)
735 pcrs_free_job(newjob);
741 * Generate hints. This has little overhead, since the
742 * hints will be NULL for a boring pattern anyway.
744 newjob->hints = pcre_study(newjob->pattern, 0, &error);
747 *errptr = PCRS_ERR_STUDY;
748 pcrs_free_job(newjob);
754 * Determine the number of capturing subpatterns.
755 * This is needed for handling $+ in the substitute.
757 if (0 > (*errptr = pcre_fullinfo(newjob->pattern, newjob->hints, PCRE_INFO_CAPTURECOUNT, &capturecount)))
759 pcrs_free_job(newjob);
765 * Compile the substitute
767 if (NULL == (newjob->substitute = pcrs_compile_replacement(substitute, newjob->flags & PCRS_TRIVIAL, capturecount, errptr)))
769 pcrs_free_job(newjob);
778 /*********************************************************************
780 * Function : pcrs_execute_list
782 * Description : This is a multiple job wrapper for pcrs_execute().
783 * Apply the regular substitutions defined by the jobs in
784 * the joblist to the subject.
785 * The subject itself is left untouched, memory for the result
786 * is malloc()ed and it is the caller's responsibility to free
787 * the result when it's no longer needed.
789 * Note: For convenient string handling, a null byte is
790 * appended to the result. It does not count towards the
791 * result_length, though.
795 * 1 : joblist = the chained list of pcrs_jobs to be executed
796 * 2 : subject = the subject string
797 * 3 : subject_length = the subject's length
798 * 4 : result = char** for returning the result
799 * 5 : result_length = size_t* for returning the result's length
801 * Returns : On success, the number of substitutions that were made.
802 * May be > 1 if job->flags contained PCRS_GLOBAL
803 * On failure, the (negative) pcre error code describing the
804 * failure, which may be translated to text using pcrs_strerror().
806 *********************************************************************/
807 int pcrs_execute_list(pcrs_job *joblist, char *subject, size_t subject_length, char **result, size_t *result_length)
810 char *old, *new = NULL;
811 int hits, total_hits;
814 *result_length = subject_length;
815 hits = total_hits = 0;
817 for (job = joblist; job != NULL; job = job->next)
819 hits = pcrs_execute(job, old, *result_length, &new, result_length);
821 if (old != subject) free(old);
840 /*********************************************************************
842 * Function : pcrs_execute
844 * Description : Apply the regular substitution defined by the job to the
846 * The subject itself is left untouched, memory for the result
847 * is malloc()ed and it is the caller's responsibility to free
848 * the result when it's no longer needed.
850 * Note: For convenient string handling, a null byte is
851 * appended to the result. It does not count towards the
852 * result_length, though.
855 * 1 : job = the pcrs_job to be executed
856 * 2 : subject = the subject (== original) string
857 * 3 : subject_length = the subject's length
858 * 4 : result = char** for returning the result
859 * 5 : result_length = size_t* for returning the result's length
861 * Returns : On success, the number of substitutions that were made.
862 * May be > 1 if job->flags contained PCRS_GLOBAL
863 * On failure, the (negative) pcre error code describing the
864 * failure, which may be translated to text using pcrs_strerror().
866 *********************************************************************/
867 int pcrs_execute(pcrs_job *job, const char *subject, size_t subject_length, char **result, size_t *result_length)
869 int offsets[3 * PCRS_MAX_SUBMATCHES],
874 max_matches = PCRS_MAX_MATCH_INIT;
876 pcrs_match *matches, *dummy;
882 * Sanity check & memory allocation
884 if (job == NULL || job->pattern == NULL || job->substitute == NULL || NULL == subject)
887 return(PCRS_ERR_BADJOB);
890 if (NULL == (matches = (pcrs_match *)malloc((size_t)max_matches * sizeof(pcrs_match))))
893 return(PCRS_ERR_NOMEM);
895 memset(matches, '\0', (size_t)max_matches * sizeof(pcrs_match));
899 * Find the pattern and calculate the space
900 * requirements for the result
902 newsize = subject_length;
904 while ((submatches = pcre_exec(job->pattern, job->hints, subject, (int)subject_length, offset, 0, offsets, 3 * PCRS_MAX_SUBMATCHES)) > 0)
906 job->flags |= PCRS_SUCCESS;
907 matches[i].submatches = submatches;
909 for (k = 0; k < submatches; k++)
911 matches[i].submatch_offset[k] = offsets[2 * k];
913 /* Note: Non-found optional submatches have length -1-(-1)==0 */
914 matches[i].submatch_length[k] = (size_t)(offsets[2 * k + 1] - offsets[2 * k]);
916 /* reserve mem for each submatch as often as it is ref'd */
917 newsize += matches[i].submatch_length[k] * (size_t)job->substitute->backref_count[k];
919 /* plus replacement text size minus match text size */
920 newsize += job->substitute->length - matches[i].submatch_length[0];
922 /* chunk before match */
923 matches[i].submatch_offset[PCRS_MAX_SUBMATCHES] = 0;
924 matches[i].submatch_length[PCRS_MAX_SUBMATCHES] = (size_t)offsets[0];
925 newsize += (size_t)offsets[0] * (size_t)job->substitute->backref_count[PCRS_MAX_SUBMATCHES];
927 /* chunk after match */
928 matches[i].submatch_offset[PCRS_MAX_SUBMATCHES + 1] = offsets[1];
929 matches[i].submatch_length[PCRS_MAX_SUBMATCHES + 1] = subject_length - (size_t)offsets[1] - 1;
930 newsize += (subject_length - (size_t)offsets[1]) * (size_t)job->substitute->backref_count[PCRS_MAX_SUBMATCHES + 1];
932 /* Storage for matches exhausted? -> Extend! */
933 if (++i >= max_matches)
935 max_matches = (int)(max_matches * PCRS_MAX_MATCH_GROW);
936 if (NULL == (dummy = (pcrs_match *)realloc(matches, (size_t)max_matches * sizeof(pcrs_match))))
940 return(PCRS_ERR_NOMEM);
945 /* Non-global search or limit reached? */
946 if (!(job->flags & PCRS_GLOBAL)) break;
948 /* Don't loop on empty matches */
949 if (offsets[1] == offset)
950 if ((size_t)offset < subject_length)
954 /* Go find the next one */
958 /* Pass pcre error through if (bad) failiure */
959 if (submatches < PCRE_ERROR_NOMATCH)
968 * Get memory for the result (must be freed by caller!)
969 * and append terminating null byte.
971 if ((*result = (char *)malloc(newsize + 1)) == NULL)
974 return PCRS_ERR_NOMEM;
978 (*result)[newsize] = '\0';
986 result_offset = *result;
988 for (i = 0; i < matches_found; i++)
990 /* copy the chunk preceding the match */
991 memcpy(result_offset, subject + offset, (size_t)(matches[i].submatch_offset[0] - offset));
992 result_offset += matches[i].submatch_offset[0] - offset;
994 /* For every segment of the substitute.. */
995 for (k = 0; k <= job->substitute->backrefs; k++)
997 /* ...copy its text.. */
998 memcpy(result_offset, job->substitute->text + job->substitute->block_offset[k], job->substitute->block_length[k]);
999 result_offset += job->substitute->block_length[k];
1001 /* ..plus, if it's not the last chunk, i.e.: There *is* a backref.. */
1002 if (k != job->substitute->backrefs
1003 /* ..in legal range.. */
1004 && job->substitute->backref[k] < PCRS_MAX_SUBMATCHES + 2
1005 /* ..and referencing a real submatch.. */
1006 && job->substitute->backref[k] < matches[i].submatches
1007 /* ..that is nonempty.. */
1008 && matches[i].submatch_length[job->substitute->backref[k]] > 0)
1010 /* ..copy the submatch that is ref'd. */
1013 subject + matches[i].submatch_offset[job->substitute->backref[k]],
1014 matches[i].submatch_length[job->substitute->backref[k]]
1016 result_offset += matches[i].submatch_length[job->substitute->backref[k]];
1019 offset = matches[i].submatch_offset[0] + (int)matches[i].submatch_length[0];
1022 /* Copy the rest. */
1023 memcpy(result_offset, subject + offset, subject_length - (size_t)offset);
1025 *result_length = newsize;
1027 return matches_found;
1032 #define is_hex_digit(x) ((x) && strchr("0123456789ABCDEF", toupper(x)))
1034 /*********************************************************************
1036 * Function : is_hex_sequence
1038 * Description : Checks the first four characters of a string
1039 * and decides if they are a valid hex sequence
1043 * 1 : sequence = The string to check
1045 * Returns : Non-zero if it's valid sequence, or
1048 *********************************************************************/
1049 static int is_hex_sequence(const char *sequence)
1051 return (sequence[0] == '\\' &&
1052 sequence[1] == 'x' &&
1053 is_hex_digit(sequence[2]) &&
1054 is_hex_digit(sequence[3]));
1058 /*********************************************************************
1060 * Function : hex_to_byte
1062 * Description : Converts two bytes in hex into a single byte
1063 * with that value. For example '40' is converted
1066 * Based on Werner Koch's _gpgme_hextobyte()
1067 * in gpgme's conversion.c.
1070 * 1 : hex_sequence = Pointer to the two bytes to convert.
1072 * Returns : The byte value.
1074 *********************************************************************/
1075 static char hex_to_byte(const char *hex_sequence)
1077 const char *current_position = hex_sequence;
1082 const char current_digit = (char)toupper(*current_position);
1084 if ((current_digit >= '0') && (current_digit <= '9'))
1086 value += current_digit - '0';
1088 else if ((current_digit >= 'A') && (current_digit <= 'F'))
1090 value += current_digit - 'A' + 10; /* + 10 for the hex offset */
1093 if (current_position == hex_sequence)
1096 * As 0xNM is N * 16**1 + M * 16**0, the value
1097 * of the first byte has to be multiplied.
1102 } while (current_position++ < hex_sequence + 1);
1110 * Functions below this line are only part of the pcrs version
1111 * included in Privoxy. If you use any of them you should not
1112 * try to dynamically link against external pcrs versions.
1115 /*********************************************************************
1117 * Function : pcrs_job_is_dynamic
1119 * Description : Checks if a job has the "D" (dynamic) option set.
1122 * 1 : job = The job to check
1124 * Returns : TRUE if the job is indeed dynamic, otherwise
1127 *********************************************************************/
1128 int pcrs_job_is_dynamic (char *job)
1130 const char delimiter = job[1];
1131 const size_t length = strlen(job);
1137 * The shortest valid (but useless)
1138 * dynamic pattern is "s@@@D"
1144 * Everything between the last character
1145 * and the last delimiter is an option ...
1147 for (option = job + length; *option != delimiter; option--)
1152 * ... and if said option is 'D' the job is dynamic.
1162 /*********************************************************************
1164 * Function : pcrs_get_delimiter
1166 * Description : Tries to find a character that is safe to
1167 * be used as a pcrs delimiter for a certain string.
1170 * 1 : string = The string to search in
1172 * Returns : A safe delimiter if one was found, otherwise '\0'.
1174 *********************************************************************/
1175 char pcrs_get_delimiter(const char *string)
1178 * Some characters that are unlikely to
1179 * be part of pcrs replacement strings.
1181 char delimiters[] = "><§#+*~%^°-:;µ!@";
1182 char *d = delimiters;
1184 /* Take the first delimiter that isn't part of the string */
1185 while (*d && NULL != strchr(string, *d))
1194 /*********************************************************************
1196 * Function : pcrs_execute_single_command
1198 * Description : Apply single pcrs command to the subject.
1199 * The subject itself is left untouched, memory for the result
1200 * is malloc()ed and it is the caller's responsibility to free
1201 * the result when it's no longer needed.
1204 * 1 : subject = the subject (== original) string
1205 * 2 : pcrs_command = the pcrs command as string (s@foo@bar@)
1206 * 3 : hits = int* for returning the number of modifications
1208 * Returns : NULL in case of errors, otherwise the
1209 * result of the pcrs command.
1211 *********************************************************************/
1212 char *pcrs_execute_single_command(const char *subject, const char *pcrs_command, int *hits)
1215 char *result = NULL;
1219 assert(pcrs_command);
1222 size = strlen(subject);
1224 job = pcrs_compile_command(pcrs_command, hits);
1227 *hits = pcrs_execute(job, subject, size, &result, &size);
1239 static const char warning[] = "... [too long, truncated]";
1240 /*********************************************************************
1242 * Function : pcrs_compile_dynamic_command
1244 * Description : Takes a dynamic pcrs command, fills in the
1245 * values of the variables and compiles it.
1248 * 1 : csp = Current client state (buffers, headers, etc...)
1249 * 2 : pcrs_command = The dynamic pcrs command to compile
1250 * 3 : v = NULL terminated array of variables and their values.
1251 * 4 : error = pcrs error code
1253 * Returns : NULL in case of hard errors, otherwise the
1254 * compiled pcrs job.
1256 *********************************************************************/
1257 pcrs_job *pcrs_compile_dynamic_command(char *pcrs_command, const struct pcrs_variable v[], int *error)
1259 char buf[PCRS_BUFFER_SIZE];
1260 const char *original_pcrs_command = pcrs_command;
1261 char *pcrs_command_tmp = NULL;
1262 pcrs_job *job = NULL;
1267 while ((NULL != v->name) && (NULL != pcrs_command))
1269 assert(NULL != v->value);
1271 if (NULL == strstr(pcrs_command, v->name))
1274 * Skip the substitution if the variable
1275 * name isn't part of the pattern.
1281 /* Use pcrs to replace the variable with its value. */
1282 d = pcrs_get_delimiter(v->value);
1285 /* No proper delimiter found */
1286 *error = PCRS_ERR_CMDSYNTAX;
1291 * Variable names are supposed to contain alpha
1292 * numerical characters plus '_' only.
1294 assert(NULL == strchr(v->name, d));
1296 ret = snprintf(buf, sizeof(buf), "s%c\\$%s%c%s%cgT", d, v->name, d, v->value, d);
1298 if (ret >= sizeof(buf))
1301 * Value didn't completely fit into buffer,
1302 * overwrite the end of the substitution text
1303 * with a truncation message and close the pattern
1306 const size_t trailer_size = sizeof(warning) + 3; /* 3 for d + "gT" */
1307 char *trailer_start = buf + sizeof(buf) - trailer_size;
1309 ret = snprintf(trailer_start, trailer_size, "%s%cgT", warning, d);
1310 assert(ret == trailer_size - 1);
1311 assert(sizeof(buf) == strlen(buf) + 1);
1315 pcrs_command_tmp = pcrs_execute_single_command(pcrs_command, buf, error);
1316 if (NULL == pcrs_command_tmp)
1321 if (pcrs_command != original_pcrs_command)
1323 freez(pcrs_command);
1325 pcrs_command = pcrs_command_tmp;
1330 job = pcrs_compile_command(pcrs_command, error);
1331 if (pcrs_command != original_pcrs_command)
1333 freez(pcrs_command);
1338 *error = PCRS_WARN_TRUNCATION;