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