Port Tor to work on Windows CE
[tor/rransom.git] / src / common / compat.c
blobf93a1619cec5c352cc99244ea9e0071797da2c26
1 /* Copyright (c) 2003-2004, Roger Dingledine
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2010, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
6 /**
7 * \file compat.c
8 * \brief Wrappers to make calls more portable. This code defines
9 * functions such as tor_malloc, tor_snprintf, get/set various data types,
10 * renaming, setting socket options, switching user IDs. It is basically
11 * where the non-portable items are conditionally included depending on
12 * the platform.
13 **/
15 /* This is required on rh7 to make strptime not complain.
16 * We also need it to make memmem get defined (where available)
18 #define _GNU_SOURCE
20 #include "compat.h"
22 #ifdef MS_WINDOWS
23 #include <process.h>
24 #include <windows.h>
25 #if !defined (WINCE)
26 #include <sys/locking.h>
27 #endif
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 #ifdef HAVE_NETDB_H
62 #include <netdb.h>
63 #endif
64 #ifdef HAVE_SYS_PARAM_H
65 #include <sys/param.h> /* FreeBSD needs this to know what version it is */
66 #endif
67 #include <stdio.h>
68 #include <stdlib.h>
69 #include <assert.h>
70 #ifdef HAVE_SIGNAL_H
71 #include <signal.h>
72 #endif
73 #ifdef HAVE_UTIME_H
74 #include <utime.h>
75 #endif
76 #ifdef HAVE_SYS_UTIME_H
77 #include <sys/utime.h>
78 #endif
79 #ifdef HAVE_SYS_MMAN_H
80 #include <sys/mman.h>
81 #endif
82 #ifdef HAVE_SYS_SYSLIMITS_H
83 #include <sys/syslimits.h>
84 #endif
85 #ifdef HAVE_SYS_FILE_H
86 #include <sys/file.h>
87 #endif
88 #if defined(HAVE_SYS_PRCTL_H) && defined(__linux__)
89 /* Only use the linux prctl; the IRIX prctl is totally different */
90 #include <sys/prctl.h>
91 #endif
93 #include "log.h"
94 #include "util.h"
95 #include "container.h"
96 #include "address.h"
98 /* Inline the strl functions if the platform doesn't have them. */
99 #ifndef HAVE_STRLCPY
100 #include "strlcpy.c"
101 #endif
102 #ifndef HAVE_STRLCAT
103 #include "strlcat.c"
104 #endif
106 #ifdef HAVE_SYS_MMAN_H
107 /** Try to create a memory mapping for <b>filename</b> and return it. On
108 * failure, return NULL. Sets errno properly, using ERANGE to mean
109 * "empty file". */
110 tor_mmap_t *
111 tor_mmap_file(const char *filename)
113 int fd; /* router file */
114 char *string;
115 int page_size;
116 tor_mmap_t *res;
117 size_t size, filesize;
119 tor_assert(filename);
121 fd = open(filename, O_RDONLY, 0);
122 if (fd<0) {
123 int save_errno = errno;
124 int severity = (errno == ENOENT) ? LOG_INFO : LOG_WARN;
125 log_fn(severity, LD_FS,"Could not open \"%s\" for mmap(): %s",filename,
126 strerror(errno));
127 errno = save_errno;
128 return NULL;
131 size = filesize = (size_t) lseek(fd, 0, SEEK_END);
132 lseek(fd, 0, SEEK_SET);
133 /* ensure page alignment */
134 page_size = getpagesize();
135 size += (size%page_size) ? page_size-(size%page_size) : 0;
137 if (!size) {
138 /* Zero-length file. If we call mmap on it, it will succeed but
139 * return NULL, and bad things will happen. So just fail. */
140 log_info(LD_FS,"File \"%s\" is empty. Ignoring.",filename);
141 errno = ERANGE;
142 close(fd);
143 return NULL;
146 string = mmap(0, size, PROT_READ, MAP_PRIVATE, fd, 0);
147 close(fd);
148 if (string == MAP_FAILED) {
149 int save_errno = errno;
150 log_warn(LD_FS,"Could not mmap file \"%s\": %s", filename,
151 strerror(errno));
152 errno = save_errno;
153 return NULL;
156 res = tor_malloc_zero(sizeof(tor_mmap_t));
157 res->data = string;
158 res->size = filesize;
159 res->mapping_size = size;
161 return res;
163 /** Release storage held for a memory mapping. */
164 void
165 tor_munmap_file(tor_mmap_t *handle)
167 munmap((char*)handle->data, handle->mapping_size);
168 tor_free(handle);
170 #elif defined(MS_WINDOWS)
171 tor_mmap_t *
172 tor_mmap_file(const char *filename)
174 WCHAR wfilename[MAX_PATH]= {0};
175 tor_mmap_t *res = tor_malloc_zero(sizeof(tor_mmap_t));
176 int empty = 0;
177 res->file_handle = INVALID_HANDLE_VALUE;
178 res->mmap_handle = NULL;
179 mbstowcs(wfilename,filename,MAX_PATH);
180 res->file_handle = CreateFileW(wfilename,
181 GENERIC_READ, FILE_SHARE_READ,
182 NULL,
183 OPEN_EXISTING,
184 FILE_ATTRIBUTE_NORMAL,
187 if (res->file_handle == INVALID_HANDLE_VALUE)
188 goto win_err;
190 res->size = GetFileSize(res->file_handle, NULL);
192 if (res->size == 0) {
193 log_info(LD_FS,"File \"%s\" is empty. Ignoring.",filename);
194 empty = 1;
195 goto err;
198 res->mmap_handle = CreateFileMapping(res->file_handle,
199 NULL,
200 PAGE_READONLY,
201 #if SIZEOF_SIZE_T > 4
202 (res->base.size >> 32),
203 #else
205 #endif
206 (res->size & 0xfffffffful),
207 NULL);
208 if (res->mmap_handle == NULL)
209 goto win_err;
210 res->data = (char*) MapViewOfFile(res->mmap_handle,
211 FILE_MAP_READ,
212 0, 0, 0);
213 if (!res->data)
214 goto win_err;
216 return res;
217 win_err: {
218 DWORD e = GetLastError();
219 int severity = (e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND) ?
220 LOG_INFO : LOG_WARN;
221 char *msg = format_win32_error(e);
222 log_fn(severity, LD_FS, "Couldn't mmap file \"%s\": %s", filename, msg);
223 tor_free(msg);
224 if (e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND)
225 errno = ENOENT;
226 else
227 errno = EINVAL;
229 err:
230 if (empty)
231 errno = ERANGE;
232 tor_munmap_file(res);
233 return NULL;
235 void
236 tor_munmap_file(tor_mmap_t *handle)
238 if (handle->data)
239 /* This is an ugly cast, but without it, "data" in struct tor_mmap_t would
240 have to be redefined as non-const. */
241 UnmapViewOfFile( (LPVOID) handle->data);
243 if (handle->mmap_handle != NULL)
244 CloseHandle(handle->mmap_handle);
245 if (handle->file_handle != INVALID_HANDLE_VALUE)
246 CloseHandle(handle->file_handle);
247 tor_free(handle);
249 #else
250 tor_mmap_t *
251 tor_mmap_file(const char *filename)
253 struct stat st;
254 char *res = read_file_to_str(filename, RFTS_BIN|RFTS_IGNORE_MISSING, &st);
255 tor_mmap_t *handle;
256 if (! res)
257 return NULL;
258 handle = tor_malloc_zero(sizeof(tor_mmap_t));
259 handle->data = res;
260 handle->size = st.st_size;
261 return handle;
263 void
264 tor_munmap_file(tor_mmap_t *handle)
266 char *d = (char*)handle->data;
267 tor_free(d);
268 memset(handle, 0, sizeof(tor_mmap_t));
269 tor_free(handle);
271 #endif
273 /** Replacement for snprintf. Differs from platform snprintf in two
274 * ways: First, always NUL-terminates its output. Second, always
275 * returns -1 if the result is truncated. (Note that this return
276 * behavior does <i>not</i> conform to C99; it just happens to be
277 * easier to emulate "return -1" with conformant implementations than
278 * it is to emulate "return number that would be written" with
279 * non-conformant implementations.) */
281 tor_snprintf(char *str, size_t size, const char *format, ...)
283 va_list ap;
284 int r;
285 va_start(ap,format);
286 r = tor_vsnprintf(str,size,format,ap);
287 va_end(ap);
288 return r;
291 /** Replacement for vsnprintf; behavior differs as tor_snprintf differs from
292 * snprintf.
295 tor_vsnprintf(char *str, size_t size, const char *format, va_list args)
297 int r;
298 if (size == 0)
299 return -1; /* no place for the NUL */
300 if (size > SSIZE_T_MAX-16)
301 return -1;
302 #ifdef MS_WINDOWS
303 r = _vsnprintf(str, size, format, args);
304 #else
305 r = vsnprintf(str, size, format, args);
306 #endif
307 str[size-1] = '\0';
308 if (r < 0 || r >= (ssize_t)size)
309 return -1;
310 return r;
314 * Portable asprintf implementation. Does a printf() into a newly malloc'd
315 * string. Sets *<b>strp</b> to this string, and returns its length (not
316 * including the terminating NUL character).
318 * You can treat this function as if its implementation were something like
319 <pre>
320 char buf[_INFINITY_];
321 tor_snprintf(buf, sizeof(buf), fmt, args);
322 *strp = tor_strdup(buf);
323 return strlen(*strp):
324 </pre>
325 * Where _INFINITY_ is an imaginary constant so big that any string can fit
326 * into it.
329 tor_asprintf(char **strp, const char *fmt, ...)
331 int r;
332 va_list args;
333 va_start(args, fmt);
334 r = tor_vasprintf(strp, fmt, args);
335 va_end(args);
336 if (!*strp || r < 0) {
337 log_err(LD_BUG, "Internal error in asprintf");
338 tor_assert(0);
340 return r;
344 * Portable vasprintf implementation. Does a printf() into a newly malloc'd
345 * string. Differs from regular vasprintf in the same ways that
346 * tor_asprintf() differs from regular asprintf.
349 tor_vasprintf(char **strp, const char *fmt, va_list args)
351 /* use a temporary variable in case *strp is in args. */
352 char *strp_tmp=NULL;
353 #ifdef HAVE_VASPRINTF
354 /* If the platform gives us one, use it. */
355 int r = vasprintf(&strp_tmp, fmt, args);
356 if (r < 0)
357 *strp = NULL;
358 else
359 *strp = strp_tmp;
360 return r;
361 #elif defined(_MSC_VER)
362 /* On Windows, _vsnprintf won't tell us the length of the string if it
363 * overflows, so we need to use _vcsprintf to tell how much to allocate */
364 int len, r;
365 char *res;
366 len = _vscprintf(fmt, args);
367 if (len < 0) {
368 *strp = NULL;
369 return -1;
371 strp_tmp = tor_malloc(len + 1);
372 r = _vsnprintf(strp_tmp, len+1, fmt, args);
373 if (r != len) {
374 tor_free(strp_tmp);
375 *strp = NULL;
376 return -1;
378 *strp = strp_tmp;
379 return len;
380 #else
381 /* Everywhere else, we have a decent vsnprintf that tells us how many
382 * characters we need. We give it a try on a short buffer first, since
383 * it might be nice to avoid the second vsnprintf call.
385 char buf[128];
386 int len, r;
387 va_list tmp_args;
388 va_copy(tmp_args, args);
389 len = vsnprintf(buf, sizeof(buf), fmt, tmp_args);
390 va_end(tmp_args);
391 if (len < (int)sizeof(buf)) {
392 *strp = tor_strdup(buf);
393 return len;
395 strp_tmp = tor_malloc(len+1);
396 r = vsnprintf(strp_tmp, len+1, fmt, args);
397 if (r != len) {
398 tor_free(strp_tmp);
399 *strp = NULL;
400 return -1;
402 *strp = strp_tmp;
403 return len;
404 #endif
407 /** Given <b>hlen</b> bytes at <b>haystack</b> and <b>nlen</b> bytes at
408 * <b>needle</b>, return a pointer to the first occurrence of the needle
409 * within the haystack, or NULL if there is no such occurrence.
411 * Requires that nlen be greater than zero.
413 const void *
414 tor_memmem(const void *_haystack, size_t hlen,
415 const void *_needle, size_t nlen)
417 #if defined(HAVE_MEMMEM) && (!defined(__GNUC__) || __GNUC__ >= 2)
418 tor_assert(nlen);
419 return memmem(_haystack, hlen, _needle, nlen);
420 #else
421 /* This isn't as fast as the GLIBC implementation, but it doesn't need to
422 * be. */
423 const char *p, *end;
424 const char *haystack = (const char*)_haystack;
425 const char *needle = (const char*)_needle;
426 char first;
427 tor_assert(nlen);
429 p = haystack;
430 end = haystack + hlen;
431 first = *(const char*)needle;
432 while ((p = memchr(p, first, end-p))) {
433 if (p+nlen > end)
434 return NULL;
435 if (!memcmp(p, needle, nlen))
436 return p;
437 ++p;
439 return NULL;
440 #endif
443 /* Tables to implement ctypes-replacement TOR_IS*() functions. Each table
444 * has 256 bits to look up whether a character is in some set or not. This
445 * fails on non-ASCII platforms, but it is hard to find a platform whose
446 * character set is not a superset of ASCII nowadays. */
447 const uint32_t TOR_ISALPHA_TABLE[8] =
448 { 0, 0, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
449 const uint32_t TOR_ISALNUM_TABLE[8] =
450 { 0, 0x3ff0000, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
451 const uint32_t TOR_ISSPACE_TABLE[8] = { 0x3e00, 0x1, 0, 0, 0, 0, 0, 0 };
452 const uint32_t TOR_ISXDIGIT_TABLE[8] =
453 { 0, 0x3ff0000, 0x7e, 0x7e, 0, 0, 0, 0 };
454 const uint32_t TOR_ISDIGIT_TABLE[8] = { 0, 0x3ff0000, 0, 0, 0, 0, 0, 0 };
455 const uint32_t TOR_ISPRINT_TABLE[8] =
456 { 0, 0xffffffff, 0xffffffff, 0x7fffffff, 0, 0, 0, 0x0 };
457 const uint32_t TOR_ISUPPER_TABLE[8] = { 0, 0, 0x7fffffe, 0, 0, 0, 0, 0 };
458 const uint32_t TOR_ISLOWER_TABLE[8] = { 0, 0, 0, 0x7fffffe, 0, 0, 0, 0 };
459 /* Upper-casing and lowercasing tables to map characters to upper/lowercase
460 * equivalents. */
461 const char TOR_TOUPPER_TABLE[256] = {
462 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
463 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
464 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
465 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
466 64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
467 80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
468 96,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
469 80,81,82,83,84,85,86,87,88,89,90,123,124,125,126,127,
470 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
471 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
472 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
473 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
474 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
475 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
476 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
477 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
479 const char TOR_TOLOWER_TABLE[256] = {
480 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
481 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
482 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
483 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
484 64,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
485 112,113,114,115,116,117,118,119,120,121,122,91,92,93,94,95,
486 96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
487 112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
488 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
489 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
490 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
491 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
492 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
493 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
494 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
495 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
498 /** Implementation of strtok_r for platforms whose coders haven't figured out
499 * how to write one. Hey guys! You can use this code here for free! */
500 char *
501 tor_strtok_r_impl(char *str, const char *sep, char **lasts)
503 char *cp, *start;
504 if (str)
505 start = cp = *lasts = str;
506 else if (!*lasts)
507 return NULL;
508 else
509 start = cp = *lasts;
511 tor_assert(*sep);
512 if (sep[1]) {
513 while (*cp && !strchr(sep, *cp))
514 ++cp;
515 } else {
516 tor_assert(strlen(sep) == 1);
517 cp = strchr(cp, *sep);
520 if (!cp || !*cp) {
521 *lasts = NULL;
522 } else {
523 *cp++ = '\0';
524 *lasts = cp;
526 return start;
529 #ifdef MS_WINDOWS
530 /** Take a filename and return a pointer to its final element. This
531 * function is called on __FILE__ to fix a MSVC nit where __FILE__
532 * contains the full path to the file. This is bad, because it
533 * confuses users to find the home directory of the person who
534 * compiled the binary in their warning messages.
536 const char *
537 tor_fix_source_file(const char *fname)
539 const char *cp1, *cp2, *r;
540 cp1 = strrchr(fname, '/');
541 cp2 = strrchr(fname, '\\');
542 if (cp1 && cp2) {
543 r = (cp1<cp2)?(cp2+1):(cp1+1);
544 } else if (cp1) {
545 r = cp1+1;
546 } else if (cp2) {
547 r = cp2+1;
548 } else {
549 r = fname;
551 return r;
553 #endif
556 * Read a 16-bit value beginning at <b>cp</b>. Equivalent to
557 * *(uint16_t*)(cp), but will not cause segfaults on platforms that forbid
558 * unaligned memory access.
560 uint16_t
561 get_uint16(const char *cp)
563 uint16_t v;
564 memcpy(&v,cp,2);
565 return v;
568 * Read a 32-bit value beginning at <b>cp</b>. Equivalent to
569 * *(uint32_t*)(cp), but will not cause segfaults on platforms that forbid
570 * unaligned memory access.
572 uint32_t
573 get_uint32(const char *cp)
575 uint32_t v;
576 memcpy(&v,cp,4);
577 return v;
580 * Read a 64-bit value beginning at <b>cp</b>. Equivalent to
581 * *(uint64_t*)(cp), but will not cause segfaults on platforms that forbid
582 * unaligned memory access.
584 uint64_t
585 get_uint64(const char *cp)
587 uint64_t v;
588 memcpy(&v,cp,8);
589 return v;
593 * Set a 16-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
594 * *(uint16_t*)(cp) = v, but will not cause segfaults on platforms that forbid
595 * unaligned memory access. */
596 void
597 set_uint16(char *cp, uint16_t v)
599 memcpy(cp,&v,2);
602 * Set a 32-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
603 * *(uint32_t*)(cp) = v, but will not cause segfaults on platforms that forbid
604 * unaligned memory access. */
605 void
606 set_uint32(char *cp, uint32_t v)
608 memcpy(cp,&v,4);
611 * Set a 64-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
612 * *(uint64_t*)(cp) = v, but will not cause segfaults on platforms that forbid
613 * unaligned memory access. */
614 void
615 set_uint64(char *cp, uint64_t v)
617 memcpy(cp,&v,8);
621 * Rename the file <b>from</b> to the file <b>to</b>. On Unix, this is
622 * the same as rename(2). On windows, this removes <b>to</b> first if
623 * it already exists.
624 * Returns 0 on success. Returns -1 and sets errno on failure.
627 replace_file(const char *from, const char *to)
629 #ifndef MS_WINDOWS
630 return rename(from,to);
631 #else
632 switch (file_status(to))
634 case FN_NOENT:
635 break;
636 case FN_FILE:
637 if (unlink(to)) return -1;
638 break;
639 case FN_ERROR:
640 return -1;
641 case FN_DIR:
642 errno = EISDIR;
643 return -1;
645 return rename(from,to);
646 #endif
649 /** Change <b>fname</b>'s modification time to now. */
651 touch_file(const char *fname)
653 if (utime(fname, NULL)!=0)
654 return -1;
655 return 0;
658 /** Represents a lockfile on which we hold the lock. */
659 struct tor_lockfile_t {
660 char *filename;
661 int fd;
664 /** Try to get a lock on the lockfile <b>filename</b>, creating it as
665 * necessary. If someone else has the lock and <b>blocking</b> is true,
666 * wait until the lock is available. Otherwise return immediately whether
667 * we succeeded or not.
669 * Set *<b>locked_out</b> to true if somebody else had the lock, and to false
670 * otherwise.
672 * Return a <b>tor_lockfile_t</b> on success, NULL on failure.
674 * (Implementation note: because we need to fall back to fcntl on some
675 * platforms, these locks are per-process, not per-thread. If you want
676 * to do in-process locking, use tor_mutex_t like a normal person.)
678 tor_lockfile_t *
679 tor_lockfile_lock(const char *filename, int blocking, int *locked_out)
681 tor_lockfile_t *result;
682 int fd;
683 *locked_out = 0;
685 log_info(LD_FS, "Locking \"%s\"", filename);
686 fd = open(filename, O_RDWR|O_CREAT|O_TRUNC, 0600);
687 if (fd < 0) {
688 log_warn(LD_FS,"Couldn't open \"%s\" for locking: %s", filename,
689 strerror(errno));
690 return NULL;
693 #ifdef WIN32
694 _lseek(fd, 0, SEEK_SET);
695 if (_locking(fd, blocking ? _LK_LOCK : _LK_NBLCK, 1) < 0) {
696 if (errno != EDEADLOCK)
697 log_warn(LD_FS,"Couldn't lock \"%s\": %s", filename, strerror(errno));
698 else
699 *locked_out = 1;
700 close(fd);
701 return NULL;
703 #elif defined(HAVE_FLOCK)
704 if (flock(fd, LOCK_EX|(blocking ? 0 : LOCK_NB)) < 0) {
705 if (errno != EWOULDBLOCK)
706 log_warn(LD_FS,"Couldn't lock \"%s\": %s", filename, strerror(errno));
707 else
708 *locked_out = 1;
709 close(fd);
710 return NULL;
712 #else
714 struct flock lock;
715 memset(&lock, 0, sizeof(lock));
716 lock.l_type = F_WRLCK;
717 lock.l_whence = SEEK_SET;
718 if (fcntl(fd, blocking ? F_SETLKW : F_SETLK, &lock) < 0) {
719 if (errno != EACCES && errno != EAGAIN)
720 log_warn(LD_FS, "Couldn't lock \"%s\": %s", filename, strerror(errno));
721 else
722 *locked_out = 1;
723 close(fd);
724 return NULL;
727 #endif
729 result = tor_malloc(sizeof(tor_lockfile_t));
730 result->filename = tor_strdup(filename);
731 result->fd = fd;
732 return result;
735 /** Release the lock held as <b>lockfile</b>. */
736 void
737 tor_lockfile_unlock(tor_lockfile_t *lockfile)
739 tor_assert(lockfile);
741 log_info(LD_FS, "Unlocking \"%s\"", lockfile->filename);
742 #ifdef WIN32
743 _lseek(lockfile->fd, 0, SEEK_SET);
744 if (_locking(lockfile->fd, _LK_UNLCK, 1) < 0) {
745 log_warn(LD_FS,"Error unlocking \"%s\": %s", lockfile->filename,
746 strerror(errno));
748 #elif defined(HAVE_FLOCK)
749 if (flock(lockfile->fd, LOCK_UN) < 0) {
750 log_warn(LD_FS, "Error unlocking \"%s\": %s", lockfile->filename,
751 strerror(errno));
753 #else
754 /* Closing the lockfile is sufficient. */
755 #endif
757 close(lockfile->fd);
758 lockfile->fd = -1;
759 tor_free(lockfile->filename);
760 tor_free(lockfile);
763 /* Some old versions of Unix didn't define constants for these values,
764 * and instead expect you to say 0, 1, or 2. */
765 #ifndef SEEK_CUR
766 #define SEEK_CUR 1
767 #endif
768 #ifndef SEEK_END
769 #define SEEK_END 2
770 #endif
772 /** Return the position of <b>fd</b> with respect to the start of the file. */
773 off_t
774 tor_fd_getpos(int fd)
776 #ifdef WIN32
777 return (off_t) _lseek(fd, 0, SEEK_CUR);
778 #else
779 return (off_t) lseek(fd, 0, SEEK_CUR);
780 #endif
783 /** Move <b>fd</b> to the end of the file. Return -1 on error, 0 on success. */
785 tor_fd_seekend(int fd)
787 #ifdef WIN32
788 return _lseek(fd, 0, SEEK_END) < 0 ? -1 : 0;
789 #else
790 return lseek(fd, 0, SEEK_END) < 0 ? -1 : 0;
791 #endif
794 #undef DEBUG_SOCKET_COUNTING
795 #ifdef DEBUG_SOCKET_COUNTING
796 /** A bitarray of all fds that should be passed to tor_socket_close(). Only
797 * used if DEBUG_SOCKET_COUNTING is defined. */
798 static bitarray_t *open_sockets = NULL;
799 /** The size of <b>open_sockets</b>, in bits. */
800 static int max_socket = -1;
801 #endif
803 /** Count of number of sockets currently open. (Undercounts sockets opened by
804 * eventdns and libevent.) */
805 static int n_sockets_open = 0;
807 /** Mutex to protect open_sockets, max_socket, and n_sockets_open. */
808 static tor_mutex_t *socket_accounting_mutex = NULL;
810 static INLINE void
811 socket_accounting_lock(void)
813 if (PREDICT_UNLIKELY(!socket_accounting_mutex))
814 socket_accounting_mutex = tor_mutex_new();
815 tor_mutex_acquire(socket_accounting_mutex);
818 static INLINE void
819 socket_accounting_unlock(void)
821 tor_mutex_release(socket_accounting_mutex);
824 /** As close(), but guaranteed to work for sockets across platforms (including
825 * Windows, where close()ing a socket doesn't work. Returns 0 on success, -1
826 * on failure. */
828 tor_close_socket(int s)
830 int r = 0;
832 /* On Windows, you have to call close() on fds returned by open(),
833 * and closesocket() on fds returned by socket(). On Unix, everything
834 * gets close()'d. We abstract this difference by always using
835 * tor_close_socket to close sockets, and always using close() on
836 * files.
838 #if defined(MS_WINDOWS)
839 r = closesocket(s);
840 #else
841 r = close(s);
842 #endif
844 socket_accounting_lock();
845 #ifdef DEBUG_SOCKET_COUNTING
846 if (s > max_socket || ! bitarray_is_set(open_sockets, s)) {
847 log_warn(LD_BUG, "Closing a socket (%d) that wasn't returned by tor_open_"
848 "socket(), or that was already closed or something.", s);
849 } else {
850 tor_assert(open_sockets && s <= max_socket);
851 bitarray_clear(open_sockets, s);
853 #endif
854 if (r == 0) {
855 --n_sockets_open;
856 } else {
857 int err = tor_socket_errno(-1);
858 log_info(LD_NET, "Close returned an error: %s", tor_socket_strerror(err));
859 #ifdef WIN32
860 if (err != WSAENOTSOCK)
861 --n_sockets_open;
862 #else
863 if (err != EBADF)
864 --n_sockets_open;
865 #endif
866 r = -1;
869 if (n_sockets_open < 0)
870 log_warn(LD_BUG, "Our socket count is below zero: %d. Please submit a "
871 "bug report.", n_sockets_open);
872 socket_accounting_unlock();
873 return r;
876 #ifdef DEBUG_SOCKET_COUNTING
877 /** Helper: if DEBUG_SOCKET_COUNTING is enabled, remember that <b>s</b> is
878 * now an open socket. */
879 static INLINE void
880 mark_socket_open(int s)
882 if (s > max_socket) {
883 if (max_socket == -1) {
884 open_sockets = bitarray_init_zero(s+128);
885 max_socket = s+128;
886 } else {
887 open_sockets = bitarray_expand(open_sockets, max_socket, s+128);
888 max_socket = s+128;
891 if (bitarray_is_set(open_sockets, s)) {
892 log_warn(LD_BUG, "I thought that %d was already open, but socket() just "
893 "gave it to me!", s);
895 bitarray_set(open_sockets, s);
897 #else
898 #define mark_socket_open(s) STMT_NIL
899 #endif
901 /** As socket(), but counts the number of open sockets. */
903 tor_open_socket(int domain, int type, int protocol)
905 int s = socket(domain, type, protocol);
906 if (s >= 0) {
907 socket_accounting_lock();
908 ++n_sockets_open;
909 mark_socket_open(s);
910 socket_accounting_unlock();
912 return s;
915 /** As socket(), but counts the number of open sockets. */
917 tor_accept_socket(int sockfd, struct sockaddr *addr, socklen_t *len)
919 int s = accept(sockfd, addr, len);
920 if (s >= 0) {
921 socket_accounting_lock();
922 ++n_sockets_open;
923 mark_socket_open(s);
924 socket_accounting_unlock();
926 return s;
929 /** Return the number of sockets we currently have opened. */
931 get_n_open_sockets(void)
933 int n;
934 socket_accounting_lock();
935 n = n_sockets_open;
936 socket_accounting_unlock();
937 return n;
940 /** Turn <b>socket</b> into a nonblocking socket.
942 void
943 set_socket_nonblocking(int socket)
945 #if defined(MS_WINDOWS)
946 unsigned long nonblocking = 1;
947 ioctlsocket(socket, FIONBIO, (unsigned long*) &nonblocking);
948 #else
949 fcntl(socket, F_SETFL, O_NONBLOCK);
950 #endif
954 * Allocate a pair of connected sockets. (Like socketpair(family,
955 * type,protocol,fd), but works on systems that don't have
956 * socketpair.)
958 * Currently, only (AF_UNIX, SOCK_STREAM, 0) sockets are supported.
960 * Note that on systems without socketpair, this call will fail if
961 * localhost is inaccessible (for example, if the networking
962 * stack is down). And even if it succeeds, the socket pair will not
963 * be able to read while localhost is down later (the socket pair may
964 * even close, depending on OS-specific timeouts).
966 * Returns 0 on success and -errno on failure; do not rely on the value
967 * of errno or WSAGetLastError().
969 /* It would be nicer just to set errno, but that won't work for windows. */
971 tor_socketpair(int family, int type, int protocol, int fd[2])
973 //don't use win32 socketpairs (they are always bad)
974 #if defined(HAVE_SOCKETPAIR) && !defined(MS_WINDOWS)
975 int r;
976 r = socketpair(family, type, protocol, fd);
977 if (r == 0) {
978 socket_accounting_lock();
979 if (fd[0] >= 0) {
980 ++n_sockets_open;
981 mark_socket_open(fd[0]);
983 if (fd[1] >= 0) {
984 ++n_sockets_open;
985 mark_socket_open(fd[1]);
987 socket_accounting_unlock();
989 return r < 0 ? -errno : r;
990 #else
991 /* This socketpair does not work when localhost is down. So
992 * it's really not the same thing at all. But it's close enough
993 * for now, and really, when localhost is down sometimes, we
994 * have other problems too.
996 int listener = -1;
997 int connector = -1;
998 int acceptor = -1;
999 struct sockaddr_in listen_addr;
1000 struct sockaddr_in connect_addr;
1001 int size;
1002 int saved_errno = -1;
1004 if (protocol
1005 #ifdef AF_UNIX
1006 || family != AF_UNIX
1007 #endif
1009 #ifdef MS_WINDOWS
1010 return -WSAEAFNOSUPPORT;
1011 #else
1012 return -EAFNOSUPPORT;
1013 #endif
1015 if (!fd) {
1016 return -EINVAL;
1019 listener = tor_open_socket(AF_INET, type, 0);
1020 if (listener < 0)
1021 return -tor_socket_errno(-1);
1022 memset(&listen_addr, 0, sizeof(listen_addr));
1023 listen_addr.sin_family = AF_INET;
1024 listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
1025 listen_addr.sin_port = 0; /* kernel chooses port. */
1026 if (bind(listener, (struct sockaddr *) &listen_addr, sizeof (listen_addr))
1027 == -1)
1028 goto tidy_up_and_fail;
1029 if (listen(listener, 1) == -1)
1030 goto tidy_up_and_fail;
1032 connector = tor_open_socket(AF_INET, type, 0);
1033 if (connector < 0)
1034 goto tidy_up_and_fail;
1035 /* We want to find out the port number to connect to. */
1036 size = sizeof(connect_addr);
1037 if (getsockname(listener, (struct sockaddr *) &connect_addr, &size) == -1)
1038 goto tidy_up_and_fail;
1039 if (size != sizeof (connect_addr))
1040 goto abort_tidy_up_and_fail;
1041 if (connect(connector, (struct sockaddr *) &connect_addr,
1042 sizeof(connect_addr)) == -1)
1043 goto tidy_up_and_fail;
1045 size = sizeof(listen_addr);
1046 acceptor = tor_accept_socket(listener,
1047 (struct sockaddr *) &listen_addr, &size);
1048 if (acceptor < 0)
1049 goto tidy_up_and_fail;
1050 if (size != sizeof(listen_addr))
1051 goto abort_tidy_up_and_fail;
1052 tor_close_socket(listener);
1053 /* Now check we are talking to ourself by matching port and host on the
1054 two sockets. */
1055 if (getsockname(connector, (struct sockaddr *) &connect_addr, &size) == -1)
1056 goto tidy_up_and_fail;
1057 if (size != sizeof (connect_addr)
1058 || listen_addr.sin_family != connect_addr.sin_family
1059 || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
1060 || listen_addr.sin_port != connect_addr.sin_port) {
1061 goto abort_tidy_up_and_fail;
1063 fd[0] = connector;
1064 fd[1] = acceptor;
1066 return 0;
1068 abort_tidy_up_and_fail:
1069 #ifdef MS_WINDOWS
1070 saved_errno = WSAECONNABORTED;
1071 #else
1072 saved_errno = ECONNABORTED; /* I hope this is portable and appropriate. */
1073 #endif
1074 tidy_up_and_fail:
1075 if (saved_errno < 0)
1076 saved_errno = errno;
1077 if (listener != -1)
1078 tor_close_socket(listener);
1079 if (connector != -1)
1080 tor_close_socket(connector);
1081 if (acceptor != -1)
1082 tor_close_socket(acceptor);
1083 return -saved_errno;
1084 #endif
1087 #define ULIMIT_BUFFER 32 /* keep 32 extra fd's beyond _ConnLimit */
1089 /** Learn the maximum allowed number of file descriptors. (Some systems
1090 * have a low soft limit.
1092 * We compute this by finding the largest number that we can use.
1093 * If we can't find a number greater than or equal to <b>limit</b>,
1094 * then we fail: return -1.
1096 * Otherwise, return 0 and store the maximum we found inside <b>max_out</b>.*/
1098 set_max_file_descriptors(rlim_t limit, int *max_out)
1100 /* Define some maximum connections values for systems where we cannot
1101 * automatically determine a limit. Re Cygwin, see
1102 * http://archives.seul.org/or/talk/Aug-2006/msg00210.html
1103 * For an iPhone, 9999 should work. For Windows and all other unknown
1104 * systems we use 15000 as the default. */
1105 #ifndef HAVE_GETRLIMIT
1106 #if defined(CYGWIN) || defined(__CYGWIN__)
1107 const char *platform = "Cygwin";
1108 const unsigned long MAX_CONNECTIONS = 3200;
1109 #elif defined(MS_WINDOWS)
1110 const char *platform = "Windows";
1111 const unsigned long MAX_CONNECTIONS = 15000;
1112 #else
1113 const char *platform = "unknown platforms with no getrlimit()";
1114 const unsigned long MAX_CONNECTIONS = 15000;
1115 #endif
1116 log_fn(LOG_INFO, LD_NET,
1117 "This platform is missing getrlimit(). Proceeding.");
1118 if (limit > MAX_CONNECTIONS) {
1119 log_warn(LD_CONFIG,
1120 "We do not support more than %lu file descriptors "
1121 "on %s. Tried to raise to %lu.",
1122 (unsigned long)MAX_CONNECTIONS, platform, (unsigned long)limit);
1123 return -1;
1125 limit = MAX_CONNECTIONS;
1126 #else /* HAVE_GETRLIMIT */
1127 struct rlimit rlim;
1128 tor_assert(limit > 0);
1130 if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) {
1131 log_warn(LD_NET, "Could not get maximum number of file descriptors: %s",
1132 strerror(errno));
1133 return -1;
1136 if (rlim.rlim_max < limit) {
1137 log_warn(LD_CONFIG,"We need %lu file descriptors available, and we're "
1138 "limited to %lu. Please change your ulimit -n.",
1139 (unsigned long)limit, (unsigned long)rlim.rlim_max);
1140 return -1;
1143 if (rlim.rlim_max > rlim.rlim_cur) {
1144 log_info(LD_NET,"Raising max file descriptors from %lu to %lu.",
1145 (unsigned long)rlim.rlim_cur, (unsigned long)rlim.rlim_max);
1147 rlim.rlim_cur = rlim.rlim_max;
1149 if (setrlimit(RLIMIT_NOFILE, &rlim) != 0) {
1150 int bad = 1;
1151 #ifdef OPEN_MAX
1152 if (errno == EINVAL && OPEN_MAX < rlim.rlim_cur) {
1153 /* On some platforms, OPEN_MAX is the real limit, and getrlimit() is
1154 * full of nasty lies. I'm looking at you, OSX 10.5.... */
1155 rlim.rlim_cur = OPEN_MAX;
1156 if (setrlimit(RLIMIT_NOFILE, &rlim) == 0) {
1157 if (rlim.rlim_cur < (rlim_t)limit) {
1158 log_warn(LD_CONFIG, "We are limited to %lu file descriptors by "
1159 "OPEN_MAX, and ConnLimit is %lu. Changing ConnLimit; sorry.",
1160 (unsigned long)OPEN_MAX, (unsigned long)limit);
1161 } else {
1162 log_info(LD_CONFIG, "Dropped connection limit to OPEN_MAX (%lu); "
1163 "Apparently, %lu was too high and rlimit lied to us.",
1164 (unsigned long)OPEN_MAX, (unsigned long)rlim.rlim_max);
1166 bad = 0;
1169 #endif /* OPEN_MAX */
1170 if (bad) {
1171 log_warn(LD_CONFIG,"Couldn't set maximum number of file descriptors: %s",
1172 strerror(errno));
1173 return -1;
1176 /* leave some overhead for logs, etc, */
1177 limit = rlim.rlim_cur;
1178 #endif /* HAVE_GETRLIMIT */
1180 if (limit < ULIMIT_BUFFER) {
1181 log_warn(LD_CONFIG,
1182 "ConnLimit must be at least %d. Failing.", ULIMIT_BUFFER);
1183 return -1;
1185 if (limit > INT_MAX)
1186 limit = INT_MAX;
1187 tor_assert(max_out);
1188 *max_out = (int)limit - ULIMIT_BUFFER;
1189 return 0;
1192 #ifndef MS_WINDOWS
1193 /** Log details of current user and group credentials. Return 0 on
1194 * success. Logs and return -1 on failure.
1196 static int
1197 log_credential_status(void)
1199 #define CREDENTIAL_LOG_LEVEL LOG_INFO
1200 /* Real, effective and saved UIDs */
1201 uid_t ruid, euid, suid;
1202 /* Read, effective and saved GIDs */
1203 gid_t rgid, egid, sgid;
1204 /* Supplementary groups */
1205 gid_t sup_gids[NGROUPS_MAX + 1];
1206 /* Number of supplementary groups */
1207 int ngids;
1209 /* log UIDs */
1210 #ifdef HAVE_GETRESUID
1211 if (getresuid(&ruid, &euid, &suid) != 0 ) {
1212 log_warn(LD_GENERAL, "Error getting changed UIDs: %s", strerror(errno));
1213 return -1;
1214 } else {
1215 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
1216 "UID is %u (real), %u (effective), %u (saved)",
1217 (unsigned)ruid, (unsigned)euid, (unsigned)suid);
1219 #else
1220 /* getresuid is not present on MacOS X, so we can't get the saved (E)UID */
1221 ruid = getuid();
1222 euid = geteuid();
1223 (void)suid;
1225 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
1226 "UID is %u (real), %u (effective), unknown (saved)",
1227 (unsigned)ruid, (unsigned)euid);
1228 #endif
1230 /* log GIDs */
1231 #ifdef HAVE_GETRESGID
1232 if (getresgid(&rgid, &egid, &sgid) != 0 ) {
1233 log_warn(LD_GENERAL, "Error getting changed GIDs: %s", strerror(errno));
1234 return -1;
1235 } else {
1236 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
1237 "GID is %u (real), %u (effective), %u (saved)",
1238 (unsigned)rgid, (unsigned)egid, (unsigned)sgid);
1240 #else
1241 /* getresgid is not present on MacOS X, so we can't get the saved (E)GID */
1242 rgid = getgid();
1243 egid = getegid();
1244 (void)sgid;
1245 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
1246 "GID is %u (real), %u (effective), unknown (saved)",
1247 (unsigned)rgid, (unsigned)egid);
1248 #endif
1250 /* log supplementary groups */
1251 if ((ngids = getgroups(NGROUPS_MAX + 1, sup_gids)) < 0) {
1252 log_warn(LD_GENERAL, "Error getting supplementary GIDs: %s",
1253 strerror(errno));
1254 return -1;
1255 } else {
1256 int i, retval = 0;
1257 char *strgid;
1258 char *s = NULL;
1259 smartlist_t *elts = smartlist_create();
1261 for (i = 0; i<ngids; i++) {
1262 strgid = tor_malloc(11);
1263 if (tor_snprintf(strgid, 11, "%u", (unsigned)sup_gids[i]) < 0) {
1264 log_warn(LD_GENERAL, "Error printing supplementary GIDs");
1265 tor_free(strgid);
1266 retval = -1;
1267 goto error;
1269 smartlist_add(elts, strgid);
1272 s = smartlist_join_strings(elts, " ", 0, NULL);
1274 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL, "Supplementary groups are: %s",s);
1276 error:
1277 tor_free(s);
1278 SMARTLIST_FOREACH(elts, char *, cp,
1280 tor_free(cp);
1282 smartlist_free(elts);
1284 return retval;
1287 return 0;
1289 #endif
1291 /** Call setuid and setgid to run as <b>user</b> and switch to their
1292 * primary group. Return 0 on success. On failure, log and return -1.
1295 switch_id(const char *user)
1297 #ifndef MS_WINDOWS
1298 struct passwd *pw = NULL;
1299 uid_t old_uid;
1300 gid_t old_gid;
1301 static int have_already_switched_id = 0;
1303 tor_assert(user);
1305 if (have_already_switched_id)
1306 return 0;
1308 /* Log the initial credential state */
1309 if (log_credential_status())
1310 return -1;
1312 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL, "Changing user and groups");
1314 /* Get old UID/GID to check if we changed correctly */
1315 old_uid = getuid();
1316 old_gid = getgid();
1318 /* Lookup the user and group information, if we have a problem, bail out. */
1319 pw = getpwnam(user);
1320 if (pw == NULL) {
1321 log_warn(LD_CONFIG, "Error setting configured user: %s not found", user);
1322 return -1;
1325 /* Properly switch egid,gid,euid,uid here or bail out */
1326 if (setgroups(1, &pw->pw_gid)) {
1327 log_warn(LD_GENERAL, "Error setting groups to gid %d: \"%s\".",
1328 (int)pw->pw_gid, strerror(errno));
1329 if (old_uid == pw->pw_uid) {
1330 log_warn(LD_GENERAL, "Tor is already running as %s. You do not need "
1331 "the \"User\" option if you are already running as the user "
1332 "you want to be. (If you did not set the User option in your "
1333 "torrc, check whether it was specified on the command line "
1334 "by a startup script.)", user);
1335 } else {
1336 log_warn(LD_GENERAL, "If you set the \"User\" option, you must start Tor"
1337 " as root.");
1339 return -1;
1342 if (setegid(pw->pw_gid)) {
1343 log_warn(LD_GENERAL, "Error setting egid to %d: %s",
1344 (int)pw->pw_gid, strerror(errno));
1345 return -1;
1348 if (setgid(pw->pw_gid)) {
1349 log_warn(LD_GENERAL, "Error setting gid to %d: %s",
1350 (int)pw->pw_gid, strerror(errno));
1351 return -1;
1354 if (setuid(pw->pw_uid)) {
1355 log_warn(LD_GENERAL, "Error setting configured uid to %s (%d): %s",
1356 user, (int)pw->pw_uid, strerror(errno));
1357 return -1;
1360 if (seteuid(pw->pw_uid)) {
1361 log_warn(LD_GENERAL, "Error setting configured euid to %s (%d): %s",
1362 user, (int)pw->pw_uid, strerror(errno));
1363 return -1;
1366 /* This is how OpenBSD rolls:
1367 if (setgroups(1, &pw->pw_gid) || setegid(pw->pw_gid) ||
1368 setgid(pw->pw_gid) || setuid(pw->pw_uid) || seteuid(pw->pw_uid)) {
1369 setgid(pw->pw_gid) || seteuid(pw->pw_uid) || setuid(pw->pw_uid)) {
1370 log_warn(LD_GENERAL, "Error setting configured UID/GID: %s",
1371 strerror(errno));
1372 return -1;
1376 /* We've properly switched egid, gid, euid, uid, and supplementary groups if
1377 * we're here. */
1379 #if !defined(CYGWIN) && !defined(__CYGWIN__)
1380 /* If we tried to drop privilege to a group/user other than root, attempt to
1381 * restore root (E)(U|G)ID, and abort if the operation succeeds */
1383 /* Only check for privilege dropping if we were asked to be non-root */
1384 if (pw->pw_uid) {
1385 /* Try changing GID/EGID */
1386 if (pw->pw_gid != old_gid &&
1387 (setgid(old_gid) != -1 || setegid(old_gid) != -1)) {
1388 log_warn(LD_GENERAL, "Was able to restore group credentials even after "
1389 "switching GID: this means that the setgid code didn't work.");
1390 return -1;
1393 /* Try changing UID/EUID */
1394 if (pw->pw_uid != old_uid &&
1395 (setuid(old_uid) != -1 || seteuid(old_uid) != -1)) {
1396 log_warn(LD_GENERAL, "Was able to restore user credentials even after "
1397 "switching UID: this means that the setuid code didn't work.");
1398 return -1;
1401 #endif
1403 /* Check what really happened */
1404 if (log_credential_status()) {
1405 return -1;
1408 have_already_switched_id = 1; /* mark success so we never try again */
1410 #if defined(__linux__) && defined(HAVE_SYS_PRCTL_H) && defined(HAVE_PRCTL)
1411 #ifdef PR_SET_DUMPABLE
1412 if (pw->pw_uid) {
1413 /* Re-enable core dumps if we're not running as root. */
1414 log_info(LD_CONFIG, "Re-enabling coredumps");
1415 if (prctl(PR_SET_DUMPABLE, 1)) {
1416 log_warn(LD_CONFIG, "Unable to re-enable coredumps: %s",strerror(errno));
1419 #endif
1420 #endif
1421 return 0;
1423 #else
1424 (void)user;
1426 log_warn(LD_CONFIG,
1427 "User specified but switching users is unsupported on your OS.");
1428 return -1;
1429 #endif
1432 #ifdef HAVE_PWD_H
1433 /** Allocate and return a string containing the home directory for the
1434 * user <b>username</b>. Only works on posix-like systems. */
1435 char *
1436 get_user_homedir(const char *username)
1438 struct passwd *pw;
1439 tor_assert(username);
1441 if (!(pw = getpwnam(username))) {
1442 log_err(LD_CONFIG,"User \"%s\" not found.", username);
1443 return NULL;
1445 return tor_strdup(pw->pw_dir);
1447 #endif
1449 /** Set *addr to the IP address (in dotted-quad notation) stored in c.
1450 * Return 1 on success, 0 if c is badly formatted. (Like inet_aton(c,addr),
1451 * but works on Windows and Solaris.)
1454 tor_inet_aton(const char *str, struct in_addr* addr)
1456 unsigned a,b,c,d;
1457 char more;
1458 if (tor_sscanf(str, "%3u.%3u.%3u.%3u%c", &a,&b,&c,&d,&more) != 4)
1459 return 0;
1460 if (a > 255) return 0;
1461 if (b > 255) return 0;
1462 if (c > 255) return 0;
1463 if (d > 255) return 0;
1464 addr->s_addr = htonl((a<<24) | (b<<16) | (c<<8) | d);
1465 return 1;
1468 /** Given <b>af</b>==AF_INET and <b>src</b> a struct in_addr, or
1469 * <b>af</b>==AF_INET6 and <b>src</b> a struct in6_addr, try to format the
1470 * address and store it in the <b>len</b>-byte buffer <b>dst</b>. Returns
1471 * <b>dst</b> on success, NULL on failure.
1473 * (Like inet_ntop(af,src,dst,len), but works on platforms that don't have it:
1474 * Tor sometimes needs to format ipv6 addresses even on platforms without ipv6
1475 * support.) */
1476 const char *
1477 tor_inet_ntop(int af, const void *src, char *dst, size_t len)
1479 if (af == AF_INET) {
1480 if (tor_inet_ntoa(src, dst, len) < 0)
1481 return NULL;
1482 else
1483 return dst;
1484 } else if (af == AF_INET6) {
1485 const struct in6_addr *addr = src;
1486 char buf[64], *cp;
1487 int longestGapLen = 0, longestGapPos = -1, i,
1488 curGapPos = -1, curGapLen = 0;
1489 uint16_t words[8];
1490 for (i = 0; i < 8; ++i) {
1491 words[i] = (((uint16_t)addr->s6_addr[2*i])<<8) + addr->s6_addr[2*i+1];
1493 if (words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0 &&
1494 words[4] == 0 && ((words[5] == 0 && words[6] && words[7]) ||
1495 (words[5] == 0xffff))) {
1496 /* This is an IPv4 address. */
1497 if (words[5] == 0) {
1498 tor_snprintf(buf, sizeof(buf), "::%d.%d.%d.%d",
1499 addr->s6_addr[12], addr->s6_addr[13],
1500 addr->s6_addr[14], addr->s6_addr[15]);
1501 } else {
1502 tor_snprintf(buf, sizeof(buf), "::%x:%d.%d.%d.%d", words[5],
1503 addr->s6_addr[12], addr->s6_addr[13],
1504 addr->s6_addr[14], addr->s6_addr[15]);
1506 if (strlen(buf) > len)
1507 return NULL;
1508 strlcpy(dst, buf, len);
1509 return dst;
1511 i = 0;
1512 while (i < 8) {
1513 if (words[i] == 0) {
1514 curGapPos = i++;
1515 curGapLen = 1;
1516 while (i<8 && words[i] == 0) {
1517 ++i; ++curGapLen;
1519 if (curGapLen > longestGapLen) {
1520 longestGapPos = curGapPos;
1521 longestGapLen = curGapLen;
1523 } else {
1524 ++i;
1527 if (longestGapLen<=1)
1528 longestGapPos = -1;
1530 cp = buf;
1531 for (i = 0; i < 8; ++i) {
1532 if (words[i] == 0 && longestGapPos == i) {
1533 if (i == 0)
1534 *cp++ = ':';
1535 *cp++ = ':';
1536 while (i < 8 && words[i] == 0)
1537 ++i;
1538 --i; /* to compensate for loop increment. */
1539 } else {
1540 tor_snprintf(cp, sizeof(buf)-(cp-buf), "%x", (unsigned)words[i]);
1541 cp += strlen(cp);
1542 if (i != 7)
1543 *cp++ = ':';
1546 *cp = '\0';
1547 if (strlen(buf) > len)
1548 return NULL;
1549 strlcpy(dst, buf, len);
1550 return dst;
1551 } else {
1552 return NULL;
1556 /** Given <b>af</b>==AF_INET or <b>af</b>==AF_INET6, and a string <b>src</b>
1557 * encoding an IPv4 address or IPv6 address correspondingly, try to parse the
1558 * address and store the result in <b>dst</b> (which must have space for a
1559 * struct in_addr or a struct in6_addr, as appropriate). Return 1 on success,
1560 * 0 on a bad parse, and -1 on a bad <b>af</b>.
1562 * (Like inet_pton(af,src,dst) but works on platforms that don't have it: Tor
1563 * sometimes needs to format ipv6 addresses even on platforms without ipv6
1564 * support.) */
1566 tor_inet_pton(int af, const char *src, void *dst)
1568 if (af == AF_INET) {
1569 return tor_inet_aton(src, dst);
1570 } else if (af == AF_INET6) {
1571 struct in6_addr *out = dst;
1572 uint16_t words[8];
1573 int gapPos = -1, i, setWords=0;
1574 const char *dot = strchr(src, '.');
1575 const char *eow; /* end of words. */
1576 if (dot == src)
1577 return 0;
1578 else if (!dot)
1579 eow = src+strlen(src);
1580 else {
1581 unsigned byte1,byte2,byte3,byte4;
1582 char more;
1583 for (eow = dot-1; eow >= src && TOR_ISDIGIT(*eow); --eow)
1585 ++eow;
1587 /* We use "scanf" because some platform inet_aton()s are too lax
1588 * about IPv4 addresses of the form "1.2.3" */
1589 if (tor_sscanf(eow, "%3u.%3u.%3u.%3u%c",
1590 &byte1,&byte2,&byte3,&byte4,&more) != 4)
1591 return 0;
1593 if (byte1 > 255 || byte2 > 255 || byte3 > 255 || byte4 > 255)
1594 return 0;
1596 words[6] = (byte1<<8) | byte2;
1597 words[7] = (byte3<<8) | byte4;
1598 setWords += 2;
1601 i = 0;
1602 while (src < eow) {
1603 if (i > 7)
1604 return 0;
1605 if (TOR_ISXDIGIT(*src)) {
1606 char *next;
1607 long r = strtol(src, &next, 16);
1608 if (next > 4+src)
1609 return 0;
1610 if (next == src)
1611 return 0;
1612 if (r<0 || r>65536)
1613 return 0;
1615 words[i++] = (uint16_t)r;
1616 setWords++;
1617 src = next;
1618 if (*src != ':' && src != eow)
1619 return 0;
1620 ++src;
1621 } else if (*src == ':' && i > 0 && gapPos==-1) {
1622 gapPos = i;
1623 ++src;
1624 } else if (*src == ':' && i == 0 && src[1] == ':' && gapPos==-1) {
1625 gapPos = i;
1626 src += 2;
1627 } else {
1628 return 0;
1632 if (setWords > 8 ||
1633 (setWords == 8 && gapPos != -1) ||
1634 (setWords < 8 && gapPos == -1))
1635 return 0;
1637 if (gapPos >= 0) {
1638 int nToMove = setWords - (dot ? 2 : 0) - gapPos;
1639 int gapLen = 8 - setWords;
1640 tor_assert(nToMove >= 0);
1641 memmove(&words[gapPos+gapLen], &words[gapPos],
1642 sizeof(uint16_t)*nToMove);
1643 memset(&words[gapPos], 0, sizeof(uint16_t)*gapLen);
1645 for (i = 0; i < 8; ++i) {
1646 out->s6_addr[2*i ] = words[i] >> 8;
1647 out->s6_addr[2*i+1] = words[i] & 0xff;
1650 return 1;
1651 } else {
1652 return -1;
1656 /** Similar behavior to Unix gethostbyname: resolve <b>name</b>, and set
1657 * *<b>addr</b> to the proper IP address, in host byte order. Returns 0
1658 * on success, -1 on failure; 1 on transient failure.
1660 * (This function exists because standard windows gethostbyname
1661 * doesn't treat raw IP addresses properly.)
1664 tor_lookup_hostname(const char *name, uint32_t *addr)
1666 tor_addr_t myaddr;
1667 int ret;
1669 if ((ret = tor_addr_lookup(name, AF_INET, &myaddr)))
1670 return ret;
1672 if (tor_addr_family(&myaddr) == AF_INET) {
1673 *addr = tor_addr_to_ipv4h(&myaddr);
1674 return ret;
1677 return -1;
1680 /** Hold the result of our call to <b>uname</b>. */
1681 static char uname_result[256];
1682 /** True iff uname_result is set. */
1683 static int uname_result_is_set = 0;
1685 /** Return a pointer to a description of our platform.
1687 const char *
1688 get_uname(void)
1690 #ifdef HAVE_UNAME
1691 struct utsname u;
1692 #endif
1693 if (!uname_result_is_set) {
1694 #ifdef HAVE_UNAME
1695 if (uname(&u) != -1) {
1696 /* (Linux says 0 is success, Solaris says 1 is success) */
1697 tor_snprintf(uname_result, sizeof(uname_result), "%s %s",
1698 u.sysname, u.machine);
1699 } else
1700 #endif
1702 #ifdef MS_WINDOWS
1703 #if defined (WINCE)
1704 OSVERSIONINFO info;
1705 #else
1706 OSVERSIONINFOEXW info;
1707 #endif
1708 int i;
1709 const char *plat = NULL;
1710 const char *extra = NULL;
1711 char acsd[MAX_PATH] = {0};
1712 static struct {
1713 unsigned major; unsigned minor; const char *version;
1714 } win_version_table[] = {
1715 { 6, 1, "Windows 7" },
1716 { 6, 0, "Windows Vista" },
1717 { 5, 2, "Windows Server 2003" },
1718 { 5, 1, "Windows XP" },
1719 { 5, 0, "Windows 2000" },
1720 /* { 4, 0, "Windows NT 4.0" }, */
1721 { 4, 90, "Windows Me" },
1722 { 4, 10, "Windows 98" },
1723 /* { 4, 0, "Windows 95" } */
1724 { 3, 51, "Windows NT 3.51" },
1725 { 0, 0, NULL }
1727 memset(&info, 0, sizeof(info));
1728 info.dwOSVersionInfoSize = sizeof(info);
1729 if (! GetVersionExW((LPOSVERSIONINFO)&info)) {
1730 strlcpy(uname_result, "Bizarre version of Windows where GetVersionEx"
1731 " doesn't work.", sizeof(uname_result));
1732 uname_result_is_set = 1;
1733 return uname_result;
1735 wcstombs(acsd, info.szCSDVersion, MAX_PATH);
1736 if (info.dwMajorVersion == 4 && info.dwMinorVersion == 0) {
1737 if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
1738 plat = "Windows NT 4.0";
1739 else
1740 plat = "Windows 95";
1741 if (acsd[1] == 'B')
1742 extra = "OSR2 (B)";
1743 else if (acsd[1] == 'C')
1744 extra = "OSR2 (C)";
1745 } else {
1746 for (i=0; win_version_table[i].major>0; ++i) {
1747 if (win_version_table[i].major == info.dwMajorVersion &&
1748 win_version_table[i].minor == info.dwMinorVersion) {
1749 plat = win_version_table[i].version;
1750 break;
1754 if (plat && !strcmp(plat, "Windows 98")) {
1755 if (acsd[1] == 'A')
1756 extra = "SE (A)";
1757 else if (acsd[1] == 'B')
1758 extra = "SE (B)";
1760 if (plat) {
1761 if (!extra)
1762 extra = acsd;
1763 tor_snprintf(uname_result, sizeof(uname_result), "%s %s",
1764 plat, extra);
1765 } else {
1766 if (info.dwMajorVersion > 6 ||
1767 (info.dwMajorVersion==6 && info.dwMinorVersion>1))
1768 tor_snprintf(uname_result, sizeof(uname_result),
1769 "Very recent version of Windows [major=%d,minor=%d] %s",
1770 (int)info.dwMajorVersion,(int)info.dwMinorVersion,
1771 acsd);
1772 else
1773 tor_snprintf(uname_result, sizeof(uname_result),
1774 "Unrecognized version of Windows [major=%d,minor=%d] %s",
1775 (int)info.dwMajorVersion,(int)info.dwMinorVersion,
1776 acsd);
1778 #if !defined (WINCE)
1779 #ifdef VER_SUITE_BACKOFFICE
1780 if (info.wProductType == VER_NT_DOMAIN_CONTROLLER) {
1781 strlcat(uname_result, " [domain controller]", sizeof(uname_result));
1782 } else if (info.wProductType == VER_NT_SERVER) {
1783 strlcat(uname_result, " [server]", sizeof(uname_result));
1784 } else if (info.wProductType == VER_NT_WORKSTATION) {
1785 strlcat(uname_result, " [workstation]", sizeof(uname_result));
1787 #endif
1788 #endif
1789 #else
1790 strlcpy(uname_result, "Unknown platform", sizeof(uname_result));
1791 #endif
1793 uname_result_is_set = 1;
1795 return uname_result;
1799 * Process control
1802 #if defined(USE_PTHREADS)
1803 /** Wraps a void (*)(void*) function and its argument so we can
1804 * invoke them in a way pthreads would expect.
1806 typedef struct tor_pthread_data_t {
1807 void (*func)(void *);
1808 void *data;
1809 } tor_pthread_data_t;
1810 /** Given a tor_pthread_data_t <b>_data</b>, call _data-&gt;func(d-&gt;data)
1811 * and free _data. Used to make sure we can call functions the way pthread
1812 * expects. */
1813 static void *
1814 tor_pthread_helper_fn(void *_data)
1816 tor_pthread_data_t *data = _data;
1817 void (*func)(void*);
1818 void *arg;
1819 /* mask signals to worker threads to avoid SIGPIPE, etc */
1820 sigset_t sigs;
1821 /* We're in a subthread; don't handle any signals here. */
1822 sigfillset(&sigs);
1823 pthread_sigmask(SIG_SETMASK, &sigs, NULL);
1825 func = data->func;
1826 arg = data->data;
1827 tor_free(_data);
1828 func(arg);
1829 return NULL;
1831 #endif
1833 /** Minimalist interface to run a void function in the background. On
1834 * Unix calls fork, on win32 calls beginthread. Returns -1 on failure.
1835 * func should not return, but rather should call spawn_exit.
1837 * NOTE: if <b>data</b> is used, it should not be allocated on the stack,
1838 * since in a multithreaded environment, there is no way to be sure that
1839 * the caller's stack will still be around when the called function is
1840 * running.
1843 spawn_func(void (*func)(void *), void *data)
1845 #if defined(USE_WIN32_THREADS)
1846 int rv;
1847 rv = (int)_beginthread(func, 0, data);
1848 if (rv == (int)-1)
1849 return -1;
1850 return 0;
1851 #elif defined(USE_PTHREADS)
1852 pthread_t thread;
1853 tor_pthread_data_t *d;
1854 d = tor_malloc(sizeof(tor_pthread_data_t));
1855 d->data = data;
1856 d->func = func;
1857 if (pthread_create(&thread,NULL,tor_pthread_helper_fn,d))
1858 return -1;
1859 if (pthread_detach(thread))
1860 return -1;
1861 return 0;
1862 #else
1863 pid_t pid;
1864 pid = fork();
1865 if (pid<0)
1866 return -1;
1867 if (pid==0) {
1868 /* Child */
1869 func(data);
1870 tor_assert(0); /* Should never reach here. */
1871 return 0; /* suppress "control-reaches-end-of-non-void" warning. */
1872 } else {
1873 /* Parent */
1874 return 0;
1876 #endif
1879 /** End the current thread/process.
1881 void
1882 spawn_exit(void)
1884 #if defined(USE_WIN32_THREADS)
1885 _endthread();
1886 //we should never get here. my compiler thinks that _endthread returns, this
1887 //is an attempt to fool it.
1888 tor_assert(0);
1889 _exit(0);
1890 #elif defined(USE_PTHREADS)
1891 pthread_exit(NULL);
1892 #else
1893 /* http://www.erlenstar.demon.co.uk/unix/faq_2.html says we should
1894 * call _exit, not exit, from child processes. */
1895 _exit(0);
1896 #endif
1899 /** Set *timeval to the current time of day. On error, log and terminate.
1900 * (Same as gettimeofday(timeval,NULL), but never returns -1.)
1902 void
1903 tor_gettimeofday(struct timeval *timeval)
1905 #ifdef MS_WINDOWS
1906 /* Epoch bias copied from perl: number of units between windows epoch and
1907 * Unix epoch. */
1908 #define EPOCH_BIAS U64_LITERAL(116444736000000000)
1909 #define UNITS_PER_SEC U64_LITERAL(10000000)
1910 #define USEC_PER_SEC U64_LITERAL(1000000)
1911 #define UNITS_PER_USEC U64_LITERAL(10)
1912 union {
1913 uint64_t ft_64;
1914 FILETIME ft_ft;
1915 } ft;
1916 #if defined (WINCE)
1917 /* wince do not have GetSystemTimeAsFileTime */
1918 SYSTEMTIME stime;
1919 GetSystemTime(&stime);
1920 SystemTimeToFileTime(&stime,&ft.ft_ft);
1921 #else
1922 /* number of 100-nsec units since Jan 1, 1601 */
1923 GetSystemTimeAsFileTime(&ft.ft_ft);
1924 #endif
1925 if (ft.ft_64 < EPOCH_BIAS) {
1926 log_err(LD_GENERAL,"System time is before 1970; failing.");
1927 exit(1);
1929 ft.ft_64 -= EPOCH_BIAS;
1930 timeval->tv_sec = (unsigned) (ft.ft_64 / UNITS_PER_SEC);
1931 timeval->tv_usec = (unsigned) ((ft.ft_64 / UNITS_PER_USEC) % USEC_PER_SEC);
1932 #elif defined(HAVE_GETTIMEOFDAY)
1933 if (gettimeofday(timeval, NULL)) {
1934 log_err(LD_GENERAL,"gettimeofday failed.");
1935 /* If gettimeofday dies, we have either given a bad timezone (we didn't),
1936 or segfaulted.*/
1937 exit(1);
1939 #elif defined(HAVE_FTIME)
1940 struct timeb tb;
1941 ftime(&tb);
1942 timeval->tv_sec = tb.time;
1943 timeval->tv_usec = tb.millitm * 1000;
1944 #else
1945 #error "No way to get time."
1946 #endif
1947 return;
1950 #if defined(TOR_IS_MULTITHREADED) && !defined(MS_WINDOWS)
1951 /** Defined iff we need to add locks when defining fake versions of reentrant
1952 * versions of time-related functions. */
1953 #define TIME_FNS_NEED_LOCKS
1954 #endif
1956 #ifndef HAVE_LOCALTIME_R
1957 #ifdef TIME_FNS_NEED_LOCKS
1958 struct tm *
1959 tor_localtime_r(const time_t *timep, struct tm *result)
1961 struct tm *r;
1962 static tor_mutex_t *m=NULL;
1963 if (!m) { m=tor_mutex_new(); }
1964 tor_assert(result);
1965 tor_mutex_acquire(m);
1966 r = localtime(timep);
1967 memcpy(result, r, sizeof(struct tm));
1968 tor_mutex_release(m);
1969 return result;
1971 #else
1972 struct tm *
1973 tor_localtime_r(const time_t *timep, struct tm *result)
1975 struct tm *r;
1976 tor_assert(result);
1977 r = localtime(timep);
1978 memcpy(result, r, sizeof(struct tm));
1979 return result;
1981 #endif
1982 #endif
1984 #ifndef HAVE_GMTIME_R
1985 #ifdef TIME_FNS_NEED_LOCKS
1986 struct tm *
1987 tor_gmtime_r(const time_t *timep, struct tm *result)
1989 struct tm *r;
1990 static tor_mutex_t *m=NULL;
1991 if (!m) { m=tor_mutex_new(); }
1992 tor_assert(result);
1993 tor_mutex_acquire(m);
1994 r = gmtime(timep);
1995 memcpy(result, r, sizeof(struct tm));
1996 tor_mutex_release(m);
1997 return result;
1999 #else
2000 struct tm *
2001 tor_gmtime_r(const time_t *timep, struct tm *result)
2003 struct tm *r;
2004 tor_assert(result);
2005 r = gmtime(timep);
2006 memcpy(result, r, sizeof(struct tm));
2007 return result;
2009 #endif
2010 #endif
2012 #if defined(USE_WIN32_THREADS)
2013 void
2014 tor_mutex_init(tor_mutex_t *m)
2016 InitializeCriticalSection(&m->mutex);
2018 void
2019 tor_mutex_uninit(tor_mutex_t *m)
2021 DeleteCriticalSection(&m->mutex);
2023 void
2024 tor_mutex_acquire(tor_mutex_t *m)
2026 tor_assert(m);
2027 EnterCriticalSection(&m->mutex);
2029 void
2030 tor_mutex_release(tor_mutex_t *m)
2032 LeaveCriticalSection(&m->mutex);
2034 unsigned long
2035 tor_get_thread_id(void)
2037 return (unsigned long)GetCurrentThreadId();
2039 #elif defined(USE_PTHREADS)
2040 /** A mutex attribute that we're going to use to tell pthreads that we want
2041 * "reentrant" mutexes (i.e., once we can re-lock if we're already holding
2042 * them.) */
2043 static pthread_mutexattr_t attr_reentrant;
2044 /** True iff we've called tor_threads_init() */
2045 static int threads_initialized = 0;
2046 /** Initialize <b>mutex</b> so it can be locked. Every mutex must be set
2047 * up with tor_mutex_init() or tor_mutex_new(); not both. */
2048 void
2049 tor_mutex_init(tor_mutex_t *mutex)
2051 int err;
2052 if (PREDICT_UNLIKELY(!threads_initialized))
2053 tor_threads_init();
2054 err = pthread_mutex_init(&mutex->mutex, &attr_reentrant);
2055 if (PREDICT_UNLIKELY(err)) {
2056 log_err(LD_GENERAL, "Error %d creating a mutex.", err);
2057 tor_fragile_assert();
2060 /** Wait until <b>m</b> is free, then acquire it. */
2061 void
2062 tor_mutex_acquire(tor_mutex_t *m)
2064 int err;
2065 tor_assert(m);
2066 err = pthread_mutex_lock(&m->mutex);
2067 if (PREDICT_UNLIKELY(err)) {
2068 log_err(LD_GENERAL, "Error %d locking a mutex.", err);
2069 tor_fragile_assert();
2072 /** Release the lock <b>m</b> so another thread can have it. */
2073 void
2074 tor_mutex_release(tor_mutex_t *m)
2076 int err;
2077 tor_assert(m);
2078 err = pthread_mutex_unlock(&m->mutex);
2079 if (PREDICT_UNLIKELY(err)) {
2080 log_err(LD_GENERAL, "Error %d unlocking a mutex.", err);
2081 tor_fragile_assert();
2084 /** Clean up the mutex <b>m</b> so that it no longer uses any system
2085 * resources. Does not free <b>m</b>. This function must only be called on
2086 * mutexes from tor_mutex_init(). */
2087 void
2088 tor_mutex_uninit(tor_mutex_t *m)
2090 int err;
2091 tor_assert(m);
2092 err = pthread_mutex_destroy(&m->mutex);
2093 if (PREDICT_UNLIKELY(err)) {
2094 log_err(LD_GENERAL, "Error %d destroying a mutex.", err);
2095 tor_fragile_assert();
2098 /** Return an integer representing this thread. */
2099 unsigned long
2100 tor_get_thread_id(void)
2102 union {
2103 pthread_t thr;
2104 unsigned long id;
2105 } r;
2106 r.thr = pthread_self();
2107 return r.id;
2109 #endif
2111 #ifdef TOR_IS_MULTITHREADED
2112 /** Return a newly allocated, ready-for-use mutex. */
2113 tor_mutex_t *
2114 tor_mutex_new(void)
2116 tor_mutex_t *m = tor_malloc_zero(sizeof(tor_mutex_t));
2117 tor_mutex_init(m);
2118 return m;
2120 /** Release all storage and system resources held by <b>m</b>. */
2121 void
2122 tor_mutex_free(tor_mutex_t *m)
2124 if (!m)
2125 return;
2126 tor_mutex_uninit(m);
2127 tor_free(m);
2129 #endif
2131 /* Conditions. */
2132 #ifdef USE_PTHREADS
2133 #if 0
2134 /** Cross-platform condition implementation. */
2135 struct tor_cond_t {
2136 pthread_cond_t cond;
2138 /** Return a newly allocated condition, with nobody waiting on it. */
2139 tor_cond_t *
2140 tor_cond_new(void)
2142 tor_cond_t *cond = tor_malloc_zero(sizeof(tor_cond_t));
2143 if (pthread_cond_init(&cond->cond, NULL)) {
2144 tor_free(cond);
2145 return NULL;
2147 return cond;
2149 /** Release all resources held by <b>cond</b>. */
2150 void
2151 tor_cond_free(tor_cond_t *cond)
2153 if (!cond)
2154 return;
2155 if (pthread_cond_destroy(&cond->cond)) {
2156 log_warn(LD_GENERAL,"Error freeing condition: %s", strerror(errno));
2157 return;
2159 tor_free(cond);
2161 /** Wait until one of the tor_cond_signal functions is called on <b>cond</b>.
2162 * All waiters on the condition must wait holding the same <b>mutex</b>.
2163 * Returns 0 on success, negative on failure. */
2165 tor_cond_wait(tor_cond_t *cond, tor_mutex_t *mutex)
2167 return pthread_cond_wait(&cond->cond, &mutex->mutex) ? -1 : 0;
2169 /** Wake up one of the waiters on <b>cond</b>. */
2170 void
2171 tor_cond_signal_one(tor_cond_t *cond)
2173 pthread_cond_signal(&cond->cond);
2175 /** Wake up all of the waiters on <b>cond</b>. */
2176 void
2177 tor_cond_signal_all(tor_cond_t *cond)
2179 pthread_cond_broadcast(&cond->cond);
2181 #endif
2182 /** Set up common structures for use by threading. */
2183 void
2184 tor_threads_init(void)
2186 if (!threads_initialized) {
2187 pthread_mutexattr_init(&attr_reentrant);
2188 pthread_mutexattr_settype(&attr_reentrant, PTHREAD_MUTEX_RECURSIVE);
2189 threads_initialized = 1;
2190 set_main_thread();
2193 #elif defined(USE_WIN32_THREADS)
2194 #if 0
2195 static DWORD cond_event_tls_index;
2196 struct tor_cond_t {
2197 CRITICAL_SECTION mutex;
2198 smartlist_t *events;
2200 tor_cond_t *
2201 tor_cond_new(void)
2203 tor_cond_t *cond = tor_malloc_zero(sizeof(tor_cond_t));
2204 InitializeCriticalSection(&cond->mutex);
2205 cond->events = smartlist_create();
2206 return cond;
2208 void
2209 tor_cond_free(tor_cond_t *cond)
2211 if (!cond)
2212 return;
2213 DeleteCriticalSection(&cond->mutex);
2214 /* XXXX notify? */
2215 smartlist_free(cond->events);
2216 tor_free(cond);
2219 tor_cond_wait(tor_cond_t *cond, tor_mutex_t *mutex)
2221 HANDLE event;
2222 int r;
2223 tor_assert(cond);
2224 tor_assert(mutex);
2225 event = TlsGetValue(cond_event_tls_index);
2226 if (!event) {
2227 event = CreateEvent(0, FALSE, FALSE, NULL);
2228 TlsSetValue(cond_event_tls_index, event);
2230 EnterCriticalSection(&cond->mutex);
2232 tor_assert(WaitForSingleObject(event, 0) == WAIT_TIMEOUT);
2233 tor_assert(!smartlist_isin(cond->events, event));
2234 smartlist_add(cond->events, event);
2236 LeaveCriticalSection(&cond->mutex);
2238 tor_mutex_release(mutex);
2239 r = WaitForSingleObject(event, INFINITE);
2240 tor_mutex_acquire(mutex);
2242 switch (r) {
2243 case WAIT_OBJECT_0: /* we got the mutex normally. */
2244 break;
2245 case WAIT_ABANDONED: /* holding thread exited. */
2246 case WAIT_TIMEOUT: /* Should never happen. */
2247 tor_assert(0);
2248 break;
2249 case WAIT_FAILED:
2250 log_warn(LD_GENERAL, "Failed to acquire mutex: %d",(int) GetLastError());
2252 return 0;
2254 void
2255 tor_cond_signal_one(tor_cond_t *cond)
2257 HANDLE event;
2258 tor_assert(cond);
2260 EnterCriticalSection(&cond->mutex);
2262 if ((event = smartlist_pop_last(cond->events)))
2263 SetEvent(event);
2265 LeaveCriticalSection(&cond->mutex);
2267 void
2268 tor_cond_signal_all(tor_cond_t *cond)
2270 tor_assert(cond);
2272 EnterCriticalSection(&cond->mutex);
2273 SMARTLIST_FOREACH(cond->events, HANDLE, event, SetEvent(event));
2274 smartlist_clear(cond->events);
2275 LeaveCriticalSection(&cond->mutex);
2277 #endif
2278 void
2279 tor_threads_init(void)
2281 #if 0
2282 cond_event_tls_index = TlsAlloc();
2283 #endif
2284 set_main_thread();
2286 #endif
2288 #if defined(HAVE_MLOCKALL) && HAVE_DECL_MLOCKALL && defined(RLIMIT_MEMLOCK)
2289 /** Attempt to raise the current and max rlimit to infinity for our process.
2290 * This only needs to be done once and can probably only be done when we have
2291 * not already dropped privileges.
2293 static int
2294 tor_set_max_memlock(void)
2296 /* Future consideration for Windows is probably SetProcessWorkingSetSize
2297 * This is similar to setting the memory rlimit of RLIMIT_MEMLOCK
2298 * http://msdn.microsoft.com/en-us/library/ms686234(VS.85).aspx
2301 struct rlimit limit;
2302 int ret;
2304 /* Do we want to report current limits first? This is not really needed. */
2305 ret = getrlimit(RLIMIT_MEMLOCK, &limit);
2306 if (ret == -1) {
2307 log_warn(LD_GENERAL, "Could not get RLIMIT_MEMLOCK: %s", strerror(errno));
2308 return -1;
2311 /* RLIM_INFINITY is -1 on some platforms. */
2312 limit.rlim_cur = RLIM_INFINITY;
2313 limit.rlim_max = RLIM_INFINITY;
2315 ret = setrlimit(RLIMIT_MEMLOCK, &limit);
2316 if (ret == -1) {
2317 if (errno == EPERM) {
2318 log_warn(LD_GENERAL, "You appear to lack permissions to change memory "
2319 "limits. Are you root?");
2320 log_warn(LD_GENERAL, "Unable to raise RLIMIT_MEMLOCK: %s",
2321 strerror(errno));
2322 } else {
2323 log_warn(LD_GENERAL, "Could not raise RLIMIT_MEMLOCK: %s",
2324 strerror(errno));
2326 return -1;
2329 return 0;
2331 #endif
2333 /** Attempt to lock all current and all future memory pages.
2334 * This should only be called once and while we're privileged.
2335 * Like mlockall() we return 0 when we're successful and -1 when we're not.
2336 * Unlike mlockall() we return 1 if we've already attempted to lock memory.
2339 tor_mlockall(void)
2341 static int memory_lock_attempted = 0;
2343 if (memory_lock_attempted) {
2344 return 1;
2347 memory_lock_attempted = 1;
2350 * Future consideration for Windows may be VirtualLock
2351 * VirtualLock appears to implement mlock() but not mlockall()
2353 * http://msdn.microsoft.com/en-us/library/aa366895(VS.85).aspx
2356 #if defined(HAVE_MLOCKALL) && HAVE_DECL_MLOCKALL && defined(RLIMIT_MEMLOCK)
2357 if (tor_set_max_memlock() == 0) {
2358 /* Perhaps we only want to log this if we're in a verbose mode? */
2359 log_notice(LD_GENERAL, "RLIMIT_MEMLOCK is now set to RLIM_INFINITY.");
2362 if (mlockall(MCL_CURRENT|MCL_FUTURE) == 0) {
2363 log_notice(LD_GENERAL, "Insecure OS paging is effectively disabled.");
2364 return 0;
2365 } else {
2366 if (errno == ENOSYS) {
2367 /* Apple - it's 2009! I'm looking at you. Grrr. */
2368 log_notice(LD_GENERAL, "It appears that mlockall() is not available on "
2369 "your platform.");
2370 } else if (errno == EPERM) {
2371 log_notice(LD_GENERAL, "It appears that you lack the permissions to "
2372 "lock memory. Are you root?");
2374 log_notice(LD_GENERAL, "Unable to lock all current and future memory "
2375 "pages: %s", strerror(errno));
2376 return -1;
2378 #else
2379 log_warn(LD_GENERAL, "Unable to lock memory pages. mlockall() unsupported?");
2380 return -1;
2381 #endif
2384 /** Identity of the "main" thread */
2385 static unsigned long main_thread_id = -1;
2387 /** Start considering the current thread to be the 'main thread'. This has
2388 * no effect on anything besides in_main_thread(). */
2389 void
2390 set_main_thread(void)
2392 main_thread_id = tor_get_thread_id();
2394 /** Return true iff called from the main thread. */
2396 in_main_thread(void)
2398 return main_thread_id == tor_get_thread_id();
2402 * On Windows, WSAEWOULDBLOCK is not always correct: when you see it,
2403 * you need to ask the socket for its actual errno. Also, you need to
2404 * get your errors from WSAGetLastError, not errno. (If you supply a
2405 * socket of -1, we check WSAGetLastError, but don't correct
2406 * WSAEWOULDBLOCKs.)
2408 * The upshot of all of this is that when a socket call fails, you
2409 * should call tor_socket_errno <em>at most once</em> on the failing
2410 * socket to get the error.
2412 #if defined(MS_WINDOWS)
2414 tor_socket_errno(int sock)
2416 int optval, optvallen=sizeof(optval);
2417 int err = WSAGetLastError();
2418 if (err == WSAEWOULDBLOCK && sock >= 0) {
2419 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval, &optvallen))
2420 return err;
2421 if (optval)
2422 return optval;
2424 return err;
2426 #endif
2428 #if defined(MS_WINDOWS)
2429 #define E(code, s) { code, (s " [" #code " ]") }
2430 struct { int code; const char *msg; } windows_socket_errors[] = {
2431 E(WSAEINTR, "Interrupted function call"),
2432 E(WSAEACCES, "Permission denied"),
2433 E(WSAEFAULT, "Bad address"),
2434 E(WSAEINVAL, "Invalid argument"),
2435 E(WSAEMFILE, "Too many open files"),
2436 E(WSAEWOULDBLOCK, "Resource temporarily unavailable"),
2437 E(WSAEINPROGRESS, "Operation now in progress"),
2438 E(WSAEALREADY, "Operation already in progress"),
2439 E(WSAENOTSOCK, "Socket operation on nonsocket"),
2440 E(WSAEDESTADDRREQ, "Destination address required"),
2441 E(WSAEMSGSIZE, "Message too long"),
2442 E(WSAEPROTOTYPE, "Protocol wrong for socket"),
2443 E(WSAENOPROTOOPT, "Bad protocol option"),
2444 E(WSAEPROTONOSUPPORT, "Protocol not supported"),
2445 E(WSAESOCKTNOSUPPORT, "Socket type not supported"),
2446 /* What's the difference between NOTSUPP and NOSUPPORT? :) */
2447 E(WSAEOPNOTSUPP, "Operation not supported"),
2448 E(WSAEPFNOSUPPORT, "Protocol family not supported"),
2449 E(WSAEAFNOSUPPORT, "Address family not supported by protocol family"),
2450 E(WSAEADDRINUSE, "Address already in use"),
2451 E(WSAEADDRNOTAVAIL, "Cannot assign requested address"),
2452 E(WSAENETDOWN, "Network is down"),
2453 E(WSAENETUNREACH, "Network is unreachable"),
2454 E(WSAENETRESET, "Network dropped connection on reset"),
2455 E(WSAECONNABORTED, "Software caused connection abort"),
2456 E(WSAECONNRESET, "Connection reset by peer"),
2457 E(WSAENOBUFS, "No buffer space available"),
2458 E(WSAEISCONN, "Socket is already connected"),
2459 E(WSAENOTCONN, "Socket is not connected"),
2460 E(WSAESHUTDOWN, "Cannot send after socket shutdown"),
2461 E(WSAETIMEDOUT, "Connection timed out"),
2462 E(WSAECONNREFUSED, "Connection refused"),
2463 E(WSAEHOSTDOWN, "Host is down"),
2464 E(WSAEHOSTUNREACH, "No route to host"),
2465 E(WSAEPROCLIM, "Too many processes"),
2466 /* Yes, some of these start with WSA, not WSAE. No, I don't know why. */
2467 E(WSASYSNOTREADY, "Network subsystem is unavailable"),
2468 E(WSAVERNOTSUPPORTED, "Winsock.dll out of range"),
2469 E(WSANOTINITIALISED, "Successful WSAStartup not yet performed"),
2470 E(WSAEDISCON, "Graceful shutdown now in progress"),
2471 #ifdef WSATYPE_NOT_FOUND
2472 E(WSATYPE_NOT_FOUND, "Class type not found"),
2473 #endif
2474 E(WSAHOST_NOT_FOUND, "Host not found"),
2475 E(WSATRY_AGAIN, "Nonauthoritative host not found"),
2476 E(WSANO_RECOVERY, "This is a nonrecoverable error"),
2477 E(WSANO_DATA, "Valid name, no data record of requested type)"),
2479 /* There are some more error codes whose numeric values are marked
2480 * <b>OS dependent</b>. They start with WSA_, apparently for the same
2481 * reason that practitioners of some craft traditions deliberately
2482 * introduce imperfections into their baskets and rugs "to allow the
2483 * evil spirits to escape." If we catch them, then our binaries
2484 * might not report consistent results across versions of Windows.
2485 * Thus, I'm going to let them all fall through.
2487 { -1, NULL },
2489 /** There does not seem to be a strerror equivalent for Winsock errors.
2490 * Naturally, we have to roll our own.
2492 const char *
2493 tor_socket_strerror(int e)
2495 int i;
2496 for (i=0; windows_socket_errors[i].code >= 0; ++i) {
2497 if (e == windows_socket_errors[i].code)
2498 return windows_socket_errors[i].msg;
2500 return strerror(e);
2502 #endif
2504 /** Called before we make any calls to network-related functions.
2505 * (Some operating systems require their network libraries to be
2506 * initialized.) */
2508 network_init(void)
2510 #ifdef MS_WINDOWS
2511 /* This silly exercise is necessary before windows will allow
2512 * gethostbyname to work. */
2513 WSADATA WSAData;
2514 int r;
2515 r = WSAStartup(0x101,&WSAData);
2516 if (r) {
2517 log_warn(LD_NET,"Error initializing windows network layer: code was %d",r);
2518 return -1;
2520 /* WSAData.iMaxSockets might show the max sockets we're allowed to use.
2521 * We might use it to complain if we're trying to be a server but have
2522 * too few sockets available. */
2523 #endif
2524 return 0;
2527 #ifdef MS_WINDOWS
2528 /** Return a newly allocated string describing the windows system error code
2529 * <b>err</b>. Note that error codes are different from errno. Error codes
2530 * come from GetLastError() when a winapi call fails. errno is set only when
2531 * ANSI functions fail. Whee. */
2532 char *
2533 format_win32_error(DWORD err)
2535 LPVOID str = NULL;
2536 char abuf[1024] = {0};
2537 char *result;
2539 /* Somebody once decided that this interface was better than strerror(). */
2540 FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
2541 FORMAT_MESSAGE_FROM_SYSTEM |
2542 FORMAT_MESSAGE_IGNORE_INSERTS,
2543 NULL, err,
2544 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
2545 (LPTSTR) &str,
2546 0, NULL);
2548 if (str) {
2549 wcstombs(abuf,str,1024);
2550 result = tor_strdup((char*)abuf);
2551 LocalFree(str); /* LocalFree != free() */
2552 } else {
2553 result = tor_strdup("<unformattable error>");
2555 return result;
2557 #endif