1 /* Copyright 2003 Roger Dingledine
2 * Copyright 2004-2007 Roger Dingledine, Nick Mathewson */
3 /* See LICENSE for licensing information */
5 const char util_c_id
[] = "$Id$";
9 * \brief Common functions for strings, IO, network, data structures,
13 /* This is required on rh7 to make strptime not complain.
22 #include "container.h"
41 #ifdef HAVE_NETINET_IN_H
42 #include <netinet/in.h>
44 #ifdef HAVE_ARPA_INET_H
45 #include <arpa/inet.h>
50 #ifdef HAVE_SYS_SOCKET_H
51 #include <sys/socket.h>
53 #ifdef HAVE_SYS_TIME_H
59 #ifdef HAVE_SYS_STAT_H
62 #ifdef HAVE_SYS_FCNTL_H
63 #include <sys/fcntl.h>
84 #define DMALLOC_FN_ARGS , file, line
86 #define dmalloc_strdup(file, line, string, xalloc_b) strdup(string)
88 #define dmalloc_malloc(file, line, size, func_id, alignment, xalloc_b) \
90 #define DMALLOC_FUNC_MALLOC 0
92 #define dmalloc_realloc(file, line, old_pnt, new_size, func_id, xalloc_b) \
93 realloc((old_pnt), (new_size))
94 #define DMALLOC_FUNC_REALLOC 0
95 #define DMALLOC_FN_ARGS
98 /** Allocate a chunk of <b>size</b> bytes of memory, and return a pointer to
99 * result. On error, log and terminate the process. (Same as malloc(size),
100 * but never returns NULL.)
102 * <b>file</b> and <b>line</b> are used if dmalloc is enabled, and
106 _tor_malloc(size_t size DMALLOC_PARAMS
)
110 #ifndef MALLOC_ZERO_WORKS
111 /* Some libcs don't do the right thing on size==0. Override them. */
116 result
= dmalloc_malloc(file
, line
, size
, DMALLOC_FUNC_MALLOC
, 0, 0);
118 if (PREDICT(result
== NULL
, 0)) {
119 log_err(LD_MM
,"Out of memory on malloc(). Dying.");
120 /* If these functions die within a worker process, they won't call
121 * spawn_exit, but that's ok, since the parent will run out of memory soon
128 /** Allocate a chunk of <b>size</b> bytes of memory, fill the memory with
129 * zero bytes, and return a pointer to the result. Log and terminate
130 * the process on error. (Same as calloc(size,1), but never returns NULL.)
133 _tor_malloc_zero(size_t size DMALLOC_PARAMS
)
135 void *result
= _tor_malloc(size DMALLOC_FN_ARGS
);
136 memset(result
, 0, size
);
140 /** Change the size of the memory block pointed to by <b>ptr</b> to <b>size</b>
141 * bytes long; return the new memory block. On error, log and
142 * terminate. (Like realloc(ptr,size), but never returns NULL.)
145 _tor_realloc(void *ptr
, size_t size DMALLOC_PARAMS
)
149 result
= dmalloc_realloc(file
, line
, ptr
, size
, DMALLOC_FUNC_REALLOC
, 0);
150 if (PREDICT(result
== NULL
, 0)) {
151 log_err(LD_MM
,"Out of memory on realloc(). Dying.");
157 /** Return a newly allocated copy of the NUL-terminated string s. On
158 * error, log and terminate. (Like strdup(s), but never returns
162 _tor_strdup(const char *s DMALLOC_PARAMS
)
167 dup
= dmalloc_strdup(file
, line
, s
, 0);
168 if (PREDICT(dup
== NULL
, 0)) {
169 log_err(LD_MM
,"Out of memory on strdup(). Dying.");
175 /** Allocate and return a new string containing the first <b>n</b>
176 * characters of <b>s</b>. If <b>s</b> is longer than <b>n</b>
177 * characters, only the first <b>n</b> are copied. The result is
178 * always NUL-terminated. (Like strndup(s,n), but never returns
182 _tor_strndup(const char *s
, size_t n DMALLOC_PARAMS
)
186 dup
= _tor_malloc((n
+1) DMALLOC_FN_ARGS
);
187 /* Performance note: Ordinarily we prefer strlcpy to strncpy. But
188 * this function gets called a whole lot, and platform strncpy is
189 * much faster than strlcpy when strlen(s) is much longer than n.
196 /** Allocate a chunk of <b>len</b> bytes, with the same contents starting at
199 _tor_memdup(const void *mem
, size_t len DMALLOC_PARAMS
)
203 dup
= _tor_malloc(len DMALLOC_FN_ARGS
);
204 memcpy(dup
, mem
, len
);
208 /** Helper for places that need to take a function pointer to the right
209 * spelling of "free()". */
217 * String manipulation
220 /** Remove from the string <b>s</b> every character which appears in
221 * <b>strip</b>. Return the number of characters removed. */
223 tor_strstrip(char *s
, const char *strip
)
227 if (strchr(strip
, *read
)) {
237 /** Set the <b>dest_len</b>-byte buffer <b>buf</b> to contain the
238 * string <b>s</b>, with the string <b>insert</b> inserted after every
239 * <b>n</b> characters. Return 0 on success, -1 on failure.
241 * Never end the string with <b>insert</b>, even if its length <i>is</i> a
242 * multiple of <b>n</b>.
245 tor_strpartition(char *dest
, size_t dest_len
,
246 const char *s
, const char *insert
, size_t n
)
249 size_t len_in
, len_out
, len_ins
;
250 int is_even
, remaining
;
254 tor_assert(n
< SIZE_T_CEILING
);
255 tor_assert(dest_len
< SIZE_T_CEILING
);
257 len_ins
= strlen(insert
);
258 tor_assert(len_in
< SIZE_T_CEILING
);
259 tor_assert(len_in
/n
< SIZE_T_CEILING
/len_ins
); /* avoid overflow */
260 len_out
= len_in
+ (len_in
/n
)*len_ins
;
261 is_even
= (len_in
%n
) == 0;
262 if (is_even
&& len_in
)
264 if (dest_len
< len_out
+1)
269 strncpy(destp
, s
, n
);
273 } else if (remaining
== 0) {
277 strncpy(destp
+n
, insert
, len_ins
+1);
281 tor_assert(len_out
== strlen(dest
));
285 /** Return a pointer to a NUL-terminated hexadecimal string encoding
286 * the first <b>fromlen</b> bytes of <b>from</b>. (fromlen must be \<= 32.) The
287 * result does not need to be deallocated, but repeated calls to
288 * hex_str will trash old results.
291 hex_str(const char *from
, size_t fromlen
)
294 if (fromlen
>(sizeof(buf
)-1)/2)
295 fromlen
= (sizeof(buf
)-1)/2;
296 base16_encode(buf
,sizeof(buf
),from
,fromlen
);
300 /** Convert all alphabetic characters in the nul-terminated string <b>s</b> to
303 tor_strlower(char *s
)
306 *s
= TOR_TOLOWER(*s
);
311 /** Convert all alphabetic characters in the nul-terminated string <b>s</b> to
314 tor_strupper(char *s
)
317 *s
= TOR_TOUPPER(*s
);
322 /** Return 1 if every character in <b>s</b> is printable, else return 0.
325 tor_strisprint(const char *s
)
328 if (!TOR_ISPRINT(*s
))
335 /** Return 1 if no character in <b>s</b> is uppercase, else return 0.
338 tor_strisnonupper(const char *s
)
348 /** Compares the first strlen(s2) characters of s1 with s2. Returns as for
352 strcmpstart(const char *s1
, const char *s2
)
354 size_t n
= strlen(s2
);
355 return strncmp(s1
, s2
, n
);
358 /** Compares the first strlen(s2) characters of s1 with s2. Returns as for
362 strcasecmpstart(const char *s1
, const char *s2
)
364 size_t n
= strlen(s2
);
365 return strncasecmp(s1
, s2
, n
);
368 /** Compares the last strlen(s2) characters of s1 with s2. Returns as for
372 strcmpend(const char *s1
, const char *s2
)
374 size_t n1
= strlen(s1
), n2
= strlen(s2
);
376 return strcmp(s1
,s2
);
378 return strncmp(s1
+(n1
-n2
), s2
, n2
);
381 /** Compares the last strlen(s2) characters of s1 with s2. Returns as for
385 strcasecmpend(const char *s1
, const char *s2
)
387 size_t n1
= strlen(s1
), n2
= strlen(s2
);
388 if (n2
>n1
) /* then they can't be the same; figure out which is bigger */
389 return strcasecmp(s1
,s2
);
391 return strncasecmp(s1
+(n1
-n2
), s2
, n2
);
394 /** Return a pointer to the first char of s that is not whitespace and
395 * not a comment, or to the terminating NUL if no such character exists.
398 eat_whitespace(const char *s
)
415 while (*s
&& *s
!= '\n')
421 /** Return a pointer to the first char of s that is not a space or a tab,
422 * or to the terminating NUL if no such character exists. */
424 eat_whitespace_no_nl(const char *s
)
426 while (*s
== ' ' || *s
== '\t')
431 /** Return a pointer to the first char of s that is whitespace or <b>#</b>,
432 * or to the terminating NUL if no such character exists.
435 find_whitespace(const char *s
)
454 /** Return true iff the 'len' bytes at 'mem' are all zero. */
456 tor_mem_is_zero(const char *mem
, size_t len
)
458 static const char ZERO
[] = {
459 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,
461 while (len
>= sizeof(ZERO
)) {
462 if (memcmp(mem
, ZERO
, sizeof(ZERO
)))
467 /* Deal with leftover bytes. */
469 return ! memcmp(mem
, ZERO
, len
);
474 /** Return true iff the DIGEST_LEN bytes in digest are all zero. */
476 tor_digest_is_zero(const char *digest
)
478 return tor_mem_is_zero(digest
, DIGEST_LEN
);
481 /* Helper: common code to check whether the result of a strtol or strtoul or
482 * strtoll is correct. */
483 #define CHECK_STRTOX_RESULT() \
484 /* Was at least one character converted? */ \
487 /* Were there unexpected unconverted characters? */ \
488 if (!next && *endptr) \
490 /* Is r within limits? */ \
491 if (r < min || r > max) \
494 if (next) *next = endptr; \
498 if (next) *next = endptr; \
501 /** Extract a long from the start of s, in the given numeric base. If
502 * there is unconverted data and next is provided, set *next to the
503 * first unconverted character. An error has occurred if no characters
504 * are converted; or if there are unconverted characters and next is NULL; or
505 * if the parsed value is not between min and max. When no error occurs,
506 * return the parsed value and set *ok (if provided) to 1. When an error
507 * occurs, return 0 and set *ok (if provided) to 0.
510 tor_parse_long(const char *s
, int base
, long min
, long max
,
511 int *ok
, char **next
)
516 r
= strtol(s
, &endptr
, base
);
517 CHECK_STRTOX_RESULT();
520 /** As tor_parse_log, but return an unsigned long. */
522 tor_parse_ulong(const char *s
, int base
, unsigned long min
,
523 unsigned long max
, int *ok
, char **next
)
528 r
= strtoul(s
, &endptr
, base
);
529 CHECK_STRTOX_RESULT();
532 /** As tor_parse_log, but return a unit64_t. Only base 10 is guaranteed to
535 tor_parse_uint64(const char *s
, int base
, uint64_t min
,
536 uint64_t max
, int *ok
, char **next
)
542 r
= (uint64_t)strtoull(s
, &endptr
, base
);
543 #elif defined(MS_WINDOWS)
544 #if defined(_MSC_VER) && _MSC_VER < 1300
545 tor_assert(base
<= 10);
546 r
= (uint64_t)_atoi64(s
);
548 while (TOR_ISSPACE(*endptr
)) endptr
++;
549 while (TOR_ISDIGIT(*endptr
)) endptr
++;
551 r
= (uint64_t)_strtoui64(s
, &endptr
, base
);
553 #elif SIZEOF_LONG == 8
554 r
= (uint64_t)strtoul(s
, &endptr
, base
);
556 #error "I don't know how to parse 64-bit numbers."
559 CHECK_STRTOX_RESULT();
562 /** Encode the <b>srclen</b> bytes at <b>src</b> in a NUL-terminated,
563 * uppercase hexadecimal string; store it in the <b>destlen</b>-byte buffer
567 base16_encode(char *dest
, size_t destlen
, const char *src
, size_t srclen
)
572 tor_assert(destlen
>= srclen
*2+1);
573 tor_assert(destlen
< SIZE_T_CEILING
);
578 *cp
++ = "0123456789ABCDEF"[ (*(const uint8_t*)src
) >> 4 ];
579 *cp
++ = "0123456789ABCDEF"[ (*(const uint8_t*)src
) & 0xf ];
585 /** Helper: given a hex digit, return its value, or -1 if it isn't hex. */
587 hex_decode_digit(char c
)
600 case 'A': case 'a': return 10;
601 case 'B': case 'b': return 11;
602 case 'C': case 'c': return 12;
603 case 'D': case 'd': return 13;
604 case 'E': case 'e': return 14;
605 case 'F': case 'f': return 15;
611 /** Given a hexadecimal string of <b>srclen</b> bytes in <b>src</b>, decode it
612 * and store the result in the <b>destlen</b>-byte buffer at <b>dest</b>.
613 * Return 0 on success, -1 on failure. */
615 base16_decode(char *dest
, size_t destlen
, const char *src
, size_t srclen
)
619 if ((srclen
% 2) != 0)
621 if (destlen
< srclen
/2 || destlen
> SIZE_T_CEILING
)
625 v1
= hex_decode_digit(*src
);
626 v2
= hex_decode_digit(*(src
+1));
629 *(uint8_t*)dest
= (v1
<<4)|v2
;
636 /** Allocate and return a new string representing the contents of <b>s</b>,
637 * surrounded by quotes and using standard C escapes.
639 * Generally, we use this for logging values that come in over the network to
640 * keep them from tricking users, and for sending certain values to the
643 * We trust values from the resolver, OS, configuration file, and command line
644 * to not be maliciously ill-formed. We validate incoming routerdescs and
645 * SOCKS requests and addresses from BEGIN cells as they're parsed;
646 * afterwards, we trust them as non-malicious.
649 esc_for_log(const char *s
)
655 return tor_strdup("");
658 for (cp
= s
; *cp
; ++cp
) {
666 if (TOR_ISPRINT(*cp
) && ((uint8_t)*cp
)<127)
674 result
= outp
= tor_malloc(len
);
676 for (cp
= s
; *cp
; ++cp
) {
697 if (TOR_ISPRINT(*cp
) && ((uint8_t)*cp
)<127) {
700 tor_snprintf(outp
, 5, "\\%03o", (int)(uint8_t) *cp
);
713 /** Allocate and return a new string representing the contents of <b>s</b>,
714 * surrounded by quotes and using standard C escapes.
716 * THIS FUNCTION IS NOT REENTRANT. Don't call it from outside the main
717 * thread. Also, each call invalidates the last-returned value, so don't
718 * try log_warn(LD_GENERAL, "%s %s", escaped(a), escaped(b));
721 escaped(const char *s
)
723 static char *_escaped_val
= NULL
;
725 tor_free(_escaped_val
);
728 _escaped_val
= esc_for_log(s
);
735 /** Rudimentary string wrapping code: given a un-wrapped <b>string</b> (no
736 * newlines!), break the string into newline-terminated lines of no more than
737 * <b>width</b> characters long (not counting newline) and insert them into
738 * <b>out</b> in order. Precede the first line with prefix0, and subsequent
739 * lines with prefixRest.
741 /* This uses a stupid greedy wrapping algorithm right now:
743 * - Try to fit as much stuff as possible, but break on a space.
744 * - If the first "word" of the line will extend beyond the allowable
745 * width, break the word at the end of the width.
748 wrap_string(smartlist_t
*out
, const char *string
, size_t width
,
749 const char *prefix0
, const char *prefixRest
)
751 size_t p0Len
, pRestLen
, pCurLen
;
752 const char *eos
, *prefixCur
;
761 p0Len
= strlen(prefix0
);
762 pRestLen
= strlen(prefixRest
);
763 tor_assert(width
> p0Len
&& width
> pRestLen
);
764 eos
= strchr(string
, '\0');
769 while ((eos
-string
)+pCurLen
> width
) {
770 const char *eol
= string
+ width
- pCurLen
;
771 while (eol
> string
&& *eol
!= ' ')
773 /* eol is now the last space that can fit, or the start of the string. */
775 size_t line_len
= (eol
-string
) + pCurLen
+ 2;
776 char *line
= tor_malloc(line_len
);
777 memcpy(line
, prefixCur
, pCurLen
);
778 memcpy(line
+pCurLen
, string
, eol
-string
);
779 line
[line_len
-2] = '\n';
780 line
[line_len
-1] = '\0';
781 smartlist_add(out
, line
);
784 size_t line_len
= width
+ 2;
785 char *line
= tor_malloc(line_len
);
786 memcpy(line
, prefixCur
, pCurLen
);
787 memcpy(line
+pCurLen
, string
, width
- pCurLen
);
788 line
[line_len
-2] = '\n';
789 line
[line_len
-1] = '\0';
790 smartlist_add(out
, line
);
791 string
+= width
-pCurLen
;
793 prefixCur
= prefixRest
;
798 size_t line_len
= (eos
-string
) + pCurLen
+ 2;
799 char *line
= tor_malloc(line_len
);
800 memcpy(line
, prefixCur
, pCurLen
);
801 memcpy(line
+pCurLen
, string
, eos
-string
);
802 line
[line_len
-2] = '\n';
803 line
[line_len
-1] = '\0';
804 smartlist_add(out
, line
);
812 /** Return the number of microseconds elapsed between *start and *end.
815 tv_udiff(struct timeval
*start
, struct timeval
*end
)
818 long secdiff
= end
->tv_sec
- start
->tv_sec
;
820 if (labs(secdiff
+1) > LONG_MAX
/1000000) {
821 log_warn(LD_GENERAL
, "comparing times too far apart.");
825 udiff
= secdiff
*1000000L + (end
->tv_usec
- start
->tv_usec
);
829 /** Return -1 if *a \< *b, 0 if *a==*b, and 1 if *a \> *b.
832 tv_cmp(struct timeval
*a
, struct timeval
*b
)
834 if (a
->tv_sec
> b
->tv_sec
)
836 if (a
->tv_sec
< b
->tv_sec
)
838 if (a
->tv_usec
> b
->tv_usec
)
840 if (a
->tv_usec
< b
->tv_usec
)
845 /** Increment *a by the number of seconds and microseconds in *b.
848 tv_add(struct timeval
*a
, struct timeval
*b
)
850 a
->tv_usec
+= b
->tv_usec
;
851 a
->tv_sec
+= b
->tv_sec
+ (a
->tv_usec
/ 1000000);
852 a
->tv_usec
%= 1000000;
855 /** Increment *a by <b>ms</b> milliseconds.
858 tv_addms(struct timeval
*a
, long ms
)
860 a
->tv_usec
+= (ms
* 1000) % 1000000;
861 a
->tv_sec
+= ((ms
* 1000) / 1000000) + (a
->tv_usec
/ 1000000);
862 a
->tv_usec
%= 1000000;
865 /** Yield true iff <b>y</b> is a leap-year. */
866 #define IS_LEAPYEAR(y) (!(y % 4) && ((y % 100) || !(y % 400)))
867 /** Helper: Return the number of leap-days between Jan 1, y1 and Jan 1, y2. */
869 n_leapdays(int y1
, int y2
)
873 return (y2
/4 - y1
/4) - (y2
/100 - y1
/100) + (y2
/400 - y1
/400);
875 /** Number of days per month in non-leap year; used by tor_timegm. */
876 static const int days_per_month
[] =
877 { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
879 /** Return a time_t given a struct tm. The result is given in GMT, and
880 * does not account for leap seconds.
883 tor_timegm(struct tm
*tm
)
885 /* This is a pretty ironclad timegm implementation, snarfed from Python2.2.
886 * It's way more brute-force than fiddling with tzset().
889 unsigned long year
, days
, hours
, minutes
;
891 year
= tm
->tm_year
+ 1900;
892 if (year
< 1970 || tm
->tm_mon
< 0 || tm
->tm_mon
> 11) {
893 log_warn(LD_BUG
, "Out-of-range argument to tor_timegm");
896 days
= 365 * (year
-1970) + n_leapdays(1970,year
);
897 for (i
= 0; i
< tm
->tm_mon
; ++i
)
898 days
+= days_per_month
[i
];
899 if (tm
->tm_mon
> 1 && IS_LEAPYEAR(year
))
901 days
+= tm
->tm_mday
- 1;
902 hours
= days
*24 + tm
->tm_hour
;
904 minutes
= hours
*60 + tm
->tm_min
;
905 ret
= minutes
*60 + tm
->tm_sec
;
909 /* strftime is locale-specific, so we need to replace those parts */
910 static const char *WEEKDAY_NAMES
[] =
911 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
912 static const char *MONTH_NAMES
[] =
913 { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
914 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
916 /** Set <b>buf</b> to the RFC1123 encoding of the GMT value of <b>t</b>.
917 * The buffer must be at least RFC1123_TIME_LEN+1 bytes long.
919 * (RFC1123 format is Fri, 29 Sep 2006 15:54:20 GMT)
922 format_rfc1123_time(char *buf
, time_t t
)
926 tor_gmtime_r(&t
, &tm
);
928 strftime(buf
, RFC1123_TIME_LEN
+1, "___, %d ___ %Y %H:%M:%S GMT", &tm
);
929 tor_assert(tm
.tm_wday
>= 0);
930 tor_assert(tm
.tm_wday
<= 6);
931 memcpy(buf
, WEEKDAY_NAMES
[tm
.tm_wday
], 3);
932 tor_assert(tm
.tm_wday
>= 0);
933 tor_assert(tm
.tm_mon
<= 11);
934 memcpy(buf
+8, MONTH_NAMES
[tm
.tm_mon
], 3);
937 /** Parse the the RFC1123 encoding of some time (in GMT) from <b>buf</b>,
938 * and store the result in *<b>t</b>.
940 * Return 0 on succcess, -1 on failure.
943 parse_rfc1123_time(const char *buf
, time_t *t
)
950 if (strlen(buf
) != RFC1123_TIME_LEN
)
952 memset(&tm
, 0, sizeof(tm
));
953 if (sscanf(buf
, "%3s, %d %3s %d %d:%d:%d GMT", weekday
,
954 &tm
.tm_mday
, month
, &tm
.tm_year
, &tm
.tm_hour
,
955 &tm
.tm_min
, &tm
.tm_sec
) < 7) {
956 char *esc
= esc_for_log(buf
);
957 log_warn(LD_GENERAL
, "Got invalid RFC1123 time %s", esc
);
963 for (i
= 0; i
< 12; ++i
) {
964 if (!strcmp(month
, MONTH_NAMES
[i
])) {
970 char *esc
= esc_for_log(buf
);
971 log_warn(LD_GENERAL
, "Got invalid RFC1123 time %s: No such month", esc
);
977 if (tm
.tm_year
< 1970) {
978 char *esc
= esc_for_log(buf
);
980 "Got invalid RFC1123 time %s. (Before 1970)", esc
);
986 *t
= tor_timegm(&tm
);
990 /** Set <b>buf</b> to the ISO8601 encoding of the local value of <b>t</b>.
991 * The buffer must be at least ISO_TIME_LEN+1 bytes long.
993 * (ISO8601 format is 2006-10-29 10:57:20)
996 format_local_iso_time(char *buf
, time_t t
)
999 strftime(buf
, ISO_TIME_LEN
+1, "%Y-%m-%d %H:%M:%S", tor_localtime_r(&t
, &tm
));
1002 /** Set <b>buf</b> to the ISO8601 encoding of the GMT value of <b>t</b>.
1003 * The buffer must be at least ISO_TIME_LEN+1 bytes long.
1006 format_iso_time(char *buf
, time_t t
)
1009 strftime(buf
, ISO_TIME_LEN
+1, "%Y-%m-%d %H:%M:%S", tor_gmtime_r(&t
, &tm
));
1012 /** Given an ISO-formatted UTC time value (after the epoch) in <b>cp</b>,
1013 * parse it and store its value in *<b>t</b>. Return 0 on success, -1 on
1014 * failure. Ignore extraneous stuff in <b>cp</b> separated by whitespace from
1015 * the end of the time string. */
1017 parse_iso_time(const char *cp
, time_t *t
)
1020 #ifdef HAVE_STRPTIME
1021 if (!strptime(cp
, "%Y-%m-%d %H:%M:%S", &st_tm
)) {
1022 log_warn(LD_GENERAL
, "ISO time was unparseable by strptime"); return -1;
1025 unsigned int year
=0, month
=0, day
=0, hour
=100, minute
=100, second
=100;
1026 if (sscanf(cp
, "%u-%u-%u %u:%u:%u", &year
, &month
,
1027 &day
, &hour
, &minute
, &second
) < 6) {
1028 log_warn(LD_GENERAL
, "ISO time was unparseable"); return -1;
1030 if (year
< 1970 || month
< 1 || month
> 12 || day
< 1 || day
> 31 ||
1031 hour
> 23 || minute
> 59 || second
> 61) {
1032 log_warn(LD_GENERAL
, "ISO time was nonsensical"); return -1;
1034 st_tm
.tm_year
= year
-1900;
1035 st_tm
.tm_mon
= month
-1;
1036 st_tm
.tm_mday
= day
;
1037 st_tm
.tm_hour
= hour
;
1038 st_tm
.tm_min
= minute
;
1039 st_tm
.tm_sec
= second
;
1041 if (st_tm
.tm_year
< 70) {
1042 char *esc
= esc_for_log(cp
);
1043 log_warn(LD_GENERAL
, "Got invalid ISO time %s. (Before 1970)", esc
);
1047 *t
= tor_timegm(&st_tm
);
1055 /** Write <b>count</b> bytes from <b>buf</b> to <b>fd</b>. <b>isSocket</b>
1056 * must be 1 if fd was returned by socket() or accept(), and 0 if fd
1057 * was returned by open(). Return the number of bytes written, or -1
1058 * on error. Only use if fd is a blocking fd. */
1060 write_all(int fd
, const char *buf
, size_t count
, int isSocket
)
1065 while (written
!= count
) {
1067 result
= tor_socket_send(fd
, buf
+written
, count
-written
, 0);
1069 result
= write(fd
, buf
+written
, count
-written
);
1077 /** Read from <b>fd</b> to <b>buf</b>, until we get <b>count</b> bytes
1078 * or reach the end of the file. <b>isSocket</b> must be 1 if fd
1079 * was returned by socket() or accept(), and 0 if fd was returned by
1080 * open(). Return the number of bytes read, or -1 on error. Only use
1081 * if fd is a blocking fd. */
1083 read_all(int fd
, char *buf
, size_t count
, int isSocket
)
1088 if (count
> SIZE_T_CEILING
)
1091 while (numread
!= count
) {
1093 result
= tor_socket_recv(fd
, buf
+numread
, count
-numread
, 0);
1095 result
= read(fd
, buf
+numread
, count
-numread
);
1098 else if (result
== 0)
1106 * Filesystem operations.
1109 /** Clean up <b>name</b> so that we can use it in a call to "stat". On Unix,
1110 * we do nothing. On Windows, we remove a trailing slash, unless the path is
1111 * the root of a disk. */
1113 clean_name_for_stat(char *name
)
1116 size_t len
= strlen(name
);
1119 if (name
[len
-1]=='\\' || name
[len
-1]=='/') {
1120 if (len
== 1 || (len
==3 && name
[1]==':'))
1129 /** Return FN_ERROR if filename can't be read, FN_NOENT if it doesn't
1130 * exist, FN_FILE if it is a regular file, or FN_DIR if it's a
1133 file_status(const char *fname
)
1138 f
= tor_strdup(fname
);
1139 clean_name_for_stat(f
);
1143 if (errno
== ENOENT
) {
1148 if (st
.st_mode
& S_IFDIR
)
1150 else if (st
.st_mode
& S_IFREG
)
1156 /** Check whether dirname exists and is private. If yes return 0. If
1157 * it does not exist, and check==CPD_CREATE is set, try to create it
1158 * and return 0 on success. If it does not exist, and
1159 * check==CPD_CHECK, and we think we can create it, return 0. Else
1162 check_private_dir(const char *dirname
, cpd_check_t check
)
1167 tor_assert(dirname
);
1168 f
= tor_strdup(dirname
);
1169 clean_name_for_stat(f
);
1173 if (errno
!= ENOENT
) {
1174 log(LOG_WARN
, LD_FS
, "Directory %s cannot be read: %s", dirname
,
1178 if (check
== CPD_NONE
) {
1179 log(LOG_WARN
, LD_FS
, "Directory %s does not exist.", dirname
);
1181 } else if (check
== CPD_CREATE
) {
1182 log_info(LD_GENERAL
, "Creating directory %s", dirname
);
1186 r
= mkdir(dirname
, 0700);
1189 log(LOG_WARN
, LD_FS
, "Error creating directory %s: %s", dirname
,
1194 /* XXXX In the case where check==CPD_CHECK, we should look at the
1195 * parent directory a little harder. */
1198 if (!(st
.st_mode
& S_IFDIR
)) {
1199 log(LOG_WARN
, LD_FS
, "%s is not a directory", dirname
);
1203 if (st
.st_uid
!= getuid()) {
1204 struct passwd
*pw
= NULL
;
1205 char *process_ownername
= NULL
;
1207 pw
= getpwuid(getuid());
1208 process_ownername
= pw
? tor_strdup(pw
->pw_name
) : tor_strdup("<unknown>");
1210 pw
= getpwuid(st
.st_uid
);
1212 log(LOG_WARN
, LD_FS
, "%s is not owned by this user (%s, %d) but by "
1213 "%s (%d). Perhaps you are running Tor as the wrong user?",
1214 dirname
, process_ownername
, (int)getuid(),
1215 pw
? pw
->pw_name
: "<unknown>", (int)st
.st_uid
);
1217 tor_free(process_ownername
);
1220 if (st
.st_mode
& 0077) {
1221 log(LOG_WARN
, LD_FS
, "Fixing permissions on directory %s", dirname
);
1222 if (chmod(dirname
, 0700)) {
1223 log(LOG_WARN
, LD_FS
, "Could not chmod directory %s: %s", dirname
,
1234 /** Create a file named <b>fname</b> with the contents <b>str</b>. Overwrite
1235 * the previous <b>fname</b> if possible. Return 0 on success, -1 on failure.
1237 * This function replaces the old file atomically, if possible.
1240 write_str_to_file(const char *fname
, const char *str
, int bin
)
1243 if (!bin
&& strchr(str
, '\r')) {
1245 "Bug: we're writing a text string that already contains a CR.");
1248 return write_bytes_to_file(fname
, str
, strlen(str
), bin
);
1251 /** Helper: given a set of flags as passed to open(2), open the file
1252 * <b>fname</b> and write all the sized_chunk_t structs in <b>chunks</b> to
1253 * the file. Do so as atomically as possible e.g. by opening temp files and
1256 write_chunks_to_file_impl(const char *fname
, const smartlist_t
*chunks
,
1259 size_t tempname_len
;
1263 tempname_len
= strlen(fname
)+16;
1264 tor_assert(tempname_len
> strlen(fname
)); /*check for overflow*/
1265 tempname
= tor_malloc(tempname_len
);
1266 if (open_flags
& O_APPEND
) {
1267 strlcpy(tempname
, fname
, tempname_len
);
1269 if (tor_snprintf(tempname
, tempname_len
, "%s.tmp", fname
)<0) {
1270 log(LOG_WARN
, LD_GENERAL
, "Failed to generate filename");
1274 if ((fd
= open(tempname
, open_flags
, 0600))
1276 log(LOG_WARN
, LD_FS
, "Couldn't open \"%s\" for writing: %s", tempname
,
1280 SMARTLIST_FOREACH(chunks
, sized_chunk_t
*, chunk
,
1282 result
= write_all(fd
, chunk
->bytes
, chunk
->len
, 0);
1283 if (result
< 0 || (size_t)result
!= chunk
->len
) {
1284 log(LOG_WARN
, LD_FS
, "Error writing to \"%s\": %s", tempname
,
1291 log(LOG_WARN
, LD_FS
, "Error flushing to \"%s\": %s", tempname
,
1295 if (!(open_flags
& O_APPEND
)) {
1296 if (replace_file(tempname
, fname
)) {
1297 log(LOG_WARN
, LD_FS
, "Error replacing \"%s\": %s", fname
,
1309 /** Given a smartlist of sized_chunk_t, write them atomically to a file
1310 * <b>fname</b>, overwriting or creating the file as necessary. */
1312 write_chunks_to_file(const char *fname
, const smartlist_t
*chunks
, int bin
)
1314 int flags
= O_WRONLY
|O_CREAT
|O_TRUNC
|(bin
?O_BINARY
:O_TEXT
);
1315 return write_chunks_to_file_impl(fname
, chunks
, flags
);
1318 /** As write_str_to_file, but does not assume a NUL-terminated
1319 * string. Instead, we write <b>len</b> bytes, starting at <b>str</b>. */
1321 write_bytes_to_file(const char *fname
, const char *str
, size_t len
,
1324 int flags
= O_WRONLY
|O_CREAT
|O_TRUNC
|(bin
?O_BINARY
:O_TEXT
);
1326 sized_chunk_t c
= { str
, len
};
1327 smartlist_t
*chunks
= smartlist_create();
1328 smartlist_add(chunks
, &c
);
1329 r
= write_chunks_to_file_impl(fname
, chunks
, flags
);
1330 smartlist_free(chunks
);
1334 /** As write_bytes_to_file, but if the file already exists, append the bytes
1335 * to the end of the file instead of overwriting it. */
1337 append_bytes_to_file(const char *fname
, const char *str
, size_t len
,
1340 int flags
= O_WRONLY
|O_CREAT
|O_APPEND
|(bin
?O_BINARY
:O_TEXT
);
1342 sized_chunk_t c
= { str
, len
};
1343 smartlist_t
*chunks
= smartlist_create();
1344 smartlist_add(chunks
, &c
);
1345 r
= write_chunks_to_file_impl(fname
, chunks
, flags
);
1346 smartlist_free(chunks
);
1350 /** Read the contents of <b>filename</b> into a newly allocated
1351 * string; return the string on success or NULL on failure.
1353 * If <b>size_out</b> is provided, store the length of the result in
1356 * If <b>flags</b> & RFTS_BIN, open the file in binary mode.
1357 * If <b>flags</b> & RFTS_IGNORE_MISSING, don't warn if the file
1361 * This function <em>may</em> return an erroneous result if the file
1362 * is modified while it is running, but must not crash or overflow.
1363 * Right now, the error case occurs when the file length grows between
1364 * the call to stat and the call to read_all: the resulting string will
1368 read_file_to_str(const char *filename
, int flags
, struct stat
*stat_out
)
1370 int fd
; /* router file */
1371 struct stat statbuf
;
1374 int bin
= flags
& RFTS_BIN
;
1376 tor_assert(filename
);
1378 fd
= open(filename
,O_RDONLY
|(bin
?O_BINARY
:O_TEXT
),0);
1380 int severity
= LOG_WARN
;
1381 if (errno
== ENOENT
&& (flags
& RFTS_IGNORE_MISSING
))
1382 severity
= LOG_INFO
;
1383 log_fn(severity
, LD_FS
,"Could not open \"%s\": %s ",filename
,
1388 if (fstat(fd
, &statbuf
)<0) {
1390 log_warn(LD_FS
,"Could not fstat \"%s\".",filename
);
1394 if ((uint64_t)(statbuf
.st_size
)+1 > SIZE_T_MAX
)
1397 string
= tor_malloc((size_t)(statbuf
.st_size
+1));
1399 r
= read_all(fd
,string
,(size_t)statbuf
.st_size
,0);
1401 log_warn(LD_FS
,"Error reading from file \"%s\": %s", filename
,
1407 string
[r
] = '\0'; /* NUL-terminate the result. */
1410 if (!bin
&& strchr(string
, '\r')) {
1411 log_debug(LD_FS
, "We didn't convert CRLF to LF as well as we hoped "
1412 "when reading %s. Coping.",
1414 tor_strstrip(string
, "\r");
1418 statbuf
.st_size
= (size_t) r
;
1421 if (r
!= statbuf
.st_size
) {
1422 /* Unless we're using text mode on win32, we'd better have an exact
1423 * match for size. */
1424 log_warn(LD_FS
,"Could read only %d of %ld bytes of file \"%s\".",
1425 r
, (long)statbuf
.st_size
,filename
);
1432 memcpy(stat_out
, &statbuf
, sizeof(struct stat
));
1438 /** Given a string containing part of a configuration file or similar format,
1439 * advance past comments and whitespace and try to parse a single line. If we
1440 * parse a line successfully, set *<b>key_out</b> to the key portion and
1441 * *<b>value_out</b> to the value portion of the line, and return a pointer to
1442 * the start of the next line. If we run out of data, return a pointer to the
1443 * end of the string. If we encounter an error, return NULL.
1445 * NOTE: We modify <b>line</b> as we parse it, by inserting NULs to terminate
1446 * the key and value.
1449 parse_line_from_str(char *line
, char **key_out
, char **value_out
)
1451 char *key
, *val
, *cp
;
1453 tor_assert(key_out
);
1454 tor_assert(value_out
);
1456 *key_out
= *value_out
= key
= val
= NULL
;
1457 /* Skip until the first keyword. */
1459 while (TOR_ISSPACE(*line
))
1462 while (*line
&& *line
!= '\n')
1469 if (!*line
) { /* End of string? */
1470 *key_out
= *value_out
= NULL
;
1474 /* Skip until the next space. */
1476 while (*line
&& !TOR_ISSPACE(*line
) && *line
!= '#')
1479 /* Skip until the value */
1480 while (*line
== ' ' || *line
== '\t')
1484 /* Find the end of the line. */
1485 while (*line
&& *line
!= '\n' && *line
!= '#')
1492 while (cp
>=val
&& TOR_ISSPACE(*cp
))
1498 } while (*line
&& *line
!= '\n');
1509 /** Expand any homedir prefix on 'filename'; return a newly allocated
1512 expand_filename(const char *filename
)
1514 tor_assert(filename
);
1515 if (*filename
== '~') {
1517 char *home
, *result
;
1520 if (filename
[1] == '/' || filename
[1] == '\0') {
1521 home
= getenv("HOME");
1523 log_warn(LD_CONFIG
, "Couldn't find $HOME environment variable while "
1524 "expanding \"%s\"", filename
);
1527 home
= tor_strdup(home
);
1528 rest
= strlen(filename
)>=2?(filename
+2):NULL
;
1531 char *username
, *slash
;
1532 slash
= strchr(filename
, '/');
1534 username
= tor_strndup(filename
+1,slash
-filename
-1);
1536 username
= tor_strdup(filename
+1);
1537 if (!(home
= get_user_homedir(username
))) {
1538 log_warn(LD_CONFIG
,"Couldn't get homedir for \"%s\"",username
);
1543 rest
= slash
? (slash
+1) : NULL
;
1545 log_warn(LD_CONFIG
, "Couldn't expend homedir on system without pwd.h");
1546 return tor_strdup(filename
);
1550 /* Remove trailing slash. */
1551 if (strlen(home
)>1 && !strcmpend(home
,"/")) {
1552 home
[strlen(home
)-1] = '\0';
1554 /* Plus one for /, plus one for NUL.
1555 * Round up to 16 in case we can't do math. */
1556 len
= strlen(home
)+strlen(rest
)+16;
1557 result
= tor_malloc(len
);
1558 tor_snprintf(result
,len
,"%s/%s",home
,rest
?rest
:"");
1562 return tor_strdup(filename
);
1566 /** Return a new list containing the filenames in the directory <b>dirname</b>.
1567 * Return NULL on error or if <b>dirname</b> is not a directory.
1570 tor_listdir(const char *dirname
)
1572 smartlist_t
*result
;
1576 WIN32_FIND_DATA findData
;
1577 size_t pattern_len
= strlen(dirname
)+16;
1578 pattern
= tor_malloc(pattern_len
);
1579 tor_snprintf(pattern
, pattern_len
, "%s\\*", dirname
);
1580 if (!(handle
= FindFirstFile(pattern
, &findData
))) {
1584 result
= smartlist_create();
1586 if (strcmp(findData
.cFileName
, ".") &&
1587 strcmp(findData
.cFileName
, "..")) {
1588 smartlist_add(result
, tor_strdup(findData
.cFileName
));
1590 if (!FindNextFile(handle
, &findData
)) {
1591 if (GetLastError() != ERROR_NO_MORE_FILES
) {
1592 log_warn(LD_FS
, "Error reading directory.");
1602 if (!(d
= opendir(dirname
)))
1605 result
= smartlist_create();
1606 while ((de
= readdir(d
))) {
1607 if (!strcmp(de
->d_name
, ".") ||
1608 !strcmp(de
->d_name
, ".."))
1610 smartlist_add(result
, tor_strdup(de
->d_name
));
1617 /** Return true iff <b>filename</b> is a relative path. */
1619 path_is_relative(const char *filename
)
1621 if (filename
&& filename
[0] == '/')
1624 else if (filename
&& filename
[0] == '\\')
1626 else if (filename
&& strlen(filename
)>3 && TOR_ISALPHA(filename
[0]) &&
1627 filename
[1] == ':' && filename
[2] == '\\')
1638 /** Return true iff <b>ip</b> (in host order) is an IP reserved to localhost,
1639 * or reserved for local networks by RFC 1918.
1642 is_internal_IP(uint32_t ip
, int for_listening
)
1644 if (for_listening
&& !ip
) /* special case for binding to 0.0.0.0 */
1646 if (((ip
& 0xff000000) == 0x0a000000) || /* 10/8 */
1647 ((ip
& 0xff000000) == 0x00000000) || /* 0/8 */
1648 ((ip
& 0xff000000) == 0x7f000000) || /* 127/8 */
1649 ((ip
& 0xffff0000) == 0xa9fe0000) || /* 169.254/16 */
1650 ((ip
& 0xfff00000) == 0xac100000) || /* 172.16/12 */
1651 ((ip
& 0xffff0000) == 0xc0a80000)) /* 192.168/16 */
1656 /** Parse a string of the form "host[:port]" from <b>addrport</b>. If
1657 * <b>address</b> is provided, set *<b>address</b> to a copy of the
1658 * host portion of the string. If <b>addr</b> is provided, try to
1659 * resolve the host portion of the string and store it into
1660 * *<b>addr</b> (in host byte order). If <b>port_out</b> is provided,
1661 * store the port number into *<b>port_out</b>, or 0 if no port is given.
1662 * If <b>port_out</b> is NULL, then there must be no port number in
1664 * Return 0 on success, -1 on failure.
1667 parse_addr_port(int severity
, const char *addrport
, char **address
,
1668 uint32_t *addr
, uint16_t *port_out
)
1671 char *_address
= NULL
;
1675 tor_assert(addrport
);
1677 colon
= strchr(addrport
, ':');
1679 _address
= tor_strndup(addrport
, colon
-addrport
);
1680 _port
= (int) tor_parse_long(colon
+1,10,1,65535,NULL
,NULL
);
1682 log_fn(severity
, LD_GENERAL
, "Port %s out of range", escaped(colon
+1));
1686 char *esc_addrport
= esc_for_log(addrport
);
1687 log_fn(severity
, LD_GENERAL
,
1688 "Port %s given on %s when not required",
1689 escaped(colon
+1), esc_addrport
);
1690 tor_free(esc_addrport
);
1694 _address
= tor_strdup(addrport
);
1699 /* There's an addr pointer, so we need to resolve the hostname. */
1700 if (tor_lookup_hostname(_address
,addr
)) {
1701 log_fn(severity
, LD_NET
, "Couldn't look up %s", escaped(_address
));
1705 *addr
= ntohl(*addr
);
1708 if (address
&& ok
) {
1709 *address
= _address
;
1716 *port_out
= ok
? ((uint16_t) _port
) : 0;
1721 /** If <b>mask</b> is an address mask for a bit-prefix, return the number of
1722 * bits. Otherwise, return -1. */
1724 addr_mask_get_bits(uint32_t mask
)
1729 if (mask
== 0xFFFFFFFFu
)
1731 for (i
=0; i
<=32; ++i
) {
1732 if (mask
== (uint32_t) ~((1u<<(32-i
))-1)) {
1739 /** Parse a string <b>s</b> in the format of (*|port(-maxport)?)?, setting the
1740 * various *out pointers as appropriate. Return 0 on success, -1 on failure.
1743 parse_port_range(const char *port
, uint16_t *port_min_out
,
1744 uint16_t *port_max_out
)
1746 int port_min
, port_max
, ok
;
1747 tor_assert(port_min_out
);
1748 tor_assert(port_max_out
);
1750 if (!port
|| *port
== '\0' || strcmp(port
, "*") == 0) {
1754 char *endptr
= NULL
;
1755 port_min
= tor_parse_long(port
, 10, 0, 65535, &ok
, &endptr
);
1757 log_warn(LD_GENERAL
,
1758 "Malformed port %s on address range; rejecting.",
1761 } else if (endptr
&& *endptr
== '-') {
1764 port_max
= tor_parse_long(port
, 10, 1, 65536, &ok
, &endptr
);
1766 log_warn(LD_GENERAL
,
1767 "Malformed port %s on address range; rejecting.",
1772 port_max
= port_min
;
1774 if (port_min
> port_max
) {
1775 log_warn(LD_GENERAL
, "Insane port range on address policy; rejecting.");
1782 if (port_max
> 65535)
1785 *port_min_out
= (uint16_t) port_min
;
1786 *port_max_out
= (uint16_t) port_max
;
1791 /** Parse a string <b>s</b> in the format of
1792 * (IP(/mask|/mask-bits)?|*)(:*|port(-maxport)?)?, setting the various
1793 * *out pointers as appropriate. Return 0 on success, -1 on failure.
1796 parse_addr_and_port_range(const char *s
, uint32_t *addr_out
,
1797 uint32_t *mask_out
, uint16_t *port_min_out
,
1798 uint16_t *port_max_out
)
1801 char *mask
, *port
, *endptr
;
1806 tor_assert(addr_out
);
1807 tor_assert(mask_out
);
1808 tor_assert(port_min_out
);
1809 tor_assert(port_max_out
);
1811 address
= tor_strdup(s
);
1812 /* Break 'address' into separate strings.
1814 mask
= strchr(address
,'/');
1815 port
= strchr(mask
?mask
:address
,':');
1820 /* Now "address" is the IP|'*' part...
1821 * "mask" is the Mask|Maskbits part...
1822 * and "port" is the *|port|min-max part.
1825 if (strcmp(address
,"*")==0) {
1827 } else if (tor_inet_aton(address
, &in
) != 0) {
1828 *addr_out
= ntohl(in
.s_addr
);
1830 log_warn(LD_GENERAL
, "Malformed IP %s in address pattern; rejecting.",
1836 if (strcmp(address
,"*")==0)
1839 *mask_out
= 0xFFFFFFFFu
;
1842 bits
= (int) strtol(mask
, &endptr
, 10);
1844 /* strtol handled the whole mask. */
1845 if (bits
< 0 || bits
> 32) {
1846 log_warn(LD_GENERAL
,
1847 "Bad number of mask bits on address range; rejecting.");
1850 *mask_out
= ~((1u<<(32-bits
))-1);
1851 } else if (tor_inet_aton(mask
, &in
) != 0) {
1852 *mask_out
= ntohl(in
.s_addr
);
1854 log_warn(LD_GENERAL
,
1855 "Malformed mask %s on address range; rejecting.",
1861 if (parse_port_range(port
, port_min_out
, port_max_out
)<0)
1871 /** Given an IPv4 address <b>in</b> (in network order, as usual),
1872 * write it as a string into the <b>buf_len</b>-byte buffer in
1876 tor_inet_ntoa(struct in_addr
*in
, char *buf
, size_t buf_len
)
1878 uint32_t a
= ntohl(in
->s_addr
);
1879 return tor_snprintf(buf
, buf_len
, "%d.%d.%d.%d",
1880 (int)(uint8_t)((a
>>24)&0xff),
1881 (int)(uint8_t)((a
>>16)&0xff),
1882 (int)(uint8_t)((a
>>8 )&0xff),
1883 (int)(uint8_t)((a
)&0xff));
1886 /** Given a host-order <b>addr</b>, call tor_inet_ntoa() on it
1887 * and return a strdup of the resulting address.
1890 tor_dup_addr(uint32_t addr
)
1892 char buf
[INET_NTOA_BUF_LEN
];
1895 in
.s_addr
= htonl(addr
);
1896 tor_inet_ntoa(&in
, buf
, sizeof(buf
));
1897 return tor_strdup(buf
);
1901 * Set *<b>addr</b> to the host-order IPv4 address (if any) of whatever
1902 * interface connects to the internet. This address should only be used in
1903 * checking whether our address has changed. Return 0 on success, -1 on
1907 get_interface_address(int severity
, uint32_t *addr
)
1910 struct sockaddr_in target_addr
, my_addr
;
1911 socklen_t my_addr_len
= sizeof(my_addr
);
1916 sock
= socket(PF_INET
,SOCK_DGRAM
,IPPROTO_UDP
);
1918 int e
= tor_socket_errno(-1);
1919 log_fn(severity
, LD_NET
, "unable to create socket: %s",
1920 tor_socket_strerror(e
));
1924 memset(&target_addr
, 0, sizeof(target_addr
));
1925 target_addr
.sin_family
= AF_INET
;
1927 target_addr
.sin_port
= 9;
1928 /* 18.0.0.1 (Don't worry: no packets are sent. We just need a real address
1929 * on the internet.) */
1930 target_addr
.sin_addr
.s_addr
= htonl(0x12000001);
1932 if (connect(sock
,(struct sockaddr
*)&target_addr
,sizeof(target_addr
))<0) {
1933 int e
= tor_socket_errno(sock
);
1934 log_fn(severity
, LD_NET
, "connect() failed: %s", tor_socket_strerror(e
));
1938 if (getsockname(sock
, (struct sockaddr
*)&my_addr
, &my_addr_len
)) {
1939 int e
= tor_socket_errno(sock
);
1940 log_fn(severity
, LD_NET
, "getsockname() to determine interface failed: %s",
1941 tor_socket_strerror(e
));
1945 *addr
= ntohl(my_addr
.sin_addr
.s_addr
);
1950 tor_close_socket(sock
);
1959 /* Based on code contributed by christian grothoff */
1960 /** True iff we've called start_daemon(). */
1961 static int start_daemon_called
= 0;
1962 /** True iff we've called finish_daemon(). */
1963 static int finish_daemon_called
= 0;
1964 /** Socketpair used to communicate between parent and child process while
1966 static int daemon_filedes
[2];
1967 /** Start putting the process into daemon mode: fork and drop all resources
1968 * except standard fds. The parent process never returns, but stays around
1969 * until finish_daemon is called. (Note: it's safe to call this more
1970 * than once: calls after the first are ignored.)
1977 if (start_daemon_called
)
1979 start_daemon_called
= 1;
1981 pipe(daemon_filedes
);
1984 log_err(LD_GENERAL
,"fork failed. Exiting.");
1987 if (pid
) { /* Parent */
1991 close(daemon_filedes
[1]); /* we only read */
1993 while (0 < read(daemon_filedes
[0], &c
, sizeof(char))) {
2001 exit(1); /* child reported error */
2002 } else { /* Child */
2003 close(daemon_filedes
[0]); /* we only write */
2005 pid
= setsid(); /* Detach from controlling terminal */
2007 * Fork one more time, so the parent (the session group leader) can exit.
2008 * This means that we, as a non-session group leader, can never regain a
2009 * controlling terminal. This part is recommended by Stevens's
2010 * _Advanced Programming in the Unix Environment_.
2019 /** Finish putting the process into daemon mode: drop standard fds, and tell
2020 * the parent process to exit. (Note: it's safe to call this more than once:
2021 * calls after the first are ignored. Calls start_daemon first if it hasn't
2022 * been called already.)
2025 finish_daemon(const char *desired_cwd
)
2029 if (finish_daemon_called
)
2031 if (!start_daemon_called
)
2033 finish_daemon_called
= 1;
2037 /* Don't hold the wrong FS mounted */
2038 if (chdir(desired_cwd
) < 0) {
2039 log_err(LD_GENERAL
,"chdir to \"%s\" failed. Exiting.",desired_cwd
);
2043 nullfd
= open("/dev/null",
2044 O_CREAT
| O_RDWR
| O_APPEND
);
2046 log_err(LD_GENERAL
,"/dev/null can't be opened. Exiting.");
2049 /* close fds linking to invoking terminal, but
2050 * close usual incoming fds, but redirect them somewhere
2051 * useful so the fds don't get reallocated elsewhere.
2053 if (dup2(nullfd
,0) < 0 ||
2054 dup2(nullfd
,1) < 0 ||
2055 dup2(nullfd
,2) < 0) {
2056 log_err(LD_GENERAL
,"dup2 failed. Exiting.");
2061 write(daemon_filedes
[1], &c
, sizeof(char)); /* signal success */
2062 close(daemon_filedes
[1]);
2065 /* defined(MS_WINDOWS) */
2071 finish_daemon(const char *cp
)
2077 /** Write the current process ID, followed by NL, into <b>filename</b>.
2080 write_pidfile(char *filename
)
2084 if ((pidfile
= fopen(filename
, "w")) == NULL
) {
2085 log_warn(LD_FS
, "Unable to open \"%s\" for writing: %s", filename
,
2089 fprintf(pidfile
, "%d\n", (int)_getpid());
2091 fprintf(pidfile
, "%d\n", (int)getpid());