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