Properly deal with Keep-Alive headers with timeout= parameters
[privoxy.git] / miscutil.c
1 const char miscutil_rcs[] = "$Id: miscutil.c,v 1.77 2012/07/23 12:41:59 fabiankeil Exp $";
2 /*********************************************************************
3  *
4  * File        :  $Source: /cvsroot/ijbswa/current/miscutil.c,v $
5  *
6  * Purpose     :  zalloc, hash_string, strcmpic, strncmpic, and
7  *                MinGW32 strdup functions.  These are each too small
8  *                to deserve their own file but don't really fit in
9  *                any other file.
10  *
11  * Copyright   :  Written by and Copyright (C) 2001-2012 the
12  *                Privoxy team. http://www.privoxy.org/
13  *
14  *                Based on the Internet Junkbuster originally written
15  *                by and Copyright (C) 1997 Anonymous Coders and
16  *                Junkbusters Corporation.  http://www.junkbusters.com
17  *
18  *                The timegm replacement function was taken from GnuPG,
19  *                Copyright (C) 2004 Free Software Foundation, Inc.
20  *
21  *                The snprintf replacement function is written by
22  *                Mark Martinec who also holds the copyright. It can be
23  *                used under the terms of the GPL or the terms of the
24  *                "Frontier Artistic License".
25  *
26  *                This program is free software; you can redistribute it
27  *                and/or modify it under the terms of the GNU General
28  *                Public License as published by the Free Software
29  *                Foundation; either version 2 of the License, or (at
30  *                your option) any later version.
31  *
32  *                This program is distributed in the hope that it will
33  *                be useful, but WITHOUT ANY WARRANTY; without even the
34  *                implied warranty of MERCHANTABILITY or FITNESS FOR A
35  *                PARTICULAR PURPOSE.  See the GNU General Public
36  *                License for more details.
37  *
38  *                The GNU General Public License should be included with
39  *                this file.  If not, you can view it at
40  *                http://www.gnu.org/copyleft/gpl.html
41  *                or write to the Free Software Foundation, Inc., 59
42  *                Temple Place - Suite 330, Boston, MA  02111-1307, USA.
43  *
44  *********************************************************************/
45
46
47 #include "config.h"
48
49 #include <stdio.h>
50 #include <sys/types.h>
51 #include <stdlib.h>
52 #if !defined(_WIN32) && !defined(__OS2__)
53 #include <unistd.h>
54 #endif /* #if !defined(_WIN32) && !defined(__OS2__) */
55 #include <string.h>
56 #include <ctype.h>
57 #include <assert.h>
58
59 #if !defined(HAVE_TIMEGM) && defined(HAVE_TZSET) && defined(HAVE_PUTENV)
60 #include <time.h>
61 #endif /* !defined(HAVE_TIMEGM) && defined(HAVE_TZSET) && defined(HAVE_PUTENV) */
62
63 #include "project.h"
64 #include "miscutil.h"
65 #include "errlog.h"
66 #include "jcc.h"
67
68 const char miscutil_h_rcs[] = MISCUTIL_H_VERSION;
69
70 /*********************************************************************
71  *
72  * Function    :  zalloc
73  *
74  * Description :  Malloc some memory and set it to '\0'.
75  *
76  * Parameters  :
77  *          1  :  size = Size of memory chunk to return.
78  *
79  * Returns     :  Pointer to newly malloc'd memory chunk.
80  *
81  *********************************************************************/
82 void *zalloc(size_t size)
83 {
84    void * ret;
85
86    if ((ret = (void *)malloc(size)) != NULL)
87    {
88       memset(ret, 0, size);
89    }
90
91    return(ret);
92
93 }
94
95
96 /*********************************************************************
97  *
98  * Function    :  strdup_or_die
99  *
100  * Description :  strdup wrapper that either succeeds or causes
101  *                program termination.
102  *
103  *                Useful in situations were the string length is
104  *                "small" and strdup() failures couldn't be handled
105  *                better anyway. In case of debug builds, failures
106  *                trigger an assert().
107  *
108  * Parameters  :
109  *          1  :  str = String to duplicate
110  *
111  * Returns     :  Pointer to newly strdup'd copy of the string.
112  *
113  *********************************************************************/
114 char *strdup_or_die(const char *str)
115 {
116    char *new_str;
117
118    new_str = strdup(str);
119
120    if (new_str == NULL)
121    {
122       assert(new_str != NULL);
123       log_error(LOG_LEVEL_FATAL, "Out of memory in strdup_or_die().");
124       exit(1);
125    }
126
127    return(new_str);
128
129 }
130
131
132 /*********************************************************************
133  *
134  * Function    :  malloc_or_die
135  *
136  * Description :  malloc wrapper that either succeeds or causes
137  *                program termination.
138  *
139  *                Useful in situations were the buffer size is "small"
140  *                and malloc() failures couldn't be handled better
141  *                anyway. In case of debug builds, failures trigger
142  *                an assert().
143  *
144  * Parameters  :
145  *          1  :  buffer_size = Size of the space to allocate
146  *
147  * Returns     :  Pointer to newly malloc'd memory
148  *
149  *********************************************************************/
150 void *malloc_or_die(size_t buffer_size)
151 {
152    char *new_buf;
153
154    new_buf = malloc(buffer_size);
155
156    if (new_buf == NULL)
157    {
158       assert(new_buf != NULL);
159       log_error(LOG_LEVEL_FATAL, "Out of memory in malloc_or_die().");
160       exit(1);
161    }
162
163    return(new_buf);
164
165 }
166
167
168 #if defined(unix)
169 /*********************************************************************
170  *
171  * Function    :  write_pid_file
172  *
173  * Description :  Writes a pid file with the pid of the main process
174  *
175  * Parameters  :  None
176  *
177  * Returns     :  N/A
178  *
179  *********************************************************************/
180 void write_pid_file(void)
181 {
182    FILE   *fp;
183
184    /*
185     * If no --pidfile option was given,
186     * we can live without one.
187     */
188    if (pidfile == NULL) return;
189
190    if ((fp = fopen(pidfile, "w")) == NULL)
191    {
192       log_error(LOG_LEVEL_INFO, "can't open pidfile '%s': %E", pidfile);
193    }
194    else
195    {
196       fprintf(fp, "%u\n", (unsigned int) getpid());
197       fclose (fp);
198    }
199    return;
200
201 }
202 #endif /* def unix */
203
204
205 /*********************************************************************
206  *
207  * Function    :  hash_string
208  *
209  * Description :  Take a string and compute a (hopefuly) unique numeric
210  *                integer value. This is useful to "switch" a string.
211  *
212  * Parameters  :
213  *          1  :  s : string to be hashed.
214  *
215  * Returns     :  The string's hash
216  *
217  *********************************************************************/
218 unsigned int hash_string(const char* s)
219 {
220    unsigned int h = 0;
221
222    for (; *s; ++s)
223    {
224       h = 5 * h + (unsigned int)*s;
225    }
226
227    return (h);
228
229 }
230
231
232 /*********************************************************************
233  *
234  * Function    :  strcmpic
235  *
236  * Description :  Case insensitive string comparison
237  *
238  * Parameters  :
239  *          1  :  s1 = string 1 to compare
240  *          2  :  s2 = string 2 to compare
241  *
242  * Returns     :  0 if s1==s2, Negative if s1<s2, Positive if s1>s2
243  *
244  *********************************************************************/
245 int strcmpic(const char *s1, const char *s2)
246 {
247    if (!s1) s1 = "";
248    if (!s2) s2 = "";
249
250    while (*s1 && *s2)
251    {
252       if ((*s1 != *s2) && (privoxy_tolower(*s1) != privoxy_tolower(*s2)))
253       {
254          break;
255       }
256       s1++, s2++;
257    }
258    return(privoxy_tolower(*s1) - privoxy_tolower(*s2));
259
260 }
261
262
263 /*********************************************************************
264  *
265  * Function    :  strncmpic
266  *
267  * Description :  Case insensitive string comparison (up to n characters)
268  *
269  * Parameters  :
270  *          1  :  s1 = string 1 to compare
271  *          2  :  s2 = string 2 to compare
272  *          3  :  n = maximum characters to compare
273  *
274  * Returns     :  0 if s1==s2, Negative if s1<s2, Positive if s1>s2
275  *
276  *********************************************************************/
277 int strncmpic(const char *s1, const char *s2, size_t n)
278 {
279    if (n <= (size_t)0) return(0);
280    if (!s1) s1 = "";
281    if (!s2) s2 = "";
282
283    while (*s1 && *s2)
284    {
285       if ((*s1 != *s2) && (privoxy_tolower(*s1) != privoxy_tolower(*s2)))
286       {
287          break;
288       }
289
290       if (--n <= (size_t)0) break;
291
292       s1++, s2++;
293    }
294    return(privoxy_tolower(*s1) - privoxy_tolower(*s2));
295
296 }
297
298
299 /*********************************************************************
300  *
301  * Function    :  chomp
302  *
303  * Description :  In-situ-eliminate all leading and trailing whitespace
304  *                from a string.
305  *
306  * Parameters  :
307  *          1  :  s : string to be chomped.
308  *
309  * Returns     :  chomped string
310  *
311  *********************************************************************/
312 char *chomp(char *string)
313 {
314    char *p, *q, *r;
315
316    /*
317     * strip trailing whitespace
318     */
319    p = string + strlen(string);
320    while (p > string && privoxy_isspace(*(p-1)))
321    {
322       p--;
323    }
324    *p = '\0';
325
326    /*
327     * find end of leading whitespace
328     */
329    q = r = string;
330    while (*q && privoxy_isspace(*q))
331    {
332       q++;
333    }
334
335    /*
336     * if there was any, move the rest forwards
337     */
338    if (q != string)
339    {
340       while (q <= p)
341       {
342          *r++ = *q++;
343       }
344    }
345
346    return(string);
347
348 }
349
350
351 /*********************************************************************
352  *
353  * Function    :  string_append
354  *
355  * Description :  Reallocate target_string and append text to it.
356  *                This makes it easier to append to malloc'd strings.
357  *                This is similar to the (removed) strsav(), but
358  *                running out of memory isn't catastrophic.
359  *
360  *                Programming style:
361  *
362  *                The following style provides sufficient error
363  *                checking for this routine, with minimal clutter
364  *                in the source code.  It is recommended if you
365  *                have many calls to this function:
366  *
367  *                char * s = strdup(...); // don't check for error
368  *                string_append(&s, ...);  // don't check for error
369  *                string_append(&s, ...);  // don't check for error
370  *                string_append(&s, ...);  // don't check for error
371  *                if (NULL == s) { ... handle error ... }
372  *
373  *                OR, equivalently:
374  *
375  *                char * s = strdup(...); // don't check for error
376  *                string_append(&s, ...);  // don't check for error
377  *                string_append(&s, ...);  // don't check for error
378  *                if (string_append(&s, ...)) {... handle error ...}
379  *
380  * Parameters  :
381  *          1  :  target_string = Pointer to old text that is to be
382  *                extended.  *target_string will be free()d by this
383  *                routine.  target_string must be non-NULL.
384  *                If *target_string is NULL, this routine will
385  *                do nothing and return with an error - this allows
386  *                you to make many calls to this routine and only
387  *                check for errors after the last one.
388  *          2  :  text_to_append = Text to be appended to old.
389  *                Must not be NULL.
390  *
391  * Returns     :  JB_ERR_OK on success, and sets *target_string
392  *                   to newly malloc'ed appended string.  Caller
393  *                   must free(*target_string).
394  *                JB_ERR_MEMORY on out-of-memory.  (And free()s
395  *                   *target_string and sets it to NULL).
396  *                JB_ERR_MEMORY if *target_string is NULL.
397  *
398  *********************************************************************/
399 jb_err string_append(char **target_string, const char *text_to_append)
400 {
401    size_t old_len;
402    char *new_string;
403    size_t new_size;
404
405    assert(target_string);
406    assert(text_to_append);
407
408    if (*target_string == NULL)
409    {
410       return JB_ERR_MEMORY;
411    }
412
413    if (*text_to_append == '\0')
414    {
415       return JB_ERR_OK;
416    }
417
418    old_len = strlen(*target_string);
419
420    new_size = strlen(text_to_append) + old_len + 1;
421
422    if (NULL == (new_string = realloc(*target_string, new_size)))
423    {
424       free(*target_string);
425
426       *target_string = NULL;
427       return JB_ERR_MEMORY;
428    }
429
430    strlcpy(new_string + old_len, text_to_append, new_size - old_len);
431
432    *target_string = new_string;
433    return JB_ERR_OK;
434 }
435
436
437 /*********************************************************************
438  *
439  * Function    :  string_join
440  *
441  * Description :  Join two strings together.  Frees BOTH the original
442  *                strings.  If either or both input strings are NULL,
443  *                fails as if it had run out of memory.
444  *
445  *                For comparison, string_append requires that the
446  *                second string is non-NULL, and doesn't free it.
447  *
448  *                Rationale: Too often, we want to do
449  *                string_append(s, html_encode(s2)).  That assert()s
450  *                if s2 is NULL or if html_encode() runs out of memory.
451  *                It also leaks memory.  Proper checking is cumbersome.
452  *                The solution: string_join(s, html_encode(s2)) is safe,
453  *                and will free the memory allocated by html_encode().
454  *
455  * Parameters  :
456  *          1  :  target_string = Pointer to old text that is to be
457  *                extended.  *target_string will be free()d by this
458  *                routine.  target_string must be non-NULL.
459  *          2  :  text_to_append = Text to be appended to old.
460  *
461  * Returns     :  JB_ERR_OK on success, and sets *target_string
462  *                   to newly malloc'ed appended string.  Caller
463  *                   must free(*target_string).
464  *                JB_ERR_MEMORY on out-of-memory, or if
465  *                   *target_string or text_to_append is NULL.  (In
466  *                   this case, frees *target_string and text_to_append,
467  *                   sets *target_string to NULL).
468  *
469  *********************************************************************/
470 jb_err string_join(char **target_string, char *text_to_append)
471 {
472    jb_err err;
473
474    assert(target_string);
475
476    if (text_to_append == NULL)
477    {
478       freez(*target_string);
479       return JB_ERR_MEMORY;
480    }
481
482    err = string_append(target_string, text_to_append);
483
484    freez(text_to_append);
485
486    return err;
487 }
488
489
490 /*********************************************************************
491  *
492  * Function    :  string_toupper
493  *
494  * Description :  Produce a copy of string with all convertible
495  *                characters converted to uppercase.
496  *
497  * Parameters  :
498  *          1  :  string = string to convert
499  *
500  * Returns     :  Uppercase copy of string if possible,
501  *                NULL on out-of-memory or if string was NULL.
502  *
503  *********************************************************************/
504 char *string_toupper(const char *string)
505 {
506    char *result, *p;
507    const char *q;
508
509    if (!string || ((result = (char *) zalloc(strlen(string) + 1)) == NULL))
510    {
511       return NULL;
512    }
513
514    q = string;
515    p = result;
516
517    while (*q != '\0')
518    {
519       *p++ = (char)toupper((int) *q++);
520    }
521
522    return result;
523
524 }
525
526
527 /*********************************************************************
528  *
529  * Function    :  string_move
530  *
531  * Description :  memmove wrapper to move the last part of a string
532  *                towards the beginning, overwriting the part in
533  *                the middle. strlcpy() can't be used here as the
534  *                strings overlap.
535  *
536  * Parameters  :
537  *          1  :  dst = Destination to overwrite
538  *          2  :  src = Source to move.
539  *
540  * Returns     :  N/A
541  *
542  *********************************************************************/
543 void string_move(char *dst, char *src)
544 {
545    assert(dst < src);
546
547    /* +1 to copy the terminating nul as well. */
548    memmove(dst, src, strlen(src)+1);
549 }
550
551
552 /*********************************************************************
553  *
554  * Function    :  bindup
555  *
556  * Description :  Duplicate the first n characters of a string that may
557  *                contain '\0' characters.
558  *
559  * Parameters  :
560  *          1  :  string = string to be duplicated
561  *          2  :  len = number of bytes to duplicate
562  *
563  * Returns     :  pointer to copy, or NULL if failiure
564  *
565  *********************************************************************/
566 char *bindup(const char *string, size_t len)
567 {
568    char *duplicate;
569
570    duplicate = (char *)malloc(len);
571    if (NULL != duplicate)
572    {
573       memcpy(duplicate, string, len);
574    }
575
576    return duplicate;
577
578 }
579
580
581 /*********************************************************************
582  *
583  * Function    :  make_path
584  *
585  * Description :  Takes a directory name and a file name, returns
586  *                the complete path.  Handles windows/unix differences.
587  *                If the file name is already an absolute path, or if
588  *                the directory name is NULL or empty, it returns
589  *                the filename.
590  *
591  * Parameters  :
592  *          1  :  dir: Name of directory or NULL for none.
593  *          2  :  file: Name of file.  Should not be NULL or empty.
594  *
595  * Returns     :  "dir/file" (Or on windows, "dir\file").
596  *                It allocates the string on the heap.  Caller frees.
597  *                Returns NULL in error (i.e. NULL file or out of
598  *                memory)
599  *
600  *********************************************************************/
601 char * make_path(const char * dir, const char * file)
602 {
603 #ifdef AMIGA
604    char path[512];
605
606    if (dir)
607    {
608       if (dir[0] == '.')
609       {
610          if (dir[1] == '/')
611          {
612             strncpy(path,dir+2,512);
613          }
614          else
615          {
616             strncpy(path,dir+1,512);
617          }
618       }
619       else
620       {
621          strncpy(path,dir,512);
622       }
623       path[511]=0;
624    }
625    else
626    {
627       path[0]=0;
628    }
629    if (AddPart(path,file,512))
630    {
631       return strdup(path);
632    }
633    else
634    {
635       return NULL;
636    }
637 #else /* ndef AMIGA */
638
639    if ((file == NULL) || (*file == '\0'))
640    {
641       return NULL; /* Error */
642    }
643
644    if ((dir == NULL) || (*dir == '\0') /* No directory specified */
645 #if defined(_WIN32) || defined(__OS2__)
646       || (*file == '\\') || (file[1] == ':') /* Absolute path (DOS) */
647 #else /* ifndef _WIN32 || __OS2__ */
648       || (*file == '/') /* Absolute path (U*ix) */
649 #endif /* ifndef _WIN32 || __OS2__  */
650       )
651    {
652       return strdup(file);
653    }
654    else
655    {
656       char * path;
657       size_t path_size = strlen(dir) + strlen(file) + 2; /* +2 for trailing (back)slash and \0 */
658
659 #if defined(unix)
660       if (*dir != '/' && basedir && *basedir)
661       {
662          /*
663           * Relative path, so start with the base directory.
664           */
665          path_size += strlen(basedir) + 1; /* +1 for the slash */
666          path = malloc(path_size);
667          if (!path) log_error(LOG_LEVEL_FATAL, "malloc failed!");
668          strlcpy(path, basedir, path_size);
669          strlcat(path, "/", path_size);
670          strlcat(path, dir, path_size);
671       }
672       else
673 #endif /* defined unix */
674       {
675          path = malloc(path_size);
676          if (!path) log_error(LOG_LEVEL_FATAL, "malloc failed!");
677          strlcpy(path, dir, path_size);
678       }
679
680       assert(NULL != path);
681 #if defined(_WIN32) || defined(__OS2__)
682       if (path[strlen(path)-1] != '\\')
683       {
684          strlcat(path, "\\", path_size);
685       }
686 #else /* ifndef _WIN32 || __OS2__ */
687       if (path[strlen(path)-1] != '/')
688       {
689          strlcat(path, "/", path_size);
690       }
691 #endif /* ifndef _WIN32 || __OS2__ */
692       strlcat(path, file, path_size);
693
694       return path;
695    }
696 #endif /* ndef AMIGA */
697 }
698
699
700 /*********************************************************************
701  *
702  * Function    :  pick_from_range
703  *
704  * Description :  Pick a positive number out of a given range.
705  *                Should only be used if randomness would be nice,
706  *                but isn't really necessary.
707  *
708  * Parameters  :
709  *          1  :  range: Highest possible number to pick.
710  *
711  * Returns     :  Picked number.
712  *
713  *********************************************************************/
714 long int pick_from_range(long int range)
715 {
716    long int number;
717 #ifdef _WIN32
718    static unsigned long seed = 0;
719 #endif /* def _WIN32 */
720
721    assert(range != 0);
722    assert(range > 0);
723
724    if (range <= 0) return 0;
725
726 #ifdef HAVE_RANDOM
727    number = random() % range + 1;
728 #elif defined(MUTEX_LOCKS_AVAILABLE)
729    privoxy_mutex_lock(&rand_mutex);
730 #ifdef _WIN32
731    if (!seed)
732    {
733       seed = (unsigned long)(GetCurrentThreadId()+GetTickCount());
734    }
735    srand(seed);
736    seed = (unsigned long)((rand() << 16) + rand());
737 #endif /* def _WIN32 */
738    number = (unsigned long)((rand() << 16) + (rand())) % (unsigned long)(range + 1);
739    privoxy_mutex_unlock(&rand_mutex);
740 #else
741    /*
742     * XXX: Which platforms reach this and are there
743     * better options than just using rand() and hoping
744     * that it's safe?
745     */
746    log_error(LOG_LEVEL_INFO, "No thread-safe PRNG available? Header time randomization "
747       "might cause crashes, predictable results or even combine these fine options.");
748    number = rand() % (long int)(range + 1);
749
750 #endif /* (def HAVE_RANDOM) */
751
752    return number;
753 }
754
755
756 #ifdef USE_PRIVOXY_STRLCPY
757 /*********************************************************************
758  *
759  * Function    :  privoxy_strlcpy
760  *
761  * Description :  strlcpy(3) look-alike for those without decent libc.
762  *
763  * Parameters  :
764  *          1  :  destination: buffer to copy into.
765  *          2  :  source: String to copy.
766  *          3  :  size: Size of destination buffer.
767  *
768  * Returns     :  The length of the string that privoxy_strlcpy() tried to create.
769  *
770  *********************************************************************/
771 size_t privoxy_strlcpy(char *destination, const char *source, const size_t size)
772 {
773    if (0 < size)
774    {
775       snprintf(destination, size, "%s", source);
776       /*
777        * Platforms that lack strlcpy() also tend to have
778        * a broken snprintf implementation that doesn't
779        * guarantee nul termination.
780        *
781        * XXX: the configure script should detect and reject those.
782        */
783       destination[size-1] = '\0';
784    }
785    return strlen(source);
786 }
787 #endif /* def USE_PRIVOXY_STRLCPY */
788
789
790 #ifndef HAVE_STRLCAT
791 /*********************************************************************
792  *
793  * Function    :  privoxy_strlcat
794  *
795  * Description :  strlcat(3) look-alike for those without decent libc.
796  *
797  * Parameters  :
798  *          1  :  destination: C string.
799  *          2  :  source: String to copy.
800  *          3  :  size: Size of destination buffer.
801  *
802  * Returns     :  The length of the string that privoxy_strlcat() tried to create.
803  *
804  *********************************************************************/
805 size_t privoxy_strlcat(char *destination, const char *source, const size_t size)
806 {
807    const size_t old_length = strlen(destination);
808    return old_length + strlcpy(destination + old_length, source, size - old_length);
809 }
810 #endif /* ndef HAVE_STRLCAT */
811
812
813 #if !defined(HAVE_TIMEGM) && defined(HAVE_TZSET) && defined(HAVE_PUTENV)
814 /*********************************************************************
815  *
816  * Function    :  timegm
817  *
818  * Description :  libc replacement function for the inverse of gmtime().
819  *                Copyright (C) 2004 Free Software Foundation, Inc.
820  *
821  *                Code originally copied from GnuPG, modifications done
822  *                for Privoxy: style changed, #ifdefs for _WIN32 added
823  *                to have it work on mingw32.
824  *
825  *                XXX: It's very unlikely to happen, but if the malloc()
826  *                call fails the time zone will be permanently set to UTC.
827  *
828  * Parameters  :
829  *          1  :  tm: Broken-down time struct.
830  *
831  * Returns     :  tm converted into time_t seconds.
832  *
833  *********************************************************************/
834 time_t timegm(struct tm *tm)
835 {
836    time_t answer;
837    char *zone;
838
839    zone = getenv("TZ");
840    putenv("TZ=UTC");
841    tzset();
842    answer = mktime(tm);
843    if (zone)
844    {
845       char *old_zone;
846
847       old_zone = malloc(3 + strlen(zone) + 1);
848       if (old_zone)
849       {
850          strcpy(old_zone, "TZ=");
851          strcat(old_zone, zone);
852          putenv(old_zone);
853 #ifdef _WIN32
854          free(old_zone);
855 #endif /* def _WIN32 */
856       }
857    }
858    else
859    {
860 #ifdef HAVE_UNSETENV
861       unsetenv("TZ");
862 #elif defined(_WIN32)
863       putenv("TZ=");
864 #else
865       putenv("TZ");
866 #endif
867    }
868    tzset();
869
870    return answer;
871 }
872 #endif /* !defined(HAVE_TIMEGM) && defined(HAVE_TZSET) && defined(HAVE_PUTENV) */
873
874
875 #ifndef HAVE_SNPRINTF
876 /*
877  * What follows is a portable snprintf routine, written by Mark Martinec.
878  * See: http://www.ijs.si/software/snprintf/
879
880                                   snprintf.c
881                    - a portable implementation of snprintf,
882        including vsnprintf.c, asnprintf, vasnprintf, asprintf, vasprintf
883
884    snprintf is a routine to convert numeric and string arguments to
885    formatted strings. It is similar to sprintf(3) provided in a system's
886    C library, yet it requires an additional argument - the buffer size -
887    and it guarantees never to store anything beyond the given buffer,
888    regardless of the format or arguments to be formatted. Some newer
889    operating systems do provide snprintf in their C library, but many do
890    not or do provide an inadequate (slow or idiosyncratic) version, which
891    calls for a portable implementation of this routine.
892
893 Author
894
895    Mark Martinec <mark.martinec@ijs.si>, April 1999, June 2000
896    Copyright Â© 1999, Mark Martinec
897
898  */
899
900 #define PORTABLE_SNPRINTF_VERSION_MAJOR 2
901 #define PORTABLE_SNPRINTF_VERSION_MINOR 2
902
903 #if defined(NEED_ASPRINTF) || defined(NEED_ASNPRINTF) || defined(NEED_VASPRINTF) || defined(NEED_VASNPRINTF)
904 # if defined(NEED_SNPRINTF_ONLY)
905 # undef NEED_SNPRINTF_ONLY
906 # endif
907 # if !defined(PREFER_PORTABLE_SNPRINTF)
908 # define PREFER_PORTABLE_SNPRINTF
909 # endif
910 #endif
911
912 #if defined(SOLARIS_BUG_COMPATIBLE) && !defined(SOLARIS_COMPATIBLE)
913 #define SOLARIS_COMPATIBLE
914 #endif
915
916 #if defined(HPUX_BUG_COMPATIBLE) && !defined(HPUX_COMPATIBLE)
917 #define HPUX_COMPATIBLE
918 #endif
919
920 #if defined(DIGITAL_UNIX_BUG_COMPATIBLE) && !defined(DIGITAL_UNIX_COMPATIBLE)
921 #define DIGITAL_UNIX_COMPATIBLE
922 #endif
923
924 #if defined(PERL_BUG_COMPATIBLE) && !defined(PERL_COMPATIBLE)
925 #define PERL_COMPATIBLE
926 #endif
927
928 #if defined(LINUX_BUG_COMPATIBLE) && !defined(LINUX_COMPATIBLE)
929 #define LINUX_COMPATIBLE
930 #endif
931
932 #include <sys/types.h>
933 #include <string.h>
934 #include <stdlib.h>
935 #include <stdio.h>
936 #include <stdarg.h>
937 #include <assert.h>
938 #include <errno.h>
939
940 #ifdef isdigit
941 #undef isdigit
942 #endif
943 #define isdigit(c) ((c) >= '0' && (c) <= '9')
944
945 /* For copying strings longer or equal to 'breakeven_point'
946  * it is more efficient to call memcpy() than to do it inline.
947  * The value depends mostly on the processor architecture,
948  * but also on the compiler and its optimization capabilities.
949  * The value is not critical, some small value greater than zero
950  * will be just fine if you don't care to squeeze every drop
951  * of performance out of the code.
952  *
953  * Small values favor memcpy, large values favor inline code.
954  */
955 #if defined(__alpha__) || defined(__alpha)
956 #  define breakeven_point   2    /* AXP (DEC Alpha)     - gcc or cc or egcs */
957 #endif
958 #if defined(__i386__)  || defined(__i386)
959 #  define breakeven_point  12    /* Intel Pentium/Linux - gcc 2.96 */
960 #endif
961 #if defined(__hppa)
962 #  define breakeven_point  10    /* HP-PA               - gcc */
963 #endif
964 #if defined(__sparc__) || defined(__sparc)
965 #  define breakeven_point  33    /* Sun Sparc 5         - gcc 2.8.1 */
966 #endif
967
968 /* some other values of possible interest: */
969 /* #define breakeven_point  8 */ /* VAX 4000          - vaxc */
970 /* #define breakeven_point 19 */ /* VAX 4000          - gcc 2.7.0 */
971
972 #ifndef breakeven_point
973 #  define breakeven_point   6    /* some reasonable one-size-fits-all value */
974 #endif
975
976 #define fast_memcpy(d,s,n) \
977   { register size_t nn = (size_t)(n); \
978     if (nn >= breakeven_point) memcpy((d), (s), nn); \
979     else if (nn > 0) { /* proc call overhead is worth only for large strings*/\
980       register char *dd; register const char *ss; \
981       for (ss=(s), dd=(d); nn>0; nn--) *dd++ = *ss++; } }
982
983 #define fast_memset(d,c,n) \
984   { register size_t nn = (size_t)(n); \
985     if (nn >= breakeven_point) memset((d), (int)(c), nn); \
986     else if (nn > 0) { /* proc call overhead is worth only for large strings*/\
987       register char *dd; register const int cc=(int)(c); \
988       for (dd=(d); nn>0; nn--) *dd++ = cc; } }
989
990 /* prototypes */
991
992 #if defined(NEED_ASPRINTF)
993 int asprintf   (char **ptr, const char *fmt, /*args*/ ...);
994 #endif
995 #if defined(NEED_VASPRINTF)
996 int vasprintf  (char **ptr, const char *fmt, va_list ap);
997 #endif
998 #if defined(NEED_ASNPRINTF)
999 int asnprintf  (char **ptr, size_t str_m, const char *fmt, /*args*/ ...);
1000 #endif
1001 #if defined(NEED_VASNPRINTF)
1002 int vasnprintf (char **ptr, size_t str_m, const char *fmt, va_list ap);
1003 #endif
1004
1005 #if defined(HAVE_SNPRINTF)
1006 /* declare our portable snprintf  routine under name portable_snprintf  */
1007 /* declare our portable vsnprintf routine under name portable_vsnprintf */
1008 #else
1009 /* declare our portable routines under names snprintf and vsnprintf */
1010 #define portable_snprintf snprintf
1011 #if !defined(NEED_SNPRINTF_ONLY)
1012 #define portable_vsnprintf vsnprintf
1013 #endif
1014 #endif
1015
1016 #if !defined(HAVE_SNPRINTF) || defined(PREFER_PORTABLE_SNPRINTF)
1017 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...);
1018 #if !defined(NEED_SNPRINTF_ONLY)
1019 int portable_vsnprintf(char *str, size_t str_m, const char *fmt, va_list ap);
1020 #endif
1021 #endif
1022
1023 /* declarations */
1024
1025 static char credits[] = "\n\
1026 @(#)snprintf.c, v2.2: Mark Martinec, <mark.martinec@ijs.si>\n\
1027 @(#)snprintf.c, v2.2: Copyright 1999, Mark Martinec. Frontier Artistic License applies.\n\
1028 @(#)snprintf.c, v2.2: http://www.ijs.si/software/snprintf/\n";
1029
1030 #if defined(NEED_ASPRINTF)
1031 int asprintf(char **ptr, const char *fmt, /*args*/ ...) {
1032   va_list ap;
1033   size_t str_m;
1034   int str_l;
1035
1036   *ptr = NULL;
1037   va_start(ap, fmt);                            /* measure the required size */
1038   str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap);
1039   va_end(ap);
1040   assert(str_l >= 0);        /* possible integer overflow if str_m > INT_MAX */
1041   *ptr = (char *) malloc(str_m = (size_t)str_l + 1);
1042   if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1043   else {
1044     int str_l2;
1045     va_start(ap, fmt);
1046     str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1047     va_end(ap);
1048     assert(str_l2 == str_l);
1049   }
1050   return str_l;
1051 }
1052 #endif
1053
1054 #if defined(NEED_VASPRINTF)
1055 int vasprintf(char **ptr, const char *fmt, va_list ap) {
1056   size_t str_m;
1057   int str_l;
1058
1059   *ptr = NULL;
1060   { va_list ap2;
1061     va_copy(ap2, ap);  /* don't consume the original ap, we'll need it again */
1062     str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap2);/*get required size*/
1063     va_end(ap2);
1064   }
1065   assert(str_l >= 0);        /* possible integer overflow if str_m > INT_MAX */
1066   *ptr = (char *) malloc(str_m = (size_t)str_l + 1);
1067   if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1068   else {
1069     int str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1070     assert(str_l2 == str_l);
1071   }
1072   return str_l;
1073 }
1074 #endif
1075
1076 #if defined(NEED_ASNPRINTF)
1077 int asnprintf (char **ptr, size_t str_m, const char *fmt, /*args*/ ...) {
1078   va_list ap;
1079   int str_l;
1080
1081   *ptr = NULL;
1082   va_start(ap, fmt);                            /* measure the required size */
1083   str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap);
1084   va_end(ap);
1085   assert(str_l >= 0);        /* possible integer overflow if str_m > INT_MAX */
1086   if ((size_t)str_l + 1 < str_m) str_m = (size_t)str_l + 1;      /* truncate */
1087   /* if str_m is 0, no buffer is allocated, just set *ptr to NULL */
1088   if (str_m == 0) {  /* not interested in resulting string, just return size */
1089   } else {
1090     *ptr = (char *) malloc(str_m);
1091     if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1092     else {
1093       int str_l2;
1094       va_start(ap, fmt);
1095       str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1096       va_end(ap);
1097       assert(str_l2 == str_l);
1098     }
1099   }
1100   return str_l;
1101 }
1102 #endif
1103
1104 #if defined(NEED_VASNPRINTF)
1105 int vasnprintf (char **ptr, size_t str_m, const char *fmt, va_list ap) {
1106   int str_l;
1107
1108   *ptr = NULL;
1109   { va_list ap2;
1110     va_copy(ap2, ap);  /* don't consume the original ap, we'll need it again */
1111     str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap2);/*get required size*/
1112     va_end(ap2);
1113   }
1114   assert(str_l >= 0);        /* possible integer overflow if str_m > INT_MAX */
1115   if ((size_t)str_l + 1 < str_m) str_m = (size_t)str_l + 1;      /* truncate */
1116   /* if str_m is 0, no buffer is allocated, just set *ptr to NULL */
1117   if (str_m == 0) {  /* not interested in resulting string, just return size */
1118   } else {
1119     *ptr = (char *) malloc(str_m);
1120     if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1121     else {
1122       int str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1123       assert(str_l2 == str_l);
1124     }
1125   }
1126   return str_l;
1127 }
1128 #endif
1129
1130 /*
1131  * If the system does have snprintf and the portable routine is not
1132  * specifically required, this module produces no code for snprintf/vsnprintf.
1133  */
1134 #if !defined(HAVE_SNPRINTF) || defined(PREFER_PORTABLE_SNPRINTF)
1135
1136 #if !defined(NEED_SNPRINTF_ONLY)
1137 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...) {
1138   va_list ap;
1139   int str_l;
1140
1141   va_start(ap, fmt);
1142   str_l = portable_vsnprintf(str, str_m, fmt, ap);
1143   va_end(ap);
1144   return str_l;
1145 }
1146 #endif
1147
1148 #if defined(NEED_SNPRINTF_ONLY)
1149 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...) {
1150 #else
1151 int portable_vsnprintf(char *str, size_t str_m, const char *fmt, va_list ap) {
1152 #endif
1153
1154 #if defined(NEED_SNPRINTF_ONLY)
1155   va_list ap;
1156 #endif
1157   size_t str_l = 0;
1158   const char *p = fmt;
1159
1160 /* In contrast with POSIX, the ISO C99 now says
1161  * that str can be NULL and str_m can be 0.
1162  * This is more useful than the old:  if (str_m < 1) return -1; */
1163
1164 #if defined(NEED_SNPRINTF_ONLY)
1165   va_start(ap, fmt);
1166 #endif
1167   if (!p) p = "";
1168   while (*p) {
1169     if (*p != '%') {
1170    /* if (str_l < str_m) str[str_l++] = *p++;    -- this would be sufficient */
1171    /* but the following code achieves better performance for cases
1172     * where format string is long and contains few conversions */
1173       const char *q = strchr(p+1,'%');
1174       size_t n = !q ? strlen(p) : (q-p);
1175       if (str_l < str_m) {
1176         size_t avail = str_m-str_l;
1177         fast_memcpy(str+str_l, p, (n>avail?avail:n));
1178       }
1179       p += n; str_l += n;
1180     } else {
1181       const char *starting_p;
1182       size_t min_field_width = 0, precision = 0;
1183       int zero_padding = 0, precision_specified = 0, justify_left = 0;
1184       int alternate_form = 0, force_sign = 0;
1185       int space_for_positive = 1; /* If both the ' ' and '+' flags appear,
1186                                      the ' ' flag should be ignored. */
1187       char length_modifier = '\0';            /* allowed values: \0, h, l, L */
1188       char tmp[32];/* temporary buffer for simple numeric->string conversion */
1189
1190       const char *str_arg;      /* string address in case of string argument */
1191       size_t str_arg_l;         /* natural field width of arg without padding
1192                                    and sign */
1193       unsigned char uchar_arg;
1194         /* unsigned char argument value - only defined for c conversion.
1195            N.B. standard explicitly states the char argument for
1196            the c conversion is unsigned */
1197
1198       size_t number_of_zeros_to_pad = 0;
1199         /* number of zeros to be inserted for numeric conversions
1200            as required by the precision or minimal field width */
1201
1202       size_t zero_padding_insertion_ind = 0;
1203         /* index into tmp where zero padding is to be inserted */
1204
1205       char fmt_spec = '\0';
1206         /* current conversion specifier character */
1207
1208       str_arg = credits;/* just to make compiler happy (defined but not used)*/
1209       str_arg = NULL;
1210       starting_p = p; p++;  /* skip '%' */
1211    /* parse flags */
1212       while (*p == '0' || *p == '-' || *p == '+' ||
1213              *p == ' ' || *p == '#' || *p == '\'') {
1214         switch (*p) {
1215         case '0': zero_padding = 1; break;
1216         case '-': justify_left = 1; break;
1217         case '+': force_sign = 1; space_for_positive = 0; break;
1218         case ' ': force_sign = 1;
1219      /* If both the ' ' and '+' flags appear, the ' ' flag should be ignored */
1220 #ifdef PERL_COMPATIBLE
1221      /* ... but in Perl the last of ' ' and '+' applies */
1222                   space_for_positive = 1;
1223 #endif
1224                   break;
1225         case '#': alternate_form = 1; break;
1226         case '\'': break;
1227         }
1228         p++;
1229       }
1230    /* If the '0' and '-' flags both appear, the '0' flag should be ignored. */
1231
1232    /* parse field width */
1233       if (*p == '*') {
1234         int j;
1235         p++; j = va_arg(ap, int);
1236         if (j >= 0) min_field_width = j;
1237         else { min_field_width = -j; justify_left = 1; }
1238       } else if (isdigit((int)(*p))) {
1239         /* size_t could be wider than unsigned int;
1240            make sure we treat argument like common implementations do */
1241         unsigned int uj = *p++ - '0';
1242         while (isdigit((int)(*p))) uj = 10*uj + (unsigned int)(*p++ - '0');
1243         min_field_width = uj;
1244       }
1245    /* parse precision */
1246       if (*p == '.') {
1247         p++; precision_specified = 1;
1248         if (*p == '*') {
1249           int j = va_arg(ap, int);
1250           p++;
1251           if (j >= 0) precision = j;
1252           else {
1253             precision_specified = 0; precision = 0;
1254          /* NOTE:
1255           *   Solaris 2.6 man page claims that in this case the precision
1256           *   should be set to 0.  Digital Unix 4.0, HPUX 10 and BSD man page
1257           *   claim that this case should be treated as unspecified precision,
1258           *   which is what we do here.
1259           */
1260           }
1261         } else if (isdigit((int)(*p))) {
1262           /* size_t could be wider than unsigned int;
1263              make sure we treat argument like common implementations do */
1264           unsigned int uj = *p++ - '0';
1265           while (isdigit((int)(*p))) uj = 10*uj + (unsigned int)(*p++ - '0');
1266           precision = uj;
1267         }
1268       }
1269    /* parse 'h', 'l' and 'll' length modifiers */
1270       if (*p == 'h' || *p == 'l') {
1271         length_modifier = *p; p++;
1272         if (length_modifier == 'l' && *p == 'l') {   /* double l = long long */
1273 #ifdef SNPRINTF_LONGLONG_SUPPORT
1274           length_modifier = '2';                  /* double l encoded as '2' */
1275 #else
1276           length_modifier = 'l';                 /* treat it as a single 'l' */
1277 #endif
1278           p++;
1279         }
1280       }
1281       fmt_spec = *p;
1282    /* common synonyms: */
1283       switch (fmt_spec) {
1284       case 'i': fmt_spec = 'd'; break;
1285       case 'D': fmt_spec = 'd'; length_modifier = 'l'; break;
1286       case 'U': fmt_spec = 'u'; length_modifier = 'l'; break;
1287       case 'O': fmt_spec = 'o'; length_modifier = 'l'; break;
1288       default: break;
1289       }
1290    /* get parameter value, do initial processing */
1291       switch (fmt_spec) {
1292       case '%': /* % behaves similar to 's' regarding flags and field widths */
1293       case 'c': /* c behaves similar to 's' regarding flags and field widths */
1294       case 's':
1295         length_modifier = '\0';          /* wint_t and wchar_t not supported */
1296      /* the result of zero padding flag with non-numeric conversion specifier*/
1297      /* is undefined. Solaris and HPUX 10 does zero padding in this case,    */
1298      /* Digital Unix and Linux does not. */
1299 #if !defined(SOLARIS_COMPATIBLE) && !defined(HPUX_COMPATIBLE)
1300         zero_padding = 0;    /* turn zero padding off for string conversions */
1301 #endif
1302         str_arg_l = 1;
1303         switch (fmt_spec) {
1304         case '%':
1305           str_arg = p; break;
1306         case 'c': {
1307           int j = va_arg(ap, int);
1308           uchar_arg = (unsigned char) j;   /* standard demands unsigned char */
1309           str_arg = (const char *) &uchar_arg;
1310           break;
1311         }
1312         case 's':
1313           str_arg = va_arg(ap, const char *);
1314           if (!str_arg) str_arg_l = 0;
1315        /* make sure not to address string beyond the specified precision !!! */
1316           else if (!precision_specified) str_arg_l = strlen(str_arg);
1317        /* truncate string if necessary as requested by precision */
1318           else if (precision == 0) str_arg_l = 0;
1319           else {
1320        /* memchr on HP does not like n > 2^31  !!! */
1321             const char *q = memchr(str_arg, '\0',
1322                              precision <= 0x7fffffff ? precision : 0x7fffffff);
1323             str_arg_l = !q ? precision : (q-str_arg);
1324           }
1325           break;
1326         default: break;
1327         }
1328         break;
1329       case 'd': case 'u': case 'o': case 'x': case 'X': case 'p': {
1330         /* NOTE: the u, o, x, X and p conversion specifiers imply
1331                  the value is unsigned;  d implies a signed value */
1332
1333         int arg_sign = 0;
1334           /* 0 if numeric argument is zero (or if pointer is NULL for 'p'),
1335             +1 if greater than zero (or nonzero for unsigned arguments),
1336             -1 if negative (unsigned argument is never negative) */
1337
1338         int int_arg = 0;  unsigned int uint_arg = 0;
1339           /* only defined for length modifier h, or for no length modifiers */
1340
1341         long int long_arg = 0;  unsigned long int ulong_arg = 0;
1342           /* only defined for length modifier l */
1343
1344         void *ptr_arg = NULL;
1345           /* pointer argument value -only defined for p conversion */
1346
1347 #ifdef SNPRINTF_LONGLONG_SUPPORT
1348         long long int long_long_arg = 0;
1349         unsigned long long int ulong_long_arg = 0;
1350           /* only defined for length modifier ll */
1351 #endif
1352         if (fmt_spec == 'p') {
1353         /* HPUX 10: An l, h, ll or L before any other conversion character
1354          *   (other than d, i, u, o, x, or X) is ignored.
1355          * Digital Unix:
1356          *   not specified, but seems to behave as HPUX does.
1357          * Solaris: If an h, l, or L appears before any other conversion
1358          *   specifier (other than d, i, u, o, x, or X), the behavior
1359          *   is undefined. (Actually %hp converts only 16-bits of address
1360          *   and %llp treats address as 64-bit data which is incompatible
1361          *   with (void *) argument on a 32-bit system).
1362          */
1363 #ifdef SOLARIS_COMPATIBLE
1364 #  ifdef SOLARIS_BUG_COMPATIBLE
1365           /* keep length modifiers even if it represents 'll' */
1366 #  else
1367           if (length_modifier == '2') length_modifier = '\0';
1368 #  endif
1369 #else
1370           length_modifier = '\0';
1371 #endif
1372           ptr_arg = va_arg(ap, void *);
1373           if (ptr_arg != NULL) arg_sign = 1;
1374         } else if (fmt_spec == 'd') {  /* signed */
1375           switch (length_modifier) {
1376           case '\0':
1377           case 'h':
1378          /* It is non-portable to specify a second argument of char or short
1379           * to va_arg, because arguments seen by the called function
1380           * are not char or short.  C converts char and short arguments
1381           * to int before passing them to a function.
1382           */
1383             int_arg = va_arg(ap, int);
1384             if      (int_arg > 0) arg_sign =  1;
1385             else if (int_arg < 0) arg_sign = -1;
1386             break;
1387           case 'l':
1388             long_arg = va_arg(ap, long int);
1389             if      (long_arg > 0) arg_sign =  1;
1390             else if (long_arg < 0) arg_sign = -1;
1391             break;
1392 #ifdef SNPRINTF_LONGLONG_SUPPORT
1393           case '2':
1394             long_long_arg = va_arg(ap, long long int);
1395             if      (long_long_arg > 0) arg_sign =  1;
1396             else if (long_long_arg < 0) arg_sign = -1;
1397             break;
1398 #endif
1399           }
1400         } else {  /* unsigned */
1401           switch (length_modifier) {
1402           case '\0':
1403           case 'h':
1404             uint_arg = va_arg(ap, unsigned int);
1405             if (uint_arg) arg_sign = 1;
1406             break;
1407           case 'l':
1408             ulong_arg = va_arg(ap, unsigned long int);
1409             if (ulong_arg) arg_sign = 1;
1410             break;
1411 #ifdef SNPRINTF_LONGLONG_SUPPORT
1412           case '2':
1413             ulong_long_arg = va_arg(ap, unsigned long long int);
1414             if (ulong_long_arg) arg_sign = 1;
1415             break;
1416 #endif
1417           }
1418         }
1419         str_arg = tmp; str_arg_l = 0;
1420      /* NOTE:
1421       *   For d, i, u, o, x, and X conversions, if precision is specified,
1422       *   the '0' flag should be ignored. This is so with Solaris 2.6,
1423       *   Digital UNIX 4.0, HPUX 10, Linux, FreeBSD, NetBSD; but not with Perl.
1424       */
1425 #ifndef PERL_COMPATIBLE
1426         if (precision_specified) zero_padding = 0;
1427 #endif
1428         if (fmt_spec == 'd') {
1429           if (force_sign && arg_sign >= 0)
1430             tmp[str_arg_l++] = space_for_positive ? ' ' : '+';
1431          /* leave negative numbers for sprintf to handle,
1432             to avoid handling tricky cases like (short int)(-32768) */
1433 #ifdef LINUX_COMPATIBLE
1434         } else if (fmt_spec == 'p' && force_sign && arg_sign > 0) {
1435           tmp[str_arg_l++] = space_for_positive ? ' ' : '+';
1436 #endif
1437         } else if (alternate_form) {
1438           if (arg_sign != 0 && (fmt_spec == 'x' || fmt_spec == 'X') )
1439             { tmp[str_arg_l++] = '0'; tmp[str_arg_l++] = fmt_spec; }
1440          /* alternate form should have no effect for p conversion, but ... */
1441 #ifdef HPUX_COMPATIBLE
1442           else if (fmt_spec == 'p'
1443          /* HPUX 10: for an alternate form of p conversion,
1444           *          a nonzero result is prefixed by 0x. */
1445 #ifndef HPUX_BUG_COMPATIBLE
1446          /* Actually it uses 0x prefix even for a zero value. */
1447                    && arg_sign != 0
1448 #endif
1449                   ) { tmp[str_arg_l++] = '0'; tmp[str_arg_l++] = 'x'; }
1450 #endif
1451         }
1452         zero_padding_insertion_ind = str_arg_l;
1453         if (!precision_specified) precision = 1;   /* default precision is 1 */
1454         if (precision == 0 && arg_sign == 0
1455 #if defined(HPUX_BUG_COMPATIBLE) || defined(LINUX_COMPATIBLE)
1456             && fmt_spec != 'p'
1457          /* HPUX 10 man page claims: With conversion character p the result of
1458           * converting a zero value with a precision of zero is a null string.
1459           * Actually HP returns all zeroes, and Linux returns "(nil)". */
1460 #endif
1461         ) {
1462          /* converted to null string */
1463          /* When zero value is formatted with an explicit precision 0,
1464             the resulting formatted string is empty (d, i, u, o, x, X, p).   */
1465         } else {
1466           char f[5]; int f_l = 0;
1467           f[f_l++] = '%';    /* construct a simple format string for sprintf */
1468           if (!length_modifier) { }
1469           else if (length_modifier=='2') { f[f_l++] = 'l'; f[f_l++] = 'l'; }
1470           else f[f_l++] = length_modifier;
1471           f[f_l++] = fmt_spec; f[f_l++] = '\0';
1472           if (fmt_spec == 'p') str_arg_l += sprintf(tmp+str_arg_l, f, ptr_arg);
1473           else if (fmt_spec == 'd') {  /* signed */
1474             switch (length_modifier) {
1475             case '\0':
1476             case 'h': str_arg_l+=sprintf(tmp+str_arg_l, f, int_arg);  break;
1477             case 'l': str_arg_l+=sprintf(tmp+str_arg_l, f, long_arg); break;
1478 #ifdef SNPRINTF_LONGLONG_SUPPORT
1479             case '2': str_arg_l+=sprintf(tmp+str_arg_l,f,long_long_arg); break;
1480 #endif
1481             }
1482           } else {  /* unsigned */
1483             switch (length_modifier) {
1484             case '\0':
1485             case 'h': str_arg_l+=sprintf(tmp+str_arg_l, f, uint_arg);  break;
1486             case 'l': str_arg_l+=sprintf(tmp+str_arg_l, f, ulong_arg); break;
1487 #ifdef SNPRINTF_LONGLONG_SUPPORT
1488             case '2': str_arg_l+=sprintf(tmp+str_arg_l,f,ulong_long_arg);break;
1489 #endif
1490             }
1491           }
1492          /* include the optional minus sign and possible "0x"
1493             in the region before the zero padding insertion point */
1494           if (zero_padding_insertion_ind < str_arg_l &&
1495               tmp[zero_padding_insertion_ind] == '-') {
1496             zero_padding_insertion_ind++;
1497           }
1498           if (zero_padding_insertion_ind+1 < str_arg_l &&
1499               tmp[zero_padding_insertion_ind]   == '0' &&
1500              (tmp[zero_padding_insertion_ind+1] == 'x' ||
1501               tmp[zero_padding_insertion_ind+1] == 'X') ) {
1502             zero_padding_insertion_ind += 2;
1503           }
1504         }
1505         { size_t num_of_digits = str_arg_l - zero_padding_insertion_ind;
1506           if (alternate_form && fmt_spec == 'o'
1507 #ifdef HPUX_COMPATIBLE                                  /* ("%#.o",0) -> ""  */
1508               && (str_arg_l > 0)
1509 #endif
1510 #ifdef DIGITAL_UNIX_BUG_COMPATIBLE                      /* ("%#o",0) -> "00" */
1511 #else
1512               /* unless zero is already the first character */
1513               && !(zero_padding_insertion_ind < str_arg_l
1514                    && tmp[zero_padding_insertion_ind] == '0')
1515 #endif
1516           ) {        /* assure leading zero for alternate-form octal numbers */
1517             if (!precision_specified || precision < num_of_digits+1) {
1518              /* precision is increased to force the first character to be zero,
1519                 except if a zero value is formatted with an explicit precision
1520                 of zero */
1521               precision = num_of_digits+1; precision_specified = 1;
1522             }
1523           }
1524        /* zero padding to specified precision? */
1525           if (num_of_digits < precision)
1526             number_of_zeros_to_pad = precision - num_of_digits;
1527         }
1528      /* zero padding to specified minimal field width? */
1529         if (!justify_left && zero_padding) {
1530           int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
1531           if (n > 0) number_of_zeros_to_pad += n;
1532         }
1533         break;
1534       }
1535       default: /* unrecognized conversion specifier, keep format string as-is*/
1536         zero_padding = 0;  /* turn zero padding off for non-numeric convers. */
1537 #ifndef DIGITAL_UNIX_COMPATIBLE
1538         justify_left = 1; min_field_width = 0;                /* reset flags */
1539 #endif
1540 #if defined(PERL_COMPATIBLE) || defined(LINUX_COMPATIBLE)
1541      /* keep the entire format string unchanged */
1542         str_arg = starting_p; str_arg_l = p - starting_p;
1543      /* well, not exactly so for Linux, which does something between,
1544       * and I don't feel an urge to imitate it: "%+++++hy" -> "%+y"  */
1545 #else
1546      /* discard the unrecognized conversion, just keep *
1547       * the unrecognized conversion character          */
1548         str_arg = p; str_arg_l = 0;
1549 #endif
1550         if (*p) str_arg_l++;  /* include invalid conversion specifier unchanged
1551                                  if not at end-of-string */
1552         break;
1553       }
1554       if (*p) p++;      /* step over the just processed conversion specifier */
1555    /* insert padding to the left as requested by min_field_width;
1556       this does not include the zero padding in case of numerical conversions*/
1557       if (!justify_left) {                /* left padding with blank or zero */
1558         int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
1559         if (n > 0) {
1560           if (str_l < str_m) {
1561             size_t avail = str_m-str_l;
1562             fast_memset(str+str_l, (zero_padding?'0':' '), (n>avail?avail:n));
1563           }
1564           str_l += n;
1565         }
1566       }
1567    /* zero padding as requested by the precision or by the minimal field width
1568     * for numeric conversions required? */
1569       if (number_of_zeros_to_pad <= 0) {
1570      /* will not copy first part of numeric right now, *
1571       * force it to be copied later in its entirety    */
1572         zero_padding_insertion_ind = 0;
1573       } else {
1574      /* insert first part of numerics (sign or '0x') before zero padding */
1575         int n = zero_padding_insertion_ind;
1576         if (n > 0) {
1577           if (str_l < str_m) {
1578             size_t avail = str_m-str_l;
1579             fast_memcpy(str+str_l, str_arg, (n>avail?avail:n));
1580           }
1581           str_l += n;
1582         }
1583      /* insert zero padding as requested by the precision or min field width */
1584         n = number_of_zeros_to_pad;
1585         if (n > 0) {
1586           if (str_l < str_m) {
1587             size_t avail = str_m-str_l;
1588             fast_memset(str+str_l, '0', (n>avail?avail:n));
1589           }
1590           str_l += n;
1591         }
1592       }
1593    /* insert formatted string
1594     * (or as-is conversion specifier for unknown conversions) */
1595       { int n = str_arg_l - zero_padding_insertion_ind;
1596         if (n > 0) {
1597           if (str_l < str_m) {
1598             size_t avail = str_m-str_l;
1599             fast_memcpy(str+str_l, str_arg+zero_padding_insertion_ind,
1600                         (n>avail?avail:n));
1601           }
1602           str_l += n;
1603         }
1604       }
1605    /* insert right padding */
1606       if (justify_left) {          /* right blank padding to the field width */
1607         int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
1608         if (n > 0) {
1609           if (str_l < str_m) {
1610             size_t avail = str_m-str_l;
1611             fast_memset(str+str_l, ' ', (n>avail?avail:n));
1612           }
1613           str_l += n;
1614         }
1615       }
1616     }
1617   }
1618 #if defined(NEED_SNPRINTF_ONLY)
1619   va_end(ap);
1620 #endif
1621   if (str_m > 0) { /* make sure the string is null-terminated
1622                       even at the expense of overwriting the last character
1623                       (shouldn't happen, but just in case) */
1624     str[str_l <= str_m-1 ? str_l : str_m-1] = '\0';
1625   }
1626   /* Return the number of characters formatted (excluding trailing null
1627    * character), that is, the number of characters that would have been
1628    * written to the buffer if it were large enough.
1629    *
1630    * The value of str_l should be returned, but str_l is of unsigned type
1631    * size_t, and snprintf is int, possibly leading to an undetected
1632    * integer overflow, resulting in a negative return value, which is illegal.
1633    * Both XSH5 and ISO C99 (at least the draft) are silent on this issue.
1634    * Should errno be set to EOVERFLOW and EOF returned in this case???
1635    */
1636   return (int) str_l;
1637 }
1638 #endif
1639 #endif /* ndef HAVE_SNPRINTF */
1640 /*
1641   Local Variables:
1642   tab-width: 3
1643   end:
1644 */