Tweak the bugfix for 2183 a bit more.
[tor/rransom.git] / src / common / compat.c
blob20394b4c5dcb921045ca1f335f85c73748a1b147
1 /* Copyright (c) 2003-2004, Roger Dingledine
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2010, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
6 /**
7 * \file compat.c
8 * \brief Wrappers to make calls more portable. This code defines
9 * functions such as tor_malloc, tor_snprintf, get/set various data types,
10 * renaming, setting socket options, switching user IDs. It is basically
11 * where the non-portable items are conditionally included depending on
12 * the platform.
13 **/
15 /* This is required on rh7 to make strptime not complain.
16 * We also need it to make memmem get defined (where available)
18 #define _GNU_SOURCE
20 #include "compat.h"
22 #ifdef MS_WINDOWS
23 #include <process.h>
24 #include <windows.h>
25 #include <sys/locking.h>
26 #endif
28 #ifdef HAVE_UNAME
29 #include <sys/utsname.h>
30 #endif
31 #ifdef HAVE_UNISTD_H
32 #include <unistd.h>
33 #endif
34 #ifdef HAVE_SYS_FCNTL_H
35 #include <sys/fcntl.h>
36 #endif
37 #ifdef HAVE_PWD_H
38 #include <pwd.h>
39 #endif
40 #ifdef HAVE_GRP_H
41 #include <grp.h>
42 #endif
43 #ifdef HAVE_FCNTL_H
44 #include <fcntl.h>
45 #endif
46 #ifdef HAVE_ERRNO_H
47 #include <errno.h>
48 #endif
49 #ifdef HAVE_ARPA_INET_H
50 #include <arpa/inet.h>
51 #endif
53 #ifndef HAVE_GETTIMEOFDAY
54 #ifdef HAVE_FTIME
55 #include <sys/timeb.h>
56 #endif
57 #endif
59 #ifdef HAVE_NETDB_H
60 #include <netdb.h>
61 #endif
62 #ifdef HAVE_SYS_PARAM_H
63 #include <sys/param.h> /* FreeBSD needs this to know what version it is */
64 #endif
65 #include <stdio.h>
66 #include <stdlib.h>
67 #include <assert.h>
68 #ifdef HAVE_SIGNAL_H
69 #include <signal.h>
70 #endif
71 #ifdef HAVE_UTIME_H
72 #include <utime.h>
73 #endif
74 #ifdef HAVE_SYS_UTIME_H
75 #include <sys/utime.h>
76 #endif
77 #ifdef HAVE_SYS_MMAN_H
78 #include <sys/mman.h>
79 #endif
80 #ifdef HAVE_SYS_SYSLIMITS_H
81 #include <sys/syslimits.h>
82 #endif
83 #ifdef HAVE_SYS_FILE_H
84 #include <sys/file.h>
85 #endif
86 #if defined(HAVE_SYS_PRCTL_H) && defined(__linux__)
87 /* Only use the linux prctl; the IRIX prctl is totally different */
88 #include <sys/prctl.h>
89 #endif
91 #include "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 size = filesize = (size_t) lseek(fd, 0, SEEK_END);
130 lseek(fd, 0, SEEK_SET);
131 /* ensure page alignment */
132 page_size = getpagesize();
133 size += (size%page_size) ? page_size-(size%page_size) : 0;
135 if (!size) {
136 /* Zero-length file. If we call mmap on it, it will succeed but
137 * return NULL, and bad things will happen. So just fail. */
138 log_info(LD_FS,"File \"%s\" is empty. Ignoring.",filename);
139 errno = ERANGE;
140 close(fd);
141 return NULL;
144 string = mmap(0, size, PROT_READ, MAP_PRIVATE, fd, 0);
145 close(fd);
146 if (string == MAP_FAILED) {
147 int save_errno = errno;
148 log_warn(LD_FS,"Could not mmap file \"%s\": %s", filename,
149 strerror(errno));
150 errno = save_errno;
151 return NULL;
154 res = tor_malloc_zero(sizeof(tor_mmap_t));
155 res->data = string;
156 res->size = filesize;
157 res->mapping_size = size;
159 return res;
161 /** Release storage held for a memory mapping. */
162 void
163 tor_munmap_file(tor_mmap_t *handle)
165 munmap((char*)handle->data, handle->mapping_size);
166 tor_free(handle);
168 #elif defined(MS_WINDOWS)
169 tor_mmap_t *
170 tor_mmap_file(const char *filename)
172 TCHAR tfilename[MAX_PATH]= {0};
173 tor_mmap_t *res = tor_malloc_zero(sizeof(tor_mmap_t));
174 int empty = 0;
175 res->file_handle = INVALID_HANDLE_VALUE;
176 res->mmap_handle = NULL;
177 #ifdef UNICODE
178 mbstowcs(tfilename,filename,MAX_PATH);
179 #else
180 strlcpy(tfilename,filename,MAX_PATH);
181 #endif
182 res->file_handle = CreateFile(tfilename,
183 GENERIC_READ, FILE_SHARE_READ,
184 NULL,
185 OPEN_EXISTING,
186 FILE_ATTRIBUTE_NORMAL,
189 if (res->file_handle == INVALID_HANDLE_VALUE)
190 goto win_err;
192 res->size = GetFileSize(res->file_handle, NULL);
194 if (res->size == 0) {
195 log_info(LD_FS,"File \"%s\" is empty. Ignoring.",filename);
196 empty = 1;
197 goto err;
200 res->mmap_handle = CreateFileMapping(res->file_handle,
201 NULL,
202 PAGE_READONLY,
203 #if SIZEOF_SIZE_T > 4
204 (res->base.size >> 32),
205 #else
207 #endif
208 (res->size & 0xfffffffful),
209 NULL);
210 if (res->mmap_handle == NULL)
211 goto win_err;
212 res->data = (char*) MapViewOfFile(res->mmap_handle,
213 FILE_MAP_READ,
214 0, 0, 0);
215 if (!res->data)
216 goto win_err;
218 return res;
219 win_err: {
220 DWORD e = GetLastError();
221 int severity = (e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND) ?
222 LOG_INFO : LOG_WARN;
223 char *msg = format_win32_error(e);
224 log_fn(severity, LD_FS, "Couldn't mmap file \"%s\": %s", filename, msg);
225 tor_free(msg);
226 if (e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND)
227 errno = ENOENT;
228 else
229 errno = EINVAL;
231 err:
232 if (empty)
233 errno = ERANGE;
234 tor_munmap_file(res);
235 return NULL;
237 void
238 tor_munmap_file(tor_mmap_t *handle)
240 if (handle->data)
241 /* This is an ugly cast, but without it, "data" in struct tor_mmap_t would
242 have to be redefined as non-const. */
243 UnmapViewOfFile( (LPVOID) handle->data);
245 if (handle->mmap_handle != NULL)
246 CloseHandle(handle->mmap_handle);
247 if (handle->file_handle != INVALID_HANDLE_VALUE)
248 CloseHandle(handle->file_handle);
249 tor_free(handle);
251 #else
252 tor_mmap_t *
253 tor_mmap_file(const char *filename)
255 struct stat st;
256 char *res = read_file_to_str(filename, RFTS_BIN|RFTS_IGNORE_MISSING, &st);
257 tor_mmap_t *handle;
258 if (! res)
259 return NULL;
260 handle = tor_malloc_zero(sizeof(tor_mmap_t));
261 handle->data = res;
262 handle->size = st.st_size;
263 return handle;
265 void
266 tor_munmap_file(tor_mmap_t *handle)
268 char *d = (char*)handle->data;
269 tor_free(d);
270 memset(handle, 0, sizeof(tor_mmap_t));
271 tor_free(handle);
273 #endif
275 /** Replacement for snprintf. Differs from platform snprintf in two
276 * ways: First, always NUL-terminates its output. Second, always
277 * returns -1 if the result is truncated. (Note that this return
278 * behavior does <i>not</i> conform to C99; it just happens to be
279 * easier to emulate "return -1" with conformant implementations than
280 * it is to emulate "return number that would be written" with
281 * non-conformant implementations.) */
283 tor_snprintf(char *str, size_t size, const char *format, ...)
285 va_list ap;
286 int r;
287 va_start(ap,format);
288 r = tor_vsnprintf(str,size,format,ap);
289 va_end(ap);
290 return r;
293 /** Replacement for vsnprintf; behavior differs as tor_snprintf differs from
294 * snprintf.
297 tor_vsnprintf(char *str, size_t size, const char *format, va_list args)
299 int r;
300 if (size == 0)
301 return -1; /* no place for the NUL */
302 if (size > SSIZE_T_MAX-16)
303 return -1;
304 #ifdef MS_WINDOWS
305 r = _vsnprintf(str, size, format, args);
306 #else
307 r = vsnprintf(str, size, format, args);
308 #endif
309 str[size-1] = '\0';
310 if (r < 0 || r >= (ssize_t)size)
311 return -1;
312 return r;
316 * Portable asprintf implementation. Does a printf() into a newly malloc'd
317 * string. Sets *<b>strp</b> to this string, and returns its length (not
318 * including the terminating NUL character).
320 * You can treat this function as if its implementation were something like
321 <pre>
322 char buf[_INFINITY_];
323 tor_snprintf(buf, sizeof(buf), fmt, args);
324 *strp = tor_strdup(buf);
325 return strlen(*strp):
326 </pre>
327 * Where _INFINITY_ is an imaginary constant so big that any string can fit
328 * into it.
331 tor_asprintf(char **strp, const char *fmt, ...)
333 int r;
334 va_list args;
335 va_start(args, fmt);
336 r = tor_vasprintf(strp, fmt, args);
337 va_end(args);
338 if (!*strp || r < 0) {
339 log_err(LD_BUG, "Internal error in asprintf");
340 tor_assert(0);
342 return r;
346 * Portable vasprintf implementation. Does a printf() into a newly malloc'd
347 * string. Differs from regular vasprintf in the same ways that
348 * tor_asprintf() differs from regular asprintf.
351 tor_vasprintf(char **strp, const char *fmt, va_list args)
353 /* use a temporary variable in case *strp is in args. */
354 char *strp_tmp=NULL;
355 #ifdef HAVE_VASPRINTF
356 /* If the platform gives us one, use it. */
357 int r = vasprintf(&strp_tmp, fmt, args);
358 if (r < 0)
359 *strp = NULL;
360 else
361 *strp = strp_tmp;
362 return r;
363 #elif defined(_MSC_VER)
364 /* On Windows, _vsnprintf won't tell us the length of the string if it
365 * overflows, so we need to use _vcsprintf to tell how much to allocate */
366 int len, r;
367 char *res;
368 len = _vscprintf(fmt, args);
369 if (len < 0) {
370 *strp = NULL;
371 return -1;
373 strp_tmp = tor_malloc(len + 1);
374 r = _vsnprintf(strp_tmp, len+1, fmt, args);
375 if (r != len) {
376 tor_free(strp_tmp);
377 *strp = NULL;
378 return -1;
380 *strp = strp_tmp;
381 return len;
382 #else
383 /* Everywhere else, we have a decent vsnprintf that tells us how many
384 * characters we need. We give it a try on a short buffer first, since
385 * it might be nice to avoid the second vsnprintf call.
387 char buf[128];
388 int len, r;
389 va_list tmp_args;
390 va_copy(tmp_args, args);
391 len = vsnprintf(buf, sizeof(buf), fmt, tmp_args);
392 va_end(tmp_args);
393 if (len < (int)sizeof(buf)) {
394 *strp = tor_strdup(buf);
395 return len;
397 strp_tmp = tor_malloc(len+1);
398 r = vsnprintf(strp_tmp, len+1, fmt, args);
399 if (r != len) {
400 tor_free(strp_tmp);
401 *strp = NULL;
402 return -1;
404 *strp = strp_tmp;
405 return len;
406 #endif
409 /** Given <b>hlen</b> bytes at <b>haystack</b> and <b>nlen</b> bytes at
410 * <b>needle</b>, return a pointer to the first occurrence of the needle
411 * within the haystack, or NULL if there is no such occurrence.
413 * Requires that nlen be greater than zero.
415 const void *
416 tor_memmem(const void *_haystack, size_t hlen,
417 const void *_needle, size_t nlen)
419 #if defined(HAVE_MEMMEM) && (!defined(__GNUC__) || __GNUC__ >= 2)
420 tor_assert(nlen);
421 return memmem(_haystack, hlen, _needle, nlen);
422 #else
423 /* This isn't as fast as the GLIBC implementation, but it doesn't need to
424 * be. */
425 const char *p, *end;
426 const char *haystack = (const char*)_haystack;
427 const char *needle = (const char*)_needle;
428 char first;
429 tor_assert(nlen);
431 p = haystack;
432 end = haystack + hlen;
433 first = *(const char*)needle;
434 while ((p = memchr(p, first, end-p))) {
435 if (p+nlen > end)
436 return NULL;
437 if (!memcmp(p, needle, nlen))
438 return p;
439 ++p;
441 return NULL;
442 #endif
445 /* Tables to implement ctypes-replacement TOR_IS*() functions. Each table
446 * has 256 bits to look up whether a character is in some set or not. This
447 * fails on non-ASCII platforms, but it is hard to find a platform whose
448 * character set is not a superset of ASCII nowadays. */
449 const uint32_t TOR_ISALPHA_TABLE[8] =
450 { 0, 0, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
451 const uint32_t TOR_ISALNUM_TABLE[8] =
452 { 0, 0x3ff0000, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
453 const uint32_t TOR_ISSPACE_TABLE[8] = { 0x3e00, 0x1, 0, 0, 0, 0, 0, 0 };
454 const uint32_t TOR_ISXDIGIT_TABLE[8] =
455 { 0, 0x3ff0000, 0x7e, 0x7e, 0, 0, 0, 0 };
456 const uint32_t TOR_ISDIGIT_TABLE[8] = { 0, 0x3ff0000, 0, 0, 0, 0, 0, 0 };
457 const uint32_t TOR_ISPRINT_TABLE[8] =
458 { 0, 0xffffffff, 0xffffffff, 0x7fffffff, 0, 0, 0, 0x0 };
459 const uint32_t TOR_ISUPPER_TABLE[8] = { 0, 0, 0x7fffffe, 0, 0, 0, 0, 0 };
460 const uint32_t TOR_ISLOWER_TABLE[8] = { 0, 0, 0, 0x7fffffe, 0, 0, 0, 0 };
461 /* Upper-casing and lowercasing tables to map characters to upper/lowercase
462 * equivalents. */
463 const char TOR_TOUPPER_TABLE[256] = {
464 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
465 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
466 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
467 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
468 64,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,91,92,93,94,95,
470 96,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
471 80,81,82,83,84,85,86,87,88,89,90,123,124,125,126,127,
472 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
473 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
474 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
475 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
476 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
477 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
478 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
479 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
481 const char TOR_TOLOWER_TABLE[256] = {
482 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
483 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
484 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
485 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
486 64,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,91,92,93,94,95,
488 96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
489 112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
490 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
491 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
492 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
493 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
494 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
495 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
496 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
497 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
500 /** Implementation of strtok_r for platforms whose coders haven't figured out
501 * how to write one. Hey guys! You can use this code here for free! */
502 char *
503 tor_strtok_r_impl(char *str, const char *sep, char **lasts)
505 char *cp, *start;
506 if (str)
507 start = cp = *lasts = str;
508 else if (!*lasts)
509 return NULL;
510 else
511 start = cp = *lasts;
513 tor_assert(*sep);
514 if (sep[1]) {
515 while (*cp && !strchr(sep, *cp))
516 ++cp;
517 } else {
518 tor_assert(strlen(sep) == 1);
519 cp = strchr(cp, *sep);
522 if (!cp || !*cp) {
523 *lasts = NULL;
524 } else {
525 *cp++ = '\0';
526 *lasts = cp;
528 return start;
531 #ifdef MS_WINDOWS
532 /** Take a filename and return a pointer to its final element. This
533 * function is called on __FILE__ to fix a MSVC nit where __FILE__
534 * contains the full path to the file. This is bad, because it
535 * confuses users to find the home directory of the person who
536 * compiled the binary in their warning messages.
538 const char *
539 tor_fix_source_file(const char *fname)
541 const char *cp1, *cp2, *r;
542 cp1 = strrchr(fname, '/');
543 cp2 = strrchr(fname, '\\');
544 if (cp1 && cp2) {
545 r = (cp1<cp2)?(cp2+1):(cp1+1);
546 } else if (cp1) {
547 r = cp1+1;
548 } else if (cp2) {
549 r = cp2+1;
550 } else {
551 r = fname;
553 return r;
555 #endif
558 * Read a 16-bit value beginning at <b>cp</b>. Equivalent to
559 * *(uint16_t*)(cp), but will not cause segfaults on platforms that forbid
560 * unaligned memory access.
562 uint16_t
563 get_uint16(const char *cp)
565 uint16_t v;
566 memcpy(&v,cp,2);
567 return v;
570 * Read a 32-bit value beginning at <b>cp</b>. Equivalent to
571 * *(uint32_t*)(cp), but will not cause segfaults on platforms that forbid
572 * unaligned memory access.
574 uint32_t
575 get_uint32(const char *cp)
577 uint32_t v;
578 memcpy(&v,cp,4);
579 return v;
582 * Read a 64-bit value beginning at <b>cp</b>. Equivalent to
583 * *(uint64_t*)(cp), but will not cause segfaults on platforms that forbid
584 * unaligned memory access.
586 uint64_t
587 get_uint64(const char *cp)
589 uint64_t v;
590 memcpy(&v,cp,8);
591 return v;
595 * Set a 16-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
596 * *(uint16_t*)(cp) = v, but will not cause segfaults on platforms that forbid
597 * unaligned memory access. */
598 void
599 set_uint16(char *cp, uint16_t v)
601 memcpy(cp,&v,2);
604 * Set a 32-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
605 * *(uint32_t*)(cp) = v, but will not cause segfaults on platforms that forbid
606 * unaligned memory access. */
607 void
608 set_uint32(char *cp, uint32_t v)
610 memcpy(cp,&v,4);
613 * Set a 64-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
614 * *(uint64_t*)(cp) = v, but will not cause segfaults on platforms that forbid
615 * unaligned memory access. */
616 void
617 set_uint64(char *cp, uint64_t v)
619 memcpy(cp,&v,8);
623 * Rename the file <b>from</b> to the file <b>to</b>. On Unix, this is
624 * the same as rename(2). On windows, this removes <b>to</b> first if
625 * it already exists.
626 * Returns 0 on success. Returns -1 and sets errno on failure.
629 replace_file(const char *from, const char *to)
631 #ifndef MS_WINDOWS
632 return rename(from,to);
633 #else
634 switch (file_status(to))
636 case FN_NOENT:
637 break;
638 case FN_FILE:
639 if (unlink(to)) return -1;
640 break;
641 case FN_ERROR:
642 return -1;
643 case FN_DIR:
644 errno = EISDIR;
645 return -1;
647 return rename(from,to);
648 #endif
651 /** Change <b>fname</b>'s modification time to now. */
653 touch_file(const char *fname)
655 if (utime(fname, NULL)!=0)
656 return -1;
657 return 0;
660 /** Represents a lockfile on which we hold the lock. */
661 struct tor_lockfile_t {
662 char *filename;
663 int fd;
666 /** Try to get a lock on the lockfile <b>filename</b>, creating it as
667 * necessary. If someone else has the lock and <b>blocking</b> is true,
668 * wait until the lock is available. Otherwise return immediately whether
669 * we succeeded or not.
671 * Set *<b>locked_out</b> to true if somebody else had the lock, and to false
672 * otherwise.
674 * Return a <b>tor_lockfile_t</b> on success, NULL on failure.
676 * (Implementation note: because we need to fall back to fcntl on some
677 * platforms, these locks are per-process, not per-thread. If you want
678 * to do in-process locking, use tor_mutex_t like a normal person.)
680 tor_lockfile_t *
681 tor_lockfile_lock(const char *filename, int blocking, int *locked_out)
683 tor_lockfile_t *result;
684 int fd;
685 *locked_out = 0;
687 log_info(LD_FS, "Locking \"%s\"", filename);
688 fd = open(filename, O_RDWR|O_CREAT|O_TRUNC, 0600);
689 if (fd < 0) {
690 log_warn(LD_FS,"Couldn't open \"%s\" for locking: %s", filename,
691 strerror(errno));
692 return NULL;
695 #ifdef WIN32
696 _lseek(fd, 0, SEEK_SET);
697 if (_locking(fd, blocking ? _LK_LOCK : _LK_NBLCK, 1) < 0) {
698 if (errno != EDEADLOCK)
699 log_warn(LD_FS,"Couldn't lock \"%s\": %s", filename, strerror(errno));
700 else
701 *locked_out = 1;
702 close(fd);
703 return NULL;
705 #elif defined(HAVE_FLOCK)
706 if (flock(fd, LOCK_EX|(blocking ? 0 : LOCK_NB)) < 0) {
707 if (errno != EWOULDBLOCK)
708 log_warn(LD_FS,"Couldn't lock \"%s\": %s", filename, strerror(errno));
709 else
710 *locked_out = 1;
711 close(fd);
712 return NULL;
714 #else
716 struct flock lock;
717 memset(&lock, 0, sizeof(lock));
718 lock.l_type = F_WRLCK;
719 lock.l_whence = SEEK_SET;
720 if (fcntl(fd, blocking ? F_SETLKW : F_SETLK, &lock) < 0) {
721 if (errno != EACCES && errno != EAGAIN)
722 log_warn(LD_FS, "Couldn't lock \"%s\": %s", filename, strerror(errno));
723 else
724 *locked_out = 1;
725 close(fd);
726 return NULL;
729 #endif
731 result = tor_malloc(sizeof(tor_lockfile_t));
732 result->filename = tor_strdup(filename);
733 result->fd = fd;
734 return result;
737 /** Release the lock held as <b>lockfile</b>. */
738 void
739 tor_lockfile_unlock(tor_lockfile_t *lockfile)
741 tor_assert(lockfile);
743 log_info(LD_FS, "Unlocking \"%s\"", lockfile->filename);
744 #ifdef WIN32
745 _lseek(lockfile->fd, 0, SEEK_SET);
746 if (_locking(lockfile->fd, _LK_UNLCK, 1) < 0) {
747 log_warn(LD_FS,"Error unlocking \"%s\": %s", lockfile->filename,
748 strerror(errno));
750 #elif defined(HAVE_FLOCK)
751 if (flock(lockfile->fd, LOCK_UN) < 0) {
752 log_warn(LD_FS, "Error unlocking \"%s\": %s", lockfile->filename,
753 strerror(errno));
755 #else
756 /* Closing the lockfile is sufficient. */
757 #endif
759 close(lockfile->fd);
760 lockfile->fd = -1;
761 tor_free(lockfile->filename);
762 tor_free(lockfile);
765 /* Some old versions of Unix didn't define constants for these values,
766 * and instead expect you to say 0, 1, or 2. */
767 #ifndef SEEK_CUR
768 #define SEEK_CUR 1
769 #endif
770 #ifndef SEEK_END
771 #define SEEK_END 2
772 #endif
774 /** Return the position of <b>fd</b> with respect to the start of the file. */
775 off_t
776 tor_fd_getpos(int fd)
778 #ifdef WIN32
779 return (off_t) _lseek(fd, 0, SEEK_CUR);
780 #else
781 return (off_t) lseek(fd, 0, SEEK_CUR);
782 #endif
785 /** Move <b>fd</b> to the end of the file. Return -1 on error, 0 on success. */
787 tor_fd_seekend(int fd)
789 #ifdef WIN32
790 return _lseek(fd, 0, SEEK_END) < 0 ? -1 : 0;
791 #else
792 return lseek(fd, 0, SEEK_END) < 0 ? -1 : 0;
793 #endif
796 #undef DEBUG_SOCKET_COUNTING
797 #ifdef DEBUG_SOCKET_COUNTING
798 /** A bitarray of all fds that should be passed to tor_socket_close(). Only
799 * used if DEBUG_SOCKET_COUNTING is defined. */
800 static bitarray_t *open_sockets = NULL;
801 /** The size of <b>open_sockets</b>, in bits. */
802 static int max_socket = -1;
803 #endif
805 /** Count of number of sockets currently open. (Undercounts sockets opened by
806 * eventdns and libevent.) */
807 static int n_sockets_open = 0;
809 /** Mutex to protect open_sockets, max_socket, and n_sockets_open. */
810 static tor_mutex_t *socket_accounting_mutex = NULL;
812 static INLINE void
813 socket_accounting_lock(void)
815 if (PREDICT_UNLIKELY(!socket_accounting_mutex))
816 socket_accounting_mutex = tor_mutex_new();
817 tor_mutex_acquire(socket_accounting_mutex);
820 static INLINE void
821 socket_accounting_unlock(void)
823 tor_mutex_release(socket_accounting_mutex);
826 /** As close(), but guaranteed to work for sockets across platforms (including
827 * Windows, where close()ing a socket doesn't work. Returns 0 on success, -1
828 * on failure. */
830 tor_close_socket(int s)
832 int r = 0;
834 /* On Windows, you have to call close() on fds returned by open(),
835 * and closesocket() on fds returned by socket(). On Unix, everything
836 * gets close()'d. We abstract this difference by always using
837 * tor_close_socket to close sockets, and always using close() on
838 * files.
840 #if defined(MS_WINDOWS)
841 r = closesocket(s);
842 #else
843 r = close(s);
844 #endif
846 socket_accounting_lock();
847 #ifdef DEBUG_SOCKET_COUNTING
848 if (s > max_socket || ! bitarray_is_set(open_sockets, s)) {
849 log_warn(LD_BUG, "Closing a socket (%d) that wasn't returned by tor_open_"
850 "socket(), or that was already closed or something.", s);
851 } else {
852 tor_assert(open_sockets && s <= max_socket);
853 bitarray_clear(open_sockets, s);
855 #endif
856 if (r == 0) {
857 --n_sockets_open;
858 } else {
859 int err = tor_socket_errno(-1);
860 log_info(LD_NET, "Close returned an error: %s", tor_socket_strerror(err));
861 #ifdef WIN32
862 if (err != WSAENOTSOCK)
863 --n_sockets_open;
864 #else
865 if (err != EBADF)
866 --n_sockets_open;
867 #endif
868 r = -1;
871 if (n_sockets_open < 0)
872 log_warn(LD_BUG, "Our socket count is below zero: %d. Please submit a "
873 "bug report.", n_sockets_open);
874 socket_accounting_unlock();
875 return r;
878 #ifdef DEBUG_SOCKET_COUNTING
879 /** Helper: if DEBUG_SOCKET_COUNTING is enabled, remember that <b>s</b> is
880 * now an open socket. */
881 static INLINE void
882 mark_socket_open(int s)
884 if (s > max_socket) {
885 if (max_socket == -1) {
886 open_sockets = bitarray_init_zero(s+128);
887 max_socket = s+128;
888 } else {
889 open_sockets = bitarray_expand(open_sockets, max_socket, s+128);
890 max_socket = s+128;
893 if (bitarray_is_set(open_sockets, s)) {
894 log_warn(LD_BUG, "I thought that %d was already open, but socket() just "
895 "gave it to me!", s);
897 bitarray_set(open_sockets, s);
899 #else
900 #define mark_socket_open(s) STMT_NIL
901 #endif
903 /** As socket(), but counts the number of open sockets. */
905 tor_open_socket(int domain, int type, int protocol)
907 int s = socket(domain, type, protocol);
908 if (s >= 0) {
909 socket_accounting_lock();
910 ++n_sockets_open;
911 mark_socket_open(s);
912 socket_accounting_unlock();
914 return s;
917 /** As socket(), but counts the number of open sockets. */
919 tor_accept_socket(int sockfd, struct sockaddr *addr, socklen_t *len)
921 int s = accept(sockfd, addr, len);
922 if (s >= 0) {
923 socket_accounting_lock();
924 ++n_sockets_open;
925 mark_socket_open(s);
926 socket_accounting_unlock();
928 return s;
931 /** Return the number of sockets we currently have opened. */
933 get_n_open_sockets(void)
935 int n;
936 socket_accounting_lock();
937 n = n_sockets_open;
938 socket_accounting_unlock();
939 return n;
942 /** Turn <b>socket</b> into a nonblocking socket.
944 void
945 set_socket_nonblocking(int socket)
947 #if defined(MS_WINDOWS)
948 unsigned long nonblocking = 1;
949 ioctlsocket(socket, FIONBIO, (unsigned long*) &nonblocking);
950 #else
951 fcntl(socket, F_SETFL, O_NONBLOCK);
952 #endif
956 * Allocate a pair of connected sockets. (Like socketpair(family,
957 * type,protocol,fd), but works on systems that don't have
958 * socketpair.)
960 * Currently, only (AF_UNIX, SOCK_STREAM, 0) sockets are supported.
962 * Note that on systems without socketpair, this call will fail if
963 * localhost is inaccessible (for example, if the networking
964 * stack is down). And even if it succeeds, the socket pair will not
965 * be able to read while localhost is down later (the socket pair may
966 * even close, depending on OS-specific timeouts).
968 * Returns 0 on success and -errno on failure; do not rely on the value
969 * of errno or WSAGetLastError().
971 /* It would be nicer just to set errno, but that won't work for windows. */
973 tor_socketpair(int family, int type, int protocol, int fd[2])
975 //don't use win32 socketpairs (they are always bad)
976 #if defined(HAVE_SOCKETPAIR) && !defined(MS_WINDOWS)
977 int r;
978 r = socketpair(family, type, protocol, fd);
979 if (r == 0) {
980 socket_accounting_lock();
981 if (fd[0] >= 0) {
982 ++n_sockets_open;
983 mark_socket_open(fd[0]);
985 if (fd[1] >= 0) {
986 ++n_sockets_open;
987 mark_socket_open(fd[1]);
989 socket_accounting_unlock();
991 return r < 0 ? -errno : r;
992 #else
993 /* This socketpair does not work when localhost is down. So
994 * it's really not the same thing at all. But it's close enough
995 * for now, and really, when localhost is down sometimes, we
996 * have other problems too.
998 int listener = -1;
999 int connector = -1;
1000 int acceptor = -1;
1001 struct sockaddr_in listen_addr;
1002 struct sockaddr_in connect_addr;
1003 int size;
1004 int saved_errno = -1;
1006 if (protocol
1007 #ifdef AF_UNIX
1008 || family != AF_UNIX
1009 #endif
1011 #ifdef MS_WINDOWS
1012 return -WSAEAFNOSUPPORT;
1013 #else
1014 return -EAFNOSUPPORT;
1015 #endif
1017 if (!fd) {
1018 return -EINVAL;
1021 listener = tor_open_socket(AF_INET, type, 0);
1022 if (listener < 0)
1023 return -tor_socket_errno(-1);
1024 memset(&listen_addr, 0, sizeof(listen_addr));
1025 listen_addr.sin_family = AF_INET;
1026 listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
1027 listen_addr.sin_port = 0; /* kernel chooses port. */
1028 if (bind(listener, (struct sockaddr *) &listen_addr, sizeof (listen_addr))
1029 == -1)
1030 goto tidy_up_and_fail;
1031 if (listen(listener, 1) == -1)
1032 goto tidy_up_and_fail;
1034 connector = tor_open_socket(AF_INET, type, 0);
1035 if (connector < 0)
1036 goto tidy_up_and_fail;
1037 /* We want to find out the port number to connect to. */
1038 size = sizeof(connect_addr);
1039 if (getsockname(listener, (struct sockaddr *) &connect_addr, &size) == -1)
1040 goto tidy_up_and_fail;
1041 if (size != sizeof (connect_addr))
1042 goto abort_tidy_up_and_fail;
1043 if (connect(connector, (struct sockaddr *) &connect_addr,
1044 sizeof(connect_addr)) == -1)
1045 goto tidy_up_and_fail;
1047 size = sizeof(listen_addr);
1048 acceptor = tor_accept_socket(listener,
1049 (struct sockaddr *) &listen_addr, &size);
1050 if (acceptor < 0)
1051 goto tidy_up_and_fail;
1052 if (size != sizeof(listen_addr))
1053 goto abort_tidy_up_and_fail;
1054 tor_close_socket(listener);
1055 /* Now check we are talking to ourself by matching port and host on the
1056 two sockets. */
1057 if (getsockname(connector, (struct sockaddr *) &connect_addr, &size) == -1)
1058 goto tidy_up_and_fail;
1059 if (size != sizeof (connect_addr)
1060 || listen_addr.sin_family != connect_addr.sin_family
1061 || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
1062 || listen_addr.sin_port != connect_addr.sin_port) {
1063 goto abort_tidy_up_and_fail;
1065 fd[0] = connector;
1066 fd[1] = acceptor;
1068 return 0;
1070 abort_tidy_up_and_fail:
1071 #ifdef MS_WINDOWS
1072 saved_errno = WSAECONNABORTED;
1073 #else
1074 saved_errno = ECONNABORTED; /* I hope this is portable and appropriate. */
1075 #endif
1076 tidy_up_and_fail:
1077 if (saved_errno < 0)
1078 saved_errno = errno;
1079 if (listener != -1)
1080 tor_close_socket(listener);
1081 if (connector != -1)
1082 tor_close_socket(connector);
1083 if (acceptor != -1)
1084 tor_close_socket(acceptor);
1085 return -saved_errno;
1086 #endif
1089 #define ULIMIT_BUFFER 32 /* keep 32 extra fd's beyond _ConnLimit */
1091 /** Learn the maximum allowed number of file descriptors. (Some systems
1092 * have a low soft limit.
1094 * We compute this by finding the largest number that we can use.
1095 * If we can't find a number greater than or equal to <b>limit</b>,
1096 * then we fail: return -1.
1098 * Otherwise, return 0 and store the maximum we found inside <b>max_out</b>.*/
1100 set_max_file_descriptors(rlim_t limit, int *max_out)
1102 /* Define some maximum connections values for systems where we cannot
1103 * automatically determine a limit. Re Cygwin, see
1104 * http://archives.seul.org/or/talk/Aug-2006/msg00210.html
1105 * For an iPhone, 9999 should work. For Windows and all other unknown
1106 * systems we use 15000 as the default. */
1107 #ifndef HAVE_GETRLIMIT
1108 #if defined(CYGWIN) || defined(__CYGWIN__)
1109 const char *platform = "Cygwin";
1110 const unsigned long MAX_CONNECTIONS = 3200;
1111 #elif defined(MS_WINDOWS)
1112 const char *platform = "Windows";
1113 const unsigned long MAX_CONNECTIONS = 15000;
1114 #else
1115 const char *platform = "unknown platforms with no getrlimit()";
1116 const unsigned long MAX_CONNECTIONS = 15000;
1117 #endif
1118 log_fn(LOG_INFO, LD_NET,
1119 "This platform is missing getrlimit(). Proceeding.");
1120 if (limit > MAX_CONNECTIONS) {
1121 log_warn(LD_CONFIG,
1122 "We do not support more than %lu file descriptors "
1123 "on %s. Tried to raise to %lu.",
1124 (unsigned long)MAX_CONNECTIONS, platform, (unsigned long)limit);
1125 return -1;
1127 limit = MAX_CONNECTIONS;
1128 #else /* HAVE_GETRLIMIT */
1129 struct rlimit rlim;
1130 tor_assert(limit > 0);
1132 if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) {
1133 log_warn(LD_NET, "Could not get maximum number of file descriptors: %s",
1134 strerror(errno));
1135 return -1;
1138 if (rlim.rlim_max < limit) {
1139 log_warn(LD_CONFIG,"We need %lu file descriptors available, and we're "
1140 "limited to %lu. Please change your ulimit -n.",
1141 (unsigned long)limit, (unsigned long)rlim.rlim_max);
1142 return -1;
1145 if (rlim.rlim_max > rlim.rlim_cur) {
1146 log_info(LD_NET,"Raising max file descriptors from %lu to %lu.",
1147 (unsigned long)rlim.rlim_cur, (unsigned long)rlim.rlim_max);
1149 rlim.rlim_cur = rlim.rlim_max;
1151 if (setrlimit(RLIMIT_NOFILE, &rlim) != 0) {
1152 int bad = 1;
1153 #ifdef OPEN_MAX
1154 if (errno == EINVAL && OPEN_MAX < rlim.rlim_cur) {
1155 /* On some platforms, OPEN_MAX is the real limit, and getrlimit() is
1156 * full of nasty lies. I'm looking at you, OSX 10.5.... */
1157 rlim.rlim_cur = OPEN_MAX;
1158 if (setrlimit(RLIMIT_NOFILE, &rlim) == 0) {
1159 if (rlim.rlim_cur < (rlim_t)limit) {
1160 log_warn(LD_CONFIG, "We are limited to %lu file descriptors by "
1161 "OPEN_MAX, and ConnLimit is %lu. Changing ConnLimit; sorry.",
1162 (unsigned long)OPEN_MAX, (unsigned long)limit);
1163 } else {
1164 log_info(LD_CONFIG, "Dropped connection limit to OPEN_MAX (%lu); "
1165 "Apparently, %lu was too high and rlimit lied to us.",
1166 (unsigned long)OPEN_MAX, (unsigned long)rlim.rlim_max);
1168 bad = 0;
1171 #endif /* OPEN_MAX */
1172 if (bad) {
1173 log_warn(LD_CONFIG,"Couldn't set maximum number of file descriptors: %s",
1174 strerror(errno));
1175 return -1;
1178 /* leave some overhead for logs, etc, */
1179 limit = rlim.rlim_cur;
1180 #endif /* HAVE_GETRLIMIT */
1182 if (limit < ULIMIT_BUFFER) {
1183 log_warn(LD_CONFIG,
1184 "ConnLimit must be at least %d. Failing.", ULIMIT_BUFFER);
1185 return -1;
1187 if (limit > INT_MAX)
1188 limit = INT_MAX;
1189 tor_assert(max_out);
1190 *max_out = (int)limit - ULIMIT_BUFFER;
1191 return 0;
1194 #ifndef MS_WINDOWS
1195 /** Log details of current user and group credentials. Return 0 on
1196 * success. Logs and return -1 on failure.
1198 static int
1199 log_credential_status(void)
1201 #define CREDENTIAL_LOG_LEVEL LOG_INFO
1202 /* Real, effective and saved UIDs */
1203 uid_t ruid, euid, suid;
1204 /* Read, effective and saved GIDs */
1205 gid_t rgid, egid, sgid;
1206 /* Supplementary groups */
1207 gid_t sup_gids[NGROUPS_MAX + 1];
1208 /* Number of supplementary groups */
1209 int ngids;
1211 /* log UIDs */
1212 #ifdef HAVE_GETRESUID
1213 if (getresuid(&ruid, &euid, &suid) != 0 ) {
1214 log_warn(LD_GENERAL, "Error getting changed UIDs: %s", strerror(errno));
1215 return -1;
1216 } else {
1217 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
1218 "UID is %u (real), %u (effective), %u (saved)",
1219 (unsigned)ruid, (unsigned)euid, (unsigned)suid);
1221 #else
1222 /* getresuid is not present on MacOS X, so we can't get the saved (E)UID */
1223 ruid = getuid();
1224 euid = geteuid();
1225 (void)suid;
1227 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
1228 "UID is %u (real), %u (effective), unknown (saved)",
1229 (unsigned)ruid, (unsigned)euid);
1230 #endif
1232 /* log GIDs */
1233 #ifdef HAVE_GETRESGID
1234 if (getresgid(&rgid, &egid, &sgid) != 0 ) {
1235 log_warn(LD_GENERAL, "Error getting changed GIDs: %s", strerror(errno));
1236 return -1;
1237 } else {
1238 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
1239 "GID is %u (real), %u (effective), %u (saved)",
1240 (unsigned)rgid, (unsigned)egid, (unsigned)sgid);
1242 #else
1243 /* getresgid is not present on MacOS X, so we can't get the saved (E)GID */
1244 rgid = getgid();
1245 egid = getegid();
1246 (void)sgid;
1247 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
1248 "GID is %u (real), %u (effective), unknown (saved)",
1249 (unsigned)rgid, (unsigned)egid);
1250 #endif
1252 /* log supplementary groups */
1253 if ((ngids = getgroups(NGROUPS_MAX + 1, sup_gids)) < 0) {
1254 log_warn(LD_GENERAL, "Error getting supplementary GIDs: %s",
1255 strerror(errno));
1256 return -1;
1257 } else {
1258 int i, retval = 0;
1259 char *strgid;
1260 char *s = NULL;
1261 smartlist_t *elts = smartlist_create();
1263 for (i = 0; i<ngids; i++) {
1264 strgid = tor_malloc(11);
1265 if (tor_snprintf(strgid, 11, "%u", (unsigned)sup_gids[i]) < 0) {
1266 log_warn(LD_GENERAL, "Error printing supplementary GIDs");
1267 tor_free(strgid);
1268 retval = -1;
1269 goto error;
1271 smartlist_add(elts, strgid);
1274 s = smartlist_join_strings(elts, " ", 0, NULL);
1276 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL, "Supplementary groups are: %s",s);
1278 error:
1279 tor_free(s);
1280 SMARTLIST_FOREACH(elts, char *, cp,
1282 tor_free(cp);
1284 smartlist_free(elts);
1286 return retval;
1289 return 0;
1291 #endif
1293 /** Call setuid and setgid to run as <b>user</b> and switch to their
1294 * primary group. Return 0 on success. On failure, log and return -1.
1297 switch_id(const char *user)
1299 #ifndef MS_WINDOWS
1300 struct passwd *pw = NULL;
1301 uid_t old_uid;
1302 gid_t old_gid;
1303 static int have_already_switched_id = 0;
1305 tor_assert(user);
1307 if (have_already_switched_id)
1308 return 0;
1310 /* Log the initial credential state */
1311 if (log_credential_status())
1312 return -1;
1314 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL, "Changing user and groups");
1316 /* Get old UID/GID to check if we changed correctly */
1317 old_uid = getuid();
1318 old_gid = getgid();
1320 /* Lookup the user and group information, if we have a problem, bail out. */
1321 pw = getpwnam(user);
1322 if (pw == NULL) {
1323 log_warn(LD_CONFIG, "Error setting configured user: %s not found", user);
1324 return -1;
1327 /* Properly switch egid,gid,euid,uid here or bail out */
1328 if (setgroups(1, &pw->pw_gid)) {
1329 log_warn(LD_GENERAL, "Error setting groups to gid %d: \"%s\".",
1330 (int)pw->pw_gid, strerror(errno));
1331 if (old_uid == pw->pw_uid) {
1332 log_warn(LD_GENERAL, "Tor is already running as %s. You do not need "
1333 "the \"User\" option if you are already running as the user "
1334 "you want to be. (If you did not set the User option in your "
1335 "torrc, check whether it was specified on the command line "
1336 "by a startup script.)", user);
1337 } else {
1338 log_warn(LD_GENERAL, "If you set the \"User\" option, you must start Tor"
1339 " as root.");
1341 return -1;
1344 if (setegid(pw->pw_gid)) {
1345 log_warn(LD_GENERAL, "Error setting egid to %d: %s",
1346 (int)pw->pw_gid, strerror(errno));
1347 return -1;
1350 if (setgid(pw->pw_gid)) {
1351 log_warn(LD_GENERAL, "Error setting gid to %d: %s",
1352 (int)pw->pw_gid, strerror(errno));
1353 return -1;
1356 if (setuid(pw->pw_uid)) {
1357 log_warn(LD_GENERAL, "Error setting configured uid to %s (%d): %s",
1358 user, (int)pw->pw_uid, strerror(errno));
1359 return -1;
1362 if (seteuid(pw->pw_uid)) {
1363 log_warn(LD_GENERAL, "Error setting configured euid to %s (%d): %s",
1364 user, (int)pw->pw_uid, strerror(errno));
1365 return -1;
1368 /* This is how OpenBSD rolls:
1369 if (setgroups(1, &pw->pw_gid) || setegid(pw->pw_gid) ||
1370 setgid(pw->pw_gid) || setuid(pw->pw_uid) || seteuid(pw->pw_uid)) {
1371 setgid(pw->pw_gid) || seteuid(pw->pw_uid) || setuid(pw->pw_uid)) {
1372 log_warn(LD_GENERAL, "Error setting configured UID/GID: %s",
1373 strerror(errno));
1374 return -1;
1378 /* We've properly switched egid, gid, euid, uid, and supplementary groups if
1379 * we're here. */
1381 #if !defined(CYGWIN) && !defined(__CYGWIN__)
1382 /* If we tried to drop privilege to a group/user other than root, attempt to
1383 * restore root (E)(U|G)ID, and abort if the operation succeeds */
1385 /* Only check for privilege dropping if we were asked to be non-root */
1386 if (pw->pw_uid) {
1387 /* Try changing GID/EGID */
1388 if (pw->pw_gid != old_gid &&
1389 (setgid(old_gid) != -1 || setegid(old_gid) != -1)) {
1390 log_warn(LD_GENERAL, "Was able to restore group credentials even after "
1391 "switching GID: this means that the setgid code didn't work.");
1392 return -1;
1395 /* Try changing UID/EUID */
1396 if (pw->pw_uid != old_uid &&
1397 (setuid(old_uid) != -1 || seteuid(old_uid) != -1)) {
1398 log_warn(LD_GENERAL, "Was able to restore user credentials even after "
1399 "switching UID: this means that the setuid code didn't work.");
1400 return -1;
1403 #endif
1405 /* Check what really happened */
1406 if (log_credential_status()) {
1407 return -1;
1410 have_already_switched_id = 1; /* mark success so we never try again */
1412 #if defined(__linux__) && defined(HAVE_SYS_PRCTL_H) && defined(HAVE_PRCTL)
1413 #ifdef PR_SET_DUMPABLE
1414 if (pw->pw_uid) {
1415 /* Re-enable core dumps if we're not running as root. */
1416 log_info(LD_CONFIG, "Re-enabling coredumps");
1417 if (prctl(PR_SET_DUMPABLE, 1)) {
1418 log_warn(LD_CONFIG, "Unable to re-enable coredumps: %s",strerror(errno));
1421 #endif
1422 #endif
1423 return 0;
1425 #else
1426 (void)user;
1428 log_warn(LD_CONFIG,
1429 "User specified but switching users is unsupported on your OS.");
1430 return -1;
1431 #endif
1434 #ifdef HAVE_PWD_H
1435 /** Allocate and return a string containing the home directory for the
1436 * user <b>username</b>. Only works on posix-like systems. */
1437 char *
1438 get_user_homedir(const char *username)
1440 struct passwd *pw;
1441 tor_assert(username);
1443 if (!(pw = getpwnam(username))) {
1444 log_err(LD_CONFIG,"User \"%s\" not found.", username);
1445 return NULL;
1447 return tor_strdup(pw->pw_dir);
1449 #endif
1451 /** Set *addr to the IP address (in dotted-quad notation) stored in c.
1452 * Return 1 on success, 0 if c is badly formatted. (Like inet_aton(c,addr),
1453 * but works on Windows and Solaris.)
1456 tor_inet_aton(const char *str, struct in_addr* addr)
1458 unsigned a,b,c,d;
1459 char more;
1460 if (tor_sscanf(str, "%3u.%3u.%3u.%3u%c", &a,&b,&c,&d,&more) != 4)
1461 return 0;
1462 if (a > 255) return 0;
1463 if (b > 255) return 0;
1464 if (c > 255) return 0;
1465 if (d > 255) return 0;
1466 addr->s_addr = htonl((a<<24) | (b<<16) | (c<<8) | d);
1467 return 1;
1470 /** Given <b>af</b>==AF_INET and <b>src</b> a struct in_addr, or
1471 * <b>af</b>==AF_INET6 and <b>src</b> a struct in6_addr, try to format the
1472 * address and store it in the <b>len</b>-byte buffer <b>dst</b>. Returns
1473 * <b>dst</b> on success, NULL on failure.
1475 * (Like inet_ntop(af,src,dst,len), but works on platforms that don't have it:
1476 * Tor sometimes needs to format ipv6 addresses even on platforms without ipv6
1477 * support.) */
1478 const char *
1479 tor_inet_ntop(int af, const void *src, char *dst, size_t len)
1481 if (af == AF_INET) {
1482 if (tor_inet_ntoa(src, dst, len) < 0)
1483 return NULL;
1484 else
1485 return dst;
1486 } else if (af == AF_INET6) {
1487 const struct in6_addr *addr = src;
1488 char buf[64], *cp;
1489 int longestGapLen = 0, longestGapPos = -1, i,
1490 curGapPos = -1, curGapLen = 0;
1491 uint16_t words[8];
1492 for (i = 0; i < 8; ++i) {
1493 words[i] = (((uint16_t)addr->s6_addr[2*i])<<8) + addr->s6_addr[2*i+1];
1495 if (words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0 &&
1496 words[4] == 0 && ((words[5] == 0 && words[6] && words[7]) ||
1497 (words[5] == 0xffff))) {
1498 /* This is an IPv4 address. */
1499 if (words[5] == 0) {
1500 tor_snprintf(buf, sizeof(buf), "::%d.%d.%d.%d",
1501 addr->s6_addr[12], addr->s6_addr[13],
1502 addr->s6_addr[14], addr->s6_addr[15]);
1503 } else {
1504 tor_snprintf(buf, sizeof(buf), "::%x:%d.%d.%d.%d", words[5],
1505 addr->s6_addr[12], addr->s6_addr[13],
1506 addr->s6_addr[14], addr->s6_addr[15]);
1508 if (strlen(buf) > len)
1509 return NULL;
1510 strlcpy(dst, buf, len);
1511 return dst;
1513 i = 0;
1514 while (i < 8) {
1515 if (words[i] == 0) {
1516 curGapPos = i++;
1517 curGapLen = 1;
1518 while (i<8 && words[i] == 0) {
1519 ++i; ++curGapLen;
1521 if (curGapLen > longestGapLen) {
1522 longestGapPos = curGapPos;
1523 longestGapLen = curGapLen;
1525 } else {
1526 ++i;
1529 if (longestGapLen<=1)
1530 longestGapPos = -1;
1532 cp = buf;
1533 for (i = 0; i < 8; ++i) {
1534 if (words[i] == 0 && longestGapPos == i) {
1535 if (i == 0)
1536 *cp++ = ':';
1537 *cp++ = ':';
1538 while (i < 8 && words[i] == 0)
1539 ++i;
1540 --i; /* to compensate for loop increment. */
1541 } else {
1542 tor_snprintf(cp, sizeof(buf)-(cp-buf), "%x", (unsigned)words[i]);
1543 cp += strlen(cp);
1544 if (i != 7)
1545 *cp++ = ':';
1548 *cp = '\0';
1549 if (strlen(buf) > len)
1550 return NULL;
1551 strlcpy(dst, buf, len);
1552 return dst;
1553 } else {
1554 return NULL;
1558 /** Given <b>af</b>==AF_INET or <b>af</b>==AF_INET6, and a string <b>src</b>
1559 * encoding an IPv4 address or IPv6 address correspondingly, try to parse the
1560 * address and store the result in <b>dst</b> (which must have space for a
1561 * struct in_addr or a struct in6_addr, as appropriate). Return 1 on success,
1562 * 0 on a bad parse, and -1 on a bad <b>af</b>.
1564 * (Like inet_pton(af,src,dst) but works on platforms that don't have it: Tor
1565 * sometimes needs to format ipv6 addresses even on platforms without ipv6
1566 * support.) */
1568 tor_inet_pton(int af, const char *src, void *dst)
1570 if (af == AF_INET) {
1571 return tor_inet_aton(src, dst);
1572 } else if (af == AF_INET6) {
1573 struct in6_addr *out = dst;
1574 uint16_t words[8];
1575 int gapPos = -1, i, setWords=0;
1576 const char *dot = strchr(src, '.');
1577 const char *eow; /* end of words. */
1578 if (dot == src)
1579 return 0;
1580 else if (!dot)
1581 eow = src+strlen(src);
1582 else {
1583 unsigned byte1,byte2,byte3,byte4;
1584 char more;
1585 for (eow = dot-1; eow >= src && TOR_ISDIGIT(*eow); --eow)
1587 ++eow;
1589 /* We use "scanf" because some platform inet_aton()s are too lax
1590 * about IPv4 addresses of the form "1.2.3" */
1591 if (tor_sscanf(eow, "%3u.%3u.%3u.%3u%c",
1592 &byte1,&byte2,&byte3,&byte4,&more) != 4)
1593 return 0;
1595 if (byte1 > 255 || byte2 > 255 || byte3 > 255 || byte4 > 255)
1596 return 0;
1598 words[6] = (byte1<<8) | byte2;
1599 words[7] = (byte3<<8) | byte4;
1600 setWords += 2;
1603 i = 0;
1604 while (src < eow) {
1605 if (i > 7)
1606 return 0;
1607 if (TOR_ISXDIGIT(*src)) {
1608 char *next;
1609 long r = strtol(src, &next, 16);
1610 if (next > 4+src)
1611 return 0;
1612 if (next == src)
1613 return 0;
1614 if (r<0 || r>65536)
1615 return 0;
1617 words[i++] = (uint16_t)r;
1618 setWords++;
1619 src = next;
1620 if (*src != ':' && src != eow)
1621 return 0;
1622 ++src;
1623 } else if (*src == ':' && i > 0 && gapPos==-1) {
1624 gapPos = i;
1625 ++src;
1626 } else if (*src == ':' && i == 0 && src[1] == ':' && gapPos==-1) {
1627 gapPos = i;
1628 src += 2;
1629 } else {
1630 return 0;
1634 if (setWords > 8 ||
1635 (setWords == 8 && gapPos != -1) ||
1636 (setWords < 8 && gapPos == -1))
1637 return 0;
1639 if (gapPos >= 0) {
1640 int nToMove = setWords - (dot ? 2 : 0) - gapPos;
1641 int gapLen = 8 - setWords;
1642 tor_assert(nToMove >= 0);
1643 memmove(&words[gapPos+gapLen], &words[gapPos],
1644 sizeof(uint16_t)*nToMove);
1645 memset(&words[gapPos], 0, sizeof(uint16_t)*gapLen);
1647 for (i = 0; i < 8; ++i) {
1648 out->s6_addr[2*i ] = words[i] >> 8;
1649 out->s6_addr[2*i+1] = words[i] & 0xff;
1652 return 1;
1653 } else {
1654 return -1;
1658 /** Similar behavior to Unix gethostbyname: resolve <b>name</b>, and set
1659 * *<b>addr</b> to the proper IP address, in host byte order. Returns 0
1660 * on success, -1 on failure; 1 on transient failure.
1662 * (This function exists because standard windows gethostbyname
1663 * doesn't treat raw IP addresses properly.)
1666 tor_lookup_hostname(const char *name, uint32_t *addr)
1668 tor_addr_t myaddr;
1669 int ret;
1671 if ((ret = tor_addr_lookup(name, AF_INET, &myaddr)))
1672 return ret;
1674 if (tor_addr_family(&myaddr) == AF_INET) {
1675 *addr = tor_addr_to_ipv4h(&myaddr);
1676 return ret;
1679 return -1;
1682 /** Hold the result of our call to <b>uname</b>. */
1683 static char uname_result[256];
1684 /** True iff uname_result is set. */
1685 static int uname_result_is_set = 0;
1687 /** Return a pointer to a description of our platform.
1689 const char *
1690 get_uname(void)
1692 #ifdef HAVE_UNAME
1693 struct utsname u;
1694 #endif
1695 if (!uname_result_is_set) {
1696 #ifdef HAVE_UNAME
1697 if (uname(&u) != -1) {
1698 /* (Linux says 0 is success, Solaris says 1 is success) */
1699 tor_snprintf(uname_result, sizeof(uname_result), "%s %s",
1700 u.sysname, u.machine);
1701 } else
1702 #endif
1704 #ifdef MS_WINDOWS
1705 OSVERSIONINFOEX info;
1706 int i;
1707 const char *plat = NULL;
1708 const char *extra = NULL;
1709 char acsd[MAX_PATH] = {0};
1710 static struct {
1711 unsigned major; unsigned minor; const char *version;
1712 } win_version_table[] = {
1713 { 6, 1, "Windows 7" },
1714 { 6, 0, "Windows Vista" },
1715 { 5, 2, "Windows Server 2003" },
1716 { 5, 1, "Windows XP" },
1717 { 5, 0, "Windows 2000" },
1718 /* { 4, 0, "Windows NT 4.0" }, */
1719 { 4, 90, "Windows Me" },
1720 { 4, 10, "Windows 98" },
1721 /* { 4, 0, "Windows 95" } */
1722 { 3, 51, "Windows NT 3.51" },
1723 { 0, 0, NULL }
1725 memset(&info, 0, sizeof(info));
1726 info.dwOSVersionInfoSize = sizeof(info);
1727 if (! GetVersionEx((LPOSVERSIONINFO)&info)) {
1728 strlcpy(uname_result, "Bizarre version of Windows where GetVersionEx"
1729 " doesn't work.", sizeof(uname_result));
1730 uname_result_is_set = 1;
1731 return uname_result;
1733 #ifdef UNICODE
1734 wcstombs(acsd, info.szCSDVersion, MAX_PATH);
1735 #else
1736 strlcpy(acsd, info.szCSDVersion, sizeof(acsd));
1737 #endif
1738 if (info.dwMajorVersion == 4 && info.dwMinorVersion == 0) {
1739 if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
1740 plat = "Windows NT 4.0";
1741 else
1742 plat = "Windows 95";
1743 if (acsd[1] == 'B')
1744 extra = "OSR2 (B)";
1745 else if (acsd[1] == 'C')
1746 extra = "OSR2 (C)";
1747 } else {
1748 for (i=0; win_version_table[i].major>0; ++i) {
1749 if (win_version_table[i].major == info.dwMajorVersion &&
1750 win_version_table[i].minor == info.dwMinorVersion) {
1751 plat = win_version_table[i].version;
1752 break;
1756 if (plat && !strcmp(plat, "Windows 98")) {
1757 if (acsd[1] == 'A')
1758 extra = "SE (A)";
1759 else if (acsd[1] == 'B')
1760 extra = "SE (B)";
1762 if (plat) {
1763 if (!extra)
1764 extra = acsd;
1765 tor_snprintf(uname_result, sizeof(uname_result), "%s %s",
1766 plat, extra);
1767 } else {
1768 if (info.dwMajorVersion > 6 ||
1769 (info.dwMajorVersion==6 && info.dwMinorVersion>1))
1770 tor_snprintf(uname_result, sizeof(uname_result),
1771 "Very recent version of Windows [major=%d,minor=%d] %s",
1772 (int)info.dwMajorVersion,(int)info.dwMinorVersion,
1773 acsd);
1774 else
1775 tor_snprintf(uname_result, sizeof(uname_result),
1776 "Unrecognized version of Windows [major=%d,minor=%d] %s",
1777 (int)info.dwMajorVersion,(int)info.dwMinorVersion,
1778 acsd);
1780 #if !defined (WINCE)
1781 #ifdef VER_SUITE_BACKOFFICE
1782 if (info.wProductType == VER_NT_DOMAIN_CONTROLLER) {
1783 strlcat(uname_result, " [domain controller]", sizeof(uname_result));
1784 } else if (info.wProductType == VER_NT_SERVER) {
1785 strlcat(uname_result, " [server]", sizeof(uname_result));
1786 } else if (info.wProductType == VER_NT_WORKSTATION) {
1787 strlcat(uname_result, " [workstation]", sizeof(uname_result));
1789 #endif
1790 #endif
1791 #else
1792 strlcpy(uname_result, "Unknown platform", sizeof(uname_result));
1793 #endif
1795 uname_result_is_set = 1;
1797 return uname_result;
1801 * Process control
1804 #if defined(USE_PTHREADS)
1805 /** Wraps a void (*)(void*) function and its argument so we can
1806 * invoke them in a way pthreads would expect.
1808 typedef struct tor_pthread_data_t {
1809 void (*func)(void *);
1810 void *data;
1811 } tor_pthread_data_t;
1812 /** Given a tor_pthread_data_t <b>_data</b>, call _data-&gt;func(d-&gt;data)
1813 * and free _data. Used to make sure we can call functions the way pthread
1814 * expects. */
1815 static void *
1816 tor_pthread_helper_fn(void *_data)
1818 tor_pthread_data_t *data = _data;
1819 void (*func)(void*);
1820 void *arg;
1821 /* mask signals to worker threads to avoid SIGPIPE, etc */
1822 sigset_t sigs;
1823 /* We're in a subthread; don't handle any signals here. */
1824 sigfillset(&sigs);
1825 pthread_sigmask(SIG_SETMASK, &sigs, NULL);
1827 func = data->func;
1828 arg = data->data;
1829 tor_free(_data);
1830 func(arg);
1831 return NULL;
1833 #endif
1835 /** Minimalist interface to run a void function in the background. On
1836 * Unix calls fork, on win32 calls beginthread. Returns -1 on failure.
1837 * func should not return, but rather should call spawn_exit.
1839 * NOTE: if <b>data</b> is used, it should not be allocated on the stack,
1840 * since in a multithreaded environment, there is no way to be sure that
1841 * the caller's stack will still be around when the called function is
1842 * running.
1845 spawn_func(void (*func)(void *), void *data)
1847 #if defined(USE_WIN32_THREADS)
1848 int rv;
1849 rv = (int)_beginthread(func, 0, data);
1850 if (rv == (int)-1)
1851 return -1;
1852 return 0;
1853 #elif defined(USE_PTHREADS)
1854 pthread_t thread;
1855 tor_pthread_data_t *d;
1856 d = tor_malloc(sizeof(tor_pthread_data_t));
1857 d->data = data;
1858 d->func = func;
1859 if (pthread_create(&thread,NULL,tor_pthread_helper_fn,d))
1860 return -1;
1861 if (pthread_detach(thread))
1862 return -1;
1863 return 0;
1864 #else
1865 pid_t pid;
1866 pid = fork();
1867 if (pid<0)
1868 return -1;
1869 if (pid==0) {
1870 /* Child */
1871 func(data);
1872 tor_assert(0); /* Should never reach here. */
1873 return 0; /* suppress "control-reaches-end-of-non-void" warning. */
1874 } else {
1875 /* Parent */
1876 return 0;
1878 #endif
1881 /** End the current thread/process.
1883 void
1884 spawn_exit(void)
1886 #if defined(USE_WIN32_THREADS)
1887 _endthread();
1888 //we should never get here. my compiler thinks that _endthread returns, this
1889 //is an attempt to fool it.
1890 tor_assert(0);
1891 _exit(0);
1892 #elif defined(USE_PTHREADS)
1893 pthread_exit(NULL);
1894 #else
1895 /* http://www.erlenstar.demon.co.uk/unix/faq_2.html says we should
1896 * call _exit, not exit, from child processes. */
1897 _exit(0);
1898 #endif
1901 /** Set *timeval to the current time of day. On error, log and terminate.
1902 * (Same as gettimeofday(timeval,NULL), but never returns -1.)
1904 void
1905 tor_gettimeofday(struct timeval *timeval)
1907 #ifdef MS_WINDOWS
1908 /* Epoch bias copied from perl: number of units between windows epoch and
1909 * Unix epoch. */
1910 #define EPOCH_BIAS U64_LITERAL(116444736000000000)
1911 #define UNITS_PER_SEC U64_LITERAL(10000000)
1912 #define USEC_PER_SEC U64_LITERAL(1000000)
1913 #define UNITS_PER_USEC U64_LITERAL(10)
1914 union {
1915 uint64_t ft_64;
1916 FILETIME ft_ft;
1917 } ft;
1918 #if defined (WINCE)
1919 /* wince do not have GetSystemTimeAsFileTime */
1920 SYSTEMTIME stime;
1921 GetSystemTime(&stime);
1922 SystemTimeToFileTime(&stime,&ft.ft_ft);
1923 #else
1924 /* number of 100-nsec units since Jan 1, 1601 */
1925 GetSystemTimeAsFileTime(&ft.ft_ft);
1926 #endif
1927 if (ft.ft_64 < EPOCH_BIAS) {
1928 log_err(LD_GENERAL,"System time is before 1970; failing.");
1929 exit(1);
1931 ft.ft_64 -= EPOCH_BIAS;
1932 timeval->tv_sec = (unsigned) (ft.ft_64 / UNITS_PER_SEC);
1933 timeval->tv_usec = (unsigned) ((ft.ft_64 / UNITS_PER_USEC) % USEC_PER_SEC);
1934 #elif defined(HAVE_GETTIMEOFDAY)
1935 if (gettimeofday(timeval, NULL)) {
1936 log_err(LD_GENERAL,"gettimeofday failed.");
1937 /* If gettimeofday dies, we have either given a bad timezone (we didn't),
1938 or segfaulted.*/
1939 exit(1);
1941 #elif defined(HAVE_FTIME)
1942 struct timeb tb;
1943 ftime(&tb);
1944 timeval->tv_sec = tb.time;
1945 timeval->tv_usec = tb.millitm * 1000;
1946 #else
1947 #error "No way to get time."
1948 #endif
1949 return;
1952 #if defined(TOR_IS_MULTITHREADED) && !defined(MS_WINDOWS)
1953 /** Defined iff we need to add locks when defining fake versions of reentrant
1954 * versions of time-related functions. */
1955 #define TIME_FNS_NEED_LOCKS
1956 #endif
1958 #ifndef HAVE_LOCALTIME_R
1959 #ifdef TIME_FNS_NEED_LOCKS
1960 struct tm *
1961 tor_localtime_r(const time_t *timep, struct tm *result)
1963 struct tm *r;
1964 static tor_mutex_t *m=NULL;
1965 if (!m) { m=tor_mutex_new(); }
1966 tor_assert(result);
1967 tor_mutex_acquire(m);
1968 r = localtime(timep);
1969 memcpy(result, r, sizeof(struct tm));
1970 tor_mutex_release(m);
1971 return result;
1973 #else
1974 struct tm *
1975 tor_localtime_r(const time_t *timep, struct tm *result)
1977 struct tm *r;
1978 tor_assert(result);
1979 r = localtime(timep);
1980 memcpy(result, r, sizeof(struct tm));
1981 return result;
1983 #endif
1984 #endif
1986 #ifndef HAVE_GMTIME_R
1987 #ifdef TIME_FNS_NEED_LOCKS
1988 struct tm *
1989 tor_gmtime_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 = gmtime(timep);
1997 memcpy(result, r, sizeof(struct tm));
1998 tor_mutex_release(m);
1999 return result;
2001 #else
2002 struct tm *
2003 tor_gmtime_r(const time_t *timep, struct tm *result)
2005 struct tm *r;
2006 tor_assert(result);
2007 r = gmtime(timep);
2008 memcpy(result, r, sizeof(struct tm));
2009 return result;
2011 #endif
2012 #endif
2014 #if defined(USE_WIN32_THREADS)
2015 void
2016 tor_mutex_init(tor_mutex_t *m)
2018 InitializeCriticalSection(&m->mutex);
2020 void
2021 tor_mutex_uninit(tor_mutex_t *m)
2023 DeleteCriticalSection(&m->mutex);
2025 void
2026 tor_mutex_acquire(tor_mutex_t *m)
2028 tor_assert(m);
2029 EnterCriticalSection(&m->mutex);
2031 void
2032 tor_mutex_release(tor_mutex_t *m)
2034 LeaveCriticalSection(&m->mutex);
2036 unsigned long
2037 tor_get_thread_id(void)
2039 return (unsigned long)GetCurrentThreadId();
2041 #elif defined(USE_PTHREADS)
2042 /** A mutex attribute that we're going to use to tell pthreads that we want
2043 * "reentrant" mutexes (i.e., once we can re-lock if we're already holding
2044 * them.) */
2045 static pthread_mutexattr_t attr_reentrant;
2046 /** True iff we've called tor_threads_init() */
2047 static int threads_initialized = 0;
2048 /** Initialize <b>mutex</b> so it can be locked. Every mutex must be set
2049 * up with tor_mutex_init() or tor_mutex_new(); not both. */
2050 void
2051 tor_mutex_init(tor_mutex_t *mutex)
2053 int err;
2054 if (PREDICT_UNLIKELY(!threads_initialized))
2055 tor_threads_init();
2056 err = pthread_mutex_init(&mutex->mutex, &attr_reentrant);
2057 if (PREDICT_UNLIKELY(err)) {
2058 log_err(LD_GENERAL, "Error %d creating a mutex.", err);
2059 tor_fragile_assert();
2062 /** Wait until <b>m</b> is free, then acquire it. */
2063 void
2064 tor_mutex_acquire(tor_mutex_t *m)
2066 int err;
2067 tor_assert(m);
2068 err = pthread_mutex_lock(&m->mutex);
2069 if (PREDICT_UNLIKELY(err)) {
2070 log_err(LD_GENERAL, "Error %d locking a mutex.", err);
2071 tor_fragile_assert();
2074 /** Release the lock <b>m</b> so another thread can have it. */
2075 void
2076 tor_mutex_release(tor_mutex_t *m)
2078 int err;
2079 tor_assert(m);
2080 err = pthread_mutex_unlock(&m->mutex);
2081 if (PREDICT_UNLIKELY(err)) {
2082 log_err(LD_GENERAL, "Error %d unlocking a mutex.", err);
2083 tor_fragile_assert();
2086 /** Clean up the mutex <b>m</b> so that it no longer uses any system
2087 * resources. Does not free <b>m</b>. This function must only be called on
2088 * mutexes from tor_mutex_init(). */
2089 void
2090 tor_mutex_uninit(tor_mutex_t *m)
2092 int err;
2093 tor_assert(m);
2094 err = pthread_mutex_destroy(&m->mutex);
2095 if (PREDICT_UNLIKELY(err)) {
2096 log_err(LD_GENERAL, "Error %d destroying a mutex.", err);
2097 tor_fragile_assert();
2100 /** Return an integer representing this thread. */
2101 unsigned long
2102 tor_get_thread_id(void)
2104 union {
2105 pthread_t thr;
2106 unsigned long id;
2107 } r;
2108 r.thr = pthread_self();
2109 return r.id;
2111 #endif
2113 #ifdef TOR_IS_MULTITHREADED
2114 /** Return a newly allocated, ready-for-use mutex. */
2115 tor_mutex_t *
2116 tor_mutex_new(void)
2118 tor_mutex_t *m = tor_malloc_zero(sizeof(tor_mutex_t));
2119 tor_mutex_init(m);
2120 return m;
2122 /** Release all storage and system resources held by <b>m</b>. */
2123 void
2124 tor_mutex_free(tor_mutex_t *m)
2126 if (!m)
2127 return;
2128 tor_mutex_uninit(m);
2129 tor_free(m);
2131 #endif
2133 /* Conditions. */
2134 #ifdef USE_PTHREADS
2135 #if 0
2136 /** Cross-platform condition implementation. */
2137 struct tor_cond_t {
2138 pthread_cond_t cond;
2140 /** Return a newly allocated condition, with nobody waiting on it. */
2141 tor_cond_t *
2142 tor_cond_new(void)
2144 tor_cond_t *cond = tor_malloc_zero(sizeof(tor_cond_t));
2145 if (pthread_cond_init(&cond->cond, NULL)) {
2146 tor_free(cond);
2147 return NULL;
2149 return cond;
2151 /** Release all resources held by <b>cond</b>. */
2152 void
2153 tor_cond_free(tor_cond_t *cond)
2155 if (!cond)
2156 return;
2157 if (pthread_cond_destroy(&cond->cond)) {
2158 log_warn(LD_GENERAL,"Error freeing condition: %s", strerror(errno));
2159 return;
2161 tor_free(cond);
2163 /** Wait until one of the tor_cond_signal functions is called on <b>cond</b>.
2164 * All waiters on the condition must wait holding the same <b>mutex</b>.
2165 * Returns 0 on success, negative on failure. */
2167 tor_cond_wait(tor_cond_t *cond, tor_mutex_t *mutex)
2169 return pthread_cond_wait(&cond->cond, &mutex->mutex) ? -1 : 0;
2171 /** Wake up one of the waiters on <b>cond</b>. */
2172 void
2173 tor_cond_signal_one(tor_cond_t *cond)
2175 pthread_cond_signal(&cond->cond);
2177 /** Wake up all of the waiters on <b>cond</b>. */
2178 void
2179 tor_cond_signal_all(tor_cond_t *cond)
2181 pthread_cond_broadcast(&cond->cond);
2183 #endif
2184 /** Set up common structures for use by threading. */
2185 void
2186 tor_threads_init(void)
2188 if (!threads_initialized) {
2189 pthread_mutexattr_init(&attr_reentrant);
2190 pthread_mutexattr_settype(&attr_reentrant, PTHREAD_MUTEX_RECURSIVE);
2191 threads_initialized = 1;
2192 set_main_thread();
2195 #elif defined(USE_WIN32_THREADS)
2196 #if 0
2197 static DWORD cond_event_tls_index;
2198 struct tor_cond_t {
2199 CRITICAL_SECTION mutex;
2200 smartlist_t *events;
2202 tor_cond_t *
2203 tor_cond_new(void)
2205 tor_cond_t *cond = tor_malloc_zero(sizeof(tor_cond_t));
2206 InitializeCriticalSection(&cond->mutex);
2207 cond->events = smartlist_create();
2208 return cond;
2210 void
2211 tor_cond_free(tor_cond_t *cond)
2213 if (!cond)
2214 return;
2215 DeleteCriticalSection(&cond->mutex);
2216 /* XXXX notify? */
2217 smartlist_free(cond->events);
2218 tor_free(cond);
2221 tor_cond_wait(tor_cond_t *cond, tor_mutex_t *mutex)
2223 HANDLE event;
2224 int r;
2225 tor_assert(cond);
2226 tor_assert(mutex);
2227 event = TlsGetValue(cond_event_tls_index);
2228 if (!event) {
2229 event = CreateEvent(0, FALSE, FALSE, NULL);
2230 TlsSetValue(cond_event_tls_index, event);
2232 EnterCriticalSection(&cond->mutex);
2234 tor_assert(WaitForSingleObject(event, 0) == WAIT_TIMEOUT);
2235 tor_assert(!smartlist_isin(cond->events, event));
2236 smartlist_add(cond->events, event);
2238 LeaveCriticalSection(&cond->mutex);
2240 tor_mutex_release(mutex);
2241 r = WaitForSingleObject(event, INFINITE);
2242 tor_mutex_acquire(mutex);
2244 switch (r) {
2245 case WAIT_OBJECT_0: /* we got the mutex normally. */
2246 break;
2247 case WAIT_ABANDONED: /* holding thread exited. */
2248 case WAIT_TIMEOUT: /* Should never happen. */
2249 tor_assert(0);
2250 break;
2251 case WAIT_FAILED:
2252 log_warn(LD_GENERAL, "Failed to acquire mutex: %d",(int) GetLastError());
2254 return 0;
2256 void
2257 tor_cond_signal_one(tor_cond_t *cond)
2259 HANDLE event;
2260 tor_assert(cond);
2262 EnterCriticalSection(&cond->mutex);
2264 if ((event = smartlist_pop_last(cond->events)))
2265 SetEvent(event);
2267 LeaveCriticalSection(&cond->mutex);
2269 void
2270 tor_cond_signal_all(tor_cond_t *cond)
2272 tor_assert(cond);
2274 EnterCriticalSection(&cond->mutex);
2275 SMARTLIST_FOREACH(cond->events, HANDLE, event, SetEvent(event));
2276 smartlist_clear(cond->events);
2277 LeaveCriticalSection(&cond->mutex);
2279 #endif
2280 void
2281 tor_threads_init(void)
2283 #if 0
2284 cond_event_tls_index = TlsAlloc();
2285 #endif
2286 set_main_thread();
2288 #endif
2290 #if defined(HAVE_MLOCKALL) && HAVE_DECL_MLOCKALL && defined(RLIMIT_MEMLOCK)
2291 /** Attempt to raise the current and max rlimit to infinity for our process.
2292 * This only needs to be done once and can probably only be done when we have
2293 * not already dropped privileges.
2295 static int
2296 tor_set_max_memlock(void)
2298 /* Future consideration for Windows is probably SetProcessWorkingSetSize
2299 * This is similar to setting the memory rlimit of RLIMIT_MEMLOCK
2300 * http://msdn.microsoft.com/en-us/library/ms686234(VS.85).aspx
2303 struct rlimit limit;
2305 /* RLIM_INFINITY is -1 on some platforms. */
2306 limit.rlim_cur = RLIM_INFINITY;
2307 limit.rlim_max = RLIM_INFINITY;
2309 if (setrlimit(RLIMIT_MEMLOCK, &limit) == -1) {
2310 if (errno == EPERM) {
2311 log_warn(LD_GENERAL, "You appear to lack permissions to change memory "
2312 "limits. Are you root?");
2314 log_warn(LD_GENERAL, "Unable to raise RLIMIT_MEMLOCK: %s",
2315 strerror(errno));
2316 return -1;
2319 return 0;
2321 #endif
2323 /** Attempt to lock all current and all future memory pages.
2324 * This should only be called once and while we're privileged.
2325 * Like mlockall() we return 0 when we're successful and -1 when we're not.
2326 * Unlike mlockall() we return 1 if we've already attempted to lock memory.
2329 tor_mlockall(void)
2331 static int memory_lock_attempted = 0;
2333 if (memory_lock_attempted) {
2334 return 1;
2337 memory_lock_attempted = 1;
2340 * Future consideration for Windows may be VirtualLock
2341 * VirtualLock appears to implement mlock() but not mlockall()
2343 * http://msdn.microsoft.com/en-us/library/aa366895(VS.85).aspx
2346 #if defined(HAVE_MLOCKALL) && HAVE_DECL_MLOCKALL && defined(RLIMIT_MEMLOCK)
2347 if (tor_set_max_memlock() == 0) {
2348 log_debug(LD_GENERAL, "RLIMIT_MEMLOCK is now set to RLIM_INFINITY.");
2351 if (mlockall(MCL_CURRENT|MCL_FUTURE) == 0) {
2352 log_info(LD_GENERAL, "Insecure OS paging is effectively disabled.");
2353 return 0;
2354 } else {
2355 if (errno == ENOSYS) {
2356 /* Apple - it's 2009! I'm looking at you. Grrr. */
2357 log_notice(LD_GENERAL, "It appears that mlockall() is not available on "
2358 "your platform.");
2359 } else if (errno == EPERM) {
2360 log_notice(LD_GENERAL, "It appears that you lack the permissions to "
2361 "lock memory. Are you root?");
2363 log_notice(LD_GENERAL, "Unable to lock all current and future memory "
2364 "pages: %s", strerror(errno));
2365 return -1;
2367 #else
2368 log_warn(LD_GENERAL, "Unable to lock memory pages. mlockall() unsupported?");
2369 return -1;
2370 #endif
2373 /** Identity of the "main" thread */
2374 static unsigned long main_thread_id = -1;
2376 /** Start considering the current thread to be the 'main thread'. This has
2377 * no effect on anything besides in_main_thread(). */
2378 void
2379 set_main_thread(void)
2381 main_thread_id = tor_get_thread_id();
2383 /** Return true iff called from the main thread. */
2385 in_main_thread(void)
2387 return main_thread_id == tor_get_thread_id();
2391 * On Windows, WSAEWOULDBLOCK is not always correct: when you see it,
2392 * you need to ask the socket for its actual errno. Also, you need to
2393 * get your errors from WSAGetLastError, not errno. (If you supply a
2394 * socket of -1, we check WSAGetLastError, but don't correct
2395 * WSAEWOULDBLOCKs.)
2397 * The upshot of all of this is that when a socket call fails, you
2398 * should call tor_socket_errno <em>at most once</em> on the failing
2399 * socket to get the error.
2401 #if defined(MS_WINDOWS)
2403 tor_socket_errno(int sock)
2405 int optval, optvallen=sizeof(optval);
2406 int err = WSAGetLastError();
2407 if (err == WSAEWOULDBLOCK && sock >= 0) {
2408 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval, &optvallen))
2409 return err;
2410 if (optval)
2411 return optval;
2413 return err;
2415 #endif
2417 #if defined(MS_WINDOWS)
2418 #define E(code, s) { code, (s " [" #code " ]") }
2419 struct { int code; const char *msg; } windows_socket_errors[] = {
2420 E(WSAEINTR, "Interrupted function call"),
2421 E(WSAEACCES, "Permission denied"),
2422 E(WSAEFAULT, "Bad address"),
2423 E(WSAEINVAL, "Invalid argument"),
2424 E(WSAEMFILE, "Too many open files"),
2425 E(WSAEWOULDBLOCK, "Resource temporarily unavailable"),
2426 E(WSAEINPROGRESS, "Operation now in progress"),
2427 E(WSAEALREADY, "Operation already in progress"),
2428 E(WSAENOTSOCK, "Socket operation on nonsocket"),
2429 E(WSAEDESTADDRREQ, "Destination address required"),
2430 E(WSAEMSGSIZE, "Message too long"),
2431 E(WSAEPROTOTYPE, "Protocol wrong for socket"),
2432 E(WSAENOPROTOOPT, "Bad protocol option"),
2433 E(WSAEPROTONOSUPPORT, "Protocol not supported"),
2434 E(WSAESOCKTNOSUPPORT, "Socket type not supported"),
2435 /* What's the difference between NOTSUPP and NOSUPPORT? :) */
2436 E(WSAEOPNOTSUPP, "Operation not supported"),
2437 E(WSAEPFNOSUPPORT, "Protocol family not supported"),
2438 E(WSAEAFNOSUPPORT, "Address family not supported by protocol family"),
2439 E(WSAEADDRINUSE, "Address already in use"),
2440 E(WSAEADDRNOTAVAIL, "Cannot assign requested address"),
2441 E(WSAENETDOWN, "Network is down"),
2442 E(WSAENETUNREACH, "Network is unreachable"),
2443 E(WSAENETRESET, "Network dropped connection on reset"),
2444 E(WSAECONNABORTED, "Software caused connection abort"),
2445 E(WSAECONNRESET, "Connection reset by peer"),
2446 E(WSAENOBUFS, "No buffer space available"),
2447 E(WSAEISCONN, "Socket is already connected"),
2448 E(WSAENOTCONN, "Socket is not connected"),
2449 E(WSAESHUTDOWN, "Cannot send after socket shutdown"),
2450 E(WSAETIMEDOUT, "Connection timed out"),
2451 E(WSAECONNREFUSED, "Connection refused"),
2452 E(WSAEHOSTDOWN, "Host is down"),
2453 E(WSAEHOSTUNREACH, "No route to host"),
2454 E(WSAEPROCLIM, "Too many processes"),
2455 /* Yes, some of these start with WSA, not WSAE. No, I don't know why. */
2456 E(WSASYSNOTREADY, "Network subsystem is unavailable"),
2457 E(WSAVERNOTSUPPORTED, "Winsock.dll out of range"),
2458 E(WSANOTINITIALISED, "Successful WSAStartup not yet performed"),
2459 E(WSAEDISCON, "Graceful shutdown now in progress"),
2460 #ifdef WSATYPE_NOT_FOUND
2461 E(WSATYPE_NOT_FOUND, "Class type not found"),
2462 #endif
2463 E(WSAHOST_NOT_FOUND, "Host not found"),
2464 E(WSATRY_AGAIN, "Nonauthoritative host not found"),
2465 E(WSANO_RECOVERY, "This is a nonrecoverable error"),
2466 E(WSANO_DATA, "Valid name, no data record of requested type)"),
2468 /* There are some more error codes whose numeric values are marked
2469 * <b>OS dependent</b>. They start with WSA_, apparently for the same
2470 * reason that practitioners of some craft traditions deliberately
2471 * introduce imperfections into their baskets and rugs "to allow the
2472 * evil spirits to escape." If we catch them, then our binaries
2473 * might not report consistent results across versions of Windows.
2474 * Thus, I'm going to let them all fall through.
2476 { -1, NULL },
2478 /** There does not seem to be a strerror equivalent for Winsock errors.
2479 * Naturally, we have to roll our own.
2481 const char *
2482 tor_socket_strerror(int e)
2484 int i;
2485 for (i=0; windows_socket_errors[i].code >= 0; ++i) {
2486 if (e == windows_socket_errors[i].code)
2487 return windows_socket_errors[i].msg;
2489 return strerror(e);
2491 #endif
2493 /** Called before we make any calls to network-related functions.
2494 * (Some operating systems require their network libraries to be
2495 * initialized.) */
2497 network_init(void)
2499 #ifdef MS_WINDOWS
2500 /* This silly exercise is necessary before windows will allow
2501 * gethostbyname to work. */
2502 WSADATA WSAData;
2503 int r;
2504 r = WSAStartup(0x101,&WSAData);
2505 if (r) {
2506 log_warn(LD_NET,"Error initializing windows network layer: code was %d",r);
2507 return -1;
2509 /* WSAData.iMaxSockets might show the max sockets we're allowed to use.
2510 * We might use it to complain if we're trying to be a server but have
2511 * too few sockets available. */
2512 #endif
2513 return 0;
2516 #ifdef MS_WINDOWS
2517 /** Return a newly allocated string describing the windows system error code
2518 * <b>err</b>. Note that error codes are different from errno. Error codes
2519 * come from GetLastError() when a winapi call fails. errno is set only when
2520 * ANSI functions fail. Whee. */
2521 char *
2522 format_win32_error(DWORD err)
2524 TCHAR *str = NULL;
2525 char *result;
2527 /* Somebody once decided that this interface was better than strerror(). */
2528 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
2529 FORMAT_MESSAGE_FROM_SYSTEM |
2530 FORMAT_MESSAGE_IGNORE_INSERTS,
2531 NULL, err,
2532 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
2533 (LPVOID)&str,
2534 0, NULL);
2536 if (str) {
2537 #ifdef UNICODE
2538 char abuf[1024] = {0};
2539 wcstombs(abuf,str,1024);
2540 result = tor_strdup(abuf);
2541 #else
2542 result = tor_strdup(str);
2543 #endif
2544 LocalFree(str); /* LocalFree != free() */
2545 } else {
2546 result = tor_strdup("<unformattable error>");
2548 return result;
2550 #endif