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)
25 #include <sys/locking.h>
29 #include <sys/utsname.h>
34 #ifdef HAVE_SYS_FCNTL_H
35 #include <sys/fcntl.h>
49 #ifdef HAVE_ARPA_INET_H
50 #include <arpa/inet.h>
53 #ifndef HAVE_GETTIMEOFDAY
55 #include <sys/timeb.h>
62 #ifdef HAVE_SYS_PARAM_H
63 #include <sys/param.h> /* FreeBSD needs this to know what version it is */
74 #ifdef HAVE_SYS_UTIME_H
75 #include <sys/utime.h>
77 #ifdef HAVE_SYS_MMAN_H
80 #ifdef HAVE_SYS_SYSLIMITS_H
81 #include <sys/syslimits.h>
83 #ifdef HAVE_SYS_FILE_H
86 #if defined(HAVE_SYS_PRCTL_H) && defined(__linux__)
87 /* Only use the linux prctl; the IRIX prctl is totally different */
88 #include <sys/prctl.h>
93 #include "container.h"
96 /* Inline the strl functions if the platform doesn't have them. */
104 #ifdef HAVE_SYS_MMAN_H
105 /** Try to create a memory mapping for <b>filename</b> and return it. On
106 * failure, return NULL. Sets errno properly, using ERANGE to mean
109 tor_mmap_file(const char *filename
)
111 int fd
; /* router file */
115 size_t size
, filesize
;
117 tor_assert(filename
);
119 fd
= open(filename
, O_RDONLY
, 0);
121 int save_errno
= errno
;
122 int severity
= (errno
== ENOENT
) ? LOG_INFO
: LOG_WARN
;
123 log_fn(severity
, LD_FS
,"Could not open \"%s\" for mmap(): %s",filename
,
129 size
= filesize
= (size_t) lseek(fd
, 0, SEEK_END
);
130 lseek(fd
, 0, SEEK_SET
);
131 /* ensure page alignment */
132 page_size
= getpagesize();
133 size
+= (size
%page_size
) ? page_size
-(size
%page_size
) : 0;
136 /* Zero-length file. If we call mmap on it, it will succeed but
137 * return NULL, and bad things will happen. So just fail. */
138 log_info(LD_FS
,"File \"%s\" is empty. Ignoring.",filename
);
144 string
= mmap(0, size
, PROT_READ
, MAP_PRIVATE
, fd
, 0);
146 if (string
== MAP_FAILED
) {
147 int save_errno
= errno
;
148 log_warn(LD_FS
,"Could not mmap file \"%s\": %s", filename
,
154 res
= tor_malloc_zero(sizeof(tor_mmap_t
));
156 res
->size
= filesize
;
157 res
->mapping_size
= size
;
161 /** Release storage held for a memory mapping. */
163 tor_munmap_file(tor_mmap_t
*handle
)
165 munmap((char*)handle
->data
, handle
->mapping_size
);
168 #elif defined(MS_WINDOWS)
170 tor_mmap_file(const char *filename
)
172 TCHAR tfilename
[MAX_PATH
]= {0};
173 tor_mmap_t
*res
= tor_malloc_zero(sizeof(tor_mmap_t
));
175 res
->file_handle
= INVALID_HANDLE_VALUE
;
176 res
->mmap_handle
= NULL
;
178 mbstowcs(tfilename
,filename
,MAX_PATH
);
180 strlcpy(tfilename
,filename
,MAX_PATH
);
182 res
->file_handle
= CreateFile(tfilename
,
183 GENERIC_READ
, FILE_SHARE_READ
,
186 FILE_ATTRIBUTE_NORMAL
,
189 if (res
->file_handle
== INVALID_HANDLE_VALUE
)
192 res
->size
= GetFileSize(res
->file_handle
, NULL
);
194 if (res
->size
== 0) {
195 log_info(LD_FS
,"File \"%s\" is empty. Ignoring.",filename
);
200 res
->mmap_handle
= CreateFileMapping(res
->file_handle
,
203 #if SIZEOF_SIZE_T > 4
204 (res
->base
.size
>> 32),
208 (res
->size
& 0xfffffffful
),
210 if (res
->mmap_handle
== NULL
)
212 res
->data
= (char*) MapViewOfFile(res
->mmap_handle
,
220 DWORD e
= GetLastError();
221 int severity
= (e
== ERROR_FILE_NOT_FOUND
|| e
== ERROR_PATH_NOT_FOUND
) ?
223 char *msg
= format_win32_error(e
);
224 log_fn(severity
, LD_FS
, "Couldn't mmap file \"%s\": %s", filename
, msg
);
226 if (e
== ERROR_FILE_NOT_FOUND
|| e
== ERROR_PATH_NOT_FOUND
)
234 tor_munmap_file(res
);
238 tor_munmap_file(tor_mmap_t
*handle
)
241 /* This is an ugly cast, but without it, "data" in struct tor_mmap_t would
242 have to be redefined as non-const. */
243 UnmapViewOfFile( (LPVOID
) handle
->data
);
245 if (handle
->mmap_handle
!= NULL
)
246 CloseHandle(handle
->mmap_handle
);
247 if (handle
->file_handle
!= INVALID_HANDLE_VALUE
)
248 CloseHandle(handle
->file_handle
);
253 tor_mmap_file(const char *filename
)
256 char *res
= read_file_to_str(filename
, RFTS_BIN
|RFTS_IGNORE_MISSING
, &st
);
260 handle
= tor_malloc_zero(sizeof(tor_mmap_t
));
262 handle
->size
= st
.st_size
;
266 tor_munmap_file(tor_mmap_t
*handle
)
268 char *d
= (char*)handle
->data
;
270 memset(handle
, 0, sizeof(tor_mmap_t
));
275 /** Replacement for snprintf. Differs from platform snprintf in two
276 * ways: First, always NUL-terminates its output. Second, always
277 * returns -1 if the result is truncated. (Note that this return
278 * behavior does <i>not</i> conform to C99; it just happens to be
279 * easier to emulate "return -1" with conformant implementations than
280 * it is to emulate "return number that would be written" with
281 * non-conformant implementations.) */
283 tor_snprintf(char *str
, size_t size
, const char *format
, ...)
288 r
= tor_vsnprintf(str
,size
,format
,ap
);
293 /** Replacement for vsnprintf; behavior differs as tor_snprintf differs from
297 tor_vsnprintf(char *str
, size_t size
, const char *format
, va_list args
)
301 return -1; /* no place for the NUL */
302 if (size
> SSIZE_T_MAX
-16)
305 r
= _vsnprintf(str
, size
, format
, args
);
307 r
= vsnprintf(str
, size
, format
, args
);
310 if (r
< 0 || r
>= (ssize_t
)size
)
316 * Portable asprintf implementation. Does a printf() into a newly malloc'd
317 * string. Sets *<b>strp</b> to this string, and returns its length (not
318 * including the terminating NUL character).
320 * You can treat this function as if its implementation were something like
322 char buf[_INFINITY_];
323 tor_snprintf(buf, sizeof(buf), fmt, args);
324 *strp = tor_strdup(buf);
325 return strlen(*strp):
327 * Where _INFINITY_ is an imaginary constant so big that any string can fit
331 tor_asprintf(char **strp
, const char *fmt
, ...)
336 r
= tor_vasprintf(strp
, fmt
, args
);
338 if (!*strp
|| r
< 0) {
339 log_err(LD_BUG
, "Internal error in asprintf");
346 * Portable vasprintf implementation. Does a printf() into a newly malloc'd
347 * string. Differs from regular vasprintf in the same ways that
348 * tor_asprintf() differs from regular asprintf.
351 tor_vasprintf(char **strp
, const char *fmt
, va_list args
)
353 /* use a temporary variable in case *strp is in args. */
355 #ifdef HAVE_VASPRINTF
356 /* If the platform gives us one, use it. */
357 int r
= vasprintf(&strp_tmp
, fmt
, args
);
363 #elif defined(_MSC_VER)
364 /* On Windows, _vsnprintf won't tell us the length of the string if it
365 * overflows, so we need to use _vcsprintf to tell how much to allocate */
368 len
= _vscprintf(fmt
, args
);
373 strp_tmp
= tor_malloc(len
+ 1);
374 r
= _vsnprintf(strp_tmp
, len
+1, fmt
, args
);
383 /* Everywhere else, we have a decent vsnprintf that tells us how many
384 * characters we need. We give it a try on a short buffer first, since
385 * it might be nice to avoid the second vsnprintf call.
390 va_copy(tmp_args
, args
);
391 len
= vsnprintf(buf
, sizeof(buf
), fmt
, tmp_args
);
393 if (len
< (int)sizeof(buf
)) {
394 *strp
= tor_strdup(buf
);
397 strp_tmp
= tor_malloc(len
+1);
398 r
= vsnprintf(strp_tmp
, len
+1, fmt
, args
);
409 /** Given <b>hlen</b> bytes at <b>haystack</b> and <b>nlen</b> bytes at
410 * <b>needle</b>, return a pointer to the first occurrence of the needle
411 * within the haystack, or NULL if there is no such occurrence.
413 * Requires that nlen be greater than zero.
416 tor_memmem(const void *_haystack
, size_t hlen
,
417 const void *_needle
, size_t nlen
)
419 #if defined(HAVE_MEMMEM) && (!defined(__GNUC__) || __GNUC__ >= 2)
421 return memmem(_haystack
, hlen
, _needle
, nlen
);
423 /* This isn't as fast as the GLIBC implementation, but it doesn't need to
426 const char *haystack
= (const char*)_haystack
;
427 const char *needle
= (const char*)_needle
;
432 end
= haystack
+ hlen
;
433 first
= *(const char*)needle
;
434 while ((p
= memchr(p
, first
, end
-p
))) {
437 if (!memcmp(p
, needle
, nlen
))
445 /* Tables to implement ctypes-replacement TOR_IS*() functions. Each table
446 * has 256 bits to look up whether a character is in some set or not. This
447 * fails on non-ASCII platforms, but it is hard to find a platform whose
448 * character set is not a superset of ASCII nowadays. */
449 const uint32_t TOR_ISALPHA_TABLE
[8] =
450 { 0, 0, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
451 const uint32_t TOR_ISALNUM_TABLE
[8] =
452 { 0, 0x3ff0000, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
453 const uint32_t TOR_ISSPACE_TABLE
[8] = { 0x3e00, 0x1, 0, 0, 0, 0, 0, 0 };
454 const uint32_t TOR_ISXDIGIT_TABLE
[8] =
455 { 0, 0x3ff0000, 0x7e, 0x7e, 0, 0, 0, 0 };
456 const uint32_t TOR_ISDIGIT_TABLE
[8] = { 0, 0x3ff0000, 0, 0, 0, 0, 0, 0 };
457 const uint32_t TOR_ISPRINT_TABLE
[8] =
458 { 0, 0xffffffff, 0xffffffff, 0x7fffffff, 0, 0, 0, 0x0 };
459 const uint32_t TOR_ISUPPER_TABLE
[8] = { 0, 0, 0x7fffffe, 0, 0, 0, 0, 0 };
460 const uint32_t TOR_ISLOWER_TABLE
[8] = { 0, 0, 0, 0x7fffffe, 0, 0, 0, 0 };
461 /* Upper-casing and lowercasing tables to map characters to upper/lowercase
463 const char TOR_TOUPPER_TABLE
[256] = {
464 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
465 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
466 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
467 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
468 64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
469 80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
470 96,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
471 80,81,82,83,84,85,86,87,88,89,90,123,124,125,126,127,
472 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
473 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
474 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
475 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
476 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
477 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
478 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
479 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
481 const char TOR_TOLOWER_TABLE
[256] = {
482 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
483 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
484 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
485 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
486 64,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
487 112,113,114,115,116,117,118,119,120,121,122,91,92,93,94,95,
488 96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
489 112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
490 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
491 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
492 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
493 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
494 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
495 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
496 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
497 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
500 /** Implementation of strtok_r for platforms whose coders haven't figured out
501 * how to write one. Hey guys! You can use this code here for free! */
503 tor_strtok_r_impl(char *str
, const char *sep
, char **lasts
)
507 start
= cp
= *lasts
= str
;
515 while (*cp
&& !strchr(sep
, *cp
))
518 tor_assert(strlen(sep
) == 1);
519 cp
= strchr(cp
, *sep
);
532 /** Take a filename and return a pointer to its final element. This
533 * function is called on __FILE__ to fix a MSVC nit where __FILE__
534 * contains the full path to the file. This is bad, because it
535 * confuses users to find the home directory of the person who
536 * compiled the binary in their warning messages.
539 tor_fix_source_file(const char *fname
)
541 const char *cp1
, *cp2
, *r
;
542 cp1
= strrchr(fname
, '/');
543 cp2
= strrchr(fname
, '\\');
545 r
= (cp1
<cp2
)?(cp2
+1):(cp1
+1);
558 * Read a 16-bit value beginning at <b>cp</b>. Equivalent to
559 * *(uint16_t*)(cp), but will not cause segfaults on platforms that forbid
560 * unaligned memory access.
563 get_uint16(const char *cp
)
570 * Read a 32-bit value beginning at <b>cp</b>. Equivalent to
571 * *(uint32_t*)(cp), but will not cause segfaults on platforms that forbid
572 * unaligned memory access.
575 get_uint32(const char *cp
)
582 * Read a 64-bit value beginning at <b>cp</b>. Equivalent to
583 * *(uint64_t*)(cp), but will not cause segfaults on platforms that forbid
584 * unaligned memory access.
587 get_uint64(const char *cp
)
595 * Set a 16-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
596 * *(uint16_t*)(cp) = v, but will not cause segfaults on platforms that forbid
597 * unaligned memory access. */
599 set_uint16(char *cp
, uint16_t v
)
604 * Set a 32-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
605 * *(uint32_t*)(cp) = v, but will not cause segfaults on platforms that forbid
606 * unaligned memory access. */
608 set_uint32(char *cp
, uint32_t v
)
613 * Set a 64-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
614 * *(uint64_t*)(cp) = v, but will not cause segfaults on platforms that forbid
615 * unaligned memory access. */
617 set_uint64(char *cp
, uint64_t v
)
623 * Rename the file <b>from</b> to the file <b>to</b>. On Unix, this is
624 * the same as rename(2). On windows, this removes <b>to</b> first if
626 * Returns 0 on success. Returns -1 and sets errno on failure.
629 replace_file(const char *from
, const char *to
)
632 return rename(from
,to
);
634 switch (file_status(to
))
639 if (unlink(to
)) return -1;
647 return rename(from
,to
);
651 /** Change <b>fname</b>'s modification time to now. */
653 touch_file(const char *fname
)
655 if (utime(fname
, NULL
)!=0)
660 /** Represents a lockfile on which we hold the lock. */
661 struct tor_lockfile_t
{
666 /** Try to get a lock on the lockfile <b>filename</b>, creating it as
667 * necessary. If someone else has the lock and <b>blocking</b> is true,
668 * wait until the lock is available. Otherwise return immediately whether
669 * we succeeded or not.
671 * Set *<b>locked_out</b> to true if somebody else had the lock, and to false
674 * Return a <b>tor_lockfile_t</b> on success, NULL on failure.
676 * (Implementation note: because we need to fall back to fcntl on some
677 * platforms, these locks are per-process, not per-thread. If you want
678 * to do in-process locking, use tor_mutex_t like a normal person.)
681 tor_lockfile_lock(const char *filename
, int blocking
, int *locked_out
)
683 tor_lockfile_t
*result
;
687 log_info(LD_FS
, "Locking \"%s\"", filename
);
688 fd
= open(filename
, O_RDWR
|O_CREAT
|O_TRUNC
, 0600);
690 log_warn(LD_FS
,"Couldn't open \"%s\" for locking: %s", filename
,
696 _lseek(fd
, 0, SEEK_SET
);
697 if (_locking(fd
, blocking
? _LK_LOCK
: _LK_NBLCK
, 1) < 0) {
698 if (errno
!= EDEADLOCK
)
699 log_warn(LD_FS
,"Couldn't lock \"%s\": %s", filename
, strerror(errno
));
705 #elif defined(HAVE_FLOCK)
706 if (flock(fd
, LOCK_EX
|(blocking
? 0 : LOCK_NB
)) < 0) {
707 if (errno
!= EWOULDBLOCK
)
708 log_warn(LD_FS
,"Couldn't lock \"%s\": %s", filename
, strerror(errno
));
717 memset(&lock
, 0, sizeof(lock
));
718 lock
.l_type
= F_WRLCK
;
719 lock
.l_whence
= SEEK_SET
;
720 if (fcntl(fd
, blocking
? F_SETLKW
: F_SETLK
, &lock
) < 0) {
721 if (errno
!= EACCES
&& errno
!= EAGAIN
)
722 log_warn(LD_FS
, "Couldn't lock \"%s\": %s", filename
, strerror(errno
));
731 result
= tor_malloc(sizeof(tor_lockfile_t
));
732 result
->filename
= tor_strdup(filename
);
737 /** Release the lock held as <b>lockfile</b>. */
739 tor_lockfile_unlock(tor_lockfile_t
*lockfile
)
741 tor_assert(lockfile
);
743 log_info(LD_FS
, "Unlocking \"%s\"", lockfile
->filename
);
745 _lseek(lockfile
->fd
, 0, SEEK_SET
);
746 if (_locking(lockfile
->fd
, _LK_UNLCK
, 1) < 0) {
747 log_warn(LD_FS
,"Error unlocking \"%s\": %s", lockfile
->filename
,
750 #elif defined(HAVE_FLOCK)
751 if (flock(lockfile
->fd
, LOCK_UN
) < 0) {
752 log_warn(LD_FS
, "Error unlocking \"%s\": %s", lockfile
->filename
,
756 /* Closing the lockfile is sufficient. */
761 tor_free(lockfile
->filename
);
765 /* Some old versions of Unix didn't define constants for these values,
766 * and instead expect you to say 0, 1, or 2. */
774 /** Return the position of <b>fd</b> with respect to the start of the file. */
776 tor_fd_getpos(int fd
)
779 return (off_t
) _lseek(fd
, 0, SEEK_CUR
);
781 return (off_t
) lseek(fd
, 0, SEEK_CUR
);
785 /** Move <b>fd</b> to the end of the file. Return -1 on error, 0 on success. */
787 tor_fd_seekend(int fd
)
790 return _lseek(fd
, 0, SEEK_END
) < 0 ? -1 : 0;
792 return lseek(fd
, 0, SEEK_END
) < 0 ? -1 : 0;
796 #undef DEBUG_SOCKET_COUNTING
797 #ifdef DEBUG_SOCKET_COUNTING
798 /** A bitarray of all fds that should be passed to tor_socket_close(). Only
799 * used if DEBUG_SOCKET_COUNTING is defined. */
800 static bitarray_t
*open_sockets
= NULL
;
801 /** The size of <b>open_sockets</b>, in bits. */
802 static int max_socket
= -1;
805 /** Count of number of sockets currently open. (Undercounts sockets opened by
806 * eventdns and libevent.) */
807 static int n_sockets_open
= 0;
809 /** Mutex to protect open_sockets, max_socket, and n_sockets_open. */
810 static tor_mutex_t
*socket_accounting_mutex
= NULL
;
813 socket_accounting_lock(void)
815 if (PREDICT_UNLIKELY(!socket_accounting_mutex
))
816 socket_accounting_mutex
= tor_mutex_new();
817 tor_mutex_acquire(socket_accounting_mutex
);
821 socket_accounting_unlock(void)
823 tor_mutex_release(socket_accounting_mutex
);
826 /** As close(), but guaranteed to work for sockets across platforms (including
827 * Windows, where close()ing a socket doesn't work. Returns 0 on success, -1
830 tor_close_socket(int s
)
834 /* On Windows, you have to call close() on fds returned by open(),
835 * and closesocket() on fds returned by socket(). On Unix, everything
836 * gets close()'d. We abstract this difference by always using
837 * tor_close_socket to close sockets, and always using close() on
840 #if defined(MS_WINDOWS)
846 socket_accounting_lock();
847 #ifdef DEBUG_SOCKET_COUNTING
848 if (s
> max_socket
|| ! bitarray_is_set(open_sockets
, s
)) {
849 log_warn(LD_BUG
, "Closing a socket (%d) that wasn't returned by tor_open_"
850 "socket(), or that was already closed or something.", s
);
852 tor_assert(open_sockets
&& s
<= max_socket
);
853 bitarray_clear(open_sockets
, s
);
859 int err
= tor_socket_errno(-1);
860 log_info(LD_NET
, "Close returned an error: %s", tor_socket_strerror(err
));
862 if (err
!= WSAENOTSOCK
)
871 if (n_sockets_open
< 0)
872 log_warn(LD_BUG
, "Our socket count is below zero: %d. Please submit a "
873 "bug report.", n_sockets_open
);
874 socket_accounting_unlock();
878 #ifdef DEBUG_SOCKET_COUNTING
879 /** Helper: if DEBUG_SOCKET_COUNTING is enabled, remember that <b>s</b> is
880 * now an open socket. */
882 mark_socket_open(int s
)
884 if (s
> max_socket
) {
885 if (max_socket
== -1) {
886 open_sockets
= bitarray_init_zero(s
+128);
889 open_sockets
= bitarray_expand(open_sockets
, max_socket
, s
+128);
893 if (bitarray_is_set(open_sockets
, s
)) {
894 log_warn(LD_BUG
, "I thought that %d was already open, but socket() just "
895 "gave it to me!", s
);
897 bitarray_set(open_sockets
, s
);
900 #define mark_socket_open(s) STMT_NIL
903 /** As socket(), but counts the number of open sockets. */
905 tor_open_socket(int domain
, int type
, int protocol
)
907 int s
= socket(domain
, type
, protocol
);
909 socket_accounting_lock();
912 socket_accounting_unlock();
917 /** As socket(), but counts the number of open sockets. */
919 tor_accept_socket(int sockfd
, struct sockaddr
*addr
, socklen_t
*len
)
921 int s
= accept(sockfd
, addr
, len
);
923 socket_accounting_lock();
926 socket_accounting_unlock();
931 /** Return the number of sockets we currently have opened. */
933 get_n_open_sockets(void)
936 socket_accounting_lock();
938 socket_accounting_unlock();
942 /** Turn <b>socket</b> into a nonblocking socket.
945 set_socket_nonblocking(int socket
)
947 #if defined(MS_WINDOWS)
948 unsigned long nonblocking
= 1;
949 ioctlsocket(socket
, FIONBIO
, (unsigned long*) &nonblocking
);
951 fcntl(socket
, F_SETFL
, O_NONBLOCK
);
956 * Allocate a pair of connected sockets. (Like socketpair(family,
957 * type,protocol,fd), but works on systems that don't have
960 * Currently, only (AF_UNIX, SOCK_STREAM, 0) sockets are supported.
962 * Note that on systems without socketpair, this call will fail if
963 * localhost is inaccessible (for example, if the networking
964 * stack is down). And even if it succeeds, the socket pair will not
965 * be able to read while localhost is down later (the socket pair may
966 * even close, depending on OS-specific timeouts).
968 * Returns 0 on success and -errno on failure; do not rely on the value
969 * of errno or WSAGetLastError().
971 /* It would be nicer just to set errno, but that won't work for windows. */
973 tor_socketpair(int family
, int type
, int protocol
, int fd
[2])
975 //don't use win32 socketpairs (they are always bad)
976 #if defined(HAVE_SOCKETPAIR) && !defined(MS_WINDOWS)
978 r
= socketpair(family
, type
, protocol
, fd
);
980 socket_accounting_lock();
983 mark_socket_open(fd
[0]);
987 mark_socket_open(fd
[1]);
989 socket_accounting_unlock();
991 return r
< 0 ? -errno
: r
;
993 /* This socketpair does not work when localhost is down. So
994 * it's really not the same thing at all. But it's close enough
995 * for now, and really, when localhost is down sometimes, we
996 * have other problems too.
1001 struct sockaddr_in listen_addr
;
1002 struct sockaddr_in connect_addr
;
1004 int saved_errno
= -1;
1008 || family
!= AF_UNIX
1012 return -WSAEAFNOSUPPORT
;
1014 return -EAFNOSUPPORT
;
1021 listener
= tor_open_socket(AF_INET
, type
, 0);
1023 return -tor_socket_errno(-1);
1024 memset(&listen_addr
, 0, sizeof(listen_addr
));
1025 listen_addr
.sin_family
= AF_INET
;
1026 listen_addr
.sin_addr
.s_addr
= htonl(INADDR_LOOPBACK
);
1027 listen_addr
.sin_port
= 0; /* kernel chooses port. */
1028 if (bind(listener
, (struct sockaddr
*) &listen_addr
, sizeof (listen_addr
))
1030 goto tidy_up_and_fail
;
1031 if (listen(listener
, 1) == -1)
1032 goto tidy_up_and_fail
;
1034 connector
= tor_open_socket(AF_INET
, type
, 0);
1036 goto tidy_up_and_fail
;
1037 /* We want to find out the port number to connect to. */
1038 size
= sizeof(connect_addr
);
1039 if (getsockname(listener
, (struct sockaddr
*) &connect_addr
, &size
) == -1)
1040 goto tidy_up_and_fail
;
1041 if (size
!= sizeof (connect_addr
))
1042 goto abort_tidy_up_and_fail
;
1043 if (connect(connector
, (struct sockaddr
*) &connect_addr
,
1044 sizeof(connect_addr
)) == -1)
1045 goto tidy_up_and_fail
;
1047 size
= sizeof(listen_addr
);
1048 acceptor
= tor_accept_socket(listener
,
1049 (struct sockaddr
*) &listen_addr
, &size
);
1051 goto tidy_up_and_fail
;
1052 if (size
!= sizeof(listen_addr
))
1053 goto abort_tidy_up_and_fail
;
1054 tor_close_socket(listener
);
1055 /* Now check we are talking to ourself by matching port and host on the
1057 if (getsockname(connector
, (struct sockaddr
*) &connect_addr
, &size
) == -1)
1058 goto tidy_up_and_fail
;
1059 if (size
!= sizeof (connect_addr
)
1060 || listen_addr
.sin_family
!= connect_addr
.sin_family
1061 || listen_addr
.sin_addr
.s_addr
!= connect_addr
.sin_addr
.s_addr
1062 || listen_addr
.sin_port
!= connect_addr
.sin_port
) {
1063 goto abort_tidy_up_and_fail
;
1070 abort_tidy_up_and_fail
:
1072 saved_errno
= WSAECONNABORTED
;
1074 saved_errno
= ECONNABORTED
; /* I hope this is portable and appropriate. */
1077 if (saved_errno
< 0)
1078 saved_errno
= errno
;
1080 tor_close_socket(listener
);
1081 if (connector
!= -1)
1082 tor_close_socket(connector
);
1084 tor_close_socket(acceptor
);
1085 return -saved_errno
;
1089 #define ULIMIT_BUFFER 32 /* keep 32 extra fd's beyond _ConnLimit */
1091 /** Learn the maximum allowed number of file descriptors. (Some systems
1092 * have a low soft limit.
1094 * We compute this by finding the largest number that we can use.
1095 * If we can't find a number greater than or equal to <b>limit</b>,
1096 * then we fail: return -1.
1098 * Otherwise, return 0 and store the maximum we found inside <b>max_out</b>.*/
1100 set_max_file_descriptors(rlim_t limit
, int *max_out
)
1102 /* Define some maximum connections values for systems where we cannot
1103 * automatically determine a limit. Re Cygwin, see
1104 * http://archives.seul.org/or/talk/Aug-2006/msg00210.html
1105 * For an iPhone, 9999 should work. For Windows and all other unknown
1106 * systems we use 15000 as the default. */
1107 #ifndef HAVE_GETRLIMIT
1108 #if defined(CYGWIN) || defined(__CYGWIN__)
1109 const char *platform
= "Cygwin";
1110 const unsigned long MAX_CONNECTIONS
= 3200;
1111 #elif defined(MS_WINDOWS)
1112 const char *platform
= "Windows";
1113 const unsigned long MAX_CONNECTIONS
= 15000;
1115 const char *platform
= "unknown platforms with no getrlimit()";
1116 const unsigned long MAX_CONNECTIONS
= 15000;
1118 log_fn(LOG_INFO
, LD_NET
,
1119 "This platform is missing getrlimit(). Proceeding.");
1120 if (limit
> MAX_CONNECTIONS
) {
1122 "We do not support more than %lu file descriptors "
1123 "on %s. Tried to raise to %lu.",
1124 (unsigned long)MAX_CONNECTIONS
, platform
, (unsigned long)limit
);
1127 limit
= MAX_CONNECTIONS
;
1128 #else /* HAVE_GETRLIMIT */
1130 tor_assert(limit
> 0);
1132 if (getrlimit(RLIMIT_NOFILE
, &rlim
) != 0) {
1133 log_warn(LD_NET
, "Could not get maximum number of file descriptors: %s",
1138 if (rlim
.rlim_max
< limit
) {
1139 log_warn(LD_CONFIG
,"We need %lu file descriptors available, and we're "
1140 "limited to %lu. Please change your ulimit -n.",
1141 (unsigned long)limit
, (unsigned long)rlim
.rlim_max
);
1145 if (rlim
.rlim_max
> rlim
.rlim_cur
) {
1146 log_info(LD_NET
,"Raising max file descriptors from %lu to %lu.",
1147 (unsigned long)rlim
.rlim_cur
, (unsigned long)rlim
.rlim_max
);
1149 rlim
.rlim_cur
= rlim
.rlim_max
;
1151 if (setrlimit(RLIMIT_NOFILE
, &rlim
) != 0) {
1154 if (errno
== EINVAL
&& OPEN_MAX
< rlim
.rlim_cur
) {
1155 /* On some platforms, OPEN_MAX is the real limit, and getrlimit() is
1156 * full of nasty lies. I'm looking at you, OSX 10.5.... */
1157 rlim
.rlim_cur
= OPEN_MAX
;
1158 if (setrlimit(RLIMIT_NOFILE
, &rlim
) == 0) {
1159 if (rlim
.rlim_cur
< (rlim_t
)limit
) {
1160 log_warn(LD_CONFIG
, "We are limited to %lu file descriptors by "
1161 "OPEN_MAX, and ConnLimit is %lu. Changing ConnLimit; sorry.",
1162 (unsigned long)OPEN_MAX
, (unsigned long)limit
);
1164 log_info(LD_CONFIG
, "Dropped connection limit to OPEN_MAX (%lu); "
1165 "Apparently, %lu was too high and rlimit lied to us.",
1166 (unsigned long)OPEN_MAX
, (unsigned long)rlim
.rlim_max
);
1171 #endif /* OPEN_MAX */
1173 log_warn(LD_CONFIG
,"Couldn't set maximum number of file descriptors: %s",
1178 /* leave some overhead for logs, etc, */
1179 limit
= rlim
.rlim_cur
;
1180 #endif /* HAVE_GETRLIMIT */
1182 if (limit
< ULIMIT_BUFFER
) {
1184 "ConnLimit must be at least %d. Failing.", ULIMIT_BUFFER
);
1187 if (limit
> INT_MAX
)
1189 tor_assert(max_out
);
1190 *max_out
= (int)limit
- ULIMIT_BUFFER
;
1195 /** Log details of current user and group credentials. Return 0 on
1196 * success. Logs and return -1 on failure.
1199 log_credential_status(void)
1201 #define CREDENTIAL_LOG_LEVEL LOG_INFO
1202 /* Real, effective and saved UIDs */
1203 uid_t ruid
, euid
, suid
;
1204 /* Read, effective and saved GIDs */
1205 gid_t rgid
, egid
, sgid
;
1206 /* Supplementary groups */
1207 gid_t sup_gids
[NGROUPS_MAX
+ 1];
1208 /* Number of supplementary groups */
1212 #ifdef HAVE_GETRESUID
1213 if (getresuid(&ruid
, &euid
, &suid
) != 0 ) {
1214 log_warn(LD_GENERAL
, "Error getting changed UIDs: %s", strerror(errno
));
1217 log_fn(CREDENTIAL_LOG_LEVEL
, LD_GENERAL
,
1218 "UID is %u (real), %u (effective), %u (saved)",
1219 (unsigned)ruid
, (unsigned)euid
, (unsigned)suid
);
1222 /* getresuid is not present on MacOS X, so we can't get the saved (E)UID */
1227 log_fn(CREDENTIAL_LOG_LEVEL
, LD_GENERAL
,
1228 "UID is %u (real), %u (effective), unknown (saved)",
1229 (unsigned)ruid
, (unsigned)euid
);
1233 #ifdef HAVE_GETRESGID
1234 if (getresgid(&rgid
, &egid
, &sgid
) != 0 ) {
1235 log_warn(LD_GENERAL
, "Error getting changed GIDs: %s", strerror(errno
));
1238 log_fn(CREDENTIAL_LOG_LEVEL
, LD_GENERAL
,
1239 "GID is %u (real), %u (effective), %u (saved)",
1240 (unsigned)rgid
, (unsigned)egid
, (unsigned)sgid
);
1243 /* getresgid is not present on MacOS X, so we can't get the saved (E)GID */
1247 log_fn(CREDENTIAL_LOG_LEVEL
, LD_GENERAL
,
1248 "GID is %u (real), %u (effective), unknown (saved)",
1249 (unsigned)rgid
, (unsigned)egid
);
1252 /* log supplementary groups */
1253 if ((ngids
= getgroups(NGROUPS_MAX
+ 1, sup_gids
)) < 0) {
1254 log_warn(LD_GENERAL
, "Error getting supplementary GIDs: %s",
1261 smartlist_t
*elts
= smartlist_create();
1263 for (i
= 0; i
<ngids
; i
++) {
1264 strgid
= tor_malloc(11);
1265 if (tor_snprintf(strgid
, 11, "%u", (unsigned)sup_gids
[i
]) < 0) {
1266 log_warn(LD_GENERAL
, "Error printing supplementary GIDs");
1271 smartlist_add(elts
, strgid
);
1274 s
= smartlist_join_strings(elts
, " ", 0, NULL
);
1276 log_fn(CREDENTIAL_LOG_LEVEL
, LD_GENERAL
, "Supplementary groups are: %s",s
);
1280 SMARTLIST_FOREACH(elts
, char *, cp
,
1284 smartlist_free(elts
);
1293 /** Call setuid and setgid to run as <b>user</b> and switch to their
1294 * primary group. Return 0 on success. On failure, log and return -1.
1297 switch_id(const char *user
)
1300 struct passwd
*pw
= NULL
;
1303 static int have_already_switched_id
= 0;
1307 if (have_already_switched_id
)
1310 /* Log the initial credential state */
1311 if (log_credential_status())
1314 log_fn(CREDENTIAL_LOG_LEVEL
, LD_GENERAL
, "Changing user and groups");
1316 /* Get old UID/GID to check if we changed correctly */
1320 /* Lookup the user and group information, if we have a problem, bail out. */
1321 pw
= getpwnam(user
);
1323 log_warn(LD_CONFIG
, "Error setting configured user: %s not found", user
);
1327 /* Properly switch egid,gid,euid,uid here or bail out */
1328 if (setgroups(1, &pw
->pw_gid
)) {
1329 log_warn(LD_GENERAL
, "Error setting groups to gid %d: \"%s\".",
1330 (int)pw
->pw_gid
, strerror(errno
));
1331 if (old_uid
== pw
->pw_uid
) {
1332 log_warn(LD_GENERAL
, "Tor is already running as %s. You do not need "
1333 "the \"User\" option if you are already running as the user "
1334 "you want to be. (If you did not set the User option in your "
1335 "torrc, check whether it was specified on the command line "
1336 "by a startup script.)", user
);
1338 log_warn(LD_GENERAL
, "If you set the \"User\" option, you must start Tor"
1344 if (setegid(pw
->pw_gid
)) {
1345 log_warn(LD_GENERAL
, "Error setting egid to %d: %s",
1346 (int)pw
->pw_gid
, strerror(errno
));
1350 if (setgid(pw
->pw_gid
)) {
1351 log_warn(LD_GENERAL
, "Error setting gid to %d: %s",
1352 (int)pw
->pw_gid
, strerror(errno
));
1356 if (setuid(pw
->pw_uid
)) {
1357 log_warn(LD_GENERAL
, "Error setting configured uid to %s (%d): %s",
1358 user
, (int)pw
->pw_uid
, strerror(errno
));
1362 if (seteuid(pw
->pw_uid
)) {
1363 log_warn(LD_GENERAL
, "Error setting configured euid to %s (%d): %s",
1364 user
, (int)pw
->pw_uid
, strerror(errno
));
1368 /* This is how OpenBSD rolls:
1369 if (setgroups(1, &pw->pw_gid) || setegid(pw->pw_gid) ||
1370 setgid(pw->pw_gid) || setuid(pw->pw_uid) || seteuid(pw->pw_uid)) {
1371 setgid(pw->pw_gid) || seteuid(pw->pw_uid) || setuid(pw->pw_uid)) {
1372 log_warn(LD_GENERAL, "Error setting configured UID/GID: %s",
1378 /* We've properly switched egid, gid, euid, uid, and supplementary groups if
1381 #if !defined(CYGWIN) && !defined(__CYGWIN__)
1382 /* If we tried to drop privilege to a group/user other than root, attempt to
1383 * restore root (E)(U|G)ID, and abort if the operation succeeds */
1385 /* Only check for privilege dropping if we were asked to be non-root */
1387 /* Try changing GID/EGID */
1388 if (pw
->pw_gid
!= old_gid
&&
1389 (setgid(old_gid
) != -1 || setegid(old_gid
) != -1)) {
1390 log_warn(LD_GENERAL
, "Was able to restore group credentials even after "
1391 "switching GID: this means that the setgid code didn't work.");
1395 /* Try changing UID/EUID */
1396 if (pw
->pw_uid
!= old_uid
&&
1397 (setuid(old_uid
) != -1 || seteuid(old_uid
) != -1)) {
1398 log_warn(LD_GENERAL
, "Was able to restore user credentials even after "
1399 "switching UID: this means that the setuid code didn't work.");
1405 /* Check what really happened */
1406 if (log_credential_status()) {
1410 have_already_switched_id
= 1; /* mark success so we never try again */
1412 #if defined(__linux__) && defined(HAVE_SYS_PRCTL_H) && defined(HAVE_PRCTL)
1413 #ifdef PR_SET_DUMPABLE
1415 /* Re-enable core dumps if we're not running as root. */
1416 log_info(LD_CONFIG
, "Re-enabling coredumps");
1417 if (prctl(PR_SET_DUMPABLE
, 1)) {
1418 log_warn(LD_CONFIG
, "Unable to re-enable coredumps: %s",strerror(errno
));
1429 "User specified but switching users is unsupported on your OS.");
1435 /** Allocate and return a string containing the home directory for the
1436 * user <b>username</b>. Only works on posix-like systems. */
1438 get_user_homedir(const char *username
)
1441 tor_assert(username
);
1443 if (!(pw
= getpwnam(username
))) {
1444 log_err(LD_CONFIG
,"User \"%s\" not found.", username
);
1447 return tor_strdup(pw
->pw_dir
);
1451 /** Set *addr to the IP address (in dotted-quad notation) stored in c.
1452 * Return 1 on success, 0 if c is badly formatted. (Like inet_aton(c,addr),
1453 * but works on Windows and Solaris.)
1456 tor_inet_aton(const char *str
, struct in_addr
* addr
)
1460 if (tor_sscanf(str
, "%3u.%3u.%3u.%3u%c", &a
,&b
,&c
,&d
,&more
) != 4)
1462 if (a
> 255) return 0;
1463 if (b
> 255) return 0;
1464 if (c
> 255) return 0;
1465 if (d
> 255) return 0;
1466 addr
->s_addr
= htonl((a
<<24) | (b
<<16) | (c
<<8) | d
);
1470 /** Given <b>af</b>==AF_INET and <b>src</b> a struct in_addr, or
1471 * <b>af</b>==AF_INET6 and <b>src</b> a struct in6_addr, try to format the
1472 * address and store it in the <b>len</b>-byte buffer <b>dst</b>. Returns
1473 * <b>dst</b> on success, NULL on failure.
1475 * (Like inet_ntop(af,src,dst,len), but works on platforms that don't have it:
1476 * Tor sometimes needs to format ipv6 addresses even on platforms without ipv6
1479 tor_inet_ntop(int af
, const void *src
, char *dst
, size_t len
)
1481 if (af
== AF_INET
) {
1482 if (tor_inet_ntoa(src
, dst
, len
) < 0)
1486 } else if (af
== AF_INET6
) {
1487 const struct in6_addr
*addr
= src
;
1489 int longestGapLen
= 0, longestGapPos
= -1, i
,
1490 curGapPos
= -1, curGapLen
= 0;
1492 for (i
= 0; i
< 8; ++i
) {
1493 words
[i
] = (((uint16_t)addr
->s6_addr
[2*i
])<<8) + addr
->s6_addr
[2*i
+1];
1495 if (words
[0] == 0 && words
[1] == 0 && words
[2] == 0 && words
[3] == 0 &&
1496 words
[4] == 0 && ((words
[5] == 0 && words
[6] && words
[7]) ||
1497 (words
[5] == 0xffff))) {
1498 /* This is an IPv4 address. */
1499 if (words
[5] == 0) {
1500 tor_snprintf(buf
, sizeof(buf
), "::%d.%d.%d.%d",
1501 addr
->s6_addr
[12], addr
->s6_addr
[13],
1502 addr
->s6_addr
[14], addr
->s6_addr
[15]);
1504 tor_snprintf(buf
, sizeof(buf
), "::%x:%d.%d.%d.%d", words
[5],
1505 addr
->s6_addr
[12], addr
->s6_addr
[13],
1506 addr
->s6_addr
[14], addr
->s6_addr
[15]);
1508 if (strlen(buf
) > len
)
1510 strlcpy(dst
, buf
, len
);
1515 if (words
[i
] == 0) {
1518 while (i
<8 && words
[i
] == 0) {
1521 if (curGapLen
> longestGapLen
) {
1522 longestGapPos
= curGapPos
;
1523 longestGapLen
= curGapLen
;
1529 if (longestGapLen
<=1)
1533 for (i
= 0; i
< 8; ++i
) {
1534 if (words
[i
] == 0 && longestGapPos
== i
) {
1538 while (i
< 8 && words
[i
] == 0)
1540 --i
; /* to compensate for loop increment. */
1542 tor_snprintf(cp
, sizeof(buf
)-(cp
-buf
), "%x", (unsigned)words
[i
]);
1549 if (strlen(buf
) > len
)
1551 strlcpy(dst
, buf
, len
);
1558 /** Given <b>af</b>==AF_INET or <b>af</b>==AF_INET6, and a string <b>src</b>
1559 * encoding an IPv4 address or IPv6 address correspondingly, try to parse the
1560 * address and store the result in <b>dst</b> (which must have space for a
1561 * struct in_addr or a struct in6_addr, as appropriate). Return 1 on success,
1562 * 0 on a bad parse, and -1 on a bad <b>af</b>.
1564 * (Like inet_pton(af,src,dst) but works on platforms that don't have it: Tor
1565 * sometimes needs to format ipv6 addresses even on platforms without ipv6
1568 tor_inet_pton(int af
, const char *src
, void *dst
)
1570 if (af
== AF_INET
) {
1571 return tor_inet_aton(src
, dst
);
1572 } else if (af
== AF_INET6
) {
1573 struct in6_addr
*out
= dst
;
1575 int gapPos
= -1, i
, setWords
=0;
1576 const char *dot
= strchr(src
, '.');
1577 const char *eow
; /* end of words. */
1581 eow
= src
+strlen(src
);
1583 unsigned byte1
,byte2
,byte3
,byte4
;
1585 for (eow
= dot
-1; eow
>= src
&& TOR_ISDIGIT(*eow
); --eow
)
1589 /* We use "scanf" because some platform inet_aton()s are too lax
1590 * about IPv4 addresses of the form "1.2.3" */
1591 if (tor_sscanf(eow
, "%3u.%3u.%3u.%3u%c",
1592 &byte1
,&byte2
,&byte3
,&byte4
,&more
) != 4)
1595 if (byte1
> 255 || byte2
> 255 || byte3
> 255 || byte4
> 255)
1598 words
[6] = (byte1
<<8) | byte2
;
1599 words
[7] = (byte3
<<8) | byte4
;
1607 if (TOR_ISXDIGIT(*src
)) {
1609 long r
= strtol(src
, &next
, 16);
1617 words
[i
++] = (uint16_t)r
;
1620 if (*src
!= ':' && src
!= eow
)
1623 } else if (*src
== ':' && i
> 0 && gapPos
==-1) {
1626 } else if (*src
== ':' && i
== 0 && src
[1] == ':' && gapPos
==-1) {
1635 (setWords
== 8 && gapPos
!= -1) ||
1636 (setWords
< 8 && gapPos
== -1))
1640 int nToMove
= setWords
- (dot
? 2 : 0) - gapPos
;
1641 int gapLen
= 8 - setWords
;
1642 tor_assert(nToMove
>= 0);
1643 memmove(&words
[gapPos
+gapLen
], &words
[gapPos
],
1644 sizeof(uint16_t)*nToMove
);
1645 memset(&words
[gapPos
], 0, sizeof(uint16_t)*gapLen
);
1647 for (i
= 0; i
< 8; ++i
) {
1648 out
->s6_addr
[2*i
] = words
[i
] >> 8;
1649 out
->s6_addr
[2*i
+1] = words
[i
] & 0xff;
1658 /** Similar behavior to Unix gethostbyname: resolve <b>name</b>, and set
1659 * *<b>addr</b> to the proper IP address, in host byte order. Returns 0
1660 * on success, -1 on failure; 1 on transient failure.
1662 * (This function exists because standard windows gethostbyname
1663 * doesn't treat raw IP addresses properly.)
1666 tor_lookup_hostname(const char *name
, uint32_t *addr
)
1671 if ((ret
= tor_addr_lookup(name
, AF_INET
, &myaddr
)))
1674 if (tor_addr_family(&myaddr
) == AF_INET
) {
1675 *addr
= tor_addr_to_ipv4h(&myaddr
);
1682 /** Hold the result of our call to <b>uname</b>. */
1683 static char uname_result
[256];
1684 /** True iff uname_result is set. */
1685 static int uname_result_is_set
= 0;
1687 /** Return a pointer to a description of our platform.
1695 if (!uname_result_is_set
) {
1697 if (uname(&u
) != -1) {
1698 /* (Linux says 0 is success, Solaris says 1 is success) */
1699 tor_snprintf(uname_result
, sizeof(uname_result
), "%s %s",
1700 u
.sysname
, u
.machine
);
1705 OSVERSIONINFOEX info
;
1707 const char *plat
= NULL
;
1708 const char *extra
= NULL
;
1709 char acsd
[MAX_PATH
] = {0};
1711 unsigned major
; unsigned minor
; const char *version
;
1712 } win_version_table
[] = {
1713 { 6, 1, "Windows 7" },
1714 { 6, 0, "Windows Vista" },
1715 { 5, 2, "Windows Server 2003" },
1716 { 5, 1, "Windows XP" },
1717 { 5, 0, "Windows 2000" },
1718 /* { 4, 0, "Windows NT 4.0" }, */
1719 { 4, 90, "Windows Me" },
1720 { 4, 10, "Windows 98" },
1721 /* { 4, 0, "Windows 95" } */
1722 { 3, 51, "Windows NT 3.51" },
1725 memset(&info
, 0, sizeof(info
));
1726 info
.dwOSVersionInfoSize
= sizeof(info
);
1727 if (! GetVersionEx((LPOSVERSIONINFO
)&info
)) {
1728 strlcpy(uname_result
, "Bizarre version of Windows where GetVersionEx"
1729 " doesn't work.", sizeof(uname_result
));
1730 uname_result_is_set
= 1;
1731 return uname_result
;
1734 wcstombs(acsd
, info
.szCSDVersion
, MAX_PATH
);
1736 strlcpy(acsd
, info
.szCSDVersion
, sizeof(acsd
));
1738 if (info
.dwMajorVersion
== 4 && info
.dwMinorVersion
== 0) {
1739 if (info
.dwPlatformId
== VER_PLATFORM_WIN32_NT
)
1740 plat
= "Windows NT 4.0";
1742 plat
= "Windows 95";
1745 else if (acsd
[1] == 'C')
1748 for (i
=0; win_version_table
[i
].major
>0; ++i
) {
1749 if (win_version_table
[i
].major
== info
.dwMajorVersion
&&
1750 win_version_table
[i
].minor
== info
.dwMinorVersion
) {
1751 plat
= win_version_table
[i
].version
;
1756 if (plat
&& !strcmp(plat
, "Windows 98")) {
1759 else if (acsd
[1] == 'B')
1765 tor_snprintf(uname_result
, sizeof(uname_result
), "%s %s",
1768 if (info
.dwMajorVersion
> 6 ||
1769 (info
.dwMajorVersion
==6 && info
.dwMinorVersion
>1))
1770 tor_snprintf(uname_result
, sizeof(uname_result
),
1771 "Very recent version of Windows [major=%d,minor=%d] %s",
1772 (int)info
.dwMajorVersion
,(int)info
.dwMinorVersion
,
1775 tor_snprintf(uname_result
, sizeof(uname_result
),
1776 "Unrecognized version of Windows [major=%d,minor=%d] %s",
1777 (int)info
.dwMajorVersion
,(int)info
.dwMinorVersion
,
1780 #if !defined (WINCE)
1781 #ifdef VER_SUITE_BACKOFFICE
1782 if (info
.wProductType
== VER_NT_DOMAIN_CONTROLLER
) {
1783 strlcat(uname_result
, " [domain controller]", sizeof(uname_result
));
1784 } else if (info
.wProductType
== VER_NT_SERVER
) {
1785 strlcat(uname_result
, " [server]", sizeof(uname_result
));
1786 } else if (info
.wProductType
== VER_NT_WORKSTATION
) {
1787 strlcat(uname_result
, " [workstation]", sizeof(uname_result
));
1792 strlcpy(uname_result
, "Unknown platform", sizeof(uname_result
));
1795 uname_result_is_set
= 1;
1797 return uname_result
;
1804 #if defined(USE_PTHREADS)
1805 /** Wraps a void (*)(void*) function and its argument so we can
1806 * invoke them in a way pthreads would expect.
1808 typedef struct tor_pthread_data_t
{
1809 void (*func
)(void *);
1811 } tor_pthread_data_t
;
1812 /** Given a tor_pthread_data_t <b>_data</b>, call _data->func(d->data)
1813 * and free _data. Used to make sure we can call functions the way pthread
1816 tor_pthread_helper_fn(void *_data
)
1818 tor_pthread_data_t
*data
= _data
;
1819 void (*func
)(void*);
1821 /* mask signals to worker threads to avoid SIGPIPE, etc */
1823 /* We're in a subthread; don't handle any signals here. */
1825 pthread_sigmask(SIG_SETMASK
, &sigs
, NULL
);
1835 /** Minimalist interface to run a void function in the background. On
1836 * Unix calls fork, on win32 calls beginthread. Returns -1 on failure.
1837 * func should not return, but rather should call spawn_exit.
1839 * NOTE: if <b>data</b> is used, it should not be allocated on the stack,
1840 * since in a multithreaded environment, there is no way to be sure that
1841 * the caller's stack will still be around when the called function is
1845 spawn_func(void (*func
)(void *), void *data
)
1847 #if defined(USE_WIN32_THREADS)
1849 rv
= (int)_beginthread(func
, 0, data
);
1853 #elif defined(USE_PTHREADS)
1855 tor_pthread_data_t
*d
;
1856 d
= tor_malloc(sizeof(tor_pthread_data_t
));
1859 if (pthread_create(&thread
,NULL
,tor_pthread_helper_fn
,d
))
1861 if (pthread_detach(thread
))
1872 tor_assert(0); /* Should never reach here. */
1873 return 0; /* suppress "control-reaches-end-of-non-void" warning. */
1881 /** End the current thread/process.
1886 #if defined(USE_WIN32_THREADS)
1888 //we should never get here. my compiler thinks that _endthread returns, this
1889 //is an attempt to fool it.
1892 #elif defined(USE_PTHREADS)
1895 /* http://www.erlenstar.demon.co.uk/unix/faq_2.html says we should
1896 * call _exit, not exit, from child processes. */
1901 /** Set *timeval to the current time of day. On error, log and terminate.
1902 * (Same as gettimeofday(timeval,NULL), but never returns -1.)
1905 tor_gettimeofday(struct timeval
*timeval
)
1908 /* Epoch bias copied from perl: number of units between windows epoch and
1910 #define EPOCH_BIAS U64_LITERAL(116444736000000000)
1911 #define UNITS_PER_SEC U64_LITERAL(10000000)
1912 #define USEC_PER_SEC U64_LITERAL(1000000)
1913 #define UNITS_PER_USEC U64_LITERAL(10)
1919 /* wince do not have GetSystemTimeAsFileTime */
1921 GetSystemTime(&stime
);
1922 SystemTimeToFileTime(&stime
,&ft
.ft_ft
);
1924 /* number of 100-nsec units since Jan 1, 1601 */
1925 GetSystemTimeAsFileTime(&ft
.ft_ft
);
1927 if (ft
.ft_64
< EPOCH_BIAS
) {
1928 log_err(LD_GENERAL
,"System time is before 1970; failing.");
1931 ft
.ft_64
-= EPOCH_BIAS
;
1932 timeval
->tv_sec
= (unsigned) (ft
.ft_64
/ UNITS_PER_SEC
);
1933 timeval
->tv_usec
= (unsigned) ((ft
.ft_64
/ UNITS_PER_USEC
) % USEC_PER_SEC
);
1934 #elif defined(HAVE_GETTIMEOFDAY)
1935 if (gettimeofday(timeval
, NULL
)) {
1936 log_err(LD_GENERAL
,"gettimeofday failed.");
1937 /* If gettimeofday dies, we have either given a bad timezone (we didn't),
1941 #elif defined(HAVE_FTIME)
1944 timeval
->tv_sec
= tb
.time
;
1945 timeval
->tv_usec
= tb
.millitm
* 1000;
1947 #error "No way to get time."
1952 #if defined(TOR_IS_MULTITHREADED) && !defined(MS_WINDOWS)
1953 /** Defined iff we need to add locks when defining fake versions of reentrant
1954 * versions of time-related functions. */
1955 #define TIME_FNS_NEED_LOCKS
1958 #ifndef HAVE_LOCALTIME_R
1959 #ifdef TIME_FNS_NEED_LOCKS
1961 tor_localtime_r(const time_t *timep
, struct tm
*result
)
1964 static tor_mutex_t
*m
=NULL
;
1965 if (!m
) { m
=tor_mutex_new(); }
1967 tor_mutex_acquire(m
);
1968 r
= localtime(timep
);
1969 memcpy(result
, r
, sizeof(struct tm
));
1970 tor_mutex_release(m
);
1975 tor_localtime_r(const time_t *timep
, struct tm
*result
)
1979 r
= localtime(timep
);
1980 memcpy(result
, r
, sizeof(struct tm
));
1986 #ifndef HAVE_GMTIME_R
1987 #ifdef TIME_FNS_NEED_LOCKS
1989 tor_gmtime_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
);
1997 memcpy(result
, r
, sizeof(struct tm
));
1998 tor_mutex_release(m
);
2003 tor_gmtime_r(const time_t *timep
, struct tm
*result
)
2008 memcpy(result
, r
, sizeof(struct tm
));
2014 #if defined(USE_WIN32_THREADS)
2016 tor_mutex_init(tor_mutex_t
*m
)
2018 InitializeCriticalSection(&m
->mutex
);
2021 tor_mutex_uninit(tor_mutex_t
*m
)
2023 DeleteCriticalSection(&m
->mutex
);
2026 tor_mutex_acquire(tor_mutex_t
*m
)
2029 EnterCriticalSection(&m
->mutex
);
2032 tor_mutex_release(tor_mutex_t
*m
)
2034 LeaveCriticalSection(&m
->mutex
);
2037 tor_get_thread_id(void)
2039 return (unsigned long)GetCurrentThreadId();
2041 #elif defined(USE_PTHREADS)
2042 /** A mutex attribute that we're going to use to tell pthreads that we want
2043 * "reentrant" mutexes (i.e., once we can re-lock if we're already holding
2045 static pthread_mutexattr_t attr_reentrant
;
2046 /** True iff we've called tor_threads_init() */
2047 static int threads_initialized
= 0;
2048 /** Initialize <b>mutex</b> so it can be locked. Every mutex must be set
2049 * up with tor_mutex_init() or tor_mutex_new(); not both. */
2051 tor_mutex_init(tor_mutex_t
*mutex
)
2054 if (PREDICT_UNLIKELY(!threads_initialized
))
2056 err
= pthread_mutex_init(&mutex
->mutex
, &attr_reentrant
);
2057 if (PREDICT_UNLIKELY(err
)) {
2058 log_err(LD_GENERAL
, "Error %d creating a mutex.", err
);
2059 tor_fragile_assert();
2062 /** Wait until <b>m</b> is free, then acquire it. */
2064 tor_mutex_acquire(tor_mutex_t
*m
)
2068 err
= pthread_mutex_lock(&m
->mutex
);
2069 if (PREDICT_UNLIKELY(err
)) {
2070 log_err(LD_GENERAL
, "Error %d locking a mutex.", err
);
2071 tor_fragile_assert();
2074 /** Release the lock <b>m</b> so another thread can have it. */
2076 tor_mutex_release(tor_mutex_t
*m
)
2080 err
= pthread_mutex_unlock(&m
->mutex
);
2081 if (PREDICT_UNLIKELY(err
)) {
2082 log_err(LD_GENERAL
, "Error %d unlocking a mutex.", err
);
2083 tor_fragile_assert();
2086 /** Clean up the mutex <b>m</b> so that it no longer uses any system
2087 * resources. Does not free <b>m</b>. This function must only be called on
2088 * mutexes from tor_mutex_init(). */
2090 tor_mutex_uninit(tor_mutex_t
*m
)
2094 err
= pthread_mutex_destroy(&m
->mutex
);
2095 if (PREDICT_UNLIKELY(err
)) {
2096 log_err(LD_GENERAL
, "Error %d destroying a mutex.", err
);
2097 tor_fragile_assert();
2100 /** Return an integer representing this thread. */
2102 tor_get_thread_id(void)
2108 r
.thr
= pthread_self();
2113 #ifdef TOR_IS_MULTITHREADED
2114 /** Return a newly allocated, ready-for-use mutex. */
2118 tor_mutex_t
*m
= tor_malloc_zero(sizeof(tor_mutex_t
));
2122 /** Release all storage and system resources held by <b>m</b>. */
2124 tor_mutex_free(tor_mutex_t
*m
)
2128 tor_mutex_uninit(m
);
2136 /** Cross-platform condition implementation. */
2138 pthread_cond_t cond
;
2140 /** Return a newly allocated condition, with nobody waiting on it. */
2144 tor_cond_t
*cond
= tor_malloc_zero(sizeof(tor_cond_t
));
2145 if (pthread_cond_init(&cond
->cond
, NULL
)) {
2151 /** Release all resources held by <b>cond</b>. */
2153 tor_cond_free(tor_cond_t
*cond
)
2157 if (pthread_cond_destroy(&cond
->cond
)) {
2158 log_warn(LD_GENERAL
,"Error freeing condition: %s", strerror(errno
));
2163 /** Wait until one of the tor_cond_signal functions is called on <b>cond</b>.
2164 * All waiters on the condition must wait holding the same <b>mutex</b>.
2165 * Returns 0 on success, negative on failure. */
2167 tor_cond_wait(tor_cond_t
*cond
, tor_mutex_t
*mutex
)
2169 return pthread_cond_wait(&cond
->cond
, &mutex
->mutex
) ? -1 : 0;
2171 /** Wake up one of the waiters on <b>cond</b>. */
2173 tor_cond_signal_one(tor_cond_t
*cond
)
2175 pthread_cond_signal(&cond
->cond
);
2177 /** Wake up all of the waiters on <b>cond</b>. */
2179 tor_cond_signal_all(tor_cond_t
*cond
)
2181 pthread_cond_broadcast(&cond
->cond
);
2184 /** Set up common structures for use by threading. */
2186 tor_threads_init(void)
2188 if (!threads_initialized
) {
2189 pthread_mutexattr_init(&attr_reentrant
);
2190 pthread_mutexattr_settype(&attr_reentrant
, PTHREAD_MUTEX_RECURSIVE
);
2191 threads_initialized
= 1;
2195 #elif defined(USE_WIN32_THREADS)
2197 static DWORD cond_event_tls_index
;
2199 CRITICAL_SECTION mutex
;
2200 smartlist_t
*events
;
2205 tor_cond_t
*cond
= tor_malloc_zero(sizeof(tor_cond_t
));
2206 InitializeCriticalSection(&cond
->mutex
);
2207 cond
->events
= smartlist_create();
2211 tor_cond_free(tor_cond_t
*cond
)
2215 DeleteCriticalSection(&cond
->mutex
);
2217 smartlist_free(cond
->events
);
2221 tor_cond_wait(tor_cond_t
*cond
, tor_mutex_t
*mutex
)
2227 event
= TlsGetValue(cond_event_tls_index
);
2229 event
= CreateEvent(0, FALSE
, FALSE
, NULL
);
2230 TlsSetValue(cond_event_tls_index
, event
);
2232 EnterCriticalSection(&cond
->mutex
);
2234 tor_assert(WaitForSingleObject(event
, 0) == WAIT_TIMEOUT
);
2235 tor_assert(!smartlist_isin(cond
->events
, event
));
2236 smartlist_add(cond
->events
, event
);
2238 LeaveCriticalSection(&cond
->mutex
);
2240 tor_mutex_release(mutex
);
2241 r
= WaitForSingleObject(event
, INFINITE
);
2242 tor_mutex_acquire(mutex
);
2245 case WAIT_OBJECT_0
: /* we got the mutex normally. */
2247 case WAIT_ABANDONED
: /* holding thread exited. */
2248 case WAIT_TIMEOUT
: /* Should never happen. */
2252 log_warn(LD_GENERAL
, "Failed to acquire mutex: %d",(int) GetLastError());
2257 tor_cond_signal_one(tor_cond_t
*cond
)
2262 EnterCriticalSection(&cond
->mutex
);
2264 if ((event
= smartlist_pop_last(cond
->events
)))
2267 LeaveCriticalSection(&cond
->mutex
);
2270 tor_cond_signal_all(tor_cond_t
*cond
)
2274 EnterCriticalSection(&cond
->mutex
);
2275 SMARTLIST_FOREACH(cond
->events
, HANDLE
, event
, SetEvent(event
));
2276 smartlist_clear(cond
->events
);
2277 LeaveCriticalSection(&cond
->mutex
);
2281 tor_threads_init(void)
2284 cond_event_tls_index
= TlsAlloc();
2290 #if defined(HAVE_MLOCKALL) && HAVE_DECL_MLOCKALL && defined(RLIMIT_MEMLOCK)
2291 /** Attempt to raise the current and max rlimit to infinity for our process.
2292 * This only needs to be done once and can probably only be done when we have
2293 * not already dropped privileges.
2296 tor_set_max_memlock(void)
2298 /* Future consideration for Windows is probably SetProcessWorkingSetSize
2299 * This is similar to setting the memory rlimit of RLIMIT_MEMLOCK
2300 * http://msdn.microsoft.com/en-us/library/ms686234(VS.85).aspx
2303 struct rlimit limit
;
2305 /* RLIM_INFINITY is -1 on some platforms. */
2306 limit
.rlim_cur
= RLIM_INFINITY
;
2307 limit
.rlim_max
= RLIM_INFINITY
;
2309 if (setrlimit(RLIMIT_MEMLOCK
, &limit
) == -1) {
2310 if (errno
== EPERM
) {
2311 log_warn(LD_GENERAL
, "You appear to lack permissions to change memory "
2312 "limits. Are you root?");
2314 log_warn(LD_GENERAL
, "Unable to raise RLIMIT_MEMLOCK: %s",
2323 /** Attempt to lock all current and all future memory pages.
2324 * This should only be called once and while we're privileged.
2325 * Like mlockall() we return 0 when we're successful and -1 when we're not.
2326 * Unlike mlockall() we return 1 if we've already attempted to lock memory.
2331 static int memory_lock_attempted
= 0;
2333 if (memory_lock_attempted
) {
2337 memory_lock_attempted
= 1;
2340 * Future consideration for Windows may be VirtualLock
2341 * VirtualLock appears to implement mlock() but not mlockall()
2343 * http://msdn.microsoft.com/en-us/library/aa366895(VS.85).aspx
2346 #if defined(HAVE_MLOCKALL) && HAVE_DECL_MLOCKALL && defined(RLIMIT_MEMLOCK)
2347 if (tor_set_max_memlock() == 0) {
2348 log_debug(LD_GENERAL
, "RLIMIT_MEMLOCK is now set to RLIM_INFINITY.");
2351 if (mlockall(MCL_CURRENT
|MCL_FUTURE
) == 0) {
2352 log_info(LD_GENERAL
, "Insecure OS paging is effectively disabled.");
2355 if (errno
== ENOSYS
) {
2356 /* Apple - it's 2009! I'm looking at you. Grrr. */
2357 log_notice(LD_GENERAL
, "It appears that mlockall() is not available on "
2359 } else if (errno
== EPERM
) {
2360 log_notice(LD_GENERAL
, "It appears that you lack the permissions to "
2361 "lock memory. Are you root?");
2363 log_notice(LD_GENERAL
, "Unable to lock all current and future memory "
2364 "pages: %s", strerror(errno
));
2368 log_warn(LD_GENERAL
, "Unable to lock memory pages. mlockall() unsupported?");
2373 /** Identity of the "main" thread */
2374 static unsigned long main_thread_id
= -1;
2376 /** Start considering the current thread to be the 'main thread'. This has
2377 * no effect on anything besides in_main_thread(). */
2379 set_main_thread(void)
2381 main_thread_id
= tor_get_thread_id();
2383 /** Return true iff called from the main thread. */
2385 in_main_thread(void)
2387 return main_thread_id
== tor_get_thread_id();
2391 * On Windows, WSAEWOULDBLOCK is not always correct: when you see it,
2392 * you need to ask the socket for its actual errno. Also, you need to
2393 * get your errors from WSAGetLastError, not errno. (If you supply a
2394 * socket of -1, we check WSAGetLastError, but don't correct
2397 * The upshot of all of this is that when a socket call fails, you
2398 * should call tor_socket_errno <em>at most once</em> on the failing
2399 * socket to get the error.
2401 #if defined(MS_WINDOWS)
2403 tor_socket_errno(int sock
)
2405 int optval
, optvallen
=sizeof(optval
);
2406 int err
= WSAGetLastError();
2407 if (err
== WSAEWOULDBLOCK
&& sock
>= 0) {
2408 if (getsockopt(sock
, SOL_SOCKET
, SO_ERROR
, (void*)&optval
, &optvallen
))
2417 #if defined(MS_WINDOWS)
2418 #define E(code, s) { code, (s " [" #code " ]") }
2419 struct { int code
; const char *msg
; } windows_socket_errors
[] = {
2420 E(WSAEINTR
, "Interrupted function call"),
2421 E(WSAEACCES
, "Permission denied"),
2422 E(WSAEFAULT
, "Bad address"),
2423 E(WSAEINVAL
, "Invalid argument"),
2424 E(WSAEMFILE
, "Too many open files"),
2425 E(WSAEWOULDBLOCK
, "Resource temporarily unavailable"),
2426 E(WSAEINPROGRESS
, "Operation now in progress"),
2427 E(WSAEALREADY
, "Operation already in progress"),
2428 E(WSAENOTSOCK
, "Socket operation on nonsocket"),
2429 E(WSAEDESTADDRREQ
, "Destination address required"),
2430 E(WSAEMSGSIZE
, "Message too long"),
2431 E(WSAEPROTOTYPE
, "Protocol wrong for socket"),
2432 E(WSAENOPROTOOPT
, "Bad protocol option"),
2433 E(WSAEPROTONOSUPPORT
, "Protocol not supported"),
2434 E(WSAESOCKTNOSUPPORT
, "Socket type not supported"),
2435 /* What's the difference between NOTSUPP and NOSUPPORT? :) */
2436 E(WSAEOPNOTSUPP
, "Operation not supported"),
2437 E(WSAEPFNOSUPPORT
, "Protocol family not supported"),
2438 E(WSAEAFNOSUPPORT
, "Address family not supported by protocol family"),
2439 E(WSAEADDRINUSE
, "Address already in use"),
2440 E(WSAEADDRNOTAVAIL
, "Cannot assign requested address"),
2441 E(WSAENETDOWN
, "Network is down"),
2442 E(WSAENETUNREACH
, "Network is unreachable"),
2443 E(WSAENETRESET
, "Network dropped connection on reset"),
2444 E(WSAECONNABORTED
, "Software caused connection abort"),
2445 E(WSAECONNRESET
, "Connection reset by peer"),
2446 E(WSAENOBUFS
, "No buffer space available"),
2447 E(WSAEISCONN
, "Socket is already connected"),
2448 E(WSAENOTCONN
, "Socket is not connected"),
2449 E(WSAESHUTDOWN
, "Cannot send after socket shutdown"),
2450 E(WSAETIMEDOUT
, "Connection timed out"),
2451 E(WSAECONNREFUSED
, "Connection refused"),
2452 E(WSAEHOSTDOWN
, "Host is down"),
2453 E(WSAEHOSTUNREACH
, "No route to host"),
2454 E(WSAEPROCLIM
, "Too many processes"),
2455 /* Yes, some of these start with WSA, not WSAE. No, I don't know why. */
2456 E(WSASYSNOTREADY
, "Network subsystem is unavailable"),
2457 E(WSAVERNOTSUPPORTED
, "Winsock.dll out of range"),
2458 E(WSANOTINITIALISED
, "Successful WSAStartup not yet performed"),
2459 E(WSAEDISCON
, "Graceful shutdown now in progress"),
2460 #ifdef WSATYPE_NOT_FOUND
2461 E(WSATYPE_NOT_FOUND
, "Class type not found"),
2463 E(WSAHOST_NOT_FOUND
, "Host not found"),
2464 E(WSATRY_AGAIN
, "Nonauthoritative host not found"),
2465 E(WSANO_RECOVERY
, "This is a nonrecoverable error"),
2466 E(WSANO_DATA
, "Valid name, no data record of requested type)"),
2468 /* There are some more error codes whose numeric values are marked
2469 * <b>OS dependent</b>. They start with WSA_, apparently for the same
2470 * reason that practitioners of some craft traditions deliberately
2471 * introduce imperfections into their baskets and rugs "to allow the
2472 * evil spirits to escape." If we catch them, then our binaries
2473 * might not report consistent results across versions of Windows.
2474 * Thus, I'm going to let them all fall through.
2478 /** There does not seem to be a strerror equivalent for Winsock errors.
2479 * Naturally, we have to roll our own.
2482 tor_socket_strerror(int e
)
2485 for (i
=0; windows_socket_errors
[i
].code
>= 0; ++i
) {
2486 if (e
== windows_socket_errors
[i
].code
)
2487 return windows_socket_errors
[i
].msg
;
2493 /** Called before we make any calls to network-related functions.
2494 * (Some operating systems require their network libraries to be
2500 /* This silly exercise is necessary before windows will allow
2501 * gethostbyname to work. */
2504 r
= WSAStartup(0x101,&WSAData
);
2506 log_warn(LD_NET
,"Error initializing windows network layer: code was %d",r
);
2509 /* WSAData.iMaxSockets might show the max sockets we're allowed to use.
2510 * We might use it to complain if we're trying to be a server but have
2511 * too few sockets available. */
2517 /** Return a newly allocated string describing the windows system error code
2518 * <b>err</b>. Note that error codes are different from errno. Error codes
2519 * come from GetLastError() when a winapi call fails. errno is set only when
2520 * ANSI functions fail. Whee. */
2522 format_win32_error(DWORD err
)
2527 /* Somebody once decided that this interface was better than strerror(). */
2528 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
|
2529 FORMAT_MESSAGE_FROM_SYSTEM
|
2530 FORMAT_MESSAGE_IGNORE_INSERTS
,
2532 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
2538 char abuf
[1024] = {0};
2539 wcstombs(abuf
,str
,1024);
2540 result
= tor_strdup(abuf
);
2542 result
= tor_strdup(str
);
2544 LocalFree(str
); /* LocalFree != free() */
2546 result
= tor_strdup("<unformattable error>");