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