1 /* Copyright (c) 2003-2004, Roger Dingledine
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2010, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
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)
26 #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>
64 #ifdef HAVE_SYS_PARAM_H
65 #include <sys/param.h> /* FreeBSD needs this to know what version it is */
76 #ifdef HAVE_SYS_UTIME_H
77 #include <sys/utime.h>
79 #ifdef HAVE_SYS_MMAN_H
82 #ifdef HAVE_SYS_SYSLIMITS_H
83 #include <sys/syslimits.h>
85 #ifdef HAVE_SYS_FILE_H
88 #if defined(HAVE_SYS_PRCTL_H) && defined(__linux__)
89 /* Only use the linux prctl; the IRIX prctl is totally different */
90 #include <sys/prctl.h>
95 #include "container.h"
98 /* Inline the strl functions if the platform doesn't have them. */
106 #ifdef HAVE_SYS_MMAN_H
107 /** Try to create a memory mapping for <b>filename</b> and return it. On
108 * failure, return NULL. Sets errno properly, using ERANGE to mean
111 tor_mmap_file(const char *filename
)
113 int fd
; /* router file */
117 size_t size
, filesize
;
119 tor_assert(filename
);
121 fd
= open(filename
, O_RDONLY
, 0);
123 int save_errno
= errno
;
124 int severity
= (errno
== ENOENT
) ? LOG_INFO
: LOG_WARN
;
125 log_fn(severity
, LD_FS
,"Could not open \"%s\" for mmap(): %s",filename
,
131 size
= filesize
= (size_t) lseek(fd
, 0, SEEK_END
);
132 lseek(fd
, 0, SEEK_SET
);
133 /* ensure page alignment */
134 page_size
= getpagesize();
135 size
+= (size
%page_size
) ? page_size
-(size
%page_size
) : 0;
138 /* Zero-length file. If we call mmap on it, it will succeed but
139 * return NULL, and bad things will happen. So just fail. */
140 log_info(LD_FS
,"File \"%s\" is empty. Ignoring.",filename
);
146 string
= mmap(0, size
, PROT_READ
, MAP_PRIVATE
, fd
, 0);
148 if (string
== MAP_FAILED
) {
149 int save_errno
= errno
;
150 log_warn(LD_FS
,"Could not mmap file \"%s\": %s", filename
,
156 res
= tor_malloc_zero(sizeof(tor_mmap_t
));
158 res
->size
= filesize
;
159 res
->mapping_size
= size
;
163 /** Release storage held for a memory mapping. */
165 tor_munmap_file(tor_mmap_t
*handle
)
167 munmap((char*)handle
->data
, handle
->mapping_size
);
170 #elif defined(MS_WINDOWS)
172 tor_mmap_file(const char *filename
)
174 WCHAR wfilename
[MAX_PATH
]= {0};
175 tor_mmap_t
*res
= tor_malloc_zero(sizeof(tor_mmap_t
));
177 res
->file_handle
= INVALID_HANDLE_VALUE
;
178 res
->mmap_handle
= NULL
;
179 mbstowcs(wfilename
,filename
,MAX_PATH
);
180 res
->file_handle
= CreateFileW(wfilename
,
181 GENERIC_READ
, FILE_SHARE_READ
,
184 FILE_ATTRIBUTE_NORMAL
,
187 if (res
->file_handle
== INVALID_HANDLE_VALUE
)
190 res
->size
= GetFileSize(res
->file_handle
, NULL
);
192 if (res
->size
== 0) {
193 log_info(LD_FS
,"File \"%s\" is empty. Ignoring.",filename
);
198 res
->mmap_handle
= CreateFileMapping(res
->file_handle
,
201 #if SIZEOF_SIZE_T > 4
202 (res
->base
.size
>> 32),
206 (res
->size
& 0xfffffffful
),
208 if (res
->mmap_handle
== NULL
)
210 res
->data
= (char*) MapViewOfFile(res
->mmap_handle
,
218 DWORD e
= GetLastError();
219 int severity
= (e
== ERROR_FILE_NOT_FOUND
|| e
== ERROR_PATH_NOT_FOUND
) ?
221 char *msg
= format_win32_error(e
);
222 log_fn(severity
, LD_FS
, "Couldn't mmap file \"%s\": %s", filename
, msg
);
224 if (e
== ERROR_FILE_NOT_FOUND
|| e
== ERROR_PATH_NOT_FOUND
)
232 tor_munmap_file(res
);
236 tor_munmap_file(tor_mmap_t
*handle
)
239 /* This is an ugly cast, but without it, "data" in struct tor_mmap_t would
240 have to be redefined as non-const. */
241 UnmapViewOfFile( (LPVOID
) handle
->data
);
243 if (handle
->mmap_handle
!= NULL
)
244 CloseHandle(handle
->mmap_handle
);
245 if (handle
->file_handle
!= INVALID_HANDLE_VALUE
)
246 CloseHandle(handle
->file_handle
);
251 tor_mmap_file(const char *filename
)
254 char *res
= read_file_to_str(filename
, RFTS_BIN
|RFTS_IGNORE_MISSING
, &st
);
258 handle
= tor_malloc_zero(sizeof(tor_mmap_t
));
260 handle
->size
= st
.st_size
;
264 tor_munmap_file(tor_mmap_t
*handle
)
266 char *d
= (char*)handle
->data
;
268 memset(handle
, 0, sizeof(tor_mmap_t
));
273 /** Replacement for snprintf. Differs from platform snprintf in two
274 * ways: First, always NUL-terminates its output. Second, always
275 * returns -1 if the result is truncated. (Note that this return
276 * behavior does <i>not</i> conform to C99; it just happens to be
277 * easier to emulate "return -1" with conformant implementations than
278 * it is to emulate "return number that would be written" with
279 * non-conformant implementations.) */
281 tor_snprintf(char *str
, size_t size
, const char *format
, ...)
286 r
= tor_vsnprintf(str
,size
,format
,ap
);
291 /** Replacement for vsnprintf; behavior differs as tor_snprintf differs from
295 tor_vsnprintf(char *str
, size_t size
, const char *format
, va_list args
)
299 return -1; /* no place for the NUL */
300 if (size
> SSIZE_T_MAX
-16)
303 r
= _vsnprintf(str
, size
, format
, args
);
305 r
= vsnprintf(str
, size
, format
, args
);
308 if (r
< 0 || r
>= (ssize_t
)size
)
314 * Portable asprintf implementation. Does a printf() into a newly malloc'd
315 * string. Sets *<b>strp</b> to this string, and returns its length (not
316 * including the terminating NUL character).
318 * You can treat this function as if its implementation were something like
320 char buf[_INFINITY_];
321 tor_snprintf(buf, sizeof(buf), fmt, args);
322 *strp = tor_strdup(buf);
323 return strlen(*strp):
325 * Where _INFINITY_ is an imaginary constant so big that any string can fit
329 tor_asprintf(char **strp
, const char *fmt
, ...)
334 r
= tor_vasprintf(strp
, fmt
, args
);
336 if (!*strp
|| r
< 0) {
337 log_err(LD_BUG
, "Internal error in asprintf");
344 * Portable vasprintf implementation. Does a printf() into a newly malloc'd
345 * string. Differs from regular vasprintf in the same ways that
346 * tor_asprintf() differs from regular asprintf.
349 tor_vasprintf(char **strp
, const char *fmt
, va_list args
)
351 /* use a temporary variable in case *strp is in args. */
353 #ifdef HAVE_VASPRINTF
354 /* If the platform gives us one, use it. */
355 int r
= vasprintf(&strp_tmp
, fmt
, args
);
361 #elif defined(_MSC_VER)
362 /* On Windows, _vsnprintf won't tell us the length of the string if it
363 * overflows, so we need to use _vcsprintf to tell how much to allocate */
366 len
= _vscprintf(fmt
, args
);
371 strp_tmp
= tor_malloc(len
+ 1);
372 r
= _vsnprintf(strp_tmp
, len
+1, fmt
, args
);
381 /* Everywhere else, we have a decent vsnprintf that tells us how many
382 * characters we need. We give it a try on a short buffer first, since
383 * it might be nice to avoid the second vsnprintf call.
388 va_copy(tmp_args
, args
);
389 len
= vsnprintf(buf
, sizeof(buf
), fmt
, tmp_args
);
391 if (len
< (int)sizeof(buf
)) {
392 *strp
= tor_strdup(buf
);
395 strp_tmp
= tor_malloc(len
+1);
396 r
= vsnprintf(strp_tmp
, len
+1, fmt
, args
);
407 /** Given <b>hlen</b> bytes at <b>haystack</b> and <b>nlen</b> bytes at
408 * <b>needle</b>, return a pointer to the first occurrence of the needle
409 * within the haystack, or NULL if there is no such occurrence.
411 * Requires that nlen be greater than zero.
414 tor_memmem(const void *_haystack
, size_t hlen
,
415 const void *_needle
, size_t nlen
)
417 #if defined(HAVE_MEMMEM) && (!defined(__GNUC__) || __GNUC__ >= 2)
419 return memmem(_haystack
, hlen
, _needle
, nlen
);
421 /* This isn't as fast as the GLIBC implementation, but it doesn't need to
424 const char *haystack
= (const char*)_haystack
;
425 const char *needle
= (const char*)_needle
;
430 end
= haystack
+ hlen
;
431 first
= *(const char*)needle
;
432 while ((p
= memchr(p
, first
, end
-p
))) {
435 if (!memcmp(p
, needle
, nlen
))
443 /* Tables to implement ctypes-replacement TOR_IS*() functions. Each table
444 * has 256 bits to look up whether a character is in some set or not. This
445 * fails on non-ASCII platforms, but it is hard to find a platform whose
446 * character set is not a superset of ASCII nowadays. */
447 const uint32_t TOR_ISALPHA_TABLE
[8] =
448 { 0, 0, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
449 const uint32_t TOR_ISALNUM_TABLE
[8] =
450 { 0, 0x3ff0000, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
451 const uint32_t TOR_ISSPACE_TABLE
[8] = { 0x3e00, 0x1, 0, 0, 0, 0, 0, 0 };
452 const uint32_t TOR_ISXDIGIT_TABLE
[8] =
453 { 0, 0x3ff0000, 0x7e, 0x7e, 0, 0, 0, 0 };
454 const uint32_t TOR_ISDIGIT_TABLE
[8] = { 0, 0x3ff0000, 0, 0, 0, 0, 0, 0 };
455 const uint32_t TOR_ISPRINT_TABLE
[8] =
456 { 0, 0xffffffff, 0xffffffff, 0x7fffffff, 0, 0, 0, 0x0 };
457 const uint32_t TOR_ISUPPER_TABLE
[8] = { 0, 0, 0x7fffffe, 0, 0, 0, 0, 0 };
458 const uint32_t TOR_ISLOWER_TABLE
[8] = { 0, 0, 0, 0x7fffffe, 0, 0, 0, 0 };
459 /* Upper-casing and lowercasing tables to map characters to upper/lowercase
461 const char TOR_TOUPPER_TABLE
[256] = {
462 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
463 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
464 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
465 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
466 64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
467 80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
468 96,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
469 80,81,82,83,84,85,86,87,88,89,90,123,124,125,126,127,
470 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
471 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
472 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
473 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
474 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
475 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
476 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
477 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
479 const char TOR_TOLOWER_TABLE
[256] = {
480 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
481 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
482 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
483 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
484 64,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
485 112,113,114,115,116,117,118,119,120,121,122,91,92,93,94,95,
486 96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
487 112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
488 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
489 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
490 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
491 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
492 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
493 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
494 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
495 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
498 /** Implementation of strtok_r for platforms whose coders haven't figured out
499 * how to write one. Hey guys! You can use this code here for free! */
501 tor_strtok_r_impl(char *str
, const char *sep
, char **lasts
)
505 start
= cp
= *lasts
= str
;
513 while (*cp
&& !strchr(sep
, *cp
))
516 tor_assert(strlen(sep
) == 1);
517 cp
= strchr(cp
, *sep
);
530 /** Take a filename and return a pointer to its final element. This
531 * function is called on __FILE__ to fix a MSVC nit where __FILE__
532 * contains the full path to the file. This is bad, because it
533 * confuses users to find the home directory of the person who
534 * compiled the binary in their warning messages.
537 tor_fix_source_file(const char *fname
)
539 const char *cp1
, *cp2
, *r
;
540 cp1
= strrchr(fname
, '/');
541 cp2
= strrchr(fname
, '\\');
543 r
= (cp1
<cp2
)?(cp2
+1):(cp1
+1);
556 * Read a 16-bit value beginning at <b>cp</b>. Equivalent to
557 * *(uint16_t*)(cp), but will not cause segfaults on platforms that forbid
558 * unaligned memory access.
561 get_uint16(const char *cp
)
568 * Read a 32-bit value beginning at <b>cp</b>. Equivalent to
569 * *(uint32_t*)(cp), but will not cause segfaults on platforms that forbid
570 * unaligned memory access.
573 get_uint32(const char *cp
)
580 * Read a 64-bit value beginning at <b>cp</b>. Equivalent to
581 * *(uint64_t*)(cp), but will not cause segfaults on platforms that forbid
582 * unaligned memory access.
585 get_uint64(const char *cp
)
593 * Set a 16-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
594 * *(uint16_t*)(cp) = v, but will not cause segfaults on platforms that forbid
595 * unaligned memory access. */
597 set_uint16(char *cp
, uint16_t v
)
602 * Set a 32-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
603 * *(uint32_t*)(cp) = v, but will not cause segfaults on platforms that forbid
604 * unaligned memory access. */
606 set_uint32(char *cp
, uint32_t v
)
611 * Set a 64-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
612 * *(uint64_t*)(cp) = v, but will not cause segfaults on platforms that forbid
613 * unaligned memory access. */
615 set_uint64(char *cp
, uint64_t v
)
621 * Rename the file <b>from</b> to the file <b>to</b>. On Unix, this is
622 * the same as rename(2). On windows, this removes <b>to</b> first if
624 * Returns 0 on success. Returns -1 and sets errno on failure.
627 replace_file(const char *from
, const char *to
)
630 return rename(from
,to
);
632 switch (file_status(to
))
637 if (unlink(to
)) return -1;
645 return rename(from
,to
);
649 /** Change <b>fname</b>'s modification time to now. */
651 touch_file(const char *fname
)
653 if (utime(fname
, NULL
)!=0)
658 /** Represents a lockfile on which we hold the lock. */
659 struct tor_lockfile_t
{
664 /** Try to get a lock on the lockfile <b>filename</b>, creating it as
665 * necessary. If someone else has the lock and <b>blocking</b> is true,
666 * wait until the lock is available. Otherwise return immediately whether
667 * we succeeded or not.
669 * Set *<b>locked_out</b> to true if somebody else had the lock, and to false
672 * Return a <b>tor_lockfile_t</b> on success, NULL on failure.
674 * (Implementation note: because we need to fall back to fcntl on some
675 * platforms, these locks are per-process, not per-thread. If you want
676 * to do in-process locking, use tor_mutex_t like a normal person.)
679 tor_lockfile_lock(const char *filename
, int blocking
, int *locked_out
)
681 tor_lockfile_t
*result
;
685 log_info(LD_FS
, "Locking \"%s\"", filename
);
686 fd
= open(filename
, O_RDWR
|O_CREAT
|O_TRUNC
, 0600);
688 log_warn(LD_FS
,"Couldn't open \"%s\" for locking: %s", filename
,
694 _lseek(fd
, 0, SEEK_SET
);
695 if (_locking(fd
, blocking
? _LK_LOCK
: _LK_NBLCK
, 1) < 0) {
696 if (errno
!= EDEADLOCK
)
697 log_warn(LD_FS
,"Couldn't lock \"%s\": %s", filename
, strerror(errno
));
703 #elif defined(HAVE_FLOCK)
704 if (flock(fd
, LOCK_EX
|(blocking
? 0 : LOCK_NB
)) < 0) {
705 if (errno
!= EWOULDBLOCK
)
706 log_warn(LD_FS
,"Couldn't lock \"%s\": %s", filename
, strerror(errno
));
715 memset(&lock
, 0, sizeof(lock
));
716 lock
.l_type
= F_WRLCK
;
717 lock
.l_whence
= SEEK_SET
;
718 if (fcntl(fd
, blocking
? F_SETLKW
: F_SETLK
, &lock
) < 0) {
719 if (errno
!= EACCES
&& errno
!= EAGAIN
)
720 log_warn(LD_FS
, "Couldn't lock \"%s\": %s", filename
, strerror(errno
));
729 result
= tor_malloc(sizeof(tor_lockfile_t
));
730 result
->filename
= tor_strdup(filename
);
735 /** Release the lock held as <b>lockfile</b>. */
737 tor_lockfile_unlock(tor_lockfile_t
*lockfile
)
739 tor_assert(lockfile
);
741 log_info(LD_FS
, "Unlocking \"%s\"", lockfile
->filename
);
743 _lseek(lockfile
->fd
, 0, SEEK_SET
);
744 if (_locking(lockfile
->fd
, _LK_UNLCK
, 1) < 0) {
745 log_warn(LD_FS
,"Error unlocking \"%s\": %s", lockfile
->filename
,
748 #elif defined(HAVE_FLOCK)
749 if (flock(lockfile
->fd
, LOCK_UN
) < 0) {
750 log_warn(LD_FS
, "Error unlocking \"%s\": %s", lockfile
->filename
,
754 /* Closing the lockfile is sufficient. */
759 tor_free(lockfile
->filename
);
763 /* Some old versions of Unix didn't define constants for these values,
764 * and instead expect you to say 0, 1, or 2. */
772 /** Return the position of <b>fd</b> with respect to the start of the file. */
774 tor_fd_getpos(int fd
)
777 return (off_t
) _lseek(fd
, 0, SEEK_CUR
);
779 return (off_t
) lseek(fd
, 0, SEEK_CUR
);
783 /** Move <b>fd</b> to the end of the file. Return -1 on error, 0 on success. */
785 tor_fd_seekend(int fd
)
788 return _lseek(fd
, 0, SEEK_END
) < 0 ? -1 : 0;
790 return lseek(fd
, 0, SEEK_END
) < 0 ? -1 : 0;
794 #undef DEBUG_SOCKET_COUNTING
795 #ifdef DEBUG_SOCKET_COUNTING
796 /** A bitarray of all fds that should be passed to tor_socket_close(). Only
797 * used if DEBUG_SOCKET_COUNTING is defined. */
798 static bitarray_t
*open_sockets
= NULL
;
799 /** The size of <b>open_sockets</b>, in bits. */
800 static int max_socket
= -1;
803 /** Count of number of sockets currently open. (Undercounts sockets opened by
804 * eventdns and libevent.) */
805 static int n_sockets_open
= 0;
807 /** Mutex to protect open_sockets, max_socket, and n_sockets_open. */
808 static tor_mutex_t
*socket_accounting_mutex
= NULL
;
811 socket_accounting_lock(void)
813 if (PREDICT_UNLIKELY(!socket_accounting_mutex
))
814 socket_accounting_mutex
= tor_mutex_new();
815 tor_mutex_acquire(socket_accounting_mutex
);
819 socket_accounting_unlock(void)
821 tor_mutex_release(socket_accounting_mutex
);
824 /** As close(), but guaranteed to work for sockets across platforms (including
825 * Windows, where close()ing a socket doesn't work. Returns 0 on success, -1
828 tor_close_socket(int s
)
832 /* On Windows, you have to call close() on fds returned by open(),
833 * and closesocket() on fds returned by socket(). On Unix, everything
834 * gets close()'d. We abstract this difference by always using
835 * tor_close_socket to close sockets, and always using close() on
838 #if defined(MS_WINDOWS)
844 socket_accounting_lock();
845 #ifdef DEBUG_SOCKET_COUNTING
846 if (s
> max_socket
|| ! bitarray_is_set(open_sockets
, s
)) {
847 log_warn(LD_BUG
, "Closing a socket (%d) that wasn't returned by tor_open_"
848 "socket(), or that was already closed or something.", s
);
850 tor_assert(open_sockets
&& s
<= max_socket
);
851 bitarray_clear(open_sockets
, s
);
857 int err
= tor_socket_errno(-1);
858 log_info(LD_NET
, "Close returned an error: %s", tor_socket_strerror(err
));
860 if (err
!= WSAENOTSOCK
)
869 if (n_sockets_open
< 0)
870 log_warn(LD_BUG
, "Our socket count is below zero: %d. Please submit a "
871 "bug report.", n_sockets_open
);
872 socket_accounting_unlock();
876 #ifdef DEBUG_SOCKET_COUNTING
877 /** Helper: if DEBUG_SOCKET_COUNTING is enabled, remember that <b>s</b> is
878 * now an open socket. */
880 mark_socket_open(int s
)
882 if (s
> max_socket
) {
883 if (max_socket
== -1) {
884 open_sockets
= bitarray_init_zero(s
+128);
887 open_sockets
= bitarray_expand(open_sockets
, max_socket
, s
+128);
891 if (bitarray_is_set(open_sockets
, s
)) {
892 log_warn(LD_BUG
, "I thought that %d was already open, but socket() just "
893 "gave it to me!", s
);
895 bitarray_set(open_sockets
, s
);
898 #define mark_socket_open(s) STMT_NIL
901 /** As socket(), but counts the number of open sockets. */
903 tor_open_socket(int domain
, int type
, int protocol
)
905 int s
= socket(domain
, type
, protocol
);
907 socket_accounting_lock();
910 socket_accounting_unlock();
915 /** As socket(), but counts the number of open sockets. */
917 tor_accept_socket(int sockfd
, struct sockaddr
*addr
, socklen_t
*len
)
919 int s
= accept(sockfd
, addr
, len
);
921 socket_accounting_lock();
924 socket_accounting_unlock();
929 /** Return the number of sockets we currently have opened. */
931 get_n_open_sockets(void)
934 socket_accounting_lock();
936 socket_accounting_unlock();
940 /** Turn <b>socket</b> into a nonblocking socket.
943 set_socket_nonblocking(int socket
)
945 #if defined(MS_WINDOWS)
946 unsigned long nonblocking
= 1;
947 ioctlsocket(socket
, FIONBIO
, (unsigned long*) &nonblocking
);
949 fcntl(socket
, F_SETFL
, O_NONBLOCK
);
954 * Allocate a pair of connected sockets. (Like socketpair(family,
955 * type,protocol,fd), but works on systems that don't have
958 * Currently, only (AF_UNIX, SOCK_STREAM, 0) sockets are supported.
960 * Note that on systems without socketpair, this call will fail if
961 * localhost is inaccessible (for example, if the networking
962 * stack is down). And even if it succeeds, the socket pair will not
963 * be able to read while localhost is down later (the socket pair may
964 * even close, depending on OS-specific timeouts).
966 * Returns 0 on success and -errno on failure; do not rely on the value
967 * of errno or WSAGetLastError().
969 /* It would be nicer just to set errno, but that won't work for windows. */
971 tor_socketpair(int family
, int type
, int protocol
, int fd
[2])
973 //don't use win32 socketpairs (they are always bad)
974 #if defined(HAVE_SOCKETPAIR) && !defined(MS_WINDOWS)
976 r
= socketpair(family
, type
, protocol
, fd
);
978 socket_accounting_lock();
981 mark_socket_open(fd
[0]);
985 mark_socket_open(fd
[1]);
987 socket_accounting_unlock();
989 return r
< 0 ? -errno
: r
;
991 /* This socketpair does not work when localhost is down. So
992 * it's really not the same thing at all. But it's close enough
993 * for now, and really, when localhost is down sometimes, we
994 * have other problems too.
999 struct sockaddr_in listen_addr
;
1000 struct sockaddr_in connect_addr
;
1002 int saved_errno
= -1;
1006 || family
!= AF_UNIX
1010 return -WSAEAFNOSUPPORT
;
1012 return -EAFNOSUPPORT
;
1019 listener
= tor_open_socket(AF_INET
, type
, 0);
1021 return -tor_socket_errno(-1);
1022 memset(&listen_addr
, 0, sizeof(listen_addr
));
1023 listen_addr
.sin_family
= AF_INET
;
1024 listen_addr
.sin_addr
.s_addr
= htonl(INADDR_LOOPBACK
);
1025 listen_addr
.sin_port
= 0; /* kernel chooses port. */
1026 if (bind(listener
, (struct sockaddr
*) &listen_addr
, sizeof (listen_addr
))
1028 goto tidy_up_and_fail
;
1029 if (listen(listener
, 1) == -1)
1030 goto tidy_up_and_fail
;
1032 connector
= tor_open_socket(AF_INET
, type
, 0);
1034 goto tidy_up_and_fail
;
1035 /* We want to find out the port number to connect to. */
1036 size
= sizeof(connect_addr
);
1037 if (getsockname(listener
, (struct sockaddr
*) &connect_addr
, &size
) == -1)
1038 goto tidy_up_and_fail
;
1039 if (size
!= sizeof (connect_addr
))
1040 goto abort_tidy_up_and_fail
;
1041 if (connect(connector
, (struct sockaddr
*) &connect_addr
,
1042 sizeof(connect_addr
)) == -1)
1043 goto tidy_up_and_fail
;
1045 size
= sizeof(listen_addr
);
1046 acceptor
= tor_accept_socket(listener
,
1047 (struct sockaddr
*) &listen_addr
, &size
);
1049 goto tidy_up_and_fail
;
1050 if (size
!= sizeof(listen_addr
))
1051 goto abort_tidy_up_and_fail
;
1052 tor_close_socket(listener
);
1053 /* Now check we are talking to ourself by matching port and host on the
1055 if (getsockname(connector
, (struct sockaddr
*) &connect_addr
, &size
) == -1)
1056 goto tidy_up_and_fail
;
1057 if (size
!= sizeof (connect_addr
)
1058 || listen_addr
.sin_family
!= connect_addr
.sin_family
1059 || listen_addr
.sin_addr
.s_addr
!= connect_addr
.sin_addr
.s_addr
1060 || listen_addr
.sin_port
!= connect_addr
.sin_port
) {
1061 goto abort_tidy_up_and_fail
;
1068 abort_tidy_up_and_fail
:
1070 saved_errno
= WSAECONNABORTED
;
1072 saved_errno
= ECONNABORTED
; /* I hope this is portable and appropriate. */
1075 if (saved_errno
< 0)
1076 saved_errno
= errno
;
1078 tor_close_socket(listener
);
1079 if (connector
!= -1)
1080 tor_close_socket(connector
);
1082 tor_close_socket(acceptor
);
1083 return -saved_errno
;
1087 #define ULIMIT_BUFFER 32 /* keep 32 extra fd's beyond _ConnLimit */
1089 /** Learn the maximum allowed number of file descriptors. (Some systems
1090 * have a low soft limit.
1092 * We compute this by finding the largest number that we can use.
1093 * If we can't find a number greater than or equal to <b>limit</b>,
1094 * then we fail: return -1.
1096 * Otherwise, return 0 and store the maximum we found inside <b>max_out</b>.*/
1098 set_max_file_descriptors(rlim_t limit
, int *max_out
)
1100 /* Define some maximum connections values for systems where we cannot
1101 * automatically determine a limit. Re Cygwin, see
1102 * http://archives.seul.org/or/talk/Aug-2006/msg00210.html
1103 * For an iPhone, 9999 should work. For Windows and all other unknown
1104 * systems we use 15000 as the default. */
1105 #ifndef HAVE_GETRLIMIT
1106 #if defined(CYGWIN) || defined(__CYGWIN__)
1107 const char *platform
= "Cygwin";
1108 const unsigned long MAX_CONNECTIONS
= 3200;
1109 #elif defined(MS_WINDOWS)
1110 const char *platform
= "Windows";
1111 const unsigned long MAX_CONNECTIONS
= 15000;
1113 const char *platform
= "unknown platforms with no getrlimit()";
1114 const unsigned long MAX_CONNECTIONS
= 15000;
1116 log_fn(LOG_INFO
, LD_NET
,
1117 "This platform is missing getrlimit(). Proceeding.");
1118 if (limit
> MAX_CONNECTIONS
) {
1120 "We do not support more than %lu file descriptors "
1121 "on %s. Tried to raise to %lu.",
1122 (unsigned long)MAX_CONNECTIONS
, platform
, (unsigned long)limit
);
1125 limit
= MAX_CONNECTIONS
;
1126 #else /* HAVE_GETRLIMIT */
1128 tor_assert(limit
> 0);
1130 if (getrlimit(RLIMIT_NOFILE
, &rlim
) != 0) {
1131 log_warn(LD_NET
, "Could not get maximum number of file descriptors: %s",
1136 if (rlim
.rlim_max
< limit
) {
1137 log_warn(LD_CONFIG
,"We need %lu file descriptors available, and we're "
1138 "limited to %lu. Please change your ulimit -n.",
1139 (unsigned long)limit
, (unsigned long)rlim
.rlim_max
);
1143 if (rlim
.rlim_max
> rlim
.rlim_cur
) {
1144 log_info(LD_NET
,"Raising max file descriptors from %lu to %lu.",
1145 (unsigned long)rlim
.rlim_cur
, (unsigned long)rlim
.rlim_max
);
1147 rlim
.rlim_cur
= rlim
.rlim_max
;
1149 if (setrlimit(RLIMIT_NOFILE
, &rlim
) != 0) {
1152 if (errno
== EINVAL
&& OPEN_MAX
< rlim
.rlim_cur
) {
1153 /* On some platforms, OPEN_MAX is the real limit, and getrlimit() is
1154 * full of nasty lies. I'm looking at you, OSX 10.5.... */
1155 rlim
.rlim_cur
= OPEN_MAX
;
1156 if (setrlimit(RLIMIT_NOFILE
, &rlim
) == 0) {
1157 if (rlim
.rlim_cur
< (rlim_t
)limit
) {
1158 log_warn(LD_CONFIG
, "We are limited to %lu file descriptors by "
1159 "OPEN_MAX, and ConnLimit is %lu. Changing ConnLimit; sorry.",
1160 (unsigned long)OPEN_MAX
, (unsigned long)limit
);
1162 log_info(LD_CONFIG
, "Dropped connection limit to OPEN_MAX (%lu); "
1163 "Apparently, %lu was too high and rlimit lied to us.",
1164 (unsigned long)OPEN_MAX
, (unsigned long)rlim
.rlim_max
);
1169 #endif /* OPEN_MAX */
1171 log_warn(LD_CONFIG
,"Couldn't set maximum number of file descriptors: %s",
1176 /* leave some overhead for logs, etc, */
1177 limit
= rlim
.rlim_cur
;
1178 #endif /* HAVE_GETRLIMIT */
1180 if (limit
< ULIMIT_BUFFER
) {
1182 "ConnLimit must be at least %d. Failing.", ULIMIT_BUFFER
);
1185 if (limit
> INT_MAX
)
1187 tor_assert(max_out
);
1188 *max_out
= (int)limit
- ULIMIT_BUFFER
;
1193 /** Log details of current user and group credentials. Return 0 on
1194 * success. Logs and return -1 on failure.
1197 log_credential_status(void)
1199 #define CREDENTIAL_LOG_LEVEL LOG_INFO
1200 /* Real, effective and saved UIDs */
1201 uid_t ruid
, euid
, suid
;
1202 /* Read, effective and saved GIDs */
1203 gid_t rgid
, egid
, sgid
;
1204 /* Supplementary groups */
1205 gid_t sup_gids
[NGROUPS_MAX
+ 1];
1206 /* Number of supplementary groups */
1210 #ifdef HAVE_GETRESUID
1211 if (getresuid(&ruid
, &euid
, &suid
) != 0 ) {
1212 log_warn(LD_GENERAL
, "Error getting changed UIDs: %s", strerror(errno
));
1215 log_fn(CREDENTIAL_LOG_LEVEL
, LD_GENERAL
,
1216 "UID is %u (real), %u (effective), %u (saved)",
1217 (unsigned)ruid
, (unsigned)euid
, (unsigned)suid
);
1220 /* getresuid is not present on MacOS X, so we can't get the saved (E)UID */
1225 log_fn(CREDENTIAL_LOG_LEVEL
, LD_GENERAL
,
1226 "UID is %u (real), %u (effective), unknown (saved)",
1227 (unsigned)ruid
, (unsigned)euid
);
1231 #ifdef HAVE_GETRESGID
1232 if (getresgid(&rgid
, &egid
, &sgid
) != 0 ) {
1233 log_warn(LD_GENERAL
, "Error getting changed GIDs: %s", strerror(errno
));
1236 log_fn(CREDENTIAL_LOG_LEVEL
, LD_GENERAL
,
1237 "GID is %u (real), %u (effective), %u (saved)",
1238 (unsigned)rgid
, (unsigned)egid
, (unsigned)sgid
);
1241 /* getresgid is not present on MacOS X, so we can't get the saved (E)GID */
1245 log_fn(CREDENTIAL_LOG_LEVEL
, LD_GENERAL
,
1246 "GID is %u (real), %u (effective), unknown (saved)",
1247 (unsigned)rgid
, (unsigned)egid
);
1250 /* log supplementary groups */
1251 if ((ngids
= getgroups(NGROUPS_MAX
+ 1, sup_gids
)) < 0) {
1252 log_warn(LD_GENERAL
, "Error getting supplementary GIDs: %s",
1259 smartlist_t
*elts
= smartlist_create();
1261 for (i
= 0; i
<ngids
; i
++) {
1262 strgid
= tor_malloc(11);
1263 if (tor_snprintf(strgid
, 11, "%u", (unsigned)sup_gids
[i
]) < 0) {
1264 log_warn(LD_GENERAL
, "Error printing supplementary GIDs");
1269 smartlist_add(elts
, strgid
);
1272 s
= smartlist_join_strings(elts
, " ", 0, NULL
);
1274 log_fn(CREDENTIAL_LOG_LEVEL
, LD_GENERAL
, "Supplementary groups are: %s",s
);
1278 SMARTLIST_FOREACH(elts
, char *, cp
,
1282 smartlist_free(elts
);
1291 /** Call setuid and setgid to run as <b>user</b> and switch to their
1292 * primary group. Return 0 on success. On failure, log and return -1.
1295 switch_id(const char *user
)
1298 struct passwd
*pw
= NULL
;
1301 static int have_already_switched_id
= 0;
1305 if (have_already_switched_id
)
1308 /* Log the initial credential state */
1309 if (log_credential_status())
1312 log_fn(CREDENTIAL_LOG_LEVEL
, LD_GENERAL
, "Changing user and groups");
1314 /* Get old UID/GID to check if we changed correctly */
1318 /* Lookup the user and group information, if we have a problem, bail out. */
1319 pw
= getpwnam(user
);
1321 log_warn(LD_CONFIG
, "Error setting configured user: %s not found", user
);
1325 /* Properly switch egid,gid,euid,uid here or bail out */
1326 if (setgroups(1, &pw
->pw_gid
)) {
1327 log_warn(LD_GENERAL
, "Error setting groups to gid %d: \"%s\".",
1328 (int)pw
->pw_gid
, strerror(errno
));
1329 if (old_uid
== pw
->pw_uid
) {
1330 log_warn(LD_GENERAL
, "Tor is already running as %s. You do not need "
1331 "the \"User\" option if you are already running as the user "
1332 "you want to be. (If you did not set the User option in your "
1333 "torrc, check whether it was specified on the command line "
1334 "by a startup script.)", user
);
1336 log_warn(LD_GENERAL
, "If you set the \"User\" option, you must start Tor"
1342 if (setegid(pw
->pw_gid
)) {
1343 log_warn(LD_GENERAL
, "Error setting egid to %d: %s",
1344 (int)pw
->pw_gid
, strerror(errno
));
1348 if (setgid(pw
->pw_gid
)) {
1349 log_warn(LD_GENERAL
, "Error setting gid to %d: %s",
1350 (int)pw
->pw_gid
, strerror(errno
));
1354 if (setuid(pw
->pw_uid
)) {
1355 log_warn(LD_GENERAL
, "Error setting configured uid to %s (%d): %s",
1356 user
, (int)pw
->pw_uid
, strerror(errno
));
1360 if (seteuid(pw
->pw_uid
)) {
1361 log_warn(LD_GENERAL
, "Error setting configured euid to %s (%d): %s",
1362 user
, (int)pw
->pw_uid
, strerror(errno
));
1366 /* This is how OpenBSD rolls:
1367 if (setgroups(1, &pw->pw_gid) || setegid(pw->pw_gid) ||
1368 setgid(pw->pw_gid) || setuid(pw->pw_uid) || seteuid(pw->pw_uid)) {
1369 setgid(pw->pw_gid) || seteuid(pw->pw_uid) || setuid(pw->pw_uid)) {
1370 log_warn(LD_GENERAL, "Error setting configured UID/GID: %s",
1376 /* We've properly switched egid, gid, euid, uid, and supplementary groups if
1379 #if !defined(CYGWIN) && !defined(__CYGWIN__)
1380 /* If we tried to drop privilege to a group/user other than root, attempt to
1381 * restore root (E)(U|G)ID, and abort if the operation succeeds */
1383 /* Only check for privilege dropping if we were asked to be non-root */
1385 /* Try changing GID/EGID */
1386 if (pw
->pw_gid
!= old_gid
&&
1387 (setgid(old_gid
) != -1 || setegid(old_gid
) != -1)) {
1388 log_warn(LD_GENERAL
, "Was able to restore group credentials even after "
1389 "switching GID: this means that the setgid code didn't work.");
1393 /* Try changing UID/EUID */
1394 if (pw
->pw_uid
!= old_uid
&&
1395 (setuid(old_uid
) != -1 || seteuid(old_uid
) != -1)) {
1396 log_warn(LD_GENERAL
, "Was able to restore user credentials even after "
1397 "switching UID: this means that the setuid code didn't work.");
1403 /* Check what really happened */
1404 if (log_credential_status()) {
1408 have_already_switched_id
= 1; /* mark success so we never try again */
1410 #if defined(__linux__) && defined(HAVE_SYS_PRCTL_H) && defined(HAVE_PRCTL)
1411 #ifdef PR_SET_DUMPABLE
1413 /* Re-enable core dumps if we're not running as root. */
1414 log_info(LD_CONFIG
, "Re-enabling coredumps");
1415 if (prctl(PR_SET_DUMPABLE
, 1)) {
1416 log_warn(LD_CONFIG
, "Unable to re-enable coredumps: %s",strerror(errno
));
1427 "User specified but switching users is unsupported on your OS.");
1433 /** Allocate and return a string containing the home directory for the
1434 * user <b>username</b>. Only works on posix-like systems. */
1436 get_user_homedir(const char *username
)
1439 tor_assert(username
);
1441 if (!(pw
= getpwnam(username
))) {
1442 log_err(LD_CONFIG
,"User \"%s\" not found.", username
);
1445 return tor_strdup(pw
->pw_dir
);
1449 /** Set *addr to the IP address (in dotted-quad notation) stored in c.
1450 * Return 1 on success, 0 if c is badly formatted. (Like inet_aton(c,addr),
1451 * but works on Windows and Solaris.)
1454 tor_inet_aton(const char *str
, struct in_addr
* addr
)
1458 if (tor_sscanf(str
, "%3u.%3u.%3u.%3u%c", &a
,&b
,&c
,&d
,&more
) != 4)
1460 if (a
> 255) return 0;
1461 if (b
> 255) return 0;
1462 if (c
> 255) return 0;
1463 if (d
> 255) return 0;
1464 addr
->s_addr
= htonl((a
<<24) | (b
<<16) | (c
<<8) | d
);
1468 /** Given <b>af</b>==AF_INET and <b>src</b> a struct in_addr, or
1469 * <b>af</b>==AF_INET6 and <b>src</b> a struct in6_addr, try to format the
1470 * address and store it in the <b>len</b>-byte buffer <b>dst</b>. Returns
1471 * <b>dst</b> on success, NULL on failure.
1473 * (Like inet_ntop(af,src,dst,len), but works on platforms that don't have it:
1474 * Tor sometimes needs to format ipv6 addresses even on platforms without ipv6
1477 tor_inet_ntop(int af
, const void *src
, char *dst
, size_t len
)
1479 if (af
== AF_INET
) {
1480 if (tor_inet_ntoa(src
, dst
, len
) < 0)
1484 } else if (af
== AF_INET6
) {
1485 const struct in6_addr
*addr
= src
;
1487 int longestGapLen
= 0, longestGapPos
= -1, i
,
1488 curGapPos
= -1, curGapLen
= 0;
1490 for (i
= 0; i
< 8; ++i
) {
1491 words
[i
] = (((uint16_t)addr
->s6_addr
[2*i
])<<8) + addr
->s6_addr
[2*i
+1];
1493 if (words
[0] == 0 && words
[1] == 0 && words
[2] == 0 && words
[3] == 0 &&
1494 words
[4] == 0 && ((words
[5] == 0 && words
[6] && words
[7]) ||
1495 (words
[5] == 0xffff))) {
1496 /* This is an IPv4 address. */
1497 if (words
[5] == 0) {
1498 tor_snprintf(buf
, sizeof(buf
), "::%d.%d.%d.%d",
1499 addr
->s6_addr
[12], addr
->s6_addr
[13],
1500 addr
->s6_addr
[14], addr
->s6_addr
[15]);
1502 tor_snprintf(buf
, sizeof(buf
), "::%x:%d.%d.%d.%d", words
[5],
1503 addr
->s6_addr
[12], addr
->s6_addr
[13],
1504 addr
->s6_addr
[14], addr
->s6_addr
[15]);
1506 if (strlen(buf
) > len
)
1508 strlcpy(dst
, buf
, len
);
1513 if (words
[i
] == 0) {
1516 while (i
<8 && words
[i
] == 0) {
1519 if (curGapLen
> longestGapLen
) {
1520 longestGapPos
= curGapPos
;
1521 longestGapLen
= curGapLen
;
1527 if (longestGapLen
<=1)
1531 for (i
= 0; i
< 8; ++i
) {
1532 if (words
[i
] == 0 && longestGapPos
== i
) {
1536 while (i
< 8 && words
[i
] == 0)
1538 --i
; /* to compensate for loop increment. */
1540 tor_snprintf(cp
, sizeof(buf
)-(cp
-buf
), "%x", (unsigned)words
[i
]);
1547 if (strlen(buf
) > len
)
1549 strlcpy(dst
, buf
, len
);
1556 /** Given <b>af</b>==AF_INET or <b>af</b>==AF_INET6, and a string <b>src</b>
1557 * encoding an IPv4 address or IPv6 address correspondingly, try to parse the
1558 * address and store the result in <b>dst</b> (which must have space for a
1559 * struct in_addr or a struct in6_addr, as appropriate). Return 1 on success,
1560 * 0 on a bad parse, and -1 on a bad <b>af</b>.
1562 * (Like inet_pton(af,src,dst) but works on platforms that don't have it: Tor
1563 * sometimes needs to format ipv6 addresses even on platforms without ipv6
1566 tor_inet_pton(int af
, const char *src
, void *dst
)
1568 if (af
== AF_INET
) {
1569 return tor_inet_aton(src
, dst
);
1570 } else if (af
== AF_INET6
) {
1571 struct in6_addr
*out
= dst
;
1573 int gapPos
= -1, i
, setWords
=0;
1574 const char *dot
= strchr(src
, '.');
1575 const char *eow
; /* end of words. */
1579 eow
= src
+strlen(src
);
1581 unsigned byte1
,byte2
,byte3
,byte4
;
1583 for (eow
= dot
-1; eow
>= src
&& TOR_ISDIGIT(*eow
); --eow
)
1587 /* We use "scanf" because some platform inet_aton()s are too lax
1588 * about IPv4 addresses of the form "1.2.3" */
1589 if (tor_sscanf(eow
, "%3u.%3u.%3u.%3u%c",
1590 &byte1
,&byte2
,&byte3
,&byte4
,&more
) != 4)
1593 if (byte1
> 255 || byte2
> 255 || byte3
> 255 || byte4
> 255)
1596 words
[6] = (byte1
<<8) | byte2
;
1597 words
[7] = (byte3
<<8) | byte4
;
1605 if (TOR_ISXDIGIT(*src
)) {
1607 long r
= strtol(src
, &next
, 16);
1615 words
[i
++] = (uint16_t)r
;
1618 if (*src
!= ':' && src
!= eow
)
1621 } else if (*src
== ':' && i
> 0 && gapPos
==-1) {
1624 } else if (*src
== ':' && i
== 0 && src
[1] == ':' && gapPos
==-1) {
1633 (setWords
== 8 && gapPos
!= -1) ||
1634 (setWords
< 8 && gapPos
== -1))
1638 int nToMove
= setWords
- (dot
? 2 : 0) - gapPos
;
1639 int gapLen
= 8 - setWords
;
1640 tor_assert(nToMove
>= 0);
1641 memmove(&words
[gapPos
+gapLen
], &words
[gapPos
],
1642 sizeof(uint16_t)*nToMove
);
1643 memset(&words
[gapPos
], 0, sizeof(uint16_t)*gapLen
);
1645 for (i
= 0; i
< 8; ++i
) {
1646 out
->s6_addr
[2*i
] = words
[i
] >> 8;
1647 out
->s6_addr
[2*i
+1] = words
[i
] & 0xff;
1656 /** Similar behavior to Unix gethostbyname: resolve <b>name</b>, and set
1657 * *<b>addr</b> to the proper IP address, in host byte order. Returns 0
1658 * on success, -1 on failure; 1 on transient failure.
1660 * (This function exists because standard windows gethostbyname
1661 * doesn't treat raw IP addresses properly.)
1664 tor_lookup_hostname(const char *name
, uint32_t *addr
)
1669 if ((ret
= tor_addr_lookup(name
, AF_INET
, &myaddr
)))
1672 if (tor_addr_family(&myaddr
) == AF_INET
) {
1673 *addr
= tor_addr_to_ipv4h(&myaddr
);
1680 /** Hold the result of our call to <b>uname</b>. */
1681 static char uname_result
[256];
1682 /** True iff uname_result is set. */
1683 static int uname_result_is_set
= 0;
1685 /** Return a pointer to a description of our platform.
1693 if (!uname_result_is_set
) {
1695 if (uname(&u
) != -1) {
1696 /* (Linux says 0 is success, Solaris says 1 is success) */
1697 tor_snprintf(uname_result
, sizeof(uname_result
), "%s %s",
1698 u
.sysname
, u
.machine
);
1706 OSVERSIONINFOEXW info
;
1709 const char *plat
= NULL
;
1710 const char *extra
= NULL
;
1711 char acsd
[MAX_PATH
] = {0};
1713 unsigned major
; unsigned minor
; const char *version
;
1714 } win_version_table
[] = {
1715 { 6, 1, "Windows 7" },
1716 { 6, 0, "Windows Vista" },
1717 { 5, 2, "Windows Server 2003" },
1718 { 5, 1, "Windows XP" },
1719 { 5, 0, "Windows 2000" },
1720 /* { 4, 0, "Windows NT 4.0" }, */
1721 { 4, 90, "Windows Me" },
1722 { 4, 10, "Windows 98" },
1723 /* { 4, 0, "Windows 95" } */
1724 { 3, 51, "Windows NT 3.51" },
1727 memset(&info
, 0, sizeof(info
));
1728 info
.dwOSVersionInfoSize
= sizeof(info
);
1729 if (! GetVersionExW((LPOSVERSIONINFO
)&info
)) {
1730 strlcpy(uname_result
, "Bizarre version of Windows where GetVersionEx"
1731 " doesn't work.", sizeof(uname_result
));
1732 uname_result_is_set
= 1;
1733 return uname_result
;
1735 wcstombs(acsd
, info
.szCSDVersion
, MAX_PATH
);
1736 if (info
.dwMajorVersion
== 4 && info
.dwMinorVersion
== 0) {
1737 if (info
.dwPlatformId
== VER_PLATFORM_WIN32_NT
)
1738 plat
= "Windows NT 4.0";
1740 plat
= "Windows 95";
1743 else if (acsd
[1] == 'C')
1746 for (i
=0; win_version_table
[i
].major
>0; ++i
) {
1747 if (win_version_table
[i
].major
== info
.dwMajorVersion
&&
1748 win_version_table
[i
].minor
== info
.dwMinorVersion
) {
1749 plat
= win_version_table
[i
].version
;
1754 if (plat
&& !strcmp(plat
, "Windows 98")) {
1757 else if (acsd
[1] == 'B')
1763 tor_snprintf(uname_result
, sizeof(uname_result
), "%s %s",
1766 if (info
.dwMajorVersion
> 6 ||
1767 (info
.dwMajorVersion
==6 && info
.dwMinorVersion
>1))
1768 tor_snprintf(uname_result
, sizeof(uname_result
),
1769 "Very recent version of Windows [major=%d,minor=%d] %s",
1770 (int)info
.dwMajorVersion
,(int)info
.dwMinorVersion
,
1773 tor_snprintf(uname_result
, sizeof(uname_result
),
1774 "Unrecognized version of Windows [major=%d,minor=%d] %s",
1775 (int)info
.dwMajorVersion
,(int)info
.dwMinorVersion
,
1778 #if !defined (WINCE)
1779 #ifdef VER_SUITE_BACKOFFICE
1780 if (info
.wProductType
== VER_NT_DOMAIN_CONTROLLER
) {
1781 strlcat(uname_result
, " [domain controller]", sizeof(uname_result
));
1782 } else if (info
.wProductType
== VER_NT_SERVER
) {
1783 strlcat(uname_result
, " [server]", sizeof(uname_result
));
1784 } else if (info
.wProductType
== VER_NT_WORKSTATION
) {
1785 strlcat(uname_result
, " [workstation]", sizeof(uname_result
));
1790 strlcpy(uname_result
, "Unknown platform", sizeof(uname_result
));
1793 uname_result_is_set
= 1;
1795 return uname_result
;
1802 #if defined(USE_PTHREADS)
1803 /** Wraps a void (*)(void*) function and its argument so we can
1804 * invoke them in a way pthreads would expect.
1806 typedef struct tor_pthread_data_t
{
1807 void (*func
)(void *);
1809 } tor_pthread_data_t
;
1810 /** Given a tor_pthread_data_t <b>_data</b>, call _data->func(d->data)
1811 * and free _data. Used to make sure we can call functions the way pthread
1814 tor_pthread_helper_fn(void *_data
)
1816 tor_pthread_data_t
*data
= _data
;
1817 void (*func
)(void*);
1819 /* mask signals to worker threads to avoid SIGPIPE, etc */
1821 /* We're in a subthread; don't handle any signals here. */
1823 pthread_sigmask(SIG_SETMASK
, &sigs
, NULL
);
1833 /** Minimalist interface to run a void function in the background. On
1834 * Unix calls fork, on win32 calls beginthread. Returns -1 on failure.
1835 * func should not return, but rather should call spawn_exit.
1837 * NOTE: if <b>data</b> is used, it should not be allocated on the stack,
1838 * since in a multithreaded environment, there is no way to be sure that
1839 * the caller's stack will still be around when the called function is
1843 spawn_func(void (*func
)(void *), void *data
)
1845 #if defined(USE_WIN32_THREADS)
1847 rv
= (int)_beginthread(func
, 0, data
);
1851 #elif defined(USE_PTHREADS)
1853 tor_pthread_data_t
*d
;
1854 d
= tor_malloc(sizeof(tor_pthread_data_t
));
1857 if (pthread_create(&thread
,NULL
,tor_pthread_helper_fn
,d
))
1859 if (pthread_detach(thread
))
1870 tor_assert(0); /* Should never reach here. */
1871 return 0; /* suppress "control-reaches-end-of-non-void" warning. */
1879 /** End the current thread/process.
1884 #if defined(USE_WIN32_THREADS)
1886 //we should never get here. my compiler thinks that _endthread returns, this
1887 //is an attempt to fool it.
1890 #elif defined(USE_PTHREADS)
1893 /* http://www.erlenstar.demon.co.uk/unix/faq_2.html says we should
1894 * call _exit, not exit, from child processes. */
1899 /** Set *timeval to the current time of day. On error, log and terminate.
1900 * (Same as gettimeofday(timeval,NULL), but never returns -1.)
1903 tor_gettimeofday(struct timeval
*timeval
)
1906 /* Epoch bias copied from perl: number of units between windows epoch and
1908 #define EPOCH_BIAS U64_LITERAL(116444736000000000)
1909 #define UNITS_PER_SEC U64_LITERAL(10000000)
1910 #define USEC_PER_SEC U64_LITERAL(1000000)
1911 #define UNITS_PER_USEC U64_LITERAL(10)
1917 /* wince do not have GetSystemTimeAsFileTime */
1919 GetSystemTime(&stime
);
1920 SystemTimeToFileTime(&stime
,&ft
.ft_ft
);
1922 /* number of 100-nsec units since Jan 1, 1601 */
1923 GetSystemTimeAsFileTime(&ft
.ft_ft
);
1925 if (ft
.ft_64
< EPOCH_BIAS
) {
1926 log_err(LD_GENERAL
,"System time is before 1970; failing.");
1929 ft
.ft_64
-= EPOCH_BIAS
;
1930 timeval
->tv_sec
= (unsigned) (ft
.ft_64
/ UNITS_PER_SEC
);
1931 timeval
->tv_usec
= (unsigned) ((ft
.ft_64
/ UNITS_PER_USEC
) % USEC_PER_SEC
);
1932 #elif defined(HAVE_GETTIMEOFDAY)
1933 if (gettimeofday(timeval
, NULL
)) {
1934 log_err(LD_GENERAL
,"gettimeofday failed.");
1935 /* If gettimeofday dies, we have either given a bad timezone (we didn't),
1939 #elif defined(HAVE_FTIME)
1942 timeval
->tv_sec
= tb
.time
;
1943 timeval
->tv_usec
= tb
.millitm
* 1000;
1945 #error "No way to get time."
1950 #if defined(TOR_IS_MULTITHREADED) && !defined(MS_WINDOWS)
1951 /** Defined iff we need to add locks when defining fake versions of reentrant
1952 * versions of time-related functions. */
1953 #define TIME_FNS_NEED_LOCKS
1956 #ifndef HAVE_LOCALTIME_R
1957 #ifdef TIME_FNS_NEED_LOCKS
1959 tor_localtime_r(const time_t *timep
, struct tm
*result
)
1962 static tor_mutex_t
*m
=NULL
;
1963 if (!m
) { m
=tor_mutex_new(); }
1965 tor_mutex_acquire(m
);
1966 r
= localtime(timep
);
1967 memcpy(result
, r
, sizeof(struct tm
));
1968 tor_mutex_release(m
);
1973 tor_localtime_r(const time_t *timep
, struct tm
*result
)
1977 r
= localtime(timep
);
1978 memcpy(result
, r
, sizeof(struct tm
));
1984 #ifndef HAVE_GMTIME_R
1985 #ifdef TIME_FNS_NEED_LOCKS
1987 tor_gmtime_r(const time_t *timep
, struct tm
*result
)
1990 static tor_mutex_t
*m
=NULL
;
1991 if (!m
) { m
=tor_mutex_new(); }
1993 tor_mutex_acquire(m
);
1995 memcpy(result
, r
, sizeof(struct tm
));
1996 tor_mutex_release(m
);
2001 tor_gmtime_r(const time_t *timep
, struct tm
*result
)
2006 memcpy(result
, r
, sizeof(struct tm
));
2012 #if defined(USE_WIN32_THREADS)
2014 tor_mutex_init(tor_mutex_t
*m
)
2016 InitializeCriticalSection(&m
->mutex
);
2019 tor_mutex_uninit(tor_mutex_t
*m
)
2021 DeleteCriticalSection(&m
->mutex
);
2024 tor_mutex_acquire(tor_mutex_t
*m
)
2027 EnterCriticalSection(&m
->mutex
);
2030 tor_mutex_release(tor_mutex_t
*m
)
2032 LeaveCriticalSection(&m
->mutex
);
2035 tor_get_thread_id(void)
2037 return (unsigned long)GetCurrentThreadId();
2039 #elif defined(USE_PTHREADS)
2040 /** A mutex attribute that we're going to use to tell pthreads that we want
2041 * "reentrant" mutexes (i.e., once we can re-lock if we're already holding
2043 static pthread_mutexattr_t attr_reentrant
;
2044 /** True iff we've called tor_threads_init() */
2045 static int threads_initialized
= 0;
2046 /** Initialize <b>mutex</b> so it can be locked. Every mutex must be set
2047 * up with tor_mutex_init() or tor_mutex_new(); not both. */
2049 tor_mutex_init(tor_mutex_t
*mutex
)
2052 if (PREDICT_UNLIKELY(!threads_initialized
))
2054 err
= pthread_mutex_init(&mutex
->mutex
, &attr_reentrant
);
2055 if (PREDICT_UNLIKELY(err
)) {
2056 log_err(LD_GENERAL
, "Error %d creating a mutex.", err
);
2057 tor_fragile_assert();
2060 /** Wait until <b>m</b> is free, then acquire it. */
2062 tor_mutex_acquire(tor_mutex_t
*m
)
2066 err
= pthread_mutex_lock(&m
->mutex
);
2067 if (PREDICT_UNLIKELY(err
)) {
2068 log_err(LD_GENERAL
, "Error %d locking a mutex.", err
);
2069 tor_fragile_assert();
2072 /** Release the lock <b>m</b> so another thread can have it. */
2074 tor_mutex_release(tor_mutex_t
*m
)
2078 err
= pthread_mutex_unlock(&m
->mutex
);
2079 if (PREDICT_UNLIKELY(err
)) {
2080 log_err(LD_GENERAL
, "Error %d unlocking a mutex.", err
);
2081 tor_fragile_assert();
2084 /** Clean up the mutex <b>m</b> so that it no longer uses any system
2085 * resources. Does not free <b>m</b>. This function must only be called on
2086 * mutexes from tor_mutex_init(). */
2088 tor_mutex_uninit(tor_mutex_t
*m
)
2092 err
= pthread_mutex_destroy(&m
->mutex
);
2093 if (PREDICT_UNLIKELY(err
)) {
2094 log_err(LD_GENERAL
, "Error %d destroying a mutex.", err
);
2095 tor_fragile_assert();
2098 /** Return an integer representing this thread. */
2100 tor_get_thread_id(void)
2106 r
.thr
= pthread_self();
2111 #ifdef TOR_IS_MULTITHREADED
2112 /** Return a newly allocated, ready-for-use mutex. */
2116 tor_mutex_t
*m
= tor_malloc_zero(sizeof(tor_mutex_t
));
2120 /** Release all storage and system resources held by <b>m</b>. */
2122 tor_mutex_free(tor_mutex_t
*m
)
2126 tor_mutex_uninit(m
);
2134 /** Cross-platform condition implementation. */
2136 pthread_cond_t cond
;
2138 /** Return a newly allocated condition, with nobody waiting on it. */
2142 tor_cond_t
*cond
= tor_malloc_zero(sizeof(tor_cond_t
));
2143 if (pthread_cond_init(&cond
->cond
, NULL
)) {
2149 /** Release all resources held by <b>cond</b>. */
2151 tor_cond_free(tor_cond_t
*cond
)
2155 if (pthread_cond_destroy(&cond
->cond
)) {
2156 log_warn(LD_GENERAL
,"Error freeing condition: %s", strerror(errno
));
2161 /** Wait until one of the tor_cond_signal functions is called on <b>cond</b>.
2162 * All waiters on the condition must wait holding the same <b>mutex</b>.
2163 * Returns 0 on success, negative on failure. */
2165 tor_cond_wait(tor_cond_t
*cond
, tor_mutex_t
*mutex
)
2167 return pthread_cond_wait(&cond
->cond
, &mutex
->mutex
) ? -1 : 0;
2169 /** Wake up one of the waiters on <b>cond</b>. */
2171 tor_cond_signal_one(tor_cond_t
*cond
)
2173 pthread_cond_signal(&cond
->cond
);
2175 /** Wake up all of the waiters on <b>cond</b>. */
2177 tor_cond_signal_all(tor_cond_t
*cond
)
2179 pthread_cond_broadcast(&cond
->cond
);
2182 /** Set up common structures for use by threading. */
2184 tor_threads_init(void)
2186 if (!threads_initialized
) {
2187 pthread_mutexattr_init(&attr_reentrant
);
2188 pthread_mutexattr_settype(&attr_reentrant
, PTHREAD_MUTEX_RECURSIVE
);
2189 threads_initialized
= 1;
2193 #elif defined(USE_WIN32_THREADS)
2195 static DWORD cond_event_tls_index
;
2197 CRITICAL_SECTION mutex
;
2198 smartlist_t
*events
;
2203 tor_cond_t
*cond
= tor_malloc_zero(sizeof(tor_cond_t
));
2204 InitializeCriticalSection(&cond
->mutex
);
2205 cond
->events
= smartlist_create();
2209 tor_cond_free(tor_cond_t
*cond
)
2213 DeleteCriticalSection(&cond
->mutex
);
2215 smartlist_free(cond
->events
);
2219 tor_cond_wait(tor_cond_t
*cond
, tor_mutex_t
*mutex
)
2225 event
= TlsGetValue(cond_event_tls_index
);
2227 event
= CreateEvent(0, FALSE
, FALSE
, NULL
);
2228 TlsSetValue(cond_event_tls_index
, event
);
2230 EnterCriticalSection(&cond
->mutex
);
2232 tor_assert(WaitForSingleObject(event
, 0) == WAIT_TIMEOUT
);
2233 tor_assert(!smartlist_isin(cond
->events
, event
));
2234 smartlist_add(cond
->events
, event
);
2236 LeaveCriticalSection(&cond
->mutex
);
2238 tor_mutex_release(mutex
);
2239 r
= WaitForSingleObject(event
, INFINITE
);
2240 tor_mutex_acquire(mutex
);
2243 case WAIT_OBJECT_0
: /* we got the mutex normally. */
2245 case WAIT_ABANDONED
: /* holding thread exited. */
2246 case WAIT_TIMEOUT
: /* Should never happen. */
2250 log_warn(LD_GENERAL
, "Failed to acquire mutex: %d",(int) GetLastError());
2255 tor_cond_signal_one(tor_cond_t
*cond
)
2260 EnterCriticalSection(&cond
->mutex
);
2262 if ((event
= smartlist_pop_last(cond
->events
)))
2265 LeaveCriticalSection(&cond
->mutex
);
2268 tor_cond_signal_all(tor_cond_t
*cond
)
2272 EnterCriticalSection(&cond
->mutex
);
2273 SMARTLIST_FOREACH(cond
->events
, HANDLE
, event
, SetEvent(event
));
2274 smartlist_clear(cond
->events
);
2275 LeaveCriticalSection(&cond
->mutex
);
2279 tor_threads_init(void)
2282 cond_event_tls_index
= TlsAlloc();
2288 #if defined(HAVE_MLOCKALL) && HAVE_DECL_MLOCKALL && defined(RLIMIT_MEMLOCK)
2289 /** Attempt to raise the current and max rlimit to infinity for our process.
2290 * This only needs to be done once and can probably only be done when we have
2291 * not already dropped privileges.
2294 tor_set_max_memlock(void)
2296 /* Future consideration for Windows is probably SetProcessWorkingSetSize
2297 * This is similar to setting the memory rlimit of RLIMIT_MEMLOCK
2298 * http://msdn.microsoft.com/en-us/library/ms686234(VS.85).aspx
2301 struct rlimit limit
;
2304 /* Do we want to report current limits first? This is not really needed. */
2305 ret
= getrlimit(RLIMIT_MEMLOCK
, &limit
);
2307 log_warn(LD_GENERAL
, "Could not get RLIMIT_MEMLOCK: %s", strerror(errno
));
2311 /* RLIM_INFINITY is -1 on some platforms. */
2312 limit
.rlim_cur
= RLIM_INFINITY
;
2313 limit
.rlim_max
= RLIM_INFINITY
;
2315 ret
= setrlimit(RLIMIT_MEMLOCK
, &limit
);
2317 if (errno
== EPERM
) {
2318 log_warn(LD_GENERAL
, "You appear to lack permissions to change memory "
2319 "limits. Are you root?");
2320 log_warn(LD_GENERAL
, "Unable to raise RLIMIT_MEMLOCK: %s",
2323 log_warn(LD_GENERAL
, "Could not raise RLIMIT_MEMLOCK: %s",
2333 /** Attempt to lock all current and all future memory pages.
2334 * This should only be called once and while we're privileged.
2335 * Like mlockall() we return 0 when we're successful and -1 when we're not.
2336 * Unlike mlockall() we return 1 if we've already attempted to lock memory.
2341 static int memory_lock_attempted
= 0;
2343 if (memory_lock_attempted
) {
2347 memory_lock_attempted
= 1;
2350 * Future consideration for Windows may be VirtualLock
2351 * VirtualLock appears to implement mlock() but not mlockall()
2353 * http://msdn.microsoft.com/en-us/library/aa366895(VS.85).aspx
2356 #if defined(HAVE_MLOCKALL) && HAVE_DECL_MLOCKALL && defined(RLIMIT_MEMLOCK)
2357 if (tor_set_max_memlock() == 0) {
2358 /* Perhaps we only want to log this if we're in a verbose mode? */
2359 log_notice(LD_GENERAL
, "RLIMIT_MEMLOCK is now set to RLIM_INFINITY.");
2362 if (mlockall(MCL_CURRENT
|MCL_FUTURE
) == 0) {
2363 log_notice(LD_GENERAL
, "Insecure OS paging is effectively disabled.");
2366 if (errno
== ENOSYS
) {
2367 /* Apple - it's 2009! I'm looking at you. Grrr. */
2368 log_notice(LD_GENERAL
, "It appears that mlockall() is not available on "
2370 } else if (errno
== EPERM
) {
2371 log_notice(LD_GENERAL
, "It appears that you lack the permissions to "
2372 "lock memory. Are you root?");
2374 log_notice(LD_GENERAL
, "Unable to lock all current and future memory "
2375 "pages: %s", strerror(errno
));
2379 log_warn(LD_GENERAL
, "Unable to lock memory pages. mlockall() unsupported?");
2384 /** Identity of the "main" thread */
2385 static unsigned long main_thread_id
= -1;
2387 /** Start considering the current thread to be the 'main thread'. This has
2388 * no effect on anything besides in_main_thread(). */
2390 set_main_thread(void)
2392 main_thread_id
= tor_get_thread_id();
2394 /** Return true iff called from the main thread. */
2396 in_main_thread(void)
2398 return main_thread_id
== tor_get_thread_id();
2402 * On Windows, WSAEWOULDBLOCK is not always correct: when you see it,
2403 * you need to ask the socket for its actual errno. Also, you need to
2404 * get your errors from WSAGetLastError, not errno. (If you supply a
2405 * socket of -1, we check WSAGetLastError, but don't correct
2408 * The upshot of all of this is that when a socket call fails, you
2409 * should call tor_socket_errno <em>at most once</em> on the failing
2410 * socket to get the error.
2412 #if defined(MS_WINDOWS)
2414 tor_socket_errno(int sock
)
2416 int optval
, optvallen
=sizeof(optval
);
2417 int err
= WSAGetLastError();
2418 if (err
== WSAEWOULDBLOCK
&& sock
>= 0) {
2419 if (getsockopt(sock
, SOL_SOCKET
, SO_ERROR
, (void*)&optval
, &optvallen
))
2428 #if defined(MS_WINDOWS)
2429 #define E(code, s) { code, (s " [" #code " ]") }
2430 struct { int code
; const char *msg
; } windows_socket_errors
[] = {
2431 E(WSAEINTR
, "Interrupted function call"),
2432 E(WSAEACCES
, "Permission denied"),
2433 E(WSAEFAULT
, "Bad address"),
2434 E(WSAEINVAL
, "Invalid argument"),
2435 E(WSAEMFILE
, "Too many open files"),
2436 E(WSAEWOULDBLOCK
, "Resource temporarily unavailable"),
2437 E(WSAEINPROGRESS
, "Operation now in progress"),
2438 E(WSAEALREADY
, "Operation already in progress"),
2439 E(WSAENOTSOCK
, "Socket operation on nonsocket"),
2440 E(WSAEDESTADDRREQ
, "Destination address required"),
2441 E(WSAEMSGSIZE
, "Message too long"),
2442 E(WSAEPROTOTYPE
, "Protocol wrong for socket"),
2443 E(WSAENOPROTOOPT
, "Bad protocol option"),
2444 E(WSAEPROTONOSUPPORT
, "Protocol not supported"),
2445 E(WSAESOCKTNOSUPPORT
, "Socket type not supported"),
2446 /* What's the difference between NOTSUPP and NOSUPPORT? :) */
2447 E(WSAEOPNOTSUPP
, "Operation not supported"),
2448 E(WSAEPFNOSUPPORT
, "Protocol family not supported"),
2449 E(WSAEAFNOSUPPORT
, "Address family not supported by protocol family"),
2450 E(WSAEADDRINUSE
, "Address already in use"),
2451 E(WSAEADDRNOTAVAIL
, "Cannot assign requested address"),
2452 E(WSAENETDOWN
, "Network is down"),
2453 E(WSAENETUNREACH
, "Network is unreachable"),
2454 E(WSAENETRESET
, "Network dropped connection on reset"),
2455 E(WSAECONNABORTED
, "Software caused connection abort"),
2456 E(WSAECONNRESET
, "Connection reset by peer"),
2457 E(WSAENOBUFS
, "No buffer space available"),
2458 E(WSAEISCONN
, "Socket is already connected"),
2459 E(WSAENOTCONN
, "Socket is not connected"),
2460 E(WSAESHUTDOWN
, "Cannot send after socket shutdown"),
2461 E(WSAETIMEDOUT
, "Connection timed out"),
2462 E(WSAECONNREFUSED
, "Connection refused"),
2463 E(WSAEHOSTDOWN
, "Host is down"),
2464 E(WSAEHOSTUNREACH
, "No route to host"),
2465 E(WSAEPROCLIM
, "Too many processes"),
2466 /* Yes, some of these start with WSA, not WSAE. No, I don't know why. */
2467 E(WSASYSNOTREADY
, "Network subsystem is unavailable"),
2468 E(WSAVERNOTSUPPORTED
, "Winsock.dll out of range"),
2469 E(WSANOTINITIALISED
, "Successful WSAStartup not yet performed"),
2470 E(WSAEDISCON
, "Graceful shutdown now in progress"),
2471 #ifdef WSATYPE_NOT_FOUND
2472 E(WSATYPE_NOT_FOUND
, "Class type not found"),
2474 E(WSAHOST_NOT_FOUND
, "Host not found"),
2475 E(WSATRY_AGAIN
, "Nonauthoritative host not found"),
2476 E(WSANO_RECOVERY
, "This is a nonrecoverable error"),
2477 E(WSANO_DATA
, "Valid name, no data record of requested type)"),
2479 /* There are some more error codes whose numeric values are marked
2480 * <b>OS dependent</b>. They start with WSA_, apparently for the same
2481 * reason that practitioners of some craft traditions deliberately
2482 * introduce imperfections into their baskets and rugs "to allow the
2483 * evil spirits to escape." If we catch them, then our binaries
2484 * might not report consistent results across versions of Windows.
2485 * Thus, I'm going to let them all fall through.
2489 /** There does not seem to be a strerror equivalent for Winsock errors.
2490 * Naturally, we have to roll our own.
2493 tor_socket_strerror(int e
)
2496 for (i
=0; windows_socket_errors
[i
].code
>= 0; ++i
) {
2497 if (e
== windows_socket_errors
[i
].code
)
2498 return windows_socket_errors
[i
].msg
;
2504 /** Called before we make any calls to network-related functions.
2505 * (Some operating systems require their network libraries to be
2511 /* This silly exercise is necessary before windows will allow
2512 * gethostbyname to work. */
2515 r
= WSAStartup(0x101,&WSAData
);
2517 log_warn(LD_NET
,"Error initializing windows network layer: code was %d",r
);
2520 /* WSAData.iMaxSockets might show the max sockets we're allowed to use.
2521 * We might use it to complain if we're trying to be a server but have
2522 * too few sockets available. */
2528 /** Return a newly allocated string describing the windows system error code
2529 * <b>err</b>. Note that error codes are different from errno. Error codes
2530 * come from GetLastError() when a winapi call fails. errno is set only when
2531 * ANSI functions fail. Whee. */
2533 format_win32_error(DWORD err
)
2536 char abuf
[1024] = {0};
2539 /* Somebody once decided that this interface was better than strerror(). */
2540 FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER
|
2541 FORMAT_MESSAGE_FROM_SYSTEM
|
2542 FORMAT_MESSAGE_IGNORE_INSERTS
,
2544 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
2549 wcstombs(abuf
,str
,1024);
2550 result
= tor_strdup((char*)abuf
);
2551 LocalFree(str
); /* LocalFree != free() */
2553 result
= tor_strdup("<unformattable error>");