1 const char pcrs_rcs[] = "$Id: pcrs.c,v 1.2 2001/05/22 18:46:04 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.2 2001/05/22 18:46:04 oes
48 * - Enabled filtering banners by size rather than URL
49 * by adding patterns that replace all standard banner
50 * sizes with the "Junkbuster" gif to the re_filterfile
52 * - Enabled filtering WebBugs by providing a pattern
53 * which kills all 1x1 images
55 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
56 * which is selected by the (nonstandard and therefore
57 * capital) letter 'U' in the option string.
58 * It causes the quantifiers to be ungreedy by default.
59 * Appending a ? turns back to greedy (!).
61 * - Added a new interceptor ijb-send-banner, which
62 * sends back the "Junkbuster" gif. Without imagelist or
63 * MSIE detection support, or if tinygif = 1, or the
64 * URL isn't recognized as an imageurl, a lame HTML
65 * explanation is sent instead.
67 * - Added new feature, which permits blocking remote
68 * script redirects and firing back a local redirect
70 * The feature is conditionally compiled, i.e. it
71 * can be disabled with --disable-fast-redirects,
72 * plus it must be activated by a "fast-redirects"
73 * line in the config file, has its own log level
74 * and of course wants to be displayed by show-proxy-args
75 * Note: Boy, all the #ifdefs in 1001 locations and
76 * all the fumbling with configure.in and acconfig.h
77 * were *way* more work than the feature itself :-(
79 * - Because a generic redirect template was needed for
80 * this, tinygif = 3 now uses the same.
82 * - Moved GIFs, and other static HTTP response templates
87 * - Removed some >400 CRs again (Jon, you really worked
90 * Revision 1.1.1.1 2001/05/15 13:59:02 oes
91 * Initial import of version 2.9.3 source tree
94 *********************************************************************/
100 const char pcrs_h_rcs[] = PCRS_H_VERSION;
103 /*********************************************************************
105 * Function : my_strsep
107 * Description : Convenience function. It acts like strsep, except that
108 * it respects quoting of the delimiter character with the
109 * quote character. (And, of course, quoting the quote char
110 * with itself.) Called from `pcrs_make_job'.
113 * 1 : token = current token
114 * 2 : text = string to tokenize
115 * 3 : delimiter = single character deliminter
116 * 4 : quote_char = character to cause quoting
118 * Returns : -1 => failure, else the length of the token found.
119 * In the latter case, *text is the token's start.
121 *********************************************************************/
122 int my_strsep(char *token, char **text, char delimiter, char quote_char)
124 int i, k=0, limit, quoted = FALSE;
126 limit = strlen(*text);
134 for (i=0; i < limit; i++)
136 if (text[0][i] == delimiter && !quoted)
141 else if (text[0][i] == quote_char && !quoted && i+1 < limit && text[0][i+1] == delimiter)
146 token[k++] = text[0][i];
156 /*********************************************************************
158 * Function : pcrs_compile_perl_options
160 * Description : This function parses a string containing the options to
161 * Perl's s/// operator. It returns an integer that is the
162 * pcre equivalent of the symbolic optstring.
163 * Since pcre doesn't know about Perl's 'g' (global) option,
164 * but pcrs needs it, the globalflag integer is set if 'g'
168 * 1 : optstring = string with options in perl syntax
169 * 2 : globalflag = see description
171 * Returns : option integer suitable for pcre
173 *********************************************************************/
174 int pcrs_compile_perl_options(char *optstring, int *globalflag)
178 for (i=0; i < strlen(optstring); i++)
183 case 'g': *globalflag = 1; break;
184 case 'i': rc |= PCRE_CASELESS; break;
185 case 'm': rc |= PCRE_MULTILINE; break;
187 case 's': rc |= PCRE_DOTALL; break;
188 case 'x': rc |= PCRE_EXTENDED; break;
189 case 'U': rc |= PCRE_UNGREEDY; break;
198 /*********************************************************************
200 * Function : pcrs_compile_replacement
202 * Description : This function takes a Perl-style replacement (2nd argument
203 * to the s/// operator and returns a compiled pcrs_substitute,
204 * or NULL if memory allocation for the substitute structure
208 * 1 : replacement = replacement part of s/// operator
210 * 2 : errptr = pointer to an integer in which error
211 * conditions can be returned.
213 * Returns : pcrs_substitute data structure, or NULL if an
214 * error is encountered. In that case, *errptr has
217 *********************************************************************/
218 pcrs_substitute *pcrs_compile_replacement(char *replacement, int *errptr)
220 int length, i, k = 0, l = 0, quoted = 0, idx;
221 char *text, *num_ptr, *numbers = "0123456789";
224 r = (pcrs_substitute *)malloc(sizeof(pcrs_substitute));
225 if (r == NULL) return NULL;
226 memset(r, '\0', sizeof(pcrs_substitute));
228 text = strdup(replacement); /* must be free()d by caller */
231 *errptr = PCRS_ERR_NOMEM;
236 length = strlen(replacement);
238 for (i=0; i < length; i++)
240 /* Backslash treatment */
241 if (replacement[i] == '\\')
245 text[k++] = replacement[i];
255 /* Dollar treatment */
256 if (replacement[i] == '$' && !quoted && i < length - 1)
258 if (strchr("0123456789&", replacement[i + 1]) == NULL)
260 text[k++] = replacement[i];
264 r->block_length[l] = k - r->block_offset[l];
266 if (replacement[i + 1] != '&')
268 while ((num_ptr = strchr(numbers, replacement[++i])) != NULL && i < length)
270 idx = num_ptr - numbers;
271 r->backref[l] = r->backref[l] * 10 + idx;
277 if (r->backref[l] < PCRS_MAX_SUBMATCHES)
278 r->backref_count[r->backref[l]] += 1;
280 r->block_offset[l] = k;
285 /* Plain char treatment */
286 text[k++] = replacement[i];
293 r->block_length[l] = k - r->block_offset[l];
299 /*********************************************************************
301 * Function : pcrs_free_job
303 * Description : Frees the memory used by a pcrs_job struct and its
304 * dependant structures. Returns a pointer to the next
305 * job, if there was any, or NULL otherwise.
308 * 1 : job = pointer to the pcrs_job structure to be freed
310 * Returns : a pointer to the next job, if there was any, or
313 *********************************************************************/
314 pcrs_job *pcrs_free_job(pcrs_job *job)
325 if (job->pattern != NULL) free(job->pattern);
326 if (job->hints != NULL) free(job->hints);
327 if (job->substitute != NULL)
329 if (job->substitute->text != NULL) free(job->substitute->text);
330 free(job->substitute);
339 /*********************************************************************
341 * Function : pcrs_make_job
343 * Description : Main entry point. Takes a string with a Perl-style
344 * s/// command and returns a corresponding pcrs_job,
345 * or NULL if compiling the job fails at any stage.
346 * Diagnostics could obviously be improved.
349 * 1 : command = string with perl-style s/// command
350 * 2 : errptr = pointer to an integer in which error
351 * conditions can be returned.
353 * Returns : a corresponding pcrs_job data structure, or NULL
354 * if an error was encountered. In that case, *errptr
357 *********************************************************************/
358 pcrs_job *pcrs_make_job(char *command, int *errptr)
360 char *dummy, *token, delimiter;
362 int i = 0, globalflag;
365 /* Get and init memory */
366 if ((newjob = (pcrs_job *)malloc(sizeof(pcrs_job))) == NULL)
368 *errptr = PCRS_ERR_NOMEM;
371 memset(newjob, '\0', sizeof(pcrs_job));
373 /* Command too short? */
374 if (strlen(command) < 4)
376 *errptr = PCRS_ERR_CMDSYNTAX;
377 pcrs_free_job(newjob);
381 /* Split command into tokens and handle them */
382 delimiter = command[1];
383 token = (char *)malloc(strlen(command)); /* current token */
384 dummy = (char *)malloc(strlen(command)); /* must store pattern, since we can't */
385 /* use it until the options are known */
386 while (my_strsep(token, &command, delimiter, '\\') >= 0)
390 /* We don't care about the command and assume 's' */
396 strcpy(dummy, token);
401 newjob->substitute = pcrs_compile_replacement(token, errptr);
402 if (newjob->substitute == NULL)
404 pcrs_free_job(newjob);
411 newjob->options = pcrs_compile_perl_options(token, &globalflag);
412 newjob->globalflag = globalflag;
415 /* There shouldn't be anything else! */
417 *errptr = PCRS_ERR_CMDSYNTAX;
418 pcrs_free_job(newjob);
425 /* Compile the pattern */
426 newjob->pattern = pcre_compile(dummy, newjob->options, &error, errptr, NULL);
427 if (newjob->pattern == NULL)
429 pcrs_free_job(newjob);
435 * Generate hints. This has little overhead, since the
436 * hints will be NULL for a boring pattern anyway.
438 newjob->hints = pcre_study(newjob->pattern, 0, &error);
441 *errptr = PCRS_ERR_STUDY;
442 pcrs_free_job(newjob);
451 /*********************************************************************
453 * Function : create_pcrs_job
455 * Description : Create a job from all its components, if you don't
456 * have a Perl command to start from. Rather boring.
459 * 1 : pattern = pointer to pcre pattern
460 * 2 : hints = pointer to pcre hints
461 * 3 : options = options in pcre format
462 * 4 : globalflag = flag that indicates if global matching is desired
463 * 5 : substitute = pointer to pcrs_substitute data structure
464 * 2 : errptr = pointer to an integer in which error
465 * conditions can be returned.
467 * Returns : pcrs_job structure, or NULL if an error was encountered.
468 * In that case, *errptr has the reason why.
470 *********************************************************************/
471 pcrs_job *create_pcrs_job(pcre *pattern, pcre_extra *hints, int options, int globalflag, pcrs_substitute *substitute, int *errptr)
475 if ((newjob = (pcrs_job *)malloc(sizeof(pcrs_job))) == NULL)
477 *errptr = PCRS_ERR_NOMEM;
480 memset(newjob, '\0', sizeof(pcrs_job));
482 newjob->pattern = pattern;
483 newjob->hints = hints;
484 newjob->options = options;
485 newjob->globalflag = globalflag;
486 newjob->substitute = substitute;
493 /*********************************************************************
495 * Function : pcrs_exec_substitution
497 * Description : Modify the subject by executing the regular substitution
498 * defined by the job. Since the result may be longer than
499 * the subject, its space requirements are precalculated in
500 * the matching phase and new memory is allocated accordingly.
501 * It is the caller's responsibility to free the result when
502 * it's no longer needed.
505 * 1 : job = the pcrs_job to be executed
506 * 2 : subject = the subject (== original) string
507 * 3 : subject_length = the subject's length
508 * 4 : result = char** for returning the result
509 * 5 : result_length = int* for returning the result's length
511 * Returns : the number of substitutions that were made. May be > 1
512 * if job->globalflag was set
514 *********************************************************************/
515 int pcrs_exec_substitution(pcrs_job *job, char *subject, int subject_length, char **result, int *result_length)
517 int offsets[3 * PCRS_MAX_SUBMATCHES],
518 offset = 0, i=0, k, matches_found, newsize, submatches;
519 pcrs_match matches[PCRS_MAX_MATCHES];
523 if (job == NULL || job->pattern == NULL || job->substitute == NULL)
526 return(PCRS_ERR_BADJOB);
529 newsize=subject_length;
532 while ((submatches = pcre_exec(job->pattern, job->hints, subject, subject_length, offset, 0, offsets, 99)) > 0)
534 matches[i].submatches = submatches;
535 for (k=0; k < submatches; k++)
537 matches[i].submatch_offset[k] = offsets[2 * k];
538 matches[i].submatch_length[k] = offsets[2 * k + 1] - offsets[2 * k]; /* Non-found optional submatches have length -1-(-1)==0 */
539 newsize += matches[i].submatch_length[k] * job->substitute->backref_count[k]; /* reserve mem for each submatch as often as it is ref'd */
541 newsize += strlen(job->substitute->text) - matches[i].submatch_length[0]; /* plus replacement text size minus match text size */
543 /* Non-global search or limit reached? */
544 if (++i >= PCRS_MAX_MATCHES || !job->globalflag ) break;
546 /* Don't loop on empty matches */
547 if (offsets[1] == offset)
548 if (offset < subject_length)
552 /* Go find the next one */
556 if (submatches < -1) return submatches; /* Pass pcre error through */
560 if ((*result = (char *)malloc(newsize)) == NULL) /* must be free()d by caller */
562 return PCRS_ERR_NOMEM;
567 result_offset = *result;
569 for (i=0; i < matches_found; i++)
571 memcpy(result_offset, subject + offset, matches[i].submatch_offset[0] - offset); /* copy the chunk preceding the match */
572 result_offset += matches[i].submatch_offset[0] - offset;
574 /* For every segment of the substitute.. */
575 for (k=0; k <= job->substitute->backrefs; k++)
577 /* ...copy its text.. */
578 memcpy(result_offset, job->substitute->text + job->substitute->block_offset[k], job->substitute->block_length[k]);
579 result_offset += job->substitute->block_length[k];
581 /* ..plus, if it's not the last chunk (i.e.: There IS a backref).. */
582 if (k != job->substitute->backrefs
583 /* ..and a nonempty match.. */
584 && matches[i].submatch_length[job->substitute->backref[k]] > 0
585 /* ..and in legal range, ... */
586 && job->substitute->backref[k] <= PCRS_MAX_SUBMATCHES)
588 /* copy the submatch that is ref'd. */
591 subject + matches[i].submatch_offset[job->substitute->backref[k]],
592 matches[i].submatch_length[job->substitute->backref[k]]
594 result_offset += matches[i].submatch_length[job->substitute->backref[k]];
597 offset = matches[i].submatch_offset[0] + matches[i].submatch_length[0];
601 memcpy(result_offset, subject + offset, subject_length - offset);
603 *result_length = newsize;
604 return matches_found;