1 /* Copyright (c) 2003, Roger Dingledine
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2015, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
8 * \brief Common functions for strings, IO, network, data structures,
12 /* This is required on rh7 to make strptime not complain.
25 #include "container.h"
28 #include "backtrace.h"
29 #include "util_process.h"
30 #include "util_format.h"
44 /* math.h needs this on Linux */
46 #define _USE_ISOC99_ 1
55 #ifdef HAVE_NETINET_IN_H
56 #include <netinet/in.h>
58 #ifdef HAVE_ARPA_INET_H
59 #include <arpa/inet.h>
64 #ifdef HAVE_SYS_SOCKET_H
65 #include <sys/socket.h>
67 #ifdef HAVE_SYS_TIME_H
73 #ifdef HAVE_SYS_STAT_H
76 #ifdef HAVE_SYS_FCNTL_H
77 #include <sys/fcntl.h>
82 #ifdef HAVE_MALLOC_MALLOC_H
83 #include <malloc/malloc.h>
86 #if !defined(OPENBSD) && !defined(__FreeBSD__)
87 /* OpenBSD has a malloc.h, but for our purposes, it only exists in order to
88 * scold us for being so stupid as to autodetect its presence. To be fair,
89 * they've done this since 1996, when autoconf was only 5 years old. */
93 #ifdef HAVE_MALLOC_NP_H
94 #include <malloc_np.h>
96 #ifdef HAVE_SYS_WAIT_H
99 #if defined(HAVE_SYS_PRCTL_H) && defined(__linux__)
100 #include <sys/prctl.h>
103 #ifdef __clang_analyzer__
104 #undef MALLOC_ZERO_WORKS
110 /** Helper for tor_assert: report the assertion failure. */
112 tor_assertion_failed_(const char *fname
, unsigned int line
,
113 const char *func
, const char *expr
)
116 log_err(LD_BUG
, "%s:%u: %s: Assertion %s failed; aborting.",
117 fname
, line
, func
, expr
);
118 tor_snprintf(buf
, sizeof(buf
),
119 "Assertion %s failed in %s at %s:%u",
120 expr
, func
, fname
, line
);
121 log_backtrace(LOG_ERR
, LD_BUG
, buf
);
130 /* Macro to pass the extra dmalloc args to another function. */
131 #define DMALLOC_FN_ARGS , file, line
133 #if defined(HAVE_DMALLOC_STRDUP)
134 /* the dmalloc_strdup should be fine as defined */
135 #elif defined(HAVE_DMALLOC_STRNDUP)
136 #define dmalloc_strdup(file, line, string, xalloc_b) \
137 dmalloc_strndup(file, line, (string), -1, xalloc_b)
139 #error "No dmalloc_strdup or equivalent"
142 #else /* not using dmalloc */
144 #define DMALLOC_FN_ARGS
147 /** Allocate a chunk of <b>size</b> bytes of memory, and return a pointer to
148 * result. On error, log and terminate the process. (Same as malloc(size),
149 * but never returns NULL.)
151 * <b>file</b> and <b>line</b> are used if dmalloc is enabled, and
155 tor_malloc_(size_t size DMALLOC_PARAMS
)
159 tor_assert(size
< SIZE_T_CEILING
);
161 #ifndef MALLOC_ZERO_WORKS
162 /* Some libc mallocs don't work when size==0. Override them. */
169 result
= dmalloc_malloc(file
, line
, size
, DMALLOC_FUNC_MALLOC
, 0, 0);
171 result
= malloc(size
);
174 if (PREDICT_UNLIKELY(result
== NULL
)) {
175 log_err(LD_MM
,"Out of memory on malloc(). Dying.");
176 /* If these functions die within a worker process, they won't call
177 * spawn_exit, but that's ok, since the parent will run out of memory soon
184 /** Allocate a chunk of <b>size</b> bytes of memory, fill the memory with
185 * zero bytes, and return a pointer to the result. Log and terminate
186 * the process on error. (Same as calloc(size,1), but never returns NULL.)
189 tor_malloc_zero_(size_t size DMALLOC_PARAMS
)
191 /* You may ask yourself, "wouldn't it be smart to use calloc instead of
192 * malloc+memset? Perhaps libc's calloc knows some nifty optimization trick
193 * we don't!" Indeed it does, but its optimizations are only a big win when
194 * we're allocating something very big (it knows if it just got the memory
195 * from the OS in a pre-zeroed state). We don't want to use tor_malloc_zero
196 * for big stuff, so we don't bother with calloc. */
197 void *result
= tor_malloc_(size DMALLOC_FN_ARGS
);
198 memset(result
, 0, size
);
202 /* The square root of SIZE_MAX + 1. If a is less than this, and b is less
203 * than this, then a*b is less than SIZE_MAX. (For example, if size_t is
204 * 32 bits, then SIZE_MAX is 0xffffffff and this value is 0x10000. If a and
205 * b are less than this, then their product is at most (65535*65535) ==
207 #define SQRT_SIZE_MAX_P1 (((size_t)1) << (sizeof(size_t)*4))
209 /** Return non-zero if and only if the product of the arguments is exact. */
211 size_mul_check(const size_t x
, const size_t y
)
213 /* This first check is equivalent to
214 (x < SQRT_SIZE_MAX_P1 && y < SQRT_SIZE_MAX_P1)
216 Rationale: if either one of x or y is >= SQRT_SIZE_MAX_P1, then it
217 will have some bit set in its most significant half.
219 return ((x
|y
) < SQRT_SIZE_MAX_P1
||
224 /** Allocate a chunk of <b>nmemb</b>*<b>size</b> bytes of memory, fill
225 * the memory with zero bytes, and return a pointer to the result.
226 * Log and terminate the process on error. (Same as
227 * calloc(<b>nmemb</b>,<b>size</b>), but never returns NULL.)
228 * The second argument (<b>size</b>) should preferably be non-zero
229 * and a compile-time constant.
232 tor_calloc_(size_t nmemb
, size_t size DMALLOC_PARAMS
)
234 tor_assert(size_mul_check(nmemb
, size
));
235 return tor_malloc_zero_((nmemb
* size
) DMALLOC_FN_ARGS
);
238 /** Change the size of the memory block pointed to by <b>ptr</b> to <b>size</b>
239 * bytes long; return the new memory block. On error, log and
240 * terminate. (Like realloc(ptr,size), but never returns NULL.)
243 tor_realloc_(void *ptr
, size_t size DMALLOC_PARAMS
)
247 tor_assert(size
< SIZE_T_CEILING
);
249 #ifndef MALLOC_ZERO_WORKS
250 /* Some libc mallocs don't work when size==0. Override them. */
257 result
= dmalloc_realloc(file
, line
, ptr
, size
, DMALLOC_FUNC_REALLOC
, 0);
259 result
= realloc(ptr
, size
);
262 if (PREDICT_UNLIKELY(result
== NULL
)) {
263 log_err(LD_MM
,"Out of memory on realloc(). Dying.");
270 * Try to realloc <b>ptr</b> so that it takes up sz1 * sz2 bytes. Check for
271 * overflow. Unlike other allocation functions, return NULL on overflow.
274 tor_reallocarray_(void *ptr
, size_t sz1
, size_t sz2 DMALLOC_PARAMS
)
276 /* XXXX we can make this return 0, but we would need to check all the
277 * reallocarray users. */
278 tor_assert(size_mul_check(sz1
, sz2
));
280 return tor_realloc(ptr
, (sz1
* sz2
) DMALLOC_FN_ARGS
);
283 /** Return a newly allocated copy of the NUL-terminated string s. On
284 * error, log and terminate. (Like strdup(s), but never returns
288 tor_strdup_(const char *s DMALLOC_PARAMS
)
294 dup
= dmalloc_strdup(file
, line
, s
, 0);
298 if (PREDICT_UNLIKELY(dup
== NULL
)) {
299 log_err(LD_MM
,"Out of memory on strdup(). Dying.");
305 /** Allocate and return a new string containing the first <b>n</b>
306 * characters of <b>s</b>. If <b>s</b> is longer than <b>n</b>
307 * characters, only the first <b>n</b> are copied. The result is
308 * always NUL-terminated. (Like strndup(s,n), but never returns
312 tor_strndup_(const char *s
, size_t n DMALLOC_PARAMS
)
316 tor_assert(n
< SIZE_T_CEILING
);
317 dup
= tor_malloc_((n
+1) DMALLOC_FN_ARGS
);
318 /* Performance note: Ordinarily we prefer strlcpy to strncpy. But
319 * this function gets called a whole lot, and platform strncpy is
320 * much faster than strlcpy when strlen(s) is much longer than n.
327 /** Allocate a chunk of <b>len</b> bytes, with the same contents as the
328 * <b>len</b> bytes starting at <b>mem</b>. */
330 tor_memdup_(const void *mem
, size_t len DMALLOC_PARAMS
)
333 tor_assert(len
< SIZE_T_CEILING
);
335 dup
= tor_malloc_(len DMALLOC_FN_ARGS
);
336 memcpy(dup
, mem
, len
);
340 /** As tor_memdup(), but add an extra 0 byte at the end of the resulting
343 tor_memdup_nulterm_(const void *mem
, size_t len DMALLOC_PARAMS
)
346 tor_assert(len
< SIZE_T_CEILING
+1);
348 dup
= tor_malloc_(len
+1 DMALLOC_FN_ARGS
);
349 memcpy(dup
, mem
, len
);
354 /** Helper for places that need to take a function pointer to the right
355 * spelling of "free()". */
362 /** Call the platform malloc info function, and dump the results to the log at
363 * level <b>severity</b>. If no such function exists, do nothing. */
365 tor_log_mallinfo(int severity
)
369 memset(&mi
, 0, sizeof(mi
));
371 tor_log(severity
, LD_MM
,
372 "mallinfo() said: arena=%d, ordblks=%d, smblks=%d, hblks=%d, "
373 "hblkhd=%d, usmblks=%d, fsmblks=%d, uordblks=%d, fordblks=%d, "
375 mi
.arena
, mi
.ordblks
, mi
.smblks
, mi
.hblks
,
376 mi
.hblkhd
, mi
.usmblks
, mi
.fsmblks
, mi
.uordblks
, mi
.fordblks
,
382 dmalloc_log_changed(0, /* Since the program started. */
383 1, /* Log info about non-freed pointers. */
384 0, /* Do not log info about freed pointers. */
385 0 /* Do not log individual pointers. */
395 * Returns the natural logarithm of d base e. We defined this wrapper here so
396 * to avoid conflicts with old versions of tor_log(), which were named log().
399 tor_mathlog(double d
)
404 /** Return the long integer closest to <b>d</b>. We define this wrapper
405 * here so that not all users of math.h need to use the right incantations
406 * to get the c99 functions. */
410 #if defined(HAVE_LROUND)
412 #elif defined(HAVE_RINT)
413 return (long)rint(d
);
415 return (long)(d
> 0 ? d
+ 0.5 : ceil(d
- 0.5));
419 /** Return the 64-bit integer closest to d. We define this wrapper here so
420 * that not all users of math.h need to use the right incantations to get the
423 tor_llround(double d
)
425 #if defined(HAVE_LLROUND)
426 return (int64_t)llround(d
);
427 #elif defined(HAVE_RINT)
428 return (int64_t)rint(d
);
430 return (int64_t)(d
> 0 ? d
+ 0.5 : ceil(d
- 0.5));
434 /** Returns floor(log2(u64)). If u64 is 0, (incorrectly) returns 0. */
436 tor_log2(uint64_t u64
)
439 if (u64
>= (U64_LITERAL(1)<<32)) {
443 if (u64
>= (U64_LITERAL(1)<<16)) {
447 if (u64
>= (U64_LITERAL(1)<<8)) {
451 if (u64
>= (U64_LITERAL(1)<<4)) {
455 if (u64
>= (U64_LITERAL(1)<<2)) {
459 if (u64
>= (U64_LITERAL(1)<<1)) {
466 /** Return the power of 2 in range [1,UINT64_MAX] closest to <b>u64</b>. If
467 * there are two powers of 2 equally close, round down. */
469 round_to_power_of_2(uint64_t u64
)
478 low
= U64_LITERAL(1) << lg2
;
483 high
= U64_LITERAL(1) << (lg2
+1);
484 if (high
- u64
< u64
- low
)
490 /** Return the lowest x such that x is at least <b>number</b>, and x modulo
491 * <b>divisor</b> == 0. If no such x can be expressed as an unsigned, return
494 round_to_next_multiple_of(unsigned number
, unsigned divisor
)
496 tor_assert(divisor
> 0);
497 if (UINT_MAX
- divisor
+ 1 < number
)
499 number
+= divisor
- 1;
500 number
-= number
% divisor
;
504 /** Return the lowest x such that x is at least <b>number</b>, and x modulo
505 * <b>divisor</b> == 0. If no such x can be expressed as a uint32_t, return
508 round_uint32_to_next_multiple_of(uint32_t number
, uint32_t divisor
)
510 tor_assert(divisor
> 0);
511 if (UINT32_MAX
- divisor
+ 1 < number
)
514 number
+= divisor
- 1;
515 number
-= number
% divisor
;
519 /** Return the lowest x such that x is at least <b>number</b>, and x modulo
520 * <b>divisor</b> == 0. If no such x can be expressed as a uint64_t, return
523 round_uint64_to_next_multiple_of(uint64_t number
, uint64_t divisor
)
525 tor_assert(divisor
> 0);
526 if (UINT64_MAX
- divisor
+ 1 < number
)
528 number
+= divisor
- 1;
529 number
-= number
% divisor
;
533 /** Return the lowest x in [INT64_MIN, INT64_MAX] such that x is at least
534 * <b>number</b>, and x modulo <b>divisor</b> == 0. If no such x can be
535 * expressed as an int64_t, return INT64_MAX */
537 round_int64_to_next_multiple_of(int64_t number
, int64_t divisor
)
539 tor_assert(divisor
> 0);
540 if (INT64_MAX
- divisor
+ 1 < number
)
543 number
+= divisor
- 1;
544 number
-= number
% divisor
;
548 /** Transform a random value <b>p</b> from the uniform distribution in
549 * [0.0, 1.0[ into a Laplace distributed value with location parameter
550 * <b>mu</b> and scale parameter <b>b</b>. Truncate the final result
551 * to be an integer in [INT64_MIN, INT64_MAX]. */
553 sample_laplace_distribution(double mu
, double b
, double p
)
556 tor_assert(p
>= 0.0 && p
< 1.0);
558 /* This is the "inverse cumulative distribution function" from:
559 * http://en.wikipedia.org/wiki/Laplace_distribution */
561 /* Avoid taking log(0.0) == -INFINITY, as some processors or compiler
562 * options can cause the program to trap. */
566 result
= mu
- b
* (p
> 0.5 ? 1.0 : -1.0)
567 * tor_mathlog(1.0 - 2.0 * fabs(p
- 0.5));
569 return clamp_double_to_int64(result
);
572 /** Add random noise between INT64_MIN and INT64_MAX coming from a Laplace
573 * distribution with mu = 0 and b = <b>delta_f</b>/<b>epsilon</b> to
574 * <b>signal</b> based on the provided <b>random</b> value in [0.0, 1.0[.
575 * The epsilon value must be between ]0.0, 1.0]. delta_f must be greater
578 add_laplace_noise(int64_t signal
, double random
, double delta_f
,
583 /* epsilon MUST be between ]0.0, 1.0] */
584 tor_assert(epsilon
> 0.0 && epsilon
<= 1.0);
585 /* delta_f MUST be greater than 0. */
586 tor_assert(delta_f
> 0.0);
588 /* Just add noise, no further signal */
589 noise
= sample_laplace_distribution(0.0,
593 /* Clip (signal + noise) to [INT64_MIN, INT64_MAX] */
594 if (noise
> 0 && INT64_MAX
- noise
< signal
)
596 else if (noise
< 0 && INT64_MIN
- noise
> signal
)
599 return signal
+ noise
;
602 /** Return the number of bits set in <b>v</b>. */
604 n_bits_set_u8(uint8_t v
)
606 static const int nybble_table
[] = {
625 return nybble_table
[v
& 15] + nybble_table
[v
>>4];
629 * String manipulation
632 /** Remove from the string <b>s</b> every character which appears in
635 tor_strstrip(char *s
, const char *strip
)
639 if (strchr(strip
, *read
)) {
648 /** Return a pointer to a NUL-terminated hexadecimal string encoding
649 * the first <b>fromlen</b> bytes of <b>from</b>. (fromlen must be \<= 32.) The
650 * result does not need to be deallocated, but repeated calls to
651 * hex_str will trash old results.
654 hex_str(const char *from
, size_t fromlen
)
657 if (fromlen
>(sizeof(buf
)-1)/2)
658 fromlen
= (sizeof(buf
)-1)/2;
659 base16_encode(buf
,sizeof(buf
),from
,fromlen
);
663 /** Convert all alphabetic characters in the nul-terminated string <b>s</b> to
666 tor_strlower(char *s
)
669 *s
= TOR_TOLOWER(*s
);
674 /** Convert all alphabetic characters in the nul-terminated string <b>s</b> to
677 tor_strupper(char *s
)
680 *s
= TOR_TOUPPER(*s
);
685 /** Return 1 if every character in <b>s</b> is printable, else return 0.
688 tor_strisprint(const char *s
)
691 if (!TOR_ISPRINT(*s
))
698 /** Return 1 if no character in <b>s</b> is uppercase, else return 0.
701 tor_strisnonupper(const char *s
)
711 /** As strcmp, except that either string may be NULL. The NULL string is
712 * considered to be before any non-NULL string. */
714 strcmp_opt(const char *s1
, const char *s2
)
724 return strcmp(s1
, s2
);
728 /** Compares the first strlen(s2) characters of s1 with s2. Returns as for
732 strcmpstart(const char *s1
, const char *s2
)
734 size_t n
= strlen(s2
);
735 return strncmp(s1
, s2
, n
);
738 /** Compare the s1_len-byte string <b>s1</b> with <b>s2</b>,
739 * without depending on a terminating nul in s1. Sorting order is first by
740 * length, then lexically; return values are as for strcmp.
743 strcmp_len(const char *s1
, const char *s2
, size_t s1_len
)
745 size_t s2_len
= strlen(s2
);
750 return fast_memcmp(s1
, s2
, s2_len
);
753 /** Compares the first strlen(s2) characters of s1 with s2. Returns as for
757 strcasecmpstart(const char *s1
, const char *s2
)
759 size_t n
= strlen(s2
);
760 return strncasecmp(s1
, s2
, n
);
763 /** Compares the last strlen(s2) characters of s1 with s2. Returns as for
767 strcmpend(const char *s1
, const char *s2
)
769 size_t n1
= strlen(s1
), n2
= strlen(s2
);
771 return strcmp(s1
,s2
);
773 return strncmp(s1
+(n1
-n2
), s2
, n2
);
776 /** Compares the last strlen(s2) characters of s1 with s2. Returns as for
780 strcasecmpend(const char *s1
, const char *s2
)
782 size_t n1
= strlen(s1
), n2
= strlen(s2
);
783 if (n2
>n1
) /* then they can't be the same; figure out which is bigger */
784 return strcasecmp(s1
,s2
);
786 return strncasecmp(s1
+(n1
-n2
), s2
, n2
);
789 /** Compare the value of the string <b>prefix</b> with the start of the
790 * <b>memlen</b>-byte memory chunk at <b>mem</b>. Return as for strcmp.
792 * [As fast_memcmp(mem, prefix, strlen(prefix)) but returns -1 if memlen is
793 * less than strlen(prefix).]
796 fast_memcmpstart(const void *mem
, size_t memlen
,
799 size_t plen
= strlen(prefix
);
802 return fast_memcmp(mem
, prefix
, plen
);
805 /** Return a pointer to the first char of s that is not whitespace and
806 * not a comment, or to the terminating NUL if no such character exists.
809 eat_whitespace(const char *s
)
826 while (*s
&& *s
!= '\n')
832 /** Return a pointer to the first char of s that is not whitespace and
833 * not a comment, or to the terminating NUL if no such character exists.
836 eat_whitespace_eos(const char *s
, const char *eos
)
839 tor_assert(eos
&& s
<= eos
);
854 while (s
< eos
&& *s
&& *s
!= '\n')
861 /** Return a pointer to the first char of s that is not a space or a tab
862 * or a \\r, or to the terminating NUL if no such character exists. */
864 eat_whitespace_no_nl(const char *s
)
866 while (*s
== ' ' || *s
== '\t' || *s
== '\r')
871 /** As eat_whitespace_no_nl, but stop at <b>eos</b> whether we have
872 * found a non-whitespace character or not. */
874 eat_whitespace_eos_no_nl(const char *s
, const char *eos
)
876 while (s
< eos
&& (*s
== ' ' || *s
== '\t' || *s
== '\r'))
881 /** Return a pointer to the first char of s that is whitespace or <b>#</b>,
882 * or to the terminating NUL if no such character exists.
885 find_whitespace(const char *s
)
904 /** As find_whitespace, but stop at <b>eos</b> whether we have found a
905 * whitespace or not. */
907 find_whitespace_eos(const char *s
, const char *eos
)
927 /** Return the first occurrence of <b>needle</b> in <b>haystack</b> that
928 * occurs at the start of a line (that is, at the beginning of <b>haystack</b>
929 * or immediately after a newline). Return NULL if no such string is found.
932 find_str_at_start_of_line(const char *haystack
, const char *needle
)
934 size_t needle_len
= strlen(needle
);
937 if (!strncmp(haystack
, needle
, needle_len
))
940 haystack
= strchr(haystack
, '\n');
950 /** Returns true if <b>string</b> could be a C identifier.
951 A C identifier must begin with a letter or an underscore and the
952 rest of its characters can be letters, numbers or underscores. No
953 length limit is imposed. */
955 string_is_C_identifier(const char *string
)
958 size_t length
= strlen(string
);
962 for (iter
= 0; iter
< length
; iter
++) {
964 if (!(TOR_ISALPHA(string
[iter
]) ||
965 string
[iter
] == '_'))
968 if (!(TOR_ISALPHA(string
[iter
]) ||
969 TOR_ISDIGIT(string
[iter
]) ||
970 string
[iter
] == '_'))
978 /** Return true iff the 'len' bytes at 'mem' are all zero. */
980 tor_mem_is_zero(const char *mem
, size_t len
)
982 static const char ZERO
[] = {
983 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
985 while (len
>= sizeof(ZERO
)) {
986 /* It's safe to use fast_memcmp here, since the very worst thing an
987 * attacker could learn is how many initial bytes of a secret were zero */
988 if (fast_memcmp(mem
, ZERO
, sizeof(ZERO
)))
993 /* Deal with leftover bytes. */
995 return fast_memeq(mem
, ZERO
, len
);
1000 /** Return true iff the DIGEST_LEN bytes in digest are all zero. */
1002 tor_digest_is_zero(const char *digest
)
1004 static const uint8_t ZERO_DIGEST
[] = {
1005 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0
1007 return tor_memeq(digest
, ZERO_DIGEST
, DIGEST_LEN
);
1010 /** Return true if <b>string</b> is a valid 'key=[value]' string.
1011 * "value" is optional, to indicate the empty string. Log at logging
1012 * <b>severity</b> if something ugly happens. */
1014 string_is_key_value(int severity
, const char *string
)
1016 /* position of equal sign in string */
1017 const char *equal_sign_pos
= NULL
;
1021 if (strlen(string
) < 2) { /* "x=" is shortest args string */
1022 tor_log(severity
, LD_GENERAL
, "'%s' is too short to be a k=v value.",
1027 equal_sign_pos
= strchr(string
, '=');
1028 if (!equal_sign_pos
) {
1029 tor_log(severity
, LD_GENERAL
, "'%s' is not a k=v value.", escaped(string
));
1033 /* validate that the '=' is not in the beginning of the string. */
1034 if (equal_sign_pos
== string
) {
1035 tor_log(severity
, LD_GENERAL
, "'%s' is not a valid k=v value.",
1043 /** Return true if <b>string</b> represents a valid IPv4 adddress in
1047 string_is_valid_ipv4_address(const char *string
)
1049 struct in_addr addr
;
1051 return (tor_inet_pton(AF_INET
,string
,&addr
) == 1);
1054 /** Return true if <b>string</b> represents a valid IPv6 address in
1055 * a form that inet_pton() can parse.
1058 string_is_valid_ipv6_address(const char *string
)
1060 struct in6_addr addr
;
1062 return (tor_inet_pton(AF_INET6
,string
,&addr
) == 1);
1065 /** Return true iff <b>string</b> matches a pattern of DNS names
1066 * that we allow Tor clients to connect to.
1068 * Note: This allows certain technically invalid characters ('_') to cope
1069 * with misconfigured zones that have been encountered in the wild.
1072 string_is_valid_hostname(const char *string
)
1075 smartlist_t
*components
;
1077 components
= smartlist_new();
1079 smartlist_split_string(components
,string
,".",0,0);
1081 SMARTLIST_FOREACH_BEGIN(components
, char *, c
) {
1082 if ((c
[0] == '-') || (*c
== '_')) {
1087 /* Allow a single terminating '.' used rarely to indicate domains
1088 * are FQDNs rather than relative. */
1089 if ((c_sl_idx
> 0) && (c_sl_idx
+ 1 == c_sl_len
) && !*c
) {
1094 if ((*c
>= 'a' && *c
<= 'z') ||
1095 (*c
>= 'A' && *c
<= 'Z') ||
1096 (*c
>= '0' && *c
<= '9') ||
1097 (*c
== '-') || (*c
== '_'))
1101 } while (result
&& *c
);
1103 } SMARTLIST_FOREACH_END(c
);
1105 SMARTLIST_FOREACH_BEGIN(components
, char *, c
) {
1107 } SMARTLIST_FOREACH_END(c
);
1109 smartlist_free(components
);
1114 /** Return true iff the DIGEST256_LEN bytes in digest are all zero. */
1116 tor_digest256_is_zero(const char *digest
)
1118 return tor_mem_is_zero(digest
, DIGEST256_LEN
);
1121 /* Helper: common code to check whether the result of a strtol or strtoul or
1122 * strtoll is correct. */
1123 #define CHECK_STRTOX_RESULT() \
1124 /* Did an overflow occur? */ \
1125 if (errno == ERANGE) \
1127 /* Was at least one character converted? */ \
1130 /* Were there unexpected unconverted characters? */ \
1131 if (!next && *endptr) \
1133 /* Is r within limits? */ \
1134 if (r < min || r > max) \
1137 if (next) *next = endptr; \
1141 if (next) *next = endptr; \
1144 /** Extract a long from the start of <b>s</b>, in the given numeric
1145 * <b>base</b>. If <b>base</b> is 0, <b>s</b> is parsed as a decimal,
1146 * octal, or hex number in the syntax of a C integer literal. If
1147 * there is unconverted data and <b>next</b> is provided, set
1148 * *<b>next</b> to the first unconverted character. An error has
1149 * occurred if no characters are converted; or if there are
1150 * unconverted characters and <b>next</b> is NULL; or if the parsed
1151 * value is not between <b>min</b> and <b>max</b>. When no error
1152 * occurs, return the parsed value and set *<b>ok</b> (if provided) to
1153 * 1. When an error occurs, return 0 and set *<b>ok</b> (if provided)
1157 tor_parse_long(const char *s
, int base
, long min
, long max
,
1158 int *ok
, char **next
)
1170 r
= strtol(s
, &endptr
, base
);
1171 CHECK_STRTOX_RESULT();
1174 /** As tor_parse_long(), but return an unsigned long. */
1176 tor_parse_ulong(const char *s
, int base
, unsigned long min
,
1177 unsigned long max
, int *ok
, char **next
)
1189 r
= strtoul(s
, &endptr
, base
);
1190 CHECK_STRTOX_RESULT();
1193 /** As tor_parse_long(), but return a double. */
1195 tor_parse_double(const char *s
, double min
, double max
, int *ok
, char **next
)
1201 r
= strtod(s
, &endptr
);
1202 CHECK_STRTOX_RESULT();
1205 /** As tor_parse_long, but return a uint64_t. Only base 10 is guaranteed to
1208 tor_parse_uint64(const char *s
, int base
, uint64_t min
,
1209 uint64_t max
, int *ok
, char **next
)
1221 #ifdef HAVE_STRTOULL
1222 r
= (uint64_t)strtoull(s
, &endptr
, base
);
1223 #elif defined(_WIN32)
1224 #if defined(_MSC_VER) && _MSC_VER < 1300
1225 tor_assert(base
<= 10);
1226 r
= (uint64_t)_atoi64(s
);
1228 while (TOR_ISSPACE(*endptr
)) endptr
++;
1229 while (TOR_ISDIGIT(*endptr
)) endptr
++;
1231 r
= (uint64_t)_strtoui64(s
, &endptr
, base
);
1233 #elif SIZEOF_LONG == 8
1234 r
= (uint64_t)strtoul(s
, &endptr
, base
);
1236 #error "I don't know how to parse 64-bit numbers."
1239 CHECK_STRTOX_RESULT();
1242 /** Allocate and return a new string representing the contents of <b>s</b>,
1243 * surrounded by quotes and using standard C escapes.
1245 * Generally, we use this for logging values that come in over the network to
1246 * keep them from tricking users, and for sending certain values to the
1249 * We trust values from the resolver, OS, configuration file, and command line
1250 * to not be maliciously ill-formed. We validate incoming routerdescs and
1251 * SOCKS requests and addresses from BEGIN cells as they're parsed;
1252 * afterwards, we trust them as non-malicious.
1255 esc_for_log(const char *s
)
1258 char *result
, *outp
;
1261 return tor_strdup("(null)");
1264 for (cp
= s
; *cp
; ++cp
) {
1275 if (TOR_ISPRINT(*cp
) && ((uint8_t)*cp
)<127)
1283 tor_assert(len
<= SSIZE_MAX
);
1285 result
= outp
= tor_malloc(len
);
1287 for (cp
= s
; *cp
; ++cp
) {
1288 /* This assertion should always succeed, since we will write at least
1289 * one char here, and two chars for closing quote and nul later */
1290 tor_assert((outp
-result
) < (ssize_t
)len
-2);
1311 if (TOR_ISPRINT(*cp
) && ((uint8_t)*cp
)<127) {
1314 tor_assert((outp
-result
) < (ssize_t
)len
-4);
1315 tor_snprintf(outp
, 5, "\\%03o", (int)(uint8_t) *cp
);
1322 tor_assert((outp
-result
) <= (ssize_t
)len
-2);
1329 /** Similar to esc_for_log. Allocate and return a new string representing
1330 * the first n characters in <b>chars</b>, surround by quotes and using
1331 * standard C escapes. If a NUL character is encountered in <b>chars</b>,
1332 * the resulting string will be terminated there.
1335 esc_for_log_len(const char *chars
, size_t n
)
1337 char *string
= tor_strndup(chars
, n
);
1338 char *string_escaped
= esc_for_log(string
);
1340 return string_escaped
;
1343 /** Allocate and return a new string representing the contents of <b>s</b>,
1344 * surrounded by quotes and using standard C escapes.
1346 * THIS FUNCTION IS NOT REENTRANT. Don't call it from outside the main
1347 * thread. Also, each call invalidates the last-returned value, so don't
1348 * try log_warn(LD_GENERAL, "%s %s", escaped(a), escaped(b));
1351 escaped(const char *s
)
1353 static char *escaped_val_
= NULL
;
1354 tor_free(escaped_val_
);
1357 escaped_val_
= esc_for_log(s
);
1359 escaped_val_
= NULL
;
1361 return escaped_val_
;
1364 /** Return a newly allocated string equal to <b>string</b>, except that every
1365 * character in <b>chars_to_escape</b> is preceded by a backslash. */
1367 tor_escape_str_for_pt_args(const char *string
, const char *chars_to_escape
)
1369 char *new_string
= NULL
;
1370 char *new_cp
= NULL
;
1371 size_t length
, new_length
;
1375 length
= strlen(string
);
1377 if (!length
) /* If we were given the empty string, return the same. */
1378 return tor_strdup("");
1379 /* (new_length > SIZE_MAX) => ((length * 2) + 1 > SIZE_MAX) =>
1380 (length*2 > SIZE_MAX - 1) => (length > (SIZE_MAX - 1)/2) */
1381 if (length
> (SIZE_MAX
- 1)/2) /* check for overflow */
1384 /* this should be enough even if all characters must be escaped */
1385 new_length
= (length
* 2) + 1;
1387 new_string
= new_cp
= tor_malloc(new_length
);
1390 if (strchr(chars_to_escape
, *string
))
1393 *new_cp
++ = *string
++;
1396 *new_cp
= '\0'; /* NUL-terminate the new string */
1405 /** Return the number of microseconds elapsed between *start and *end.
1408 tv_udiff(const struct timeval
*start
, const struct timeval
*end
)
1411 long secdiff
= end
->tv_sec
- start
->tv_sec
;
1413 if (labs(secdiff
+1) > LONG_MAX
/1000000) {
1414 log_warn(LD_GENERAL
, "comparing times on microsecond detail too far "
1415 "apart: %ld seconds", secdiff
);
1419 udiff
= secdiff
*1000000L + (end
->tv_usec
- start
->tv_usec
);
1423 /** Return the number of milliseconds elapsed between *start and *end.
1426 tv_mdiff(const struct timeval
*start
, const struct timeval
*end
)
1429 long secdiff
= end
->tv_sec
- start
->tv_sec
;
1431 if (labs(secdiff
+1) > LONG_MAX
/1000) {
1432 log_warn(LD_GENERAL
, "comparing times on millisecond detail too far "
1433 "apart: %ld seconds", secdiff
);
1437 /* Subtract and round */
1438 mdiff
= secdiff
*1000L +
1439 ((long)end
->tv_usec
- (long)start
->tv_usec
+ 500L) / 1000L;
1444 * Converts timeval to milliseconds.
1447 tv_to_msec(const struct timeval
*tv
)
1449 int64_t conv
= ((int64_t)tv
->tv_sec
)*1000L;
1450 /* Round ghetto-style */
1451 conv
+= ((int64_t)tv
->tv_usec
+500)/1000L;
1455 /** Yield true iff <b>y</b> is a leap-year. */
1456 #define IS_LEAPYEAR(y) (!(y % 4) && ((y % 100) || !(y % 400)))
1457 /** Helper: Return the number of leap-days between Jan 1, y1 and Jan 1, y2. */
1459 n_leapdays(int y1
, int y2
)
1463 return (y2
/4 - y1
/4) - (y2
/100 - y1
/100) + (y2
/400 - y1
/400);
1465 /** Number of days per month in non-leap year; used by tor_timegm and
1466 * parse_rfc1123_time. */
1467 static const int days_per_month
[] =
1468 { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
1470 /** Compute a time_t given a struct tm. The result is given in UTC, and
1471 * does not account for leap seconds. Return 0 on success, -1 on failure.
1474 tor_timegm(const struct tm
*tm
, time_t *time_out
)
1476 /* This is a pretty ironclad timegm implementation, snarfed from Python2.2.
1477 * It's way more brute-force than fiddling with tzset().
1479 time_t year
, days
, hours
, minutes
, seconds
;
1480 int i
, invalid_year
, dpm
;
1481 /* avoid int overflow on addition */
1482 if (tm
->tm_year
< INT32_MAX
-1900) {
1483 year
= tm
->tm_year
+ 1900;
1488 invalid_year
= (year
< 1970 || tm
->tm_year
>= INT32_MAX
-1900);
1490 if (tm
->tm_mon
>= 0 && tm
->tm_mon
<= 11) {
1491 dpm
= days_per_month
[tm
->tm_mon
];
1492 if (tm
->tm_mon
== 1 && !invalid_year
&& IS_LEAPYEAR(tm
->tm_year
)) {
1496 /* invalid month - default to 0 days per month */
1501 tm
->tm_mon
< 0 || tm
->tm_mon
> 11 ||
1502 tm
->tm_mday
< 1 || tm
->tm_mday
> dpm
||
1503 tm
->tm_hour
< 0 || tm
->tm_hour
> 23 ||
1504 tm
->tm_min
< 0 || tm
->tm_min
> 59 ||
1505 tm
->tm_sec
< 0 || tm
->tm_sec
> 60) {
1506 log_warn(LD_BUG
, "Out-of-range argument to tor_timegm");
1509 days
= 365 * (year
-1970) + n_leapdays(1970,(int)year
);
1510 for (i
= 0; i
< tm
->tm_mon
; ++i
)
1511 days
+= days_per_month
[i
];
1512 if (tm
->tm_mon
> 1 && IS_LEAPYEAR(year
))
1514 days
+= tm
->tm_mday
- 1;
1515 hours
= days
*24 + tm
->tm_hour
;
1517 minutes
= hours
*60 + tm
->tm_min
;
1518 seconds
= minutes
*60 + tm
->tm_sec
;
1519 *time_out
= seconds
;
1523 /* strftime is locale-specific, so we need to replace those parts */
1525 /** A c-locale array of 3-letter names of weekdays, starting with Sun. */
1526 static const char *WEEKDAY_NAMES
[] =
1527 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
1528 /** A c-locale array of 3-letter names of months, starting with Jan. */
1529 static const char *MONTH_NAMES
[] =
1530 { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1531 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
1533 /** Set <b>buf</b> to the RFC1123 encoding of the UTC value of <b>t</b>.
1534 * The buffer must be at least RFC1123_TIME_LEN+1 bytes long.
1536 * (RFC1123 format is "Fri, 29 Sep 2006 15:54:20 GMT". Note the "GMT"
1537 * rather than "UTC".)
1540 format_rfc1123_time(char *buf
, time_t t
)
1544 tor_gmtime_r(&t
, &tm
);
1546 strftime(buf
, RFC1123_TIME_LEN
+1, "___, %d ___ %Y %H:%M:%S GMT", &tm
);
1547 tor_assert(tm
.tm_wday
>= 0);
1548 tor_assert(tm
.tm_wday
<= 6);
1549 memcpy(buf
, WEEKDAY_NAMES
[tm
.tm_wday
], 3);
1550 tor_assert(tm
.tm_mon
>= 0);
1551 tor_assert(tm
.tm_mon
<= 11);
1552 memcpy(buf
+8, MONTH_NAMES
[tm
.tm_mon
], 3);
1555 /** Parse the (a subset of) the RFC1123 encoding of some time (in UTC) from
1556 * <b>buf</b>, and store the result in *<b>t</b>.
1558 * Note that we only accept the subset generated by format_rfc1123_time above,
1559 * not the full range of formats suggested by RFC 1123.
1561 * Return 0 on success, -1 on failure.
1564 parse_rfc1123_time(const char *buf
, time_t *t
)
1569 int i
, m
, invalid_year
;
1570 unsigned tm_mday
, tm_year
, tm_hour
, tm_min
, tm_sec
;
1573 if (strlen(buf
) != RFC1123_TIME_LEN
)
1575 memset(&tm
, 0, sizeof(tm
));
1576 if (tor_sscanf(buf
, "%3s, %2u %3s %u %2u:%2u:%2u GMT", weekday
,
1577 &tm_mday
, month
, &tm_year
, &tm_hour
,
1578 &tm_min
, &tm_sec
) < 7) {
1579 char *esc
= esc_for_log(buf
);
1580 log_warn(LD_GENERAL
, "Got invalid RFC1123 time %s", esc
);
1586 for (i
= 0; i
< 12; ++i
) {
1587 if (!strcmp(month
, MONTH_NAMES
[i
])) {
1593 char *esc
= esc_for_log(buf
);
1594 log_warn(LD_GENERAL
, "Got invalid RFC1123 time %s: No such month", esc
);
1600 invalid_year
= (tm_year
>= INT32_MAX
|| tm_year
< 1970);
1601 tor_assert(m
>= 0 && m
<= 11);
1602 dpm
= days_per_month
[m
];
1603 if (m
== 1 && !invalid_year
&& IS_LEAPYEAR(tm_year
)) {
1607 if (invalid_year
|| tm_mday
< 1 || tm_mday
> dpm
||
1608 tm_hour
> 23 || tm_min
> 59 || tm_sec
> 60) {
1609 char *esc
= esc_for_log(buf
);
1610 log_warn(LD_GENERAL
, "Got invalid RFC1123 time %s", esc
);
1614 tm
.tm_mday
= (int)tm_mday
;
1615 tm
.tm_year
= (int)tm_year
;
1616 tm
.tm_hour
= (int)tm_hour
;
1617 tm
.tm_min
= (int)tm_min
;
1618 tm
.tm_sec
= (int)tm_sec
;
1620 if (tm
.tm_year
< 1970) {
1621 char *esc
= esc_for_log(buf
);
1622 log_warn(LD_GENERAL
,
1623 "Got invalid RFC1123 time %s. (Before 1970)", esc
);
1629 return tor_timegm(&tm
, t
);
1632 /** Set <b>buf</b> to the ISO8601 encoding of the local value of <b>t</b>.
1633 * The buffer must be at least ISO_TIME_LEN+1 bytes long.
1635 * (ISO8601 format is 2006-10-29 10:57:20)
1638 format_local_iso_time(char *buf
, time_t t
)
1641 strftime(buf
, ISO_TIME_LEN
+1, "%Y-%m-%d %H:%M:%S", tor_localtime_r(&t
, &tm
));
1644 /** Set <b>buf</b> to the ISO8601 encoding of the GMT value of <b>t</b>.
1645 * The buffer must be at least ISO_TIME_LEN+1 bytes long.
1648 format_iso_time(char *buf
, time_t t
)
1651 strftime(buf
, ISO_TIME_LEN
+1, "%Y-%m-%d %H:%M:%S", tor_gmtime_r(&t
, &tm
));
1654 /** As format_iso_time, but use the yyyy-mm-ddThh:mm:ss format to avoid
1655 * embedding an internal space. */
1657 format_iso_time_nospace(char *buf
, time_t t
)
1659 format_iso_time(buf
, t
);
1663 /** As format_iso_time_nospace, but include microseconds in decimal
1664 * fixed-point format. Requires that buf be at least ISO_TIME_USEC_LEN+1
1667 format_iso_time_nospace_usec(char *buf
, const struct timeval
*tv
)
1670 format_iso_time_nospace(buf
, (time_t)tv
->tv_sec
);
1671 tor_snprintf(buf
+ISO_TIME_LEN
, 8, ".%06d", (int)tv
->tv_usec
);
1674 /** Given an ISO-formatted UTC time value (after the epoch) in <b>cp</b>,
1675 * parse it and store its value in *<b>t</b>. Return 0 on success, -1 on
1676 * failure. Ignore extraneous stuff in <b>cp</b> after the end of the time
1677 * string, unless <b>strict</b> is set. */
1679 parse_iso_time_(const char *cp
, time_t *t
, int strict
)
1682 unsigned int year
=0, month
=0, day
=0, hour
=0, minute
=0, second
=0;
1685 n_fields
= tor_sscanf(cp
, "%u-%2u-%2u %2u:%2u:%2u%c", &year
, &month
,
1686 &day
, &hour
, &minute
, &second
, &extra_char
);
1687 if (strict
? (n_fields
!= 6) : (n_fields
< 6)) {
1688 char *esc
= esc_for_log(cp
);
1689 log_warn(LD_GENERAL
, "ISO time %s was unparseable", esc
);
1693 if (year
< 1970 || month
< 1 || month
> 12 || day
< 1 || day
> 31 ||
1694 hour
> 23 || minute
> 59 || second
> 60 || year
>= INT32_MAX
) {
1695 char *esc
= esc_for_log(cp
);
1696 log_warn(LD_GENERAL
, "ISO time %s was nonsensical", esc
);
1700 st_tm
.tm_year
= (int)year
-1900;
1701 st_tm
.tm_mon
= month
-1;
1702 st_tm
.tm_mday
= day
;
1703 st_tm
.tm_hour
= hour
;
1704 st_tm
.tm_min
= minute
;
1705 st_tm
.tm_sec
= second
;
1707 if (st_tm
.tm_year
< 70) {
1708 char *esc
= esc_for_log(cp
);
1709 log_warn(LD_GENERAL
, "Got invalid ISO time %s. (Before 1970)", esc
);
1713 return tor_timegm(&st_tm
, t
);
1716 /** Given an ISO-formatted UTC time value (after the epoch) in <b>cp</b>,
1717 * parse it and store its value in *<b>t</b>. Return 0 on success, -1 on
1718 * failure. Reject the string if any characters are present after the time.
1721 parse_iso_time(const char *cp
, time_t *t
)
1723 return parse_iso_time_(cp
, t
, 1);
1726 /** Given a <b>date</b> in one of the three formats allowed by HTTP (ugh),
1727 * parse it into <b>tm</b>. Return 0 on success, negative on failure. */
1729 parse_http_time(const char *date
, struct tm
*tm
)
1735 unsigned tm_mday
, tm_year
, tm_hour
, tm_min
, tm_sec
;
1738 memset(tm
, 0, sizeof(*tm
));
1740 /* First, try RFC1123 or RFC850 format: skip the weekday. */
1741 if ((cp
= strchr(date
, ','))) {
1746 if (tor_sscanf(cp
, "%2u %3s %4u %2u:%2u:%2u GMT",
1747 &tm_mday
, month
, &tm_year
,
1748 &tm_hour
, &tm_min
, &tm_sec
) == 6) {
1751 } else if (tor_sscanf(cp
, "%2u-%3s-%2u %2u:%2u:%2u GMT",
1752 &tm_mday
, month
, &tm_year
,
1753 &tm_hour
, &tm_min
, &tm_sec
) == 6) {
1759 /* No comma; possibly asctime() format. */
1760 if (tor_sscanf(date
, "%3s %3s %2u %2u:%2u:%2u %4u",
1761 wkday
, month
, &tm_mday
,
1762 &tm_hour
, &tm_min
, &tm_sec
, &tm_year
) == 7) {
1768 tm
->tm_mday
= (int)tm_mday
;
1769 tm
->tm_year
= (int)tm_year
;
1770 tm
->tm_hour
= (int)tm_hour
;
1771 tm
->tm_min
= (int)tm_min
;
1772 tm
->tm_sec
= (int)tm_sec
;
1775 /* Okay, now decode the month. */
1776 /* set tm->tm_mon to dummy value so the check below fails. */
1778 for (i
= 0; i
< 12; ++i
) {
1779 if (!strcasecmp(MONTH_NAMES
[i
], month
)) {
1784 if (tm
->tm_year
< 0 ||
1785 tm
->tm_mon
< 0 || tm
->tm_mon
> 11 ||
1786 tm
->tm_mday
< 1 || tm
->tm_mday
> 31 ||
1787 tm
->tm_hour
< 0 || tm
->tm_hour
> 23 ||
1788 tm
->tm_min
< 0 || tm
->tm_min
> 59 ||
1789 tm
->tm_sec
< 0 || tm
->tm_sec
> 60)
1790 return -1; /* Out of range, or bad month. */
1795 /** Given an <b>interval</b> in seconds, try to write it to the
1796 * <b>out_len</b>-byte buffer in <b>out</b> in a human-readable form.
1797 * Return 0 on success, -1 on failure.
1800 format_time_interval(char *out
, size_t out_len
, long interval
)
1802 /* We only report seconds if there's no hours. */
1803 long sec
= 0, min
= 0, hour
= 0, day
= 0;
1805 /* -LONG_MIN is LONG_MAX + 1, which causes signed overflow */
1806 if (interval
< -LONG_MAX
)
1807 interval
= LONG_MAX
;
1808 else if (interval
< 0)
1809 interval
= -interval
;
1811 if (interval
>= 86400) {
1812 day
= interval
/ 86400;
1815 if (interval
>= 3600) {
1816 hour
= interval
/ 3600;
1819 if (interval
>= 60) {
1820 min
= interval
/ 60;
1826 return tor_snprintf(out
, out_len
, "%ld days, %ld hours, %ld minutes",
1829 return tor_snprintf(out
, out_len
, "%ld hours, %ld minutes", hour
, min
);
1831 return tor_snprintf(out
, out_len
, "%ld minutes, %ld seconds", min
, sec
);
1833 return tor_snprintf(out
, out_len
, "%ld seconds", sec
);
1841 #ifndef TIME_IS_FAST
1842 /** Cached estimate of the current time. Updated around once per second;
1843 * may be a few seconds off if we are really busy. This is a hack to avoid
1844 * calling time(NULL) (which not everybody has optimized) on critical paths.
1846 static time_t cached_approx_time
= 0;
1848 /** Return a cached estimate of the current time from when
1849 * update_approx_time() was last called. This is a hack to avoid calling
1850 * time(NULL) on critical paths: please do not even think of calling it
1855 return cached_approx_time
;
1858 /** Update the cached estimate of the current time. This function SHOULD be
1859 * called once per second, and MUST be called before the first call to
1860 * get_approx_time. */
1862 update_approx_time(time_t now
)
1864 cached_approx_time
= now
;
1872 /** If the rate-limiter <b>lim</b> is ready at <b>now</b>, return the number
1873 * of calls to rate_limit_is_ready (including this one!) since the last time
1874 * rate_limit_is_ready returned nonzero. Otherwise return 0. */
1876 rate_limit_is_ready(ratelim_t
*lim
, time_t now
)
1878 if (lim
->rate
+ lim
->last_allowed
<= now
) {
1879 int res
= lim
->n_calls_since_last_time
+ 1;
1880 lim
->last_allowed
= now
;
1881 lim
->n_calls_since_last_time
= 0;
1884 ++lim
->n_calls_since_last_time
;
1889 /** If the rate-limiter <b>lim</b> is ready at <b>now</b>, return a newly
1890 * allocated string indicating how many messages were suppressed, suitable to
1891 * append to a log message. Otherwise return NULL. */
1893 rate_limit_log(ratelim_t
*lim
, time_t now
)
1896 if ((n
= rate_limit_is_ready(lim
, now
))) {
1898 return tor_strdup("");
1902 " [%d similar message(s) suppressed in last %d seconds]",
1915 /** Write <b>count</b> bytes from <b>buf</b> to <b>fd</b>. <b>isSocket</b>
1916 * must be 1 if fd was returned by socket() or accept(), and 0 if fd
1917 * was returned by open(). Return the number of bytes written, or -1
1918 * on error. Only use if fd is a blocking fd. */
1920 write_all(tor_socket_t fd
, const char *buf
, size_t count
, int isSocket
)
1924 tor_assert(count
< SSIZE_MAX
);
1926 while (written
!= count
) {
1928 result
= tor_socket_send(fd
, buf
+written
, count
-written
, 0);
1930 result
= write((int)fd
, buf
+written
, count
-written
);
1935 return (ssize_t
)count
;
1938 /** Read from <b>fd</b> to <b>buf</b>, until we get <b>count</b> bytes
1939 * or reach the end of the file. <b>isSocket</b> must be 1 if fd
1940 * was returned by socket() or accept(), and 0 if fd was returned by
1941 * open(). Return the number of bytes read, or -1 on error. Only use
1942 * if fd is a blocking fd. */
1944 read_all(tor_socket_t fd
, char *buf
, size_t count
, int isSocket
)
1949 if (count
> SIZE_T_CEILING
|| count
> SSIZE_MAX
) {
1954 while (numread
!= count
) {
1956 result
= tor_socket_recv(fd
, buf
+numread
, count
-numread
, 0);
1958 result
= read((int)fd
, buf
+numread
, count
-numread
);
1961 else if (result
== 0)
1965 return (ssize_t
)numread
;
1969 * Filesystem operations.
1972 /** Clean up <b>name</b> so that we can use it in a call to "stat". On Unix,
1973 * we do nothing. On Windows, we remove a trailing slash, unless the path is
1974 * the root of a disk. */
1976 clean_name_for_stat(char *name
)
1979 size_t len
= strlen(name
);
1982 if (name
[len
-1]=='\\' || name
[len
-1]=='/') {
1983 if (len
== 1 || (len
==3 && name
[1]==':'))
1993 * FN_ERROR if filename can't be read, is NULL, or is zero-length,
1994 * FN_NOENT if it doesn't exist,
1995 * FN_FILE if it is a non-empty regular file, or a FIFO on unix-like systems,
1996 * FN_EMPTY for zero-byte regular files,
1997 * FN_DIR if it's a directory, and
1998 * FN_ERROR for any other file type.
1999 * On FN_ERROR and FN_NOENT, sets errno. (errno is not set when FN_ERROR
2000 * is returned due to an unhandled file type.) */
2002 file_status(const char *fname
)
2007 if (!fname
|| strlen(fname
) == 0) {
2010 f
= tor_strdup(fname
);
2011 clean_name_for_stat(f
);
2012 log_debug(LD_FS
, "stat()ing %s", f
);
2013 r
= stat(sandbox_intern_string(f
), &st
);
2016 if (errno
== ENOENT
) {
2021 if (st
.st_mode
& S_IFDIR
) {
2023 } else if (st
.st_mode
& S_IFREG
) {
2024 if (st
.st_size
> 0) {
2026 } else if (st
.st_size
== 0) {
2032 } else if (st
.st_mode
& S_IFIFO
) {
2040 /** Check whether <b>dirname</b> exists and is private. If yes return 0. If
2041 * it does not exist, and <b>check</b>&CPD_CREATE is set, try to create it
2042 * and return 0 on success. If it does not exist, and
2043 * <b>check</b>&CPD_CHECK, and we think we can create it, return 0. Else
2044 * return -1. If CPD_GROUP_OK is set, then it's okay if the directory
2045 * is group-readable, but in all cases we create the directory mode 0700.
2046 * If CPD_GROUP_READ is set, existing directory behaves as CPD_GROUP_OK and
2047 * if the directory is created it will use mode 0750 with group read
2048 * permission. Group read privileges also assume execute permission
2049 * as norm for directories. If CPD_CHECK_MODE_ONLY is set, then we don't
2050 * alter the directory permissions if they are too permissive:
2051 * we just return -1.
2052 * When effective_user is not NULL, check permissions against the given user
2053 * and its primary group.
2056 check_private_dir(const char *dirname
, cpd_check_t check
,
2057 const char *effective_user
)
2063 unsigned unwanted_bits
= 0;
2064 const struct passwd
*pw
= NULL
;
2068 (void)effective_user
;
2071 tor_assert(dirname
);
2072 f
= tor_strdup(dirname
);
2073 clean_name_for_stat(f
);
2074 log_debug(LD_FS
, "stat()ing %s", f
);
2075 r
= stat(sandbox_intern_string(f
), &st
);
2078 if (errno
!= ENOENT
) {
2079 log_warn(LD_FS
, "Directory %s cannot be read: %s", dirname
,
2083 if (check
& CPD_CREATE
) {
2084 log_info(LD_GENERAL
, "Creating directory %s", dirname
);
2085 #if defined (_WIN32)
2088 if (check
& CPD_GROUP_READ
) {
2089 r
= mkdir(dirname
, 0750);
2091 r
= mkdir(dirname
, 0700);
2095 log_warn(LD_FS
, "Error creating directory %s: %s", dirname
,
2099 } else if (!(check
& CPD_CHECK
)) {
2100 log_warn(LD_FS
, "Directory %s does not exist.", dirname
);
2103 /* XXXX In the case where check==CPD_CHECK, we should look at the
2104 * parent directory a little harder. */
2107 if (!(st
.st_mode
& S_IFDIR
)) {
2108 log_warn(LD_FS
, "%s is not a directory", dirname
);
2112 if (effective_user
) {
2113 /* Look up the user and group information.
2114 * If we have a problem, bail out. */
2115 pw
= tor_getpwnam(effective_user
);
2117 log_warn(LD_CONFIG
, "Error setting configured user: %s not found",
2121 running_uid
= pw
->pw_uid
;
2122 running_gid
= pw
->pw_gid
;
2124 running_uid
= getuid();
2125 running_gid
= getgid();
2128 if (st
.st_uid
!= running_uid
) {
2129 const struct passwd
*pw
= NULL
;
2130 char *process_ownername
= NULL
;
2132 pw
= tor_getpwuid(running_uid
);
2133 process_ownername
= pw
? tor_strdup(pw
->pw_name
) : tor_strdup("<unknown>");
2135 pw
= tor_getpwuid(st
.st_uid
);
2137 log_warn(LD_FS
, "%s is not owned by this user (%s, %d) but by "
2138 "%s (%d). Perhaps you are running Tor as the wrong user?",
2139 dirname
, process_ownername
, (int)running_uid
,
2140 pw
? pw
->pw_name
: "<unknown>", (int)st
.st_uid
);
2142 tor_free(process_ownername
);
2145 if ( (check
& (CPD_GROUP_OK
|CPD_GROUP_READ
))
2146 && (st
.st_gid
!= running_gid
) ) {
2148 char *process_groupname
= NULL
;
2149 gr
= getgrgid(running_gid
);
2150 process_groupname
= gr
? tor_strdup(gr
->gr_name
) : tor_strdup("<unknown>");
2151 gr
= getgrgid(st
.st_gid
);
2153 log_warn(LD_FS
, "%s is not owned by this group (%s, %d) but by group "
2154 "%s (%d). Are you running Tor as the wrong user?",
2155 dirname
, process_groupname
, (int)running_gid
,
2156 gr
? gr
->gr_name
: "<unknown>", (int)st
.st_gid
);
2158 tor_free(process_groupname
);
2161 if (check
& (CPD_GROUP_OK
|CPD_GROUP_READ
)) {
2162 unwanted_bits
= 0027;
2164 unwanted_bits
= 0077;
2166 if ((st
.st_mode
& unwanted_bits
) != 0) {
2168 if (check
& CPD_CHECK_MODE_ONLY
) {
2169 log_warn(LD_FS
, "Permissions on directory %s are too permissive.",
2173 log_warn(LD_FS
, "Fixing permissions on directory %s", dirname
);
2174 new_mode
= st
.st_mode
;
2175 new_mode
|= 0700; /* Owner should have rwx */
2176 if (check
& CPD_GROUP_READ
) {
2177 new_mode
|= 0050; /* Group should have rx */
2179 new_mode
&= ~unwanted_bits
; /* Clear the bits that we didn't want set...*/
2180 if (chmod(dirname
, new_mode
)) {
2181 log_warn(LD_FS
, "Could not chmod directory %s: %s", dirname
,
2192 /** Create a file named <b>fname</b> with the contents <b>str</b>. Overwrite
2193 * the previous <b>fname</b> if possible. Return 0 on success, -1 on failure.
2195 * This function replaces the old file atomically, if possible. This
2196 * function, and all other functions in util.c that create files, create them
2200 write_str_to_file(const char *fname
, const char *str
, int bin
)
2203 if (!bin
&& strchr(str
, '\r')) {
2205 "We're writing a text string that already contains a CR to %s",
2209 return write_bytes_to_file(fname
, str
, strlen(str
), bin
);
2212 /** Represents a file that we're writing to, with support for atomic commit:
2213 * we can write into a temporary file, and either remove the file on
2214 * failure, or replace the original file on success. */
2215 struct open_file_t
{
2216 char *tempname
; /**< Name of the temporary file. */
2217 char *filename
; /**< Name of the original file. */
2218 unsigned rename_on_close
:1; /**< Are we using the temporary file or not? */
2219 unsigned binary
:1; /**< Did we open in binary mode? */
2220 int fd
; /**< fd for the open file. */
2221 FILE *stdio_file
; /**< stdio wrapper for <b>fd</b>. */
2224 /** Try to start writing to the file in <b>fname</b>, passing the flags
2225 * <b>open_flags</b> to the open() syscall, creating the file (if needed) with
2226 * access value <b>mode</b>. If the O_APPEND flag is set, we append to the
2227 * original file. Otherwise, we open a new temporary file in the same
2228 * directory, and either replace the original or remove the temporary file
2231 * Return the fd for the newly opened file, and store working data in
2232 * *<b>data_out</b>. The caller should not close the fd manually:
2233 * instead, call finish_writing_to_file() or abort_writing_to_file().
2234 * Returns -1 on failure.
2236 * NOTE: When not appending, the flags O_CREAT and O_TRUNC are treated
2237 * as true and the flag O_EXCL is treated as false.
2239 * NOTE: Ordinarily, O_APPEND means "seek to the end of the file before each
2240 * write()". We don't do that.
2243 start_writing_to_file(const char *fname
, int open_flags
, int mode
,
2244 open_file_t
**data_out
)
2246 open_file_t
*new_file
= tor_malloc_zero(sizeof(open_file_t
));
2247 const char *open_name
;
2251 tor_assert(data_out
);
2252 #if (O_BINARY != 0 && O_TEXT != 0)
2253 tor_assert((open_flags
& (O_BINARY
|O_TEXT
)) != 0);
2256 new_file
->filename
= tor_strdup(fname
);
2257 if (open_flags
& O_APPEND
) {
2259 new_file
->rename_on_close
= 0;
2261 open_flags
&= ~O_APPEND
;
2263 tor_asprintf(&new_file
->tempname
, "%s.tmp", fname
);
2264 open_name
= new_file
->tempname
;
2265 /* We always replace an existing temporary file if there is one. */
2266 open_flags
|= O_CREAT
|O_TRUNC
;
2267 open_flags
&= ~O_EXCL
;
2268 new_file
->rename_on_close
= 1;
2271 if (open_flags
& O_BINARY
)
2272 new_file
->binary
= 1;
2275 new_file
->fd
= tor_open_cloexec(open_name
, open_flags
, mode
);
2276 if (new_file
->fd
< 0) {
2277 log_warn(LD_FS
, "Couldn't open \"%s\" (%s) for writing: %s",
2278 open_name
, fname
, strerror(errno
));
2282 if (tor_fd_seekend(new_file
->fd
) < 0) {
2283 log_warn(LD_FS
, "Couldn't seek to end of file \"%s\": %s", open_name
,
2289 *data_out
= new_file
;
2291 return new_file
->fd
;
2294 if (new_file
->fd
>= 0)
2295 close(new_file
->fd
);
2297 tor_free(new_file
->filename
);
2298 tor_free(new_file
->tempname
);
2303 /** Given <b>file_data</b> from start_writing_to_file(), return a stdio FILE*
2304 * that can be used to write to the same file. The caller should not mix
2305 * stdio calls with non-stdio calls. */
2307 fdopen_file(open_file_t
*file_data
)
2309 tor_assert(file_data
);
2310 if (file_data
->stdio_file
)
2311 return file_data
->stdio_file
;
2312 tor_assert(file_data
->fd
>= 0);
2313 if (!(file_data
->stdio_file
= fdopen(file_data
->fd
,
2314 file_data
->binary
?"ab":"a"))) {
2315 log_warn(LD_FS
, "Couldn't fdopen \"%s\" [%d]: %s", file_data
->filename
,
2316 file_data
->fd
, strerror(errno
));
2318 return file_data
->stdio_file
;
2321 /** Combines start_writing_to_file with fdopen_file(): arguments are as
2322 * for start_writing_to_file, but */
2324 start_writing_to_stdio_file(const char *fname
, int open_flags
, int mode
,
2325 open_file_t
**data_out
)
2328 if (start_writing_to_file(fname
, open_flags
, mode
, data_out
)<0)
2330 if (!(res
= fdopen_file(*data_out
))) {
2331 abort_writing_to_file(*data_out
);
2337 /** Helper function: close and free the underlying file and memory in
2338 * <b>file_data</b>. If we were writing into a temporary file, then delete
2339 * that file (if abort_write is true) or replaces the target file with
2340 * the temporary file (if abort_write is false). */
2342 finish_writing_to_file_impl(open_file_t
*file_data
, int abort_write
)
2346 tor_assert(file_data
&& file_data
->filename
);
2347 if (file_data
->stdio_file
) {
2348 if (fclose(file_data
->stdio_file
)) {
2349 log_warn(LD_FS
, "Error closing \"%s\": %s", file_data
->filename
,
2351 abort_write
= r
= -1;
2353 } else if (file_data
->fd
>= 0 && close(file_data
->fd
) < 0) {
2354 log_warn(LD_FS
, "Error flushing \"%s\": %s", file_data
->filename
,
2356 abort_write
= r
= -1;
2359 if (file_data
->rename_on_close
) {
2360 tor_assert(file_data
->tempname
&& file_data
->filename
);
2362 int res
= unlink(file_data
->tempname
);
2364 /* We couldn't unlink and we'll leave a mess behind */
2365 log_warn(LD_FS
, "Failed to unlink %s: %s",
2366 file_data
->tempname
, strerror(errno
));
2370 tor_assert(strcmp(file_data
->filename
, file_data
->tempname
));
2371 if (replace_file(file_data
->tempname
, file_data
->filename
)) {
2372 log_warn(LD_FS
, "Error replacing \"%s\": %s", file_data
->filename
,
2379 tor_free(file_data
->filename
);
2380 tor_free(file_data
->tempname
);
2381 tor_free(file_data
);
2386 /** Finish writing to <b>file_data</b>: close the file handle, free memory as
2387 * needed, and if using a temporary file, replace the original file with
2388 * the temporary file. */
2390 finish_writing_to_file(open_file_t
*file_data
)
2392 return finish_writing_to_file_impl(file_data
, 0);
2395 /** Finish writing to <b>file_data</b>: close the file handle, free memory as
2396 * needed, and if using a temporary file, delete it. */
2398 abort_writing_to_file(open_file_t
*file_data
)
2400 return finish_writing_to_file_impl(file_data
, 1);
2403 /** Helper: given a set of flags as passed to open(2), open the file
2404 * <b>fname</b> and write all the sized_chunk_t structs in <b>chunks</b> to
2405 * the file. Do so as atomically as possible e.g. by opening temp files and
2408 write_chunks_to_file_impl(const char *fname
, const smartlist_t
*chunks
,
2411 open_file_t
*file
= NULL
;
2414 fd
= start_writing_to_file(fname
, open_flags
, 0600, &file
);
2417 SMARTLIST_FOREACH(chunks
, sized_chunk_t
*, chunk
,
2419 result
= write_all(fd
, chunk
->bytes
, chunk
->len
, 0);
2421 log_warn(LD_FS
, "Error writing to \"%s\": %s", fname
,
2425 tor_assert((size_t)result
== chunk
->len
);
2428 return finish_writing_to_file(file
);
2430 abort_writing_to_file(file
);
2434 /** Given a smartlist of sized_chunk_t, write them to a file
2435 * <b>fname</b>, overwriting or creating the file as necessary.
2436 * If <b>no_tempfile</b> is 0 then the file will be written
2439 write_chunks_to_file(const char *fname
, const smartlist_t
*chunks
, int bin
,
2442 int flags
= OPEN_FLAGS_REPLACE
|(bin
?O_BINARY
:O_TEXT
);
2445 /* O_APPEND stops write_chunks_to_file from using tempfiles */
2448 return write_chunks_to_file_impl(fname
, chunks
, flags
);
2451 /** Write <b>len</b> bytes, starting at <b>str</b>, to <b>fname</b>
2452 using the open() flags passed in <b>flags</b>. */
2454 write_bytes_to_file_impl(const char *fname
, const char *str
, size_t len
,
2458 sized_chunk_t c
= { str
, len
};
2459 smartlist_t
*chunks
= smartlist_new();
2460 smartlist_add(chunks
, &c
);
2461 r
= write_chunks_to_file_impl(fname
, chunks
, flags
);
2462 smartlist_free(chunks
);
2466 /** As write_str_to_file, but does not assume a NUL-terminated
2467 * string. Instead, we write <b>len</b> bytes, starting at <b>str</b>. */
2469 write_bytes_to_file
,(const char *fname
, const char *str
, size_t len
,
2472 return write_bytes_to_file_impl(fname
, str
, len
,
2473 OPEN_FLAGS_REPLACE
|(bin
?O_BINARY
:O_TEXT
));
2476 /** As write_bytes_to_file, but if the file already exists, append the bytes
2477 * to the end of the file instead of overwriting it. */
2479 append_bytes_to_file(const char *fname
, const char *str
, size_t len
,
2482 return write_bytes_to_file_impl(fname
, str
, len
,
2483 OPEN_FLAGS_APPEND
|(bin
?O_BINARY
:O_TEXT
));
2486 /** Like write_str_to_file(), but also return -1 if there was a file
2487 already residing in <b>fname</b>. */
2489 write_bytes_to_new_file(const char *fname
, const char *str
, size_t len
,
2492 return write_bytes_to_file_impl(fname
, str
, len
,
2493 OPEN_FLAGS_DONT_REPLACE
|
2494 (bin
?O_BINARY
:O_TEXT
));
2498 * Read the contents of the open file <b>fd</b> presuming it is a FIFO
2499 * (or similar) file descriptor for which the size of the file isn't
2500 * known ahead of time. Return NULL on failure, and a NUL-terminated
2501 * string on success. On success, set <b>sz_out</b> to the number of
2505 read_file_to_str_until_eof(int fd
, size_t max_bytes_to_read
, size_t *sz_out
)
2509 char *string
= NULL
;
2510 size_t string_max
= 0;
2512 if (max_bytes_to_read
+1 >= SIZE_T_CEILING
) {
2518 /* XXXX This "add 1K" approach is a little goofy; if we care about
2519 * performance here, we should be doubling. But in practice we shouldn't
2520 * be using this function on big files anyway. */
2521 string_max
= pos
+ 1024;
2522 if (string_max
> max_bytes_to_read
)
2523 string_max
= max_bytes_to_read
+ 1;
2524 string
= tor_realloc(string
, string_max
);
2525 r
= read(fd
, string
+ pos
, string_max
- pos
- 1);
2527 int save_errno
= errno
;
2534 } while (r
> 0 && pos
< max_bytes_to_read
);
2536 tor_assert(pos
< string_max
);
2542 /** Read the contents of <b>filename</b> into a newly allocated
2543 * string; return the string on success or NULL on failure.
2545 * If <b>stat_out</b> is provided, store the result of stat()ing the
2546 * file into <b>stat_out</b>.
2548 * If <b>flags</b> & RFTS_BIN, open the file in binary mode.
2549 * If <b>flags</b> & RFTS_IGNORE_MISSING, don't warn if the file
2553 * This function <em>may</em> return an erroneous result if the file
2554 * is modified while it is running, but must not crash or overflow.
2555 * Right now, the error case occurs when the file length grows between
2556 * the call to stat and the call to read_all: the resulting string will
2560 read_file_to_str(const char *filename
, int flags
, struct stat
*stat_out
)
2562 int fd
; /* router file */
2563 struct stat statbuf
;
2566 int bin
= flags
& RFTS_BIN
;
2568 tor_assert(filename
);
2570 fd
= tor_open_cloexec(filename
,O_RDONLY
|(bin
?O_BINARY
:O_TEXT
),0);
2572 int severity
= LOG_WARN
;
2573 int save_errno
= errno
;
2574 if (errno
== ENOENT
&& (flags
& RFTS_IGNORE_MISSING
))
2575 severity
= LOG_INFO
;
2576 log_fn(severity
, LD_FS
,"Could not open \"%s\": %s",filename
,
2582 if (fstat(fd
, &statbuf
)<0) {
2583 int save_errno
= errno
;
2585 log_warn(LD_FS
,"Could not fstat \"%s\".",filename
);
2591 /** When we detect that we're reading from a FIFO, don't read more than
2592 * this many bytes. It's insane overkill for most uses. */
2593 #define FIFO_READ_MAX (1024*1024)
2594 if (S_ISFIFO(statbuf
.st_mode
)) {
2596 string
= read_file_to_str_until_eof(fd
, FIFO_READ_MAX
, &sz
);
2597 int save_errno
= errno
;
2598 if (string
&& stat_out
) {
2599 statbuf
.st_size
= sz
;
2600 memcpy(stat_out
, &statbuf
, sizeof(struct stat
));
2609 if ((uint64_t)(statbuf
.st_size
)+1 >= SIZE_T_CEILING
) {
2615 string
= tor_malloc((size_t)(statbuf
.st_size
+1));
2617 r
= read_all(fd
,string
,(size_t)statbuf
.st_size
,0);
2619 int save_errno
= errno
;
2620 log_warn(LD_FS
,"Error reading from file \"%s\": %s", filename
,
2627 string
[r
] = '\0'; /* NUL-terminate the result. */
2629 #if defined(_WIN32) || defined(__CYGWIN__)
2630 if (!bin
&& strchr(string
, '\r')) {
2631 log_debug(LD_FS
, "We didn't convert CRLF to LF as well as we hoped "
2632 "when reading %s. Coping.",
2634 tor_strstrip(string
, "\r");
2638 statbuf
.st_size
= (size_t) r
;
2641 if (r
!= statbuf
.st_size
) {
2642 /* Unless we're using text mode on win32, we'd better have an exact
2643 * match for size. */
2644 int save_errno
= errno
;
2645 log_warn(LD_FS
,"Could read only %d of %ld bytes of file \"%s\".",
2646 (int)r
, (long)statbuf
.st_size
,filename
);
2654 memcpy(stat_out
, &statbuf
, sizeof(struct stat
));
2660 #define TOR_ISODIGIT(c) ('0' <= (c) && (c) <= '7')
2662 /** Given a c-style double-quoted escaped string in <b>s</b>, extract and
2663 * decode its contents into a newly allocated string. On success, assign this
2664 * string to *<b>result</b>, assign its length to <b>size_out</b> (if
2665 * provided), and return a pointer to the position in <b>s</b> immediately
2666 * after the string. On failure, return NULL.
2669 unescape_string(const char *s
, char **result
, size_t *size_out
)
2684 if (cp
[1] == 'x' || cp
[1] == 'X') {
2685 if (!(TOR_ISXDIGIT(cp
[2]) && TOR_ISXDIGIT(cp
[3])))
2688 } else if (TOR_ISODIGIT(cp
[1])) {
2690 if (TOR_ISODIGIT(*cp
)) ++cp
;
2691 if (TOR_ISODIGIT(*cp
)) ++cp
;
2692 } else if (cp
[1] == 'n' || cp
[1] == 'r' || cp
[1] == 't' || cp
[1] == '"'
2693 || cp
[1] == '\\' || cp
[1] == '\'') {
2705 out
= *result
= tor_malloc(cp
-s
+ 1);
2712 if (size_out
) *size_out
= out
- *result
;
2715 tor_fragile_assert();
2721 case 'n': *out
++ = '\n'; cp
+= 2; break;
2722 case 'r': *out
++ = '\r'; cp
+= 2; break;
2723 case 't': *out
++ = '\t'; cp
+= 2; break;
2728 x1
= hex_decode_digit(cp
[2]);
2729 x2
= hex_decode_digit(cp
[3]);
2730 if (x1
== -1 || x2
== -1) {
2735 *out
++ = ((x1
<<4) + x2
);
2739 case '0': case '1': case '2': case '3': case '4': case '5':
2744 if (TOR_ISODIGIT(*cp
)) { n
= n
*8 + *cp
-'0'; cp
++; }
2745 if (TOR_ISODIGIT(*cp
)) { n
= n
*8 + *cp
-'0'; cp
++; }
2746 if (n
> 255) { tor_free(*result
); return NULL
; }
2758 tor_free(*result
); return NULL
;
2767 /** Given a string containing part of a configuration file or similar format,
2768 * advance past comments and whitespace and try to parse a single line. If we
2769 * parse a line successfully, set *<b>key_out</b> to a new string holding the
2770 * key portion and *<b>value_out</b> to a new string holding the value portion
2771 * of the line, and return a pointer to the start of the next line. If we run
2772 * out of data, return a pointer to the end of the string. If we encounter an
2773 * error, return NULL and set *<b>err_out</b> (if provided) to an error
2777 parse_config_line_from_str_verbose(const char *line
, char **key_out
,
2779 const char **err_out
)
2782 See torrc_format.txt for a description of the (silly) format this parses.
2784 const char *key
, *val
, *cp
;
2785 int continuation
= 0;
2787 tor_assert(key_out
);
2788 tor_assert(value_out
);
2790 *key_out
= *value_out
= NULL
;
2792 /* Skip until the first keyword. */
2794 while (TOR_ISSPACE(*line
))
2797 while (*line
&& *line
!= '\n')
2804 if (!*line
) { /* End of string? */
2805 *key_out
= *value_out
= NULL
;
2809 /* Skip until the next space or \ followed by newline. */
2811 while (*line
&& !TOR_ISSPACE(*line
) && *line
!= '#' &&
2812 ! (line
[0] == '\\' && line
[1] == '\n'))
2814 *key_out
= tor_strndup(key
, line
-key
);
2816 /* Skip until the value. */
2817 while (*line
== ' ' || *line
== '\t')
2822 /* Find the end of the line. */
2823 if (*line
== '\"') { // XXX No continuation handling is done here
2824 if (!(line
= unescape_string(line
, value_out
, NULL
))) {
2826 *err_out
= "Invalid escape sequence in quoted string";
2829 while (*line
== ' ' || *line
== '\t')
2831 if (*line
&& *line
!= '#' && *line
!= '\n') {
2833 *err_out
= "Excess data after quoted string";
2837 /* Look for the end of the line. */
2838 while (*line
&& *line
!= '\n' && (*line
!= '#' || continuation
)) {
2839 if (*line
== '\\' && line
[1] == '\n') {
2842 } else if (*line
== '#') {
2845 } while (*line
&& *line
!= '\n');
2853 if (*line
== '\n') {
2858 /* Now back cp up to be the last nonspace character */
2859 while (cp
>val
&& TOR_ISSPACE(*(cp
-1)))
2862 tor_assert(cp
>= val
);
2864 /* Now copy out and decode the value. */
2865 *value_out
= tor_strndup(val
, cp
-val
);
2868 v_out
= v_in
= *value_out
;
2873 } while (*v_in
&& *v_in
!= '\n');
2876 } else if (v_in
[0] == '\\' && v_in
[1] == '\n') {
2889 } while (*line
&& *line
!= '\n');
2891 while (TOR_ISSPACE(*line
)) ++line
;
2896 /** Expand any homedir prefix on <b>filename</b>; return a newly allocated
2899 expand_filename(const char *filename
)
2901 tor_assert(filename
);
2903 return tor_strdup(filename
);
2905 if (*filename
== '~') {
2906 char *home
, *result
=NULL
;
2909 if (filename
[1] == '/' || filename
[1] == '\0') {
2910 home
= getenv("HOME");
2912 log_warn(LD_CONFIG
, "Couldn't find $HOME environment variable while "
2913 "expanding \"%s\"; defaulting to \"\".", filename
);
2914 home
= tor_strdup("");
2916 home
= tor_strdup(home
);
2918 rest
= strlen(filename
)>=2?(filename
+2):"";
2921 char *username
, *slash
;
2922 slash
= strchr(filename
, '/');
2924 username
= tor_strndup(filename
+1,slash
-filename
-1);
2926 username
= tor_strdup(filename
+1);
2927 if (!(home
= get_user_homedir(username
))) {
2928 log_warn(LD_CONFIG
,"Couldn't get homedir for \"%s\"",username
);
2933 rest
= slash
? (slash
+1) : "";
2935 log_warn(LD_CONFIG
, "Couldn't expand homedir on system without pwd.h");
2936 return tor_strdup(filename
);
2940 /* Remove trailing slash. */
2941 if (strlen(home
)>1 && !strcmpend(home
,PATH_SEPARATOR
)) {
2942 home
[strlen(home
)-1] = '\0';
2944 tor_asprintf(&result
,"%s"PATH_SEPARATOR
"%s",home
,rest
);
2948 return tor_strdup(filename
);
2953 #define MAX_SCANF_WIDTH 9999
2955 /** Helper: given an ASCII-encoded decimal digit, return its numeric value.
2956 * NOTE: requires that its input be in-bounds. */
2958 digit_to_num(char d
)
2960 int num
= ((int)d
) - (int)'0';
2961 tor_assert(num
<= 9 && num
>= 0);
2965 /** Helper: Read an unsigned int from *<b>bufp</b> of up to <b>width</b>
2966 * characters. (Handle arbitrary width if <b>width</b> is less than 0.) On
2967 * success, store the result in <b>out</b>, advance bufp to the next
2968 * character, and return 0. On failure, return -1. */
2970 scan_unsigned(const char **bufp
, unsigned long *out
, int width
, int base
)
2972 unsigned long result
= 0;
2973 int scanned_so_far
= 0;
2974 const int hex
= base
==16;
2975 tor_assert(base
== 10 || base
== 16);
2976 if (!bufp
|| !*bufp
|| !out
)
2979 width
=MAX_SCANF_WIDTH
;
2981 while (**bufp
&& (hex
?TOR_ISXDIGIT(**bufp
):TOR_ISDIGIT(**bufp
))
2982 && scanned_so_far
< width
) {
2983 int digit
= hex
?hex_decode_digit(*(*bufp
)++):digit_to_num(*(*bufp
)++);
2984 // Check for overflow beforehand, without actually causing any overflow
2985 // This preserves functionality on compilers that don't wrap overflow
2986 // (i.e. that trap or optimise away overflow)
2987 // result * base + digit > ULONG_MAX
2988 // result * base > ULONG_MAX - digit
2989 if (result
> (ULONG_MAX
- digit
)/base
)
2990 return -1; /* Processing this digit would overflow */
2991 result
= result
* base
+ digit
;
2995 if (!scanned_so_far
) /* No actual digits scanned */
3002 /** Helper: Read an signed int from *<b>bufp</b> of up to <b>width</b>
3003 * characters. (Handle arbitrary width if <b>width</b> is less than 0.) On
3004 * success, store the result in <b>out</b>, advance bufp to the next
3005 * character, and return 0. On failure, return -1. */
3007 scan_signed(const char **bufp
, long *out
, int width
)
3010 unsigned long result
= 0;
3012 if (!bufp
|| !*bufp
|| !out
)
3015 width
=MAX_SCANF_WIDTH
;
3017 if (**bufp
== '-') {
3023 if (scan_unsigned(bufp
, &result
, width
, 10) < 0)
3026 if (neg
&& result
> 0) {
3027 if (result
> ((unsigned long)LONG_MAX
) + 1)
3028 return -1; /* Underflow */
3029 // Avoid overflow on the cast to signed long when result is LONG_MIN
3030 // by subtracting 1 from the unsigned long positive value,
3031 // then, after it has been cast to signed and negated,
3032 // subtracting the original 1 (the double-subtraction is intentional).
3033 // Otherwise, the cast to signed could cause a temporary long
3034 // to equal LONG_MAX + 1, which is undefined.
3035 // We avoid underflow on the subtraction by treating -0 as positive.
3036 *out
= (-(long)(result
- 1)) - 1;
3038 if (result
> LONG_MAX
)
3039 return -1; /* Overflow */
3040 *out
= (long)result
;
3046 /** Helper: Read a decimal-formatted double from *<b>bufp</b> of up to
3047 * <b>width</b> characters. (Handle arbitrary width if <b>width</b> is less
3048 * than 0.) On success, store the result in <b>out</b>, advance bufp to the
3049 * next character, and return 0. On failure, return -1. */
3051 scan_double(const char **bufp
, double *out
, int width
)
3055 int scanned_so_far
= 0;
3057 if (!bufp
|| !*bufp
|| !out
)
3060 width
=MAX_SCANF_WIDTH
;
3062 if (**bufp
== '-') {
3067 while (**bufp
&& TOR_ISDIGIT(**bufp
) && scanned_so_far
< width
) {
3068 const int digit
= digit_to_num(*(*bufp
)++);
3069 result
= result
* 10 + digit
;
3072 if (**bufp
== '.') {
3073 double fracval
= 0, denominator
= 1;
3076 while (**bufp
&& TOR_ISDIGIT(**bufp
) && scanned_so_far
< width
) {
3077 const int digit
= digit_to_num(*(*bufp
)++);
3078 fracval
= fracval
* 10 + digit
;
3082 result
+= fracval
/ denominator
;
3085 if (!scanned_so_far
) /* No actual digits scanned */
3088 *out
= neg
? -result
: result
;
3092 /** Helper: copy up to <b>width</b> non-space characters from <b>bufp</b> to
3093 * <b>out</b>. Make sure <b>out</b> is nul-terminated. Advance <b>bufp</b>
3094 * to the next non-space character or the EOS. */
3096 scan_string(const char **bufp
, char *out
, int width
)
3098 int scanned_so_far
= 0;
3099 if (!bufp
|| !out
|| width
< 0)
3101 while (**bufp
&& ! TOR_ISSPACE(**bufp
) && scanned_so_far
< width
) {
3102 *out
++ = *(*bufp
)++;
3109 /** Locale-independent, minimal, no-surprises scanf variant, accepting only a
3110 * restricted pattern format. For more info on what it supports, see
3111 * tor_sscanf() documentation. */
3113 tor_vsscanf(const char *buf
, const char *pattern
, va_list ap
)
3118 if (*pattern
!= '%') {
3119 if (*buf
== *pattern
) {
3130 if (TOR_ISDIGIT(*pattern
)) {
3131 width
= digit_to_num(*pattern
++);
3132 while (TOR_ISDIGIT(*pattern
)) {
3134 width
+= digit_to_num(*pattern
++);
3135 if (width
> MAX_SCANF_WIDTH
)
3138 if (!width
) /* No zero-width things. */
3141 if (*pattern
== 'l') {
3145 if (*pattern
== 'u' || *pattern
== 'x') {
3147 const int base
= (*pattern
== 'u') ? 10 : 16;
3150 if (scan_unsigned(&buf
, &u
, width
, base
)<0)
3153 unsigned long *out
= va_arg(ap
, unsigned long *);
3156 unsigned *out
= va_arg(ap
, unsigned *);
3159 *out
= (unsigned) u
;
3163 } else if (*pattern
== 'f') {
3164 double *d
= va_arg(ap
, double *);
3166 return -1; /* float not supported */
3169 if (scan_double(&buf
, d
, width
)<0)
3173 } else if (*pattern
== 'd') {
3175 if (scan_signed(&buf
, &lng
, width
)<0)
3178 long *out
= va_arg(ap
, long *);
3181 int *out
= va_arg(ap
, int *);
3182 if (lng
< INT_MIN
|| lng
> INT_MAX
)
3188 } else if (*pattern
== 's') {
3189 char *s
= va_arg(ap
, char *);
3194 if (scan_string(&buf
, s
, width
)<0)
3198 } else if (*pattern
== 'c') {
3199 char *ch
= va_arg(ap
, char *);
3209 } else if (*pattern
== '%') {
3217 return -1; /* Unrecognized pattern component. */
3225 /** Minimal sscanf replacement: parse <b>buf</b> according to <b>pattern</b>
3226 * and store the results in the corresponding argument fields. Differs from
3228 * <ul><li>It only handles %u, %lu, %x, %lx, %[NUM]s, %d, %ld, %lf, and %c.
3229 * <li>It only handles decimal inputs for %lf. (12.3, not 1.23e1)
3230 * <li>It does not handle arbitrarily long widths.
3231 * <li>Numbers do not consume any space characters.
3232 * <li>It is locale-independent.
3233 * <li>%u and %x do not consume any space.
3234 * <li>It returns -1 on malformed patterns.</ul>
3236 * (As with other locale-independent functions, we need this to parse data that
3237 * is in ASCII without worrying that the C library's locale-handling will make
3238 * miscellaneous characters look like numbers, spaces, and so on.)
3241 tor_sscanf(const char *buf
, const char *pattern
, ...)
3245 va_start(ap
, pattern
);
3246 r
= tor_vsscanf(buf
, pattern
, ap
);
3251 /** Append the string produced by tor_asprintf(<b>pattern</b>, <b>...</b>)
3254 smartlist_add_asprintf(struct smartlist_t
*sl
, const char *pattern
, ...)
3257 va_start(ap
, pattern
);
3258 smartlist_add_vasprintf(sl
, pattern
, ap
);
3262 /** va_list-based backend of smartlist_add_asprintf. */
3264 smartlist_add_vasprintf(struct smartlist_t
*sl
, const char *pattern
,
3269 tor_vasprintf(&str
, pattern
, args
);
3270 tor_assert(str
!= NULL
);
3272 smartlist_add(sl
, str
);
3275 /** Return a new list containing the filenames in the directory <b>dirname</b>.
3276 * Return NULL on error or if <b>dirname</b> is not a directory.
3279 tor_listdir(const char *dirname
)
3281 smartlist_t
*result
;
3284 TCHAR tpattern
[MAX_PATH
] = {0};
3285 char name
[MAX_PATH
*2+1] = {0};
3287 WIN32_FIND_DATA findData
;
3288 tor_asprintf(&pattern
, "%s\\*", dirname
);
3290 mbstowcs(tpattern
,pattern
,MAX_PATH
);
3292 strlcpy(tpattern
, pattern
, MAX_PATH
);
3294 if (INVALID_HANDLE_VALUE
== (handle
= FindFirstFile(tpattern
, &findData
))) {
3298 result
= smartlist_new();
3301 wcstombs(name
,findData
.cFileName
,MAX_PATH
);
3302 name
[sizeof(name
)-1] = '\0';
3304 strlcpy(name
,findData
.cFileName
,sizeof(name
));
3306 if (strcmp(name
, ".") &&
3307 strcmp(name
, "..")) {
3308 smartlist_add(result
, tor_strdup(name
));
3310 if (!FindNextFile(handle
, &findData
)) {
3312 if ((err
= GetLastError()) != ERROR_NO_MORE_FILES
) {
3313 char *errstr
= format_win32_error(err
);
3314 log_warn(LD_FS
, "Error reading directory '%s': %s", dirname
, errstr
);
3323 const char *prot_dname
= sandbox_intern_string(dirname
);
3326 if (!(d
= opendir(prot_dname
)))
3329 result
= smartlist_new();
3330 while ((de
= readdir(d
))) {
3331 if (!strcmp(de
->d_name
, ".") ||
3332 !strcmp(de
->d_name
, ".."))
3334 smartlist_add(result
, tor_strdup(de
->d_name
));
3341 /** Return true iff <b>filename</b> is a relative path. */
3343 path_is_relative(const char *filename
)
3345 if (filename
&& filename
[0] == '/')
3348 else if (filename
&& filename
[0] == '\\')
3350 else if (filename
&& strlen(filename
)>3 && TOR_ISALPHA(filename
[0]) &&
3351 filename
[1] == ':' && filename
[2] == '\\')
3363 /* Based on code contributed by christian grothoff */
3364 /** True iff we've called start_daemon(). */
3365 static int start_daemon_called
= 0;
3366 /** True iff we've called finish_daemon(). */
3367 static int finish_daemon_called
= 0;
3368 /** Socketpair used to communicate between parent and child process while
3370 static int daemon_filedes
[2];
3371 /** Start putting the process into daemon mode: fork and drop all resources
3372 * except standard fds. The parent process never returns, but stays around
3373 * until finish_daemon is called. (Note: it's safe to call this more
3374 * than once: calls after the first are ignored.)
3381 if (start_daemon_called
)
3383 start_daemon_called
= 1;
3385 if (pipe(daemon_filedes
)) {
3386 log_err(LD_GENERAL
,"pipe failed; exiting. Error was %s", strerror(errno
));
3391 log_err(LD_GENERAL
,"fork failed. Exiting.");
3394 if (pid
) { /* Parent */
3398 close(daemon_filedes
[1]); /* we only read */
3400 while (0 < read(daemon_filedes
[0], &c
, sizeof(char))) {
3408 exit(1); /* child reported error */
3409 } else { /* Child */
3410 close(daemon_filedes
[0]); /* we only write */
3412 pid
= setsid(); /* Detach from controlling terminal */
3414 * Fork one more time, so the parent (the session group leader) can exit.
3415 * This means that we, as a non-session group leader, can never regain a
3416 * controlling terminal. This part is recommended by Stevens's
3417 * _Advanced Programming in the Unix Environment_.
3422 set_main_thread(); /* We are now the main thread. */
3428 /** Finish putting the process into daemon mode: drop standard fds, and tell
3429 * the parent process to exit. (Note: it's safe to call this more than once:
3430 * calls after the first are ignored. Calls start_daemon first if it hasn't
3431 * been called already.)
3434 finish_daemon(const char *desired_cwd
)
3438 if (finish_daemon_called
)
3440 if (!start_daemon_called
)
3442 finish_daemon_called
= 1;
3446 /* Don't hold the wrong FS mounted */
3447 if (chdir(desired_cwd
) < 0) {
3448 log_err(LD_GENERAL
,"chdir to \"%s\" failed. Exiting.",desired_cwd
);
3452 nullfd
= tor_open_cloexec("/dev/null", O_RDWR
, 0);
3454 log_err(LD_GENERAL
,"/dev/null can't be opened. Exiting.");
3457 /* close fds linking to invoking terminal, but
3458 * close usual incoming fds, but redirect them somewhere
3459 * useful so the fds don't get reallocated elsewhere.
3461 if (dup2(nullfd
,0) < 0 ||
3462 dup2(nullfd
,1) < 0 ||
3463 dup2(nullfd
,2) < 0) {
3464 log_err(LD_GENERAL
,"dup2 failed. Exiting.");
3469 /* signal success */
3470 if (write(daemon_filedes
[1], &c
, sizeof(char)) != sizeof(char)) {
3471 log_err(LD_GENERAL
,"write failed. Exiting.");
3473 close(daemon_filedes
[1]);
3476 /* defined(_WIN32) */
3482 finish_daemon(const char *cp
)
3488 /** Write the current process ID, followed by NL, into <b>filename</b>.
3491 write_pidfile(const char *filename
)
3495 if ((pidfile
= fopen(filename
, "w")) == NULL
) {
3496 log_warn(LD_FS
, "Unable to open \"%s\" for writing: %s", filename
,
3500 fprintf(pidfile
, "%d\n", (int)_getpid());
3502 fprintf(pidfile
, "%d\n", (int)getpid());
3510 load_windows_system_library(const TCHAR
*library_name
)
3512 TCHAR path
[MAX_PATH
];
3514 n
= GetSystemDirectory(path
, MAX_PATH
);
3515 if (n
== 0 || n
+ _tcslen(library_name
) + 2 >= MAX_PATH
)
3517 _tcscat(path
, TEXT("\\"));
3518 _tcscat(path
, library_name
);
3519 return LoadLibrary(path
);
3523 /** Format a single argument for being put on a Windows command line.
3524 * Returns a newly allocated string */
3526 format_win_cmdline_argument(const char *arg
)
3528 char *formatted_arg
;
3533 /* Backslash we can point to when one is inserted into the string */
3534 const char backslash
= '\\';
3536 /* Smartlist of *char */
3537 smartlist_t
*arg_chars
;
3538 arg_chars
= smartlist_new();
3540 /* Quote string if it contains whitespace or is empty */
3541 need_quotes
= (strchr(arg
, ' ') || strchr(arg
, '\t') || '\0' == arg
[0]);
3543 /* Build up smartlist of *chars */
3544 for (c
=arg
; *c
!= '\0'; c
++) {
3546 /* Double up backslashes preceding a quote */
3547 for (i
=0; i
<(bs_counter
*2); i
++)
3548 smartlist_add(arg_chars
, (void*)&backslash
);
3550 /* Escape the quote */
3551 smartlist_add(arg_chars
, (void*)&backslash
);
3552 smartlist_add(arg_chars
, (void*)c
);
3553 } else if ('\\' == *c
) {
3554 /* Count backslashes until we know whether to double up */
3557 /* Don't double up slashes preceding a non-quote */
3558 for (i
=0; i
<bs_counter
; i
++)
3559 smartlist_add(arg_chars
, (void*)&backslash
);
3561 smartlist_add(arg_chars
, (void*)c
);
3564 /* Don't double up trailing backslashes */
3565 for (i
=0; i
<bs_counter
; i
++)
3566 smartlist_add(arg_chars
, (void*)&backslash
);
3568 /* Allocate space for argument, quotes (if needed), and terminator */
3569 const size_t formatted_arg_len
= smartlist_len(arg_chars
) +
3570 (need_quotes
? 2 : 0) + 1;
3571 formatted_arg
= tor_malloc_zero(formatted_arg_len
);
3573 /* Add leading quote */
3576 formatted_arg
[i
++] = '"';
3578 /* Add characters */
3579 SMARTLIST_FOREACH(arg_chars
, char*, c
,
3581 formatted_arg
[i
++] = *c
;
3584 /* Add trailing quote */
3586 formatted_arg
[i
++] = '"';
3587 formatted_arg
[i
] = '\0';
3589 smartlist_free(arg_chars
);
3590 return formatted_arg
;
3593 /** Format a command line for use on Windows, which takes the command as a
3594 * string rather than string array. Follows the rules from "Parsing C++
3595 * Command-Line Arguments" in MSDN. Algorithm based on list2cmdline in the
3596 * Python subprocess module. Returns a newly allocated string */
3598 tor_join_win_cmdline(const char *argv
[])
3600 smartlist_t
*argv_list
;
3604 /* Format each argument and put the result in a smartlist */
3605 argv_list
= smartlist_new();
3606 for (i
=0; argv
[i
] != NULL
; i
++) {
3607 smartlist_add(argv_list
, (void *)format_win_cmdline_argument(argv
[i
]));
3610 /* Join the arguments with whitespace */
3611 joined_argv
= smartlist_join_strings(argv_list
, " ", 0, NULL
);
3613 /* Free the newly allocated arguments, and the smartlist */
3614 SMARTLIST_FOREACH(argv_list
, char *, arg
,
3618 smartlist_free(argv_list
);
3623 /* As format_{hex,dex}_number_sigsafe, but takes a <b>radix</b> argument
3624 * in range 2..16 inclusive. */
3626 format_number_sigsafe(unsigned long x
, char *buf
, int buf_len
,
3633 /* NOT tor_assert. This needs to be safe to run from within a signal handler,
3634 * and from within the 'tor_assert() has failed' code. */
3635 if (radix
< 2 || radix
> 16)
3638 /* Count how many digits we need. */
3641 while (tmp
>= radix
) {
3646 /* Not long enough */
3647 if (!buf
|| len
>= buf_len
)
3653 unsigned digit
= (unsigned) (x
% radix
);
3654 tor_assert(cp
> buf
);
3656 *cp
= "0123456789ABCDEF"[digit
];
3660 /* NOT tor_assert; see above. */
3669 * Helper function to output hex numbers from within a signal handler.
3671 * Writes the nul-terminated hexadecimal digits of <b>x</b> into a buffer
3672 * <b>buf</b> of size <b>buf_len</b>, and return the actual number of digits
3673 * written, not counting the terminal NUL.
3675 * If there is insufficient space, write nothing and return 0.
3677 * This accepts an unsigned int because format_helper_exit_status() needs to
3678 * call it with a signed int and an unsigned char, and since the C standard
3679 * does not guarantee that an int is wider than a char (an int must be at
3680 * least 16 bits but it is permitted for a char to be that wide as well), we
3681 * can't assume a signed int is sufficient to accomodate an unsigned char.
3682 * Thus, format_helper_exit_status() will still need to emit any require '-'
3685 * For most purposes, you'd want to use tor_snprintf("%x") instead of this
3686 * function; it's designed to be used in code paths where you can't call
3687 * arbitrary C functions.
3690 format_hex_number_sigsafe(unsigned long x
, char *buf
, int buf_len
)
3692 return format_number_sigsafe(x
, buf
, buf_len
, 16);
3695 /** As format_hex_number_sigsafe, but format the number in base 10. */
3697 format_dec_number_sigsafe(unsigned long x
, char *buf
, int buf_len
)
3699 return format_number_sigsafe(x
, buf
, buf_len
, 10);
3703 /** Format <b>child_state</b> and <b>saved_errno</b> as a hex string placed in
3704 * <b>hex_errno</b>. Called between fork and _exit, so must be signal-handler
3707 * <b>hex_errno</b> must have at least HEX_ERRNO_SIZE+1 bytes available.
3709 * The format of <b>hex_errno</b> is: "CHILD_STATE/ERRNO\n", left-padded
3710 * with spaces. CHILD_STATE indicates where
3711 * in the processs of starting the child process did the failure occur (see
3712 * CHILD_STATE_* macros for definition), and SAVED_ERRNO is the value of
3713 * errno when the failure occurred.
3715 * On success return the number of characters added to hex_errno, not counting
3716 * the terminating NUL; return -1 on error.
3719 format_helper_exit_status(unsigned char child_state
, int saved_errno
,
3722 unsigned int unsigned_errno
;
3728 /* Fill hex_errno with spaces, and a trailing newline (memset may
3729 not be signal handler safe, so we can't use it) */
3730 for (i
= 0; i
< (HEX_ERRNO_SIZE
- 1); i
++)
3732 hex_errno
[HEX_ERRNO_SIZE
- 1] = '\n';
3734 /* Convert errno to be unsigned for hex conversion */
3735 if (saved_errno
< 0) {
3736 // Avoid overflow on the cast to unsigned int when result is INT_MIN
3737 // by adding 1 to the signed int negative value,
3738 // then, after it has been negated and cast to unsigned,
3739 // adding the original 1 back (the double-addition is intentional).
3740 // Otherwise, the cast to signed could cause a temporary int
3741 // to equal INT_MAX + 1, which is undefined.
3742 unsigned_errno
= ((unsigned int) -(saved_errno
+ 1)) + 1;
3744 unsigned_errno
= (unsigned int) saved_errno
;
3748 * Count how many chars of space we have left, and keep a pointer into the
3749 * current point in the buffer.
3751 left
= HEX_ERRNO_SIZE
+1;
3754 /* Emit child_state */
3755 written
= format_hex_number_sigsafe(child_state
, cur
, left
);
3760 /* Adjust left and cur */
3769 /* Adjust left and cur */
3776 if (saved_errno
< 0) {
3784 /* Emit unsigned_errno */
3785 written
= format_hex_number_sigsafe(unsigned_errno
, cur
, left
);
3790 /* Adjust left and cur */
3794 /* Check that we have enough space left for a newline and a NUL */
3798 /* Emit the newline and NUL */
3802 res
= (int)(cur
- hex_errno
- 1);
3808 * In error exit, just write a '\0' in the first char so whatever called
3809 * this at least won't fall off the end.
3818 /* Maximum number of file descriptors, if we cannot get it via sysconf() */
3819 #define DEFAULT_MAX_FD 256
3821 /** Terminate the process of <b>process_handle</b>.
3822 * Code borrowed from Python's os.kill. */
3824 tor_terminate_process(process_handle_t
*process_handle
)
3827 if (tor_get_exit_code(process_handle
, 0, NULL
) == PROCESS_EXIT_RUNNING
) {
3828 HANDLE handle
= process_handle
->pid
.hProcess
;
3830 if (!TerminateProcess(handle
, 0))
3836 if (process_handle
->waitpid_cb
) {
3837 /* We haven't got a waitpid yet, so we can just kill off the process. */
3838 return kill(process_handle
->pid
, SIGTERM
);
3845 /** Return the Process ID of <b>process_handle</b>. */
3847 tor_process_get_pid(process_handle_t
*process_handle
)
3850 return (int) process_handle
->pid
.dwProcessId
;
3852 return (int) process_handle
->pid
;
3858 tor_process_get_stdout_pipe(process_handle_t
*process_handle
)
3860 return process_handle
->stdout_pipe
;
3863 /* DOCDOC tor_process_get_stdout_pipe */
3865 tor_process_get_stdout_pipe(process_handle_t
*process_handle
)
3867 return process_handle
->stdout_handle
;
3871 /* DOCDOC process_handle_new */
3872 static process_handle_t
*
3873 process_handle_new(void)
3875 process_handle_t
*out
= tor_malloc_zero(sizeof(process_handle_t
));
3878 out
->stdin_pipe
= INVALID_HANDLE_VALUE
;
3879 out
->stdout_pipe
= INVALID_HANDLE_VALUE
;
3880 out
->stderr_pipe
= INVALID_HANDLE_VALUE
;
3882 out
->stdin_pipe
= -1;
3883 out
->stdout_pipe
= -1;
3884 out
->stderr_pipe
= -1;
3891 /** Invoked when a process that we've launched via tor_spawn_background() has
3892 * been found to have terminated.
3895 process_handle_waitpid_cb(int status
, void *arg
)
3897 process_handle_t
*process_handle
= arg
;
3899 process_handle
->waitpid_exit_status
= status
;
3900 clear_waitpid_callback(process_handle
->waitpid_cb
);
3901 if (process_handle
->status
== PROCESS_STATUS_RUNNING
)
3902 process_handle
->status
= PROCESS_STATUS_NOTRUNNING
;
3903 process_handle
->waitpid_cb
= 0;
3908 * @name child-process states
3910 * Each of these values represents a possible state that a child process can
3911 * be in. They're used to determine what to say when telling the parent how
3912 * far along we were before failure.
3916 #define CHILD_STATE_INIT 0
3917 #define CHILD_STATE_PIPE 1
3918 #define CHILD_STATE_MAXFD 2
3919 #define CHILD_STATE_FORK 3
3920 #define CHILD_STATE_DUPOUT 4
3921 #define CHILD_STATE_DUPERR 5
3922 #define CHILD_STATE_DUPIN 6
3923 #define CHILD_STATE_CLOSEFD 7
3924 #define CHILD_STATE_EXEC 8
3925 #define CHILD_STATE_FAILEXEC 9
3927 /** Start a program in the background. If <b>filename</b> contains a '/', then
3928 * it will be treated as an absolute or relative path. Otherwise, on
3929 * non-Windows systems, the system path will be searched for <b>filename</b>.
3930 * On Windows, only the current directory will be searched. Here, to search the
3931 * system path (as well as the application directory, current working
3932 * directory, and system directories), set filename to NULL.
3934 * The strings in <b>argv</b> will be passed as the command line arguments of
3935 * the child program (following convention, argv[0] should normally be the
3936 * filename of the executable, and this must be the case if <b>filename</b> is
3937 * NULL). The last element of argv must be NULL. A handle to the child process
3938 * will be returned in process_handle (which must be non-NULL). Read
3939 * process_handle.status to find out if the process was successfully launched.
3940 * For convenience, process_handle.status is returned by this function.
3942 * Some parts of this code are based on the POSIX subprocess module from
3943 * Python, and example code from
3944 * http://msdn.microsoft.com/en-us/library/ms682499%28v=vs.85%29.aspx.
3947 tor_spawn_background(const char *const filename
, const char **argv
,
3948 process_environment_t
*env
,
3949 process_handle_t
**process_handle_out
)
3952 HANDLE stdout_pipe_read
= NULL
;
3953 HANDLE stdout_pipe_write
= NULL
;
3954 HANDLE stderr_pipe_read
= NULL
;
3955 HANDLE stderr_pipe_write
= NULL
;
3956 HANDLE stdin_pipe_read
= NULL
;
3957 HANDLE stdin_pipe_write
= NULL
;
3958 process_handle_t
*process_handle
;
3961 STARTUPINFOA siStartInfo
;
3962 BOOL retval
= FALSE
;
3964 SECURITY_ATTRIBUTES saAttr
;
3967 saAttr
.nLength
= sizeof(SECURITY_ATTRIBUTES
);
3968 saAttr
.bInheritHandle
= TRUE
;
3969 /* TODO: should we set explicit security attributes? (#2046, comment 5) */
3970 saAttr
.lpSecurityDescriptor
= NULL
;
3972 /* Assume failure to start process */
3973 status
= PROCESS_STATUS_ERROR
;
3975 /* Set up pipe for stdout */
3976 if (!CreatePipe(&stdout_pipe_read
, &stdout_pipe_write
, &saAttr
, 0)) {
3977 log_warn(LD_GENERAL
,
3978 "Failed to create pipe for stdout communication with child process: %s",
3979 format_win32_error(GetLastError()));
3982 if (!SetHandleInformation(stdout_pipe_read
, HANDLE_FLAG_INHERIT
, 0)) {
3983 log_warn(LD_GENERAL
,
3984 "Failed to configure pipe for stdout communication with child "
3985 "process: %s", format_win32_error(GetLastError()));
3989 /* Set up pipe for stderr */
3990 if (!CreatePipe(&stderr_pipe_read
, &stderr_pipe_write
, &saAttr
, 0)) {
3991 log_warn(LD_GENERAL
,
3992 "Failed to create pipe for stderr communication with child process: %s",
3993 format_win32_error(GetLastError()));
3996 if (!SetHandleInformation(stderr_pipe_read
, HANDLE_FLAG_INHERIT
, 0)) {
3997 log_warn(LD_GENERAL
,
3998 "Failed to configure pipe for stderr communication with child "
3999 "process: %s", format_win32_error(GetLastError()));
4003 /* Set up pipe for stdin */
4004 if (!CreatePipe(&stdin_pipe_read
, &stdin_pipe_write
, &saAttr
, 0)) {
4005 log_warn(LD_GENERAL
,
4006 "Failed to create pipe for stdin communication with child process: %s",
4007 format_win32_error(GetLastError()));
4010 if (!SetHandleInformation(stdin_pipe_write
, HANDLE_FLAG_INHERIT
, 0)) {
4011 log_warn(LD_GENERAL
,
4012 "Failed to configure pipe for stdin communication with child "
4013 "process: %s", format_win32_error(GetLastError()));
4017 /* Create the child process */
4019 /* Windows expects argv to be a whitespace delimited string, so join argv up
4021 joined_argv
= tor_join_win_cmdline(argv
);
4023 process_handle
= process_handle_new();
4024 process_handle
->status
= status
;
4026 ZeroMemory(&(process_handle
->pid
), sizeof(PROCESS_INFORMATION
));
4027 ZeroMemory(&siStartInfo
, sizeof(STARTUPINFO
));
4028 siStartInfo
.cb
= sizeof(STARTUPINFO
);
4029 siStartInfo
.hStdError
= stderr_pipe_write
;
4030 siStartInfo
.hStdOutput
= stdout_pipe_write
;
4031 siStartInfo
.hStdInput
= stdin_pipe_read
;
4032 siStartInfo
.dwFlags
|= STARTF_USESTDHANDLES
;
4034 /* Create the child process */
4036 retval
= CreateProcessA(filename
, // module name
4037 joined_argv
, // command line
4038 /* TODO: should we set explicit security attributes? (#2046, comment 5) */
4039 NULL
, // process security attributes
4040 NULL
, // primary thread security attributes
4041 TRUE
, // handles are inherited
4042 /*(TODO: set CREATE_NEW CONSOLE/PROCESS_GROUP to make GetExitCodeProcess()
4044 CREATE_NO_WINDOW
, // creation flags
4045 (env
==NULL
) ? NULL
: env
->windows_environment_block
,
4046 NULL
, // use parent's current directory
4047 &siStartInfo
, // STARTUPINFO pointer
4048 &(process_handle
->pid
)); // receives PROCESS_INFORMATION
4050 tor_free(joined_argv
);
4053 log_warn(LD_GENERAL
,
4054 "Failed to create child process %s: %s", filename
?filename
:argv
[0],
4055 format_win32_error(GetLastError()));
4056 tor_free(process_handle
);
4058 /* TODO: Close hProcess and hThread in process_handle->pid? */
4059 process_handle
->stdout_pipe
= stdout_pipe_read
;
4060 process_handle
->stderr_pipe
= stderr_pipe_read
;
4061 process_handle
->stdin_pipe
= stdin_pipe_write
;
4062 status
= process_handle
->status
= PROCESS_STATUS_RUNNING
;
4065 /* TODO: Close pipes on exit */
4066 *process_handle_out
= process_handle
;
4075 process_handle_t
*process_handle
;
4078 const char *error_message
= SPAWN_ERROR_MESSAGE
;
4079 size_t error_message_length
;
4081 /* Represents where in the process of spawning the program is;
4082 this is used for printing out the error message */
4083 unsigned char child_state
= CHILD_STATE_INIT
;
4085 char hex_errno
[HEX_ERRNO_SIZE
+ 2]; /* + 1 should be sufficient actually */
4087 static int max_fd
= -1;
4089 status
= PROCESS_STATUS_ERROR
;
4091 /* We do the strlen here because strlen() is not signal handler safe,
4092 and we are not allowed to use unsafe functions between fork and exec */
4093 error_message_length
= strlen(error_message
);
4095 child_state
= CHILD_STATE_PIPE
;
4097 /* Set up pipe for redirecting stdout, stderr, and stdin of child */
4098 retval
= pipe(stdout_pipe
);
4100 log_warn(LD_GENERAL
,
4101 "Failed to set up pipe for stdout communication with child process: %s",
4106 retval
= pipe(stderr_pipe
);
4108 log_warn(LD_GENERAL
,
4109 "Failed to set up pipe for stderr communication with child process: %s",
4112 close(stdout_pipe
[0]);
4113 close(stdout_pipe
[1]);
4118 retval
= pipe(stdin_pipe
);
4120 log_warn(LD_GENERAL
,
4121 "Failed to set up pipe for stdin communication with child process: %s",
4124 close(stdout_pipe
[0]);
4125 close(stdout_pipe
[1]);
4126 close(stderr_pipe
[0]);
4127 close(stderr_pipe
[1]);
4132 child_state
= CHILD_STATE_MAXFD
;
4136 max_fd
= (int) sysconf(_SC_OPEN_MAX
);
4138 max_fd
= DEFAULT_MAX_FD
;
4139 log_warn(LD_GENERAL
,
4140 "Cannot find maximum file descriptor, assuming %d", max_fd
);
4144 max_fd
= DEFAULT_MAX_FD
;
4147 child_state
= CHILD_STATE_FORK
;
4153 #if defined(HAVE_SYS_PRCTL_H) && defined(__linux__)
4154 /* Attempt to have the kernel issue a SIGTERM if the parent
4155 * goes away. Certain attributes of the binary being execve()ed
4156 * will clear this during the execve() call, but it's better
4159 prctl(PR_SET_PDEATHSIG
, SIGTERM
);
4162 child_state
= CHILD_STATE_DUPOUT
;
4164 /* Link child stdout to the write end of the pipe */
4165 retval
= dup2(stdout_pipe
[1], STDOUT_FILENO
);
4169 child_state
= CHILD_STATE_DUPERR
;
4171 /* Link child stderr to the write end of the pipe */
4172 retval
= dup2(stderr_pipe
[1], STDERR_FILENO
);
4176 child_state
= CHILD_STATE_DUPIN
;
4178 /* Link child stdin to the read end of the pipe */
4179 retval
= dup2(stdin_pipe
[0], STDIN_FILENO
);
4183 child_state
= CHILD_STATE_CLOSEFD
;
4185 close(stderr_pipe
[0]);
4186 close(stderr_pipe
[1]);
4187 close(stdout_pipe
[0]);
4188 close(stdout_pipe
[1]);
4189 close(stdin_pipe
[0]);
4190 close(stdin_pipe
[1]);
4192 /* Close all other fds, including the read end of the pipe */
4193 /* XXX: We should now be doing enough FD_CLOEXEC setting to make
4195 for (fd
= STDERR_FILENO
+ 1; fd
< max_fd
; fd
++) {
4199 child_state
= CHILD_STATE_EXEC
;
4201 /* Call the requested program. We need the cast because
4202 execvp doesn't define argv as const, even though it
4203 does not modify the arguments */
4205 execve(filename
, (char *const *) argv
, env
->unixoid_environment_block
);
4207 static char *new_env
[] = { NULL
};
4208 execve(filename
, (char *const *) argv
, new_env
);
4211 /* If we got here, the exec or open(/dev/null) failed */
4213 child_state
= CHILD_STATE_FAILEXEC
;
4217 /* XXX: are we leaking fds from the pipe? */
4220 n
= format_helper_exit_status(child_state
, errno
, hex_errno
);
4223 /* Write the error message. GCC requires that we check the return
4224 value, but there is nothing we can do if it fails */
4225 /* TODO: Don't use STDOUT, use a pipe set up just for this purpose */
4226 nbytes
= write(STDOUT_FILENO
, error_message
, error_message_length
);
4227 nbytes
= write(STDOUT_FILENO
, hex_errno
, n
);
4234 /* Never reached, but avoids compiler warning */
4241 log_warn(LD_GENERAL
, "Failed to fork child process: %s", strerror(errno
));
4242 close(stdin_pipe
[0]);
4243 close(stdin_pipe
[1]);
4244 close(stdout_pipe
[0]);
4245 close(stdout_pipe
[1]);
4246 close(stderr_pipe
[0]);
4247 close(stderr_pipe
[1]);
4251 process_handle
= process_handle_new();
4252 process_handle
->status
= status
;
4253 process_handle
->pid
= pid
;
4255 /* TODO: If the child process forked but failed to exec, waitpid it */
4257 /* Return read end of the pipes to caller, and close write end */
4258 process_handle
->stdout_pipe
= stdout_pipe
[0];
4259 retval
= close(stdout_pipe
[1]);
4262 log_warn(LD_GENERAL
,
4263 "Failed to close write end of stdout pipe in parent process: %s",
4267 process_handle
->waitpid_cb
= set_waitpid_callback(pid
,
4268 process_handle_waitpid_cb
,
4271 process_handle
->stderr_pipe
= stderr_pipe
[0];
4272 retval
= close(stderr_pipe
[1]);
4275 log_warn(LD_GENERAL
,
4276 "Failed to close write end of stderr pipe in parent process: %s",
4280 /* Return write end of the stdin pipe to caller, and close the read end */
4281 process_handle
->stdin_pipe
= stdin_pipe
[1];
4282 retval
= close(stdin_pipe
[0]);
4285 log_warn(LD_GENERAL
,
4286 "Failed to close read end of stdin pipe in parent process: %s",
4290 status
= process_handle
->status
= PROCESS_STATUS_RUNNING
;
4291 /* Set stdin/stdout/stderr pipes to be non-blocking */
4292 if (fcntl(process_handle
->stdout_pipe
, F_SETFL
, O_NONBLOCK
) < 0 ||
4293 fcntl(process_handle
->stderr_pipe
, F_SETFL
, O_NONBLOCK
) < 0 ||
4294 fcntl(process_handle
->stdin_pipe
, F_SETFL
, O_NONBLOCK
) < 0) {
4295 log_warn(LD_GENERAL
, "Failed to set stderror/stdout/stdin pipes "
4296 "nonblocking in parent process: %s", strerror(errno
));
4298 /* Open the buffered IO streams */
4299 process_handle
->stdout_handle
= fdopen(process_handle
->stdout_pipe
, "r");
4300 process_handle
->stderr_handle
= fdopen(process_handle
->stderr_pipe
, "r");
4301 process_handle
->stdin_handle
= fdopen(process_handle
->stdin_pipe
, "r");
4303 *process_handle_out
= process_handle
;
4304 return process_handle
->status
;
4308 /** Destroy all resources allocated by the process handle in
4309 * <b>process_handle</b>.
4310 * If <b>also_terminate_process</b> is true, also terminate the
4311 * process of the process handle. */
4313 tor_process_handle_destroy
,(process_handle_t
*process_handle
,
4314 int also_terminate_process
))
4316 if (!process_handle
)
4319 if (also_terminate_process
) {
4320 if (tor_terminate_process(process_handle
) < 0) {
4321 const char *errstr
=
4323 format_win32_error(GetLastError());
4327 log_notice(LD_GENERAL
, "Failed to terminate process with "
4328 "PID '%d' ('%s').", tor_process_get_pid(process_handle
),
4331 log_info(LD_GENERAL
, "Terminated process with PID '%d'.",
4332 tor_process_get_pid(process_handle
));
4336 process_handle
->status
= PROCESS_STATUS_NOTRUNNING
;
4339 if (process_handle
->stdout_pipe
)
4340 CloseHandle(process_handle
->stdout_pipe
);
4342 if (process_handle
->stderr_pipe
)
4343 CloseHandle(process_handle
->stderr_pipe
);
4345 if (process_handle
->stdin_pipe
)
4346 CloseHandle(process_handle
->stdin_pipe
);
4348 if (process_handle
->stdout_handle
)
4349 fclose(process_handle
->stdout_handle
);
4351 if (process_handle
->stderr_handle
)
4352 fclose(process_handle
->stderr_handle
);
4354 if (process_handle
->stdin_handle
)
4355 fclose(process_handle
->stdin_handle
);
4357 clear_waitpid_callback(process_handle
->waitpid_cb
);
4360 memset(process_handle
, 0x0f, sizeof(process_handle_t
));
4361 tor_free(process_handle
);
4364 /** Get the exit code of a process specified by <b>process_handle</b> and store
4365 * it in <b>exit_code</b>, if set to a non-NULL value. If <b>block</b> is set
4366 * to true, the call will block until the process has exited. Otherwise if
4367 * the process is still running, the function will return
4368 * PROCESS_EXIT_RUNNING, and exit_code will be left unchanged. Returns
4369 * PROCESS_EXIT_EXITED if the process did exit. If there is a failure,
4370 * PROCESS_EXIT_ERROR will be returned and the contents of exit_code (if
4371 * non-NULL) will be undefined. N.B. Under *nix operating systems, this will
4372 * probably not work in Tor, because waitpid() is called in main.c to reap any
4373 * terminated child processes.*/
4375 tor_get_exit_code(process_handle_t
*process_handle
,
4376 int block
, int *exit_code
)
4383 /* Wait for the process to exit */
4384 retval
= WaitForSingleObject(process_handle
->pid
.hProcess
, INFINITE
);
4385 if (retval
!= WAIT_OBJECT_0
) {
4386 log_warn(LD_GENERAL
, "WaitForSingleObject() failed (%d): %s",
4387 (int)retval
, format_win32_error(GetLastError()));
4388 return PROCESS_EXIT_ERROR
;
4391 retval
= WaitForSingleObject(process_handle
->pid
.hProcess
, 0);
4392 if (WAIT_TIMEOUT
== retval
) {
4393 /* Process has not exited */
4394 return PROCESS_EXIT_RUNNING
;
4395 } else if (retval
!= WAIT_OBJECT_0
) {
4396 log_warn(LD_GENERAL
, "WaitForSingleObject() failed (%d): %s",
4397 (int)retval
, format_win32_error(GetLastError()));
4398 return PROCESS_EXIT_ERROR
;
4402 if (exit_code
!= NULL
) {
4403 success
= GetExitCodeProcess(process_handle
->pid
.hProcess
,
4406 log_warn(LD_GENERAL
, "GetExitCodeProcess() failed: %s",
4407 format_win32_error(GetLastError()));
4408 return PROCESS_EXIT_ERROR
;
4415 if (process_handle
->waitpid_cb
) {
4416 /* We haven't processed a SIGCHLD yet. */
4417 retval
= waitpid(process_handle
->pid
, &stat_loc
, block
?0:WNOHANG
);
4418 if (retval
== process_handle
->pid
) {
4419 clear_waitpid_callback(process_handle
->waitpid_cb
);
4420 process_handle
->waitpid_cb
= NULL
;
4421 process_handle
->waitpid_exit_status
= stat_loc
;
4424 /* We already got a SIGCHLD for this process, and handled it. */
4425 retval
= process_handle
->pid
;
4426 stat_loc
= process_handle
->waitpid_exit_status
;
4429 if (!block
&& 0 == retval
) {
4430 /* Process has not exited */
4431 return PROCESS_EXIT_RUNNING
;
4432 } else if (retval
!= process_handle
->pid
) {
4433 log_warn(LD_GENERAL
, "waitpid() failed for PID %d: %s",
4434 process_handle
->pid
, strerror(errno
));
4435 return PROCESS_EXIT_ERROR
;
4438 if (!WIFEXITED(stat_loc
)) {
4439 log_warn(LD_GENERAL
, "Process %d did not exit normally",
4440 process_handle
->pid
);
4441 return PROCESS_EXIT_ERROR
;
4444 if (exit_code
!= NULL
)
4445 *exit_code
= WEXITSTATUS(stat_loc
);
4448 return PROCESS_EXIT_EXITED
;
4451 /** Helper: return the number of characters in <b>s</b> preceding the first
4452 * occurrence of <b>ch</b>. If <b>ch</b> does not occur in <b>s</b>, return
4453 * the length of <b>s</b>. Should be equivalent to strspn(s, "ch"). */
4454 static INLINE
size_t
4455 str_num_before(const char *s
, char ch
)
4457 const char *cp
= strchr(s
, ch
);
4464 /** Return non-zero iff getenv would consider <b>s1</b> and <b>s2</b>
4465 * to have the same name as strings in a process's environment. */
4467 environment_variable_names_equal(const char *s1
, const char *s2
)
4469 size_t s1_name_len
= str_num_before(s1
, '=');
4470 size_t s2_name_len
= str_num_before(s2
, '=');
4472 return (s1_name_len
== s2_name_len
&&
4473 tor_memeq(s1
, s2
, s1_name_len
));
4476 /** Free <b>env</b> (assuming it was produced by
4477 * process_environment_make). */
4479 process_environment_free(process_environment_t
*env
)
4481 if (env
== NULL
) return;
4483 /* As both an optimization hack to reduce consing on Unixoid systems
4484 * and a nice way to ensure that some otherwise-Windows-specific
4485 * code will always get tested before changes to it get merged, the
4486 * strings which env->unixoid_environment_block points to are packed
4487 * into env->windows_environment_block. */
4488 tor_free(env
->unixoid_environment_block
);
4489 tor_free(env
->windows_environment_block
);
4494 /** Make a process_environment_t containing the environment variables
4495 * specified in <b>env_vars</b> (as C strings of the form
4497 process_environment_t
*
4498 process_environment_make(struct smartlist_t
*env_vars
)
4500 process_environment_t
*env
= tor_malloc_zero(sizeof(process_environment_t
));
4501 size_t n_env_vars
= smartlist_len(env_vars
);
4503 size_t total_env_length
;
4504 smartlist_t
*env_vars_sorted
;
4506 tor_assert(n_env_vars
+ 1 != 0);
4507 env
->unixoid_environment_block
= tor_calloc(n_env_vars
+ 1, sizeof(char *));
4508 /* env->unixoid_environment_block is already NULL-terminated,
4509 * because we assume that NULL == 0 (and check that during compilation). */
4511 total_env_length
= 1; /* terminating NUL of terminating empty string */
4512 for (i
= 0; i
< n_env_vars
; ++i
) {
4513 const char *s
= smartlist_get(env_vars
, i
);
4514 size_t slen
= strlen(s
);
4516 tor_assert(slen
+ 1 != 0);
4517 tor_assert(slen
+ 1 < SIZE_MAX
- total_env_length
);
4518 total_env_length
+= slen
+ 1;
4521 env
->windows_environment_block
= tor_malloc_zero(total_env_length
);
4522 /* env->windows_environment_block is already
4523 * (NUL-terminated-empty-string)-terminated. */
4525 /* Some versions of Windows supposedly require that environment
4526 * blocks be sorted. Or maybe some Windows programs (or their
4527 * runtime libraries) fail to look up strings in non-sorted
4528 * environment blocks.
4530 * Also, sorting strings makes it easy to find duplicate environment
4531 * variables and environment-variable strings without an '=' on all
4532 * OSes, and they can cause badness. Let's complain about those. */
4533 env_vars_sorted
= smartlist_new();
4534 smartlist_add_all(env_vars_sorted
, env_vars
);
4535 smartlist_sort_strings(env_vars_sorted
);
4537 /* Now copy the strings into the environment blocks. */
4539 char *cp
= env
->windows_environment_block
;
4540 const char *prev_env_var
= NULL
;
4542 for (i
= 0; i
< n_env_vars
; ++i
) {
4543 const char *s
= smartlist_get(env_vars_sorted
, i
);
4544 size_t slen
= strlen(s
);
4545 size_t s_name_len
= str_num_before(s
, '=');
4547 if (s_name_len
== slen
) {
4548 log_warn(LD_GENERAL
,
4549 "Preparing an environment containing a variable "
4550 "without a value: %s",
4553 if (prev_env_var
!= NULL
&&
4554 environment_variable_names_equal(s
, prev_env_var
)) {
4555 log_warn(LD_GENERAL
,
4556 "Preparing an environment containing two variables "
4557 "with the same name: %s and %s",
4563 /* Actually copy the string into the environment. */
4564 memcpy(cp
, s
, slen
+1);
4565 env
->unixoid_environment_block
[i
] = cp
;
4569 tor_assert(cp
== env
->windows_environment_block
+ total_env_length
- 1);
4572 smartlist_free(env_vars_sorted
);
4577 /** Return a newly allocated smartlist containing every variable in
4578 * this process's environment, as a NUL-terminated string of the form
4579 * "NAME=VALUE". Note that on some/many/most/all OSes, the parent
4580 * process can put strings not of that form in our environment;
4581 * callers should try to not get crashed by that.
4583 * The returned strings are heap-allocated, and must be freed by the
4585 struct smartlist_t
*
4586 get_current_process_environment_variables(void)
4588 smartlist_t
*sl
= smartlist_new();
4590 char **environ_tmp
; /* Not const char ** ? Really? */
4591 for (environ_tmp
= get_environment(); *environ_tmp
; ++environ_tmp
) {
4592 smartlist_add(sl
, tor_strdup(*environ_tmp
));
4598 /** For each string s in <b>env_vars</b> such that
4599 * environment_variable_names_equal(s, <b>new_var</b>), remove it; if
4600 * <b>free_p</b> is non-zero, call <b>free_old</b>(s). If
4601 * <b>new_var</b> contains '=', insert it into <b>env_vars</b>. */
4603 set_environment_variable_in_smartlist(struct smartlist_t
*env_vars
,
4604 const char *new_var
,
4605 void (*free_old
)(void*),
4608 SMARTLIST_FOREACH_BEGIN(env_vars
, const char *, s
) {
4609 if (environment_variable_names_equal(s
, new_var
)) {
4610 SMARTLIST_DEL_CURRENT(env_vars
, s
);
4612 free_old((void *)s
);
4615 } SMARTLIST_FOREACH_END(s
);
4617 if (strchr(new_var
, '=') != NULL
) {
4618 smartlist_add(env_vars
, (void *)new_var
);
4623 /** Read from a handle <b>h</b> into <b>buf</b>, up to <b>count</b> bytes. If
4624 * <b>hProcess</b> is NULL, the function will return immediately if there is
4625 * nothing more to read. Otherwise <b>hProcess</b> should be set to the handle
4626 * to the process owning the <b>h</b>. In this case, the function will exit
4627 * only once the process has exited, or <b>count</b> bytes are read. Returns
4628 * the number of bytes read, or -1 on error. */
4630 tor_read_all_handle(HANDLE h
, char *buf
, size_t count
,
4631 const process_handle_t
*process
)
4636 BOOL process_exited
= FALSE
;
4638 if (count
> SIZE_T_CEILING
|| count
> SSIZE_MAX
)
4641 while (numread
!= count
) {
4642 /* Check if there is anything to read */
4643 retval
= PeekNamedPipe(h
, NULL
, 0, NULL
, &byte_count
, NULL
);
4645 log_warn(LD_GENERAL
,
4646 "Failed to peek from handle: %s",
4647 format_win32_error(GetLastError()));
4649 } else if (0 == byte_count
) {
4650 /* Nothing available: process exited or it is busy */
4652 /* Exit if we don't know whether the process is running */
4653 if (NULL
== process
)
4656 /* The process exited and there's nothing left to read from it */
4660 /* If process is not running, check for output one more time in case
4661 it wrote something after the peek was performed. Otherwise keep on
4662 waiting for output */
4663 tor_assert(process
!= NULL
);
4664 byte_count
= WaitForSingleObject(process
->pid
.hProcess
, 0);
4665 if (WAIT_TIMEOUT
!= byte_count
)
4666 process_exited
= TRUE
;
4671 /* There is data to read; read it */
4672 retval
= ReadFile(h
, buf
+numread
, count
-numread
, &byte_count
, NULL
);
4673 tor_assert(byte_count
+ numread
<= count
);
4675 log_warn(LD_GENERAL
, "Failed to read from handle: %s",
4676 format_win32_error(GetLastError()));
4678 } else if (0 == byte_count
) {
4682 numread
+= byte_count
;
4684 return (ssize_t
)numread
;
4687 /** Read from a handle <b>h</b> into <b>buf</b>, up to <b>count</b> bytes. If
4688 * <b>process</b> is NULL, the function will return immediately if there is
4689 * nothing more to read. Otherwise data will be read until end of file, or
4690 * <b>count</b> bytes are read. Returns the number of bytes read, or -1 on
4691 * error. Sets <b>eof</b> to true if <b>eof</b> is not NULL and the end of the
4692 * file has been reached. */
4694 tor_read_all_handle(FILE *h
, char *buf
, size_t count
,
4695 const process_handle_t
*process
,
4704 if (count
> SIZE_T_CEILING
|| count
> SSIZE_MAX
)
4707 while (numread
!= count
) {
4708 /* Use fgets because that is what we use in log_from_pipe() */
4709 retval
= fgets(buf
+numread
, (int)(count
-numread
), h
);
4710 if (NULL
== retval
) {
4712 log_debug(LD_GENERAL
, "fgets() reached end of file");
4717 if (EAGAIN
== errno
) {
4723 log_warn(LD_GENERAL
, "fgets() from handle failed: %s",
4729 tor_assert(retval
!= NULL
);
4730 tor_assert(strlen(retval
) + numread
<= count
);
4731 numread
+= strlen(retval
);
4734 log_debug(LD_GENERAL
, "fgets() read %d bytes from handle", (int)numread
);
4735 return (ssize_t
)numread
;
4739 /** Read from stdout of a process until the process exits. */
4741 tor_read_all_from_process_stdout(const process_handle_t
*process_handle
,
4742 char *buf
, size_t count
)
4745 return tor_read_all_handle(process_handle
->stdout_pipe
, buf
, count
,
4748 return tor_read_all_handle(process_handle
->stdout_handle
, buf
, count
,
4749 process_handle
, NULL
);
4753 /** Read from stdout of a process until the process exits. */
4755 tor_read_all_from_process_stderr(const process_handle_t
*process_handle
,
4756 char *buf
, size_t count
)
4759 return tor_read_all_handle(process_handle
->stderr_pipe
, buf
, count
,
4762 return tor_read_all_handle(process_handle
->stderr_handle
, buf
, count
,
4763 process_handle
, NULL
);
4767 /** Split buf into lines, and add to smartlist. The buffer <b>buf</b> will be
4768 * modified. The resulting smartlist will consist of pointers to buf, so there
4769 * is no need to free the contents of sl. <b>buf</b> must be a NUL-terminated
4770 * string. <b>len</b> should be set to the length of the buffer excluding the
4771 * NUL. Non-printable characters (including NUL) will be replaced with "." */
4773 tor_split_lines(smartlist_t
*sl
, char *buf
, int len
)
4775 /* Index in buf of the start of the current line */
4777 /* Index in buf of the current character being processed */
4779 /* Are we currently in a line */
4782 /* Loop over string */
4784 /* Loop until end of line or end of string */
4785 for (; cur
< len
; cur
++) {
4787 if ('\r' == buf
[cur
] || '\n' == buf
[cur
]) {
4790 /* Point cur to the next line */
4792 /* Line starts at start and ends with a nul */
4795 if (!TOR_ISPRINT(buf
[cur
]))
4799 if ('\r' == buf
[cur
] || '\n' == buf
[cur
]) {
4800 /* Skip leading vertical space */
4805 if (!TOR_ISPRINT(buf
[cur
]))
4810 /* We are at the end of the line or end of string. If in_line is true there
4811 * is a line which starts at buf+start and ends at a NUL. cur points to
4812 * the character after the NUL. */
4814 smartlist_add(sl
, (void *)(buf
+start
));
4817 return smartlist_len(sl
);
4820 /** Return a string corresponding to <b>stream_status</b>. */
4822 stream_status_to_string(enum stream_status stream_status
)
4824 switch (stream_status
) {
4825 case IO_STREAM_OKAY
:
4827 case IO_STREAM_EAGAIN
:
4828 return "temporarily unavailable";
4829 case IO_STREAM_TERM
:
4830 return "terminated";
4831 case IO_STREAM_CLOSED
:
4834 tor_fragile_assert();
4841 log_portfw_spawn_error_message(const char *buf
,
4842 const char *executable
, int *child_status
)
4844 /* Parse error message */
4845 int retval
, child_state
, saved_errno
;
4846 retval
= tor_sscanf(buf
, SPAWN_ERROR_MESSAGE
"%x/%x",
4847 &child_state
, &saved_errno
);
4849 log_warn(LD_GENERAL
,
4850 "Failed to start child process \"%s\" in state %d: %s",
4851 executable
, child_state
, strerror(saved_errno
));
4855 /* Failed to parse message from child process, log it as a
4857 log_warn(LD_GENERAL
,
4858 "Unexpected message from port forwarding helper \"%s\": %s",
4865 /** Return a smartlist containing lines outputted from
4866 * <b>handle</b>. Return NULL on error, and set
4867 * <b>stream_status_out</b> appropriately. */
4868 MOCK_IMPL(smartlist_t
*,
4869 tor_get_lines_from_handle
, (HANDLE
*handle
,
4870 enum stream_status
*stream_status_out
))
4873 char stdout_buf
[600] = {0};
4874 smartlist_t
*lines
= NULL
;
4876 tor_assert(stream_status_out
);
4878 *stream_status_out
= IO_STREAM_TERM
;
4880 pos
= tor_read_all_handle(handle
, stdout_buf
, sizeof(stdout_buf
) - 1, NULL
);
4882 *stream_status_out
= IO_STREAM_TERM
;
4886 *stream_status_out
= IO_STREAM_EAGAIN
;
4890 /* End with a null even if there isn't a \r\n at the end */
4891 /* TODO: What if this is a partial line? */
4892 stdout_buf
[pos
] = '\0';
4894 /* Split up the buffer */
4895 lines
= smartlist_new();
4896 tor_split_lines(lines
, stdout_buf
, pos
);
4898 /* Currently 'lines' is populated with strings residing on the
4899 stack. Replace them with their exact copies on the heap: */
4900 SMARTLIST_FOREACH(lines
, char *, line
,
4901 SMARTLIST_REPLACE_CURRENT(lines
, line
, tor_strdup(line
)));
4903 *stream_status_out
= IO_STREAM_OKAY
;
4908 /** Read from stream, and send lines to log at the specified log level.
4909 * Returns -1 if there is a error reading, and 0 otherwise.
4910 * If the generated stream is flushed more often than on new lines, or
4911 * a read exceeds 256 bytes, lines will be truncated. This should be fixed,
4912 * along with the corresponding problem on *nix (see bug #2045).
4915 log_from_handle(HANDLE
*pipe
, int severity
)
4921 pos
= tor_read_all_handle(pipe
, buf
, sizeof(buf
) - 1, NULL
);
4924 log_warn(LD_GENERAL
, "Failed to read data from subprocess");
4929 /* There's nothing to read (process is busy or has exited) */
4930 log_debug(LD_GENERAL
, "Subprocess had nothing to say");
4934 /* End with a null even if there isn't a \r\n at the end */
4935 /* TODO: What if this is a partial line? */
4937 log_debug(LD_GENERAL
, "Subprocess had %d bytes to say", pos
);
4939 /* Split up the buffer */
4940 lines
= smartlist_new();
4941 tor_split_lines(lines
, buf
, pos
);
4944 SMARTLIST_FOREACH(lines
, char *, line
,
4946 log_fn(severity
, LD_GENERAL
, "Port forwarding helper says: %s", line
);
4948 smartlist_free(lines
);
4955 /** Return a smartlist containing lines outputted from
4956 * <b>handle</b>. Return NULL on error, and set
4957 * <b>stream_status_out</b> appropriately. */
4958 MOCK_IMPL(smartlist_t
*,
4959 tor_get_lines_from_handle
, (FILE *handle
,
4960 enum stream_status
*stream_status_out
))
4962 enum stream_status stream_status
;
4963 char stdout_buf
[400];
4964 smartlist_t
*lines
= NULL
;
4967 memset(stdout_buf
, 0, sizeof(stdout_buf
));
4969 stream_status
= get_string_from_pipe(handle
,
4970 stdout_buf
, sizeof(stdout_buf
) - 1);
4971 if (stream_status
!= IO_STREAM_OKAY
)
4974 if (!lines
) lines
= smartlist_new();
4975 smartlist_add(lines
, tor_strdup(stdout_buf
));
4979 *stream_status_out
= stream_status
;
4983 /** Read from stream, and send lines to log at the specified log level.
4984 * Returns 1 if stream is closed normally, -1 if there is a error reading, and
4985 * 0 otherwise. Handles lines from tor-fw-helper and
4986 * tor_spawn_background() specially.
4989 log_from_pipe(FILE *stream
, int severity
, const char *executable
,
4993 enum stream_status r
;
4996 r
= get_string_from_pipe(stream
, buf
, sizeof(buf
) - 1);
4998 if (r
== IO_STREAM_CLOSED
) {
5000 } else if (r
== IO_STREAM_EAGAIN
) {
5002 } else if (r
== IO_STREAM_TERM
) {
5006 tor_assert(r
== IO_STREAM_OKAY
);
5008 /* Check if buf starts with SPAWN_ERROR_MESSAGE */
5009 if (strcmpstart(buf
, SPAWN_ERROR_MESSAGE
) == 0) {
5010 log_portfw_spawn_error_message(buf
, executable
, child_status
);
5012 log_fn(severity
, LD_GENERAL
, "Port forwarding helper says: %s", buf
);
5016 /* We should never get here */
5021 /** Reads from <b>stream</b> and stores input in <b>buf_out</b> making
5022 * sure it's below <b>count</b> bytes.
5023 * If the string has a trailing newline, we strip it off.
5025 * This function is specifically created to handle input from managed
5026 * proxies, according to the pluggable transports spec. Make sure it
5027 * fits your needs before using it.
5030 * IO_STREAM_CLOSED: If the stream is closed.
5031 * IO_STREAM_EAGAIN: If there is nothing to read and we should check back
5033 * IO_STREAM_TERM: If something is wrong with the stream.
5034 * IO_STREAM_OKAY: If everything went okay and we got a string
5035 * in <b>buf_out</b>. */
5037 get_string_from_pipe(FILE *stream
, char *buf_out
, size_t count
)
5042 tor_assert(count
<= INT_MAX
);
5044 retval
= fgets(buf_out
, (int)count
, stream
);
5048 /* Program has closed stream (probably it exited) */
5049 /* TODO: check error */
5050 return IO_STREAM_CLOSED
;
5052 if (EAGAIN
== errno
) {
5053 /* Nothing more to read, try again next time */
5054 return IO_STREAM_EAGAIN
;
5056 /* There was a problem, abandon this child process */
5057 return IO_STREAM_TERM
;
5061 len
= strlen(buf_out
);
5063 /* this probably means we got a NUL at the start of the string. */
5064 return IO_STREAM_EAGAIN
;
5067 if (buf_out
[len
- 1] == '\n') {
5068 /* Remove the trailing newline */
5069 buf_out
[len
- 1] = '\0';
5071 /* No newline; check whether we overflowed the buffer */
5073 log_info(LD_GENERAL
,
5074 "Line from stream was truncated: %s", buf_out
);
5075 /* TODO: What to do with this error? */
5078 return IO_STREAM_OKAY
;
5081 /* We should never get here */
5082 return IO_STREAM_TERM
;
5085 /** Parse a <b>line</b> from tor-fw-helper and issue an appropriate
5086 * log message to our user. */
5088 handle_fw_helper_line(const char *executable
, const char *line
)
5090 smartlist_t
*tokens
= smartlist_new();
5091 char *message
= NULL
;
5092 char *message_for_log
= NULL
;
5093 const char *external_port
= NULL
;
5094 const char *internal_port
= NULL
;
5095 const char *result
= NULL
;
5099 if (strcmpstart(line
, SPAWN_ERROR_MESSAGE
) == 0) {
5100 /* We need to check for SPAWN_ERROR_MESSAGE again here, since it's
5101 * possible that it got sent after we tried to read it in log_from_pipe.
5103 * XXX Ideally, we should be using one of stdout/stderr for the real
5104 * output, and one for the output of the startup code. We used to do that
5105 * before cd05f35d2c.
5108 log_portfw_spawn_error_message(line
, executable
, &child_status
);
5112 smartlist_split_string(tokens
, line
, NULL
,
5113 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, -1);
5115 if (smartlist_len(tokens
) < 5)
5118 if (strcmp(smartlist_get(tokens
, 0), "tor-fw-helper") ||
5119 strcmp(smartlist_get(tokens
, 1), "tcp-forward"))
5122 external_port
= smartlist_get(tokens
, 2);
5123 internal_port
= smartlist_get(tokens
, 3);
5124 result
= smartlist_get(tokens
, 4);
5126 if (smartlist_len(tokens
) > 5) {
5127 /* If there are more than 5 tokens, they are part of [<message>].
5128 Let's use a second smartlist to form the whole message;
5129 strncat loops suck. */
5131 int message_words_n
= smartlist_len(tokens
) - 5;
5132 smartlist_t
*message_sl
= smartlist_new();
5133 for (i
= 0; i
< message_words_n
; i
++)
5134 smartlist_add(message_sl
, smartlist_get(tokens
, 5+i
));
5136 tor_assert(smartlist_len(message_sl
) > 0);
5137 message
= smartlist_join_strings(message_sl
, " ", 0, NULL
);
5139 /* wrap the message in log-friendly wrapping */
5140 tor_asprintf(&message_for_log
, " ('%s')", message
);
5142 smartlist_free(message_sl
);
5145 port
= atoi(external_port
);
5146 if (port
< 1 || port
> 65535)
5149 port
= atoi(internal_port
);
5150 if (port
< 1 || port
> 65535)
5153 if (!strcmp(result
, "SUCCESS"))
5155 else if (!strcmp(result
, "FAIL"))
5161 log_warn(LD_GENERAL
, "Tor was unable to forward TCP port '%s' to '%s'%s. "
5162 "Please make sure that your router supports port "
5163 "forwarding protocols (like NAT-PMP). Note that if '%s' is "
5164 "your ORPort, your relay will be unable to receive inbound "
5165 "traffic.", external_port
, internal_port
,
5166 message_for_log
? message_for_log
: "",
5169 log_info(LD_GENERAL
,
5170 "Tor successfully forwarded TCP port '%s' to '%s'%s.",
5171 external_port
, internal_port
,
5172 message_for_log
? message_for_log
: "");
5178 log_warn(LD_GENERAL
, "tor-fw-helper sent us a string we could not "
5179 "parse (%s).", line
);
5182 SMARTLIST_FOREACH(tokens
, char *, cp
, tor_free(cp
));
5183 smartlist_free(tokens
);
5185 tor_free(message_for_log
);
5188 /** Read what tor-fw-helper has to say in its stdout and handle it
5191 handle_fw_helper_output(const char *executable
,
5192 process_handle_t
*process_handle
)
5194 smartlist_t
*fw_helper_output
= NULL
;
5195 enum stream_status stream_status
= 0;
5198 tor_get_lines_from_handle(tor_process_get_stdout_pipe(process_handle
),
5200 if (!fw_helper_output
) { /* didn't get any output from tor-fw-helper */
5201 /* if EAGAIN we should retry in the future */
5202 return (stream_status
== IO_STREAM_EAGAIN
) ? 0 : -1;
5205 /* Handle the lines we got: */
5206 SMARTLIST_FOREACH_BEGIN(fw_helper_output
, char *, line
) {
5207 handle_fw_helper_line(executable
, line
);
5209 } SMARTLIST_FOREACH_END(line
);
5211 smartlist_free(fw_helper_output
);
5216 /** Spawn tor-fw-helper and ask it to forward the ports in
5217 * <b>ports_to_forward</b>. <b>ports_to_forward</b> contains strings
5218 * of the form "<external port>:<internal port>", which is the format
5219 * that tor-fw-helper expects. */
5221 tor_check_port_forwarding(const char *filename
,
5222 smartlist_t
*ports_to_forward
,
5225 /* When fw-helper succeeds, how long do we wait until running it again */
5226 #define TIME_TO_EXEC_FWHELPER_SUCCESS 300
5227 /* When fw-helper failed to start, how long do we wait until running it again
5229 #define TIME_TO_EXEC_FWHELPER_FAIL 60
5231 /* Static variables are initialized to zero, so child_handle.status=0
5232 * which corresponds to it not running on startup */
5233 static process_handle_t
*child_handle
=NULL
;
5235 static time_t time_to_run_helper
= 0;
5236 int stderr_status
, retval
;
5237 int stdout_status
= 0;
5239 tor_assert(filename
);
5241 /* Start the child, if it is not already running */
5242 if ((!child_handle
|| child_handle
->status
!= PROCESS_STATUS_RUNNING
) &&
5243 time_to_run_helper
< now
) {
5244 /*tor-fw-helper cli looks like this: tor_fw_helper -p :5555 -p 4555:1111 */
5245 const char **argv
; /* cli arguments */
5247 int argv_index
= 0; /* index inside 'argv' */
5249 tor_assert(smartlist_len(ports_to_forward
) > 0);
5251 /* check for overflow during 'argv' allocation:
5252 (len(ports_to_forward)*2 + 2)*sizeof(char*) > SIZE_MAX ==
5253 len(ports_to_forward) > (((SIZE_MAX/sizeof(char*)) - 2)/2) */
5254 if ((size_t) smartlist_len(ports_to_forward
) >
5255 (((SIZE_MAX
/sizeof(char*)) - 2)/2)) {
5256 log_warn(LD_GENERAL
,
5257 "Overflow during argv allocation. This shouldn't happen.");
5260 /* check for overflow during 'argv_index' increase:
5261 ((len(ports_to_forward)*2 + 2) > INT_MAX) ==
5262 len(ports_to_forward) > (INT_MAX - 2)/2 */
5263 if (smartlist_len(ports_to_forward
) > (INT_MAX
- 2)/2) {
5264 log_warn(LD_GENERAL
,
5265 "Overflow during argv_index increase. This shouldn't happen.");
5269 /* Calculate number of cli arguments: one for the filename, two
5270 for each smartlist element (one for "-p" and one for the
5271 ports), and one for the final NULL. */
5272 args_n
= 1 + 2*smartlist_len(ports_to_forward
) + 1;
5273 argv
= tor_calloc(args_n
, sizeof(char *));
5275 argv
[argv_index
++] = filename
;
5276 SMARTLIST_FOREACH_BEGIN(ports_to_forward
, const char *, port
) {
5277 argv
[argv_index
++] = "-p";
5278 argv
[argv_index
++] = port
;
5279 } SMARTLIST_FOREACH_END(port
);
5280 argv
[argv_index
] = NULL
;
5282 /* Assume tor-fw-helper will succeed, start it later*/
5283 time_to_run_helper
= now
+ TIME_TO_EXEC_FWHELPER_SUCCESS
;
5286 tor_process_handle_destroy(child_handle
, 1);
5287 child_handle
= NULL
;
5291 /* Passing NULL as lpApplicationName makes Windows search for the .exe */
5292 status
= tor_spawn_background(NULL
, argv
, NULL
, &child_handle
);
5294 status
= tor_spawn_background(filename
, argv
, NULL
, &child_handle
);
5297 tor_free_((void*)argv
);
5300 if (PROCESS_STATUS_ERROR
== status
) {
5301 log_warn(LD_GENERAL
, "Failed to start port forwarding helper %s",
5303 time_to_run_helper
= now
+ TIME_TO_EXEC_FWHELPER_FAIL
;
5307 log_info(LD_GENERAL
,
5308 "Started port forwarding helper (%s) with pid '%d'",
5309 filename
, tor_process_get_pid(child_handle
));
5312 /* If child is running, read from its stdout and stderr) */
5313 if (child_handle
&& PROCESS_STATUS_RUNNING
== child_handle
->status
) {
5314 /* Read from stdout/stderr and log result */
5317 stderr_status
= log_from_handle(child_handle
->stderr_pipe
, LOG_INFO
);
5319 stderr_status
= log_from_pipe(child_handle
->stderr_handle
,
5320 LOG_INFO
, filename
, &retval
);
5322 if (handle_fw_helper_output(filename
, child_handle
) < 0) {
5323 log_warn(LD_GENERAL
, "Failed to handle fw helper output.");
5329 /* There was a problem in the child process */
5330 time_to_run_helper
= now
+ TIME_TO_EXEC_FWHELPER_FAIL
;
5333 /* Combine the two statuses in order of severity */
5334 if (-1 == stdout_status
|| -1 == stderr_status
)
5335 /* There was a failure */
5338 else if (!child_handle
|| tor_get_exit_code(child_handle
, 0, NULL
) !=
5339 PROCESS_EXIT_RUNNING
) {
5340 /* process has exited or there was an error */
5341 /* TODO: Do something with the process return value */
5342 /* TODO: What if the process output something since
5343 * between log_from_handle and tor_get_exit_code? */
5347 else if (1 == stdout_status
|| 1 == stderr_status
)
5348 /* stdout or stderr was closed, the process probably
5349 * exited. It will be reaped by waitpid() in main.c */
5350 /* TODO: Do something with the process return value */
5357 /* If either pipe indicates a failure, act on it */
5360 log_info(LD_GENERAL
, "Port forwarding helper terminated");
5361 child_handle
->status
= PROCESS_STATUS_NOTRUNNING
;
5363 log_warn(LD_GENERAL
, "Failed to read from port forwarding helper");
5364 child_handle
->status
= PROCESS_STATUS_ERROR
;
5367 /* TODO: The child might not actually be finished (maybe it failed or
5368 closed stdout/stderr), so maybe we shouldn't start another? */
5373 /** Initialize the insecure RNG <b>rng</b> from a seed value <b>seed</b>. */
5375 tor_init_weak_random(tor_weak_rng_t
*rng
, unsigned seed
)
5377 rng
->state
= (uint32_t)(seed
& 0x7fffffff);
5380 /** Return a randomly chosen value in the range 0..TOR_WEAK_RANDOM_MAX based
5381 * on the RNG state of <b>rng</b>. This entropy will not be cryptographically
5382 * strong; do not rely on it for anything an adversary should not be able to
5385 tor_weak_random(tor_weak_rng_t
*rng
)
5387 /* Here's a linear congruential generator. OpenBSD and glibc use these
5388 * parameters; they aren't too bad, and should have maximal period over the
5389 * range 0..INT32_MAX. We don't want to use the platform rand() or random(),
5390 * since some platforms have bad weak RNGs that only return values in the
5391 * range 0..INT16_MAX, which just isn't enough. */
5392 rng
->state
= (rng
->state
* 1103515245 + 12345) & 0x7fffffff;
5393 return (int32_t) rng
->state
;
5396 /** Return a random number in the range [0 , <b>top</b>). {That is, the range
5397 * of integers i such that 0 <= i < top.} Chooses uniformly. Requires that
5398 * top is greater than 0. This randomness is not cryptographically strong; do
5399 * not rely on it for anything an adversary should not be able to predict. */
5401 tor_weak_random_range(tor_weak_rng_t
*rng
, int32_t top
)
5403 /* We don't want to just do tor_weak_random() % top, since random() is often
5404 * implemented with an LCG whose modulus is a power of 2, and those are
5405 * cyclic in their low-order bits. */
5406 int divisor
, result
;
5407 tor_assert(top
> 0);
5408 divisor
= TOR_WEAK_RANDOM_MAX
/ top
;
5410 result
= (int32_t)(tor_weak_random(rng
) / divisor
);
5411 } while (result
>= top
);
5415 /** Cast a given double value to a int64_t. Return 0 if number is NaN.
5416 * Returns either INT64_MIN or INT64_MAX if number is outside of the int64_t
5419 clamp_double_to_int64(double number
)
5423 /* NaN is a special case that can't be used with the logic below. */
5424 if (isnan(number
)) {
5428 /* Time to validate if result can overflows a int64_t value. Fun with
5429 * float! Find that exponent exp such that
5430 * number == x * 2^exp
5431 * for some x with abs(x) in [0.5, 1.0). Note that this implies that the
5432 * magnitude of number is strictly less than 2^exp.
5434 * If number is infinite, the call to frexp is legal but the contents of
5435 * exp are unspecified. */
5436 frexp(number
, &exp
);
5438 /* If the magnitude of number is strictly less than 2^63, the truncated
5439 * version of number is guaranteed to be representable. The only
5440 * representable integer for which this is not the case is INT64_MIN, but
5441 * it is covered by the logic below. */
5442 if (isfinite(number
) && exp
<= 63) {
5446 /* Handle infinities and finite numbers with magnitude >= 2^63. */
5447 return signbit(number
) ? INT64_MIN
: INT64_MAX
;