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