1 /* Copyright (c) 2003-2004, Roger Dingledine
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2008, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
6 const char compat_c_id
[] =
11 * \brief Wrappers to make calls more portable. This code defines
12 * functions such as tor_malloc, tor_snprintf, get/set various data types,
13 * renaming, setting socket options, switching user IDs. It is basically
14 * where the non-portable items are conditionally included depending on
18 /* This is required on rh7 to make strptime not complain.
19 * We also need it to make memmem get defined (where available)
32 #include <sys/utsname.h>
34 #ifdef HAVE_SYS_TIME_H
40 #ifdef HAVE_SYS_FCNTL_H
41 #include <sys/fcntl.h>
52 #ifdef HAVE_SYS_RESOURCE_H
53 #include <sys/resource.h>
58 #ifdef HAVE_NETINET_IN_H
59 #include <netinet/in.h>
61 #ifdef HAVE_ARPA_INET_H
62 #include <arpa/inet.h>
64 #ifndef HAVE_GETTIMEOFDAY
66 #include <sys/timeb.h>
69 #ifdef HAVE_SYS_SOCKET_H
70 #include <sys/socket.h>
75 #ifdef HAVE_SYS_PARAM_H
76 #include <sys/param.h> /* FreeBSD needs this to know what version it is */
92 #ifdef HAVE_SYS_UTIME_H
93 #include <sys/utime.h>
95 #ifdef HAVE_SYS_MMAN_H
98 #ifdef HAVE_SYS_SYSLIMITS_H
99 #include <sys/syslimits.h>
108 #include "container.h"
110 /* Inline the strl functions if the platform doesn't have them. */
119 /* This is used by inet_addr, but apparently Solaris doesn't define it
121 #define INADDR_NONE ((unsigned long) -1)
124 #ifdef HAVE_SYS_MMAN_H
125 /** Implementation for tor_mmap_t: holds the regular tor_mmap_t, along
126 * with extra fields needed for mmap()-based memory mapping. */
127 typedef struct tor_mmap_impl_t
{
129 size_t mapping_size
; /**< Size of the actual mapping. (This is this file
130 * size, rounded up to the nearest page.) */
133 /** Try to create a memory mapping for <b>filename</b> and return it. On
134 * failure, return NULL. Sets errno properly, using ERANGE to mean
137 tor_mmap_file(const char *filename
)
139 int fd
; /* router file */
142 tor_mmap_impl_t
*res
;
143 size_t size
, filesize
;
145 tor_assert(filename
);
147 fd
= open(filename
, O_RDONLY
, 0);
149 int save_errno
= errno
;
150 int severity
= (errno
== ENOENT
) ? LOG_INFO
: LOG_WARN
;
151 log_fn(severity
, LD_FS
,"Could not open \"%s\" for mmap(): %s",filename
,
157 size
= filesize
= (size_t) lseek(fd
, 0, SEEK_END
);
158 lseek(fd
, 0, SEEK_SET
);
159 /* ensure page alignment */
160 page_size
= getpagesize();
161 size
+= (size
%page_size
) ? page_size
-(size
%page_size
) : 0;
164 /* Zero-length file. If we call mmap on it, it will succeed but
165 * return NULL, and bad things will happen. So just fail. */
166 log_info(LD_FS
,"File \"%s\" is empty. Ignoring.",filename
);
172 string
= mmap(0, size
, PROT_READ
, MAP_PRIVATE
, fd
, 0);
174 if (string
== MAP_FAILED
) {
175 int save_errno
= errno
;
176 log_warn(LD_FS
,"Could not mmap file \"%s\": %s", filename
,
182 res
= tor_malloc_zero(sizeof(tor_mmap_impl_t
));
183 res
->base
.data
= string
;
184 res
->base
.size
= filesize
;
185 res
->mapping_size
= size
;
189 /** Release storage held for a memory mapping. */
191 tor_munmap_file(tor_mmap_t
*handle
)
193 tor_mmap_impl_t
*h
= SUBTYPE_P(handle
, tor_mmap_impl_t
, base
);
194 munmap((char*)h
->base
.data
, h
->mapping_size
);
197 #elif defined(MS_WINDOWS)
198 /** Implementation for tor_mmap_t: holds the regular tor_mmap_t, along
199 * with extra fields needed for WIN32 memory mapping. */
200 typedef struct win_mmap_t
{
206 tor_mmap_file(const char *filename
)
208 win_mmap_t
*res
= tor_malloc_zero(sizeof(win_mmap_t
));
210 res
->file_handle
= INVALID_HANDLE_VALUE
;
211 res
->mmap_handle
= NULL
;
213 res
->file_handle
= CreateFile(filename
,
214 GENERIC_READ
, FILE_SHARE_READ
,
217 FILE_ATTRIBUTE_NORMAL
,
220 if (res
->file_handle
== INVALID_HANDLE_VALUE
)
223 res
->base
.size
= GetFileSize(res
->file_handle
, NULL
);
225 if (res
->base
.size
== 0) {
226 log_info(LD_FS
,"File \"%s\" is empty. Ignoring.",filename
);
231 res
->mmap_handle
= CreateFileMapping(res
->file_handle
,
234 #if SIZEOF_SIZE_T > 4
235 (res
->base
.size
>> 32),
239 (res
->base
.size
& 0xfffffffful
),
241 if (res
->mmap_handle
== NULL
)
243 res
->base
.data
= (char*) MapViewOfFile(res
->mmap_handle
,
251 DWORD e
= GetLastError();
252 int severity
= (e
== ERROR_FILE_NOT_FOUND
|| e
== ERROR_PATH_NOT_FOUND
) ?
254 char *msg
= format_win32_error(e
);
255 log_fn(severity
, LD_FS
, "Couldn't mmap file \"%s\": %s", filename
, msg
);
257 if (e
== ERROR_FILE_NOT_FOUND
|| e
== ERROR_PATH_NOT_FOUND
)
265 tor_munmap_file(&res
->base
);
269 tor_munmap_file(tor_mmap_t
*handle
)
271 win_mmap_t
*h
= SUBTYPE_P(handle
, win_mmap_t
, base
);
273 /* This is an ugly cast, but without it, "data" in struct tor_mmap_t would
274 have to be redefined as non-const. */
275 UnmapViewOfFile( (LPVOID
) handle
->data
);
277 if (h
->mmap_handle
!= NULL
)
278 CloseHandle(h
->mmap_handle
);
279 if (h
->file_handle
!= INVALID_HANDLE_VALUE
)
280 CloseHandle(h
->file_handle
);
285 tor_mmap_file(const char *filename
)
288 char *res
= read_file_to_str(filename
, RFTS_BIN
|RFTS_IGNORE_MISSING
, &st
);
292 handle
= tor_malloc_zero(sizeof(tor_mmap_t
));
294 handle
->size
= st
.st_size
;
298 tor_munmap_file(tor_mmap_t
*handle
)
300 char *d
= (char*)handle
->data
;
302 memset(handle
, 0, sizeof(tor_mmap_t
));
307 /** Replacement for snprintf. Differs from platform snprintf in two
308 * ways: First, always NUL-terminates its output. Second, always
309 * returns -1 if the result is truncated. (Note that this return
310 * behavior does <i>not</i> conform to C99; it just happens to be
311 * easier to emulate "return -1" with conformant implementations than
312 * it is to emulate "return number that would be written" with
313 * non-conformant implementations.) */
315 tor_snprintf(char *str
, size_t size
, const char *format
, ...)
320 r
= tor_vsnprintf(str
,size
,format
,ap
);
325 /** Replacement for vsnprintf; behavior differs as tor_snprintf differs from
329 tor_vsnprintf(char *str
, size_t size
, const char *format
, va_list args
)
333 return -1; /* no place for the NUL */
334 if (size
> SIZE_T_CEILING
)
337 r
= _vsnprintf(str
, size
, format
, args
);
339 r
= vsnprintf(str
, size
, format
, args
);
342 if (r
< 0 || ((size_t)r
) >= size
)
347 /** Given <b>hlen</b> bytes at <b>haystack</b> and <b>nlen</b> bytes at
348 * <b>needle</b>, return a pointer to the first occurrence of the needle
349 * within the haystack, or NULL if there is no such occurrence.
351 * Requires that nlen be greater than zero.
354 tor_memmem(const void *_haystack
, size_t hlen
,
355 const void *_needle
, size_t nlen
)
357 #if defined(HAVE_MEMMEM) && (!defined(__GNUC__) || __GNUC__ >= 2)
359 return memmem(_haystack
, hlen
, _needle
, nlen
);
361 /* This isn't as fast as the GLIBC implementation, but it doesn't need to
364 const char *haystack
= (const char*)_haystack
;
365 const char *needle
= (const char*)_needle
;
370 end
= haystack
+ hlen
;
371 first
= *(const char*)needle
;
372 while ((p
= memchr(p
, first
, end
-p
))) {
375 if (!memcmp(p
, needle
, nlen
))
384 /** Take a filename and return a pointer to its final element. This
385 * function is called on __FILE__ to fix a MSVC nit where __FILE__
386 * contains the full path to the file. This is bad, because it
387 * confuses users to find the home directory of the person who
388 * compiled the binary in their warrning messages.
391 tor_fix_source_file(const char *fname
)
393 const char *cp1
, *cp2
, *r
;
394 cp1
= strrchr(fname
, '/');
395 cp2
= strrchr(fname
, '\\');
397 r
= (cp1
<cp2
)?(cp2
+1):(cp1
+1);
410 * Read a 16-bit value beginning at <b>cp</b>. Equivalent to
411 * *(uint16_t*)(cp), but will not cause segfaults on platforms that forbid
412 * unaligned memory access.
415 get_uint16(const char *cp
)
422 * Read a 32-bit value beginning at <b>cp</b>. Equivalent to
423 * *(uint32_t*)(cp), but will not cause segfaults on platforms that forbid
424 * unaligned memory access.
427 get_uint32(const char *cp
)
434 * Set a 16-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
435 * *(uint16_t)(cp) = v, but will not cause segfaults on platforms that forbid
436 * unaligned memory access. */
438 set_uint16(char *cp
, uint16_t v
)
443 * Set a 32-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
444 * *(uint32_t)(cp) = v, but will not cause segfaults on platforms that forbid
445 * unaligned memory access. */
447 set_uint32(char *cp
, uint32_t v
)
453 * Rename the file <b>from</b> to the file <b>to</b>. On unix, this is
454 * the same as rename(2). On windows, this removes <b>to</b> first if
456 * Returns 0 on success. Returns -1 and sets errno on failure.
459 replace_file(const char *from
, const char *to
)
462 return rename(from
,to
);
464 switch (file_status(to
))
469 if (unlink(to
)) return -1;
477 return rename(from
,to
);
481 /** Change <b>fname</b>'s modification time to now. */
483 touch_file(const char *fname
)
485 if (utime(fname
, NULL
)!=0)
490 /** Count of number of sockets currently open. (Undercounts sockets opened by
491 * eventdns and libevent.) */
492 static int n_sockets_open
= 0;
494 /** As close(), but guaranteed to work for sockets across platforms (including
495 * Windows, where close()ing a socket doesn't work. Returns 0 on success, -1
498 tor_close_socket(int s
)
501 /* On Windows, you have to call close() on fds returned by open(),
502 * and closesocket() on fds returned by socket(). On Unix, everything
503 * gets close()'d. We abstract this difference by always using
504 * tor_close_socket to close sockets, and always using close() on
509 #elif defined(MS_WINDOWS)
517 int err
= tor_socket_errno(-1);
518 log_info(LD_NET
, "Close returned an error: %s", tor_socket_strerror(err
));
520 if (err
!= WSAENOTSOCK
)
528 if (n_sockets_open
< 0)
529 log_warn(LD_BUG
, "Our socket count is below zero: %d. Please submit a "
530 "bug report.", n_sockets_open
);
534 /** As socket(), but counts the number of open sockets. */
536 tor_open_socket(int domain
, int type
, int protocol
)
538 int s
= socket(domain
, type
, protocol
);
544 /** Return the number of sockets we currently have opened. */
546 get_n_open_sockets(void)
548 return n_sockets_open
;
551 /** Turn <b>socket</b> into a nonblocking socket.
554 set_socket_nonblocking(int socket
)
556 #if defined(MS_WINDOWS) && !defined(USE_BSOCKETS)
557 unsigned long nonblocking
= 1;
558 ioctlsocket(socket
, FIONBIO
, (unsigned long*) &nonblocking
);
560 fcntl(socket
, F_SETFL
, O_NONBLOCK
);
565 * Allocate a pair of connected sockets. (Like socketpair(family,
566 * type,protocol,fd), but works on systems that don't have
569 * Currently, only (AF_UNIX, SOCK_STREAM, 0) sockets are supported.
571 * Note that on systems without socketpair, this call will fail if
572 * localhost is inaccessible (for example, if the networking
573 * stack is down). And even if it succeeds, the socket pair will not
574 * be able to read while localhost is down later (the socket pair may
575 * even close, depending on OS-specific timeouts).
577 * Returns 0 on success and -errno on failure; do not rely on the value
578 * of errno or WSAGetLastError().
580 /* It would be nicer just to set errno, but that won't work for windows. */
582 tor_socketpair(int family
, int type
, int protocol
, int fd
[2])
584 //don't use win32 socketpairs (they are always bad)
585 #if defined(HAVE_SOCKETPAIR) && !defined(MS_WINDOWS)
587 r
= socketpair(family
, type
, protocol
, fd
);
588 return r
< 0 ? -errno
: r
;
589 #elif defined(USE_BSOCKETS)
590 return bsocketpair(family
, type
, protocol
, fd
);
592 /* This socketpair does not work when localhost is down. So
593 * it's really not the same thing at all. But it's close enough
594 * for now, and really, when localhost is down sometimes, we
595 * have other problems too.
600 struct sockaddr_in listen_addr
;
601 struct sockaddr_in connect_addr
;
603 int saved_errno
= -1;
611 return -WSAEAFNOSUPPORT
;
613 return -EAFNOSUPPORT
;
620 listener
= tor_open_socket(AF_INET
, type
, 0);
622 return -tor_socket_errno(-1);
623 memset(&listen_addr
, 0, sizeof(listen_addr
));
624 listen_addr
.sin_family
= AF_INET
;
625 listen_addr
.sin_addr
.s_addr
= htonl(INADDR_LOOPBACK
);
626 listen_addr
.sin_port
= 0; /* kernel chooses port. */
627 if (bind(listener
, (struct sockaddr
*) &listen_addr
, sizeof (listen_addr
))
629 goto tidy_up_and_fail
;
630 if (listen(listener
, 1) == -1)
631 goto tidy_up_and_fail
;
633 connector
= tor_open_socket(AF_INET
, type
, 0);
635 goto tidy_up_and_fail
;
636 /* We want to find out the port number to connect to. */
637 size
= sizeof(connect_addr
);
638 if (getsockname(listener
, (struct sockaddr
*) &connect_addr
, &size
) == -1)
639 goto tidy_up_and_fail
;
640 if (size
!= sizeof (connect_addr
))
641 goto abort_tidy_up_and_fail
;
642 if (connect(connector
, (struct sockaddr
*) &connect_addr
,
643 sizeof(connect_addr
)) == -1)
644 goto tidy_up_and_fail
;
646 size
= sizeof(listen_addr
);
647 acceptor
= accept(listener
, (struct sockaddr
*) &listen_addr
, &size
);
649 goto tidy_up_and_fail
;
650 if (size
!= sizeof(listen_addr
))
651 goto abort_tidy_up_and_fail
;
652 tor_close_socket(listener
);
653 /* Now check we are talking to ourself by matching port and host on the
655 if (getsockname(connector
, (struct sockaddr
*) &connect_addr
, &size
) == -1)
656 goto tidy_up_and_fail
;
657 if (size
!= sizeof (connect_addr
)
658 || listen_addr
.sin_family
!= connect_addr
.sin_family
659 || listen_addr
.sin_addr
.s_addr
!= connect_addr
.sin_addr
.s_addr
660 || listen_addr
.sin_port
!= connect_addr
.sin_port
) {
661 goto abort_tidy_up_and_fail
;
668 abort_tidy_up_and_fail
:
670 saved_errno
= WSAECONNABORTED
;
672 saved_errno
= ECONNABORTED
; /* I hope this is portable and appropriate. */
678 tor_close_socket(listener
);
680 tor_close_socket(connector
);
682 tor_close_socket(acceptor
);
687 #define ULIMIT_BUFFER 32 /* keep 32 extra fd's beyond _ConnLimit */
689 #if defined(HAVE_GETRLIMIT) && !defined(HAVE_RLIM_T)
690 typedef unsigned long rlim_t
;
693 /** Learn the maximum allowed number of file descriptors. (Some systems
694 * have a low soft limit.
696 * We compute this by finding the largest number between <b>limit</b>
697 * and <b>cap</b> that we can use. If we can't find a number greater
698 * than or equal to <b>limit</b>, then we fail: return -1.
700 * Otherwise, return the number minus some buffer to allow for other
701 * file descriptors we'll want available for ordinary use. */
703 set_max_file_descriptors(unsigned long limit
, unsigned long cap
)
705 #ifndef HAVE_GETRLIMIT
706 log_fn(LOG_INFO
, LD_NET
,
707 "This platform is missing getrlimit(). Proceeding.");
709 log_info(LD_CONFIG
, "ConnLimit must be at most %d. Using that.", (int)cap
);
715 tor_assert(limit
> 0);
718 if (getrlimit(RLIMIT_NOFILE
, &rlim
) != 0) {
719 log_warn(LD_NET
, "Could not get maximum number of file descriptors: %s",
723 //log_notice(LD_CONFIG, "%llu %llu", rlim.rlim_cur, rlim.rlim_max);
724 if ((unsigned long)rlim
.rlim_max
< limit
) {
725 log_warn(LD_CONFIG
,"We need %lu file descriptors available, and we're "
726 "limited to %lu. Please change your ulimit -n.",
727 limit
, (unsigned long)rlim
.rlim_max
);
730 most
= rlim
.rlim_max
> (rlim_t
)cap
? (rlim_t
)cap
: rlim
.rlim_max
;
731 if ((rlim_t
)most
> rlim
.rlim_cur
) {
732 log_info(LD_NET
,"Raising max file descriptors from %lu to %lu.",
733 (unsigned long)rlim
.rlim_cur
, (unsigned long)most
);
735 rlim
.rlim_cur
= most
;
737 if (setrlimit(RLIMIT_NOFILE
, &rlim
) != 0) {
740 if (errno
== EINVAL
&& OPEN_MAX
< rlim
.rlim_cur
) {
741 /* On some platforms, OPEN_MAX is the real limit, and getrlimit() is
742 * full of nasty lies. I'm looking at you, OSX 10.5.... */
743 rlim
.rlim_cur
= OPEN_MAX
;
744 if (setrlimit(RLIMIT_NOFILE
, &rlim
) == 0) {
745 if (rlim
.rlim_cur
< (rlim_t
)limit
) {
746 log_warn(LD_CONFIG
, "We are limited to %lu file descriptors by "
747 "OPEN_MAX, and ConnLimit is %lu. Changing ConnLimit; sorry.",
748 (unsigned long)OPEN_MAX
, limit
);
750 log_info(LD_CONFIG
, "Dropped connection limit to OPEN_MAX (%lu); "
751 "Apparently, %lu was too high and rlimit lied to us.",
752 (unsigned long)OPEN_MAX
, (unsigned long)most
);
754 most
= rlim
.rlim_cur
;
760 log_warn(LD_CONFIG
,"Couldn't set maximum number of file descriptors: %s",
765 /* leave some overhead for logs, etc, */
769 if (limit
< ULIMIT_BUFFER
) {
771 "ConnLimit must be at least %d. Failing.", ULIMIT_BUFFER
);
774 return limit
- ULIMIT_BUFFER
;
777 /** Call setuid and setgid to run as <b>user</b>:<b>group</b>. Return 0 on
778 * success. On failure, log and return -1.
781 switch_id(const char *user
, const char *group
)
784 struct passwd
*pw
= NULL
;
785 struct group
*gr
= NULL
;
790 log_warn(LD_CONFIG
,"User '%s' not found.", user
);
795 /* switch the group first, while we still have the privileges to do so */
797 gr
= getgrnam(group
);
799 log_warn(LD_CONFIG
,"Group '%s' not found.", group
);
803 if (setgid(gr
->gr_gid
) != 0) {
804 log_warn(LD_GENERAL
,"Error setting to configured GID: %s",
809 if (setgid(pw
->pw_gid
) != 0) {
810 log_warn(LD_GENERAL
,"Error setting to user GID: %s", strerror(errno
));
815 /* now that the group is switched, we can switch users and lose
818 if (setuid(pw
->pw_uid
) != 0) {
819 log_warn(LD_GENERAL
,"Error setting UID: %s", strerror(errno
));
831 "User or group specified, but switching users is not supported.");
836 /** Allocate and return a string containing the home directory for the
837 * user <b>username</b>. Only works on posix-like systems. */
839 get_user_homedir(const char *username
)
842 tor_assert(username
);
844 if (!(pw
= getpwnam(username
))) {
845 log_err(LD_CONFIG
,"User \"%s\" not found.", username
);
848 return tor_strdup(pw
->pw_dir
);
852 /** Set *addr to the IP address (in dotted-quad notation) stored in c.
853 * Return 1 on success, 0 if c is badly formatted. (Like inet_aton(c,addr),
854 * but works on Windows and Solaris.)
857 tor_inet_aton(const char *c
, struct in_addr
* addr
)
859 #ifdef HAVE_INET_ATON
860 return inet_aton(c
, addr
);
865 if (strcmp(c
, "255.255.255.255") == 0) {
866 addr
->s_addr
= 0xFFFFFFFFu
;
870 if (r
== INADDR_NONE
)
877 /** Given <b>af</b>==AF_INET and <b>src</b> a struct in_addr, or
878 * <b>af</b>==AF_INET6 and <b>src</b> a struct in6_addr, try to format the
879 * address and store it in the <b>len</b>-byte buffer <b>dst</b>. Returns
880 * <b>dst</b> on success, NULL on failure.
882 * (Like inet_ntop(af,src,dst,len), but works on platforms that don't have it:
883 * Tor sometimes needs to format ipv6 addresses even on platforms without ipv6
886 tor_inet_ntop(int af
, const void *src
, char *dst
, size_t len
)
889 if (tor_inet_ntoa(src
, dst
, len
) < 0)
893 } else if (af
== AF_INET6
) {
894 const struct in6_addr
*addr
= src
;
896 int longestGapLen
= 0, longestGapPos
= -1, i
,
897 curGapPos
= -1, curGapLen
= 0;
899 for (i
= 0; i
< 8; ++i
) {
900 words
[i
] = (((uint16_t)addr
->s6_addr
[2*i
])<<8) + addr
->s6_addr
[2*i
+1];
902 if (words
[0] == 0 && words
[1] == 0 && words
[2] == 0 && words
[3] == 0 &&
903 words
[4] == 0 && ((words
[5] == 0 && words
[6] && words
[7]) ||
904 (words
[5] == 0xffff))) {
905 /* This is an IPv4 address. */
907 tor_snprintf(buf
, sizeof(buf
), "::%d.%d.%d.%d",
908 addr
->s6_addr
[12], addr
->s6_addr
[13],
909 addr
->s6_addr
[14], addr
->s6_addr
[15]);
911 tor_snprintf(buf
, sizeof(buf
), "::%x:%d.%d.%d.%d", words
[5],
912 addr
->s6_addr
[12], addr
->s6_addr
[13],
913 addr
->s6_addr
[14], addr
->s6_addr
[15]);
915 if (strlen(buf
) > len
)
917 strlcpy(dst
, buf
, len
);
925 while (i
<8 && words
[i
] == 0) {
928 if (curGapLen
> longestGapLen
) {
929 longestGapPos
= curGapPos
;
930 longestGapLen
= curGapLen
;
936 if (longestGapLen
<=1)
940 for (i
= 0; i
< 8; ++i
) {
941 if (words
[i
] == 0 && longestGapPos
== i
) {
945 while (i
< 8 && words
[i
] == 0)
947 --i
; /* to compensate for loop increment. */
949 tor_snprintf(cp
, sizeof(buf
)-(cp
-buf
), "%x", (unsigned)words
[i
]);
956 if (strlen(buf
) > len
)
958 strlcpy(dst
, buf
, len
);
965 /** Given <b>af</b>==AF_INET or <b>af</b>==AF_INET6, and a string <b>src</b>
966 * encoding an IPv4 address or IPv6 address correspondingly, try to parse the
967 * address and store the result in <b>dst</b> (which must have space for a
968 * struct in_addr or a struct in6_addr, as appropriate). Return 1 on success,
969 * 0 on a bad parse, and -1 on a bad <b>af</b>.
971 * (Like inet_pton(af,src,dst) but works on platforms that don't have it: Tor
972 * sometimes needs to format ipv6 addresses even on platforms without ipv6
975 tor_inet_pton(int af
, const char *src
, void *dst
)
978 return tor_inet_aton(src
, dst
);
979 } else if (af
== AF_INET6
) {
980 struct in6_addr
*out
= dst
;
982 int gapPos
= -1, i
, setWords
=0;
983 const char *dot
= strchr(src
, '.');
984 const char *eow
; /* end of words. */
988 eow
= src
+strlen(src
);
990 int byte1
,byte2
,byte3
,byte4
;
992 for (eow
= dot
-1; eow
>= src
&& TOR_ISDIGIT(*eow
); --eow
)
996 /* We use "scanf" because some platform inet_aton()s are too lax
997 * about IPv4 addresses of the form "1.2.3" */
998 if (sscanf(eow
, "%d.%d.%d.%d%c", &byte1
,&byte2
,&byte3
,&byte4
,&more
) != 4)
1001 if (byte1
> 255 || byte1
< 0 ||
1002 byte2
> 255 || byte2
< 0 ||
1003 byte3
> 255 || byte3
< 0 ||
1004 byte4
> 255 || byte4
< 0)
1007 words
[6] = (byte1
<<8) | byte2
;
1008 words
[7] = (byte3
<<8) | byte4
;
1016 if (TOR_ISXDIGIT(*src
)) {
1018 int r
= strtol(src
, &next
, 16);
1026 words
[i
++] = (uint16_t)r
;
1029 if (*src
!= ':' && src
!= eow
)
1032 } else if (*src
== ':' && i
> 0 && gapPos
==-1) {
1035 } else if (*src
== ':' && i
== 0 && src
[1] == ':' && gapPos
==-1) {
1044 (setWords
== 8 && gapPos
!= -1) ||
1045 (setWords
< 8 && gapPos
== -1))
1049 int nToMove
= setWords
- (dot
? 2 : 0) - gapPos
;
1050 int gapLen
= 8 - setWords
;
1051 tor_assert(nToMove
>= 0);
1052 memmove(&words
[gapPos
+gapLen
], &words
[gapPos
],
1053 sizeof(uint16_t)*nToMove
);
1054 memset(&words
[gapPos
], 0, sizeof(uint16_t)*gapLen
);
1056 for (i
= 0; i
< 8; ++i
) {
1057 out
->s6_addr
[2*i
] = words
[i
] >> 8;
1058 out
->s6_addr
[2*i
+1] = words
[i
] & 0xff;
1067 /** Similar behavior to Unix gethostbyname: resolve <b>name</b>, and set
1068 * *<b>addr</b> to the proper IP address, in host byte order. Returns 0
1069 * on success, -1 on failure; 1 on transient failure.
1071 * (This function exists because standard windows gethostbyname
1072 * doesn't treat raw IP addresses properly.)
1075 tor_lookup_hostname(const char *name
, uint32_t *addr
)
1080 if ((ret
= tor_addr_lookup(name
, AF_INET
, &myaddr
)))
1083 if (IN_FAMILY(&myaddr
) == AF_INET
) {
1084 *addr
= IPV4IPh(&myaddr
);
1091 /** Similar behavior to Unix gethostbyname: resolve <b>name</b>, and set
1092 * *<b>addr</b> to the proper IP address and family. The <b>family</b>
1093 * argument (which must be AF_INET, AF_INET6, or AF_UNSPEC) declares a
1094 * <i>preferred</i> family, though another one may be returned if only one
1095 * family is implemented for this address.
1097 * Return 0 on success, -1 on failure; 1 on transient failure.
1100 tor_addr_lookup(const char *name
, uint16_t family
, tor_addr_t
*addr
)
1102 /* Perhaps eventually this should be replaced by a tor_getaddrinfo or
1105 struct in_addr iaddr
;
1106 struct in6_addr iaddr6
;
1109 tor_assert(family
== AF_INET
|| family
== AF_UNSPEC
);
1110 memset(addr
, 0, sizeof(addr
)); /* Clear the extraneous fields. */
1112 /* Empty address is an error. */
1114 } else if (tor_inet_pton(AF_INET
, name
, &iaddr
)) {
1115 /* It's an IPv4 IP. */
1116 addr
->family
= AF_INET
;
1117 memcpy(&addr
->addr
.in_addr
, &iaddr
, sizeof(struct in_addr
));
1119 } else if (tor_inet_pton(AF_INET6
, name
, &iaddr6
)) {
1120 addr
->family
= AF_INET6
;
1121 memcpy(&addr
->addr
.in6_addr
, &iaddr6
, sizeof(struct in6_addr
));
1124 #ifdef HAVE_GETADDRINFO
1126 struct addrinfo
*res
=NULL
, *res_p
;
1127 struct addrinfo
*best
=NULL
;
1128 struct addrinfo hints
;
1130 memset(&hints
, 0, sizeof(hints
));
1131 hints
.ai_family
= family
;
1132 hints
.ai_socktype
= SOCK_STREAM
;
1133 err
= getaddrinfo(name
, NULL
, &hints
, &res
);
1136 for (res_p
= res
; res_p
; res_p
= res_p
->ai_next
) {
1137 if (family
== AF_UNSPEC
) {
1138 if (res_p
->ai_family
== AF_INET
) {
1141 } else if (res_p
->ai_family
== AF_INET6
&& !best
) {
1144 } else if (family
== res_p
->ai_family
) {
1151 if (best
->ai_family
== AF_INET
) {
1152 addr
->family
= AF_INET
;
1153 memcpy(&addr
->addr
.in_addr
,
1154 &((struct sockaddr_in
*)best
->ai_addr
)->sin_addr
,
1155 sizeof(struct in_addr
));
1157 } else if (best
->ai_family
== AF_INET6
) {
1158 addr
->family
= AF_INET6
;
1159 memcpy(&addr
->addr
.in6_addr
,
1160 &((struct sockaddr_in6
*)best
->ai_addr
)->sin6_addr
,
1161 sizeof(struct in6_addr
));
1167 return (err
== EAI_AGAIN
) ? 1 : -1;
1169 struct hostent
*ent
;
1171 #ifdef HAVE_GETHOSTBYNAME_R_6_ARG
1173 struct hostent hostent
;
1175 r
= gethostbyname_r(name
, &hostent
, buf
, sizeof(buf
), &ent
, &err
);
1176 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
1178 struct hostent hostent
;
1179 ent
= gethostbyname_r(name
, &hostent
, buf
, sizeof(buf
), &err
);
1180 #elif defined(HAVE_GETHOSTBYNAME_R_3_ARG)
1181 struct hostent_data data
;
1182 struct hostent hent
;
1183 memset(&data
, 0, sizeof(data
));
1184 err
= gethostbyname_r(name
, &hent
, &data
);
1185 ent
= err
? NULL
: &hent
;
1187 ent
= gethostbyname(name
);
1189 err
= WSAGetLastError();
1193 #endif /* endif HAVE_GETHOSTBYNAME_R_6_ARG. */
1195 addr
->family
= ent
->h_addrtype
;
1196 if (ent
->h_addrtype
== AF_INET
) {
1197 memcpy(&addr
->addr
.in_addr
, ent
->h_addr
, sizeof(struct in_addr
));
1198 } else if (ent
->h_addrtype
== AF_INET6
) {
1199 memcpy(&addr
->addr
.in6_addr
, ent
->h_addr
, sizeof(struct in6_addr
));
1201 tor_assert(0); /* gethostbyname() returned a bizarre addrtype */
1206 return (err
== WSATRY_AGAIN
) ? 1 : -1;
1208 return (err
== TRY_AGAIN
) ? 1 : -1;
1214 /** Hold the result of our call to <b>uname</b>. */
1215 static char uname_result
[256];
1216 /** True iff uname_result is set. */
1217 static int uname_result_is_set
= 0;
1219 /** Return a pointer to a description of our platform.
1227 if (!uname_result_is_set
) {
1229 if (uname(&u
) != -1) {
1230 /* (linux says 0 is success, solaris says 1 is success) */
1231 tor_snprintf(uname_result
, sizeof(uname_result
), "%s %s",
1232 u
.sysname
, u
.machine
);
1237 OSVERSIONINFOEX info
;
1239 unsigned int leftover_mask
;
1240 const char *plat
= NULL
;
1241 const char *extra
= NULL
;
1243 unsigned major
; unsigned minor
; const char *version
;
1244 } win_version_table
[] = {
1245 { 6, 0, "Windows \"Longhorn\"" },
1246 { 5, 2, "Windows Server 2003" },
1247 { 5, 1, "Windows XP" },
1248 { 5, 0, "Windows 2000" },
1249 /* { 4, 0, "Windows NT 4.0" }, */
1250 { 4, 90, "Windows Me" },
1251 { 4, 10, "Windows 98" },
1252 /* { 4, 0, "Windows 95" } */
1253 { 3, 51, "Windows NT 3.51" },
1256 #ifdef VER_SUITE_BACKOFFICE
1258 unsigned int mask
; const char *str
;
1259 } win_mask_table
[] = {
1260 { VER_SUITE_BACKOFFICE
, " {backoffice}" },
1261 { VER_SUITE_BLADE
, " {\"blade\" (2003, web edition)}" },
1262 { VER_SUITE_DATACENTER
, " {datacenter}" },
1263 { VER_SUITE_ENTERPRISE
, " {enterprise}" },
1264 { VER_SUITE_EMBEDDEDNT
, " {embedded}" },
1265 { VER_SUITE_PERSONAL
, " {personal}" },
1266 { VER_SUITE_SINGLEUSERTS
,
1267 " {terminal services, single user}" },
1268 { VER_SUITE_SMALLBUSINESS
, " {small business}" },
1269 { VER_SUITE_SMALLBUSINESS_RESTRICTED
,
1270 " {small business, restricted}" },
1271 { VER_SUITE_TERMINAL
, " {terminal services}" },
1275 memset(&info
, 0, sizeof(info
));
1276 info
.dwOSVersionInfoSize
= sizeof(info
);
1277 if (! GetVersionEx((LPOSVERSIONINFO
)&info
)) {
1278 strlcpy(uname_result
, "Bizarre version of Windows where GetVersionEx"
1279 " doesn't work.", sizeof(uname_result
));
1280 uname_result_is_set
= 1;
1281 return uname_result
;
1283 if (info
.dwMajorVersion
== 4 && info
.dwMinorVersion
== 0) {
1284 if (info
.dwPlatformId
== VER_PLATFORM_WIN32_NT
)
1285 plat
= "Windows NT 4.0";
1287 plat
= "Windows 95";
1288 if (info
.szCSDVersion
[1] == 'B')
1290 else if (info
.szCSDVersion
[1] == 'C')
1293 for (i
=0; win_version_table
[i
].major
>0; ++i
) {
1294 if (win_version_table
[i
].major
== info
.dwMajorVersion
&&
1295 win_version_table
[i
].minor
== info
.dwMinorVersion
) {
1296 plat
= win_version_table
[i
].version
;
1301 if (plat
&& !strcmp(plat
, "Windows 98")) {
1302 if (info
.szCSDVersion
[1] == 'A')
1304 else if (info
.szCSDVersion
[1] == 'B')
1309 extra
= info
.szCSDVersion
;
1310 tor_snprintf(uname_result
, sizeof(uname_result
), "%s %s",
1313 if (info
.dwMajorVersion
> 6 ||
1314 (info
.dwMajorVersion
==6 && info
.dwMinorVersion
>0))
1315 tor_snprintf(uname_result
, sizeof(uname_result
),
1316 "Very recent version of Windows [major=%d,minor=%d] %s",
1317 (int)info
.dwMajorVersion
,(int)info
.dwMinorVersion
,
1320 tor_snprintf(uname_result
, sizeof(uname_result
),
1321 "Unrecognized version of Windows [major=%d,minor=%d] %s",
1322 (int)info
.dwMajorVersion
,(int)info
.dwMinorVersion
,
1325 #ifdef VER_SUITE_BACKOFFICE
1326 if (info
.wProductType
== VER_NT_DOMAIN_CONTROLLER
) {
1327 strlcat(uname_result
, " [domain controller]", sizeof(uname_result
));
1328 } else if (info
.wProductType
== VER_NT_SERVER
) {
1329 strlcat(uname_result
, " [server]", sizeof(uname_result
));
1330 } else if (info
.wProductType
== VER_NT_WORKSTATION
) {
1331 strlcat(uname_result
, " [workstation]", sizeof(uname_result
));
1333 leftover_mask
= info
.wSuiteMask
;
1334 for (i
= 0; win_mask_table
[i
].mask
; ++i
) {
1335 if (info
.wSuiteMask
& win_mask_table
[i
].mask
) {
1336 strlcat(uname_result
, win_mask_table
[i
].str
, sizeof(uname_result
));
1337 leftover_mask
&= ~win_mask_table
[i
].mask
;
1340 if (leftover_mask
) {
1341 size_t len
= strlen(uname_result
);
1342 tor_snprintf(uname_result
+len
, sizeof(uname_result
)-len
,
1343 " {0x%x}", info
.wSuiteMask
);
1347 strlcpy(uname_result
, "Unknown platform", sizeof(uname_result
));
1350 uname_result_is_set
= 1;
1352 return uname_result
;
1359 #if defined(USE_PTHREADS)
1360 /** Wraps a void (*)(void*) function and its argument so we can
1361 * invoke them in a way pthreads would expect.
1363 typedef struct tor_pthread_data_t
{
1364 void (*func
)(void *);
1366 } tor_pthread_data_t
;
1367 /** Given a tor_pthread_data_t <b>_data</b>, call _data->func(d->data)
1368 * and free _data. Used to make sure we can call functions the way pthread
1371 tor_pthread_helper_fn(void *_data
)
1373 tor_pthread_data_t
*data
= _data
;
1374 void (*func
)(void*);
1376 /* mask signals to worker threads to avoid SIGPIPE, etc */
1378 /* We're in a subthread; don't handle any signals here. */
1380 pthread_sigmask(SIG_SETMASK
, &sigs
, NULL
);
1390 /** Minimalist interface to run a void function in the background. On
1391 * unix calls fork, on win32 calls beginthread. Returns -1 on failure.
1392 * func should not return, but rather should call spawn_exit.
1394 * NOTE: if <b>data</b> is used, it should not be allocated on the stack,
1395 * since in a multithreaded environment, there is no way to be sure that
1396 * the caller's stack will still be around when the called function is
1400 spawn_func(void (*func
)(void *), void *data
)
1402 #if defined(USE_WIN32_THREADS)
1404 rv
= (int)_beginthread(func
, 0, data
);
1408 #elif defined(USE_PTHREADS)
1410 tor_pthread_data_t
*d
;
1411 d
= tor_malloc(sizeof(tor_pthread_data_t
));
1414 if (pthread_create(&thread
,NULL
,tor_pthread_helper_fn
,d
))
1416 if (pthread_detach(thread
))
1427 tor_assert(0); /* Should never reach here. */
1428 return 0; /* suppress "control-reaches-end-of-non-void" warning. */
1436 /** End the current thread/process.
1441 #if defined(USE_WIN32_THREADS)
1443 //we should never get here. my compiler thinks that _endthread returns, this
1444 //is an attempt to fool it.
1447 #elif defined(USE_PTHREADS)
1450 /* http://www.erlenstar.demon.co.uk/unix/faq_2.html says we should
1451 * call _exit, not exit, from child processes. */
1457 /** Set *timeval to the current time of day. On error, log and terminate.
1458 * (Same as gettimeofday(timeval,NULL), but never returns -1.)
1461 tor_gettimeofday(struct timeval
*timeval
)
1464 /* Epoch bias copied from perl: number of units between windows epoch and
1466 #define EPOCH_BIAS U64_LITERAL(116444736000000000)
1467 #define UNITS_PER_SEC U64_LITERAL(10000000)
1468 #define USEC_PER_SEC U64_LITERAL(1000000)
1469 #define UNITS_PER_USEC U64_LITERAL(10)
1474 /* number of 100-nsec units since Jan 1, 1601 */
1475 GetSystemTimeAsFileTime(&ft
.ft_ft
);
1476 if (ft
.ft_64
< EPOCH_BIAS
) {
1477 log_err(LD_GENERAL
,"System time is before 1970; failing.");
1480 ft
.ft_64
-= EPOCH_BIAS
;
1481 timeval
->tv_sec
= (unsigned) (ft
.ft_64
/ UNITS_PER_SEC
);
1482 timeval
->tv_usec
= (unsigned) ((ft
.ft_64
/ UNITS_PER_USEC
) % USEC_PER_SEC
);
1483 #elif defined(HAVE_GETTIMEOFDAY)
1484 if (gettimeofday(timeval
, NULL
)) {
1485 log_err(LD_GENERAL
,"gettimeofday failed.");
1486 /* If gettimeofday dies, we have either given a bad timezone (we didn't),
1490 #elif defined(HAVE_FTIME)
1493 timeval
->tv_sec
= tb
.time
;
1494 timeval
->tv_usec
= tb
.millitm
* 1000;
1496 #error "No way to get time."
1501 #if defined(TOR_IS_MULTITHREADED) && !defined(MS_WINDOWS)
1502 /** Defined iff we need to add locks when defining fake versions of reentrant
1503 * versions of time-related functions. */
1504 #define TIME_FNS_NEED_LOCKS
1507 #ifndef HAVE_LOCALTIME_R
1508 #ifdef TIME_FNS_NEED_LOCKS
1510 tor_localtime_r(const time_t *timep
, struct tm
*result
)
1513 static tor_mutex_t
*m
=NULL
;
1514 if (!m
) { m
=tor_mutex_new(); }
1516 tor_mutex_acquire(m
);
1517 r
= localtime(timep
);
1518 memcpy(result
, r
, sizeof(struct tm
));
1519 tor_mutex_release(m
);
1524 tor_localtime_r(const time_t *timep
, struct tm
*result
)
1528 r
= localtime(timep
);
1529 memcpy(result
, r
, sizeof(struct tm
));
1535 #ifndef HAVE_GMTIME_R
1536 #ifdef TIME_FNS_NEED_LOCKS
1538 tor_gmtime_r(const time_t *timep
, struct tm
*result
)
1541 static tor_mutex_t
*m
=NULL
;
1542 if (!m
) { m
=tor_mutex_new(); }
1544 tor_mutex_acquire(m
);
1546 memcpy(result
, r
, sizeof(struct tm
));
1547 tor_mutex_release(m
);
1552 tor_gmtime_r(const time_t *timep
, struct tm
*result
)
1557 memcpy(result
, r
, sizeof(struct tm
));
1563 #if defined(USE_WIN32_THREADS) && 0
1564 /** A generic lock structure for multithreaded builds. */
1565 struct tor_mutex_t
{
1572 m
= tor_malloc_zero(sizeof(tor_mutex_t
));
1573 m
->handle
= CreateMutex(NULL
, FALSE
, NULL
);
1574 tor_assert(m
->handle
!= NULL
);
1578 tor_mutex_free(tor_mutex_t
*m
)
1580 CloseHandle(m
->handle
);
1584 tor_mutex_acquire(tor_mutex_t
*m
)
1587 r
= WaitForSingleObject(m
->handle
, INFINITE
);
1589 case WAIT_ABANDONED
: /* holding thread exited. */
1590 case WAIT_OBJECT_0
: /* we got the mutex normally. */
1592 case WAIT_TIMEOUT
: /* Should never happen. */
1596 log_warn(LD_GENERAL
, "Failed to acquire mutex: %d",(int) GetLastError());
1600 tor_mutex_release(tor_mutex_t
*m
)
1603 r
= ReleaseMutex(m
->handle
);
1605 log_warn(LD_GENERAL
, "Failed to release mutex: %d", (int) GetLastError());
1609 tor_get_thread_id(void)
1611 return (unsigned long)GetCurrentThreadId();
1613 #elif defined(USE_WIN32_THREADS)
1614 /** A generic lock structure for multithreaded builds. */
1615 struct tor_mutex_t
{
1616 CRITICAL_SECTION mutex
;
1621 tor_mutex_t
*m
= tor_malloc_zero(sizeof(tor_mutex_t
));
1622 InitializeCriticalSection(&m
->mutex
);
1626 tor_mutex_free(tor_mutex_t
*m
)
1628 DeleteCriticalSection(&m
->mutex
);
1632 tor_mutex_acquire(tor_mutex_t
*m
)
1635 EnterCriticalSection(&m
->mutex
);
1638 tor_mutex_release(tor_mutex_t
*m
)
1640 LeaveCriticalSection(&m
->mutex
);
1643 tor_get_thread_id(void)
1645 return (unsigned long)GetCurrentThreadId();
1647 #elif defined(USE_PTHREADS)
1648 /** A generic lock structure for multithreaded builds. */
1649 struct tor_mutex_t
{
1650 pthread_mutex_t mutex
;
1652 /** Allocate and return new lock. */
1657 tor_mutex_t
*mutex
= tor_malloc_zero(sizeof(tor_mutex_t
));
1658 err
= pthread_mutex_init(&mutex
->mutex
, NULL
);
1659 if (PREDICT_UNLIKELY(err
)) {
1660 log_err(LD_GENERAL
, "Error %d creating a mutex.", err
);
1661 tor_fragile_assert();
1665 /** Wait until <b>m</b> is free, then acquire it. */
1667 tor_mutex_acquire(tor_mutex_t
*m
)
1671 err
= pthread_mutex_lock(&m
->mutex
);
1672 if (PREDICT_UNLIKELY(err
)) {
1673 log_err(LD_GENERAL
, "Error %d locking a mutex.", err
);
1674 tor_fragile_assert();
1677 /** Release the lock <b>m</b> so another thread can have it. */
1679 tor_mutex_release(tor_mutex_t
*m
)
1683 err
= pthread_mutex_unlock(&m
->mutex
);
1684 if (PREDICT_UNLIKELY(err
)) {
1685 log_err(LD_GENERAL
, "Error %d unlocking a mutex.", err
);
1686 tor_fragile_assert();
1689 /** Free all storage held by the lock <b>m</b>. */
1691 tor_mutex_free(tor_mutex_t
*m
)
1695 err
= pthread_mutex_destroy(&m
->mutex
);
1696 if (PREDICT_UNLIKELY(err
)) {
1697 log_err(LD_GENERAL
, "Error %d destroying a mutex.", err
);
1698 tor_fragile_assert();
1702 /** Return an integer representing this thread. */
1704 tor_get_thread_id(void)
1710 r
.thr
= pthread_self();
1714 /** A generic lock structure for multithreaded builds. */
1715 struct tor_mutex_t
{
1723 /** Cross-platform condition implementation. */
1725 pthread_cond_t cond
;
1727 /** Return a newly allocated condition, with nobody waiting on it. */
1731 tor_cond_t
*cond
= tor_malloc_zero(sizeof(tor_cond_t
));
1732 if (pthread_cond_init(&cond
->cond
, NULL
)) {
1738 /** Release all resources held by <b>cond</b>. */
1740 tor_cond_free(tor_cond_t
*cond
)
1743 if (pthread_cond_destroy(&cond
->cond
)) {
1744 log_warn(LD_GENERAL
,"Error freeing condition: %s", strerror(errno
));
1749 /** Wait until one of the tor_cond_signal functions is called on <b>cond</b>.
1750 * All waiters on the condition must wait holding the same <b>mutex</b>.
1751 * Returns 0 on success, negative on failure. */
1753 tor_cond_wait(tor_cond_t
*cond
, tor_mutex_t
*mutex
)
1755 return pthread_cond_wait(&cond
->cond
, &mutex
->mutex
) ? -1 : 0;
1757 /** Wake up one of the waiters on <b>cond</b>. */
1759 tor_cond_signal_one(tor_cond_t
*cond
)
1761 pthread_cond_signal(&cond
->cond
);
1763 /** Wake up all of the waiters on <b>cond</b>. */
1765 tor_cond_signal_all(tor_cond_t
*cond
)
1767 pthread_cond_broadcast(&cond
->cond
);
1770 /** Set up common structures for use by threading. */
1772 tor_threads_init(void)
1775 #elif defined(USE_WIN32_THREADS)
1777 static DWORD cond_event_tls_index
;
1779 CRITICAL_SECTION mutex
;
1780 smartlist_t
*events
;
1785 tor_cond_t
*cond
= tor_malloc_zero(sizeof(tor_cond_t
));
1786 InitializeCriticalSection(&cond
->mutex
);
1787 cond
->events
= smartlist_create();
1791 tor_cond_free(tor_cond_t
*cond
)
1794 DeleteCriticalSection(&cond
->mutex
);
1796 smartlist_free(cond
->events
);
1800 tor_cond_wait(tor_cond_t
*cond
, tor_mutex_t
*mutex
)
1806 event
= TlsGetValue(cond_event_tls_index
);
1808 event
= CreateEvent(0, FALSE
, FALSE
, NULL
);
1809 TlsSetValue(cond_event_tls_index
, event
);
1811 EnterCriticalSection(&cond
->mutex
);
1813 tor_assert(WaitForSingleObject(event
, 0) == WAIT_TIMEOUT
);
1814 tor_assert(!smartlist_isin(cond
->events
, event
));
1815 smartlist_add(cond
->events
, event
);
1817 LeaveCriticalSection(&cond
->mutex
);
1819 tor_mutex_release(mutex
);
1820 r
= WaitForSingleObject(event
, INFINITE
);
1821 tor_mutex_acquire(mutex
);
1824 case WAIT_OBJECT_0
: /* we got the mutex normally. */
1826 case WAIT_ABANDONED
: /* holding thread exited. */
1827 case WAIT_TIMEOUT
: /* Should never happen. */
1831 log_warn(LD_GENERAL
, "Failed to acquire mutex: %d",(int) GetLastError());
1836 tor_cond_signal_one(tor_cond_t
*cond
)
1841 EnterCriticalSection(&cond
->mutex
);
1843 if ((event
= smartlist_pop_last(cond
->events
)))
1846 LeaveCriticalSection(&cond
->mutex
);
1849 tor_cond_signal_all(tor_cond_t
*cond
)
1853 EnterCriticalSection(&cond
->mutex
);
1854 SMARTLIST_FOREACH(cond
->events
, HANDLE
, event
, SetEvent(event
));
1855 smartlist_clear(cond
->events
);
1856 LeaveCriticalSection(&cond
->mutex
);
1860 tor_threads_init(void)
1863 cond_event_tls_index
= TlsAlloc();
1869 * On Windows, WSAEWOULDBLOCK is not always correct: when you see it,
1870 * you need to ask the socket for its actual errno. Also, you need to
1871 * get your errors from WSAGetLastError, not errno. (If you supply a
1872 * socket of -1, we check WSAGetLastError, but don't correct
1875 * The upshot of all of this is that when a socket call fails, you
1876 * should call tor_socket_errno <em>at most once</em> on the failing
1877 * socket to get the error.
1879 #if defined(MS_WINDOWS) && !defined(USE_BSOCKETS)
1881 tor_socket_errno(int sock
)
1883 int optval
, optvallen
=sizeof(optval
);
1884 int err
= WSAGetLastError();
1885 if (err
== WSAEWOULDBLOCK
&& sock
>= 0) {
1886 if (getsockopt(sock
, SOL_SOCKET
, SO_ERROR
, (void*)&optval
, &optvallen
))
1895 #if defined(MS_WINDOWS) && !defined(USE_BSOCKETS)
1896 #define E(code, s) { code, (s " [" #code " ]") }
1897 struct { int code
; const char *msg
; } windows_socket_errors
[] = {
1898 E(WSAEINTR
, "Interrupted function call"),
1899 E(WSAEACCES
, "Permission denied"),
1900 E(WSAEFAULT
, "Bad address"),
1901 E(WSAEINVAL
, "Invalid argument"),
1902 E(WSAEMFILE
, "Too many open files"),
1903 E(WSAEWOULDBLOCK
, "Resource temporarily unavailable"),
1904 E(WSAEINPROGRESS
, "Operation now in progress"),
1905 E(WSAEALREADY
, "Operation already in progress"),
1906 E(WSAENOTSOCK
, "Socket operation on nonsocket"),
1907 E(WSAEDESTADDRREQ
, "Destination address required"),
1908 E(WSAEMSGSIZE
, "Message too long"),
1909 E(WSAEPROTOTYPE
, "Protocol wrong for socket"),
1910 E(WSAENOPROTOOPT
, "Bad protocol option"),
1911 E(WSAEPROTONOSUPPORT
, "Protocol not supported"),
1912 E(WSAESOCKTNOSUPPORT
, "Socket type not supported"),
1913 /* What's the difference between NOTSUPP and NOSUPPORT? :) */
1914 E(WSAEOPNOTSUPP
, "Operation not supported"),
1915 E(WSAEPFNOSUPPORT
, "Protocol family not supported"),
1916 E(WSAEAFNOSUPPORT
, "Address family not supported by protocol family"),
1917 E(WSAEADDRINUSE
, "Address already in use"),
1918 E(WSAEADDRNOTAVAIL
, "Cannot assign requested address"),
1919 E(WSAENETDOWN
, "Network is down"),
1920 E(WSAENETUNREACH
, "Network is unreachable"),
1921 E(WSAENETRESET
, "Network dropped connection on reset"),
1922 E(WSAECONNABORTED
, "Software caused connection abort"),
1923 E(WSAECONNRESET
, "Connection reset by peer"),
1924 E(WSAENOBUFS
, "No buffer space available"),
1925 E(WSAEISCONN
, "Socket is already connected"),
1926 E(WSAENOTCONN
, "Socket is not connected"),
1927 E(WSAESHUTDOWN
, "Cannot send after socket shutdown"),
1928 E(WSAETIMEDOUT
, "Connection timed out"),
1929 E(WSAECONNREFUSED
, "Connection refused"),
1930 E(WSAEHOSTDOWN
, "Host is down"),
1931 E(WSAEHOSTUNREACH
, "No route to host"),
1932 E(WSAEPROCLIM
, "Too many processes"),
1933 /* Yes, some of these start with WSA, not WSAE. No, I don't know why. */
1934 E(WSASYSNOTREADY
, "Network subsystem is unavailable"),
1935 E(WSAVERNOTSUPPORTED
, "Winsock.dll out of range"),
1936 E(WSANOTINITIALISED
, "Successful WSAStartup not yet performed"),
1937 E(WSAEDISCON
, "Graceful shutdown now in progress"),
1938 #ifdef WSATYPE_NOT_FOUND
1939 E(WSATYPE_NOT_FOUND
, "Class type not found"),
1941 E(WSAHOST_NOT_FOUND
, "Host not found"),
1942 E(WSATRY_AGAIN
, "Nonauthoritative host not found"),
1943 E(WSANO_RECOVERY
, "This is a nonrecoverable error"),
1944 E(WSANO_DATA
, "Valid name, no data record of requested type)"),
1946 /* There are some more error codes whose numeric values are marked
1947 * <b>OS dependent</b>. They start with WSA_, apparently for the same
1948 * reason that practitioners of some craft traditions deliberately
1949 * introduce imperfections into their baskets and rugs "to allow the
1950 * evil spirits to escape." If we catch them, then our binaries
1951 * might not report consistent results across versions of Windows.
1952 * Thus, I'm going to let them all fall through.
1956 /** There does not seem to be a strerror equivalent for winsock errors.
1957 * Naturally, we have to roll our own.
1960 tor_socket_strerror(int e
)
1963 for (i
=0; windows_socket_errors
[i
].code
>= 0; ++i
) {
1964 if (e
== windows_socket_errors
[i
].code
)
1965 return windows_socket_errors
[i
].msg
;
1971 /** Called before we make any calls to network-related functions.
1972 * (Some operating systems require their network libraries to be
1978 /* This silly exercise is necessary before windows will allow
1979 * gethostbyname to work. */
1982 r
= WSAStartup(0x101,&WSAData
);
1984 log_warn(LD_NET
,"Error initializing windows network layer: code was %d",r
);
1987 /* WSAData.iMaxSockets might show the max sockets we're allowed to use.
1988 * We might use it to complain if we're trying to be a server but have
1989 * too few sockets available. */
1995 /** Return a newly allocated string describing the windows system error code
1996 * <b>err</b>. Note that error codes are different from errno. Error codes
1997 * come from GetLastError() when a winapi call fails. errno is set only when
1998 * ansi functions fail. Whee. */
2000 format_win32_error(DWORD err
)
2005 /* Somebody once decided that this interface was better than strerror(). */
2006 FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
|
2007 FORMAT_MESSAGE_FROM_SYSTEM
|
2008 FORMAT_MESSAGE_IGNORE_INSERTS
,
2010 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
2015 result
= tor_strdup((char*)str
);
2016 LocalFree(str
); /* LocalFree != free() */
2018 result
= tor_strdup("<unformattable error>");