1 const char pcrs_rcs[] = "$Id: pcrs.c,v 1.6 2001/06/03 19:12:45 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 * Short note: I addition to perl's options, 'U' for ungreedy
24 * and 't' for trivial (i.e.: ignore backrefs in the substitute)
27 * Copyright : Written and Copyright (C) 2000, 2001 by Andreas S. Oesterhelt
28 * <andreas@oesterhelt.org>
30 * This program is free software; you can redistribute it
31 * and/or modify it under the terms of the GNU General
32 * Public License as published by the Free Software
33 * Foundation; either version 2 of the License, or (at
34 * your option) any later version.
36 * This program is distributed in the hope that it will
37 * be useful, but WITHOUT ANY WARRANTY; without even the
38 * implied warranty of MERCHANTABILITY or FITNESS FOR A
39 * PARTICULAR PURPOSE. See the GNU General Public
40 * License for more details.
42 * The GNU General Public License should be included with
43 * this file. If not, you can view it at
44 * http://www.gnu.org/copyleft/gpl.html
45 * or write to the Free Software Foundation, Inc., 59
46 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
50 * Revision 1.6 2001/06/03 19:12:45 oes
53 * Revision 1.5 2001/05/29 09:50:24 jongfoster
54 * Unified blocklist/imagelist/permissionslist.
55 * File format is still under discussion, but the internal changes
58 * Also modified interceptor behaviour:
59 * - We now intercept all URLs beginning with one of the following
60 * prefixes (and *only* these prefixes):
62 * * http://ijbswa.sf.net/config/
63 * * http://ijbswa.sourceforge.net/config/
64 * - New interceptors "home page" - go to http://i.j.b/ to see it.
65 * - Internal changes so that intercepted and fast redirect pages
66 * are not replaced with an image.
67 * - Interceptors now have the option to send a binary page direct
68 * to the client. (i.e. ijb-send-banner uses this)
69 * - Implemented show-url-info interceptor. (Which is why I needed
70 * the above interceptors changes - a typical URL is
71 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
72 * The previous mechanism would not have intercepted that, and
73 * if it had been intercepted then it then it would have replaced
76 * Revision 1.4 2001/05/25 14:12:40 oes
77 * Fixed bug: Empty substitutes now detected
79 * Revision 1.3 2001/05/25 11:03:55 oes
80 * Added sanity check for NULL jobs to pcrs_exec_substitution
82 * Revision 1.2 2001/05/22 18:46:04 oes
84 * - Enabled filtering banners by size rather than URL
85 * by adding patterns that replace all standard banner
86 * sizes with the "Junkbuster" gif to the re_filterfile
88 * - Enabled filtering WebBugs by providing a pattern
89 * which kills all 1x1 images
91 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
92 * which is selected by the (nonstandard and therefore
93 * capital) letter 'U' in the option string.
94 * It causes the quantifiers to be ungreedy by default.
95 * Appending a ? turns back to greedy (!).
97 * - Added a new interceptor ijb-send-banner, which
98 * sends back the "Junkbuster" gif. Without imagelist or
99 * MSIE detection support, or if tinygif = 1, or the
100 * URL isn't recognized as an imageurl, a lame HTML
101 * explanation is sent instead.
103 * - Added new feature, which permits blocking remote
104 * script redirects and firing back a local redirect
106 * The feature is conditionally compiled, i.e. it
107 * can be disabled with --disable-fast-redirects,
108 * plus it must be activated by a "fast-redirects"
109 * line in the config file, has its own log level
110 * and of course wants to be displayed by show-proxy-args
111 * Note: Boy, all the #ifdefs in 1001 locations and
112 * all the fumbling with configure.in and acconfig.h
113 * were *way* more work than the feature itself :-(
115 * - Because a generic redirect template was needed for
116 * this, tinygif = 3 now uses the same.
118 * - Moved GIFs, and other static HTTP response templates
123 * - Removed some >400 CRs again (Jon, you really worked
126 * Revision 1.1.1.1 2001/05/15 13:59:02 oes
127 * Initial import of version 2.9.3 source tree
130 *********************************************************************/
136 const char pcrs_h_rcs[] = PCRS_H_VERSION;
139 /*********************************************************************
141 * Function : pcrs_compile_perl_options
143 * Description : This function parses a string containing the options to
144 * Perl's s/// operator. It returns an integer that is the
145 * pcre equivalent of the symbolic optstring.
146 * Since pcre doesn't know about Perl's 'g' (global) or pcrs',
147 * 'T' (trivial) options but pcrs needs them, the corresponding
148 * flags are set if 'g'or 'T' is encountered.
149 * Note: The 'T' and 'U' options do not conform to Perl.
152 * 1 : optstring = string with options in perl syntax
153 * 2 : flags = see description
155 * Returns : option integer suitable for pcre
157 *********************************************************************/
158 int pcrs_compile_perl_options(char *optstring, int *flags)
163 for (i=0; i < strlen(optstring); i++)
168 case 'g': *flags |= PCRS_GLOBAL; break;
169 case 'i': rc |= PCRE_CASELESS; break;
170 case 'm': rc |= PCRE_MULTILINE; break;
172 case 's': rc |= PCRE_DOTALL; break;
173 case 'x': rc |= PCRE_EXTENDED; break;
174 case 'U': rc |= PCRE_UNGREEDY; break;
175 case 'T': *flags |= PCRS_TRIVIAL; break;
184 /*********************************************************************
186 * Function : pcrs_compile_replacement
188 * Description : This function takes a Perl-style replacement (2nd argument
189 * to the s/// operator and returns a compiled pcrs_substitute,
190 * or NULL if memory allocation for the substitute structure
194 * 1 : replacement = replacement part of s/// operator
196 * 2 : errptr = pointer to an integer in which error
197 * conditions can be returned.
199 * Returns : pcrs_substitute data structure, or NULL if an
200 * error is encountered. In that case, *errptr has
203 *********************************************************************/
204 pcrs_substitute *pcrs_compile_replacement(char *replacement, int trivialflag, int *errptr)
206 int length, i, k = 0, l = 0, quoted = 0, idx;
207 char *text, *num_ptr, *numbers = "0123456789";
210 r = (pcrs_substitute *)malloc(sizeof(pcrs_substitute));
211 if (r == NULL) return NULL;
212 memset(r, '\0', sizeof(pcrs_substitute));
214 text = strdup(replacement); /* must be free()d by caller */
217 *errptr = PCRS_ERR_NOMEM;
222 length = strlen(replacement);
230 for (i=0; i < length; i++)
232 /* Backslash treatment */
233 if (replacement[i] == '\\')
237 text[k++] = replacement[i];
247 /* Dollar treatment */
248 if (replacement[i] == '$' && !quoted && i < length - 1)
250 if (strchr("0123456789&", replacement[i + 1]) == NULL)
252 text[k++] = replacement[i];
256 r->block_length[l] = k - r->block_offset[l];
258 if (replacement[i + 1] != '&')
260 while ((num_ptr = strchr(numbers, replacement[++i])) != NULL && i < length)
262 idx = num_ptr - numbers;
263 r->backref[l] = r->backref[l] * 10 + idx;
269 if (r->backref[l] < PCRS_MAX_SUBMATCHES)
270 r->backref_count[r->backref[l]] += 1;
272 r->block_offset[l] = k;
277 /* Plain char treatment */
278 text[k++] = replacement[i];
281 } /* -END- if (!trivialflag) */
286 r->block_length[l] = k - r->block_offset[l];
292 /*********************************************************************
294 * Function : pcrs_free_job
296 * Description : Frees the memory used by a pcrs_job struct and its
297 * dependant structures. Returns a pointer to the next
298 * job, if there was any, or NULL otherwise.
301 * 1 : job = pointer to the pcrs_job structure to be freed
303 * Returns : a pointer to the next job, if there was any, or
306 *********************************************************************/
307 pcrs_job *pcrs_free_job(pcrs_job *job)
318 if (job->pattern != NULL) free(job->pattern);
319 if (job->hints != NULL) free(job->hints);
320 if (job->substitute != NULL)
322 if (job->substitute->text != NULL) free(job->substitute->text);
323 free(job->substitute);
331 /*********************************************************************
333 * Function : pcrs_free_joblist
335 * Description : Iterates through a chained list of pcrs_job's and
336 * frees them using pcrs_free_job.
339 * 1 : joblist = pointer to the first pcrs_job structure to
344 *********************************************************************/
345 void pcrs_free_joblist(pcrs_job *joblist)
347 while ( NULL != (joblist = pcrs_free_job(joblist)) ) {};
354 /*********************************************************************
356 * Function : pcrs_compile
358 * Description : Main entry point. Takes a string with a Perl-style
359 * s/// command and returns a corresponding pcrs_job,
360 * or NULL if compiling the job fails at any stage.
363 * 1 : command = string with perl-style s/// command
364 * 2 : errptr = pointer to an integer in which error
365 * conditions can be returned.
367 * Returns : a corresponding pcrs_job data structure, or NULL
368 * if an error was encountered. In that case, *errptr
371 *********************************************************************/
372 pcrs_job *pcrs_compile(char *command, int *errptr)
374 int i, k, l, limit, quoted = FALSE;
382 * Tokenize the perl command
384 limit = strlen(command);
387 *errptr = PCRS_ERR_CMDSYNTAX;
392 delimiter = command[1];
395 tokens[l] = (char *) malloc(limit + 1);
397 for (i=0; i <= limit; i++)
400 if (command[i] == delimiter && !quoted)
407 tokens[0][k++] = '\0';
408 tokens[++l] = tokens[0] + k;
412 else if (command[i] == '\\' && !quoted && i+1 < limit && command[i+1] == delimiter)
417 tokens[0][k++] = command[i];
427 *errptr = PCRS_ERR_CMDSYNTAX;
432 newjob = pcrs_make_job(tokens[1], tokens[2], tokens[3], errptr);
439 /*********************************************************************
441 * Function : pcrs_make_job
443 * Description : Takes the three arguments to a perl s/// command
444 * and compiles a pcrs_job structure from them.
447 * 1 : pattern = string with perl-style pattern
448 * 2 : substitute = string with perl-style substitute
449 * 3 : options = string with perl-style options
450 * 4 : errptr = pointer to an integer in which error
451 * conditions can be returned.
453 * Returns : a corresponding pcrs_job data structure, or NULL
454 * if an error was encountered. In that case, *errptr
457 *********************************************************************/
458 pcrs_job *pcrs_make_job(char *pattern, char *substitute, char *options, int *errptr)
465 * Handle NULL arguments
467 if (pattern == NULL) pattern = "";
468 if (substitute == NULL) substitute = "";
469 if (options == NULL) options = "";
472 * Get and init memory
474 if (NULL == (newjob = (pcrs_job *)malloc(sizeof(pcrs_job))))
476 *errptr = PCRS_ERR_NOMEM;
479 memset(newjob, '\0', sizeof(pcrs_job));
483 * Evaluate the options
485 newjob->options = pcrs_compile_perl_options(options, &flags);
486 newjob->flags = flags;
490 * Compile the pattern
492 newjob->pattern = pcre_compile(pattern, newjob->options, &error, errptr, NULL);
493 if (newjob->pattern == NULL)
495 pcrs_free_job(newjob);
501 * Generate hints. This has little overhead, since the
502 * hints will be NULL for a boring pattern anyway.
504 newjob->hints = pcre_study(newjob->pattern, 0, &error);
507 *errptr = PCRS_ERR_STUDY;
508 pcrs_free_job(newjob);
514 * Compile the substitute
516 if (NULL == (newjob->substitute = pcrs_compile_replacement(substitute, newjob->flags & PCRS_TRIVIAL, errptr)))
518 pcrs_free_job(newjob);
527 /*********************************************************************
529 * Function : pcrs_execute
531 * Description : Modify the subject by executing the regular substitution
532 * defined by the job. Since the result may be longer than
533 * the subject, its space requirements are precalculated in
534 * the matching phase and new memory is allocated accordingly.
535 * It is the caller's responsibility to free the result when
536 * it's no longer needed.
539 * 1 : job = the pcrs_job to be executed
540 * 2 : subject = the subject (== original) string
541 * 3 : subject_length = the subject's length
542 * INCLUDING the terminating zero, if string!
543 * 4 : result = char** for returning the result
544 * 5 : result_length = int* for returning the result's length
546 * Returns : the number of substitutions that were made. May be > 1
547 * if job->flags contained PCRS_GLOBAL
549 *********************************************************************/
550 int pcrs_execute(pcrs_job *job, char *subject, int subject_length, char **result, int *result_length)
552 int offsets[3 * PCRS_MAX_SUBMATCHES],
557 pcrs_match matches[PCRS_MAX_MATCHES];
565 if (job == NULL || job->pattern == NULL || job->substitute == NULL)
568 return(PCRS_ERR_BADJOB);
573 * Find the pattern and calculate the space
574 * requirements for the result (newsize)
576 newsize=subject_length;
578 while ((submatches = pcre_exec(job->pattern, job->hints, subject, subject_length, offset, 0, offsets, 3 * PCRS_MAX_SUBMATCHES)) > 0)
580 job->flags |= PCRS_SUCCESS;
581 matches[i].submatches = submatches;
582 for (k=0; k < submatches; k++)
584 matches[i].submatch_offset[k] = offsets[2 * k];
586 /* Note: Non-found optional submatches have length -1-(-1)==0 */
587 matches[i].submatch_length[k] = offsets[2 * k + 1] - offsets[2 * k];
589 /* reserve mem for each submatch as often as it is ref'd */
590 newsize += matches[i].submatch_length[k] * job->substitute->backref_count[k];
592 /* plus replacement text size minus match text size */
593 newsize += strlen(job->substitute->text) - matches[i].submatch_length[0];
595 /* Non-global search or limit reached? */
596 if (++i >= PCRS_MAX_MATCHES || !(job->flags & PCRS_GLOBAL) ) break;
598 /* Don't loop on empty matches */
599 if (offsets[1] == offset)
600 if (offset < subject_length)
604 /* Go find the next one */
608 /* Pass pcre error through if failiure*/
609 if (submatches < -1) return submatches;
614 * Get memory for the result
616 if ((*result = (char *)malloc(newsize)) == NULL) /* must be free()d by caller */
618 return PCRS_ERR_NOMEM;
626 result_offset = *result;
628 for (i=0; i < matches_found; i++)
630 /* copy the chunk preceding the match */
631 memcpy(result_offset, subject + offset, matches[i].submatch_offset[0] - offset);
632 result_offset += matches[i].submatch_offset[0] - offset;
634 /* For every segment of the substitute.. */
635 for (k=0; k <= job->substitute->backrefs; k++)
637 /* ...copy its text.. */
638 memcpy(result_offset, job->substitute->text + job->substitute->block_offset[k], job->substitute->block_length[k]);
639 result_offset += job->substitute->block_length[k];
641 /* ..plus, if it's not the last chunk (i.e.: There IS a backref).. */
642 if (k != job->substitute->backrefs
643 /* ..and a nonempty match.. */
644 && matches[i].submatch_length[job->substitute->backref[k]] > 0
645 /* ..and in legal range, ... */
646 && job->substitute->backref[k] <= PCRS_MAX_SUBMATCHES)
648 /* copy the submatch that is ref'd. */
651 subject + matches[i].submatch_offset[job->substitute->backref[k]],
652 matches[i].submatch_length[job->substitute->backref[k]]
654 result_offset += matches[i].submatch_length[job->substitute->backref[k]];
657 offset = matches[i].submatch_offset[0] + matches[i].submatch_length[0];
661 memcpy(result_offset, subject + offset, subject_length - offset);
663 *result_length = newsize;
664 return matches_found;