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