Disallow disabling DisableDebuggerAttachment on runnning Tor
[tor.git] / src / common / compat.c
blobff9d877cd65b397c076fbb775596f4c103cd1d8b
1 /* Copyright (c) 2003-2004, Roger Dingledine
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2011, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
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 /* XXXX023 We should just use AC_USE_SYSTEM_EXTENSIONS in our autoconf,
19 * and get this (and other important stuff!) automatically */
20 #define _GNU_SOURCE
22 #include "compat.h"
24 #ifdef MS_WINDOWS
25 #include <process.h>
26 #include <windows.h>
27 #include <sys/locking.h>
28 #endif
30 #ifdef HAVE_UNAME
31 #include <sys/utsname.h>
32 #endif
33 #ifdef HAVE_UNISTD_H
34 #include <unistd.h>
35 #endif
36 #ifdef HAVE_SYS_FCNTL_H
37 #include <sys/fcntl.h>
38 #endif
39 #ifdef HAVE_PWD_H
40 #include <pwd.h>
41 #endif
42 #ifdef HAVE_GRP_H
43 #include <grp.h>
44 #endif
45 #ifdef HAVE_FCNTL_H
46 #include <fcntl.h>
47 #endif
48 #ifdef HAVE_ERRNO_H
49 #include <errno.h>
50 #endif
51 #ifdef HAVE_ARPA_INET_H
52 #include <arpa/inet.h>
53 #endif
55 #ifndef HAVE_GETTIMEOFDAY
56 #ifdef HAVE_FTIME
57 #include <sys/timeb.h>
58 #endif
59 #endif
61 /* Includes for the process attaching prevention */
62 #if defined(HAVE_SYS_PRCTL_H) && defined(__linux__)
63 #include <sys/prctl.h>
64 #elif defined(__APPLE__)
65 #include <sys/types.h>
66 #include <sys/ptrace.h>
67 #endif
69 #ifdef HAVE_NETDB_H
70 #include <netdb.h>
71 #endif
72 #ifdef HAVE_SYS_PARAM_H
73 #include <sys/param.h> /* FreeBSD needs this to know what version it is */
74 #endif
75 #include <stdio.h>
76 #include <stdlib.h>
77 #include <assert.h>
78 #ifdef HAVE_SIGNAL_H
79 #include <signal.h>
80 #endif
81 #ifdef HAVE_UTIME_H
82 #include <utime.h>
83 #endif
84 #ifdef HAVE_SYS_UTIME_H
85 #include <sys/utime.h>
86 #endif
87 #ifdef HAVE_SYS_MMAN_H
88 #include <sys/mman.h>
89 #endif
90 #ifdef HAVE_SYS_SYSLIMITS_H
91 #include <sys/syslimits.h>
92 #endif
93 #ifdef HAVE_SYS_FILE_H
94 #include <sys/file.h>
95 #endif
96 #if defined(HAVE_SYS_PRCTL_H) && defined(__linux__)
97 /* Only use the linux prctl; the IRIX prctl is totally different */
98 #include <sys/prctl.h>
99 #endif
101 #include "torlog.h"
102 #include "util.h"
103 #include "container.h"
104 #include "address.h"
106 /* Inline the strl functions if the platform doesn't have them. */
107 #ifndef HAVE_STRLCPY
108 #include "strlcpy.c"
109 #endif
110 #ifndef HAVE_STRLCAT
111 #include "strlcat.c"
112 #endif
114 /** As open(path, flags, mode), but return an fd with the close-on-exec mode
115 * set. */
117 tor_open_cloexec(const char *path, int flags, unsigned mode)
119 #ifdef O_CLOEXEC
120 return open(path, flags|O_CLOEXEC, mode);
121 #else
122 int fd = open(path, flags, mode);
123 #ifdef FD_CLOEXEC
124 if (fd >= 0)
125 fcntl(fd, F_SETFD, FD_CLOEXEC);
126 #endif
127 return fd;
128 #endif
131 /** DOCDOC */
132 FILE *
133 tor_fopen_cloexec(const char *path, const char *mode)
135 FILE *result = fopen(path, mode);
136 #ifdef FD_CLOEXEC
137 if (result != NULL)
138 fcntl(fileno(result), F_SETFD, FD_CLOEXEC);
139 #endif
140 return result;
143 #ifdef HAVE_SYS_MMAN_H
144 /** Try to create a memory mapping for <b>filename</b> and return it. On
145 * failure, return NULL. Sets errno properly, using ERANGE to mean
146 * "empty file". */
147 tor_mmap_t *
148 tor_mmap_file(const char *filename)
150 int fd; /* router file */
151 char *string;
152 int page_size;
153 tor_mmap_t *res;
154 size_t size, filesize;
156 tor_assert(filename);
158 fd = tor_open_cloexec(filename, O_RDONLY, 0);
159 if (fd<0) {
160 int save_errno = errno;
161 int severity = (errno == ENOENT) ? LOG_INFO : LOG_WARN;
162 log_fn(severity, LD_FS,"Could not open \"%s\" for mmap(): %s",filename,
163 strerror(errno));
164 errno = save_errno;
165 return NULL;
168 /* XXXX why not just do fstat here? */
169 size = filesize = (size_t) lseek(fd, 0, SEEK_END);
170 lseek(fd, 0, SEEK_SET);
171 /* ensure page alignment */
172 page_size = getpagesize();
173 size += (size%page_size) ? page_size-(size%page_size) : 0;
175 if (!size) {
176 /* Zero-length file. If we call mmap on it, it will succeed but
177 * return NULL, and bad things will happen. So just fail. */
178 log_info(LD_FS,"File \"%s\" is empty. Ignoring.",filename);
179 errno = ERANGE;
180 close(fd);
181 return NULL;
184 string = mmap(0, size, PROT_READ, MAP_PRIVATE, fd, 0);
185 close(fd);
186 if (string == MAP_FAILED) {
187 int save_errno = errno;
188 log_warn(LD_FS,"Could not mmap file \"%s\": %s", filename,
189 strerror(errno));
190 errno = save_errno;
191 return NULL;
194 res = tor_malloc_zero(sizeof(tor_mmap_t));
195 res->data = string;
196 res->size = filesize;
197 res->mapping_size = size;
199 return res;
201 /** Release storage held for a memory mapping. */
202 void
203 tor_munmap_file(tor_mmap_t *handle)
205 munmap((char*)handle->data, handle->mapping_size);
206 tor_free(handle);
208 #elif defined(MS_WINDOWS)
209 tor_mmap_t *
210 tor_mmap_file(const char *filename)
212 TCHAR tfilename[MAX_PATH]= {0};
213 tor_mmap_t *res = tor_malloc_zero(sizeof(tor_mmap_t));
214 int empty = 0;
215 res->file_handle = INVALID_HANDLE_VALUE;
216 res->mmap_handle = NULL;
217 #ifdef UNICODE
218 mbstowcs(tfilename,filename,MAX_PATH);
219 #else
220 strlcpy(tfilename,filename,MAX_PATH);
221 #endif
222 res->file_handle = CreateFile(tfilename,
223 GENERIC_READ, FILE_SHARE_READ,
224 NULL,
225 OPEN_EXISTING,
226 FILE_ATTRIBUTE_NORMAL,
229 if (res->file_handle == INVALID_HANDLE_VALUE)
230 goto win_err;
232 res->size = GetFileSize(res->file_handle, NULL);
234 if (res->size == 0) {
235 log_info(LD_FS,"File \"%s\" is empty. Ignoring.",filename);
236 empty = 1;
237 goto err;
240 res->mmap_handle = CreateFileMapping(res->file_handle,
241 NULL,
242 PAGE_READONLY,
243 #if SIZEOF_SIZE_T > 4
244 (res->base.size >> 32),
245 #else
247 #endif
248 (res->size & 0xfffffffful),
249 NULL);
250 if (res->mmap_handle == NULL)
251 goto win_err;
252 res->data = (char*) MapViewOfFile(res->mmap_handle,
253 FILE_MAP_READ,
254 0, 0, 0);
255 if (!res->data)
256 goto win_err;
258 return res;
259 win_err: {
260 DWORD e = GetLastError();
261 int severity = (e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND) ?
262 LOG_INFO : LOG_WARN;
263 char *msg = format_win32_error(e);
264 log_fn(severity, LD_FS, "Couldn't mmap file \"%s\": %s", filename, msg);
265 tor_free(msg);
266 if (e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND)
267 errno = ENOENT;
268 else
269 errno = EINVAL;
271 err:
272 if (empty)
273 errno = ERANGE;
274 tor_munmap_file(res);
275 return NULL;
277 void
278 tor_munmap_file(tor_mmap_t *handle)
280 if (handle->data)
281 /* This is an ugly cast, but without it, "data" in struct tor_mmap_t would
282 have to be redefined as non-const. */
283 UnmapViewOfFile( (LPVOID) handle->data);
285 if (handle->mmap_handle != NULL)
286 CloseHandle(handle->mmap_handle);
287 if (handle->file_handle != INVALID_HANDLE_VALUE)
288 CloseHandle(handle->file_handle);
289 tor_free(handle);
291 #else
292 tor_mmap_t *
293 tor_mmap_file(const char *filename)
295 struct stat st;
296 char *res = read_file_to_str(filename, RFTS_BIN|RFTS_IGNORE_MISSING, &st);
297 tor_mmap_t *handle;
298 if (! res)
299 return NULL;
300 handle = tor_malloc_zero(sizeof(tor_mmap_t));
301 handle->data = res;
302 handle->size = st.st_size;
303 return handle;
305 void
306 tor_munmap_file(tor_mmap_t *handle)
308 char *d = (char*)handle->data;
309 tor_free(d);
310 memset(handle, 0, sizeof(tor_mmap_t));
311 tor_free(handle);
313 #endif
315 /** Replacement for snprintf. Differs from platform snprintf in two
316 * ways: First, always NUL-terminates its output. Second, always
317 * returns -1 if the result is truncated. (Note that this return
318 * behavior does <i>not</i> conform to C99; it just happens to be
319 * easier to emulate "return -1" with conformant implementations than
320 * it is to emulate "return number that would be written" with
321 * non-conformant implementations.) */
323 tor_snprintf(char *str, size_t size, const char *format, ...)
325 va_list ap;
326 int r;
327 va_start(ap,format);
328 r = tor_vsnprintf(str,size,format,ap);
329 va_end(ap);
330 return r;
333 /** Replacement for vsnprintf; behavior differs as tor_snprintf differs from
334 * snprintf.
337 tor_vsnprintf(char *str, size_t size, const char *format, va_list args)
339 int r;
340 if (size == 0)
341 return -1; /* no place for the NUL */
342 if (size > SIZE_T_CEILING)
343 return -1;
344 #ifdef MS_WINDOWS
345 r = _vsnprintf(str, size, format, args);
346 #else
347 r = vsnprintf(str, size, format, args);
348 #endif
349 str[size-1] = '\0';
350 if (r < 0 || r >= (ssize_t)size)
351 return -1;
352 return r;
356 * Portable asprintf implementation. Does a printf() into a newly malloc'd
357 * string. Sets *<b>strp</b> to this string, and returns its length (not
358 * including the terminating NUL character).
360 * You can treat this function as if its implementation were something like
361 <pre>
362 char buf[_INFINITY_];
363 tor_snprintf(buf, sizeof(buf), fmt, args);
364 *strp = tor_strdup(buf);
365 return strlen(*strp):
366 </pre>
367 * Where _INFINITY_ is an imaginary constant so big that any string can fit
368 * into it.
371 tor_asprintf(char **strp, const char *fmt, ...)
373 int r;
374 va_list args;
375 va_start(args, fmt);
376 r = tor_vasprintf(strp, fmt, args);
377 va_end(args);
378 if (!*strp || r < 0) {
379 log_err(LD_BUG, "Internal error in asprintf");
380 tor_assert(0);
382 return r;
386 * Portable vasprintf implementation. Does a printf() into a newly malloc'd
387 * string. Differs from regular vasprintf in the same ways that
388 * tor_asprintf() differs from regular asprintf.
391 tor_vasprintf(char **strp, const char *fmt, va_list args)
393 /* use a temporary variable in case *strp is in args. */
394 char *strp_tmp=NULL;
395 #ifdef HAVE_VASPRINTF
396 /* If the platform gives us one, use it. */
397 int r = vasprintf(&strp_tmp, fmt, args);
398 if (r < 0)
399 *strp = NULL;
400 else
401 *strp = strp_tmp;
402 return r;
403 #elif defined(_MSC_VER)
404 /* On Windows, _vsnprintf won't tell us the length of the string if it
405 * overflows, so we need to use _vcsprintf to tell how much to allocate */
406 int len, r;
407 char *res;
408 len = _vscprintf(fmt, args);
409 if (len < 0) {
410 *strp = NULL;
411 return -1;
413 strp_tmp = tor_malloc(len + 1);
414 r = _vsnprintf(strp_tmp, len+1, fmt, args);
415 if (r != len) {
416 tor_free(strp_tmp);
417 *strp = NULL;
418 return -1;
420 *strp = strp_tmp;
421 return len;
422 #else
423 /* Everywhere else, we have a decent vsnprintf that tells us how many
424 * characters we need. We give it a try on a short buffer first, since
425 * it might be nice to avoid the second vsnprintf call.
427 char buf[128];
428 int len, r;
429 va_list tmp_args;
430 va_copy(tmp_args, args);
431 len = vsnprintf(buf, sizeof(buf), fmt, tmp_args);
432 va_end(tmp_args);
433 if (len < (int)sizeof(buf)) {
434 *strp = tor_strdup(buf);
435 return len;
437 strp_tmp = tor_malloc(len+1);
438 r = vsnprintf(strp_tmp, len+1, fmt, args);
439 if (r != len) {
440 tor_free(strp_tmp);
441 *strp = NULL;
442 return -1;
444 *strp = strp_tmp;
445 return len;
446 #endif
449 /** Given <b>hlen</b> bytes at <b>haystack</b> and <b>nlen</b> bytes at
450 * <b>needle</b>, return a pointer to the first occurrence of the needle
451 * within the haystack, or NULL if there is no such occurrence.
453 * This function is <em>not</em> timing-safe.
455 * Requires that <b>nlen</b> be greater than zero.
457 const void *
458 tor_memmem(const void *_haystack, size_t hlen,
459 const void *_needle, size_t nlen)
461 #if defined(HAVE_MEMMEM) && (!defined(__GNUC__) || __GNUC__ >= 2)
462 tor_assert(nlen);
463 return memmem(_haystack, hlen, _needle, nlen);
464 #else
465 /* This isn't as fast as the GLIBC implementation, but it doesn't need to
466 * be. */
467 const char *p, *end;
468 const char *haystack = (const char*)_haystack;
469 const char *needle = (const char*)_needle;
470 char first;
471 tor_assert(nlen);
473 p = haystack;
474 end = haystack + hlen;
475 first = *(const char*)needle;
476 while ((p = memchr(p, first, end-p))) {
477 if (p+nlen > end)
478 return NULL;
479 if (fast_memeq(p, needle, nlen))
480 return p;
481 ++p;
483 return NULL;
484 #endif
487 /* Tables to implement ctypes-replacement TOR_IS*() functions. Each table
488 * has 256 bits to look up whether a character is in some set or not. This
489 * fails on non-ASCII platforms, but it is hard to find a platform whose
490 * character set is not a superset of ASCII nowadays. */
491 const uint32_t TOR_ISALPHA_TABLE[8] =
492 { 0, 0, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
493 const uint32_t TOR_ISALNUM_TABLE[8] =
494 { 0, 0x3ff0000, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
495 const uint32_t TOR_ISSPACE_TABLE[8] = { 0x3e00, 0x1, 0, 0, 0, 0, 0, 0 };
496 const uint32_t TOR_ISXDIGIT_TABLE[8] =
497 { 0, 0x3ff0000, 0x7e, 0x7e, 0, 0, 0, 0 };
498 const uint32_t TOR_ISDIGIT_TABLE[8] = { 0, 0x3ff0000, 0, 0, 0, 0, 0, 0 };
499 const uint32_t TOR_ISPRINT_TABLE[8] =
500 { 0, 0xffffffff, 0xffffffff, 0x7fffffff, 0, 0, 0, 0x0 };
501 const uint32_t TOR_ISUPPER_TABLE[8] = { 0, 0, 0x7fffffe, 0, 0, 0, 0, 0 };
502 const uint32_t TOR_ISLOWER_TABLE[8] = { 0, 0, 0, 0x7fffffe, 0, 0, 0, 0 };
503 /* Upper-casing and lowercasing tables to map characters to upper/lowercase
504 * equivalents. */
505 const char TOR_TOUPPER_TABLE[256] = {
506 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
507 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
508 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
509 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
510 64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
511 80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
512 96,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
513 80,81,82,83,84,85,86,87,88,89,90,123,124,125,126,127,
514 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
515 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
516 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
517 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
518 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
519 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
520 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
521 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
523 const char TOR_TOLOWER_TABLE[256] = {
524 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
525 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
526 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
527 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
528 64,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
529 112,113,114,115,116,117,118,119,120,121,122,91,92,93,94,95,
530 96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
531 112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
532 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
533 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
534 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
535 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
536 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
537 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
538 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
539 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
542 /** Implementation of strtok_r for platforms whose coders haven't figured out
543 * how to write one. Hey guys! You can use this code here for free! */
544 char *
545 tor_strtok_r_impl(char *str, const char *sep, char **lasts)
547 char *cp, *start;
548 if (str)
549 start = cp = *lasts = str;
550 else if (!*lasts)
551 return NULL;
552 else
553 start = cp = *lasts;
555 tor_assert(*sep);
556 if (sep[1]) {
557 while (*cp && !strchr(sep, *cp))
558 ++cp;
559 } else {
560 tor_assert(strlen(sep) == 1);
561 cp = strchr(cp, *sep);
564 if (!cp || !*cp) {
565 *lasts = NULL;
566 } else {
567 *cp++ = '\0';
568 *lasts = cp;
570 return start;
573 #ifdef MS_WINDOWS
574 /** Take a filename and return a pointer to its final element. This
575 * function is called on __FILE__ to fix a MSVC nit where __FILE__
576 * contains the full path to the file. This is bad, because it
577 * confuses users to find the home directory of the person who
578 * compiled the binary in their warning messages.
580 const char *
581 tor_fix_source_file(const char *fname)
583 const char *cp1, *cp2, *r;
584 cp1 = strrchr(fname, '/');
585 cp2 = strrchr(fname, '\\');
586 if (cp1 && cp2) {
587 r = (cp1<cp2)?(cp2+1):(cp1+1);
588 } else if (cp1) {
589 r = cp1+1;
590 } else if (cp2) {
591 r = cp2+1;
592 } else {
593 r = fname;
595 return r;
597 #endif
600 * Read a 16-bit value beginning at <b>cp</b>. Equivalent to
601 * *(uint16_t*)(cp), but will not cause segfaults on platforms that forbid
602 * unaligned memory access.
604 uint16_t
605 get_uint16(const void *cp)
607 uint16_t v;
608 memcpy(&v,cp,2);
609 return v;
612 * Read a 32-bit value beginning at <b>cp</b>. Equivalent to
613 * *(uint32_t*)(cp), but will not cause segfaults on platforms that forbid
614 * unaligned memory access.
616 uint32_t
617 get_uint32(const void *cp)
619 uint32_t v;
620 memcpy(&v,cp,4);
621 return v;
624 * Read a 64-bit value beginning at <b>cp</b>. Equivalent to
625 * *(uint64_t*)(cp), but will not cause segfaults on platforms that forbid
626 * unaligned memory access.
628 uint64_t
629 get_uint64(const void *cp)
631 uint64_t v;
632 memcpy(&v,cp,8);
633 return v;
637 * Set a 16-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
638 * *(uint16_t*)(cp) = v, but will not cause segfaults on platforms that forbid
639 * unaligned memory access. */
640 void
641 set_uint16(void *cp, uint16_t v)
643 memcpy(cp,&v,2);
646 * Set a 32-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
647 * *(uint32_t*)(cp) = v, but will not cause segfaults on platforms that forbid
648 * unaligned memory access. */
649 void
650 set_uint32(void *cp, uint32_t v)
652 memcpy(cp,&v,4);
655 * Set a 64-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
656 * *(uint64_t*)(cp) = v, but will not cause segfaults on platforms that forbid
657 * unaligned memory access. */
658 void
659 set_uint64(void *cp, uint64_t v)
661 memcpy(cp,&v,8);
665 * Rename the file <b>from</b> to the file <b>to</b>. On Unix, this is
666 * the same as rename(2). On windows, this removes <b>to</b> first if
667 * it already exists.
668 * Returns 0 on success. Returns -1 and sets errno on failure.
671 replace_file(const char *from, const char *to)
673 #ifndef MS_WINDOWS
674 return rename(from,to);
675 #else
676 switch (file_status(to))
678 case FN_NOENT:
679 break;
680 case FN_FILE:
681 if (unlink(to)) return -1;
682 break;
683 case FN_ERROR:
684 return -1;
685 case FN_DIR:
686 errno = EISDIR;
687 return -1;
689 return rename(from,to);
690 #endif
693 /** Change <b>fname</b>'s modification time to now. */
695 touch_file(const char *fname)
697 if (utime(fname, NULL)!=0)
698 return -1;
699 return 0;
702 /** Represents a lockfile on which we hold the lock. */
703 struct tor_lockfile_t {
704 /** Name of the file */
705 char *filename;
706 /** File descriptor used to hold the file open */
707 int fd;
710 /** Try to get a lock on the lockfile <b>filename</b>, creating it as
711 * necessary. If someone else has the lock and <b>blocking</b> is true,
712 * wait until the lock is available. Otherwise return immediately whether
713 * we succeeded or not.
715 * Set *<b>locked_out</b> to true if somebody else had the lock, and to false
716 * otherwise.
718 * Return a <b>tor_lockfile_t</b> on success, NULL on failure.
720 * (Implementation note: because we need to fall back to fcntl on some
721 * platforms, these locks are per-process, not per-thread. If you want
722 * to do in-process locking, use tor_mutex_t like a normal person.
723 * On Windows, when <b>blocking</b> is true, the maximum time that
724 * is actually waited is 10 seconds, after which NULL is returned
725 * and <b>locked_out</b> is set to 1.)
727 tor_lockfile_t *
728 tor_lockfile_lock(const char *filename, int blocking, int *locked_out)
730 tor_lockfile_t *result;
731 int fd;
732 *locked_out = 0;
734 log_info(LD_FS, "Locking \"%s\"", filename);
735 fd = tor_open_cloexec(filename, O_RDWR|O_CREAT|O_TRUNC, 0600);
736 if (fd < 0) {
737 log_warn(LD_FS,"Couldn't open \"%s\" for locking: %s", filename,
738 strerror(errno));
739 return NULL;
742 #ifdef WIN32
743 _lseek(fd, 0, SEEK_SET);
744 if (_locking(fd, blocking ? _LK_LOCK : _LK_NBLCK, 1) < 0) {
745 if (errno != EACCES && errno != EDEADLOCK)
746 log_warn(LD_FS,"Couldn't lock \"%s\": %s", filename, strerror(errno));
747 else
748 *locked_out = 1;
749 close(fd);
750 return NULL;
752 #elif defined(HAVE_FLOCK)
753 if (flock(fd, LOCK_EX|(blocking ? 0 : LOCK_NB)) < 0) {
754 if (errno != EWOULDBLOCK)
755 log_warn(LD_FS,"Couldn't lock \"%s\": %s", filename, strerror(errno));
756 else
757 *locked_out = 1;
758 close(fd);
759 return NULL;
761 #else
763 struct flock lock;
764 memset(&lock, 0, sizeof(lock));
765 lock.l_type = F_WRLCK;
766 lock.l_whence = SEEK_SET;
767 if (fcntl(fd, blocking ? F_SETLKW : F_SETLK, &lock) < 0) {
768 if (errno != EACCES && errno != EAGAIN)
769 log_warn(LD_FS, "Couldn't lock \"%s\": %s", filename, strerror(errno));
770 else
771 *locked_out = 1;
772 close(fd);
773 return NULL;
776 #endif
778 result = tor_malloc(sizeof(tor_lockfile_t));
779 result->filename = tor_strdup(filename);
780 result->fd = fd;
781 return result;
784 /** Release the lock held as <b>lockfile</b>. */
785 void
786 tor_lockfile_unlock(tor_lockfile_t *lockfile)
788 tor_assert(lockfile);
790 log_info(LD_FS, "Unlocking \"%s\"", lockfile->filename);
791 #ifdef WIN32
792 _lseek(lockfile->fd, 0, SEEK_SET);
793 if (_locking(lockfile->fd, _LK_UNLCK, 1) < 0) {
794 log_warn(LD_FS,"Error unlocking \"%s\": %s", lockfile->filename,
795 strerror(errno));
797 #elif defined(HAVE_FLOCK)
798 if (flock(lockfile->fd, LOCK_UN) < 0) {
799 log_warn(LD_FS, "Error unlocking \"%s\": %s", lockfile->filename,
800 strerror(errno));
802 #else
803 /* Closing the lockfile is sufficient. */
804 #endif
806 close(lockfile->fd);
807 lockfile->fd = -1;
808 tor_free(lockfile->filename);
809 tor_free(lockfile);
812 /** @{ */
813 /** Some old versions of Unix didn't define constants for these values,
814 * and instead expect you to say 0, 1, or 2. */
815 #ifndef SEEK_CUR
816 #define SEEK_CUR 1
817 #endif
818 #ifndef SEEK_END
819 #define SEEK_END 2
820 #endif
821 /** @} */
823 /** Return the position of <b>fd</b> with respect to the start of the file. */
824 off_t
825 tor_fd_getpos(int fd)
827 #ifdef WIN32
828 return (off_t) _lseek(fd, 0, SEEK_CUR);
829 #else
830 return (off_t) lseek(fd, 0, SEEK_CUR);
831 #endif
834 /** Move <b>fd</b> to the end of the file. Return -1 on error, 0 on success. */
836 tor_fd_seekend(int fd)
838 #ifdef WIN32
839 return _lseek(fd, 0, SEEK_END) < 0 ? -1 : 0;
840 #else
841 return lseek(fd, 0, SEEK_END) < 0 ? -1 : 0;
842 #endif
845 #undef DEBUG_SOCKET_COUNTING
846 #ifdef DEBUG_SOCKET_COUNTING
847 /** A bitarray of all fds that should be passed to tor_socket_close(). Only
848 * used if DEBUG_SOCKET_COUNTING is defined. */
849 static bitarray_t *open_sockets = NULL;
850 /** The size of <b>open_sockets</b>, in bits. */
851 static int max_socket = -1;
852 #endif
854 /** Count of number of sockets currently open. (Undercounts sockets opened by
855 * eventdns and libevent.) */
856 static int n_sockets_open = 0;
858 /** Mutex to protect open_sockets, max_socket, and n_sockets_open. */
859 static tor_mutex_t *socket_accounting_mutex = NULL;
861 /** Helper: acquire the socket accounting lock. */
862 static INLINE void
863 socket_accounting_lock(void)
865 if (PREDICT_UNLIKELY(!socket_accounting_mutex))
866 socket_accounting_mutex = tor_mutex_new();
867 tor_mutex_acquire(socket_accounting_mutex);
870 /** Helper: release the socket accounting lock. */
871 static INLINE void
872 socket_accounting_unlock(void)
874 tor_mutex_release(socket_accounting_mutex);
877 /** As close(), but guaranteed to work for sockets across platforms (including
878 * Windows, where close()ing a socket doesn't work. Returns 0 on success, -1
879 * on failure. */
881 tor_close_socket(tor_socket_t s)
883 int r = 0;
885 /* On Windows, you have to call close() on fds returned by open(),
886 * and closesocket() on fds returned by socket(). On Unix, everything
887 * gets close()'d. We abstract this difference by always using
888 * tor_close_socket to close sockets, and always using close() on
889 * files.
891 #if defined(MS_WINDOWS)
892 r = closesocket(s);
893 #else
894 r = close(s);
895 #endif
897 socket_accounting_lock();
898 #ifdef DEBUG_SOCKET_COUNTING
899 if (s > max_socket || ! bitarray_is_set(open_sockets, s)) {
900 log_warn(LD_BUG, "Closing a socket (%d) that wasn't returned by tor_open_"
901 "socket(), or that was already closed or something.", s);
902 } else {
903 tor_assert(open_sockets && s <= max_socket);
904 bitarray_clear(open_sockets, s);
906 #endif
907 if (r == 0) {
908 --n_sockets_open;
909 } else {
910 int err = tor_socket_errno(-1);
911 log_info(LD_NET, "Close returned an error: %s", tor_socket_strerror(err));
912 #ifdef WIN32
913 if (err != WSAENOTSOCK)
914 --n_sockets_open;
915 #else
916 if (err != EBADF)
917 --n_sockets_open;
918 #endif
919 r = -1;
922 if (n_sockets_open < 0)
923 log_warn(LD_BUG, "Our socket count is below zero: %d. Please submit a "
924 "bug report.", n_sockets_open);
925 socket_accounting_unlock();
926 return r;
929 /** @{ */
930 #ifdef DEBUG_SOCKET_COUNTING
931 /** Helper: if DEBUG_SOCKET_COUNTING is enabled, remember that <b>s</b> is
932 * now an open socket. */
933 static INLINE void
934 mark_socket_open(tor_socket_t s)
936 /* XXXX This bitarray business will NOT work on windows: sockets aren't
937 small ints there. */
938 if (s > max_socket) {
939 if (max_socket == -1) {
940 open_sockets = bitarray_init_zero(s+128);
941 max_socket = s+128;
942 } else {
943 open_sockets = bitarray_expand(open_sockets, max_socket, s+128);
944 max_socket = s+128;
947 if (bitarray_is_set(open_sockets, s)) {
948 log_warn(LD_BUG, "I thought that %d was already open, but socket() just "
949 "gave it to me!", s);
951 bitarray_set(open_sockets, s);
953 #else
954 #define mark_socket_open(s) STMT_NIL
955 #endif
956 /** @} */
958 /** As socket(), but counts the number of open sockets. */
959 tor_socket_t
960 tor_open_socket(int domain, int type, int protocol)
962 tor_socket_t s;
963 #ifdef SOCK_CLOEXEC
964 #define LINUX_CLOEXEC_OPEN_SOCKET
965 type |= SOCK_CLOEXEC;
966 #endif
967 s = socket(domain, type, protocol);
968 if (SOCKET_OK(s)) {
969 #if !defined(LINUX_CLOEXEC_OPEN_SOCKET) && defined(FD_CLOEXEC)
970 fcntl(s, F_SETFD, FD_CLOEXEC);
971 #endif
972 socket_accounting_lock();
973 ++n_sockets_open;
974 mark_socket_open(s);
975 socket_accounting_unlock();
977 return s;
980 /** As socket(), but counts the number of open sockets. */
981 tor_socket_t
982 tor_accept_socket(tor_socket_t sockfd, struct sockaddr *addr, socklen_t *len)
984 tor_socket_t s;
985 #if defined(HAVE_ACCEPT4) && defined(SOCK_CLOEXEC)
986 #define LINUX_CLOEXEC_ACCEPT
987 s = accept4(sockfd, addr, len, SOCK_CLOEXEC);
988 #else
989 s = accept(sockfd, addr, len);
990 #endif
991 if (SOCKET_OK(s)) {
992 #if !defined(LINUX_CLOEXEC_ACCEPT) && defined(FD_CLOEXEC)
993 fcntl(s, F_SETFD, FD_CLOEXEC);
994 #endif
995 socket_accounting_lock();
996 ++n_sockets_open;
997 mark_socket_open(s);
998 socket_accounting_unlock();
1000 return s;
1003 /** Return the number of sockets we currently have opened. */
1005 get_n_open_sockets(void)
1007 int n;
1008 socket_accounting_lock();
1009 n = n_sockets_open;
1010 socket_accounting_unlock();
1011 return n;
1014 /** Turn <b>socket</b> into a nonblocking socket.
1016 void
1017 set_socket_nonblocking(tor_socket_t socket)
1019 #if defined(MS_WINDOWS)
1020 unsigned long nonblocking = 1;
1021 ioctlsocket(socket, FIONBIO, (unsigned long*) &nonblocking);
1022 #else
1023 fcntl(socket, F_SETFL, O_NONBLOCK);
1024 #endif
1028 * Allocate a pair of connected sockets. (Like socketpair(family,
1029 * type,protocol,fd), but works on systems that don't have
1030 * socketpair.)
1032 * Currently, only (AF_UNIX, SOCK_STREAM, 0) sockets are supported.
1034 * Note that on systems without socketpair, this call will fail if
1035 * localhost is inaccessible (for example, if the networking
1036 * stack is down). And even if it succeeds, the socket pair will not
1037 * be able to read while localhost is down later (the socket pair may
1038 * even close, depending on OS-specific timeouts).
1040 * Returns 0 on success and -errno on failure; do not rely on the value
1041 * of errno or WSAGetLastError().
1043 /* It would be nicer just to set errno, but that won't work for windows. */
1045 tor_socketpair(int family, int type, int protocol, tor_socket_t fd[2])
1047 //don't use win32 socketpairs (they are always bad)
1048 #if defined(HAVE_SOCKETPAIR) && !defined(MS_WINDOWS)
1049 int r;
1050 #ifdef SOCK_CLOEXEC
1051 type |= SOCK_CLOEXEC;
1052 #endif
1053 r = socketpair(family, type, protocol, fd);
1054 if (r == 0) {
1055 #if !defined(SOCK_CLOEXEC) && defined(FD_CLOEXEC)
1056 if (fd[0] >= 0)
1057 fcntl(fd[0], F_SETFD, FD_CLOEXEC);
1058 if (fd[1] >= 0)
1059 fcntl(fd[1], F_SETFD, FD_CLOEXEC);
1060 #endif
1061 socket_accounting_lock();
1062 if (fd[0] >= 0) {
1063 ++n_sockets_open;
1064 mark_socket_open(fd[0]);
1066 if (fd[1] >= 0) {
1067 ++n_sockets_open;
1068 mark_socket_open(fd[1]);
1070 socket_accounting_unlock();
1072 return r < 0 ? -errno : r;
1073 #else
1074 /* This socketpair does not work when localhost is down. So
1075 * it's really not the same thing at all. But it's close enough
1076 * for now, and really, when localhost is down sometimes, we
1077 * have other problems too.
1079 tor_socket_t listener = -1;
1080 tor_socket_t connector = -1;
1081 tor_socket_t acceptor = -1;
1082 struct sockaddr_in listen_addr;
1083 struct sockaddr_in connect_addr;
1084 int size;
1085 int saved_errno = -1;
1087 if (protocol
1088 #ifdef AF_UNIX
1089 || family != AF_UNIX
1090 #endif
1092 #ifdef MS_WINDOWS
1093 return -WSAEAFNOSUPPORT;
1094 #else
1095 return -EAFNOSUPPORT;
1096 #endif
1098 if (!fd) {
1099 return -EINVAL;
1102 listener = tor_open_socket(AF_INET, type, 0);
1103 if (listener < 0)
1104 return -tor_socket_errno(-1);
1105 memset(&listen_addr, 0, sizeof(listen_addr));
1106 listen_addr.sin_family = AF_INET;
1107 listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
1108 listen_addr.sin_port = 0; /* kernel chooses port. */
1109 if (bind(listener, (struct sockaddr *) &listen_addr, sizeof (listen_addr))
1110 == -1)
1111 goto tidy_up_and_fail;
1112 if (listen(listener, 1) == -1)
1113 goto tidy_up_and_fail;
1115 connector = tor_open_socket(AF_INET, type, 0);
1116 if (connector < 0)
1117 goto tidy_up_and_fail;
1118 /* We want to find out the port number to connect to. */
1119 size = sizeof(connect_addr);
1120 if (getsockname(listener, (struct sockaddr *) &connect_addr, &size) == -1)
1121 goto tidy_up_and_fail;
1122 if (size != sizeof (connect_addr))
1123 goto abort_tidy_up_and_fail;
1124 if (connect(connector, (struct sockaddr *) &connect_addr,
1125 sizeof(connect_addr)) == -1)
1126 goto tidy_up_and_fail;
1128 size = sizeof(listen_addr);
1129 acceptor = tor_accept_socket(listener,
1130 (struct sockaddr *) &listen_addr, &size);
1131 if (acceptor < 0)
1132 goto tidy_up_and_fail;
1133 if (size != sizeof(listen_addr))
1134 goto abort_tidy_up_and_fail;
1135 tor_close_socket(listener);
1136 /* Now check we are talking to ourself by matching port and host on the
1137 two sockets. */
1138 if (getsockname(connector, (struct sockaddr *) &connect_addr, &size) == -1)
1139 goto tidy_up_and_fail;
1140 if (size != sizeof (connect_addr)
1141 || listen_addr.sin_family != connect_addr.sin_family
1142 || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
1143 || listen_addr.sin_port != connect_addr.sin_port) {
1144 goto abort_tidy_up_and_fail;
1146 fd[0] = connector;
1147 fd[1] = acceptor;
1149 return 0;
1151 abort_tidy_up_and_fail:
1152 #ifdef MS_WINDOWS
1153 saved_errno = WSAECONNABORTED;
1154 #else
1155 saved_errno = ECONNABORTED; /* I hope this is portable and appropriate. */
1156 #endif
1157 tidy_up_and_fail:
1158 if (saved_errno < 0)
1159 saved_errno = errno;
1160 if (listener != -1)
1161 tor_close_socket(listener);
1162 if (connector != -1)
1163 tor_close_socket(connector);
1164 if (acceptor != -1)
1165 tor_close_socket(acceptor);
1166 return -saved_errno;
1167 #endif
1170 /** Number of extra file descriptors to keep in reserve beyond those that we
1171 * tell Tor it's allowed to use. */
1172 #define ULIMIT_BUFFER 32 /* keep 32 extra fd's beyond _ConnLimit */
1174 /** Learn the maximum allowed number of file descriptors. (Some systems
1175 * have a low soft limit.
1177 * We compute this by finding the largest number that we can use.
1178 * If we can't find a number greater than or equal to <b>limit</b>,
1179 * then we fail: return -1.
1181 * Otherwise, return 0 and store the maximum we found inside <b>max_out</b>.*/
1183 set_max_file_descriptors(rlim_t limit, int *max_out)
1185 /* Define some maximum connections values for systems where we cannot
1186 * automatically determine a limit. Re Cygwin, see
1187 * http://archives.seul.org/or/talk/Aug-2006/msg00210.html
1188 * For an iPhone, 9999 should work. For Windows and all other unknown
1189 * systems we use 15000 as the default. */
1190 #ifndef HAVE_GETRLIMIT
1191 #if defined(CYGWIN) || defined(__CYGWIN__)
1192 const char *platform = "Cygwin";
1193 const unsigned long MAX_CONNECTIONS = 3200;
1194 #elif defined(MS_WINDOWS)
1195 const char *platform = "Windows";
1196 const unsigned long MAX_CONNECTIONS = 15000;
1197 #else
1198 const char *platform = "unknown platforms with no getrlimit()";
1199 const unsigned long MAX_CONNECTIONS = 15000;
1200 #endif
1201 log_fn(LOG_INFO, LD_NET,
1202 "This platform is missing getrlimit(). Proceeding.");
1203 if (limit > MAX_CONNECTIONS) {
1204 log_warn(LD_CONFIG,
1205 "We do not support more than %lu file descriptors "
1206 "on %s. Tried to raise to %lu.",
1207 (unsigned long)MAX_CONNECTIONS, platform, (unsigned long)limit);
1208 return -1;
1210 limit = MAX_CONNECTIONS;
1211 #else /* HAVE_GETRLIMIT */
1212 struct rlimit rlim;
1213 tor_assert(limit > 0);
1215 if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) {
1216 log_warn(LD_NET, "Could not get maximum number of file descriptors: %s",
1217 strerror(errno));
1218 return -1;
1221 if (rlim.rlim_max < limit) {
1222 log_warn(LD_CONFIG,"We need %lu file descriptors available, and we're "
1223 "limited to %lu. Please change your ulimit -n.",
1224 (unsigned long)limit, (unsigned long)rlim.rlim_max);
1225 return -1;
1228 if (rlim.rlim_max > rlim.rlim_cur) {
1229 log_info(LD_NET,"Raising max file descriptors from %lu to %lu.",
1230 (unsigned long)rlim.rlim_cur, (unsigned long)rlim.rlim_max);
1232 rlim.rlim_cur = rlim.rlim_max;
1234 if (setrlimit(RLIMIT_NOFILE, &rlim) != 0) {
1235 int bad = 1;
1236 #ifdef OPEN_MAX
1237 if (errno == EINVAL && OPEN_MAX < rlim.rlim_cur) {
1238 /* On some platforms, OPEN_MAX is the real limit, and getrlimit() is
1239 * full of nasty lies. I'm looking at you, OSX 10.5.... */
1240 rlim.rlim_cur = OPEN_MAX;
1241 if (setrlimit(RLIMIT_NOFILE, &rlim) == 0) {
1242 if (rlim.rlim_cur < (rlim_t)limit) {
1243 log_warn(LD_CONFIG, "We are limited to %lu file descriptors by "
1244 "OPEN_MAX, and ConnLimit is %lu. Changing ConnLimit; sorry.",
1245 (unsigned long)OPEN_MAX, (unsigned long)limit);
1246 } else {
1247 log_info(LD_CONFIG, "Dropped connection limit to OPEN_MAX (%lu); "
1248 "Apparently, %lu was too high and rlimit lied to us.",
1249 (unsigned long)OPEN_MAX, (unsigned long)rlim.rlim_max);
1251 bad = 0;
1254 #endif /* OPEN_MAX */
1255 if (bad) {
1256 log_warn(LD_CONFIG,"Couldn't set maximum number of file descriptors: %s",
1257 strerror(errno));
1258 return -1;
1261 /* leave some overhead for logs, etc, */
1262 limit = rlim.rlim_cur;
1263 #endif /* HAVE_GETRLIMIT */
1265 if (limit < ULIMIT_BUFFER) {
1266 log_warn(LD_CONFIG,
1267 "ConnLimit must be at least %d. Failing.", ULIMIT_BUFFER);
1268 return -1;
1270 if (limit > INT_MAX)
1271 limit = INT_MAX;
1272 tor_assert(max_out);
1273 *max_out = (int)limit - ULIMIT_BUFFER;
1274 return 0;
1277 #ifndef MS_WINDOWS
1278 /** Log details of current user and group credentials. Return 0 on
1279 * success. Logs and return -1 on failure.
1281 static int
1282 log_credential_status(void)
1284 /** Log level to use when describing non-error UID/GID status. */
1285 #define CREDENTIAL_LOG_LEVEL LOG_INFO
1286 /* Real, effective and saved UIDs */
1287 uid_t ruid, euid, suid;
1288 /* Read, effective and saved GIDs */
1289 gid_t rgid, egid, sgid;
1290 /* Supplementary groups */
1291 gid_t *sup_gids = NULL;
1292 int sup_gids_size;
1293 /* Number of supplementary groups */
1294 int ngids;
1296 /* log UIDs */
1297 #ifdef HAVE_GETRESUID
1298 if (getresuid(&ruid, &euid, &suid) != 0 ) {
1299 log_warn(LD_GENERAL, "Error getting changed UIDs: %s", strerror(errno));
1300 return -1;
1301 } else {
1302 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
1303 "UID is %u (real), %u (effective), %u (saved)",
1304 (unsigned)ruid, (unsigned)euid, (unsigned)suid);
1306 #else
1307 /* getresuid is not present on MacOS X, so we can't get the saved (E)UID */
1308 ruid = getuid();
1309 euid = geteuid();
1310 (void)suid;
1312 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
1313 "UID is %u (real), %u (effective), unknown (saved)",
1314 (unsigned)ruid, (unsigned)euid);
1315 #endif
1317 /* log GIDs */
1318 #ifdef HAVE_GETRESGID
1319 if (getresgid(&rgid, &egid, &sgid) != 0 ) {
1320 log_warn(LD_GENERAL, "Error getting changed GIDs: %s", strerror(errno));
1321 return -1;
1322 } else {
1323 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
1324 "GID is %u (real), %u (effective), %u (saved)",
1325 (unsigned)rgid, (unsigned)egid, (unsigned)sgid);
1327 #else
1328 /* getresgid is not present on MacOS X, so we can't get the saved (E)GID */
1329 rgid = getgid();
1330 egid = getegid();
1331 (void)sgid;
1332 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
1333 "GID is %u (real), %u (effective), unknown (saved)",
1334 (unsigned)rgid, (unsigned)egid);
1335 #endif
1337 /* log supplementary groups */
1338 sup_gids_size = 64;
1339 sup_gids = tor_malloc(sizeof(gid_t) * 64);
1340 while ((ngids = getgroups(sup_gids_size, sup_gids)) < 0 &&
1341 errno == EINVAL &&
1342 sup_gids_size < NGROUPS_MAX) {
1343 sup_gids_size *= 2;
1344 sup_gids = tor_realloc(sup_gids, sizeof(gid_t) * sup_gids_size);
1347 if (ngids < 0) {
1348 log_warn(LD_GENERAL, "Error getting supplementary GIDs: %s",
1349 strerror(errno));
1350 tor_free(sup_gids);
1351 return -1;
1352 } else {
1353 int i, retval = 0;
1354 char *strgid;
1355 char *s = NULL;
1356 smartlist_t *elts = smartlist_create();
1358 for (i = 0; i<ngids; i++) {
1359 strgid = tor_malloc(11);
1360 if (tor_snprintf(strgid, 11, "%u", (unsigned)sup_gids[i]) < 0) {
1361 log_warn(LD_GENERAL, "Error printing supplementary GIDs");
1362 tor_free(strgid);
1363 retval = -1;
1364 goto error;
1366 smartlist_add(elts, strgid);
1369 s = smartlist_join_strings(elts, " ", 0, NULL);
1371 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL, "Supplementary groups are: %s",s);
1373 error:
1374 tor_free(s);
1375 SMARTLIST_FOREACH(elts, char *, cp,
1377 tor_free(cp);
1379 smartlist_free(elts);
1380 tor_free(sup_gids);
1382 return retval;
1385 return 0;
1387 #endif
1389 /** Call setuid and setgid to run as <b>user</b> and switch to their
1390 * primary group. Return 0 on success. On failure, log and return -1.
1393 switch_id(const char *user)
1395 #ifndef MS_WINDOWS
1396 struct passwd *pw = NULL;
1397 uid_t old_uid;
1398 gid_t old_gid;
1399 static int have_already_switched_id = 0;
1401 tor_assert(user);
1403 if (have_already_switched_id)
1404 return 0;
1406 /* Log the initial credential state */
1407 if (log_credential_status())
1408 return -1;
1410 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL, "Changing user and groups");
1412 /* Get old UID/GID to check if we changed correctly */
1413 old_uid = getuid();
1414 old_gid = getgid();
1416 /* Lookup the user and group information, if we have a problem, bail out. */
1417 pw = getpwnam(user);
1418 if (pw == NULL) {
1419 log_warn(LD_CONFIG, "Error setting configured user: %s not found", user);
1420 return -1;
1423 /* Properly switch egid,gid,euid,uid here or bail out */
1424 if (setgroups(1, &pw->pw_gid)) {
1425 log_warn(LD_GENERAL, "Error setting groups to gid %d: \"%s\".",
1426 (int)pw->pw_gid, strerror(errno));
1427 if (old_uid == pw->pw_uid) {
1428 log_warn(LD_GENERAL, "Tor is already running as %s. You do not need "
1429 "the \"User\" option if you are already running as the user "
1430 "you want to be. (If you did not set the User option in your "
1431 "torrc, check whether it was specified on the command line "
1432 "by a startup script.)", user);
1433 } else {
1434 log_warn(LD_GENERAL, "If you set the \"User\" option, you must start Tor"
1435 " as root.");
1437 return -1;
1440 if (setegid(pw->pw_gid)) {
1441 log_warn(LD_GENERAL, "Error setting egid to %d: %s",
1442 (int)pw->pw_gid, strerror(errno));
1443 return -1;
1446 if (setgid(pw->pw_gid)) {
1447 log_warn(LD_GENERAL, "Error setting gid to %d: %s",
1448 (int)pw->pw_gid, strerror(errno));
1449 return -1;
1452 if (setuid(pw->pw_uid)) {
1453 log_warn(LD_GENERAL, "Error setting configured uid to %s (%d): %s",
1454 user, (int)pw->pw_uid, strerror(errno));
1455 return -1;
1458 if (seteuid(pw->pw_uid)) {
1459 log_warn(LD_GENERAL, "Error setting configured euid to %s (%d): %s",
1460 user, (int)pw->pw_uid, strerror(errno));
1461 return -1;
1464 /* This is how OpenBSD rolls:
1465 if (setgroups(1, &pw->pw_gid) || setegid(pw->pw_gid) ||
1466 setgid(pw->pw_gid) || setuid(pw->pw_uid) || seteuid(pw->pw_uid)) {
1467 setgid(pw->pw_gid) || seteuid(pw->pw_uid) || setuid(pw->pw_uid)) {
1468 log_warn(LD_GENERAL, "Error setting configured UID/GID: %s",
1469 strerror(errno));
1470 return -1;
1474 /* We've properly switched egid, gid, euid, uid, and supplementary groups if
1475 * we're here. */
1477 #if !defined(CYGWIN) && !defined(__CYGWIN__)
1478 /* If we tried to drop privilege to a group/user other than root, attempt to
1479 * restore root (E)(U|G)ID, and abort if the operation succeeds */
1481 /* Only check for privilege dropping if we were asked to be non-root */
1482 if (pw->pw_uid) {
1483 /* Try changing GID/EGID */
1484 if (pw->pw_gid != old_gid &&
1485 (setgid(old_gid) != -1 || setegid(old_gid) != -1)) {
1486 log_warn(LD_GENERAL, "Was able to restore group credentials even after "
1487 "switching GID: this means that the setgid code didn't work.");
1488 return -1;
1491 /* Try changing UID/EUID */
1492 if (pw->pw_uid != old_uid &&
1493 (setuid(old_uid) != -1 || seteuid(old_uid) != -1)) {
1494 log_warn(LD_GENERAL, "Was able to restore user credentials even after "
1495 "switching UID: this means that the setuid code didn't work.");
1496 return -1;
1499 #endif
1501 /* Check what really happened */
1502 if (log_credential_status()) {
1503 return -1;
1506 have_already_switched_id = 1; /* mark success so we never try again */
1508 #if defined(__linux__) && defined(HAVE_SYS_PRCTL_H) && defined(HAVE_PRCTL)
1509 #ifdef PR_SET_DUMPABLE
1510 if (pw->pw_uid) {
1511 /* Re-enable core dumps if we're not running as root. */
1512 log_info(LD_CONFIG, "Re-enabling coredumps");
1513 if (prctl(PR_SET_DUMPABLE, 1)) {
1514 log_warn(LD_CONFIG, "Unable to re-enable coredumps: %s",strerror(errno));
1517 #endif
1518 #endif
1519 return 0;
1521 #else
1522 (void)user;
1524 log_warn(LD_CONFIG,
1525 "User specified but switching users is unsupported on your OS.");
1526 return -1;
1527 #endif
1530 /* We only use the linux prctl for now. There is no Win32 support; this may
1531 * also work on various BSD systems and Mac OS X - send testing feedback!
1533 * On recent Gnu/Linux kernels it is possible to create a system-wide policy
1534 * that will prevent non-root processes from attaching to other processes
1535 * unless they are the parent process; thus gdb can attach to programs that
1536 * they execute but they cannot attach to other processes running as the same
1537 * user. The system wide policy may be set with the sysctl
1538 * kernel.yama.ptrace_scope or by inspecting
1539 * /proc/sys/kernel/yama/ptrace_scope and it is 1 by default on Ubuntu 11.04.
1541 * This ptrace scope will be ignored on Gnu/Linux for users with
1542 * CAP_SYS_PTRACE and so it is very likely that root will still be able to
1543 * attach to the Tor process.
1545 /** Attempt to disable debugger attachment: return 1 on success, -1 on
1546 * failure, and 0 if we don't know how to try on this platform. */
1548 tor_disable_debugger_attach(void)
1550 int r, attempted;
1551 r = -1;
1552 attempted = 0;
1553 log_debug(LD_CONFIG,
1554 "Attemping to disable debugger attachment to Tor for "
1555 "unprivileged users.");
1556 #if defined(__linux__) && defined(HAVE_SYS_PRCTL_H) && defined(HAVE_PRCTL)
1557 #ifdef PR_SET_DUMPABLE
1558 attempted = 1;
1559 r = prctl(PR_SET_DUMPABLE, 0);
1560 #endif
1561 #endif
1562 #if defined(__APPLE__) && defined(PT_DENY_ATTACH)
1563 if (r < 0) {
1564 attempted = 1;
1565 r = ptrace(PT_DENY_ATTACH, 0, 0, 0);
1567 #endif
1569 // XXX: TODO - Mac OS X has dtrace and this may be disabled.
1570 // XXX: TODO - Windows probably has something similar
1571 if (r == 0 && attempted) {
1572 log_debug(LD_CONFIG,"Debugger attachment disabled for "
1573 "unprivileged users.");
1574 return 1;
1575 } else if (attempted) {
1576 log_warn(LD_CONFIG, "Unable to disable debugger attaching: %s",
1577 strerror(errno));
1579 return r;
1582 #ifdef HAVE_PWD_H
1583 /** Allocate and return a string containing the home directory for the
1584 * user <b>username</b>. Only works on posix-like systems. */
1585 char *
1586 get_user_homedir(const char *username)
1588 struct passwd *pw;
1589 tor_assert(username);
1591 if (!(pw = getpwnam(username))) {
1592 log_err(LD_CONFIG,"User \"%s\" not found.", username);
1593 return NULL;
1595 return tor_strdup(pw->pw_dir);
1597 #endif
1599 /** Modify <b>fname</b> to contain the name of the directory */
1601 get_parent_directory(char *fname)
1603 char *cp;
1604 int at_end = 1;
1605 tor_assert(fname);
1606 #ifdef MS_WINDOWS
1607 /* If we start with, say, c:, then don't consider that the start of the path
1609 if (fname[0] && fname[1] == ':') {
1610 fname += 2;
1612 #endif
1613 /* Now we want to remove all path-separators at the end of the string,
1614 * and to remove the end of the string starting with the path separator
1615 * before the last non-path-separator. In perl, this would be
1616 * s#[/]*$##; s#/[^/]*$##;
1617 * on a unixy platform.
1619 cp = fname + strlen(fname);
1620 at_end = 1;
1621 while (--cp > fname) {
1622 int is_sep = (*cp == '/'
1623 #ifdef MS_WINDOWS
1624 || *cp == '\\'
1625 #endif
1627 if (is_sep) {
1628 *cp = '\0';
1629 if (! at_end)
1630 return 0;
1631 } else {
1632 at_end = 0;
1635 return -1;
1638 /** Expand possibly relative path <b>fname</b> to an absolute path.
1639 * Return a newly allocated string, possibly equal to <b>fname</b>. */
1640 char *
1641 make_path_absolute(char *fname)
1643 #ifdef WINDOWS
1644 char *absfname_malloced = _fullpath(NULL, fname, 1);
1646 /* We don't want to assume that tor_free can free a string allocated
1647 * with malloc. On failure, return fname (it's better than nothing). */
1648 char *absfname = tor_strdup(absfname_malloced ? absfname_malloced : fname);
1649 if (absfname_malloced) free(absfname_malloced);
1651 return absfname;
1652 #else
1653 char path[PATH_MAX+1];
1654 char *absfname = NULL;
1656 tor_assert(fname);
1658 if (fname[0] == '/') {
1659 absfname = tor_strdup(fname);
1660 } else {
1661 if (getcwd(path, PATH_MAX) != NULL) {
1662 tor_asprintf(&absfname, "%s/%s", path, fname);
1663 } else {
1664 /* If getcwd failed, the best we can do here is keep using the
1665 * relative path. (Perhaps / isn't readable by this UID/GID.) */
1666 absfname = tor_strdup(fname);
1670 return absfname;
1671 #endif
1674 /** Set *addr to the IP address (in dotted-quad notation) stored in c.
1675 * Return 1 on success, 0 if c is badly formatted. (Like inet_aton(c,addr),
1676 * but works on Windows and Solaris.)
1679 tor_inet_aton(const char *str, struct in_addr* addr)
1681 unsigned a,b,c,d;
1682 char more;
1683 if (tor_sscanf(str, "%3u.%3u.%3u.%3u%c", &a,&b,&c,&d,&more) != 4)
1684 return 0;
1685 if (a > 255) return 0;
1686 if (b > 255) return 0;
1687 if (c > 255) return 0;
1688 if (d > 255) return 0;
1689 addr->s_addr = htonl((a<<24) | (b<<16) | (c<<8) | d);
1690 return 1;
1693 /** Given <b>af</b>==AF_INET and <b>src</b> a struct in_addr, or
1694 * <b>af</b>==AF_INET6 and <b>src</b> a struct in6_addr, try to format the
1695 * address and store it in the <b>len</b>-byte buffer <b>dst</b>. Returns
1696 * <b>dst</b> on success, NULL on failure.
1698 * (Like inet_ntop(af,src,dst,len), but works on platforms that don't have it:
1699 * Tor sometimes needs to format ipv6 addresses even on platforms without ipv6
1700 * support.) */
1701 const char *
1702 tor_inet_ntop(int af, const void *src, char *dst, size_t len)
1704 if (af == AF_INET) {
1705 if (tor_inet_ntoa(src, dst, len) < 0)
1706 return NULL;
1707 else
1708 return dst;
1709 } else if (af == AF_INET6) {
1710 const struct in6_addr *addr = src;
1711 char buf[64], *cp;
1712 int longestGapLen = 0, longestGapPos = -1, i,
1713 curGapPos = -1, curGapLen = 0;
1714 uint16_t words[8];
1715 for (i = 0; i < 8; ++i) {
1716 words[i] = (((uint16_t)addr->s6_addr[2*i])<<8) + addr->s6_addr[2*i+1];
1718 if (words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0 &&
1719 words[4] == 0 && ((words[5] == 0 && words[6] && words[7]) ||
1720 (words[5] == 0xffff))) {
1721 /* This is an IPv4 address. */
1722 if (words[5] == 0) {
1723 tor_snprintf(buf, sizeof(buf), "::%d.%d.%d.%d",
1724 addr->s6_addr[12], addr->s6_addr[13],
1725 addr->s6_addr[14], addr->s6_addr[15]);
1726 } else {
1727 tor_snprintf(buf, sizeof(buf), "::%x:%d.%d.%d.%d", words[5],
1728 addr->s6_addr[12], addr->s6_addr[13],
1729 addr->s6_addr[14], addr->s6_addr[15]);
1731 if ((strlen(buf) + 1) > len) /* +1 for \0 */
1732 return NULL;
1733 strlcpy(dst, buf, len);
1734 return dst;
1736 i = 0;
1737 while (i < 8) {
1738 if (words[i] == 0) {
1739 curGapPos = i++;
1740 curGapLen = 1;
1741 while (i<8 && words[i] == 0) {
1742 ++i; ++curGapLen;
1744 if (curGapLen > longestGapLen) {
1745 longestGapPos = curGapPos;
1746 longestGapLen = curGapLen;
1748 } else {
1749 ++i;
1752 if (longestGapLen<=1)
1753 longestGapPos = -1;
1755 cp = buf;
1756 for (i = 0; i < 8; ++i) {
1757 if (words[i] == 0 && longestGapPos == i) {
1758 if (i == 0)
1759 *cp++ = ':';
1760 *cp++ = ':';
1761 while (i < 8 && words[i] == 0)
1762 ++i;
1763 --i; /* to compensate for loop increment. */
1764 } else {
1765 tor_snprintf(cp, sizeof(buf)-(cp-buf), "%x", (unsigned)words[i]);
1766 cp += strlen(cp);
1767 if (i != 7)
1768 *cp++ = ':';
1771 *cp = '\0';
1772 if ((strlen(buf) + 1) > len) /* +1 for \0 */
1773 return NULL;
1774 strlcpy(dst, buf, len);
1775 return dst;
1776 } else {
1777 return NULL;
1781 /** Given <b>af</b>==AF_INET or <b>af</b>==AF_INET6, and a string <b>src</b>
1782 * encoding an IPv4 address or IPv6 address correspondingly, try to parse the
1783 * address and store the result in <b>dst</b> (which must have space for a
1784 * struct in_addr or a struct in6_addr, as appropriate). Return 1 on success,
1785 * 0 on a bad parse, and -1 on a bad <b>af</b>.
1787 * (Like inet_pton(af,src,dst) but works on platforms that don't have it: Tor
1788 * sometimes needs to format ipv6 addresses even on platforms without ipv6
1789 * support.) */
1791 tor_inet_pton(int af, const char *src, void *dst)
1793 if (af == AF_INET) {
1794 return tor_inet_aton(src, dst);
1795 } else if (af == AF_INET6) {
1796 struct in6_addr *out = dst;
1797 uint16_t words[8];
1798 int gapPos = -1, i, setWords=0;
1799 const char *dot = strchr(src, '.');
1800 const char *eow; /* end of words. */
1801 if (dot == src)
1802 return 0;
1803 else if (!dot)
1804 eow = src+strlen(src);
1805 else {
1806 unsigned byte1,byte2,byte3,byte4;
1807 char more;
1808 for (eow = dot-1; eow >= src && TOR_ISDIGIT(*eow); --eow)
1810 ++eow;
1812 /* We use "scanf" because some platform inet_aton()s are too lax
1813 * about IPv4 addresses of the form "1.2.3" */
1814 if (tor_sscanf(eow, "%3u.%3u.%3u.%3u%c",
1815 &byte1,&byte2,&byte3,&byte4,&more) != 4)
1816 return 0;
1818 if (byte1 > 255 || byte2 > 255 || byte3 > 255 || byte4 > 255)
1819 return 0;
1821 words[6] = (byte1<<8) | byte2;
1822 words[7] = (byte3<<8) | byte4;
1823 setWords += 2;
1826 i = 0;
1827 while (src < eow) {
1828 if (i > 7)
1829 return 0;
1830 if (TOR_ISXDIGIT(*src)) {
1831 char *next;
1832 ssize_t len;
1833 long r = strtol(src, &next, 16);
1834 tor_assert(next != NULL);
1835 tor_assert(next != src);
1837 len = *next == '\0' ? eow - src : next - src;
1838 if (len > 4)
1839 return 0;
1840 if (len > 1 && !TOR_ISXDIGIT(src[1]))
1841 return 0; /* 0x is not valid */
1843 tor_assert(r >= 0);
1844 tor_assert(r < 65536);
1845 words[i++] = (uint16_t)r;
1846 setWords++;
1847 src = next;
1848 if (*src != ':' && src != eow)
1849 return 0;
1850 ++src;
1851 } else if (*src == ':' && i > 0 && gapPos == -1) {
1852 gapPos = i;
1853 ++src;
1854 } else if (*src == ':' && i == 0 && src+1 < eow && src[1] == ':' &&
1855 gapPos == -1) {
1856 gapPos = i;
1857 src += 2;
1858 } else {
1859 return 0;
1863 if (setWords > 8 ||
1864 (setWords == 8 && gapPos != -1) ||
1865 (setWords < 8 && gapPos == -1))
1866 return 0;
1868 if (gapPos >= 0) {
1869 int nToMove = setWords - (dot ? 2 : 0) - gapPos;
1870 int gapLen = 8 - setWords;
1871 tor_assert(nToMove >= 0);
1872 memmove(&words[gapPos+gapLen], &words[gapPos],
1873 sizeof(uint16_t)*nToMove);
1874 memset(&words[gapPos], 0, sizeof(uint16_t)*gapLen);
1876 for (i = 0; i < 8; ++i) {
1877 out->s6_addr[2*i ] = words[i] >> 8;
1878 out->s6_addr[2*i+1] = words[i] & 0xff;
1881 return 1;
1882 } else {
1883 return -1;
1887 /** Similar behavior to Unix gethostbyname: resolve <b>name</b>, and set
1888 * *<b>addr</b> to the proper IP address, in host byte order. Returns 0
1889 * on success, -1 on failure; 1 on transient failure.
1891 * (This function exists because standard windows gethostbyname
1892 * doesn't treat raw IP addresses properly.)
1895 tor_lookup_hostname(const char *name, uint32_t *addr)
1897 tor_addr_t myaddr;
1898 int ret;
1900 if ((ret = tor_addr_lookup(name, AF_INET, &myaddr)))
1901 return ret;
1903 if (tor_addr_family(&myaddr) == AF_INET) {
1904 *addr = tor_addr_to_ipv4h(&myaddr);
1905 return ret;
1908 return -1;
1911 /** Initialize the insecure libc RNG. */
1912 void
1913 tor_init_weak_random(unsigned seed)
1915 #ifdef MS_WINDOWS
1916 srand(seed);
1917 #else
1918 srandom(seed);
1919 #endif
1922 /** Return a randomly chosen value in the range 0..TOR_RAND_MAX. This
1923 * entropy will not be cryptographically strong; do not rely on it
1924 * for anything an adversary should not be able to predict. */
1925 long
1926 tor_weak_random(void)
1928 #ifdef MS_WINDOWS
1929 return rand();
1930 #else
1931 return random();
1932 #endif
1935 /** Hold the result of our call to <b>uname</b>. */
1936 static char uname_result[256];
1937 /** True iff uname_result is set. */
1938 static int uname_result_is_set = 0;
1940 /** Return a pointer to a description of our platform.
1942 const char *
1943 get_uname(void)
1945 #ifdef HAVE_UNAME
1946 struct utsname u;
1947 #endif
1948 if (!uname_result_is_set) {
1949 #ifdef HAVE_UNAME
1950 if (uname(&u) != -1) {
1951 /* (Linux says 0 is success, Solaris says 1 is success) */
1952 tor_snprintf(uname_result, sizeof(uname_result), "%s %s",
1953 u.sysname, u.machine);
1954 } else
1955 #endif
1957 #ifdef MS_WINDOWS
1958 OSVERSIONINFOEX info;
1959 int i;
1960 const char *plat = NULL;
1961 const char *extra = NULL;
1962 char acsd[MAX_PATH] = {0};
1963 static struct {
1964 unsigned major; unsigned minor; const char *version;
1965 } win_version_table[] = {
1966 { 6, 2, "Windows 8" },
1967 { 6, 1, "Windows 7" },
1968 { 6, 0, "Windows Vista" },
1969 { 5, 2, "Windows Server 2003" },
1970 { 5, 1, "Windows XP" },
1971 { 5, 0, "Windows 2000" },
1972 /* { 4, 0, "Windows NT 4.0" }, */
1973 { 4, 90, "Windows Me" },
1974 { 4, 10, "Windows 98" },
1975 /* { 4, 0, "Windows 95" } */
1976 { 3, 51, "Windows NT 3.51" },
1977 { 0, 0, NULL }
1979 memset(&info, 0, sizeof(info));
1980 info.dwOSVersionInfoSize = sizeof(info);
1981 if (! GetVersionEx((LPOSVERSIONINFO)&info)) {
1982 strlcpy(uname_result, "Bizarre version of Windows where GetVersionEx"
1983 " doesn't work.", sizeof(uname_result));
1984 uname_result_is_set = 1;
1985 return uname_result;
1987 #ifdef UNICODE
1988 wcstombs(acsd, info.szCSDVersion, MAX_PATH);
1989 #else
1990 strlcpy(acsd, info.szCSDVersion, sizeof(acsd));
1991 #endif
1992 if (info.dwMajorVersion == 4 && info.dwMinorVersion == 0) {
1993 if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
1994 plat = "Windows NT 4.0";
1995 else
1996 plat = "Windows 95";
1997 if (acsd[1] == 'B')
1998 extra = "OSR2 (B)";
1999 else if (acsd[1] == 'C')
2000 extra = "OSR2 (C)";
2001 } else {
2002 for (i=0; win_version_table[i].major>0; ++i) {
2003 if (win_version_table[i].major == info.dwMajorVersion &&
2004 win_version_table[i].minor == info.dwMinorVersion) {
2005 plat = win_version_table[i].version;
2006 break;
2010 if (plat && !strcmp(plat, "Windows 98")) {
2011 if (acsd[1] == 'A')
2012 extra = "SE (A)";
2013 else if (acsd[1] == 'B')
2014 extra = "SE (B)";
2016 if (plat) {
2017 if (!extra)
2018 extra = acsd;
2019 tor_snprintf(uname_result, sizeof(uname_result), "%s %s",
2020 plat, extra);
2021 } else {
2022 if (info.dwMajorVersion > 6 ||
2023 (info.dwMajorVersion==6 && info.dwMinorVersion>2))
2024 tor_snprintf(uname_result, sizeof(uname_result),
2025 "Very recent version of Windows [major=%d,minor=%d] %s",
2026 (int)info.dwMajorVersion,(int)info.dwMinorVersion,
2027 acsd);
2028 else
2029 tor_snprintf(uname_result, sizeof(uname_result),
2030 "Unrecognized version of Windows [major=%d,minor=%d] %s",
2031 (int)info.dwMajorVersion,(int)info.dwMinorVersion,
2032 acsd);
2034 #if !defined (WINCE)
2035 #ifdef VER_SUITE_BACKOFFICE
2036 if (info.wProductType == VER_NT_DOMAIN_CONTROLLER) {
2037 strlcat(uname_result, " [domain controller]", sizeof(uname_result));
2038 } else if (info.wProductType == VER_NT_SERVER) {
2039 strlcat(uname_result, " [server]", sizeof(uname_result));
2040 } else if (info.wProductType == VER_NT_WORKSTATION) {
2041 strlcat(uname_result, " [workstation]", sizeof(uname_result));
2043 #endif
2044 #endif
2045 #else
2046 strlcpy(uname_result, "Unknown platform", sizeof(uname_result));
2047 #endif
2049 uname_result_is_set = 1;
2051 return uname_result;
2055 * Process control
2058 #if defined(USE_PTHREADS)
2059 /** Wraps a void (*)(void*) function and its argument so we can
2060 * invoke them in a way pthreads would expect.
2062 typedef struct tor_pthread_data_t {
2063 void (*func)(void *);
2064 void *data;
2065 } tor_pthread_data_t;
2066 /** Given a tor_pthread_data_t <b>_data</b>, call _data-&gt;func(d-&gt;data)
2067 * and free _data. Used to make sure we can call functions the way pthread
2068 * expects. */
2069 static void *
2070 tor_pthread_helper_fn(void *_data)
2072 tor_pthread_data_t *data = _data;
2073 void (*func)(void*);
2074 void *arg;
2075 /* mask signals to worker threads to avoid SIGPIPE, etc */
2076 sigset_t sigs;
2077 /* We're in a subthread; don't handle any signals here. */
2078 sigfillset(&sigs);
2079 pthread_sigmask(SIG_SETMASK, &sigs, NULL);
2081 func = data->func;
2082 arg = data->data;
2083 tor_free(_data);
2084 func(arg);
2085 return NULL;
2087 #endif
2089 /** Minimalist interface to run a void function in the background. On
2090 * Unix calls fork, on win32 calls beginthread. Returns -1 on failure.
2091 * func should not return, but rather should call spawn_exit.
2093 * NOTE: if <b>data</b> is used, it should not be allocated on the stack,
2094 * since in a multithreaded environment, there is no way to be sure that
2095 * the caller's stack will still be around when the called function is
2096 * running.
2099 spawn_func(void (*func)(void *), void *data)
2101 #if defined(USE_WIN32_THREADS)
2102 int rv;
2103 rv = (int)_beginthread(func, 0, data);
2104 if (rv == (int)-1)
2105 return -1;
2106 return 0;
2107 #elif defined(USE_PTHREADS)
2108 pthread_t thread;
2109 tor_pthread_data_t *d;
2110 d = tor_malloc(sizeof(tor_pthread_data_t));
2111 d->data = data;
2112 d->func = func;
2113 if (pthread_create(&thread,NULL,tor_pthread_helper_fn,d))
2114 return -1;
2115 if (pthread_detach(thread))
2116 return -1;
2117 return 0;
2118 #else
2119 pid_t pid;
2120 pid = fork();
2121 if (pid<0)
2122 return -1;
2123 if (pid==0) {
2124 /* Child */
2125 func(data);
2126 tor_assert(0); /* Should never reach here. */
2127 return 0; /* suppress "control-reaches-end-of-non-void" warning. */
2128 } else {
2129 /* Parent */
2130 return 0;
2132 #endif
2135 /** End the current thread/process.
2137 void
2138 spawn_exit(void)
2140 #if defined(USE_WIN32_THREADS)
2141 _endthread();
2142 //we should never get here. my compiler thinks that _endthread returns, this
2143 //is an attempt to fool it.
2144 tor_assert(0);
2145 _exit(0);
2146 #elif defined(USE_PTHREADS)
2147 pthread_exit(NULL);
2148 #else
2149 /* http://www.erlenstar.demon.co.uk/unix/faq_2.html says we should
2150 * call _exit, not exit, from child processes. */
2151 _exit(0);
2152 #endif
2155 /** Implementation logic for compute_num_cpus(). */
2156 static int
2157 compute_num_cpus_impl(void)
2159 #ifdef MS_WINDOWS
2160 SYSTEM_INFO info;
2161 memset(&info, 0, sizeof(info));
2162 GetSystemInfo(&info);
2163 if (info.dwNumberOfProcessors >= 1 && info.dwNumberOfProcessors < INT_MAX)
2164 return (int)info.dwNumberOfProcessors;
2165 else
2166 return -1;
2167 #elif defined(HAVE_SYSCONF) && defined(_SC_NPROCESSORS_CONF)
2168 long cpus = sysconf(_SC_NPROCESSORS_CONF);
2169 if (cpus >= 1 && cpus < INT_MAX)
2170 return (int)cpus;
2171 else
2172 return -1;
2173 #else
2174 return -1;
2175 #endif
2178 #define MAX_DETECTABLE_CPUS 16
2180 /** Return how many CPUs we are running with. We assume that nobody is
2181 * using hot-swappable CPUs, so we don't recompute this after the first
2182 * time. Return -1 if we don't know how to tell the number of CPUs on this
2183 * system.
2186 compute_num_cpus(void)
2188 static int num_cpus = -2;
2189 if (num_cpus == -2) {
2190 num_cpus = compute_num_cpus_impl();
2191 tor_assert(num_cpus != -2);
2192 if (num_cpus > MAX_DETECTABLE_CPUS)
2193 log_notice(LD_GENERAL, "Wow! I detected that you have %d CPUs. I "
2194 "will not autodetect any more than %d, though. If you "
2195 "want to configure more, set NumCPUs in your torrc",
2196 num_cpus, MAX_DETECTABLE_CPUS);
2198 return num_cpus;
2201 /** Set *timeval to the current time of day. On error, log and terminate.
2202 * (Same as gettimeofday(timeval,NULL), but never returns -1.)
2204 void
2205 tor_gettimeofday(struct timeval *timeval)
2207 #ifdef MS_WINDOWS
2208 /* Epoch bias copied from perl: number of units between windows epoch and
2209 * Unix epoch. */
2210 #define EPOCH_BIAS U64_LITERAL(116444736000000000)
2211 #define UNITS_PER_SEC U64_LITERAL(10000000)
2212 #define USEC_PER_SEC U64_LITERAL(1000000)
2213 #define UNITS_PER_USEC U64_LITERAL(10)
2214 union {
2215 uint64_t ft_64;
2216 FILETIME ft_ft;
2217 } ft;
2218 #if defined (WINCE)
2219 /* wince do not have GetSystemTimeAsFileTime */
2220 SYSTEMTIME stime;
2221 GetSystemTime(&stime);
2222 SystemTimeToFileTime(&stime,&ft.ft_ft);
2223 #else
2224 /* number of 100-nsec units since Jan 1, 1601 */
2225 GetSystemTimeAsFileTime(&ft.ft_ft);
2226 #endif
2227 if (ft.ft_64 < EPOCH_BIAS) {
2228 log_err(LD_GENERAL,"System time is before 1970; failing.");
2229 exit(1);
2231 ft.ft_64 -= EPOCH_BIAS;
2232 timeval->tv_sec = (unsigned) (ft.ft_64 / UNITS_PER_SEC);
2233 timeval->tv_usec = (unsigned) ((ft.ft_64 / UNITS_PER_USEC) % USEC_PER_SEC);
2234 #elif defined(HAVE_GETTIMEOFDAY)
2235 if (gettimeofday(timeval, NULL)) {
2236 log_err(LD_GENERAL,"gettimeofday failed.");
2237 /* If gettimeofday dies, we have either given a bad timezone (we didn't),
2238 or segfaulted.*/
2239 exit(1);
2241 #elif defined(HAVE_FTIME)
2242 struct timeb tb;
2243 ftime(&tb);
2244 timeval->tv_sec = tb.time;
2245 timeval->tv_usec = tb.millitm * 1000;
2246 #else
2247 #error "No way to get time."
2248 #endif
2249 return;
2252 #if defined(TOR_IS_MULTITHREADED) && !defined(MS_WINDOWS)
2253 /** Defined iff we need to add locks when defining fake versions of reentrant
2254 * versions of time-related functions. */
2255 #define TIME_FNS_NEED_LOCKS
2256 #endif
2258 static struct tm *
2259 correct_tm(int islocal, const time_t *timep, struct tm *resultbuf,
2260 struct tm *r)
2262 const char *outcome;
2264 if (PREDICT_LIKELY(r)) {
2265 if (r->tm_year > 8099) { /* We can't strftime dates after 9999 CE. */
2266 r->tm_year = 8099;
2267 r->tm_mon = 11;
2268 r->tm_mday = 31;
2269 r->tm_yday = 365;
2270 r->tm_hour = 23;
2271 r->tm_min = 59;
2272 r->tm_sec = 59;
2274 return r;
2277 /* If we get here, gmtime or localtime returned NULL. It might have done
2278 * this because of overrun or underrun, or it might have done it because of
2279 * some other weird issue. */
2280 if (timep) {
2281 if (*timep < 0) {
2282 r = resultbuf;
2283 r->tm_year = 70; /* 1970 CE */
2284 r->tm_mon = 0;
2285 r->tm_mday = 1;
2286 r->tm_yday = 1;
2287 r->tm_hour = 0;
2288 r->tm_min = 0 ;
2289 r->tm_sec = 0;
2290 outcome = "Rounding up to 1970";
2291 goto done;
2292 } else if (*timep >= INT32_MAX) {
2293 /* Rounding down to INT32_MAX isn't so great, but keep in mind that we
2294 * only do it if gmtime/localtime tells us NULL. */
2295 r = resultbuf;
2296 r->tm_year = 137; /* 2037 CE */
2297 r->tm_mon = 11;
2298 r->tm_mday = 31;
2299 r->tm_yday = 365;
2300 r->tm_hour = 23;
2301 r->tm_min = 59;
2302 r->tm_sec = 59;
2303 outcome = "Rounding down to 2037";
2304 goto done;
2308 /* If we get here, then gmtime/localtime failed without getting an extreme
2309 * value for *timep */
2311 tor_fragile_assert();
2312 r = resultbuf;
2313 memset(resultbuf, 0, sizeof(struct tm));
2314 outcome="can't recover";
2315 done:
2316 log_warn(LD_BUG, "%s("I64_FORMAT") failed with error %s: %s",
2317 islocal?"localtime":"gmtime",
2318 timep?I64_PRINTF_ARG(*timep):0,
2319 strerror(errno),
2320 outcome);
2321 return r;
2324 /** @{ */
2325 /** As localtime_r, but defined for platforms that don't have it:
2327 * Convert *<b>timep</b> to a struct tm in local time, and store the value in
2328 * *<b>result</b>. Return the result on success, or NULL on failure.
2330 #ifdef HAVE_LOCALTIME_R
2331 struct tm *
2332 tor_localtime_r(const time_t *timep, struct tm *result)
2334 struct tm *r;
2335 r = localtime_r(timep, result);
2336 return correct_tm(1, timep, result, r);
2338 #elif defined(TIME_FNS_NEED_LOCKS)
2339 struct tm *
2340 tor_localtime_r(const time_t *timep, struct tm *result)
2342 struct tm *r;
2343 static tor_mutex_t *m=NULL;
2344 if (!m) { m=tor_mutex_new(); }
2345 tor_assert(result);
2346 tor_mutex_acquire(m);
2347 r = localtime(timep);
2348 if (r)
2349 memcpy(result, r, sizeof(struct tm));
2350 tor_mutex_release(m);
2351 return correct_tm(1, timep, result, r);
2353 #else
2354 struct tm *
2355 tor_localtime_r(const time_t *timep, struct tm *result)
2357 struct tm *r;
2358 tor_assert(result);
2359 r = localtime(timep);
2360 if (r)
2361 memcpy(result, r, sizeof(struct tm));
2362 return correct_tm(1, timep, result, r);
2364 #endif
2365 /** @} */
2367 /** @{ */
2368 /** As gmtimee_r, but defined for platforms that don't have it:
2370 * Convert *<b>timep</b> to a struct tm in UTC, and store the value in
2371 * *<b>result</b>. Return the result on success, or NULL on failure.
2373 #ifdef HAVE_GMTIME_R
2374 struct tm *
2375 tor_gmtime_r(const time_t *timep, struct tm *result)
2377 struct tm *r;
2378 r = gmtime_r(timep, result);
2379 return correct_tm(0, timep, result, r);
2381 #elif defined(TIME_FNS_NEED_LOCKS)
2382 struct tm *
2383 tor_gmtime_r(const time_t *timep, struct tm *result)
2385 struct tm *r;
2386 static tor_mutex_t *m=NULL;
2387 if (!m) { m=tor_mutex_new(); }
2388 tor_assert(result);
2389 tor_mutex_acquire(m);
2390 r = gmtime(timep);
2391 if (r)
2392 memcpy(result, r, sizeof(struct tm));
2393 tor_mutex_release(m);
2394 return correct_tm(0, timep, result, r);
2396 #else
2397 struct tm *
2398 tor_gmtime_r(const time_t *timep, struct tm *result)
2400 struct tm *r;
2401 tor_assert(result);
2402 r = gmtime(timep);
2403 if (r)
2404 memcpy(result, r, sizeof(struct tm));
2405 return correct_tm(0, timep, result, r);
2407 #endif
2409 #if defined(USE_WIN32_THREADS)
2410 void
2411 tor_mutex_init(tor_mutex_t *m)
2413 InitializeCriticalSection(&m->mutex);
2415 void
2416 tor_mutex_uninit(tor_mutex_t *m)
2418 DeleteCriticalSection(&m->mutex);
2420 void
2421 tor_mutex_acquire(tor_mutex_t *m)
2423 tor_assert(m);
2424 EnterCriticalSection(&m->mutex);
2426 void
2427 tor_mutex_release(tor_mutex_t *m)
2429 LeaveCriticalSection(&m->mutex);
2431 unsigned long
2432 tor_get_thread_id(void)
2434 return (unsigned long)GetCurrentThreadId();
2436 #elif defined(USE_PTHREADS)
2437 /** A mutex attribute that we're going to use to tell pthreads that we want
2438 * "reentrant" mutexes (i.e., once we can re-lock if we're already holding
2439 * them.) */
2440 static pthread_mutexattr_t attr_reentrant;
2441 /** True iff we've called tor_threads_init() */
2442 static int threads_initialized = 0;
2443 /** Initialize <b>mutex</b> so it can be locked. Every mutex must be set
2444 * up with tor_mutex_init() or tor_mutex_new(); not both. */
2445 void
2446 tor_mutex_init(tor_mutex_t *mutex)
2448 int err;
2449 if (PREDICT_UNLIKELY(!threads_initialized))
2450 tor_threads_init();
2451 err = pthread_mutex_init(&mutex->mutex, &attr_reentrant);
2452 if (PREDICT_UNLIKELY(err)) {
2453 log_err(LD_GENERAL, "Error %d creating a mutex.", err);
2454 tor_fragile_assert();
2457 /** Wait until <b>m</b> is free, then acquire it. */
2458 void
2459 tor_mutex_acquire(tor_mutex_t *m)
2461 int err;
2462 tor_assert(m);
2463 err = pthread_mutex_lock(&m->mutex);
2464 if (PREDICT_UNLIKELY(err)) {
2465 log_err(LD_GENERAL, "Error %d locking a mutex.", err);
2466 tor_fragile_assert();
2469 /** Release the lock <b>m</b> so another thread can have it. */
2470 void
2471 tor_mutex_release(tor_mutex_t *m)
2473 int err;
2474 tor_assert(m);
2475 err = pthread_mutex_unlock(&m->mutex);
2476 if (PREDICT_UNLIKELY(err)) {
2477 log_err(LD_GENERAL, "Error %d unlocking a mutex.", err);
2478 tor_fragile_assert();
2481 /** Clean up the mutex <b>m</b> so that it no longer uses any system
2482 * resources. Does not free <b>m</b>. This function must only be called on
2483 * mutexes from tor_mutex_init(). */
2484 void
2485 tor_mutex_uninit(tor_mutex_t *m)
2487 int err;
2488 tor_assert(m);
2489 err = pthread_mutex_destroy(&m->mutex);
2490 if (PREDICT_UNLIKELY(err)) {
2491 log_err(LD_GENERAL, "Error %d destroying a mutex.", err);
2492 tor_fragile_assert();
2495 /** Return an integer representing this thread. */
2496 unsigned long
2497 tor_get_thread_id(void)
2499 union {
2500 pthread_t thr;
2501 unsigned long id;
2502 } r;
2503 r.thr = pthread_self();
2504 return r.id;
2506 #endif
2508 #ifdef TOR_IS_MULTITHREADED
2509 /** Return a newly allocated, ready-for-use mutex. */
2510 tor_mutex_t *
2511 tor_mutex_new(void)
2513 tor_mutex_t *m = tor_malloc_zero(sizeof(tor_mutex_t));
2514 tor_mutex_init(m);
2515 return m;
2517 /** Release all storage and system resources held by <b>m</b>. */
2518 void
2519 tor_mutex_free(tor_mutex_t *m)
2521 if (!m)
2522 return;
2523 tor_mutex_uninit(m);
2524 tor_free(m);
2526 #endif
2528 /* Conditions. */
2529 #ifdef USE_PTHREADS
2530 #if 0
2531 /** Cross-platform condition implementation. */
2532 struct tor_cond_t {
2533 pthread_cond_t cond;
2535 /** Return a newly allocated condition, with nobody waiting on it. */
2536 tor_cond_t *
2537 tor_cond_new(void)
2539 tor_cond_t *cond = tor_malloc_zero(sizeof(tor_cond_t));
2540 if (pthread_cond_init(&cond->cond, NULL)) {
2541 tor_free(cond);
2542 return NULL;
2544 return cond;
2546 /** Release all resources held by <b>cond</b>. */
2547 void
2548 tor_cond_free(tor_cond_t *cond)
2550 if (!cond)
2551 return;
2552 if (pthread_cond_destroy(&cond->cond)) {
2553 log_warn(LD_GENERAL,"Error freeing condition: %s", strerror(errno));
2554 return;
2556 tor_free(cond);
2558 /** Wait until one of the tor_cond_signal functions is called on <b>cond</b>.
2559 * All waiters on the condition must wait holding the same <b>mutex</b>.
2560 * Returns 0 on success, negative on failure. */
2562 tor_cond_wait(tor_cond_t *cond, tor_mutex_t *mutex)
2564 return pthread_cond_wait(&cond->cond, &mutex->mutex) ? -1 : 0;
2566 /** Wake up one of the waiters on <b>cond</b>. */
2567 void
2568 tor_cond_signal_one(tor_cond_t *cond)
2570 pthread_cond_signal(&cond->cond);
2572 /** Wake up all of the waiters on <b>cond</b>. */
2573 void
2574 tor_cond_signal_all(tor_cond_t *cond)
2576 pthread_cond_broadcast(&cond->cond);
2578 #endif
2579 /** Set up common structures for use by threading. */
2580 void
2581 tor_threads_init(void)
2583 if (!threads_initialized) {
2584 pthread_mutexattr_init(&attr_reentrant);
2585 pthread_mutexattr_settype(&attr_reentrant, PTHREAD_MUTEX_RECURSIVE);
2586 threads_initialized = 1;
2587 set_main_thread();
2590 #elif defined(USE_WIN32_THREADS)
2591 #if 0
2592 static DWORD cond_event_tls_index;
2593 struct tor_cond_t {
2594 CRITICAL_SECTION mutex;
2595 smartlist_t *events;
2597 tor_cond_t *
2598 tor_cond_new(void)
2600 tor_cond_t *cond = tor_malloc_zero(sizeof(tor_cond_t));
2601 InitializeCriticalSection(&cond->mutex);
2602 cond->events = smartlist_create();
2603 return cond;
2605 void
2606 tor_cond_free(tor_cond_t *cond)
2608 if (!cond)
2609 return;
2610 DeleteCriticalSection(&cond->mutex);
2611 /* XXXX notify? */
2612 smartlist_free(cond->events);
2613 tor_free(cond);
2616 tor_cond_wait(tor_cond_t *cond, tor_mutex_t *mutex)
2618 HANDLE event;
2619 int r;
2620 tor_assert(cond);
2621 tor_assert(mutex);
2622 event = TlsGetValue(cond_event_tls_index);
2623 if (!event) {
2624 event = CreateEvent(0, FALSE, FALSE, NULL);
2625 TlsSetValue(cond_event_tls_index, event);
2627 EnterCriticalSection(&cond->mutex);
2629 tor_assert(WaitForSingleObject(event, 0) == WAIT_TIMEOUT);
2630 tor_assert(!smartlist_isin(cond->events, event));
2631 smartlist_add(cond->events, event);
2633 LeaveCriticalSection(&cond->mutex);
2635 tor_mutex_release(mutex);
2636 r = WaitForSingleObject(event, INFINITE);
2637 tor_mutex_acquire(mutex);
2639 switch (r) {
2640 case WAIT_OBJECT_0: /* we got the mutex normally. */
2641 break;
2642 case WAIT_ABANDONED: /* holding thread exited. */
2643 case WAIT_TIMEOUT: /* Should never happen. */
2644 tor_assert(0);
2645 break;
2646 case WAIT_FAILED:
2647 log_warn(LD_GENERAL, "Failed to acquire mutex: %d",(int) GetLastError());
2649 return 0;
2651 void
2652 tor_cond_signal_one(tor_cond_t *cond)
2654 HANDLE event;
2655 tor_assert(cond);
2657 EnterCriticalSection(&cond->mutex);
2659 if ((event = smartlist_pop_last(cond->events)))
2660 SetEvent(event);
2662 LeaveCriticalSection(&cond->mutex);
2664 void
2665 tor_cond_signal_all(tor_cond_t *cond)
2667 tor_assert(cond);
2669 EnterCriticalSection(&cond->mutex);
2670 SMARTLIST_FOREACH(cond->events, HANDLE, event, SetEvent(event));
2671 smartlist_clear(cond->events);
2672 LeaveCriticalSection(&cond->mutex);
2674 #endif
2675 void
2676 tor_threads_init(void)
2678 #if 0
2679 cond_event_tls_index = TlsAlloc();
2680 #endif
2681 set_main_thread();
2683 #endif
2685 #if defined(HAVE_MLOCKALL) && HAVE_DECL_MLOCKALL && defined(RLIMIT_MEMLOCK)
2686 /** Attempt to raise the current and max rlimit to infinity for our process.
2687 * This only needs to be done once and can probably only be done when we have
2688 * not already dropped privileges.
2690 static int
2691 tor_set_max_memlock(void)
2693 /* Future consideration for Windows is probably SetProcessWorkingSetSize
2694 * This is similar to setting the memory rlimit of RLIMIT_MEMLOCK
2695 * http://msdn.microsoft.com/en-us/library/ms686234(VS.85).aspx
2698 struct rlimit limit;
2700 /* RLIM_INFINITY is -1 on some platforms. */
2701 limit.rlim_cur = RLIM_INFINITY;
2702 limit.rlim_max = RLIM_INFINITY;
2704 if (setrlimit(RLIMIT_MEMLOCK, &limit) == -1) {
2705 if (errno == EPERM) {
2706 log_warn(LD_GENERAL, "You appear to lack permissions to change memory "
2707 "limits. Are you root?");
2709 log_warn(LD_GENERAL, "Unable to raise RLIMIT_MEMLOCK: %s",
2710 strerror(errno));
2711 return -1;
2714 return 0;
2716 #endif
2718 /** Attempt to lock all current and all future memory pages.
2719 * This should only be called once and while we're privileged.
2720 * Like mlockall() we return 0 when we're successful and -1 when we're not.
2721 * Unlike mlockall() we return 1 if we've already attempted to lock memory.
2724 tor_mlockall(void)
2726 static int memory_lock_attempted = 0;
2728 if (memory_lock_attempted) {
2729 return 1;
2732 memory_lock_attempted = 1;
2735 * Future consideration for Windows may be VirtualLock
2736 * VirtualLock appears to implement mlock() but not mlockall()
2738 * http://msdn.microsoft.com/en-us/library/aa366895(VS.85).aspx
2741 #if defined(HAVE_MLOCKALL) && HAVE_DECL_MLOCKALL && defined(RLIMIT_MEMLOCK)
2742 if (tor_set_max_memlock() == 0) {
2743 log_debug(LD_GENERAL, "RLIMIT_MEMLOCK is now set to RLIM_INFINITY.");
2746 if (mlockall(MCL_CURRENT|MCL_FUTURE) == 0) {
2747 log_info(LD_GENERAL, "Insecure OS paging is effectively disabled.");
2748 return 0;
2749 } else {
2750 if (errno == ENOSYS) {
2751 /* Apple - it's 2009! I'm looking at you. Grrr. */
2752 log_notice(LD_GENERAL, "It appears that mlockall() is not available on "
2753 "your platform.");
2754 } else if (errno == EPERM) {
2755 log_notice(LD_GENERAL, "It appears that you lack the permissions to "
2756 "lock memory. Are you root?");
2758 log_notice(LD_GENERAL, "Unable to lock all current and future memory "
2759 "pages: %s", strerror(errno));
2760 return -1;
2762 #else
2763 log_warn(LD_GENERAL, "Unable to lock memory pages. mlockall() unsupported?");
2764 return -1;
2765 #endif
2768 /** Identity of the "main" thread */
2769 static unsigned long main_thread_id = -1;
2771 /** Start considering the current thread to be the 'main thread'. This has
2772 * no effect on anything besides in_main_thread(). */
2773 void
2774 set_main_thread(void)
2776 main_thread_id = tor_get_thread_id();
2778 /** Return true iff called from the main thread. */
2780 in_main_thread(void)
2782 return main_thread_id == tor_get_thread_id();
2786 * On Windows, WSAEWOULDBLOCK is not always correct: when you see it,
2787 * you need to ask the socket for its actual errno. Also, you need to
2788 * get your errors from WSAGetLastError, not errno. (If you supply a
2789 * socket of -1, we check WSAGetLastError, but don't correct
2790 * WSAEWOULDBLOCKs.)
2792 * The upshot of all of this is that when a socket call fails, you
2793 * should call tor_socket_errno <em>at most once</em> on the failing
2794 * socket to get the error.
2796 #if defined(MS_WINDOWS)
2798 tor_socket_errno(tor_socket_t sock)
2800 int optval, optvallen=sizeof(optval);
2801 int err = WSAGetLastError();
2802 if (err == WSAEWOULDBLOCK && SOCKET_OK(sock)) {
2803 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval, &optvallen))
2804 return err;
2805 if (optval)
2806 return optval;
2808 return err;
2810 #endif
2812 #if defined(MS_WINDOWS)
2813 #define E(code, s) { code, (s " [" #code " ]") }
2814 struct { int code; const char *msg; } windows_socket_errors[] = {
2815 E(WSAEINTR, "Interrupted function call"),
2816 E(WSAEACCES, "Permission denied"),
2817 E(WSAEFAULT, "Bad address"),
2818 E(WSAEINVAL, "Invalid argument"),
2819 E(WSAEMFILE, "Too many open files"),
2820 E(WSAEWOULDBLOCK, "Resource temporarily unavailable"),
2821 E(WSAEINPROGRESS, "Operation now in progress"),
2822 E(WSAEALREADY, "Operation already in progress"),
2823 E(WSAENOTSOCK, "Socket operation on nonsocket"),
2824 E(WSAEDESTADDRREQ, "Destination address required"),
2825 E(WSAEMSGSIZE, "Message too long"),
2826 E(WSAEPROTOTYPE, "Protocol wrong for socket"),
2827 E(WSAENOPROTOOPT, "Bad protocol option"),
2828 E(WSAEPROTONOSUPPORT, "Protocol not supported"),
2829 E(WSAESOCKTNOSUPPORT, "Socket type not supported"),
2830 /* What's the difference between NOTSUPP and NOSUPPORT? :) */
2831 E(WSAEOPNOTSUPP, "Operation not supported"),
2832 E(WSAEPFNOSUPPORT, "Protocol family not supported"),
2833 E(WSAEAFNOSUPPORT, "Address family not supported by protocol family"),
2834 E(WSAEADDRINUSE, "Address already in use"),
2835 E(WSAEADDRNOTAVAIL, "Cannot assign requested address"),
2836 E(WSAENETDOWN, "Network is down"),
2837 E(WSAENETUNREACH, "Network is unreachable"),
2838 E(WSAENETRESET, "Network dropped connection on reset"),
2839 E(WSAECONNABORTED, "Software caused connection abort"),
2840 E(WSAECONNRESET, "Connection reset by peer"),
2841 E(WSAENOBUFS, "No buffer space available"),
2842 E(WSAEISCONN, "Socket is already connected"),
2843 E(WSAENOTCONN, "Socket is not connected"),
2844 E(WSAESHUTDOWN, "Cannot send after socket shutdown"),
2845 E(WSAETIMEDOUT, "Connection timed out"),
2846 E(WSAECONNREFUSED, "Connection refused"),
2847 E(WSAEHOSTDOWN, "Host is down"),
2848 E(WSAEHOSTUNREACH, "No route to host"),
2849 E(WSAEPROCLIM, "Too many processes"),
2850 /* Yes, some of these start with WSA, not WSAE. No, I don't know why. */
2851 E(WSASYSNOTREADY, "Network subsystem is unavailable"),
2852 E(WSAVERNOTSUPPORTED, "Winsock.dll out of range"),
2853 E(WSANOTINITIALISED, "Successful WSAStartup not yet performed"),
2854 E(WSAEDISCON, "Graceful shutdown now in progress"),
2855 #ifdef WSATYPE_NOT_FOUND
2856 E(WSATYPE_NOT_FOUND, "Class type not found"),
2857 #endif
2858 E(WSAHOST_NOT_FOUND, "Host not found"),
2859 E(WSATRY_AGAIN, "Nonauthoritative host not found"),
2860 E(WSANO_RECOVERY, "This is a nonrecoverable error"),
2861 E(WSANO_DATA, "Valid name, no data record of requested type)"),
2863 /* There are some more error codes whose numeric values are marked
2864 * <b>OS dependent</b>. They start with WSA_, apparently for the same
2865 * reason that practitioners of some craft traditions deliberately
2866 * introduce imperfections into their baskets and rugs "to allow the
2867 * evil spirits to escape." If we catch them, then our binaries
2868 * might not report consistent results across versions of Windows.
2869 * Thus, I'm going to let them all fall through.
2871 { -1, NULL },
2873 /** There does not seem to be a strerror equivalent for Winsock errors.
2874 * Naturally, we have to roll our own.
2876 const char *
2877 tor_socket_strerror(int e)
2879 int i;
2880 for (i=0; windows_socket_errors[i].code >= 0; ++i) {
2881 if (e == windows_socket_errors[i].code)
2882 return windows_socket_errors[i].msg;
2884 return strerror(e);
2886 #endif
2888 /** Called before we make any calls to network-related functions.
2889 * (Some operating systems require their network libraries to be
2890 * initialized.) */
2892 network_init(void)
2894 #ifdef MS_WINDOWS
2895 /* This silly exercise is necessary before windows will allow
2896 * gethostbyname to work. */
2897 WSADATA WSAData;
2898 int r;
2899 r = WSAStartup(0x101,&WSAData);
2900 if (r) {
2901 log_warn(LD_NET,"Error initializing windows network layer: code was %d",r);
2902 return -1;
2904 /* WSAData.iMaxSockets might show the max sockets we're allowed to use.
2905 * We might use it to complain if we're trying to be a server but have
2906 * too few sockets available. */
2907 #endif
2908 return 0;
2911 #ifdef MS_WINDOWS
2912 /** Return a newly allocated string describing the windows system error code
2913 * <b>err</b>. Note that error codes are different from errno. Error codes
2914 * come from GetLastError() when a winapi call fails. errno is set only when
2915 * ANSI functions fail. Whee. */
2916 char *
2917 format_win32_error(DWORD err)
2919 TCHAR *str = NULL;
2920 char *result;
2922 /* Somebody once decided that this interface was better than strerror(). */
2923 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
2924 FORMAT_MESSAGE_FROM_SYSTEM |
2925 FORMAT_MESSAGE_IGNORE_INSERTS,
2926 NULL, err,
2927 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
2928 (LPVOID)&str,
2929 0, NULL);
2931 if (str) {
2932 #ifdef UNICODE
2933 char abuf[1024] = {0};
2934 wcstombs(abuf,str,1024);
2935 result = tor_strdup(abuf);
2936 #else
2937 result = tor_strdup(str);
2938 #endif
2939 LocalFree(str); /* LocalFree != free() */
2940 } else {
2941 result = tor_strdup("<unformattable error>");
2943 return result;
2945 #endif