1 const char pcrs_rcs[] = "$Id: pcrs.c,v 1.27 2007/08/05 13:47:04 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.27 2007/08/05 13:47:04 fabiankeil
41 * #1763173 from Stefan Huehner: s@const static@static const@.
43 * Revision 1.26 2007/07/01 13:29:54 fabiankeil
44 * Add limited hex notation support for the PCRS
45 * substitution text ('\x7e' = '~'). Closes #1627140.
47 * Revision 1.25 2007/04/30 15:02:18 fabiankeil
48 * Introduce dynamic pcrs jobs that can resolve variables.
50 * Revision 1.24 2007/01/05 15:46:12 fabiankeil
51 * Don't use strlen() to calculate the length of
52 * the pcrs substitutes. They don't have to be valid C
53 * strings and getting their length wrong can result in
54 * user-controlled memory corruption.
56 * Thanks to Felix Gröbert for reporting the problem
57 * and providing the fix [#1627140].
59 * Revision 1.23 2006/12/29 17:53:05 fabiankeil
60 * Fixed gcc43 conversion warnings.
62 * Revision 1.22 2006/12/24 17:34:20 fabiankeil
63 * Add pcrs_strerror() message for PCRE_ERROR_MATCHLIMIT
64 * and give a hint why an error code might be unknown.
66 * Catch NULL subjects early in pcrs_execute().
68 * Revision 1.21 2006/07/18 14:48:47 david__schmidt
69 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
70 * with what was really the latest development (the v_3_0_branch branch)
72 * Revision 1.19.2.4 2005/05/07 21:50:55 david__schmidt
73 * A few memory leaks plugged (mostly on error paths)
75 * Revision 1.19.2.3 2003/12/04 12:32:45 oes
76 * Append a trailing nullbyte to result to facilitate string processing
78 * Revision 1.19.2.2 2002/10/08 16:22:28 oes
79 * Bugfix: Need to check validity of backreferences explicitly,
80 * because when max_matches are reached and matches is expanded,
81 * realloc() does not zero the memory. Fixes Bug # 606227
83 * Revision 1.19.2.1 2002/08/10 11:23:40 oes
84 * Include prce.h via project.h, where the appropriate
85 * source will have been selected
87 * Revision 1.19 2002/03/08 14:47:48 oes
90 * Revision 1.18 2002/03/08 14:17:14 oes
91 * Fixing -Wconversion warnings
93 * Revision 1.17 2002/03/08 13:45:48 oes
94 * Hiding internal functions
96 * Revision 1.16 2001/11/30 21:32:14 jongfoster
97 * Fixing signed/unsigned comparison (Andreas please check this!)
100 * Revision 1.15 2001/09/20 16:11:06 steudten
102 * Add casting for some string functions.
104 * Revision 1.14 2001/09/09 21:41:57 oes
105 * Fixing yet another silly bug
107 * Revision 1.13 2001/09/06 14:05:59 oes
110 * Revision 1.12 2001/08/18 11:35:00 oes
111 * - Introduced pcrs_strerror()
112 * - made some NULL arguments non-fatal
113 * - added support for \n \r \e \b \t \f \a \0 in substitute
114 * - made quoting adhere to standard rules
115 * - added warning for bad backrefs
116 * - added pcrs_execute_list()
118 * - bugfix & cosmetics
120 * Revision 1.11 2001/08/15 15:32:03 oes
121 * - Added support for Perl's special variables $+, $' and $`
122 * - Improved the substitute parser
123 * - Replaced the hard limit for the maximum number of matches
124 * by dynamic reallocation
126 * Revision 1.10 2001/08/05 13:13:11 jongfoster
127 * Making parameters "const" where possible.
129 * Revision 1.9 2001/07/18 17:27:00 oes
130 * Changed interface; Cosmetics
132 * Revision 1.8 2001/06/29 21:45:41 oes
133 * Indentation, CRLF->LF, Tab-> Space
135 * Revision 1.7 2001/06/29 13:33:04 oes
136 * - Cleaned up, renamed and reordered functions,
138 * - Removed my_strsep
139 * - Replaced globalflag with a general flags int
140 * that holds PCRS_GLOBAL, PCRS_SUCCESS, and PCRS_TRIVIAL
141 * - Introduced trivial option that will prevent pcrs
142 * from honouring backreferences in the substitute,
143 * which is useful for large substitutes that are
144 * red in from somewhere and saves the pain of escaping
146 * - Introduced convenience function pcrs_free_joblist()
147 * - Split pcrs_make_job() into pcrs_compile(), which still
148 * takes a complete s/// comand as argument and parses it,
149 * and a new function pcrs_make_job, which takes the
150 * three separate components. This should make for a
151 * much friendlier frontend.
152 * - Removed create_pcrs_job() which was useless
153 * - Fixed a bug in pcrs_execute
154 * - Success flag is now handled by pcrs instead of user
156 * Revision 1.6 2001/06/03 19:12:45 oes
159 * Revision 1.5 2001/05/29 09:50:24 jongfoster
160 * (Fixed one int -> size_t)
162 * Revision 1.4 2001/05/25 14:12:40 oes
163 * Fixed bug: Empty substitutes now detected
165 * Revision 1.3 2001/05/25 11:03:55 oes
166 * Added sanity check for NULL jobs to pcrs_exec_substitution
168 * Revision 1.2 2001/05/22 18:46:04 oes
170 * Added support for PCRE_UNGREEDY behaviour to pcrs,
171 * which is selected by the (nonstandard and therefore
172 * capital) letter 'U' in the option string.
173 * It causes the quantifiers to be ungreedy by default.
174 * Appending a ? turns back to greedy (!).
176 * Revision 1.1.1.1 2001/05/15 13:59:02 oes
177 * Initial import of version 2.9.3 source tree
180 *********************************************************************/
184 * Include project.h just so that the right pcre.h gets
185 * included from there
189 /* For snprintf only */
190 #include "miscutil.h"
200 const char pcrs_h_rcs[] = PCRS_H_VERSION;
203 * Internal prototypes
206 static int pcrs_parse_perl_options(const char *optstring, int *flags);
207 static pcrs_substitute *pcrs_compile_replacement(const char *replacement, int trivialflag,
208 int capturecount, int *errptr);
209 static int is_hex_sequence(const char *sequence);
211 /*********************************************************************
213 * Function : pcrs_strerror
215 * Description : Return a string describing a given error code.
218 * 1 : error = the error code
220 * Returns : char * to the descriptive string
222 *********************************************************************/
223 const char *pcrs_strerror(const int error)
229 /* Passed-through PCRE error: */
230 case PCRE_ERROR_NOMEMORY: return "(pcre:) No memory";
232 /* Shouldn't happen unless PCRE or PCRS bug, or user messed with compiled job: */
233 case PCRE_ERROR_NULL: return "(pcre:) NULL code or subject or ovector";
234 case PCRE_ERROR_BADOPTION: return "(pcre:) Unrecognized option bit";
235 case PCRE_ERROR_BADMAGIC: return "(pcre:) Bad magic number in code";
236 case PCRE_ERROR_UNKNOWN_NODE: return "(pcre:) Bad node in pattern";
238 /* Can't happen / not passed: */
239 case PCRE_ERROR_NOSUBSTRING: return "(pcre:) Fire in power supply";
240 case PCRE_ERROR_NOMATCH: return "(pcre:) Water in power supply";
242 #ifdef PCRE_ERROR_MATCHLIMIT
244 * Only reported by PCRE versions newer than our own.
246 case PCRE_ERROR_MATCHLIMIT: return "(pcre:) Match limit reached";
247 #endif /* def PCRE_ERROR_MATCHLIMIT */
250 case PCRS_ERR_NOMEM: return "(pcrs:) No memory";
251 case PCRS_ERR_CMDSYNTAX: return "(pcrs:) Syntax error while parsing command";
252 case PCRS_ERR_STUDY: return "(pcrs:) PCRE error while studying the pattern";
253 case PCRS_ERR_BADJOB: return "(pcrs:) Bad job - NULL job, pattern or substitute";
254 case PCRS_WARN_BADREF: return "(pcrs:) Backreference out of range";
255 case PCRS_WARN_TRUNCATION:
256 return "(pcrs:) At least one variable was too big and has been truncated before compilation";
259 * XXX: With the exception of PCRE_ERROR_MATCHLIMIT we
260 * only catch PCRE errors that can happen with our internal
261 * version. If Privoxy is linked against a newer
262 * PCRE version all bets are off ...
264 default: return "Unknown error. Privoxy out of sync with PCRE?";
267 /* error >= 0: No error */
268 return "(pcrs:) Everything's just fine. Thanks for asking.";
273 /*********************************************************************
275 * Function : pcrs_parse_perl_options
277 * Description : This function parses a string containing the options to
278 * Perl's s/// operator. It returns an integer that is the
279 * pcre equivalent of the symbolic optstring.
280 * Since pcre doesn't know about Perl's 'g' (global) or pcrs',
281 * 'T' (trivial) options but pcrs needs them, the corresponding
282 * flags are set if 'g'or 'T' is encountered.
283 * Note: The 'T' and 'U' options do not conform to Perl.
286 * 1 : optstring = string with options in perl syntax
287 * 2 : flags = see description
289 * Returns : option integer suitable for pcre
291 *********************************************************************/
292 static int pcrs_parse_perl_options(const char *optstring, int *flags)
298 if (NULL == optstring) return 0;
300 for (i = 0; i < strlen(optstring); i++)
304 case 'e': break; /* ToDo ;-) */
305 case 'g': *flags |= PCRS_GLOBAL; break;
306 case 'i': rc |= PCRE_CASELESS; break;
307 case 'm': rc |= PCRE_MULTILINE; break;
309 case 's': rc |= PCRE_DOTALL; break;
310 case 'x': rc |= PCRE_EXTENDED; break;
311 case 'U': rc |= PCRE_UNGREEDY; break;
312 case 'T': *flags |= PCRS_TRIVIAL; break;
321 /*********************************************************************
323 * Function : pcrs_compile_replacement
325 * Description : This function takes a Perl-style replacement (2nd argument
326 * to the s/// operator and returns a compiled pcrs_substitute,
327 * or NULL if memory allocation for the substitute structure
331 * 1 : replacement = replacement part of s/// operator
333 * 2 : trivialflag = Flag that causes backreferences to be
335 * 3 : capturecount = Number of capturing subpatterns in
336 * the pattern. Needed for $+ handling.
337 * 4 : errptr = pointer to an integer in which error
338 * conditions can be returned.
340 * Returns : pcrs_substitute data structure, or NULL if an
341 * error is encountered. In that case, *errptr has
344 *********************************************************************/
345 static pcrs_substitute *pcrs_compile_replacement(const char *replacement, int trivialflag, int capturecount, int *errptr)
352 i = k = l = quoted = 0;
357 if (NULL == replacement)
365 if (NULL == (r = (pcrs_substitute *)malloc(sizeof(pcrs_substitute))))
367 *errptr = PCRS_ERR_NOMEM;
370 memset(r, '\0', sizeof(pcrs_substitute));
372 length = strlen(replacement);
374 if (NULL == (text = (char *)malloc(length + 1)))
377 *errptr = PCRS_ERR_NOMEM;
380 memset(text, '\0', length + 1);
384 * In trivial mode, just copy the substitute text
388 text = strncpy(text, replacement, length + 1);
393 * Else, parse, cut out and record all backreferences
397 while (i < (int)length)
400 if (replacement[i] == '\\')
404 text[k++] = replacement[i++];
409 if (replacement[i+1] && strchr("tnrfae0", replacement[i+1]))
411 switch (replacement[++i])
437 else if (is_hex_sequence(&replacement[i]))
440 * Replace a hex sequence with a single
441 * character with the sequence's ascii value.
442 * e.g.: '\x7e' => '~'
444 const int ascii_value = xtoi(&replacement[i+2]);
446 assert(ascii_value > 0);
447 assert(ascii_value < 256);
448 text[k++] = (char)ascii_value;
461 if (replacement[i] == '$' && !quoted && i < (int)(length - 1))
463 char *symbol, symbols[] = "'`+&";
464 r->block_length[l] = (size_t)(k - r->block_offset[l]);
466 /* Numerical backreferences */
467 if (isdigit((int)replacement[i + 1]))
469 while (i < (int)length && isdigit((int)replacement[++i]))
471 r->backref[l] = r->backref[l] * 10 + replacement[i] - 48;
473 if (r->backref[l] > capturecount)
475 *errptr = PCRS_WARN_BADREF;
479 /* Symbolic backreferences: */
480 else if (NULL != (symbol = strchr(symbols, replacement[i + 1])))
483 if (symbol - symbols == 2) /* $+ */
485 r->backref[l] = capturecount;
487 else if (symbol - symbols == 3) /* $& */
493 r->backref[l] = PCRS_MAX_SUBMATCHES + 1 - (symbol - symbols);
498 /* Invalid backref -> plain '$' */
504 /* Valid and in range? -> record */
505 if (r->backref[l] < PCRS_MAX_SUBMATCHES + 2)
507 r->backref_count[r->backref[l]] += 1;
508 r->block_offset[++l] = k;
512 *errptr = PCRS_WARN_BADREF;
518 /* Plain chars are copied */
519 text[k++] = replacement[i++];
522 } /* -END- if (!trivialflag) */
529 r->length = (size_t)k;
530 r->block_length[l] = (size_t)(k - r->block_offset[l]);
537 /*********************************************************************
539 * Function : pcrs_free_job
541 * Description : Frees the memory used by a pcrs_job struct and its
542 * dependant structures.
545 * 1 : job = pointer to the pcrs_job structure to be freed
547 * Returns : a pointer to the next job, if there was any, or
550 *********************************************************************/
551 pcrs_job *pcrs_free_job(pcrs_job *job)
562 if (job->pattern != NULL) free(job->pattern);
563 if (job->hints != NULL) free(job->hints);
564 if (job->substitute != NULL)
566 if (job->substitute->text != NULL) free(job->substitute->text);
567 free(job->substitute);
576 /*********************************************************************
578 * Function : pcrs_free_joblist
580 * Description : Iterates through a chained list of pcrs_job's and
581 * frees them using pcrs_free_job.
584 * 1 : joblist = pointer to the first pcrs_job structure to
589 *********************************************************************/
590 void pcrs_free_joblist(pcrs_job *joblist)
592 while ( NULL != (joblist = pcrs_free_job(joblist)) ) {};
599 /*********************************************************************
601 * Function : pcrs_compile_command
603 * Description : Parses a string with a Perl-style s/// command,
604 * calls pcrs_compile, and returns a corresponding
605 * pcrs_job, or NULL if parsing or compiling the job
609 * 1 : command = string with perl-style s/// command
610 * 2 : errptr = pointer to an integer in which error
611 * conditions can be returned.
613 * Returns : a corresponding pcrs_job data structure, or NULL
614 * if an error was encountered. In that case, *errptr
617 *********************************************************************/
618 pcrs_job *pcrs_compile_command(const char *command, int *errptr)
620 int i, k, l, quoted = FALSE;
629 * Tokenize the perl command
631 limit = strlen(command);
634 *errptr = PCRS_ERR_CMDSYNTAX;
639 delimiter = command[1];
642 tokens[l] = (char *) malloc(limit + 1);
644 for (i = 0; i <= (int)limit; i++)
647 if (command[i] == delimiter && !quoted)
654 tokens[0][k++] = '\0';
655 tokens[++l] = tokens[0] + k;
659 else if (command[i] == '\\' && !quoted)
662 if (command[i+1] == delimiter) continue;
668 tokens[0][k++] = command[i];
676 *errptr = PCRS_ERR_CMDSYNTAX;
681 newjob = pcrs_compile(tokens[1], tokens[2], tokens[3], errptr);
688 /*********************************************************************
690 * Function : pcrs_compile
692 * Description : Takes the three arguments to a perl s/// command
693 * and compiles a pcrs_job structure from them.
696 * 1 : pattern = string with perl-style pattern
697 * 2 : substitute = string with perl-style substitute
698 * 3 : options = string with perl-style options
699 * 4 : errptr = pointer to an integer in which error
700 * conditions can be returned.
702 * Returns : a corresponding pcrs_job data structure, or NULL
703 * if an error was encountered. In that case, *errptr
706 *********************************************************************/
707 pcrs_job *pcrs_compile(const char *pattern, const char *substitute, const char *options, int *errptr)
717 * Handle NULL arguments
719 if (pattern == NULL) pattern = "";
720 if (substitute == NULL) substitute = "";
724 * Get and init memory
726 if (NULL == (newjob = (pcrs_job *)malloc(sizeof(pcrs_job))))
728 *errptr = PCRS_ERR_NOMEM;
731 memset(newjob, '\0', sizeof(pcrs_job));
735 * Evaluate the options
737 newjob->options = pcrs_parse_perl_options(options, &flags);
738 newjob->flags = flags;
742 * Compile the pattern
744 newjob->pattern = pcre_compile(pattern, newjob->options, &error, errptr, NULL);
745 if (newjob->pattern == NULL)
747 pcrs_free_job(newjob);
753 * Generate hints. This has little overhead, since the
754 * hints will be NULL for a boring pattern anyway.
756 newjob->hints = pcre_study(newjob->pattern, 0, &error);
759 *errptr = PCRS_ERR_STUDY;
760 pcrs_free_job(newjob);
766 * Determine the number of capturing subpatterns.
767 * This is needed for handling $+ in the substitute.
769 if (0 > (*errptr = pcre_fullinfo(newjob->pattern, newjob->hints, PCRE_INFO_CAPTURECOUNT, &capturecount)))
771 pcrs_free_job(newjob);
777 * Compile the substitute
779 if (NULL == (newjob->substitute = pcrs_compile_replacement(substitute, newjob->flags & PCRS_TRIVIAL, capturecount, errptr)))
781 pcrs_free_job(newjob);
790 /*********************************************************************
792 * Function : pcrs_execute_list
794 * Description : This is a multiple job wrapper for pcrs_execute().
795 * Apply the regular substitutions defined by the jobs in
796 * the joblist to the subject.
797 * The subject itself is left untouched, memory for the result
798 * is malloc()ed and it is the caller's responsibility to free
799 * the result when it's no longer needed.
801 * Note: For convenient string handling, a null byte is
802 * appended to the result. It does not count towards the
803 * result_length, though.
807 * 1 : joblist = the chained list of pcrs_jobs to be executed
808 * 2 : subject = the subject string
809 * 3 : subject_length = the subject's length
810 * 4 : result = char** for returning the result
811 * 5 : result_length = size_t* for returning the result's length
813 * Returns : On success, the number of substitutions that were made.
814 * May be > 1 if job->flags contained PCRS_GLOBAL
815 * On failure, the (negative) pcre error code describing the
816 * failure, which may be translated to text using pcrs_strerror().
818 *********************************************************************/
819 int pcrs_execute_list(pcrs_job *joblist, char *subject, size_t subject_length, char **result, size_t *result_length)
822 char *old, *new = NULL;
823 int hits, total_hits;
826 *result_length = subject_length;
827 hits = total_hits = 0;
829 for (job = joblist; job != NULL; job = job->next)
831 hits = pcrs_execute(job, old, *result_length, &new, result_length);
833 if (old != subject) free(old);
852 /*********************************************************************
854 * Function : pcrs_execute
856 * Description : Apply the regular substitution defined by the job to the
858 * The subject itself is left untouched, memory for the result
859 * is malloc()ed and it is the caller's responsibility to free
860 * the result when it's no longer needed.
862 * Note: For convenient string handling, a null byte is
863 * appended to the result. It does not count towards the
864 * result_length, though.
867 * 1 : job = the pcrs_job to be executed
868 * 2 : subject = the subject (== original) string
869 * 3 : subject_length = the subject's length
870 * 4 : result = char** for returning the result
871 * 5 : result_length = size_t* for returning the result's length
873 * Returns : On success, the number of substitutions that were made.
874 * May be > 1 if job->flags contained PCRS_GLOBAL
875 * On failure, the (negative) pcre error code describing the
876 * failure, which may be translated to text using pcrs_strerror().
878 *********************************************************************/
879 int pcrs_execute(pcrs_job *job, const char *subject, size_t subject_length, char **result, size_t *result_length)
881 int offsets[3 * PCRS_MAX_SUBMATCHES],
886 max_matches = PCRS_MAX_MATCH_INIT;
888 pcrs_match *matches, *dummy;
894 * Sanity check & memory allocation
896 if (job == NULL || job->pattern == NULL || job->substitute == NULL || NULL == subject)
899 return(PCRS_ERR_BADJOB);
902 if (NULL == (matches = (pcrs_match *)malloc((size_t)max_matches * sizeof(pcrs_match))))
905 return(PCRS_ERR_NOMEM);
907 memset(matches, '\0', (size_t)max_matches * sizeof(pcrs_match));
911 * Find the pattern and calculate the space
912 * requirements for the result
914 newsize = subject_length;
916 while ((submatches = pcre_exec(job->pattern, job->hints, subject, (int)subject_length, offset, 0, offsets, 3 * PCRS_MAX_SUBMATCHES)) > 0)
918 job->flags |= PCRS_SUCCESS;
919 matches[i].submatches = submatches;
921 for (k = 0; k < submatches; k++)
923 matches[i].submatch_offset[k] = offsets[2 * k];
925 /* Note: Non-found optional submatches have length -1-(-1)==0 */
926 matches[i].submatch_length[k] = (size_t)(offsets[2 * k + 1] - offsets[2 * k]);
928 /* reserve mem for each submatch as often as it is ref'd */
929 newsize += matches[i].submatch_length[k] * (size_t)job->substitute->backref_count[k];
931 /* plus replacement text size minus match text size */
932 newsize += job->substitute->length - matches[i].submatch_length[0];
934 /* chunk before match */
935 matches[i].submatch_offset[PCRS_MAX_SUBMATCHES] = 0;
936 matches[i].submatch_length[PCRS_MAX_SUBMATCHES] = (size_t)offsets[0];
937 newsize += (size_t)offsets[0] * (size_t)job->substitute->backref_count[PCRS_MAX_SUBMATCHES];
939 /* chunk after match */
940 matches[i].submatch_offset[PCRS_MAX_SUBMATCHES + 1] = offsets[1];
941 matches[i].submatch_length[PCRS_MAX_SUBMATCHES + 1] = subject_length - (size_t)offsets[1] - 1;
942 newsize += (subject_length - (size_t)offsets[1]) * (size_t)job->substitute->backref_count[PCRS_MAX_SUBMATCHES + 1];
944 /* Storage for matches exhausted? -> Extend! */
945 if (++i >= max_matches)
947 max_matches = (int)(max_matches * PCRS_MAX_MATCH_GROW);
948 if (NULL == (dummy = (pcrs_match *)realloc(matches, (size_t)max_matches * sizeof(pcrs_match))))
952 return(PCRS_ERR_NOMEM);
957 /* Non-global search or limit reached? */
958 if (!(job->flags & PCRS_GLOBAL)) break;
960 /* Don't loop on empty matches */
961 if (offsets[1] == offset)
962 if ((size_t)offset < subject_length)
966 /* Go find the next one */
970 /* Pass pcre error through if (bad) failiure */
971 if (submatches < PCRE_ERROR_NOMATCH)
980 * Get memory for the result (must be freed by caller!)
981 * and append terminating null byte.
983 if ((*result = (char *)malloc(newsize + 1)) == NULL)
986 return PCRS_ERR_NOMEM;
990 (*result)[newsize] = '\0';
998 result_offset = *result;
1000 for (i = 0; i < matches_found; i++)
1002 /* copy the chunk preceding the match */
1003 memcpy(result_offset, subject + offset, (size_t)(matches[i].submatch_offset[0] - offset));
1004 result_offset += matches[i].submatch_offset[0] - offset;
1006 /* For every segment of the substitute.. */
1007 for (k = 0; k <= job->substitute->backrefs; k++)
1009 /* ...copy its text.. */
1010 memcpy(result_offset, job->substitute->text + job->substitute->block_offset[k], job->substitute->block_length[k]);
1011 result_offset += job->substitute->block_length[k];
1013 /* ..plus, if it's not the last chunk, i.e.: There *is* a backref.. */
1014 if (k != job->substitute->backrefs
1015 /* ..in legal range.. */
1016 && job->substitute->backref[k] < PCRS_MAX_SUBMATCHES + 2
1017 /* ..and referencing a real submatch.. */
1018 && job->substitute->backref[k] < matches[i].submatches
1019 /* ..that is nonempty.. */
1020 && matches[i].submatch_length[job->substitute->backref[k]] > 0)
1022 /* ..copy the submatch that is ref'd. */
1025 subject + matches[i].submatch_offset[job->substitute->backref[k]],
1026 matches[i].submatch_length[job->substitute->backref[k]]
1028 result_offset += matches[i].submatch_length[job->substitute->backref[k]];
1031 offset = matches[i].submatch_offset[0] + (int)matches[i].submatch_length[0];
1034 /* Copy the rest. */
1035 memcpy(result_offset, subject + offset, subject_length - (size_t)offset);
1037 *result_length = newsize;
1039 return matches_found;
1044 #define is_hex_digit(x) ((x) && strchr("0123456789ABCDEF", toupper(x)))
1046 /*********************************************************************
1048 * Function : is_hex_sequence
1050 * Description : Checks the first four characters of a string
1051 * and decides if they are a valid hex sequence
1055 * 1 : sequence = The string to check
1057 * Returns : Non-zero if it's valid sequence, or
1060 *********************************************************************/
1061 static int is_hex_sequence(const char *sequence)
1063 return (sequence[0] == '\\' &&
1064 sequence[1] == 'x' &&
1065 is_hex_digit(sequence[2]) &&
1066 is_hex_digit(sequence[3]));
1071 * Functions below this line are only part of the pcrs version
1072 * included in Privoxy. If you use any of them you should not
1073 * try to dynamically link against external pcrs versions.
1076 /*********************************************************************
1078 * Function : pcrs_job_is_dynamic
1080 * Description : Checks if a job has the "D" (dynamic) option set.
1083 * 1 : job = The job to check
1085 * Returns : TRUE if the job is indeed dynamic, otherwise
1088 *********************************************************************/
1089 int pcrs_job_is_dynamic (char *job)
1091 const char delimiter = job[1];
1092 const size_t length = strlen(job);
1098 * The shortest valid (but useless)
1099 * dynamic pattern is "s@@@D"
1105 * Everything between the last character
1106 * and the last delimiter is an option ...
1108 for (option = job + length; *option != delimiter; option--)
1113 * ... and if said option is 'D' the job is dynamic.
1123 /*********************************************************************
1125 * Function : pcrs_get_delimiter
1127 * Description : Tries to find a character that is safe to
1128 * be used as a pcrs delimiter for a certain string.
1131 * 1 : string = The string to search in
1133 * Returns : A safe delimiter if one was found, otherwise '\0'.
1135 *********************************************************************/
1136 char pcrs_get_delimiter(const char *string)
1139 * Some characters that are unlikely to
1140 * be part of pcrs replacement strings.
1142 char delimiters[] = "><§#+*~%^°-:;µ!@";
1143 char *d = delimiters;
1145 /* Take the first delimiter that isn't part of the string */
1146 while (*d && NULL != strchr(string, *d))
1155 /*********************************************************************
1157 * Function : pcrs_execute_single_command
1159 * Description : Apply single pcrs command to the subject.
1160 * The subject itself is left untouched, memory for the result
1161 * is malloc()ed and it is the caller's responsibility to free
1162 * the result when it's no longer needed.
1165 * 1 : subject = the subject (== original) string
1166 * 2 : pcrs_command = the pcrs command as string (s@foo@bar@)
1167 * 3 : hits = int* for returning the number of modifications
1169 * Returns : NULL in case of errors, otherwise the
1170 * result of the pcrs command.
1172 *********************************************************************/
1173 char *pcrs_execute_single_command(const char *subject, const char *pcrs_command, int *hits)
1176 char *result = NULL;
1180 assert(pcrs_command);
1183 size = strlen(subject);
1185 job = pcrs_compile_command(pcrs_command, hits);
1188 *hits = pcrs_execute(job, subject, size, &result, &size);
1200 static const char warning[] = "... [too long, truncated]";
1201 /*********************************************************************
1203 * Function : pcrs_compile_dynamic_command
1205 * Description : Takes a dynamic pcrs command, fills in the
1206 * values of the variables and compiles it.
1209 * 1 : csp = Current client state (buffers, headers, etc...)
1210 * 2 : pcrs_command = The dynamic pcrs command to compile
1211 * 3 : v = NULL terminated array of variables and their values.
1212 * 4 : error = pcrs error code
1214 * Returns : NULL in case of hard errors, otherwise the
1215 * compiled pcrs job.
1217 *********************************************************************/
1218 pcrs_job *pcrs_compile_dynamic_command(char *pcrs_command, const struct pcrs_variable v[], int *error)
1220 char buf[PCRS_BUFFER_SIZE];
1221 const char *original_pcrs_command = pcrs_command;
1222 char *pcrs_command_tmp = NULL;
1223 pcrs_job *job = NULL;
1228 while ((NULL != v->name) && (NULL != pcrs_command))
1230 assert(NULL != v->value);
1232 if (NULL == strstr(pcrs_command, v->name))
1235 * Skip the substitution if the variable
1236 * name isn't part of the pattern.
1242 /* Use pcrs to replace the variable with its value. */
1243 d = pcrs_get_delimiter(v->value);
1246 /* No proper delimiter found */
1247 *error = PCRS_ERR_CMDSYNTAX;
1252 * Variable names are supposed to contain alpha
1253 * numerical characters plus '_' only.
1255 assert(NULL == strchr(v->name, d));
1257 ret = snprintf(buf, sizeof(buf), "s%c\\$%s%c%s%cgT", d, v->name, d, v->value, d);
1259 if (ret >= sizeof(buf))
1262 * Value didn't completely fit into buffer,
1263 * overwrite the end of the substitution text
1264 * with a truncation message and close the pattern
1267 const size_t trailer_size = sizeof(warning) + 3; /* 3 for d + "gT" */
1268 char *trailer_start = buf + sizeof(buf) - trailer_size;
1270 ret = snprintf(trailer_start, trailer_size, "%s%cgT", warning, d);
1271 assert(ret == trailer_size - 1);
1272 assert(sizeof(buf) == strlen(buf) + 1);
1276 pcrs_command_tmp = pcrs_execute_single_command(pcrs_command, buf, error);
1277 if (NULL == pcrs_command_tmp)
1282 if (pcrs_command != original_pcrs_command)
1284 freez(pcrs_command);
1286 pcrs_command = pcrs_command_tmp;
1291 job = pcrs_compile_command(pcrs_command, error);
1292 if (pcrs_command != original_pcrs_command)
1294 freez(pcrs_command);
1299 *error = PCRS_WARN_TRUNCATION;