Efficiency hack: call tor_fix_source_file late, not early. Add "BUG" domain. Domains...
[tor.git] / src / common / util.c
blobdd289ff258190eef3fcca0b51f579a38b2b24025
1 /* Copyright 2003 Roger Dingledine
2 * Copyright 2004-2005 Roger Dingledine, Nick Mathewson */
3 /* See LICENSE for licensing information */
4 /* $Id$ */
5 const char util_c_id[] = "$Id$";
7 /**
8 * \file util.c
9 * \brief Common functions for strings, IO, network, data structures,
10 * process control.
11 **/
13 /* This is required on rh7 to make strptime not complain.
15 #define _GNU_SOURCE
17 #include "orconfig.h"
18 #include "util.h"
19 #include "log.h"
20 #include "crypto.h"
21 #include "torint.h"
22 #include "container.h"
24 #ifdef MS_WINDOWS
25 #include <io.h>
26 #include <direct.h>
27 #else
28 #include <dirent.h>
29 #endif
31 #ifdef HAVE_CTYPE_H
32 #include <ctype.h>
33 #endif
34 #include <stdlib.h>
35 #include <stdio.h>
36 #include <string.h>
37 #include <assert.h>
39 #ifdef HAVE_NETINET_IN_H
40 #include <netinet/in.h>
41 #endif
42 #ifdef HAVE_ARPA_INET_H
43 #include <arpa/inet.h>
44 #endif
45 #ifdef HAVE_ERRNO_H
46 #include <errno.h>
47 #endif
48 #ifdef HAVE_LIMITS_H
49 #include <limits.h>
50 #endif
51 #ifdef HAVE_SYS_LIMITS_H
52 #include <sys/limits.h>
53 #endif
54 #ifdef HAVE_MACHINE_LIMITS_H
55 #ifndef __FreeBSD__
56 /* FreeBSD has a bug where it complains that this file is obsolete,
57 and I should migrate to using sys/limits. It complains even when
58 I include both. */
59 #include <machine/limits.h>
60 #endif
61 #endif
62 #ifdef HAVE_SYS_TYPES_H
63 #include <sys/types.h> /* Must be included before sys/stat.h for Ultrix */
64 #endif
65 #ifdef HAVE_SYS_SOCKET_H
66 #include <sys/socket.h>
67 #endif
68 #ifdef HAVE_SYS_TIME_H
69 #include <sys/time.h>
70 #endif
71 #ifdef HAVE_UNISTD_H
72 #include <unistd.h>
73 #endif
74 #ifdef HAVE_SYS_STAT_H
75 #include <sys/stat.h>
76 #endif
77 #ifdef HAVE_SYS_FCNTL_H
78 #include <sys/fcntl.h>
79 #endif
80 #ifdef HAVE_FCNTL_H
81 #include <fcntl.h>
82 #endif
83 #ifdef HAVE_TIME_H
84 #include <time.h>
85 #endif
87 #ifndef O_BINARY
88 #define O_BINARY 0
89 #endif
90 #ifndef O_TEXT
91 #define O_TEXT 0
92 #endif
94 /* =====
95 * Memory management
96 * ===== */
97 #ifdef USE_DMALLOC
98 #include <dmalloc.h>
99 #define DMALLOC_FN_ARGS , file, line
100 #else
101 #define dmalloc_strdup(file, line, string, xalloc_b) strdup(string)
103 #define dmalloc_malloc(file, line, size, func_id, alignment, xalloc_b) malloc(size)
104 #define DMALLOC_FUNC_MALLOC 0
106 #define dmalloc_realloc(file, line, old_pnt, new_size, func_id, xalloc_b) realloc((old_pnt), (new_size))
107 #define DMALLOC_FUNC_REALLOC 0
108 #define DMALLOC_FN_ARGS
109 #endif
111 /** Allocate a chunk of <b>size</b> bytes of memory, and return a pointer to
112 * result. On error, log and terminate the process. (Same as malloc(size),
113 * but never returns NULL.)
115 * <b>file</b> and <b>line</b> are used if dmalloc is enabled, and
116 * ignored otherwise.
118 void *
119 _tor_malloc(size_t size DMALLOC_PARAMS)
121 void *result;
123 /* Some libcs don't do the right thing on size==0. Override them. */
124 if (size==0) {
125 size=1;
127 result = dmalloc_malloc(file, line, size, DMALLOC_FUNC_MALLOC, 0, 0);
129 if (!result) {
130 err(LD_MM,"Out of memory. Dying.");
131 /* XXX if these functions die within a worker process, they won't
132 * call spawn_exit */
133 exit(1);
135 // memset(result,'X',size); /* deadbeef to encourage bugs */
136 return result;
139 /* Allocate a chunk of <b>size</b> bytes of memory, fill the memory with
140 * zero bytes, and return a pointer to the result. Log and terminate
141 * the process on error. (Same as calloc(size,1), but never returns NULL.)
143 void *
144 _tor_malloc_zero(size_t size DMALLOC_PARAMS)
146 void *result = _tor_malloc(size DMALLOC_FN_ARGS);
147 memset(result, 0, size);
148 return result;
151 /** Change the size of the memory block pointed to by <b>ptr</b> to <b>size</b>
152 * bytes long; return the new memory block. On error, log and
153 * terminate. (Like realloc(ptr,size), but never returns NULL.)
155 void *
156 _tor_realloc(void *ptr, size_t size DMALLOC_PARAMS)
158 void *result;
160 result = dmalloc_realloc(file, line, ptr, size, DMALLOC_FUNC_REALLOC, 0);
161 if (!result) {
162 err(LD_MM,"Out of memory. Dying.");
163 exit(1);
165 return result;
168 /** Return a newly allocated copy of the NUL-terminated string s. On
169 * error, log and terminate. (Like strdup(s), but never returns
170 * NULL.)
172 char *
173 _tor_strdup(const char *s DMALLOC_PARAMS)
175 char *dup;
176 tor_assert(s);
178 dup = dmalloc_strdup(file, line, s, 0);
179 if (!dup) {
180 err(LD_MM,"Out of memory. Dying.");
181 exit(1);
183 return dup;
186 /** Allocate and return a new string containing the first <b>n</b>
187 * characters of <b>s</b>. If <b>s</b> is longer than <b>n</b>
188 * characters, only the first <b>n</b> are copied. The result is
189 * always NUL-terminated. (Like strndup(s,n), but never returns
190 * NULL.)
192 char *
193 _tor_strndup(const char *s, size_t n DMALLOC_PARAMS)
195 char *dup;
196 tor_assert(s);
197 dup = _tor_malloc((n+1) DMALLOC_FN_ARGS);
198 /* Performance note: Ordinarily we prefer strlcpy to strncpy. But
199 * this function gets called a whole lot, and platform strncpy is
200 * much faster than strlcpy when strlen(s) is much longer than n.
202 strncpy(dup, s, n);
203 dup[n]='\0';
204 return dup;
207 /* =====
208 * String manipulation
209 * ===== */
211 /** Remove from the string <b>s</b> every character which appears in
212 * <b>strip</b>. Return the number of characters removed. */
214 tor_strstrip(char *s, const char *strip)
216 char *read = s;
217 while (*read) {
218 if (strchr(strip, *read)) {
219 ++read;
220 } else {
221 *s++ = *read++;
224 *s = '\0';
225 return read-s;
228 /** Set the <b>dest_len</b>-byte buffer <b>buf</b> to contain the
229 * string <b>s</b>, with the string <b>insert</b> inserted after every
230 * <b>n</b> characters. Return 0 on success, -1 on failure.
232 * If <b>rule</b> is ALWAYS_TERMINATE, then always end the string with
233 * <b>insert</b>, even if its length is not a multiple of <b>n</b>. If
234 * <b>rule</b> is NEVER_TERMINATE, then never end the string with
235 * <b>insert</b>, even if its length <i>is</i> a multiple of <b>n</b>.
236 * If <b>rule</b> is TERMINATE_IF_EVEN, then end the string with <b>insert</b>
237 * exactly when its length <i>is</i> a multiple of <b>n</b>.
240 tor_strpartition(char *dest, size_t dest_len,
241 const char *s, const char *insert, size_t n,
242 part_finish_rule_t rule)
244 char *destp;
245 size_t len_in, len_out, len_ins;
246 int is_even, remaining;
247 tor_assert(s);
248 tor_assert(insert);
249 tor_assert(n > 0);
250 tor_assert(n < SIZE_T_CEILING);
251 tor_assert(dest_len < SIZE_T_CEILING);
252 len_in = strlen(s);
253 len_ins = strlen(insert);
254 tor_assert(len_in < SIZE_T_CEILING);
255 tor_assert(len_in/n < SIZE_T_CEILING/len_ins); /* avoid overflow */
256 len_out = len_in + (len_in/n)*len_ins;
257 is_even = (len_in%n) == 0;
258 switch (rule)
260 case ALWAYS_TERMINATE:
261 if (!is_even) len_out += len_ins;
262 break;
263 case NEVER_TERMINATE:
264 if (is_even && len_in) len_out -= len_ins;
265 break;
266 case TERMINATE_IF_EVEN:
267 break;
269 if (dest_len < len_out+1)
270 return -1;
271 destp = dest;
272 remaining = len_in;
273 while (remaining) {
274 strncpy(destp, s, n);
275 remaining -= n;
276 if (remaining < 0) {
277 if (rule == ALWAYS_TERMINATE)
278 strcpy(destp+n+remaining,insert);
279 break;
280 } else if (remaining == 0 && rule == NEVER_TERMINATE) {
281 *(destp+n) = '\0';
282 break;
284 strcpy(destp+n, insert);
285 s += n;
286 destp += n+len_ins;
288 tor_assert(len_out == strlen(dest));
289 return 0;
292 /** Return a pointer to a NUL-terminated hexadecimal string encoding
293 * the first <b>fromlen</b> bytes of <b>from</b>. (fromlen must be \<= 32.) The
294 * result does not need to be deallocated, but repeated calls to
295 * hex_str will trash old results.
297 const char *
298 hex_str(const char *from, size_t fromlen)
300 static char buf[65];
301 if (fromlen>(sizeof(buf)-1)/2)
302 fromlen = (sizeof(buf)-1)/2;
303 base16_encode(buf,sizeof(buf),from,fromlen);
304 return buf;
307 /** Convert all alphabetic characters in the nul-terminated string <b>s</b> to
308 * lowercase. */
309 void
310 tor_strlower(char *s)
312 while (*s) {
313 *s = tolower(*s);
314 ++s;
318 /** Convert all alphabetic characters in the nul-terminated string <b>s</b> to
319 * lowercase. */
320 void
321 tor_strupper(char *s)
323 while (*s) {
324 *s = toupper(*s);
325 ++s;
329 /* Compares the first strlen(s2) characters of s1 with s2. Returns as for
330 * strcmp.
333 strcmpstart(const char *s1, const char *s2)
335 size_t n = strlen(s2);
336 return strncmp(s1, s2, n);
339 /* Compares the first strlen(s2) characters of s1 with s2. Returns as for
340 * strcasecmp.
343 strcasecmpstart(const char *s1, const char *s2)
345 size_t n = strlen(s2);
346 return strncasecmp(s1, s2, n);
349 /* Compares the last strlen(s2) characters of s1 with s2. Returns as for
350 * strcmp.
353 strcmpend(const char *s1, const char *s2)
355 size_t n1 = strlen(s1), n2 = strlen(s2);
356 if (n2>n1)
357 return strcmp(s1,s2);
358 else
359 return strncmp(s1+(n1-n2), s2, n2);
362 /* Compares the last strlen(s2) characters of s1 with s2. Returns as for
363 * strcasecmp.
366 strcasecmpend(const char *s1, const char *s2)
368 size_t n1 = strlen(s1), n2 = strlen(s2);
369 if (n2>n1) /* then they can't be the same; figure out which is bigger */
370 return strcasecmp(s1,s2);
371 else
372 return strncasecmp(s1+(n1-n2), s2, n2);
375 /** Return a pointer to the first char of s that is not whitespace and
376 * not a comment, or to the terminating NUL if no such character exists.
378 const char *
379 eat_whitespace(const char *s)
381 tor_assert(s);
383 while (TOR_ISSPACE(*s) || *s == '#') {
384 while (TOR_ISSPACE(*s))
385 s++;
386 if (*s == '#') { /* read to a \n or \0 */
387 while (*s && *s != '\n')
388 s++;
389 if (!*s)
390 return s;
393 return s;
396 /** Return a pointer to the first char of s that is not a space or a tab,
397 * or to the terminating NUL if no such character exists. */
398 const char *
399 eat_whitespace_no_nl(const char *s)
401 while (*s == ' ' || *s == '\t')
402 ++s;
403 return s;
406 /** Return a pointer to the first char of s that is whitespace or <b>#</b>,
407 * or to the terminating NUL if no such character exists.
409 const char *
410 find_whitespace(const char *s)
412 /* tor_assert(s); */
414 while (*s && !TOR_ISSPACE(*s) && *s != '#')
415 s++;
417 return s;
420 #define CHECK_STRTOX_RESULT() \
421 /* Was at least one character converted? */ \
422 if (endptr == s) \
423 goto err; \
424 /* Were there unexpected unconverted characters? */ \
425 if (!next && *endptr) \
426 goto err; \
427 /* Is r within limits? */ \
428 if (r < min || r > max) \
429 goto err; \
430 if (ok) *ok = 1; \
431 if (next) *next = endptr; \
432 return r; \
433 err: \
434 if (ok) *ok = 0; \
435 if (next) *next = endptr; \
436 return 0;
438 /** Extract a long from the start of s, in the given numeric base. If
439 * there is unconverted data and next is provided, set *next to the
440 * first unconverted character. An error has occurred if no characters
441 * are converted; or if there are unconverted characters and next is NULL; or
442 * if the parsed value is not between min and max. When no error occurs,
443 * return the parsed value and set *ok (if provided) to 1. When an error
444 * occurs, return 0 and set *ok (if provided) to 0.
446 long
447 tor_parse_long(const char *s, int base, long min, long max,
448 int *ok, char **next)
450 char *endptr;
451 long r;
453 r = strtol(s, &endptr, base);
454 CHECK_STRTOX_RESULT();
457 unsigned long
458 tor_parse_ulong(const char *s, int base, unsigned long min,
459 unsigned long max, int *ok, char **next)
461 char *endptr;
462 unsigned long r;
464 r = strtoul(s, &endptr, base);
465 CHECK_STRTOX_RESULT();
468 /** Only base 10 is guaranteed to work for now. */
469 uint64_t
470 tor_parse_uint64(const char *s, int base, uint64_t min,
471 uint64_t max, int *ok, char **next)
473 char *endptr;
474 uint64_t r;
476 #ifdef HAVE_STRTOULL
477 r = (uint64_t)strtoull(s, &endptr, base);
478 #elif defined(MS_WINDOWS)
479 #if _MSC_VER < 1300
480 tor_assert(base <= 10);
481 r = (uint64_t)_atoi64(s);
482 endptr = (char*)s;
483 while (TOR_ISSPACE(*endptr)) endptr++;
484 while (TOR_ISDIGIT(*endptr)) endptr++;
485 #else
486 r = (uint64_t)_strtoui64(s, &endptr, base);
487 #endif
488 #elif SIZEOF_LONG == 8
489 r = (uint64_t)strtoul(s, &endptr, base);
490 #else
491 #error "I don't know how to parse 64-bit numbers."
492 #endif
494 CHECK_STRTOX_RESULT();
497 void
498 base16_encode(char *dest, size_t destlen, const char *src, size_t srclen)
500 const char *end;
501 char *cp;
503 tor_assert(destlen >= srclen*2+1);
504 tor_assert(destlen < SIZE_T_CEILING);
506 cp = dest;
507 end = src+srclen;
508 while (src<end) {
509 sprintf(cp,"%02X",*(const uint8_t*)src);
510 ++src;
511 cp += 2;
513 *cp = '\0';
516 static const char HEX_DIGITS[] = "0123456789ABCDEFabcdef";
518 static INLINE int
519 hex_decode_digit(char c)
521 const char *cp;
522 int n;
523 cp = strchr(HEX_DIGITS, c);
524 if (!cp)
525 return -1;
526 n = cp-HEX_DIGITS;
527 if (n<=15)
528 return n; /* digit or uppercase */
529 else
530 return n-6; /* lowercase */
534 base16_decode(char *dest, size_t destlen, const char *src, size_t srclen)
536 const char *end;
537 int v1,v2;
538 if ((srclen % 2) != 0)
539 return -1;
540 if (destlen < srclen/2 || destlen > SIZE_T_CEILING)
541 return -1;
542 end = src+srclen;
543 while (src<end) {
544 v1 = hex_decode_digit(*src);
545 v2 = hex_decode_digit(*(src+1));
546 if (v1<0||v2<0)
547 return -1;
548 *(uint8_t*)dest = (v1<<4)|v2;
549 ++dest;
550 src+=2;
552 return 0;
555 /* =====
556 * Time
557 * ===== */
559 /** Return the number of microseconds elapsed between *start and *end.
561 long
562 tv_udiff(struct timeval *start, struct timeval *end)
564 long udiff;
565 long secdiff = end->tv_sec - start->tv_sec;
567 if (labs(secdiff+1) > LONG_MAX/1000000) {
568 warn(LD_GENERAL, "comparing times too far apart.");
569 return LONG_MAX;
572 udiff = secdiff*1000000L + (end->tv_usec - start->tv_usec);
573 return udiff;
576 /** Return -1 if *a \< *b, 0 if *a==*b, and 1 if *a \> *b.
579 tv_cmp(struct timeval *a, struct timeval *b)
581 if (a->tv_sec > b->tv_sec)
582 return 1;
583 if (a->tv_sec < b->tv_sec)
584 return -1;
585 if (a->tv_usec > b->tv_usec)
586 return 1;
587 if (a->tv_usec < b->tv_usec)
588 return -1;
589 return 0;
592 /** Increment *a by the number of seconds and microseconds in *b.
594 void
595 tv_add(struct timeval *a, struct timeval *b)
597 a->tv_usec += b->tv_usec;
598 a->tv_sec += b->tv_sec + (a->tv_usec / 1000000);
599 a->tv_usec %= 1000000;
602 /** Increment *a by <b>ms</b> milliseconds.
604 void
605 tv_addms(struct timeval *a, long ms)
607 a->tv_usec += (ms * 1000) % 1000000;
608 a->tv_sec += ((ms * 1000) / 1000000) + (a->tv_usec / 1000000);
609 a->tv_usec %= 1000000;
612 #define IS_LEAPYEAR(y) (!(y % 4) && ((y % 100) || !(y % 400)))
613 static int
614 n_leapdays(int y1, int y2)
616 --y1;
617 --y2;
618 return (y2/4 - y1/4) - (y2/100 - y1/100) + (y2/400 - y1/400);
620 /** Number of days per month in non-leap year; used by tor_timegm. */
621 static const int days_per_month[] =
622 { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
624 /** Return a time_t given a struct tm. The result is given in GMT, and
625 * does not account for leap seconds.
627 time_t
628 tor_timegm(struct tm *tm)
630 /* This is a pretty ironclad timegm implementation, snarfed from Python2.2.
631 * It's way more brute-force than fiddling with tzset().
633 time_t ret;
634 unsigned long year, days, hours, minutes;
635 int i;
636 year = tm->tm_year + 1900;
637 tor_assert(year >= 1970);
638 tor_assert(tm->tm_mon >= 0);
639 tor_assert(tm->tm_mon <= 11);
640 days = 365 * (year-1970) + n_leapdays(1970,year);
641 for (i = 0; i < tm->tm_mon; ++i)
642 days += days_per_month[i];
643 if (tm->tm_mon > 1 && IS_LEAPYEAR(year))
644 ++days;
645 days += tm->tm_mday - 1;
646 hours = days*24 + tm->tm_hour;
648 minutes = hours*60 + tm->tm_min;
649 ret = minutes*60 + tm->tm_sec;
650 return ret;
653 /* strftime is locale-specific, so we need to replace those parts */
654 static const char *WEEKDAY_NAMES[] =
655 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
656 static const char *MONTH_NAMES[] =
657 { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
658 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
660 void
661 format_rfc1123_time(char *buf, time_t t)
663 struct tm tm;
665 tor_gmtime_r(&t, &tm);
667 strftime(buf, RFC1123_TIME_LEN+1, "___, %d ___ %Y %H:%M:%S GMT", &tm);
668 tor_assert(tm.tm_wday >= 0);
669 tor_assert(tm.tm_wday <= 6);
670 memcpy(buf, WEEKDAY_NAMES[tm.tm_wday], 3);
671 tor_assert(tm.tm_wday >= 0);
672 tor_assert(tm.tm_mon <= 11);
673 memcpy(buf+8, MONTH_NAMES[tm.tm_mon], 3);
677 parse_rfc1123_time(const char *buf, time_t *t)
679 struct tm tm;
680 char month[4];
681 char weekday[4];
682 int i, m;
684 if (strlen(buf) != RFC1123_TIME_LEN)
685 return -1;
686 memset(&tm, 0, sizeof(tm));
687 if (sscanf(buf, "%3s, %d %3s %d %d:%d:%d GMT", weekday,
688 &tm.tm_mday, month, &tm.tm_year, &tm.tm_hour,
689 &tm.tm_min, &tm.tm_sec) < 7) {
690 warn(LD_GENERAL, "Got invalid RFC1123 time \"%s\"", buf);
691 return -1;
694 m = -1;
695 for (i = 0; i < 12; ++i) {
696 if (!strcmp(month, MONTH_NAMES[i])) {
697 m = i;
698 break;
701 if (m<0) {
702 warn(LD_GENERAL, "Got invalid RFC1123 time \"%s\"", buf);
703 return -1;
706 tm.tm_mon = m;
707 tm.tm_year -= 1900;
708 *t = tor_timegm(&tm);
709 return 0;
712 void
713 format_local_iso_time(char *buf, time_t t)
715 struct tm tm;
716 strftime(buf, ISO_TIME_LEN+1, "%Y-%m-%d %H:%M:%S", tor_localtime_r(&t, &tm));
719 void
720 format_iso_time(char *buf, time_t t)
722 struct tm tm;
723 strftime(buf, ISO_TIME_LEN+1, "%Y-%m-%d %H:%M:%S", tor_gmtime_r(&t, &tm));
727 parse_iso_time(const char *cp, time_t *t)
729 struct tm st_tm;
730 #ifdef HAVE_STRPTIME
731 if (!strptime(cp, "%Y-%m-%d %H:%M:%S", &st_tm)) {
732 warn(LD_GENERAL, "Published time was unparseable"); return -1;
734 #else
735 unsigned int year=0, month=0, day=0, hour=100, minute=100, second=100;
736 if (sscanf(cp, "%u-%u-%u %u:%u:%u", &year, &month,
737 &day, &hour, &minute, &second) < 6) {
738 warn(LD_GENERAL, "Published time was unparseable"); return -1;
740 if (year < 1970 || month < 1 || month > 12 || day < 1 || day > 31 ||
741 hour > 23 || minute > 59 || second > 61) {
742 warn(LD_GENERAL, "Published time was nonsensical"); return -1;
744 st_tm.tm_year = year-1900;
745 st_tm.tm_mon = month-1;
746 st_tm.tm_mday = day;
747 st_tm.tm_hour = hour;
748 st_tm.tm_min = minute;
749 st_tm.tm_sec = second;
750 #endif
751 *t = tor_timegm(&st_tm);
752 return 0;
755 /* =====
756 * File helpers
757 * ===== */
759 /** Write <b>count</b> bytes from <b>buf</b> to <b>fd</b>. <b>isSocket</b>
760 * must be 1 if fd was returned by socket() or accept(), and 0 if fd
761 * was returned by open(). Return the number of bytes written, or -1
762 * on error. Only use if fd is a blocking fd. */
764 write_all(int fd, const char *buf, size_t count, int isSocket)
766 size_t written = 0;
767 int result;
769 while (written != count) {
770 if (isSocket)
771 result = send(fd, buf+written, count-written, 0);
772 else
773 result = write(fd, buf+written, count-written);
774 if (result<0)
775 return -1;
776 written += result;
778 return count;
781 /** Read from <b>fd</b> to <b>buf</b>, until we get <b>count</b> bytes
782 * or reach the end of the file. <b>isSocket</b> must be 1 if fd
783 * was returned by socket() or accept(), and 0 if fd was returned by
784 * open(). Return the number of bytes read, or -1 on error. Only use
785 * if fd is a blocking fd. */
787 read_all(int fd, char *buf, size_t count, int isSocket)
789 size_t numread = 0;
790 int result;
792 if (count > SIZE_T_CEILING)
793 return -1;
795 while (numread != count) {
796 if (isSocket)
797 result = recv(fd, buf+numread, count-numread, 0);
798 else
799 result = read(fd, buf+numread, count-numread);
800 if (result<0)
801 return -1;
802 else if (result == 0)
803 break;
804 numread += result;
806 return numread;
810 * Filesystem operations.
813 /** Clean up <b>name</b> so that we can use it in a call to "stat". On Unix,
814 * we do nothing. On Windows, we remove a trailing slash, unless the path is
815 * the root of a disk. */
816 static void
817 clean_name_for_stat(char *name)
819 #ifdef MS_WINDOWS
820 size_t len = strlen(name);
821 if (!len)
822 return;
823 if (name[len-1]=='\\' || name[len-1]=='/') {
824 if (len == 1 || (len==3 && name[1]==':'))
825 return;
826 name[len-1]='\0';
828 #endif
831 /** Return FN_ERROR if filename can't be read, FN_NOENT if it doesn't
832 * exist, FN_FILE if it is a regular file, or FN_DIR if it's a
833 * directory. */
834 file_status_t
835 file_status(const char *fname)
837 struct stat st;
838 char *f;
839 int r;
840 f = tor_strdup(fname);
841 clean_name_for_stat(f);
842 r = stat(f, &st);
843 tor_free(f);
844 if (r) {
845 if (errno == ENOENT) {
846 return FN_NOENT;
848 return FN_ERROR;
850 if (st.st_mode & S_IFDIR)
851 return FN_DIR;
852 else if (st.st_mode & S_IFREG)
853 return FN_FILE;
854 else
855 return FN_ERROR;
858 /** Check whether dirname exists and is private. If yes return 0. If
859 * it does not exist, and check==CPD_CREATE is set, try to create it
860 * and return 0 on success. If it does not exist, and
861 * check==CPD_CHECK, and we think we can create it, return 0. Else
862 * return -1. */
864 check_private_dir(const char *dirname, cpd_check_t check)
866 int r;
867 struct stat st;
868 char *f;
869 tor_assert(dirname);
870 f = tor_strdup(dirname);
871 clean_name_for_stat(f);
872 r = stat(f, &st);
873 tor_free(f);
874 if (r) {
875 if (errno != ENOENT) {
876 log(LOG_WARN, LD_FS, "Directory %s cannot be read: %s", dirname,
877 strerror(errno));
878 return -1;
880 if (check == CPD_NONE) {
881 log(LOG_WARN, LD_FS, "Directory %s does not exist.", dirname);
882 return -1;
883 } else if (check == CPD_CREATE) {
884 info(LD_GENERAL, "Creating directory %s", dirname);
885 #ifdef MS_WINDOWS
886 r = mkdir(dirname);
887 #else
888 r = mkdir(dirname, 0700);
889 #endif
890 if (r) {
891 log(LOG_WARN, LD_FS, "Error creating directory %s: %s", dirname,
892 strerror(errno));
893 return -1;
896 /* XXXX In the case where check==CPD_CHECK, we should look at the
897 * parent directory a little harder. */
898 return 0;
900 if (!(st.st_mode & S_IFDIR)) {
901 log(LOG_WARN, LD_FS, "%s is not a directory", dirname);
902 return -1;
904 #ifndef MS_WINDOWS
905 if (st.st_uid != getuid()) {
906 log(LOG_WARN, LD_FS, "%s is not owned by this UID (%d). You must fix this to proceed.", dirname, (int)getuid());
907 return -1;
909 if (st.st_mode & 0077) {
910 log(LOG_WARN, LD_FS, "Fixing permissions on directory %s", dirname);
911 if (chmod(dirname, 0700)) {
912 log(LOG_WARN, LD_FS, "Could not chmod directory %s: %s", dirname,
913 strerror(errno));
914 return -1;
915 } else {
916 return 0;
919 #endif
920 return 0;
923 /** Create a file named <b>fname</b> with the contents <b>str</b>. Overwrite the
924 * previous <b>fname</b> if possible. Return 0 on success, -1 on failure.
926 * This function replaces the old file atomically, if possible.
929 write_str_to_file(const char *fname, const char *str, int bin)
931 #ifdef MS_WINDOWS
932 if (!bin && strchr(str, '\r')) {
933 warn(LD_BUG,
934 "Bug: we're writing a text string that already contains a CR.");
936 #endif
937 return write_bytes_to_file(fname, str, strlen(str), bin);
940 /* DOCDOC */
941 static int
942 write_chunks_to_file_impl(const char *fname, const smartlist_t *chunks,
943 int open_flags)
945 size_t tempname_len;
946 char *tempname;
947 int fd;
948 int result;
949 tempname_len = strlen(fname)+16;
950 tor_assert(tempname_len > strlen(fname)); /*check for overflow*/
951 tempname = tor_malloc(tempname_len);
952 if (open_flags & O_APPEND) {
953 strlcpy(tempname, fname, tempname_len);
954 } else {
955 if (tor_snprintf(tempname, tempname_len, "%s.tmp", fname)<0) {
956 log(LOG_WARN, LD_GENERAL, "Failed to generate filename");
957 goto err;
960 if ((fd = open(tempname, open_flags, 0600))
961 < 0) {
962 log(LOG_WARN, LD_FS, "Couldn't open \"%s\" for writing: %s", tempname,
963 strerror(errno));
964 goto err;
966 SMARTLIST_FOREACH(chunks, sized_chunk_t *, chunk,
968 result = write_all(fd, chunk->bytes, chunk->len, 0);
969 if (result < 0 || (size_t)result != chunk->len) {
970 log(LOG_WARN, LD_FS, "Error writing to \"%s\": %s", tempname, strerror(errno));
971 close(fd);
972 goto err;
975 if (close(fd)) {
976 log(LOG_WARN, LD_FS, "Error flushing to \"%s\": %s", tempname, strerror(errno));
977 goto err;
979 if (!(open_flags & O_APPEND)) {
980 if (replace_file(tempname, fname)) {
981 log(LOG_WARN, LD_FS, "Error replacing \"%s\": %s", fname, strerror(errno));
982 goto err;
985 tor_free(tempname);
986 return 0;
987 err:
988 tor_free(tempname);
989 return -1;
992 /* DOCDOC */
994 write_chunks_to_file(const char *fname, const smartlist_t *chunks, int bin)
996 int flags = O_WRONLY|O_CREAT|O_TRUNC|(bin?O_BINARY:O_TEXT);
997 return write_chunks_to_file_impl(fname, chunks, flags);
1000 /** As write_str_to_file, but does not assume a NUL-terminated *
1001 * string. Instead, we write <b>len</b> bytes, starting at <b>str</b>. */
1003 write_bytes_to_file(const char *fname, const char *str, size_t len,
1004 int bin)
1006 int flags = O_WRONLY|O_CREAT|O_TRUNC|(bin?O_BINARY:O_TEXT);
1007 int r;
1008 sized_chunk_t c = { str, len };
1009 smartlist_t *chunks = smartlist_create();
1010 smartlist_add(chunks, &c);
1011 r = write_chunks_to_file_impl(fname, chunks, flags);
1012 smartlist_free(chunks);
1013 return r;
1016 /* DOCDOC */
1018 append_bytes_to_file(const char *fname, const char *str, size_t len,
1019 int bin)
1021 int flags = O_WRONLY|O_CREAT|O_APPEND|(bin?O_BINARY:O_TEXT);
1022 int r;
1023 sized_chunk_t c = { str, len };
1024 smartlist_t *chunks = smartlist_create();
1025 smartlist_add(chunks, &c);
1026 r = write_chunks_to_file_impl(fname, chunks, flags);
1027 smartlist_free(chunks);
1028 return r;
1031 /** Read the contents of <b>filename</b> into a newly allocated
1032 * string; return the string on success or NULL on failure.
1035 * This function <em>may</em> return an erroneous result if the file
1036 * is modified while it is running, but must not crash or overflow.
1037 * Right now, the error case occurs when the file length grows between
1038 * the call to stat and the call to read_all: the resulting string will
1039 * be truncated.
1041 char *
1042 read_file_to_str(const char *filename, int bin)
1044 int fd; /* router file */
1045 struct stat statbuf;
1046 char *string, *f;
1047 int r;
1049 tor_assert(filename);
1051 f = tor_strdup(filename);
1052 clean_name_for_stat(f);
1053 r = stat(f, &statbuf);
1054 tor_free(f);
1055 if (r < 0) {
1056 info(LD_FS,"Could not stat \"%s\".",filename);
1057 return NULL;
1060 fd = open(filename,O_RDONLY|(bin?O_BINARY:O_TEXT),0);
1061 if (fd<0) {
1062 warn(LD_FS,"Could not open \"%s\".",filename);
1063 return NULL;
1066 string = tor_malloc(statbuf.st_size+1);
1068 r = read_all(fd,string,statbuf.st_size,0);
1069 if (r<0) {
1070 warn(LD_FS,"Error reading from file \"%s\": %s", filename,
1071 strerror(errno));
1072 tor_free(string);
1073 close(fd);
1074 return NULL;
1076 string[r] = '\0'; /* NUL-terminate the result. */
1078 if (bin && r != statbuf.st_size) {
1079 /* If we're in binary mode, then we'd better have an exact match for
1080 * size. Otherwise, win32 encoding may throw us off, and that's okay. */
1081 warn(LD_FS,"Could read only %d of %ld bytes of file \"%s\".",
1082 r, (long)statbuf.st_size,filename);
1083 tor_free(string);
1084 close(fd);
1085 return NULL;
1087 #ifdef MS_WINDOWS
1088 if (!bin && strchr(string, '\r')) {
1089 debug(LD_FS, "We didn't convert CRLF to LF as well as we hoped when reading %s. Coping.",
1090 filename);
1091 tor_strstrip(string, "\r");
1093 #endif
1094 close(fd);
1096 return string;
1099 /** Given a string containing part of a configuration file or similar format,
1100 * advance past comments and whitespace and try to parse a single line. If we
1101 * parse a line successfully, set *<b>key_out</b> to the key portion and
1102 * *<b>value_out</b> to the value portion of the line, and return a pointer to
1103 * the start of the next line. If we run out of data, return a pointer to the
1104 * end of the string. If we encounter an error, return NULL.
1106 * NOTE: We modify <b>line</b> as we parse it, by inserting NULs to terminate
1107 * the key and value.
1109 char *
1110 parse_line_from_str(char *line, char **key_out, char **value_out)
1112 char *key, *val, *cp;
1114 tor_assert(key_out);
1115 tor_assert(value_out);
1117 *key_out = *value_out = key = val = NULL;
1118 /* Skip until the first keyword. */
1119 while (1) {
1120 while (TOR_ISSPACE(*line))
1121 ++line;
1122 if (*line == '#') {
1123 while (*line && *line != '\n')
1124 ++line;
1125 } else {
1126 break;
1130 if (!*line) { /* End of string? */
1131 *key_out = *value_out = NULL;
1132 return line;
1135 /* Skip until the next space. */
1136 key = line;
1137 while (*line && !TOR_ISSPACE(*line) && *line != '#')
1138 ++line;
1140 /* Skip until the value */
1141 while (*line == ' ' || *line == '\t')
1142 *line++ = '\0';
1143 val = line;
1145 /* Find the end of the line. */
1146 while (*line && *line != '\n' && *line != '#')
1147 ++line;
1148 if (*line == '\n')
1149 cp = line++;
1150 else {
1151 cp = line-1;
1153 while (cp>=val && TOR_ISSPACE(*cp))
1154 *cp-- = '\0';
1156 if (*line == '#') {
1157 do {
1158 *line++ = '\0';
1159 } while (*line && *line != '\n');
1160 if (*line == '\n')
1161 ++line;
1164 *key_out = key;
1165 *value_out = val;
1167 return line;
1170 /** Expand any homedir prefix on 'filename'; return a newly allocated
1171 * string. */
1172 char *
1173 expand_filename(const char *filename)
1175 tor_assert(filename);
1176 if (*filename == '~') {
1177 size_t len;
1178 char *home, *result;
1179 const char *rest;
1181 if (filename[1] == '/' || filename[1] == '\0') {
1182 home = getenv("HOME");
1183 if (!home) {
1184 warn(LD_CONFIG, "Couldn't find $HOME environment variable while expanding %s", filename);
1185 return NULL;
1187 home = tor_strdup(home);
1188 rest = strlen(filename)>=2?(filename+2):NULL;
1189 } else {
1190 #ifdef HAVE_PWD_H
1191 char *username, *slash;
1192 slash = strchr(filename, '/');
1193 if (slash)
1194 username = tor_strndup(filename+1,slash-filename-1);
1195 else
1196 username = tor_strdup(filename+1);
1197 if (!(home = get_user_homedir(username))) {
1198 warn(LD_CONFIG,"Couldn't get homedir for \"%s\"",username);
1199 tor_free(username);
1200 return NULL;
1202 tor_free(username);
1203 rest = slash ? (slash+1) : NULL;
1204 #else
1205 warn(LD_CONFIG, "Couldn't expend homedir on system without pwd.h");
1206 return tor_strdup(filename);
1207 #endif
1209 tor_assert(home);
1210 /* Remove trailing slash. */
1211 if (strlen(home)>1 && !strcmpend(home,"/")) {
1212 home[strlen(home)-1] = '\0';
1214 /* Plus one for /, plus one for NUL.
1215 * Round up to 16 in case we can't do math. */
1216 len = strlen(home)+strlen(rest)+16;
1217 result = tor_malloc(len);
1218 tor_snprintf(result,len,"%s/%s",home,rest?rest:"");
1219 tor_free(home);
1220 return result;
1221 } else {
1222 return tor_strdup(filename);
1226 /** Return a new list containing the filenames in the directory <b>dirname</b>.
1227 * Return NULL on error or if <b>dirname</b> is not a directory.
1229 smartlist_t *
1230 tor_listdir(const char *dirname)
1232 smartlist_t *result;
1233 #ifdef MS_WINDOWS
1234 char *pattern;
1235 HANDLE handle;
1236 WIN32_FIND_DATA findData;
1237 size_t pattern_len = strlen(dirname)+16;
1238 pattern = tor_malloc(pattern_len);
1239 tor_snprintf(pattern, pattern_len, "%s\\*", dirname);
1240 if (!(handle = FindFirstFile(pattern, &findData))) {
1241 tor_free(pattern);
1242 return NULL;
1244 result = smartlist_create();
1245 while (1) {
1246 if (!strcmp(findData.cFileName, ".") ||
1247 !strcmp(findData.cFileName, ".."))
1248 continue;
1249 smartlist_add(result, tor_strdup(findData.cFileName));
1250 if (!FindNextFile(handle, &findData)) {
1251 if (GetLastError() != ERROR_NO_MORE_FILES) {
1252 log_fn(LOG_WARN, "Error reading directory.");
1254 break;
1257 FindClose(handle);
1258 tor_free(pattern);
1259 #else
1260 DIR *d;
1261 struct dirent *de;
1262 if (!(d = opendir(dirname)))
1263 return NULL;
1265 result = smartlist_create();
1266 while ((de = readdir(d))) {
1267 if (!strcmp(de->d_name, ".") ||
1268 !strcmp(de->d_name, ".."))
1269 continue;
1270 smartlist_add(result, tor_strdup(de->d_name));
1272 closedir(d);
1273 #endif
1274 return result;
1277 /* =====
1278 * Net helpers
1279 * ===== */
1281 /** Return true iff <b>ip</b> (in host order) is an IP reserved to localhost,
1282 * or reserved for local networks by RFC 1918.
1285 is_internal_IP(uint32_t ip)
1287 if (((ip & 0xff000000) == 0x0a000000) || /* 10/8 */
1288 ((ip & 0xff000000) == 0x00000000) || /* 0/8 */
1289 ((ip & 0xff000000) == 0x7f000000) || /* 127/8 */
1290 ((ip & 0xffff0000) == 0xa9fe0000) || /* 169.254/16 */
1291 ((ip & 0xfff00000) == 0xac100000) || /* 172.16/12 */
1292 ((ip & 0xffff0000) == 0xc0a80000)) /* 192.168/16 */
1293 return 1;
1294 return 0;
1297 /** Return true iff <b>ip</b> (in host order) is judged to be on the
1298 * same network as us. For now, check if it's an internal IP.
1300 * XXX Also check if it's on the same class C network as our public IP.
1303 is_local_IP(uint32_t ip)
1305 return is_internal_IP(ip);
1308 /** Parse a string of the form "host[:port]" from <b>addrport</b>. If
1309 * <b>address</b> is provided, set *<b>address</b> to a copy of the
1310 * host portion of the string. If <b>addr</b> is provided, try to
1311 * resolve the host portion of the string and store it into
1312 * *<b>addr</b> (in host byte order). If <b>port_out</b> is provided,
1313 * store the port number into *<b>port_out</b>, or 0 if no port is given.
1314 * If <b>port_out</b> is NULL, then there must be no port number in
1315 * <b>addrport</b>.
1316 * Return 0 on success, -1 on failure.
1319 parse_addr_port(const char *addrport, char **address, uint32_t *addr,
1320 uint16_t *port_out)
1322 const char *colon;
1323 char *_address = NULL;
1324 int _port;
1325 int ok = 1;
1327 tor_assert(addrport);
1329 colon = strchr(addrport, ':');
1330 if (colon) {
1331 _address = tor_strndup(addrport, colon-addrport);
1332 _port = (int) tor_parse_long(colon+1,10,1,65535,NULL,NULL);
1333 if (!_port) {
1334 warn(LD_GENERAL, "Port '%s' out of range", colon+1);
1335 ok = 0;
1337 if (!port_out) {
1338 warn(LD_GENERAL, "Port '%s' given on '%s' when not required", colon+1,
1339 addrport);
1340 ok = 0;
1342 } else {
1343 _address = tor_strdup(addrport);
1344 _port = 0;
1347 if (addr) {
1348 /* There's an addr pointer, so we need to resolve the hostname. */
1349 if (tor_lookup_hostname(_address,addr)) {
1350 warn(LD_NET, "Couldn't look up '%s'", _address);
1351 ok = 0;
1352 *addr = 0;
1354 *addr = ntohl(*addr);
1357 if (address && ok) {
1358 *address = _address;
1359 } else {
1360 if (address)
1361 *address = NULL;
1362 tor_free(_address);
1364 if (port_out)
1365 *port_out = ok ? ((uint16_t) _port) : 0;
1367 return ok ? 0 : -1;
1370 /** Parse a string <b>s</b> in the format of
1371 * (IP(/mask|/mask-bits)?|*):(*|port(-maxport)?), setting the various
1372 * *out pointers as appropriate. Return 0 on success, -1 on failure.
1375 parse_addr_and_port_range(const char *s, uint32_t *addr_out,
1376 uint32_t *mask_out, uint16_t *port_min_out,
1377 uint16_t *port_max_out)
1379 char *address;
1380 char *mask, *port, *endptr;
1381 struct in_addr in;
1382 int bits;
1384 tor_assert(s);
1385 tor_assert(addr_out);
1386 tor_assert(mask_out);
1387 tor_assert(port_min_out);
1388 tor_assert(port_max_out);
1390 address = tor_strdup(s);
1391 /* Break 'address' into separate strings.
1393 mask = strchr(address,'/');
1394 port = strchr(mask?mask:address,':');
1395 if (mask)
1396 *mask++ = '\0';
1397 if (port)
1398 *port++ = '\0';
1399 /* Now "address" is the IP|'*' part...
1400 * "mask" is the Mask|Maskbits part...
1401 * and "port" is the *|port|min-max part.
1404 if (strcmp(address,"*")==0) {
1405 *addr_out = 0;
1406 } else if (tor_inet_aton(address, &in) != 0) {
1407 *addr_out = ntohl(in.s_addr);
1408 } else {
1409 warn(LD_GENERAL, "Malformed IP \"%s\" in address pattern; rejecting.",address);
1410 goto err;
1413 if (!mask) {
1414 if (strcmp(address,"*")==0)
1415 *mask_out = 0;
1416 else
1417 *mask_out = 0xFFFFFFFFu;
1418 } else {
1419 endptr = NULL;
1420 bits = (int) strtol(mask, &endptr, 10);
1421 if (!*endptr) {
1422 /* strtol handled the whole mask. */
1423 if (bits < 0 || bits > 32) {
1424 warn(LD_GENERAL, "Bad number of mask bits on address range; rejecting.");
1425 goto err;
1427 *mask_out = ~((1<<(32-bits))-1);
1428 } else if (tor_inet_aton(mask, &in) != 0) {
1429 *mask_out = ntohl(in.s_addr);
1430 } else {
1431 warn(LD_GENERAL, "Malformed mask \"%s\" on address range; rejecting.",
1432 mask);
1433 goto err;
1437 if (!port || strcmp(port, "*") == 0) {
1438 *port_min_out = 1;
1439 *port_max_out = 65535;
1440 } else {
1441 endptr = NULL;
1442 *port_min_out = (uint16_t) tor_parse_long(port, 10, 1, 65535,
1443 NULL, &endptr);
1444 if (*endptr == '-') {
1445 port = endptr+1;
1446 endptr = NULL;
1447 *port_max_out = (uint16_t) tor_parse_long(port, 10, 1, 65535, NULL,
1448 &endptr);
1449 if (*endptr || !*port_max_out) {
1450 warn(LD_GENERAL, "Malformed port \"%s\" on address range rejecting.",
1451 port);
1453 } else if (*endptr || !*port_min_out) {
1454 warn(LD_GENERAL, "Malformed port \"%s\" on address range; rejecting.",
1455 port);
1456 goto err;
1457 } else {
1458 *port_max_out = *port_min_out;
1460 if (*port_min_out > *port_max_out) {
1461 warn(LD_GENERAL, "Insane port range on address policy; rejecting.");
1462 goto err;
1466 tor_free(address);
1467 return 0;
1468 err:
1469 tor_free(address);
1470 return -1;
1473 /** Given an IPv4 address <b>in</b> (in network order, as usual),
1474 * write it as a string into the <b>buf_len</b>-byte buffer in
1475 * <b>buf</b>.
1478 tor_inet_ntoa(struct in_addr *in, char *buf, size_t buf_len)
1480 uint32_t a = ntohl(in->s_addr);
1481 return tor_snprintf(buf, buf_len, "%d.%d.%d.%d",
1482 (int)(uint8_t)((a>>24)&0xff),
1483 (int)(uint8_t)((a>>16)&0xff),
1484 (int)(uint8_t)((a>>8 )&0xff),
1485 (int)(uint8_t)((a )&0xff));
1488 /** Given a host-order <b>addr</b>, call tor_inet_ntoa() on it
1489 * and return a strdup of the resulting address.
1491 char *
1492 tor_dup_addr(uint32_t addr)
1494 char buf[INET_NTOA_BUF_LEN];
1495 struct in_addr in;
1497 in.s_addr = htonl(addr);
1498 tor_inet_ntoa(&in, buf, sizeof(buf));
1499 return tor_strdup(buf);
1502 /* Return true iff <b>name</b> looks like it might be a hostname or IP
1503 * address of some kind. */
1505 is_plausible_address(const char *name)
1507 const char *cp;
1508 tor_assert(name);
1509 /* We could check better here. */
1510 for (cp=name; *cp; cp++) {
1511 if (*cp != '.' && *cp != '-' && !TOR_ISALNUM(*cp))
1512 return 0;
1515 return 1;
1519 * Set *<b>addr</b> to the host-order IPv4 address (if any) of whatever
1520 * interface connects to the internet. This address should only be used in
1521 * checking whether our address has changed. Return 0 on success, -1 on
1522 * failure.
1525 get_interface_address(uint32_t *addr)
1527 int sock=-1, r=-1;
1528 struct sockaddr_in target_addr, my_addr;
1529 socklen_t my_addr_len = sizeof(my_addr);
1531 tor_assert(addr);
1532 *addr = 0;
1534 sock = socket(PF_INET,SOCK_DGRAM,IPPROTO_UDP);
1535 if (sock < 0) {
1536 int e = tor_socket_errno(-1);
1537 warn(LD_NET, "unable to create socket: %s", tor_socket_strerror(e));
1538 goto err;
1541 memset(&target_addr, 0, sizeof(target_addr));
1542 target_addr.sin_family = AF_INET;
1543 /* discard port */
1544 target_addr.sin_port = 9;
1545 /* 18.0.0.1 (Don't worry: no packets are sent. We just need a real address
1546 * on the internet.) */
1547 target_addr.sin_addr.s_addr = htonl(0x12000001);
1549 if (connect(sock,(struct sockaddr *)&target_addr,sizeof(target_addr))<0) {
1550 int e = tor_socket_errno(sock);
1551 warn(LD_NET, "connnect() failed: %s", tor_socket_strerror(e));
1552 goto err;
1555 /* XXXX Can this be right on IPv6 clients? */
1556 if (getsockname(sock, (struct sockaddr*)&my_addr, &my_addr_len)) {
1557 int e = tor_socket_errno(sock);
1558 warn(LD_NET, "getsockname() failed: %s", tor_socket_strerror(e));
1559 goto err;
1562 *addr = ntohl(my_addr.sin_addr.s_addr);
1564 r=0;
1565 err:
1566 if (sock >= 0)
1567 tor_close_socket(sock);
1568 return r;
1571 /* =====
1572 * Process helpers
1573 * ===== */
1575 #ifndef MS_WINDOWS
1576 /* Based on code contributed by christian grothoff */
1577 static int start_daemon_called = 0;
1578 static int finish_daemon_called = 0;
1579 static int daemon_filedes[2];
1580 /** Start putting the process into daemon mode: fork and drop all resources
1581 * except standard fds. The parent process never returns, but stays around
1582 * until finish_daemon is called. (Note: it's safe to call this more
1583 * than once: calls after the first are ignored.)
1585 void
1586 start_daemon(void)
1588 pid_t pid;
1590 if (start_daemon_called)
1591 return;
1592 start_daemon_called = 1;
1594 pipe(daemon_filedes);
1595 pid = fork();
1596 if (pid < 0) {
1597 err(LD_GENERAL,"fork failed. Exiting.");
1598 exit(1);
1600 if (pid) { /* Parent */
1601 int ok;
1602 char c;
1604 close(daemon_filedes[1]); /* we only read */
1605 ok = -1;
1606 while (0 < read(daemon_filedes[0], &c, sizeof(char))) {
1607 if (c == '.')
1608 ok = 1;
1610 fflush(stdout);
1611 if (ok == 1)
1612 exit(0);
1613 else
1614 exit(1); /* child reported error */
1615 } else { /* Child */
1616 close(daemon_filedes[0]); /* we only write */
1618 pid = setsid(); /* Detach from controlling terminal */
1620 * Fork one more time, so the parent (the session group leader) can exit.
1621 * This means that we, as a non-session group leader, can never regain a
1622 * controlling terminal. This part is recommended by Stevens's
1623 * _Advanced Programming in the Unix Environment_.
1625 if (fork() != 0) {
1626 exit(0);
1628 return;
1632 /** Finish putting the process into daemon mode: drop standard fds, and tell
1633 * the parent process to exit. (Note: it's safe to call this more than once:
1634 * calls after the first are ignored. Calls start_daemon first if it hasn't
1635 * been called already.)
1637 void
1638 finish_daemon(const char *desired_cwd)
1640 int nullfd;
1641 char c = '.';
1642 if (finish_daemon_called)
1643 return;
1644 if (!start_daemon_called)
1645 start_daemon();
1646 finish_daemon_called = 1;
1648 if (!desired_cwd)
1649 desired_cwd = "/";
1650 /* Don't hold the wrong FS mounted */
1651 if (chdir(desired_cwd) < 0) {
1652 err(LD_GENERAL,"chdir to \"%s\" failed. Exiting.",desired_cwd);
1653 exit(1);
1656 nullfd = open("/dev/null",
1657 O_CREAT | O_RDWR | O_APPEND);
1658 if (nullfd < 0) {
1659 err(LD_GENERAL,"/dev/null can't be opened. Exiting.");
1660 exit(1);
1662 /* close fds linking to invoking terminal, but
1663 * close usual incoming fds, but redirect them somewhere
1664 * useful so the fds don't get reallocated elsewhere.
1666 if (dup2(nullfd,0) < 0 ||
1667 dup2(nullfd,1) < 0 ||
1668 dup2(nullfd,2) < 0) {
1669 err(LD_GENERAL,"dup2 failed. Exiting.");
1670 exit(1);
1672 if (nullfd > 2)
1673 close(nullfd);
1674 write(daemon_filedes[1], &c, sizeof(char)); /* signal success */
1675 close(daemon_filedes[1]);
1677 #else
1678 /* defined(MS_WINDOWS) */
1679 void
1680 start_daemon(void)
1683 void
1684 finish_daemon(const char *cp)
1687 #endif
1689 /** Write the current process ID, followed by NL, into <b>filename</b>.
1691 void
1692 write_pidfile(char *filename)
1694 #ifndef MS_WINDOWS
1695 FILE *pidfile;
1697 if ((pidfile = fopen(filename, "w")) == NULL) {
1698 warn(LD_FS, "Unable to open \"%s\" for writing: %s", filename,
1699 strerror(errno));
1700 } else {
1701 fprintf(pidfile, "%d\n", (int)getpid());
1702 fclose(pidfile);
1704 #endif