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