1 /* Copyright 2003-2004 Roger Dingledine
2 * Copyright 2004-2005 Roger Dingledine, Nick Mathewson */
3 /* See LICENSE for licensing information */
5 const char compat_c_id
[] = "$Id$";
9 * \brief Wrappers to make calls more portable. This code defines
10 * functions such as tor_malloc, tor_snprintf, get/set various data types,
11 * renaming, setting socket options, switching user IDs. It is basically
12 * where the non-portable items are conditionally included depending on
16 /* This is required on rh7 to make strptime not complain.
17 * We also need it to make memmem get defined (where available)
29 #include <sys/utsname.h>
31 #ifdef HAVE_SYS_TIME_H
37 #ifdef HAVE_SYS_FCNTL_H
38 #include <sys/fcntl.h>
49 #ifdef HAVE_SYS_RESOURCE_H
50 #include <sys/resource.h>
55 #ifdef HAVE_NETINET_IN_H
56 #include <netinet/in.h>
58 #ifdef HAVE_ARPA_INET_H
59 #include <arpa/inet.h>
61 #ifndef HAVE_GETTIMEOFDAY
63 #include <sys/timeb.h>
66 #ifdef HAVE_SYS_SOCKET_H
67 #include <sys/socket.h>
72 #ifdef HAVE_SYS_PARAM_H
73 #include <sys/param.h> /* FreeBSD needs this to know what version it is */
86 #ifdef HAVE_SYS_UTIME_H
87 #include <sys/utime.h>
93 /* Inline the strl functions if the platform doesn't have them. */
101 /* used by inet_addr, not defined on solaris anywhere!? */
103 #define INADDR_NONE ((unsigned long) -1)
106 /** Replacement for snprintf. Differs from platform snprintf in two
107 * ways: First, always NUL-terminates its output. Second, always
108 * returns -1 if the result is truncated. (Note that this return
109 * behavior does <i>not</i> conform to C99; it just happens to be the
110 * easiest to emulate "return -1" with conformant implementations than
111 * it is to emulate "return number that would be written" with
112 * non-conformant implementations.) */
114 tor_snprintf(char *str
, size_t size
, const char *format
, ...)
119 r
= tor_vsnprintf(str
,size
,format
,ap
);
124 /** Replacement for vsnprintf; behavior differs as tor_snprintf differs from
128 tor_vsnprintf(char *str
, size_t size
, const char *format
, va_list args
)
132 return -1; /* no place for the NUL */
133 if (size
> SIZE_T_CEILING
)
136 r
= _vsnprintf(str
, size
, format
, args
);
138 r
= vsnprintf(str
, size
, format
, args
);
141 if (r
< 0 || ((size_t)r
) >= size
)
146 /** Given <b>hlen</b> bytes at <b>haystack</b> and <b>nlen</b> bytes at
147 * <b>needle</b>, return a pointer to the first occurrence of the needle
148 * within the haystack, or NULL if there is no such occurrence.
150 * Requires that nlen be greater than zero.
153 tor_memmem(const void *_haystack
, size_t hlen
, const void *_needle
, size_t nlen
)
155 #if defined(HAVE_MEMMEM) && (!defined(__GNUC__) || __GNUC__ >= 2)
157 return memmem(_haystack
, hlen
, _needle
, nlen
);
159 /* This isn't as fast as the GLIBC implementation, but it doesn't need to be. */
161 const char *haystack
= (const char*)_haystack
;
162 const char *needle
= (const char*)_needle
;
167 end
= haystack
+ hlen
;
168 first
= *(const char*)needle
;
169 while ((p
= memchr(p
, first
, end
-p
))) {
172 if (!memcmp(p
, needle
, nlen
))
180 /** Take a filename and return a pointer to its final element. This
181 * function is called on __FILE__ to fix a MSVC nit where __FILE__
182 * contains the full path to the file. This is bad, because it
183 * confuses users to find the home directory of the person who
184 * compiled the binary in their warrning messages.
187 _tor_fix_source_file(const char *fname
)
189 const char *cp1
, *cp2
, *r
;
190 cp1
= strrchr(fname
, '/');
191 cp2
= strrchr(fname
, '\\');
193 r
= (cp1
<cp2
)?(cp2
+1):(cp1
+1);
204 #ifndef UNALIGNED_INT_ACCESS_OK
206 * Read a 16-bit value beginning at <b>cp</b>. Equivalent to
207 * *(uint16_t*)(cp), but will not cause segfaults on platforms that forbid
208 * unaligned memory access.
211 get_uint16(const char *cp
)
218 * Read a 32-bit value beginning at <b>cp</b>. Equivalent to
219 * *(uint32_t*)(cp), but will not cause segfaults on platforms that forbid
220 * unaligned memory access.
223 get_uint32(const char *cp
)
230 * Set a 16-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
231 * *(uint16_t)(cp) = v, but will not cause segfaults on platforms that forbid
232 * unaligned memory access. */
234 set_uint16(char *cp
, uint16_t v
)
239 * Set a 32-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
240 * *(uint32_t)(cp) = v, but will not cause segfaults on platforms that forbid
241 * unaligned memory access. */
243 set_uint32(char *cp
, uint32_t v
)
250 * Rename the file <b>from</b> to the file <b>to</b>. On unix, this is
251 * the same as rename(2). On windows, this removes <b>to</b> first if
253 * Returns 0 on success. Returns -1 and sets errno on failure.
256 replace_file(const char *from
, const char *to
)
259 return rename(from
,to
);
261 switch (file_status(to
))
266 if (unlink(to
)) return -1;
274 return rename(from
,to
);
278 /** Change <b>fname</b>'s modification time to now. */
280 touch_file(const char *fname
)
282 if (utime(fname
, NULL
)!=0)
287 /** Turn <b>socket</b> into a nonblocking socket.
290 set_socket_nonblocking(int socket
)
294 ioctlsocket(socket
, FIONBIO
, (unsigned long*) &nonblocking
);
296 fcntl(socket
, F_SETFL
, O_NONBLOCK
);
301 * Allocate a pair of connected sockets. (Like socketpair(family,
302 * type,protocol,fd), but works on systems that don't have
305 * Currently, only (AF_UNIX, SOCK_STREAM, 0 ) sockets are supported.
307 * Note that on systems without socketpair, this call will fail if
308 * localhost is inaccessible (for example, if the networking
309 * stack is down). And even if it succeeds, the socket pair will not
310 * be able to read while localhost is down later (the socket pair may
311 * even close, depending on OS-specific timeouts).
313 * Returns 0 on success and -errno on failure; do not rely on the value
314 * of errno or WSAGetLastSocketError().
316 /* It would be nicer just to set errno, but that won't work for windows. */
318 tor_socketpair(int family
, int type
, int protocol
, int fd
[2])
320 #ifdef HAVE_SOCKETPAIR
322 r
= socketpair(family
, type
, protocol
, fd
);
323 return r
< 0 ? -errno
: r
;
325 /* This socketpair does not work when localhost is down. So
326 * it's really not the same thing at all. But it's close enough
327 * for now, and really, when localhost is down sometimes, we
328 * have other problems too.
333 struct sockaddr_in listen_addr
;
334 struct sockaddr_in connect_addr
;
336 int saved_errno
= -1;
344 return -WSAEAFNOSUPPORT
;
346 return -EAFNOSUPPORT
;
353 listener
= socket(AF_INET
, type
, 0);
355 return -tor_socket_errno(-1);
356 if (!SOCKET_IS_POLLABLE(listener
)) {
357 log_fn(LOG_WARN
, "Too many connections; can't open socketpair");
358 tor_close_socket(listener
);
365 memset(&listen_addr
, 0, sizeof(listen_addr
));
366 listen_addr
.sin_family
= AF_INET
;
367 listen_addr
.sin_addr
.s_addr
= htonl(INADDR_LOOPBACK
);
368 listen_addr
.sin_port
= 0; /* kernel chooses port. */
369 if (bind(listener
, (struct sockaddr
*) &listen_addr
, sizeof (listen_addr
))
371 goto tidy_up_and_fail
;
372 if (listen(listener
, 1) == -1)
373 goto tidy_up_and_fail
;
375 connector
= socket(AF_INET
, type
, 0);
377 goto tidy_up_and_fail
;
378 if (!SOCKET_IS_POLLABLE(connector
)) {
379 log_fn(LOG_WARN
, "Too many connections; can't open socketpair");
380 goto tidy_up_and_fail
;
382 /* We want to find out the port number to connect to. */
383 size
= sizeof(connect_addr
);
384 if (getsockname(listener
, (struct sockaddr
*) &connect_addr
, &size
) == -1)
385 goto tidy_up_and_fail
;
386 if (size
!= sizeof (connect_addr
))
387 goto abort_tidy_up_and_fail
;
388 if (connect(connector
, (struct sockaddr
*) &connect_addr
,
389 sizeof(connect_addr
)) == -1)
390 goto tidy_up_and_fail
;
392 size
= sizeof(listen_addr
);
393 acceptor
= accept(listener
, (struct sockaddr
*) &listen_addr
, &size
);
395 goto tidy_up_and_fail
;
396 if (!SOCKET_IS_POLLABLE(acceptor
)) {
397 log_fn(LOG_WARN
, "Too many connections; can't open socketpair");
398 goto tidy_up_and_fail
;
400 if (size
!= sizeof(listen_addr
))
401 goto abort_tidy_up_and_fail
;
402 tor_close_socket(listener
);
403 /* Now check we are talking to ourself by matching port and host on the
405 if (getsockname(connector
, (struct sockaddr
*) &connect_addr
, &size
) == -1)
406 goto tidy_up_and_fail
;
407 if (size
!= sizeof (connect_addr
)
408 || listen_addr
.sin_family
!= connect_addr
.sin_family
409 || listen_addr
.sin_addr
.s_addr
!= connect_addr
.sin_addr
.s_addr
410 || listen_addr
.sin_port
!= connect_addr
.sin_port
) {
411 goto abort_tidy_up_and_fail
;
418 abort_tidy_up_and_fail
:
420 saved_errno
= WSAECONNABORTED
;
422 saved_errno
= ECONNABORTED
; /* I hope this is portable and appropriate. */
428 tor_close_socket(listener
);
430 tor_close_socket(connector
);
432 tor_close_socket(acceptor
);
437 #define ULIMIT_BUFFER 32 /* keep 32 extra fd's beyond _ConnLimit */
439 /** Get the maximum allowed number of file descriptors. (Some systems
440 * have a low soft limit.) Make sure we set it to at least
441 * <b>limit</b>. Return a new limit if we can, or -1 if we fail. */
443 set_max_file_descriptors(unsigned long limit
, unsigned long cap
)
445 #ifndef HAVE_GETRLIMIT
446 log_fn(LOG_INFO
,"This platform is missing getrlimit(). Proceeding.");
448 log(LOG_INFO
, "ConnLimit must be at most %d. Capping it.", cap
);
454 tor_assert(limit
> 0);
457 if (getrlimit(RLIMIT_NOFILE
, &rlim
) != 0) {
458 log_fn(LOG_WARN
, "Could not get maximum number of file descriptors: %s",
462 if (rlim
.rlim_max
< limit
) {
463 log_fn(LOG_WARN
,"We need %lu file descriptors available, and we're limited to %lu. Please change your ulimit -n.", limit
, (unsigned long)rlim
.rlim_max
);
466 most
= (rlim
.rlim_max
> cap
) ? cap
: (unsigned) rlim
.rlim_max
;
467 if (most
> rlim
.rlim_cur
) {
468 log_fn(LOG_INFO
,"Raising max file descriptors from %lu to %lu.",
469 (unsigned long)rlim
.rlim_cur
, most
);
471 rlim
.rlim_cur
= most
;
472 if (setrlimit(RLIMIT_NOFILE
, &rlim
) != 0) {
473 log_fn(LOG_WARN
, "Could not set maximum number of file descriptors: %s",
477 /* leave some overhead for logs, etc, */
481 if (limit
< ULIMIT_BUFFER
) {
482 log_fn(LOG_WARN
,"ConnLimit must be at least %d. Failing.", ULIMIT_BUFFER
);
485 return limit
- ULIMIT_BUFFER
;
488 /** Call setuid and setgid to run as <b>user</b>:<b>group</b>. Return 0 on
489 * success. On failure, log and return -1.
492 switch_id(char *user
, char *group
)
495 struct passwd
*pw
= NULL
;
496 struct group
*gr
= NULL
;
501 log_fn(LOG_ERR
,"User '%s' not found.", user
);
506 /* switch the group first, while we still have the privileges to do so */
508 gr
= getgrnam(group
);
510 log_fn(LOG_ERR
,"Group '%s' not found.", group
);
514 if (setgid(gr
->gr_gid
) != 0) {
515 log_fn(LOG_ERR
,"Error setting GID: %s", strerror(errno
));
519 if (setgid(pw
->pw_gid
) != 0) {
520 log_fn(LOG_ERR
,"Error setting GID: %s", strerror(errno
));
525 /* now that the group is switched, we can switch users and lose
528 if (setuid(pw
->pw_uid
) != 0) {
529 log_fn(LOG_ERR
,"Error setting UID: %s", strerror(errno
));
538 "User or group specified, but switching users is not supported.");
544 /** Allocate and return a string containing the home directory for the
545 * user <b>username</b>. Only works on posix-like systems */
547 get_user_homedir(const char *username
)
550 tor_assert(username
);
552 if (!(pw
= getpwnam(username
))) {
553 log_fn(LOG_ERR
,"User \"%s\" not found.", username
);
556 return tor_strdup(pw
->pw_dir
);
560 /** Set *addr to the IP address (in dotted-quad notation) stored in c.
561 * Return 1 on success, 0 if c is badly formatted. (Like inet_aton(c,addr),
562 * but works on Windows and Solaris.)
565 tor_inet_aton(const char *c
, struct in_addr
* addr
)
567 #ifdef HAVE_INET_ATON
568 return inet_aton(c
, addr
);
573 if (strcmp(c
, "255.255.255.255") == 0) {
574 addr
->s_addr
= 0xFFFFFFFFu
;
578 if (r
== INADDR_NONE
)
585 /** Similar behavior to Unix gethostbyname: resolve <b>name</b>, and set
586 * *addr to the proper IP address, in network byte order. Returns 0
587 * on success, -1 on failure; 1 on transient failure.
589 * (This function exists because standard windows gethostbyname
590 * doesn't treat raw IP addresses properly.)
593 tor_lookup_hostname(const char *name
, uint32_t *addr
)
595 /* Perhaps eventually this should be replaced by a tor_getaddrinfo or
598 struct in_addr iaddr
;
602 /* Empty address is an error. */
604 } else if (tor_inet_aton(name
, &iaddr
)) {
606 memcpy(addr
, &iaddr
.s_addr
, 4);
609 #ifdef HAVE_GETADDRINFO
611 struct addrinfo
*res
=NULL
, *res_p
;
612 struct addrinfo hints
;
614 memset(&hints
, 0, sizeof(hints
));
615 hints
.ai_family
= PF_INET
;
616 hints
.ai_socktype
= SOCK_STREAM
;
617 err
= getaddrinfo(name
, NULL
, NULL
, &res
);
619 for (res_p
= res
; res_p
; res_p
= res_p
->ai_next
) {
620 if (res_p
->ai_family
== AF_INET
) {
621 struct sockaddr_in
*sin
= (struct sockaddr_in
*)res_p
->ai_addr
;
622 memcpy(addr
, &sin
->sin_addr
, 4);
630 return (err
== EAI_AGAIN
) ? 1 : -1;
634 #ifdef HAVE_GETHOSTBYNAME_R_6_ARG
636 struct hostent hostent
;
638 r
= gethostbyname_r(name
, &hostent
, buf
, sizeof(buf
), &ent
, &err
);
639 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
641 struct hostent hostent
;
642 ent
= gethostbyname_r(name
, &hostent
, buf
, sizeof(buf
), &err
);
643 #elif defined(HAVE_GETHOSTBYNAME_R_3_ARG)
644 struct hostent_data data
;
646 memset(&data
, 0, sizeof(data
));
647 err
= gethostbyname_r(name
, &hent
, &data
);
648 ent
= err
? NULL
: &hent
;
650 ent
= gethostbyname(name
);
652 err
= WSAGetLastError();
658 /* break to remind us if we move away from IPv4 */
659 tor_assert(ent
->h_length
== 4);
660 memcpy(addr
, ent
->h_addr
, 4);
665 return (err
== WSATRY_AGAIN
) ? 1 : -1;
667 return (err
== TRY_AGAIN
) ? 1 : -1;
673 /** Hold the result of our call to <b>uname</b>. */
674 static char uname_result
[256];
675 /** True iff uname_result is set. */
676 static int uname_result_is_set
= 0;
678 /** Return a pointer to a description of our platform.
686 if (!uname_result_is_set
) {
688 if (uname(&u
) != -1) {
689 /* (linux says 0 is success, solaris says 1 is success) */
690 tor_snprintf(uname_result
, sizeof(uname_result
), "%s %s",
691 u
.sysname
, u
.machine
);
698 const char *plat
= NULL
;
700 int major
; int minor
; const char *version
;
701 } win_version_table
[] = {
702 { 5, 2, "Windows Server 2003" },
703 { 5, 1, "Windows XP" },
704 { 5, 0, "Windows 2000" },
705 /* { 4, 0, "Windows NT 4.0" }, */
706 { 4, 90, "Windows Me" },
707 { 4, 10, "Windows 98" },
708 /* { 4, 0, "Windows 95" } */
709 { 3, 51, "Windows NT 3.51" },
712 info
.dwOSVersionInfoSize
= sizeof(info
);
714 if (info
.dwMajorVersion
== 4 && info
.dwMinorVersion
== 0) {
715 if (info
.dwPlatformId
== VER_PLATFORM_WIN32_NT
)
716 plat
= "Windows NT 4.0";
720 for (i
=0; win_version_table
[i
].major
>=0; ++i
) {
721 if (win_version_table
[i
].major
== info
.dwMajorVersion
&&
722 win_version_table
[i
].minor
== info
.dwMinorVersion
) {
723 plat
= win_version_table
[i
].version
;
729 strlcpy(uname_result
, plat
, sizeof(uname_result
));
731 if (info
.dwMajorVersion
> 5 ||
732 (info
.dwMajorVersion
==5 && info
.dwMinorVersion
>2))
733 tor_snprintf(uname_result
, sizeof(uname_result
),
734 "Very recent version of Windows [major=%d,minor=%d]",
735 (int)info
.dwMajorVersion
,(int)info
.dwMinorVersion
);
737 tor_snprintf(uname_result
, sizeof(uname_result
),
738 "Unrecognized version of Windows [major=%d,minor=%d]",
739 (int)info
.dwMajorVersion
,(int)info
.dwMinorVersion
);
742 strlcpy(uname_result
, "Unknown platform", sizeof(uname_result
));
745 uname_result_is_set
= 1;
754 #if defined(USE_PTHREADS)
755 typedef struct tor_pthread_data_t
{
758 } tor_pthread_data_t
;
760 tor_pthread_helper_fn(void *_data
)
762 tor_pthread_data_t
*data
= _data
;
773 /** Minimalist interface to run a void function in the background. On
774 * unix calls fork, on win32 calls beginthread. Returns -1 on failure.
775 * func should not return, but rather should call spawn_exit.
777 * NOTE: if <b>data</b> is used, it should not be allocated on the stack,
778 * since in a multithreaded environment, there is no way to be sure that
779 * the caller's stack will still be around when the called function is
783 spawn_func(int (*func
)(void *), void *data
)
785 #if defined(USE_WIN32_THREADS)
787 rv
= _beginthread(func
, 0, data
);
788 if (rv
== (unsigned long) -1)
791 #elif defined(USE_PTHREADS)
793 tor_pthread_data_t
*d
;
794 d
= tor_malloc(sizeof(tor_pthread_data_t
));
797 if (pthread_create(&thread
,NULL
,tor_pthread_helper_fn
,d
))
799 if (pthread_detach(thread
))
810 tor_assert(0); /* Should never reach here. */
811 return 0; /* suppress "control-reaches-end-of-non-void" warning. */
819 /** End the current thread/process.
824 #if defined(USE_WIN32_THREADS)
826 #elif defined(USE_PTHREADS)
829 /* http://www.erlenstar.demon.co.uk/unix/faq_2.html says we should
830 * call _exit, not exit, from child processes. */
835 /** Set *timeval to the current time of day. On error, log and terminate.
836 * (Same as gettimeofday(timeval,NULL), but never returns -1.)
839 tor_gettimeofday(struct timeval
*timeval
)
842 /* Epoch bias copied from perl: number of units between windows epoch and
844 #define EPOCH_BIAS U64_LITERAL(116444736000000000)
845 #define UNITS_PER_SEC U64_LITERAL(10000000)
846 #define USEC_PER_SEC U64_LITERAL(1000000)
847 #define UNITS_PER_USEC U64_LITERAL(10)
852 /* number of 100-nsec units since Jan 1, 1601 */
853 GetSystemTimeAsFileTime(&ft
.ft_ft
);
854 if (ft
.ft_64
< EPOCH_BIAS
) {
855 log_fn(LOG_ERR
, "System time is before 1970; failing.");
858 ft
.ft_64
-= EPOCH_BIAS
;
859 timeval
->tv_sec
= (unsigned) (ft
.ft_64
/ UNITS_PER_SEC
);
860 timeval
->tv_usec
= (unsigned) ((ft
.ft_64
/ UNITS_PER_USEC
) % USEC_PER_SEC
);
861 #elif defined(HAVE_GETTIMEOFDAY)
862 if (gettimeofday(timeval
, NULL
)) {
863 log_fn(LOG_ERR
, "gettimeofday failed.");
864 /* If gettimeofday dies, we have either given a bad timezone (we didn't),
868 #elif defined(HAVE_FTIME)
871 timeval
->tv_sec
= tb
.time
;
872 timeval
->tv_usec
= tb
.millitm
* 1000;
874 #error "No way to get time."
879 #if defined(TOR_IS_MULTITHREADED) && !defined(MS_WINDOWS)
880 #define TIME_FNS_NEED_LOCKS
883 #ifndef HAVE_LOCALTIME_R
884 #ifdef TIME_FNS_NEED_LOCKS
886 tor_localtime_r(const time_t *timep
, struct tm
*result
)
889 static tor_mutex_t
*m
=NULL
;
890 if (!m
) { m
=tor_mutex_new(); }
892 tor_mutex_acquire(m
);
893 r
= localtime(timep
);
894 memcpy(result
, r
, sizeof(struct tm
));
895 tor_mutex_release(m
);
900 tor_localtime_r(const time_t *timep
, struct tm
*result
)
904 r
= localtime(timep
);
905 memcpy(result
, r
, sizeof(struct tm
));
911 #ifndef HAVE_GMTIME_R
912 #ifdef TIME_FNS_NEED_LOCKS
914 tor_gmtime_r(const time_t *timep
, struct tm
*result
)
917 static tor_mutex_t
*m
=NULL
;
918 if (!m
) { m
=tor_mutex_new(); }
920 tor_mutex_acquire(m
);
922 memcpy(result
, r
, sizeof(struct tm
));
923 tor_mutex_release(m
);
928 tor_gmtime_r(const time_t *timep
, struct tm
*result
)
933 memcpy(result
, r
, sizeof(struct tm
));
939 #ifdef USE_WIN32_THREADS
947 m
= tor_malloc_zero(sizeof(tor_mutex_t
));
948 m
->handle
= CreateMutex(NULL
, FALSE
, NULL
);
949 tor_assert(m
->handle
!= NULL
);
953 tor_mutex_free(tor_mutex_t
*m
)
955 CloseHandle(m
->handle
);
959 tor_mutex_acquire(tor_mutex_t
*m
)
962 r
= WaitForSingleObject(m
->handle
, INFINITE
);
964 case WAIT_ABANDONED
: /* holding thread exited. */
965 case WAIT_OBJECT_0
: /* we got the mutex normally. */
967 case WAIT_TIMEOUT
: /* Should never happen. */
971 log_fn(LOG_WARN
, "Failed to acquire mutex: %d", GetLastError());
975 tor_mutex_release(tor_mutex_t
*m
)
978 r
= ReleaseMutex(m
->handle
);
980 log_fn(LOG_WARN
, "Failed to release mutex: %d", GetLastError());
984 tor_get_thread_id(void)
986 return (unsigned long)GetCurrentThreadId();
988 #elif defined(USE_PTHREADS)
990 pthread_mutex_t mutex
;
995 tor_mutex_t
*mutex
= tor_malloc_zero(sizeof(tor_mutex_t
));
996 pthread_mutex_init(&mutex
->mutex
, NULL
);
1000 tor_mutex_acquire(tor_mutex_t
*m
)
1003 pthread_mutex_lock(&m
->mutex
);
1006 tor_mutex_release(tor_mutex_t
*m
)
1009 pthread_mutex_unlock(&m
->mutex
);
1012 tor_mutex_free(tor_mutex_t
*m
)
1015 pthread_mutex_destroy(&m
->mutex
);
1019 tor_get_thread_id(void)
1025 r
.thr
= pthread_self();
1029 struct tor_mutex_t
{
1035 * On Windows, WSAEWOULDBLOCK is not always correct: when you see it,
1036 * you need to ask the socket for its actual errno. Also, you need to
1037 * get your errors from WSAGetLastError, not errno. (If you supply a
1038 * socket of -1, we check WSAGetLastError, but don't correct
1041 * The upshot of all of this is that when a socket call fails, you
1042 * should call tor_socket_errno <em>at most once</em> on the failing
1043 * socket to get the error.
1047 tor_socket_errno(int sock
)
1049 int optval
, optvallen
=sizeof(optval
);
1050 int err
= WSAGetLastError();
1051 if (err
== WSAEWOULDBLOCK
&& sock
>= 0) {
1052 if (getsockopt(sock
, SOL_SOCKET
, SO_ERROR
, (void*)&optval
, &optvallen
))
1062 #define E(code, s) { code, (s " [" #code " ]") }
1063 struct { int code
; const char *msg
; } windows_socket_errors
[] = {
1064 E(WSAEINTR
, "Interrupted function call"),
1065 E(WSAEACCES
, "Permission denied"),
1066 E(WSAEFAULT
, "Bad address"),
1067 E(WSAEINVAL
, "Invalid argument"),
1068 E(WSAEMFILE
, "Too many open files"),
1069 E(WSAEWOULDBLOCK
, "Resource temporarily unavailable"),
1070 E(WSAEINPROGRESS
, "Operation now in progress"),
1071 E(WSAEALREADY
, "Operation already in progress"),
1072 E(WSAENOTSOCK
, "Socket operation on nonsocket"),
1073 E(WSAEDESTADDRREQ
, "Destination address required"),
1074 E(WSAEMSGSIZE
, "Message too long"),
1075 E(WSAEPROTOTYPE
, "Protocol wrong for socket"),
1076 E(WSAENOPROTOOPT
, "Bad protocol option"),
1077 E(WSAEPROTONOSUPPORT
, "Protocol not supported"),
1078 E(WSAESOCKTNOSUPPORT
, "Socket type not supported"),
1079 /* What's the difference between NOTSUPP and NOSUPPORT? :) */
1080 E(WSAEOPNOTSUPP
, "Operation not supported"),
1081 E(WSAEPFNOSUPPORT
, "Protocol family not supported"),
1082 E(WSAEAFNOSUPPORT
, "Address family not supported by protocol family"),
1083 E(WSAEADDRINUSE
, "Address already in use"),
1084 E(WSAEADDRNOTAVAIL
, "Cannot assign requested address"),
1085 E(WSAENETDOWN
, "Network is down"),
1086 E(WSAENETUNREACH
, "Network is unreachable"),
1087 E(WSAENETRESET
, "Network dropped connection on reset"),
1088 E(WSAECONNABORTED
, "Software caused connection abort"),
1089 E(WSAECONNRESET
, "Connection reset by peer"),
1090 E(WSAENOBUFS
, "No buffer space available"),
1091 E(WSAEISCONN
, "Socket is already connected"),
1092 E(WSAENOTCONN
, "Socket is not connected"),
1093 E(WSAESHUTDOWN
, "Cannot send after socket shutdown"),
1094 E(WSAETIMEDOUT
, "Connection timed out"),
1095 E(WSAECONNREFUSED
, "Connection refused"),
1096 E(WSAEHOSTDOWN
, "Host is down"),
1097 E(WSAEHOSTUNREACH
, "No route to host"),
1098 E(WSAEPROCLIM
, "Too many processes"),
1099 /* Yes, some of these start with WSA, not WSAE. No, I don't know why. */
1100 E(WSASYSNOTREADY
, "Network subsystem is unavailable"),
1101 E(WSAVERNOTSUPPORTED
, "Winsock.dll out of range"),
1102 E(WSANOTINITIALISED
, "Successful WSAStartup not yet performed"),
1103 E(WSAEDISCON
, "Graceful shutdown now in progress"),
1104 #ifdef WSATYPE_NOT_FOUND
1105 E(WSATYPE_NOT_FOUND
, "Class type not found"),
1107 E(WSAHOST_NOT_FOUND
, "Host not found"),
1108 E(WSATRY_AGAIN
, "Nonauthoritative host not found"),
1109 E(WSANO_RECOVERY
, "This is a nonrecoverable error"),
1110 E(WSANO_DATA
, "Valid name, no data record of requested type)"),
1112 /* There are some more error codes whose numeric values are marked
1113 * <b>OS dependent</b>. They start with WSA_, apparently for the same
1114 * reason that practitioners of some craft traditions deliberately
1115 * introduce imperfections into their baskets and rugs "to allow the
1116 * evil spirits to escape." If we catch them, then our binaries
1117 * might not report consistent results across versions of Windows.
1118 * Thus, I'm going to let them all fall through.
1122 /** There does not seem to be a strerror equivalent for winsock errors.
1123 * Naturally, we have to roll our own.
1126 tor_socket_strerror(int e
)
1129 for (i
=0; windows_socket_errors
[i
].code
>= 0; ++i
) {
1130 if (e
== windows_socket_errors
[i
].code
)
1131 return windows_socket_errors
[i
].msg
;
1137 /** Called before we make any calls to network-related functions.
1138 * (Some operating systems require their network libraries to be
1144 /* This silly exercise is necessary before windows will allow
1145 * gethostbyname to work. */
1148 r
= WSAStartup(0x101,&WSAData
);
1150 log_fn(LOG_WARN
,"Error initializing windows network layer: code was %d",r
);
1153 /* WSAData.iMaxSockets might show the max sockets we're allowed to use.
1154 * We might use it to complain if we're trying to be a server but have
1155 * too few sockets available. */