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