Windows has EACCES, not EACCESS
[tor/rransom.git] / src / common / compat.c
blobd29cacf372ea23af6d28b001ed758b4161279f37
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 #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 "torlog.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 /* XXXX why not just do fstat here? */
130 size = filesize = (size_t) lseek(fd, 0, SEEK_END);
131 lseek(fd, 0, SEEK_SET);
132 /* ensure page alignment */
133 page_size = getpagesize();
134 size += (size%page_size) ? page_size-(size%page_size) : 0;
136 if (!size) {
137 /* Zero-length file. If we call mmap on it, it will succeed but
138 * return NULL, and bad things will happen. So just fail. */
139 log_info(LD_FS,"File \"%s\" is empty. Ignoring.",filename);
140 errno = ERANGE;
141 close(fd);
142 return NULL;
145 string = mmap(0, size, PROT_READ, MAP_PRIVATE, fd, 0);
146 close(fd);
147 if (string == MAP_FAILED) {
148 int save_errno = errno;
149 log_warn(LD_FS,"Could not mmap file \"%s\": %s", filename,
150 strerror(errno));
151 errno = save_errno;
152 return NULL;
155 res = tor_malloc_zero(sizeof(tor_mmap_t));
156 res->data = string;
157 res->size = filesize;
158 res->mapping_size = size;
160 return res;
162 /** Release storage held for a memory mapping. */
163 void
164 tor_munmap_file(tor_mmap_t *handle)
166 munmap((char*)handle->data, handle->mapping_size);
167 tor_free(handle);
169 #elif defined(MS_WINDOWS)
170 tor_mmap_t *
171 tor_mmap_file(const char *filename)
173 TCHAR tfilename[MAX_PATH]= {0};
174 tor_mmap_t *res = tor_malloc_zero(sizeof(tor_mmap_t));
175 int empty = 0;
176 res->file_handle = INVALID_HANDLE_VALUE;
177 res->mmap_handle = NULL;
178 #ifdef UNICODE
179 mbstowcs(tfilename,filename,MAX_PATH);
180 #else
181 strlcpy(tfilename,filename,MAX_PATH);
182 #endif
183 res->file_handle = CreateFile(tfilename,
184 GENERIC_READ, FILE_SHARE_READ,
185 NULL,
186 OPEN_EXISTING,
187 FILE_ATTRIBUTE_NORMAL,
190 if (res->file_handle == INVALID_HANDLE_VALUE)
191 goto win_err;
193 res->size = GetFileSize(res->file_handle, NULL);
195 if (res->size == 0) {
196 log_info(LD_FS,"File \"%s\" is empty. Ignoring.",filename);
197 empty = 1;
198 goto err;
201 res->mmap_handle = CreateFileMapping(res->file_handle,
202 NULL,
203 PAGE_READONLY,
204 #if SIZEOF_SIZE_T > 4
205 (res->base.size >> 32),
206 #else
208 #endif
209 (res->size & 0xfffffffful),
210 NULL);
211 if (res->mmap_handle == NULL)
212 goto win_err;
213 res->data = (char*) MapViewOfFile(res->mmap_handle,
214 FILE_MAP_READ,
215 0, 0, 0);
216 if (!res->data)
217 goto win_err;
219 return res;
220 win_err: {
221 DWORD e = GetLastError();
222 int severity = (e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND) ?
223 LOG_INFO : LOG_WARN;
224 char *msg = format_win32_error(e);
225 log_fn(severity, LD_FS, "Couldn't mmap file \"%s\": %s", filename, msg);
226 tor_free(msg);
227 if (e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND)
228 errno = ENOENT;
229 else
230 errno = EINVAL;
232 err:
233 if (empty)
234 errno = ERANGE;
235 tor_munmap_file(res);
236 return NULL;
238 void
239 tor_munmap_file(tor_mmap_t *handle)
241 if (handle->data)
242 /* This is an ugly cast, but without it, "data" in struct tor_mmap_t would
243 have to be redefined as non-const. */
244 UnmapViewOfFile( (LPVOID) handle->data);
246 if (handle->mmap_handle != NULL)
247 CloseHandle(handle->mmap_handle);
248 if (handle->file_handle != INVALID_HANDLE_VALUE)
249 CloseHandle(handle->file_handle);
250 tor_free(handle);
252 #else
253 tor_mmap_t *
254 tor_mmap_file(const char *filename)
256 struct stat st;
257 char *res = read_file_to_str(filename, RFTS_BIN|RFTS_IGNORE_MISSING, &st);
258 tor_mmap_t *handle;
259 if (! res)
260 return NULL;
261 handle = tor_malloc_zero(sizeof(tor_mmap_t));
262 handle->data = res;
263 handle->size = st.st_size;
264 return handle;
266 void
267 tor_munmap_file(tor_mmap_t *handle)
269 char *d = (char*)handle->data;
270 tor_free(d);
271 memset(handle, 0, sizeof(tor_mmap_t));
272 tor_free(handle);
274 #endif
276 /** Replacement for snprintf. Differs from platform snprintf in two
277 * ways: First, always NUL-terminates its output. Second, always
278 * returns -1 if the result is truncated. (Note that this return
279 * behavior does <i>not</i> conform to C99; it just happens to be
280 * easier to emulate "return -1" with conformant implementations than
281 * it is to emulate "return number that would be written" with
282 * non-conformant implementations.) */
284 tor_snprintf(char *str, size_t size, const char *format, ...)
286 va_list ap;
287 int r;
288 va_start(ap,format);
289 r = tor_vsnprintf(str,size,format,ap);
290 va_end(ap);
291 return r;
294 /** Replacement for vsnprintf; behavior differs as tor_snprintf differs from
295 * snprintf.
298 tor_vsnprintf(char *str, size_t size, const char *format, va_list args)
300 int r;
301 if (size == 0)
302 return -1; /* no place for the NUL */
303 if (size > SIZE_T_CEILING)
304 return -1;
305 #ifdef MS_WINDOWS
306 r = _vsnprintf(str, size, format, args);
307 #else
308 r = vsnprintf(str, size, format, args);
309 #endif
310 str[size-1] = '\0';
311 if (r < 0 || r >= (ssize_t)size)
312 return -1;
313 return r;
317 * Portable asprintf implementation. Does a printf() into a newly malloc'd
318 * string. Sets *<b>strp</b> to this string, and returns its length (not
319 * including the terminating NUL character).
321 * You can treat this function as if its implementation were something like
322 <pre>
323 char buf[_INFINITY_];
324 tor_snprintf(buf, sizeof(buf), fmt, args);
325 *strp = tor_strdup(buf);
326 return strlen(*strp):
327 </pre>
328 * Where _INFINITY_ is an imaginary constant so big that any string can fit
329 * into it.
332 tor_asprintf(char **strp, const char *fmt, ...)
334 int r;
335 va_list args;
336 va_start(args, fmt);
337 r = tor_vasprintf(strp, fmt, args);
338 va_end(args);
339 if (!*strp || r < 0) {
340 log_err(LD_BUG, "Internal error in asprintf");
341 tor_assert(0);
343 return r;
347 * Portable vasprintf implementation. Does a printf() into a newly malloc'd
348 * string. Differs from regular vasprintf in the same ways that
349 * tor_asprintf() differs from regular asprintf.
352 tor_vasprintf(char **strp, const char *fmt, va_list args)
354 /* use a temporary variable in case *strp is in args. */
355 char *strp_tmp=NULL;
356 #ifdef HAVE_VASPRINTF
357 /* If the platform gives us one, use it. */
358 int r = vasprintf(&strp_tmp, fmt, args);
359 if (r < 0)
360 *strp = NULL;
361 else
362 *strp = strp_tmp;
363 return r;
364 #elif defined(_MSC_VER)
365 /* On Windows, _vsnprintf won't tell us the length of the string if it
366 * overflows, so we need to use _vcsprintf to tell how much to allocate */
367 int len, r;
368 char *res;
369 len = _vscprintf(fmt, args);
370 if (len < 0) {
371 *strp = NULL;
372 return -1;
374 strp_tmp = tor_malloc(len + 1);
375 r = _vsnprintf(strp_tmp, len+1, fmt, args);
376 if (r != len) {
377 tor_free(strp_tmp);
378 *strp = NULL;
379 return -1;
381 *strp = strp_tmp;
382 return len;
383 #else
384 /* Everywhere else, we have a decent vsnprintf that tells us how many
385 * characters we need. We give it a try on a short buffer first, since
386 * it might be nice to avoid the second vsnprintf call.
388 char buf[128];
389 int len, r;
390 va_list tmp_args;
391 va_copy(tmp_args, args);
392 len = vsnprintf(buf, sizeof(buf), fmt, tmp_args);
393 va_end(tmp_args);
394 if (len < (int)sizeof(buf)) {
395 *strp = tor_strdup(buf);
396 return len;
398 strp_tmp = tor_malloc(len+1);
399 r = vsnprintf(strp_tmp, len+1, fmt, args);
400 if (r != len) {
401 tor_free(strp_tmp);
402 *strp = NULL;
403 return -1;
405 *strp = strp_tmp;
406 return len;
407 #endif
410 /** Given <b>hlen</b> bytes at <b>haystack</b> and <b>nlen</b> bytes at
411 * <b>needle</b>, return a pointer to the first occurrence of the needle
412 * within the haystack, or NULL if there is no such occurrence.
414 * Requires that nlen be greater than zero.
416 const void *
417 tor_memmem(const void *_haystack, size_t hlen,
418 const void *_needle, size_t nlen)
420 #if defined(HAVE_MEMMEM) && (!defined(__GNUC__) || __GNUC__ >= 2)
421 tor_assert(nlen);
422 return memmem(_haystack, hlen, _needle, nlen);
423 #else
424 /* This isn't as fast as the GLIBC implementation, but it doesn't need to
425 * be. */
426 const char *p, *end;
427 const char *haystack = (const char*)_haystack;
428 const char *needle = (const char*)_needle;
429 char first;
430 tor_assert(nlen);
432 p = haystack;
433 end = haystack + hlen;
434 first = *(const char*)needle;
435 while ((p = memchr(p, first, end-p))) {
436 if (p+nlen > end)
437 return NULL;
438 if (!memcmp(p, needle, nlen))
439 return p;
440 ++p;
442 return NULL;
443 #endif
446 /* Tables to implement ctypes-replacement TOR_IS*() functions. Each table
447 * has 256 bits to look up whether a character is in some set or not. This
448 * fails on non-ASCII platforms, but it is hard to find a platform whose
449 * character set is not a superset of ASCII nowadays. */
450 const uint32_t TOR_ISALPHA_TABLE[8] =
451 { 0, 0, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
452 const uint32_t TOR_ISALNUM_TABLE[8] =
453 { 0, 0x3ff0000, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
454 const uint32_t TOR_ISSPACE_TABLE[8] = { 0x3e00, 0x1, 0, 0, 0, 0, 0, 0 };
455 const uint32_t TOR_ISXDIGIT_TABLE[8] =
456 { 0, 0x3ff0000, 0x7e, 0x7e, 0, 0, 0, 0 };
457 const uint32_t TOR_ISDIGIT_TABLE[8] = { 0, 0x3ff0000, 0, 0, 0, 0, 0, 0 };
458 const uint32_t TOR_ISPRINT_TABLE[8] =
459 { 0, 0xffffffff, 0xffffffff, 0x7fffffff, 0, 0, 0, 0x0 };
460 const uint32_t TOR_ISUPPER_TABLE[8] = { 0, 0, 0x7fffffe, 0, 0, 0, 0, 0 };
461 const uint32_t TOR_ISLOWER_TABLE[8] = { 0, 0, 0, 0x7fffffe, 0, 0, 0, 0 };
462 /* Upper-casing and lowercasing tables to map characters to upper/lowercase
463 * equivalents. */
464 const char TOR_TOUPPER_TABLE[256] = {
465 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
466 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
467 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
468 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
469 64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
470 80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
471 96,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
472 80,81,82,83,84,85,86,87,88,89,90,123,124,125,126,127,
473 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
474 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
475 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
476 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
477 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
478 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
479 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
480 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
482 const char TOR_TOLOWER_TABLE[256] = {
483 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
484 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
485 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
486 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
487 64,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
488 112,113,114,115,116,117,118,119,120,121,122,91,92,93,94,95,
489 96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
490 112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
491 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
492 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
493 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
494 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
495 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
496 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
497 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
498 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
501 /** Implementation of strtok_r for platforms whose coders haven't figured out
502 * how to write one. Hey guys! You can use this code here for free! */
503 char *
504 tor_strtok_r_impl(char *str, const char *sep, char **lasts)
506 char *cp, *start;
507 if (str)
508 start = cp = *lasts = str;
509 else if (!*lasts)
510 return NULL;
511 else
512 start = cp = *lasts;
514 tor_assert(*sep);
515 if (sep[1]) {
516 while (*cp && !strchr(sep, *cp))
517 ++cp;
518 } else {
519 tor_assert(strlen(sep) == 1);
520 cp = strchr(cp, *sep);
523 if (!cp || !*cp) {
524 *lasts = NULL;
525 } else {
526 *cp++ = '\0';
527 *lasts = cp;
529 return start;
532 #ifdef MS_WINDOWS
533 /** Take a filename and return a pointer to its final element. This
534 * function is called on __FILE__ to fix a MSVC nit where __FILE__
535 * contains the full path to the file. This is bad, because it
536 * confuses users to find the home directory of the person who
537 * compiled the binary in their warning messages.
539 const char *
540 tor_fix_source_file(const char *fname)
542 const char *cp1, *cp2, *r;
543 cp1 = strrchr(fname, '/');
544 cp2 = strrchr(fname, '\\');
545 if (cp1 && cp2) {
546 r = (cp1<cp2)?(cp2+1):(cp1+1);
547 } else if (cp1) {
548 r = cp1+1;
549 } else if (cp2) {
550 r = cp2+1;
551 } else {
552 r = fname;
554 return r;
556 #endif
559 * Read a 16-bit value beginning at <b>cp</b>. Equivalent to
560 * *(uint16_t*)(cp), but will not cause segfaults on platforms that forbid
561 * unaligned memory access.
563 uint16_t
564 get_uint16(const void *cp)
566 uint16_t v;
567 memcpy(&v,cp,2);
568 return v;
571 * Read a 32-bit value beginning at <b>cp</b>. Equivalent to
572 * *(uint32_t*)(cp), but will not cause segfaults on platforms that forbid
573 * unaligned memory access.
575 uint32_t
576 get_uint32(const void *cp)
578 uint32_t v;
579 memcpy(&v,cp,4);
580 return v;
583 * Read a 64-bit value beginning at <b>cp</b>. Equivalent to
584 * *(uint64_t*)(cp), but will not cause segfaults on platforms that forbid
585 * unaligned memory access.
587 uint64_t
588 get_uint64(const void *cp)
590 uint64_t v;
591 memcpy(&v,cp,8);
592 return v;
596 * Set a 16-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
597 * *(uint16_t*)(cp) = v, but will not cause segfaults on platforms that forbid
598 * unaligned memory access. */
599 void
600 set_uint16(void *cp, uint16_t v)
602 memcpy(cp,&v,2);
605 * Set a 32-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
606 * *(uint32_t*)(cp) = v, but will not cause segfaults on platforms that forbid
607 * unaligned memory access. */
608 void
609 set_uint32(void *cp, uint32_t v)
611 memcpy(cp,&v,4);
614 * Set a 64-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
615 * *(uint64_t*)(cp) = v, but will not cause segfaults on platforms that forbid
616 * unaligned memory access. */
617 void
618 set_uint64(void *cp, uint64_t v)
620 memcpy(cp,&v,8);
624 * Rename the file <b>from</b> to the file <b>to</b>. On Unix, this is
625 * the same as rename(2). On windows, this removes <b>to</b> first if
626 * it already exists.
627 * Returns 0 on success. Returns -1 and sets errno on failure.
630 replace_file(const char *from, const char *to)
632 #ifndef MS_WINDOWS
633 return rename(from,to);
634 #else
635 switch (file_status(to))
637 case FN_NOENT:
638 break;
639 case FN_FILE:
640 if (unlink(to)) return -1;
641 break;
642 case FN_ERROR:
643 return -1;
644 case FN_DIR:
645 errno = EISDIR;
646 return -1;
648 return rename(from,to);
649 #endif
652 /** Change <b>fname</b>'s modification time to now. */
654 touch_file(const char *fname)
656 if (utime(fname, NULL)!=0)
657 return -1;
658 return 0;
661 /** Represents a lockfile on which we hold the lock. */
662 struct tor_lockfile_t {
663 char *filename;
664 int fd;
667 /** Try to get a lock on the lockfile <b>filename</b>, creating it as
668 * necessary. If someone else has the lock and <b>blocking</b> is true,
669 * wait until the lock is available. Otherwise return immediately whether
670 * we succeeded or not.
672 * Set *<b>locked_out</b> to true if somebody else had the lock, and to false
673 * otherwise.
675 * Return a <b>tor_lockfile_t</b> on success, NULL on failure.
677 * (Implementation note: because we need to fall back to fcntl on some
678 * platforms, these locks are per-process, not per-thread. If you want
679 * to do in-process locking, use tor_mutex_t like a normal person.
680 * On Windows, when <b>blocking</b> is true, the maximum time that
681 * is actually waited is 10 seconds, after which NULL is returned
682 * and <b>locked_out</b> is set to 1.)
684 tor_lockfile_t *
685 tor_lockfile_lock(const char *filename, int blocking, int *locked_out)
687 tor_lockfile_t *result;
688 int fd;
689 *locked_out = 0;
691 log_info(LD_FS, "Locking \"%s\"", filename);
692 fd = open(filename, O_RDWR|O_CREAT|O_TRUNC, 0600);
693 if (fd < 0) {
694 log_warn(LD_FS,"Couldn't open \"%s\" for locking: %s", filename,
695 strerror(errno));
696 return NULL;
699 #ifdef WIN32
700 _lseek(fd, 0, SEEK_SET);
701 if (_locking(fd, blocking ? _LK_LOCK : _LK_NBLCK, 1) < 0) {
702 if (errno != EACCES && errno != EDEADLOCK)
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 #elif defined(HAVE_FLOCK)
710 if (flock(fd, LOCK_EX|(blocking ? 0 : LOCK_NB)) < 0) {
711 if (errno != EWOULDBLOCK)
712 log_warn(LD_FS,"Couldn't lock \"%s\": %s", filename, strerror(errno));
713 else
714 *locked_out = 1;
715 close(fd);
716 return NULL;
718 #else
720 struct flock lock;
721 memset(&lock, 0, sizeof(lock));
722 lock.l_type = F_WRLCK;
723 lock.l_whence = SEEK_SET;
724 if (fcntl(fd, blocking ? F_SETLKW : F_SETLK, &lock) < 0) {
725 if (errno != EACCES && errno != EAGAIN)
726 log_warn(LD_FS, "Couldn't lock \"%s\": %s", filename, strerror(errno));
727 else
728 *locked_out = 1;
729 close(fd);
730 return NULL;
733 #endif
735 result = tor_malloc(sizeof(tor_lockfile_t));
736 result->filename = tor_strdup(filename);
737 result->fd = fd;
738 return result;
741 /** Release the lock held as <b>lockfile</b>. */
742 void
743 tor_lockfile_unlock(tor_lockfile_t *lockfile)
745 tor_assert(lockfile);
747 log_info(LD_FS, "Unlocking \"%s\"", lockfile->filename);
748 #ifdef WIN32
749 _lseek(lockfile->fd, 0, SEEK_SET);
750 if (_locking(lockfile->fd, _LK_UNLCK, 1) < 0) {
751 log_warn(LD_FS,"Error unlocking \"%s\": %s", lockfile->filename,
752 strerror(errno));
754 #elif defined(HAVE_FLOCK)
755 if (flock(lockfile->fd, LOCK_UN) < 0) {
756 log_warn(LD_FS, "Error unlocking \"%s\": %s", lockfile->filename,
757 strerror(errno));
759 #else
760 /* Closing the lockfile is sufficient. */
761 #endif
763 close(lockfile->fd);
764 lockfile->fd = -1;
765 tor_free(lockfile->filename);
766 tor_free(lockfile);
769 /* Some old versions of Unix didn't define constants for these values,
770 * and instead expect you to say 0, 1, or 2. */
771 #ifndef SEEK_CUR
772 #define SEEK_CUR 1
773 #endif
774 #ifndef SEEK_END
775 #define SEEK_END 2
776 #endif
778 /** Return the position of <b>fd</b> with respect to the start of the file. */
779 off_t
780 tor_fd_getpos(int fd)
782 #ifdef WIN32
783 return (off_t) _lseek(fd, 0, SEEK_CUR);
784 #else
785 return (off_t) lseek(fd, 0, SEEK_CUR);
786 #endif
789 /** Move <b>fd</b> to the end of the file. Return -1 on error, 0 on success. */
791 tor_fd_seekend(int fd)
793 #ifdef WIN32
794 return _lseek(fd, 0, SEEK_END) < 0 ? -1 : 0;
795 #else
796 return lseek(fd, 0, SEEK_END) < 0 ? -1 : 0;
797 #endif
800 #undef DEBUG_SOCKET_COUNTING
801 #ifdef DEBUG_SOCKET_COUNTING
802 /** A bitarray of all fds that should be passed to tor_socket_close(). Only
803 * used if DEBUG_SOCKET_COUNTING is defined. */
804 static bitarray_t *open_sockets = NULL;
805 /** The size of <b>open_sockets</b>, in bits. */
806 static int max_socket = -1;
807 #endif
809 /** Count of number of sockets currently open. (Undercounts sockets opened by
810 * eventdns and libevent.) */
811 static int n_sockets_open = 0;
813 /** Mutex to protect open_sockets, max_socket, and n_sockets_open. */
814 static tor_mutex_t *socket_accounting_mutex = NULL;
816 static INLINE void
817 socket_accounting_lock(void)
819 if (PREDICT_UNLIKELY(!socket_accounting_mutex))
820 socket_accounting_mutex = tor_mutex_new();
821 tor_mutex_acquire(socket_accounting_mutex);
824 static INLINE void
825 socket_accounting_unlock(void)
827 tor_mutex_release(socket_accounting_mutex);
830 /** As close(), but guaranteed to work for sockets across platforms (including
831 * Windows, where close()ing a socket doesn't work. Returns 0 on success, -1
832 * on failure. */
834 tor_close_socket(int s)
836 int r = 0;
838 /* On Windows, you have to call close() on fds returned by open(),
839 * and closesocket() on fds returned by socket(). On Unix, everything
840 * gets close()'d. We abstract this difference by always using
841 * tor_close_socket to close sockets, and always using close() on
842 * files.
844 #if defined(MS_WINDOWS)
845 r = closesocket(s);
846 #else
847 r = close(s);
848 #endif
850 socket_accounting_lock();
851 #ifdef DEBUG_SOCKET_COUNTING
852 if (s > max_socket || ! bitarray_is_set(open_sockets, s)) {
853 log_warn(LD_BUG, "Closing a socket (%d) that wasn't returned by tor_open_"
854 "socket(), or that was already closed or something.", s);
855 } else {
856 tor_assert(open_sockets && s <= max_socket);
857 bitarray_clear(open_sockets, s);
859 #endif
860 if (r == 0) {
861 --n_sockets_open;
862 } else {
863 int err = tor_socket_errno(-1);
864 log_info(LD_NET, "Close returned an error: %s", tor_socket_strerror(err));
865 #ifdef WIN32
866 if (err != WSAENOTSOCK)
867 --n_sockets_open;
868 #else
869 if (err != EBADF)
870 --n_sockets_open;
871 #endif
872 r = -1;
875 if (n_sockets_open < 0)
876 log_warn(LD_BUG, "Our socket count is below zero: %d. Please submit a "
877 "bug report.", n_sockets_open);
878 socket_accounting_unlock();
879 return r;
882 #ifdef DEBUG_SOCKET_COUNTING
883 /** Helper: if DEBUG_SOCKET_COUNTING is enabled, remember that <b>s</b> is
884 * now an open socket. */
885 static INLINE void
886 mark_socket_open(int s)
888 if (s > max_socket) {
889 if (max_socket == -1) {
890 open_sockets = bitarray_init_zero(s+128);
891 max_socket = s+128;
892 } else {
893 open_sockets = bitarray_expand(open_sockets, max_socket, s+128);
894 max_socket = s+128;
897 if (bitarray_is_set(open_sockets, s)) {
898 log_warn(LD_BUG, "I thought that %d was already open, but socket() just "
899 "gave it to me!", s);
901 bitarray_set(open_sockets, s);
903 #else
904 #define mark_socket_open(s) STMT_NIL
905 #endif
907 /** As socket(), but counts the number of open sockets. */
909 tor_open_socket(int domain, int type, int protocol)
911 int s = socket(domain, type, protocol);
912 if (s >= 0) {
913 socket_accounting_lock();
914 ++n_sockets_open;
915 mark_socket_open(s);
916 socket_accounting_unlock();
918 return s;
921 /** As socket(), but counts the number of open sockets. */
923 tor_accept_socket(int sockfd, struct sockaddr *addr, socklen_t *len)
925 int s = accept(sockfd, addr, len);
926 if (s >= 0) {
927 socket_accounting_lock();
928 ++n_sockets_open;
929 mark_socket_open(s);
930 socket_accounting_unlock();
932 return s;
935 /** Return the number of sockets we currently have opened. */
937 get_n_open_sockets(void)
939 int n;
940 socket_accounting_lock();
941 n = n_sockets_open;
942 socket_accounting_unlock();
943 return n;
946 /** Turn <b>socket</b> into a nonblocking socket.
948 void
949 set_socket_nonblocking(int socket)
951 #if defined(MS_WINDOWS)
952 unsigned long nonblocking = 1;
953 ioctlsocket(socket, FIONBIO, (unsigned long*) &nonblocking);
954 #else
955 fcntl(socket, F_SETFL, O_NONBLOCK);
956 #endif
960 * Allocate a pair of connected sockets. (Like socketpair(family,
961 * type,protocol,fd), but works on systems that don't have
962 * socketpair.)
964 * Currently, only (AF_UNIX, SOCK_STREAM, 0) sockets are supported.
966 * Note that on systems without socketpair, this call will fail if
967 * localhost is inaccessible (for example, if the networking
968 * stack is down). And even if it succeeds, the socket pair will not
969 * be able to read while localhost is down later (the socket pair may
970 * even close, depending on OS-specific timeouts).
972 * Returns 0 on success and -errno on failure; do not rely on the value
973 * of errno or WSAGetLastError().
975 /* It would be nicer just to set errno, but that won't work for windows. */
977 tor_socketpair(int family, int type, int protocol, int fd[2])
979 //don't use win32 socketpairs (they are always bad)
980 #if defined(HAVE_SOCKETPAIR) && !defined(MS_WINDOWS)
981 int r;
982 r = socketpair(family, type, protocol, fd);
983 if (r == 0) {
984 socket_accounting_lock();
985 if (fd[0] >= 0) {
986 ++n_sockets_open;
987 mark_socket_open(fd[0]);
989 if (fd[1] >= 0) {
990 ++n_sockets_open;
991 mark_socket_open(fd[1]);
993 socket_accounting_unlock();
995 return r < 0 ? -errno : r;
996 #else
997 /* This socketpair does not work when localhost is down. So
998 * it's really not the same thing at all. But it's close enough
999 * for now, and really, when localhost is down sometimes, we
1000 * have other problems too.
1002 int listener = -1;
1003 int connector = -1;
1004 int acceptor = -1;
1005 struct sockaddr_in listen_addr;
1006 struct sockaddr_in connect_addr;
1007 int size;
1008 int saved_errno = -1;
1010 if (protocol
1011 #ifdef AF_UNIX
1012 || family != AF_UNIX
1013 #endif
1015 #ifdef MS_WINDOWS
1016 return -WSAEAFNOSUPPORT;
1017 #else
1018 return -EAFNOSUPPORT;
1019 #endif
1021 if (!fd) {
1022 return -EINVAL;
1025 listener = tor_open_socket(AF_INET, type, 0);
1026 if (listener < 0)
1027 return -tor_socket_errno(-1);
1028 memset(&listen_addr, 0, sizeof(listen_addr));
1029 listen_addr.sin_family = AF_INET;
1030 listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
1031 listen_addr.sin_port = 0; /* kernel chooses port. */
1032 if (bind(listener, (struct sockaddr *) &listen_addr, sizeof (listen_addr))
1033 == -1)
1034 goto tidy_up_and_fail;
1035 if (listen(listener, 1) == -1)
1036 goto tidy_up_and_fail;
1038 connector = tor_open_socket(AF_INET, type, 0);
1039 if (connector < 0)
1040 goto tidy_up_and_fail;
1041 /* We want to find out the port number to connect to. */
1042 size = sizeof(connect_addr);
1043 if (getsockname(listener, (struct sockaddr *) &connect_addr, &size) == -1)
1044 goto tidy_up_and_fail;
1045 if (size != sizeof (connect_addr))
1046 goto abort_tidy_up_and_fail;
1047 if (connect(connector, (struct sockaddr *) &connect_addr,
1048 sizeof(connect_addr)) == -1)
1049 goto tidy_up_and_fail;
1051 size = sizeof(listen_addr);
1052 acceptor = tor_accept_socket(listener,
1053 (struct sockaddr *) &listen_addr, &size);
1054 if (acceptor < 0)
1055 goto tidy_up_and_fail;
1056 if (size != sizeof(listen_addr))
1057 goto abort_tidy_up_and_fail;
1058 tor_close_socket(listener);
1059 /* Now check we are talking to ourself by matching port and host on the
1060 two sockets. */
1061 if (getsockname(connector, (struct sockaddr *) &connect_addr, &size) == -1)
1062 goto tidy_up_and_fail;
1063 if (size != sizeof (connect_addr)
1064 || listen_addr.sin_family != connect_addr.sin_family
1065 || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
1066 || listen_addr.sin_port != connect_addr.sin_port) {
1067 goto abort_tidy_up_and_fail;
1069 fd[0] = connector;
1070 fd[1] = acceptor;
1072 return 0;
1074 abort_tidy_up_and_fail:
1075 #ifdef MS_WINDOWS
1076 saved_errno = WSAECONNABORTED;
1077 #else
1078 saved_errno = ECONNABORTED; /* I hope this is portable and appropriate. */
1079 #endif
1080 tidy_up_and_fail:
1081 if (saved_errno < 0)
1082 saved_errno = errno;
1083 if (listener != -1)
1084 tor_close_socket(listener);
1085 if (connector != -1)
1086 tor_close_socket(connector);
1087 if (acceptor != -1)
1088 tor_close_socket(acceptor);
1089 return -saved_errno;
1090 #endif
1093 #define ULIMIT_BUFFER 32 /* keep 32 extra fd's beyond _ConnLimit */
1095 /** Learn the maximum allowed number of file descriptors. (Some systems
1096 * have a low soft limit.
1098 * We compute this by finding the largest number that we can use.
1099 * If we can't find a number greater than or equal to <b>limit</b>,
1100 * then we fail: return -1.
1102 * Otherwise, return 0 and store the maximum we found inside <b>max_out</b>.*/
1104 set_max_file_descriptors(rlim_t limit, int *max_out)
1106 /* Define some maximum connections values for systems where we cannot
1107 * automatically determine a limit. Re Cygwin, see
1108 * http://archives.seul.org/or/talk/Aug-2006/msg00210.html
1109 * For an iPhone, 9999 should work. For Windows and all other unknown
1110 * systems we use 15000 as the default. */
1111 #ifndef HAVE_GETRLIMIT
1112 #if defined(CYGWIN) || defined(__CYGWIN__)
1113 const char *platform = "Cygwin";
1114 const unsigned long MAX_CONNECTIONS = 3200;
1115 #elif defined(MS_WINDOWS)
1116 const char *platform = "Windows";
1117 const unsigned long MAX_CONNECTIONS = 15000;
1118 #else
1119 const char *platform = "unknown platforms with no getrlimit()";
1120 const unsigned long MAX_CONNECTIONS = 15000;
1121 #endif
1122 log_fn(LOG_INFO, LD_NET,
1123 "This platform is missing getrlimit(). Proceeding.");
1124 if (limit > MAX_CONNECTIONS) {
1125 log_warn(LD_CONFIG,
1126 "We do not support more than %lu file descriptors "
1127 "on %s. Tried to raise to %lu.",
1128 (unsigned long)MAX_CONNECTIONS, platform, (unsigned long)limit);
1129 return -1;
1131 limit = MAX_CONNECTIONS;
1132 #else /* HAVE_GETRLIMIT */
1133 struct rlimit rlim;
1134 tor_assert(limit > 0);
1136 if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) {
1137 log_warn(LD_NET, "Could not get maximum number of file descriptors: %s",
1138 strerror(errno));
1139 return -1;
1142 if (rlim.rlim_max < limit) {
1143 log_warn(LD_CONFIG,"We need %lu file descriptors available, and we're "
1144 "limited to %lu. Please change your ulimit -n.",
1145 (unsigned long)limit, (unsigned long)rlim.rlim_max);
1146 return -1;
1149 if (rlim.rlim_max > rlim.rlim_cur) {
1150 log_info(LD_NET,"Raising max file descriptors from %lu to %lu.",
1151 (unsigned long)rlim.rlim_cur, (unsigned long)rlim.rlim_max);
1153 rlim.rlim_cur = rlim.rlim_max;
1155 if (setrlimit(RLIMIT_NOFILE, &rlim) != 0) {
1156 int bad = 1;
1157 #ifdef OPEN_MAX
1158 if (errno == EINVAL && OPEN_MAX < rlim.rlim_cur) {
1159 /* On some platforms, OPEN_MAX is the real limit, and getrlimit() is
1160 * full of nasty lies. I'm looking at you, OSX 10.5.... */
1161 rlim.rlim_cur = OPEN_MAX;
1162 if (setrlimit(RLIMIT_NOFILE, &rlim) == 0) {
1163 if (rlim.rlim_cur < (rlim_t)limit) {
1164 log_warn(LD_CONFIG, "We are limited to %lu file descriptors by "
1165 "OPEN_MAX, and ConnLimit is %lu. Changing ConnLimit; sorry.",
1166 (unsigned long)OPEN_MAX, (unsigned long)limit);
1167 } else {
1168 log_info(LD_CONFIG, "Dropped connection limit to OPEN_MAX (%lu); "
1169 "Apparently, %lu was too high and rlimit lied to us.",
1170 (unsigned long)OPEN_MAX, (unsigned long)rlim.rlim_max);
1172 bad = 0;
1175 #endif /* OPEN_MAX */
1176 if (bad) {
1177 log_warn(LD_CONFIG,"Couldn't set maximum number of file descriptors: %s",
1178 strerror(errno));
1179 return -1;
1182 /* leave some overhead for logs, etc, */
1183 limit = rlim.rlim_cur;
1184 #endif /* HAVE_GETRLIMIT */
1186 if (limit < ULIMIT_BUFFER) {
1187 log_warn(LD_CONFIG,
1188 "ConnLimit must be at least %d. Failing.", ULIMIT_BUFFER);
1189 return -1;
1191 if (limit > INT_MAX)
1192 limit = INT_MAX;
1193 tor_assert(max_out);
1194 *max_out = (int)limit - ULIMIT_BUFFER;
1195 return 0;
1198 #ifndef MS_WINDOWS
1199 /** Log details of current user and group credentials. Return 0 on
1200 * success. Logs and return -1 on failure.
1202 static int
1203 log_credential_status(void)
1205 #define CREDENTIAL_LOG_LEVEL LOG_INFO
1206 /* Real, effective and saved UIDs */
1207 uid_t ruid, euid, suid;
1208 /* Read, effective and saved GIDs */
1209 gid_t rgid, egid, sgid;
1210 /* Supplementary groups */
1211 gid_t sup_gids[NGROUPS_MAX + 1];
1212 /* Number of supplementary groups */
1213 int ngids;
1215 /* log UIDs */
1216 #ifdef HAVE_GETRESUID
1217 if (getresuid(&ruid, &euid, &suid) != 0 ) {
1218 log_warn(LD_GENERAL, "Error getting changed UIDs: %s", strerror(errno));
1219 return -1;
1220 } else {
1221 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
1222 "UID is %u (real), %u (effective), %u (saved)",
1223 (unsigned)ruid, (unsigned)euid, (unsigned)suid);
1225 #else
1226 /* getresuid is not present on MacOS X, so we can't get the saved (E)UID */
1227 ruid = getuid();
1228 euid = geteuid();
1229 (void)suid;
1231 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
1232 "UID is %u (real), %u (effective), unknown (saved)",
1233 (unsigned)ruid, (unsigned)euid);
1234 #endif
1236 /* log GIDs */
1237 #ifdef HAVE_GETRESGID
1238 if (getresgid(&rgid, &egid, &sgid) != 0 ) {
1239 log_warn(LD_GENERAL, "Error getting changed GIDs: %s", strerror(errno));
1240 return -1;
1241 } else {
1242 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
1243 "GID is %u (real), %u (effective), %u (saved)",
1244 (unsigned)rgid, (unsigned)egid, (unsigned)sgid);
1246 #else
1247 /* getresgid is not present on MacOS X, so we can't get the saved (E)GID */
1248 rgid = getgid();
1249 egid = getegid();
1250 (void)sgid;
1251 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
1252 "GID is %u (real), %u (effective), unknown (saved)",
1253 (unsigned)rgid, (unsigned)egid);
1254 #endif
1256 /* log supplementary groups */
1257 if ((ngids = getgroups(NGROUPS_MAX + 1, sup_gids)) < 0) {
1258 log_warn(LD_GENERAL, "Error getting supplementary GIDs: %s",
1259 strerror(errno));
1260 return -1;
1261 } else {
1262 int i, retval = 0;
1263 char *strgid;
1264 char *s = NULL;
1265 smartlist_t *elts = smartlist_create();
1267 for (i = 0; i<ngids; i++) {
1268 strgid = tor_malloc(11);
1269 if (tor_snprintf(strgid, 11, "%u", (unsigned)sup_gids[i]) < 0) {
1270 log_warn(LD_GENERAL, "Error printing supplementary GIDs");
1271 tor_free(strgid);
1272 retval = -1;
1273 goto error;
1275 smartlist_add(elts, strgid);
1278 s = smartlist_join_strings(elts, " ", 0, NULL);
1280 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL, "Supplementary groups are: %s",s);
1282 error:
1283 tor_free(s);
1284 SMARTLIST_FOREACH(elts, char *, cp,
1286 tor_free(cp);
1288 smartlist_free(elts);
1290 return retval;
1293 return 0;
1295 #endif
1297 /** Call setuid and setgid to run as <b>user</b> and switch to their
1298 * primary group. Return 0 on success. On failure, log and return -1.
1301 switch_id(const char *user)
1303 #ifndef MS_WINDOWS
1304 struct passwd *pw = NULL;
1305 uid_t old_uid;
1306 gid_t old_gid;
1307 static int have_already_switched_id = 0;
1309 tor_assert(user);
1311 if (have_already_switched_id)
1312 return 0;
1314 /* Log the initial credential state */
1315 if (log_credential_status())
1316 return -1;
1318 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL, "Changing user and groups");
1320 /* Get old UID/GID to check if we changed correctly */
1321 old_uid = getuid();
1322 old_gid = getgid();
1324 /* Lookup the user and group information, if we have a problem, bail out. */
1325 pw = getpwnam(user);
1326 if (pw == NULL) {
1327 log_warn(LD_CONFIG, "Error setting configured user: %s not found", user);
1328 return -1;
1331 /* Properly switch egid,gid,euid,uid here or bail out */
1332 if (setgroups(1, &pw->pw_gid)) {
1333 log_warn(LD_GENERAL, "Error setting groups to gid %d: \"%s\".",
1334 (int)pw->pw_gid, strerror(errno));
1335 if (old_uid == pw->pw_uid) {
1336 log_warn(LD_GENERAL, "Tor is already running as %s. You do not need "
1337 "the \"User\" option if you are already running as the user "
1338 "you want to be. (If you did not set the User option in your "
1339 "torrc, check whether it was specified on the command line "
1340 "by a startup script.)", user);
1341 } else {
1342 log_warn(LD_GENERAL, "If you set the \"User\" option, you must start Tor"
1343 " as root.");
1345 return -1;
1348 if (setegid(pw->pw_gid)) {
1349 log_warn(LD_GENERAL, "Error setting egid to %d: %s",
1350 (int)pw->pw_gid, strerror(errno));
1351 return -1;
1354 if (setgid(pw->pw_gid)) {
1355 log_warn(LD_GENERAL, "Error setting gid to %d: %s",
1356 (int)pw->pw_gid, strerror(errno));
1357 return -1;
1360 if (setuid(pw->pw_uid)) {
1361 log_warn(LD_GENERAL, "Error setting configured uid to %s (%d): %s",
1362 user, (int)pw->pw_uid, strerror(errno));
1363 return -1;
1366 if (seteuid(pw->pw_uid)) {
1367 log_warn(LD_GENERAL, "Error setting configured euid to %s (%d): %s",
1368 user, (int)pw->pw_uid, strerror(errno));
1369 return -1;
1372 /* This is how OpenBSD rolls:
1373 if (setgroups(1, &pw->pw_gid) || setegid(pw->pw_gid) ||
1374 setgid(pw->pw_gid) || setuid(pw->pw_uid) || seteuid(pw->pw_uid)) {
1375 setgid(pw->pw_gid) || seteuid(pw->pw_uid) || setuid(pw->pw_uid)) {
1376 log_warn(LD_GENERAL, "Error setting configured UID/GID: %s",
1377 strerror(errno));
1378 return -1;
1382 /* We've properly switched egid, gid, euid, uid, and supplementary groups if
1383 * we're here. */
1385 #if !defined(CYGWIN) && !defined(__CYGWIN__)
1386 /* If we tried to drop privilege to a group/user other than root, attempt to
1387 * restore root (E)(U|G)ID, and abort if the operation succeeds */
1389 /* Only check for privilege dropping if we were asked to be non-root */
1390 if (pw->pw_uid) {
1391 /* Try changing GID/EGID */
1392 if (pw->pw_gid != old_gid &&
1393 (setgid(old_gid) != -1 || setegid(old_gid) != -1)) {
1394 log_warn(LD_GENERAL, "Was able to restore group credentials even after "
1395 "switching GID: this means that the setgid code didn't work.");
1396 return -1;
1399 /* Try changing UID/EUID */
1400 if (pw->pw_uid != old_uid &&
1401 (setuid(old_uid) != -1 || seteuid(old_uid) != -1)) {
1402 log_warn(LD_GENERAL, "Was able to restore user credentials even after "
1403 "switching UID: this means that the setuid code didn't work.");
1404 return -1;
1407 #endif
1409 /* Check what really happened */
1410 if (log_credential_status()) {
1411 return -1;
1414 have_already_switched_id = 1; /* mark success so we never try again */
1416 #if defined(__linux__) && defined(HAVE_SYS_PRCTL_H) && defined(HAVE_PRCTL)
1417 #ifdef PR_SET_DUMPABLE
1418 if (pw->pw_uid) {
1419 /* Re-enable core dumps if we're not running as root. */
1420 log_info(LD_CONFIG, "Re-enabling coredumps");
1421 if (prctl(PR_SET_DUMPABLE, 1)) {
1422 log_warn(LD_CONFIG, "Unable to re-enable coredumps: %s",strerror(errno));
1425 #endif
1426 #endif
1427 return 0;
1429 #else
1430 (void)user;
1432 log_warn(LD_CONFIG,
1433 "User specified but switching users is unsupported on your OS.");
1434 return -1;
1435 #endif
1438 #ifdef HAVE_PWD_H
1439 /** Allocate and return a string containing the home directory for the
1440 * user <b>username</b>. Only works on posix-like systems. */
1441 char *
1442 get_user_homedir(const char *username)
1444 struct passwd *pw;
1445 tor_assert(username);
1447 if (!(pw = getpwnam(username))) {
1448 log_err(LD_CONFIG,"User \"%s\" not found.", username);
1449 return NULL;
1451 return tor_strdup(pw->pw_dir);
1453 #endif
1455 /** Set *addr to the IP address (in dotted-quad notation) stored in c.
1456 * Return 1 on success, 0 if c is badly formatted. (Like inet_aton(c,addr),
1457 * but works on Windows and Solaris.)
1460 tor_inet_aton(const char *str, struct in_addr* addr)
1462 unsigned a,b,c,d;
1463 char more;
1464 if (tor_sscanf(str, "%3u.%3u.%3u.%3u%c", &a,&b,&c,&d,&more) != 4)
1465 return 0;
1466 if (a > 255) return 0;
1467 if (b > 255) return 0;
1468 if (c > 255) return 0;
1469 if (d > 255) return 0;
1470 addr->s_addr = htonl((a<<24) | (b<<16) | (c<<8) | d);
1471 return 1;
1474 /** Given <b>af</b>==AF_INET and <b>src</b> a struct in_addr, or
1475 * <b>af</b>==AF_INET6 and <b>src</b> a struct in6_addr, try to format the
1476 * address and store it in the <b>len</b>-byte buffer <b>dst</b>. Returns
1477 * <b>dst</b> on success, NULL on failure.
1479 * (Like inet_ntop(af,src,dst,len), but works on platforms that don't have it:
1480 * Tor sometimes needs to format ipv6 addresses even on platforms without ipv6
1481 * support.) */
1482 const char *
1483 tor_inet_ntop(int af, const void *src, char *dst, size_t len)
1485 if (af == AF_INET) {
1486 if (tor_inet_ntoa(src, dst, len) < 0)
1487 return NULL;
1488 else
1489 return dst;
1490 } else if (af == AF_INET6) {
1491 const struct in6_addr *addr = src;
1492 char buf[64], *cp;
1493 int longestGapLen = 0, longestGapPos = -1, i,
1494 curGapPos = -1, curGapLen = 0;
1495 uint16_t words[8];
1496 for (i = 0; i < 8; ++i) {
1497 words[i] = (((uint16_t)addr->s6_addr[2*i])<<8) + addr->s6_addr[2*i+1];
1499 if (words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0 &&
1500 words[4] == 0 && ((words[5] == 0 && words[6] && words[7]) ||
1501 (words[5] == 0xffff))) {
1502 /* This is an IPv4 address. */
1503 if (words[5] == 0) {
1504 tor_snprintf(buf, sizeof(buf), "::%d.%d.%d.%d",
1505 addr->s6_addr[12], addr->s6_addr[13],
1506 addr->s6_addr[14], addr->s6_addr[15]);
1507 } else {
1508 tor_snprintf(buf, sizeof(buf), "::%x:%d.%d.%d.%d", words[5],
1509 addr->s6_addr[12], addr->s6_addr[13],
1510 addr->s6_addr[14], addr->s6_addr[15]);
1512 if (strlen(buf) > len)
1513 return NULL;
1514 strlcpy(dst, buf, len);
1515 return dst;
1517 i = 0;
1518 while (i < 8) {
1519 if (words[i] == 0) {
1520 curGapPos = i++;
1521 curGapLen = 1;
1522 while (i<8 && words[i] == 0) {
1523 ++i; ++curGapLen;
1525 if (curGapLen > longestGapLen) {
1526 longestGapPos = curGapPos;
1527 longestGapLen = curGapLen;
1529 } else {
1530 ++i;
1533 if (longestGapLen<=1)
1534 longestGapPos = -1;
1536 cp = buf;
1537 for (i = 0; i < 8; ++i) {
1538 if (words[i] == 0 && longestGapPos == i) {
1539 if (i == 0)
1540 *cp++ = ':';
1541 *cp++ = ':';
1542 while (i < 8 && words[i] == 0)
1543 ++i;
1544 --i; /* to compensate for loop increment. */
1545 } else {
1546 tor_snprintf(cp, sizeof(buf)-(cp-buf), "%x", (unsigned)words[i]);
1547 cp += strlen(cp);
1548 if (i != 7)
1549 *cp++ = ':';
1552 *cp = '\0';
1553 if (strlen(buf) > len)
1554 return NULL;
1555 strlcpy(dst, buf, len);
1556 return dst;
1557 } else {
1558 return NULL;
1562 /** Given <b>af</b>==AF_INET or <b>af</b>==AF_INET6, and a string <b>src</b>
1563 * encoding an IPv4 address or IPv6 address correspondingly, try to parse the
1564 * address and store the result in <b>dst</b> (which must have space for a
1565 * struct in_addr or a struct in6_addr, as appropriate). Return 1 on success,
1566 * 0 on a bad parse, and -1 on a bad <b>af</b>.
1568 * (Like inet_pton(af,src,dst) but works on platforms that don't have it: Tor
1569 * sometimes needs to format ipv6 addresses even on platforms without ipv6
1570 * support.) */
1572 tor_inet_pton(int af, const char *src, void *dst)
1574 if (af == AF_INET) {
1575 return tor_inet_aton(src, dst);
1576 } else if (af == AF_INET6) {
1577 struct in6_addr *out = dst;
1578 uint16_t words[8];
1579 int gapPos = -1, i, setWords=0;
1580 const char *dot = strchr(src, '.');
1581 const char *eow; /* end of words. */
1582 if (dot == src)
1583 return 0;
1584 else if (!dot)
1585 eow = src+strlen(src);
1586 else {
1587 unsigned byte1,byte2,byte3,byte4;
1588 char more;
1589 for (eow = dot-1; eow >= src && TOR_ISDIGIT(*eow); --eow)
1591 ++eow;
1593 /* We use "scanf" because some platform inet_aton()s are too lax
1594 * about IPv4 addresses of the form "1.2.3" */
1595 if (tor_sscanf(eow, "%3u.%3u.%3u.%3u%c",
1596 &byte1,&byte2,&byte3,&byte4,&more) != 4)
1597 return 0;
1599 if (byte1 > 255 || byte2 > 255 || byte3 > 255 || byte4 > 255)
1600 return 0;
1602 words[6] = (byte1<<8) | byte2;
1603 words[7] = (byte3<<8) | byte4;
1604 setWords += 2;
1607 i = 0;
1608 while (src < eow) {
1609 if (i > 7)
1610 return 0;
1611 if (TOR_ISXDIGIT(*src)) {
1612 char *next;
1613 long r = strtol(src, &next, 16);
1614 if (next > 4+src)
1615 return 0;
1616 if (next == src)
1617 return 0;
1618 if (r<0 || r>65536)
1619 return 0;
1621 words[i++] = (uint16_t)r;
1622 setWords++;
1623 src = next;
1624 if (*src != ':' && src != eow)
1625 return 0;
1626 ++src;
1627 } else if (*src == ':' && i > 0 && gapPos==-1) {
1628 gapPos = i;
1629 ++src;
1630 } else if (*src == ':' && i == 0 && src[1] == ':' && gapPos==-1) {
1631 gapPos = i;
1632 src += 2;
1633 } else {
1634 return 0;
1638 if (setWords > 8 ||
1639 (setWords == 8 && gapPos != -1) ||
1640 (setWords < 8 && gapPos == -1))
1641 return 0;
1643 if (gapPos >= 0) {
1644 int nToMove = setWords - (dot ? 2 : 0) - gapPos;
1645 int gapLen = 8 - setWords;
1646 tor_assert(nToMove >= 0);
1647 memmove(&words[gapPos+gapLen], &words[gapPos],
1648 sizeof(uint16_t)*nToMove);
1649 memset(&words[gapPos], 0, sizeof(uint16_t)*gapLen);
1651 for (i = 0; i < 8; ++i) {
1652 out->s6_addr[2*i ] = words[i] >> 8;
1653 out->s6_addr[2*i+1] = words[i] & 0xff;
1656 return 1;
1657 } else {
1658 return -1;
1662 /** Similar behavior to Unix gethostbyname: resolve <b>name</b>, and set
1663 * *<b>addr</b> to the proper IP address, in host byte order. Returns 0
1664 * on success, -1 on failure; 1 on transient failure.
1666 * (This function exists because standard windows gethostbyname
1667 * doesn't treat raw IP addresses properly.)
1670 tor_lookup_hostname(const char *name, uint32_t *addr)
1672 tor_addr_t myaddr;
1673 int ret;
1675 if ((ret = tor_addr_lookup(name, AF_INET, &myaddr)))
1676 return ret;
1678 if (tor_addr_family(&myaddr) == AF_INET) {
1679 *addr = tor_addr_to_ipv4h(&myaddr);
1680 return ret;
1683 return -1;
1686 /** Initialize the insecure libc RNG. */
1687 void
1688 tor_init_weak_random(unsigned seed)
1690 #ifdef MS_WINDOWS
1691 srand(seed);
1692 #else
1693 srandom(seed);
1694 #endif
1697 /** Return a randomly chosen value in the range 0..TOR_RAND_MAX. This
1698 * entropy will not be cryptographically strong; do not rely on it
1699 * for anything an adversary should not be able to predict. */
1700 long
1701 tor_weak_random(void)
1703 #ifdef MS_WINDOWS
1704 return rand();
1705 #else
1706 return random();
1707 #endif
1710 /** Hold the result of our call to <b>uname</b>. */
1711 static char uname_result[256];
1712 /** True iff uname_result is set. */
1713 static int uname_result_is_set = 0;
1715 /** Return a pointer to a description of our platform.
1717 const char *
1718 get_uname(void)
1720 #ifdef HAVE_UNAME
1721 struct utsname u;
1722 #endif
1723 if (!uname_result_is_set) {
1724 #ifdef HAVE_UNAME
1725 if (uname(&u) != -1) {
1726 /* (Linux says 0 is success, Solaris says 1 is success) */
1727 tor_snprintf(uname_result, sizeof(uname_result), "%s %s",
1728 u.sysname, u.machine);
1729 } else
1730 #endif
1732 #ifdef MS_WINDOWS
1733 OSVERSIONINFOEX info;
1734 int i;
1735 const char *plat = NULL;
1736 const char *extra = NULL;
1737 char acsd[MAX_PATH] = {0};
1738 static struct {
1739 unsigned major; unsigned minor; const char *version;
1740 } win_version_table[] = {
1741 { 6, 1, "Windows 7" },
1742 { 6, 0, "Windows Vista" },
1743 { 5, 2, "Windows Server 2003" },
1744 { 5, 1, "Windows XP" },
1745 { 5, 0, "Windows 2000" },
1746 /* { 4, 0, "Windows NT 4.0" }, */
1747 { 4, 90, "Windows Me" },
1748 { 4, 10, "Windows 98" },
1749 /* { 4, 0, "Windows 95" } */
1750 { 3, 51, "Windows NT 3.51" },
1751 { 0, 0, NULL }
1753 memset(&info, 0, sizeof(info));
1754 info.dwOSVersionInfoSize = sizeof(info);
1755 if (! GetVersionEx((LPOSVERSIONINFO)&info)) {
1756 strlcpy(uname_result, "Bizarre version of Windows where GetVersionEx"
1757 " doesn't work.", sizeof(uname_result));
1758 uname_result_is_set = 1;
1759 return uname_result;
1761 #ifdef UNICODE
1762 wcstombs(acsd, info.szCSDVersion, MAX_PATH);
1763 #else
1764 strlcpy(acsd, info.szCSDVersion, sizeof(acsd));
1765 #endif
1766 if (info.dwMajorVersion == 4 && info.dwMinorVersion == 0) {
1767 if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
1768 plat = "Windows NT 4.0";
1769 else
1770 plat = "Windows 95";
1771 if (acsd[1] == 'B')
1772 extra = "OSR2 (B)";
1773 else if (acsd[1] == 'C')
1774 extra = "OSR2 (C)";
1775 } else {
1776 for (i=0; win_version_table[i].major>0; ++i) {
1777 if (win_version_table[i].major == info.dwMajorVersion &&
1778 win_version_table[i].minor == info.dwMinorVersion) {
1779 plat = win_version_table[i].version;
1780 break;
1784 if (plat && !strcmp(plat, "Windows 98")) {
1785 if (acsd[1] == 'A')
1786 extra = "SE (A)";
1787 else if (acsd[1] == 'B')
1788 extra = "SE (B)";
1790 if (plat) {
1791 if (!extra)
1792 extra = acsd;
1793 tor_snprintf(uname_result, sizeof(uname_result), "%s %s",
1794 plat, extra);
1795 } else {
1796 if (info.dwMajorVersion > 6 ||
1797 (info.dwMajorVersion==6 && info.dwMinorVersion>1))
1798 tor_snprintf(uname_result, sizeof(uname_result),
1799 "Very recent version of Windows [major=%d,minor=%d] %s",
1800 (int)info.dwMajorVersion,(int)info.dwMinorVersion,
1801 acsd);
1802 else
1803 tor_snprintf(uname_result, sizeof(uname_result),
1804 "Unrecognized version of Windows [major=%d,minor=%d] %s",
1805 (int)info.dwMajorVersion,(int)info.dwMinorVersion,
1806 acsd);
1808 #if !defined (WINCE)
1809 #ifdef VER_SUITE_BACKOFFICE
1810 if (info.wProductType == VER_NT_DOMAIN_CONTROLLER) {
1811 strlcat(uname_result, " [domain controller]", sizeof(uname_result));
1812 } else if (info.wProductType == VER_NT_SERVER) {
1813 strlcat(uname_result, " [server]", sizeof(uname_result));
1814 } else if (info.wProductType == VER_NT_WORKSTATION) {
1815 strlcat(uname_result, " [workstation]", sizeof(uname_result));
1817 #endif
1818 #endif
1819 #else
1820 strlcpy(uname_result, "Unknown platform", sizeof(uname_result));
1821 #endif
1823 uname_result_is_set = 1;
1825 return uname_result;
1829 * Process control
1832 #if defined(USE_PTHREADS)
1833 /** Wraps a void (*)(void*) function and its argument so we can
1834 * invoke them in a way pthreads would expect.
1836 typedef struct tor_pthread_data_t {
1837 void (*func)(void *);
1838 void *data;
1839 } tor_pthread_data_t;
1840 /** Given a tor_pthread_data_t <b>_data</b>, call _data-&gt;func(d-&gt;data)
1841 * and free _data. Used to make sure we can call functions the way pthread
1842 * expects. */
1843 static void *
1844 tor_pthread_helper_fn(void *_data)
1846 tor_pthread_data_t *data = _data;
1847 void (*func)(void*);
1848 void *arg;
1849 /* mask signals to worker threads to avoid SIGPIPE, etc */
1850 sigset_t sigs;
1851 /* We're in a subthread; don't handle any signals here. */
1852 sigfillset(&sigs);
1853 pthread_sigmask(SIG_SETMASK, &sigs, NULL);
1855 func = data->func;
1856 arg = data->data;
1857 tor_free(_data);
1858 func(arg);
1859 return NULL;
1861 #endif
1863 /** Minimalist interface to run a void function in the background. On
1864 * Unix calls fork, on win32 calls beginthread. Returns -1 on failure.
1865 * func should not return, but rather should call spawn_exit.
1867 * NOTE: if <b>data</b> is used, it should not be allocated on the stack,
1868 * since in a multithreaded environment, there is no way to be sure that
1869 * the caller's stack will still be around when the called function is
1870 * running.
1873 spawn_func(void (*func)(void *), void *data)
1875 #if defined(USE_WIN32_THREADS)
1876 int rv;
1877 rv = (int)_beginthread(func, 0, data);
1878 if (rv == (int)-1)
1879 return -1;
1880 return 0;
1881 #elif defined(USE_PTHREADS)
1882 pthread_t thread;
1883 tor_pthread_data_t *d;
1884 d = tor_malloc(sizeof(tor_pthread_data_t));
1885 d->data = data;
1886 d->func = func;
1887 if (pthread_create(&thread,NULL,tor_pthread_helper_fn,d))
1888 return -1;
1889 if (pthread_detach(thread))
1890 return -1;
1891 return 0;
1892 #else
1893 pid_t pid;
1894 pid = fork();
1895 if (pid<0)
1896 return -1;
1897 if (pid==0) {
1898 /* Child */
1899 func(data);
1900 tor_assert(0); /* Should never reach here. */
1901 return 0; /* suppress "control-reaches-end-of-non-void" warning. */
1902 } else {
1903 /* Parent */
1904 return 0;
1906 #endif
1909 /** End the current thread/process.
1911 void
1912 spawn_exit(void)
1914 #if defined(USE_WIN32_THREADS)
1915 _endthread();
1916 //we should never get here. my compiler thinks that _endthread returns, this
1917 //is an attempt to fool it.
1918 tor_assert(0);
1919 _exit(0);
1920 #elif defined(USE_PTHREADS)
1921 pthread_exit(NULL);
1922 #else
1923 /* http://www.erlenstar.demon.co.uk/unix/faq_2.html says we should
1924 * call _exit, not exit, from child processes. */
1925 _exit(0);
1926 #endif
1929 /** Set *timeval to the current time of day. On error, log and terminate.
1930 * (Same as gettimeofday(timeval,NULL), but never returns -1.)
1932 void
1933 tor_gettimeofday(struct timeval *timeval)
1935 #ifdef MS_WINDOWS
1936 /* Epoch bias copied from perl: number of units between windows epoch and
1937 * Unix epoch. */
1938 #define EPOCH_BIAS U64_LITERAL(116444736000000000)
1939 #define UNITS_PER_SEC U64_LITERAL(10000000)
1940 #define USEC_PER_SEC U64_LITERAL(1000000)
1941 #define UNITS_PER_USEC U64_LITERAL(10)
1942 union {
1943 uint64_t ft_64;
1944 FILETIME ft_ft;
1945 } ft;
1946 #if defined (WINCE)
1947 /* wince do not have GetSystemTimeAsFileTime */
1948 SYSTEMTIME stime;
1949 GetSystemTime(&stime);
1950 SystemTimeToFileTime(&stime,&ft.ft_ft);
1951 #else
1952 /* number of 100-nsec units since Jan 1, 1601 */
1953 GetSystemTimeAsFileTime(&ft.ft_ft);
1954 #endif
1955 if (ft.ft_64 < EPOCH_BIAS) {
1956 log_err(LD_GENERAL,"System time is before 1970; failing.");
1957 exit(1);
1959 ft.ft_64 -= EPOCH_BIAS;
1960 timeval->tv_sec = (unsigned) (ft.ft_64 / UNITS_PER_SEC);
1961 timeval->tv_usec = (unsigned) ((ft.ft_64 / UNITS_PER_USEC) % USEC_PER_SEC);
1962 #elif defined(HAVE_GETTIMEOFDAY)
1963 if (gettimeofday(timeval, NULL)) {
1964 log_err(LD_GENERAL,"gettimeofday failed.");
1965 /* If gettimeofday dies, we have either given a bad timezone (we didn't),
1966 or segfaulted.*/
1967 exit(1);
1969 #elif defined(HAVE_FTIME)
1970 struct timeb tb;
1971 ftime(&tb);
1972 timeval->tv_sec = tb.time;
1973 timeval->tv_usec = tb.millitm * 1000;
1974 #else
1975 #error "No way to get time."
1976 #endif
1977 return;
1980 #if defined(TOR_IS_MULTITHREADED) && !defined(MS_WINDOWS)
1981 /** Defined iff we need to add locks when defining fake versions of reentrant
1982 * versions of time-related functions. */
1983 #define TIME_FNS_NEED_LOCKS
1984 #endif
1986 #ifndef HAVE_LOCALTIME_R
1987 #ifdef TIME_FNS_NEED_LOCKS
1988 struct tm *
1989 tor_localtime_r(const time_t *timep, struct tm *result)
1991 struct tm *r;
1992 static tor_mutex_t *m=NULL;
1993 if (!m) { m=tor_mutex_new(); }
1994 tor_assert(result);
1995 tor_mutex_acquire(m);
1996 r = localtime(timep);
1997 memcpy(result, r, sizeof(struct tm));
1998 tor_mutex_release(m);
1999 return result;
2001 #else
2002 struct tm *
2003 tor_localtime_r(const time_t *timep, struct tm *result)
2005 struct tm *r;
2006 tor_assert(result);
2007 r = localtime(timep);
2008 memcpy(result, r, sizeof(struct tm));
2009 return result;
2011 #endif
2012 #endif
2014 #ifndef HAVE_GMTIME_R
2015 #ifdef TIME_FNS_NEED_LOCKS
2016 struct tm *
2017 tor_gmtime_r(const time_t *timep, struct tm *result)
2019 struct tm *r;
2020 static tor_mutex_t *m=NULL;
2021 if (!m) { m=tor_mutex_new(); }
2022 tor_assert(result);
2023 tor_mutex_acquire(m);
2024 r = gmtime(timep);
2025 memcpy(result, r, sizeof(struct tm));
2026 tor_mutex_release(m);
2027 return result;
2029 #else
2030 struct tm *
2031 tor_gmtime_r(const time_t *timep, struct tm *result)
2033 struct tm *r;
2034 tor_assert(result);
2035 r = gmtime(timep);
2036 memcpy(result, r, sizeof(struct tm));
2037 return result;
2039 #endif
2040 #endif
2042 #if defined(USE_WIN32_THREADS)
2043 void
2044 tor_mutex_init(tor_mutex_t *m)
2046 InitializeCriticalSection(&m->mutex);
2048 void
2049 tor_mutex_uninit(tor_mutex_t *m)
2051 DeleteCriticalSection(&m->mutex);
2053 void
2054 tor_mutex_acquire(tor_mutex_t *m)
2056 tor_assert(m);
2057 EnterCriticalSection(&m->mutex);
2059 void
2060 tor_mutex_release(tor_mutex_t *m)
2062 LeaveCriticalSection(&m->mutex);
2064 unsigned long
2065 tor_get_thread_id(void)
2067 return (unsigned long)GetCurrentThreadId();
2069 #elif defined(USE_PTHREADS)
2070 /** A mutex attribute that we're going to use to tell pthreads that we want
2071 * "reentrant" mutexes (i.e., once we can re-lock if we're already holding
2072 * them.) */
2073 static pthread_mutexattr_t attr_reentrant;
2074 /** True iff we've called tor_threads_init() */
2075 static int threads_initialized = 0;
2076 /** Initialize <b>mutex</b> so it can be locked. Every mutex must be set
2077 * up with tor_mutex_init() or tor_mutex_new(); not both. */
2078 void
2079 tor_mutex_init(tor_mutex_t *mutex)
2081 int err;
2082 if (PREDICT_UNLIKELY(!threads_initialized))
2083 tor_threads_init();
2084 err = pthread_mutex_init(&mutex->mutex, &attr_reentrant);
2085 if (PREDICT_UNLIKELY(err)) {
2086 log_err(LD_GENERAL, "Error %d creating a mutex.", err);
2087 tor_fragile_assert();
2090 /** Wait until <b>m</b> is free, then acquire it. */
2091 void
2092 tor_mutex_acquire(tor_mutex_t *m)
2094 int err;
2095 tor_assert(m);
2096 err = pthread_mutex_lock(&m->mutex);
2097 if (PREDICT_UNLIKELY(err)) {
2098 log_err(LD_GENERAL, "Error %d locking a mutex.", err);
2099 tor_fragile_assert();
2102 /** Release the lock <b>m</b> so another thread can have it. */
2103 void
2104 tor_mutex_release(tor_mutex_t *m)
2106 int err;
2107 tor_assert(m);
2108 err = pthread_mutex_unlock(&m->mutex);
2109 if (PREDICT_UNLIKELY(err)) {
2110 log_err(LD_GENERAL, "Error %d unlocking a mutex.", err);
2111 tor_fragile_assert();
2114 /** Clean up the mutex <b>m</b> so that it no longer uses any system
2115 * resources. Does not free <b>m</b>. This function must only be called on
2116 * mutexes from tor_mutex_init(). */
2117 void
2118 tor_mutex_uninit(tor_mutex_t *m)
2120 int err;
2121 tor_assert(m);
2122 err = pthread_mutex_destroy(&m->mutex);
2123 if (PREDICT_UNLIKELY(err)) {
2124 log_err(LD_GENERAL, "Error %d destroying a mutex.", err);
2125 tor_fragile_assert();
2128 /** Return an integer representing this thread. */
2129 unsigned long
2130 tor_get_thread_id(void)
2132 union {
2133 pthread_t thr;
2134 unsigned long id;
2135 } r;
2136 r.thr = pthread_self();
2137 return r.id;
2139 #endif
2141 #ifdef TOR_IS_MULTITHREADED
2142 /** Return a newly allocated, ready-for-use mutex. */
2143 tor_mutex_t *
2144 tor_mutex_new(void)
2146 tor_mutex_t *m = tor_malloc_zero(sizeof(tor_mutex_t));
2147 tor_mutex_init(m);
2148 return m;
2150 /** Release all storage and system resources held by <b>m</b>. */
2151 void
2152 tor_mutex_free(tor_mutex_t *m)
2154 if (!m)
2155 return;
2156 tor_mutex_uninit(m);
2157 tor_free(m);
2159 #endif
2161 /* Conditions. */
2162 #ifdef USE_PTHREADS
2163 #if 0
2164 /** Cross-platform condition implementation. */
2165 struct tor_cond_t {
2166 pthread_cond_t cond;
2168 /** Return a newly allocated condition, with nobody waiting on it. */
2169 tor_cond_t *
2170 tor_cond_new(void)
2172 tor_cond_t *cond = tor_malloc_zero(sizeof(tor_cond_t));
2173 if (pthread_cond_init(&cond->cond, NULL)) {
2174 tor_free(cond);
2175 return NULL;
2177 return cond;
2179 /** Release all resources held by <b>cond</b>. */
2180 void
2181 tor_cond_free(tor_cond_t *cond)
2183 if (!cond)
2184 return;
2185 if (pthread_cond_destroy(&cond->cond)) {
2186 log_warn(LD_GENERAL,"Error freeing condition: %s", strerror(errno));
2187 return;
2189 tor_free(cond);
2191 /** Wait until one of the tor_cond_signal functions is called on <b>cond</b>.
2192 * All waiters on the condition must wait holding the same <b>mutex</b>.
2193 * Returns 0 on success, negative on failure. */
2195 tor_cond_wait(tor_cond_t *cond, tor_mutex_t *mutex)
2197 return pthread_cond_wait(&cond->cond, &mutex->mutex) ? -1 : 0;
2199 /** Wake up one of the waiters on <b>cond</b>. */
2200 void
2201 tor_cond_signal_one(tor_cond_t *cond)
2203 pthread_cond_signal(&cond->cond);
2205 /** Wake up all of the waiters on <b>cond</b>. */
2206 void
2207 tor_cond_signal_all(tor_cond_t *cond)
2209 pthread_cond_broadcast(&cond->cond);
2211 #endif
2212 /** Set up common structures for use by threading. */
2213 void
2214 tor_threads_init(void)
2216 if (!threads_initialized) {
2217 pthread_mutexattr_init(&attr_reentrant);
2218 pthread_mutexattr_settype(&attr_reentrant, PTHREAD_MUTEX_RECURSIVE);
2219 threads_initialized = 1;
2220 set_main_thread();
2223 #elif defined(USE_WIN32_THREADS)
2224 #if 0
2225 static DWORD cond_event_tls_index;
2226 struct tor_cond_t {
2227 CRITICAL_SECTION mutex;
2228 smartlist_t *events;
2230 tor_cond_t *
2231 tor_cond_new(void)
2233 tor_cond_t *cond = tor_malloc_zero(sizeof(tor_cond_t));
2234 InitializeCriticalSection(&cond->mutex);
2235 cond->events = smartlist_create();
2236 return cond;
2238 void
2239 tor_cond_free(tor_cond_t *cond)
2241 if (!cond)
2242 return;
2243 DeleteCriticalSection(&cond->mutex);
2244 /* XXXX notify? */
2245 smartlist_free(cond->events);
2246 tor_free(cond);
2249 tor_cond_wait(tor_cond_t *cond, tor_mutex_t *mutex)
2251 HANDLE event;
2252 int r;
2253 tor_assert(cond);
2254 tor_assert(mutex);
2255 event = TlsGetValue(cond_event_tls_index);
2256 if (!event) {
2257 event = CreateEvent(0, FALSE, FALSE, NULL);
2258 TlsSetValue(cond_event_tls_index, event);
2260 EnterCriticalSection(&cond->mutex);
2262 tor_assert(WaitForSingleObject(event, 0) == WAIT_TIMEOUT);
2263 tor_assert(!smartlist_isin(cond->events, event));
2264 smartlist_add(cond->events, event);
2266 LeaveCriticalSection(&cond->mutex);
2268 tor_mutex_release(mutex);
2269 r = WaitForSingleObject(event, INFINITE);
2270 tor_mutex_acquire(mutex);
2272 switch (r) {
2273 case WAIT_OBJECT_0: /* we got the mutex normally. */
2274 break;
2275 case WAIT_ABANDONED: /* holding thread exited. */
2276 case WAIT_TIMEOUT: /* Should never happen. */
2277 tor_assert(0);
2278 break;
2279 case WAIT_FAILED:
2280 log_warn(LD_GENERAL, "Failed to acquire mutex: %d",(int) GetLastError());
2282 return 0;
2284 void
2285 tor_cond_signal_one(tor_cond_t *cond)
2287 HANDLE event;
2288 tor_assert(cond);
2290 EnterCriticalSection(&cond->mutex);
2292 if ((event = smartlist_pop_last(cond->events)))
2293 SetEvent(event);
2295 LeaveCriticalSection(&cond->mutex);
2297 void
2298 tor_cond_signal_all(tor_cond_t *cond)
2300 tor_assert(cond);
2302 EnterCriticalSection(&cond->mutex);
2303 SMARTLIST_FOREACH(cond->events, HANDLE, event, SetEvent(event));
2304 smartlist_clear(cond->events);
2305 LeaveCriticalSection(&cond->mutex);
2307 #endif
2308 void
2309 tor_threads_init(void)
2311 #if 0
2312 cond_event_tls_index = TlsAlloc();
2313 #endif
2314 set_main_thread();
2316 #endif
2318 #if defined(HAVE_MLOCKALL) && HAVE_DECL_MLOCKALL && defined(RLIMIT_MEMLOCK)
2319 /** Attempt to raise the current and max rlimit to infinity for our process.
2320 * This only needs to be done once and can probably only be done when we have
2321 * not already dropped privileges.
2323 static int
2324 tor_set_max_memlock(void)
2326 /* Future consideration for Windows is probably SetProcessWorkingSetSize
2327 * This is similar to setting the memory rlimit of RLIMIT_MEMLOCK
2328 * http://msdn.microsoft.com/en-us/library/ms686234(VS.85).aspx
2331 struct rlimit limit;
2333 /* RLIM_INFINITY is -1 on some platforms. */
2334 limit.rlim_cur = RLIM_INFINITY;
2335 limit.rlim_max = RLIM_INFINITY;
2337 if (setrlimit(RLIMIT_MEMLOCK, &limit) == -1) {
2338 if (errno == EPERM) {
2339 log_warn(LD_GENERAL, "You appear to lack permissions to change memory "
2340 "limits. Are you root?");
2342 log_warn(LD_GENERAL, "Unable to raise RLIMIT_MEMLOCK: %s",
2343 strerror(errno));
2344 return -1;
2347 return 0;
2349 #endif
2351 /** Attempt to lock all current and all future memory pages.
2352 * This should only be called once and while we're privileged.
2353 * Like mlockall() we return 0 when we're successful and -1 when we're not.
2354 * Unlike mlockall() we return 1 if we've already attempted to lock memory.
2357 tor_mlockall(void)
2359 static int memory_lock_attempted = 0;
2361 if (memory_lock_attempted) {
2362 return 1;
2365 memory_lock_attempted = 1;
2368 * Future consideration for Windows may be VirtualLock
2369 * VirtualLock appears to implement mlock() but not mlockall()
2371 * http://msdn.microsoft.com/en-us/library/aa366895(VS.85).aspx
2374 #if defined(HAVE_MLOCKALL) && HAVE_DECL_MLOCKALL && defined(RLIMIT_MEMLOCK)
2375 if (tor_set_max_memlock() == 0) {
2376 log_debug(LD_GENERAL, "RLIMIT_MEMLOCK is now set to RLIM_INFINITY.");
2379 if (mlockall(MCL_CURRENT|MCL_FUTURE) == 0) {
2380 log_info(LD_GENERAL, "Insecure OS paging is effectively disabled.");
2381 return 0;
2382 } else {
2383 if (errno == ENOSYS) {
2384 /* Apple - it's 2009! I'm looking at you. Grrr. */
2385 log_notice(LD_GENERAL, "It appears that mlockall() is not available on "
2386 "your platform.");
2387 } else if (errno == EPERM) {
2388 log_notice(LD_GENERAL, "It appears that you lack the permissions to "
2389 "lock memory. Are you root?");
2391 log_notice(LD_GENERAL, "Unable to lock all current and future memory "
2392 "pages: %s", strerror(errno));
2393 return -1;
2395 #else
2396 log_warn(LD_GENERAL, "Unable to lock memory pages. mlockall() unsupported?");
2397 return -1;
2398 #endif
2401 /** Identity of the "main" thread */
2402 static unsigned long main_thread_id = -1;
2404 /** Start considering the current thread to be the 'main thread'. This has
2405 * no effect on anything besides in_main_thread(). */
2406 void
2407 set_main_thread(void)
2409 main_thread_id = tor_get_thread_id();
2411 /** Return true iff called from the main thread. */
2413 in_main_thread(void)
2415 return main_thread_id == tor_get_thread_id();
2419 * On Windows, WSAEWOULDBLOCK is not always correct: when you see it,
2420 * you need to ask the socket for its actual errno. Also, you need to
2421 * get your errors from WSAGetLastError, not errno. (If you supply a
2422 * socket of -1, we check WSAGetLastError, but don't correct
2423 * WSAEWOULDBLOCKs.)
2425 * The upshot of all of this is that when a socket call fails, you
2426 * should call tor_socket_errno <em>at most once</em> on the failing
2427 * socket to get the error.
2429 #if defined(MS_WINDOWS)
2431 tor_socket_errno(int sock)
2433 int optval, optvallen=sizeof(optval);
2434 int err = WSAGetLastError();
2435 if (err == WSAEWOULDBLOCK && sock >= 0) {
2436 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval, &optvallen))
2437 return err;
2438 if (optval)
2439 return optval;
2441 return err;
2443 #endif
2445 #if defined(MS_WINDOWS)
2446 #define E(code, s) { code, (s " [" #code " ]") }
2447 struct { int code; const char *msg; } windows_socket_errors[] = {
2448 E(WSAEINTR, "Interrupted function call"),
2449 E(WSAEACCES, "Permission denied"),
2450 E(WSAEFAULT, "Bad address"),
2451 E(WSAEINVAL, "Invalid argument"),
2452 E(WSAEMFILE, "Too many open files"),
2453 E(WSAEWOULDBLOCK, "Resource temporarily unavailable"),
2454 E(WSAEINPROGRESS, "Operation now in progress"),
2455 E(WSAEALREADY, "Operation already in progress"),
2456 E(WSAENOTSOCK, "Socket operation on nonsocket"),
2457 E(WSAEDESTADDRREQ, "Destination address required"),
2458 E(WSAEMSGSIZE, "Message too long"),
2459 E(WSAEPROTOTYPE, "Protocol wrong for socket"),
2460 E(WSAENOPROTOOPT, "Bad protocol option"),
2461 E(WSAEPROTONOSUPPORT, "Protocol not supported"),
2462 E(WSAESOCKTNOSUPPORT, "Socket type not supported"),
2463 /* What's the difference between NOTSUPP and NOSUPPORT? :) */
2464 E(WSAEOPNOTSUPP, "Operation not supported"),
2465 E(WSAEPFNOSUPPORT, "Protocol family not supported"),
2466 E(WSAEAFNOSUPPORT, "Address family not supported by protocol family"),
2467 E(WSAEADDRINUSE, "Address already in use"),
2468 E(WSAEADDRNOTAVAIL, "Cannot assign requested address"),
2469 E(WSAENETDOWN, "Network is down"),
2470 E(WSAENETUNREACH, "Network is unreachable"),
2471 E(WSAENETRESET, "Network dropped connection on reset"),
2472 E(WSAECONNABORTED, "Software caused connection abort"),
2473 E(WSAECONNRESET, "Connection reset by peer"),
2474 E(WSAENOBUFS, "No buffer space available"),
2475 E(WSAEISCONN, "Socket is already connected"),
2476 E(WSAENOTCONN, "Socket is not connected"),
2477 E(WSAESHUTDOWN, "Cannot send after socket shutdown"),
2478 E(WSAETIMEDOUT, "Connection timed out"),
2479 E(WSAECONNREFUSED, "Connection refused"),
2480 E(WSAEHOSTDOWN, "Host is down"),
2481 E(WSAEHOSTUNREACH, "No route to host"),
2482 E(WSAEPROCLIM, "Too many processes"),
2483 /* Yes, some of these start with WSA, not WSAE. No, I don't know why. */
2484 E(WSASYSNOTREADY, "Network subsystem is unavailable"),
2485 E(WSAVERNOTSUPPORTED, "Winsock.dll out of range"),
2486 E(WSANOTINITIALISED, "Successful WSAStartup not yet performed"),
2487 E(WSAEDISCON, "Graceful shutdown now in progress"),
2488 #ifdef WSATYPE_NOT_FOUND
2489 E(WSATYPE_NOT_FOUND, "Class type not found"),
2490 #endif
2491 E(WSAHOST_NOT_FOUND, "Host not found"),
2492 E(WSATRY_AGAIN, "Nonauthoritative host not found"),
2493 E(WSANO_RECOVERY, "This is a nonrecoverable error"),
2494 E(WSANO_DATA, "Valid name, no data record of requested type)"),
2496 /* There are some more error codes whose numeric values are marked
2497 * <b>OS dependent</b>. They start with WSA_, apparently for the same
2498 * reason that practitioners of some craft traditions deliberately
2499 * introduce imperfections into their baskets and rugs "to allow the
2500 * evil spirits to escape." If we catch them, then our binaries
2501 * might not report consistent results across versions of Windows.
2502 * Thus, I'm going to let them all fall through.
2504 { -1, NULL },
2506 /** There does not seem to be a strerror equivalent for Winsock errors.
2507 * Naturally, we have to roll our own.
2509 const char *
2510 tor_socket_strerror(int e)
2512 int i;
2513 for (i=0; windows_socket_errors[i].code >= 0; ++i) {
2514 if (e == windows_socket_errors[i].code)
2515 return windows_socket_errors[i].msg;
2517 return strerror(e);
2519 #endif
2521 /** Called before we make any calls to network-related functions.
2522 * (Some operating systems require their network libraries to be
2523 * initialized.) */
2525 network_init(void)
2527 #ifdef MS_WINDOWS
2528 /* This silly exercise is necessary before windows will allow
2529 * gethostbyname to work. */
2530 WSADATA WSAData;
2531 int r;
2532 r = WSAStartup(0x101,&WSAData);
2533 if (r) {
2534 log_warn(LD_NET,"Error initializing windows network layer: code was %d",r);
2535 return -1;
2537 /* WSAData.iMaxSockets might show the max sockets we're allowed to use.
2538 * We might use it to complain if we're trying to be a server but have
2539 * too few sockets available. */
2540 #endif
2541 return 0;
2544 #ifdef MS_WINDOWS
2545 /** Return a newly allocated string describing the windows system error code
2546 * <b>err</b>. Note that error codes are different from errno. Error codes
2547 * come from GetLastError() when a winapi call fails. errno is set only when
2548 * ANSI functions fail. Whee. */
2549 char *
2550 format_win32_error(DWORD err)
2552 TCHAR *str = NULL;
2553 char *result;
2555 /* Somebody once decided that this interface was better than strerror(). */
2556 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
2557 FORMAT_MESSAGE_FROM_SYSTEM |
2558 FORMAT_MESSAGE_IGNORE_INSERTS,
2559 NULL, err,
2560 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
2561 (LPVOID)&str,
2562 0, NULL);
2564 if (str) {
2565 #ifdef UNICODE
2566 char abuf[1024] = {0};
2567 wcstombs(abuf,str,1024);
2568 result = tor_strdup(abuf);
2569 #else
2570 result = tor_strdup(str);
2571 #endif
2572 LocalFree(str); /* LocalFree != free() */
2573 } else {
2574 result = tor_strdup("<unformattable error>");
2576 return result;
2578 #endif