1 /* Copyright 2003 Roger Dingledine */
2 /* See LICENSE for licensing information */
4 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.
36 #ifdef HAVE_NETINET_IN_H
37 #include <netinet/in.h>
39 #ifdef HAVE_ARPA_INET_H
40 #include <arpa/inet.h>
48 #ifdef HAVE_SYS_LIMITS_H
49 #include <sys/limits.h>
51 #ifdef HAVE_MACHINE_LIMITS_H
53 /* FreeBSD has a bug where it complains that this file is obsolete,
54 and I should migrate to using sys/limits. It complains even when
56 #include <machine/limits.h>
59 #ifdef HAVE_SYS_TYPES_H
60 #include <sys/types.h> /* Must be included before sys/stat.h for Ultrix */
62 #ifdef HAVE_SYS_SOCKET_H
63 #include <sys/socket.h>
65 #ifdef HAVE_SYS_TIME_H
71 #ifdef HAVE_SYS_STAT_H
74 #ifdef HAVE_SYS_FCNTL_H
75 #include <sys/fcntl.h>
94 #define dmalloc_strdup(file, line, string, xalloc_b) strdup(string)
96 #define dmalloc_malloc(file, line, size, func_id, alignment, xalloc_b) malloc(size)
97 #define DMALLOC_FUNC_MALLOC 0
99 #define dmalloc_realloc(file, line, old_pnt, new_size, func_id, xalloc_b) realloc((old_pnt), (new_size))
100 #define DMALLOC_FUNC_REALLOC 0
103 /** Allocate a chunk of <b>size</b> bytes of memory, and return a pointer to
104 * result. On error, log and terminate the process. (Same as malloc(size),
105 * but never returns NULL.)
107 * <b>file</b> and <b>line</b> are used if dmalloc is enabled, and
110 void *_tor_malloc(const char *file
, const int line
, size_t size
) {
113 /* Some libcs don't do the right thing on size==0. Override them. */
117 result
= dmalloc_malloc(file
, line
, size
, DMALLOC_FUNC_MALLOC
, 0, 0);
120 log_fn(LOG_ERR
, "Out of memory. Dying.");
121 /* XXX if these functions die within a worker process, they won't
125 // memset(result,'X',size); /* deadbeef to encourage bugs */
129 /* Allocate a chunk of <b>size</b> bytes of memory, fill the memory with
130 * zero bytes, and return a pointer to the result. Log and terminate
131 * the process on error. (Same as calloc(size,1), but never returns NULL.)
133 void *_tor_malloc_zero(const char *file
, const int line
, size_t size
) {
134 void *result
= _tor_malloc(file
, line
, size
);
135 memset(result
, 0, size
);
139 /** Change the size of the memory block pointed to by <b>ptr</b> to <b>size</b>
140 * bytes long; return the new memory block. On error, log and
141 * terminate. (Like realloc(ptr,size), but never returns NULL.)
143 void *_tor_realloc(const char *file
, const int line
, void *ptr
, size_t size
) {
146 result
= dmalloc_realloc(file
, line
, ptr
, size
, DMALLOC_FUNC_REALLOC
, 0);
148 log_fn(LOG_ERR
, "Out of memory. Dying.");
154 /** Return a newly allocated copy of the NUL-terminated string s. On
155 * error, log and terminate. (Like strdup(s), but never returns
158 char *_tor_strdup(const char *file
, const int line
, const char *s
) {
162 dup
= dmalloc_strdup(file
, line
, s
, 0);
164 log_fn(LOG_ERR
,"Out of memory. Dying.");
170 /** Allocate and return a new string containing the first <b>n</b>
171 * characters of <b>s</b>. If <b>s</b> is longer than <b>n</b>
172 * characters, only the first <b>n</b> are copied. The result is
173 * always NUL-terminated. (Like strndup(s,n), but never returns
176 char *_tor_strndup(const char *file
, const int line
, const char *s
, size_t n
) {
179 dup
= _tor_malloc(file
, line
, n
+1);
180 /* Performance note: Ordinarily we prefer strlcpy to strncpy. But
181 * this function gets called a whole lot, and platform strncpy is
182 * much faster than strlcpy when strlen(s) is much longer than n.
190 * String manipulation
193 /** Remove from the string <b>s</b> every character which appears in
194 * <b>strip</b>. Return the number of characters removed. */
195 int tor_strstrip(char *s
, const char *strip
)
199 if (strchr(strip
, *read
)) {
209 /** Set the <b>dest_len</b>-byte buffer <b>buf</b> to contain the
210 * string <b>s</b>, with the string <b>insert</b> inserted after every
211 * <b>n</b> characters. Return 0 on success, -1 on failure.
213 * If <b>rule</b> is ALWAYS_TERMINATE, then always end the string with
214 * <b>insert</b>, even if its length is not a multiple of <b>n</b>. If
215 * <b>rule</b> is NEVER_TERMINATE, then never end the string with
216 * <b>insert</b>, even if its length <i>is</i> a multiple of <b>n</b>.
217 * If <b>rule</b> is TERMINATE_IF_EVEN, then end the string with <b>insert</b>
218 * exactly when its length <i>is</i> a multiple of <b>n</b>.
220 int tor_strpartition(char *dest
, size_t dest_len
,
221 const char *s
, const char *insert
, size_t n
,
222 part_finish_rule_t rule
)
225 size_t len_in
, len_out
, len_ins
;
226 int is_even
, remaining
;
230 tor_assert(n
< SIZE_T_CEILING
);
231 tor_assert(dest_len
< SIZE_T_CEILING
);
233 len_ins
= strlen(insert
);
234 tor_assert(len_in
< SIZE_T_CEILING
);
235 tor_assert(len_in
/n
< SIZE_T_CEILING
/len_ins
); /* avoid overflow */
236 len_out
= len_in
+ (len_in
/n
)*len_ins
;
237 is_even
= (len_in
%n
) == 0;
240 case ALWAYS_TERMINATE
:
241 if (!is_even
) len_out
+= len_ins
;
243 case NEVER_TERMINATE
:
244 if (is_even
&& len_in
) len_out
-= len_ins
;
246 case TERMINATE_IF_EVEN
:
249 if (dest_len
< len_out
+1)
254 strncpy(destp
, s
, n
);
257 if (rule
== ALWAYS_TERMINATE
)
258 strcpy(destp
+n
+remaining
,insert
);
260 } else if (remaining
== 0 && rule
== NEVER_TERMINATE
) {
264 strcpy(destp
+n
, insert
);
268 tor_assert(len_out
== strlen(dest
));
272 /** Return a pointer to a NUL-terminated hexadecimal string encoding
273 * the first <b>fromlen</b> bytes of <b>from</b>. (fromlen must be \<= 32.) The
274 * result does not need to be deallocated, but repeated calls to
275 * hex_str will trash old results.
277 const char *hex_str(const char *from
, size_t fromlen
)
280 if (fromlen
>(sizeof(buf
)-1)/2)
281 fromlen
= (sizeof(buf
)-1)/2;
282 base16_encode(buf
,sizeof(buf
),from
,fromlen
);
286 /** Convert all alphabetic characters in the nul-terminated string <b>s</b> to
288 void tor_strlower(char *s
)
296 /* Compares the first strlen(s2) characters of s1 with s2. Returns as for
299 int strcmpstart(const char *s1
, const char *s2
)
301 size_t n
= strlen(s2
);
302 return strncmp(s1
, s2
, n
);
305 /* Compares the first strlen(s2) characters of s1 with s2. Returns as for
308 int strcasecmpstart(const char *s1
, const char *s2
)
310 size_t n
= strlen(s2
);
311 return strncasecmp(s1
, s2
, n
);
314 /* Compares the last strlen(s2) characters of s1 with s2. Returns as for
317 int strcmpend(const char *s1
, const char *s2
)
319 size_t n1
= strlen(s1
), n2
= strlen(s2
);
321 return strcmp(s1
,s2
);
323 return strncmp(s1
+(n1
-n2
), s2
, n2
);
326 /* Compares the last strlen(s2) characters of s1 with s2. Returns as for
329 int strcasecmpend(const char *s1
, const char *s2
)
331 size_t n1
= strlen(s1
), n2
= strlen(s2
);
332 if (n2
>n1
) /* then they can't be the same; figure out which is bigger */
333 return strcasecmp(s1
,s2
);
335 return strncasecmp(s1
+(n1
-n2
), s2
, n2
);
338 /** Return a pointer to the first char of s that is not whitespace and
339 * not a comment, or to the terminating NUL if no such character exists.
341 const char *eat_whitespace(const char *s
) {
344 while (TOR_ISSPACE(*s
) || *s
== '#') {
345 while (TOR_ISSPACE(*s
))
347 if (*s
== '#') { /* read to a \n or \0 */
348 while (*s
&& *s
!= '\n')
357 /** Return a pointer to the first char of s that is not a space or a tab,
358 * or to the terminating NUL if no such character exists. */
359 const char *eat_whitespace_no_nl(const char *s
) {
360 while (*s
== ' ' || *s
== '\t')
365 /** Return a pointer to the first char of s that is whitespace or <b>#</b>,
366 * or to the terminating NUL if no such character exists.
368 const char *find_whitespace(const char *s
) {
371 while (*s
&& !TOR_ISSPACE(*s
) && *s
!= '#')
377 #define CHECK_STRTOX_RESULT() \
378 /* Was at least one character converted? */ \
381 /* Were there unexpected unconverted characters? */ \
382 if (!next && *endptr) \
384 /* Is r within limits? */ \
385 if (r < min || r > max) \
388 if (next) *next = endptr; \
392 if (next) *next = endptr; \
395 /** Extract a long from the start of s, in the given numeric base. If
396 * there is unconverted data and next is provided, set *next to the
397 * first unconverted character. An error has occurred if no characters
398 * are converted; or if there are unconverted characters and next is NULL; or
399 * if the parsed value is not between min and max. When no error occurs,
400 * return the parsed value and set *ok (if provided) to 1. When an error
401 * occurs, return 0 and set *ok (if provided) to 0.
404 tor_parse_long(const char *s
, int base
, long min
, long max
,
405 int *ok
, char **next
)
410 r
= strtol(s
, &endptr
, base
);
411 CHECK_STRTOX_RESULT();
415 tor_parse_ulong(const char *s
, int base
, unsigned long min
,
416 unsigned long max
, int *ok
, char **next
)
421 r
= strtoul(s
, &endptr
, base
);
422 CHECK_STRTOX_RESULT();
425 /** Only base 10 is guaranteed to work for now. */
427 tor_parse_uint64(const char *s
, int base
, uint64_t min
,
428 uint64_t max
, int *ok
, char **next
)
434 r
= (uint64_t)strtoull(s
, &endptr
, base
);
435 #elif defined(MS_WINDOWS)
437 tor_assert(base
<= 10);
438 r
= (uint64_t)_atoi64(s
);
440 while (TOR_ISSPACE(*endptr
)) endptr
++;
441 while (TOR_ISDIGIT(*endptr
)) endptr
++;
443 r
= (uint64_t)_strtoui64(s
, &endptr
, base
);
445 #elif SIZEOF_LONG == 8
446 r
= (uint64_t)strtoul(s
, &endptr
, base
);
448 #error "I don't know how to parse 64-bit numbers."
451 CHECK_STRTOX_RESULT();
454 void base16_encode(char *dest
, size_t destlen
, const char *src
, size_t srclen
)
459 tor_assert(destlen
>= srclen
*2+1);
460 tor_assert(destlen
< SIZE_T_CEILING
);
465 sprintf(cp
,"%02X",*(const uint8_t*)src
);
472 static const char HEX_DIGITS
[] = "0123456789ABCDEFabcdef";
474 static INLINE
int hex_decode_digit(char c
)
478 cp
= strchr(HEX_DIGITS
, c
);
483 return n
; /* digit or uppercase */
485 return n
-6; /* lowercase */
488 int base16_decode(char *dest
, size_t destlen
, const char *src
, size_t srclen
)
492 if ((srclen
% 2) != 0)
494 if (destlen
< srclen
/2 || destlen
> SIZE_T_CEILING
)
498 v1
= hex_decode_digit(*src
);
499 v2
= hex_decode_digit(*(src
+1));
502 *(uint8_t*)dest
= (v1
<<4)|v2
;
513 /** Return the number of microseconds elapsed between *start and *end.
516 tv_udiff(struct timeval
*start
, struct timeval
*end
)
519 long secdiff
= end
->tv_sec
- start
->tv_sec
;
521 if (labs(secdiff
+1) > LONG_MAX
/1000000) {
522 log_fn(LOG_WARN
, "comparing times too far apart.");
526 udiff
= secdiff
*1000000L + (end
->tv_usec
- start
->tv_usec
);
530 /** Return -1 if *a \< *b, 0 if *a==*b, and 1 if *a \> *b.
532 int tv_cmp(struct timeval
*a
, struct timeval
*b
) {
533 if (a
->tv_sec
> b
->tv_sec
)
535 if (a
->tv_sec
< b
->tv_sec
)
537 if (a
->tv_usec
> b
->tv_usec
)
539 if (a
->tv_usec
< b
->tv_usec
)
544 /** Increment *a by the number of seconds and microseconds in *b.
546 void tv_add(struct timeval
*a
, struct timeval
*b
) {
547 a
->tv_usec
+= b
->tv_usec
;
548 a
->tv_sec
+= b
->tv_sec
+ (a
->tv_usec
/ 1000000);
549 a
->tv_usec
%= 1000000;
552 /** Increment *a by <b>ms</b> milliseconds.
554 void tv_addms(struct timeval
*a
, long ms
) {
555 a
->tv_usec
+= (ms
* 1000) % 1000000;
556 a
->tv_sec
+= ((ms
* 1000) / 1000000) + (a
->tv_usec
/ 1000000);
557 a
->tv_usec
%= 1000000;
560 #define IS_LEAPYEAR(y) (!(y % 4) && ((y % 100) || !(y % 400)))
561 static int n_leapdays(int y1
, int y2
) {
564 return (y2
/4 - y1
/4) - (y2
/100 - y1
/100) + (y2
/400 - y1
/400);
566 /** Number of days per month in non-leap year; used by tor_timegm. */
567 static const int days_per_month
[] =
568 { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
570 /** Return a time_t given a struct tm. The result is given in GMT, and
571 * does not account for leap seconds.
574 tor_timegm(struct tm
*tm
) {
575 /* This is a pretty ironclad timegm implementation, snarfed from Python2.2.
576 * It's way more brute-force than fiddling with tzset().
579 unsigned long year
, days
, hours
, minutes
;
581 year
= tm
->tm_year
+ 1900;
582 tor_assert(year
>= 1970);
583 tor_assert(tm
->tm_mon
>= 0);
584 tor_assert(tm
->tm_mon
<= 11);
585 days
= 365 * (year
-1970) + n_leapdays(1970,year
);
586 for (i
= 0; i
< tm
->tm_mon
; ++i
)
587 days
+= days_per_month
[i
];
588 if (tm
->tm_mon
> 1 && IS_LEAPYEAR(year
))
590 days
+= tm
->tm_mday
- 1;
591 hours
= days
*24 + tm
->tm_hour
;
593 minutes
= hours
*60 + tm
->tm_min
;
594 ret
= minutes
*60 + tm
->tm_sec
;
598 /* strftime is locale-specific, so we need to replace those parts */
599 static const char *WEEKDAY_NAMES
[] =
600 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
601 static const char *MONTH_NAMES
[] =
602 { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
603 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
605 void format_rfc1123_time(char *buf
, time_t t
) {
606 struct tm
*tm
= gmtime(&t
);
608 strftime(buf
, RFC1123_TIME_LEN
+1, "___, %d ___ %Y %H:%M:%S GMT", tm
);
609 tor_assert(tm
->tm_wday
>= 0);
610 tor_assert(tm
->tm_wday
<= 6);
611 memcpy(buf
, WEEKDAY_NAMES
[tm
->tm_wday
], 3);
612 tor_assert(tm
->tm_wday
>= 0);
613 tor_assert(tm
->tm_mon
<= 11);
614 memcpy(buf
+8, MONTH_NAMES
[tm
->tm_mon
], 3);
617 int parse_rfc1123_time(const char *buf
, time_t *t
) {
623 if (strlen(buf
) != RFC1123_TIME_LEN
)
625 memset(&tm
, 0, sizeof(tm
));
626 if (sscanf(buf
, "%3s, %d %3s %d %d:%d:%d GMT", weekday
,
627 &tm
.tm_mday
, month
, &tm
.tm_year
, &tm
.tm_hour
,
628 &tm
.tm_min
, &tm
.tm_sec
) < 7) {
629 log_fn(LOG_WARN
, "Got invalid RFC1123 time \"%s\"", buf
);
634 for (i
= 0; i
< 12; ++i
) {
635 if (!strcmp(month
, MONTH_NAMES
[i
])) {
641 log_fn(LOG_WARN
, "Got invalid RFC1123 time \"%s\"", buf
);
647 *t
= tor_timegm(&tm
);
651 void format_local_iso_time(char *buf
, time_t t
) {
652 strftime(buf
, ISO_TIME_LEN
+1, "%Y-%m-%d %H:%M:%S", localtime(&t
));
655 void format_iso_time(char *buf
, time_t t
) {
656 strftime(buf
, ISO_TIME_LEN
+1, "%Y-%m-%d %H:%M:%S", gmtime(&t
));
659 int parse_iso_time(const char *cp
, time_t *t
) {
662 if (!strptime(cp
, "%Y-%m-%d %H:%M:%S", &st_tm
)) {
663 log_fn(LOG_WARN
, "Published time was unparseable"); return -1;
666 unsigned int year
=0, month
=0, day
=0, hour
=100, minute
=100, second
=100;
667 if (sscanf(cp
, "%u-%u-%u %u:%u:%u", &year
, &month
,
668 &day
, &hour
, &minute
, &second
) < 6) {
669 log_fn(LOG_WARN
, "Published time was unparseable"); return -1;
671 if (year
< 1970 || month
< 1 || month
> 12 || day
< 1 || day
> 31 ||
672 hour
> 23 || minute
> 59 || second
> 61) {
673 log_fn(LOG_WARN
, "Published time was nonsensical"); return -1;
675 st_tm
.tm_year
= year
-1900;
676 st_tm
.tm_mon
= month
-1;
678 st_tm
.tm_hour
= hour
;
679 st_tm
.tm_min
= minute
;
680 st_tm
.tm_sec
= second
;
682 *t
= tor_timegm(&st_tm
);
690 /** Write <b>count</b> bytes from <b>buf</b> to <b>fd</b>. <b>isSocket</b>
691 * must be 1 if fd was returned by socket() or accept(), and 0 if fd
692 * was returned by open(). Return the number of bytes written, or -1
693 * on error. Only use if fd is a blocking fd. */
694 int write_all(int fd
, const char *buf
, size_t count
, int isSocket
) {
698 while (written
!= count
) {
700 result
= send(fd
, buf
+written
, count
-written
, 0);
702 result
= write(fd
, buf
+written
, count
-written
);
710 /** Read from <b>fd</b> to <b>buf</b>, until we get <b>count</b> bytes
711 * or reach the end of the file. <b>isSocket</b> must be 1 if fd
712 * was returned by socket() or accept(), and 0 if fd was returned by
713 * open(). Return the number of bytes read, or -1 on error. Only use
714 * if fd is a blocking fd. */
715 int read_all(int fd
, char *buf
, size_t count
, int isSocket
) {
719 if (count
> SIZE_T_CEILING
)
722 while (numread
!= count
) {
724 result
= recv(fd
, buf
+numread
, count
-numread
, 0);
726 result
= read(fd
, buf
+numread
, count
-numread
);
729 else if (result
== 0)
737 * Filesystem operations.
740 /** Return FN_ERROR if filename can't be read, FN_NOENT if it doesn't
741 * exist, FN_FILE if it is a regular file, or FN_DIR if it's a
743 file_status_t
file_status(const char *fname
)
746 if (stat(fname
, &st
)) {
747 if (errno
== ENOENT
) {
752 if (st
.st_mode
& S_IFDIR
)
754 else if (st
.st_mode
& S_IFREG
)
760 /** Check whether dirname exists and is private. If yes return 0. If
761 * it does not exist, and check==CPD_CREATE is set, try to create it
762 * and return 0 on success. If it does not exist, and
763 * check==CPD_CHECK, and we think we can create it, return 0. Else
765 int check_private_dir(const char *dirname
, cpd_check_t check
)
770 if (stat(dirname
, &st
)) {
771 if (errno
!= ENOENT
) {
772 log(LOG_WARN
, "Directory %s cannot be read: %s", dirname
,
776 if (check
== CPD_NONE
) {
777 log(LOG_WARN
, "Directory %s does not exist.", dirname
);
779 } else if (check
== CPD_CREATE
) {
780 log(LOG_INFO
, "Creating directory %s", dirname
);
784 r
= mkdir(dirname
, 0700);
787 log(LOG_WARN
, "Error creating directory %s: %s", dirname
,
792 /* XXXX In the case where check==CPD_CHECK, we should look at the
793 * parent directory a little harder. */
796 if (!(st
.st_mode
& S_IFDIR
)) {
797 log(LOG_WARN
, "%s is not a directory", dirname
);
801 if (st
.st_uid
!= getuid()) {
802 log(LOG_WARN
, "%s is not owned by this UID (%d). You must fix this to proceed.", dirname
, (int)getuid());
805 if (st
.st_mode
& 0077) {
806 log(LOG_WARN
, "Fixing permissions on directory %s", dirname
);
807 if (chmod(dirname
, 0700)) {
808 log(LOG_WARN
, "Could not chmod directory %s: %s", dirname
,
819 /** Create a file named <b>fname</b> with the contents <b>str</b>. Overwrite the
820 * previous <b>fname</b> if possible. Return 0 on success, -1 on failure.
822 * This function replaces the old file atomically, if possible.
825 write_str_to_file(const char *fname
, const char *str
, int bin
)
828 if (!bin
&& strchr(str
, '\r')) {
830 "How odd. Writing a string that does contain CR already.");
833 return write_bytes_to_file(fname
, str
, strlen(str
), bin
);
836 /** As write_str_to_file, but does not assume a NUL-terminated *
837 * string. Instead, we write <b>len</b> bytes, starting at <b>str</b>. */
838 int write_bytes_to_file(const char *fname
, const char *str
, size_t len
,
844 if ((strlcpy(tempname
,fname
,1024) >= 1024) ||
845 (strlcat(tempname
,".tmp",1024) >= 1024)) {
846 log(LOG_WARN
, "Filename %s.tmp too long (>1024 chars)", fname
);
849 if ((fd
= open(tempname
, O_WRONLY
|O_CREAT
|O_TRUNC
|(bin
?O_BINARY
:O_TEXT
), 0600))
851 log(LOG_WARN
, "Couldn't open %s for writing: %s", tempname
,
855 result
= write_all(fd
, str
, len
, 0);
856 if (result
< 0 || (size_t)result
!= len
) {
857 log(LOG_WARN
, "Error writing to %s: %s", tempname
, strerror(errno
));
862 log(LOG_WARN
,"Error flushing to %s: %s", tempname
, strerror(errno
));
865 if (replace_file(tempname
, fname
)) {
866 log(LOG_WARN
, "Error replacing %s: %s", fname
, strerror(errno
));
872 /** Read the contents of <b>filename</b> into a newly allocated string; return the
873 * string on success or NULL on failure.
875 char *read_file_to_str(const char *filename
, int bin
) {
876 int fd
; /* router file */
881 tor_assert(filename
);
883 if (stat(filename
, &statbuf
) < 0) {
884 log_fn(LOG_INFO
,"Could not stat %s.",filename
);
888 fd
= open(filename
,O_RDONLY
|(bin
?O_BINARY
:O_TEXT
),0);
890 log_fn(LOG_WARN
,"Could not open %s.",filename
);
894 string
= tor_malloc(statbuf
.st_size
+1);
896 r
= read_all(fd
,string
,statbuf
.st_size
,0);
898 log_fn(LOG_WARN
,"Error reading from file '%s': %s", filename
,
904 string
[r
] = '\0'; /* NUL-terminate the result. */
906 if (bin
&& r
!= statbuf
.st_size
) {
907 /* If we're in binary mode, then we'd better have an exact match for
908 * size. Otherwise, win32 encoding may throw us off, and that's okay. */
909 log_fn(LOG_WARN
,"Could read only %d of %ld bytes of file '%s'.",
910 r
, (long)statbuf
.st_size
,filename
);
916 if (!bin
&& strchr(string
, '\r')) {
917 log_fn(LOG_DEBUG
, "We didn't convert CRLF to LF as well as we hoped when reading %s. Coping.",
919 tor_strstrip(string
, "\r");
927 /** Given a string containing part of a configuration file or similar format,
928 * advance past comments and whitespace and try to parse a single line. If we
929 * parse a line successfully, set *<b>key_out</b> to the key portion and
930 * *<b>value_out</b> to the value portion of the line, and return a pointer to
931 * the start of the next line. If we run out of data, return a pointer to the
932 * end of the string. If we encounter an error, return NULL.
934 * NOTE: We modify <b>line</b> as we parse it, by inserting NULs to terminate
938 parse_line_from_str(char *line
, char **key_out
, char **value_out
)
940 char *key
, *val
, *cp
;
943 tor_assert(value_out
);
945 *key_out
= *value_out
= key
= val
= NULL
;
946 /* Skip until the first keyword. */
948 while (TOR_ISSPACE(*line
))
951 while (*line
&& *line
!= '\n')
958 if (!*line
) { /* End of string? */
959 *key_out
= *value_out
= NULL
;
963 /* Skip until the next space. */
965 while (*line
&& !TOR_ISSPACE(*line
) && *line
!= '#')
968 /* Skip until the value */
969 while (*line
== ' ' || *line
== '\t')
973 /* Find the end of the line. */
974 while (*line
&& *line
!= '\n' && *line
!= '#')
981 while (cp
>=val
&& TOR_ISSPACE(*cp
))
987 } while (*line
&& *line
!= '\n');
998 /** Expand any homedir prefix on 'filename'; return a newly allocated
1000 char *expand_filename(const char *filename
)
1002 tor_assert(filename
);
1003 if (*filename
== '~') {
1005 char *home
, *result
;
1008 if (filename
[1] == '/' || filename
[1] == '\0') {
1009 home
= getenv("HOME");
1011 log_fn(LOG_WARN
, "Couldn't find $HOME environment variable while expanding %s", filename
);
1014 home
= tor_strdup(home
);
1015 rest
= strlen(filename
)>=2?(filename
+2):NULL
;
1018 char *username
, *slash
;
1019 slash
= strchr(filename
, '/');
1021 username
= tor_strndup(filename
+1,slash
-filename
-1);
1023 username
= tor_strdup(filename
+1);
1024 if (!(home
= get_user_homedir(username
))) {
1025 log_fn(LOG_WARN
,"Couldn't get homedir for %s",username
);
1030 rest
= slash
? (slash
+1) : NULL
;
1032 log_fn(LOG_WARN
, "Couldn't expend homedir on system without pwd.h");
1033 return tor_strdup(filename
);
1037 /* Remove trailing slash. */
1038 if (strlen(home
)>1 && !strcmpend(home
,"/")) {
1039 home
[strlen(home
)-1] = '\0';
1041 /* Plus one for /, plus one for NUL.
1042 * Round up to 16 in case we can't do math. */
1043 len
= strlen(home
)+strlen(rest
)+16;
1044 result
= tor_malloc(len
);
1045 tor_snprintf(result
,len
,"%s/%s",home
,rest
?rest
:"");
1049 return tor_strdup(filename
);
1057 /** Return true iff <b>ip</b> (in host order) is an IP reserved to localhost,
1058 * or reserved for local networks by RFC 1918.
1060 int is_internal_IP(uint32_t ip
) {
1062 if (((ip
& 0xff000000) == 0x0a000000) || /* 10/8 */
1063 ((ip
& 0xff000000) == 0x00000000) || /* 0/8 */
1064 ((ip
& 0xff000000) == 0x7f000000) || /* 127/8 */
1065 ((ip
& 0xffff0000) == 0xa9fe0000) || /* 169.254/16 */
1066 ((ip
& 0xfff00000) == 0xac100000) || /* 172.16/12 */
1067 ((ip
& 0xffff0000) == 0xc0a80000)) /* 192.168/16 */
1072 /** Return true iff <b>ip</b> (in host order) is judged to be on the
1073 * same network as us. For now, check if it's an internal IP.
1075 * XXX Also check if it's on the same class C network as our public IP.
1077 int is_local_IP(uint32_t ip
) {
1078 return is_internal_IP(ip
);
1081 /** Parse a string of the form "host[:port]" from <b>addrport</b>. If
1082 * <b>address</b> is provided, set *<b>address</b> to a copy of the
1083 * host portion of the string. If <b>addr</b> is provided, try to
1084 * resolve the host portion of the string and store it into
1085 * *<b>addr</b> (in host byte order). If <b>port</b> is provided,
1086 * store the port number into *<b>port</b>, or 0 if no port is given.
1087 * Return 0 on success, -1 on failure.
1090 parse_addr_port(const char *addrport
, char **address
, uint32_t *addr
,
1094 char *_address
= NULL
;
1098 tor_assert(addrport
);
1101 colon
= strchr(addrport
, ':');
1103 _address
= tor_strndup(addrport
, colon
-addrport
);
1104 _port
= (int) tor_parse_long(colon
+1,10,1,65535,NULL
,NULL
);
1106 log_fn(LOG_WARN
, "Port '%s' out of range", colon
+1);
1110 _address
= tor_strdup(addrport
);
1115 /* There's an addr pointer, so we need to resolve the hostname. */
1116 if (tor_lookup_hostname(_address
,addr
)) {
1117 log_fn(LOG_WARN
, "Couldn't look up '%s'", _address
);
1121 *addr
= ntohl(*addr
);
1124 if (address
&& ok
) {
1125 *address
= _address
;
1132 *port
= ok
? ((uint16_t) _port
) : 0;
1137 /** Parse a string <b>s</b> in the format of
1138 * (IP(/mask|/mask-bits)?|*):(*|port(-maxport)?), setting the various
1139 * *out pointers as appropriate. Return 0 on success, -1 on failure.
1142 parse_addr_and_port_range(const char *s
, uint32_t *addr_out
,
1143 uint32_t *mask_out
, uint16_t *port_min_out
,
1144 uint16_t *port_max_out
)
1147 char *mask
, *port
, *endptr
;
1152 tor_assert(addr_out
);
1153 tor_assert(mask_out
);
1154 tor_assert(port_min_out
);
1155 tor_assert(port_max_out
);
1157 address
= tor_strdup(s
);
1158 /* Break 'address' into separate strings.
1160 mask
= strchr(address
,'/');
1161 port
= strchr(mask
?mask
:address
,':');
1166 /* Now "address" is the IP|'*' part...
1167 * "mask" is the Mask|Maskbits part...
1168 * and "port" is the *|port|min-max part.
1171 if (strcmp(address
,"*")==0) {
1173 } else if (tor_inet_aton(address
, &in
) != 0) {
1174 *addr_out
= ntohl(in
.s_addr
);
1176 log_fn(LOG_WARN
, "Malformed IP %s in address pattern; rejecting.",address
);
1181 if (strcmp(address
,"*")==0)
1184 *mask_out
= 0xFFFFFFFFu
;
1187 bits
= (int) strtol(mask
, &endptr
, 10);
1189 /* strtol handled the whole mask. */
1190 if (bits
< 0 || bits
> 32) {
1191 log_fn(LOG_WARN
, "Bad number of mask bits on address range; rejecting.");
1194 *mask_out
= ~((1<<(32-bits
))-1);
1195 } else if (tor_inet_aton(mask
, &in
) != 0) {
1196 *mask_out
= ntohl(in
.s_addr
);
1198 log_fn(LOG_WARN
, "Malformed mask %s on address range; rejecting.",
1204 if (!port
|| strcmp(port
, "*") == 0) {
1206 *port_max_out
= 65535;
1209 *port_min_out
= (uint16_t) tor_parse_long(port
, 10, 1, 65535,
1211 if (*endptr
== '-') {
1214 *port_max_out
= (uint16_t) tor_parse_long(port
, 10, 1, 65535, NULL
,
1216 if (*endptr
|| !*port_max_out
) {
1217 log_fn(LOG_WARN
, "Malformed port %s on address range rejecting.",
1220 } else if (*endptr
|| !*port_min_out
) {
1221 log_fn(LOG_WARN
, "Malformed port %s on address range; rejecting.",
1225 *port_max_out
= *port_min_out
;
1227 if (*port_min_out
> *port_max_out
) {
1228 log_fn(LOG_WARN
,"Insane port range on address policy; rejecting.");
1245 /* Based on code contributed by christian grothoff */
1246 static int start_daemon_called
= 0;
1247 static int finish_daemon_called
= 0;
1248 static int daemon_filedes
[2];
1249 /** Start putting the process into daemon mode: fork and drop all resources
1250 * except standard fds. The parent process never returns, but stays around
1251 * until finish_daemon is called. (Note: it's safe to call this more
1252 * than once: calls after the first are ignored.)
1254 void start_daemon(const char *desired_cwd
)
1258 if (start_daemon_called
)
1260 start_daemon_called
= 1;
1264 /* Don't hold the wrong FS mounted */
1265 if (chdir(desired_cwd
) < 0) {
1266 log_fn(LOG_ERR
,"chdir to %s failed. Exiting.",desired_cwd
);
1270 pipe(daemon_filedes
);
1273 log_fn(LOG_ERR
,"fork failed. Exiting.");
1276 if (pid
) { /* Parent */
1280 close(daemon_filedes
[1]); /* we only read */
1282 while (0 < read(daemon_filedes
[0], &c
, sizeof(char))) {
1290 exit(1); /* child reported error */
1291 } else { /* Child */
1292 close(daemon_filedes
[0]); /* we only write */
1294 pid
= setsid(); /* Detach from controlling terminal */
1296 * Fork one more time, so the parent (the session group leader) can exit.
1297 * This means that we, as a non-session group leader, can never regain a
1298 * controlling terminal. This part is recommended by Stevens's
1299 * _Advanced Programming in the Unix Environment_.
1308 /** Finish putting the process into daemon mode: drop standard fds, and tell
1309 * the parent process to exit. (Note: it's safe to call this more than once:
1310 * calls after the first are ignored. Calls start_daemon first if it hasn't
1311 * been called already.)
1313 void finish_daemon(void)
1317 if (finish_daemon_called
)
1319 if (!start_daemon_called
)
1321 finish_daemon_called
= 1;
1323 nullfd
= open("/dev/null",
1324 O_CREAT
| O_RDWR
| O_APPEND
);
1326 log_fn(LOG_ERR
,"/dev/null can't be opened. Exiting.");
1329 /* close fds linking to invoking terminal, but
1330 * close usual incoming fds, but redirect them somewhere
1331 * useful so the fds don't get reallocated elsewhere.
1333 if (dup2(nullfd
,0) < 0 ||
1334 dup2(nullfd
,1) < 0 ||
1335 dup2(nullfd
,2) < 0) {
1336 log_fn(LOG_ERR
,"dup2 failed. Exiting.");
1339 write(daemon_filedes
[1], &c
, sizeof(char)); /* signal success */
1340 close(daemon_filedes
[1]);
1343 /* defined(MS_WINDOWS) */
1344 void start_daemon(const char *cp
) {}
1345 void finish_daemon(void) {}
1348 /** Write the current process ID, followed by NL, into <b>filename</b>.
1350 void write_pidfile(char *filename
) {
1354 if ((pidfile
= fopen(filename
, "w")) == NULL
) {
1355 log_fn(LOG_WARN
, "Unable to open %s for writing: %s", filename
,
1358 fprintf(pidfile
, "%d\n", (int)getpid());