1 const char pcrs_rcs[] = "$Id: pcrs.c,v 1.1.1.1 2001/05/15 13:59:02 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.1.1.1 2001/05/15 13:59:02 oes
47 * Initial import of version 2.9.3 source tree
50 *********************************************************************/
56 const char pcrs_h_rcs[] = PCRS_H_VERSION;
59 /*********************************************************************
61 * Function : my_strsep
63 * Description : Convenience function. It acts like strsep, except that
64 * it respects quoting of the delimiter character with the
65 * quote character. (And, of course, quoting the quote char
66 * with itself.) Called from `pcrs_make_job'.
69 * 1 : token = current token
70 * 2 : text = string to tokenize
71 * 3 : delimiter = single character deliminter
72 * 4 : quote_char = character to cause quoting
74 * Returns : -1 => failure, else the length of the token found.
75 * In the latter case, *text is the token's start.
77 *********************************************************************/
78 int my_strsep(char *token, char **text, char delimiter, char quote_char)
80 int i, k=0, limit, quoted = FALSE;
82 limit = strlen(*text);
90 for (i=0; i < limit; i++)
92 if (text[0][i] == delimiter && !quoted)
97 else if (text[0][i] == quote_char && !quoted && i+1 < limit && text[0][i+1] == delimiter)
102 token[k++] = text[0][i];
112 /*********************************************************************
114 * Function : pcrs_compile_perl_options
116 * Description : This function parses a string containing the options to
117 * Perl's s/// operator. It returns an integer that is the
118 * pcre equivalent of the symbolic optstring.
119 * Since pcre doesn't know about Perl's 'g' (global) option,
120 * but pcrs needs it, the globalflag integer is set if 'g'
124 * 1 : optstring = string with options in perl syntax
125 * 2 : globalflag = see description
127 * Returns : option integer suitable for pcre
129 *********************************************************************/
130 int pcrs_compile_perl_options(char *optstring, int *globalflag)
134 for (i=0; i < strlen(optstring); i++)
139 case 'g': *globalflag = 1; break;
140 case 'i': rc |= PCRE_CASELESS; break;
141 case 'm': rc |= PCRE_MULTILINE; break;
143 case 's': rc |= PCRE_DOTALL; break;
144 case 'x': rc |= PCRE_EXTENDED; break;
145 case 'U': rc |= PCRE_UNGREEDY; break;
154 /*********************************************************************
156 * Function : pcrs_compile_replacement
158 * Description : This function takes a Perl-style replacement (2nd argument
159 * to the s/// operator and returns a compiled pcrs_substitute,
160 * or NULL if memory allocation for the substitute structure
164 * 1 : replacement = replacement part of s/// operator
166 * 2 : errptr = pointer to an integer in which error
167 * conditions can be returned.
169 * Returns : pcrs_substitute data structure, or NULL if an
170 * error is encountered. In that case, *errptr has
173 *********************************************************************/
174 pcrs_substitute *pcrs_compile_replacement(char *replacement, int *errptr)
176 int length, i, k = 0, l = 0, quoted = 0, idx;
177 char *text, *num_ptr, *numbers = "0123456789";
180 r = (pcrs_substitute *)malloc(sizeof(pcrs_substitute));
181 if (r == NULL) return NULL;
182 memset(r, '\0', sizeof(pcrs_substitute));
184 text = strdup(replacement); /* must be free()d by caller */
187 *errptr = PCRS_ERR_NOMEM;
192 length = strlen(replacement);
194 for (i=0; i < length; i++)
196 /* Backslash treatment */
197 if (replacement[i] == '\\')
201 text[k++] = replacement[i];
211 /* Dollar treatment */
212 if (replacement[i] == '$' && !quoted && i < length - 1)
214 if (strchr("0123456789&", replacement[i + 1]) == NULL)
216 text[k++] = replacement[i];
220 r->block_length[l] = k - r->block_offset[l];
222 if (replacement[i + 1] != '&')
224 while ((num_ptr = strchr(numbers, replacement[++i])) != NULL && i < length)
226 idx = num_ptr - numbers;
227 r->backref[l] = r->backref[l] * 10 + idx;
233 if (r->backref[l] < PCRS_MAX_SUBMATCHES)
234 r->backref_count[r->backref[l]] += 1;
236 r->block_offset[l] = k;
241 /* Plain char treatment */
242 text[k++] = replacement[i];
249 r->block_length[l] = k - r->block_offset[l];
255 /*********************************************************************
257 * Function : pcrs_free_job
259 * Description : Frees the memory used by a pcrs_job struct and its
260 * dependant structures. Returns a pointer to the next
261 * job, if there was any, or NULL otherwise.
264 * 1 : job = pointer to the pcrs_job structure to be freed
266 * Returns : a pointer to the next job, if there was any, or
269 *********************************************************************/
270 pcrs_job *pcrs_free_job(pcrs_job *job)
281 if (job->pattern != NULL) free(job->pattern);
282 if (job->hints != NULL) free(job->hints);
283 if (job->substitute != NULL)
285 if (job->substitute->text != NULL) free(job->substitute->text);
286 free(job->substitute);
295 /*********************************************************************
297 * Function : pcrs_make_job
299 * Description : Main entry point. Takes a string with a Perl-style
300 * s/// command and returns a corresponding pcrs_job,
301 * or NULL if compiling the job fails at any stage.
302 * Diagnostics could obviously be improved.
305 * 1 : command = string with perl-style s/// command
306 * 2 : errptr = pointer to an integer in which error
307 * conditions can be returned.
309 * Returns : a corresponding pcrs_job data structure, or NULL
310 * if an error was encountered. In that case, *errptr
313 *********************************************************************/
314 pcrs_job *pcrs_make_job(char *command, int *errptr)
316 char *dummy, *token, delimiter;
318 int i = 0, globalflag;
321 /* Get and init memory */
322 if ((newjob = (pcrs_job *)malloc(sizeof(pcrs_job))) == NULL)
324 *errptr = PCRS_ERR_NOMEM;
327 memset(newjob, '\0', sizeof(pcrs_job));
329 /* Command too short? */
330 if (strlen(command) < 4)
332 *errptr = PCRS_ERR_CMDSYNTAX;
333 pcrs_free_job(newjob);
337 /* Split command into tokens and handle them */
338 delimiter = command[1];
339 token = (char *)malloc(strlen(command)); /* current token */
340 dummy = (char *)malloc(strlen(command)); /* must store pattern, since we can't */
341 /* use it until the options are known */
342 while (my_strsep(token, &command, delimiter, '\\') >= 0)
346 /* We don't care about the command and assume 's' */
352 strcpy(dummy, token);
357 newjob->substitute = pcrs_compile_replacement(token, errptr);
358 if (newjob->substitute == NULL)
360 pcrs_free_job(newjob);
367 newjob->options = pcrs_compile_perl_options(token, &globalflag);
368 newjob->globalflag = globalflag;
371 /* There shouldn't be anything else! */
373 *errptr = PCRS_ERR_CMDSYNTAX;
374 pcrs_free_job(newjob);
381 /* Compile the pattern */
382 newjob->pattern = pcre_compile(dummy, newjob->options, &error, errptr, NULL);
383 if (newjob->pattern == NULL)
385 pcrs_free_job(newjob);
391 * Generate hints. This has little overhead, since the
392 * hints will be NULL for a boring pattern anyway.
394 newjob->hints = pcre_study(newjob->pattern, 0, &error);
397 *errptr = PCRS_ERR_STUDY;
398 pcrs_free_job(newjob);
407 /*********************************************************************
409 * Function : create_pcrs_job
411 * Description : Create a job from all its components, if you don't
412 * have a Perl command to start from. Rather boring.
415 * 1 : pattern = pointer to pcre pattern
416 * 2 : hints = pointer to pcre hints
417 * 3 : options = options in pcre format
418 * 4 : globalflag = flag that indicates if global matching is desired
419 * 5 : substitute = pointer to pcrs_substitute data structure
420 * 2 : errptr = pointer to an integer in which error
421 * conditions can be returned.
423 * Returns : pcrs_job structure, or NULL if an error was encountered.
424 * In that case, *errptr has the reason why.
426 *********************************************************************/
427 pcrs_job *create_pcrs_job(pcre *pattern, pcre_extra *hints, int options, int globalflag, pcrs_substitute *substitute, int *errptr)
431 if ((newjob = (pcrs_job *)malloc(sizeof(pcrs_job))) == NULL)
433 *errptr = PCRS_ERR_NOMEM;
436 memset(newjob, '\0', sizeof(pcrs_job));
438 newjob->pattern = pattern;
439 newjob->hints = hints;
440 newjob->options = options;
441 newjob->globalflag = globalflag;
442 newjob->substitute = substitute;
449 /*********************************************************************
451 * Function : pcrs_exec_substitution
453 * Description : Modify the subject by executing the regular substitution
454 * defined by the job. Since the result may be longer than
455 * the subject, its space requirements are precalculated in
456 * the matching phase and new memory is allocated accordingly.
457 * It is the caller's responsibility to free the result when
458 * it's no longer needed.
461 * 1 : job = the pcrs_job to be executed
462 * 2 : subject = the subject (== original) string
463 * 3 : subject_length = the subject's length
464 * 4 : result = char** for returning the result
465 * 5 : result_length = int* for returning the result's length
467 * Returns : the number of substitutions that were made. May be > 1
468 * if job->globalflag was set
470 *********************************************************************/
471 int pcrs_exec_substitution(pcrs_job *job, char *subject, int subject_length, char **result, int *result_length)
473 int offsets[3 * PCRS_MAX_SUBMATCHES],
474 offset = 0, i=0, k, matches_found, newsize, submatches;
475 pcrs_match matches[PCRS_MAX_MATCHES];
478 newsize=subject_length;
481 while ((submatches = pcre_exec(job->pattern, job->hints, subject, subject_length, offset, 0, offsets, 99)) > 0)
483 matches[i].submatches = submatches;
484 for (k=0; k < submatches; k++)
486 matches[i].submatch_offset[k] = offsets[2 * k];
487 matches[i].submatch_length[k] = offsets[2 * k + 1] - offsets[2 * k]; /* Non-found optional submatches have length -1-(-1)==0 */
488 newsize += matches[i].submatch_length[k] * job->substitute->backref_count[k]; /* reserve mem for each submatch as often as it is ref'd */
490 newsize += strlen(job->substitute->text) - matches[i].submatch_length[0]; /* plus replacement text size minus match text size */
492 /* Non-global search or limit reached? */
493 if (++i >= PCRS_MAX_MATCHES || !job->globalflag ) break;
495 /* Don't loop on empty matches */
496 if (offsets[1] == offset)
497 if (offset < subject_length)
501 /* Go find the next one */
505 if (submatches < -1) return submatches; /* Pass pcre error through */
509 if ((*result = (char *)malloc(newsize)) == NULL) /* must be free()d by caller */
511 return PCRS_ERR_NOMEM;
516 result_offset = *result;
518 for (i=0; i < matches_found; i++)
520 memcpy(result_offset, subject + offset, matches[i].submatch_offset[0] - offset); /* copy the chunk preceding the match */
521 result_offset += matches[i].submatch_offset[0] - offset;
523 /* For every segment of the substitute.. */
524 for (k=0; k <= job->substitute->backrefs; k++)
526 /* ...copy its text.. */
527 memcpy(result_offset, job->substitute->text + job->substitute->block_offset[k], job->substitute->block_length[k]);
528 result_offset += job->substitute->block_length[k];
530 /* ..plus, if it's not the last chunk (i.e.: There IS a backref).. */
531 if (k != job->substitute->backrefs
532 /* ..and a nonempty match.. */
533 && matches[i].submatch_length[job->substitute->backref[k]] > 0
534 /* ..and in legal range, ... */
535 && job->substitute->backref[k] <= PCRS_MAX_SUBMATCHES)
537 /* copy the submatch that is ref'd. */
540 subject + matches[i].submatch_offset[job->substitute->backref[k]],
541 matches[i].submatch_length[job->substitute->backref[k]]
543 result_offset += matches[i].submatch_length[job->substitute->backref[k]];
546 offset = matches[i].submatch_offset[0] + matches[i].submatch_length[0];
550 memcpy(result_offset, subject + offset, subject_length - offset);
552 *result_length = newsize;
553 return matches_found;