Added docbook paths for debian sarge; set status for release
[privoxy.git] / miscutil.c
1 const char miscutil_rcs[] = "$Id: miscutil.c,v 1.37.2.3 2003/11/20 11:39:24 oes Exp $";
2 /*********************************************************************
3  *
4  * File        :  $Source: /cvsroot/ijbswa/current/Attic/miscutil.c,v $
5  *
6  * Purpose     :  zalloc, hash_string, safe_strerror, strcmpic,
7  *                strncmpic, chomp, and MinGW32 strdup
8  *                functions. 
9  *                These are each too small to deserve their own file
10  *                but don't really fit in any other file.
11  *
12  * Copyright   :  Written by and Copyright (C) 2001 the SourceForge
13  *                Privoxy team. http://www.privoxy.org/
14  *
15  *                Based on the Internet Junkbuster originally written
16  *                by and Copyright (C) 1997 Anonymous Coders and 
17  *                Junkbusters Corporation.  http://www.junkbusters.com
18  *
19  *                This program is free software; you can redistribute it 
20  *                and/or modify it under the terms of the GNU General
21  *                Public License as published by the Free Software
22  *                Foundation; either version 2 of the License, or (at
23  *                your option) any later version.
24  *
25  *                This program is distributed in the hope that it will
26  *                be useful, but WITHOUT ANY WARRANTY; without even the
27  *                implied warranty of MERCHANTABILITY or FITNESS FOR A
28  *                PARTICULAR PURPOSE.  See the GNU General Public
29  *                License for more details.
30  *
31  *                The GNU General Public License should be included with
32  *                this file.  If not, you can view it at
33  *                http://www.gnu.org/copyleft/gpl.html
34  *                or write to the Free Software Foundation, Inc., 59
35  *                Temple Place - Suite 330, Boston, MA  02111-1307, USA.
36  *
37  * Revisions   :
38  *    $Log: miscutil.c,v $
39  *    Revision 1.37.2.3  2003/11/20 11:39:24  oes
40  *    Bugfix: The "?" wildcard for domain names had never been implemented. Ooops\!
41  *
42  *    Revision 1.37.2.2  2002/11/12 14:28:18  oes
43  *    Proper backtracking in simplematch; fixes bug #632888
44  *
45  *    Revision 1.37.2.1  2002/09/25 12:58:51  oes
46  *    Made strcmpic and strncmpic safe against NULL arguments
47  *    (which are now treated as empty strings).
48  *
49  *    Revision 1.37  2002/04/26 18:29:43  jongfoster
50  *    Fixing this Visual C++ warning:
51  *    miscutil.c(710) : warning C4090: '=' : different 'const' qualifiers
52  *
53  *    Revision 1.36  2002/04/26 12:55:38  oes
54  *    New function string_toupper
55  *
56  *    Revision 1.35  2002/03/26 22:29:55  swa
57  *    we have a new homepage!
58  *
59  *    Revision 1.34  2002/03/24 13:25:43  swa
60  *    name change related issues
61  *
62  *    Revision 1.33  2002/03/07 03:46:53  oes
63  *    Fixed compiler warnings etc
64  *
65  *    Revision 1.32  2002/03/06 23:02:57  jongfoster
66  *    Removing tabs
67  *
68  *    Revision 1.31  2002/03/05 04:52:42  oes
69  *    Deleted non-errlog debugging code
70  *
71  *    Revision 1.30  2002/03/04 18:27:42  oes
72  *    - Deleted deletePidFile
73  *    - Made write_pid_file use the --pidfile option value
74  *      (or no PID file, if the option was absent)
75  *    - Played styleguide police
76  *
77  *    Revision 1.29  2002/03/04 02:08:02  david__schmidt
78  *    Enable web editing of actions file on OS/2 (it had been broken all this time!)
79  *
80  *    Revision 1.28  2002/03/03 09:18:03  joergs
81  *    Made jumbjuster work on AmigaOS again.
82  *
83  *    Revision 1.27  2002/01/21 00:52:32  jongfoster
84  *    Adding string_join()
85  *
86  *    Revision 1.26  2001/12/30 14:07:32  steudten
87  *    - Add signal handling (unix)
88  *    - Add SIGHUP handler (unix)
89  *    - Add creation of pidfile (unix)
90  *    - Add action 'top' in rc file (RH)
91  *    - Add entry 'SIGNALS' to manpage
92  *    - Add exit message to logfile (unix)
93  *
94  *    Revision 1.25  2001/11/13 00:16:38  jongfoster
95  *    Replacing references to malloc.h with the standard stdlib.h
96  *    (See ANSI or K&R 2nd Ed)
97  *
98  *    Revision 1.24  2001/11/05 21:41:43  steudten
99  *    Add changes to be a real daemon just for unix os.
100  *    (change cwd to /, detach from controlling tty, set
101  *    process group and session leader to the own process.
102  *    Add DBG() Macro.
103  *    Add some fatal-error log message for failed malloc().
104  *    Add '-d' if compiled with 'configure --with-debug' to
105  *    enable debug output.
106  *
107  *    Revision 1.23  2001/10/29 03:48:10  david__schmidt
108  *    OS/2 native needed a snprintf() routine.  Added one to miscutil, brackedted
109  *    by and __OS2__ ifdef.
110  *
111  *    Revision 1.22  2001/10/26 17:39:38  oes
112  *    Moved ijb_isspace and ijb_tolower to project.h
113  *
114  *    Revision 1.21  2001/10/23 21:27:50  jongfoster
115  *    Standardising error codes in string_append
116  *    make_path() no longer adds '\\' if the dir already ends in '\\' (this
117  *    is just copying a UNIX-specific fix to the Windows-specific part)
118  *
119  *    Revision 1.20  2001/10/22 15:33:56  david__schmidt
120  *    Special-cased OS/2 out of the Netscape-abort-on-404-in-js problem in
121  *    filters.c.  Added a FIXME in front of the offending code.  I'll gladly
122  *    put in a better/more robust fix for all parties if one is presented...
123  *    It seems that just returning 200 instead of 404 would pretty much fix
124  *    it for everyone, but I don't know all the history of the problem.
125  *
126  *    Revision 1.19  2001/10/14 22:02:57  jongfoster
127  *    New function string_append() which is like strsav(), but running
128  *    out of memory isn't automatically FATAL.
129  *
130  *    Revision 1.18  2001/09/20 13:33:43  steudten
131  *
132  *    change long to int as return value in hash_string(). Remember the wraparound
133  *    for int = long = sizeof(4) - thats maybe not what we want.
134  *
135  *    Revision 1.17  2001/09/13 20:51:29  jongfoster
136  *    Fixing potential problems with characters >=128 in simplematch()
137  *    This was also a compiler warning.
138  *
139  *    Revision 1.16  2001/09/10 10:56:59  oes
140  *    Silenced compiler warnings
141  *
142  *    Revision 1.15  2001/07/13 14:02:24  oes
143  *    Removed vim-settings
144  *
145  *    Revision 1.14  2001/06/29 21:45:41  oes
146  *    Indentation, CRLF->LF, Tab-> Space
147  *
148  *    Revision 1.13  2001/06/29 13:32:14  oes
149  *    Removed logentry from cancelled commit
150  *
151  *    Revision 1.12  2001/06/09 10:55:28  jongfoster
152  *    Changing BUFSIZ ==> BUFFER_SIZE
153  *
154  *    Revision 1.11  2001/06/07 23:09:19  jongfoster
155  *    Cosmetic indentation changes.
156  *
157  *    Revision 1.10  2001/06/07 14:51:38  joergs
158  *    make_path() no longer adds '/' if the dir already ends in '/'.
159  *
160  *    Revision 1.9  2001/06/07 14:43:17  swa
161  *    slight mistake in make_path, unix path style is /.
162  *
163  *    Revision 1.8  2001/06/05 22:32:01  jongfoster
164  *    New function make_path() to splice directory and file names together.
165  *
166  *    Revision 1.7  2001/06/03 19:12:30  oes
167  *    introduced bindup()
168  *
169  *    Revision 1.6  2001/06/01 18:14:49  jongfoster
170  *    Changing the calls to strerr() to check HAVE_STRERR (which is defined
171  *    in config.h if appropriate) rather than the NO_STRERR macro.
172  *
173  *    Revision 1.5  2001/06/01 10:31:51  oes
174  *    Added character class matching to trivimatch; renamed to simplematch
175  *
176  *    Revision 1.4  2001/05/31 17:32:31  oes
177  *
178  *     - Enhanced domain part globbing with infix and prefix asterisk
179  *       matching and optional unanchored operation
180  *
181  *    Revision 1.3  2001/05/29 23:10:09  oes
182  *
183  *
184  *     - Introduced chomp()
185  *     - Moved strsav() from showargs to miscutil
186  *
187  *    Revision 1.2  2001/05/29 09:50:24  jongfoster
188  *    Unified blocklist/imagelist/permissionslist.
189  *    File format is still under discussion, but the internal changes
190  *    are (mostly) done.
191  *
192  *    Also modified interceptor behaviour:
193  *    - We now intercept all URLs beginning with one of the following
194  *      prefixes (and *only* these prefixes):
195  *        * http://i.j.b/
196  *        * http://ijbswa.sf.net/config/
197  *        * http://ijbswa.sourceforge.net/config/
198  *    - New interceptors "home page" - go to http://i.j.b/ to see it.
199  *    - Internal changes so that intercepted and fast redirect pages
200  *      are not replaced with an image.
201  *    - Interceptors now have the option to send a binary page direct
202  *      to the client. (i.e. ijb-send-banner uses this)
203  *    - Implemented show-url-info interceptor.  (Which is why I needed
204  *      the above interceptors changes - a typical URL is
205  *      "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
206  *      The previous mechanism would not have intercepted that, and
207  *      if it had been intercepted then it then it would have replaced
208  *      it with an image.)
209  *
210  *    Revision 1.1.1.1  2001/05/15 13:59:00  oes
211  *    Initial import of version 2.9.3 source tree
212  *
213  *
214  *********************************************************************/
215 \f
216
217 #include "config.h"
218
219 #include <stdio.h>
220 #include <sys/types.h>
221 #include <stdlib.h>
222 #if !defined(_WIN32) && !defined(__OS2__)
223 #include <unistd.h>
224 #endif /* #if !defined(_WIN32) && !defined(__OS2__) */
225 #include <string.h>
226 #include <ctype.h>
227 #include <assert.h>
228
229 #include "project.h"
230 #include "miscutil.h"
231 #include "errlog.h"
232 #include "jcc.h"
233
234 const char miscutil_h_rcs[] = MISCUTIL_H_VERSION;
235
236 /*********************************************************************
237  *
238  * Function    :  zalloc
239  *
240  * Description :  Malloc some memory and set it to '\0'.
241  *                The way calloc() ought to be -acjc
242  *
243  * Parameters  :
244  *          1  :  size = Size of memory chunk to return.
245  *
246  * Returns     :  Pointer to newly malloc'd memory chunk.
247  *
248  *********************************************************************/
249 void *zalloc(size_t size)
250 {
251    void * ret;
252
253    if ((ret = (void *)malloc(size)) != NULL)
254    {
255       memset(ret, 0, size);
256    }
257
258    return(ret);
259
260 }
261
262
263 #if defined(unix)
264 /*********************************************************************
265  *
266  * Function    :  write_pid_file 
267  *
268  * Description :  Writes a pid file with the pid of the main process 
269  *
270  * Parameters  :  None
271  *
272  * Returns     :  N/A 
273  *
274  *********************************************************************/
275 void write_pid_file(void)
276 {
277    FILE   *fp;
278    
279    /*
280     * If no --pidfile option was given,
281     * we can live without one.
282     */
283    if (pidfile == NULL) return;
284
285    if ((fp = fopen(pidfile, "w")) == NULL)
286    {
287       log_error(LOG_LEVEL_INFO, "can't open pidfile '%s': %E", pidfile);
288    }
289    else
290    {
291       fprintf(fp, "%u\n", (unsigned int) getpid());
292       fclose (fp);
293    }
294    return;
295
296 }
297 #endif /* def unix */
298
299
300 /*********************************************************************
301  *
302  * Function    :  hash_string
303  *
304  * Description :  Take a string and compute a (hopefuly) unique numeric
305  *                integer value.  This has several uses, but being able
306  *                to "switch" a string the one of my favorites.
307  *
308  * Parameters  :
309  *          1  :  s : string to be hashed.
310  *
311  * Returns     :  an unsigned long variable with the hashed value.
312  *
313  *********************************************************************/
314 unsigned int hash_string( const char* s )
315 {
316    unsigned int h = 0; 
317
318    for ( ; *s; ++s )
319    {
320       h = 5 * h + *s;
321    }
322
323    return (h);
324
325 }
326
327
328 #ifdef __MINGW32__
329 /*********************************************************************
330  *
331  * Function    :  strdup
332  *
333  * Description :  For some reason (which is beyond me), gcc and WIN32
334  *                don't like strdup.  When a "free" is executed on a
335  *                strdup'd ptr, it can at times freez up!  So I just
336  *                replaced it and problem was solved.
337  *
338  * Parameters  :
339  *          1  :  s = string to duplicate
340  *
341  * Returns     :  Pointer to newly malloc'ed copy of the string.
342  *
343  *********************************************************************/
344 char *strdup( const char *s )
345 {
346    char * result = (char *)malloc( strlen(s)+1 );
347
348    if (result != NULL)
349    {
350       strcpy( result, s );
351    }
352
353    return( result );
354 }
355
356 #endif /* def __MINGW32__ */
357
358
359
360 /*********************************************************************
361  *
362  * Function    :  safe_strerror
363  *
364  * Description :  Variant of the library routine strerror() which will
365  *                work on systems without the library routine, and
366  *                which should never return NULL.
367  *
368  * Parameters  :
369  *          1  :  err = the `errno' of the last operation.
370  *
371  * Returns     :  An "English" string of the last `errno'.  Allocated
372  *                with strdup(), so caller frees.  May be NULL if the
373  *                system is out of memory.
374  *
375  *********************************************************************/
376 char *safe_strerror(int err)
377 {
378    char *s = NULL;
379    char buf[BUFFER_SIZE];
380
381
382 #ifdef HAVE_STRERROR
383    s = strerror(err);
384 #endif /* HAVE_STRERROR */
385
386    if (s == NULL)
387    {
388       sprintf(buf, "(errno = %d)", err);
389       s = buf;
390    }
391
392    return(strdup(s));
393
394 }
395
396
397 /*********************************************************************
398  *
399  * Function    :  strcmpic
400  *
401  * Description :  Case insensitive string comparison
402  *
403  * Parameters  :
404  *          1  :  s1 = string 1 to compare
405  *          2  :  s2 = string 2 to compare
406  *
407  * Returns     :  0 if s1==s2, Negative if s1<s2, Positive if s1>s2
408  *
409  *********************************************************************/
410 int strcmpic(const char *s1, const char *s2)
411 {
412    if (!s1) s1 = "";
413    if (!s2) s2 = "";
414
415    while (*s1 && *s2)
416    {
417       if ( ( *s1 != *s2 ) && ( ijb_tolower(*s1) != ijb_tolower(*s2) ) )
418       {
419          break;
420       }
421       s1++, s2++;
422    }
423    return(ijb_tolower(*s1) - ijb_tolower(*s2));
424
425 }
426
427
428 /*********************************************************************
429  *
430  * Function    :  strncmpic
431  *
432  * Description :  Case insensitive string comparison (upto n characters)
433  *
434  * Parameters  :
435  *          1  :  s1 = string 1 to compare
436  *          2  :  s2 = string 2 to compare
437  *          3  :  n = maximum characters to compare
438  *
439  * Returns     :  0 if s1==s2, Negative if s1<s2, Positive if s1>s2
440  *
441  *********************************************************************/
442 int strncmpic(const char *s1, const char *s2, size_t n)
443 {
444    if (n <= 0) return(0);
445    if (!s1) s1 = "";
446    if (!s2) s2 = "";
447    
448    while (*s1 && *s2)
449    {
450       if ( ( *s1 != *s2 ) && ( ijb_tolower(*s1) != ijb_tolower(*s2) ) )
451       {
452          break;
453       }
454
455       if (--n <= 0) break;
456
457       s1++, s2++;
458    }
459    return(ijb_tolower(*s1) - ijb_tolower(*s2));
460
461 }
462
463
464 /*********************************************************************
465  *
466  * Function    :  chomp
467  *
468  * Description :  In-situ-eliminate all leading and trailing whitespace
469  *                from a string.
470  *
471  * Parameters  :
472  *          1  :  s : string to be chomped.
473  *
474  * Returns     :  chomped string
475  *
476  *********************************************************************/
477 char *chomp(char *string)
478 {
479    char *p, *q, *r;
480
481    /* 
482     * strip trailing whitespace
483     */
484    p = string + strlen(string);
485    while (p > string && ijb_isspace(*(p-1)))
486    {
487       p--;
488    }
489    *p = '\0';
490
491    /* 
492     * find end of leading whitespace 
493     */
494    q = r = string;
495    while (*q && ijb_isspace(*q))
496    {
497       q++;
498    }
499
500    /*
501     * if there was any, move the rest forwards
502     */
503    if (q != string)
504    {
505       while (q <= p)
506       {
507          *r++ = *q++;
508       }
509    }
510
511    return(string);
512
513 }
514
515
516 /*********************************************************************
517  *
518  * Function    :  strsav
519  *
520  * Description :  Reallocate "old" and append text to it.  This makes
521  *                it easier to append to malloc'd strings.
522  *                Running out of memory is a FATAL error.
523  *
524  * Parameters  :
525  *          1  :  old = Old text that is to be extended.  Will be
526  *                free()d by this routine.  May be NULL.
527  *          2  :  text_to_append = Text to be appended to old.
528  *                May be NULL.
529  *
530  * Returns     :  Pointer to newly malloc'ed appended string.
531  *                If there is no text to append, return old.  Caller
532  *                must free().
533  *
534  *********************************************************************/
535 char *strsav(char *old, const char *text_to_append)
536 {
537    size_t old_len, new_len = 0;
538    char *p;
539
540    if ((text_to_append == NULL) || (*text_to_append == '\0'))
541    {
542       return(old);
543    }
544
545    if (NULL == old)
546    {
547       if ((p = strdup(text_to_append)) == NULL)
548       {
549          log_error(LOG_LEVEL_FATAL, "strdup() failed!");
550          /* Never get here - LOG_LEVEL_FATAL causes program exit */
551       }
552       return p;
553    }
554
555    old_len = strlen(old);
556    new_len = old_len + strlen(text_to_append) + 1;
557
558    if ((p = realloc(old, new_len)) == NULL)
559    {
560       log_error(LOG_LEVEL_FATAL, "realloc(%d) bytes failed!", new_len);
561       /* Never get here - LOG_LEVEL_FATAL causes program exit */
562    }
563
564    strcpy(p + old_len, text_to_append);
565    return(p);
566 }
567
568
569 /*********************************************************************
570  *
571  * Function    :  string_append
572  *
573  * Description :  Reallocate target_string and append text to it.  
574  *                This makes it easier to append to malloc'd strings.
575  *                This is similar to the (removed) strsav(), but
576  *                running out of memory isn't catastrophic.
577  *
578  *                Programming style:
579  *
580  *                The following style provides sufficient error
581  *                checking for this routine, with minimal clutter
582  *                in the source code.  It is recommended if you
583  *                have many calls to this function:
584  *
585  *                char * s = strdup(...); // don't check for error
586  *                string_append(&s, ...);  // don't check for error
587  *                string_append(&s, ...);  // don't check for error
588  *                string_append(&s, ...);  // don't check for error
589  *                if (NULL == s) { ... handle error ... }
590  *
591  *                OR, equivalently:
592  *
593  *                char * s = strdup(...); // don't check for error
594  *                string_append(&s, ...);  // don't check for error
595  *                string_append(&s, ...);  // don't check for error
596  *                if (string_append(&s, ...)) {... handle error ...}
597  *
598  * Parameters  :
599  *          1  :  target_string = Pointer to old text that is to be
600  *                extended.  *target_string will be free()d by this
601  *                routine.  target_string must be non-NULL.
602  *                If *target_string is NULL, this routine will
603  *                do nothing and return with an error - this allows
604  *                you to make many calls to this routine and only
605  *                check for errors after the last one.
606  *          2  :  text_to_append = Text to be appended to old.
607  *                Must not be NULL.
608  *
609  * Returns     :  JB_ERR_OK on success, and sets *target_string
610  *                   to newly malloc'ed appended string.  Caller
611  *                   must free(*target_string).
612  *                JB_ERR_MEMORY on out-of-memory.  (And free()s
613  *                   *target_string and sets it to NULL).
614  *                JB_ERR_MEMORY if *target_string is NULL.
615  *
616  *********************************************************************/
617 jb_err string_append(char **target_string, const char *text_to_append)
618 {
619    size_t old_len;
620    char *new_string;
621
622    assert(target_string);
623    assert(text_to_append);
624
625    if (*target_string == NULL)
626    {
627       return JB_ERR_MEMORY;
628    }
629
630    if (*text_to_append == '\0')
631    {
632       return JB_ERR_OK;
633    }
634
635    old_len = strlen(*target_string);
636
637    if (NULL == (new_string = realloc(*target_string,
638           strlen(text_to_append) + old_len + 1)))
639    {
640       free(*target_string);
641
642       *target_string = NULL;
643       return JB_ERR_MEMORY;
644    }
645
646    strcpy(new_string + old_len, text_to_append);
647
648    *target_string = new_string;
649    return JB_ERR_OK;
650 }
651
652
653 /*********************************************************************
654  *
655  * Function    :  string_join
656  *
657  * Description :  Join two strings together.  Frees BOTH the original
658  *                strings.  If either or both input strings are NULL,
659  *                fails as if it had run out of memory.
660  *
661  *                For comparison, string_append requires that the
662  *                second string is non-NULL, and doesn't free it.
663  *
664  *                Rationale: Too often, we want to do
665  *                string_append(s, html_encode(s2)).  That assert()s
666  *                if s2 is NULL or if html_encode() runs out of memory.
667  *                It also leaks memory.  Proper checking is cumbersome.
668  *                The solution: string_join(s, html_encode(s2)) is safe,
669  *                and will free the memory allocated by html_encode().
670  *
671  * Parameters  :
672  *          1  :  target_string = Pointer to old text that is to be
673  *                extended.  *target_string will be free()d by this
674  *                routine.  target_string must be non-NULL.
675  *          2  :  text_to_append = Text to be appended to old.
676  *
677  * Returns     :  JB_ERR_OK on success, and sets *target_string
678  *                   to newly malloc'ed appended string.  Caller
679  *                   must free(*target_string).
680  *                JB_ERR_MEMORY on out-of-memory, or if
681  *                   *target_string or text_to_append is NULL.  (In
682  *                   this case, frees *target_string and text_to_append,
683  *                   sets *target_string to NULL).
684  *
685  *********************************************************************/
686 jb_err string_join(char **target_string, char *text_to_append)
687 {
688    jb_err err;
689
690    assert(target_string);
691
692    if (text_to_append == NULL)
693    {
694       freez(*target_string);
695       return JB_ERR_MEMORY;
696    }
697
698    err = string_append(target_string, text_to_append);
699
700    free(text_to_append);
701
702    return err;
703 }
704
705
706 /*********************************************************************
707  *
708  * Function    :  string_toupper
709  *
710  * Description :  Produce a copy of string with all convertible
711  *                characters converted to uppercase.
712  *
713  * Parameters  :
714  *          1  :  string = string to convert
715  *
716  * Returns     :  Uppercase copy of string if possible, 
717  *                NULL on out-of-memory or if string was NULL.
718  *
719  *********************************************************************/
720 char *string_toupper(const char *string)
721 {
722    char *result, *p;
723    const char *q;
724
725    if (!string || ((result = (char *) zalloc(strlen(string) + 1)) == NULL))
726    {
727       return NULL;
728    }
729    
730    q = string;
731    p = result;
732
733    while (*q != '\0')
734    {
735       *p++ = toupper(*q++);
736    }
737
738    return result;
739
740 }
741
742
743 /*********************************************************************
744  *
745  * Function    :  simplematch
746  *
747  * Description :  String matching, with a (greedy) '*' wildcard that
748  *                stands for zero or more arbitrary characters and
749  *                character classes in [], which take both enumerations
750  *                and ranges.
751  *
752  * Parameters  :
753  *          1  :  pattern = pattern for matching
754  *          2  :  text    = text to be matched
755  *
756  * Returns     :  0 if match, else nonzero
757  *
758  *********************************************************************/
759 int simplematch(char *pattern, char *text)
760 {
761    unsigned char *pat = (unsigned char *) pattern;
762    unsigned char *txt = (unsigned char *) text;
763    unsigned char *fallback = pat; 
764    int wildcard = 0;
765   
766    unsigned char lastchar = 'a';
767    unsigned i;
768    unsigned char charmap[32];
769   
770    while (*txt)
771    {
772
773       /* EOF pattern but !EOF text? */
774       if (*pat == '\0')
775       {
776          if (wildcard)
777          {
778             pat = fallback;
779          }
780          else
781          {
782             return 1;
783          }
784       }
785
786       /* '*' in the pattern?  */
787       if (*pat == '*') 
788       {
789      
790          /* The pattern ends afterwards? Speed up the return. */
791          if (*++pat == '\0')
792          {
793             return 0;
794          }
795      
796          /* Else, set wildcard mode and remember position after '*' */
797          wildcard = 1;
798          fallback = pat;
799       }
800
801       /* Character range specification? */
802       if (*pat == '[')
803       {
804          memset(charmap, '\0', sizeof(charmap));
805
806          while (*++pat != ']')
807          {
808             if (!*pat)
809             { 
810                return 1;
811             }
812             else if (*pat == '-')
813             {
814                if ((*++pat == ']') || *pat == '\0')
815                {
816                   return(1);
817                }
818                for(i = lastchar; i <= *pat; i++)
819                {
820                   charmap[i / 8] |= (1 << (i % 8));
821                } 
822             }
823             else
824             {
825                charmap[*pat / 8] |= (1 << (*pat % 8));
826                lastchar = *pat;
827             }
828          }
829       } /* -END- if Character range specification */
830
831
832       /* 
833        * Char match, or char range match? 
834        */
835       if ( (*pat == *txt)
836       ||   (*pat == '?')
837       ||   ((*pat == ']') && (charmap[*txt / 8] & (1 << (*txt % 8)))) )
838       {
839          /* 
840           * Sucess: Go ahead
841           */
842          pat++;
843       }
844       else if (!wildcard)
845       {
846          /* 
847           * No match && no wildcard: No luck
848           */
849          return 1;
850       }
851       else if (pat != fallback)
852       {
853          /*
854           * Wildcard mode && nonmatch beyond fallback: Rewind pattern
855           */
856          pat = fallback;
857       }
858       txt++;
859    }
860
861    /* Cut off extra '*'s */
862    if(*pat == '*')  pat++;
863
864    /* If this is the pattern's end, fine! */
865    return(*pat);
866
867 }
868
869
870 /*********************************************************************
871  *
872  * Function    :  bindup
873  *
874  * Description :  Duplicate the first n characters of a string that may
875  *                contain '\0' characters.
876  *
877  * Parameters  :
878  *          1  :  string = string to be duplicated
879  *          2  :  len = number of bytes to duplicate
880  *
881  * Returns     :  pointer to copy, or NULL if failiure
882  *
883  *********************************************************************/
884 char *bindup(const char *string, size_t len)
885 {
886    char *duplicate;
887
888    if (NULL == (duplicate = (char *)malloc(len)))
889    {
890       return NULL;
891    }
892    else
893    {
894      memcpy(duplicate, string, len);
895    }
896
897    return duplicate;
898
899 }
900
901
902 /*********************************************************************
903  *
904  * Function    :  make_path
905  *
906  * Description :  Takes a directory name and a file name, returns 
907  *                the complete path.  Handles windows/unix differences.
908  *                If the file name is already an absolute path, or if
909  *                the directory name is NULL or empty, it returns 
910  *                the filename. 
911  *
912  * Parameters  :
913  *          1  :  dir: Name of directory or NULL for none.
914  *          2  :  file: Name of file.  Should not be NULL or empty.
915  *
916  * Returns     :  "dir/file" (Or on windows, "dir\file").
917  *                It allocates the string on the heap.  Caller frees.
918  *                Returns NULL in error (i.e. NULL file or out of
919  *                memory) 
920  *
921  *********************************************************************/
922 char * make_path(const char * dir, const char * file)
923 {
924 #ifdef AMIGA
925    char path[512];
926
927    if(dir)
928    {
929       if(dir[0] == '.')
930       {
931          if(dir[1] == '/')
932          {
933             strncpy(path,dir+2,512);
934          }
935          else
936          {
937             strncpy(path,dir+1,512);
938          }
939       }
940       else
941       {
942          strncpy(path,dir,512);
943       }
944       path[511]=0;
945    } else {
946       path[0]=0;
947    }
948    if(AddPart(path,file,512))
949    {
950       return strdup(path);
951    } else {
952       return NULL;
953    }
954 #else /* ndef AMIGA */
955
956    if ((file == NULL) || (*file == '\0'))
957    {
958       return NULL; /* Error */
959    }
960
961    if ((dir == NULL) || (*dir == '\0') /* No directory specified */
962 #if defined(_WIN32) || defined(__OS2__)
963       || (*file == '\\') || (file[1] == ':') /* Absolute path (DOS) */
964 #else /* ifndef _WIN32 || __OS2__ */
965       || (*file == '/') /* Absolute path (U*ix) */
966 #endif /* ifndef _WIN32 || __OS2__  */
967       )
968    {
969       return strdup(file);
970    }
971    else
972    {
973       char * path;
974
975 #if defined(unix)
976       if ( *dir != '/' && basedir && *basedir )
977       {
978          path = malloc( strlen( basedir ) + strlen(dir) + strlen(file) + 3);
979          if (!path ) log_error(LOG_LEVEL_FATAL, "malloc failed!");
980          strcpy(path, basedir);
981          strcat(path, "/");
982          strcat(path, dir);
983       }
984       else
985       {
986          path = malloc(strlen(dir) + strlen(file) + 2);
987          if (!path ) log_error(LOG_LEVEL_FATAL, "malloc failed!");
988          strcpy(path, dir);
989       }
990 #else
991
992       path = malloc(strlen(dir) + strlen(file) + 2);
993       if (!path ) log_error(LOG_LEVEL_FATAL, "malloc failed!");
994       strcpy(path, dir);
995
996 #endif /* defined unix */
997
998 #if defined(_WIN32) || defined(__OS2__)
999       if(path[strlen(path)-1] != '\\')
1000       {
1001          strcat(path, "\\");
1002       }
1003 #else /* ifndef _WIN32 || __OS2__ */
1004       if(path[strlen(path)-1] != '/')
1005       {
1006          strcat(path, "/");
1007       }
1008 #endif /* ifndef _WIN32 || __OS2__ */
1009       strcat(path, file);
1010
1011       return path;
1012    }
1013 #endif /* ndef AMIGA */
1014 }
1015
1016
1017 /*
1018  * What follows is a portable snprintf routine, written by Mark Martinec.
1019  * See: http://www.ijs.si/software/snprintf/
1020  * Anyone who needs it can add a define for themselves... so far, only 
1021  * OS/2 (native) lacks snprintf.
1022
1023                                   snprintf.c
1024                    - a portable implementation of snprintf,
1025        including vsnprintf.c, asnprintf, vasnprintf, asprintf, vasprintf
1026                                        
1027    snprintf is a routine to convert numeric and string arguments to
1028    formatted strings. It is similar to sprintf(3) provided in a system's
1029    C library, yet it requires an additional argument - the buffer size -
1030    and it guarantees never to store anything beyond the given buffer,
1031    regardless of the format or arguments to be formatted. Some newer
1032    operating systems do provide snprintf in their C library, but many do
1033    not or do provide an inadequate (slow or idiosyncratic) version, which
1034    calls for a portable implementation of this routine.
1035
1036 Author
1037
1038    Mark Martinec <mark.martinec@ijs.si>, April 1999, June 2000
1039    Copyright Â© 1999, Mark Martinec
1040
1041  */
1042
1043 #ifdef __OS2__
1044
1045 #define PORTABLE_SNPRINTF_VERSION_MAJOR 2
1046 #define PORTABLE_SNPRINTF_VERSION_MINOR 2
1047
1048 #if defined(NEED_ASPRINTF) || defined(NEED_ASNPRINTF) || defined(NEED_VASPRINTF) || defined(NEED_VASNPRINTF)
1049 # if defined(NEED_SNPRINTF_ONLY)
1050 # undef NEED_SNPRINTF_ONLY
1051 # endif
1052 # if !defined(PREFER_PORTABLE_SNPRINTF)
1053 # define PREFER_PORTABLE_SNPRINTF
1054 # endif
1055 #endif
1056
1057 #if defined(SOLARIS_BUG_COMPATIBLE) && !defined(SOLARIS_COMPATIBLE)
1058 #define SOLARIS_COMPATIBLE
1059 #endif
1060
1061 #if defined(HPUX_BUG_COMPATIBLE) && !defined(HPUX_COMPATIBLE)
1062 #define HPUX_COMPATIBLE
1063 #endif
1064
1065 #if defined(DIGITAL_UNIX_BUG_COMPATIBLE) && !defined(DIGITAL_UNIX_COMPATIBLE)
1066 #define DIGITAL_UNIX_COMPATIBLE
1067 #endif
1068
1069 #if defined(PERL_BUG_COMPATIBLE) && !defined(PERL_COMPATIBLE)
1070 #define PERL_COMPATIBLE
1071 #endif
1072
1073 #if defined(LINUX_BUG_COMPATIBLE) && !defined(LINUX_COMPATIBLE)
1074 #define LINUX_COMPATIBLE
1075 #endif
1076
1077 #include <sys/types.h>
1078 #include <string.h>
1079 #include <stdlib.h>
1080 #include <stdio.h>
1081 #include <stdarg.h>
1082 #include <assert.h>
1083 #include <errno.h>
1084
1085 #ifdef isdigit
1086 #undef isdigit
1087 #endif
1088 #define isdigit(c) ((c) >= '0' && (c) <= '9')
1089
1090 /* For copying strings longer or equal to 'breakeven_point'
1091  * it is more efficient to call memcpy() than to do it inline.
1092  * The value depends mostly on the processor architecture,
1093  * but also on the compiler and its optimization capabilities.
1094  * The value is not critical, some small value greater than zero
1095  * will be just fine if you don't care to squeeze every drop
1096  * of performance out of the code.
1097  *
1098  * Small values favor memcpy, large values favor inline code.
1099  */
1100 #if defined(__alpha__) || defined(__alpha)
1101 #  define breakeven_point   2    /* AXP (DEC Alpha)     - gcc or cc or egcs */
1102 #endif
1103 #if defined(__i386__)  || defined(__i386)
1104 #  define breakeven_point  12    /* Intel Pentium/Linux - gcc 2.96 */
1105 #endif
1106 #if defined(__hppa)
1107 #  define breakeven_point  10    /* HP-PA               - gcc */
1108 #endif
1109 #if defined(__sparc__) || defined(__sparc)
1110 #  define breakeven_point  33    /* Sun Sparc 5         - gcc 2.8.1 */
1111 #endif
1112
1113 /* some other values of possible interest: */
1114 /* #define breakeven_point  8 */ /* VAX 4000          - vaxc */
1115 /* #define breakeven_point 19 */ /* VAX 4000          - gcc 2.7.0 */
1116
1117 #ifndef breakeven_point
1118 #  define breakeven_point   6    /* some reasonable one-size-fits-all value */
1119 #endif
1120
1121 #define fast_memcpy(d,s,n) \
1122   { register size_t nn = (size_t)(n); \
1123     if (nn >= breakeven_point) memcpy((d), (s), nn); \
1124     else if (nn > 0) { /* proc call overhead is worth only for large strings*/\
1125       register char *dd; register const char *ss; \
1126       for (ss=(s), dd=(d); nn>0; nn--) *dd++ = *ss++; } }
1127
1128 #define fast_memset(d,c,n) \
1129   { register size_t nn = (size_t)(n); \
1130     if (nn >= breakeven_point) memset((d), (int)(c), nn); \
1131     else if (nn > 0) { /* proc call overhead is worth only for large strings*/\
1132       register char *dd; register const int cc=(int)(c); \
1133       for (dd=(d); nn>0; nn--) *dd++ = cc; } }
1134
1135 /* prototypes */
1136
1137 #if defined(NEED_ASPRINTF)
1138 int asprintf   (char **ptr, const char *fmt, /*args*/ ...);
1139 #endif
1140 #if defined(NEED_VASPRINTF)
1141 int vasprintf  (char **ptr, const char *fmt, va_list ap);
1142 #endif
1143 #if defined(NEED_ASNPRINTF)
1144 int asnprintf  (char **ptr, size_t str_m, const char *fmt, /*args*/ ...);
1145 #endif
1146 #if defined(NEED_VASNPRINTF)
1147 int vasnprintf (char **ptr, size_t str_m, const char *fmt, va_list ap);
1148 #endif
1149
1150 #if defined(HAVE_SNPRINTF)
1151 /* declare our portable snprintf  routine under name portable_snprintf  */
1152 /* declare our portable vsnprintf routine under name portable_vsnprintf */
1153 #else
1154 /* declare our portable routines under names snprintf and vsnprintf */
1155 #define portable_snprintf snprintf
1156 #if !defined(NEED_SNPRINTF_ONLY)
1157 #define portable_vsnprintf vsnprintf
1158 #endif
1159 #endif
1160
1161 #if !defined(HAVE_SNPRINTF) || defined(PREFER_PORTABLE_SNPRINTF)
1162 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...);
1163 #if !defined(NEED_SNPRINTF_ONLY)
1164 int portable_vsnprintf(char *str, size_t str_m, const char *fmt, va_list ap);
1165 #endif
1166 #endif
1167
1168 /* declarations */
1169
1170 static char credits[] = "\n\
1171 @(#)snprintf.c, v2.2: Mark Martinec, <mark.martinec@ijs.si>\n\
1172 @(#)snprintf.c, v2.2: Copyright 1999, Mark Martinec. Frontier Artistic License applies.\n\
1173 @(#)snprintf.c, v2.2: http://www.ijs.si/software/snprintf/\n";
1174
1175 #if defined(NEED_ASPRINTF)
1176 int asprintf(char **ptr, const char *fmt, /*args*/ ...) {
1177   va_list ap;
1178   size_t str_m;
1179   int str_l;
1180
1181   *ptr = NULL;
1182   va_start(ap, fmt);                            /* measure the required size */
1183   str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap);
1184   va_end(ap);
1185   assert(str_l >= 0);        /* possible integer overflow if str_m > INT_MAX */
1186   *ptr = (char *) malloc(str_m = (size_t)str_l + 1);
1187   if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1188   else {
1189     int str_l2;
1190     va_start(ap, fmt);
1191     str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1192     va_end(ap);
1193     assert(str_l2 == str_l);
1194   }
1195   return str_l;
1196 }
1197 #endif
1198
1199 #if defined(NEED_VASPRINTF)
1200 int vasprintf(char **ptr, const char *fmt, va_list ap) {
1201   size_t str_m;
1202   int str_l;
1203
1204   *ptr = NULL;
1205   { va_list ap2;
1206     va_copy(ap2, ap);  /* don't consume the original ap, we'll need it again */
1207     str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap2);/*get required size*/
1208     va_end(ap2);
1209   }
1210   assert(str_l >= 0);        /* possible integer overflow if str_m > INT_MAX */
1211   *ptr = (char *) malloc(str_m = (size_t)str_l + 1);
1212   if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1213   else {
1214     int str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1215     assert(str_l2 == str_l);
1216   }
1217   return str_l;
1218 }
1219 #endif
1220
1221 #if defined(NEED_ASNPRINTF)
1222 int asnprintf (char **ptr, size_t str_m, const char *fmt, /*args*/ ...) {
1223   va_list ap;
1224   int str_l;
1225
1226   *ptr = NULL;
1227   va_start(ap, fmt);                            /* measure the required size */
1228   str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap);
1229   va_end(ap);
1230   assert(str_l >= 0);        /* possible integer overflow if str_m > INT_MAX */
1231   if ((size_t)str_l + 1 < str_m) str_m = (size_t)str_l + 1;      /* truncate */
1232   /* if str_m is 0, no buffer is allocated, just set *ptr to NULL */
1233   if (str_m == 0) {  /* not interested in resulting string, just return size */
1234   } else {
1235     *ptr = (char *) malloc(str_m);
1236     if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1237     else {
1238       int str_l2;
1239       va_start(ap, fmt);
1240       str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1241       va_end(ap);
1242       assert(str_l2 == str_l);
1243     }
1244   }
1245   return str_l;
1246 }
1247 #endif
1248
1249 #if defined(NEED_VASNPRINTF)
1250 int vasnprintf (char **ptr, size_t str_m, const char *fmt, va_list ap) {
1251   int str_l;
1252
1253   *ptr = NULL;
1254   { va_list ap2;
1255     va_copy(ap2, ap);  /* don't consume the original ap, we'll need it again */
1256     str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap2);/*get required size*/
1257     va_end(ap2);
1258   }
1259   assert(str_l >= 0);        /* possible integer overflow if str_m > INT_MAX */
1260   if ((size_t)str_l + 1 < str_m) str_m = (size_t)str_l + 1;      /* truncate */
1261   /* if str_m is 0, no buffer is allocated, just set *ptr to NULL */
1262   if (str_m == 0) {  /* not interested in resulting string, just return size */
1263   } else {
1264     *ptr = (char *) malloc(str_m);
1265     if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1266     else {
1267       int str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1268       assert(str_l2 == str_l);
1269     }
1270   }
1271   return str_l;
1272 }
1273 #endif
1274
1275 /*
1276  * If the system does have snprintf and the portable routine is not
1277  * specifically required, this module produces no code for snprintf/vsnprintf.
1278  */
1279 #if !defined(HAVE_SNPRINTF) || defined(PREFER_PORTABLE_SNPRINTF)
1280
1281 #if !defined(NEED_SNPRINTF_ONLY)
1282 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...) {
1283   va_list ap;
1284   int str_l;
1285
1286   va_start(ap, fmt);
1287   str_l = portable_vsnprintf(str, str_m, fmt, ap);
1288   va_end(ap);
1289   return str_l;
1290 }
1291 #endif
1292
1293 #if defined(NEED_SNPRINTF_ONLY)
1294 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...) {
1295 #else
1296 int portable_vsnprintf(char *str, size_t str_m, const char *fmt, va_list ap) {
1297 #endif
1298
1299 #if defined(NEED_SNPRINTF_ONLY)
1300   va_list ap;
1301 #endif
1302   size_t str_l = 0;
1303   const char *p = fmt;
1304
1305 /* In contrast with POSIX, the ISO C99 now says
1306  * that str can be NULL and str_m can be 0.
1307  * This is more useful than the old:  if (str_m < 1) return -1; */
1308
1309 #if defined(NEED_SNPRINTF_ONLY)
1310   va_start(ap, fmt);
1311 #endif
1312   if (!p) p = "";
1313   while (*p) {
1314     if (*p != '%') {
1315    /* if (str_l < str_m) str[str_l++] = *p++;    -- this would be sufficient */
1316    /* but the following code achieves better performance for cases
1317     * where format string is long and contains few conversions */
1318       const char *q = strchr(p+1,'%');
1319       size_t n = !q ? strlen(p) : (q-p);
1320       if (str_l < str_m) {
1321         size_t avail = str_m-str_l;
1322         fast_memcpy(str+str_l, p, (n>avail?avail:n));
1323       }
1324       p += n; str_l += n;
1325     } else {
1326       const char *starting_p;
1327       size_t min_field_width = 0, precision = 0;
1328       int zero_padding = 0, precision_specified = 0, justify_left = 0;
1329       int alternate_form = 0, force_sign = 0;
1330       int space_for_positive = 1; /* If both the ' ' and '+' flags appear,
1331                                      the ' ' flag should be ignored. */
1332       char length_modifier = '\0';            /* allowed values: \0, h, l, L */
1333       char tmp[32];/* temporary buffer for simple numeric->string conversion */
1334
1335       const char *str_arg;      /* string address in case of string argument */
1336       size_t str_arg_l;         /* natural field width of arg without padding
1337                                    and sign */
1338       unsigned char uchar_arg;
1339         /* unsigned char argument value - only defined for c conversion.
1340            N.B. standard explicitly states the char argument for
1341            the c conversion is unsigned */
1342
1343       size_t number_of_zeros_to_pad = 0;
1344         /* number of zeros to be inserted for numeric conversions
1345            as required by the precision or minimal field width */
1346
1347       size_t zero_padding_insertion_ind = 0;
1348         /* index into tmp where zero padding is to be inserted */
1349
1350       char fmt_spec = '\0';
1351         /* current conversion specifier character */
1352
1353       str_arg = credits;/* just to make compiler happy (defined but not used)*/
1354       str_arg = NULL;
1355       starting_p = p; p++;  /* skip '%' */
1356    /* parse flags */
1357       while (*p == '0' || *p == '-' || *p == '+' ||
1358              *p == ' ' || *p == '#' || *p == '\'') {
1359         switch (*p) {
1360         case '0': zero_padding = 1; break;
1361         case '-': justify_left = 1; break;
1362         case '+': force_sign = 1; space_for_positive = 0; break;
1363         case ' ': force_sign = 1;
1364      /* If both the ' ' and '+' flags appear, the ' ' flag should be ignored */
1365 #ifdef PERL_COMPATIBLE
1366      /* ... but in Perl the last of ' ' and '+' applies */
1367                   space_for_positive = 1;
1368 #endif
1369                   break;
1370         case '#': alternate_form = 1; break;
1371         case '\'': break;
1372         }
1373         p++;
1374       }
1375    /* If the '0' and '-' flags both appear, the '0' flag should be ignored. */
1376
1377    /* parse field width */
1378       if (*p == '*') {
1379         int j;
1380         p++; j = va_arg(ap, int);
1381         if (j >= 0) min_field_width = j;
1382         else { min_field_width = -j; justify_left = 1; }
1383       } else if (isdigit((int)(*p))) {
1384         /* size_t could be wider than unsigned int;
1385            make sure we treat argument like common implementations do */
1386         unsigned int uj = *p++ - '0';
1387         while (isdigit((int)(*p))) uj = 10*uj + (unsigned int)(*p++ - '0');
1388         min_field_width = uj;
1389       }
1390    /* parse precision */
1391       if (*p == '.') {
1392         p++; precision_specified = 1;
1393         if (*p == '*') {
1394           int j = va_arg(ap, int);
1395           p++;
1396           if (j >= 0) precision = j;
1397           else {
1398             precision_specified = 0; precision = 0;
1399          /* NOTE:
1400           *   Solaris 2.6 man page claims that in this case the precision
1401           *   should be set to 0.  Digital Unix 4.0, HPUX 10 and BSD man page
1402           *   claim that this case should be treated as unspecified precision,
1403           *   which is what we do here.
1404           */
1405           }
1406         } else if (isdigit((int)(*p))) {
1407           /* size_t could be wider than unsigned int;
1408              make sure we treat argument like common implementations do */
1409           unsigned int uj = *p++ - '0';
1410           while (isdigit((int)(*p))) uj = 10*uj + (unsigned int)(*p++ - '0');
1411           precision = uj;
1412         }
1413       }
1414    /* parse 'h', 'l' and 'll' length modifiers */
1415       if (*p == 'h' || *p == 'l') {
1416         length_modifier = *p; p++;
1417         if (length_modifier == 'l' && *p == 'l') {   /* double l = long long */
1418 #ifdef SNPRINTF_LONGLONG_SUPPORT
1419           length_modifier = '2';                  /* double l encoded as '2' */
1420 #else
1421           length_modifier = 'l';                 /* treat it as a single 'l' */
1422 #endif
1423           p++;
1424         }
1425       }
1426       fmt_spec = *p;
1427    /* common synonyms: */
1428       switch (fmt_spec) {
1429       case 'i': fmt_spec = 'd'; break;
1430       case 'D': fmt_spec = 'd'; length_modifier = 'l'; break;
1431       case 'U': fmt_spec = 'u'; length_modifier = 'l'; break;
1432       case 'O': fmt_spec = 'o'; length_modifier = 'l'; break;
1433       default: break;
1434       }
1435    /* get parameter value, do initial processing */
1436       switch (fmt_spec) {
1437       case '%': /* % behaves similar to 's' regarding flags and field widths */
1438       case 'c': /* c behaves similar to 's' regarding flags and field widths */
1439       case 's':
1440         length_modifier = '\0';          /* wint_t and wchar_t not supported */
1441      /* the result of zero padding flag with non-numeric conversion specifier*/
1442      /* is undefined. Solaris and HPUX 10 does zero padding in this case,    */
1443      /* Digital Unix and Linux does not. */
1444 #if !defined(SOLARIS_COMPATIBLE) && !defined(HPUX_COMPATIBLE)
1445         zero_padding = 0;    /* turn zero padding off for string conversions */
1446 #endif
1447         str_arg_l = 1;
1448         switch (fmt_spec) {
1449         case '%':
1450           str_arg = p; break;
1451         case 'c': {
1452           int j = va_arg(ap, int);
1453           uchar_arg = (unsigned char) j;   /* standard demands unsigned char */
1454           str_arg = (const char *) &uchar_arg;
1455           break;
1456         }
1457         case 's':
1458           str_arg = va_arg(ap, const char *);
1459           if (!str_arg) str_arg_l = 0;
1460        /* make sure not to address string beyond the specified precision !!! */
1461           else if (!precision_specified) str_arg_l = strlen(str_arg);
1462        /* truncate string if necessary as requested by precision */
1463           else if (precision == 0) str_arg_l = 0;
1464           else {
1465        /* memchr on HP does not like n > 2^31  !!! */
1466             const char *q = memchr(str_arg, '\0',
1467                              precision <= 0x7fffffff ? precision : 0x7fffffff);
1468             str_arg_l = !q ? precision : (q-str_arg);
1469           }
1470           break;
1471         default: break;
1472         }
1473         break;
1474       case 'd': case 'u': case 'o': case 'x': case 'X': case 'p': {
1475         /* NOTE: the u, o, x, X and p conversion specifiers imply
1476                  the value is unsigned;  d implies a signed value */
1477
1478         int arg_sign = 0;
1479           /* 0 if numeric argument is zero (or if pointer is NULL for 'p'),
1480             +1 if greater than zero (or nonzero for unsigned arguments),
1481             -1 if negative (unsigned argument is never negative) */
1482
1483         int int_arg = 0;  unsigned int uint_arg = 0;
1484           /* only defined for length modifier h, or for no length modifiers */
1485
1486         long int long_arg = 0;  unsigned long int ulong_arg = 0;
1487           /* only defined for length modifier l */
1488
1489         void *ptr_arg = NULL;
1490           /* pointer argument value -only defined for p conversion */
1491
1492 #ifdef SNPRINTF_LONGLONG_SUPPORT
1493         long long int long_long_arg = 0;
1494         unsigned long long int ulong_long_arg = 0;
1495           /* only defined for length modifier ll */
1496 #endif
1497         if (fmt_spec == 'p') {
1498         /* HPUX 10: An l, h, ll or L before any other conversion character
1499          *   (other than d, i, u, o, x, or X) is ignored.
1500          * Digital Unix:
1501          *   not specified, but seems to behave as HPUX does.
1502          * Solaris: If an h, l, or L appears before any other conversion
1503          *   specifier (other than d, i, u, o, x, or X), the behavior
1504          *   is undefined. (Actually %hp converts only 16-bits of address
1505          *   and %llp treats address as 64-bit data which is incompatible
1506          *   with (void *) argument on a 32-bit system).
1507          */
1508 #ifdef SOLARIS_COMPATIBLE
1509 #  ifdef SOLARIS_BUG_COMPATIBLE
1510           /* keep length modifiers even if it represents 'll' */
1511 #  else
1512           if (length_modifier == '2') length_modifier = '\0';
1513 #  endif
1514 #else
1515           length_modifier = '\0';
1516 #endif
1517           ptr_arg = va_arg(ap, void *);
1518           if (ptr_arg != NULL) arg_sign = 1;
1519         } else if (fmt_spec == 'd') {  /* signed */
1520           switch (length_modifier) {
1521           case '\0':
1522           case 'h':
1523          /* It is non-portable to specify a second argument of char or short
1524           * to va_arg, because arguments seen by the called function
1525           * are not char or short.  C converts char and short arguments
1526           * to int before passing them to a function.
1527           */
1528             int_arg = va_arg(ap, int);
1529             if      (int_arg > 0) arg_sign =  1;
1530             else if (int_arg < 0) arg_sign = -1;
1531             break;
1532           case 'l':
1533             long_arg = va_arg(ap, long int);
1534             if      (long_arg > 0) arg_sign =  1;
1535             else if (long_arg < 0) arg_sign = -1;
1536             break;
1537 #ifdef SNPRINTF_LONGLONG_SUPPORT
1538           case '2':
1539             long_long_arg = va_arg(ap, long long int);
1540             if      (long_long_arg > 0) arg_sign =  1;
1541             else if (long_long_arg < 0) arg_sign = -1;
1542             break;
1543 #endif
1544           }
1545         } else {  /* unsigned */
1546           switch (length_modifier) {
1547           case '\0':
1548           case 'h':
1549             uint_arg = va_arg(ap, unsigned int);
1550             if (uint_arg) arg_sign = 1;
1551             break;
1552           case 'l':
1553             ulong_arg = va_arg(ap, unsigned long int);
1554             if (ulong_arg) arg_sign = 1;
1555             break;
1556 #ifdef SNPRINTF_LONGLONG_SUPPORT
1557           case '2':
1558             ulong_long_arg = va_arg(ap, unsigned long long int);
1559             if (ulong_long_arg) arg_sign = 1;
1560             break;
1561 #endif
1562           }
1563         }
1564         str_arg = tmp; str_arg_l = 0;
1565      /* NOTE:
1566       *   For d, i, u, o, x, and X conversions, if precision is specified,
1567       *   the '0' flag should be ignored. This is so with Solaris 2.6,
1568       *   Digital UNIX 4.0, HPUX 10, Linux, FreeBSD, NetBSD; but not with Perl.
1569       */
1570 #ifndef PERL_COMPATIBLE
1571         if (precision_specified) zero_padding = 0;
1572 #endif
1573         if (fmt_spec == 'd') {
1574           if (force_sign && arg_sign >= 0)
1575             tmp[str_arg_l++] = space_for_positive ? ' ' : '+';
1576          /* leave negative numbers for sprintf to handle,
1577             to avoid handling tricky cases like (short int)(-32768) */
1578 #ifdef LINUX_COMPATIBLE
1579         } else if (fmt_spec == 'p' && force_sign && arg_sign > 0) {
1580           tmp[str_arg_l++] = space_for_positive ? ' ' : '+';
1581 #endif
1582         } else if (alternate_form) {
1583           if (arg_sign != 0 && (fmt_spec == 'x' || fmt_spec == 'X') )
1584             { tmp[str_arg_l++] = '0'; tmp[str_arg_l++] = fmt_spec; }
1585          /* alternate form should have no effect for p conversion, but ... */
1586 #ifdef HPUX_COMPATIBLE
1587           else if (fmt_spec == 'p'
1588          /* HPUX 10: for an alternate form of p conversion,
1589           *          a nonzero result is prefixed by 0x. */
1590 #ifndef HPUX_BUG_COMPATIBLE
1591          /* Actually it uses 0x prefix even for a zero value. */
1592                    && arg_sign != 0
1593 #endif
1594                   ) { tmp[str_arg_l++] = '0'; tmp[str_arg_l++] = 'x'; }
1595 #endif
1596         }
1597         zero_padding_insertion_ind = str_arg_l;
1598         if (!precision_specified) precision = 1;   /* default precision is 1 */
1599         if (precision == 0 && arg_sign == 0
1600 #if defined(HPUX_BUG_COMPATIBLE) || defined(LINUX_COMPATIBLE)
1601             && fmt_spec != 'p'
1602          /* HPUX 10 man page claims: With conversion character p the result of
1603           * converting a zero value with a precision of zero is a null string.
1604           * Actually HP returns all zeroes, and Linux returns "(nil)". */
1605 #endif
1606         ) {
1607          /* converted to null string */
1608          /* When zero value is formatted with an explicit precision 0,
1609             the resulting formatted string is empty (d, i, u, o, x, X, p).   */
1610         } else {
1611           char f[5]; int f_l = 0;
1612           f[f_l++] = '%';    /* construct a simple format string for sprintf */
1613           if (!length_modifier) { }
1614           else if (length_modifier=='2') { f[f_l++] = 'l'; f[f_l++] = 'l'; }
1615           else f[f_l++] = length_modifier;
1616           f[f_l++] = fmt_spec; f[f_l++] = '\0';
1617           if (fmt_spec == 'p') str_arg_l += sprintf(tmp+str_arg_l, f, ptr_arg);
1618           else if (fmt_spec == 'd') {  /* signed */
1619             switch (length_modifier) {
1620             case '\0':
1621             case 'h': str_arg_l+=sprintf(tmp+str_arg_l, f, int_arg);  break;
1622             case 'l': str_arg_l+=sprintf(tmp+str_arg_l, f, long_arg); break;
1623 #ifdef SNPRINTF_LONGLONG_SUPPORT
1624             case '2': str_arg_l+=sprintf(tmp+str_arg_l,f,long_long_arg); break;
1625 #endif
1626             }
1627           } else {  /* unsigned */
1628             switch (length_modifier) {
1629             case '\0':
1630             case 'h': str_arg_l+=sprintf(tmp+str_arg_l, f, uint_arg);  break;
1631             case 'l': str_arg_l+=sprintf(tmp+str_arg_l, f, ulong_arg); break;
1632 #ifdef SNPRINTF_LONGLONG_SUPPORT
1633             case '2': str_arg_l+=sprintf(tmp+str_arg_l,f,ulong_long_arg);break;
1634 #endif
1635             }
1636           }
1637          /* include the optional minus sign and possible "0x"
1638             in the region before the zero padding insertion point */
1639           if (zero_padding_insertion_ind < str_arg_l &&
1640               tmp[zero_padding_insertion_ind] == '-') {
1641             zero_padding_insertion_ind++;
1642           }
1643           if (zero_padding_insertion_ind+1 < str_arg_l &&
1644               tmp[zero_padding_insertion_ind]   == '0' &&
1645              (tmp[zero_padding_insertion_ind+1] == 'x' ||
1646               tmp[zero_padding_insertion_ind+1] == 'X') ) {
1647             zero_padding_insertion_ind += 2;
1648           }
1649         }
1650         { size_t num_of_digits = str_arg_l - zero_padding_insertion_ind;
1651           if (alternate_form && fmt_spec == 'o'
1652 #ifdef HPUX_COMPATIBLE                                  /* ("%#.o",0) -> ""  */
1653               && (str_arg_l > 0)
1654 #endif
1655 #ifdef DIGITAL_UNIX_BUG_COMPATIBLE                      /* ("%#o",0) -> "00" */
1656 #else
1657               /* unless zero is already the first character */
1658               && !(zero_padding_insertion_ind < str_arg_l
1659                    && tmp[zero_padding_insertion_ind] == '0')
1660 #endif
1661           ) {        /* assure leading zero for alternate-form octal numbers */
1662             if (!precision_specified || precision < num_of_digits+1) {
1663              /* precision is increased to force the first character to be zero,
1664                 except if a zero value is formatted with an explicit precision
1665                 of zero */
1666               precision = num_of_digits+1; precision_specified = 1;
1667             }
1668           }
1669        /* zero padding to specified precision? */
1670           if (num_of_digits < precision) 
1671             number_of_zeros_to_pad = precision - num_of_digits;
1672         }
1673      /* zero padding to specified minimal field width? */
1674         if (!justify_left && zero_padding) {
1675           int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
1676           if (n > 0) number_of_zeros_to_pad += n;
1677         }
1678         break;
1679       }
1680       default: /* unrecognized conversion specifier, keep format string as-is*/
1681         zero_padding = 0;  /* turn zero padding off for non-numeric convers. */
1682 #ifndef DIGITAL_UNIX_COMPATIBLE
1683         justify_left = 1; min_field_width = 0;                /* reset flags */
1684 #endif
1685 #if defined(PERL_COMPATIBLE) || defined(LINUX_COMPATIBLE)
1686      /* keep the entire format string unchanged */
1687         str_arg = starting_p; str_arg_l = p - starting_p;
1688      /* well, not exactly so for Linux, which does something inbetween,
1689       * and I don't feel an urge to imitate it: "%+++++hy" -> "%+y"  */
1690 #else
1691      /* discard the unrecognized conversion, just keep *
1692       * the unrecognized conversion character          */
1693         str_arg = p; str_arg_l = 0;
1694 #endif
1695         if (*p) str_arg_l++;  /* include invalid conversion specifier unchanged
1696                                  if not at end-of-string */
1697         break;
1698       }
1699       if (*p) p++;      /* step over the just processed conversion specifier */
1700    /* insert padding to the left as requested by min_field_width;
1701       this does not include the zero padding in case of numerical conversions*/
1702       if (!justify_left) {                /* left padding with blank or zero */
1703         int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
1704         if (n > 0) {
1705           if (str_l < str_m) {
1706             size_t avail = str_m-str_l;
1707             fast_memset(str+str_l, (zero_padding?'0':' '), (n>avail?avail:n));
1708           }
1709           str_l += n;
1710         }
1711       }
1712    /* zero padding as requested by the precision or by the minimal field width
1713     * for numeric conversions required? */
1714       if (number_of_zeros_to_pad <= 0) {
1715      /* will not copy first part of numeric right now, *
1716       * force it to be copied later in its entirety    */
1717         zero_padding_insertion_ind = 0;
1718       } else {
1719      /* insert first part of numerics (sign or '0x') before zero padding */
1720         int n = zero_padding_insertion_ind;
1721         if (n > 0) {
1722           if (str_l < str_m) {
1723             size_t avail = str_m-str_l;
1724             fast_memcpy(str+str_l, str_arg, (n>avail?avail:n));
1725           }
1726           str_l += n;
1727         }
1728      /* insert zero padding as requested by the precision or min field width */
1729         n = number_of_zeros_to_pad;
1730         if (n > 0) {
1731           if (str_l < str_m) {
1732             size_t avail = str_m-str_l;
1733             fast_memset(str+str_l, '0', (n>avail?avail:n));
1734           }
1735           str_l += n;
1736         }
1737       }
1738    /* insert formatted string
1739     * (or as-is conversion specifier for unknown conversions) */
1740       { int n = str_arg_l - zero_padding_insertion_ind;
1741         if (n > 0) {
1742           if (str_l < str_m) {
1743             size_t avail = str_m-str_l;
1744             fast_memcpy(str+str_l, str_arg+zero_padding_insertion_ind,
1745                         (n>avail?avail:n));
1746           }
1747           str_l += n;
1748         }
1749       }
1750    /* insert right padding */
1751       if (justify_left) {          /* right blank padding to the field width */
1752         int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
1753         if (n > 0) {
1754           if (str_l < str_m) {
1755             size_t avail = str_m-str_l;
1756             fast_memset(str+str_l, ' ', (n>avail?avail:n));
1757           }
1758           str_l += n;
1759         }
1760       }
1761     }
1762   }
1763 #if defined(NEED_SNPRINTF_ONLY)
1764   va_end(ap);
1765 #endif
1766   if (str_m > 0) { /* make sure the string is null-terminated
1767                       even at the expense of overwriting the last character
1768                       (shouldn't happen, but just in case) */
1769     str[str_l <= str_m-1 ? str_l : str_m-1] = '\0';
1770   }
1771   /* Return the number of characters formatted (excluding trailing null
1772    * character), that is, the number of characters that would have been
1773    * written to the buffer if it were large enough.
1774    *
1775    * The value of str_l should be returned, but str_l is of unsigned type
1776    * size_t, and snprintf is int, possibly leading to an undetected
1777    * integer overflow, resulting in a negative return value, which is illegal.
1778    * Both XSH5 and ISO C99 (at least the draft) are silent on this issue.
1779    * Should errno be set to EOVERFLOW and EOF returned in this case???
1780    */
1781   return (int) str_l;
1782 }
1783 #endif
1784 #endif /* __OS2__ */
1785 /*
1786   Local Variables:
1787   tab-width: 3
1788   end:
1789 */