1 /* Copyright (c) 2003-2004, Roger Dingledine
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2011, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
8 * \brief Wrappers to make calls more portable. This code defines
9 * functions such as tor_malloc, tor_snprintf, get/set various data types,
10 * renaming, setting socket options, switching user IDs. It is basically
11 * where the non-portable items are conditionally included depending on
15 /* This is required on rh7 to make strptime not complain.
16 * We also need it to make memmem get defined (where available)
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 /* XXXX why not just do fstat here? */
130 size
= filesize
= (size_t) lseek(fd
, 0, SEEK_END
);
131 lseek(fd
, 0, SEEK_SET
);
132 /* ensure page alignment */
133 page_size
= getpagesize();
134 size
+= (size
%page_size
) ? page_size
-(size
%page_size
) : 0;
137 /* Zero-length file. If we call mmap on it, it will succeed but
138 * return NULL, and bad things will happen. So just fail. */
139 log_info(LD_FS
,"File \"%s\" is empty. Ignoring.",filename
);
145 string
= mmap(0, size
, PROT_READ
, MAP_PRIVATE
, fd
, 0);
147 if (string
== MAP_FAILED
) {
148 int save_errno
= errno
;
149 log_warn(LD_FS
,"Could not mmap file \"%s\": %s", filename
,
155 res
= tor_malloc_zero(sizeof(tor_mmap_t
));
157 res
->size
= filesize
;
158 res
->mapping_size
= size
;
162 /** Release storage held for a memory mapping. */
164 tor_munmap_file(tor_mmap_t
*handle
)
166 munmap((char*)handle
->data
, handle
->mapping_size
);
169 #elif defined(MS_WINDOWS)
171 tor_mmap_file(const char *filename
)
173 TCHAR tfilename
[MAX_PATH
]= {0};
174 tor_mmap_t
*res
= tor_malloc_zero(sizeof(tor_mmap_t
));
176 res
->file_handle
= INVALID_HANDLE_VALUE
;
177 res
->mmap_handle
= NULL
;
179 mbstowcs(tfilename
,filename
,MAX_PATH
);
181 strlcpy(tfilename
,filename
,MAX_PATH
);
183 res
->file_handle
= CreateFile(tfilename
,
184 GENERIC_READ
, FILE_SHARE_READ
,
187 FILE_ATTRIBUTE_NORMAL
,
190 if (res
->file_handle
== INVALID_HANDLE_VALUE
)
193 res
->size
= GetFileSize(res
->file_handle
, NULL
);
195 if (res
->size
== 0) {
196 log_info(LD_FS
,"File \"%s\" is empty. Ignoring.",filename
);
201 res
->mmap_handle
= CreateFileMapping(res
->file_handle
,
204 #if SIZEOF_SIZE_T > 4
205 (res
->base
.size
>> 32),
209 (res
->size
& 0xfffffffful
),
211 if (res
->mmap_handle
== NULL
)
213 res
->data
= (char*) MapViewOfFile(res
->mmap_handle
,
221 DWORD e
= GetLastError();
222 int severity
= (e
== ERROR_FILE_NOT_FOUND
|| e
== ERROR_PATH_NOT_FOUND
) ?
224 char *msg
= format_win32_error(e
);
225 log_fn(severity
, LD_FS
, "Couldn't mmap file \"%s\": %s", filename
, msg
);
227 if (e
== ERROR_FILE_NOT_FOUND
|| e
== ERROR_PATH_NOT_FOUND
)
235 tor_munmap_file(res
);
239 tor_munmap_file(tor_mmap_t
*handle
)
242 /* This is an ugly cast, but without it, "data" in struct tor_mmap_t would
243 have to be redefined as non-const. */
244 UnmapViewOfFile( (LPVOID
) handle
->data
);
246 if (handle
->mmap_handle
!= NULL
)
247 CloseHandle(handle
->mmap_handle
);
248 if (handle
->file_handle
!= INVALID_HANDLE_VALUE
)
249 CloseHandle(handle
->file_handle
);
254 tor_mmap_file(const char *filename
)
257 char *res
= read_file_to_str(filename
, RFTS_BIN
|RFTS_IGNORE_MISSING
, &st
);
261 handle
= tor_malloc_zero(sizeof(tor_mmap_t
));
263 handle
->size
= st
.st_size
;
267 tor_munmap_file(tor_mmap_t
*handle
)
269 char *d
= (char*)handle
->data
;
271 memset(handle
, 0, sizeof(tor_mmap_t
));
276 /** Replacement for snprintf. Differs from platform snprintf in two
277 * ways: First, always NUL-terminates its output. Second, always
278 * returns -1 if the result is truncated. (Note that this return
279 * behavior does <i>not</i> conform to C99; it just happens to be
280 * easier to emulate "return -1" with conformant implementations than
281 * it is to emulate "return number that would be written" with
282 * non-conformant implementations.) */
284 tor_snprintf(char *str
, size_t size
, const char *format
, ...)
289 r
= tor_vsnprintf(str
,size
,format
,ap
);
294 /** Replacement for vsnprintf; behavior differs as tor_snprintf differs from
298 tor_vsnprintf(char *str
, size_t size
, const char *format
, va_list args
)
302 return -1; /* no place for the NUL */
303 if (size
> SIZE_T_CEILING
)
306 r
= _vsnprintf(str
, size
, format
, args
);
308 r
= vsnprintf(str
, size
, format
, args
);
311 if (r
< 0 || r
>= (ssize_t
)size
)
317 * Portable asprintf implementation. Does a printf() into a newly malloc'd
318 * string. Sets *<b>strp</b> to this string, and returns its length (not
319 * including the terminating NUL character).
321 * You can treat this function as if its implementation were something like
323 char buf[_INFINITY_];
324 tor_snprintf(buf, sizeof(buf), fmt, args);
325 *strp = tor_strdup(buf);
326 return strlen(*strp):
328 * Where _INFINITY_ is an imaginary constant so big that any string can fit
332 tor_asprintf(char **strp
, const char *fmt
, ...)
337 r
= tor_vasprintf(strp
, fmt
, args
);
339 if (!*strp
|| r
< 0) {
340 log_err(LD_BUG
, "Internal error in asprintf");
347 * Portable vasprintf implementation. Does a printf() into a newly malloc'd
348 * string. Differs from regular vasprintf in the same ways that
349 * tor_asprintf() differs from regular asprintf.
352 tor_vasprintf(char **strp
, const char *fmt
, va_list args
)
354 /* use a temporary variable in case *strp is in args. */
356 #ifdef HAVE_VASPRINTF
357 /* If the platform gives us one, use it. */
358 int r
= vasprintf(&strp_tmp
, fmt
, args
);
364 #elif defined(_MSC_VER)
365 /* On Windows, _vsnprintf won't tell us the length of the string if it
366 * overflows, so we need to use _vcsprintf to tell how much to allocate */
369 len
= _vscprintf(fmt
, args
);
374 strp_tmp
= tor_malloc(len
+ 1);
375 r
= _vsnprintf(strp_tmp
, len
+1, fmt
, args
);
384 /* Everywhere else, we have a decent vsnprintf that tells us how many
385 * characters we need. We give it a try on a short buffer first, since
386 * it might be nice to avoid the second vsnprintf call.
391 va_copy(tmp_args
, args
);
392 len
= vsnprintf(buf
, sizeof(buf
), fmt
, tmp_args
);
394 if (len
< (int)sizeof(buf
)) {
395 *strp
= tor_strdup(buf
);
398 strp_tmp
= tor_malloc(len
+1);
399 r
= vsnprintf(strp_tmp
, len
+1, fmt
, args
);
410 /** Given <b>hlen</b> bytes at <b>haystack</b> and <b>nlen</b> bytes at
411 * <b>needle</b>, return a pointer to the first occurrence of the needle
412 * within the haystack, or NULL if there is no such occurrence.
414 * Requires that nlen be greater than zero.
417 tor_memmem(const void *_haystack
, size_t hlen
,
418 const void *_needle
, size_t nlen
)
420 #if defined(HAVE_MEMMEM) && (!defined(__GNUC__) || __GNUC__ >= 2)
422 return memmem(_haystack
, hlen
, _needle
, nlen
);
424 /* This isn't as fast as the GLIBC implementation, but it doesn't need to
427 const char *haystack
= (const char*)_haystack
;
428 const char *needle
= (const char*)_needle
;
433 end
= haystack
+ hlen
;
434 first
= *(const char*)needle
;
435 while ((p
= memchr(p
, first
, end
-p
))) {
438 if (!memcmp(p
, needle
, nlen
))
446 /* Tables to implement ctypes-replacement TOR_IS*() functions. Each table
447 * has 256 bits to look up whether a character is in some set or not. This
448 * fails on non-ASCII platforms, but it is hard to find a platform whose
449 * character set is not a superset of ASCII nowadays. */
450 const uint32_t TOR_ISALPHA_TABLE
[8] =
451 { 0, 0, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
452 const uint32_t TOR_ISALNUM_TABLE
[8] =
453 { 0, 0x3ff0000, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
454 const uint32_t TOR_ISSPACE_TABLE
[8] = { 0x3e00, 0x1, 0, 0, 0, 0, 0, 0 };
455 const uint32_t TOR_ISXDIGIT_TABLE
[8] =
456 { 0, 0x3ff0000, 0x7e, 0x7e, 0, 0, 0, 0 };
457 const uint32_t TOR_ISDIGIT_TABLE
[8] = { 0, 0x3ff0000, 0, 0, 0, 0, 0, 0 };
458 const uint32_t TOR_ISPRINT_TABLE
[8] =
459 { 0, 0xffffffff, 0xffffffff, 0x7fffffff, 0, 0, 0, 0x0 };
460 const uint32_t TOR_ISUPPER_TABLE
[8] = { 0, 0, 0x7fffffe, 0, 0, 0, 0, 0 };
461 const uint32_t TOR_ISLOWER_TABLE
[8] = { 0, 0, 0, 0x7fffffe, 0, 0, 0, 0 };
462 /* Upper-casing and lowercasing tables to map characters to upper/lowercase
464 const char TOR_TOUPPER_TABLE
[256] = {
465 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
466 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
467 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
468 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
469 64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
470 80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
471 96,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
472 80,81,82,83,84,85,86,87,88,89,90,123,124,125,126,127,
473 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
474 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
475 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
476 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
477 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
478 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
479 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
480 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
482 const char TOR_TOLOWER_TABLE
[256] = {
483 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
484 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
485 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
486 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
487 64,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
488 112,113,114,115,116,117,118,119,120,121,122,91,92,93,94,95,
489 96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
490 112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
491 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
492 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
493 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
494 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
495 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
496 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
497 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
498 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
501 /** Implementation of strtok_r for platforms whose coders haven't figured out
502 * how to write one. Hey guys! You can use this code here for free! */
504 tor_strtok_r_impl(char *str
, const char *sep
, char **lasts
)
508 start
= cp
= *lasts
= str
;
516 while (*cp
&& !strchr(sep
, *cp
))
519 tor_assert(strlen(sep
) == 1);
520 cp
= strchr(cp
, *sep
);
533 /** Take a filename and return a pointer to its final element. This
534 * function is called on __FILE__ to fix a MSVC nit where __FILE__
535 * contains the full path to the file. This is bad, because it
536 * confuses users to find the home directory of the person who
537 * compiled the binary in their warning messages.
540 tor_fix_source_file(const char *fname
)
542 const char *cp1
, *cp2
, *r
;
543 cp1
= strrchr(fname
, '/');
544 cp2
= strrchr(fname
, '\\');
546 r
= (cp1
<cp2
)?(cp2
+1):(cp1
+1);
559 * Read a 16-bit value beginning at <b>cp</b>. Equivalent to
560 * *(uint16_t*)(cp), but will not cause segfaults on platforms that forbid
561 * unaligned memory access.
564 get_uint16(const void *cp
)
571 * Read a 32-bit value beginning at <b>cp</b>. Equivalent to
572 * *(uint32_t*)(cp), but will not cause segfaults on platforms that forbid
573 * unaligned memory access.
576 get_uint32(const void *cp
)
583 * Read a 64-bit value beginning at <b>cp</b>. Equivalent to
584 * *(uint64_t*)(cp), but will not cause segfaults on platforms that forbid
585 * unaligned memory access.
588 get_uint64(const void *cp
)
596 * Set a 16-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
597 * *(uint16_t*)(cp) = v, but will not cause segfaults on platforms that forbid
598 * unaligned memory access. */
600 set_uint16(void *cp
, uint16_t v
)
605 * Set a 32-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
606 * *(uint32_t*)(cp) = v, but will not cause segfaults on platforms that forbid
607 * unaligned memory access. */
609 set_uint32(void *cp
, uint32_t v
)
614 * Set a 64-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
615 * *(uint64_t*)(cp) = v, but will not cause segfaults on platforms that forbid
616 * unaligned memory access. */
618 set_uint64(void *cp
, uint64_t v
)
624 * Rename the file <b>from</b> to the file <b>to</b>. On Unix, this is
625 * the same as rename(2). On windows, this removes <b>to</b> first if
627 * Returns 0 on success. Returns -1 and sets errno on failure.
630 replace_file(const char *from
, const char *to
)
633 return rename(from
,to
);
635 switch (file_status(to
))
640 if (unlink(to
)) return -1;
648 return rename(from
,to
);
652 /** Change <b>fname</b>'s modification time to now. */
654 touch_file(const char *fname
)
656 if (utime(fname
, NULL
)!=0)
661 /** Represents a lockfile on which we hold the lock. */
662 struct tor_lockfile_t
{
667 /** Try to get a lock on the lockfile <b>filename</b>, creating it as
668 * necessary. If someone else has the lock and <b>blocking</b> is true,
669 * wait until the lock is available. Otherwise return immediately whether
670 * we succeeded or not.
672 * Set *<b>locked_out</b> to true if somebody else had the lock, and to false
675 * Return a <b>tor_lockfile_t</b> on success, NULL on failure.
677 * (Implementation note: because we need to fall back to fcntl on some
678 * platforms, these locks are per-process, not per-thread. If you want
679 * to do in-process locking, use tor_mutex_t like a normal person.
680 * On Windows, when <b>blocking</b> is true, the maximum time that
681 * is actually waited is 10 seconds, after which NULL is returned
682 * and <b>locked_out</b> is set to 1.)
685 tor_lockfile_lock(const char *filename
, int blocking
, int *locked_out
)
687 tor_lockfile_t
*result
;
691 log_info(LD_FS
, "Locking \"%s\"", filename
);
692 fd
= open(filename
, O_RDWR
|O_CREAT
|O_TRUNC
, 0600);
694 log_warn(LD_FS
,"Couldn't open \"%s\" for locking: %s", filename
,
700 _lseek(fd
, 0, SEEK_SET
);
701 if (_locking(fd
, blocking
? _LK_LOCK
: _LK_NBLCK
, 1) < 0) {
702 if (errno
!= EACCES
&& errno
!= EDEADLOCK
)
703 log_warn(LD_FS
,"Couldn't lock \"%s\": %s", filename
, strerror(errno
));
709 #elif defined(HAVE_FLOCK)
710 if (flock(fd
, LOCK_EX
|(blocking
? 0 : LOCK_NB
)) < 0) {
711 if (errno
!= EWOULDBLOCK
)
712 log_warn(LD_FS
,"Couldn't lock \"%s\": %s", filename
, strerror(errno
));
721 memset(&lock
, 0, sizeof(lock
));
722 lock
.l_type
= F_WRLCK
;
723 lock
.l_whence
= SEEK_SET
;
724 if (fcntl(fd
, blocking
? F_SETLKW
: F_SETLK
, &lock
) < 0) {
725 if (errno
!= EACCES
&& errno
!= EAGAIN
)
726 log_warn(LD_FS
, "Couldn't lock \"%s\": %s", filename
, strerror(errno
));
735 result
= tor_malloc(sizeof(tor_lockfile_t
));
736 result
->filename
= tor_strdup(filename
);
741 /** Release the lock held as <b>lockfile</b>. */
743 tor_lockfile_unlock(tor_lockfile_t
*lockfile
)
745 tor_assert(lockfile
);
747 log_info(LD_FS
, "Unlocking \"%s\"", lockfile
->filename
);
749 _lseek(lockfile
->fd
, 0, SEEK_SET
);
750 if (_locking(lockfile
->fd
, _LK_UNLCK
, 1) < 0) {
751 log_warn(LD_FS
,"Error unlocking \"%s\": %s", lockfile
->filename
,
754 #elif defined(HAVE_FLOCK)
755 if (flock(lockfile
->fd
, LOCK_UN
) < 0) {
756 log_warn(LD_FS
, "Error unlocking \"%s\": %s", lockfile
->filename
,
760 /* Closing the lockfile is sufficient. */
765 tor_free(lockfile
->filename
);
769 /* Some old versions of Unix didn't define constants for these values,
770 * and instead expect you to say 0, 1, or 2. */
778 /** Return the position of <b>fd</b> with respect to the start of the file. */
780 tor_fd_getpos(int fd
)
783 return (off_t
) _lseek(fd
, 0, SEEK_CUR
);
785 return (off_t
) lseek(fd
, 0, SEEK_CUR
);
789 /** Move <b>fd</b> to the end of the file. Return -1 on error, 0 on success. */
791 tor_fd_seekend(int fd
)
794 return _lseek(fd
, 0, SEEK_END
) < 0 ? -1 : 0;
796 return lseek(fd
, 0, SEEK_END
) < 0 ? -1 : 0;
800 #undef DEBUG_SOCKET_COUNTING
801 #ifdef DEBUG_SOCKET_COUNTING
802 /** A bitarray of all fds that should be passed to tor_socket_close(). Only
803 * used if DEBUG_SOCKET_COUNTING is defined. */
804 static bitarray_t
*open_sockets
= NULL
;
805 /** The size of <b>open_sockets</b>, in bits. */
806 static int max_socket
= -1;
809 /** Count of number of sockets currently open. (Undercounts sockets opened by
810 * eventdns and libevent.) */
811 static int n_sockets_open
= 0;
813 /** Mutex to protect open_sockets, max_socket, and n_sockets_open. */
814 static tor_mutex_t
*socket_accounting_mutex
= NULL
;
817 socket_accounting_lock(void)
819 if (PREDICT_UNLIKELY(!socket_accounting_mutex
))
820 socket_accounting_mutex
= tor_mutex_new();
821 tor_mutex_acquire(socket_accounting_mutex
);
825 socket_accounting_unlock(void)
827 tor_mutex_release(socket_accounting_mutex
);
830 /** As close(), but guaranteed to work for sockets across platforms (including
831 * Windows, where close()ing a socket doesn't work. Returns 0 on success, -1
834 tor_close_socket(int s
)
838 /* On Windows, you have to call close() on fds returned by open(),
839 * and closesocket() on fds returned by socket(). On Unix, everything
840 * gets close()'d. We abstract this difference by always using
841 * tor_close_socket to close sockets, and always using close() on
844 #if defined(MS_WINDOWS)
850 socket_accounting_lock();
851 #ifdef DEBUG_SOCKET_COUNTING
852 if (s
> max_socket
|| ! bitarray_is_set(open_sockets
, s
)) {
853 log_warn(LD_BUG
, "Closing a socket (%d) that wasn't returned by tor_open_"
854 "socket(), or that was already closed or something.", s
);
856 tor_assert(open_sockets
&& s
<= max_socket
);
857 bitarray_clear(open_sockets
, s
);
863 int err
= tor_socket_errno(-1);
864 log_info(LD_NET
, "Close returned an error: %s", tor_socket_strerror(err
));
866 if (err
!= WSAENOTSOCK
)
875 if (n_sockets_open
< 0)
876 log_warn(LD_BUG
, "Our socket count is below zero: %d. Please submit a "
877 "bug report.", n_sockets_open
);
878 socket_accounting_unlock();
882 #ifdef DEBUG_SOCKET_COUNTING
883 /** Helper: if DEBUG_SOCKET_COUNTING is enabled, remember that <b>s</b> is
884 * now an open socket. */
886 mark_socket_open(int s
)
888 if (s
> max_socket
) {
889 if (max_socket
== -1) {
890 open_sockets
= bitarray_init_zero(s
+128);
893 open_sockets
= bitarray_expand(open_sockets
, max_socket
, s
+128);
897 if (bitarray_is_set(open_sockets
, s
)) {
898 log_warn(LD_BUG
, "I thought that %d was already open, but socket() just "
899 "gave it to me!", s
);
901 bitarray_set(open_sockets
, s
);
904 #define mark_socket_open(s) STMT_NIL
907 /** As socket(), but counts the number of open sockets. */
909 tor_open_socket(int domain
, int type
, int protocol
)
911 int s
= socket(domain
, type
, protocol
);
913 socket_accounting_lock();
916 socket_accounting_unlock();
921 /** As socket(), but counts the number of open sockets. */
923 tor_accept_socket(int sockfd
, struct sockaddr
*addr
, socklen_t
*len
)
925 int s
= accept(sockfd
, addr
, len
);
927 socket_accounting_lock();
930 socket_accounting_unlock();
935 /** Return the number of sockets we currently have opened. */
937 get_n_open_sockets(void)
940 socket_accounting_lock();
942 socket_accounting_unlock();
946 /** Turn <b>socket</b> into a nonblocking socket.
949 set_socket_nonblocking(int socket
)
951 #if defined(MS_WINDOWS)
952 unsigned long nonblocking
= 1;
953 ioctlsocket(socket
, FIONBIO
, (unsigned long*) &nonblocking
);
955 fcntl(socket
, F_SETFL
, O_NONBLOCK
);
960 * Allocate a pair of connected sockets. (Like socketpair(family,
961 * type,protocol,fd), but works on systems that don't have
964 * Currently, only (AF_UNIX, SOCK_STREAM, 0) sockets are supported.
966 * Note that on systems without socketpair, this call will fail if
967 * localhost is inaccessible (for example, if the networking
968 * stack is down). And even if it succeeds, the socket pair will not
969 * be able to read while localhost is down later (the socket pair may
970 * even close, depending on OS-specific timeouts).
972 * Returns 0 on success and -errno on failure; do not rely on the value
973 * of errno or WSAGetLastError().
975 /* It would be nicer just to set errno, but that won't work for windows. */
977 tor_socketpair(int family
, int type
, int protocol
, int fd
[2])
979 //don't use win32 socketpairs (they are always bad)
980 #if defined(HAVE_SOCKETPAIR) && !defined(MS_WINDOWS)
982 r
= socketpair(family
, type
, protocol
, fd
);
984 socket_accounting_lock();
987 mark_socket_open(fd
[0]);
991 mark_socket_open(fd
[1]);
993 socket_accounting_unlock();
995 return r
< 0 ? -errno
: r
;
997 /* This socketpair does not work when localhost is down. So
998 * it's really not the same thing at all. But it's close enough
999 * for now, and really, when localhost is down sometimes, we
1000 * have other problems too.
1005 struct sockaddr_in listen_addr
;
1006 struct sockaddr_in connect_addr
;
1008 int saved_errno
= -1;
1012 || family
!= AF_UNIX
1016 return -WSAEAFNOSUPPORT
;
1018 return -EAFNOSUPPORT
;
1025 listener
= tor_open_socket(AF_INET
, type
, 0);
1027 return -tor_socket_errno(-1);
1028 memset(&listen_addr
, 0, sizeof(listen_addr
));
1029 listen_addr
.sin_family
= AF_INET
;
1030 listen_addr
.sin_addr
.s_addr
= htonl(INADDR_LOOPBACK
);
1031 listen_addr
.sin_port
= 0; /* kernel chooses port. */
1032 if (bind(listener
, (struct sockaddr
*) &listen_addr
, sizeof (listen_addr
))
1034 goto tidy_up_and_fail
;
1035 if (listen(listener
, 1) == -1)
1036 goto tidy_up_and_fail
;
1038 connector
= tor_open_socket(AF_INET
, type
, 0);
1040 goto tidy_up_and_fail
;
1041 /* We want to find out the port number to connect to. */
1042 size
= sizeof(connect_addr
);
1043 if (getsockname(listener
, (struct sockaddr
*) &connect_addr
, &size
) == -1)
1044 goto tidy_up_and_fail
;
1045 if (size
!= sizeof (connect_addr
))
1046 goto abort_tidy_up_and_fail
;
1047 if (connect(connector
, (struct sockaddr
*) &connect_addr
,
1048 sizeof(connect_addr
)) == -1)
1049 goto tidy_up_and_fail
;
1051 size
= sizeof(listen_addr
);
1052 acceptor
= tor_accept_socket(listener
,
1053 (struct sockaddr
*) &listen_addr
, &size
);
1055 goto tidy_up_and_fail
;
1056 if (size
!= sizeof(listen_addr
))
1057 goto abort_tidy_up_and_fail
;
1058 tor_close_socket(listener
);
1059 /* Now check we are talking to ourself by matching port and host on the
1061 if (getsockname(connector
, (struct sockaddr
*) &connect_addr
, &size
) == -1)
1062 goto tidy_up_and_fail
;
1063 if (size
!= sizeof (connect_addr
)
1064 || listen_addr
.sin_family
!= connect_addr
.sin_family
1065 || listen_addr
.sin_addr
.s_addr
!= connect_addr
.sin_addr
.s_addr
1066 || listen_addr
.sin_port
!= connect_addr
.sin_port
) {
1067 goto abort_tidy_up_and_fail
;
1074 abort_tidy_up_and_fail
:
1076 saved_errno
= WSAECONNABORTED
;
1078 saved_errno
= ECONNABORTED
; /* I hope this is portable and appropriate. */
1081 if (saved_errno
< 0)
1082 saved_errno
= errno
;
1084 tor_close_socket(listener
);
1085 if (connector
!= -1)
1086 tor_close_socket(connector
);
1088 tor_close_socket(acceptor
);
1089 return -saved_errno
;
1093 #define ULIMIT_BUFFER 32 /* keep 32 extra fd's beyond _ConnLimit */
1095 /** Learn the maximum allowed number of file descriptors. (Some systems
1096 * have a low soft limit.
1098 * We compute this by finding the largest number that we can use.
1099 * If we can't find a number greater than or equal to <b>limit</b>,
1100 * then we fail: return -1.
1102 * Otherwise, return 0 and store the maximum we found inside <b>max_out</b>.*/
1104 set_max_file_descriptors(rlim_t limit
, int *max_out
)
1106 /* Define some maximum connections values for systems where we cannot
1107 * automatically determine a limit. Re Cygwin, see
1108 * http://archives.seul.org/or/talk/Aug-2006/msg00210.html
1109 * For an iPhone, 9999 should work. For Windows and all other unknown
1110 * systems we use 15000 as the default. */
1111 #ifndef HAVE_GETRLIMIT
1112 #if defined(CYGWIN) || defined(__CYGWIN__)
1113 const char *platform
= "Cygwin";
1114 const unsigned long MAX_CONNECTIONS
= 3200;
1115 #elif defined(MS_WINDOWS)
1116 const char *platform
= "Windows";
1117 const unsigned long MAX_CONNECTIONS
= 15000;
1119 const char *platform
= "unknown platforms with no getrlimit()";
1120 const unsigned long MAX_CONNECTIONS
= 15000;
1122 log_fn(LOG_INFO
, LD_NET
,
1123 "This platform is missing getrlimit(). Proceeding.");
1124 if (limit
> MAX_CONNECTIONS
) {
1126 "We do not support more than %lu file descriptors "
1127 "on %s. Tried to raise to %lu.",
1128 (unsigned long)MAX_CONNECTIONS
, platform
, (unsigned long)limit
);
1131 limit
= MAX_CONNECTIONS
;
1132 #else /* HAVE_GETRLIMIT */
1134 tor_assert(limit
> 0);
1136 if (getrlimit(RLIMIT_NOFILE
, &rlim
) != 0) {
1137 log_warn(LD_NET
, "Could not get maximum number of file descriptors: %s",
1142 if (rlim
.rlim_max
< limit
) {
1143 log_warn(LD_CONFIG
,"We need %lu file descriptors available, and we're "
1144 "limited to %lu. Please change your ulimit -n.",
1145 (unsigned long)limit
, (unsigned long)rlim
.rlim_max
);
1149 if (rlim
.rlim_max
> rlim
.rlim_cur
) {
1150 log_info(LD_NET
,"Raising max file descriptors from %lu to %lu.",
1151 (unsigned long)rlim
.rlim_cur
, (unsigned long)rlim
.rlim_max
);
1153 rlim
.rlim_cur
= rlim
.rlim_max
;
1155 if (setrlimit(RLIMIT_NOFILE
, &rlim
) != 0) {
1158 if (errno
== EINVAL
&& OPEN_MAX
< rlim
.rlim_cur
) {
1159 /* On some platforms, OPEN_MAX is the real limit, and getrlimit() is
1160 * full of nasty lies. I'm looking at you, OSX 10.5.... */
1161 rlim
.rlim_cur
= OPEN_MAX
;
1162 if (setrlimit(RLIMIT_NOFILE
, &rlim
) == 0) {
1163 if (rlim
.rlim_cur
< (rlim_t
)limit
) {
1164 log_warn(LD_CONFIG
, "We are limited to %lu file descriptors by "
1165 "OPEN_MAX, and ConnLimit is %lu. Changing ConnLimit; sorry.",
1166 (unsigned long)OPEN_MAX
, (unsigned long)limit
);
1168 log_info(LD_CONFIG
, "Dropped connection limit to OPEN_MAX (%lu); "
1169 "Apparently, %lu was too high and rlimit lied to us.",
1170 (unsigned long)OPEN_MAX
, (unsigned long)rlim
.rlim_max
);
1175 #endif /* OPEN_MAX */
1177 log_warn(LD_CONFIG
,"Couldn't set maximum number of file descriptors: %s",
1182 /* leave some overhead for logs, etc, */
1183 limit
= rlim
.rlim_cur
;
1184 #endif /* HAVE_GETRLIMIT */
1186 if (limit
< ULIMIT_BUFFER
) {
1188 "ConnLimit must be at least %d. Failing.", ULIMIT_BUFFER
);
1191 if (limit
> INT_MAX
)
1193 tor_assert(max_out
);
1194 *max_out
= (int)limit
- ULIMIT_BUFFER
;
1199 /** Log details of current user and group credentials. Return 0 on
1200 * success. Logs and return -1 on failure.
1203 log_credential_status(void)
1205 #define CREDENTIAL_LOG_LEVEL LOG_INFO
1206 /* Real, effective and saved UIDs */
1207 uid_t ruid
, euid
, suid
;
1208 /* Read, effective and saved GIDs */
1209 gid_t rgid
, egid
, sgid
;
1210 /* Supplementary groups */
1211 gid_t sup_gids
[NGROUPS_MAX
+ 1];
1212 /* Number of supplementary groups */
1216 #ifdef HAVE_GETRESUID
1217 if (getresuid(&ruid
, &euid
, &suid
) != 0 ) {
1218 log_warn(LD_GENERAL
, "Error getting changed UIDs: %s", strerror(errno
));
1221 log_fn(CREDENTIAL_LOG_LEVEL
, LD_GENERAL
,
1222 "UID is %u (real), %u (effective), %u (saved)",
1223 (unsigned)ruid
, (unsigned)euid
, (unsigned)suid
);
1226 /* getresuid is not present on MacOS X, so we can't get the saved (E)UID */
1231 log_fn(CREDENTIAL_LOG_LEVEL
, LD_GENERAL
,
1232 "UID is %u (real), %u (effective), unknown (saved)",
1233 (unsigned)ruid
, (unsigned)euid
);
1237 #ifdef HAVE_GETRESGID
1238 if (getresgid(&rgid
, &egid
, &sgid
) != 0 ) {
1239 log_warn(LD_GENERAL
, "Error getting changed GIDs: %s", strerror(errno
));
1242 log_fn(CREDENTIAL_LOG_LEVEL
, LD_GENERAL
,
1243 "GID is %u (real), %u (effective), %u (saved)",
1244 (unsigned)rgid
, (unsigned)egid
, (unsigned)sgid
);
1247 /* getresgid is not present on MacOS X, so we can't get the saved (E)GID */
1251 log_fn(CREDENTIAL_LOG_LEVEL
, LD_GENERAL
,
1252 "GID is %u (real), %u (effective), unknown (saved)",
1253 (unsigned)rgid
, (unsigned)egid
);
1256 /* log supplementary groups */
1257 if ((ngids
= getgroups(NGROUPS_MAX
+ 1, sup_gids
)) < 0) {
1258 log_warn(LD_GENERAL
, "Error getting supplementary GIDs: %s",
1265 smartlist_t
*elts
= smartlist_create();
1267 for (i
= 0; i
<ngids
; i
++) {
1268 strgid
= tor_malloc(11);
1269 if (tor_snprintf(strgid
, 11, "%u", (unsigned)sup_gids
[i
]) < 0) {
1270 log_warn(LD_GENERAL
, "Error printing supplementary GIDs");
1275 smartlist_add(elts
, strgid
);
1278 s
= smartlist_join_strings(elts
, " ", 0, NULL
);
1280 log_fn(CREDENTIAL_LOG_LEVEL
, LD_GENERAL
, "Supplementary groups are: %s",s
);
1284 SMARTLIST_FOREACH(elts
, char *, cp
,
1288 smartlist_free(elts
);
1297 /** Call setuid and setgid to run as <b>user</b> and switch to their
1298 * primary group. Return 0 on success. On failure, log and return -1.
1301 switch_id(const char *user
)
1304 struct passwd
*pw
= NULL
;
1307 static int have_already_switched_id
= 0;
1311 if (have_already_switched_id
)
1314 /* Log the initial credential state */
1315 if (log_credential_status())
1318 log_fn(CREDENTIAL_LOG_LEVEL
, LD_GENERAL
, "Changing user and groups");
1320 /* Get old UID/GID to check if we changed correctly */
1324 /* Lookup the user and group information, if we have a problem, bail out. */
1325 pw
= getpwnam(user
);
1327 log_warn(LD_CONFIG
, "Error setting configured user: %s not found", user
);
1331 /* Properly switch egid,gid,euid,uid here or bail out */
1332 if (setgroups(1, &pw
->pw_gid
)) {
1333 log_warn(LD_GENERAL
, "Error setting groups to gid %d: \"%s\".",
1334 (int)pw
->pw_gid
, strerror(errno
));
1335 if (old_uid
== pw
->pw_uid
) {
1336 log_warn(LD_GENERAL
, "Tor is already running as %s. You do not need "
1337 "the \"User\" option if you are already running as the user "
1338 "you want to be. (If you did not set the User option in your "
1339 "torrc, check whether it was specified on the command line "
1340 "by a startup script.)", user
);
1342 log_warn(LD_GENERAL
, "If you set the \"User\" option, you must start Tor"
1348 if (setegid(pw
->pw_gid
)) {
1349 log_warn(LD_GENERAL
, "Error setting egid to %d: %s",
1350 (int)pw
->pw_gid
, strerror(errno
));
1354 if (setgid(pw
->pw_gid
)) {
1355 log_warn(LD_GENERAL
, "Error setting gid to %d: %s",
1356 (int)pw
->pw_gid
, strerror(errno
));
1360 if (setuid(pw
->pw_uid
)) {
1361 log_warn(LD_GENERAL
, "Error setting configured uid to %s (%d): %s",
1362 user
, (int)pw
->pw_uid
, strerror(errno
));
1366 if (seteuid(pw
->pw_uid
)) {
1367 log_warn(LD_GENERAL
, "Error setting configured euid to %s (%d): %s",
1368 user
, (int)pw
->pw_uid
, strerror(errno
));
1372 /* This is how OpenBSD rolls:
1373 if (setgroups(1, &pw->pw_gid) || setegid(pw->pw_gid) ||
1374 setgid(pw->pw_gid) || setuid(pw->pw_uid) || seteuid(pw->pw_uid)) {
1375 setgid(pw->pw_gid) || seteuid(pw->pw_uid) || setuid(pw->pw_uid)) {
1376 log_warn(LD_GENERAL, "Error setting configured UID/GID: %s",
1382 /* We've properly switched egid, gid, euid, uid, and supplementary groups if
1385 #if !defined(CYGWIN) && !defined(__CYGWIN__)
1386 /* If we tried to drop privilege to a group/user other than root, attempt to
1387 * restore root (E)(U|G)ID, and abort if the operation succeeds */
1389 /* Only check for privilege dropping if we were asked to be non-root */
1391 /* Try changing GID/EGID */
1392 if (pw
->pw_gid
!= old_gid
&&
1393 (setgid(old_gid
) != -1 || setegid(old_gid
) != -1)) {
1394 log_warn(LD_GENERAL
, "Was able to restore group credentials even after "
1395 "switching GID: this means that the setgid code didn't work.");
1399 /* Try changing UID/EUID */
1400 if (pw
->pw_uid
!= old_uid
&&
1401 (setuid(old_uid
) != -1 || seteuid(old_uid
) != -1)) {
1402 log_warn(LD_GENERAL
, "Was able to restore user credentials even after "
1403 "switching UID: this means that the setuid code didn't work.");
1409 /* Check what really happened */
1410 if (log_credential_status()) {
1414 have_already_switched_id
= 1; /* mark success so we never try again */
1416 #if defined(__linux__) && defined(HAVE_SYS_PRCTL_H) && defined(HAVE_PRCTL)
1417 #ifdef PR_SET_DUMPABLE
1419 /* Re-enable core dumps if we're not running as root. */
1420 log_info(LD_CONFIG
, "Re-enabling coredumps");
1421 if (prctl(PR_SET_DUMPABLE
, 1)) {
1422 log_warn(LD_CONFIG
, "Unable to re-enable coredumps: %s",strerror(errno
));
1433 "User specified but switching users is unsupported on your OS.");
1439 /** Allocate and return a string containing the home directory for the
1440 * user <b>username</b>. Only works on posix-like systems. */
1442 get_user_homedir(const char *username
)
1445 tor_assert(username
);
1447 if (!(pw
= getpwnam(username
))) {
1448 log_err(LD_CONFIG
,"User \"%s\" not found.", username
);
1451 return tor_strdup(pw
->pw_dir
);
1455 /** Set *addr to the IP address (in dotted-quad notation) stored in c.
1456 * Return 1 on success, 0 if c is badly formatted. (Like inet_aton(c,addr),
1457 * but works on Windows and Solaris.)
1460 tor_inet_aton(const char *str
, struct in_addr
* addr
)
1464 if (tor_sscanf(str
, "%3u.%3u.%3u.%3u%c", &a
,&b
,&c
,&d
,&more
) != 4)
1466 if (a
> 255) return 0;
1467 if (b
> 255) return 0;
1468 if (c
> 255) return 0;
1469 if (d
> 255) return 0;
1470 addr
->s_addr
= htonl((a
<<24) | (b
<<16) | (c
<<8) | d
);
1474 /** Given <b>af</b>==AF_INET and <b>src</b> a struct in_addr, or
1475 * <b>af</b>==AF_INET6 and <b>src</b> a struct in6_addr, try to format the
1476 * address and store it in the <b>len</b>-byte buffer <b>dst</b>. Returns
1477 * <b>dst</b> on success, NULL on failure.
1479 * (Like inet_ntop(af,src,dst,len), but works on platforms that don't have it:
1480 * Tor sometimes needs to format ipv6 addresses even on platforms without ipv6
1483 tor_inet_ntop(int af
, const void *src
, char *dst
, size_t len
)
1485 if (af
== AF_INET
) {
1486 if (tor_inet_ntoa(src
, dst
, len
) < 0)
1490 } else if (af
== AF_INET6
) {
1491 const struct in6_addr
*addr
= src
;
1493 int longestGapLen
= 0, longestGapPos
= -1, i
,
1494 curGapPos
= -1, curGapLen
= 0;
1496 for (i
= 0; i
< 8; ++i
) {
1497 words
[i
] = (((uint16_t)addr
->s6_addr
[2*i
])<<8) + addr
->s6_addr
[2*i
+1];
1499 if (words
[0] == 0 && words
[1] == 0 && words
[2] == 0 && words
[3] == 0 &&
1500 words
[4] == 0 && ((words
[5] == 0 && words
[6] && words
[7]) ||
1501 (words
[5] == 0xffff))) {
1502 /* This is an IPv4 address. */
1503 if (words
[5] == 0) {
1504 tor_snprintf(buf
, sizeof(buf
), "::%d.%d.%d.%d",
1505 addr
->s6_addr
[12], addr
->s6_addr
[13],
1506 addr
->s6_addr
[14], addr
->s6_addr
[15]);
1508 tor_snprintf(buf
, sizeof(buf
), "::%x:%d.%d.%d.%d", words
[5],
1509 addr
->s6_addr
[12], addr
->s6_addr
[13],
1510 addr
->s6_addr
[14], addr
->s6_addr
[15]);
1512 if (strlen(buf
) > len
)
1514 strlcpy(dst
, buf
, len
);
1519 if (words
[i
] == 0) {
1522 while (i
<8 && words
[i
] == 0) {
1525 if (curGapLen
> longestGapLen
) {
1526 longestGapPos
= curGapPos
;
1527 longestGapLen
= curGapLen
;
1533 if (longestGapLen
<=1)
1537 for (i
= 0; i
< 8; ++i
) {
1538 if (words
[i
] == 0 && longestGapPos
== i
) {
1542 while (i
< 8 && words
[i
] == 0)
1544 --i
; /* to compensate for loop increment. */
1546 tor_snprintf(cp
, sizeof(buf
)-(cp
-buf
), "%x", (unsigned)words
[i
]);
1553 if (strlen(buf
) > len
)
1555 strlcpy(dst
, buf
, len
);
1562 /** Given <b>af</b>==AF_INET or <b>af</b>==AF_INET6, and a string <b>src</b>
1563 * encoding an IPv4 address or IPv6 address correspondingly, try to parse the
1564 * address and store the result in <b>dst</b> (which must have space for a
1565 * struct in_addr or a struct in6_addr, as appropriate). Return 1 on success,
1566 * 0 on a bad parse, and -1 on a bad <b>af</b>.
1568 * (Like inet_pton(af,src,dst) but works on platforms that don't have it: Tor
1569 * sometimes needs to format ipv6 addresses even on platforms without ipv6
1572 tor_inet_pton(int af
, const char *src
, void *dst
)
1574 if (af
== AF_INET
) {
1575 return tor_inet_aton(src
, dst
);
1576 } else if (af
== AF_INET6
) {
1577 struct in6_addr
*out
= dst
;
1579 int gapPos
= -1, i
, setWords
=0;
1580 const char *dot
= strchr(src
, '.');
1581 const char *eow
; /* end of words. */
1585 eow
= src
+strlen(src
);
1587 unsigned byte1
,byte2
,byte3
,byte4
;
1589 for (eow
= dot
-1; eow
>= src
&& TOR_ISDIGIT(*eow
); --eow
)
1593 /* We use "scanf" because some platform inet_aton()s are too lax
1594 * about IPv4 addresses of the form "1.2.3" */
1595 if (tor_sscanf(eow
, "%3u.%3u.%3u.%3u%c",
1596 &byte1
,&byte2
,&byte3
,&byte4
,&more
) != 4)
1599 if (byte1
> 255 || byte2
> 255 || byte3
> 255 || byte4
> 255)
1602 words
[6] = (byte1
<<8) | byte2
;
1603 words
[7] = (byte3
<<8) | byte4
;
1611 if (TOR_ISXDIGIT(*src
)) {
1613 long r
= strtol(src
, &next
, 16);
1621 words
[i
++] = (uint16_t)r
;
1624 if (*src
!= ':' && src
!= eow
)
1627 } else if (*src
== ':' && i
> 0 && gapPos
==-1) {
1630 } else if (*src
== ':' && i
== 0 && src
[1] == ':' && gapPos
==-1) {
1639 (setWords
== 8 && gapPos
!= -1) ||
1640 (setWords
< 8 && gapPos
== -1))
1644 int nToMove
= setWords
- (dot
? 2 : 0) - gapPos
;
1645 int gapLen
= 8 - setWords
;
1646 tor_assert(nToMove
>= 0);
1647 memmove(&words
[gapPos
+gapLen
], &words
[gapPos
],
1648 sizeof(uint16_t)*nToMove
);
1649 memset(&words
[gapPos
], 0, sizeof(uint16_t)*gapLen
);
1651 for (i
= 0; i
< 8; ++i
) {
1652 out
->s6_addr
[2*i
] = words
[i
] >> 8;
1653 out
->s6_addr
[2*i
+1] = words
[i
] & 0xff;
1662 /** Similar behavior to Unix gethostbyname: resolve <b>name</b>, and set
1663 * *<b>addr</b> to the proper IP address, in host byte order. Returns 0
1664 * on success, -1 on failure; 1 on transient failure.
1666 * (This function exists because standard windows gethostbyname
1667 * doesn't treat raw IP addresses properly.)
1670 tor_lookup_hostname(const char *name
, uint32_t *addr
)
1675 if ((ret
= tor_addr_lookup(name
, AF_INET
, &myaddr
)))
1678 if (tor_addr_family(&myaddr
) == AF_INET
) {
1679 *addr
= tor_addr_to_ipv4h(&myaddr
);
1686 /** Initialize the insecure libc RNG. */
1688 tor_init_weak_random(unsigned seed
)
1697 /** Return a randomly chosen value in the range 0..TOR_RAND_MAX. This
1698 * entropy will not be cryptographically strong; do not rely on it
1699 * for anything an adversary should not be able to predict. */
1701 tor_weak_random(void)
1710 /** Hold the result of our call to <b>uname</b>. */
1711 static char uname_result
[256];
1712 /** True iff uname_result is set. */
1713 static int uname_result_is_set
= 0;
1715 /** Return a pointer to a description of our platform.
1723 if (!uname_result_is_set
) {
1725 if (uname(&u
) != -1) {
1726 /* (Linux says 0 is success, Solaris says 1 is success) */
1727 tor_snprintf(uname_result
, sizeof(uname_result
), "%s %s",
1728 u
.sysname
, u
.machine
);
1733 OSVERSIONINFOEX info
;
1735 const char *plat
= NULL
;
1736 const char *extra
= NULL
;
1737 char acsd
[MAX_PATH
] = {0};
1739 unsigned major
; unsigned minor
; const char *version
;
1740 } win_version_table
[] = {
1741 { 6, 1, "Windows 7" },
1742 { 6, 0, "Windows Vista" },
1743 { 5, 2, "Windows Server 2003" },
1744 { 5, 1, "Windows XP" },
1745 { 5, 0, "Windows 2000" },
1746 /* { 4, 0, "Windows NT 4.0" }, */
1747 { 4, 90, "Windows Me" },
1748 { 4, 10, "Windows 98" },
1749 /* { 4, 0, "Windows 95" } */
1750 { 3, 51, "Windows NT 3.51" },
1753 memset(&info
, 0, sizeof(info
));
1754 info
.dwOSVersionInfoSize
= sizeof(info
);
1755 if (! GetVersionEx((LPOSVERSIONINFO
)&info
)) {
1756 strlcpy(uname_result
, "Bizarre version of Windows where GetVersionEx"
1757 " doesn't work.", sizeof(uname_result
));
1758 uname_result_is_set
= 1;
1759 return uname_result
;
1762 wcstombs(acsd
, info
.szCSDVersion
, MAX_PATH
);
1764 strlcpy(acsd
, info
.szCSDVersion
, sizeof(acsd
));
1766 if (info
.dwMajorVersion
== 4 && info
.dwMinorVersion
== 0) {
1767 if (info
.dwPlatformId
== VER_PLATFORM_WIN32_NT
)
1768 plat
= "Windows NT 4.0";
1770 plat
= "Windows 95";
1773 else if (acsd
[1] == 'C')
1776 for (i
=0; win_version_table
[i
].major
>0; ++i
) {
1777 if (win_version_table
[i
].major
== info
.dwMajorVersion
&&
1778 win_version_table
[i
].minor
== info
.dwMinorVersion
) {
1779 plat
= win_version_table
[i
].version
;
1784 if (plat
&& !strcmp(plat
, "Windows 98")) {
1787 else if (acsd
[1] == 'B')
1793 tor_snprintf(uname_result
, sizeof(uname_result
), "%s %s",
1796 if (info
.dwMajorVersion
> 6 ||
1797 (info
.dwMajorVersion
==6 && info
.dwMinorVersion
>1))
1798 tor_snprintf(uname_result
, sizeof(uname_result
),
1799 "Very recent version of Windows [major=%d,minor=%d] %s",
1800 (int)info
.dwMajorVersion
,(int)info
.dwMinorVersion
,
1803 tor_snprintf(uname_result
, sizeof(uname_result
),
1804 "Unrecognized version of Windows [major=%d,minor=%d] %s",
1805 (int)info
.dwMajorVersion
,(int)info
.dwMinorVersion
,
1808 #if !defined (WINCE)
1809 #ifdef VER_SUITE_BACKOFFICE
1810 if (info
.wProductType
== VER_NT_DOMAIN_CONTROLLER
) {
1811 strlcat(uname_result
, " [domain controller]", sizeof(uname_result
));
1812 } else if (info
.wProductType
== VER_NT_SERVER
) {
1813 strlcat(uname_result
, " [server]", sizeof(uname_result
));
1814 } else if (info
.wProductType
== VER_NT_WORKSTATION
) {
1815 strlcat(uname_result
, " [workstation]", sizeof(uname_result
));
1820 strlcpy(uname_result
, "Unknown platform", sizeof(uname_result
));
1823 uname_result_is_set
= 1;
1825 return uname_result
;
1832 #if defined(USE_PTHREADS)
1833 /** Wraps a void (*)(void*) function and its argument so we can
1834 * invoke them in a way pthreads would expect.
1836 typedef struct tor_pthread_data_t
{
1837 void (*func
)(void *);
1839 } tor_pthread_data_t
;
1840 /** Given a tor_pthread_data_t <b>_data</b>, call _data->func(d->data)
1841 * and free _data. Used to make sure we can call functions the way pthread
1844 tor_pthread_helper_fn(void *_data
)
1846 tor_pthread_data_t
*data
= _data
;
1847 void (*func
)(void*);
1849 /* mask signals to worker threads to avoid SIGPIPE, etc */
1851 /* We're in a subthread; don't handle any signals here. */
1853 pthread_sigmask(SIG_SETMASK
, &sigs
, NULL
);
1863 /** Minimalist interface to run a void function in the background. On
1864 * Unix calls fork, on win32 calls beginthread. Returns -1 on failure.
1865 * func should not return, but rather should call spawn_exit.
1867 * NOTE: if <b>data</b> is used, it should not be allocated on the stack,
1868 * since in a multithreaded environment, there is no way to be sure that
1869 * the caller's stack will still be around when the called function is
1873 spawn_func(void (*func
)(void *), void *data
)
1875 #if defined(USE_WIN32_THREADS)
1877 rv
= (int)_beginthread(func
, 0, data
);
1881 #elif defined(USE_PTHREADS)
1883 tor_pthread_data_t
*d
;
1884 d
= tor_malloc(sizeof(tor_pthread_data_t
));
1887 if (pthread_create(&thread
,NULL
,tor_pthread_helper_fn
,d
))
1889 if (pthread_detach(thread
))
1900 tor_assert(0); /* Should never reach here. */
1901 return 0; /* suppress "control-reaches-end-of-non-void" warning. */
1909 /** End the current thread/process.
1914 #if defined(USE_WIN32_THREADS)
1916 //we should never get here. my compiler thinks that _endthread returns, this
1917 //is an attempt to fool it.
1920 #elif defined(USE_PTHREADS)
1923 /* http://www.erlenstar.demon.co.uk/unix/faq_2.html says we should
1924 * call _exit, not exit, from child processes. */
1929 /** Set *timeval to the current time of day. On error, log and terminate.
1930 * (Same as gettimeofday(timeval,NULL), but never returns -1.)
1933 tor_gettimeofday(struct timeval
*timeval
)
1936 /* Epoch bias copied from perl: number of units between windows epoch and
1938 #define EPOCH_BIAS U64_LITERAL(116444736000000000)
1939 #define UNITS_PER_SEC U64_LITERAL(10000000)
1940 #define USEC_PER_SEC U64_LITERAL(1000000)
1941 #define UNITS_PER_USEC U64_LITERAL(10)
1947 /* wince do not have GetSystemTimeAsFileTime */
1949 GetSystemTime(&stime
);
1950 SystemTimeToFileTime(&stime
,&ft
.ft_ft
);
1952 /* number of 100-nsec units since Jan 1, 1601 */
1953 GetSystemTimeAsFileTime(&ft
.ft_ft
);
1955 if (ft
.ft_64
< EPOCH_BIAS
) {
1956 log_err(LD_GENERAL
,"System time is before 1970; failing.");
1959 ft
.ft_64
-= EPOCH_BIAS
;
1960 timeval
->tv_sec
= (unsigned) (ft
.ft_64
/ UNITS_PER_SEC
);
1961 timeval
->tv_usec
= (unsigned) ((ft
.ft_64
/ UNITS_PER_USEC
) % USEC_PER_SEC
);
1962 #elif defined(HAVE_GETTIMEOFDAY)
1963 if (gettimeofday(timeval
, NULL
)) {
1964 log_err(LD_GENERAL
,"gettimeofday failed.");
1965 /* If gettimeofday dies, we have either given a bad timezone (we didn't),
1969 #elif defined(HAVE_FTIME)
1972 timeval
->tv_sec
= tb
.time
;
1973 timeval
->tv_usec
= tb
.millitm
* 1000;
1975 #error "No way to get time."
1980 #if defined(TOR_IS_MULTITHREADED) && !defined(MS_WINDOWS)
1981 /** Defined iff we need to add locks when defining fake versions of reentrant
1982 * versions of time-related functions. */
1983 #define TIME_FNS_NEED_LOCKS
1986 #ifndef HAVE_LOCALTIME_R
1987 #ifdef TIME_FNS_NEED_LOCKS
1989 tor_localtime_r(const time_t *timep
, struct tm
*result
)
1992 static tor_mutex_t
*m
=NULL
;
1993 if (!m
) { m
=tor_mutex_new(); }
1995 tor_mutex_acquire(m
);
1996 r
= localtime(timep
);
1997 memcpy(result
, r
, sizeof(struct tm
));
1998 tor_mutex_release(m
);
2003 tor_localtime_r(const time_t *timep
, struct tm
*result
)
2007 r
= localtime(timep
);
2008 memcpy(result
, r
, sizeof(struct tm
));
2014 #ifndef HAVE_GMTIME_R
2015 #ifdef TIME_FNS_NEED_LOCKS
2017 tor_gmtime_r(const time_t *timep
, struct tm
*result
)
2020 static tor_mutex_t
*m
=NULL
;
2021 if (!m
) { m
=tor_mutex_new(); }
2023 tor_mutex_acquire(m
);
2025 memcpy(result
, r
, sizeof(struct tm
));
2026 tor_mutex_release(m
);
2031 tor_gmtime_r(const time_t *timep
, struct tm
*result
)
2036 memcpy(result
, r
, sizeof(struct tm
));
2042 #if defined(USE_WIN32_THREADS)
2044 tor_mutex_init(tor_mutex_t
*m
)
2046 InitializeCriticalSection(&m
->mutex
);
2049 tor_mutex_uninit(tor_mutex_t
*m
)
2051 DeleteCriticalSection(&m
->mutex
);
2054 tor_mutex_acquire(tor_mutex_t
*m
)
2057 EnterCriticalSection(&m
->mutex
);
2060 tor_mutex_release(tor_mutex_t
*m
)
2062 LeaveCriticalSection(&m
->mutex
);
2065 tor_get_thread_id(void)
2067 return (unsigned long)GetCurrentThreadId();
2069 #elif defined(USE_PTHREADS)
2070 /** A mutex attribute that we're going to use to tell pthreads that we want
2071 * "reentrant" mutexes (i.e., once we can re-lock if we're already holding
2073 static pthread_mutexattr_t attr_reentrant
;
2074 /** True iff we've called tor_threads_init() */
2075 static int threads_initialized
= 0;
2076 /** Initialize <b>mutex</b> so it can be locked. Every mutex must be set
2077 * up with tor_mutex_init() or tor_mutex_new(); not both. */
2079 tor_mutex_init(tor_mutex_t
*mutex
)
2082 if (PREDICT_UNLIKELY(!threads_initialized
))
2084 err
= pthread_mutex_init(&mutex
->mutex
, &attr_reentrant
);
2085 if (PREDICT_UNLIKELY(err
)) {
2086 log_err(LD_GENERAL
, "Error %d creating a mutex.", err
);
2087 tor_fragile_assert();
2090 /** Wait until <b>m</b> is free, then acquire it. */
2092 tor_mutex_acquire(tor_mutex_t
*m
)
2096 err
= pthread_mutex_lock(&m
->mutex
);
2097 if (PREDICT_UNLIKELY(err
)) {
2098 log_err(LD_GENERAL
, "Error %d locking a mutex.", err
);
2099 tor_fragile_assert();
2102 /** Release the lock <b>m</b> so another thread can have it. */
2104 tor_mutex_release(tor_mutex_t
*m
)
2108 err
= pthread_mutex_unlock(&m
->mutex
);
2109 if (PREDICT_UNLIKELY(err
)) {
2110 log_err(LD_GENERAL
, "Error %d unlocking a mutex.", err
);
2111 tor_fragile_assert();
2114 /** Clean up the mutex <b>m</b> so that it no longer uses any system
2115 * resources. Does not free <b>m</b>. This function must only be called on
2116 * mutexes from tor_mutex_init(). */
2118 tor_mutex_uninit(tor_mutex_t
*m
)
2122 err
= pthread_mutex_destroy(&m
->mutex
);
2123 if (PREDICT_UNLIKELY(err
)) {
2124 log_err(LD_GENERAL
, "Error %d destroying a mutex.", err
);
2125 tor_fragile_assert();
2128 /** Return an integer representing this thread. */
2130 tor_get_thread_id(void)
2136 r
.thr
= pthread_self();
2141 #ifdef TOR_IS_MULTITHREADED
2142 /** Return a newly allocated, ready-for-use mutex. */
2146 tor_mutex_t
*m
= tor_malloc_zero(sizeof(tor_mutex_t
));
2150 /** Release all storage and system resources held by <b>m</b>. */
2152 tor_mutex_free(tor_mutex_t
*m
)
2156 tor_mutex_uninit(m
);
2164 /** Cross-platform condition implementation. */
2166 pthread_cond_t cond
;
2168 /** Return a newly allocated condition, with nobody waiting on it. */
2172 tor_cond_t
*cond
= tor_malloc_zero(sizeof(tor_cond_t
));
2173 if (pthread_cond_init(&cond
->cond
, NULL
)) {
2179 /** Release all resources held by <b>cond</b>. */
2181 tor_cond_free(tor_cond_t
*cond
)
2185 if (pthread_cond_destroy(&cond
->cond
)) {
2186 log_warn(LD_GENERAL
,"Error freeing condition: %s", strerror(errno
));
2191 /** Wait until one of the tor_cond_signal functions is called on <b>cond</b>.
2192 * All waiters on the condition must wait holding the same <b>mutex</b>.
2193 * Returns 0 on success, negative on failure. */
2195 tor_cond_wait(tor_cond_t
*cond
, tor_mutex_t
*mutex
)
2197 return pthread_cond_wait(&cond
->cond
, &mutex
->mutex
) ? -1 : 0;
2199 /** Wake up one of the waiters on <b>cond</b>. */
2201 tor_cond_signal_one(tor_cond_t
*cond
)
2203 pthread_cond_signal(&cond
->cond
);
2205 /** Wake up all of the waiters on <b>cond</b>. */
2207 tor_cond_signal_all(tor_cond_t
*cond
)
2209 pthread_cond_broadcast(&cond
->cond
);
2212 /** Set up common structures for use by threading. */
2214 tor_threads_init(void)
2216 if (!threads_initialized
) {
2217 pthread_mutexattr_init(&attr_reentrant
);
2218 pthread_mutexattr_settype(&attr_reentrant
, PTHREAD_MUTEX_RECURSIVE
);
2219 threads_initialized
= 1;
2223 #elif defined(USE_WIN32_THREADS)
2225 static DWORD cond_event_tls_index
;
2227 CRITICAL_SECTION mutex
;
2228 smartlist_t
*events
;
2233 tor_cond_t
*cond
= tor_malloc_zero(sizeof(tor_cond_t
));
2234 InitializeCriticalSection(&cond
->mutex
);
2235 cond
->events
= smartlist_create();
2239 tor_cond_free(tor_cond_t
*cond
)
2243 DeleteCriticalSection(&cond
->mutex
);
2245 smartlist_free(cond
->events
);
2249 tor_cond_wait(tor_cond_t
*cond
, tor_mutex_t
*mutex
)
2255 event
= TlsGetValue(cond_event_tls_index
);
2257 event
= CreateEvent(0, FALSE
, FALSE
, NULL
);
2258 TlsSetValue(cond_event_tls_index
, event
);
2260 EnterCriticalSection(&cond
->mutex
);
2262 tor_assert(WaitForSingleObject(event
, 0) == WAIT_TIMEOUT
);
2263 tor_assert(!smartlist_isin(cond
->events
, event
));
2264 smartlist_add(cond
->events
, event
);
2266 LeaveCriticalSection(&cond
->mutex
);
2268 tor_mutex_release(mutex
);
2269 r
= WaitForSingleObject(event
, INFINITE
);
2270 tor_mutex_acquire(mutex
);
2273 case WAIT_OBJECT_0
: /* we got the mutex normally. */
2275 case WAIT_ABANDONED
: /* holding thread exited. */
2276 case WAIT_TIMEOUT
: /* Should never happen. */
2280 log_warn(LD_GENERAL
, "Failed to acquire mutex: %d",(int) GetLastError());
2285 tor_cond_signal_one(tor_cond_t
*cond
)
2290 EnterCriticalSection(&cond
->mutex
);
2292 if ((event
= smartlist_pop_last(cond
->events
)))
2295 LeaveCriticalSection(&cond
->mutex
);
2298 tor_cond_signal_all(tor_cond_t
*cond
)
2302 EnterCriticalSection(&cond
->mutex
);
2303 SMARTLIST_FOREACH(cond
->events
, HANDLE
, event
, SetEvent(event
));
2304 smartlist_clear(cond
->events
);
2305 LeaveCriticalSection(&cond
->mutex
);
2309 tor_threads_init(void)
2312 cond_event_tls_index
= TlsAlloc();
2318 #if defined(HAVE_MLOCKALL) && HAVE_DECL_MLOCKALL && defined(RLIMIT_MEMLOCK)
2319 /** Attempt to raise the current and max rlimit to infinity for our process.
2320 * This only needs to be done once and can probably only be done when we have
2321 * not already dropped privileges.
2324 tor_set_max_memlock(void)
2326 /* Future consideration for Windows is probably SetProcessWorkingSetSize
2327 * This is similar to setting the memory rlimit of RLIMIT_MEMLOCK
2328 * http://msdn.microsoft.com/en-us/library/ms686234(VS.85).aspx
2331 struct rlimit limit
;
2333 /* RLIM_INFINITY is -1 on some platforms. */
2334 limit
.rlim_cur
= RLIM_INFINITY
;
2335 limit
.rlim_max
= RLIM_INFINITY
;
2337 if (setrlimit(RLIMIT_MEMLOCK
, &limit
) == -1) {
2338 if (errno
== EPERM
) {
2339 log_warn(LD_GENERAL
, "You appear to lack permissions to change memory "
2340 "limits. Are you root?");
2342 log_warn(LD_GENERAL
, "Unable to raise RLIMIT_MEMLOCK: %s",
2351 /** Attempt to lock all current and all future memory pages.
2352 * This should only be called once and while we're privileged.
2353 * Like mlockall() we return 0 when we're successful and -1 when we're not.
2354 * Unlike mlockall() we return 1 if we've already attempted to lock memory.
2359 static int memory_lock_attempted
= 0;
2361 if (memory_lock_attempted
) {
2365 memory_lock_attempted
= 1;
2368 * Future consideration for Windows may be VirtualLock
2369 * VirtualLock appears to implement mlock() but not mlockall()
2371 * http://msdn.microsoft.com/en-us/library/aa366895(VS.85).aspx
2374 #if defined(HAVE_MLOCKALL) && HAVE_DECL_MLOCKALL && defined(RLIMIT_MEMLOCK)
2375 if (tor_set_max_memlock() == 0) {
2376 log_debug(LD_GENERAL
, "RLIMIT_MEMLOCK is now set to RLIM_INFINITY.");
2379 if (mlockall(MCL_CURRENT
|MCL_FUTURE
) == 0) {
2380 log_info(LD_GENERAL
, "Insecure OS paging is effectively disabled.");
2383 if (errno
== ENOSYS
) {
2384 /* Apple - it's 2009! I'm looking at you. Grrr. */
2385 log_notice(LD_GENERAL
, "It appears that mlockall() is not available on "
2387 } else if (errno
== EPERM
) {
2388 log_notice(LD_GENERAL
, "It appears that you lack the permissions to "
2389 "lock memory. Are you root?");
2391 log_notice(LD_GENERAL
, "Unable to lock all current and future memory "
2392 "pages: %s", strerror(errno
));
2396 log_warn(LD_GENERAL
, "Unable to lock memory pages. mlockall() unsupported?");
2401 /** Identity of the "main" thread */
2402 static unsigned long main_thread_id
= -1;
2404 /** Start considering the current thread to be the 'main thread'. This has
2405 * no effect on anything besides in_main_thread(). */
2407 set_main_thread(void)
2409 main_thread_id
= tor_get_thread_id();
2411 /** Return true iff called from the main thread. */
2413 in_main_thread(void)
2415 return main_thread_id
== tor_get_thread_id();
2419 * On Windows, WSAEWOULDBLOCK is not always correct: when you see it,
2420 * you need to ask the socket for its actual errno. Also, you need to
2421 * get your errors from WSAGetLastError, not errno. (If you supply a
2422 * socket of -1, we check WSAGetLastError, but don't correct
2425 * The upshot of all of this is that when a socket call fails, you
2426 * should call tor_socket_errno <em>at most once</em> on the failing
2427 * socket to get the error.
2429 #if defined(MS_WINDOWS)
2431 tor_socket_errno(int sock
)
2433 int optval
, optvallen
=sizeof(optval
);
2434 int err
= WSAGetLastError();
2435 if (err
== WSAEWOULDBLOCK
&& sock
>= 0) {
2436 if (getsockopt(sock
, SOL_SOCKET
, SO_ERROR
, (void*)&optval
, &optvallen
))
2445 #if defined(MS_WINDOWS)
2446 #define E(code, s) { code, (s " [" #code " ]") }
2447 struct { int code
; const char *msg
; } windows_socket_errors
[] = {
2448 E(WSAEINTR
, "Interrupted function call"),
2449 E(WSAEACCES
, "Permission denied"),
2450 E(WSAEFAULT
, "Bad address"),
2451 E(WSAEINVAL
, "Invalid argument"),
2452 E(WSAEMFILE
, "Too many open files"),
2453 E(WSAEWOULDBLOCK
, "Resource temporarily unavailable"),
2454 E(WSAEINPROGRESS
, "Operation now in progress"),
2455 E(WSAEALREADY
, "Operation already in progress"),
2456 E(WSAENOTSOCK
, "Socket operation on nonsocket"),
2457 E(WSAEDESTADDRREQ
, "Destination address required"),
2458 E(WSAEMSGSIZE
, "Message too long"),
2459 E(WSAEPROTOTYPE
, "Protocol wrong for socket"),
2460 E(WSAENOPROTOOPT
, "Bad protocol option"),
2461 E(WSAEPROTONOSUPPORT
, "Protocol not supported"),
2462 E(WSAESOCKTNOSUPPORT
, "Socket type not supported"),
2463 /* What's the difference between NOTSUPP and NOSUPPORT? :) */
2464 E(WSAEOPNOTSUPP
, "Operation not supported"),
2465 E(WSAEPFNOSUPPORT
, "Protocol family not supported"),
2466 E(WSAEAFNOSUPPORT
, "Address family not supported by protocol family"),
2467 E(WSAEADDRINUSE
, "Address already in use"),
2468 E(WSAEADDRNOTAVAIL
, "Cannot assign requested address"),
2469 E(WSAENETDOWN
, "Network is down"),
2470 E(WSAENETUNREACH
, "Network is unreachable"),
2471 E(WSAENETRESET
, "Network dropped connection on reset"),
2472 E(WSAECONNABORTED
, "Software caused connection abort"),
2473 E(WSAECONNRESET
, "Connection reset by peer"),
2474 E(WSAENOBUFS
, "No buffer space available"),
2475 E(WSAEISCONN
, "Socket is already connected"),
2476 E(WSAENOTCONN
, "Socket is not connected"),
2477 E(WSAESHUTDOWN
, "Cannot send after socket shutdown"),
2478 E(WSAETIMEDOUT
, "Connection timed out"),
2479 E(WSAECONNREFUSED
, "Connection refused"),
2480 E(WSAEHOSTDOWN
, "Host is down"),
2481 E(WSAEHOSTUNREACH
, "No route to host"),
2482 E(WSAEPROCLIM
, "Too many processes"),
2483 /* Yes, some of these start with WSA, not WSAE. No, I don't know why. */
2484 E(WSASYSNOTREADY
, "Network subsystem is unavailable"),
2485 E(WSAVERNOTSUPPORTED
, "Winsock.dll out of range"),
2486 E(WSANOTINITIALISED
, "Successful WSAStartup not yet performed"),
2487 E(WSAEDISCON
, "Graceful shutdown now in progress"),
2488 #ifdef WSATYPE_NOT_FOUND
2489 E(WSATYPE_NOT_FOUND
, "Class type not found"),
2491 E(WSAHOST_NOT_FOUND
, "Host not found"),
2492 E(WSATRY_AGAIN
, "Nonauthoritative host not found"),
2493 E(WSANO_RECOVERY
, "This is a nonrecoverable error"),
2494 E(WSANO_DATA
, "Valid name, no data record of requested type)"),
2496 /* There are some more error codes whose numeric values are marked
2497 * <b>OS dependent</b>. They start with WSA_, apparently for the same
2498 * reason that practitioners of some craft traditions deliberately
2499 * introduce imperfections into their baskets and rugs "to allow the
2500 * evil spirits to escape." If we catch them, then our binaries
2501 * might not report consistent results across versions of Windows.
2502 * Thus, I'm going to let them all fall through.
2506 /** There does not seem to be a strerror equivalent for Winsock errors.
2507 * Naturally, we have to roll our own.
2510 tor_socket_strerror(int e
)
2513 for (i
=0; windows_socket_errors
[i
].code
>= 0; ++i
) {
2514 if (e
== windows_socket_errors
[i
].code
)
2515 return windows_socket_errors
[i
].msg
;
2521 /** Called before we make any calls to network-related functions.
2522 * (Some operating systems require their network libraries to be
2528 /* This silly exercise is necessary before windows will allow
2529 * gethostbyname to work. */
2532 r
= WSAStartup(0x101,&WSAData
);
2534 log_warn(LD_NET
,"Error initializing windows network layer: code was %d",r
);
2537 /* WSAData.iMaxSockets might show the max sockets we're allowed to use.
2538 * We might use it to complain if we're trying to be a server but have
2539 * too few sockets available. */
2545 /** Return a newly allocated string describing the windows system error code
2546 * <b>err</b>. Note that error codes are different from errno. Error codes
2547 * come from GetLastError() when a winapi call fails. errno is set only when
2548 * ANSI functions fail. Whee. */
2550 format_win32_error(DWORD err
)
2555 /* Somebody once decided that this interface was better than strerror(). */
2556 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
|
2557 FORMAT_MESSAGE_FROM_SYSTEM
|
2558 FORMAT_MESSAGE_IGNORE_INSERTS
,
2560 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
2566 char abuf
[1024] = {0};
2567 wcstombs(abuf
,str
,1024);
2568 result
= tor_strdup(abuf
);
2570 result
= tor_strdup(str
);
2572 LocalFree(str
); /* LocalFree != free() */
2574 result
= tor_strdup("<unformattable error>");