Add support for Brotli decompression
[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) && !defined(__OS2__)
52 #include <unistd.h>
53 #endif /* #if !defined(_WIN32) && !defined(__OS2__) */
54 #include <string.h>
55 #include <ctype.h>
56 #include <assert.h>
57
58 #if !defined(HAVE_TIMEGM) && defined(HAVE_TZSET) && defined(HAVE_PUTENV)
59 #include <time.h>
60 #endif /* !defined(HAVE_TIMEGM) && defined(HAVE_TZSET) && defined(HAVE_PUTENV) */
61
62 #include "project.h"
63 #include "miscutil.h"
64 #include "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) || defined(__OS2__)
651       || (*file == '\\') || (file[1] == ':') /* Absolute path (DOS) */
652 #else /* ifndef _WIN32 || __OS2__ */
653       || (*file == '/') /* Absolute path (U*ix) */
654 #endif /* ifndef _WIN32 || __OS2__  */
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) || defined(__OS2__)
687       if (path[strlen(path)-1] != '\\')
688       {
689          strlcat(path, "\\", path_size);
690       }
691 #else /* ifndef _WIN32 || __OS2__ */
692       if (path[strlen(path)-1] != '/')
693       {
694          strlcat(path, "/", path_size);
695       }
696 #endif /* ifndef _WIN32 || __OS2__ */
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 #elif defined(__OS2__)
846    DosSleep(milliseconds * 10);
847
848    return 0;
849 #else
850 #warning Missing privoxy_milisleep() implementation. delay-response{} will not work.
851
852    return -1;
853 #endif /* def HAVE_NANOSLEEP */
854
855 }
856
857
858 /*********************************************************************
859  *
860  * Function    :  privoxy_gmtime_r
861  *
862  * Description :  Behave like gmtime_r() and convert a
863  *                time_t to a struct tm.
864  *
865  * Parameters  :
866  *          1  :  time_spec: The time to convert
867  *          2  :  result: The struct tm to use as storage
868  *
869  * Returns     :  Pointer to the result or NULL on error.
870  *
871  *********************************************************************/
872 struct tm *privoxy_gmtime_r(const time_t *time_spec, struct tm *result)
873 {
874    struct tm *timeptr;
875
876 #ifdef HAVE_GMTIME_R
877    timeptr = gmtime_r(time_spec, result);
878 #elif defined(MUTEX_LOCKS_AVAILABLE)
879    privoxy_mutex_lock(&gmtime_mutex);
880    timeptr = gmtime(time_spec);
881 #else
882 #warning Using unlocked gmtime()
883    timeptr = gmtime(time_spec);
884 #endif
885
886    if (timeptr == NULL)
887    {
888 #if !defined(HAVE_GMTIME_R) && defined(MUTEX_LOCKS_AVAILABLE)
889       privoxy_mutex_unlock(&gmtime_mutex);
890 #endif
891       return NULL;
892    }
893
894 #if !defined(HAVE_GMTIME_R)
895    *result = *timeptr;
896    timeptr = result;
897 #ifdef MUTEX_LOCKS_AVAILABLE
898    privoxy_mutex_unlock(&gmtime_mutex);
899 #endif
900 #endif
901
902    return timeptr;
903 }
904
905 #if !defined(HAVE_TIMEGM) && defined(HAVE_TZSET) && defined(HAVE_PUTENV)
906 /*********************************************************************
907  *
908  * Function    :  timegm
909  *
910  * Description :  libc replacement function for the inverse of gmtime().
911  *                Copyright (C) 2004 Free Software Foundation, Inc.
912  *
913  *                Code originally copied from GnuPG, modifications done
914  *                for Privoxy: style changed, #ifdefs for _WIN32 added
915  *                to have it work on mingw32.
916  *
917  *                XXX: It's very unlikely to happen, but if the malloc()
918  *                call fails the time zone will be permanently set to UTC.
919  *
920  * Parameters  :
921  *          1  :  tm: Broken-down time struct.
922  *
923  * Returns     :  tm converted into time_t seconds.
924  *
925  *********************************************************************/
926 time_t timegm(struct tm *tm)
927 {
928    time_t answer;
929    char *zone;
930
931    zone = getenv("TZ");
932    putenv("TZ=UTC");
933    tzset();
934    answer = mktime(tm);
935    if (zone)
936    {
937       char *old_zone;
938
939       old_zone = malloc(3 + strlen(zone) + 1);
940       if (old_zone)
941       {
942          strcpy(old_zone, "TZ=");
943          strcat(old_zone, zone);
944          putenv(old_zone);
945 #ifdef _WIN32
946          /* http://man7.org/linux/man-pages/man3/putenv.3.html
947           *   int putenv(char *string);
948           *     The string pointed to by string becomes part of the environment, so altering the
949           *     string changes the environment.
950           * In other words, the memory pointed to by *string is used until
951           *   a) another call to putenv() with the same e-var name
952           *   b) the program exits
953           *
954           * Windows e-vars don't work that way, so let's not leak memory.
955           */
956          free(old_zone);
957 #endif /* def _WIN32 */
958       }
959    }
960    else
961    {
962 #ifdef HAVE_UNSETENV
963       unsetenv("TZ");
964 #elif defined(_WIN32)
965       putenv("TZ=");
966 #else
967       putenv("TZ");
968 #endif
969    }
970    tzset();
971
972    return answer;
973 }
974 #endif /* !defined(HAVE_TIMEGM) && defined(HAVE_TZSET) && defined(HAVE_PUTENV) */
975
976
977 #ifndef HAVE_SNPRINTF
978 /*
979  * What follows is a portable snprintf routine, written by Mark Martinec.
980  * See: http://www.ijs.si/software/snprintf/
981
982                                   snprintf.c
983                    - a portable implementation of snprintf,
984        including vsnprintf.c, asnprintf, vasnprintf, asprintf, vasprintf
985
986    snprintf is a routine to convert numeric and string arguments to
987    formatted strings. It is similar to sprintf(3) provided in a system's
988    C library, yet it requires an additional argument - the buffer size -
989    and it guarantees never to store anything beyond the given buffer,
990    regardless of the format or arguments to be formatted. Some newer
991    operating systems do provide snprintf in their C library, but many do
992    not or do provide an inadequate (slow or idiosyncratic) version, which
993    calls for a portable implementation of this routine.
994
995 Author
996
997    Mark Martinec <mark.martinec@ijs.si>, April 1999, June 2000
998    Copyright Â© 1999, Mark Martinec
999
1000  */
1001
1002 #define PORTABLE_SNPRINTF_VERSION_MAJOR 2
1003 #define PORTABLE_SNPRINTF_VERSION_MINOR 2
1004
1005 #if defined(NEED_ASPRINTF) || defined(NEED_ASNPRINTF) || defined(NEED_VASPRINTF) || defined(NEED_VASNPRINTF)
1006 # if defined(NEED_SNPRINTF_ONLY)
1007 # undef NEED_SNPRINTF_ONLY
1008 # endif
1009 # if !defined(PREFER_PORTABLE_SNPRINTF)
1010 # define PREFER_PORTABLE_SNPRINTF
1011 # endif
1012 #endif
1013
1014 #if defined(SOLARIS_BUG_COMPATIBLE) && !defined(SOLARIS_COMPATIBLE)
1015 #define SOLARIS_COMPATIBLE
1016 #endif
1017
1018 #if defined(HPUX_BUG_COMPATIBLE) && !defined(HPUX_COMPATIBLE)
1019 #define HPUX_COMPATIBLE
1020 #endif
1021
1022 #if defined(DIGITAL_UNIX_BUG_COMPATIBLE) && !defined(DIGITAL_UNIX_COMPATIBLE)
1023 #define DIGITAL_UNIX_COMPATIBLE
1024 #endif
1025
1026 #if defined(PERL_BUG_COMPATIBLE) && !defined(PERL_COMPATIBLE)
1027 #define PERL_COMPATIBLE
1028 #endif
1029
1030 #if defined(LINUX_BUG_COMPATIBLE) && !defined(LINUX_COMPATIBLE)
1031 #define LINUX_COMPATIBLE
1032 #endif
1033
1034 #include <sys/types.h>
1035 #include <string.h>
1036 #include <stdlib.h>
1037 #include <stdio.h>
1038 #include <stdarg.h>
1039 #include <assert.h>
1040 #include <errno.h>
1041
1042 #ifdef isdigit
1043 #undef isdigit
1044 #endif
1045 #define isdigit(c) ((c) >= '0' && (c) <= '9')
1046
1047 /* For copying strings longer or equal to 'breakeven_point'
1048  * it is more efficient to call memcpy() than to do it inline.
1049  * The value depends mostly on the processor architecture,
1050  * but also on the compiler and its optimization capabilities.
1051  * The value is not critical, some small value greater than zero
1052  * will be just fine if you don't care to squeeze every drop
1053  * of performance out of the code.
1054  *
1055  * Small values favor memcpy, large values favor inline code.
1056  */
1057 #if defined(__alpha__) || defined(__alpha)
1058 #  define breakeven_point   2    /* AXP (DEC Alpha)     - gcc or cc or egcs */
1059 #endif
1060 #if defined(__i386__)  || defined(__i386)
1061 #  define breakeven_point  12    /* Intel Pentium/Linux - gcc 2.96 */
1062 #endif
1063 #if defined(__hppa)
1064 #  define breakeven_point  10    /* HP-PA               - gcc */
1065 #endif
1066 #if defined(__sparc__) || defined(__sparc)
1067 #  define breakeven_point  33    /* Sun Sparc 5         - gcc 2.8.1 */
1068 #endif
1069
1070 /* some other values of possible interest: */
1071 /* #define breakeven_point  8 */ /* VAX 4000          - vaxc */
1072 /* #define breakeven_point 19 */ /* VAX 4000          - gcc 2.7.0 */
1073
1074 #ifndef breakeven_point
1075 #  define breakeven_point   6    /* some reasonable one-size-fits-all value */
1076 #endif
1077
1078 #define fast_memcpy(d,s,n) \
1079   { register size_t nn = (size_t)(n); \
1080     if (nn >= breakeven_point) memcpy((d), (s), nn); \
1081     else if (nn > 0) { /* proc call overhead is worth only for large strings*/\
1082       register char *dd; register const char *ss; \
1083       for (ss=(s), dd=(d); nn>0; nn--) *dd++ = *ss++; } }
1084
1085 #define fast_memset(d,c,n) \
1086   { register size_t nn = (size_t)(n); \
1087     if (nn >= breakeven_point) memset((d), (int)(c), nn); \
1088     else if (nn > 0) { /* proc call overhead is worth only for large strings*/\
1089       register char *dd; register const int cc=(int)(c); \
1090       for (dd=(d); nn>0; nn--) *dd++ = cc; } }
1091
1092 /* prototypes */
1093
1094 #if defined(NEED_ASPRINTF)
1095 int asprintf   (char **ptr, const char *fmt, /*args*/ ...);
1096 #endif
1097 #if defined(NEED_VASPRINTF)
1098 int vasprintf  (char **ptr, const char *fmt, va_list ap);
1099 #endif
1100 #if defined(NEED_ASNPRINTF)
1101 int asnprintf  (char **ptr, size_t str_m, const char *fmt, /*args*/ ...);
1102 #endif
1103 #if defined(NEED_VASNPRINTF)
1104 int vasnprintf (char **ptr, size_t str_m, const char *fmt, va_list ap);
1105 #endif
1106
1107 #if defined(HAVE_SNPRINTF)
1108 /* declare our portable snprintf  routine under name portable_snprintf  */
1109 /* declare our portable vsnprintf routine under name portable_vsnprintf */
1110 #else
1111 /* declare our portable routines under names snprintf and vsnprintf */
1112 #define portable_snprintf snprintf
1113 #if !defined(NEED_SNPRINTF_ONLY)
1114 #define portable_vsnprintf vsnprintf
1115 #endif
1116 #endif
1117
1118 #if !defined(HAVE_SNPRINTF) || defined(PREFER_PORTABLE_SNPRINTF)
1119 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...);
1120 #if !defined(NEED_SNPRINTF_ONLY)
1121 int portable_vsnprintf(char *str, size_t str_m, const char *fmt, va_list ap);
1122 #endif
1123 #endif
1124
1125 /* declarations */
1126
1127 static char credits[] = "\n\
1128 @(#)snprintf.c, v2.2: Mark Martinec, <mark.martinec@ijs.si>\n\
1129 @(#)snprintf.c, v2.2: Copyright 1999, Mark Martinec. Frontier Artistic License applies.\n\
1130 @(#)snprintf.c, v2.2: http://www.ijs.si/software/snprintf/\n";
1131
1132 #if defined(NEED_ASPRINTF)
1133 int asprintf(char **ptr, const char *fmt, /*args*/ ...) {
1134   va_list ap;
1135   size_t str_m;
1136   int str_l;
1137
1138   *ptr = NULL;
1139   va_start(ap, fmt);                            /* measure the required size */
1140   str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap);
1141   va_end(ap);
1142   assert(str_l >= 0);        /* possible integer overflow if str_m > INT_MAX */
1143   *ptr = (char *) malloc(str_m = (size_t)str_l + 1);
1144   if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1145   else {
1146     int str_l2;
1147     va_start(ap, fmt);
1148     str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1149     va_end(ap);
1150     assert(str_l2 == str_l);
1151   }
1152   return str_l;
1153 }
1154 #endif
1155
1156 #if defined(NEED_VASPRINTF)
1157 int vasprintf(char **ptr, const char *fmt, va_list ap) {
1158   size_t str_m;
1159   int str_l;
1160
1161   *ptr = NULL;
1162   { va_list ap2;
1163     va_copy(ap2, ap);  /* don't consume the original ap, we'll need it again */
1164     str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap2);/*get required size*/
1165     va_end(ap2);
1166   }
1167   assert(str_l >= 0);        /* possible integer overflow if str_m > INT_MAX */
1168   *ptr = (char *) malloc(str_m = (size_t)str_l + 1);
1169   if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1170   else {
1171     int str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1172     assert(str_l2 == str_l);
1173   }
1174   return str_l;
1175 }
1176 #endif
1177
1178 #if defined(NEED_ASNPRINTF)
1179 int asnprintf (char **ptr, size_t str_m, const char *fmt, /*args*/ ...) {
1180   va_list ap;
1181   int str_l;
1182
1183   *ptr = NULL;
1184   va_start(ap, fmt);                            /* measure the required size */
1185   str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap);
1186   va_end(ap);
1187   assert(str_l >= 0);        /* possible integer overflow if str_m > INT_MAX */
1188   if ((size_t)str_l + 1 < str_m) str_m = (size_t)str_l + 1;      /* truncate */
1189   /* if str_m is 0, no buffer is allocated, just set *ptr to NULL */
1190   if (str_m == 0) {  /* not interested in resulting string, just return size */
1191   } else {
1192     *ptr = (char *) malloc(str_m);
1193     if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1194     else {
1195       int str_l2;
1196       va_start(ap, fmt);
1197       str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1198       va_end(ap);
1199       assert(str_l2 == str_l);
1200     }
1201   }
1202   return str_l;
1203 }
1204 #endif
1205
1206 #if defined(NEED_VASNPRINTF)
1207 int vasnprintf (char **ptr, size_t str_m, const char *fmt, va_list ap) {
1208   int str_l;
1209
1210   *ptr = NULL;
1211   { va_list ap2;
1212     va_copy(ap2, ap);  /* don't consume the original ap, we'll need it again */
1213     str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap2);/*get required size*/
1214     va_end(ap2);
1215   }
1216   assert(str_l >= 0);        /* possible integer overflow if str_m > INT_MAX */
1217   if ((size_t)str_l + 1 < str_m) str_m = (size_t)str_l + 1;      /* truncate */
1218   /* if str_m is 0, no buffer is allocated, just set *ptr to NULL */
1219   if (str_m == 0) {  /* not interested in resulting string, just return size */
1220   } else {
1221     *ptr = (char *) malloc(str_m);
1222     if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1223     else {
1224       int str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1225       assert(str_l2 == str_l);
1226     }
1227   }
1228   return str_l;
1229 }
1230 #endif
1231
1232 /*
1233  * If the system does have snprintf and the portable routine is not
1234  * specifically required, this module produces no code for snprintf/vsnprintf.
1235  */
1236 #if !defined(HAVE_SNPRINTF) || defined(PREFER_PORTABLE_SNPRINTF)
1237
1238 #if !defined(NEED_SNPRINTF_ONLY)
1239 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...) {
1240   va_list ap;
1241   int str_l;
1242
1243   va_start(ap, fmt);
1244   str_l = portable_vsnprintf(str, str_m, fmt, ap);
1245   va_end(ap);
1246   return str_l;
1247 }
1248 #endif
1249
1250 #if defined(NEED_SNPRINTF_ONLY)
1251 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...) {
1252 #else
1253 int portable_vsnprintf(char *str, size_t str_m, const char *fmt, va_list ap) {
1254 #endif
1255
1256 #if defined(NEED_SNPRINTF_ONLY)
1257   va_list ap;
1258 #endif
1259   size_t str_l = 0;
1260   const char *p = fmt;
1261
1262 /* In contrast with POSIX, the ISO C99 now says
1263  * that str can be NULL and str_m can be 0.
1264  * This is more useful than the old:  if (str_m < 1) return -1; */
1265
1266 #if defined(NEED_SNPRINTF_ONLY)
1267   va_start(ap, fmt);
1268 #endif
1269   if (!p) p = "";
1270   while (*p) {
1271     if (*p != '%') {
1272    /* if (str_l < str_m) str[str_l++] = *p++;    -- this would be sufficient */
1273    /* but the following code achieves better performance for cases
1274     * where format string is long and contains few conversions */
1275       const char *q = strchr(p+1,'%');
1276       size_t n = !q ? strlen(p) : (q-p);
1277       if (str_l < str_m) {
1278         size_t avail = str_m-str_l;
1279         fast_memcpy(str+str_l, p, (n>avail?avail:n));
1280       }
1281       p += n; str_l += n;
1282     } else {
1283       const char *starting_p;
1284       size_t min_field_width = 0, precision = 0;
1285       int zero_padding = 0, precision_specified = 0, justify_left = 0;
1286       int alternate_form = 0, force_sign = 0;
1287       int space_for_positive = 1; /* If both the ' ' and '+' flags appear,
1288                                      the ' ' flag should be ignored. */
1289       char length_modifier = '\0';            /* allowed values: \0, h, l, L */
1290       char tmp[32];/* temporary buffer for simple numeric->string conversion */
1291
1292       const char *str_arg;      /* string address in case of string argument */
1293       size_t str_arg_l;         /* natural field width of arg without padding
1294                                    and sign */
1295       unsigned char uchar_arg;
1296         /* unsigned char argument value - only defined for c conversion.
1297            N.B. standard explicitly states the char argument for
1298            the c conversion is unsigned */
1299
1300       size_t number_of_zeros_to_pad = 0;
1301         /* number of zeros to be inserted for numeric conversions
1302            as required by the precision or minimal field width */
1303
1304       size_t zero_padding_insertion_ind = 0;
1305         /* index into tmp where zero padding is to be inserted */
1306
1307       char fmt_spec = '\0';
1308         /* current conversion specifier character */
1309
1310       str_arg = credits;/* just to make compiler happy (defined but not used)*/
1311       str_arg = NULL;
1312       starting_p = p; p++;  /* skip '%' */
1313    /* parse flags */
1314       while (*p == '0' || *p == '-' || *p == '+' ||
1315              *p == ' ' || *p == '#' || *p == '\'') {
1316         switch (*p) {
1317         case '0': zero_padding = 1; break;
1318         case '-': justify_left = 1; break;
1319         case '+': force_sign = 1; space_for_positive = 0; break;
1320         case ' ': force_sign = 1;
1321      /* If both the ' ' and '+' flags appear, the ' ' flag should be ignored */
1322 #ifdef PERL_COMPATIBLE
1323      /* ... but in Perl the last of ' ' and '+' applies */
1324                   space_for_positive = 1;
1325 #endif
1326                   break;
1327         case '#': alternate_form = 1; break;
1328         case '\'': break;
1329         }
1330         p++;
1331       }
1332    /* If the '0' and '-' flags both appear, the '0' flag should be ignored. */
1333
1334    /* parse field width */
1335       if (*p == '*') {
1336         int j;
1337         p++; j = va_arg(ap, int);
1338         if (j >= 0) min_field_width = j;
1339         else { min_field_width = -j; justify_left = 1; }
1340       } else if (isdigit((int)(*p))) {
1341         /* size_t could be wider than unsigned int;
1342            make sure we treat argument like common implementations do */
1343         unsigned int uj = *p++ - '0';
1344         while (isdigit((int)(*p))) uj = 10*uj + (unsigned int)(*p++ - '0');
1345         min_field_width = uj;
1346       }
1347    /* parse precision */
1348       if (*p == '.') {
1349         p++; precision_specified = 1;
1350         if (*p == '*') {
1351           int j = va_arg(ap, int);
1352           p++;
1353           if (j >= 0) precision = j;
1354           else {
1355             precision_specified = 0; precision = 0;
1356          /* NOTE:
1357           *   Solaris 2.6 man page claims that in this case the precision
1358           *   should be set to 0.  Digital Unix 4.0, HPUX 10 and BSD man page
1359           *   claim that this case should be treated as unspecified precision,
1360           *   which is what we do here.
1361           */
1362           }
1363         } else if (isdigit((int)(*p))) {
1364           /* size_t could be wider than unsigned int;
1365              make sure we treat argument like common implementations do */
1366           unsigned int uj = *p++ - '0';
1367           while (isdigit((int)(*p))) uj = 10*uj + (unsigned int)(*p++ - '0');
1368           precision = uj;
1369         }
1370       }
1371    /* parse 'h', 'l' and 'll' length modifiers */
1372       if (*p == 'h' || *p == 'l') {
1373         length_modifier = *p; p++;
1374         if (length_modifier == 'l' && *p == 'l') {   /* double l = long long */
1375 #ifdef SNPRINTF_LONGLONG_SUPPORT
1376           length_modifier = '2';                  /* double l encoded as '2' */
1377 #else
1378           length_modifier = 'l';                 /* treat it as a single 'l' */
1379 #endif
1380           p++;
1381         }
1382       }
1383       fmt_spec = *p;
1384    /* common synonyms: */
1385       switch (fmt_spec) {
1386       case 'i': fmt_spec = 'd'; break;
1387       case 'D': fmt_spec = 'd'; length_modifier = 'l'; break;
1388       case 'U': fmt_spec = 'u'; length_modifier = 'l'; break;
1389       case 'O': fmt_spec = 'o'; length_modifier = 'l'; break;
1390       default: break;
1391       }
1392    /* get parameter value, do initial processing */
1393       switch (fmt_spec) {
1394       case '%': /* % behaves similar to 's' regarding flags and field widths */
1395       case 'c': /* c behaves similar to 's' regarding flags and field widths */
1396       case 's':
1397         length_modifier = '\0';          /* wint_t and wchar_t not supported */
1398      /* the result of zero padding flag with non-numeric conversion specifier*/
1399      /* is undefined. Solaris and HPUX 10 does zero padding in this case,    */
1400      /* Digital Unix and Linux does not. */
1401 #if !defined(SOLARIS_COMPATIBLE) && !defined(HPUX_COMPATIBLE)
1402         zero_padding = 0;    /* turn zero padding off for string conversions */
1403 #endif
1404         str_arg_l = 1;
1405         switch (fmt_spec) {
1406         case '%':
1407           str_arg = p; break;
1408         case 'c': {
1409           int j = va_arg(ap, int);
1410           uchar_arg = (unsigned char) j;   /* standard demands unsigned char */
1411           str_arg = (const char *) &uchar_arg;
1412           break;
1413         }
1414         case 's':
1415           str_arg = va_arg(ap, const char *);
1416           if (!str_arg) str_arg_l = 0;
1417        /* make sure not to address string beyond the specified precision !!! */
1418           else if (!precision_specified) str_arg_l = strlen(str_arg);
1419        /* truncate string if necessary as requested by precision */
1420           else if (precision == 0) str_arg_l = 0;
1421           else {
1422        /* memchr on HP does not like n > 2^31  !!! */
1423             const char *q = memchr(str_arg, '\0',
1424                              precision <= 0x7fffffff ? precision : 0x7fffffff);
1425             str_arg_l = !q ? precision : (q-str_arg);
1426           }
1427           break;
1428         default: break;
1429         }
1430         break;
1431       case 'd': case 'u': case 'o': case 'x': case 'X': case 'p': {
1432         /* NOTE: the u, o, x, X and p conversion specifiers imply
1433                  the value is unsigned;  d implies a signed value */
1434
1435         int arg_sign = 0;
1436           /* 0 if numeric argument is zero (or if pointer is NULL for 'p'),
1437             +1 if greater than zero (or nonzero for unsigned arguments),
1438             -1 if negative (unsigned argument is never negative) */
1439
1440         int int_arg = 0;  unsigned int uint_arg = 0;
1441           /* only defined for length modifier h, or for no length modifiers */
1442
1443         long int long_arg = 0;  unsigned long int ulong_arg = 0;
1444           /* only defined for length modifier l */
1445
1446         void *ptr_arg = NULL;
1447           /* pointer argument value -only defined for p conversion */
1448
1449 #ifdef SNPRINTF_LONGLONG_SUPPORT
1450         long long int long_long_arg = 0;
1451         unsigned long long int ulong_long_arg = 0;
1452           /* only defined for length modifier ll */
1453 #endif
1454         if (fmt_spec == 'p') {
1455         /* HPUX 10: An l, h, ll or L before any other conversion character
1456          *   (other than d, i, u, o, x, or X) is ignored.
1457          * Digital Unix:
1458          *   not specified, but seems to behave as HPUX does.
1459          * Solaris: If an h, l, or L appears before any other conversion
1460          *   specifier (other than d, i, u, o, x, or X), the behavior
1461          *   is undefined. (Actually %hp converts only 16-bits of address
1462          *   and %llp treats address as 64-bit data which is incompatible
1463          *   with (void *) argument on a 32-bit system).
1464          */
1465 #ifdef SOLARIS_COMPATIBLE
1466 #  ifdef SOLARIS_BUG_COMPATIBLE
1467           /* keep length modifiers even if it represents 'll' */
1468 #  else
1469           if (length_modifier == '2') length_modifier = '\0';
1470 #  endif
1471 #else
1472           length_modifier = '\0';
1473 #endif
1474           ptr_arg = va_arg(ap, void *);
1475           if (ptr_arg != NULL) arg_sign = 1;
1476         } else if (fmt_spec == 'd') {  /* signed */
1477           switch (length_modifier) {
1478           case '\0':
1479           case 'h':
1480          /* It is non-portable to specify a second argument of char or short
1481           * to va_arg, because arguments seen by the called function
1482           * are not char or short.  C converts char and short arguments
1483           * to int before passing them to a function.
1484           */
1485             int_arg = va_arg(ap, int);
1486             if      (int_arg > 0) arg_sign =  1;
1487             else if (int_arg < 0) arg_sign = -1;
1488             break;
1489           case 'l':
1490             long_arg = va_arg(ap, long int);
1491             if      (long_arg > 0) arg_sign =  1;
1492             else if (long_arg < 0) arg_sign = -1;
1493             break;
1494 #ifdef SNPRINTF_LONGLONG_SUPPORT
1495           case '2':
1496             long_long_arg = va_arg(ap, long long int);
1497             if      (long_long_arg > 0) arg_sign =  1;
1498             else if (long_long_arg < 0) arg_sign = -1;
1499             break;
1500 #endif
1501           }
1502         } else {  /* unsigned */
1503           switch (length_modifier) {
1504           case '\0':
1505           case 'h':
1506             uint_arg = va_arg(ap, unsigned int);
1507             if (uint_arg) arg_sign = 1;
1508             break;
1509           case 'l':
1510             ulong_arg = va_arg(ap, unsigned long int);
1511             if (ulong_arg) arg_sign = 1;
1512             break;
1513 #ifdef SNPRINTF_LONGLONG_SUPPORT
1514           case '2':
1515             ulong_long_arg = va_arg(ap, unsigned long long int);
1516             if (ulong_long_arg) arg_sign = 1;
1517             break;
1518 #endif
1519           }
1520         }
1521         str_arg = tmp; str_arg_l = 0;
1522      /* NOTE:
1523       *   For d, i, u, o, x, and X conversions, if precision is specified,
1524       *   the '0' flag should be ignored. This is so with Solaris 2.6,
1525       *   Digital UNIX 4.0, HPUX 10, Linux, FreeBSD, NetBSD; but not with Perl.
1526       */
1527 #ifndef PERL_COMPATIBLE
1528         if (precision_specified) zero_padding = 0;
1529 #endif
1530         if (fmt_spec == 'd') {
1531           if (force_sign && arg_sign >= 0)
1532             tmp[str_arg_l++] = space_for_positive ? ' ' : '+';
1533          /* leave negative numbers for sprintf to handle,
1534             to avoid handling tricky cases like (short int)(-32768) */
1535 #ifdef LINUX_COMPATIBLE
1536         } else if (fmt_spec == 'p' && force_sign && arg_sign > 0) {
1537           tmp[str_arg_l++] = space_for_positive ? ' ' : '+';
1538 #endif
1539         } else if (alternate_form) {
1540           if (arg_sign != 0 && (fmt_spec == 'x' || fmt_spec == 'X') )
1541             { tmp[str_arg_l++] = '0'; tmp[str_arg_l++] = fmt_spec; }
1542          /* alternate form should have no effect for p conversion, but ... */
1543 #ifdef HPUX_COMPATIBLE
1544           else if (fmt_spec == 'p'
1545          /* HPUX 10: for an alternate form of p conversion,
1546           *          a nonzero result is prefixed by 0x. */
1547 #ifndef HPUX_BUG_COMPATIBLE
1548          /* Actually it uses 0x prefix even for a zero value. */
1549                    && arg_sign != 0
1550 #endif
1551                   ) { tmp[str_arg_l++] = '0'; tmp[str_arg_l++] = 'x'; }
1552 #endif
1553         }
1554         zero_padding_insertion_ind = str_arg_l;
1555         if (!precision_specified) precision = 1;   /* default precision is 1 */
1556         if (precision == 0 && arg_sign == 0
1557 #if defined(HPUX_BUG_COMPATIBLE) || defined(LINUX_COMPATIBLE)
1558             && fmt_spec != 'p'
1559          /* HPUX 10 man page claims: With conversion character p the result of
1560           * converting a zero value with a precision of zero is a null string.
1561           * Actually HP returns all zeroes, and Linux returns "(nil)". */
1562 #endif
1563         ) {
1564          /* converted to null string */
1565          /* When zero value is formatted with an explicit precision 0,
1566             the resulting formatted string is empty (d, i, u, o, x, X, p).   */
1567         } else {
1568           char f[5]; int f_l = 0;
1569           f[f_l++] = '%';    /* construct a simple format string for sprintf */
1570           if (!length_modifier) { }
1571           else if (length_modifier=='2') { f[f_l++] = 'l'; f[f_l++] = 'l'; }
1572           else f[f_l++] = length_modifier;
1573           f[f_l++] = fmt_spec; f[f_l++] = '\0';
1574           if (fmt_spec == 'p') str_arg_l += sprintf(tmp+str_arg_l, f, ptr_arg);
1575           else if (fmt_spec == 'd') {  /* signed */
1576             switch (length_modifier) {
1577             case '\0':
1578             case 'h': str_arg_l+=sprintf(tmp+str_arg_l, f, int_arg);  break;
1579             case 'l': str_arg_l+=sprintf(tmp+str_arg_l, f, long_arg); break;
1580 #ifdef SNPRINTF_LONGLONG_SUPPORT
1581             case '2': str_arg_l+=sprintf(tmp+str_arg_l,f,long_long_arg); break;
1582 #endif
1583             }
1584           } else {  /* unsigned */
1585             switch (length_modifier) {
1586             case '\0':
1587             case 'h': str_arg_l+=sprintf(tmp+str_arg_l, f, uint_arg);  break;
1588             case 'l': str_arg_l+=sprintf(tmp+str_arg_l, f, ulong_arg); break;
1589 #ifdef SNPRINTF_LONGLONG_SUPPORT
1590             case '2': str_arg_l+=sprintf(tmp+str_arg_l,f,ulong_long_arg);break;
1591 #endif
1592             }
1593           }
1594          /* include the optional minus sign and possible "0x"
1595             in the region before the zero padding insertion point */
1596           if (zero_padding_insertion_ind < str_arg_l &&
1597               tmp[zero_padding_insertion_ind] == '-') {
1598             zero_padding_insertion_ind++;
1599           }
1600           if (zero_padding_insertion_ind+1 < str_arg_l &&
1601               tmp[zero_padding_insertion_ind]   == '0' &&
1602              (tmp[zero_padding_insertion_ind+1] == 'x' ||
1603               tmp[zero_padding_insertion_ind+1] == 'X') ) {
1604             zero_padding_insertion_ind += 2;
1605           }
1606         }
1607         { size_t num_of_digits = str_arg_l - zero_padding_insertion_ind;
1608           if (alternate_form && fmt_spec == 'o'
1609 #ifdef HPUX_COMPATIBLE                                  /* ("%#.o",0) -> ""  */
1610               && (str_arg_l > 0)
1611 #endif
1612 #ifdef DIGITAL_UNIX_BUG_COMPATIBLE                      /* ("%#o",0) -> "00" */
1613 #else
1614               /* unless zero is already the first character */
1615               && !(zero_padding_insertion_ind < str_arg_l
1616                    && tmp[zero_padding_insertion_ind] == '0')
1617 #endif
1618           ) {        /* assure leading zero for alternate-form octal numbers */
1619             if (!precision_specified || precision < num_of_digits+1) {
1620              /* precision is increased to force the first character to be zero,
1621                 except if a zero value is formatted with an explicit precision
1622                 of zero */
1623               precision = num_of_digits+1; precision_specified = 1;
1624             }
1625           }
1626        /* zero padding to specified precision? */
1627           if (num_of_digits < precision)
1628             number_of_zeros_to_pad = precision - num_of_digits;
1629         }
1630      /* zero padding to specified minimal field width? */
1631         if (!justify_left && zero_padding) {
1632           int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
1633           if (n > 0) number_of_zeros_to_pad += n;
1634         }
1635         break;
1636       }
1637       default: /* unrecognized conversion specifier, keep format string as-is*/
1638         zero_padding = 0;  /* turn zero padding off for non-numeric convers. */
1639 #ifndef DIGITAL_UNIX_COMPATIBLE
1640         justify_left = 1; min_field_width = 0;                /* reset flags */
1641 #endif
1642 #if defined(PERL_COMPATIBLE) || defined(LINUX_COMPATIBLE)
1643      /* keep the entire format string unchanged */
1644         str_arg = starting_p; str_arg_l = p - starting_p;
1645      /* well, not exactly so for Linux, which does something between,
1646       * and I don't feel an urge to imitate it: "%+++++hy" -> "%+y"  */
1647 #else
1648      /* discard the unrecognized conversion, just keep *
1649       * the unrecognized conversion character          */
1650         str_arg = p; str_arg_l = 0;
1651 #endif
1652         if (*p) str_arg_l++;  /* include invalid conversion specifier unchanged
1653                                  if not at end-of-string */
1654         break;
1655       }
1656       if (*p) p++;      /* step over the just processed conversion specifier */
1657    /* insert padding to the left as requested by min_field_width;
1658       this does not include the zero padding in case of numerical conversions*/
1659       if (!justify_left) {                /* left padding with blank or zero */
1660         int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
1661         if (n > 0) {
1662           if (str_l < str_m) {
1663             size_t avail = str_m-str_l;
1664             fast_memset(str+str_l, (zero_padding?'0':' '), (n>avail?avail:n));
1665           }
1666           str_l += n;
1667         }
1668       }
1669    /* zero padding as requested by the precision or by the minimal field width
1670     * for numeric conversions required? */
1671       if (number_of_zeros_to_pad <= 0) {
1672      /* will not copy first part of numeric right now, *
1673       * force it to be copied later in its entirety    */
1674         zero_padding_insertion_ind = 0;
1675       } else {
1676      /* insert first part of numerics (sign or '0x') before zero padding */
1677         int n = zero_padding_insertion_ind;
1678         if (n > 0) {
1679           if (str_l < str_m) {
1680             size_t avail = str_m-str_l;
1681             fast_memcpy(str+str_l, str_arg, (n>avail?avail:n));
1682           }
1683           str_l += n;
1684         }
1685      /* insert zero padding as requested by the precision or min field width */
1686         n = number_of_zeros_to_pad;
1687         if (n > 0) {
1688           if (str_l < str_m) {
1689             size_t avail = str_m-str_l;
1690             fast_memset(str+str_l, '0', (n>avail?avail:n));
1691           }
1692           str_l += n;
1693         }
1694       }
1695    /* insert formatted string
1696     * (or as-is conversion specifier for unknown conversions) */
1697       { int n = str_arg_l - zero_padding_insertion_ind;
1698         if (n > 0) {
1699           if (str_l < str_m) {
1700             size_t avail = str_m-str_l;
1701             fast_memcpy(str+str_l, str_arg+zero_padding_insertion_ind,
1702                         (n>avail?avail:n));
1703           }
1704           str_l += n;
1705         }
1706       }
1707    /* insert right padding */
1708       if (justify_left) {          /* right blank padding to the field width */
1709         int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
1710         if (n > 0) {
1711           if (str_l < str_m) {
1712             size_t avail = str_m-str_l;
1713             fast_memset(str+str_l, ' ', (n>avail?avail:n));
1714           }
1715           str_l += n;
1716         }
1717       }
1718     }
1719   }
1720 #if defined(NEED_SNPRINTF_ONLY)
1721   va_end(ap);
1722 #endif
1723   if (str_m > 0) { /* make sure the string is null-terminated
1724                       even at the expense of overwriting the last character
1725                       (shouldn't happen, but just in case) */
1726     str[str_l <= str_m-1 ? str_l : str_m-1] = '\0';
1727   }
1728   /* Return the number of characters formatted (excluding trailing null
1729    * character), that is, the number of characters that would have been
1730    * written to the buffer if it were large enough.
1731    *
1732    * The value of str_l should be returned, but str_l is of unsigned type
1733    * size_t, and snprintf is int, possibly leading to an undetected
1734    * integer overflow, resulting in a negative return value, which is illegal.
1735    * Both XSH5 and ISO C99 (at least the draft) are silent on this issue.
1736    * Should errno be set to EOVERFLOW and EOF returned in this case???
1737    */
1738   return (int) str_l;
1739 }
1740 #endif
1741 #endif /* ndef HAVE_SNPRINTF */
1742 /*
1743   Local Variables:
1744   tab-width: 3
1745   end:
1746 */