Fix two compile-blockers in tor_vasprintf().
[tor.git] / src / common / compat.c
blob0fb169b7347793b016027652091473c7f5cf7317
1 /* Copyright (c) 2003-2004, Roger Dingledine
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2010, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
6 /**
7 * \file compat.c
8 * \brief Wrappers to make calls more portable. This code defines
9 * functions such as tor_malloc, tor_snprintf, get/set various data types,
10 * renaming, setting socket options, switching user IDs. It is basically
11 * where the non-portable items are conditionally included depending on
12 * the platform.
13 **/
15 /* This is required on rh7 to make strptime not complain.
16 * We also need it to make memmem get defined (where available)
18 #define _GNU_SOURCE
20 #include "compat.h"
22 #ifdef MS_WINDOWS
23 #include <process.h>
24 #include <windows.h>
25 #include <sys/locking.h>
26 #endif
28 #ifdef HAVE_UNAME
29 #include <sys/utsname.h>
30 #endif
31 #ifdef HAVE_UNISTD_H
32 #include <unistd.h>
33 #endif
34 #ifdef HAVE_SYS_FCNTL_H
35 #include <sys/fcntl.h>
36 #endif
37 #ifdef HAVE_PWD_H
38 #include <pwd.h>
39 #endif
40 #ifdef HAVE_GRP_H
41 #include <grp.h>
42 #endif
43 #ifdef HAVE_FCNTL_H
44 #include <fcntl.h>
45 #endif
46 #ifdef HAVE_ERRNO_H
47 #include <errno.h>
48 #endif
49 #ifdef HAVE_ARPA_INET_H
50 #include <arpa/inet.h>
51 #endif
53 #ifndef HAVE_GETTIMEOFDAY
54 #ifdef HAVE_FTIME
55 #include <sys/timeb.h>
56 #endif
57 #endif
59 #ifdef HAVE_NETDB_H
60 #include <netdb.h>
61 #endif
62 #ifdef HAVE_SYS_PARAM_H
63 #include <sys/param.h> /* FreeBSD needs this to know what version it is */
64 #endif
65 #include <stdio.h>
66 #include <stdlib.h>
67 #include <assert.h>
68 #ifdef HAVE_SIGNAL_H
69 #include <signal.h>
70 #endif
71 #ifdef HAVE_UTIME_H
72 #include <utime.h>
73 #endif
74 #ifdef HAVE_SYS_UTIME_H
75 #include <sys/utime.h>
76 #endif
77 #ifdef HAVE_SYS_MMAN_H
78 #include <sys/mman.h>
79 #endif
80 #ifdef HAVE_SYS_SYSLIMITS_H
81 #include <sys/syslimits.h>
82 #endif
83 #ifdef HAVE_SYS_FILE_H
84 #include <sys/file.h>
85 #endif
86 #if defined(HAVE_SYS_PRCTL_H) && defined(__linux__)
87 /* Only use the linux prctl; the IRIX prctl is totally different */
88 #include <sys/prctl.h>
89 #endif
91 #include "log.h"
92 #include "util.h"
93 #include "container.h"
94 #include "address.h"
96 /* Inline the strl functions if the platform doesn't have them. */
97 #ifndef HAVE_STRLCPY
98 #include "strlcpy.c"
99 #endif
100 #ifndef HAVE_STRLCAT
101 #include "strlcat.c"
102 #endif
104 #ifdef HAVE_SYS_MMAN_H
105 /** Try to create a memory mapping for <b>filename</b> and return it. On
106 * failure, return NULL. Sets errno properly, using ERANGE to mean
107 * "empty file". */
108 tor_mmap_t *
109 tor_mmap_file(const char *filename)
111 int fd; /* router file */
112 char *string;
113 int page_size;
114 tor_mmap_t *res;
115 size_t size, filesize;
117 tor_assert(filename);
119 fd = open(filename, O_RDONLY, 0);
120 if (fd<0) {
121 int save_errno = errno;
122 int severity = (errno == ENOENT) ? LOG_INFO : LOG_WARN;
123 log_fn(severity, LD_FS,"Could not open \"%s\" for mmap(): %s",filename,
124 strerror(errno));
125 errno = save_errno;
126 return NULL;
129 size = filesize = (size_t) lseek(fd, 0, SEEK_END);
130 lseek(fd, 0, SEEK_SET);
131 /* ensure page alignment */
132 page_size = getpagesize();
133 size += (size%page_size) ? page_size-(size%page_size) : 0;
135 if (!size) {
136 /* Zero-length file. If we call mmap on it, it will succeed but
137 * return NULL, and bad things will happen. So just fail. */
138 log_info(LD_FS,"File \"%s\" is empty. Ignoring.",filename);
139 errno = ERANGE;
140 close(fd);
141 return NULL;
144 string = mmap(0, size, PROT_READ, MAP_PRIVATE, fd, 0);
145 close(fd);
146 if (string == MAP_FAILED) {
147 int save_errno = errno;
148 log_warn(LD_FS,"Could not mmap file \"%s\": %s", filename,
149 strerror(errno));
150 errno = save_errno;
151 return NULL;
154 res = tor_malloc_zero(sizeof(tor_mmap_t));
155 res->data = string;
156 res->size = filesize;
157 res->mapping_size = size;
159 return res;
161 /** Release storage held for a memory mapping. */
162 void
163 tor_munmap_file(tor_mmap_t *handle)
165 munmap((char*)handle->data, handle->mapping_size);
166 tor_free(handle);
168 #elif defined(MS_WINDOWS)
169 tor_mmap_t *
170 tor_mmap_file(const char *filename)
172 tor_mmap_t *res = tor_malloc_zero(sizeof(tor_mmap_t));
173 int empty = 0;
174 res->file_handle = INVALID_HANDLE_VALUE;
175 res->mmap_handle = NULL;
177 res->file_handle = CreateFile(filename,
178 GENERIC_READ, FILE_SHARE_READ,
179 NULL,
180 OPEN_EXISTING,
181 FILE_ATTRIBUTE_NORMAL,
184 if (res->file_handle == INVALID_HANDLE_VALUE)
185 goto win_err;
187 res->size = GetFileSize(res->file_handle, NULL);
189 if (res->size == 0) {
190 log_info(LD_FS,"File \"%s\" is empty. Ignoring.",filename);
191 empty = 1;
192 goto err;
195 res->mmap_handle = CreateFileMapping(res->file_handle,
196 NULL,
197 PAGE_READONLY,
198 #if SIZEOF_SIZE_T > 4
199 (res->base.size >> 32),
200 #else
202 #endif
203 (res->size & 0xfffffffful),
204 NULL);
205 if (res->mmap_handle == NULL)
206 goto win_err;
207 res->data = (char*) MapViewOfFile(res->mmap_handle,
208 FILE_MAP_READ,
209 0, 0, 0);
210 if (!res->data)
211 goto win_err;
213 return res;
214 win_err: {
215 DWORD e = GetLastError();
216 int severity = (e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND) ?
217 LOG_INFO : LOG_WARN;
218 char *msg = format_win32_error(e);
219 log_fn(severity, LD_FS, "Couldn't mmap file \"%s\": %s", filename, msg);
220 tor_free(msg);
221 if (e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND)
222 errno = ENOENT;
223 else
224 errno = EINVAL;
226 err:
227 if (empty)
228 errno = ERANGE;
229 tor_munmap_file(res);
230 return NULL;
232 void
233 tor_munmap_file(tor_mmap_t *handle)
235 if (handle->data)
236 /* This is an ugly cast, but without it, "data" in struct tor_mmap_t would
237 have to be redefined as non-const. */
238 UnmapViewOfFile( (LPVOID) handle->data);
240 if (handle->mmap_handle != NULL)
241 CloseHandle(handle->mmap_handle);
242 if (handle->file_handle != INVALID_HANDLE_VALUE)
243 CloseHandle(handle->file_handle);
244 tor_free(handle);
246 #else
247 tor_mmap_t *
248 tor_mmap_file(const char *filename)
250 struct stat st;
251 char *res = read_file_to_str(filename, RFTS_BIN|RFTS_IGNORE_MISSING, &st);
252 tor_mmap_t *handle;
253 if (! res)
254 return NULL;
255 handle = tor_malloc_zero(sizeof(tor_mmap_t));
256 handle->data = res;
257 handle->size = st.st_size;
258 return handle;
260 void
261 tor_munmap_file(tor_mmap_t *handle)
263 char *d = (char*)handle->data;
264 tor_free(d);
265 memset(handle, 0, sizeof(tor_mmap_t));
266 tor_free(handle);
268 #endif
270 /** Replacement for snprintf. Differs from platform snprintf in two
271 * ways: First, always NUL-terminates its output. Second, always
272 * returns -1 if the result is truncated. (Note that this return
273 * behavior does <i>not</i> conform to C99; it just happens to be
274 * easier to emulate "return -1" with conformant implementations than
275 * it is to emulate "return number that would be written" with
276 * non-conformant implementations.) */
278 tor_snprintf(char *str, size_t size, const char *format, ...)
280 va_list ap;
281 int r;
282 va_start(ap,format);
283 r = tor_vsnprintf(str,size,format,ap);
284 va_end(ap);
285 return r;
288 /** Replacement for vsnprintf; behavior differs as tor_snprintf differs from
289 * snprintf.
292 tor_vsnprintf(char *str, size_t size, const char *format, va_list args)
294 int r;
295 if (size == 0)
296 return -1; /* no place for the NUL */
297 if (size > SSIZE_T_MAX-16)
298 return -1;
299 #ifdef MS_WINDOWS
300 r = _vsnprintf(str, size, format, args);
301 #else
302 r = vsnprintf(str, size, format, args);
303 #endif
304 str[size-1] = '\0';
305 if (r < 0 || r >= (ssize_t)size)
306 return -1;
307 return r;
311 * Portable asprintf implementation. Does a printf() into a newly malloc'd
312 * string. Sets *<b>strp</b> to this string, and returns its length (not
313 * including the terminating NUL character).
315 * You can treat this function as if its implementation were something like
316 <pre>
317 char buf[_INFINITY_];
318 tor_snprintf(buf, sizeof(buf), fmt, args);
319 *strp = tor_strdup(buf);
320 return strlen(*strp):
321 </pre>
322 * Where _INFINITY_ is an imaginary constant so big that any string can fit
323 * into it.
326 tor_asprintf(char **strp, const char *fmt, ...)
328 int r;
329 va_list args;
330 va_start(args, fmt);
331 r = tor_vasprintf(strp, fmt, args);
332 va_end(args);
333 if (!*strp || r < 0) {
334 log_err(LD_BUG, "Internal error in asprintf");
335 tor_assert(0);
337 return r;
341 * Portable vasprintf implementation. Does a printf() into a newly malloc'd
342 * string. Differs from regular vasprintf in the same ways that
343 * tor_asprintf() differs from regular asprintf.
346 tor_vasprintf(char **strp, const char *fmt, va_list args)
348 /* use a temporary variable in case *strp is in args. */
349 char *strp_tmp=NULL;
350 #ifdef HAVE_VASPRINTF
351 /* If the platform gives us one, use it. */
352 int r = vasprintf(&strp_tmp, fmt, args);
353 if (r < 0)
354 *strp = NULL;
355 else
356 *strp = strp_tmp;
357 return r;
358 #elif defined(_MSC_VER)
359 /* On Windows, _vsnprintf won't tell us the length of the string if it
360 * overflows, so we need to use _vcsprintf to tell how much to allocate */
361 int len, r;
362 char *res;
363 len = _vscprintf(fmt, args);
364 if (len < 0) {
365 *strp = NULL;
366 return -1;
368 strp_tmp = tor_malloc(len + 1);
369 r = _vsnprintf(strp_tmp, len+1, fmt, args);
370 if (r != len) {
371 tor_free(strp_tmp);
372 *strp = NULL;
373 return -1;
375 *strp = strp_tmp;
376 return len;
377 #else
378 /* Everywhere else, we have a decent vsnprintf that tells us how many
379 * characters we need. We give it a try on a short buffer first, since
380 * it might be nice to avoid the second vsnprintf call.
382 char buf[128];
383 int len, r;
384 va_list tmp_args;
385 va_copy(tmp_args, args);
386 len = vsnprintf(buf, sizeof(buf), fmt, tmp_args);
387 va_end(tmp_args);
388 if (len < (int)sizeof(buf)) {
389 *strp = tor_strdup(buf);
390 return len;
392 strp_tmp = tor_malloc(len+1);
393 r = vsnprintf(strp_tmp, len+1, fmt, args);
394 if (r != len) {
395 tor_free(strp_tmp);
396 *strp = NULL;
397 return -1;
399 *strp = strp_tmp;
400 return len;
401 #endif
404 /** Given <b>hlen</b> bytes at <b>haystack</b> and <b>nlen</b> bytes at
405 * <b>needle</b>, return a pointer to the first occurrence of the needle
406 * within the haystack, or NULL if there is no such occurrence.
408 * Requires that nlen be greater than zero.
410 const void *
411 tor_memmem(const void *_haystack, size_t hlen,
412 const void *_needle, size_t nlen)
414 #if defined(HAVE_MEMMEM) && (!defined(__GNUC__) || __GNUC__ >= 2)
415 tor_assert(nlen);
416 return memmem(_haystack, hlen, _needle, nlen);
417 #else
418 /* This isn't as fast as the GLIBC implementation, but it doesn't need to
419 * be. */
420 const char *p, *end;
421 const char *haystack = (const char*)_haystack;
422 const char *needle = (const char*)_needle;
423 char first;
424 tor_assert(nlen);
426 p = haystack;
427 end = haystack + hlen;
428 first = *(const char*)needle;
429 while ((p = memchr(p, first, end-p))) {
430 if (p+nlen > end)
431 return NULL;
432 if (!memcmp(p, needle, nlen))
433 return p;
434 ++p;
436 return NULL;
437 #endif
440 /* Tables to implement ctypes-replacement TOR_IS*() functions. Each table
441 * has 256 bits to look up whether a character is in some set or not. This
442 * fails on non-ASCII platforms, but it is hard to find a platform whose
443 * character set is not a superset of ASCII nowadays. */
444 const uint32_t TOR_ISALPHA_TABLE[8] =
445 { 0, 0, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
446 const uint32_t TOR_ISALNUM_TABLE[8] =
447 { 0, 0x3ff0000, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
448 const uint32_t TOR_ISSPACE_TABLE[8] = { 0x3e00, 0x1, 0, 0, 0, 0, 0, 0 };
449 const uint32_t TOR_ISXDIGIT_TABLE[8] =
450 { 0, 0x3ff0000, 0x7e, 0x7e, 0, 0, 0, 0 };
451 const uint32_t TOR_ISDIGIT_TABLE[8] = { 0, 0x3ff0000, 0, 0, 0, 0, 0, 0 };
452 const uint32_t TOR_ISPRINT_TABLE[8] =
453 { 0, 0xffffffff, 0xffffffff, 0x7fffffff, 0, 0, 0, 0x0 };
454 const uint32_t TOR_ISUPPER_TABLE[8] = { 0, 0, 0x7fffffe, 0, 0, 0, 0, 0 };
455 const uint32_t TOR_ISLOWER_TABLE[8] = { 0, 0, 0, 0x7fffffe, 0, 0, 0, 0 };
456 /* Upper-casing and lowercasing tables to map characters to upper/lowercase
457 * equivalents. */
458 const char TOR_TOUPPER_TABLE[256] = {
459 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
460 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
461 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
462 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
463 64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
464 80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
465 96,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
466 80,81,82,83,84,85,86,87,88,89,90,123,124,125,126,127,
467 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
468 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
469 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
470 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
471 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
472 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
473 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
474 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
476 const char TOR_TOLOWER_TABLE[256] = {
477 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
478 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
479 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
480 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
481 64,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
482 112,113,114,115,116,117,118,119,120,121,122,91,92,93,94,95,
483 96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
484 112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
485 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
486 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
487 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
488 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
489 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
490 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
491 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
492 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
495 /** Implementation of strtok_r for platforms whose coders haven't figured out
496 * how to write one. Hey guys! You can use this code here for free! */
497 char *
498 tor_strtok_r_impl(char *str, const char *sep, char **lasts)
500 char *cp, *start;
501 if (str)
502 start = cp = *lasts = str;
503 else if (!*lasts)
504 return NULL;
505 else
506 start = cp = *lasts;
508 tor_assert(*sep);
509 if (sep[1]) {
510 while (*cp && !strchr(sep, *cp))
511 ++cp;
512 } else {
513 tor_assert(strlen(sep) == 1);
514 cp = strchr(cp, *sep);
517 if (!cp || !*cp) {
518 *lasts = NULL;
519 } else {
520 *cp++ = '\0';
521 *lasts = cp;
523 return start;
526 #ifdef MS_WINDOWS
527 /** Take a filename and return a pointer to its final element. This
528 * function is called on __FILE__ to fix a MSVC nit where __FILE__
529 * contains the full path to the file. This is bad, because it
530 * confuses users to find the home directory of the person who
531 * compiled the binary in their warning messages.
533 const char *
534 tor_fix_source_file(const char *fname)
536 const char *cp1, *cp2, *r;
537 cp1 = strrchr(fname, '/');
538 cp2 = strrchr(fname, '\\');
539 if (cp1 && cp2) {
540 r = (cp1<cp2)?(cp2+1):(cp1+1);
541 } else if (cp1) {
542 r = cp1+1;
543 } else if (cp2) {
544 r = cp2+1;
545 } else {
546 r = fname;
548 return r;
550 #endif
553 * Read a 16-bit value beginning at <b>cp</b>. Equivalent to
554 * *(uint16_t*)(cp), but will not cause segfaults on platforms that forbid
555 * unaligned memory access.
557 uint16_t
558 get_uint16(const char *cp)
560 uint16_t v;
561 memcpy(&v,cp,2);
562 return v;
565 * Read a 32-bit value beginning at <b>cp</b>. Equivalent to
566 * *(uint32_t*)(cp), but will not cause segfaults on platforms that forbid
567 * unaligned memory access.
569 uint32_t
570 get_uint32(const char *cp)
572 uint32_t v;
573 memcpy(&v,cp,4);
574 return v;
577 * Read a 64-bit value beginning at <b>cp</b>. Equivalent to
578 * *(uint64_t*)(cp), but will not cause segfaults on platforms that forbid
579 * unaligned memory access.
581 uint64_t
582 get_uint64(const char *cp)
584 uint64_t v;
585 memcpy(&v,cp,8);
586 return v;
590 * Set a 16-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
591 * *(uint16_t*)(cp) = v, but will not cause segfaults on platforms that forbid
592 * unaligned memory access. */
593 void
594 set_uint16(char *cp, uint16_t v)
596 memcpy(cp,&v,2);
599 * Set a 32-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
600 * *(uint32_t*)(cp) = v, but will not cause segfaults on platforms that forbid
601 * unaligned memory access. */
602 void
603 set_uint32(char *cp, uint32_t v)
605 memcpy(cp,&v,4);
608 * Set a 64-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
609 * *(uint64_t*)(cp) = v, but will not cause segfaults on platforms that forbid
610 * unaligned memory access. */
611 void
612 set_uint64(char *cp, uint64_t v)
614 memcpy(cp,&v,8);
618 * Rename the file <b>from</b> to the file <b>to</b>. On Unix, this is
619 * the same as rename(2). On windows, this removes <b>to</b> first if
620 * it already exists.
621 * Returns 0 on success. Returns -1 and sets errno on failure.
624 replace_file(const char *from, const char *to)
626 #ifndef MS_WINDOWS
627 return rename(from,to);
628 #else
629 switch (file_status(to))
631 case FN_NOENT:
632 break;
633 case FN_FILE:
634 if (unlink(to)) return -1;
635 break;
636 case FN_ERROR:
637 return -1;
638 case FN_DIR:
639 errno = EISDIR;
640 return -1;
642 return rename(from,to);
643 #endif
646 /** Change <b>fname</b>'s modification time to now. */
648 touch_file(const char *fname)
650 if (utime(fname, NULL)!=0)
651 return -1;
652 return 0;
655 /** Represents a lockfile on which we hold the lock. */
656 struct tor_lockfile_t {
657 char *filename;
658 int fd;
661 /** Try to get a lock on the lockfile <b>filename</b>, creating it as
662 * necessary. If someone else has the lock and <b>blocking</b> is true,
663 * wait until the lock is available. Otherwise return immediately whether
664 * we succeeded or not.
666 * Set *<b>locked_out</b> to true if somebody else had the lock, and to false
667 * otherwise.
669 * Return a <b>tor_lockfile_t</b> on success, NULL on failure.
671 * (Implementation note: because we need to fall back to fcntl on some
672 * platforms, these locks are per-process, not per-thread. If you want
673 * to do in-process locking, use tor_mutex_t like a normal person.)
675 tor_lockfile_t *
676 tor_lockfile_lock(const char *filename, int blocking, int *locked_out)
678 tor_lockfile_t *result;
679 int fd;
680 *locked_out = 0;
682 log_info(LD_FS, "Locking \"%s\"", filename);
683 fd = open(filename, O_RDWR|O_CREAT|O_TRUNC, 0600);
684 if (fd < 0) {
685 log_warn(LD_FS,"Couldn't open \"%s\" for locking: %s", filename,
686 strerror(errno));
687 return NULL;
690 #ifdef WIN32
691 _lseek(fd, 0, SEEK_SET);
692 if (_locking(fd, blocking ? _LK_LOCK : _LK_NBLCK, 1) < 0) {
693 if (errno != EDEADLOCK)
694 log_warn(LD_FS,"Couldn't lock \"%s\": %s", filename, strerror(errno));
695 else
696 *locked_out = 1;
697 close(fd);
698 return NULL;
700 #elif defined(HAVE_FLOCK)
701 if (flock(fd, LOCK_EX|(blocking ? 0 : LOCK_NB)) < 0) {
702 if (errno != EWOULDBLOCK)
703 log_warn(LD_FS,"Couldn't lock \"%s\": %s", filename, strerror(errno));
704 else
705 *locked_out = 1;
706 close(fd);
707 return NULL;
709 #else
711 struct flock lock;
712 memset(&lock, 0, sizeof(lock));
713 lock.l_type = F_WRLCK;
714 lock.l_whence = SEEK_SET;
715 if (fcntl(fd, blocking ? F_SETLKW : F_SETLK, &lock) < 0) {
716 if (errno != EACCES && errno != EAGAIN)
717 log_warn(LD_FS, "Couldn't lock \"%s\": %s", filename, strerror(errno));
718 else
719 *locked_out = 1;
720 close(fd);
721 return NULL;
724 #endif
726 result = tor_malloc(sizeof(tor_lockfile_t));
727 result->filename = tor_strdup(filename);
728 result->fd = fd;
729 return result;
732 /** Release the lock held as <b>lockfile</b>. */
733 void
734 tor_lockfile_unlock(tor_lockfile_t *lockfile)
736 tor_assert(lockfile);
738 log_info(LD_FS, "Unlocking \"%s\"", lockfile->filename);
739 #ifdef WIN32
740 _lseek(lockfile->fd, 0, SEEK_SET);
741 if (_locking(lockfile->fd, _LK_UNLCK, 1) < 0) {
742 log_warn(LD_FS,"Error unlocking \"%s\": %s", lockfile->filename,
743 strerror(errno));
745 #elif defined(HAVE_FLOCK)
746 if (flock(lockfile->fd, LOCK_UN) < 0) {
747 log_warn(LD_FS, "Error unlocking \"%s\": %s", lockfile->filename,
748 strerror(errno));
750 #else
751 /* Closing the lockfile is sufficient. */
752 #endif
754 close(lockfile->fd);
755 lockfile->fd = -1;
756 tor_free(lockfile->filename);
757 tor_free(lockfile);
760 /* Some old versions of Unix didn't define constants for these values,
761 * and instead expect you to say 0, 1, or 2. */
762 #ifndef SEEK_CUR
763 #define SEEK_CUR 1
764 #endif
765 #ifndef SEEK_END
766 #define SEEK_END 2
767 #endif
769 /** Return the position of <b>fd</b> with respect to the start of the file. */
770 off_t
771 tor_fd_getpos(int fd)
773 #ifdef WIN32
774 return (off_t) _lseek(fd, 0, SEEK_CUR);
775 #else
776 return (off_t) lseek(fd, 0, SEEK_CUR);
777 #endif
780 /** Move <b>fd</b> to the end of the file. Return -1 on error, 0 on success. */
782 tor_fd_seekend(int fd)
784 #ifdef WIN32
785 return _lseek(fd, 0, SEEK_END) < 0 ? -1 : 0;
786 #else
787 return lseek(fd, 0, SEEK_END) < 0 ? -1 : 0;
788 #endif
791 #undef DEBUG_SOCKET_COUNTING
792 #ifdef DEBUG_SOCKET_COUNTING
793 /** A bitarray of all fds that should be passed to tor_socket_close(). Only
794 * used if DEBUG_SOCKET_COUNTING is defined. */
795 static bitarray_t *open_sockets = NULL;
796 /** The size of <b>open_sockets</b>, in bits. */
797 static int max_socket = -1;
798 #endif
800 /** Count of number of sockets currently open. (Undercounts sockets opened by
801 * eventdns and libevent.) */
802 static int n_sockets_open = 0;
804 /** Mutex to protect open_sockets, max_socket, and n_sockets_open. */
805 static tor_mutex_t *socket_accounting_mutex = NULL;
807 static INLINE void
808 socket_accounting_lock(void)
810 if (PREDICT_UNLIKELY(!socket_accounting_mutex))
811 socket_accounting_mutex = tor_mutex_new();
812 tor_mutex_acquire(socket_accounting_mutex);
815 static INLINE void
816 socket_accounting_unlock(void)
818 tor_mutex_release(socket_accounting_mutex);
821 /** As close(), but guaranteed to work for sockets across platforms (including
822 * Windows, where close()ing a socket doesn't work. Returns 0 on success, -1
823 * on failure. */
825 tor_close_socket(int s)
827 int r = 0;
829 /* On Windows, you have to call close() on fds returned by open(),
830 * and closesocket() on fds returned by socket(). On Unix, everything
831 * gets close()'d. We abstract this difference by always using
832 * tor_close_socket to close sockets, and always using close() on
833 * files.
835 #if defined(MS_WINDOWS)
836 r = closesocket(s);
837 #else
838 r = close(s);
839 #endif
841 socket_accounting_lock();
842 #ifdef DEBUG_SOCKET_COUNTING
843 if (s > max_socket || ! bitarray_is_set(open_sockets, s)) {
844 log_warn(LD_BUG, "Closing a socket (%d) that wasn't returned by tor_open_"
845 "socket(), or that was already closed or something.", s);
846 } else {
847 tor_assert(open_sockets && s <= max_socket);
848 bitarray_clear(open_sockets, s);
850 #endif
851 if (r == 0) {
852 --n_sockets_open;
853 } else {
854 int err = tor_socket_errno(-1);
855 log_info(LD_NET, "Close returned an error: %s", tor_socket_strerror(err));
856 #ifdef WIN32
857 if (err != WSAENOTSOCK)
858 --n_sockets_open;
859 #else
860 if (err != EBADF)
861 --n_sockets_open;
862 #endif
863 r = -1;
866 if (n_sockets_open < 0)
867 log_warn(LD_BUG, "Our socket count is below zero: %d. Please submit a "
868 "bug report.", n_sockets_open);
869 socket_accounting_unlock();
870 return r;
873 #ifdef DEBUG_SOCKET_COUNTING
874 /** Helper: if DEBUG_SOCKET_COUNTING is enabled, remember that <b>s</b> is
875 * now an open socket. */
876 static INLINE void
877 mark_socket_open(int s)
879 if (s > max_socket) {
880 if (max_socket == -1) {
881 open_sockets = bitarray_init_zero(s+128);
882 max_socket = s+128;
883 } else {
884 open_sockets = bitarray_expand(open_sockets, max_socket, s+128);
885 max_socket = s+128;
888 if (bitarray_is_set(open_sockets, s)) {
889 log_warn(LD_BUG, "I thought that %d was already open, but socket() just "
890 "gave it to me!", s);
892 bitarray_set(open_sockets, s);
894 #else
895 #define mark_socket_open(s) STMT_NIL
896 #endif
898 /** As socket(), but counts the number of open sockets. */
900 tor_open_socket(int domain, int type, int protocol)
902 int s = socket(domain, type, protocol);
903 if (s >= 0) {
904 socket_accounting_lock();
905 ++n_sockets_open;
906 mark_socket_open(s);
907 socket_accounting_unlock();
909 return s;
912 /** As socket(), but counts the number of open sockets. */
914 tor_accept_socket(int sockfd, struct sockaddr *addr, socklen_t *len)
916 int s = accept(sockfd, addr, len);
917 if (s >= 0) {
918 socket_accounting_lock();
919 ++n_sockets_open;
920 mark_socket_open(s);
921 socket_accounting_unlock();
923 return s;
926 /** Return the number of sockets we currently have opened. */
928 get_n_open_sockets(void)
930 int n;
931 socket_accounting_lock();
932 n = n_sockets_open;
933 socket_accounting_unlock();
934 return n;
937 /** Turn <b>socket</b> into a nonblocking socket.
939 void
940 set_socket_nonblocking(int socket)
942 #if defined(MS_WINDOWS)
943 unsigned long nonblocking = 1;
944 ioctlsocket(socket, FIONBIO, (unsigned long*) &nonblocking);
945 #else
946 fcntl(socket, F_SETFL, O_NONBLOCK);
947 #endif
951 * Allocate a pair of connected sockets. (Like socketpair(family,
952 * type,protocol,fd), but works on systems that don't have
953 * socketpair.)
955 * Currently, only (AF_UNIX, SOCK_STREAM, 0) sockets are supported.
957 * Note that on systems without socketpair, this call will fail if
958 * localhost is inaccessible (for example, if the networking
959 * stack is down). And even if it succeeds, the socket pair will not
960 * be able to read while localhost is down later (the socket pair may
961 * even close, depending on OS-specific timeouts).
963 * Returns 0 on success and -errno on failure; do not rely on the value
964 * of errno or WSAGetLastError().
966 /* It would be nicer just to set errno, but that won't work for windows. */
968 tor_socketpair(int family, int type, int protocol, int fd[2])
970 //don't use win32 socketpairs (they are always bad)
971 #if defined(HAVE_SOCKETPAIR) && !defined(MS_WINDOWS)
972 int r;
973 r = socketpair(family, type, protocol, fd);
974 if (r == 0) {
975 socket_accounting_lock();
976 if (fd[0] >= 0) {
977 ++n_sockets_open;
978 mark_socket_open(fd[0]);
980 if (fd[1] >= 0) {
981 ++n_sockets_open;
982 mark_socket_open(fd[1]);
984 socket_accounting_unlock();
986 return r < 0 ? -errno : r;
987 #else
988 /* This socketpair does not work when localhost is down. So
989 * it's really not the same thing at all. But it's close enough
990 * for now, and really, when localhost is down sometimes, we
991 * have other problems too.
993 int listener = -1;
994 int connector = -1;
995 int acceptor = -1;
996 struct sockaddr_in listen_addr;
997 struct sockaddr_in connect_addr;
998 int size;
999 int saved_errno = -1;
1001 if (protocol
1002 #ifdef AF_UNIX
1003 || family != AF_UNIX
1004 #endif
1006 #ifdef MS_WINDOWS
1007 return -WSAEAFNOSUPPORT;
1008 #else
1009 return -EAFNOSUPPORT;
1010 #endif
1012 if (!fd) {
1013 return -EINVAL;
1016 listener = tor_open_socket(AF_INET, type, 0);
1017 if (listener < 0)
1018 return -tor_socket_errno(-1);
1019 memset(&listen_addr, 0, sizeof(listen_addr));
1020 listen_addr.sin_family = AF_INET;
1021 listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
1022 listen_addr.sin_port = 0; /* kernel chooses port. */
1023 if (bind(listener, (struct sockaddr *) &listen_addr, sizeof (listen_addr))
1024 == -1)
1025 goto tidy_up_and_fail;
1026 if (listen(listener, 1) == -1)
1027 goto tidy_up_and_fail;
1029 connector = tor_open_socket(AF_INET, type, 0);
1030 if (connector < 0)
1031 goto tidy_up_and_fail;
1032 /* We want to find out the port number to connect to. */
1033 size = sizeof(connect_addr);
1034 if (getsockname(listener, (struct sockaddr *) &connect_addr, &size) == -1)
1035 goto tidy_up_and_fail;
1036 if (size != sizeof (connect_addr))
1037 goto abort_tidy_up_and_fail;
1038 if (connect(connector, (struct sockaddr *) &connect_addr,
1039 sizeof(connect_addr)) == -1)
1040 goto tidy_up_and_fail;
1042 size = sizeof(listen_addr);
1043 acceptor = tor_accept_socket(listener,
1044 (struct sockaddr *) &listen_addr, &size);
1045 if (acceptor < 0)
1046 goto tidy_up_and_fail;
1047 if (size != sizeof(listen_addr))
1048 goto abort_tidy_up_and_fail;
1049 tor_close_socket(listener);
1050 /* Now check we are talking to ourself by matching port and host on the
1051 two sockets. */
1052 if (getsockname(connector, (struct sockaddr *) &connect_addr, &size) == -1)
1053 goto tidy_up_and_fail;
1054 if (size != sizeof (connect_addr)
1055 || listen_addr.sin_family != connect_addr.sin_family
1056 || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
1057 || listen_addr.sin_port != connect_addr.sin_port) {
1058 goto abort_tidy_up_and_fail;
1060 fd[0] = connector;
1061 fd[1] = acceptor;
1063 return 0;
1065 abort_tidy_up_and_fail:
1066 #ifdef MS_WINDOWS
1067 saved_errno = WSAECONNABORTED;
1068 #else
1069 saved_errno = ECONNABORTED; /* I hope this is portable and appropriate. */
1070 #endif
1071 tidy_up_and_fail:
1072 if (saved_errno < 0)
1073 saved_errno = errno;
1074 if (listener != -1)
1075 tor_close_socket(listener);
1076 if (connector != -1)
1077 tor_close_socket(connector);
1078 if (acceptor != -1)
1079 tor_close_socket(acceptor);
1080 return -saved_errno;
1081 #endif
1084 #define ULIMIT_BUFFER 32 /* keep 32 extra fd's beyond _ConnLimit */
1086 /** Learn the maximum allowed number of file descriptors. (Some systems
1087 * have a low soft limit.
1089 * We compute this by finding the largest number that we can use.
1090 * If we can't find a number greater than or equal to <b>limit</b>,
1091 * then we fail: return -1.
1093 * Otherwise, return 0 and store the maximum we found inside <b>max_out</b>.*/
1095 set_max_file_descriptors(rlim_t limit, int *max_out)
1097 /* Define some maximum connections values for systems where we cannot
1098 * automatically determine a limit. Re Cygwin, see
1099 * http://archives.seul.org/or/talk/Aug-2006/msg00210.html
1100 * For an iPhone, 9999 should work. For Windows and all other unknown
1101 * systems we use 15000 as the default. */
1102 #ifndef HAVE_GETRLIMIT
1103 #if defined(CYGWIN) || defined(__CYGWIN__)
1104 const char *platform = "Cygwin";
1105 const unsigned long MAX_CONNECTIONS = 3200;
1106 #elif defined(MS_WINDOWS)
1107 const char *platform = "Windows";
1108 const unsigned long MAX_CONNECTIONS = 15000;
1109 #else
1110 const char *platform = "unknown platforms with no getrlimit()";
1111 const unsigned long MAX_CONNECTIONS = 15000;
1112 #endif
1113 log_fn(LOG_INFO, LD_NET,
1114 "This platform is missing getrlimit(). Proceeding.");
1115 if (limit > MAX_CONNECTIONS) {
1116 log_warn(LD_CONFIG,
1117 "We do not support more than %lu file descriptors "
1118 "on %s. Tried to raise to %lu.",
1119 (unsigned long)MAX_CONNECTIONS, platform, (unsigned long)limit);
1120 return -1;
1122 limit = MAX_CONNECTIONS;
1123 #else /* HAVE_GETRLIMIT */
1124 struct rlimit rlim;
1125 tor_assert(limit > 0);
1127 if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) {
1128 log_warn(LD_NET, "Could not get maximum number of file descriptors: %s",
1129 strerror(errno));
1130 return -1;
1133 if (rlim.rlim_max < limit) {
1134 log_warn(LD_CONFIG,"We need %lu file descriptors available, and we're "
1135 "limited to %lu. Please change your ulimit -n.",
1136 (unsigned long)limit, (unsigned long)rlim.rlim_max);
1137 return -1;
1140 if (rlim.rlim_max > rlim.rlim_cur) {
1141 log_info(LD_NET,"Raising max file descriptors from %lu to %lu.",
1142 (unsigned long)rlim.rlim_cur, (unsigned long)rlim.rlim_max);
1144 rlim.rlim_cur = rlim.rlim_max;
1146 if (setrlimit(RLIMIT_NOFILE, &rlim) != 0) {
1147 int bad = 1;
1148 #ifdef OPEN_MAX
1149 if (errno == EINVAL && OPEN_MAX < rlim.rlim_cur) {
1150 /* On some platforms, OPEN_MAX is the real limit, and getrlimit() is
1151 * full of nasty lies. I'm looking at you, OSX 10.5.... */
1152 rlim.rlim_cur = OPEN_MAX;
1153 if (setrlimit(RLIMIT_NOFILE, &rlim) == 0) {
1154 if (rlim.rlim_cur < (rlim_t)limit) {
1155 log_warn(LD_CONFIG, "We are limited to %lu file descriptors by "
1156 "OPEN_MAX, and ConnLimit is %lu. Changing ConnLimit; sorry.",
1157 (unsigned long)OPEN_MAX, (unsigned long)limit);
1158 } else {
1159 log_info(LD_CONFIG, "Dropped connection limit to OPEN_MAX (%lu); "
1160 "Apparently, %lu was too high and rlimit lied to us.",
1161 (unsigned long)OPEN_MAX, (unsigned long)rlim.rlim_max);
1163 bad = 0;
1166 #endif /* OPEN_MAX */
1167 if (bad) {
1168 log_warn(LD_CONFIG,"Couldn't set maximum number of file descriptors: %s",
1169 strerror(errno));
1170 return -1;
1173 /* leave some overhead for logs, etc, */
1174 limit = rlim.rlim_cur;
1175 #endif /* HAVE_GETRLIMIT */
1177 if (limit < ULIMIT_BUFFER) {
1178 log_warn(LD_CONFIG,
1179 "ConnLimit must be at least %d. Failing.", ULIMIT_BUFFER);
1180 return -1;
1182 if (limit > INT_MAX)
1183 limit = INT_MAX;
1184 tor_assert(max_out);
1185 *max_out = (int)limit - ULIMIT_BUFFER;
1186 return 0;
1189 #ifndef MS_WINDOWS
1190 /** Log details of current user and group credentials. Return 0 on
1191 * success. Logs and return -1 on failure.
1193 static int
1194 log_credential_status(void)
1196 #define CREDENTIAL_LOG_LEVEL LOG_INFO
1197 /* Real, effective and saved UIDs */
1198 uid_t ruid, euid, suid;
1199 /* Read, effective and saved GIDs */
1200 gid_t rgid, egid, sgid;
1201 /* Supplementary groups */
1202 gid_t sup_gids[NGROUPS_MAX + 1];
1203 /* Number of supplementary groups */
1204 int ngids;
1206 /* log UIDs */
1207 #ifdef HAVE_GETRESUID
1208 if (getresuid(&ruid, &euid, &suid) != 0 ) {
1209 log_warn(LD_GENERAL, "Error getting changed UIDs: %s", strerror(errno));
1210 return -1;
1211 } else {
1212 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
1213 "UID is %u (real), %u (effective), %u (saved)",
1214 (unsigned)ruid, (unsigned)euid, (unsigned)suid);
1216 #else
1217 /* getresuid is not present on MacOS X, so we can't get the saved (E)UID */
1218 ruid = getuid();
1219 euid = geteuid();
1220 (void)suid;
1222 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
1223 "UID is %u (real), %u (effective), unknown (saved)",
1224 (unsigned)ruid, (unsigned)euid);
1225 #endif
1227 /* log GIDs */
1228 #ifdef HAVE_GETRESGID
1229 if (getresgid(&rgid, &egid, &sgid) != 0 ) {
1230 log_warn(LD_GENERAL, "Error getting changed GIDs: %s", strerror(errno));
1231 return -1;
1232 } else {
1233 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
1234 "GID is %u (real), %u (effective), %u (saved)",
1235 (unsigned)rgid, (unsigned)egid, (unsigned)sgid);
1237 #else
1238 /* getresgid is not present on MacOS X, so we can't get the saved (E)GID */
1239 rgid = getgid();
1240 egid = getegid();
1241 (void)sgid;
1242 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
1243 "GID is %u (real), %u (effective), unknown (saved)",
1244 (unsigned)rgid, (unsigned)egid);
1245 #endif
1247 /* log supplementary groups */
1248 if ((ngids = getgroups(NGROUPS_MAX + 1, sup_gids)) < 0) {
1249 log_warn(LD_GENERAL, "Error getting supplementary GIDs: %s",
1250 strerror(errno));
1251 return -1;
1252 } else {
1253 int i, retval = 0;
1254 char *strgid;
1255 char *s = NULL;
1256 smartlist_t *elts = smartlist_create();
1258 for (i = 0; i<ngids; i++) {
1259 strgid = tor_malloc(11);
1260 if (tor_snprintf(strgid, 11, "%u", (unsigned)sup_gids[i]) < 0) {
1261 log_warn(LD_GENERAL, "Error printing supplementary GIDs");
1262 tor_free(strgid);
1263 retval = -1;
1264 goto error;
1266 smartlist_add(elts, strgid);
1269 s = smartlist_join_strings(elts, " ", 0, NULL);
1271 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL, "Supplementary groups are: %s",s);
1273 error:
1274 tor_free(s);
1275 SMARTLIST_FOREACH(elts, char *, cp,
1277 tor_free(cp);
1279 smartlist_free(elts);
1281 return retval;
1284 return 0;
1286 #endif
1288 /** Call setuid and setgid to run as <b>user</b> and switch to their
1289 * primary group. Return 0 on success. On failure, log and return -1.
1292 switch_id(const char *user)
1294 #ifndef MS_WINDOWS
1295 struct passwd *pw = NULL;
1296 uid_t old_uid;
1297 gid_t old_gid;
1298 static int have_already_switched_id = 0;
1300 tor_assert(user);
1302 if (have_already_switched_id)
1303 return 0;
1305 /* Log the initial credential state */
1306 if (log_credential_status())
1307 return -1;
1309 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL, "Changing user and groups");
1311 /* Get old UID/GID to check if we changed correctly */
1312 old_uid = getuid();
1313 old_gid = getgid();
1315 /* Lookup the user and group information, if we have a problem, bail out. */
1316 pw = getpwnam(user);
1317 if (pw == NULL) {
1318 log_warn(LD_CONFIG, "Error setting configured user: %s not found", user);
1319 return -1;
1322 /* Properly switch egid,gid,euid,uid here or bail out */
1323 if (setgroups(1, &pw->pw_gid)) {
1324 log_warn(LD_GENERAL, "Error setting groups to gid %d: \"%s\".",
1325 (int)pw->pw_gid, strerror(errno));
1326 if (old_uid == pw->pw_uid) {
1327 log_warn(LD_GENERAL, "Tor is already running as %s. You do not need "
1328 "the \"User\" option if you are already running as the user "
1329 "you want to be. (If you did not set the User option in your "
1330 "torrc, check whether it was specified on the command line "
1331 "by a startup script.)", user);
1332 } else {
1333 log_warn(LD_GENERAL, "If you set the \"User\" option, you must start Tor"
1334 " as root.");
1336 return -1;
1339 if (setegid(pw->pw_gid)) {
1340 log_warn(LD_GENERAL, "Error setting egid to %d: %s",
1341 (int)pw->pw_gid, strerror(errno));
1342 return -1;
1345 if (setgid(pw->pw_gid)) {
1346 log_warn(LD_GENERAL, "Error setting gid to %d: %s",
1347 (int)pw->pw_gid, strerror(errno));
1348 return -1;
1351 if (setuid(pw->pw_uid)) {
1352 log_warn(LD_GENERAL, "Error setting configured uid to %s (%d): %s",
1353 user, (int)pw->pw_uid, strerror(errno));
1354 return -1;
1357 if (seteuid(pw->pw_uid)) {
1358 log_warn(LD_GENERAL, "Error setting configured euid to %s (%d): %s",
1359 user, (int)pw->pw_uid, strerror(errno));
1360 return -1;
1363 /* This is how OpenBSD rolls:
1364 if (setgroups(1, &pw->pw_gid) || setegid(pw->pw_gid) ||
1365 setgid(pw->pw_gid) || setuid(pw->pw_uid) || seteuid(pw->pw_uid)) {
1366 setgid(pw->pw_gid) || seteuid(pw->pw_uid) || setuid(pw->pw_uid)) {
1367 log_warn(LD_GENERAL, "Error setting configured UID/GID: %s",
1368 strerror(errno));
1369 return -1;
1373 /* We've properly switched egid, gid, euid, uid, and supplementary groups if
1374 * we're here. */
1376 #if !defined(CYGWIN) && !defined(__CYGWIN__)
1377 /* If we tried to drop privilege to a group/user other than root, attempt to
1378 * restore root (E)(U|G)ID, and abort if the operation succeeds */
1380 /* Only check for privilege dropping if we were asked to be non-root */
1381 if (pw->pw_uid) {
1382 /* Try changing GID/EGID */
1383 if (pw->pw_gid != old_gid &&
1384 (setgid(old_gid) != -1 || setegid(old_gid) != -1)) {
1385 log_warn(LD_GENERAL, "Was able to restore group credentials even after "
1386 "switching GID: this means that the setgid code didn't work.");
1387 return -1;
1390 /* Try changing UID/EUID */
1391 if (pw->pw_uid != old_uid &&
1392 (setuid(old_uid) != -1 || seteuid(old_uid) != -1)) {
1393 log_warn(LD_GENERAL, "Was able to restore user credentials even after "
1394 "switching UID: this means that the setuid code didn't work.");
1395 return -1;
1398 #endif
1400 /* Check what really happened */
1401 if (log_credential_status()) {
1402 return -1;
1405 have_already_switched_id = 1; /* mark success so we never try again */
1407 #if defined(__linux__) && defined(HAVE_SYS_PRCTL_H) && defined(HAVE_PRCTL)
1408 #ifdef PR_SET_DUMPABLE
1409 if (pw->pw_uid) {
1410 /* Re-enable core dumps if we're not running as root. */
1411 log_info(LD_CONFIG, "Re-enabling coredumps");
1412 if (prctl(PR_SET_DUMPABLE, 1)) {
1413 log_warn(LD_CONFIG, "Unable to re-enable coredumps: %s",strerror(errno));
1416 #endif
1417 #endif
1418 return 0;
1420 #else
1421 (void)user;
1423 log_warn(LD_CONFIG,
1424 "User specified but switching users is unsupported on your OS.");
1425 return -1;
1426 #endif
1429 #ifdef HAVE_PWD_H
1430 /** Allocate and return a string containing the home directory for the
1431 * user <b>username</b>. Only works on posix-like systems. */
1432 char *
1433 get_user_homedir(const char *username)
1435 struct passwd *pw;
1436 tor_assert(username);
1438 if (!(pw = getpwnam(username))) {
1439 log_err(LD_CONFIG,"User \"%s\" not found.", username);
1440 return NULL;
1442 return tor_strdup(pw->pw_dir);
1444 #endif
1446 /** Set *addr to the IP address (in dotted-quad notation) stored in c.
1447 * Return 1 on success, 0 if c is badly formatted. (Like inet_aton(c,addr),
1448 * but works on Windows and Solaris.)
1451 tor_inet_aton(const char *str, struct in_addr* addr)
1453 unsigned a,b,c,d;
1454 char more;
1455 if (tor_sscanf(str, "%3u.%3u.%3u.%3u%c", &a,&b,&c,&d,&more) != 4)
1456 return 0;
1457 if (a > 255) return 0;
1458 if (b > 255) return 0;
1459 if (c > 255) return 0;
1460 if (d > 255) return 0;
1461 addr->s_addr = htonl((a<<24) | (b<<16) | (c<<8) | d);
1462 return 1;
1465 /** Given <b>af</b>==AF_INET and <b>src</b> a struct in_addr, or
1466 * <b>af</b>==AF_INET6 and <b>src</b> a struct in6_addr, try to format the
1467 * address and store it in the <b>len</b>-byte buffer <b>dst</b>. Returns
1468 * <b>dst</b> on success, NULL on failure.
1470 * (Like inet_ntop(af,src,dst,len), but works on platforms that don't have it:
1471 * Tor sometimes needs to format ipv6 addresses even on platforms without ipv6
1472 * support.) */
1473 const char *
1474 tor_inet_ntop(int af, const void *src, char *dst, size_t len)
1476 if (af == AF_INET) {
1477 if (tor_inet_ntoa(src, dst, len) < 0)
1478 return NULL;
1479 else
1480 return dst;
1481 } else if (af == AF_INET6) {
1482 const struct in6_addr *addr = src;
1483 char buf[64], *cp;
1484 int longestGapLen = 0, longestGapPos = -1, i,
1485 curGapPos = -1, curGapLen = 0;
1486 uint16_t words[8];
1487 for (i = 0; i < 8; ++i) {
1488 words[i] = (((uint16_t)addr->s6_addr[2*i])<<8) + addr->s6_addr[2*i+1];
1490 if (words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0 &&
1491 words[4] == 0 && ((words[5] == 0 && words[6] && words[7]) ||
1492 (words[5] == 0xffff))) {
1493 /* This is an IPv4 address. */
1494 if (words[5] == 0) {
1495 tor_snprintf(buf, sizeof(buf), "::%d.%d.%d.%d",
1496 addr->s6_addr[12], addr->s6_addr[13],
1497 addr->s6_addr[14], addr->s6_addr[15]);
1498 } else {
1499 tor_snprintf(buf, sizeof(buf), "::%x:%d.%d.%d.%d", words[5],
1500 addr->s6_addr[12], addr->s6_addr[13],
1501 addr->s6_addr[14], addr->s6_addr[15]);
1503 if (strlen(buf) > len)
1504 return NULL;
1505 strlcpy(dst, buf, len);
1506 return dst;
1508 i = 0;
1509 while (i < 8) {
1510 if (words[i] == 0) {
1511 curGapPos = i++;
1512 curGapLen = 1;
1513 while (i<8 && words[i] == 0) {
1514 ++i; ++curGapLen;
1516 if (curGapLen > longestGapLen) {
1517 longestGapPos = curGapPos;
1518 longestGapLen = curGapLen;
1520 } else {
1521 ++i;
1524 if (longestGapLen<=1)
1525 longestGapPos = -1;
1527 cp = buf;
1528 for (i = 0; i < 8; ++i) {
1529 if (words[i] == 0 && longestGapPos == i) {
1530 if (i == 0)
1531 *cp++ = ':';
1532 *cp++ = ':';
1533 while (i < 8 && words[i] == 0)
1534 ++i;
1535 --i; /* to compensate for loop increment. */
1536 } else {
1537 tor_snprintf(cp, sizeof(buf)-(cp-buf), "%x", (unsigned)words[i]);
1538 cp += strlen(cp);
1539 if (i != 7)
1540 *cp++ = ':';
1543 *cp = '\0';
1544 if (strlen(buf) > len)
1545 return NULL;
1546 strlcpy(dst, buf, len);
1547 return dst;
1548 } else {
1549 return NULL;
1553 /** Given <b>af</b>==AF_INET or <b>af</b>==AF_INET6, and a string <b>src</b>
1554 * encoding an IPv4 address or IPv6 address correspondingly, try to parse the
1555 * address and store the result in <b>dst</b> (which must have space for a
1556 * struct in_addr or a struct in6_addr, as appropriate). Return 1 on success,
1557 * 0 on a bad parse, and -1 on a bad <b>af</b>.
1559 * (Like inet_pton(af,src,dst) but works on platforms that don't have it: Tor
1560 * sometimes needs to format ipv6 addresses even on platforms without ipv6
1561 * support.) */
1563 tor_inet_pton(int af, const char *src, void *dst)
1565 if (af == AF_INET) {
1566 return tor_inet_aton(src, dst);
1567 } else if (af == AF_INET6) {
1568 struct in6_addr *out = dst;
1569 uint16_t words[8];
1570 int gapPos = -1, i, setWords=0;
1571 const char *dot = strchr(src, '.');
1572 const char *eow; /* end of words. */
1573 if (dot == src)
1574 return 0;
1575 else if (!dot)
1576 eow = src+strlen(src);
1577 else {
1578 unsigned byte1,byte2,byte3,byte4;
1579 char more;
1580 for (eow = dot-1; eow >= src && TOR_ISDIGIT(*eow); --eow)
1582 ++eow;
1584 /* We use "scanf" because some platform inet_aton()s are too lax
1585 * about IPv4 addresses of the form "1.2.3" */
1586 if (tor_sscanf(eow, "%3u.%3u.%3u.%3u%c",
1587 &byte1,&byte2,&byte3,&byte4,&more) != 4)
1588 return 0;
1590 if (byte1 > 255 || byte2 > 255 || byte3 > 255 || byte4 > 255)
1591 return 0;
1593 words[6] = (byte1<<8) | byte2;
1594 words[7] = (byte3<<8) | byte4;
1595 setWords += 2;
1598 i = 0;
1599 while (src < eow) {
1600 if (i > 7)
1601 return 0;
1602 if (TOR_ISXDIGIT(*src)) {
1603 char *next;
1604 long r = strtol(src, &next, 16);
1605 if (next > 4+src)
1606 return 0;
1607 if (next == src)
1608 return 0;
1609 if (r<0 || r>65536)
1610 return 0;
1612 words[i++] = (uint16_t)r;
1613 setWords++;
1614 src = next;
1615 if (*src != ':' && src != eow)
1616 return 0;
1617 ++src;
1618 } else if (*src == ':' && i > 0 && gapPos==-1) {
1619 gapPos = i;
1620 ++src;
1621 } else if (*src == ':' && i == 0 && src[1] == ':' && gapPos==-1) {
1622 gapPos = i;
1623 src += 2;
1624 } else {
1625 return 0;
1629 if (setWords > 8 ||
1630 (setWords == 8 && gapPos != -1) ||
1631 (setWords < 8 && gapPos == -1))
1632 return 0;
1634 if (gapPos >= 0) {
1635 int nToMove = setWords - (dot ? 2 : 0) - gapPos;
1636 int gapLen = 8 - setWords;
1637 tor_assert(nToMove >= 0);
1638 memmove(&words[gapPos+gapLen], &words[gapPos],
1639 sizeof(uint16_t)*nToMove);
1640 memset(&words[gapPos], 0, sizeof(uint16_t)*gapLen);
1642 for (i = 0; i < 8; ++i) {
1643 out->s6_addr[2*i ] = words[i] >> 8;
1644 out->s6_addr[2*i+1] = words[i] & 0xff;
1647 return 1;
1648 } else {
1649 return -1;
1653 /** Similar behavior to Unix gethostbyname: resolve <b>name</b>, and set
1654 * *<b>addr</b> to the proper IP address, in host byte order. Returns 0
1655 * on success, -1 on failure; 1 on transient failure.
1657 * (This function exists because standard windows gethostbyname
1658 * doesn't treat raw IP addresses properly.)
1661 tor_lookup_hostname(const char *name, uint32_t *addr)
1663 tor_addr_t myaddr;
1664 int ret;
1666 if ((ret = tor_addr_lookup(name, AF_INET, &myaddr)))
1667 return ret;
1669 if (tor_addr_family(&myaddr) == AF_INET) {
1670 *addr = tor_addr_to_ipv4h(&myaddr);
1671 return ret;
1674 return -1;
1677 /** Hold the result of our call to <b>uname</b>. */
1678 static char uname_result[256];
1679 /** True iff uname_result is set. */
1680 static int uname_result_is_set = 0;
1682 /** Return a pointer to a description of our platform.
1684 const char *
1685 get_uname(void)
1687 #ifdef HAVE_UNAME
1688 struct utsname u;
1689 #endif
1690 if (!uname_result_is_set) {
1691 #ifdef HAVE_UNAME
1692 if (uname(&u) != -1) {
1693 /* (Linux says 0 is success, Solaris says 1 is success) */
1694 tor_snprintf(uname_result, sizeof(uname_result), "%s %s",
1695 u.sysname, u.machine);
1696 } else
1697 #endif
1699 #ifdef MS_WINDOWS
1700 OSVERSIONINFOEX info;
1701 int i;
1702 const char *plat = NULL;
1703 const char *extra = NULL;
1704 static struct {
1705 unsigned major; unsigned minor; const char *version;
1706 } win_version_table[] = {
1707 { 6, 1, "Windows 7" },
1708 { 6, 0, "Windows Vista" },
1709 { 5, 2, "Windows Server 2003" },
1710 { 5, 1, "Windows XP" },
1711 { 5, 0, "Windows 2000" },
1712 /* { 4, 0, "Windows NT 4.0" }, */
1713 { 4, 90, "Windows Me" },
1714 { 4, 10, "Windows 98" },
1715 /* { 4, 0, "Windows 95" } */
1716 { 3, 51, "Windows NT 3.51" },
1717 { 0, 0, NULL }
1719 memset(&info, 0, sizeof(info));
1720 info.dwOSVersionInfoSize = sizeof(info);
1721 if (! GetVersionEx((LPOSVERSIONINFO)&info)) {
1722 strlcpy(uname_result, "Bizarre version of Windows where GetVersionEx"
1723 " doesn't work.", sizeof(uname_result));
1724 uname_result_is_set = 1;
1725 return uname_result;
1727 if (info.dwMajorVersion == 4 && info.dwMinorVersion == 0) {
1728 if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
1729 plat = "Windows NT 4.0";
1730 else
1731 plat = "Windows 95";
1732 if (info.szCSDVersion[1] == 'B')
1733 extra = "OSR2 (B)";
1734 else if (info.szCSDVersion[1] == 'C')
1735 extra = "OSR2 (C)";
1736 } else {
1737 for (i=0; win_version_table[i].major>0; ++i) {
1738 if (win_version_table[i].major == info.dwMajorVersion &&
1739 win_version_table[i].minor == info.dwMinorVersion) {
1740 plat = win_version_table[i].version;
1741 break;
1745 if (plat && !strcmp(plat, "Windows 98")) {
1746 if (info.szCSDVersion[1] == 'A')
1747 extra = "SE (A)";
1748 else if (info.szCSDVersion[1] == 'B')
1749 extra = "SE (B)";
1751 if (plat) {
1752 if (!extra)
1753 extra = info.szCSDVersion;
1754 tor_snprintf(uname_result, sizeof(uname_result), "%s %s",
1755 plat, extra);
1756 } else {
1757 if (info.dwMajorVersion > 6 ||
1758 (info.dwMajorVersion==6 && info.dwMinorVersion>1))
1759 tor_snprintf(uname_result, sizeof(uname_result),
1760 "Very recent version of Windows [major=%d,minor=%d] %s",
1761 (int)info.dwMajorVersion,(int)info.dwMinorVersion,
1762 info.szCSDVersion);
1763 else
1764 tor_snprintf(uname_result, sizeof(uname_result),
1765 "Unrecognized version of Windows [major=%d,minor=%d] %s",
1766 (int)info.dwMajorVersion,(int)info.dwMinorVersion,
1767 info.szCSDVersion);
1769 #ifdef VER_SUITE_BACKOFFICE
1770 if (info.wProductType == VER_NT_DOMAIN_CONTROLLER) {
1771 strlcat(uname_result, " [domain controller]", sizeof(uname_result));
1772 } else if (info.wProductType == VER_NT_SERVER) {
1773 strlcat(uname_result, " [server]", sizeof(uname_result));
1774 } else if (info.wProductType == VER_NT_WORKSTATION) {
1775 strlcat(uname_result, " [workstation]", sizeof(uname_result));
1777 #endif
1778 #else
1779 strlcpy(uname_result, "Unknown platform", sizeof(uname_result));
1780 #endif
1782 uname_result_is_set = 1;
1784 return uname_result;
1788 * Process control
1791 #if defined(USE_PTHREADS)
1792 /** Wraps a void (*)(void*) function and its argument so we can
1793 * invoke them in a way pthreads would expect.
1795 typedef struct tor_pthread_data_t {
1796 void (*func)(void *);
1797 void *data;
1798 } tor_pthread_data_t;
1799 /** Given a tor_pthread_data_t <b>_data</b>, call _data-&gt;func(d-&gt;data)
1800 * and free _data. Used to make sure we can call functions the way pthread
1801 * expects. */
1802 static void *
1803 tor_pthread_helper_fn(void *_data)
1805 tor_pthread_data_t *data = _data;
1806 void (*func)(void*);
1807 void *arg;
1808 /* mask signals to worker threads to avoid SIGPIPE, etc */
1809 sigset_t sigs;
1810 /* We're in a subthread; don't handle any signals here. */
1811 sigfillset(&sigs);
1812 pthread_sigmask(SIG_SETMASK, &sigs, NULL);
1814 func = data->func;
1815 arg = data->data;
1816 tor_free(_data);
1817 func(arg);
1818 return NULL;
1820 #endif
1822 /** Minimalist interface to run a void function in the background. On
1823 * Unix calls fork, on win32 calls beginthread. Returns -1 on failure.
1824 * func should not return, but rather should call spawn_exit.
1826 * NOTE: if <b>data</b> is used, it should not be allocated on the stack,
1827 * since in a multithreaded environment, there is no way to be sure that
1828 * the caller's stack will still be around when the called function is
1829 * running.
1832 spawn_func(void (*func)(void *), void *data)
1834 #if defined(USE_WIN32_THREADS)
1835 int rv;
1836 rv = (int)_beginthread(func, 0, data);
1837 if (rv == (int)-1)
1838 return -1;
1839 return 0;
1840 #elif defined(USE_PTHREADS)
1841 pthread_t thread;
1842 tor_pthread_data_t *d;
1843 d = tor_malloc(sizeof(tor_pthread_data_t));
1844 d->data = data;
1845 d->func = func;
1846 if (pthread_create(&thread,NULL,tor_pthread_helper_fn,d))
1847 return -1;
1848 if (pthread_detach(thread))
1849 return -1;
1850 return 0;
1851 #else
1852 pid_t pid;
1853 pid = fork();
1854 if (pid<0)
1855 return -1;
1856 if (pid==0) {
1857 /* Child */
1858 func(data);
1859 tor_assert(0); /* Should never reach here. */
1860 return 0; /* suppress "control-reaches-end-of-non-void" warning. */
1861 } else {
1862 /* Parent */
1863 return 0;
1865 #endif
1868 /** End the current thread/process.
1870 void
1871 spawn_exit(void)
1873 #if defined(USE_WIN32_THREADS)
1874 _endthread();
1875 //we should never get here. my compiler thinks that _endthread returns, this
1876 //is an attempt to fool it.
1877 tor_assert(0);
1878 _exit(0);
1879 #elif defined(USE_PTHREADS)
1880 pthread_exit(NULL);
1881 #else
1882 /* http://www.erlenstar.demon.co.uk/unix/faq_2.html says we should
1883 * call _exit, not exit, from child processes. */
1884 _exit(0);
1885 #endif
1888 /** Set *timeval to the current time of day. On error, log and terminate.
1889 * (Same as gettimeofday(timeval,NULL), but never returns -1.)
1891 void
1892 tor_gettimeofday(struct timeval *timeval)
1894 #ifdef MS_WINDOWS
1895 /* Epoch bias copied from perl: number of units between windows epoch and
1896 * Unix epoch. */
1897 #define EPOCH_BIAS U64_LITERAL(116444736000000000)
1898 #define UNITS_PER_SEC U64_LITERAL(10000000)
1899 #define USEC_PER_SEC U64_LITERAL(1000000)
1900 #define UNITS_PER_USEC U64_LITERAL(10)
1901 union {
1902 uint64_t ft_64;
1903 FILETIME ft_ft;
1904 } ft;
1905 /* number of 100-nsec units since Jan 1, 1601 */
1906 GetSystemTimeAsFileTime(&ft.ft_ft);
1907 if (ft.ft_64 < EPOCH_BIAS) {
1908 log_err(LD_GENERAL,"System time is before 1970; failing.");
1909 exit(1);
1911 ft.ft_64 -= EPOCH_BIAS;
1912 timeval->tv_sec = (unsigned) (ft.ft_64 / UNITS_PER_SEC);
1913 timeval->tv_usec = (unsigned) ((ft.ft_64 / UNITS_PER_USEC) % USEC_PER_SEC);
1914 #elif defined(HAVE_GETTIMEOFDAY)
1915 if (gettimeofday(timeval, NULL)) {
1916 log_err(LD_GENERAL,"gettimeofday failed.");
1917 /* If gettimeofday dies, we have either given a bad timezone (we didn't),
1918 or segfaulted.*/
1919 exit(1);
1921 #elif defined(HAVE_FTIME)
1922 struct timeb tb;
1923 ftime(&tb);
1924 timeval->tv_sec = tb.time;
1925 timeval->tv_usec = tb.millitm * 1000;
1926 #else
1927 #error "No way to get time."
1928 #endif
1929 return;
1932 #if defined(TOR_IS_MULTITHREADED) && !defined(MS_WINDOWS)
1933 /** Defined iff we need to add locks when defining fake versions of reentrant
1934 * versions of time-related functions. */
1935 #define TIME_FNS_NEED_LOCKS
1936 #endif
1938 #ifndef HAVE_LOCALTIME_R
1939 #ifdef TIME_FNS_NEED_LOCKS
1940 struct tm *
1941 tor_localtime_r(const time_t *timep, struct tm *result)
1943 struct tm *r;
1944 static tor_mutex_t *m=NULL;
1945 if (!m) { m=tor_mutex_new(); }
1946 tor_assert(result);
1947 tor_mutex_acquire(m);
1948 r = localtime(timep);
1949 memcpy(result, r, sizeof(struct tm));
1950 tor_mutex_release(m);
1951 return result;
1953 #else
1954 struct tm *
1955 tor_localtime_r(const time_t *timep, struct tm *result)
1957 struct tm *r;
1958 tor_assert(result);
1959 r = localtime(timep);
1960 memcpy(result, r, sizeof(struct tm));
1961 return result;
1963 #endif
1964 #endif
1966 #ifndef HAVE_GMTIME_R
1967 #ifdef TIME_FNS_NEED_LOCKS
1968 struct tm *
1969 tor_gmtime_r(const time_t *timep, struct tm *result)
1971 struct tm *r;
1972 static tor_mutex_t *m=NULL;
1973 if (!m) { m=tor_mutex_new(); }
1974 tor_assert(result);
1975 tor_mutex_acquire(m);
1976 r = gmtime(timep);
1977 memcpy(result, r, sizeof(struct tm));
1978 tor_mutex_release(m);
1979 return result;
1981 #else
1982 struct tm *
1983 tor_gmtime_r(const time_t *timep, struct tm *result)
1985 struct tm *r;
1986 tor_assert(result);
1987 r = gmtime(timep);
1988 memcpy(result, r, sizeof(struct tm));
1989 return result;
1991 #endif
1992 #endif
1994 #if defined(USE_WIN32_THREADS)
1995 void
1996 tor_mutex_init(tor_mutex_t *m)
1998 InitializeCriticalSection(&m->mutex);
2000 void
2001 tor_mutex_uninit(tor_mutex_t *m)
2003 DeleteCriticalSection(&m->mutex);
2005 void
2006 tor_mutex_acquire(tor_mutex_t *m)
2008 tor_assert(m);
2009 EnterCriticalSection(&m->mutex);
2011 void
2012 tor_mutex_release(tor_mutex_t *m)
2014 LeaveCriticalSection(&m->mutex);
2016 unsigned long
2017 tor_get_thread_id(void)
2019 return (unsigned long)GetCurrentThreadId();
2021 #elif defined(USE_PTHREADS)
2022 /** A mutex attribute that we're going to use to tell pthreads that we want
2023 * "reentrant" mutexes (i.e., once we can re-lock if we're already holding
2024 * them.) */
2025 static pthread_mutexattr_t attr_reentrant;
2026 /** True iff we've called tor_threads_init() */
2027 static int threads_initialized = 0;
2028 /** Initialize <b>mutex</b> so it can be locked. Every mutex must be set
2029 * up with tor_mutex_init() or tor_mutex_new(); not both. */
2030 void
2031 tor_mutex_init(tor_mutex_t *mutex)
2033 int err;
2034 if (PREDICT_UNLIKELY(!threads_initialized))
2035 tor_threads_init();
2036 err = pthread_mutex_init(&mutex->mutex, &attr_reentrant);
2037 if (PREDICT_UNLIKELY(err)) {
2038 log_err(LD_GENERAL, "Error %d creating a mutex.", err);
2039 tor_fragile_assert();
2042 /** Wait until <b>m</b> is free, then acquire it. */
2043 void
2044 tor_mutex_acquire(tor_mutex_t *m)
2046 int err;
2047 tor_assert(m);
2048 err = pthread_mutex_lock(&m->mutex);
2049 if (PREDICT_UNLIKELY(err)) {
2050 log_err(LD_GENERAL, "Error %d locking a mutex.", err);
2051 tor_fragile_assert();
2054 /** Release the lock <b>m</b> so another thread can have it. */
2055 void
2056 tor_mutex_release(tor_mutex_t *m)
2058 int err;
2059 tor_assert(m);
2060 err = pthread_mutex_unlock(&m->mutex);
2061 if (PREDICT_UNLIKELY(err)) {
2062 log_err(LD_GENERAL, "Error %d unlocking a mutex.", err);
2063 tor_fragile_assert();
2066 /** Clean up the mutex <b>m</b> so that it no longer uses any system
2067 * resources. Does not free <b>m</b>. This function must only be called on
2068 * mutexes from tor_mutex_init(). */
2069 void
2070 tor_mutex_uninit(tor_mutex_t *m)
2072 int err;
2073 tor_assert(m);
2074 err = pthread_mutex_destroy(&m->mutex);
2075 if (PREDICT_UNLIKELY(err)) {
2076 log_err(LD_GENERAL, "Error %d destroying a mutex.", err);
2077 tor_fragile_assert();
2080 /** Return an integer representing this thread. */
2081 unsigned long
2082 tor_get_thread_id(void)
2084 union {
2085 pthread_t thr;
2086 unsigned long id;
2087 } r;
2088 r.thr = pthread_self();
2089 return r.id;
2091 #endif
2093 #ifdef TOR_IS_MULTITHREADED
2094 /** Return a newly allocated, ready-for-use mutex. */
2095 tor_mutex_t *
2096 tor_mutex_new(void)
2098 tor_mutex_t *m = tor_malloc_zero(sizeof(tor_mutex_t));
2099 tor_mutex_init(m);
2100 return m;
2102 /** Release all storage and system resources held by <b>m</b>. */
2103 void
2104 tor_mutex_free(tor_mutex_t *m)
2106 if (!m)
2107 return;
2108 tor_mutex_uninit(m);
2109 tor_free(m);
2111 #endif
2113 /* Conditions. */
2114 #ifdef USE_PTHREADS
2115 #if 0
2116 /** Cross-platform condition implementation. */
2117 struct tor_cond_t {
2118 pthread_cond_t cond;
2120 /** Return a newly allocated condition, with nobody waiting on it. */
2121 tor_cond_t *
2122 tor_cond_new(void)
2124 tor_cond_t *cond = tor_malloc_zero(sizeof(tor_cond_t));
2125 if (pthread_cond_init(&cond->cond, NULL)) {
2126 tor_free(cond);
2127 return NULL;
2129 return cond;
2131 /** Release all resources held by <b>cond</b>. */
2132 void
2133 tor_cond_free(tor_cond_t *cond)
2135 if (!cond)
2136 return;
2137 if (pthread_cond_destroy(&cond->cond)) {
2138 log_warn(LD_GENERAL,"Error freeing condition: %s", strerror(errno));
2139 return;
2141 tor_free(cond);
2143 /** Wait until one of the tor_cond_signal functions is called on <b>cond</b>.
2144 * All waiters on the condition must wait holding the same <b>mutex</b>.
2145 * Returns 0 on success, negative on failure. */
2147 tor_cond_wait(tor_cond_t *cond, tor_mutex_t *mutex)
2149 return pthread_cond_wait(&cond->cond, &mutex->mutex) ? -1 : 0;
2151 /** Wake up one of the waiters on <b>cond</b>. */
2152 void
2153 tor_cond_signal_one(tor_cond_t *cond)
2155 pthread_cond_signal(&cond->cond);
2157 /** Wake up all of the waiters on <b>cond</b>. */
2158 void
2159 tor_cond_signal_all(tor_cond_t *cond)
2161 pthread_cond_broadcast(&cond->cond);
2163 #endif
2164 /** Set up common structures for use by threading. */
2165 void
2166 tor_threads_init(void)
2168 if (!threads_initialized) {
2169 pthread_mutexattr_init(&attr_reentrant);
2170 pthread_mutexattr_settype(&attr_reentrant, PTHREAD_MUTEX_RECURSIVE);
2171 threads_initialized = 1;
2172 set_main_thread();
2175 #elif defined(USE_WIN32_THREADS)
2176 #if 0
2177 static DWORD cond_event_tls_index;
2178 struct tor_cond_t {
2179 CRITICAL_SECTION mutex;
2180 smartlist_t *events;
2182 tor_cond_t *
2183 tor_cond_new(void)
2185 tor_cond_t *cond = tor_malloc_zero(sizeof(tor_cond_t));
2186 InitializeCriticalSection(&cond->mutex);
2187 cond->events = smartlist_create();
2188 return cond;
2190 void
2191 tor_cond_free(tor_cond_t *cond)
2193 if (!cond)
2194 return;
2195 DeleteCriticalSection(&cond->mutex);
2196 /* XXXX notify? */
2197 smartlist_free(cond->events);
2198 tor_free(cond);
2201 tor_cond_wait(tor_cond_t *cond, tor_mutex_t *mutex)
2203 HANDLE event;
2204 int r;
2205 tor_assert(cond);
2206 tor_assert(mutex);
2207 event = TlsGetValue(cond_event_tls_index);
2208 if (!event) {
2209 event = CreateEvent(0, FALSE, FALSE, NULL);
2210 TlsSetValue(cond_event_tls_index, event);
2212 EnterCriticalSection(&cond->mutex);
2214 tor_assert(WaitForSingleObject(event, 0) == WAIT_TIMEOUT);
2215 tor_assert(!smartlist_isin(cond->events, event));
2216 smartlist_add(cond->events, event);
2218 LeaveCriticalSection(&cond->mutex);
2220 tor_mutex_release(mutex);
2221 r = WaitForSingleObject(event, INFINITE);
2222 tor_mutex_acquire(mutex);
2224 switch (r) {
2225 case WAIT_OBJECT_0: /* we got the mutex normally. */
2226 break;
2227 case WAIT_ABANDONED: /* holding thread exited. */
2228 case WAIT_TIMEOUT: /* Should never happen. */
2229 tor_assert(0);
2230 break;
2231 case WAIT_FAILED:
2232 log_warn(LD_GENERAL, "Failed to acquire mutex: %d",(int) GetLastError());
2234 return 0;
2236 void
2237 tor_cond_signal_one(tor_cond_t *cond)
2239 HANDLE event;
2240 tor_assert(cond);
2242 EnterCriticalSection(&cond->mutex);
2244 if ((event = smartlist_pop_last(cond->events)))
2245 SetEvent(event);
2247 LeaveCriticalSection(&cond->mutex);
2249 void
2250 tor_cond_signal_all(tor_cond_t *cond)
2252 tor_assert(cond);
2254 EnterCriticalSection(&cond->mutex);
2255 SMARTLIST_FOREACH(cond->events, HANDLE, event, SetEvent(event));
2256 smartlist_clear(cond->events);
2257 LeaveCriticalSection(&cond->mutex);
2259 #endif
2260 void
2261 tor_threads_init(void)
2263 #if 0
2264 cond_event_tls_index = TlsAlloc();
2265 #endif
2266 set_main_thread();
2268 #endif
2270 #if defined(HAVE_MLOCKALL) && HAVE_DECL_MLOCKALL && defined(RLIMIT_MEMLOCK)
2271 /** Attempt to raise the current and max rlimit to infinity for our process.
2272 * This only needs to be done once and can probably only be done when we have
2273 * not already dropped privileges.
2275 static int
2276 tor_set_max_memlock(void)
2278 /* Future consideration for Windows is probably SetProcessWorkingSetSize
2279 * This is similar to setting the memory rlimit of RLIMIT_MEMLOCK
2280 * http://msdn.microsoft.com/en-us/library/ms686234(VS.85).aspx
2283 struct rlimit limit;
2284 int ret;
2286 /* Do we want to report current limits first? This is not really needed. */
2287 ret = getrlimit(RLIMIT_MEMLOCK, &limit);
2288 if (ret == -1) {
2289 log_warn(LD_GENERAL, "Could not get RLIMIT_MEMLOCK: %s", strerror(errno));
2290 return -1;
2293 /* RLIM_INFINITY is -1 on some platforms. */
2294 limit.rlim_cur = RLIM_INFINITY;
2295 limit.rlim_max = RLIM_INFINITY;
2297 ret = setrlimit(RLIMIT_MEMLOCK, &limit);
2298 if (ret == -1) {
2299 if (errno == EPERM) {
2300 log_warn(LD_GENERAL, "You appear to lack permissions to change memory "
2301 "limits. Are you root?");
2302 log_warn(LD_GENERAL, "Unable to raise RLIMIT_MEMLOCK: %s",
2303 strerror(errno));
2304 } else {
2305 log_warn(LD_GENERAL, "Could not raise RLIMIT_MEMLOCK: %s",
2306 strerror(errno));
2308 return -1;
2311 return 0;
2313 #endif
2315 /** Attempt to lock all current and all future memory pages.
2316 * This should only be called once and while we're privileged.
2317 * Like mlockall() we return 0 when we're successful and -1 when we're not.
2318 * Unlike mlockall() we return 1 if we've already attempted to lock memory.
2321 tor_mlockall(void)
2323 static int memory_lock_attempted = 0;
2325 if (memory_lock_attempted) {
2326 return 1;
2329 memory_lock_attempted = 1;
2332 * Future consideration for Windows may be VirtualLock
2333 * VirtualLock appears to implement mlock() but not mlockall()
2335 * http://msdn.microsoft.com/en-us/library/aa366895(VS.85).aspx
2338 #if defined(HAVE_MLOCKALL) && HAVE_DECL_MLOCKALL && defined(RLIMIT_MEMLOCK)
2339 if (tor_set_max_memlock() == 0) {
2340 /* Perhaps we only want to log this if we're in a verbose mode? */
2341 log_notice(LD_GENERAL, "RLIMIT_MEMLOCK is now set to RLIM_INFINITY.");
2344 if (mlockall(MCL_CURRENT|MCL_FUTURE) == 0) {
2345 log_notice(LD_GENERAL, "Insecure OS paging is effectively disabled.");
2346 return 0;
2347 } else {
2348 if (errno == ENOSYS) {
2349 /* Apple - it's 2009! I'm looking at you. Grrr. */
2350 log_notice(LD_GENERAL, "It appears that mlockall() is not available on "
2351 "your platform.");
2352 } else if (errno == EPERM) {
2353 log_notice(LD_GENERAL, "It appears that you lack the permissions to "
2354 "lock memory. Are you root?");
2356 log_notice(LD_GENERAL, "Unable to lock all current and future memory "
2357 "pages: %s", strerror(errno));
2358 return -1;
2360 #else
2361 log_warn(LD_GENERAL, "Unable to lock memory pages. mlockall() unsupported?");
2362 return -1;
2363 #endif
2366 /** Identity of the "main" thread */
2367 static unsigned long main_thread_id = -1;
2369 /** Start considering the current thread to be the 'main thread'. This has
2370 * no effect on anything besides in_main_thread(). */
2371 void
2372 set_main_thread(void)
2374 main_thread_id = tor_get_thread_id();
2376 /** Return true iff called from the main thread. */
2378 in_main_thread(void)
2380 return main_thread_id == tor_get_thread_id();
2384 * On Windows, WSAEWOULDBLOCK is not always correct: when you see it,
2385 * you need to ask the socket for its actual errno. Also, you need to
2386 * get your errors from WSAGetLastError, not errno. (If you supply a
2387 * socket of -1, we check WSAGetLastError, but don't correct
2388 * WSAEWOULDBLOCKs.)
2390 * The upshot of all of this is that when a socket call fails, you
2391 * should call tor_socket_errno <em>at most once</em> on the failing
2392 * socket to get the error.
2394 #if defined(MS_WINDOWS)
2396 tor_socket_errno(int sock)
2398 int optval, optvallen=sizeof(optval);
2399 int err = WSAGetLastError();
2400 if (err == WSAEWOULDBLOCK && sock >= 0) {
2401 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval, &optvallen))
2402 return err;
2403 if (optval)
2404 return optval;
2406 return err;
2408 #endif
2410 #if defined(MS_WINDOWS)
2411 #define E(code, s) { code, (s " [" #code " ]") }
2412 struct { int code; const char *msg; } windows_socket_errors[] = {
2413 E(WSAEINTR, "Interrupted function call"),
2414 E(WSAEACCES, "Permission denied"),
2415 E(WSAEFAULT, "Bad address"),
2416 E(WSAEINVAL, "Invalid argument"),
2417 E(WSAEMFILE, "Too many open files"),
2418 E(WSAEWOULDBLOCK, "Resource temporarily unavailable"),
2419 E(WSAEINPROGRESS, "Operation now in progress"),
2420 E(WSAEALREADY, "Operation already in progress"),
2421 E(WSAENOTSOCK, "Socket operation on nonsocket"),
2422 E(WSAEDESTADDRREQ, "Destination address required"),
2423 E(WSAEMSGSIZE, "Message too long"),
2424 E(WSAEPROTOTYPE, "Protocol wrong for socket"),
2425 E(WSAENOPROTOOPT, "Bad protocol option"),
2426 E(WSAEPROTONOSUPPORT, "Protocol not supported"),
2427 E(WSAESOCKTNOSUPPORT, "Socket type not supported"),
2428 /* What's the difference between NOTSUPP and NOSUPPORT? :) */
2429 E(WSAEOPNOTSUPP, "Operation not supported"),
2430 E(WSAEPFNOSUPPORT, "Protocol family not supported"),
2431 E(WSAEAFNOSUPPORT, "Address family not supported by protocol family"),
2432 E(WSAEADDRINUSE, "Address already in use"),
2433 E(WSAEADDRNOTAVAIL, "Cannot assign requested address"),
2434 E(WSAENETDOWN, "Network is down"),
2435 E(WSAENETUNREACH, "Network is unreachable"),
2436 E(WSAENETRESET, "Network dropped connection on reset"),
2437 E(WSAECONNABORTED, "Software caused connection abort"),
2438 E(WSAECONNRESET, "Connection reset by peer"),
2439 E(WSAENOBUFS, "No buffer space available"),
2440 E(WSAEISCONN, "Socket is already connected"),
2441 E(WSAENOTCONN, "Socket is not connected"),
2442 E(WSAESHUTDOWN, "Cannot send after socket shutdown"),
2443 E(WSAETIMEDOUT, "Connection timed out"),
2444 E(WSAECONNREFUSED, "Connection refused"),
2445 E(WSAEHOSTDOWN, "Host is down"),
2446 E(WSAEHOSTUNREACH, "No route to host"),
2447 E(WSAEPROCLIM, "Too many processes"),
2448 /* Yes, some of these start with WSA, not WSAE. No, I don't know why. */
2449 E(WSASYSNOTREADY, "Network subsystem is unavailable"),
2450 E(WSAVERNOTSUPPORTED, "Winsock.dll out of range"),
2451 E(WSANOTINITIALISED, "Successful WSAStartup not yet performed"),
2452 E(WSAEDISCON, "Graceful shutdown now in progress"),
2453 #ifdef WSATYPE_NOT_FOUND
2454 E(WSATYPE_NOT_FOUND, "Class type not found"),
2455 #endif
2456 E(WSAHOST_NOT_FOUND, "Host not found"),
2457 E(WSATRY_AGAIN, "Nonauthoritative host not found"),
2458 E(WSANO_RECOVERY, "This is a nonrecoverable error"),
2459 E(WSANO_DATA, "Valid name, no data record of requested type)"),
2461 /* There are some more error codes whose numeric values are marked
2462 * <b>OS dependent</b>. They start with WSA_, apparently for the same
2463 * reason that practitioners of some craft traditions deliberately
2464 * introduce imperfections into their baskets and rugs "to allow the
2465 * evil spirits to escape." If we catch them, then our binaries
2466 * might not report consistent results across versions of Windows.
2467 * Thus, I'm going to let them all fall through.
2469 { -1, NULL },
2471 /** There does not seem to be a strerror equivalent for Winsock errors.
2472 * Naturally, we have to roll our own.
2474 const char *
2475 tor_socket_strerror(int e)
2477 int i;
2478 for (i=0; windows_socket_errors[i].code >= 0; ++i) {
2479 if (e == windows_socket_errors[i].code)
2480 return windows_socket_errors[i].msg;
2482 return strerror(e);
2484 #endif
2486 /** Called before we make any calls to network-related functions.
2487 * (Some operating systems require their network libraries to be
2488 * initialized.) */
2490 network_init(void)
2492 #ifdef MS_WINDOWS
2493 /* This silly exercise is necessary before windows will allow
2494 * gethostbyname to work. */
2495 WSADATA WSAData;
2496 int r;
2497 r = WSAStartup(0x101,&WSAData);
2498 if (r) {
2499 log_warn(LD_NET,"Error initializing windows network layer: code was %d",r);
2500 return -1;
2502 /* WSAData.iMaxSockets might show the max sockets we're allowed to use.
2503 * We might use it to complain if we're trying to be a server but have
2504 * too few sockets available. */
2505 #endif
2506 return 0;
2509 #ifdef MS_WINDOWS
2510 /** Return a newly allocated string describing the windows system error code
2511 * <b>err</b>. Note that error codes are different from errno. Error codes
2512 * come from GetLastError() when a winapi call fails. errno is set only when
2513 * ANSI functions fail. Whee. */
2514 char *
2515 format_win32_error(DWORD err)
2517 LPVOID str = NULL;
2518 char *result;
2520 /* Somebody once decided that this interface was better than strerror(). */
2521 FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
2522 FORMAT_MESSAGE_FROM_SYSTEM |
2523 FORMAT_MESSAGE_IGNORE_INSERTS,
2524 NULL, err,
2525 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
2526 (LPTSTR) &str,
2527 0, NULL);
2529 if (str) {
2530 result = tor_strdup((char*)str);
2531 LocalFree(str); /* LocalFree != free() */
2532 } else {
2533 result = tor_strdup("<unformattable error>");
2535 return result;
2537 #endif