1 const char pcrs_rcs[] = "$Id: pcrs.c,v 1.3 2001/05/25 11:03:55 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.3 2001/05/25 11:03:55 oes
47 * Added sanity check for NULL jobs to pcrs_exec_substitution
49 * Revision 1.2 2001/05/22 18:46:04 oes
51 * - Enabled filtering banners by size rather than URL
52 * by adding patterns that replace all standard banner
53 * sizes with the "Junkbuster" gif to the re_filterfile
55 * - Enabled filtering WebBugs by providing a pattern
56 * which kills all 1x1 images
58 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
59 * which is selected by the (nonstandard and therefore
60 * capital) letter 'U' in the option string.
61 * It causes the quantifiers to be ungreedy by default.
62 * Appending a ? turns back to greedy (!).
64 * - Added a new interceptor ijb-send-banner, which
65 * sends back the "Junkbuster" gif. Without imagelist or
66 * MSIE detection support, or if tinygif = 1, or the
67 * URL isn't recognized as an imageurl, a lame HTML
68 * explanation is sent instead.
70 * - Added new feature, which permits blocking remote
71 * script redirects and firing back a local redirect
73 * The feature is conditionally compiled, i.e. it
74 * can be disabled with --disable-fast-redirects,
75 * plus it must be activated by a "fast-redirects"
76 * line in the config file, has its own log level
77 * and of course wants to be displayed by show-proxy-args
78 * Note: Boy, all the #ifdefs in 1001 locations and
79 * all the fumbling with configure.in and acconfig.h
80 * were *way* more work than the feature itself :-(
82 * - Because a generic redirect template was needed for
83 * this, tinygif = 3 now uses the same.
85 * - Moved GIFs, and other static HTTP response templates
90 * - Removed some >400 CRs again (Jon, you really worked
93 * Revision 1.1.1.1 2001/05/15 13:59:02 oes
94 * Initial import of version 2.9.3 source tree
97 *********************************************************************/
103 const char pcrs_h_rcs[] = PCRS_H_VERSION;
106 /*********************************************************************
108 * Function : my_strsep
110 * Description : Convenience function. It acts like strsep, except that
111 * it respects quoting of the delimiter character with the
112 * quote character. (And, of course, quoting the quote char
113 * with itself.) Called from `pcrs_make_job'.
116 * 1 : token = current token
117 * 2 : text = string to tokenize
118 * 3 : delimiter = single character deliminter
119 * 4 : quote_char = character to cause quoting
121 * Returns : -1 => failure, else the length of the token found.
122 * In the latter case, *text is the token's start.
124 *********************************************************************/
125 int my_strsep(char *token, char **text, char delimiter, char quote_char)
127 int i, k=0, limit, quoted = FALSE;
129 limit = strlen(*text);
137 for (i=0; i < limit; i++)
139 if (text[0][i] == delimiter && !quoted)
144 else if (text[0][i] == quote_char && !quoted && i+1 < limit && text[0][i+1] == delimiter)
149 token[k++] = text[0][i];
159 /*********************************************************************
161 * Function : pcrs_compile_perl_options
163 * Description : This function parses a string containing the options to
164 * Perl's s/// operator. It returns an integer that is the
165 * pcre equivalent of the symbolic optstring.
166 * Since pcre doesn't know about Perl's 'g' (global) option,
167 * but pcrs needs it, the globalflag integer is set if 'g'
171 * 1 : optstring = string with options in perl syntax
172 * 2 : globalflag = see description
174 * Returns : option integer suitable for pcre
176 *********************************************************************/
177 int pcrs_compile_perl_options(char *optstring, int *globalflag)
181 for (i=0; i < strlen(optstring); i++)
186 case 'g': *globalflag = 1; break;
187 case 'i': rc |= PCRE_CASELESS; break;
188 case 'm': rc |= PCRE_MULTILINE; break;
190 case 's': rc |= PCRE_DOTALL; break;
191 case 'x': rc |= PCRE_EXTENDED; break;
192 case 'U': rc |= PCRE_UNGREEDY; break;
201 /*********************************************************************
203 * Function : pcrs_compile_replacement
205 * Description : This function takes a Perl-style replacement (2nd argument
206 * to the s/// operator and returns a compiled pcrs_substitute,
207 * or NULL if memory allocation for the substitute structure
211 * 1 : replacement = replacement part of s/// operator
213 * 2 : errptr = pointer to an integer in which error
214 * conditions can be returned.
216 * Returns : pcrs_substitute data structure, or NULL if an
217 * error is encountered. In that case, *errptr has
220 *********************************************************************/
221 pcrs_substitute *pcrs_compile_replacement(char *replacement, int *errptr)
223 int length, i, k = 0, l = 0, quoted = 0, idx;
224 char *text, *num_ptr, *numbers = "0123456789";
227 r = (pcrs_substitute *)malloc(sizeof(pcrs_substitute));
228 if (r == NULL) return NULL;
229 memset(r, '\0', sizeof(pcrs_substitute));
231 text = strdup(replacement); /* must be free()d by caller */
234 *errptr = PCRS_ERR_NOMEM;
239 length = strlen(replacement);
241 for (i=0; i < length; i++)
243 /* Backslash treatment */
244 if (replacement[i] == '\\')
248 text[k++] = replacement[i];
258 /* Dollar treatment */
259 if (replacement[i] == '$' && !quoted && i < length - 1)
261 if (strchr("0123456789&", replacement[i + 1]) == NULL)
263 text[k++] = replacement[i];
267 r->block_length[l] = k - r->block_offset[l];
269 if (replacement[i + 1] != '&')
271 while ((num_ptr = strchr(numbers, replacement[++i])) != NULL && i < length)
273 idx = num_ptr - numbers;
274 r->backref[l] = r->backref[l] * 10 + idx;
280 if (r->backref[l] < PCRS_MAX_SUBMATCHES)
281 r->backref_count[r->backref[l]] += 1;
283 r->block_offset[l] = k;
288 /* Plain char treatment */
289 text[k++] = replacement[i];
296 r->block_length[l] = k - r->block_offset[l];
302 /*********************************************************************
304 * Function : pcrs_free_job
306 * Description : Frees the memory used by a pcrs_job struct and its
307 * dependant structures. Returns a pointer to the next
308 * job, if there was any, or NULL otherwise.
311 * 1 : job = pointer to the pcrs_job structure to be freed
313 * Returns : a pointer to the next job, if there was any, or
316 *********************************************************************/
317 pcrs_job *pcrs_free_job(pcrs_job *job)
328 if (job->pattern != NULL) free(job->pattern);
329 if (job->hints != NULL) free(job->hints);
330 if (job->substitute != NULL)
332 if (job->substitute->text != NULL) free(job->substitute->text);
333 free(job->substitute);
342 /*********************************************************************
344 * Function : pcrs_make_job
346 * Description : Main entry point. Takes a string with a Perl-style
347 * s/// command and returns a corresponding pcrs_job,
348 * or NULL if compiling the job fails at any stage.
349 * Diagnostics could obviously be improved.
352 * 1 : command = string with perl-style s/// command
353 * 2 : errptr = pointer to an integer in which error
354 * conditions can be returned.
356 * Returns : a corresponding pcrs_job data structure, or NULL
357 * if an error was encountered. In that case, *errptr
360 *********************************************************************/
361 pcrs_job *pcrs_make_job(char *command, int *errptr)
363 char *dummy, *token, delimiter;
365 int i = 0, globalflag;
368 /* Get and init memory */
369 if ((newjob = (pcrs_job *)malloc(sizeof(pcrs_job))) == NULL)
371 *errptr = PCRS_ERR_NOMEM;
374 memset(newjob, '\0', sizeof(pcrs_job));
376 /* Command too short? */
377 if (strlen(command) < 4)
379 *errptr = PCRS_ERR_CMDSYNTAX;
380 pcrs_free_job(newjob);
384 /* Split command into tokens and handle them */
385 delimiter = command[1];
386 token = (char *)malloc(strlen(command)); /* current token */
387 dummy = (char *)malloc(strlen(command)); /* must store pattern, since we can't */
388 /* use it until the options are known */
389 while (my_strsep(token, &command, delimiter, '\\') >= 0)
393 /* We don't care about the command and assume 's' */
399 strcpy(dummy, token);
404 if ((newjob->substitute = pcrs_compile_replacement(token, errptr)) == NULL)
406 pcrs_free_job(newjob);
416 newjob->options = pcrs_compile_perl_options(token, &globalflag);
417 newjob->globalflag = globalflag;
420 /* There shouldn't be anything else! */
422 *errptr = PCRS_ERR_CMDSYNTAX;
423 pcrs_free_job(newjob);
430 /* We have a valid substitute? */
431 if (newjob->substitute == NULL)
433 *errptr = PCRS_ERR_CMDSYNTAX;
434 pcrs_free_job(newjob);
438 /* Compile the pattern */
439 newjob->pattern = pcre_compile(dummy, newjob->options, &error, errptr, NULL);
440 if (newjob->pattern == NULL)
442 pcrs_free_job(newjob);
448 * Generate hints. This has little overhead, since the
449 * hints will be NULL for a boring pattern anyway.
451 newjob->hints = pcre_study(newjob->pattern, 0, &error);
454 *errptr = PCRS_ERR_STUDY;
455 pcrs_free_job(newjob);
464 /*********************************************************************
466 * Function : create_pcrs_job
468 * Description : Create a job from all its components, if you don't
469 * have a Perl command to start from. Rather boring.
472 * 1 : pattern = pointer to pcre pattern
473 * 2 : hints = pointer to pcre hints
474 * 3 : options = options in pcre format
475 * 4 : globalflag = flag that indicates if global matching is desired
476 * 5 : substitute = pointer to pcrs_substitute data structure
477 * 2 : errptr = pointer to an integer in which error
478 * conditions can be returned.
480 * Returns : pcrs_job structure, or NULL if an error was encountered.
481 * In that case, *errptr has the reason why.
483 *********************************************************************/
484 pcrs_job *create_pcrs_job(pcre *pattern, pcre_extra *hints, int options, int globalflag, pcrs_substitute *substitute, int *errptr)
488 if ((newjob = (pcrs_job *)malloc(sizeof(pcrs_job))) == NULL)
490 *errptr = PCRS_ERR_NOMEM;
493 memset(newjob, '\0', sizeof(pcrs_job));
495 newjob->pattern = pattern;
496 newjob->hints = hints;
497 newjob->options = options;
498 newjob->globalflag = globalflag;
499 newjob->substitute = substitute;
506 /*********************************************************************
508 * Function : pcrs_exec_substitution
510 * Description : Modify the subject by executing the regular substitution
511 * defined by the job. Since the result may be longer than
512 * the subject, its space requirements are precalculated in
513 * the matching phase and new memory is allocated accordingly.
514 * It is the caller's responsibility to free the result when
515 * it's no longer needed.
518 * 1 : job = the pcrs_job to be executed
519 * 2 : subject = the subject (== original) string
520 * 3 : subject_length = the subject's length
521 * 4 : result = char** for returning the result
522 * 5 : result_length = int* for returning the result's length
524 * Returns : the number of substitutions that were made. May be > 1
525 * if job->globalflag was set
527 *********************************************************************/
528 int pcrs_exec_substitution(pcrs_job *job, char *subject, int subject_length, char **result, int *result_length)
530 int offsets[3 * PCRS_MAX_SUBMATCHES],
531 offset = 0, i=0, k, matches_found, newsize, submatches;
532 pcrs_match matches[PCRS_MAX_MATCHES];
536 if (job == NULL || job->pattern == NULL || job->substitute == NULL)
539 return(PCRS_ERR_BADJOB);
542 newsize=subject_length;
545 while ((submatches = pcre_exec(job->pattern, job->hints, subject, subject_length, offset, 0, offsets, 99)) > 0)
547 matches[i].submatches = submatches;
548 for (k=0; k < submatches; k++)
550 matches[i].submatch_offset[k] = offsets[2 * k];
551 matches[i].submatch_length[k] = offsets[2 * k + 1] - offsets[2 * k]; /* Non-found optional submatches have length -1-(-1)==0 */
552 newsize += matches[i].submatch_length[k] * job->substitute->backref_count[k]; /* reserve mem for each submatch as often as it is ref'd */
554 newsize += strlen(job->substitute->text) - matches[i].submatch_length[0]; /* plus replacement text size minus match text size */
556 /* Non-global search or limit reached? */
557 if (++i >= PCRS_MAX_MATCHES || !job->globalflag ) break;
559 /* Don't loop on empty matches */
560 if (offsets[1] == offset)
561 if (offset < subject_length)
565 /* Go find the next one */
569 if (submatches < -1) return submatches; /* Pass pcre error through */
573 if ((*result = (char *)malloc(newsize)) == NULL) /* must be free()d by caller */
575 return PCRS_ERR_NOMEM;
580 result_offset = *result;
582 for (i=0; i < matches_found; i++)
584 memcpy(result_offset, subject + offset, matches[i].submatch_offset[0] - offset); /* copy the chunk preceding the match */
585 result_offset += matches[i].submatch_offset[0] - offset;
587 /* For every segment of the substitute.. */
588 for (k=0; k <= job->substitute->backrefs; k++)
590 /* ...copy its text.. */
591 memcpy(result_offset, job->substitute->text + job->substitute->block_offset[k], job->substitute->block_length[k]);
592 result_offset += job->substitute->block_length[k];
594 /* ..plus, if it's not the last chunk (i.e.: There IS a backref).. */
595 if (k != job->substitute->backrefs
596 /* ..and a nonempty match.. */
597 && matches[i].submatch_length[job->substitute->backref[k]] > 0
598 /* ..and in legal range, ... */
599 && job->substitute->backref[k] <= PCRS_MAX_SUBMATCHES)
601 /* copy the submatch that is ref'd. */
604 subject + matches[i].submatch_offset[job->substitute->backref[k]],
605 matches[i].submatch_length[job->substitute->backref[k]]
607 result_offset += matches[i].submatch_length[job->substitute->backref[k]];
610 offset = matches[i].submatch_offset[0] + matches[i].submatch_length[0];
614 memcpy(result_offset, subject + offset, subject_length - offset);
616 *result_length = newsize;
617 return matches_found;