Resyncing HEAD with v_3_0_branch for two OSX fixes:
[privoxy.git] / src / pcrs.c
1 const char pcrs_rcs[] = "$Id: pcrs.c,v 2.4 2003/01/21 02:49:27 david__schmidt Exp $";
2
3 /*********************************************************************
4  *
5  * File        :  $Source: /cvsroot/ijbswa/current/src/pcrs.c,v $
6  *
7  * Purpose     :  pcrs is a supplement to the pcre library by Philip Hazel
8  *                <ph10@cam.ac.uk> and adds Perl-style substitution. That
9  *                is, it mimics Perl's 's' operator. See pcrs(3) for details.
10  *
11  *
12  * Copyright   :  Written and Copyright (C) 2000, 2001 by Andreas S. Oesterhelt
13  *                <andreas@oesterhelt.org>
14  *
15  *                This program is free software; you can redistribute it 
16  *                and/or modify it under the terms of the GNU Lesser
17  *                General Public License (LGPL), version 2.1, which  should
18  *                be included in this distribution (see LICENSE.txt), with
19  *                the exception that the permission to replace that license
20  *                with the GNU General Public License (GPL) given in section
21  *                3 is restricted to version 2 of the GPL.
22  *
23  *                This program is distributed in the hope that it will
24  *                be useful, but WITHOUT ANY WARRANTY; without even the
25  *                implied warranty of MERCHANTABILITY or FITNESS FOR A
26  *                PARTICULAR PURPOSE.  See the license for more details.
27  *
28  *                The GNU Lesser General Public License should be included
29  *                with this file.  If not, you can view it at
30  *                http://www.gnu.org/licenses/lgpl.html
31  *                or write to the Free Software Foundation, Inc., 59
32  *                Temple Place - Suite 330, Boston, MA  02111-1307, USA.
33  *
34  * Revisions   :
35  *    $Log: pcrs.c,v $
36  *    Revision 2.4  2003/01/21 02:49:27  david__schmidt
37  *    Developer TODO 612294: src: C++ keyword as variable name
38  *    I changed all ocurrences of 'new' to 'new_something' wherever I found
39  *    one.  I also brought up all the source files in MSDEV to see if I could
40  *    spot any highlighted keywords that really were variables.  Non-scientific,
41  *    but at least I tried. :-)
42  *
43  *    Revision 2.3  2002/10/08 16:25:30  oes
44  *    Bugfix: Need to check validity of backreferences explicitly, because when max_matches are reached and matches is expanded, realloc() does not zero the memory. Fixes Bug # 606227
45  *
46  *    Revision 2.2  2002/09/04 15:52:02  oes
47  *    Synced with the stable branch:
48  *        Revision 1.19.2.1  2002/08/10 11:23:40  oes
49  *        Include prce.h via project.h, where the appropriate
50  *        source will have been selected
51  *
52  *    Revision 2.1  2002/08/26 11:18:24  sarantis
53  *    Fix typo.
54  *
55  *    Revision 2.0  2002/06/04 14:34:21  jongfoster
56  *    Moving source files to src/
57  *
58  *    Revision 1.19  2002/03/08 14:47:48  oes
59  *    Cosmetics
60  *
61  *    Revision 1.18  2002/03/08 14:17:14  oes
62  *    Fixing -Wconversion warnings
63  *
64  *    Revision 1.17  2002/03/08 13:45:48  oes
65  *    Hiding internal functions
66  *
67  *    Revision 1.16  2001/11/30 21:32:14  jongfoster
68  *    Fixing signed/unsigned comparison (Andreas please check this!)
69  *    One tab->space
70  *
71  *    Revision 1.15  2001/09/20 16:11:06  steudten
72  *
73  *    Add casting for some string functions.
74  *
75  *    Revision 1.14  2001/09/09 21:41:57  oes
76  *    Fixing yet another silly bug
77  *
78  *    Revision 1.13  2001/09/06 14:05:59  oes
79  *    Fixed silly bug
80  *
81  *    Revision 1.12  2001/08/18 11:35:00  oes
82  *    - Introduced pcrs_strerror()
83  *    - made some NULL arguments non-fatal
84  *    - added support for \n \r \e \b \t \f \a \0 in substitute
85  *    - made quoting adhere to standard rules
86  *    - added warning for bad backrefs
87  *    - added pcrs_execute_list()
88  *    - fixed comments
89  *    - bugfix & cosmetics
90  *
91  *    Revision 1.11  2001/08/15 15:32:03  oes
92  *     - Added support for Perl's special variables $+, $' and $`
93  *     - Improved the substitute parser
94  *     - Replaced the hard limit for the maximum number of matches
95  *       by dynamic reallocation
96  *
97  *    Revision 1.10  2001/08/05 13:13:11  jongfoster
98  *    Making parameters "const" where possible.
99  *
100  *    Revision 1.9  2001/07/18 17:27:00  oes
101  *    Changed interface; Cosmetics
102  *
103  *    Revision 1.8  2001/06/29 21:45:41  oes
104  *    Indentation, CRLF->LF, Tab-> Space
105  *
106  *    Revision 1.7  2001/06/29 13:33:04  oes
107  *    - Cleaned up, renamed and reordered functions,
108  *      improved comments
109  *    - Removed my_strsep
110  *    - Replaced globalflag with a general flags int
111  *      that holds PCRS_GLOBAL, PCRS_SUCCESS, and PCRS_TRIVIAL
112  *    - Introduced trivial option that will prevent pcrs
113  *      from honouring backreferences in the substitute,
114  *      which is useful for large substitutes that are
115  *      red in from somewhere and saves the pain of escaping
116  *      the backrefs
117  *    - Introduced convenience function pcrs_free_joblist()
118  *    - Split pcrs_make_job() into pcrs_compile(), which still
119  *      takes a complete s/// comand as argument and parses it,
120  *      and a new function pcrs_make_job, which takes the
121  *      three separate components. This should make for a
122  *      much friendlier frontend.
123  *    - Removed create_pcrs_job() which was useless
124  *    - Fixed a bug in pcrs_execute
125  *    - Success flag is now handled by pcrs instead of user
126  *
127  *    Revision 1.6  2001/06/03 19:12:45  oes
128  *    added FIXME
129  *
130  *    Revision 1.5  2001/05/29 09:50:24  jongfoster
131  *    (Fixed one int -> size_t)
132  *
133  *    Revision 1.4  2001/05/25 14:12:40  oes
134  *    Fixed bug: Empty substitutes now detected
135  *
136  *    Revision 1.3  2001/05/25 11:03:55  oes
137  *    Added sanity check for NULL jobs to pcrs_exec_substitution
138  *
139  *    Revision 1.2  2001/05/22 18:46:04  oes
140  *
141  *      Added support for PCRE_UNGREEDY behaviour to pcrs,
142  *      which is selected by the (nonstandard and therefore
143  *      capital) letter 'U' in the option string.
144  *      It causes the quantifiers to be ungreedy by default.
145  *      Appending a ? turns back to greedy (!).
146  *
147  *    Revision 1.1.1.1  2001/05/15 13:59:02  oes
148  *    Initial import of version 2.9.3 source tree
149  *
150  *
151  *********************************************************************/
152 \f
153
154 /*
155  * Include project.h just so that the right pcre.h gets
156  * included from there
157  */
158 #include "project.h"
159
160 #include <string.h>
161 #include <ctype.h>
162
163 #include "pcrs.h"
164
165 const char pcrs_h_rcs[] = PCRS_H_VERSION;
166
167 /*
168  * Internal prototypes
169  */
170
171 static int              pcrs_parse_perl_options(const char *optstring, int *flags);
172 static pcrs_substitute *pcrs_compile_replacement(const char *replacement, int trivialflag,
173                         int capturecount, int *errptr);
174
175 /*********************************************************************
176  *
177  * Function    :  pcrs_strerror
178  *
179  * Description :  Return a string describing a given error code.
180  *             
181  * Parameters  :
182  *          1  :  error = the error code
183  *
184  * Returns     :  char * to the descriptive string
185  *
186  *********************************************************************/
187 const char *pcrs_strerror(const int error)
188 {
189    if (error < 0)
190    {
191       switch (error)
192       {
193          /* Passed-through PCRE error: */
194          case PCRE_ERROR_NOMEMORY:     return "(pcre:) No memory";
195
196          /* Shouldn't happen unless PCRE or PCRS bug, or user messed with compiled job: */
197          case PCRE_ERROR_NULL:         return "(pcre:) NULL code or subject or ovector";
198          case PCRE_ERROR_BADOPTION:    return "(pcre:) Unrecognized option bit";
199          case PCRE_ERROR_BADMAGIC:     return "(pcre:) Bad magic number in code";
200          case PCRE_ERROR_UNKNOWN_NODE: return "(pcre:) Bad node in pattern";
201
202          /* Can't happen / not passed: */
203          case PCRE_ERROR_NOSUBSTRING:  return "(pcre:) Fire in power supply"; 
204          case PCRE_ERROR_NOMATCH:      return "(pcre:) Water in power supply";
205
206          /* PCRS errors: */
207          case PCRS_ERR_NOMEM:          return "(pcrs:) No memory";
208          case PCRS_ERR_CMDSYNTAX:      return "(pcrs:) Syntax error while parsing command";
209          case PCRS_ERR_STUDY:          return "(pcrs:) PCRE error while studying the pattern";
210          case PCRS_ERR_BADJOB:         return "(pcrs:) Bad job - NULL job, pattern or substitute";
211          case PCRS_WARN_BADREF:        return "(pcrs:) Backreference out of range";
212
213          /* What's that? */
214          default:  return "Unknown error";
215       }
216    }
217    /* error >= 0: No error */
218    return "(pcrs:) Everything's just fine. Thanks for asking.";
219
220 }
221
222
223 /*********************************************************************
224  *
225  * Function    :  pcrs_parse_perl_options
226  *
227  * Description :  This function parses a string containing the options to
228  *                Perl's s/// operator. It returns an integer that is the
229  *                pcre equivalent of the symbolic optstring.
230  *                Since pcre doesn't know about Perl's 'g' (global) or pcrs',
231  *                'T' (trivial) options but pcrs needs them, the corresponding
232  *                flags are set if 'g'or 'T' is encountered.
233  *                Note: The 'T' and 'U' options do not conform to Perl.
234  *             
235  * Parameters  :
236  *          1  :  optstring = string with options in perl syntax
237  *          2  :  flags = see description
238  *
239  * Returns     :  option integer suitable for pcre 
240  *
241  *********************************************************************/
242 static int pcrs_parse_perl_options(const char *optstring, int *flags)
243 {
244    size_t i;
245    int rc = 0;
246    *flags = 0;
247
248    if (NULL == optstring) return 0;
249
250    for (i = 0; i < strlen(optstring); i++)
251    {
252       switch(optstring[i])
253       {
254          case 'e': break; /* ToDo ;-) */
255          case 'g': *flags |= PCRS_GLOBAL; break;
256          case 'i': rc |= PCRE_CASELESS; break;
257          case 'm': rc |= PCRE_MULTILINE; break;
258          case 'o': break;
259          case 's': rc |= PCRE_DOTALL; break;
260          case 'x': rc |= PCRE_EXTENDED; break;
261          case 'U': rc |= PCRE_UNGREEDY; break;
262          case 'T': *flags |= PCRS_TRIVIAL; break;
263          default: break;
264       }
265    }
266    return rc;
267
268 }
269
270
271 /*********************************************************************
272  *
273  * Function    :  pcrs_compile_replacement
274  *
275  * Description :  This function takes a Perl-style replacement (2nd argument
276  *                to the s/// operator and returns a compiled pcrs_substitute,
277  *                or NULL if memory allocation for the substitute structure
278  *                fails.
279  *
280  * Parameters  :
281  *          1  :  replacement = replacement part of s/// operator
282  *                              in perl syntax
283  *          2  :  trivialflag = Flag that causes backreferences to be
284  *                              ignored.
285  *          3  :  capturecount = Number of capturing subpatterns in
286  *                               the pattern. Needed for $+ handling.
287  *          4  :  errptr = pointer to an integer in which error
288  *                         conditions can be returned.
289  *
290  * Returns     :  pcrs_substitute data structure, or NULL if an
291  *                error is encountered. In that case, *errptr has
292  *                the reason.
293  *
294  *********************************************************************/
295 static pcrs_substitute *pcrs_compile_replacement(const char *replacement, int trivialflag, int capturecount, int *errptr)
296 {
297    int i, k, l, quoted;
298    size_t length;
299    char *text;
300    pcrs_substitute *r;
301
302    i = k = l = quoted = 0;
303
304    /*
305     * Sanity check
306     */
307    if (NULL == replacement)
308    {
309       replacement = "";
310    }
311
312    /*
313     * Get memory or fail
314     */
315    if (NULL == (r = (pcrs_substitute *)malloc(sizeof(pcrs_substitute))))
316    {
317       *errptr = PCRS_ERR_NOMEM;
318       return NULL;
319    }
320    memset(r, '\0', sizeof(pcrs_substitute));
321
322    length = strlen(replacement);
323
324    if (NULL == (text = (char *)malloc(length + 1)))
325    {
326       free(r);
327       *errptr = PCRS_ERR_NOMEM;
328       return NULL;
329    }
330    memset(text, '\0', length + 1);
331    
332
333    /*
334     * In trivial mode, just copy the substitute text
335     */
336    if (trivialflag)
337    {
338       text = strncpy(text, replacement, length + 1);
339       k = length;
340    }
341
342    /*
343     * Else, parse, cut out and record all backreferences
344     */
345    else
346    {
347       while (i < (int)length)
348       {
349          /* Quoting */
350          if (replacement[i] == '\\')
351          {
352             if (quoted)
353             {
354                text[k++] = replacement[i++];
355                quoted = 0;
356             }
357             else
358             {
359                if (replacement[i+1] && strchr("tnrfae0", replacement[i+1]))
360                {
361                   switch (replacement[++i])
362                   {
363                   case 't':
364                      text[k++] = '\t';
365                      break;
366                   case 'n':
367                      text[k++] = '\n';
368                      break;
369                   case 'r':
370                      text[k++] = '\r';
371                      break;
372                   case 'f':
373                      text[k++] = '\f';
374                      break;
375                   case 'a':
376                      text[k++] = 7;
377                      break;
378                   case 'e':
379                      text[k++] = 27;
380                      break;
381                   case '0':
382                      text[k++] = '\0';
383                      break;
384                   }
385                   i++;
386                }
387                else
388                {
389                   quoted = 1;
390                   i++;
391                }
392             }
393             continue;
394          }
395
396          /* Backreferences */
397          if (replacement[i] == '$' && !quoted && i < (int)(length - 1))
398          {
399             char *symbol, symbols[] = "'`+&";
400             r->block_length[l] = k - r->block_offset[l];
401
402             /* Numerical backreferences */
403             if (isdigit((int)replacement[i + 1]))
404             {
405                while (i < (int)length && isdigit((int)replacement[++i]))
406                {
407                   r->backref[l] = r->backref[l] * 10 + replacement[i] - 48;
408                }
409                if (r->backref[l] > capturecount)
410                {
411                   *errptr = PCRS_WARN_BADREF;
412                }
413             }
414
415             /* Symbolic backreferences: */
416             else if (NULL != (symbol = strchr(symbols, replacement[i + 1])))
417             {
418                
419                if (symbol - symbols == 2) /* $+ */
420                {
421                   r->backref[l] = capturecount;
422                }
423                else if (symbol - symbols == 3) /* $& */
424                {
425                   r->backref[l] = 0;
426                }
427                else /* $' or $` */
428                {
429                   r->backref[l] = PCRS_MAX_SUBMATCHES + 1 - (symbol - symbols);
430                }
431                i += 2;
432             }
433
434             /* Invalid backref -> plain '$' */
435             else
436             {
437                goto plainchar;
438             }
439
440             /* Valid and in range? -> record */
441             if (r->backref[l] < PCRS_MAX_SUBMATCHES + 2)
442             {
443                r->backref_count[r->backref[l]] += 1;
444                r->block_offset[++l] = k;
445             }
446             else
447             {
448                *errptr = PCRS_WARN_BADREF;
449             }   
450             continue;
451          }
452          
453 plainchar:
454          /* Plain chars are copied */
455          text[k++] = replacement[i++];
456          quoted = 0;
457       }
458    } /* -END- if (!trivialflag) */
459
460    /*
461     * Finish & return
462     */
463    r->text = text;
464    r->backrefs = l;
465    r->block_length[l] = k - r->block_offset[l];
466
467    return r;
468
469 }
470
471
472 /*********************************************************************
473  *
474  * Function    :  pcrs_free_job
475  *
476  * Description :  Frees the memory used by a pcrs_job struct and its
477  *                dependant structures.
478  *
479  * Parameters  :
480  *          1  :  job = pointer to the pcrs_job structure to be freed
481  *
482  * Returns     :  a pointer to the next job, if there was any, or
483  *                NULL otherwise. 
484  *
485  *********************************************************************/
486 pcrs_job *pcrs_free_job(pcrs_job *job)
487 {
488    pcrs_job *next;
489
490    if (job == NULL)
491    {
492       return NULL;
493    }
494    else
495    {
496       next = job->next;
497       if (job->pattern != NULL) free(job->pattern);
498       if (job->hints != NULL) free(job->hints);
499       if (job->substitute != NULL)
500       {
501          if (job->substitute->text != NULL) free(job->substitute->text);
502          free(job->substitute);
503       }
504       free(job);
505    }
506    return next;
507
508 }
509
510
511 /*********************************************************************
512  *
513  * Function    :  pcrs_free_joblist
514  *
515  * Description :  Iterates through a chained list of pcrs_job's and
516  *                frees them using pcrs_free_job.
517  *
518  * Parameters  :
519  *          1  :  joblist = pointer to the first pcrs_job structure to
520  *                be freed
521  *
522  * Returns     :  N/A
523  *
524  *********************************************************************/
525 void pcrs_free_joblist(pcrs_job *joblist)
526 {
527    while ( NULL != (joblist = pcrs_free_job(joblist)) ) {};
528
529    return;
530
531 }
532
533
534 /*********************************************************************
535  *
536  * Function    :  pcrs_compile_command
537  *
538  * Description :  Parses a string with a Perl-style s/// command, 
539  *                calls pcrs_compile, and returns a corresponding
540  *                pcrs_job, or NULL if parsing or compiling the job
541  *                fails.
542  *
543  * Parameters  :
544  *          1  :  command = string with perl-style s/// command
545  *          2  :  errptr = pointer to an integer in which error
546  *                         conditions can be returned.
547  *
548  * Returns     :  a corresponding pcrs_job data structure, or NULL
549  *                if an error was encountered. In that case, *errptr
550  *                has the reason.
551  *
552  *********************************************************************/
553 pcrs_job *pcrs_compile_command(const char *command, int *errptr)
554 {
555    int i, k, l, quoted = FALSE;
556    size_t limit;
557    char delimiter;
558    char *tokens[4];   
559    pcrs_job *newjob;
560    
561    i = k = l = 0;
562    
563    /*
564     * Tokenize the perl command
565     */
566    limit = strlen(command);
567    if (limit < 4)
568    {
569       *errptr = PCRS_ERR_CMDSYNTAX;
570       return NULL;
571    }
572    else
573    {
574       delimiter = command[1];
575    }
576
577    tokens[l] = (char *) malloc(limit + 1);
578
579    for (i = 0; i <= (int)limit; i++)
580    {
581       
582       if (command[i] == delimiter && !quoted)
583       {
584          if (l == 3)
585          {
586             l = -1;
587             break;
588          }
589          tokens[0][k++] = '\0';
590          tokens[++l] = tokens[0] + k;
591          continue;
592       }
593       
594       else if (command[i] == '\\' && !quoted)
595       {
596          quoted = TRUE;
597          if (command[i+1] == delimiter) continue;
598       }
599       else
600       {
601          quoted = FALSE;
602       }
603       tokens[0][k++] = command[i];
604    }
605
606    /*
607     * Syntax error ?
608     */
609    if (l != 3)
610    {
611       *errptr = PCRS_ERR_CMDSYNTAX;
612       free(tokens[0]);
613       return NULL;
614    }
615    
616    newjob = pcrs_compile(tokens[1], tokens[2], tokens[3], errptr);
617    free(tokens[0]);
618    return newjob;
619    
620 }
621
622
623 /*********************************************************************
624  *
625  * Function    :  pcrs_compile
626  *
627  * Description :  Takes the three arguments to a perl s/// command
628  *                and compiles a pcrs_job structure from them.
629  *
630  * Parameters  :
631  *          1  :  pattern = string with perl-style pattern
632  *          2  :  substitute = string with perl-style substitute
633  *          3  :  options = string with perl-style options
634  *          4  :  errptr = pointer to an integer in which error
635  *                         conditions can be returned.
636  *
637  * Returns     :  a corresponding pcrs_job data structure, or NULL
638  *                if an error was encountered. In that case, *errptr
639  *                has the reason.
640  *
641  *********************************************************************/
642 pcrs_job *pcrs_compile(const char *pattern, const char *substitute, const char *options, int *errptr)
643 {
644    pcrs_job *newjob;
645    int flags;
646    int capturecount;
647    const char *error;
648
649    *errptr = 0;
650
651    /* 
652     * Handle NULL arguments
653     */
654    if (pattern == NULL) pattern = "";
655    if (substitute == NULL) substitute = "";
656
657
658    /* 
659     * Get and init memory
660     */
661    if (NULL == (newjob = (pcrs_job *)malloc(sizeof(pcrs_job))))
662    {
663       *errptr = PCRS_ERR_NOMEM;
664       return NULL;
665    }
666    memset(newjob, '\0', sizeof(pcrs_job));
667
668
669    /*
670     * Evaluate the options
671     */
672    newjob->options = pcrs_parse_perl_options(options, &flags);
673    newjob->flags = flags;
674
675
676    /*
677     * Compile the pattern
678     */
679    newjob->pattern = pcre_compile(pattern, newjob->options, &error, errptr, NULL);
680    if (newjob->pattern == NULL)
681    {
682       pcrs_free_job(newjob);
683       return NULL;
684    }
685
686
687    /*
688     * Generate hints. This has little overhead, since the
689     * hints will be NULL for a boring pattern anyway.
690     */
691    newjob->hints = pcre_study(newjob->pattern, 0, &error);
692    if (error != NULL)
693    {
694       *errptr = PCRS_ERR_STUDY;
695       pcrs_free_job(newjob);
696       return NULL;
697    }
698  
699
700    /* 
701     * Determine the number of capturing subpatterns. 
702     * This is needed for handling $+ in the substitute.
703     */
704    if (0 > (*errptr = pcre_fullinfo(newjob->pattern, newjob->hints, PCRE_INFO_CAPTURECOUNT, &capturecount)))
705    {
706       pcrs_free_job(newjob);
707       return NULL;
708    }
709  
710
711    /*
712     * Compile the substitute
713     */
714    if (NULL == (newjob->substitute = pcrs_compile_replacement(substitute, newjob->flags & PCRS_TRIVIAL, capturecount, errptr)))
715    {
716       pcrs_free_job(newjob);
717       return NULL;
718    }
719  
720    return newjob;
721
722 }
723
724
725 /*********************************************************************
726  *
727  * Function    :  pcrs_execute_list
728  *
729  * Description :  This is a multiple job wrapper for pcrs_execute().
730  *                Apply the regular substitutions defined by the jobs in
731  *                the joblist to the subject.
732  *                The subject itself is left untouched, memory for the result
733  *                is malloc()ed and it is the caller's responsibility to free
734  *                the result when it's no longer needed.
735  *
736  * Parameters  :
737  *          1  :  joblist = the chained list of pcrs_jobs to be executed
738  *          2  :  subject = the subject string
739  *          3  :  subject_length = the subject's length 
740  *                INCLUDING the terminating zero, if string!
741  *          4  :  result = char** for returning  the result 
742  *          5  :  result_length = size_t* for returning the result's length
743  *
744  * Returns     :  On success, the number of substitutions that were made.
745  *                 May be > 1 if job->flags contained PCRS_GLOBAL
746  *                On failure, the (negative) pcre error code describing the
747  *                 failure, which may be translated to text using pcrs_strerror().
748  *
749  *********************************************************************/
750 int pcrs_execute_list(pcrs_job *joblist, char *subject, size_t subject_length, char **result, size_t *result_length)
751 {
752    pcrs_job *job;
753    char *old_item, *new_item;
754    int hits, total_hits;
755  
756    old_item = subject;
757    *result_length = subject_length;
758    hits = total_hits = 0;
759
760    for (job = joblist; job != NULL; job = job->next)
761    {
762       hits = pcrs_execute(job, old_item, *result_length, &new_item, result_length);
763
764       if (old_item != subject) free(old_item);
765
766       if (hits < 0)
767       {
768          return(hits);
769       }
770       else
771       {
772          total_hits += hits;
773          old_item = new_item;
774       }
775    }
776
777    *result = new_item;
778    return(total_hits);
779
780 }
781
782
783 /*********************************************************************
784  *
785  * Function    :  pcrs_execute
786  *
787  * Description :  Apply the regular substitution defined by the job to the
788  *                subject.
789  *                The subject itself is left untouched, memory for the result
790  *                is malloc()ed and it is the caller's responsibility to free
791  *                the result when it's no longer needed.
792  *
793  * Parameters  :
794  *          1  :  job = the pcrs_job to be executed
795  *          2  :  subject = the subject (== original) string
796  *          3  :  subject_length = the subject's length 
797  *                INCLUDING the terminating zero, if string!
798  *          4  :  result = char** for returning  the result 
799  *          5  :  result_length = size_t* for returning the result's length
800  *
801  * Returns     :  On success, the number of substitutions that were made.
802  *                 May be > 1 if job->flags contained PCRS_GLOBAL
803  *                On failure, the (negative) pcre error code describing the
804  *                 failure, which may be translated to text using pcrs_strerror().
805  *
806  *********************************************************************/
807 int pcrs_execute(pcrs_job *job, char *subject, size_t subject_length, char **result, size_t *result_length)
808 {
809    int offsets[3 * PCRS_MAX_SUBMATCHES],
810        offset,
811        i, k,
812        matches_found,
813        submatches,
814        max_matches = PCRS_MAX_MATCH_INIT;
815    size_t newsize;
816    pcrs_match *matches, *dummy;
817    char *result_offset;
818
819    offset = i = k = 0;
820
821    /* 
822     * Sanity check & memory allocation
823     */
824    if (job == NULL || job->pattern == NULL || job->substitute == NULL)
825    {
826       *result = NULL;
827       return(PCRS_ERR_BADJOB);
828    }
829
830    if (NULL == (matches = (pcrs_match *)malloc(max_matches * sizeof(pcrs_match))))
831    {
832       *result = NULL;
833       return(PCRS_ERR_NOMEM);
834    }
835    memset(matches, '\0', max_matches * sizeof(pcrs_match));
836
837
838    /*
839     * Find the pattern and calculate the space
840     * requirements for the result
841     */
842    newsize = subject_length;
843
844    while ((submatches = pcre_exec(job->pattern, job->hints, subject, (int)subject_length, offset, 0, offsets, 3 * PCRS_MAX_SUBMATCHES)) > 0)
845    {
846       job->flags |= PCRS_SUCCESS;
847       matches[i].submatches = submatches;
848
849       for (k = 0; k < submatches; k++)
850       {
851          matches[i].submatch_offset[k] = offsets[2 * k];
852
853          /* Note: Non-found optional submatches have length -1-(-1)==0 */
854          matches[i].submatch_length[k] = offsets[2 * k + 1] - offsets[2 * k]; 
855
856          /* reserve mem for each submatch as often as it is ref'd */
857          newsize += matches[i].submatch_length[k] * job->substitute->backref_count[k]; 
858       }
859       /* plus replacement text size minus match text size */
860       newsize += strlen(job->substitute->text) - matches[i].submatch_length[0]; 
861
862       /* chunk before match */
863       matches[i].submatch_offset[PCRS_MAX_SUBMATCHES] = 0;
864       matches[i].submatch_length[PCRS_MAX_SUBMATCHES] = offsets[0];
865       newsize += offsets[0] * job->substitute->backref_count[PCRS_MAX_SUBMATCHES];
866
867       /* chunk after match */
868       matches[i].submatch_offset[PCRS_MAX_SUBMATCHES + 1] = offsets[1];
869       matches[i].submatch_length[PCRS_MAX_SUBMATCHES + 1] = subject_length - offsets[1] - 1;
870       newsize += (subject_length - offsets[1]) * job->substitute->backref_count[PCRS_MAX_SUBMATCHES + 1];
871
872       /* Storage for matches exhausted? -> Extend! */
873       if (++i >= max_matches)
874       {
875          max_matches = (int)(max_matches * PCRS_MAX_MATCH_GROW);
876          if (NULL == (dummy = (pcrs_match *)realloc(matches, max_matches * sizeof(pcrs_match))))
877          {
878             free(matches);
879             *result = NULL;
880             return(PCRS_ERR_NOMEM);
881          }
882          matches = dummy;
883       }
884
885       /* Non-global search or limit reached? */
886       if (!(job->flags & PCRS_GLOBAL)) break;
887
888       /* Don't loop on empty matches */
889       if (offsets[1] == offset)
890          if ((size_t)offset < subject_length)
891             offset++;
892          else
893             break;
894       /* Go find the next one */
895       else
896          offset = offsets[1];
897    }
898    /* Pass pcre error through if (bad) failure */
899    if (submatches < PCRE_ERROR_NOMATCH)
900    {
901       free(matches);
902       return submatches;   
903    }
904    matches_found = i;
905
906
907    /* 
908     * Get memory for the result
909     */
910    if ((*result = (char *)malloc(newsize)) == NULL)   /* must be free()d by caller */
911    {
912       free(matches);
913       return PCRS_ERR_NOMEM;
914    }
915
916
917    /* 
918     * Replace
919     */
920    offset = 0;
921    result_offset = *result;
922
923    for (i = 0; i < matches_found; i++)
924    {
925       /* copy the chunk preceding the match */
926       memcpy(result_offset, subject + offset, (size_t)matches[i].submatch_offset[0] - offset); 
927       result_offset += matches[i].submatch_offset[0] - offset;
928
929       /* For every segment of the substitute.. */
930       for (k = 0; k <= job->substitute->backrefs; k++)
931       {
932          /* ...copy its text.. */
933          memcpy(result_offset, job->substitute->text + job->substitute->block_offset[k], job->substitute->block_length[k]);
934          result_offset += job->substitute->block_length[k];
935
936          /* ..plus, if it's not the last chunk, i.e.: There *is* a backref.. */
937          if (k != job->substitute->backrefs
938              /* ..in legal range.. */
939              && job->substitute->backref[k] < PCRS_MAX_SUBMATCHES + 2
940               /* ..and referencing a real submatch.. */
941              && job->substitute->backref[k] < matches[i].submatches
942              /* ..that is nonempty.. */
943              && matches[i].submatch_length[job->substitute->backref[k]] > 0)
944          {
945             /* ..copy the submatch that is ref'd. */
946             memcpy(
947                result_offset,
948                subject + matches[i].submatch_offset[job->substitute->backref[k]],
949                matches[i].submatch_length[job->substitute->backref[k]]
950             );
951             result_offset += matches[i].submatch_length[job->substitute->backref[k]];
952          }
953       }
954       offset =  matches[i].submatch_offset[0] + matches[i].submatch_length[0];
955    }
956
957    /* Copy the rest. */
958    memcpy(result_offset, subject + offset, subject_length - offset);
959
960    *result_length = newsize;
961    free(matches);
962    return matches_found;
963
964 }
965
966
967 /*
968   Local Variables:
969   tab-width: 3
970   end:
971 */