1 const char pcrs_rcs[] = "$Id: pcrs.c,v 1.4 2001/05/25 14:12:40 oes Exp $";
3 /*********************************************************************
5 * File : $Source: /cvsroot/ijbswa/current/pcrs.c,v $
7 * Purpose : This is the alpha release of libpcrs. It is only published
8 * at this early stage of development, because it is
9 * needed for a new feature in JunkBuster.
11 * While no inconsistencies, memory leaks or functional bugs
12 * are known at this time, there *could* be plenty ;-). Also,
13 * Many pcre-specific options are not yet supported, and
14 * error handling needs improvement.
16 * pcrs is a supplement to the brilliant pcre library by Philip
17 * Hazel (ph10@cam.ac.uk) and adds Perl-style substitution. That
18 * is, it mimics Perl's 's' operator.
20 * Currently, there's no documentation besides comments and the
23 * Copyright : Written and Copyright (C) 2000 by Andreas Oesterhelt
24 * <andreas@oesterhelt.org>
26 * This program is free software; you can redistribute it
27 * and/or modify it under the terms of the GNU General
28 * Public License as published by the Free Software
29 * Foundation; either version 2 of the License, or (at
30 * your option) any later version.
32 * This program is distributed in the hope that it will
33 * be useful, but WITHOUT ANY WARRANTY; without even the
34 * implied warranty of MERCHANTABILITY or FITNESS FOR A
35 * PARTICULAR PURPOSE. See the GNU General Public
36 * License for more details.
38 * The GNU General Public License should be included with
39 * this file. If not, you can view it at
40 * http://www.gnu.org/copyleft/gpl.html
41 * or write to the Free Software Foundation, Inc., 59
42 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
46 * Revision 1.4 2001/05/25 14:12:40 oes
47 * Fixed bug: Empty substitutes now detected
49 * Revision 1.3 2001/05/25 11:03:55 oes
50 * Added sanity check for NULL jobs to pcrs_exec_substitution
52 * Revision 1.2 2001/05/22 18:46:04 oes
54 * - Enabled filtering banners by size rather than URL
55 * by adding patterns that replace all standard banner
56 * sizes with the "Junkbuster" gif to the re_filterfile
58 * - Enabled filtering WebBugs by providing a pattern
59 * which kills all 1x1 images
61 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
62 * which is selected by the (nonstandard and therefore
63 * capital) letter 'U' in the option string.
64 * It causes the quantifiers to be ungreedy by default.
65 * Appending a ? turns back to greedy (!).
67 * - Added a new interceptor ijb-send-banner, which
68 * sends back the "Junkbuster" gif. Without imagelist or
69 * MSIE detection support, or if tinygif = 1, or the
70 * URL isn't recognized as an imageurl, a lame HTML
71 * explanation is sent instead.
73 * - Added new feature, which permits blocking remote
74 * script redirects and firing back a local redirect
76 * The feature is conditionally compiled, i.e. it
77 * can be disabled with --disable-fast-redirects,
78 * plus it must be activated by a "fast-redirects"
79 * line in the config file, has its own log level
80 * and of course wants to be displayed by show-proxy-args
81 * Note: Boy, all the #ifdefs in 1001 locations and
82 * all the fumbling with configure.in and acconfig.h
83 * were *way* more work than the feature itself :-(
85 * - Because a generic redirect template was needed for
86 * this, tinygif = 3 now uses the same.
88 * - Moved GIFs, and other static HTTP response templates
93 * - Removed some >400 CRs again (Jon, you really worked
96 * Revision 1.1.1.1 2001/05/15 13:59:02 oes
97 * Initial import of version 2.9.3 source tree
100 *********************************************************************/
106 const char pcrs_h_rcs[] = PCRS_H_VERSION;
109 /*********************************************************************
111 * Function : my_strsep
113 * Description : Convenience function. It acts like strsep, except that
114 * it respects quoting of the delimiter character with the
115 * quote character. (And, of course, quoting the quote char
116 * with itself.) Called from `pcrs_make_job'.
119 * 1 : token = current token
120 * 2 : text = string to tokenize
121 * 3 : delimiter = single character deliminter
122 * 4 : quote_char = character to cause quoting
124 * Returns : -1 => failure, else the length of the token found.
125 * In the latter case, *text is the token's start.
127 *********************************************************************/
128 int my_strsep(char *token, char **text, char delimiter, char quote_char)
130 int i, k=0, limit, quoted = FALSE;
132 limit = strlen(*text);
140 for (i=0; i < limit; i++)
142 if (text[0][i] == delimiter && !quoted)
147 else if (text[0][i] == quote_char && !quoted && i+1 < limit && text[0][i+1] == delimiter)
152 token[k++] = text[0][i];
162 /*********************************************************************
164 * Function : pcrs_compile_perl_options
166 * Description : This function parses a string containing the options to
167 * Perl's s/// operator. It returns an integer that is the
168 * pcre equivalent of the symbolic optstring.
169 * Since pcre doesn't know about Perl's 'g' (global) option,
170 * but pcrs needs it, the globalflag integer is set if 'g'
174 * 1 : optstring = string with options in perl syntax
175 * 2 : globalflag = see description
177 * Returns : option integer suitable for pcre
179 *********************************************************************/
180 int pcrs_compile_perl_options(char *optstring, int *globalflag)
185 for (i=0; i < strlen(optstring); i++)
190 case 'g': *globalflag = 1; break;
191 case 'i': rc |= PCRE_CASELESS; break;
192 case 'm': rc |= PCRE_MULTILINE; break;
194 case 's': rc |= PCRE_DOTALL; break;
195 case 'x': rc |= PCRE_EXTENDED; break;
196 case 'U': rc |= PCRE_UNGREEDY; break;
205 /*********************************************************************
207 * Function : pcrs_compile_replacement
209 * Description : This function takes a Perl-style replacement (2nd argument
210 * to the s/// operator and returns a compiled pcrs_substitute,
211 * or NULL if memory allocation for the substitute structure
215 * 1 : replacement = replacement part of s/// operator
217 * 2 : errptr = pointer to an integer in which error
218 * conditions can be returned.
220 * Returns : pcrs_substitute data structure, or NULL if an
221 * error is encountered. In that case, *errptr has
224 *********************************************************************/
225 pcrs_substitute *pcrs_compile_replacement(char *replacement, int *errptr)
227 int length, i, k = 0, l = 0, quoted = 0, idx;
228 char *text, *num_ptr, *numbers = "0123456789";
231 r = (pcrs_substitute *)malloc(sizeof(pcrs_substitute));
232 if (r == NULL) return NULL;
233 memset(r, '\0', sizeof(pcrs_substitute));
235 text = strdup(replacement); /* must be free()d by caller */
238 *errptr = PCRS_ERR_NOMEM;
243 length = strlen(replacement);
245 for (i=0; i < length; i++)
247 /* Backslash treatment */
248 if (replacement[i] == '\\')
252 text[k++] = replacement[i];
262 /* Dollar treatment */
263 if (replacement[i] == '$' && !quoted && i < length - 1)
265 if (strchr("0123456789&", replacement[i + 1]) == NULL)
267 text[k++] = replacement[i];
271 r->block_length[l] = k - r->block_offset[l];
273 if (replacement[i + 1] != '&')
275 while ((num_ptr = strchr(numbers, replacement[++i])) != NULL && i < length)
277 idx = num_ptr - numbers;
278 r->backref[l] = r->backref[l] * 10 + idx;
284 if (r->backref[l] < PCRS_MAX_SUBMATCHES)
285 r->backref_count[r->backref[l]] += 1;
287 r->block_offset[l] = k;
292 /* Plain char treatment */
293 text[k++] = replacement[i];
300 r->block_length[l] = k - r->block_offset[l];
306 /*********************************************************************
308 * Function : pcrs_free_job
310 * Description : Frees the memory used by a pcrs_job struct and its
311 * dependant structures. Returns a pointer to the next
312 * job, if there was any, or NULL otherwise.
315 * 1 : job = pointer to the pcrs_job structure to be freed
317 * Returns : a pointer to the next job, if there was any, or
320 *********************************************************************/
321 pcrs_job *pcrs_free_job(pcrs_job *job)
332 if (job->pattern != NULL) free(job->pattern);
333 if (job->hints != NULL) free(job->hints);
334 if (job->substitute != NULL)
336 if (job->substitute->text != NULL) free(job->substitute->text);
337 free(job->substitute);
346 /*********************************************************************
348 * Function : pcrs_make_job
350 * Description : Main entry point. Takes a string with a Perl-style
351 * s/// command and returns a corresponding pcrs_job,
352 * or NULL if compiling the job fails at any stage.
353 * Diagnostics could obviously be improved.
356 * 1 : command = string with perl-style s/// command
357 * 2 : errptr = pointer to an integer in which error
358 * conditions can be returned.
360 * Returns : a corresponding pcrs_job data structure, or NULL
361 * if an error was encountered. In that case, *errptr
364 *********************************************************************/
365 pcrs_job *pcrs_make_job(char *command, int *errptr)
367 char *dummy, *token, delimiter;
369 int i = 0, globalflag;
372 /* Get and init memory */
373 if ((newjob = (pcrs_job *)malloc(sizeof(pcrs_job))) == NULL)
375 *errptr = PCRS_ERR_NOMEM;
378 memset(newjob, '\0', sizeof(pcrs_job));
380 /* Command too short? */
381 if (strlen(command) < 4)
383 *errptr = PCRS_ERR_CMDSYNTAX;
384 pcrs_free_job(newjob);
388 /* Split command into tokens and handle them */
389 delimiter = command[1];
390 token = (char *)malloc(strlen(command)); /* current token */
391 dummy = (char *)malloc(strlen(command)); /* must store pattern, since we can't */
392 /* use it until the options are known */
393 while (my_strsep(token, &command, delimiter, '\\') >= 0)
397 /* We don't care about the command and assume 's' */
403 strcpy(dummy, token);
408 if ((newjob->substitute = pcrs_compile_replacement(token, errptr)) == NULL)
410 pcrs_free_job(newjob);
420 newjob->options = pcrs_compile_perl_options(token, &globalflag);
421 newjob->globalflag = globalflag;
424 /* There shouldn't be anything else! */
426 *errptr = PCRS_ERR_CMDSYNTAX;
427 pcrs_free_job(newjob);
434 /* We have a valid substitute? */
435 if (newjob->substitute == NULL)
437 *errptr = PCRS_ERR_CMDSYNTAX;
438 pcrs_free_job(newjob);
442 /* Compile the pattern */
443 newjob->pattern = pcre_compile(dummy, newjob->options, &error, errptr, NULL);
444 if (newjob->pattern == NULL)
446 pcrs_free_job(newjob);
452 * Generate hints. This has little overhead, since the
453 * hints will be NULL for a boring pattern anyway.
455 newjob->hints = pcre_study(newjob->pattern, 0, &error);
458 *errptr = PCRS_ERR_STUDY;
459 pcrs_free_job(newjob);
468 /*********************************************************************
470 * Function : create_pcrs_job
472 * Description : Create a job from all its components, if you don't
473 * have a Perl command to start from. Rather boring.
476 * 1 : pattern = pointer to pcre pattern
477 * 2 : hints = pointer to pcre hints
478 * 3 : options = options in pcre format
479 * 4 : globalflag = flag that indicates if global matching is desired
480 * 5 : substitute = pointer to pcrs_substitute data structure
481 * 2 : errptr = pointer to an integer in which error
482 * conditions can be returned.
484 * Returns : pcrs_job structure, or NULL if an error was encountered.
485 * In that case, *errptr has the reason why.
487 *********************************************************************/
488 pcrs_job *create_pcrs_job(pcre *pattern, pcre_extra *hints, int options, int globalflag, pcrs_substitute *substitute, int *errptr)
492 if ((newjob = (pcrs_job *)malloc(sizeof(pcrs_job))) == NULL)
494 *errptr = PCRS_ERR_NOMEM;
497 memset(newjob, '\0', sizeof(pcrs_job));
499 newjob->pattern = pattern;
500 newjob->hints = hints;
501 newjob->options = options;
502 newjob->globalflag = globalflag;
503 newjob->substitute = substitute;
510 /*********************************************************************
512 * Function : pcrs_exec_substitution
514 * Description : Modify the subject by executing the regular substitution
515 * defined by the job. Since the result may be longer than
516 * the subject, its space requirements are precalculated in
517 * the matching phase and new memory is allocated accordingly.
518 * It is the caller's responsibility to free the result when
519 * it's no longer needed.
522 * 1 : job = the pcrs_job to be executed
523 * 2 : subject = the subject (== original) string
524 * 3 : subject_length = the subject's length
525 * 4 : result = char** for returning the result
526 * 5 : result_length = int* for returning the result's length
528 * Returns : the number of substitutions that were made. May be > 1
529 * if job->globalflag was set
531 *********************************************************************/
532 int pcrs_exec_substitution(pcrs_job *job, char *subject, int subject_length, char **result, int *result_length)
534 int offsets[3 * PCRS_MAX_SUBMATCHES],
535 offset = 0, i=0, k, matches_found, newsize, submatches;
536 pcrs_match matches[PCRS_MAX_MATCHES];
540 if (job == NULL || job->pattern == NULL || job->substitute == NULL)
543 return(PCRS_ERR_BADJOB);
546 newsize=subject_length;
549 while ((submatches = pcre_exec(job->pattern, job->hints, subject, subject_length, offset, 0, offsets, 99)) > 0)
551 matches[i].submatches = submatches;
552 for (k=0; k < submatches; k++)
554 matches[i].submatch_offset[k] = offsets[2 * k];
555 matches[i].submatch_length[k] = offsets[2 * k + 1] - offsets[2 * k]; /* Non-found optional submatches have length -1-(-1)==0 */
556 newsize += matches[i].submatch_length[k] * job->substitute->backref_count[k]; /* reserve mem for each submatch as often as it is ref'd */
558 newsize += strlen(job->substitute->text) - matches[i].submatch_length[0]; /* plus replacement text size minus match text size */
560 /* Non-global search or limit reached? */
561 if (++i >= PCRS_MAX_MATCHES || !job->globalflag ) break;
563 /* Don't loop on empty matches */
564 if (offsets[1] == offset)
565 if (offset < subject_length)
569 /* Go find the next one */
573 if (submatches < -1) return submatches; /* Pass pcre error through */
577 if ((*result = (char *)malloc(newsize)) == NULL) /* must be free()d by caller */
579 return PCRS_ERR_NOMEM;
584 result_offset = *result;
586 for (i=0; i < matches_found; i++)
588 memcpy(result_offset, subject + offset, matches[i].submatch_offset[0] - offset); /* copy the chunk preceding the match */
589 result_offset += matches[i].submatch_offset[0] - offset;
591 /* For every segment of the substitute.. */
592 for (k=0; k <= job->substitute->backrefs; k++)
594 /* ...copy its text.. */
595 memcpy(result_offset, job->substitute->text + job->substitute->block_offset[k], job->substitute->block_length[k]);
596 result_offset += job->substitute->block_length[k];
598 /* ..plus, if it's not the last chunk (i.e.: There IS a backref).. */
599 if (k != job->substitute->backrefs
600 /* ..and a nonempty match.. */
601 && matches[i].submatch_length[job->substitute->backref[k]] > 0
602 /* ..and in legal range, ... */
603 && job->substitute->backref[k] <= PCRS_MAX_SUBMATCHES)
605 /* copy the submatch that is ref'd. */
608 subject + matches[i].submatch_offset[job->substitute->backref[k]],
609 matches[i].submatch_length[job->substitute->backref[k]]
611 result_offset += matches[i].submatch_length[job->substitute->backref[k]];
614 offset = matches[i].submatch_offset[0] + matches[i].submatch_length[0];
618 memcpy(result_offset, subject + offset, subject_length - offset);
620 *result_length = newsize;
621 return matches_found;