1 /* Copyright (c) 2003-2004, Roger Dingledine
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2009, 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)
25 #include <sys/locking.h>
29 #include <sys/utsname.h>
34 #ifdef HAVE_SYS_FCNTL_H
35 #include <sys/fcntl.h>
49 #ifdef HAVE_ARPA_INET_H
50 #include <arpa/inet.h>
53 #ifndef HAVE_GETTIMEOFDAY
55 #include <sys/timeb.h>
62 #ifdef HAVE_SYS_PARAM_H
63 #include <sys/param.h> /* FreeBSD needs this to know what version it is */
74 #ifdef HAVE_SYS_UTIME_H
75 #include <sys/utime.h>
77 #ifdef HAVE_SYS_MMAN_H
80 #ifdef HAVE_SYS_SYSLIMITS_H
81 #include <sys/syslimits.h>
83 #ifdef HAVE_SYS_FILE_H
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>
93 #include "container.h"
96 /* Inline the strl functions if the platform doesn't have them. */
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
109 tor_mmap_file(const char *filename
)
111 int fd
; /* router file */
115 size_t size
, filesize
;
117 tor_assert(filename
);
119 fd
= open(filename
, O_RDONLY
, 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
,
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;
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
);
144 string
= mmap(0, size
, PROT_READ
, MAP_PRIVATE
, fd
, 0);
146 if (string
== MAP_FAILED
) {
147 int save_errno
= errno
;
148 log_warn(LD_FS
,"Could not mmap file \"%s\": %s", filename
,
154 res
= tor_malloc_zero(sizeof(tor_mmap_t
));
156 res
->size
= filesize
;
157 res
->mapping_size
= size
;
161 /** Release storage held for a memory mapping. */
163 tor_munmap_file(tor_mmap_t
*handle
)
165 munmap((char*)handle
->data
, handle
->mapping_size
);
168 #elif defined(MS_WINDOWS)
170 tor_mmap_file(const char *filename
)
172 tor_mmap_t
*res
= tor_malloc_zero(sizeof(tor_mmap_t
));
174 res
->file_handle
= INVALID_HANDLE_VALUE
;
175 res
->mmap_handle
= NULL
;
177 res
->file_handle
= CreateFile(filename
,
178 GENERIC_READ
, FILE_SHARE_READ
,
181 FILE_ATTRIBUTE_NORMAL
,
184 if (res
->file_handle
== INVALID_HANDLE_VALUE
)
187 res
->size
= GetFileSize(res
->file_handle
, NULL
);
189 if (res
->size
== 0) {
190 log_info(LD_FS
,"File \"%s\" is empty. Ignoring.",filename
);
195 res
->mmap_handle
= CreateFileMapping(res
->file_handle
,
198 #if SIZEOF_SIZE_T > 4
199 (res
->base
.size
>> 32),
203 (res
->size
& 0xfffffffful
),
205 if (res
->mmap_handle
== NULL
)
207 res
->data
= (char*) MapViewOfFile(res
->mmap_handle
,
215 DWORD e
= GetLastError();
216 int severity
= (e
== ERROR_FILE_NOT_FOUND
|| e
== ERROR_PATH_NOT_FOUND
) ?
218 char *msg
= format_win32_error(e
);
219 log_fn(severity
, LD_FS
, "Couldn't mmap file \"%s\": %s", filename
, msg
);
221 if (e
== ERROR_FILE_NOT_FOUND
|| e
== ERROR_PATH_NOT_FOUND
)
229 tor_munmap_file(res
);
233 tor_munmap_file(tor_mmap_t
*handle
)
236 /* This is an ugly cast, but without it, "data" in struct tor_mmap_t would
237 have to be redefined as non-const. */
238 UnmapViewOfFile( (LPVOID
) handle
->data
);
240 if (handle
->mmap_handle
!= NULL
)
241 CloseHandle(handle
->mmap_handle
);
242 if (handle
->file_handle
!= INVALID_HANDLE_VALUE
)
243 CloseHandle(handle
->file_handle
);
248 tor_mmap_file(const char *filename
)
251 char *res
= read_file_to_str(filename
, RFTS_BIN
|RFTS_IGNORE_MISSING
, &st
);
255 handle
= tor_malloc_zero(sizeof(tor_mmap_t
));
257 handle
->size
= st
.st_size
;
261 tor_munmap_file(tor_mmap_t
*handle
)
263 char *d
= (char*)handle
->data
;
265 memset(handle
, 0, sizeof(tor_mmap_t
));
270 /** Replacement for snprintf. Differs from platform snprintf in two
271 * ways: First, always NUL-terminates its output. Second, always
272 * returns -1 if the result is truncated. (Note that this return
273 * behavior does <i>not</i> conform to C99; it just happens to be
274 * easier to emulate "return -1" with conformant implementations than
275 * it is to emulate "return number that would be written" with
276 * non-conformant implementations.) */
278 tor_snprintf(char *str
, size_t size
, const char *format
, ...)
283 r
= tor_vsnprintf(str
,size
,format
,ap
);
288 /** Replacement for vsnprintf; behavior differs as tor_snprintf differs from
292 tor_vsnprintf(char *str
, size_t size
, const char *format
, va_list args
)
296 return -1; /* no place for the NUL */
297 if (size
> SSIZE_T_MAX
-16)
300 r
= _vsnprintf(str
, size
, format
, args
);
302 r
= vsnprintf(str
, size
, format
, args
);
305 if (r
< 0 || r
>= (ssize_t
)size
)
310 /** Given <b>hlen</b> bytes at <b>haystack</b> and <b>nlen</b> bytes at
311 * <b>needle</b>, return a pointer to the first occurrence of the needle
312 * within the haystack, or NULL if there is no such occurrence.
314 * Requires that nlen be greater than zero.
317 tor_memmem(const void *_haystack
, size_t hlen
,
318 const void *_needle
, size_t nlen
)
320 #if defined(HAVE_MEMMEM) && (!defined(__GNUC__) || __GNUC__ >= 2)
322 return memmem(_haystack
, hlen
, _needle
, nlen
);
324 /* This isn't as fast as the GLIBC implementation, but it doesn't need to
327 const char *haystack
= (const char*)_haystack
;
328 const char *needle
= (const char*)_needle
;
333 end
= haystack
+ hlen
;
334 first
= *(const char*)needle
;
335 while ((p
= memchr(p
, first
, end
-p
))) {
338 if (!memcmp(p
, needle
, nlen
))
346 /* Tables to implement ctypes-replacement TOR_IS*() functions. Each table
347 * has 256 bits to look up whether a character is in some set or not. This
348 * fails on non-ASCII platforms, but it is hard to find a platform whose
349 * character set is not a superset of ASCII nowadays. */
350 const uint32_t TOR_ISALPHA_TABLE
[8] =
351 { 0, 0, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
352 const uint32_t TOR_ISALNUM_TABLE
[8] =
353 { 0, 0x3ff0000, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
354 const uint32_t TOR_ISSPACE_TABLE
[8] = { 0x3e00, 0x1, 0, 0, 0, 0, 0, 0 };
355 const uint32_t TOR_ISXDIGIT_TABLE
[8] =
356 { 0, 0x3ff0000, 0x7e, 0x7e, 0, 0, 0, 0 };
357 const uint32_t TOR_ISDIGIT_TABLE
[8] = { 0, 0x3ff0000, 0, 0, 0, 0, 0, 0 };
358 const uint32_t TOR_ISPRINT_TABLE
[8] =
359 { 0, 0xffffffff, 0xffffffff, 0x7fffffff, 0, 0, 0, 0x0 };
360 const uint32_t TOR_ISUPPER_TABLE
[8] = { 0, 0, 0x7fffffe, 0, 0, 0, 0, 0 };
361 const uint32_t TOR_ISLOWER_TABLE
[8] = { 0, 0, 0, 0x7fffffe, 0, 0, 0, 0 };
362 /* Upper-casing and lowercasing tables to map characters to upper/lowercase
364 const char TOR_TOUPPER_TABLE
[256] = {
365 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
366 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
367 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
368 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
369 64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
370 80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
371 96,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
372 80,81,82,83,84,85,86,87,88,89,90,123,124,125,126,127,
373 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
374 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
375 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
376 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
377 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
378 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
379 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
380 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
382 const char TOR_TOLOWER_TABLE
[256] = {
383 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
384 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
385 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
386 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
387 64,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
388 112,113,114,115,116,117,118,119,120,121,122,91,92,93,94,95,
389 96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
390 112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
391 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
392 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
393 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
394 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
395 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
396 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
397 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
398 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
401 /** Implementation of strtok_r for platforms whose coders haven't figured out
402 * how to write one. Hey guys! You can use this code here for free! */
404 tor_strtok_r_impl(char *str
, const char *sep
, char **lasts
)
408 start
= cp
= *lasts
= str
;
416 while (*cp
&& !strchr(sep
, *cp
))
419 tor_assert(strlen(sep
) == 1);
420 cp
= strchr(cp
, *sep
);
433 /** Take a filename and return a pointer to its final element. This
434 * function is called on __FILE__ to fix a MSVC nit where __FILE__
435 * contains the full path to the file. This is bad, because it
436 * confuses users to find the home directory of the person who
437 * compiled the binary in their warning messages.
440 tor_fix_source_file(const char *fname
)
442 const char *cp1
, *cp2
, *r
;
443 cp1
= strrchr(fname
, '/');
444 cp2
= strrchr(fname
, '\\');
446 r
= (cp1
<cp2
)?(cp2
+1):(cp1
+1);
459 * Read a 16-bit value beginning at <b>cp</b>. Equivalent to
460 * *(uint16_t*)(cp), but will not cause segfaults on platforms that forbid
461 * unaligned memory access.
464 get_uint16(const char *cp
)
471 * Read a 32-bit value beginning at <b>cp</b>. Equivalent to
472 * *(uint32_t*)(cp), but will not cause segfaults on platforms that forbid
473 * unaligned memory access.
476 get_uint32(const char *cp
)
483 * Read a 64-bit value beginning at <b>cp</b>. Equivalent to
484 * *(uint64_t*)(cp), but will not cause segfaults on platforms that forbid
485 * unaligned memory access.
488 get_uint64(const char *cp
)
496 * Set a 16-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
497 * *(uint16_t*)(cp) = v, but will not cause segfaults on platforms that forbid
498 * unaligned memory access. */
500 set_uint16(char *cp
, uint16_t v
)
505 * Set a 32-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
506 * *(uint32_t*)(cp) = v, but will not cause segfaults on platforms that forbid
507 * unaligned memory access. */
509 set_uint32(char *cp
, uint32_t v
)
514 * Set a 64-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
515 * *(uint64_t*)(cp) = v, but will not cause segfaults on platforms that forbid
516 * unaligned memory access. */
518 set_uint64(char *cp
, uint64_t v
)
524 * Rename the file <b>from</b> to the file <b>to</b>. On Unix, this is
525 * the same as rename(2). On windows, this removes <b>to</b> first if
527 * Returns 0 on success. Returns -1 and sets errno on failure.
530 replace_file(const char *from
, const char *to
)
533 return rename(from
,to
);
535 switch (file_status(to
))
540 if (unlink(to
)) return -1;
548 return rename(from
,to
);
552 /** Change <b>fname</b>'s modification time to now. */
554 touch_file(const char *fname
)
556 if (utime(fname
, NULL
)!=0)
561 /** Represents a lockfile on which we hold the lock. */
562 struct tor_lockfile_t
{
567 /** Try to get a lock on the lockfile <b>filename</b>, creating it as
568 * necessary. If someone else has the lock and <b>blocking</b> is true,
569 * wait until the lock is available. Otherwise return immediately whether
570 * we succeeded or not.
572 * Set *<b>locked_out</b> to true if somebody else had the lock, and to false
575 * Return a <b>tor_lockfile_t</b> on success, NULL on failure.
577 * (Implementation note: because we need to fall back to fcntl on some
578 * platforms, these locks are per-process, not per-thread. If you want
579 * to do in-process locking, use tor_mutex_t like a normal person.)
582 tor_lockfile_lock(const char *filename
, int blocking
, int *locked_out
)
584 tor_lockfile_t
*result
;
588 log_info(LD_FS
, "Locking \"%s\"", filename
);
589 fd
= open(filename
, O_RDWR
|O_CREAT
|O_TRUNC
, 0600);
591 log_warn(LD_FS
,"Couldn't open \"%s\" for locking: %s", filename
,
597 _lseek(fd
, 0, SEEK_SET
);
598 if (_locking(fd
, blocking
? _LK_LOCK
: _LK_NBLCK
, 1) < 0) {
599 if (errno
!= EDEADLOCK
)
600 log_warn(LD_FS
,"Couldn't lock \"%s\": %s", filename
, strerror(errno
));
606 #elif defined(HAVE_FLOCK)
607 if (flock(fd
, LOCK_EX
|(blocking
? 0 : LOCK_NB
)) < 0) {
608 if (errno
!= EWOULDBLOCK
)
609 log_warn(LD_FS
,"Couldn't lock \"%s\": %s", filename
, strerror(errno
));
618 memset(&lock
, 0, sizeof(lock
));
619 lock
.l_type
= F_WRLCK
;
620 lock
.l_whence
= SEEK_SET
;
621 if (fcntl(fd
, blocking
? F_SETLKW
: F_SETLK
, &lock
) < 0) {
622 if (errno
!= EACCES
&& errno
!= EAGAIN
)
623 log_warn(LD_FS
, "Couldn't lock \"%s\": %s", filename
, strerror(errno
));
632 result
= tor_malloc(sizeof(tor_lockfile_t
));
633 result
->filename
= tor_strdup(filename
);
638 /** Release the lock held as <b>lockfile</b>. */
640 tor_lockfile_unlock(tor_lockfile_t
*lockfile
)
642 tor_assert(lockfile
);
644 log_info(LD_FS
, "Unlocking \"%s\"", lockfile
->filename
);
646 _lseek(lockfile
->fd
, 0, SEEK_SET
);
647 if (_locking(lockfile
->fd
, _LK_UNLCK
, 1) < 0) {
648 log_warn(LD_FS
,"Error unlocking \"%s\": %s", lockfile
->filename
,
651 #elif defined(HAVE_FLOCK)
652 if (flock(lockfile
->fd
, LOCK_UN
) < 0) {
653 log_warn(LD_FS
, "Error unlocking \"%s\": %s", lockfile
->filename
,
657 /* Closing the lockfile is sufficient. */
662 tor_free(lockfile
->filename
);
666 /* Some old versions of Unix didn't define constants for these values,
667 * and instead expect you to say 0, 1, or 2. */
675 /** Return the position of <b>fd</b> with respect to the start of the file. */
677 tor_fd_getpos(int fd
)
680 return (off_t
) _lseek(fd
, 0, SEEK_CUR
);
682 return (off_t
) lseek(fd
, 0, SEEK_CUR
);
686 /** Move <b>fd</b> to the end of the file. Return -1 on error, 0 on success. */
688 tor_fd_seekend(int fd
)
691 return _lseek(fd
, 0, SEEK_END
) < 0 ? -1 : 0;
693 return lseek(fd
, 0, SEEK_END
) < 0 ? -1 : 0;
697 #undef DEBUG_SOCKET_COUNTING
698 #ifdef DEBUG_SOCKET_COUNTING
699 /** A bitarray of all fds that should be passed to tor_socket_close(). Only
700 * used if DEBUG_SOCKET_COUNTING is defined. */
701 static bitarray_t
*open_sockets
= NULL
;
702 /** The size of <b>open_sockets</b>, in bits. */
703 static int max_socket
= -1;
706 /** Count of number of sockets currently open. (Undercounts sockets opened by
707 * eventdns and libevent.) */
708 static int n_sockets_open
= 0;
710 /** Mutex to protect open_sockets, max_socket, and n_sockets_open. */
711 static tor_mutex_t
*socket_accounting_mutex
= NULL
;
714 socket_accounting_lock(void)
716 if (PREDICT_UNLIKELY(!socket_accounting_mutex
))
717 socket_accounting_mutex
= tor_mutex_new();
718 tor_mutex_acquire(socket_accounting_mutex
);
722 socket_accounting_unlock(void)
724 tor_mutex_release(socket_accounting_mutex
);
727 /** As close(), but guaranteed to work for sockets across platforms (including
728 * Windows, where close()ing a socket doesn't work. Returns 0 on success, -1
731 tor_close_socket(int s
)
735 /* On Windows, you have to call close() on fds returned by open(),
736 * and closesocket() on fds returned by socket(). On Unix, everything
737 * gets close()'d. We abstract this difference by always using
738 * tor_close_socket to close sockets, and always using close() on
741 #if defined(MS_WINDOWS)
747 socket_accounting_lock();
748 #ifdef DEBUG_SOCKET_COUNTING
749 if (s
> max_socket
|| ! bitarray_is_set(open_sockets
, s
)) {
750 log_warn(LD_BUG
, "Closing a socket (%d) that wasn't returned by tor_open_"
751 "socket(), or that was already closed or something.", s
);
753 tor_assert(open_sockets
&& s
<= max_socket
);
754 bitarray_clear(open_sockets
, s
);
760 int err
= tor_socket_errno(-1);
761 log_info(LD_NET
, "Close returned an error: %s", tor_socket_strerror(err
));
763 if (err
!= WSAENOTSOCK
)
772 if (n_sockets_open
< 0)
773 log_warn(LD_BUG
, "Our socket count is below zero: %d. Please submit a "
774 "bug report.", n_sockets_open
);
775 socket_accounting_unlock();
779 #ifdef DEBUG_SOCKET_COUNTING
780 /** Helper: if DEBUG_SOCKET_COUNTING is enabled, remember that <b>s</b> is
781 * now an open socket. */
783 mark_socket_open(int s
)
785 if (s
> max_socket
) {
786 if (max_socket
== -1) {
787 open_sockets
= bitarray_init_zero(s
+128);
790 open_sockets
= bitarray_expand(open_sockets
, max_socket
, s
+128);
794 if (bitarray_is_set(open_sockets
, s
)) {
795 log_warn(LD_BUG
, "I thought that %d was already open, but socket() just "
796 "gave it to me!", s
);
798 bitarray_set(open_sockets
, s
);
801 #define mark_socket_open(s) STMT_NIL
804 /** As socket(), but counts the number of open sockets. */
806 tor_open_socket(int domain
, int type
, int protocol
)
808 int s
= socket(domain
, type
, protocol
);
810 socket_accounting_lock();
813 socket_accounting_unlock();
818 /** As socket(), but counts the number of open sockets. */
820 tor_accept_socket(int sockfd
, struct sockaddr
*addr
, socklen_t
*len
)
822 int s
= accept(sockfd
, addr
, len
);
824 socket_accounting_lock();
827 socket_accounting_unlock();
832 /** Return the number of sockets we currently have opened. */
834 get_n_open_sockets(void)
837 socket_accounting_lock();
839 socket_accounting_unlock();
843 /** Turn <b>socket</b> into a nonblocking socket.
846 set_socket_nonblocking(int socket
)
848 #if defined(MS_WINDOWS)
849 unsigned long nonblocking
= 1;
850 ioctlsocket(socket
, FIONBIO
, (unsigned long*) &nonblocking
);
852 fcntl(socket
, F_SETFL
, O_NONBLOCK
);
857 * Allocate a pair of connected sockets. (Like socketpair(family,
858 * type,protocol,fd), but works on systems that don't have
861 * Currently, only (AF_UNIX, SOCK_STREAM, 0) sockets are supported.
863 * Note that on systems without socketpair, this call will fail if
864 * localhost is inaccessible (for example, if the networking
865 * stack is down). And even if it succeeds, the socket pair will not
866 * be able to read while localhost is down later (the socket pair may
867 * even close, depending on OS-specific timeouts).
869 * Returns 0 on success and -errno on failure; do not rely on the value
870 * of errno or WSAGetLastError().
872 /* It would be nicer just to set errno, but that won't work for windows. */
874 tor_socketpair(int family
, int type
, int protocol
, int fd
[2])
876 //don't use win32 socketpairs (they are always bad)
877 #if defined(HAVE_SOCKETPAIR) && !defined(MS_WINDOWS)
879 r
= socketpair(family
, type
, protocol
, fd
);
881 socket_accounting_lock();
884 mark_socket_open(fd
[0]);
888 mark_socket_open(fd
[1]);
890 socket_accounting_unlock();
892 return r
< 0 ? -errno
: r
;
894 /* This socketpair does not work when localhost is down. So
895 * it's really not the same thing at all. But it's close enough
896 * for now, and really, when localhost is down sometimes, we
897 * have other problems too.
902 struct sockaddr_in listen_addr
;
903 struct sockaddr_in connect_addr
;
905 int saved_errno
= -1;
913 return -WSAEAFNOSUPPORT
;
915 return -EAFNOSUPPORT
;
922 listener
= tor_open_socket(AF_INET
, type
, 0);
924 return -tor_socket_errno(-1);
925 memset(&listen_addr
, 0, sizeof(listen_addr
));
926 listen_addr
.sin_family
= AF_INET
;
927 listen_addr
.sin_addr
.s_addr
= htonl(INADDR_LOOPBACK
);
928 listen_addr
.sin_port
= 0; /* kernel chooses port. */
929 if (bind(listener
, (struct sockaddr
*) &listen_addr
, sizeof (listen_addr
))
931 goto tidy_up_and_fail
;
932 if (listen(listener
, 1) == -1)
933 goto tidy_up_and_fail
;
935 connector
= tor_open_socket(AF_INET
, type
, 0);
937 goto tidy_up_and_fail
;
938 /* We want to find out the port number to connect to. */
939 size
= sizeof(connect_addr
);
940 if (getsockname(listener
, (struct sockaddr
*) &connect_addr
, &size
) == -1)
941 goto tidy_up_and_fail
;
942 if (size
!= sizeof (connect_addr
))
943 goto abort_tidy_up_and_fail
;
944 if (connect(connector
, (struct sockaddr
*) &connect_addr
,
945 sizeof(connect_addr
)) == -1)
946 goto tidy_up_and_fail
;
948 size
= sizeof(listen_addr
);
949 acceptor
= tor_accept_socket(listener
,
950 (struct sockaddr
*) &listen_addr
, &size
);
952 goto tidy_up_and_fail
;
953 if (size
!= sizeof(listen_addr
))
954 goto abort_tidy_up_and_fail
;
955 tor_close_socket(listener
);
956 /* Now check we are talking to ourself by matching port and host on the
958 if (getsockname(connector
, (struct sockaddr
*) &connect_addr
, &size
) == -1)
959 goto tidy_up_and_fail
;
960 if (size
!= sizeof (connect_addr
)
961 || listen_addr
.sin_family
!= connect_addr
.sin_family
962 || listen_addr
.sin_addr
.s_addr
!= connect_addr
.sin_addr
.s_addr
963 || listen_addr
.sin_port
!= connect_addr
.sin_port
) {
964 goto abort_tidy_up_and_fail
;
971 abort_tidy_up_and_fail
:
973 saved_errno
= WSAECONNABORTED
;
975 saved_errno
= ECONNABORTED
; /* I hope this is portable and appropriate. */
981 tor_close_socket(listener
);
983 tor_close_socket(connector
);
985 tor_close_socket(acceptor
);
990 #define ULIMIT_BUFFER 32 /* keep 32 extra fd's beyond _ConnLimit */
992 /** Learn the maximum allowed number of file descriptors. (Some systems
993 * have a low soft limit.
995 * We compute this by finding the largest number that we can use.
996 * If we can't find a number greater than or equal to <b>limit</b>,
997 * then we fail: return -1.
999 * Otherwise, return 0 and store the maximum we found inside <b>max_out</b>.*/
1001 set_max_file_descriptors(rlim_t limit
, int *max_out
)
1003 /* Define some maximum connections values for systems where we cannot
1004 * automatically determine a limit. Re Cygwin, see
1005 * http://archives.seul.org/or/talk/Aug-2006/msg00210.html
1006 * For an iPhone, 9999 should work. For Windows and all other unknown
1007 * systems we use 15000 as the default. */
1008 #ifndef HAVE_GETRLIMIT
1009 #if defined(CYGWIN) || defined(__CYGWIN__)
1010 const char *platform
= "Cygwin";
1011 const unsigned long MAX_CONNECTIONS
= 3200;
1012 #elif defined(IPHONE)
1013 const char *platform
= "iPhone";
1014 const unsigned long MAX_CONNECTIONS
= 9999;
1015 #elif defined(MS_WINDOWS)
1016 const char *platform
= "Windows";
1017 const unsigned long MAX_CONNECTIONS
= 15000;
1019 const char *platform
= "unknown platforms with no getrlimit()";
1020 const unsigned long MAX_CONNECTIONS
= 15000;
1022 log_fn(LOG_INFO
, LD_NET
,
1023 "This platform is missing getrlimit(). Proceeding.");
1024 if (limit
> MAX_CONNECTIONS
) {
1026 "We do not support more than %lu file descriptors "
1027 "on %s. Tried to raise to %lu.",
1028 (unsigned long)MAX_CONNECTIONS
, platform
, (unsigned long)limit
);
1031 limit
= MAX_CONNECTIONS
;
1032 #else /* HAVE_GETRLIMIT */
1034 tor_assert(limit
> 0);
1036 if (getrlimit(RLIMIT_NOFILE
, &rlim
) != 0) {
1037 log_warn(LD_NET
, "Could not get maximum number of file descriptors: %s",
1042 if (rlim
.rlim_max
< limit
) {
1043 log_warn(LD_CONFIG
,"We need %lu file descriptors available, and we're "
1044 "limited to %lu. Please change your ulimit -n.",
1045 (unsigned long)limit
, (unsigned long)rlim
.rlim_max
);
1049 if (rlim
.rlim_max
> rlim
.rlim_cur
) {
1050 log_info(LD_NET
,"Raising max file descriptors from %lu to %lu.",
1051 (unsigned long)rlim
.rlim_cur
, (unsigned long)rlim
.rlim_max
);
1053 rlim
.rlim_cur
= rlim
.rlim_max
;
1055 if (setrlimit(RLIMIT_NOFILE
, &rlim
) != 0) {
1058 if (errno
== EINVAL
&& OPEN_MAX
< rlim
.rlim_cur
) {
1059 /* On some platforms, OPEN_MAX is the real limit, and getrlimit() is
1060 * full of nasty lies. I'm looking at you, OSX 10.5.... */
1061 rlim
.rlim_cur
= OPEN_MAX
;
1062 if (setrlimit(RLIMIT_NOFILE
, &rlim
) == 0) {
1063 if (rlim
.rlim_cur
< (rlim_t
)limit
) {
1064 log_warn(LD_CONFIG
, "We are limited to %lu file descriptors by "
1065 "OPEN_MAX, and ConnLimit is %lu. Changing ConnLimit; sorry.",
1066 (unsigned long)OPEN_MAX
, (unsigned long)limit
);
1068 log_info(LD_CONFIG
, "Dropped connection limit to OPEN_MAX (%lu); "
1069 "Apparently, %lu was too high and rlimit lied to us.",
1070 (unsigned long)OPEN_MAX
, (unsigned long)rlim
.rlim_max
);
1075 #endif /* OPEN_MAX */
1077 log_warn(LD_CONFIG
,"Couldn't set maximum number of file descriptors: %s",
1082 /* leave some overhead for logs, etc, */
1083 limit
= rlim
.rlim_cur
;
1084 #endif /* HAVE_GETRLIMIT */
1086 if (limit
< ULIMIT_BUFFER
) {
1088 "ConnLimit must be at least %d. Failing.", ULIMIT_BUFFER
);
1091 if (limit
> INT_MAX
)
1093 tor_assert(max_out
);
1094 *max_out
= (int)limit
- ULIMIT_BUFFER
;
1099 /** Log details of current user and group credentials. Return 0 on
1100 * success. Logs and return -1 on failure.
1103 log_credential_status(void)
1105 #define CREDENTIAL_LOG_LEVEL LOG_INFO
1106 /* Real, effective and saved UIDs */
1107 uid_t ruid
, euid
, suid
;
1108 /* Read, effective and saved GIDs */
1109 gid_t rgid
, egid
, sgid
;
1110 /* Supplementary groups */
1111 gid_t sup_gids
[NGROUPS_MAX
+ 1];
1112 /* Number of supplementary groups */
1116 #ifdef HAVE_GETRESUID
1117 if (getresuid(&ruid
, &euid
, &suid
) != 0 ) {
1118 log_warn(LD_GENERAL
, "Error getting changed UIDs: %s", strerror(errno
));
1121 log_fn(CREDENTIAL_LOG_LEVEL
, LD_GENERAL
,
1122 "UID is %u (real), %u (effective), %u (saved)",
1123 (unsigned)ruid
, (unsigned)euid
, (unsigned)suid
);
1126 /* getresuid is not present on MacOS X, so we can't get the saved (E)UID */
1131 log_fn(CREDENTIAL_LOG_LEVEL
, LD_GENERAL
,
1132 "UID is %u (real), %u (effective), unknown (saved)",
1133 (unsigned)ruid
, (unsigned)euid
);
1137 #ifdef HAVE_GETRESGID
1138 if (getresgid(&rgid
, &egid
, &sgid
) != 0 ) {
1139 log_warn(LD_GENERAL
, "Error getting changed GIDs: %s", strerror(errno
));
1142 log_fn(CREDENTIAL_LOG_LEVEL
, LD_GENERAL
,
1143 "GID is %u (real), %u (effective), %u (saved)",
1144 (unsigned)rgid
, (unsigned)egid
, (unsigned)sgid
);
1147 /* getresgid is not present on MacOS X, so we can't get the saved (E)GID */
1151 log_fn(CREDENTIAL_LOG_LEVEL
, LD_GENERAL
,
1152 "GID is %u (real), %u (effective), unknown (saved)",
1153 (unsigned)rgid
, (unsigned)egid
);
1156 /* log supplementary groups */
1157 if ((ngids
= getgroups(NGROUPS_MAX
+ 1, sup_gids
)) < 0) {
1158 log_warn(LD_GENERAL
, "Error getting supplementary GIDs: %s",
1165 smartlist_t
*elts
= smartlist_create();
1167 for (i
= 0; i
<ngids
; i
++) {
1168 strgid
= tor_malloc(11);
1169 if (tor_snprintf(strgid
, 11, "%u", (unsigned)sup_gids
[i
]) < 0) {
1170 log_warn(LD_GENERAL
, "Error printing supplementary GIDs");
1175 smartlist_add(elts
, strgid
);
1178 s
= smartlist_join_strings(elts
, " ", 0, NULL
);
1180 log_fn(CREDENTIAL_LOG_LEVEL
, LD_GENERAL
, "Supplementary groups are: %s",s
);
1184 SMARTLIST_FOREACH(elts
, char *, cp
,
1188 smartlist_free(elts
);
1197 /** Call setuid and setgid to run as <b>user</b> and switch to their
1198 * primary group. Return 0 on success. On failure, log and return -1.
1201 switch_id(const char *user
)
1204 struct passwd
*pw
= NULL
;
1207 static int have_already_switched_id
= 0;
1211 if (have_already_switched_id
)
1214 /* Log the initial credential state */
1215 if (log_credential_status())
1218 log_fn(CREDENTIAL_LOG_LEVEL
, LD_GENERAL
, "Changing user and groups");
1220 /* Get old UID/GID to check if we changed correctly */
1224 /* Lookup the user and group information, if we have a problem, bail out. */
1225 pw
= getpwnam(user
);
1227 log_warn(LD_CONFIG
, "Error setting configured user: %s not found", user
);
1231 /* Properly switch egid,gid,euid,uid here or bail out */
1232 if (setgroups(1, &pw
->pw_gid
)) {
1233 log_warn(LD_GENERAL
, "Error setting groups to gid %d: \"%s\".",
1234 (int)pw
->pw_gid
, strerror(errno
));
1235 if (old_uid
== pw
->pw_uid
) {
1236 log_warn(LD_GENERAL
, "Tor is already running as %s. You do not need "
1237 "the \"User\" option if you are already running as the user "
1238 "you want to be. (If you did not set the User option in your "
1239 "torrc, check whether it was specified on the command line "
1240 "by a startup script.)", user
);
1242 log_warn(LD_GENERAL
, "If you set the \"User\" option, you must start Tor"
1248 if (setegid(pw
->pw_gid
)) {
1249 log_warn(LD_GENERAL
, "Error setting egid to %d: %s",
1250 (int)pw
->pw_gid
, strerror(errno
));
1254 if (setgid(pw
->pw_gid
)) {
1255 log_warn(LD_GENERAL
, "Error setting gid to %d: %s",
1256 (int)pw
->pw_gid
, strerror(errno
));
1260 if (setuid(pw
->pw_uid
)) {
1261 log_warn(LD_GENERAL
, "Error setting configured uid to %s (%d): %s",
1262 user
, (int)pw
->pw_uid
, strerror(errno
));
1266 if (seteuid(pw
->pw_uid
)) {
1267 log_warn(LD_GENERAL
, "Error setting configured euid to %s (%d): %s",
1268 user
, (int)pw
->pw_uid
, strerror(errno
));
1272 /* This is how OpenBSD rolls:
1273 if (setgroups(1, &pw->pw_gid) || setegid(pw->pw_gid) ||
1274 setgid(pw->pw_gid) || setuid(pw->pw_uid) || seteuid(pw->pw_uid)) {
1275 setgid(pw->pw_gid) || seteuid(pw->pw_uid) || setuid(pw->pw_uid)) {
1276 log_warn(LD_GENERAL, "Error setting configured UID/GID: %s",
1282 /* We've properly switched egid, gid, euid, uid, and supplementary groups if
1285 #if !defined(CYGWIN) && !defined(__CYGWIN__)
1286 /* If we tried to drop privilege to a group/user other than root, attempt to
1287 * restore root (E)(U|G)ID, and abort if the operation succeeds */
1289 /* Only check for privilege dropping if we were asked to be non-root */
1291 /* Try changing GID/EGID */
1292 if (pw
->pw_gid
!= old_gid
&&
1293 (setgid(old_gid
) != -1 || setegid(old_gid
) != -1)) {
1294 log_warn(LD_GENERAL
, "Was able to restore group credentials even after "
1295 "switching GID: this means that the setgid code didn't work.");
1299 /* Try changing UID/EUID */
1300 if (pw
->pw_uid
!= old_uid
&&
1301 (setuid(old_uid
) != -1 || seteuid(old_uid
) != -1)) {
1302 log_warn(LD_GENERAL
, "Was able to restore user credentials even after "
1303 "switching UID: this means that the setuid code didn't work.");
1309 /* Check what really happened */
1310 if (log_credential_status()) {
1314 have_already_switched_id
= 1; /* mark success so we never try again */
1316 #if defined(__linux__) && defined(HAVE_SYS_PRCTL_H) && defined(HAVE_PRCTL)
1317 #ifdef PR_SET_DUMPABLE
1319 /* Re-enable core dumps if we're not running as root. */
1320 log_info(LD_CONFIG
, "Re-enabling coredumps");
1321 if (prctl(PR_SET_DUMPABLE
, 1)) {
1322 log_warn(LD_CONFIG
, "Unable to re-enable coredumps: %s",strerror(errno
));
1333 "User specified but switching users is unsupported on your OS.");
1339 /** Allocate and return a string containing the home directory for the
1340 * user <b>username</b>. Only works on posix-like systems. */
1342 get_user_homedir(const char *username
)
1345 tor_assert(username
);
1347 if (!(pw
= getpwnam(username
))) {
1348 log_err(LD_CONFIG
,"User \"%s\" not found.", username
);
1351 return tor_strdup(pw
->pw_dir
);
1355 /** Set *addr to the IP address (in dotted-quad notation) stored in c.
1356 * Return 1 on success, 0 if c is badly formatted. (Like inet_aton(c,addr),
1357 * but works on Windows and Solaris.)
1360 tor_inet_aton(const char *str
, struct in_addr
* addr
)
1364 if (tor_sscanf(str
, "%3u.%3u.%3u.%3u%c", &a
,&b
,&c
,&d
,&more
) != 4)
1366 if (a
> 255) return 0;
1367 if (b
> 255) return 0;
1368 if (c
> 255) return 0;
1369 if (d
> 255) return 0;
1370 addr
->s_addr
= htonl((a
<<24) | (b
<<16) | (c
<<8) | d
);
1374 /** Given <b>af</b>==AF_INET and <b>src</b> a struct in_addr, or
1375 * <b>af</b>==AF_INET6 and <b>src</b> a struct in6_addr, try to format the
1376 * address and store it in the <b>len</b>-byte buffer <b>dst</b>. Returns
1377 * <b>dst</b> on success, NULL on failure.
1379 * (Like inet_ntop(af,src,dst,len), but works on platforms that don't have it:
1380 * Tor sometimes needs to format ipv6 addresses even on platforms without ipv6
1383 tor_inet_ntop(int af
, const void *src
, char *dst
, size_t len
)
1385 if (af
== AF_INET
) {
1386 if (tor_inet_ntoa(src
, dst
, len
) < 0)
1390 } else if (af
== AF_INET6
) {
1391 const struct in6_addr
*addr
= src
;
1393 int longestGapLen
= 0, longestGapPos
= -1, i
,
1394 curGapPos
= -1, curGapLen
= 0;
1396 for (i
= 0; i
< 8; ++i
) {
1397 words
[i
] = (((uint16_t)addr
->s6_addr
[2*i
])<<8) + addr
->s6_addr
[2*i
+1];
1399 if (words
[0] == 0 && words
[1] == 0 && words
[2] == 0 && words
[3] == 0 &&
1400 words
[4] == 0 && ((words
[5] == 0 && words
[6] && words
[7]) ||
1401 (words
[5] == 0xffff))) {
1402 /* This is an IPv4 address. */
1403 if (words
[5] == 0) {
1404 tor_snprintf(buf
, sizeof(buf
), "::%d.%d.%d.%d",
1405 addr
->s6_addr
[12], addr
->s6_addr
[13],
1406 addr
->s6_addr
[14], addr
->s6_addr
[15]);
1408 tor_snprintf(buf
, sizeof(buf
), "::%x:%d.%d.%d.%d", words
[5],
1409 addr
->s6_addr
[12], addr
->s6_addr
[13],
1410 addr
->s6_addr
[14], addr
->s6_addr
[15]);
1412 if (strlen(buf
) > len
)
1414 strlcpy(dst
, buf
, len
);
1419 if (words
[i
] == 0) {
1422 while (i
<8 && words
[i
] == 0) {
1425 if (curGapLen
> longestGapLen
) {
1426 longestGapPos
= curGapPos
;
1427 longestGapLen
= curGapLen
;
1433 if (longestGapLen
<=1)
1437 for (i
= 0; i
< 8; ++i
) {
1438 if (words
[i
] == 0 && longestGapPos
== i
) {
1442 while (i
< 8 && words
[i
] == 0)
1444 --i
; /* to compensate for loop increment. */
1446 tor_snprintf(cp
, sizeof(buf
)-(cp
-buf
), "%x", (unsigned)words
[i
]);
1453 if (strlen(buf
) > len
)
1455 strlcpy(dst
, buf
, len
);
1462 /** Given <b>af</b>==AF_INET or <b>af</b>==AF_INET6, and a string <b>src</b>
1463 * encoding an IPv4 address or IPv6 address correspondingly, try to parse the
1464 * address and store the result in <b>dst</b> (which must have space for a
1465 * struct in_addr or a struct in6_addr, as appropriate). Return 1 on success,
1466 * 0 on a bad parse, and -1 on a bad <b>af</b>.
1468 * (Like inet_pton(af,src,dst) but works on platforms that don't have it: Tor
1469 * sometimes needs to format ipv6 addresses even on platforms without ipv6
1472 tor_inet_pton(int af
, const char *src
, void *dst
)
1474 if (af
== AF_INET
) {
1475 return tor_inet_aton(src
, dst
);
1476 } else if (af
== AF_INET6
) {
1477 struct in6_addr
*out
= dst
;
1479 int gapPos
= -1, i
, setWords
=0;
1480 const char *dot
= strchr(src
, '.');
1481 const char *eow
; /* end of words. */
1485 eow
= src
+strlen(src
);
1487 unsigned byte1
,byte2
,byte3
,byte4
;
1489 for (eow
= dot
-1; eow
>= src
&& TOR_ISDIGIT(*eow
); --eow
)
1493 /* We use "scanf" because some platform inet_aton()s are too lax
1494 * about IPv4 addresses of the form "1.2.3" */
1495 if (tor_sscanf(eow
, "%3u.%3u.%3u.%3u%c",
1496 &byte1
,&byte2
,&byte3
,&byte4
,&more
) != 4)
1499 if (byte1
> 255 || byte2
> 255 || byte3
> 255 || byte4
> 255)
1502 words
[6] = (byte1
<<8) | byte2
;
1503 words
[7] = (byte3
<<8) | byte4
;
1511 if (TOR_ISXDIGIT(*src
)) {
1513 long r
= strtol(src
, &next
, 16);
1521 words
[i
++] = (uint16_t)r
;
1524 if (*src
!= ':' && src
!= eow
)
1527 } else if (*src
== ':' && i
> 0 && gapPos
==-1) {
1530 } else if (*src
== ':' && i
== 0 && src
[1] == ':' && gapPos
==-1) {
1539 (setWords
== 8 && gapPos
!= -1) ||
1540 (setWords
< 8 && gapPos
== -1))
1544 int nToMove
= setWords
- (dot
? 2 : 0) - gapPos
;
1545 int gapLen
= 8 - setWords
;
1546 tor_assert(nToMove
>= 0);
1547 memmove(&words
[gapPos
+gapLen
], &words
[gapPos
],
1548 sizeof(uint16_t)*nToMove
);
1549 memset(&words
[gapPos
], 0, sizeof(uint16_t)*gapLen
);
1551 for (i
= 0; i
< 8; ++i
) {
1552 out
->s6_addr
[2*i
] = words
[i
] >> 8;
1553 out
->s6_addr
[2*i
+1] = words
[i
] & 0xff;
1562 /** Similar behavior to Unix gethostbyname: resolve <b>name</b>, and set
1563 * *<b>addr</b> to the proper IP address, in host byte order. Returns 0
1564 * on success, -1 on failure; 1 on transient failure.
1566 * (This function exists because standard windows gethostbyname
1567 * doesn't treat raw IP addresses properly.)
1570 tor_lookup_hostname(const char *name
, uint32_t *addr
)
1575 if ((ret
= tor_addr_lookup(name
, AF_INET
, &myaddr
)))
1578 if (tor_addr_family(&myaddr
) == AF_INET
) {
1579 *addr
= tor_addr_to_ipv4h(&myaddr
);
1586 /** Hold the result of our call to <b>uname</b>. */
1587 static char uname_result
[256];
1588 /** True iff uname_result is set. */
1589 static int uname_result_is_set
= 0;
1591 /** Return a pointer to a description of our platform.
1599 if (!uname_result_is_set
) {
1601 if (uname(&u
) != -1) {
1602 /* (Linux says 0 is success, Solaris says 1 is success) */
1603 tor_snprintf(uname_result
, sizeof(uname_result
), "%s %s",
1604 u
.sysname
, u
.machine
);
1609 OSVERSIONINFOEX info
;
1611 const char *plat
= NULL
;
1612 const char *extra
= NULL
;
1614 unsigned major
; unsigned minor
; const char *version
;
1615 } win_version_table
[] = {
1616 { 6, 0, "Windows \"Longhorn\"" },
1617 { 5, 2, "Windows Server 2003" },
1618 { 5, 1, "Windows XP" },
1619 { 5, 0, "Windows 2000" },
1620 /* { 4, 0, "Windows NT 4.0" }, */
1621 { 4, 90, "Windows Me" },
1622 { 4, 10, "Windows 98" },
1623 /* { 4, 0, "Windows 95" } */
1624 { 3, 51, "Windows NT 3.51" },
1627 memset(&info
, 0, sizeof(info
));
1628 info
.dwOSVersionInfoSize
= sizeof(info
);
1629 if (! GetVersionEx((LPOSVERSIONINFO
)&info
)) {
1630 strlcpy(uname_result
, "Bizarre version of Windows where GetVersionEx"
1631 " doesn't work.", sizeof(uname_result
));
1632 uname_result_is_set
= 1;
1633 return uname_result
;
1635 if (info
.dwMajorVersion
== 4 && info
.dwMinorVersion
== 0) {
1636 if (info
.dwPlatformId
== VER_PLATFORM_WIN32_NT
)
1637 plat
= "Windows NT 4.0";
1639 plat
= "Windows 95";
1640 if (info
.szCSDVersion
[1] == 'B')
1642 else if (info
.szCSDVersion
[1] == 'C')
1645 for (i
=0; win_version_table
[i
].major
>0; ++i
) {
1646 if (win_version_table
[i
].major
== info
.dwMajorVersion
&&
1647 win_version_table
[i
].minor
== info
.dwMinorVersion
) {
1648 plat
= win_version_table
[i
].version
;
1653 if (plat
&& !strcmp(plat
, "Windows 98")) {
1654 if (info
.szCSDVersion
[1] == 'A')
1656 else if (info
.szCSDVersion
[1] == 'B')
1661 extra
= info
.szCSDVersion
;
1662 tor_snprintf(uname_result
, sizeof(uname_result
), "%s %s",
1665 if (info
.dwMajorVersion
> 6 ||
1666 (info
.dwMajorVersion
==6 && info
.dwMinorVersion
>0))
1667 tor_snprintf(uname_result
, sizeof(uname_result
),
1668 "Very recent version of Windows [major=%d,minor=%d] %s",
1669 (int)info
.dwMajorVersion
,(int)info
.dwMinorVersion
,
1672 tor_snprintf(uname_result
, sizeof(uname_result
),
1673 "Unrecognized version of Windows [major=%d,minor=%d] %s",
1674 (int)info
.dwMajorVersion
,(int)info
.dwMinorVersion
,
1677 #ifdef VER_SUITE_BACKOFFICE
1678 if (info
.wProductType
== VER_NT_DOMAIN_CONTROLLER
) {
1679 strlcat(uname_result
, " [domain controller]", sizeof(uname_result
));
1680 } else if (info
.wProductType
== VER_NT_SERVER
) {
1681 strlcat(uname_result
, " [server]", sizeof(uname_result
));
1682 } else if (info
.wProductType
== VER_NT_WORKSTATION
) {
1683 strlcat(uname_result
, " [workstation]", sizeof(uname_result
));
1687 strlcpy(uname_result
, "Unknown platform", sizeof(uname_result
));
1690 uname_result_is_set
= 1;
1692 return uname_result
;
1699 #if defined(USE_PTHREADS)
1700 /** Wraps a void (*)(void*) function and its argument so we can
1701 * invoke them in a way pthreads would expect.
1703 typedef struct tor_pthread_data_t
{
1704 void (*func
)(void *);
1706 } tor_pthread_data_t
;
1707 /** Given a tor_pthread_data_t <b>_data</b>, call _data->func(d->data)
1708 * and free _data. Used to make sure we can call functions the way pthread
1711 tor_pthread_helper_fn(void *_data
)
1713 tor_pthread_data_t
*data
= _data
;
1714 void (*func
)(void*);
1716 /* mask signals to worker threads to avoid SIGPIPE, etc */
1718 /* We're in a subthread; don't handle any signals here. */
1720 pthread_sigmask(SIG_SETMASK
, &sigs
, NULL
);
1730 /** Minimalist interface to run a void function in the background. On
1731 * Unix calls fork, on win32 calls beginthread. Returns -1 on failure.
1732 * func should not return, but rather should call spawn_exit.
1734 * NOTE: if <b>data</b> is used, it should not be allocated on the stack,
1735 * since in a multithreaded environment, there is no way to be sure that
1736 * the caller's stack will still be around when the called function is
1740 spawn_func(void (*func
)(void *), void *data
)
1742 #if defined(USE_WIN32_THREADS)
1744 rv
= (int)_beginthread(func
, 0, data
);
1748 #elif defined(USE_PTHREADS)
1750 tor_pthread_data_t
*d
;
1751 d
= tor_malloc(sizeof(tor_pthread_data_t
));
1754 if (pthread_create(&thread
,NULL
,tor_pthread_helper_fn
,d
))
1756 if (pthread_detach(thread
))
1767 tor_assert(0); /* Should never reach here. */
1768 return 0; /* suppress "control-reaches-end-of-non-void" warning. */
1776 /** End the current thread/process.
1781 #if defined(USE_WIN32_THREADS)
1783 //we should never get here. my compiler thinks that _endthread returns, this
1784 //is an attempt to fool it.
1787 #elif defined(USE_PTHREADS)
1790 /* http://www.erlenstar.demon.co.uk/unix/faq_2.html says we should
1791 * call _exit, not exit, from child processes. */
1797 /** Set *timeval to the current time of day. On error, log and terminate.
1798 * (Same as gettimeofday(timeval,NULL), but never returns -1.)
1801 tor_gettimeofday(struct timeval
*timeval
)
1804 /* Epoch bias copied from perl: number of units between windows epoch and
1806 #define EPOCH_BIAS U64_LITERAL(116444736000000000)
1807 #define UNITS_PER_SEC U64_LITERAL(10000000)
1808 #define USEC_PER_SEC U64_LITERAL(1000000)
1809 #define UNITS_PER_USEC U64_LITERAL(10)
1814 /* number of 100-nsec units since Jan 1, 1601 */
1815 GetSystemTimeAsFileTime(&ft
.ft_ft
);
1816 if (ft
.ft_64
< EPOCH_BIAS
) {
1817 log_err(LD_GENERAL
,"System time is before 1970; failing.");
1820 ft
.ft_64
-= EPOCH_BIAS
;
1821 timeval
->tv_sec
= (unsigned) (ft
.ft_64
/ UNITS_PER_SEC
);
1822 timeval
->tv_usec
= (unsigned) ((ft
.ft_64
/ UNITS_PER_USEC
) % USEC_PER_SEC
);
1823 #elif defined(HAVE_GETTIMEOFDAY)
1824 if (gettimeofday(timeval
, NULL
)) {
1825 log_err(LD_GENERAL
,"gettimeofday failed.");
1826 /* If gettimeofday dies, we have either given a bad timezone (we didn't),
1830 #elif defined(HAVE_FTIME)
1833 timeval
->tv_sec
= tb
.time
;
1834 timeval
->tv_usec
= tb
.millitm
* 1000;
1836 #error "No way to get time."
1841 #if defined(TOR_IS_MULTITHREADED) && !defined(MS_WINDOWS)
1842 /** Defined iff we need to add locks when defining fake versions of reentrant
1843 * versions of time-related functions. */
1844 #define TIME_FNS_NEED_LOCKS
1847 #ifndef HAVE_LOCALTIME_R
1848 #ifdef TIME_FNS_NEED_LOCKS
1850 tor_localtime_r(const time_t *timep
, struct tm
*result
)
1853 static tor_mutex_t
*m
=NULL
;
1854 if (!m
) { m
=tor_mutex_new(); }
1856 tor_mutex_acquire(m
);
1857 r
= localtime(timep
);
1858 memcpy(result
, r
, sizeof(struct tm
));
1859 tor_mutex_release(m
);
1864 tor_localtime_r(const time_t *timep
, struct tm
*result
)
1868 r
= localtime(timep
);
1869 memcpy(result
, r
, sizeof(struct tm
));
1875 #ifndef HAVE_GMTIME_R
1876 #ifdef TIME_FNS_NEED_LOCKS
1878 tor_gmtime_r(const time_t *timep
, struct tm
*result
)
1881 static tor_mutex_t
*m
=NULL
;
1882 if (!m
) { m
=tor_mutex_new(); }
1884 tor_mutex_acquire(m
);
1886 memcpy(result
, r
, sizeof(struct tm
));
1887 tor_mutex_release(m
);
1892 tor_gmtime_r(const time_t *timep
, struct tm
*result
)
1897 memcpy(result
, r
, sizeof(struct tm
));
1903 #if defined(USE_WIN32_THREADS)
1905 tor_mutex_init(tor_mutex_t
*m
)
1907 InitializeCriticalSection(&m
->mutex
);
1910 tor_mutex_uninit(tor_mutex_t
*m
)
1912 DeleteCriticalSection(&m
->mutex
);
1915 tor_mutex_acquire(tor_mutex_t
*m
)
1918 EnterCriticalSection(&m
->mutex
);
1921 tor_mutex_release(tor_mutex_t
*m
)
1923 LeaveCriticalSection(&m
->mutex
);
1926 tor_get_thread_id(void)
1928 return (unsigned long)GetCurrentThreadId();
1930 #elif defined(USE_PTHREADS)
1931 /** A mutex attribute that we're going to use to tell pthreads that we want
1932 * "reentrant" mutexes (i.e., once we can re-lock if we're already holding
1934 static pthread_mutexattr_t attr_reentrant
;
1935 /** True iff we've called tor_threads_init() */
1936 static int threads_initialized
= 0;
1937 /** Initialize <b>mutex</b> so it can be locked. Every mutex must be set
1938 * up with tor_mutex_init() or tor_mutex_new(); not both. */
1940 tor_mutex_init(tor_mutex_t
*mutex
)
1943 if (PREDICT_UNLIKELY(!threads_initialized
))
1945 err
= pthread_mutex_init(&mutex
->mutex
, &attr_reentrant
);
1946 if (PREDICT_UNLIKELY(err
)) {
1947 log_err(LD_GENERAL
, "Error %d creating a mutex.", err
);
1948 tor_fragile_assert();
1951 /** Wait until <b>m</b> is free, then acquire it. */
1953 tor_mutex_acquire(tor_mutex_t
*m
)
1957 err
= pthread_mutex_lock(&m
->mutex
);
1958 if (PREDICT_UNLIKELY(err
)) {
1959 log_err(LD_GENERAL
, "Error %d locking a mutex.", err
);
1960 tor_fragile_assert();
1963 /** Release the lock <b>m</b> so another thread can have it. */
1965 tor_mutex_release(tor_mutex_t
*m
)
1969 err
= pthread_mutex_unlock(&m
->mutex
);
1970 if (PREDICT_UNLIKELY(err
)) {
1971 log_err(LD_GENERAL
, "Error %d unlocking a mutex.", err
);
1972 tor_fragile_assert();
1975 /** Clean up the mutex <b>m</b> so that it no longer uses any system
1976 * resources. Does not free <b>m</b>. This function must only be called on
1977 * mutexes from tor_mutex_init(). */
1979 tor_mutex_uninit(tor_mutex_t
*m
)
1983 err
= pthread_mutex_destroy(&m
->mutex
);
1984 if (PREDICT_UNLIKELY(err
)) {
1985 log_err(LD_GENERAL
, "Error %d destroying a mutex.", err
);
1986 tor_fragile_assert();
1989 /** Return an integer representing this thread. */
1991 tor_get_thread_id(void)
1997 r
.thr
= pthread_self();
2002 #ifdef TOR_IS_MULTITHREADED
2003 /** Return a newly allocated, ready-for-use mutex. */
2007 tor_mutex_t
*m
= tor_malloc_zero(sizeof(tor_mutex_t
));
2011 /** Release all storage and system resources held by <b>m</b>. */
2013 tor_mutex_free(tor_mutex_t
*m
)
2017 tor_mutex_uninit(m
);
2025 /** Cross-platform condition implementation. */
2027 pthread_cond_t cond
;
2029 /** Return a newly allocated condition, with nobody waiting on it. */
2033 tor_cond_t
*cond
= tor_malloc_zero(sizeof(tor_cond_t
));
2034 if (pthread_cond_init(&cond
->cond
, NULL
)) {
2040 /** Release all resources held by <b>cond</b>. */
2042 tor_cond_free(tor_cond_t
*cond
)
2046 if (pthread_cond_destroy(&cond
->cond
)) {
2047 log_warn(LD_GENERAL
,"Error freeing condition: %s", strerror(errno
));
2052 /** Wait until one of the tor_cond_signal functions is called on <b>cond</b>.
2053 * All waiters on the condition must wait holding the same <b>mutex</b>.
2054 * Returns 0 on success, negative on failure. */
2056 tor_cond_wait(tor_cond_t
*cond
, tor_mutex_t
*mutex
)
2058 return pthread_cond_wait(&cond
->cond
, &mutex
->mutex
) ? -1 : 0;
2060 /** Wake up one of the waiters on <b>cond</b>. */
2062 tor_cond_signal_one(tor_cond_t
*cond
)
2064 pthread_cond_signal(&cond
->cond
);
2066 /** Wake up all of the waiters on <b>cond</b>. */
2068 tor_cond_signal_all(tor_cond_t
*cond
)
2070 pthread_cond_broadcast(&cond
->cond
);
2073 /** Set up common structures for use by threading. */
2075 tor_threads_init(void)
2077 if (!threads_initialized
) {
2078 pthread_mutexattr_init(&attr_reentrant
);
2079 pthread_mutexattr_settype(&attr_reentrant
, PTHREAD_MUTEX_RECURSIVE
);
2080 threads_initialized
= 1;
2084 #elif defined(USE_WIN32_THREADS)
2086 static DWORD cond_event_tls_index
;
2088 CRITICAL_SECTION mutex
;
2089 smartlist_t
*events
;
2094 tor_cond_t
*cond
= tor_malloc_zero(sizeof(tor_cond_t
));
2095 InitializeCriticalSection(&cond
->mutex
);
2096 cond
->events
= smartlist_create();
2100 tor_cond_free(tor_cond_t
*cond
)
2104 DeleteCriticalSection(&cond
->mutex
);
2106 smartlist_free(cond
->events
);
2110 tor_cond_wait(tor_cond_t
*cond
, tor_mutex_t
*mutex
)
2116 event
= TlsGetValue(cond_event_tls_index
);
2118 event
= CreateEvent(0, FALSE
, FALSE
, NULL
);
2119 TlsSetValue(cond_event_tls_index
, event
);
2121 EnterCriticalSection(&cond
->mutex
);
2123 tor_assert(WaitForSingleObject(event
, 0) == WAIT_TIMEOUT
);
2124 tor_assert(!smartlist_isin(cond
->events
, event
));
2125 smartlist_add(cond
->events
, event
);
2127 LeaveCriticalSection(&cond
->mutex
);
2129 tor_mutex_release(mutex
);
2130 r
= WaitForSingleObject(event
, INFINITE
);
2131 tor_mutex_acquire(mutex
);
2134 case WAIT_OBJECT_0
: /* we got the mutex normally. */
2136 case WAIT_ABANDONED
: /* holding thread exited. */
2137 case WAIT_TIMEOUT
: /* Should never happen. */
2141 log_warn(LD_GENERAL
, "Failed to acquire mutex: %d",(int) GetLastError());
2146 tor_cond_signal_one(tor_cond_t
*cond
)
2151 EnterCriticalSection(&cond
->mutex
);
2153 if ((event
= smartlist_pop_last(cond
->events
)))
2156 LeaveCriticalSection(&cond
->mutex
);
2159 tor_cond_signal_all(tor_cond_t
*cond
)
2163 EnterCriticalSection(&cond
->mutex
);
2164 SMARTLIST_FOREACH(cond
->events
, HANDLE
, event
, SetEvent(event
));
2165 smartlist_clear(cond
->events
);
2166 LeaveCriticalSection(&cond
->mutex
);
2170 tor_threads_init(void)
2173 cond_event_tls_index
= TlsAlloc();
2179 #if defined(HAVE_MLOCKALL) && HAVE_DECL_MLOCKALL
2180 /** Attempt to raise the current and max rlimit to infinity for our process.
2181 * This only needs to be done once and can probably only be done when we have
2182 * not already dropped privileges.
2185 tor_set_max_memlock(void)
2187 /* Future consideration for Windows is probably SetProcessWorkingSetSize
2188 * This is similar to setting the memory rlimit of RLIMIT_MEMLOCK
2189 * http://msdn.microsoft.com/en-us/library/ms686234(VS.85).aspx
2192 struct rlimit limit
;
2195 /* Do we want to report current limits first? This is not really needed. */
2196 ret
= getrlimit(RLIMIT_MEMLOCK
, &limit
);
2198 log_warn(LD_GENERAL
, "Could not get RLIMIT_MEMLOCK: %s", strerror(errno
));
2202 /* RLIM_INFINITY is -1 on some platforms. */
2203 limit
.rlim_cur
= RLIM_INFINITY
;
2204 limit
.rlim_max
= RLIM_INFINITY
;
2206 ret
= setrlimit(RLIMIT_MEMLOCK
, &limit
);
2208 if (errno
== EPERM
) {
2209 log_warn(LD_GENERAL
, "You appear to lack permissions to change memory "
2210 "limits. Are you root?");
2211 log_warn(LD_GENERAL
, "Unable to raise RLIMIT_MEMLOCK: %s",
2214 log_warn(LD_GENERAL
, "Could not raise RLIMIT_MEMLOCK: %s",
2224 /** Attempt to lock all current and all future memory pages.
2225 * This should only be called once and while we're privileged.
2226 * Like mlockall() we return 0 when we're successful and -1 when we're not.
2227 * Unlike mlockall() we return 1 if we've already attempted to lock memory.
2232 static int memory_lock_attempted
= 0;
2234 if (memory_lock_attempted
) {
2238 memory_lock_attempted
= 1;
2241 * Future consideration for Windows may be VirtualLock
2242 * VirtualLock appears to implement mlock() but not mlockall()
2244 * http://msdn.microsoft.com/en-us/library/aa366895(VS.85).aspx
2247 #if defined(HAVE_MLOCKALL) && HAVE_DECL_MLOCKALL
2248 if (tor_set_max_memlock() == 0) {
2249 /* Perhaps we only want to log this if we're in a verbose mode? */
2250 log_notice(LD_GENERAL
, "RLIMIT_MEMLOCK is now set to RLIM_INFINITY.");
2253 if (mlockall(MCL_CURRENT
|MCL_FUTURE
) == 0) {
2254 log_notice(LD_GENERAL
, "Insecure OS paging is effectively disabled.");
2257 if (errno
== ENOSYS
) {
2258 /* Apple - it's 2009! I'm looking at you. Grrr. */
2259 log_notice(LD_GENERAL
, "It appears that mlockall() is not available on "
2261 } else if (errno
== EPERM
) {
2262 log_notice(LD_GENERAL
, "It appears that you lack the permissions to "
2263 "lock memory. Are you root?");
2265 log_notice(LD_GENERAL
, "Unable to lock all current and future memory "
2266 "pages: %s", strerror(errno
));
2270 log_warn(LD_GENERAL
, "Unable to lock memory pages. mlockall() unsupported?");
2275 /** Identity of the "main" thread */
2276 static unsigned long main_thread_id
= -1;
2278 /** Start considering the current thread to be the 'main thread'. This has
2279 * no effect on anything besides in_main_thread(). */
2281 set_main_thread(void)
2283 main_thread_id
= tor_get_thread_id();
2285 /** Return true iff called from the main thread. */
2287 in_main_thread(void)
2289 return main_thread_id
== tor_get_thread_id();
2293 * On Windows, WSAEWOULDBLOCK is not always correct: when you see it,
2294 * you need to ask the socket for its actual errno. Also, you need to
2295 * get your errors from WSAGetLastError, not errno. (If you supply a
2296 * socket of -1, we check WSAGetLastError, but don't correct
2299 * The upshot of all of this is that when a socket call fails, you
2300 * should call tor_socket_errno <em>at most once</em> on the failing
2301 * socket to get the error.
2303 #if defined(MS_WINDOWS)
2305 tor_socket_errno(int sock
)
2307 int optval
, optvallen
=sizeof(optval
);
2308 int err
= WSAGetLastError();
2309 if (err
== WSAEWOULDBLOCK
&& sock
>= 0) {
2310 if (getsockopt(sock
, SOL_SOCKET
, SO_ERROR
, (void*)&optval
, &optvallen
))
2319 #if defined(MS_WINDOWS)
2320 #define E(code, s) { code, (s " [" #code " ]") }
2321 struct { int code
; const char *msg
; } windows_socket_errors
[] = {
2322 E(WSAEINTR
, "Interrupted function call"),
2323 E(WSAEACCES
, "Permission denied"),
2324 E(WSAEFAULT
, "Bad address"),
2325 E(WSAEINVAL
, "Invalid argument"),
2326 E(WSAEMFILE
, "Too many open files"),
2327 E(WSAEWOULDBLOCK
, "Resource temporarily unavailable"),
2328 E(WSAEINPROGRESS
, "Operation now in progress"),
2329 E(WSAEALREADY
, "Operation already in progress"),
2330 E(WSAENOTSOCK
, "Socket operation on nonsocket"),
2331 E(WSAEDESTADDRREQ
, "Destination address required"),
2332 E(WSAEMSGSIZE
, "Message too long"),
2333 E(WSAEPROTOTYPE
, "Protocol wrong for socket"),
2334 E(WSAENOPROTOOPT
, "Bad protocol option"),
2335 E(WSAEPROTONOSUPPORT
, "Protocol not supported"),
2336 E(WSAESOCKTNOSUPPORT
, "Socket type not supported"),
2337 /* What's the difference between NOTSUPP and NOSUPPORT? :) */
2338 E(WSAEOPNOTSUPP
, "Operation not supported"),
2339 E(WSAEPFNOSUPPORT
, "Protocol family not supported"),
2340 E(WSAEAFNOSUPPORT
, "Address family not supported by protocol family"),
2341 E(WSAEADDRINUSE
, "Address already in use"),
2342 E(WSAEADDRNOTAVAIL
, "Cannot assign requested address"),
2343 E(WSAENETDOWN
, "Network is down"),
2344 E(WSAENETUNREACH
, "Network is unreachable"),
2345 E(WSAENETRESET
, "Network dropped connection on reset"),
2346 E(WSAECONNABORTED
, "Software caused connection abort"),
2347 E(WSAECONNRESET
, "Connection reset by peer"),
2348 E(WSAENOBUFS
, "No buffer space available"),
2349 E(WSAEISCONN
, "Socket is already connected"),
2350 E(WSAENOTCONN
, "Socket is not connected"),
2351 E(WSAESHUTDOWN
, "Cannot send after socket shutdown"),
2352 E(WSAETIMEDOUT
, "Connection timed out"),
2353 E(WSAECONNREFUSED
, "Connection refused"),
2354 E(WSAEHOSTDOWN
, "Host is down"),
2355 E(WSAEHOSTUNREACH
, "No route to host"),
2356 E(WSAEPROCLIM
, "Too many processes"),
2357 /* Yes, some of these start with WSA, not WSAE. No, I don't know why. */
2358 E(WSASYSNOTREADY
, "Network subsystem is unavailable"),
2359 E(WSAVERNOTSUPPORTED
, "Winsock.dll out of range"),
2360 E(WSANOTINITIALISED
, "Successful WSAStartup not yet performed"),
2361 E(WSAEDISCON
, "Graceful shutdown now in progress"),
2362 #ifdef WSATYPE_NOT_FOUND
2363 E(WSATYPE_NOT_FOUND
, "Class type not found"),
2365 E(WSAHOST_NOT_FOUND
, "Host not found"),
2366 E(WSATRY_AGAIN
, "Nonauthoritative host not found"),
2367 E(WSANO_RECOVERY
, "This is a nonrecoverable error"),
2368 E(WSANO_DATA
, "Valid name, no data record of requested type)"),
2370 /* There are some more error codes whose numeric values are marked
2371 * <b>OS dependent</b>. They start with WSA_, apparently for the same
2372 * reason that practitioners of some craft traditions deliberately
2373 * introduce imperfections into their baskets and rugs "to allow the
2374 * evil spirits to escape." If we catch them, then our binaries
2375 * might not report consistent results across versions of Windows.
2376 * Thus, I'm going to let them all fall through.
2380 /** There does not seem to be a strerror equivalent for Winsock errors.
2381 * Naturally, we have to roll our own.
2384 tor_socket_strerror(int e
)
2387 for (i
=0; windows_socket_errors
[i
].code
>= 0; ++i
) {
2388 if (e
== windows_socket_errors
[i
].code
)
2389 return windows_socket_errors
[i
].msg
;
2395 /** Called before we make any calls to network-related functions.
2396 * (Some operating systems require their network libraries to be
2402 /* This silly exercise is necessary before windows will allow
2403 * gethostbyname to work. */
2406 r
= WSAStartup(0x101,&WSAData
);
2408 log_warn(LD_NET
,"Error initializing windows network layer: code was %d",r
);
2411 /* WSAData.iMaxSockets might show the max sockets we're allowed to use.
2412 * We might use it to complain if we're trying to be a server but have
2413 * too few sockets available. */
2419 /** Return a newly allocated string describing the windows system error code
2420 * <b>err</b>. Note that error codes are different from errno. Error codes
2421 * come from GetLastError() when a winapi call fails. errno is set only when
2422 * ANSI functions fail. Whee. */
2424 format_win32_error(DWORD err
)
2429 /* Somebody once decided that this interface was better than strerror(). */
2430 FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
|
2431 FORMAT_MESSAGE_FROM_SYSTEM
|
2432 FORMAT_MESSAGE_IGNORE_INSERTS
,
2434 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
2439 result
= tor_strdup((char*)str
);
2440 LocalFree(str
); /* LocalFree != free() */
2442 result
= tor_strdup("<unformattable error>");