1 /* Copyright (c) 2003-2004, Roger Dingledine
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2011, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
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
15 /* This is required on rh7 to make strptime not complain.
16 * We also need it to make memmem get defined (where available)
18 /* XXXX023 We should just use AC_USE_SYSTEM_EXTENSIONS in our autoconf,
19 * and get this (and other important stuff!) automatically */
27 #include <sys/locking.h>
31 #include <sys/utsname.h>
36 #ifdef HAVE_SYS_FCNTL_H
37 #include <sys/fcntl.h>
51 #ifdef HAVE_ARPA_INET_H
52 #include <arpa/inet.h>
55 #ifndef HAVE_GETTIMEOFDAY
57 #include <sys/timeb.h>
61 /* Includes for the process attaching prevention */
62 #if defined(HAVE_SYS_PRCTL_H) && defined(__linux__)
63 #include <sys/prctl.h>
64 #elif defined(__APPLE__)
65 #include <sys/types.h>
66 #include <sys/ptrace.h>
72 #ifdef HAVE_SYS_PARAM_H
73 #include <sys/param.h> /* FreeBSD needs this to know what version it is */
84 #ifdef HAVE_SYS_UTIME_H
85 #include <sys/utime.h>
87 #ifdef HAVE_SYS_MMAN_H
90 #ifdef HAVE_SYS_SYSLIMITS_H
91 #include <sys/syslimits.h>
93 #ifdef HAVE_SYS_FILE_H
96 #if defined(HAVE_SYS_PRCTL_H) && defined(__linux__)
97 /* Only use the linux prctl; the IRIX prctl is totally different */
98 #include <sys/prctl.h>
103 #include "container.h"
106 /* Inline the strl functions if the platform doesn't have them. */
114 /** As open(path, flags, mode), but return an fd with the close-on-exec mode
117 tor_open_cloexec(const char *path
, int flags
, unsigned mode
)
120 return open(path
, flags
|O_CLOEXEC
, mode
);
122 int fd
= open(path
, flags
, mode
);
125 fcntl(fd
, F_SETFD
, FD_CLOEXEC
);
133 tor_fopen_cloexec(const char *path
, const char *mode
)
135 FILE *result
= fopen(path
, mode
);
138 fcntl(fileno(result
), F_SETFD
, FD_CLOEXEC
);
143 #ifdef HAVE_SYS_MMAN_H
144 /** Try to create a memory mapping for <b>filename</b> and return it. On
145 * failure, return NULL. Sets errno properly, using ERANGE to mean
148 tor_mmap_file(const char *filename
)
150 int fd
; /* router file */
154 size_t size
, filesize
;
156 tor_assert(filename
);
158 fd
= tor_open_cloexec(filename
, O_RDONLY
, 0);
160 int save_errno
= errno
;
161 int severity
= (errno
== ENOENT
) ? LOG_INFO
: LOG_WARN
;
162 log_fn(severity
, LD_FS
,"Could not open \"%s\" for mmap(): %s",filename
,
168 /* XXXX why not just do fstat here? */
169 size
= filesize
= (size_t) lseek(fd
, 0, SEEK_END
);
170 lseek(fd
, 0, SEEK_SET
);
171 /* ensure page alignment */
172 page_size
= getpagesize();
173 size
+= (size
%page_size
) ? page_size
-(size
%page_size
) : 0;
176 /* Zero-length file. If we call mmap on it, it will succeed but
177 * return NULL, and bad things will happen. So just fail. */
178 log_info(LD_FS
,"File \"%s\" is empty. Ignoring.",filename
);
184 string
= mmap(0, size
, PROT_READ
, MAP_PRIVATE
, fd
, 0);
186 if (string
== MAP_FAILED
) {
187 int save_errno
= errno
;
188 log_warn(LD_FS
,"Could not mmap file \"%s\": %s", filename
,
194 res
= tor_malloc_zero(sizeof(tor_mmap_t
));
196 res
->size
= filesize
;
197 res
->mapping_size
= size
;
201 /** Release storage held for a memory mapping. */
203 tor_munmap_file(tor_mmap_t
*handle
)
205 munmap((char*)handle
->data
, handle
->mapping_size
);
208 #elif defined(MS_WINDOWS)
210 tor_mmap_file(const char *filename
)
212 TCHAR tfilename
[MAX_PATH
]= {0};
213 tor_mmap_t
*res
= tor_malloc_zero(sizeof(tor_mmap_t
));
215 res
->file_handle
= INVALID_HANDLE_VALUE
;
216 res
->mmap_handle
= NULL
;
218 mbstowcs(tfilename
,filename
,MAX_PATH
);
220 strlcpy(tfilename
,filename
,MAX_PATH
);
222 res
->file_handle
= CreateFile(tfilename
,
223 GENERIC_READ
, FILE_SHARE_READ
,
226 FILE_ATTRIBUTE_NORMAL
,
229 if (res
->file_handle
== INVALID_HANDLE_VALUE
)
232 res
->size
= GetFileSize(res
->file_handle
, NULL
);
234 if (res
->size
== 0) {
235 log_info(LD_FS
,"File \"%s\" is empty. Ignoring.",filename
);
240 res
->mmap_handle
= CreateFileMapping(res
->file_handle
,
243 #if SIZEOF_SIZE_T > 4
244 (res
->base
.size
>> 32),
248 (res
->size
& 0xfffffffful
),
250 if (res
->mmap_handle
== NULL
)
252 res
->data
= (char*) MapViewOfFile(res
->mmap_handle
,
260 DWORD e
= GetLastError();
261 int severity
= (e
== ERROR_FILE_NOT_FOUND
|| e
== ERROR_PATH_NOT_FOUND
) ?
263 char *msg
= format_win32_error(e
);
264 log_fn(severity
, LD_FS
, "Couldn't mmap file \"%s\": %s", filename
, msg
);
266 if (e
== ERROR_FILE_NOT_FOUND
|| e
== ERROR_PATH_NOT_FOUND
)
274 tor_munmap_file(res
);
278 tor_munmap_file(tor_mmap_t
*handle
)
281 /* This is an ugly cast, but without it, "data" in struct tor_mmap_t would
282 have to be redefined as non-const. */
283 UnmapViewOfFile( (LPVOID
) handle
->data
);
285 if (handle
->mmap_handle
!= NULL
)
286 CloseHandle(handle
->mmap_handle
);
287 if (handle
->file_handle
!= INVALID_HANDLE_VALUE
)
288 CloseHandle(handle
->file_handle
);
293 tor_mmap_file(const char *filename
)
296 char *res
= read_file_to_str(filename
, RFTS_BIN
|RFTS_IGNORE_MISSING
, &st
);
300 handle
= tor_malloc_zero(sizeof(tor_mmap_t
));
302 handle
->size
= st
.st_size
;
306 tor_munmap_file(tor_mmap_t
*handle
)
308 char *d
= (char*)handle
->data
;
310 memset(handle
, 0, sizeof(tor_mmap_t
));
315 /** Replacement for snprintf. Differs from platform snprintf in two
316 * ways: First, always NUL-terminates its output. Second, always
317 * returns -1 if the result is truncated. (Note that this return
318 * behavior does <i>not</i> conform to C99; it just happens to be
319 * easier to emulate "return -1" with conformant implementations than
320 * it is to emulate "return number that would be written" with
321 * non-conformant implementations.) */
323 tor_snprintf(char *str
, size_t size
, const char *format
, ...)
328 r
= tor_vsnprintf(str
,size
,format
,ap
);
333 /** Replacement for vsnprintf; behavior differs as tor_snprintf differs from
337 tor_vsnprintf(char *str
, size_t size
, const char *format
, va_list args
)
341 return -1; /* no place for the NUL */
342 if (size
> SIZE_T_CEILING
)
345 r
= _vsnprintf(str
, size
, format
, args
);
347 r
= vsnprintf(str
, size
, format
, args
);
350 if (r
< 0 || r
>= (ssize_t
)size
)
356 * Portable asprintf implementation. Does a printf() into a newly malloc'd
357 * string. Sets *<b>strp</b> to this string, and returns its length (not
358 * including the terminating NUL character).
360 * You can treat this function as if its implementation were something like
362 char buf[_INFINITY_];
363 tor_snprintf(buf, sizeof(buf), fmt, args);
364 *strp = tor_strdup(buf);
365 return strlen(*strp):
367 * Where _INFINITY_ is an imaginary constant so big that any string can fit
371 tor_asprintf(char **strp
, const char *fmt
, ...)
376 r
= tor_vasprintf(strp
, fmt
, args
);
378 if (!*strp
|| r
< 0) {
379 log_err(LD_BUG
, "Internal error in asprintf");
386 * Portable vasprintf implementation. Does a printf() into a newly malloc'd
387 * string. Differs from regular vasprintf in the same ways that
388 * tor_asprintf() differs from regular asprintf.
391 tor_vasprintf(char **strp
, const char *fmt
, va_list args
)
393 /* use a temporary variable in case *strp is in args. */
395 #ifdef HAVE_VASPRINTF
396 /* If the platform gives us one, use it. */
397 int r
= vasprintf(&strp_tmp
, fmt
, args
);
403 #elif defined(_MSC_VER)
404 /* On Windows, _vsnprintf won't tell us the length of the string if it
405 * overflows, so we need to use _vcsprintf to tell how much to allocate */
408 len
= _vscprintf(fmt
, args
);
413 strp_tmp
= tor_malloc(len
+ 1);
414 r
= _vsnprintf(strp_tmp
, len
+1, fmt
, args
);
423 /* Everywhere else, we have a decent vsnprintf that tells us how many
424 * characters we need. We give it a try on a short buffer first, since
425 * it might be nice to avoid the second vsnprintf call.
430 va_copy(tmp_args
, args
);
431 len
= vsnprintf(buf
, sizeof(buf
), fmt
, tmp_args
);
433 if (len
< (int)sizeof(buf
)) {
434 *strp
= tor_strdup(buf
);
437 strp_tmp
= tor_malloc(len
+1);
438 r
= vsnprintf(strp_tmp
, len
+1, fmt
, args
);
449 /** Given <b>hlen</b> bytes at <b>haystack</b> and <b>nlen</b> bytes at
450 * <b>needle</b>, return a pointer to the first occurrence of the needle
451 * within the haystack, or NULL if there is no such occurrence.
453 * This function is <em>not</em> timing-safe.
455 * Requires that <b>nlen</b> be greater than zero.
458 tor_memmem(const void *_haystack
, size_t hlen
,
459 const void *_needle
, size_t nlen
)
461 #if defined(HAVE_MEMMEM) && (!defined(__GNUC__) || __GNUC__ >= 2)
463 return memmem(_haystack
, hlen
, _needle
, nlen
);
465 /* This isn't as fast as the GLIBC implementation, but it doesn't need to
468 const char *haystack
= (const char*)_haystack
;
469 const char *needle
= (const char*)_needle
;
474 end
= haystack
+ hlen
;
475 first
= *(const char*)needle
;
476 while ((p
= memchr(p
, first
, end
-p
))) {
479 if (fast_memeq(p
, needle
, nlen
))
487 /* Tables to implement ctypes-replacement TOR_IS*() functions. Each table
488 * has 256 bits to look up whether a character is in some set or not. This
489 * fails on non-ASCII platforms, but it is hard to find a platform whose
490 * character set is not a superset of ASCII nowadays. */
491 const uint32_t TOR_ISALPHA_TABLE
[8] =
492 { 0, 0, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
493 const uint32_t TOR_ISALNUM_TABLE
[8] =
494 { 0, 0x3ff0000, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
495 const uint32_t TOR_ISSPACE_TABLE
[8] = { 0x3e00, 0x1, 0, 0, 0, 0, 0, 0 };
496 const uint32_t TOR_ISXDIGIT_TABLE
[8] =
497 { 0, 0x3ff0000, 0x7e, 0x7e, 0, 0, 0, 0 };
498 const uint32_t TOR_ISDIGIT_TABLE
[8] = { 0, 0x3ff0000, 0, 0, 0, 0, 0, 0 };
499 const uint32_t TOR_ISPRINT_TABLE
[8] =
500 { 0, 0xffffffff, 0xffffffff, 0x7fffffff, 0, 0, 0, 0x0 };
501 const uint32_t TOR_ISUPPER_TABLE
[8] = { 0, 0, 0x7fffffe, 0, 0, 0, 0, 0 };
502 const uint32_t TOR_ISLOWER_TABLE
[8] = { 0, 0, 0, 0x7fffffe, 0, 0, 0, 0 };
503 /* Upper-casing and lowercasing tables to map characters to upper/lowercase
505 const char TOR_TOUPPER_TABLE
[256] = {
506 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
507 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
508 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
509 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
510 64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
511 80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
512 96,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
513 80,81,82,83,84,85,86,87,88,89,90,123,124,125,126,127,
514 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
515 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
516 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
517 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
518 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
519 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
520 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
521 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
523 const char TOR_TOLOWER_TABLE
[256] = {
524 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
525 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
526 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
527 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
528 64,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
529 112,113,114,115,116,117,118,119,120,121,122,91,92,93,94,95,
530 96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
531 112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
532 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
533 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
534 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
535 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
536 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
537 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
538 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
539 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
542 /** Implementation of strtok_r for platforms whose coders haven't figured out
543 * how to write one. Hey guys! You can use this code here for free! */
545 tor_strtok_r_impl(char *str
, const char *sep
, char **lasts
)
549 start
= cp
= *lasts
= str
;
557 while (*cp
&& !strchr(sep
, *cp
))
560 tor_assert(strlen(sep
) == 1);
561 cp
= strchr(cp
, *sep
);
574 /** Take a filename and return a pointer to its final element. This
575 * function is called on __FILE__ to fix a MSVC nit where __FILE__
576 * contains the full path to the file. This is bad, because it
577 * confuses users to find the home directory of the person who
578 * compiled the binary in their warning messages.
581 tor_fix_source_file(const char *fname
)
583 const char *cp1
, *cp2
, *r
;
584 cp1
= strrchr(fname
, '/');
585 cp2
= strrchr(fname
, '\\');
587 r
= (cp1
<cp2
)?(cp2
+1):(cp1
+1);
600 * Read a 16-bit value beginning at <b>cp</b>. Equivalent to
601 * *(uint16_t*)(cp), but will not cause segfaults on platforms that forbid
602 * unaligned memory access.
605 get_uint16(const void *cp
)
612 * Read a 32-bit value beginning at <b>cp</b>. Equivalent to
613 * *(uint32_t*)(cp), but will not cause segfaults on platforms that forbid
614 * unaligned memory access.
617 get_uint32(const void *cp
)
624 * Read a 64-bit value beginning at <b>cp</b>. Equivalent to
625 * *(uint64_t*)(cp), but will not cause segfaults on platforms that forbid
626 * unaligned memory access.
629 get_uint64(const void *cp
)
637 * Set a 16-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
638 * *(uint16_t*)(cp) = v, but will not cause segfaults on platforms that forbid
639 * unaligned memory access. */
641 set_uint16(void *cp
, uint16_t v
)
646 * Set a 32-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
647 * *(uint32_t*)(cp) = v, but will not cause segfaults on platforms that forbid
648 * unaligned memory access. */
650 set_uint32(void *cp
, uint32_t v
)
655 * Set a 64-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
656 * *(uint64_t*)(cp) = v, but will not cause segfaults on platforms that forbid
657 * unaligned memory access. */
659 set_uint64(void *cp
, uint64_t v
)
665 * Rename the file <b>from</b> to the file <b>to</b>. On Unix, this is
666 * the same as rename(2). On windows, this removes <b>to</b> first if
668 * Returns 0 on success. Returns -1 and sets errno on failure.
671 replace_file(const char *from
, const char *to
)
674 return rename(from
,to
);
676 switch (file_status(to
))
681 if (unlink(to
)) return -1;
689 return rename(from
,to
);
693 /** Change <b>fname</b>'s modification time to now. */
695 touch_file(const char *fname
)
697 if (utime(fname
, NULL
)!=0)
702 /** Represents a lockfile on which we hold the lock. */
703 struct tor_lockfile_t
{
704 /** Name of the file */
706 /** File descriptor used to hold the file open */
710 /** Try to get a lock on the lockfile <b>filename</b>, creating it as
711 * necessary. If someone else has the lock and <b>blocking</b> is true,
712 * wait until the lock is available. Otherwise return immediately whether
713 * we succeeded or not.
715 * Set *<b>locked_out</b> to true if somebody else had the lock, and to false
718 * Return a <b>tor_lockfile_t</b> on success, NULL on failure.
720 * (Implementation note: because we need to fall back to fcntl on some
721 * platforms, these locks are per-process, not per-thread. If you want
722 * to do in-process locking, use tor_mutex_t like a normal person.
723 * On Windows, when <b>blocking</b> is true, the maximum time that
724 * is actually waited is 10 seconds, after which NULL is returned
725 * and <b>locked_out</b> is set to 1.)
728 tor_lockfile_lock(const char *filename
, int blocking
, int *locked_out
)
730 tor_lockfile_t
*result
;
734 log_info(LD_FS
, "Locking \"%s\"", filename
);
735 fd
= tor_open_cloexec(filename
, O_RDWR
|O_CREAT
|O_TRUNC
, 0600);
737 log_warn(LD_FS
,"Couldn't open \"%s\" for locking: %s", filename
,
743 _lseek(fd
, 0, SEEK_SET
);
744 if (_locking(fd
, blocking
? _LK_LOCK
: _LK_NBLCK
, 1) < 0) {
745 if (errno
!= EACCES
&& errno
!= EDEADLOCK
)
746 log_warn(LD_FS
,"Couldn't lock \"%s\": %s", filename
, strerror(errno
));
752 #elif defined(HAVE_FLOCK)
753 if (flock(fd
, LOCK_EX
|(blocking
? 0 : LOCK_NB
)) < 0) {
754 if (errno
!= EWOULDBLOCK
)
755 log_warn(LD_FS
,"Couldn't lock \"%s\": %s", filename
, strerror(errno
));
764 memset(&lock
, 0, sizeof(lock
));
765 lock
.l_type
= F_WRLCK
;
766 lock
.l_whence
= SEEK_SET
;
767 if (fcntl(fd
, blocking
? F_SETLKW
: F_SETLK
, &lock
) < 0) {
768 if (errno
!= EACCES
&& errno
!= EAGAIN
)
769 log_warn(LD_FS
, "Couldn't lock \"%s\": %s", filename
, strerror(errno
));
778 result
= tor_malloc(sizeof(tor_lockfile_t
));
779 result
->filename
= tor_strdup(filename
);
784 /** Release the lock held as <b>lockfile</b>. */
786 tor_lockfile_unlock(tor_lockfile_t
*lockfile
)
788 tor_assert(lockfile
);
790 log_info(LD_FS
, "Unlocking \"%s\"", lockfile
->filename
);
792 _lseek(lockfile
->fd
, 0, SEEK_SET
);
793 if (_locking(lockfile
->fd
, _LK_UNLCK
, 1) < 0) {
794 log_warn(LD_FS
,"Error unlocking \"%s\": %s", lockfile
->filename
,
797 #elif defined(HAVE_FLOCK)
798 if (flock(lockfile
->fd
, LOCK_UN
) < 0) {
799 log_warn(LD_FS
, "Error unlocking \"%s\": %s", lockfile
->filename
,
803 /* Closing the lockfile is sufficient. */
808 tor_free(lockfile
->filename
);
813 /** Some old versions of Unix didn't define constants for these values,
814 * and instead expect you to say 0, 1, or 2. */
823 /** Return the position of <b>fd</b> with respect to the start of the file. */
825 tor_fd_getpos(int fd
)
828 return (off_t
) _lseek(fd
, 0, SEEK_CUR
);
830 return (off_t
) lseek(fd
, 0, SEEK_CUR
);
834 /** Move <b>fd</b> to the end of the file. Return -1 on error, 0 on success. */
836 tor_fd_seekend(int fd
)
839 return _lseek(fd
, 0, SEEK_END
) < 0 ? -1 : 0;
841 return lseek(fd
, 0, SEEK_END
) < 0 ? -1 : 0;
845 #undef DEBUG_SOCKET_COUNTING
846 #ifdef DEBUG_SOCKET_COUNTING
847 /** A bitarray of all fds that should be passed to tor_socket_close(). Only
848 * used if DEBUG_SOCKET_COUNTING is defined. */
849 static bitarray_t
*open_sockets
= NULL
;
850 /** The size of <b>open_sockets</b>, in bits. */
851 static int max_socket
= -1;
854 /** Count of number of sockets currently open. (Undercounts sockets opened by
855 * eventdns and libevent.) */
856 static int n_sockets_open
= 0;
858 /** Mutex to protect open_sockets, max_socket, and n_sockets_open. */
859 static tor_mutex_t
*socket_accounting_mutex
= NULL
;
861 /** Helper: acquire the socket accounting lock. */
863 socket_accounting_lock(void)
865 if (PREDICT_UNLIKELY(!socket_accounting_mutex
))
866 socket_accounting_mutex
= tor_mutex_new();
867 tor_mutex_acquire(socket_accounting_mutex
);
870 /** Helper: release the socket accounting lock. */
872 socket_accounting_unlock(void)
874 tor_mutex_release(socket_accounting_mutex
);
877 /** As close(), but guaranteed to work for sockets across platforms (including
878 * Windows, where close()ing a socket doesn't work. Returns 0 on success, -1
881 tor_close_socket(tor_socket_t s
)
885 /* On Windows, you have to call close() on fds returned by open(),
886 * and closesocket() on fds returned by socket(). On Unix, everything
887 * gets close()'d. We abstract this difference by always using
888 * tor_close_socket to close sockets, and always using close() on
891 #if defined(MS_WINDOWS)
897 socket_accounting_lock();
898 #ifdef DEBUG_SOCKET_COUNTING
899 if (s
> max_socket
|| ! bitarray_is_set(open_sockets
, s
)) {
900 log_warn(LD_BUG
, "Closing a socket (%d) that wasn't returned by tor_open_"
901 "socket(), or that was already closed or something.", s
);
903 tor_assert(open_sockets
&& s
<= max_socket
);
904 bitarray_clear(open_sockets
, s
);
910 int err
= tor_socket_errno(-1);
911 log_info(LD_NET
, "Close returned an error: %s", tor_socket_strerror(err
));
913 if (err
!= WSAENOTSOCK
)
922 if (n_sockets_open
< 0)
923 log_warn(LD_BUG
, "Our socket count is below zero: %d. Please submit a "
924 "bug report.", n_sockets_open
);
925 socket_accounting_unlock();
930 #ifdef DEBUG_SOCKET_COUNTING
931 /** Helper: if DEBUG_SOCKET_COUNTING is enabled, remember that <b>s</b> is
932 * now an open socket. */
934 mark_socket_open(tor_socket_t s
)
936 /* XXXX This bitarray business will NOT work on windows: sockets aren't
938 if (s
> max_socket
) {
939 if (max_socket
== -1) {
940 open_sockets
= bitarray_init_zero(s
+128);
943 open_sockets
= bitarray_expand(open_sockets
, max_socket
, s
+128);
947 if (bitarray_is_set(open_sockets
, s
)) {
948 log_warn(LD_BUG
, "I thought that %d was already open, but socket() just "
949 "gave it to me!", s
);
951 bitarray_set(open_sockets
, s
);
954 #define mark_socket_open(s) STMT_NIL
958 /** As socket(), but counts the number of open sockets. */
960 tor_open_socket(int domain
, int type
, int protocol
)
964 #define LINUX_CLOEXEC_OPEN_SOCKET
965 type
|= SOCK_CLOEXEC
;
967 s
= socket(domain
, type
, protocol
);
969 #if !defined(LINUX_CLOEXEC_OPEN_SOCKET) && defined(FD_CLOEXEC)
970 fcntl(s
, F_SETFD
, FD_CLOEXEC
);
972 socket_accounting_lock();
975 socket_accounting_unlock();
980 /** As socket(), but counts the number of open sockets. */
982 tor_accept_socket(tor_socket_t sockfd
, struct sockaddr
*addr
, socklen_t
*len
)
985 #if defined(HAVE_ACCEPT4) && defined(SOCK_CLOEXEC)
986 #define LINUX_CLOEXEC_ACCEPT
987 s
= accept4(sockfd
, addr
, len
, SOCK_CLOEXEC
);
989 s
= accept(sockfd
, addr
, len
);
992 #if !defined(LINUX_CLOEXEC_ACCEPT) && defined(FD_CLOEXEC)
993 fcntl(s
, F_SETFD
, FD_CLOEXEC
);
995 socket_accounting_lock();
998 socket_accounting_unlock();
1003 /** Return the number of sockets we currently have opened. */
1005 get_n_open_sockets(void)
1008 socket_accounting_lock();
1010 socket_accounting_unlock();
1014 /** Turn <b>socket</b> into a nonblocking socket.
1017 set_socket_nonblocking(tor_socket_t socket
)
1019 #if defined(MS_WINDOWS)
1020 unsigned long nonblocking
= 1;
1021 ioctlsocket(socket
, FIONBIO
, (unsigned long*) &nonblocking
);
1023 fcntl(socket
, F_SETFL
, O_NONBLOCK
);
1028 * Allocate a pair of connected sockets. (Like socketpair(family,
1029 * type,protocol,fd), but works on systems that don't have
1032 * Currently, only (AF_UNIX, SOCK_STREAM, 0) sockets are supported.
1034 * Note that on systems without socketpair, this call will fail if
1035 * localhost is inaccessible (for example, if the networking
1036 * stack is down). And even if it succeeds, the socket pair will not
1037 * be able to read while localhost is down later (the socket pair may
1038 * even close, depending on OS-specific timeouts).
1040 * Returns 0 on success and -errno on failure; do not rely on the value
1041 * of errno or WSAGetLastError().
1043 /* It would be nicer just to set errno, but that won't work for windows. */
1045 tor_socketpair(int family
, int type
, int protocol
, tor_socket_t fd
[2])
1047 //don't use win32 socketpairs (they are always bad)
1048 #if defined(HAVE_SOCKETPAIR) && !defined(MS_WINDOWS)
1051 type
|= SOCK_CLOEXEC
;
1053 r
= socketpair(family
, type
, protocol
, fd
);
1055 #if !defined(SOCK_CLOEXEC) && defined(FD_CLOEXEC)
1057 fcntl(fd
[0], F_SETFD
, FD_CLOEXEC
);
1059 fcntl(fd
[1], F_SETFD
, FD_CLOEXEC
);
1061 socket_accounting_lock();
1064 mark_socket_open(fd
[0]);
1068 mark_socket_open(fd
[1]);
1070 socket_accounting_unlock();
1072 return r
< 0 ? -errno
: r
;
1074 /* This socketpair does not work when localhost is down. So
1075 * it's really not the same thing at all. But it's close enough
1076 * for now, and really, when localhost is down sometimes, we
1077 * have other problems too.
1079 tor_socket_t listener
= -1;
1080 tor_socket_t connector
= -1;
1081 tor_socket_t acceptor
= -1;
1082 struct sockaddr_in listen_addr
;
1083 struct sockaddr_in connect_addr
;
1085 int saved_errno
= -1;
1089 || family
!= AF_UNIX
1093 return -WSAEAFNOSUPPORT
;
1095 return -EAFNOSUPPORT
;
1102 listener
= tor_open_socket(AF_INET
, type
, 0);
1104 return -tor_socket_errno(-1);
1105 memset(&listen_addr
, 0, sizeof(listen_addr
));
1106 listen_addr
.sin_family
= AF_INET
;
1107 listen_addr
.sin_addr
.s_addr
= htonl(INADDR_LOOPBACK
);
1108 listen_addr
.sin_port
= 0; /* kernel chooses port. */
1109 if (bind(listener
, (struct sockaddr
*) &listen_addr
, sizeof (listen_addr
))
1111 goto tidy_up_and_fail
;
1112 if (listen(listener
, 1) == -1)
1113 goto tidy_up_and_fail
;
1115 connector
= tor_open_socket(AF_INET
, type
, 0);
1117 goto tidy_up_and_fail
;
1118 /* We want to find out the port number to connect to. */
1119 size
= sizeof(connect_addr
);
1120 if (getsockname(listener
, (struct sockaddr
*) &connect_addr
, &size
) == -1)
1121 goto tidy_up_and_fail
;
1122 if (size
!= sizeof (connect_addr
))
1123 goto abort_tidy_up_and_fail
;
1124 if (connect(connector
, (struct sockaddr
*) &connect_addr
,
1125 sizeof(connect_addr
)) == -1)
1126 goto tidy_up_and_fail
;
1128 size
= sizeof(listen_addr
);
1129 acceptor
= tor_accept_socket(listener
,
1130 (struct sockaddr
*) &listen_addr
, &size
);
1132 goto tidy_up_and_fail
;
1133 if (size
!= sizeof(listen_addr
))
1134 goto abort_tidy_up_and_fail
;
1135 tor_close_socket(listener
);
1136 /* Now check we are talking to ourself by matching port and host on the
1138 if (getsockname(connector
, (struct sockaddr
*) &connect_addr
, &size
) == -1)
1139 goto tidy_up_and_fail
;
1140 if (size
!= sizeof (connect_addr
)
1141 || listen_addr
.sin_family
!= connect_addr
.sin_family
1142 || listen_addr
.sin_addr
.s_addr
!= connect_addr
.sin_addr
.s_addr
1143 || listen_addr
.sin_port
!= connect_addr
.sin_port
) {
1144 goto abort_tidy_up_and_fail
;
1151 abort_tidy_up_and_fail
:
1153 saved_errno
= WSAECONNABORTED
;
1155 saved_errno
= ECONNABORTED
; /* I hope this is portable and appropriate. */
1158 if (saved_errno
< 0)
1159 saved_errno
= errno
;
1161 tor_close_socket(listener
);
1162 if (connector
!= -1)
1163 tor_close_socket(connector
);
1165 tor_close_socket(acceptor
);
1166 return -saved_errno
;
1170 /** Number of extra file descriptors to keep in reserve beyond those that we
1171 * tell Tor it's allowed to use. */
1172 #define ULIMIT_BUFFER 32 /* keep 32 extra fd's beyond _ConnLimit */
1174 /** Learn the maximum allowed number of file descriptors. (Some systems
1175 * have a low soft limit.
1177 * We compute this by finding the largest number that we can use.
1178 * If we can't find a number greater than or equal to <b>limit</b>,
1179 * then we fail: return -1.
1181 * Otherwise, return 0 and store the maximum we found inside <b>max_out</b>.*/
1183 set_max_file_descriptors(rlim_t limit
, int *max_out
)
1185 /* Define some maximum connections values for systems where we cannot
1186 * automatically determine a limit. Re Cygwin, see
1187 * http://archives.seul.org/or/talk/Aug-2006/msg00210.html
1188 * For an iPhone, 9999 should work. For Windows and all other unknown
1189 * systems we use 15000 as the default. */
1190 #ifndef HAVE_GETRLIMIT
1191 #if defined(CYGWIN) || defined(__CYGWIN__)
1192 const char *platform
= "Cygwin";
1193 const unsigned long MAX_CONNECTIONS
= 3200;
1194 #elif defined(MS_WINDOWS)
1195 const char *platform
= "Windows";
1196 const unsigned long MAX_CONNECTIONS
= 15000;
1198 const char *platform
= "unknown platforms with no getrlimit()";
1199 const unsigned long MAX_CONNECTIONS
= 15000;
1201 log_fn(LOG_INFO
, LD_NET
,
1202 "This platform is missing getrlimit(). Proceeding.");
1203 if (limit
> MAX_CONNECTIONS
) {
1205 "We do not support more than %lu file descriptors "
1206 "on %s. Tried to raise to %lu.",
1207 (unsigned long)MAX_CONNECTIONS
, platform
, (unsigned long)limit
);
1210 limit
= MAX_CONNECTIONS
;
1211 #else /* HAVE_GETRLIMIT */
1213 tor_assert(limit
> 0);
1215 if (getrlimit(RLIMIT_NOFILE
, &rlim
) != 0) {
1216 log_warn(LD_NET
, "Could not get maximum number of file descriptors: %s",
1221 if (rlim
.rlim_max
< limit
) {
1222 log_warn(LD_CONFIG
,"We need %lu file descriptors available, and we're "
1223 "limited to %lu. Please change your ulimit -n.",
1224 (unsigned long)limit
, (unsigned long)rlim
.rlim_max
);
1228 if (rlim
.rlim_max
> rlim
.rlim_cur
) {
1229 log_info(LD_NET
,"Raising max file descriptors from %lu to %lu.",
1230 (unsigned long)rlim
.rlim_cur
, (unsigned long)rlim
.rlim_max
);
1232 rlim
.rlim_cur
= rlim
.rlim_max
;
1234 if (setrlimit(RLIMIT_NOFILE
, &rlim
) != 0) {
1237 if (errno
== EINVAL
&& OPEN_MAX
< rlim
.rlim_cur
) {
1238 /* On some platforms, OPEN_MAX is the real limit, and getrlimit() is
1239 * full of nasty lies. I'm looking at you, OSX 10.5.... */
1240 rlim
.rlim_cur
= OPEN_MAX
;
1241 if (setrlimit(RLIMIT_NOFILE
, &rlim
) == 0) {
1242 if (rlim
.rlim_cur
< (rlim_t
)limit
) {
1243 log_warn(LD_CONFIG
, "We are limited to %lu file descriptors by "
1244 "OPEN_MAX, and ConnLimit is %lu. Changing ConnLimit; sorry.",
1245 (unsigned long)OPEN_MAX
, (unsigned long)limit
);
1247 log_info(LD_CONFIG
, "Dropped connection limit to OPEN_MAX (%lu); "
1248 "Apparently, %lu was too high and rlimit lied to us.",
1249 (unsigned long)OPEN_MAX
, (unsigned long)rlim
.rlim_max
);
1254 #endif /* OPEN_MAX */
1256 log_warn(LD_CONFIG
,"Couldn't set maximum number of file descriptors: %s",
1261 /* leave some overhead for logs, etc, */
1262 limit
= rlim
.rlim_cur
;
1263 #endif /* HAVE_GETRLIMIT */
1265 if (limit
< ULIMIT_BUFFER
) {
1267 "ConnLimit must be at least %d. Failing.", ULIMIT_BUFFER
);
1270 if (limit
> INT_MAX
)
1272 tor_assert(max_out
);
1273 *max_out
= (int)limit
- ULIMIT_BUFFER
;
1278 /** Log details of current user and group credentials. Return 0 on
1279 * success. Logs and return -1 on failure.
1282 log_credential_status(void)
1284 /** Log level to use when describing non-error UID/GID status. */
1285 #define CREDENTIAL_LOG_LEVEL LOG_INFO
1286 /* Real, effective and saved UIDs */
1287 uid_t ruid
, euid
, suid
;
1288 /* Read, effective and saved GIDs */
1289 gid_t rgid
, egid
, sgid
;
1290 /* Supplementary groups */
1291 gid_t
*sup_gids
= NULL
;
1293 /* Number of supplementary groups */
1297 #ifdef HAVE_GETRESUID
1298 if (getresuid(&ruid
, &euid
, &suid
) != 0 ) {
1299 log_warn(LD_GENERAL
, "Error getting changed UIDs: %s", strerror(errno
));
1302 log_fn(CREDENTIAL_LOG_LEVEL
, LD_GENERAL
,
1303 "UID is %u (real), %u (effective), %u (saved)",
1304 (unsigned)ruid
, (unsigned)euid
, (unsigned)suid
);
1307 /* getresuid is not present on MacOS X, so we can't get the saved (E)UID */
1312 log_fn(CREDENTIAL_LOG_LEVEL
, LD_GENERAL
,
1313 "UID is %u (real), %u (effective), unknown (saved)",
1314 (unsigned)ruid
, (unsigned)euid
);
1318 #ifdef HAVE_GETRESGID
1319 if (getresgid(&rgid
, &egid
, &sgid
) != 0 ) {
1320 log_warn(LD_GENERAL
, "Error getting changed GIDs: %s", strerror(errno
));
1323 log_fn(CREDENTIAL_LOG_LEVEL
, LD_GENERAL
,
1324 "GID is %u (real), %u (effective), %u (saved)",
1325 (unsigned)rgid
, (unsigned)egid
, (unsigned)sgid
);
1328 /* getresgid is not present on MacOS X, so we can't get the saved (E)GID */
1332 log_fn(CREDENTIAL_LOG_LEVEL
, LD_GENERAL
,
1333 "GID is %u (real), %u (effective), unknown (saved)",
1334 (unsigned)rgid
, (unsigned)egid
);
1337 /* log supplementary groups */
1339 sup_gids
= tor_malloc(sizeof(gid_t
) * 64);
1340 while ((ngids
= getgroups(sup_gids_size
, sup_gids
)) < 0 &&
1342 sup_gids_size
< NGROUPS_MAX
) {
1344 sup_gids
= tor_realloc(sup_gids
, sizeof(gid_t
) * sup_gids_size
);
1348 log_warn(LD_GENERAL
, "Error getting supplementary GIDs: %s",
1356 smartlist_t
*elts
= smartlist_create();
1358 for (i
= 0; i
<ngids
; i
++) {
1359 strgid
= tor_malloc(11);
1360 if (tor_snprintf(strgid
, 11, "%u", (unsigned)sup_gids
[i
]) < 0) {
1361 log_warn(LD_GENERAL
, "Error printing supplementary GIDs");
1366 smartlist_add(elts
, strgid
);
1369 s
= smartlist_join_strings(elts
, " ", 0, NULL
);
1371 log_fn(CREDENTIAL_LOG_LEVEL
, LD_GENERAL
, "Supplementary groups are: %s",s
);
1375 SMARTLIST_FOREACH(elts
, char *, cp
,
1379 smartlist_free(elts
);
1389 /** Call setuid and setgid to run as <b>user</b> and switch to their
1390 * primary group. Return 0 on success. On failure, log and return -1.
1393 switch_id(const char *user
)
1396 struct passwd
*pw
= NULL
;
1399 static int have_already_switched_id
= 0;
1403 if (have_already_switched_id
)
1406 /* Log the initial credential state */
1407 if (log_credential_status())
1410 log_fn(CREDENTIAL_LOG_LEVEL
, LD_GENERAL
, "Changing user and groups");
1412 /* Get old UID/GID to check if we changed correctly */
1416 /* Lookup the user and group information, if we have a problem, bail out. */
1417 pw
= getpwnam(user
);
1419 log_warn(LD_CONFIG
, "Error setting configured user: %s not found", user
);
1423 /* Properly switch egid,gid,euid,uid here or bail out */
1424 if (setgroups(1, &pw
->pw_gid
)) {
1425 log_warn(LD_GENERAL
, "Error setting groups to gid %d: \"%s\".",
1426 (int)pw
->pw_gid
, strerror(errno
));
1427 if (old_uid
== pw
->pw_uid
) {
1428 log_warn(LD_GENERAL
, "Tor is already running as %s. You do not need "
1429 "the \"User\" option if you are already running as the user "
1430 "you want to be. (If you did not set the User option in your "
1431 "torrc, check whether it was specified on the command line "
1432 "by a startup script.)", user
);
1434 log_warn(LD_GENERAL
, "If you set the \"User\" option, you must start Tor"
1440 if (setegid(pw
->pw_gid
)) {
1441 log_warn(LD_GENERAL
, "Error setting egid to %d: %s",
1442 (int)pw
->pw_gid
, strerror(errno
));
1446 if (setgid(pw
->pw_gid
)) {
1447 log_warn(LD_GENERAL
, "Error setting gid to %d: %s",
1448 (int)pw
->pw_gid
, strerror(errno
));
1452 if (setuid(pw
->pw_uid
)) {
1453 log_warn(LD_GENERAL
, "Error setting configured uid to %s (%d): %s",
1454 user
, (int)pw
->pw_uid
, strerror(errno
));
1458 if (seteuid(pw
->pw_uid
)) {
1459 log_warn(LD_GENERAL
, "Error setting configured euid to %s (%d): %s",
1460 user
, (int)pw
->pw_uid
, strerror(errno
));
1464 /* This is how OpenBSD rolls:
1465 if (setgroups(1, &pw->pw_gid) || setegid(pw->pw_gid) ||
1466 setgid(pw->pw_gid) || setuid(pw->pw_uid) || seteuid(pw->pw_uid)) {
1467 setgid(pw->pw_gid) || seteuid(pw->pw_uid) || setuid(pw->pw_uid)) {
1468 log_warn(LD_GENERAL, "Error setting configured UID/GID: %s",
1474 /* We've properly switched egid, gid, euid, uid, and supplementary groups if
1477 #if !defined(CYGWIN) && !defined(__CYGWIN__)
1478 /* If we tried to drop privilege to a group/user other than root, attempt to
1479 * restore root (E)(U|G)ID, and abort if the operation succeeds */
1481 /* Only check for privilege dropping if we were asked to be non-root */
1483 /* Try changing GID/EGID */
1484 if (pw
->pw_gid
!= old_gid
&&
1485 (setgid(old_gid
) != -1 || setegid(old_gid
) != -1)) {
1486 log_warn(LD_GENERAL
, "Was able to restore group credentials even after "
1487 "switching GID: this means that the setgid code didn't work.");
1491 /* Try changing UID/EUID */
1492 if (pw
->pw_uid
!= old_uid
&&
1493 (setuid(old_uid
) != -1 || seteuid(old_uid
) != -1)) {
1494 log_warn(LD_GENERAL
, "Was able to restore user credentials even after "
1495 "switching UID: this means that the setuid code didn't work.");
1501 /* Check what really happened */
1502 if (log_credential_status()) {
1506 have_already_switched_id
= 1; /* mark success so we never try again */
1508 #if defined(__linux__) && defined(HAVE_SYS_PRCTL_H) && defined(HAVE_PRCTL)
1509 #ifdef PR_SET_DUMPABLE
1511 /* Re-enable core dumps if we're not running as root. */
1512 log_info(LD_CONFIG
, "Re-enabling coredumps");
1513 if (prctl(PR_SET_DUMPABLE
, 1)) {
1514 log_warn(LD_CONFIG
, "Unable to re-enable coredumps: %s",strerror(errno
));
1525 "User specified but switching users is unsupported on your OS.");
1530 /* We only use the linux prctl for now. There is no Win32 support; this may
1531 * also work on various BSD systems and Mac OS X - send testing feedback!
1533 * On recent Gnu/Linux kernels it is possible to create a system-wide policy
1534 * that will prevent non-root processes from attaching to other processes
1535 * unless they are the parent process; thus gdb can attach to programs that
1536 * they execute but they cannot attach to other processes running as the same
1537 * user. The system wide policy may be set with the sysctl
1538 * kernel.yama.ptrace_scope or by inspecting
1539 * /proc/sys/kernel/yama/ptrace_scope and it is 1 by default on Ubuntu 11.04.
1541 * This ptrace scope will be ignored on Gnu/Linux for users with
1542 * CAP_SYS_PTRACE and so it is very likely that root will still be able to
1543 * attach to the Tor process.
1545 /** Attempt to disable debugger attachment: return 1 on success, -1 on
1546 * failure, and 0 if we don't know how to try on this platform. */
1548 tor_disable_debugger_attach(void)
1553 log_debug(LD_CONFIG
,
1554 "Attemping to disable debugger attachment to Tor for "
1555 "unprivileged users.");
1556 #if defined(__linux__) && defined(HAVE_SYS_PRCTL_H) && defined(HAVE_PRCTL)
1557 #ifdef PR_SET_DUMPABLE
1559 r
= prctl(PR_SET_DUMPABLE
, 0);
1562 #if defined(__APPLE__) && defined(PT_DENY_ATTACH)
1565 r
= ptrace(PT_DENY_ATTACH
, 0, 0, 0);
1569 // XXX: TODO - Mac OS X has dtrace and this may be disabled.
1570 // XXX: TODO - Windows probably has something similar
1571 if (r
== 0 && attempted
) {
1572 log_debug(LD_CONFIG
,"Debugger attachment disabled for "
1573 "unprivileged users.");
1575 } else if (attempted
) {
1576 log_warn(LD_CONFIG
, "Unable to disable debugger attaching: %s",
1583 /** Allocate and return a string containing the home directory for the
1584 * user <b>username</b>. Only works on posix-like systems. */
1586 get_user_homedir(const char *username
)
1589 tor_assert(username
);
1591 if (!(pw
= getpwnam(username
))) {
1592 log_err(LD_CONFIG
,"User \"%s\" not found.", username
);
1595 return tor_strdup(pw
->pw_dir
);
1599 /** Modify <b>fname</b> to contain the name of the directory */
1601 get_parent_directory(char *fname
)
1607 /* If we start with, say, c:, then don't consider that the start of the path
1609 if (fname
[0] && fname
[1] == ':') {
1613 /* Now we want to remove all path-separators at the end of the string,
1614 * and to remove the end of the string starting with the path separator
1615 * before the last non-path-separator. In perl, this would be
1616 * s#[/]*$##; s#/[^/]*$##;
1617 * on a unixy platform.
1619 cp
= fname
+ strlen(fname
);
1621 while (--cp
> fname
) {
1622 int is_sep
= (*cp
== '/'
1638 /** Expand possibly relative path <b>fname</b> to an absolute path.
1639 * Return a newly allocated string, possibly equal to <b>fname</b>. */
1641 make_path_absolute(char *fname
)
1644 char *absfname_malloced
= _fullpath(NULL
, fname
, 1);
1646 /* We don't want to assume that tor_free can free a string allocated
1647 * with malloc. On failure, return fname (it's better than nothing). */
1648 char *absfname
= tor_strdup(absfname_malloced
? absfname_malloced
: fname
);
1649 if (absfname_malloced
) free(absfname_malloced
);
1653 char path
[PATH_MAX
+1];
1654 char *absfname
= NULL
;
1658 if (fname
[0] == '/') {
1659 absfname
= tor_strdup(fname
);
1661 if (getcwd(path
, PATH_MAX
) != NULL
) {
1662 tor_asprintf(&absfname
, "%s/%s", path
, fname
);
1664 /* If getcwd failed, the best we can do here is keep using the
1665 * relative path. (Perhaps / isn't readable by this UID/GID.) */
1666 absfname
= tor_strdup(fname
);
1674 /** Set *addr to the IP address (in dotted-quad notation) stored in c.
1675 * Return 1 on success, 0 if c is badly formatted. (Like inet_aton(c,addr),
1676 * but works on Windows and Solaris.)
1679 tor_inet_aton(const char *str
, struct in_addr
* addr
)
1683 if (tor_sscanf(str
, "%3u.%3u.%3u.%3u%c", &a
,&b
,&c
,&d
,&more
) != 4)
1685 if (a
> 255) return 0;
1686 if (b
> 255) return 0;
1687 if (c
> 255) return 0;
1688 if (d
> 255) return 0;
1689 addr
->s_addr
= htonl((a
<<24) | (b
<<16) | (c
<<8) | d
);
1693 /** Given <b>af</b>==AF_INET and <b>src</b> a struct in_addr, or
1694 * <b>af</b>==AF_INET6 and <b>src</b> a struct in6_addr, try to format the
1695 * address and store it in the <b>len</b>-byte buffer <b>dst</b>. Returns
1696 * <b>dst</b> on success, NULL on failure.
1698 * (Like inet_ntop(af,src,dst,len), but works on platforms that don't have it:
1699 * Tor sometimes needs to format ipv6 addresses even on platforms without ipv6
1702 tor_inet_ntop(int af
, const void *src
, char *dst
, size_t len
)
1704 if (af
== AF_INET
) {
1705 if (tor_inet_ntoa(src
, dst
, len
) < 0)
1709 } else if (af
== AF_INET6
) {
1710 const struct in6_addr
*addr
= src
;
1712 int longestGapLen
= 0, longestGapPos
= -1, i
,
1713 curGapPos
= -1, curGapLen
= 0;
1715 for (i
= 0; i
< 8; ++i
) {
1716 words
[i
] = (((uint16_t)addr
->s6_addr
[2*i
])<<8) + addr
->s6_addr
[2*i
+1];
1718 if (words
[0] == 0 && words
[1] == 0 && words
[2] == 0 && words
[3] == 0 &&
1719 words
[4] == 0 && ((words
[5] == 0 && words
[6] && words
[7]) ||
1720 (words
[5] == 0xffff))) {
1721 /* This is an IPv4 address. */
1722 if (words
[5] == 0) {
1723 tor_snprintf(buf
, sizeof(buf
), "::%d.%d.%d.%d",
1724 addr
->s6_addr
[12], addr
->s6_addr
[13],
1725 addr
->s6_addr
[14], addr
->s6_addr
[15]);
1727 tor_snprintf(buf
, sizeof(buf
), "::%x:%d.%d.%d.%d", words
[5],
1728 addr
->s6_addr
[12], addr
->s6_addr
[13],
1729 addr
->s6_addr
[14], addr
->s6_addr
[15]);
1731 if ((strlen(buf
) + 1) > len
) /* +1 for \0 */
1733 strlcpy(dst
, buf
, len
);
1738 if (words
[i
] == 0) {
1741 while (i
<8 && words
[i
] == 0) {
1744 if (curGapLen
> longestGapLen
) {
1745 longestGapPos
= curGapPos
;
1746 longestGapLen
= curGapLen
;
1752 if (longestGapLen
<=1)
1756 for (i
= 0; i
< 8; ++i
) {
1757 if (words
[i
] == 0 && longestGapPos
== i
) {
1761 while (i
< 8 && words
[i
] == 0)
1763 --i
; /* to compensate for loop increment. */
1765 tor_snprintf(cp
, sizeof(buf
)-(cp
-buf
), "%x", (unsigned)words
[i
]);
1772 if ((strlen(buf
) + 1) > len
) /* +1 for \0 */
1774 strlcpy(dst
, buf
, len
);
1781 /** Given <b>af</b>==AF_INET or <b>af</b>==AF_INET6, and a string <b>src</b>
1782 * encoding an IPv4 address or IPv6 address correspondingly, try to parse the
1783 * address and store the result in <b>dst</b> (which must have space for a
1784 * struct in_addr or a struct in6_addr, as appropriate). Return 1 on success,
1785 * 0 on a bad parse, and -1 on a bad <b>af</b>.
1787 * (Like inet_pton(af,src,dst) but works on platforms that don't have it: Tor
1788 * sometimes needs to format ipv6 addresses even on platforms without ipv6
1791 tor_inet_pton(int af
, const char *src
, void *dst
)
1793 if (af
== AF_INET
) {
1794 return tor_inet_aton(src
, dst
);
1795 } else if (af
== AF_INET6
) {
1796 struct in6_addr
*out
= dst
;
1798 int gapPos
= -1, i
, setWords
=0;
1799 const char *dot
= strchr(src
, '.');
1800 const char *eow
; /* end of words. */
1804 eow
= src
+strlen(src
);
1806 unsigned byte1
,byte2
,byte3
,byte4
;
1808 for (eow
= dot
-1; eow
>= src
&& TOR_ISDIGIT(*eow
); --eow
)
1812 /* We use "scanf" because some platform inet_aton()s are too lax
1813 * about IPv4 addresses of the form "1.2.3" */
1814 if (tor_sscanf(eow
, "%3u.%3u.%3u.%3u%c",
1815 &byte1
,&byte2
,&byte3
,&byte4
,&more
) != 4)
1818 if (byte1
> 255 || byte2
> 255 || byte3
> 255 || byte4
> 255)
1821 words
[6] = (byte1
<<8) | byte2
;
1822 words
[7] = (byte3
<<8) | byte4
;
1830 if (TOR_ISXDIGIT(*src
)) {
1833 long r
= strtol(src
, &next
, 16);
1834 tor_assert(next
!= NULL
);
1835 tor_assert(next
!= src
);
1837 len
= *next
== '\0' ? eow
- src
: next
- src
;
1840 if (len
> 1 && !TOR_ISXDIGIT(src
[1]))
1841 return 0; /* 0x is not valid */
1844 tor_assert(r
< 65536);
1845 words
[i
++] = (uint16_t)r
;
1848 if (*src
!= ':' && src
!= eow
)
1851 } else if (*src
== ':' && i
> 0 && gapPos
== -1) {
1854 } else if (*src
== ':' && i
== 0 && src
+1 < eow
&& src
[1] == ':' &&
1864 (setWords
== 8 && gapPos
!= -1) ||
1865 (setWords
< 8 && gapPos
== -1))
1869 int nToMove
= setWords
- (dot
? 2 : 0) - gapPos
;
1870 int gapLen
= 8 - setWords
;
1871 tor_assert(nToMove
>= 0);
1872 memmove(&words
[gapPos
+gapLen
], &words
[gapPos
],
1873 sizeof(uint16_t)*nToMove
);
1874 memset(&words
[gapPos
], 0, sizeof(uint16_t)*gapLen
);
1876 for (i
= 0; i
< 8; ++i
) {
1877 out
->s6_addr
[2*i
] = words
[i
] >> 8;
1878 out
->s6_addr
[2*i
+1] = words
[i
] & 0xff;
1887 /** Similar behavior to Unix gethostbyname: resolve <b>name</b>, and set
1888 * *<b>addr</b> to the proper IP address, in host byte order. Returns 0
1889 * on success, -1 on failure; 1 on transient failure.
1891 * (This function exists because standard windows gethostbyname
1892 * doesn't treat raw IP addresses properly.)
1895 tor_lookup_hostname(const char *name
, uint32_t *addr
)
1900 if ((ret
= tor_addr_lookup(name
, AF_INET
, &myaddr
)))
1903 if (tor_addr_family(&myaddr
) == AF_INET
) {
1904 *addr
= tor_addr_to_ipv4h(&myaddr
);
1911 /** Initialize the insecure libc RNG. */
1913 tor_init_weak_random(unsigned seed
)
1922 /** Return a randomly chosen value in the range 0..TOR_RAND_MAX. This
1923 * entropy will not be cryptographically strong; do not rely on it
1924 * for anything an adversary should not be able to predict. */
1926 tor_weak_random(void)
1935 /** Hold the result of our call to <b>uname</b>. */
1936 static char uname_result
[256];
1937 /** True iff uname_result is set. */
1938 static int uname_result_is_set
= 0;
1940 /** Return a pointer to a description of our platform.
1948 if (!uname_result_is_set
) {
1950 if (uname(&u
) != -1) {
1951 /* (Linux says 0 is success, Solaris says 1 is success) */
1952 tor_snprintf(uname_result
, sizeof(uname_result
), "%s %s",
1953 u
.sysname
, u
.machine
);
1958 OSVERSIONINFOEX info
;
1960 const char *plat
= NULL
;
1961 const char *extra
= NULL
;
1962 char acsd
[MAX_PATH
] = {0};
1964 unsigned major
; unsigned minor
; const char *version
;
1965 } win_version_table
[] = {
1966 { 6, 2, "Windows 8" },
1967 { 6, 1, "Windows 7" },
1968 { 6, 0, "Windows Vista" },
1969 { 5, 2, "Windows Server 2003" },
1970 { 5, 1, "Windows XP" },
1971 { 5, 0, "Windows 2000" },
1972 /* { 4, 0, "Windows NT 4.0" }, */
1973 { 4, 90, "Windows Me" },
1974 { 4, 10, "Windows 98" },
1975 /* { 4, 0, "Windows 95" } */
1976 { 3, 51, "Windows NT 3.51" },
1979 memset(&info
, 0, sizeof(info
));
1980 info
.dwOSVersionInfoSize
= sizeof(info
);
1981 if (! GetVersionEx((LPOSVERSIONINFO
)&info
)) {
1982 strlcpy(uname_result
, "Bizarre version of Windows where GetVersionEx"
1983 " doesn't work.", sizeof(uname_result
));
1984 uname_result_is_set
= 1;
1985 return uname_result
;
1988 wcstombs(acsd
, info
.szCSDVersion
, MAX_PATH
);
1990 strlcpy(acsd
, info
.szCSDVersion
, sizeof(acsd
));
1992 if (info
.dwMajorVersion
== 4 && info
.dwMinorVersion
== 0) {
1993 if (info
.dwPlatformId
== VER_PLATFORM_WIN32_NT
)
1994 plat
= "Windows NT 4.0";
1996 plat
= "Windows 95";
1999 else if (acsd
[1] == 'C')
2002 for (i
=0; win_version_table
[i
].major
>0; ++i
) {
2003 if (win_version_table
[i
].major
== info
.dwMajorVersion
&&
2004 win_version_table
[i
].minor
== info
.dwMinorVersion
) {
2005 plat
= win_version_table
[i
].version
;
2010 if (plat
&& !strcmp(plat
, "Windows 98")) {
2013 else if (acsd
[1] == 'B')
2019 tor_snprintf(uname_result
, sizeof(uname_result
), "%s %s",
2022 if (info
.dwMajorVersion
> 6 ||
2023 (info
.dwMajorVersion
==6 && info
.dwMinorVersion
>2))
2024 tor_snprintf(uname_result
, sizeof(uname_result
),
2025 "Very recent version of Windows [major=%d,minor=%d] %s",
2026 (int)info
.dwMajorVersion
,(int)info
.dwMinorVersion
,
2029 tor_snprintf(uname_result
, sizeof(uname_result
),
2030 "Unrecognized version of Windows [major=%d,minor=%d] %s",
2031 (int)info
.dwMajorVersion
,(int)info
.dwMinorVersion
,
2034 #if !defined (WINCE)
2035 #ifdef VER_SUITE_BACKOFFICE
2036 if (info
.wProductType
== VER_NT_DOMAIN_CONTROLLER
) {
2037 strlcat(uname_result
, " [domain controller]", sizeof(uname_result
));
2038 } else if (info
.wProductType
== VER_NT_SERVER
) {
2039 strlcat(uname_result
, " [server]", sizeof(uname_result
));
2040 } else if (info
.wProductType
== VER_NT_WORKSTATION
) {
2041 strlcat(uname_result
, " [workstation]", sizeof(uname_result
));
2046 strlcpy(uname_result
, "Unknown platform", sizeof(uname_result
));
2049 uname_result_is_set
= 1;
2051 return uname_result
;
2058 #if defined(USE_PTHREADS)
2059 /** Wraps a void (*)(void*) function and its argument so we can
2060 * invoke them in a way pthreads would expect.
2062 typedef struct tor_pthread_data_t
{
2063 void (*func
)(void *);
2065 } tor_pthread_data_t
;
2066 /** Given a tor_pthread_data_t <b>_data</b>, call _data->func(d->data)
2067 * and free _data. Used to make sure we can call functions the way pthread
2070 tor_pthread_helper_fn(void *_data
)
2072 tor_pthread_data_t
*data
= _data
;
2073 void (*func
)(void*);
2075 /* mask signals to worker threads to avoid SIGPIPE, etc */
2077 /* We're in a subthread; don't handle any signals here. */
2079 pthread_sigmask(SIG_SETMASK
, &sigs
, NULL
);
2089 /** Minimalist interface to run a void function in the background. On
2090 * Unix calls fork, on win32 calls beginthread. Returns -1 on failure.
2091 * func should not return, but rather should call spawn_exit.
2093 * NOTE: if <b>data</b> is used, it should not be allocated on the stack,
2094 * since in a multithreaded environment, there is no way to be sure that
2095 * the caller's stack will still be around when the called function is
2099 spawn_func(void (*func
)(void *), void *data
)
2101 #if defined(USE_WIN32_THREADS)
2103 rv
= (int)_beginthread(func
, 0, data
);
2107 #elif defined(USE_PTHREADS)
2109 tor_pthread_data_t
*d
;
2110 d
= tor_malloc(sizeof(tor_pthread_data_t
));
2113 if (pthread_create(&thread
,NULL
,tor_pthread_helper_fn
,d
))
2115 if (pthread_detach(thread
))
2126 tor_assert(0); /* Should never reach here. */
2127 return 0; /* suppress "control-reaches-end-of-non-void" warning. */
2135 /** End the current thread/process.
2140 #if defined(USE_WIN32_THREADS)
2142 //we should never get here. my compiler thinks that _endthread returns, this
2143 //is an attempt to fool it.
2146 #elif defined(USE_PTHREADS)
2149 /* http://www.erlenstar.demon.co.uk/unix/faq_2.html says we should
2150 * call _exit, not exit, from child processes. */
2155 /** Implementation logic for compute_num_cpus(). */
2157 compute_num_cpus_impl(void)
2161 memset(&info
, 0, sizeof(info
));
2162 GetSystemInfo(&info
);
2163 if (info
.dwNumberOfProcessors
>= 1 && info
.dwNumberOfProcessors
< INT_MAX
)
2164 return (int)info
.dwNumberOfProcessors
;
2167 #elif defined(HAVE_SYSCONF) && defined(_SC_NPROCESSORS_CONF)
2168 long cpus
= sysconf(_SC_NPROCESSORS_CONF
);
2169 if (cpus
>= 1 && cpus
< INT_MAX
)
2178 #define MAX_DETECTABLE_CPUS 16
2180 /** Return how many CPUs we are running with. We assume that nobody is
2181 * using hot-swappable CPUs, so we don't recompute this after the first
2182 * time. Return -1 if we don't know how to tell the number of CPUs on this
2186 compute_num_cpus(void)
2188 static int num_cpus
= -2;
2189 if (num_cpus
== -2) {
2190 num_cpus
= compute_num_cpus_impl();
2191 tor_assert(num_cpus
!= -2);
2192 if (num_cpus
> MAX_DETECTABLE_CPUS
)
2193 log_notice(LD_GENERAL
, "Wow! I detected that you have %d CPUs. I "
2194 "will not autodetect any more than %d, though. If you "
2195 "want to configure more, set NumCPUs in your torrc",
2196 num_cpus
, MAX_DETECTABLE_CPUS
);
2201 /** Set *timeval to the current time of day. On error, log and terminate.
2202 * (Same as gettimeofday(timeval,NULL), but never returns -1.)
2205 tor_gettimeofday(struct timeval
*timeval
)
2208 /* Epoch bias copied from perl: number of units between windows epoch and
2210 #define EPOCH_BIAS U64_LITERAL(116444736000000000)
2211 #define UNITS_PER_SEC U64_LITERAL(10000000)
2212 #define USEC_PER_SEC U64_LITERAL(1000000)
2213 #define UNITS_PER_USEC U64_LITERAL(10)
2219 /* wince do not have GetSystemTimeAsFileTime */
2221 GetSystemTime(&stime
);
2222 SystemTimeToFileTime(&stime
,&ft
.ft_ft
);
2224 /* number of 100-nsec units since Jan 1, 1601 */
2225 GetSystemTimeAsFileTime(&ft
.ft_ft
);
2227 if (ft
.ft_64
< EPOCH_BIAS
) {
2228 log_err(LD_GENERAL
,"System time is before 1970; failing.");
2231 ft
.ft_64
-= EPOCH_BIAS
;
2232 timeval
->tv_sec
= (unsigned) (ft
.ft_64
/ UNITS_PER_SEC
);
2233 timeval
->tv_usec
= (unsigned) ((ft
.ft_64
/ UNITS_PER_USEC
) % USEC_PER_SEC
);
2234 #elif defined(HAVE_GETTIMEOFDAY)
2235 if (gettimeofday(timeval
, NULL
)) {
2236 log_err(LD_GENERAL
,"gettimeofday failed.");
2237 /* If gettimeofday dies, we have either given a bad timezone (we didn't),
2241 #elif defined(HAVE_FTIME)
2244 timeval
->tv_sec
= tb
.time
;
2245 timeval
->tv_usec
= tb
.millitm
* 1000;
2247 #error "No way to get time."
2252 #if defined(TOR_IS_MULTITHREADED) && !defined(MS_WINDOWS)
2253 /** Defined iff we need to add locks when defining fake versions of reentrant
2254 * versions of time-related functions. */
2255 #define TIME_FNS_NEED_LOCKS
2259 correct_tm(int islocal
, const time_t *timep
, struct tm
*resultbuf
,
2262 const char *outcome
;
2264 if (PREDICT_LIKELY(r
)) {
2265 if (r
->tm_year
> 8099) { /* We can't strftime dates after 9999 CE. */
2277 /* If we get here, gmtime or localtime returned NULL. It might have done
2278 * this because of overrun or underrun, or it might have done it because of
2279 * some other weird issue. */
2283 r
->tm_year
= 70; /* 1970 CE */
2290 outcome
= "Rounding up to 1970";
2292 } else if (*timep
>= INT32_MAX
) {
2293 /* Rounding down to INT32_MAX isn't so great, but keep in mind that we
2294 * only do it if gmtime/localtime tells us NULL. */
2296 r
->tm_year
= 137; /* 2037 CE */
2303 outcome
= "Rounding down to 2037";
2308 /* If we get here, then gmtime/localtime failed without getting an extreme
2309 * value for *timep */
2311 tor_fragile_assert();
2313 memset(resultbuf
, 0, sizeof(struct tm
));
2314 outcome
="can't recover";
2316 log_warn(LD_BUG
, "%s("I64_FORMAT
") failed with error %s: %s",
2317 islocal
?"localtime":"gmtime",
2318 timep
?I64_PRINTF_ARG(*timep
):0,
2325 /** As localtime_r, but defined for platforms that don't have it:
2327 * Convert *<b>timep</b> to a struct tm in local time, and store the value in
2328 * *<b>result</b>. Return the result on success, or NULL on failure.
2330 #ifdef HAVE_LOCALTIME_R
2332 tor_localtime_r(const time_t *timep
, struct tm
*result
)
2335 r
= localtime_r(timep
, result
);
2336 return correct_tm(1, timep
, result
, r
);
2338 #elif defined(TIME_FNS_NEED_LOCKS)
2340 tor_localtime_r(const time_t *timep
, struct tm
*result
)
2343 static tor_mutex_t
*m
=NULL
;
2344 if (!m
) { m
=tor_mutex_new(); }
2346 tor_mutex_acquire(m
);
2347 r
= localtime(timep
);
2349 memcpy(result
, r
, sizeof(struct tm
));
2350 tor_mutex_release(m
);
2351 return correct_tm(1, timep
, result
, r
);
2355 tor_localtime_r(const time_t *timep
, struct tm
*result
)
2359 r
= localtime(timep
);
2361 memcpy(result
, r
, sizeof(struct tm
));
2362 return correct_tm(1, timep
, result
, r
);
2368 /** As gmtimee_r, but defined for platforms that don't have it:
2370 * Convert *<b>timep</b> to a struct tm in UTC, and store the value in
2371 * *<b>result</b>. Return the result on success, or NULL on failure.
2373 #ifdef HAVE_GMTIME_R
2375 tor_gmtime_r(const time_t *timep
, struct tm
*result
)
2378 r
= gmtime_r(timep
, result
);
2379 return correct_tm(0, timep
, result
, r
);
2381 #elif defined(TIME_FNS_NEED_LOCKS)
2383 tor_gmtime_r(const time_t *timep
, struct tm
*result
)
2386 static tor_mutex_t
*m
=NULL
;
2387 if (!m
) { m
=tor_mutex_new(); }
2389 tor_mutex_acquire(m
);
2392 memcpy(result
, r
, sizeof(struct tm
));
2393 tor_mutex_release(m
);
2394 return correct_tm(0, timep
, result
, r
);
2398 tor_gmtime_r(const time_t *timep
, struct tm
*result
)
2404 memcpy(result
, r
, sizeof(struct tm
));
2405 return correct_tm(0, timep
, result
, r
);
2409 #if defined(USE_WIN32_THREADS)
2411 tor_mutex_init(tor_mutex_t
*m
)
2413 InitializeCriticalSection(&m
->mutex
);
2416 tor_mutex_uninit(tor_mutex_t
*m
)
2418 DeleteCriticalSection(&m
->mutex
);
2421 tor_mutex_acquire(tor_mutex_t
*m
)
2424 EnterCriticalSection(&m
->mutex
);
2427 tor_mutex_release(tor_mutex_t
*m
)
2429 LeaveCriticalSection(&m
->mutex
);
2432 tor_get_thread_id(void)
2434 return (unsigned long)GetCurrentThreadId();
2436 #elif defined(USE_PTHREADS)
2437 /** A mutex attribute that we're going to use to tell pthreads that we want
2438 * "reentrant" mutexes (i.e., once we can re-lock if we're already holding
2440 static pthread_mutexattr_t attr_reentrant
;
2441 /** True iff we've called tor_threads_init() */
2442 static int threads_initialized
= 0;
2443 /** Initialize <b>mutex</b> so it can be locked. Every mutex must be set
2444 * up with tor_mutex_init() or tor_mutex_new(); not both. */
2446 tor_mutex_init(tor_mutex_t
*mutex
)
2449 if (PREDICT_UNLIKELY(!threads_initialized
))
2451 err
= pthread_mutex_init(&mutex
->mutex
, &attr_reentrant
);
2452 if (PREDICT_UNLIKELY(err
)) {
2453 log_err(LD_GENERAL
, "Error %d creating a mutex.", err
);
2454 tor_fragile_assert();
2457 /** Wait until <b>m</b> is free, then acquire it. */
2459 tor_mutex_acquire(tor_mutex_t
*m
)
2463 err
= pthread_mutex_lock(&m
->mutex
);
2464 if (PREDICT_UNLIKELY(err
)) {
2465 log_err(LD_GENERAL
, "Error %d locking a mutex.", err
);
2466 tor_fragile_assert();
2469 /** Release the lock <b>m</b> so another thread can have it. */
2471 tor_mutex_release(tor_mutex_t
*m
)
2475 err
= pthread_mutex_unlock(&m
->mutex
);
2476 if (PREDICT_UNLIKELY(err
)) {
2477 log_err(LD_GENERAL
, "Error %d unlocking a mutex.", err
);
2478 tor_fragile_assert();
2481 /** Clean up the mutex <b>m</b> so that it no longer uses any system
2482 * resources. Does not free <b>m</b>. This function must only be called on
2483 * mutexes from tor_mutex_init(). */
2485 tor_mutex_uninit(tor_mutex_t
*m
)
2489 err
= pthread_mutex_destroy(&m
->mutex
);
2490 if (PREDICT_UNLIKELY(err
)) {
2491 log_err(LD_GENERAL
, "Error %d destroying a mutex.", err
);
2492 tor_fragile_assert();
2495 /** Return an integer representing this thread. */
2497 tor_get_thread_id(void)
2503 r
.thr
= pthread_self();
2508 #ifdef TOR_IS_MULTITHREADED
2509 /** Return a newly allocated, ready-for-use mutex. */
2513 tor_mutex_t
*m
= tor_malloc_zero(sizeof(tor_mutex_t
));
2517 /** Release all storage and system resources held by <b>m</b>. */
2519 tor_mutex_free(tor_mutex_t
*m
)
2523 tor_mutex_uninit(m
);
2531 /** Cross-platform condition implementation. */
2533 pthread_cond_t cond
;
2535 /** Return a newly allocated condition, with nobody waiting on it. */
2539 tor_cond_t
*cond
= tor_malloc_zero(sizeof(tor_cond_t
));
2540 if (pthread_cond_init(&cond
->cond
, NULL
)) {
2546 /** Release all resources held by <b>cond</b>. */
2548 tor_cond_free(tor_cond_t
*cond
)
2552 if (pthread_cond_destroy(&cond
->cond
)) {
2553 log_warn(LD_GENERAL
,"Error freeing condition: %s", strerror(errno
));
2558 /** Wait until one of the tor_cond_signal functions is called on <b>cond</b>.
2559 * All waiters on the condition must wait holding the same <b>mutex</b>.
2560 * Returns 0 on success, negative on failure. */
2562 tor_cond_wait(tor_cond_t
*cond
, tor_mutex_t
*mutex
)
2564 return pthread_cond_wait(&cond
->cond
, &mutex
->mutex
) ? -1 : 0;
2566 /** Wake up one of the waiters on <b>cond</b>. */
2568 tor_cond_signal_one(tor_cond_t
*cond
)
2570 pthread_cond_signal(&cond
->cond
);
2572 /** Wake up all of the waiters on <b>cond</b>. */
2574 tor_cond_signal_all(tor_cond_t
*cond
)
2576 pthread_cond_broadcast(&cond
->cond
);
2579 /** Set up common structures for use by threading. */
2581 tor_threads_init(void)
2583 if (!threads_initialized
) {
2584 pthread_mutexattr_init(&attr_reentrant
);
2585 pthread_mutexattr_settype(&attr_reentrant
, PTHREAD_MUTEX_RECURSIVE
);
2586 threads_initialized
= 1;
2590 #elif defined(USE_WIN32_THREADS)
2592 static DWORD cond_event_tls_index
;
2594 CRITICAL_SECTION mutex
;
2595 smartlist_t
*events
;
2600 tor_cond_t
*cond
= tor_malloc_zero(sizeof(tor_cond_t
));
2601 InitializeCriticalSection(&cond
->mutex
);
2602 cond
->events
= smartlist_create();
2606 tor_cond_free(tor_cond_t
*cond
)
2610 DeleteCriticalSection(&cond
->mutex
);
2612 smartlist_free(cond
->events
);
2616 tor_cond_wait(tor_cond_t
*cond
, tor_mutex_t
*mutex
)
2622 event
= TlsGetValue(cond_event_tls_index
);
2624 event
= CreateEvent(0, FALSE
, FALSE
, NULL
);
2625 TlsSetValue(cond_event_tls_index
, event
);
2627 EnterCriticalSection(&cond
->mutex
);
2629 tor_assert(WaitForSingleObject(event
, 0) == WAIT_TIMEOUT
);
2630 tor_assert(!smartlist_isin(cond
->events
, event
));
2631 smartlist_add(cond
->events
, event
);
2633 LeaveCriticalSection(&cond
->mutex
);
2635 tor_mutex_release(mutex
);
2636 r
= WaitForSingleObject(event
, INFINITE
);
2637 tor_mutex_acquire(mutex
);
2640 case WAIT_OBJECT_0
: /* we got the mutex normally. */
2642 case WAIT_ABANDONED
: /* holding thread exited. */
2643 case WAIT_TIMEOUT
: /* Should never happen. */
2647 log_warn(LD_GENERAL
, "Failed to acquire mutex: %d",(int) GetLastError());
2652 tor_cond_signal_one(tor_cond_t
*cond
)
2657 EnterCriticalSection(&cond
->mutex
);
2659 if ((event
= smartlist_pop_last(cond
->events
)))
2662 LeaveCriticalSection(&cond
->mutex
);
2665 tor_cond_signal_all(tor_cond_t
*cond
)
2669 EnterCriticalSection(&cond
->mutex
);
2670 SMARTLIST_FOREACH(cond
->events
, HANDLE
, event
, SetEvent(event
));
2671 smartlist_clear(cond
->events
);
2672 LeaveCriticalSection(&cond
->mutex
);
2676 tor_threads_init(void)
2679 cond_event_tls_index
= TlsAlloc();
2685 #if defined(HAVE_MLOCKALL) && HAVE_DECL_MLOCKALL && defined(RLIMIT_MEMLOCK)
2686 /** Attempt to raise the current and max rlimit to infinity for our process.
2687 * This only needs to be done once and can probably only be done when we have
2688 * not already dropped privileges.
2691 tor_set_max_memlock(void)
2693 /* Future consideration for Windows is probably SetProcessWorkingSetSize
2694 * This is similar to setting the memory rlimit of RLIMIT_MEMLOCK
2695 * http://msdn.microsoft.com/en-us/library/ms686234(VS.85).aspx
2698 struct rlimit limit
;
2700 /* RLIM_INFINITY is -1 on some platforms. */
2701 limit
.rlim_cur
= RLIM_INFINITY
;
2702 limit
.rlim_max
= RLIM_INFINITY
;
2704 if (setrlimit(RLIMIT_MEMLOCK
, &limit
) == -1) {
2705 if (errno
== EPERM
) {
2706 log_warn(LD_GENERAL
, "You appear to lack permissions to change memory "
2707 "limits. Are you root?");
2709 log_warn(LD_GENERAL
, "Unable to raise RLIMIT_MEMLOCK: %s",
2718 /** Attempt to lock all current and all future memory pages.
2719 * This should only be called once and while we're privileged.
2720 * Like mlockall() we return 0 when we're successful and -1 when we're not.
2721 * Unlike mlockall() we return 1 if we've already attempted to lock memory.
2726 static int memory_lock_attempted
= 0;
2728 if (memory_lock_attempted
) {
2732 memory_lock_attempted
= 1;
2735 * Future consideration for Windows may be VirtualLock
2736 * VirtualLock appears to implement mlock() but not mlockall()
2738 * http://msdn.microsoft.com/en-us/library/aa366895(VS.85).aspx
2741 #if defined(HAVE_MLOCKALL) && HAVE_DECL_MLOCKALL && defined(RLIMIT_MEMLOCK)
2742 if (tor_set_max_memlock() == 0) {
2743 log_debug(LD_GENERAL
, "RLIMIT_MEMLOCK is now set to RLIM_INFINITY.");
2746 if (mlockall(MCL_CURRENT
|MCL_FUTURE
) == 0) {
2747 log_info(LD_GENERAL
, "Insecure OS paging is effectively disabled.");
2750 if (errno
== ENOSYS
) {
2751 /* Apple - it's 2009! I'm looking at you. Grrr. */
2752 log_notice(LD_GENERAL
, "It appears that mlockall() is not available on "
2754 } else if (errno
== EPERM
) {
2755 log_notice(LD_GENERAL
, "It appears that you lack the permissions to "
2756 "lock memory. Are you root?");
2758 log_notice(LD_GENERAL
, "Unable to lock all current and future memory "
2759 "pages: %s", strerror(errno
));
2763 log_warn(LD_GENERAL
, "Unable to lock memory pages. mlockall() unsupported?");
2768 /** Identity of the "main" thread */
2769 static unsigned long main_thread_id
= -1;
2771 /** Start considering the current thread to be the 'main thread'. This has
2772 * no effect on anything besides in_main_thread(). */
2774 set_main_thread(void)
2776 main_thread_id
= tor_get_thread_id();
2778 /** Return true iff called from the main thread. */
2780 in_main_thread(void)
2782 return main_thread_id
== tor_get_thread_id();
2786 * On Windows, WSAEWOULDBLOCK is not always correct: when you see it,
2787 * you need to ask the socket for its actual errno. Also, you need to
2788 * get your errors from WSAGetLastError, not errno. (If you supply a
2789 * socket of -1, we check WSAGetLastError, but don't correct
2792 * The upshot of all of this is that when a socket call fails, you
2793 * should call tor_socket_errno <em>at most once</em> on the failing
2794 * socket to get the error.
2796 #if defined(MS_WINDOWS)
2798 tor_socket_errno(tor_socket_t sock
)
2800 int optval
, optvallen
=sizeof(optval
);
2801 int err
= WSAGetLastError();
2802 if (err
== WSAEWOULDBLOCK
&& SOCKET_OK(sock
)) {
2803 if (getsockopt(sock
, SOL_SOCKET
, SO_ERROR
, (void*)&optval
, &optvallen
))
2812 #if defined(MS_WINDOWS)
2813 #define E(code, s) { code, (s " [" #code " ]") }
2814 struct { int code
; const char *msg
; } windows_socket_errors
[] = {
2815 E(WSAEINTR
, "Interrupted function call"),
2816 E(WSAEACCES
, "Permission denied"),
2817 E(WSAEFAULT
, "Bad address"),
2818 E(WSAEINVAL
, "Invalid argument"),
2819 E(WSAEMFILE
, "Too many open files"),
2820 E(WSAEWOULDBLOCK
, "Resource temporarily unavailable"),
2821 E(WSAEINPROGRESS
, "Operation now in progress"),
2822 E(WSAEALREADY
, "Operation already in progress"),
2823 E(WSAENOTSOCK
, "Socket operation on nonsocket"),
2824 E(WSAEDESTADDRREQ
, "Destination address required"),
2825 E(WSAEMSGSIZE
, "Message too long"),
2826 E(WSAEPROTOTYPE
, "Protocol wrong for socket"),
2827 E(WSAENOPROTOOPT
, "Bad protocol option"),
2828 E(WSAEPROTONOSUPPORT
, "Protocol not supported"),
2829 E(WSAESOCKTNOSUPPORT
, "Socket type not supported"),
2830 /* What's the difference between NOTSUPP and NOSUPPORT? :) */
2831 E(WSAEOPNOTSUPP
, "Operation not supported"),
2832 E(WSAEPFNOSUPPORT
, "Protocol family not supported"),
2833 E(WSAEAFNOSUPPORT
, "Address family not supported by protocol family"),
2834 E(WSAEADDRINUSE
, "Address already in use"),
2835 E(WSAEADDRNOTAVAIL
, "Cannot assign requested address"),
2836 E(WSAENETDOWN
, "Network is down"),
2837 E(WSAENETUNREACH
, "Network is unreachable"),
2838 E(WSAENETRESET
, "Network dropped connection on reset"),
2839 E(WSAECONNABORTED
, "Software caused connection abort"),
2840 E(WSAECONNRESET
, "Connection reset by peer"),
2841 E(WSAENOBUFS
, "No buffer space available"),
2842 E(WSAEISCONN
, "Socket is already connected"),
2843 E(WSAENOTCONN
, "Socket is not connected"),
2844 E(WSAESHUTDOWN
, "Cannot send after socket shutdown"),
2845 E(WSAETIMEDOUT
, "Connection timed out"),
2846 E(WSAECONNREFUSED
, "Connection refused"),
2847 E(WSAEHOSTDOWN
, "Host is down"),
2848 E(WSAEHOSTUNREACH
, "No route to host"),
2849 E(WSAEPROCLIM
, "Too many processes"),
2850 /* Yes, some of these start with WSA, not WSAE. No, I don't know why. */
2851 E(WSASYSNOTREADY
, "Network subsystem is unavailable"),
2852 E(WSAVERNOTSUPPORTED
, "Winsock.dll out of range"),
2853 E(WSANOTINITIALISED
, "Successful WSAStartup not yet performed"),
2854 E(WSAEDISCON
, "Graceful shutdown now in progress"),
2855 #ifdef WSATYPE_NOT_FOUND
2856 E(WSATYPE_NOT_FOUND
, "Class type not found"),
2858 E(WSAHOST_NOT_FOUND
, "Host not found"),
2859 E(WSATRY_AGAIN
, "Nonauthoritative host not found"),
2860 E(WSANO_RECOVERY
, "This is a nonrecoverable error"),
2861 E(WSANO_DATA
, "Valid name, no data record of requested type)"),
2863 /* There are some more error codes whose numeric values are marked
2864 * <b>OS dependent</b>. They start with WSA_, apparently for the same
2865 * reason that practitioners of some craft traditions deliberately
2866 * introduce imperfections into their baskets and rugs "to allow the
2867 * evil spirits to escape." If we catch them, then our binaries
2868 * might not report consistent results across versions of Windows.
2869 * Thus, I'm going to let them all fall through.
2873 /** There does not seem to be a strerror equivalent for Winsock errors.
2874 * Naturally, we have to roll our own.
2877 tor_socket_strerror(int e
)
2880 for (i
=0; windows_socket_errors
[i
].code
>= 0; ++i
) {
2881 if (e
== windows_socket_errors
[i
].code
)
2882 return windows_socket_errors
[i
].msg
;
2888 /** Called before we make any calls to network-related functions.
2889 * (Some operating systems require their network libraries to be
2895 /* This silly exercise is necessary before windows will allow
2896 * gethostbyname to work. */
2899 r
= WSAStartup(0x101,&WSAData
);
2901 log_warn(LD_NET
,"Error initializing windows network layer: code was %d",r
);
2904 /* WSAData.iMaxSockets might show the max sockets we're allowed to use.
2905 * We might use it to complain if we're trying to be a server but have
2906 * too few sockets available. */
2912 /** Return a newly allocated string describing the windows system error code
2913 * <b>err</b>. Note that error codes are different from errno. Error codes
2914 * come from GetLastError() when a winapi call fails. errno is set only when
2915 * ANSI functions fail. Whee. */
2917 format_win32_error(DWORD err
)
2922 /* Somebody once decided that this interface was better than strerror(). */
2923 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
|
2924 FORMAT_MESSAGE_FROM_SYSTEM
|
2925 FORMAT_MESSAGE_IGNORE_INSERTS
,
2927 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
2933 char abuf
[1024] = {0};
2934 wcstombs(abuf
,str
,1024);
2935 result
= tor_strdup(abuf
);
2937 result
= tor_strdup(str
);
2939 LocalFree(str
); /* LocalFree != free() */
2941 result
= tor_strdup("<unformattable error>");