1 /* Copyright (c) 2003, Roger Dingledine
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2011, 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.
26 #include "container.h"
41 /* math.h needs this on Linux */
43 #define __USE_ISOC99 1
52 #ifdef HAVE_NETINET_IN_H
53 #include <netinet/in.h>
55 #ifdef HAVE_ARPA_INET_H
56 #include <arpa/inet.h>
61 #ifdef HAVE_SYS_SOCKET_H
62 #include <sys/socket.h>
64 #ifdef HAVE_SYS_TIME_H
70 #ifdef HAVE_SYS_STAT_H
73 #ifdef HAVE_SYS_FCNTL_H
74 #include <sys/fcntl.h>
79 #ifdef HAVE_MALLOC_MALLOC_H
80 #include <malloc/malloc.h>
84 /* OpenBSD has a malloc.h, but for our purposes, it only exists in order to
85 * scold us for being so stupid as to autodetect its presence. To be fair,
86 * they've done this since 1996, when autoconf was only 5 years old. */
90 #ifdef HAVE_MALLOC_NP_H
91 #include <malloc_np.h>
93 #ifdef HAVE_SYS_WAIT_H
103 /* Macro to pass the extra dmalloc args to another function. */
104 #define DMALLOC_FN_ARGS , file, line
106 #if defined(HAVE_DMALLOC_STRDUP)
107 /* the dmalloc_strdup should be fine as defined */
108 #elif defined(HAVE_DMALLOC_STRNDUP)
109 #define dmalloc_strdup(file, line, string, xalloc_b) \
110 dmalloc_strndup(file, line, (string), -1, xalloc_b)
112 #error "No dmalloc_strdup or equivalent"
115 #else /* not using dmalloc */
117 #define DMALLOC_FN_ARGS
120 /** Allocate a chunk of <b>size</b> bytes of memory, and return a pointer to
121 * result. On error, log and terminate the process. (Same as malloc(size),
122 * but never returns NULL.)
124 * <b>file</b> and <b>line</b> are used if dmalloc is enabled, and
128 _tor_malloc(size_t size DMALLOC_PARAMS
)
132 tor_assert(size
< SIZE_T_CEILING
);
134 #ifndef MALLOC_ZERO_WORKS
135 /* Some libc mallocs don't work when size==0. Override them. */
142 result
= dmalloc_malloc(file
, line
, size
, DMALLOC_FUNC_MALLOC
, 0, 0);
144 result
= malloc(size
);
147 if (PREDICT_UNLIKELY(result
== NULL
)) {
148 log_err(LD_MM
,"Out of memory on malloc(). Dying.");
149 /* If these functions die within a worker process, they won't call
150 * spawn_exit, but that's ok, since the parent will run out of memory soon
157 /** Allocate a chunk of <b>size</b> bytes of memory, fill the memory with
158 * zero bytes, and return a pointer to the result. Log and terminate
159 * the process on error. (Same as calloc(size,1), but never returns NULL.)
162 _tor_malloc_zero(size_t size DMALLOC_PARAMS
)
164 /* You may ask yourself, "wouldn't it be smart to use calloc instead of
165 * malloc+memset? Perhaps libc's calloc knows some nifty optimization trick
166 * we don't!" Indeed it does, but its optimizations are only a big win when
167 * we're allocating something very big (it knows if it just got the memory
168 * from the OS in a pre-zeroed state). We don't want to use tor_malloc_zero
169 * for big stuff, so we don't bother with calloc. */
170 void *result
= _tor_malloc(size DMALLOC_FN_ARGS
);
171 memset(result
, 0, size
);
175 /** Change the size of the memory block pointed to by <b>ptr</b> to <b>size</b>
176 * bytes long; return the new memory block. On error, log and
177 * terminate. (Like realloc(ptr,size), but never returns NULL.)
180 _tor_realloc(void *ptr
, size_t size DMALLOC_PARAMS
)
184 tor_assert(size
< SIZE_T_CEILING
);
187 result
= dmalloc_realloc(file
, line
, ptr
, size
, DMALLOC_FUNC_REALLOC
, 0);
189 result
= realloc(ptr
, size
);
192 if (PREDICT_UNLIKELY(result
== NULL
)) {
193 log_err(LD_MM
,"Out of memory on realloc(). Dying.");
199 /** Return a newly allocated copy of the NUL-terminated string s. On
200 * error, log and terminate. (Like strdup(s), but never returns
204 _tor_strdup(const char *s DMALLOC_PARAMS
)
210 dup
= dmalloc_strdup(file
, line
, s
, 0);
214 if (PREDICT_UNLIKELY(dup
== NULL
)) {
215 log_err(LD_MM
,"Out of memory on strdup(). Dying.");
221 /** Allocate and return a new string containing the first <b>n</b>
222 * characters of <b>s</b>. If <b>s</b> is longer than <b>n</b>
223 * characters, only the first <b>n</b> are copied. The result is
224 * always NUL-terminated. (Like strndup(s,n), but never returns
228 _tor_strndup(const char *s
, size_t n DMALLOC_PARAMS
)
232 tor_assert(n
< SIZE_T_CEILING
);
233 dup
= _tor_malloc((n
+1) DMALLOC_FN_ARGS
);
234 /* Performance note: Ordinarily we prefer strlcpy to strncpy. But
235 * this function gets called a whole lot, and platform strncpy is
236 * much faster than strlcpy when strlen(s) is much longer than n.
243 /** Allocate a chunk of <b>len</b> bytes, with the same contents as the
244 * <b>len</b> bytes starting at <b>mem</b>. */
246 _tor_memdup(const void *mem
, size_t len DMALLOC_PARAMS
)
249 tor_assert(len
< SIZE_T_CEILING
);
251 dup
= _tor_malloc(len DMALLOC_FN_ARGS
);
252 memcpy(dup
, mem
, len
);
256 /** Helper for places that need to take a function pointer to the right
257 * spelling of "free()". */
264 #if defined(HAVE_MALLOC_GOOD_SIZE) && !defined(HAVE_MALLOC_GOOD_SIZE_PROTOTYPE)
265 /* Some version of Mac OSX have malloc_good_size in their libc, but not
266 * actually defined in malloc/malloc.h. We detect this and work around it by
269 extern size_t malloc_good_size(size_t size
);
272 /** Allocate and return a chunk of memory of size at least *<b>size</b>, using
273 * the same resources we would use to malloc *<b>sizep</b>. Set *<b>sizep</b>
274 * to the number of usable bytes in the chunk of memory. */
276 _tor_malloc_roundup(size_t *sizep DMALLOC_PARAMS
)
278 #ifdef HAVE_MALLOC_GOOD_SIZE
279 tor_assert(*sizep
< SIZE_T_CEILING
);
280 *sizep
= malloc_good_size(*sizep
);
281 return _tor_malloc(*sizep DMALLOC_FN_ARGS
);
282 #elif 0 && defined(HAVE_MALLOC_USABLE_SIZE) && !defined(USE_DMALLOC)
283 /* Never use malloc_usable_size(); it makes valgrind really unhappy,
284 * and doesn't win much in terms of usable space where it exists. */
286 tor_assert(*sizep
< SIZE_T_CEILING
);
287 result
= _tor_malloc(*sizep DMALLOC_FN_ARGS
);
288 *sizep
= malloc_usable_size(result
);
291 return _tor_malloc(*sizep DMALLOC_FN_ARGS
);
295 /** Call the platform malloc info function, and dump the results to the log at
296 * level <b>severity</b>. If no such function exists, do nothing. */
298 tor_log_mallinfo(int severity
)
302 memset(&mi
, 0, sizeof(mi
));
304 tor_log(severity
, LD_MM
,
305 "mallinfo() said: arena=%d, ordblks=%d, smblks=%d, hblks=%d, "
306 "hblkhd=%d, usmblks=%d, fsmblks=%d, uordblks=%d, fordblks=%d, "
308 mi
.arena
, mi
.ordblks
, mi
.smblks
, mi
.hblks
,
309 mi
.hblkhd
, mi
.usmblks
, mi
.fsmblks
, mi
.uordblks
, mi
.fordblks
,
315 dmalloc_log_changed(0, /* Since the program started. */
316 1, /* Log info about non-freed pointers. */
317 0, /* Do not log info about freed pointers. */
318 0 /* Do not log individual pointers. */
328 * Returns the natural logarithm of d base 2. We define this wrapper here so
329 * as to make it easier not to conflict with Tor's log() macro.
332 tor_mathlog(double d
)
337 /** Return the long integer closest to d. We define this wrapper here so
338 * that not all users of math.h need to use the right incancations to get
339 * the c99 functions. */
343 #if defined(HAVE_LROUND)
345 #elif defined(HAVE_RINT)
346 return (long)rint(d
);
348 return (long)(d
> 0 ? d
+ 0.5 : ceil(d
- 0.5));
352 /** Returns floor(log2(u64)). If u64 is 0, (incorrectly) returns 0. */
354 tor_log2(uint64_t u64
)
357 if (u64
>= (U64_LITERAL(1)<<32)) {
361 if (u64
>= (U64_LITERAL(1)<<16)) {
365 if (u64
>= (U64_LITERAL(1)<<8)) {
369 if (u64
>= (U64_LITERAL(1)<<4)) {
373 if (u64
>= (U64_LITERAL(1)<<2)) {
377 if (u64
>= (U64_LITERAL(1)<<1)) {
384 /** Return the power of 2 closest to <b>u64</b>. */
386 round_to_power_of_2(uint64_t u64
)
388 int lg2
= tor_log2(u64
);
389 uint64_t low
= U64_LITERAL(1) << lg2
, high
= U64_LITERAL(1) << (lg2
+1);
390 if (high
- u64
< u64
- low
)
396 /** Return the lowest x such that x is at least <b>number</b>, and x modulo
397 * <b>divisor</b> == 0. */
399 round_to_next_multiple_of(unsigned number
, unsigned divisor
)
401 number
+= divisor
- 1;
402 number
-= number
% divisor
;
406 /** Return the lowest x such that x is at least <b>number</b>, and x modulo
407 * <b>divisor</b> == 0. */
409 round_uint32_to_next_multiple_of(uint32_t number
, uint32_t divisor
)
411 number
+= divisor
- 1;
412 number
-= number
% divisor
;
416 /** Return the lowest x such that x is at least <b>number</b>, and x modulo
417 * <b>divisor</b> == 0. */
419 round_uint64_to_next_multiple_of(uint64_t number
, uint64_t divisor
)
421 number
+= divisor
- 1;
422 number
-= number
% divisor
;
426 /** Return the number of bits set in <b>v</b>. */
428 n_bits_set_u8(uint8_t v
)
430 static const int nybble_table
[] = {
449 return nybble_table
[v
& 15] + nybble_table
[v
>>4];
453 * String manipulation
456 /** Remove from the string <b>s</b> every character which appears in
459 tor_strstrip(char *s
, const char *strip
)
463 if (strchr(strip
, *read
)) {
472 /** Return a pointer to a NUL-terminated hexadecimal string encoding
473 * the first <b>fromlen</b> bytes of <b>from</b>. (fromlen must be \<= 32.) The
474 * result does not need to be deallocated, but repeated calls to
475 * hex_str will trash old results.
478 hex_str(const char *from
, size_t fromlen
)
481 if (fromlen
>(sizeof(buf
)-1)/2)
482 fromlen
= (sizeof(buf
)-1)/2;
483 base16_encode(buf
,sizeof(buf
),from
,fromlen
);
487 /** Convert all alphabetic characters in the nul-terminated string <b>s</b> to
490 tor_strlower(char *s
)
493 *s
= TOR_TOLOWER(*s
);
498 /** Convert all alphabetic characters in the nul-terminated string <b>s</b> to
501 tor_strupper(char *s
)
504 *s
= TOR_TOUPPER(*s
);
509 /** Return 1 if every character in <b>s</b> is printable, else return 0.
512 tor_strisprint(const char *s
)
515 if (!TOR_ISPRINT(*s
))
522 /** Return 1 if no character in <b>s</b> is uppercase, else return 0.
525 tor_strisnonupper(const char *s
)
535 /** As strcmp, except that either string may be NULL. The NULL string is
536 * considered to be before any non-NULL string. */
538 strcmp_opt(const char *s1
, const char *s2
)
548 return strcmp(s1
, s2
);
552 /** Compares the first strlen(s2) characters of s1 with s2. Returns as for
556 strcmpstart(const char *s1
, const char *s2
)
558 size_t n
= strlen(s2
);
559 return strncmp(s1
, s2
, n
);
562 /** Compare the s1_len-byte string <b>s1</b> with <b>s2</b>,
563 * without depending on a terminating nul in s1. Sorting order is first by
564 * length, then lexically; return values are as for strcmp.
567 strcmp_len(const char *s1
, const char *s2
, size_t s1_len
)
569 size_t s2_len
= strlen(s2
);
574 return fast_memcmp(s1
, s2
, s2_len
);
577 /** Compares the first strlen(s2) characters of s1 with s2. Returns as for
581 strcasecmpstart(const char *s1
, const char *s2
)
583 size_t n
= strlen(s2
);
584 return strncasecmp(s1
, s2
, n
);
587 /** Compares the last strlen(s2) characters of s1 with s2. Returns as for
591 strcmpend(const char *s1
, const char *s2
)
593 size_t n1
= strlen(s1
), n2
= strlen(s2
);
595 return strcmp(s1
,s2
);
597 return strncmp(s1
+(n1
-n2
), s2
, n2
);
600 /** Compares the last strlen(s2) characters of s1 with s2. Returns as for
604 strcasecmpend(const char *s1
, const char *s2
)
606 size_t n1
= strlen(s1
), n2
= strlen(s2
);
607 if (n2
>n1
) /* then they can't be the same; figure out which is bigger */
608 return strcasecmp(s1
,s2
);
610 return strncasecmp(s1
+(n1
-n2
), s2
, n2
);
613 /** Compare the value of the string <b>prefix</b> with the start of the
614 * <b>memlen</b>-byte memory chunk at <b>mem</b>. Return as for strcmp.
616 * [As fast_memcmp(mem, prefix, strlen(prefix)) but returns -1 if memlen is
617 * less than strlen(prefix).]
620 fast_memcmpstart(const void *mem
, size_t memlen
,
623 size_t plen
= strlen(prefix
);
626 return fast_memcmp(mem
, prefix
, plen
);
629 /** Return a pointer to the first char of s that is not whitespace and
630 * not a comment, or to the terminating NUL if no such character exists.
633 eat_whitespace(const char *s
)
650 while (*s
&& *s
!= '\n')
656 /** Return a pointer to the first char of s that is not whitespace and
657 * not a comment, or to the terminating NUL if no such character exists.
660 eat_whitespace_eos(const char *s
, const char *eos
)
663 tor_assert(eos
&& s
<= eos
);
678 while (s
< eos
&& *s
&& *s
!= '\n')
685 /** Return a pointer to the first char of s that is not a space or a tab
686 * or a \\r, or to the terminating NUL if no such character exists. */
688 eat_whitespace_no_nl(const char *s
)
690 while (*s
== ' ' || *s
== '\t' || *s
== '\r')
695 /** As eat_whitespace_no_nl, but stop at <b>eos</b> whether we have
696 * found a non-whitespace character or not. */
698 eat_whitespace_eos_no_nl(const char *s
, const char *eos
)
700 while (s
< eos
&& (*s
== ' ' || *s
== '\t' || *s
== '\r'))
705 /** Return a pointer to the first char of s that is whitespace or <b>#</b>,
706 * or to the terminating NUL if no such character exists.
709 find_whitespace(const char *s
)
728 /** As find_whitespace, but stop at <b>eos</b> whether we have found a
729 * whitespace or not. */
731 find_whitespace_eos(const char *s
, const char *eos
)
751 /** Return the first occurrence of <b>needle</b> in <b>haystack</b> that
752 * occurs at the start of a line (that is, at the beginning of <b>haystack</b>
753 * or immediately after a newline). Return NULL if no such string is found.
756 find_str_at_start_of_line(const char *haystack
, const char *needle
)
758 size_t needle_len
= strlen(needle
);
761 if (!strncmp(haystack
, needle
, needle_len
))
764 haystack
= strchr(haystack
, '\n');
774 /** Returns true if <b>string</b> could be a C identifier.
775 A C identifier must begin with a letter or an underscore and the
776 rest of its characters can be letters, numbers or underscores. No
777 length limit is imposed. */
779 string_is_C_identifier(const char *string
)
782 size_t length
= strlen(string
);
786 for (iter
= 0; iter
< length
; iter
++) {
788 if (!(TOR_ISALPHA(string
[iter
]) ||
789 string
[iter
] == '_'))
792 if (!(TOR_ISALPHA(string
[iter
]) ||
793 TOR_ISDIGIT(string
[iter
]) ||
794 string
[iter
] == '_'))
802 /** Return true iff the 'len' bytes at 'mem' are all zero. */
804 tor_mem_is_zero(const char *mem
, size_t len
)
806 static const char ZERO
[] = {
807 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,
809 while (len
>= sizeof(ZERO
)) {
810 /* It's safe to use fast_memcmp here, since the very worst thing an
811 * attacker could learn is how many initial bytes of a secret were zero */
812 if (fast_memcmp(mem
, ZERO
, sizeof(ZERO
)))
817 /* Deal with leftover bytes. */
819 return fast_memeq(mem
, ZERO
, len
);
824 /** Return true iff the DIGEST_LEN bytes in digest are all zero. */
826 tor_digest_is_zero(const char *digest
)
828 static const uint8_t ZERO_DIGEST
[] = {
829 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0
831 return tor_memeq(digest
, ZERO_DIGEST
, DIGEST_LEN
);
834 /** Return true iff the DIGEST256_LEN bytes in digest are all zero. */
836 tor_digest256_is_zero(const char *digest
)
838 return tor_mem_is_zero(digest
, DIGEST256_LEN
);
841 /* Helper: common code to check whether the result of a strtol or strtoul or
842 * strtoll is correct. */
843 #define CHECK_STRTOX_RESULT() \
844 /* Was at least one character converted? */ \
847 /* Were there unexpected unconverted characters? */ \
848 if (!next && *endptr) \
850 /* Is r within limits? */ \
851 if (r < min || r > max) \
854 if (next) *next = endptr; \
858 if (next) *next = endptr; \
861 /** Extract a long from the start of <b>s</b>, in the given numeric
862 * <b>base</b>. If <b>base</b> is 0, <b>s</b> is parsed as a decimal,
863 * octal, or hex number in the syntax of a C integer literal. If
864 * there is unconverted data and <b>next</b> is provided, set
865 * *<b>next</b> to the first unconverted character. An error has
866 * occurred if no characters are converted; or if there are
867 * unconverted characters and <b>next</b> is NULL; or if the parsed
868 * value is not between <b>min</b> and <b>max</b>. When no error
869 * occurs, return the parsed value and set *<b>ok</b> (if provided) to
870 * 1. When an error occurs, return 0 and set *<b>ok</b> (if provided)
874 tor_parse_long(const char *s
, int base
, long min
, long max
,
875 int *ok
, char **next
)
880 r
= strtol(s
, &endptr
, base
);
881 CHECK_STRTOX_RESULT();
884 /** As tor_parse_long(), but return an unsigned long. */
886 tor_parse_ulong(const char *s
, int base
, unsigned long min
,
887 unsigned long max
, int *ok
, char **next
)
892 r
= strtoul(s
, &endptr
, base
);
893 CHECK_STRTOX_RESULT();
896 /** As tor_parse_long(), but return a double. */
898 tor_parse_double(const char *s
, double min
, double max
, int *ok
, char **next
)
903 r
= strtod(s
, &endptr
);
904 CHECK_STRTOX_RESULT();
907 /** As tor_parse_long, but return a uint64_t. Only base 10 is guaranteed to
910 tor_parse_uint64(const char *s
, int base
, uint64_t min
,
911 uint64_t max
, int *ok
, char **next
)
917 r
= (uint64_t)strtoull(s
, &endptr
, base
);
918 #elif defined(MS_WINDOWS)
919 #if defined(_MSC_VER) && _MSC_VER < 1300
920 tor_assert(base
<= 10);
921 r
= (uint64_t)_atoi64(s
);
923 while (TOR_ISSPACE(*endptr
)) endptr
++;
924 while (TOR_ISDIGIT(*endptr
)) endptr
++;
926 r
= (uint64_t)_strtoui64(s
, &endptr
, base
);
928 #elif SIZEOF_LONG == 8
929 r
= (uint64_t)strtoul(s
, &endptr
, base
);
931 #error "I don't know how to parse 64-bit numbers."
934 CHECK_STRTOX_RESULT();
937 /** Encode the <b>srclen</b> bytes at <b>src</b> in a NUL-terminated,
938 * uppercase hexadecimal string; store it in the <b>destlen</b>-byte buffer
942 base16_encode(char *dest
, size_t destlen
, const char *src
, size_t srclen
)
947 tor_assert(destlen
>= srclen
*2+1);
948 tor_assert(destlen
< SIZE_T_CEILING
);
953 *cp
++ = "0123456789ABCDEF"[ (*(const uint8_t*)src
) >> 4 ];
954 *cp
++ = "0123456789ABCDEF"[ (*(const uint8_t*)src
) & 0xf ];
960 /** Helper: given a hex digit, return its value, or -1 if it isn't hex. */
962 _hex_decode_digit(char c
)
975 case 'A': case 'a': return 10;
976 case 'B': case 'b': return 11;
977 case 'C': case 'c': return 12;
978 case 'D': case 'd': return 13;
979 case 'E': case 'e': return 14;
980 case 'F': case 'f': return 15;
986 /** Helper: given a hex digit, return its value, or -1 if it isn't hex. */
988 hex_decode_digit(char c
)
990 return _hex_decode_digit(c
);
993 /** Given a hexadecimal string of <b>srclen</b> bytes in <b>src</b>, decode it
994 * and store the result in the <b>destlen</b>-byte buffer at <b>dest</b>.
995 * Return 0 on success, -1 on failure. */
997 base16_decode(char *dest
, size_t destlen
, const char *src
, size_t srclen
)
1002 if ((srclen
% 2) != 0)
1004 if (destlen
< srclen
/2 || destlen
> SIZE_T_CEILING
)
1008 v1
= _hex_decode_digit(*src
);
1009 v2
= _hex_decode_digit(*(src
+1));
1012 *(uint8_t*)dest
= (v1
<<4)|v2
;
1019 /** Allocate and return a new string representing the contents of <b>s</b>,
1020 * surrounded by quotes and using standard C escapes.
1022 * Generally, we use this for logging values that come in over the network to
1023 * keep them from tricking users, and for sending certain values to the
1026 * We trust values from the resolver, OS, configuration file, and command line
1027 * to not be maliciously ill-formed. We validate incoming routerdescs and
1028 * SOCKS requests and addresses from BEGIN cells as they're parsed;
1029 * afterwards, we trust them as non-malicious.
1032 esc_for_log(const char *s
)
1035 char *result
, *outp
;
1038 return tor_strdup("(null)");
1041 for (cp
= s
; *cp
; ++cp
) {
1052 if (TOR_ISPRINT(*cp
) && ((uint8_t)*cp
)<127)
1060 result
= outp
= tor_malloc(len
);
1062 for (cp
= s
; *cp
; ++cp
) {
1083 if (TOR_ISPRINT(*cp
) && ((uint8_t)*cp
)<127) {
1086 tor_snprintf(outp
, 5, "\\%03o", (int)(uint8_t) *cp
);
1099 /** Allocate and return a new string representing the contents of <b>s</b>,
1100 * surrounded by quotes and using standard C escapes.
1102 * THIS FUNCTION IS NOT REENTRANT. Don't call it from outside the main
1103 * thread. Also, each call invalidates the last-returned value, so don't
1104 * try log_warn(LD_GENERAL, "%s %s", escaped(a), escaped(b));
1107 escaped(const char *s
)
1109 static char *_escaped_val
= NULL
;
1110 tor_free(_escaped_val
);
1113 _escaped_val
= esc_for_log(s
);
1115 _escaped_val
= NULL
;
1117 return _escaped_val
;
1120 /** Rudimentary string wrapping code: given a un-wrapped <b>string</b> (no
1121 * newlines!), break the string into newline-terminated lines of no more than
1122 * <b>width</b> characters long (not counting newline) and insert them into
1123 * <b>out</b> in order. Precede the first line with prefix0, and subsequent
1124 * lines with prefixRest.
1126 /* This uses a stupid greedy wrapping algorithm right now:
1128 * - Try to fit as much stuff as possible, but break on a space.
1129 * - If the first "word" of the line will extend beyond the allowable
1130 * width, break the word at the end of the width.
1133 wrap_string(smartlist_t
*out
, const char *string
, size_t width
,
1134 const char *prefix0
, const char *prefixRest
)
1136 size_t p0Len
, pRestLen
, pCurLen
;
1137 const char *eos
, *prefixCur
;
1146 p0Len
= strlen(prefix0
);
1147 pRestLen
= strlen(prefixRest
);
1148 tor_assert(width
> p0Len
&& width
> pRestLen
);
1149 eos
= strchr(string
, '\0');
1152 prefixCur
= prefix0
;
1154 while ((eos
-string
)+pCurLen
> width
) {
1155 const char *eol
= string
+ width
- pCurLen
;
1156 while (eol
> string
&& *eol
!= ' ')
1158 /* eol is now the last space that can fit, or the start of the string. */
1160 size_t line_len
= (eol
-string
) + pCurLen
+ 2;
1161 char *line
= tor_malloc(line_len
);
1162 memcpy(line
, prefixCur
, pCurLen
);
1163 memcpy(line
+pCurLen
, string
, eol
-string
);
1164 line
[line_len
-2] = '\n';
1165 line
[line_len
-1] = '\0';
1166 smartlist_add(out
, line
);
1169 size_t line_len
= width
+ 2;
1170 char *line
= tor_malloc(line_len
);
1171 memcpy(line
, prefixCur
, pCurLen
);
1172 memcpy(line
+pCurLen
, string
, width
- pCurLen
);
1173 line
[line_len
-2] = '\n';
1174 line
[line_len
-1] = '\0';
1175 smartlist_add(out
, line
);
1176 string
+= width
-pCurLen
;
1178 prefixCur
= prefixRest
;
1183 size_t line_len
= (eos
-string
) + pCurLen
+ 2;
1184 char *line
= tor_malloc(line_len
);
1185 memcpy(line
, prefixCur
, pCurLen
);
1186 memcpy(line
+pCurLen
, string
, eos
-string
);
1187 line
[line_len
-2] = '\n';
1188 line
[line_len
-1] = '\0';
1189 smartlist_add(out
, line
);
1198 * Converts struct timeval to a double value.
1199 * Preserves microsecond precision, but just barely.
1200 * Error is approx +/- 0.1 usec when dealing with epoch values.
1203 tv_to_double(const struct timeval
*tv
)
1205 double conv
= tv
->tv_sec
;
1206 conv
+= tv
->tv_usec
/1000000.0;
1211 * Converts timeval to milliseconds.
1214 tv_to_msec(const struct timeval
*tv
)
1216 int64_t conv
= ((int64_t)tv
->tv_sec
)*1000L;
1217 /* Round ghetto-style */
1218 conv
+= ((int64_t)tv
->tv_usec
+500)/1000L;
1223 * Converts timeval to microseconds.
1226 tv_to_usec(const struct timeval
*tv
)
1228 int64_t conv
= ((int64_t)tv
->tv_sec
)*1000000L;
1229 conv
+= tv
->tv_usec
;
1233 /** Return the number of microseconds elapsed between *start and *end.
1236 tv_udiff(const struct timeval
*start
, const struct timeval
*end
)
1239 long secdiff
= end
->tv_sec
- start
->tv_sec
;
1241 if (labs(secdiff
+1) > LONG_MAX
/1000000) {
1242 log_warn(LD_GENERAL
, "comparing times on microsecond detail too far "
1243 "apart: %ld seconds", secdiff
);
1247 udiff
= secdiff
*1000000L + (end
->tv_usec
- start
->tv_usec
);
1251 /** Return the number of milliseconds elapsed between *start and *end.
1254 tv_mdiff(const struct timeval
*start
, const struct timeval
*end
)
1257 long secdiff
= end
->tv_sec
- start
->tv_sec
;
1259 if (labs(secdiff
+1) > LONG_MAX
/1000) {
1260 log_warn(LD_GENERAL
, "comparing times on millisecond detail too far "
1261 "apart: %ld seconds", secdiff
);
1265 /* Subtract and round */
1266 mdiff
= secdiff
*1000L +
1267 ((long)end
->tv_usec
- (long)start
->tv_usec
+ 500L) / 1000L;
1271 /** Yield true iff <b>y</b> is a leap-year. */
1272 #define IS_LEAPYEAR(y) (!(y % 4) && ((y % 100) || !(y % 400)))
1273 /** Helper: Return the number of leap-days between Jan 1, y1 and Jan 1, y2. */
1275 n_leapdays(int y1
, int y2
)
1279 return (y2
/4 - y1
/4) - (y2
/100 - y1
/100) + (y2
/400 - y1
/400);
1281 /** Number of days per month in non-leap year; used by tor_timegm. */
1282 static const int days_per_month
[] =
1283 { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
1285 /** Return a time_t given a struct tm. The result is given in GMT, and
1286 * does not account for leap seconds.
1289 tor_timegm(struct tm
*tm
)
1291 /* This is a pretty ironclad timegm implementation, snarfed from Python2.2.
1292 * It's way more brute-force than fiddling with tzset().
1294 time_t year
, days
, hours
, minutes
, seconds
;
1296 year
= tm
->tm_year
+ 1900;
1297 if (year
< 1970 || tm
->tm_mon
< 0 || tm
->tm_mon
> 11) {
1298 log_warn(LD_BUG
, "Out-of-range argument to tor_timegm");
1301 tor_assert(year
< INT_MAX
);
1302 days
= 365 * (year
-1970) + n_leapdays(1970,(int)year
);
1303 for (i
= 0; i
< tm
->tm_mon
; ++i
)
1304 days
+= days_per_month
[i
];
1305 if (tm
->tm_mon
> 1 && IS_LEAPYEAR(year
))
1307 days
+= tm
->tm_mday
- 1;
1308 hours
= days
*24 + tm
->tm_hour
;
1310 minutes
= hours
*60 + tm
->tm_min
;
1311 seconds
= minutes
*60 + tm
->tm_sec
;
1315 /* strftime is locale-specific, so we need to replace those parts */
1317 /** A c-locale array of 3-letter names of weekdays, starting with Sun. */
1318 static const char *WEEKDAY_NAMES
[] =
1319 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
1320 /** A c-locale array of 3-letter names of months, starting with Jan. */
1321 static const char *MONTH_NAMES
[] =
1322 { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1323 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
1325 /** Set <b>buf</b> to the RFC1123 encoding of the GMT value of <b>t</b>.
1326 * The buffer must be at least RFC1123_TIME_LEN+1 bytes long.
1328 * (RFC1123 format is Fri, 29 Sep 2006 15:54:20 GMT)
1331 format_rfc1123_time(char *buf
, time_t t
)
1335 tor_gmtime_r(&t
, &tm
);
1337 strftime(buf
, RFC1123_TIME_LEN
+1, "___, %d ___ %Y %H:%M:%S GMT", &tm
);
1338 tor_assert(tm
.tm_wday
>= 0);
1339 tor_assert(tm
.tm_wday
<= 6);
1340 memcpy(buf
, WEEKDAY_NAMES
[tm
.tm_wday
], 3);
1341 tor_assert(tm
.tm_wday
>= 0);
1342 tor_assert(tm
.tm_mon
<= 11);
1343 memcpy(buf
+8, MONTH_NAMES
[tm
.tm_mon
], 3);
1346 /** Parse the RFC1123 encoding of some time (in GMT) from <b>buf</b>,
1347 * and store the result in *<b>t</b>.
1349 * Return 0 on success, -1 on failure.
1352 parse_rfc1123_time(const char *buf
, time_t *t
)
1358 unsigned tm_mday
, tm_year
, tm_hour
, tm_min
, tm_sec
;
1360 if (strlen(buf
) != RFC1123_TIME_LEN
)
1362 memset(&tm
, 0, sizeof(tm
));
1363 if (tor_sscanf(buf
, "%3s, %2u %3s %u %2u:%2u:%2u GMT", weekday
,
1364 &tm_mday
, month
, &tm_year
, &tm_hour
,
1365 &tm_min
, &tm_sec
) < 7) {
1366 char *esc
= esc_for_log(buf
);
1367 log_warn(LD_GENERAL
, "Got invalid RFC1123 time %s", esc
);
1371 if (tm_mday
> 31 || tm_hour
> 23 || tm_min
> 59 || tm_sec
> 61) {
1372 char *esc
= esc_for_log(buf
);
1373 log_warn(LD_GENERAL
, "Got invalid RFC1123 time %s", esc
);
1377 tm
.tm_mday
= (int)tm_mday
;
1378 tm
.tm_year
= (int)tm_year
;
1379 tm
.tm_hour
= (int)tm_hour
;
1380 tm
.tm_min
= (int)tm_min
;
1381 tm
.tm_sec
= (int)tm_sec
;
1384 for (i
= 0; i
< 12; ++i
) {
1385 if (!strcmp(month
, MONTH_NAMES
[i
])) {
1391 char *esc
= esc_for_log(buf
);
1392 log_warn(LD_GENERAL
, "Got invalid RFC1123 time %s: No such month", esc
);
1398 if (tm
.tm_year
< 1970) {
1399 char *esc
= esc_for_log(buf
);
1400 log_warn(LD_GENERAL
,
1401 "Got invalid RFC1123 time %s. (Before 1970)", esc
);
1407 *t
= tor_timegm(&tm
);
1411 /** Set <b>buf</b> to the ISO8601 encoding of the local value of <b>t</b>.
1412 * The buffer must be at least ISO_TIME_LEN+1 bytes long.
1414 * (ISO8601 format is 2006-10-29 10:57:20)
1417 format_local_iso_time(char *buf
, time_t t
)
1420 strftime(buf
, ISO_TIME_LEN
+1, "%Y-%m-%d %H:%M:%S", tor_localtime_r(&t
, &tm
));
1423 /** Set <b>buf</b> to the ISO8601 encoding of the GMT value of <b>t</b>.
1424 * The buffer must be at least ISO_TIME_LEN+1 bytes long.
1427 format_iso_time(char *buf
, time_t t
)
1430 strftime(buf
, ISO_TIME_LEN
+1, "%Y-%m-%d %H:%M:%S", tor_gmtime_r(&t
, &tm
));
1433 /** Given an ISO-formatted UTC time value (after the epoch) in <b>cp</b>,
1434 * parse it and store its value in *<b>t</b>. Return 0 on success, -1 on
1435 * failure. Ignore extraneous stuff in <b>cp</b> separated by whitespace from
1436 * the end of the time string. */
1438 parse_iso_time(const char *cp
, time_t *t
)
1441 unsigned int year
=0, month
=0, day
=0, hour
=100, minute
=100, second
=100;
1442 if (tor_sscanf(cp
, "%u-%2u-%2u %2u:%2u:%2u", &year
, &month
,
1443 &day
, &hour
, &minute
, &second
) < 6) {
1444 char *esc
= esc_for_log(cp
);
1445 log_warn(LD_GENERAL
, "ISO time %s was unparseable", esc
);
1449 if (year
< 1970 || month
< 1 || month
> 12 || day
< 1 || day
> 31 ||
1450 hour
> 23 || minute
> 59 || second
> 61) {
1451 char *esc
= esc_for_log(cp
);
1452 log_warn(LD_GENERAL
, "ISO time %s was nonsensical", esc
);
1456 st_tm
.tm_year
= year
-1900;
1457 st_tm
.tm_mon
= month
-1;
1458 st_tm
.tm_mday
= day
;
1459 st_tm
.tm_hour
= hour
;
1460 st_tm
.tm_min
= minute
;
1461 st_tm
.tm_sec
= second
;
1463 if (st_tm
.tm_year
< 70) {
1464 char *esc
= esc_for_log(cp
);
1465 log_warn(LD_GENERAL
, "Got invalid ISO time %s. (Before 1970)", esc
);
1469 *t
= tor_timegm(&st_tm
);
1473 /** Given a <b>date</b> in one of the three formats allowed by HTTP (ugh),
1474 * parse it into <b>tm</b>. Return 0 on success, negative on failure. */
1476 parse_http_time(const char *date
, struct tm
*tm
)
1482 unsigned tm_mday
, tm_year
, tm_hour
, tm_min
, tm_sec
;
1485 memset(tm
, 0, sizeof(*tm
));
1487 /* First, try RFC1123 or RFC850 format: skip the weekday. */
1488 if ((cp
= strchr(date
, ','))) {
1490 if (tor_sscanf(date
, "%2u %3s %4u %2u:%2u:%2u GMT",
1491 &tm_mday
, month
, &tm_year
,
1492 &tm_hour
, &tm_min
, &tm_sec
) == 6) {
1495 } else if (tor_sscanf(date
, "%2u-%3s-%2u %2u:%2u:%2u GMT",
1496 &tm_mday
, month
, &tm_year
,
1497 &tm_hour
, &tm_min
, &tm_sec
) == 6) {
1503 /* No comma; possibly asctime() format. */
1504 if (tor_sscanf(date
, "%3s %3s %2u %2u:%2u:%2u %4u",
1505 wkday
, month
, &tm_mday
,
1506 &tm_hour
, &tm_min
, &tm_sec
, &tm_year
) == 7) {
1512 tm
->tm_mday
= (int)tm_mday
;
1513 tm
->tm_year
= (int)tm_year
;
1514 tm
->tm_hour
= (int)tm_hour
;
1515 tm
->tm_min
= (int)tm_min
;
1516 tm
->tm_sec
= (int)tm_sec
;
1519 /* Okay, now decode the month. */
1520 for (i
= 0; i
< 12; ++i
) {
1521 if (!strcasecmp(MONTH_NAMES
[i
], month
)) {
1526 if (tm
->tm_year
< 0 ||
1527 tm
->tm_mon
< 1 || tm
->tm_mon
> 12 ||
1528 tm
->tm_mday
< 0 || tm
->tm_mday
> 31 ||
1529 tm
->tm_hour
< 0 || tm
->tm_hour
> 23 ||
1530 tm
->tm_min
< 0 || tm
->tm_min
> 59 ||
1531 tm
->tm_sec
< 0 || tm
->tm_sec
> 61)
1532 return -1; /* Out of range, or bad month. */
1537 /** Given an <b>interval</b> in seconds, try to write it to the
1538 * <b>out_len</b>-byte buffer in <b>out</b> in a human-readable form.
1539 * Return 0 on success, -1 on failure.
1542 format_time_interval(char *out
, size_t out_len
, long interval
)
1544 /* We only report seconds if there's no hours. */
1545 long sec
= 0, min
= 0, hour
= 0, day
= 0;
1547 interval
= -interval
;
1549 if (interval
>= 86400) {
1550 day
= interval
/ 86400;
1553 if (interval
>= 3600) {
1554 hour
= interval
/ 3600;
1557 if (interval
>= 60) {
1558 min
= interval
/ 60;
1564 return tor_snprintf(out
, out_len
, "%ld days, %ld hours, %ld minutes",
1567 return tor_snprintf(out
, out_len
, "%ld hours, %ld minutes", hour
, min
);
1569 return tor_snprintf(out
, out_len
, "%ld minutes, %ld seconds", min
, sec
);
1571 return tor_snprintf(out
, out_len
, "%ld seconds", sec
);
1579 #ifndef TIME_IS_FAST
1580 /** Cached estimate of the current time. Updated around once per second;
1581 * may be a few seconds off if we are really busy. This is a hack to avoid
1582 * calling time(NULL) (which not everybody has optimized) on critical paths.
1584 static time_t cached_approx_time
= 0;
1586 /** Return a cached estimate of the current time from when
1587 * update_approx_time() was last called. This is a hack to avoid calling
1588 * time(NULL) on critical paths: please do not even think of calling it
1593 return cached_approx_time
;
1596 /** Update the cached estimate of the current time. This function SHOULD be
1597 * called once per second, and MUST be called before the first call to
1598 * get_approx_time. */
1600 update_approx_time(time_t now
)
1602 cached_approx_time
= now
;
1610 /** If the rate-limiter <b>lim</b> is ready at <b>now</b>, return the number
1611 * of calls to rate_limit_is_ready (including this one!) since the last time
1612 * rate_limit_is_ready returned nonzero. Otherwise return 0. */
1614 rate_limit_is_ready(ratelim_t
*lim
, time_t now
)
1616 if (lim
->rate
+ lim
->last_allowed
<= now
) {
1617 int res
= lim
->n_calls_since_last_time
+ 1;
1618 lim
->last_allowed
= now
;
1619 lim
->n_calls_since_last_time
= 0;
1622 ++lim
->n_calls_since_last_time
;
1627 /** If the rate-limiter <b>lim</b> is ready at <b>now</b>, return a newly
1628 * allocated string indicating how many messages were suppressed, suitable to
1629 * append to a log message. Otherwise return NULL. */
1631 rate_limit_log(ratelim_t
*lim
, time_t now
)
1634 if ((n
= rate_limit_is_ready(lim
, now
))) {
1636 return tor_strdup("");
1640 " [%d similar message(s) suppressed in last %d seconds]",
1653 /** Write <b>count</b> bytes from <b>buf</b> to <b>fd</b>. <b>isSocket</b>
1654 * must be 1 if fd was returned by socket() or accept(), and 0 if fd
1655 * was returned by open(). Return the number of bytes written, or -1
1656 * on error. Only use if fd is a blocking fd. */
1658 write_all(tor_socket_t fd
, const char *buf
, size_t count
, int isSocket
)
1662 tor_assert(count
< SSIZE_T_MAX
);
1664 while (written
!= count
) {
1666 result
= tor_socket_send(fd
, buf
+written
, count
-written
, 0);
1668 result
= write((int)fd
, buf
+written
, count
-written
);
1673 return (ssize_t
)count
;
1676 /** Read from <b>fd</b> to <b>buf</b>, until we get <b>count</b> bytes
1677 * or reach the end of the file. <b>isSocket</b> must be 1 if fd
1678 * was returned by socket() or accept(), and 0 if fd was returned by
1679 * open(). Return the number of bytes read, or -1 on error. Only use
1680 * if fd is a blocking fd. */
1682 read_all(tor_socket_t fd
, char *buf
, size_t count
, int isSocket
)
1687 if (count
> SIZE_T_CEILING
|| count
> SSIZE_T_MAX
)
1690 while (numread
!= count
) {
1692 result
= tor_socket_recv(fd
, buf
+numread
, count
-numread
, 0);
1694 result
= read((int)fd
, buf
+numread
, count
-numread
);
1697 else if (result
== 0)
1701 return (ssize_t
)numread
;
1705 * Filesystem operations.
1708 /** Clean up <b>name</b> so that we can use it in a call to "stat". On Unix,
1709 * we do nothing. On Windows, we remove a trailing slash, unless the path is
1710 * the root of a disk. */
1712 clean_name_for_stat(char *name
)
1715 size_t len
= strlen(name
);
1718 if (name
[len
-1]=='\\' || name
[len
-1]=='/') {
1719 if (len
== 1 || (len
==3 && name
[1]==':'))
1728 /** Return FN_ERROR if filename can't be read, FN_NOENT if it doesn't
1729 * exist, FN_FILE if it is a regular file, or FN_DIR if it's a
1730 * directory. On FN_ERROR, sets errno. */
1732 file_status(const char *fname
)
1737 f
= tor_strdup(fname
);
1738 clean_name_for_stat(f
);
1742 if (errno
== ENOENT
) {
1747 if (st
.st_mode
& S_IFDIR
)
1749 else if (st
.st_mode
& S_IFREG
)
1755 /** Check whether <b>dirname</b> exists and is private. If yes return 0. If
1756 * it does not exist, and <b>check</b>&CPD_CREATE is set, try to create it
1757 * and return 0 on success. If it does not exist, and
1758 * <b>check</b>&CPD_CHECK, and we think we can create it, return 0. Else
1759 * return -1. If CPD_GROUP_OK is set, then it's okay if the directory
1760 * is group-readable, but in all cases we create the directory mode 0700.
1761 * If CPD_CHECK_MODE_ONLY is set, then we don't alter the directory permissions
1762 * if they are too permissive: we just return -1.
1763 * When effective_user is not NULL, check permissions against the given user
1764 * and its primary group.
1767 check_private_dir(const char *dirname
, cpd_check_t check
,
1768 const char *effective_user
)
1775 struct passwd
*pw
= NULL
;
1779 (void)effective_user
;
1782 tor_assert(dirname
);
1783 f
= tor_strdup(dirname
);
1784 clean_name_for_stat(f
);
1788 if (errno
!= ENOENT
) {
1789 log_warn(LD_FS
, "Directory %s cannot be read: %s", dirname
,
1793 if (check
& CPD_CREATE
) {
1794 log_info(LD_GENERAL
, "Creating directory %s", dirname
);
1795 #if defined (MS_WINDOWS) && !defined (WINCE)
1798 r
= mkdir(dirname
, 0700);
1801 log_warn(LD_FS
, "Error creating directory %s: %s", dirname
,
1805 } else if (!(check
& CPD_CHECK
)) {
1806 log_warn(LD_FS
, "Directory %s does not exist.", dirname
);
1809 /* XXXX In the case where check==CPD_CHECK, we should look at the
1810 * parent directory a little harder. */
1813 if (!(st
.st_mode
& S_IFDIR
)) {
1814 log_warn(LD_FS
, "%s is not a directory", dirname
);
1818 if (effective_user
) {
1819 /* Look up the user and group information.
1820 * If we have a problem, bail out. */
1821 pw
= getpwnam(effective_user
);
1823 log_warn(LD_CONFIG
, "Error setting configured user: %s not found",
1827 running_uid
= pw
->pw_uid
;
1828 running_gid
= pw
->pw_gid
;
1830 running_uid
= getuid();
1831 running_gid
= getgid();
1834 if (st
.st_uid
!= running_uid
) {
1835 struct passwd
*pw
= NULL
;
1836 char *process_ownername
= NULL
;
1838 pw
= getpwuid(running_uid
);
1839 process_ownername
= pw
? tor_strdup(pw
->pw_name
) : tor_strdup("<unknown>");
1841 pw
= getpwuid(st
.st_uid
);
1843 log_warn(LD_FS
, "%s is not owned by this user (%s, %d) but by "
1844 "%s (%d). Perhaps you are running Tor as the wrong user?",
1845 dirname
, process_ownername
, (int)running_uid
,
1846 pw
? pw
->pw_name
: "<unknown>", (int)st
.st_uid
);
1848 tor_free(process_ownername
);
1851 if ((check
& CPD_GROUP_OK
) && st
.st_gid
!= running_gid
) {
1853 char *process_groupname
= NULL
;
1854 gr
= getgrgid(running_gid
);
1855 process_groupname
= gr
? tor_strdup(gr
->gr_name
) : tor_strdup("<unknown>");
1856 gr
= getgrgid(st
.st_gid
);
1858 log_warn(LD_FS
, "%s is not owned by this group (%s, %d) but by group "
1859 "%s (%d). Are you running Tor as the wrong user?",
1860 dirname
, process_groupname
, (int)running_gid
,
1861 gr
? gr
->gr_name
: "<unknown>", (int)st
.st_gid
);
1863 tor_free(process_groupname
);
1866 if (check
& CPD_GROUP_OK
) {
1871 if (st
.st_mode
& mask
) {
1873 if (check
& CPD_CHECK_MODE_ONLY
) {
1874 log_warn(LD_FS
, "Permissions on directory %s are too permissive.",
1878 log_warn(LD_FS
, "Fixing permissions on directory %s", dirname
);
1879 new_mode
= st
.st_mode
;
1880 new_mode
|= 0700; /* Owner should have rwx */
1881 new_mode
&= ~mask
; /* Clear the other bits that we didn't want set...*/
1882 if (chmod(dirname
, new_mode
)) {
1883 log_warn(LD_FS
, "Could not chmod directory %s: %s", dirname
,
1894 /** Create a file named <b>fname</b> with the contents <b>str</b>. Overwrite
1895 * the previous <b>fname</b> if possible. Return 0 on success, -1 on failure.
1897 * This function replaces the old file atomically, if possible. This
1898 * function, and all other functions in util.c that create files, create them
1902 write_str_to_file(const char *fname
, const char *str
, int bin
)
1905 if (!bin
&& strchr(str
, '\r')) {
1907 "We're writing a text string that already contains a CR.");
1910 return write_bytes_to_file(fname
, str
, strlen(str
), bin
);
1913 /** Represents a file that we're writing to, with support for atomic commit:
1914 * we can write into a temporary file, and either remove the file on
1915 * failure, or replace the original file on success. */
1916 struct open_file_t
{
1917 char *tempname
; /**< Name of the temporary file. */
1918 char *filename
; /**< Name of the original file. */
1919 unsigned rename_on_close
:1; /**< Are we using the temporary file or not? */
1920 unsigned binary
:1; /**< Did we open in binary mode? */
1921 int fd
; /**< fd for the open file. */
1922 FILE *stdio_file
; /**< stdio wrapper for <b>fd</b>. */
1925 /** Try to start writing to the file in <b>fname</b>, passing the flags
1926 * <b>open_flags</b> to the open() syscall, creating the file (if needed) with
1927 * access value <b>mode</b>. If the O_APPEND flag is set, we append to the
1928 * original file. Otherwise, we open a new temporary file in the same
1929 * directory, and either replace the original or remove the temporary file
1932 * Return the fd for the newly opened file, and store working data in
1933 * *<b>data_out</b>. The caller should not close the fd manually:
1934 * instead, call finish_writing_to_file() or abort_writing_to_file().
1935 * Returns -1 on failure.
1937 * NOTE: When not appending, the flags O_CREAT and O_TRUNC are treated
1938 * as true and the flag O_EXCL is treated as false.
1940 * NOTE: Ordinarily, O_APPEND means "seek to the end of the file before each
1941 * write()". We don't do that.
1944 start_writing_to_file(const char *fname
, int open_flags
, int mode
,
1945 open_file_t
**data_out
)
1947 size_t tempname_len
= strlen(fname
)+16;
1948 open_file_t
*new_file
= tor_malloc_zero(sizeof(open_file_t
));
1949 const char *open_name
;
1953 tor_assert(data_out
);
1954 #if (O_BINARY != 0 && O_TEXT != 0)
1955 tor_assert((open_flags
& (O_BINARY
|O_TEXT
)) != 0);
1958 tor_assert(tempname_len
> strlen(fname
)); /*check for overflow*/
1959 new_file
->filename
= tor_strdup(fname
);
1960 if (open_flags
& O_APPEND
) {
1962 new_file
->rename_on_close
= 0;
1964 open_flags
&= ~O_APPEND
;
1966 open_name
= new_file
->tempname
= tor_malloc(tempname_len
);
1967 if (tor_snprintf(new_file
->tempname
, tempname_len
, "%s.tmp", fname
)<0) {
1968 log_warn(LD_GENERAL
, "Failed to generate filename");
1971 /* We always replace an existing temporary file if there is one. */
1972 open_flags
|= O_CREAT
|O_TRUNC
;
1973 open_flags
&= ~O_EXCL
;
1974 new_file
->rename_on_close
= 1;
1976 if (open_flags
& O_BINARY
)
1977 new_file
->binary
= 1;
1979 new_file
->fd
= tor_open_cloexec(open_name
, open_flags
, mode
);
1980 if (new_file
->fd
< 0) {
1981 log_warn(LD_FS
, "Couldn't open \"%s\" (%s) for writing: %s",
1982 open_name
, fname
, strerror(errno
));
1986 if (tor_fd_seekend(new_file
->fd
) < 0) {
1987 log_warn(LD_FS
, "Couldn't seek to end of file \"%s\": %s", open_name
,
1993 *data_out
= new_file
;
1995 return new_file
->fd
;
1998 if (new_file
->fd
>= 0)
1999 close(new_file
->fd
);
2001 tor_free(new_file
->filename
);
2002 tor_free(new_file
->tempname
);
2007 /** Given <b>file_data</b> from start_writing_to_file(), return a stdio FILE*
2008 * that can be used to write to the same file. The caller should not mix
2009 * stdio calls with non-stdio calls. */
2011 fdopen_file(open_file_t
*file_data
)
2013 tor_assert(file_data
);
2014 if (file_data
->stdio_file
)
2015 return file_data
->stdio_file
;
2016 tor_assert(file_data
->fd
>= 0);
2017 if (!(file_data
->stdio_file
= fdopen(file_data
->fd
,
2018 file_data
->binary
?"ab":"a"))) {
2019 log_warn(LD_FS
, "Couldn't fdopen \"%s\" [%d]: %s", file_data
->filename
,
2020 file_data
->fd
, strerror(errno
));
2022 return file_data
->stdio_file
;
2025 /** Combines start_writing_to_file with fdopen_file(): arguments are as
2026 * for start_writing_to_file, but */
2028 start_writing_to_stdio_file(const char *fname
, int open_flags
, int mode
,
2029 open_file_t
**data_out
)
2032 if (start_writing_to_file(fname
, open_flags
, mode
, data_out
)<0)
2034 if (!(res
= fdopen_file(*data_out
))) {
2035 abort_writing_to_file(*data_out
);
2041 /** Helper function: close and free the underlying file and memory in
2042 * <b>file_data</b>. If we were writing into a temporary file, then delete
2043 * that file (if abort_write is true) or replaces the target file with
2044 * the temporary file (if abort_write is false). */
2046 finish_writing_to_file_impl(open_file_t
*file_data
, int abort_write
)
2049 tor_assert(file_data
&& file_data
->filename
);
2050 if (file_data
->stdio_file
) {
2051 if (fclose(file_data
->stdio_file
)) {
2052 log_warn(LD_FS
, "Error closing \"%s\": %s", file_data
->filename
,
2054 abort_write
= r
= -1;
2056 } else if (file_data
->fd
>= 0 && close(file_data
->fd
) < 0) {
2057 log_warn(LD_FS
, "Error flushing \"%s\": %s", file_data
->filename
,
2059 abort_write
= r
= -1;
2062 if (file_data
->rename_on_close
) {
2063 tor_assert(file_data
->tempname
&& file_data
->filename
);
2065 unlink(file_data
->tempname
);
2067 tor_assert(strcmp(file_data
->filename
, file_data
->tempname
));
2068 if (replace_file(file_data
->tempname
, file_data
->filename
)) {
2069 log_warn(LD_FS
, "Error replacing \"%s\": %s", file_data
->filename
,
2076 tor_free(file_data
->filename
);
2077 tor_free(file_data
->tempname
);
2078 tor_free(file_data
);
2083 /** Finish writing to <b>file_data</b>: close the file handle, free memory as
2084 * needed, and if using a temporary file, replace the original file with
2085 * the temporary file. */
2087 finish_writing_to_file(open_file_t
*file_data
)
2089 return finish_writing_to_file_impl(file_data
, 0);
2092 /** Finish writing to <b>file_data</b>: close the file handle, free memory as
2093 * needed, and if using a temporary file, delete it. */
2095 abort_writing_to_file(open_file_t
*file_data
)
2097 return finish_writing_to_file_impl(file_data
, 1);
2100 /** Helper: given a set of flags as passed to open(2), open the file
2101 * <b>fname</b> and write all the sized_chunk_t structs in <b>chunks</b> to
2102 * the file. Do so as atomically as possible e.g. by opening temp files and
2105 write_chunks_to_file_impl(const char *fname
, const smartlist_t
*chunks
,
2108 open_file_t
*file
= NULL
;
2111 fd
= start_writing_to_file(fname
, open_flags
, 0600, &file
);
2114 SMARTLIST_FOREACH(chunks
, sized_chunk_t
*, chunk
,
2116 result
= write_all(fd
, chunk
->bytes
, chunk
->len
, 0);
2118 log_warn(LD_FS
, "Error writing to \"%s\": %s", fname
,
2122 tor_assert((size_t)result
== chunk
->len
);
2125 return finish_writing_to_file(file
);
2127 abort_writing_to_file(file
);
2131 /** Given a smartlist of sized_chunk_t, write them atomically to a file
2132 * <b>fname</b>, overwriting or creating the file as necessary. */
2134 write_chunks_to_file(const char *fname
, const smartlist_t
*chunks
, int bin
)
2136 int flags
= OPEN_FLAGS_REPLACE
|(bin
?O_BINARY
:O_TEXT
);
2137 return write_chunks_to_file_impl(fname
, chunks
, flags
);
2140 /** Write <b>len</b> bytes, starting at <b>str</b>, to <b>fname</b>
2141 using the open() flags passed in <b>flags</b>. */
2143 write_bytes_to_file_impl(const char *fname
, const char *str
, size_t len
,
2147 sized_chunk_t c
= { str
, len
};
2148 smartlist_t
*chunks
= smartlist_create();
2149 smartlist_add(chunks
, &c
);
2150 r
= write_chunks_to_file_impl(fname
, chunks
, flags
);
2151 smartlist_free(chunks
);
2155 /** As write_str_to_file, but does not assume a NUL-terminated
2156 * string. Instead, we write <b>len</b> bytes, starting at <b>str</b>. */
2158 write_bytes_to_file(const char *fname
, const char *str
, size_t len
,
2161 return write_bytes_to_file_impl(fname
, str
, len
,
2162 OPEN_FLAGS_REPLACE
|(bin
?O_BINARY
:O_TEXT
));
2165 /** As write_bytes_to_file, but if the file already exists, append the bytes
2166 * to the end of the file instead of overwriting it. */
2168 append_bytes_to_file(const char *fname
, const char *str
, size_t len
,
2171 return write_bytes_to_file_impl(fname
, str
, len
,
2172 OPEN_FLAGS_APPEND
|(bin
?O_BINARY
:O_TEXT
));
2175 /** Like write_str_to_file(), but also return -1 if there was a file
2176 already residing in <b>fname</b>. */
2178 write_bytes_to_new_file(const char *fname
, const char *str
, size_t len
,
2181 return write_bytes_to_file_impl(fname
, str
, len
,
2182 OPEN_FLAGS_DONT_REPLACE
|
2183 (bin
?O_BINARY
:O_TEXT
));
2186 /** Read the contents of <b>filename</b> into a newly allocated
2187 * string; return the string on success or NULL on failure.
2189 * If <b>stat_out</b> is provided, store the result of stat()ing the
2190 * file into <b>stat_out</b>.
2192 * If <b>flags</b> & RFTS_BIN, open the file in binary mode.
2193 * If <b>flags</b> & RFTS_IGNORE_MISSING, don't warn if the file
2197 * This function <em>may</em> return an erroneous result if the file
2198 * is modified while it is running, but must not crash or overflow.
2199 * Right now, the error case occurs when the file length grows between
2200 * the call to stat and the call to read_all: the resulting string will
2204 read_file_to_str(const char *filename
, int flags
, struct stat
*stat_out
)
2206 int fd
; /* router file */
2207 struct stat statbuf
;
2210 int bin
= flags
& RFTS_BIN
;
2212 tor_assert(filename
);
2214 fd
= tor_open_cloexec(filename
,O_RDONLY
|(bin
?O_BINARY
:O_TEXT
),0);
2216 int severity
= LOG_WARN
;
2217 int save_errno
= errno
;
2218 if (errno
== ENOENT
&& (flags
& RFTS_IGNORE_MISSING
))
2219 severity
= LOG_INFO
;
2220 log_fn(severity
, LD_FS
,"Could not open \"%s\": %s",filename
,
2226 if (fstat(fd
, &statbuf
)<0) {
2227 int save_errno
= errno
;
2229 log_warn(LD_FS
,"Could not fstat \"%s\".",filename
);
2234 if ((uint64_t)(statbuf
.st_size
)+1 >= SIZE_T_CEILING
)
2237 string
= tor_malloc((size_t)(statbuf
.st_size
+1));
2239 r
= read_all(fd
,string
,(size_t)statbuf
.st_size
,0);
2241 int save_errno
= errno
;
2242 log_warn(LD_FS
,"Error reading from file \"%s\": %s", filename
,
2249 string
[r
] = '\0'; /* NUL-terminate the result. */
2252 if (!bin
&& strchr(string
, '\r')) {
2253 log_debug(LD_FS
, "We didn't convert CRLF to LF as well as we hoped "
2254 "when reading %s. Coping.",
2256 tor_strstrip(string
, "\r");
2260 statbuf
.st_size
= (size_t) r
;
2263 if (r
!= statbuf
.st_size
) {
2264 /* Unless we're using text mode on win32, we'd better have an exact
2265 * match for size. */
2266 int save_errno
= errno
;
2267 log_warn(LD_FS
,"Could read only %d of %ld bytes of file \"%s\".",
2268 (int)r
, (long)statbuf
.st_size
,filename
);
2276 memcpy(stat_out
, &statbuf
, sizeof(struct stat
));
2282 #define TOR_ISODIGIT(c) ('0' <= (c) && (c) <= '7')
2284 /** Given a c-style double-quoted escaped string in <b>s</b>, extract and
2285 * decode its contents into a newly allocated string. On success, assign this
2286 * string to *<b>result</b>, assign its length to <b>size_out</b> (if
2287 * provided), and return a pointer to the position in <b>s</b> immediately
2288 * after the string. On failure, return NULL.
2291 unescape_string(const char *s
, char **result
, size_t *size_out
)
2306 if ((cp
[1] == 'x' || cp
[1] == 'X')
2307 && TOR_ISXDIGIT(cp
[2]) && TOR_ISXDIGIT(cp
[3])) {
2309 } else if (TOR_ISODIGIT(cp
[1])) {
2311 if (TOR_ISODIGIT(*cp
)) ++cp
;
2312 if (TOR_ISODIGIT(*cp
)) ++cp
;
2325 out
= *result
= tor_malloc(cp
-s
+ 1);
2332 if (size_out
) *size_out
= out
- *result
;
2335 tor_fragile_assert();
2341 case 'n': *out
++ = '\n'; cp
+= 2; break;
2342 case 'r': *out
++ = '\r'; cp
+= 2; break;
2343 case 't': *out
++ = '\t'; cp
+= 2; break;
2345 *out
++ = ((hex_decode_digit(cp
[2])<<4) +
2346 hex_decode_digit(cp
[3]));
2349 case '0': case '1': case '2': case '3': case '4': case '5':
2354 if (TOR_ISODIGIT(*cp
)) { n
= n
*8 + *cp
-'0'; cp
++; }
2355 if (TOR_ISODIGIT(*cp
)) { n
= n
*8 + *cp
-'0'; cp
++; }
2356 if (n
> 255) { tor_free(*result
); return NULL
; }
2368 tor_free(*result
); return NULL
;
2377 /** Given a string containing part of a configuration file or similar format,
2378 * advance past comments and whitespace and try to parse a single line. If we
2379 * parse a line successfully, set *<b>key_out</b> to a new string holding the
2380 * key portion and *<b>value_out</b> to a new string holding the value portion
2381 * of the line, and return a pointer to the start of the next line. If we run
2382 * out of data, return a pointer to the end of the string. If we encounter an
2383 * error, return NULL.
2386 parse_config_line_from_str(const char *line
, char **key_out
, char **value_out
)
2388 /* I believe the file format here is supposed to be:
2389 FILE = (EMPTYLINE | LINE)* (EMPTYLASTLINE | LASTLINE)?
2391 EMPTYLASTLINE = SPACE* | COMMENT
2392 EMPTYLINE = EMPTYLASTLINE NL
2393 SPACE = ' ' | '\r' | '\t'
2394 COMMENT = '#' NOT-NL*
2395 NOT-NL = Any character except '\n'
2398 LASTLINE = SPACE* KEY SPACE* VALUES
2401 KEYCHAR = Any character except ' ', '\r', '\n', '\t', '#', "\"
2403 VALUES = QUOTEDVALUE | NORMALVALUE
2404 QUOTEDVALUE = QUOTE QVITEM* QUOTE EOLSPACE?
2406 QVCHAR = KEYCHAR | ESC ('n' | 't' | 'r' | '"' | ESC |'\'' | OCTAL | HEX)
2408 OCTAL = ODIGIT (ODIGIT ODIGIT?)?
2409 HEX = ('x' | 'X') HEXDIGIT HEXDIGIT
2411 HEXDIGIT = '0'..'9' | 'a' .. 'f' | 'A' .. 'F'
2412 EOLSPACE = SPACE* COMMENT?
2414 NORMALVALUE = (VALCHAR | ESC ESC_IGNORE | CONTINUATION)* EOLSPACE?
2415 VALCHAR = Any character except ESC, '#', and '\n'
2416 ESC_IGNORE = Any character except '#' or '\n'
2417 CONTINUATION = ESC NL ( COMMENT NL )*
2420 const char *key
, *val
, *cp
;
2421 int continuation
= 0;
2423 tor_assert(key_out
);
2424 tor_assert(value_out
);
2426 *key_out
= *value_out
= NULL
;
2428 /* Skip until the first keyword. */
2430 while (TOR_ISSPACE(*line
))
2433 while (*line
&& *line
!= '\n')
2440 if (!*line
) { /* End of string? */
2441 *key_out
= *value_out
= NULL
;
2445 /* Skip until the next space or \ followed by newline. */
2447 while (*line
&& !TOR_ISSPACE(*line
) && *line
!= '#' &&
2448 ! (line
[0] == '\\' && line
[1] == '\n'))
2450 *key_out
= tor_strndup(key
, line
-key
);
2452 /* Skip until the value. */
2453 while (*line
== ' ' || *line
== '\t')
2458 /* Find the end of the line. */
2459 if (*line
== '\"') { // XXX No continuation handling is done here
2460 if (!(line
= unescape_string(line
, value_out
, NULL
)))
2462 while (*line
== ' ' || *line
== '\t')
2464 if (*line
&& *line
!= '#' && *line
!= '\n')
2467 /* Look for the end of the line. */
2468 while (*line
&& *line
!= '\n' && (*line
!= '#' || continuation
)) {
2469 if (*line
== '\\' && line
[1] == '\n') {
2472 } else if (*line
== '#') {
2475 } while (*line
&& *line
!= '\n');
2483 if (*line
== '\n') {
2488 /* Now back cp up to be the last nonspace character */
2489 while (cp
>val
&& TOR_ISSPACE(*(cp
-1)))
2492 tor_assert(cp
>= val
);
2494 /* Now copy out and decode the value. */
2495 *value_out
= tor_strndup(val
, cp
-val
);
2498 v_out
= v_in
= *value_out
;
2503 } while (*v_in
&& *v_in
!= '\n');
2506 } else if (v_in
[0] == '\\' && v_in
[1] == '\n') {
2519 } while (*line
&& *line
!= '\n');
2521 while (TOR_ISSPACE(*line
)) ++line
;
2526 /** Expand any homedir prefix on <b>filename</b>; return a newly allocated
2529 expand_filename(const char *filename
)
2531 tor_assert(filename
);
2533 return tor_strdup(filename
);
2535 if (*filename
== '~') {
2536 char *home
, *result
=NULL
;
2539 if (filename
[1] == '/' || filename
[1] == '\0') {
2540 home
= getenv("HOME");
2542 log_warn(LD_CONFIG
, "Couldn't find $HOME environment variable while "
2543 "expanding \"%s\"; defaulting to \"\".", filename
);
2544 home
= tor_strdup("");
2546 home
= tor_strdup(home
);
2548 rest
= strlen(filename
)>=2?(filename
+2):"";
2551 char *username
, *slash
;
2552 slash
= strchr(filename
, '/');
2554 username
= tor_strndup(filename
+1,slash
-filename
-1);
2556 username
= tor_strdup(filename
+1);
2557 if (!(home
= get_user_homedir(username
))) {
2558 log_warn(LD_CONFIG
,"Couldn't get homedir for \"%s\"",username
);
2563 rest
= slash
? (slash
+1) : "";
2565 log_warn(LD_CONFIG
, "Couldn't expend homedir on system without pwd.h");
2566 return tor_strdup(filename
);
2570 /* Remove trailing slash. */
2571 if (strlen(home
)>1 && !strcmpend(home
,PATH_SEPARATOR
)) {
2572 home
[strlen(home
)-1] = '\0';
2574 tor_asprintf(&result
,"%s"PATH_SEPARATOR
"%s",home
,rest
);
2578 return tor_strdup(filename
);
2583 #define MAX_SCANF_WIDTH 9999
2585 /** Helper: given an ASCII-encoded decimal digit, return its numeric value.
2586 * NOTE: requires that its input be in-bounds. */
2588 digit_to_num(char d
)
2590 int num
= ((int)d
) - (int)'0';
2591 tor_assert(num
<= 9 && num
>= 0);
2595 /** Helper: Read an unsigned int from *<b>bufp</b> of up to <b>width</b>
2596 * characters. (Handle arbitrary width if <b>width</b> is less than 0.) On
2597 * success, store the result in <b>out</b>, advance bufp to the next
2598 * character, and return 0. On failure, return -1. */
2600 scan_unsigned(const char **bufp
, unsigned *out
, int width
, int base
)
2602 unsigned result
= 0;
2603 int scanned_so_far
= 0;
2604 const int hex
= base
==16;
2605 tor_assert(base
== 10 || base
== 16);
2606 if (!bufp
|| !*bufp
|| !out
)
2609 width
=MAX_SCANF_WIDTH
;
2611 while (**bufp
&& (hex
?TOR_ISXDIGIT(**bufp
):TOR_ISDIGIT(**bufp
))
2612 && scanned_so_far
< width
) {
2613 int digit
= hex
?hex_decode_digit(*(*bufp
)++):digit_to_num(*(*bufp
)++);
2614 unsigned new_result
= result
* base
+ digit
;
2615 if (new_result
> UINT32_MAX
|| new_result
< result
)
2616 return -1; /* over/underflow. */
2617 result
= new_result
;
2621 if (!scanned_so_far
) /* No actual digits scanned */
2628 /** Helper: copy up to <b>width</b> non-space characters from <b>bufp</b> to
2629 * <b>out</b>. Make sure <b>out</b> is nul-terminated. Advance <b>bufp</b>
2630 * to the next non-space character or the EOS. */
2632 scan_string(const char **bufp
, char *out
, int width
)
2634 int scanned_so_far
= 0;
2635 if (!bufp
|| !out
|| width
< 0)
2637 while (**bufp
&& ! TOR_ISSPACE(**bufp
) && scanned_so_far
< width
) {
2638 *out
++ = *(*bufp
)++;
2645 /** Locale-independent, minimal, no-surprises scanf variant, accepting only a
2646 * restricted pattern format. For more info on what it supports, see
2647 * tor_sscanf() documentation. */
2649 tor_vsscanf(const char *buf
, const char *pattern
, va_list ap
)
2654 if (*pattern
!= '%') {
2655 if (*buf
== *pattern
) {
2665 if (TOR_ISDIGIT(*pattern
)) {
2666 width
= digit_to_num(*pattern
++);
2667 while (TOR_ISDIGIT(*pattern
)) {
2669 width
+= digit_to_num(*pattern
++);
2670 if (width
> MAX_SCANF_WIDTH
)
2673 if (!width
) /* No zero-width things. */
2676 if (*pattern
== 'u' || *pattern
== 'x') {
2677 unsigned *u
= va_arg(ap
, unsigned *);
2678 const int base
= (*pattern
== 'u') ? 10 : 16;
2681 if (scan_unsigned(&buf
, u
, width
, base
)<0)
2685 } else if (*pattern
== 's') {
2686 char *s
= va_arg(ap
, char *);
2689 if (scan_string(&buf
, s
, width
)<0)
2693 } else if (*pattern
== 'c') {
2694 char *ch
= va_arg(ap
, char *);
2702 } else if (*pattern
== '%') {
2708 return -1; /* Unrecognized pattern component. */
2716 /** Minimal sscanf replacement: parse <b>buf</b> according to <b>pattern</b>
2717 * and store the results in the corresponding argument fields. Differs from
2718 * sscanf in that it: Only handles %u and %x and %Ns. Does not handle
2719 * arbitrarily long widths. %u and %x do not consume any space. Is
2720 * locale-independent. Returns -1 on malformed patterns.
2722 * (As with other locale-independent functions, we need this to parse data that
2723 * is in ASCII without worrying that the C library's locale-handling will make
2724 * miscellaneous characters look like numbers, spaces, and so on.)
2727 tor_sscanf(const char *buf
, const char *pattern
, ...)
2731 va_start(ap
, pattern
);
2732 r
= tor_vsscanf(buf
, pattern
, ap
);
2737 /** Append the string produced by tor_asprintf(<b>pattern</b>, <b>...</b>)
2740 smartlist_asprintf_add(struct smartlist_t
*sl
, const char *pattern
, ...)
2743 va_start(ap
, pattern
);
2744 smartlist_vasprintf_add(sl
, pattern
, ap
);
2748 /** va_list-based backend of smartlist_asprintf_add. */
2750 smartlist_vasprintf_add(struct smartlist_t
*sl
, const char *pattern
,
2755 tor_vasprintf(&str
, pattern
, args
);
2756 tor_assert(str
!= NULL
);
2758 smartlist_add(sl
, str
);
2761 /** Return a new list containing the filenames in the directory <b>dirname</b>.
2762 * Return NULL on error or if <b>dirname</b> is not a directory.
2765 tor_listdir(const char *dirname
)
2767 smartlist_t
*result
;
2770 TCHAR tpattern
[MAX_PATH
] = {0};
2771 char name
[MAX_PATH
] = {0};
2773 WIN32_FIND_DATA findData
;
2774 size_t pattern_len
= strlen(dirname
)+16;
2775 pattern
= tor_malloc(pattern_len
);
2776 tor_snprintf(pattern
, pattern_len
, "%s\\*", dirname
);
2778 mbstowcs(tpattern
,pattern
,MAX_PATH
);
2780 strlcpy(tpattern
, pattern
, MAX_PATH
);
2782 if (INVALID_HANDLE_VALUE
== (handle
= FindFirstFile(tpattern
, &findData
))) {
2786 result
= smartlist_create();
2789 wcstombs(name
,findData
.cFileName
,MAX_PATH
);
2791 strlcpy(name
,findData
.cFileName
,sizeof(name
));
2793 if (strcmp(name
, ".") &&
2794 strcmp(name
, "..")) {
2795 smartlist_add(result
, tor_strdup(name
));
2797 if (!FindNextFile(handle
, &findData
)) {
2799 if ((err
= GetLastError()) != ERROR_NO_MORE_FILES
) {
2800 char *errstr
= format_win32_error(err
);
2801 log_warn(LD_FS
, "Error reading directory '%s': %s", dirname
, errstr
);
2812 if (!(d
= opendir(dirname
)))
2815 result
= smartlist_create();
2816 while ((de
= readdir(d
))) {
2817 if (!strcmp(de
->d_name
, ".") ||
2818 !strcmp(de
->d_name
, ".."))
2820 smartlist_add(result
, tor_strdup(de
->d_name
));
2827 /** Return true iff <b>filename</b> is a relative path. */
2829 path_is_relative(const char *filename
)
2831 if (filename
&& filename
[0] == '/')
2834 else if (filename
&& filename
[0] == '\\')
2836 else if (filename
&& strlen(filename
)>3 && TOR_ISALPHA(filename
[0]) &&
2837 filename
[1] == ':' && filename
[2] == '\\')
2849 /* Based on code contributed by christian grothoff */
2850 /** True iff we've called start_daemon(). */
2851 static int start_daemon_called
= 0;
2852 /** True iff we've called finish_daemon(). */
2853 static int finish_daemon_called
= 0;
2854 /** Socketpair used to communicate between parent and child process while
2856 static int daemon_filedes
[2];
2857 /** Start putting the process into daemon mode: fork and drop all resources
2858 * except standard fds. The parent process never returns, but stays around
2859 * until finish_daemon is called. (Note: it's safe to call this more
2860 * than once: calls after the first are ignored.)
2867 if (start_daemon_called
)
2869 start_daemon_called
= 1;
2871 if (pipe(daemon_filedes
)) {
2872 log_err(LD_GENERAL
,"pipe failed; exiting. Error was %s", strerror(errno
));
2877 log_err(LD_GENERAL
,"fork failed. Exiting.");
2880 if (pid
) { /* Parent */
2884 close(daemon_filedes
[1]); /* we only read */
2886 while (0 < read(daemon_filedes
[0], &c
, sizeof(char))) {
2894 exit(1); /* child reported error */
2895 } else { /* Child */
2896 close(daemon_filedes
[0]); /* we only write */
2898 pid
= setsid(); /* Detach from controlling terminal */
2900 * Fork one more time, so the parent (the session group leader) can exit.
2901 * This means that we, as a non-session group leader, can never regain a
2902 * controlling terminal. This part is recommended by Stevens's
2903 * _Advanced Programming in the Unix Environment_.
2908 set_main_thread(); /* We are now the main thread. */
2914 /** Finish putting the process into daemon mode: drop standard fds, and tell
2915 * the parent process to exit. (Note: it's safe to call this more than once:
2916 * calls after the first are ignored. Calls start_daemon first if it hasn't
2917 * been called already.)
2920 finish_daemon(const char *desired_cwd
)
2924 if (finish_daemon_called
)
2926 if (!start_daemon_called
)
2928 finish_daemon_called
= 1;
2932 /* Don't hold the wrong FS mounted */
2933 if (chdir(desired_cwd
) < 0) {
2934 log_err(LD_GENERAL
,"chdir to \"%s\" failed. Exiting.",desired_cwd
);
2938 nullfd
= tor_open_cloexec("/dev/null", O_RDWR
, 0);
2940 log_err(LD_GENERAL
,"/dev/null can't be opened. Exiting.");
2943 /* close fds linking to invoking terminal, but
2944 * close usual incoming fds, but redirect them somewhere
2945 * useful so the fds don't get reallocated elsewhere.
2947 if (dup2(nullfd
,0) < 0 ||
2948 dup2(nullfd
,1) < 0 ||
2949 dup2(nullfd
,2) < 0) {
2950 log_err(LD_GENERAL
,"dup2 failed. Exiting.");
2955 /* signal success */
2956 if (write(daemon_filedes
[1], &c
, sizeof(char)) != sizeof(char)) {
2957 log_err(LD_GENERAL
,"write failed. Exiting.");
2959 close(daemon_filedes
[1]);
2962 /* defined(MS_WINDOWS) */
2968 finish_daemon(const char *cp
)
2974 /** Write the current process ID, followed by NL, into <b>filename</b>.
2977 write_pidfile(char *filename
)
2981 if ((pidfile
= fopen(filename
, "w")) == NULL
) {
2982 log_warn(LD_FS
, "Unable to open \"%s\" for writing: %s", filename
,
2986 fprintf(pidfile
, "%d\n", (int)_getpid());
2988 fprintf(pidfile
, "%d\n", (int)getpid());
2996 load_windows_system_library(const TCHAR
*library_name
)
2998 TCHAR path
[MAX_PATH
];
3000 n
= GetSystemDirectory(path
, MAX_PATH
);
3001 if (n
== 0 || n
+ _tcslen(library_name
) + 2 >= MAX_PATH
)
3003 _tcscat(path
, TEXT("\\"));
3004 _tcscat(path
, library_name
);
3005 return LoadLibrary(path
);
3009 /** Format a single argument for being put on a Windows command line.
3010 * Returns a newly allocated string */
3012 format_win_cmdline_argument(const char *arg
)
3014 char *formatted_arg
;
3019 /* Backslash we can point to when one is inserted into the string */
3020 const char backslash
= '\\';
3022 /* Smartlist of *char */
3023 smartlist_t
*arg_chars
;
3024 arg_chars
= smartlist_create();
3026 /* Quote string if it contains whitespace or is empty */
3027 need_quotes
= (strchr(arg
, ' ') || strchr(arg
, '\t') || '\0' == arg
[0]);
3029 /* Build up smartlist of *chars */
3030 for (c
=arg
; *c
!= '\0'; c
++) {
3032 /* Double up backslashes preceding a quote */
3033 for (i
=0; i
<(bs_counter
*2); i
++)
3034 smartlist_add(arg_chars
, (void*)&backslash
);
3036 /* Escape the quote */
3037 smartlist_add(arg_chars
, (void*)&backslash
);
3038 smartlist_add(arg_chars
, (void*)c
);
3039 } else if ('\\' == *c
) {
3040 /* Count backslashes until we know whether to double up */
3043 /* Don't double up slashes preceding a non-quote */
3044 for (i
=0; i
<bs_counter
; i
++)
3045 smartlist_add(arg_chars
, (void*)&backslash
);
3047 smartlist_add(arg_chars
, (void*)c
);
3050 /* Don't double up trailing backslashes */
3051 for (i
=0; i
<bs_counter
; i
++)
3052 smartlist_add(arg_chars
, (void*)&backslash
);
3054 /* Allocate space for argument, quotes (if needed), and terminator */
3055 formatted_arg
= tor_malloc(sizeof(char) *
3056 (smartlist_len(arg_chars
) + (need_quotes
?2:0) + 1));
3058 /* Add leading quote */
3061 formatted_arg
[i
++] = '"';
3063 /* Add characters */
3064 SMARTLIST_FOREACH(arg_chars
, char*, c
,
3066 formatted_arg
[i
++] = *c
;
3069 /* Add trailing quote */
3071 formatted_arg
[i
++] = '"';
3072 formatted_arg
[i
] = '\0';
3074 smartlist_free(arg_chars
);
3075 return formatted_arg
;
3078 /** Format a command line for use on Windows, which takes the command as a
3079 * string rather than string array. Follows the rules from "Parsing C++
3080 * Command-Line Arguments" in MSDN. Algorithm based on list2cmdline in the
3081 * Python subprocess module. Returns a newly allocated string */
3083 tor_join_win_cmdline(const char *argv
[])
3085 smartlist_t
*argv_list
;
3089 /* Format each argument and put the result in a smartlist */
3090 argv_list
= smartlist_create();
3091 for (i
=0; argv
[i
] != NULL
; i
++) {
3092 smartlist_add(argv_list
, (void *)format_win_cmdline_argument(argv
[i
]));
3095 /* Join the arguments with whitespace */
3096 joined_argv
= smartlist_join_strings(argv_list
, " ", 0, NULL
);
3098 /* Free the newly allocated arguments, and the smartlist */
3099 SMARTLIST_FOREACH(argv_list
, char *, arg
,
3103 smartlist_free(argv_list
);
3108 /** Format <b>child_state</b> and <b>saved_errno</b> as a hex string placed in
3109 * <b>hex_errno</b>. Called between fork and _exit, so must be signal-handler
3112 * <b>hex_errno</b> must have at least HEX_ERRNO_SIZE bytes available.
3114 * The format of <b>hex_errno</b> is: "CHILD_STATE/ERRNO\n", left-padded
3115 * with spaces. Note that there is no trailing \0. CHILD_STATE indicates where
3116 * in the processs of starting the child process did the failure occur (see
3117 * CHILD_STATE_* macros for definition), and SAVED_ERRNO is the value of
3118 * errno when the failure occurred.
3122 format_helper_exit_status(unsigned char child_state
, int saved_errno
,
3125 unsigned int unsigned_errno
;
3129 /* Fill hex_errno with spaces, and a trailing newline (memset may
3130 not be signal handler safe, so we can't use it) */
3131 for (i
= 0; i
< (HEX_ERRNO_SIZE
- 1); i
++)
3133 hex_errno
[HEX_ERRNO_SIZE
- 1] = '\n';
3135 /* Convert errno to be unsigned for hex conversion */
3136 if (saved_errno
< 0) {
3137 unsigned_errno
= (unsigned int) -saved_errno
;
3139 unsigned_errno
= (unsigned int) saved_errno
;
3142 /* Convert errno to hex (start before \n) */
3143 cur
= hex_errno
+ HEX_ERRNO_SIZE
- 2;
3145 /* Check for overflow on first iteration of the loop */
3146 if (cur
< hex_errno
)
3150 *cur
-- = "0123456789ABCDEF"[unsigned_errno
% 16];
3151 unsigned_errno
/= 16;
3152 } while (unsigned_errno
!= 0 && cur
>= hex_errno
);
3154 /* Prepend the minus sign if errno was negative */
3155 if (saved_errno
< 0 && cur
>= hex_errno
)
3159 if (cur
>= hex_errno
)
3162 /* Check for overflow on first iteration of the loop */
3163 if (cur
< hex_errno
)
3166 /* Convert child_state to hex */
3168 *cur
-- = "0123456789ABCDEF"[child_state
% 16];
3170 } while (child_state
!= 0 && cur
>= hex_errno
);
3173 /* Maximum number of file descriptors, if we cannot get it via sysconf() */
3174 #define DEFAULT_MAX_FD 256
3176 /** Terminate the process of <b>process_handle</b>.
3177 * Code borrowed from Python's os.kill. */
3179 tor_terminate_process(process_handle_t
*process_handle
)
3182 if (tor_get_exit_code(process_handle
, 0, NULL
) == PROCESS_EXIT_RUNNING
) {
3184 /* If the signal is outside of what GenerateConsoleCtrlEvent can use,
3185 attempt to open and terminate the process. */
3186 handle
= OpenProcess(PROCESS_ALL_ACCESS
, FALSE
,
3187 process_handle
->pid
.dwProcessId
);
3191 if (!TerminateProcess(handle
, 0))
3197 return kill(process_handle
->pid
, SIGTERM
);
3203 /** Return the Process ID of <b>process_handle</b>. */
3205 tor_process_get_pid(process_handle_t
*process_handle
)
3208 return (int) process_handle
->pid
.dwProcessId
;
3210 return (int) process_handle
->pid
;
3216 tor_process_get_stdout_pipe(process_handle_t
*process_handle
)
3218 return process_handle
->stdout_pipe
;
3222 tor_process_get_stdout_pipe(process_handle_t
*process_handle
)
3224 return process_handle
->stdout_handle
;
3228 static process_handle_t
*
3229 process_handle_new(void)
3231 process_handle_t
*out
= tor_malloc_zero(sizeof(process_handle_t
));
3234 out
->stdout_pipe
= -1;
3235 out
->stderr_pipe
= -1;
3242 #define CHILD_STATE_INIT 0
3243 #define CHILD_STATE_PIPE 1
3244 #define CHILD_STATE_MAXFD 2
3245 #define CHILD_STATE_FORK 3
3246 #define CHILD_STATE_DUPOUT 4
3247 #define CHILD_STATE_DUPERR 5
3248 #define CHILD_STATE_REDIRECT 6
3249 #define CHILD_STATE_CLOSEFD 7
3250 #define CHILD_STATE_EXEC 8
3251 #define CHILD_STATE_FAILEXEC 9
3253 /** Start a program in the background. If <b>filename</b> contains a '/', then
3254 * it will be treated as an absolute or relative path. Otherwise, on
3255 * non-Windows systems, the system path will be searched for <b>filename</b>.
3256 * On Windows, only the current directory will be searched. Here, to search the
3257 * system path (as well as the application directory, current working
3258 * directory, and system directories), set filename to NULL.
3260 * The strings in <b>argv</b> will be passed as the command line arguments of
3261 * the child program (following convention, argv[0] should normally be the
3262 * filename of the executable, and this must be the case if <b>filename</b> is
3263 * NULL). The last element of argv must be NULL. A handle to the child process
3264 * will be returned in process_handle (which must be non-NULL). Read
3265 * process_handle.status to find out if the process was successfully launched.
3266 * For convenience, process_handle.status is returned by this function.
3268 * Some parts of this code are based on the POSIX subprocess module from
3269 * Python, and example code from
3270 * http://msdn.microsoft.com/en-us/library/ms682499%28v=vs.85%29.aspx.
3273 tor_spawn_background(const char *const filename
, const char **argv
,
3279 process_handle_t
**process_handle_out
)
3282 HANDLE stdout_pipe_read
= NULL
;
3283 HANDLE stdout_pipe_write
= NULL
;
3284 HANDLE stderr_pipe_read
= NULL
;
3285 HANDLE stderr_pipe_write
= NULL
;
3286 process_handle_t
*process_handle
;
3289 STARTUPINFO siStartInfo
;
3290 BOOL retval
= FALSE
;
3292 SECURITY_ATTRIBUTES saAttr
;
3295 (void)envp
; // Unused on Windows
3297 saAttr
.nLength
= sizeof(SECURITY_ATTRIBUTES
);
3298 saAttr
.bInheritHandle
= TRUE
;
3299 /* TODO: should we set explicit security attributes? (#2046, comment 5) */
3300 saAttr
.lpSecurityDescriptor
= NULL
;
3302 /* Assume failure to start process */
3303 status
= PROCESS_STATUS_ERROR
;
3305 /* Set up pipe for stdout */
3306 if (!CreatePipe(&stdout_pipe_read
, &stdout_pipe_write
, &saAttr
, 0)) {
3307 log_warn(LD_GENERAL
,
3308 "Failed to create pipe for stdout communication with child process: %s",
3309 format_win32_error(GetLastError()));
3312 if (!SetHandleInformation(stdout_pipe_read
, HANDLE_FLAG_INHERIT
, 0)) {
3313 log_warn(LD_GENERAL
,
3314 "Failed to configure pipe for stdout communication with child "
3315 "process: %s", format_win32_error(GetLastError()));
3319 /* Set up pipe for stderr */
3320 if (!CreatePipe(&stderr_pipe_read
, &stderr_pipe_write
, &saAttr
, 0)) {
3321 log_warn(LD_GENERAL
,
3322 "Failed to create pipe for stderr communication with child process: %s",
3323 format_win32_error(GetLastError()));
3326 if (!SetHandleInformation(stderr_pipe_read
, HANDLE_FLAG_INHERIT
, 0)) {
3327 log_warn(LD_GENERAL
,
3328 "Failed to configure pipe for stderr communication with child "
3329 "process: %s", format_win32_error(GetLastError()));
3333 /* Create the child process */
3335 /* Windows expects argv to be a whitespace delimited string, so join argv up
3337 joined_argv
= tor_join_win_cmdline(argv
);
3339 process_handle
= process_handle_new();
3340 process_handle
->status
= status
;
3342 ZeroMemory(&(process_handle
->pid
), sizeof(PROCESS_INFORMATION
));
3343 ZeroMemory(&siStartInfo
, sizeof(STARTUPINFO
));
3344 siStartInfo
.cb
= sizeof(STARTUPINFO
);
3345 siStartInfo
.hStdError
= stderr_pipe_write
;
3346 siStartInfo
.hStdOutput
= stdout_pipe_write
;
3347 siStartInfo
.hStdInput
= NULL
;
3348 siStartInfo
.dwFlags
|= STARTF_USESTDHANDLES
;
3350 /* Create the child process */
3352 retval
= CreateProcess(filename
, // module name
3353 joined_argv
, // command line
3354 /* TODO: should we set explicit security attributes? (#2046, comment 5) */
3355 NULL
, // process security attributes
3356 NULL
, // primary thread security attributes
3357 TRUE
, // handles are inherited
3358 /*(TODO: set CREATE_NEW CONSOLE/PROCESS_GROUP to make GetExitCodeProcess()
3360 0, // creation flags
3361 envp
, // use parent's environment
3362 NULL
, // use parent's current directory
3363 &siStartInfo
, // STARTUPINFO pointer
3364 &(process_handle
->pid
)); // receives PROCESS_INFORMATION
3366 tor_free(joined_argv
);
3369 log_warn(LD_GENERAL
,
3370 "Failed to create child process %s: %s", filename
?filename
:argv
[0],
3371 format_win32_error(GetLastError()));
3372 tor_free(process_handle
);
3374 /* TODO: Close hProcess and hThread in process_handle->pid? */
3375 process_handle
->stdout_pipe
= stdout_pipe_read
;
3376 process_handle
->stderr_pipe
= stderr_pipe_read
;
3377 status
= process_handle
->status
= PROCESS_STATUS_RUNNING
;
3380 /* TODO: Close pipes on exit */
3381 *process_handle_out
= process_handle
;
3389 process_handle_t
*process_handle
;
3392 const char *error_message
= SPAWN_ERROR_MESSAGE
;
3393 size_t error_message_length
;
3395 /* Represents where in the process of spawning the program is;
3396 this is used for printing out the error message */
3397 unsigned char child_state
= CHILD_STATE_INIT
;
3399 char hex_errno
[HEX_ERRNO_SIZE
];
3401 static int max_fd
= -1;
3403 status
= PROCESS_STATUS_ERROR
;
3405 /* We do the strlen here because strlen() is not signal handler safe,
3406 and we are not allowed to use unsafe functions between fork and exec */
3407 error_message_length
= strlen(error_message
);
3409 child_state
= CHILD_STATE_PIPE
;
3411 /* Set up pipe for redirecting stdout and stderr of child */
3412 retval
= pipe(stdout_pipe
);
3414 log_warn(LD_GENERAL
,
3415 "Failed to set up pipe for stdout communication with child process: %s",
3420 retval
= pipe(stderr_pipe
);
3422 log_warn(LD_GENERAL
,
3423 "Failed to set up pipe for stderr communication with child process: %s",
3428 child_state
= CHILD_STATE_MAXFD
;
3432 max_fd
= (int) sysconf(_SC_OPEN_MAX
);
3434 max_fd
= DEFAULT_MAX_FD
;
3435 log_warn(LD_GENERAL
,
3436 "Cannot find maximum file descriptor, assuming %d", max_fd
);
3439 max_fd
= DEFAULT_MAX_FD
;
3442 child_state
= CHILD_STATE_FORK
;
3448 child_state
= CHILD_STATE_DUPOUT
;
3450 /* Link child stdout to the write end of the pipe */
3451 retval
= dup2(stdout_pipe
[1], STDOUT_FILENO
);
3455 child_state
= CHILD_STATE_DUPERR
;
3457 /* Link child stderr to the write end of the pipe */
3458 retval
= dup2(stderr_pipe
[1], STDERR_FILENO
);
3462 child_state
= CHILD_STATE_REDIRECT
;
3464 /* Link stdin to /dev/null */
3465 fd
= open("/dev/null", O_RDONLY
); /* NOT cloexec, obviously. */
3467 dup2(fd
, STDIN_FILENO
);
3471 child_state
= CHILD_STATE_CLOSEFD
;
3473 close(stderr_pipe
[0]);
3474 close(stderr_pipe
[1]);
3475 close(stdout_pipe
[0]);
3476 close(stdout_pipe
[1]);
3479 /* Close all other fds, including the read end of the pipe */
3480 /* XXX: We should now be doing enough FD_CLOEXEC setting to make
3482 for (fd
= STDERR_FILENO
+ 1; fd
< max_fd
; fd
++) {
3486 child_state
= CHILD_STATE_EXEC
;
3488 /* Call the requested program. We need the cast because
3489 execvp doesn't define argv as const, even though it
3490 does not modify the arguments */
3492 execve(filename
, (char *const *) argv
, (char*const*)envp
);
3494 execvp(filename
, (char *const *) argv
);
3496 /* If we got here, the exec or open(/dev/null) failed */
3498 child_state
= CHILD_STATE_FAILEXEC
;
3501 /* XXX: are we leaking fds from the pipe? */
3503 format_helper_exit_status(child_state
, errno
, hex_errno
);
3505 /* Write the error message. GCC requires that we check the return
3506 value, but there is nothing we can do if it fails */
3507 /* TODO: Don't use STDOUT, use a pipe set up just for this purpose */
3508 nbytes
= write(STDOUT_FILENO
, error_message
, error_message_length
);
3509 nbytes
= write(STDOUT_FILENO
, hex_errno
, sizeof(hex_errno
));
3514 /* Never reached, but avoids compiler warning */
3521 log_warn(LD_GENERAL
, "Failed to fork child process: %s", strerror(errno
));
3522 close(stdout_pipe
[0]);
3523 close(stdout_pipe
[1]);
3524 close(stderr_pipe
[0]);
3525 close(stderr_pipe
[1]);
3529 process_handle
= process_handle_new();
3530 process_handle
->status
= status
;
3531 process_handle
->pid
= pid
;
3533 /* TODO: If the child process forked but failed to exec, waitpid it */
3535 /* Return read end of the pipes to caller, and close write end */
3536 process_handle
->stdout_pipe
= stdout_pipe
[0];
3537 retval
= close(stdout_pipe
[1]);
3540 log_warn(LD_GENERAL
,
3541 "Failed to close write end of stdout pipe in parent process: %s",
3545 process_handle
->stderr_pipe
= stderr_pipe
[0];
3546 retval
= close(stderr_pipe
[1]);
3549 log_warn(LD_GENERAL
,
3550 "Failed to close write end of stderr pipe in parent process: %s",
3554 status
= process_handle
->status
= PROCESS_STATUS_RUNNING
;
3555 /* Set stdout/stderr pipes to be non-blocking */
3556 fcntl(process_handle
->stdout_pipe
, F_SETFL
, O_NONBLOCK
);
3557 fcntl(process_handle
->stderr_pipe
, F_SETFL
, O_NONBLOCK
);
3558 /* Open the buffered IO streams */
3559 process_handle
->stdout_handle
= fdopen(process_handle
->stdout_pipe
, "r");
3560 process_handle
->stderr_handle
= fdopen(process_handle
->stderr_pipe
, "r");
3562 *process_handle_out
= process_handle
;
3563 return process_handle
->status
;
3564 #endif // MS_WINDOWS
3567 /** Destroy all resources allocated by the process handle in
3568 * <b>process_handle</b>.
3569 * If <b>also_terminate_process</b> is true, also terminate the
3570 * process of the process handle. */
3572 tor_process_handle_destroy(process_handle_t
*process_handle
,
3573 int also_terminate_process
)
3575 if (!process_handle
)
3578 if (also_terminate_process
) {
3579 if (tor_terminate_process(process_handle
) < 0) {
3580 log_notice(LD_GENERAL
, "Failed to terminate process with PID '%d'",
3581 tor_process_get_pid(process_handle
));
3583 log_info(LD_GENERAL
, "Terminated process with PID '%d'",
3584 tor_process_get_pid(process_handle
));
3588 process_handle
->status
= PROCESS_STATUS_NOTRUNNING
;
3591 if (process_handle
->stdout_pipe
)
3592 CloseHandle(process_handle
->stdout_pipe
);
3594 if (process_handle
->stderr_pipe
)
3595 CloseHandle(process_handle
->stderr_pipe
);
3597 if (process_handle
->stdout_handle
)
3598 fclose(process_handle
->stdout_handle
);
3600 if (process_handle
->stderr_handle
)
3601 fclose(process_handle
->stderr_handle
);
3604 memset(process_handle
, 0x0f, sizeof(process_handle_t
));
3605 tor_free(process_handle
);
3608 /** Get the exit code of a process specified by <b>process_handle</b> and store
3609 * it in <b>exit_code</b>, if set to a non-NULL value. If <b>block</b> is set
3610 * to true, the call will block until the process has exited. Otherwise if
3611 * the process is still running, the function will return
3612 * PROCESS_EXIT_RUNNING, and exit_code will be left unchanged. Returns
3613 * PROCESS_EXIT_EXITED if the process did exit. If there is a failure,
3614 * PROCESS_EXIT_ERROR will be returned and the contents of exit_code (if
3615 * non-NULL) will be undefined. N.B. Under *nix operating systems, this will
3616 * probably not work in Tor, because waitpid() is called in main.c to reap any
3617 * terminated child processes.*/
3619 tor_get_exit_code(const process_handle_t
*process_handle
,
3620 int block
, int *exit_code
)
3627 /* Wait for the process to exit */
3628 retval
= WaitForSingleObject(process_handle
->pid
.hProcess
, INFINITE
);
3629 if (retval
!= WAIT_OBJECT_0
) {
3630 log_warn(LD_GENERAL
, "WaitForSingleObject() failed (%d): %s",
3631 (int)retval
, format_win32_error(GetLastError()));
3632 return PROCESS_EXIT_ERROR
;
3635 retval
= WaitForSingleObject(process_handle
->pid
.hProcess
, 0);
3636 if (WAIT_TIMEOUT
== retval
) {
3637 /* Process has not exited */
3638 return PROCESS_EXIT_RUNNING
;
3639 } else if (retval
!= WAIT_OBJECT_0
) {
3640 log_warn(LD_GENERAL
, "WaitForSingleObject() failed (%d): %s",
3641 (int)retval
, format_win32_error(GetLastError()));
3642 return PROCESS_EXIT_ERROR
;
3646 if (exit_code
!= NULL
) {
3647 success
= GetExitCodeProcess(process_handle
->pid
.hProcess
,
3650 log_warn(LD_GENERAL
, "GetExitCodeProcess() failed: %s",
3651 format_win32_error(GetLastError()));
3652 return PROCESS_EXIT_ERROR
;
3659 retval
= waitpid(process_handle
->pid
, &stat_loc
, block
?0:WNOHANG
);
3660 if (!block
&& 0 == retval
) {
3661 /* Process has not exited */
3662 return PROCESS_EXIT_RUNNING
;
3663 } else if (retval
!= process_handle
->pid
) {
3664 log_warn(LD_GENERAL
, "waitpid() failed for PID %d: %s",
3665 process_handle
->pid
, strerror(errno
));
3666 return PROCESS_EXIT_ERROR
;
3669 if (!WIFEXITED(stat_loc
)) {
3670 log_warn(LD_GENERAL
, "Process %d did not exit normally",
3671 process_handle
->pid
);
3672 return PROCESS_EXIT_ERROR
;
3675 if (exit_code
!= NULL
)
3676 *exit_code
= WEXITSTATUS(stat_loc
);
3677 #endif // MS_WINDOWS
3679 return PROCESS_EXIT_EXITED
;
3683 /** Read from a handle <b>h</b> into <b>buf</b>, up to <b>count</b> bytes. If
3684 * <b>hProcess</b> is NULL, the function will return immediately if there is
3685 * nothing more to read. Otherwise <b>hProcess</b> should be set to the handle
3686 * to the process owning the <b>h</b>. In this case, the function will exit
3687 * only once the process has exited, or <b>count</b> bytes are read. Returns
3688 * the number of bytes read, or -1 on error. */
3690 tor_read_all_handle(HANDLE h
, char *buf
, size_t count
,
3691 const process_handle_t
*process
)
3696 BOOL process_exited
= FALSE
;
3698 if (count
> SIZE_T_CEILING
|| count
> SSIZE_T_MAX
)
3701 while (numread
!= count
) {
3702 /* Check if there is anything to read */
3703 retval
= PeekNamedPipe(h
, NULL
, 0, NULL
, &byte_count
, NULL
);
3705 log_warn(LD_GENERAL
,
3706 "Failed to peek from handle: %s",
3707 format_win32_error(GetLastError()));
3709 } else if (0 == byte_count
) {
3710 /* Nothing available: process exited or it is busy */
3712 /* Exit if we don't know whether the process is running */
3713 if (NULL
== process
)
3716 /* The process exited and there's nothing left to read from it */
3720 /* If process is not running, check for output one more time in case
3721 it wrote something after the peek was performed. Otherwise keep on
3722 waiting for output */
3723 tor_assert(process
!= NULL
);
3724 byte_count
= WaitForSingleObject(process
->pid
.hProcess
, 0);
3725 if (WAIT_TIMEOUT
!= byte_count
)
3726 process_exited
= TRUE
;
3731 /* There is data to read; read it */
3732 retval
= ReadFile(h
, buf
+numread
, count
-numread
, &byte_count
, NULL
);
3733 tor_assert(byte_count
+ numread
<= count
);
3735 log_warn(LD_GENERAL
, "Failed to read from handle: %s",
3736 format_win32_error(GetLastError()));
3738 } else if (0 == byte_count
) {
3742 numread
+= byte_count
;
3744 return (ssize_t
)numread
;
3747 /** Read from a handle <b>h</b> into <b>buf</b>, up to <b>count</b> bytes. If
3748 * <b>process</b> is NULL, the function will return immediately if there is
3749 * nothing more to read. Otherwise data will be read until end of file, or
3750 * <b>count</b> bytes are read. Returns the number of bytes read, or -1 on
3751 * error. Sets <b>eof</b> to true if <b>eof</b> is not NULL and the end of the
3752 * file has been reached. */
3754 tor_read_all_handle(FILE *h
, char *buf
, size_t count
,
3755 const process_handle_t
*process
,
3764 if (count
> SIZE_T_CEILING
|| count
> SSIZE_T_MAX
)
3767 while (numread
!= count
) {
3768 /* Use fgets because that is what we use in log_from_pipe() */
3769 retval
= fgets(buf
+numread
, (int)(count
-numread
), h
);
3770 if (NULL
== retval
) {
3772 log_debug(LD_GENERAL
, "fgets() reached end of file");
3777 if (EAGAIN
== errno
) {
3783 log_warn(LD_GENERAL
, "fgets() from handle failed: %s",
3789 tor_assert(retval
!= NULL
);
3790 tor_assert(strlen(retval
) + numread
<= count
);
3791 numread
+= strlen(retval
);
3794 log_debug(LD_GENERAL
, "fgets() read %d bytes from handle", (int)numread
);
3795 return (ssize_t
)numread
;
3799 /** Read from stdout of a process until the process exits. */
3801 tor_read_all_from_process_stdout(const process_handle_t
*process_handle
,
3802 char *buf
, size_t count
)
3805 return tor_read_all_handle(process_handle
->stdout_pipe
, buf
, count
,
3808 return tor_read_all_handle(process_handle
->stdout_handle
, buf
, count
,
3809 process_handle
, NULL
);
3813 /** Read from stdout of a process until the process exits. */
3815 tor_read_all_from_process_stderr(const process_handle_t
*process_handle
,
3816 char *buf
, size_t count
)
3819 return tor_read_all_handle(process_handle
->stderr_pipe
, buf
, count
,
3822 return tor_read_all_handle(process_handle
->stderr_handle
, buf
, count
,
3823 process_handle
, NULL
);
3827 /** Split buf into lines, and add to smartlist. The buffer <b>buf</b> will be
3828 * modified. The resulting smartlist will consist of pointers to buf, so there
3829 * is no need to free the contents of sl. <b>buf</b> must be a NUL-terminated
3830 * string. <b>len</b> should be set to the length of the buffer excluding the
3831 * NUL. Non-printable characters (including NUL) will be replaced with "." */
3833 tor_split_lines(smartlist_t
*sl
, char *buf
, int len
)
3835 /* Index in buf of the start of the current line */
3837 /* Index in buf of the current character being processed */
3839 /* Are we currently in a line */
3842 /* Loop over string */
3844 /* Loop until end of line or end of string */
3845 for (; cur
< len
; cur
++) {
3847 if ('\r' == buf
[cur
] || '\n' == buf
[cur
]) {
3850 /* Point cur to the next line */
3852 /* Line starts at start and ends with a nul */
3855 if (!TOR_ISPRINT(buf
[cur
]))
3859 if ('\r' == buf
[cur
] || '\n' == buf
[cur
]) {
3860 /* Skip leading vertical space */
3865 if (!TOR_ISPRINT(buf
[cur
]))
3870 /* We are at the end of the line or end of string. If in_line is true there
3871 * is a line which starts at buf+start and ends at a NUL. cur points to
3872 * the character after the NUL. */
3874 smartlist_add(sl
, (void *)(buf
+start
));
3877 return smartlist_len(sl
);
3881 /** Read from stream, and send lines to log at the specified log level.
3882 * Returns -1 if there is a error reading, and 0 otherwise.
3883 * If the generated stream is flushed more often than on new lines, or
3884 * a read exceeds 256 bytes, lines will be truncated. This should be fixed,
3885 * along with the corresponding problem on *nix (see bug #2045).
3888 log_from_handle(HANDLE
*pipe
, int severity
)
3894 pos
= tor_read_all_handle(pipe
, buf
, sizeof(buf
) - 1, NULL
);
3897 log_warn(LD_GENERAL
, "Failed to read data from subprocess");
3902 /* There's nothing to read (process is busy or has exited) */
3903 log_debug(LD_GENERAL
, "Subprocess had nothing to say");
3907 /* End with a null even if there isn't a \r\n at the end */
3908 /* TODO: What if this is a partial line? */
3910 log_debug(LD_GENERAL
, "Subprocess had %d bytes to say", pos
);
3912 /* Split up the buffer */
3913 lines
= smartlist_create();
3914 tor_split_lines(lines
, buf
, pos
);
3917 SMARTLIST_FOREACH(lines
, char *, line
,
3919 log_fn(severity
, LD_GENERAL
, "Port forwarding helper says: %s", line
);
3921 smartlist_free(lines
);
3928 /** Read from stream, and send lines to log at the specified log level.
3929 * Returns 1 if stream is closed normally, -1 if there is a error reading, and
3930 * 0 otherwise. Handles lines from tor-fw-helper and
3931 * tor_spawn_background() specially.
3934 log_from_pipe(FILE *stream
, int severity
, const char *executable
,
3938 enum stream_status r
;
3941 r
= get_string_from_pipe(stream
, buf
, sizeof(buf
) - 1);
3943 if (r
== IO_STREAM_CLOSED
) {
3945 } else if (r
== IO_STREAM_EAGAIN
) {
3947 } else if (r
== IO_STREAM_TERM
) {
3951 tor_assert(r
== IO_STREAM_OKAY
);
3953 /* Check if buf starts with SPAWN_ERROR_MESSAGE */
3954 if (strcmpstart(buf
, SPAWN_ERROR_MESSAGE
) == 0) {
3955 /* Parse error message */
3956 int retval
, child_state
, saved_errno
;
3957 retval
= tor_sscanf(buf
, SPAWN_ERROR_MESSAGE
"%x/%x",
3958 &child_state
, &saved_errno
);
3960 log_warn(LD_GENERAL
,
3961 "Failed to start child process \"%s\" in state %d: %s",
3962 executable
, child_state
, strerror(saved_errno
));
3966 /* Failed to parse message from child process, log it as a
3968 log_warn(LD_GENERAL
,
3969 "Unexpected message from port forwarding helper \"%s\": %s",
3973 log_fn(severity
, LD_GENERAL
, "Port forwarding helper says: %s", buf
);
3977 /* We should never get here */
3982 /** Reads from <b>stream</b> and stores input in <b>buf_out</b> making
3983 * sure it's below <b>count</b> bytes.
3984 * If the string has a trailing newline, we strip it off.
3986 * This function is specifically created to handle input from managed
3987 * proxies, according to the pluggable transports spec. Make sure it
3988 * fits your needs before using it.
3991 * IO_STREAM_CLOSED: If the stream is closed.
3992 * IO_STREAM_EAGAIN: If there is nothing to read and we should check back
3994 * IO_STREAM_TERM: If something is wrong with the stream.
3995 * IO_STREAM_OKAY: If everything went okay and we got a string
3996 * in <b>buf_out</b>. */
3998 get_string_from_pipe(FILE *stream
, char *buf_out
, size_t count
)
4003 tor_assert(count
<= INT_MAX
);
4005 retval
= fgets(buf_out
, (int)count
, stream
);
4009 /* Program has closed stream (probably it exited) */
4010 /* TODO: check error */
4011 return IO_STREAM_CLOSED
;
4013 if (EAGAIN
== errno
) {
4014 /* Nothing more to read, try again next time */
4015 return IO_STREAM_EAGAIN
;
4017 /* There was a problem, abandon this child process */
4018 return IO_STREAM_TERM
;
4022 len
= strlen(buf_out
);
4025 if (buf_out
[len
- 1] == '\n') {
4026 /* Remove the trailing newline */
4027 buf_out
[len
- 1] = '\0';
4029 /* No newline; check whether we overflowed the buffer */
4031 log_info(LD_GENERAL
,
4032 "Line from stream was truncated: %s", buf_out
);
4033 /* TODO: What to do with this error? */
4036 return IO_STREAM_OKAY
;
4039 /* We should never get here */
4040 return IO_STREAM_TERM
;
4044 tor_check_port_forwarding(const char *filename
, int dir_port
, int or_port
,
4047 /* When fw-helper succeeds, how long do we wait until running it again */
4048 #define TIME_TO_EXEC_FWHELPER_SUCCESS 300
4049 /* When fw-helper failed to start, how long do we wait until running it again
4051 #define TIME_TO_EXEC_FWHELPER_FAIL 60
4053 /* Static variables are initialized to zero, so child_handle.status=0
4054 * which corresponds to it not running on startup */
4055 static process_handle_t
*child_handle
=NULL
;
4057 static time_t time_to_run_helper
= 0;
4058 int stdout_status
, stderr_status
, retval
;
4059 const char *argv
[10];
4060 char s_dirport
[6], s_orport
[6];
4062 tor_assert(filename
);
4064 /* Set up command line for tor-fw-helper */
4065 snprintf(s_dirport
, sizeof s_dirport
, "%d", dir_port
);
4066 snprintf(s_orport
, sizeof s_orport
, "%d", or_port
);
4068 /* TODO: Allow different internal and external ports */
4070 argv
[1] = "--internal-or-port";
4072 argv
[3] = "--external-or-port";
4074 argv
[5] = "--internal-dir-port";
4075 argv
[6] = s_dirport
;
4076 argv
[7] = "--external-dir-port";
4077 argv
[8] = s_dirport
;
4080 /* Start the child, if it is not already running */
4081 if ((!child_handle
|| child_handle
->status
!= PROCESS_STATUS_RUNNING
) &&
4082 time_to_run_helper
< now
) {
4085 /* Assume tor-fw-helper will succeed, start it later*/
4086 time_to_run_helper
= now
+ TIME_TO_EXEC_FWHELPER_SUCCESS
;
4089 tor_process_handle_destroy(child_handle
, 1);
4090 child_handle
= NULL
;
4094 /* Passing NULL as lpApplicationName makes Windows search for the .exe */
4095 status
= tor_spawn_background(NULL
, argv
, NULL
, &child_handle
);
4097 status
= tor_spawn_background(filename
, argv
, NULL
, &child_handle
);
4100 if (PROCESS_STATUS_ERROR
== status
) {
4101 log_warn(LD_GENERAL
, "Failed to start port forwarding helper %s",
4103 time_to_run_helper
= now
+ TIME_TO_EXEC_FWHELPER_FAIL
;
4107 log_info(LD_GENERAL
,
4108 "Started port forwarding helper (%s) with pid '%d'",
4109 filename
, tor_process_get_pid(child_handle
));
4112 /* If child is running, read from its stdout and stderr) */
4113 if (child_handle
&& PROCESS_STATUS_RUNNING
== child_handle
->status
) {
4114 /* Read from stdout/stderr and log result */
4117 stdout_status
= log_from_handle(child_handle
->stdout_pipe
, LOG_INFO
);
4118 stderr_status
= log_from_handle(child_handle
->stderr_pipe
, LOG_WARN
);
4119 /* If we got this far (on Windows), the process started */
4122 stdout_status
= log_from_pipe(child_handle
->stdout_handle
,
4123 LOG_INFO
, filename
, &retval
);
4124 stderr_status
= log_from_pipe(child_handle
->stderr_handle
,
4125 LOG_WARN
, filename
, &retval
);
4128 /* There was a problem in the child process */
4129 time_to_run_helper
= now
+ TIME_TO_EXEC_FWHELPER_FAIL
;
4132 /* Combine the two statuses in order of severity */
4133 if (-1 == stdout_status
|| -1 == stderr_status
)
4134 /* There was a failure */
4137 else if (!child_handle
|| tor_get_exit_code(child_handle
, 0, NULL
) !=
4138 PROCESS_EXIT_RUNNING
) {
4139 /* process has exited or there was an error */
4140 /* TODO: Do something with the process return value */
4141 /* TODO: What if the process output something since
4142 * between log_from_handle and tor_get_exit_code? */
4146 else if (1 == stdout_status
|| 1 == stderr_status
)
4147 /* stdout or stderr was closed, the process probably
4148 * exited. It will be reaped by waitpid() in main.c */
4149 /* TODO: Do something with the process return value */
4156 /* If either pipe indicates a failure, act on it */
4159 log_info(LD_GENERAL
, "Port forwarding helper terminated");
4160 child_handle
->status
= PROCESS_STATUS_NOTRUNNING
;
4162 log_warn(LD_GENERAL
, "Failed to read from port forwarding helper");
4163 child_handle
->status
= PROCESS_STATUS_ERROR
;
4166 /* TODO: The child might not actually be finished (maybe it failed or
4167 closed stdout/stderr), so maybe we shouldn't start another? */