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