Reformat inconsistent function declarations.
[tor.git] / src / common / compat.c
blob9a398fbf5395f240e5cfaf8c87260c88a25283d6
1 /* Copyright 2003-2004 Roger Dingledine
2 * Copyright 2004-2005 Roger Dingledine, Nick Mathewson */
3 /* See LICENSE for licensing information */
4 /* $Id$ */
5 const char compat_c_id[] = "$Id$";
7 /**
8 * \file compat.c
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
13 * the platform.
14 **/
16 /* This is required on rh7 to make strptime not complain.
17 * We also need it to make memmem get defined (where available)
19 #define _GNU_SOURCE
21 #include "orconfig.h"
22 #include "compat.h"
24 #ifdef MS_WINDOWS
25 #include <process.h>
27 #endif
28 #ifdef HAVE_UNAME
29 #include <sys/utsname.h>
30 #endif
31 #ifdef HAVE_SYS_TIME_H
32 #include <sys/time.h>
33 #endif
34 #ifdef HAVE_UNISTD_H
35 #include <unistd.h>
36 #endif
37 #ifdef HAVE_SYS_FCNTL_H
38 #include <sys/fcntl.h>
39 #endif
40 #ifdef HAVE_PWD_H
41 #include <pwd.h>
42 #endif
43 #ifdef HAVE_GRP_H
44 #include <grp.h>
45 #endif
46 #ifdef HAVE_FCNTL_H
47 #include <fcntl.h>
48 #endif
49 #ifdef HAVE_SYS_RESOURCE_H
50 #include <sys/resource.h>
51 #endif
52 #ifdef HAVE_ERRNO_H
53 #include <errno.h>
54 #endif
55 #ifdef HAVE_NETINET_IN_H
56 #include <netinet/in.h>
57 #endif
58 #ifdef HAVE_ARPA_INET_H
59 #include <arpa/inet.h>
60 #endif
61 #ifndef HAVE_GETTIMEOFDAY
62 #ifdef HAVE_FTIME
63 #include <sys/timeb.h>
64 #endif
65 #endif
66 #ifdef HAVE_SYS_SOCKET_H
67 #include <sys/socket.h>
68 #endif
69 #ifdef HAVE_NETDB_H
70 #include <netdb.h>
71 #endif
72 #ifdef HAVE_SYS_PARAM_H
73 #include <sys/param.h> /* FreeBSD needs this to know what version it is */
74 #endif
75 #include <stdarg.h>
76 #include <stdio.h>
77 #include <stdlib.h>
78 #include <string.h>
79 #include <assert.h>
80 #ifdef HAVE_PTHREAD_H
81 #include <pthread.h>
82 #endif
83 #ifdef HAVE_UTIME_H
84 #include <utime.h>
85 #endif
86 #ifdef HAVE_SYS_UTIME_H
87 #include <sys/utime.h>
88 #endif
90 #include "log.h"
91 #include "util.h"
93 /* Inline the strl functions if the platform doesn't have them. */
94 #ifndef HAVE_STRLCPY
95 #include "strlcpy.c"
96 #endif
97 #ifndef HAVE_STRLCAT
98 #include "strlcat.c"
99 #endif
101 /* used by inet_addr, not defined on solaris anywhere!? */
102 #ifndef INADDR_NONE
103 #define INADDR_NONE ((unsigned long) -1)
104 #endif
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, ...)
116 va_list ap;
117 int r;
118 va_start(ap,format);
119 r = tor_vsnprintf(str,size,format,ap);
120 va_end(ap);
121 return r;
124 /** Replacement for vsnprintf; behavior differs as tor_snprintf differs from
125 * snprintf.
128 tor_vsnprintf(char *str, size_t size, const char *format, va_list args)
130 int r;
131 if (size == 0)
132 return -1; /* no place for the NUL */
133 if (size > SIZE_T_CEILING)
134 return -1;
135 #ifdef MS_WINDOWS
136 r = _vsnprintf(str, size, format, args);
137 #else
138 r = vsnprintf(str, size, format, args);
139 #endif
140 str[size-1] = '\0';
141 if (r < 0 || ((size_t)r) >= size)
142 return -1;
143 return r;
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.
152 const void *
153 tor_memmem(const void *_haystack, size_t hlen, const void *_needle, size_t nlen)
155 #if defined(HAVE_MEMMEM) && (!defined(__GNUC__) || __GNUC__ >= 2)
156 tor_assert(nlen);
157 return memmem(_haystack, hlen, _needle, nlen);
158 #else
159 /* This isn't as fast as the GLIBC implementation, but it doesn't need to be. */
160 const char *p, *end;
161 const char *haystack = (const char*)_haystack;
162 const char *needle = (const char*)_needle;
163 char first;
164 tor_assert(nlen);
166 p = haystack;
167 end = haystack + hlen;
168 first = *(const char*)needle;
169 while ((p = memchr(p, first, end-p))) {
170 if (p+nlen > end)
171 return NULL;
172 if (!memcmp(p, needle, nlen))
173 return p;
174 ++p;
176 return NULL;
177 #endif
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.
186 const char *
187 _tor_fix_source_file(const char *fname)
189 const char *cp1, *cp2, *r;
190 cp1 = strrchr(fname, '/');
191 cp2 = strrchr(fname, '\\');
192 if (cp1 && cp2) {
193 r = (cp1<cp2)?(cp2+1):(cp1+1);
194 } else if (cp1) {
195 r = cp1+1;
196 } else if (cp2) {
197 r = cp2+1;
198 } else {
199 r = fname;
201 return r;
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.
210 uint16_t
211 get_uint16(const char *cp)
213 uint16_t v;
214 memcpy(&v,cp,2);
215 return v;
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.
222 uint32_t
223 get_uint32(const char *cp)
225 uint32_t v;
226 memcpy(&v,cp,4);
227 return v;
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. */
233 void
234 set_uint16(char *cp, uint16_t v)
236 memcpy(cp,&v,2);
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. */
242 void
243 set_uint32(char *cp, uint32_t v)
245 memcpy(cp,&v,4);
247 #endif
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
252 * it already exists.
253 * Returns 0 on success. Returns -1 and sets errno on failure.
256 replace_file(const char *from, const char *to)
258 #ifndef MS_WINDOWS
259 return rename(from,to);
260 #else
261 switch (file_status(to))
263 case FN_NOENT:
264 break;
265 case FN_FILE:
266 if (unlink(to)) return -1;
267 break;
268 case FN_ERROR:
269 return -1;
270 case FN_DIR:
271 errno = EISDIR;
272 return -1;
274 return rename(from,to);
275 #endif
278 /** Change <b>fname</b>'s modification time to now. */
280 touch_file(const char *fname)
282 if (utime(fname, NULL)!=0)
283 return -1;
284 return 0;
287 /** Turn <b>socket</b> into a nonblocking socket.
289 void
290 set_socket_nonblocking(int socket)
292 #ifdef MS_WINDOWS
293 int nonblocking = 1;
294 ioctlsocket(socket, FIONBIO, (unsigned long*) &nonblocking);
295 #else
296 fcntl(socket, F_SETFL, O_NONBLOCK);
297 #endif
301 * Allocate a pair of connected sockets. (Like socketpair(family,
302 * type,protocol,fd), but works on systems that don't have
303 * socketpair.)
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
321 int r;
322 r = socketpair(family, type, protocol, fd);
323 return r < 0 ? -errno : r;
324 #else
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.
330 int listener = -1;
331 int connector = -1;
332 int acceptor = -1;
333 struct sockaddr_in listen_addr;
334 struct sockaddr_in connect_addr;
335 int size;
336 int saved_errno = -1;
338 if (protocol
339 #ifdef AF_UNIX
340 || family != AF_UNIX
341 #endif
343 #ifdef MS_WINDOWS
344 return -WSAEAFNOSUPPORT;
345 #else
346 return -EAFNOSUPPORT;
347 #endif
349 if (!fd) {
350 return -EINVAL;
353 listener = socket(AF_INET, type, 0);
354 if (listener == -1)
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);
359 #ifdef MS_WINDOWS
360 return -ENFILE;
361 #else
362 return -ENCONN;
363 #endif
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))
370 == -1)
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);
376 if (connector == -1)
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);
394 if (acceptor == -1)
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
404 two sockets. */
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;
413 fd[0] = connector;
414 fd[1] = acceptor;
416 return 0;
418 abort_tidy_up_and_fail:
419 #ifdef MS_WINDOWS
420 saved_errno = WSAECONNABORTED;
421 #else
422 saved_errno = ECONNABORTED; /* I hope this is portable and appropriate. */
423 #endif
424 tidy_up_and_fail:
425 if (saved_errno < 0)
426 saved_errno = errno;
427 if (listener != -1)
428 tor_close_socket(listener);
429 if (connector != -1)
430 tor_close_socket(connector);
431 if (acceptor != -1)
432 tor_close_socket(acceptor);
433 return -saved_errno;
434 #endif
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.");
447 if (limit > cap) {
448 log(LOG_INFO, "ConnLimit must be at most %d. Capping it.", cap);
449 limit = cap;
451 #else
452 struct rlimit rlim;
453 unsigned long most;
454 tor_assert(limit > 0);
455 tor_assert(cap > 0);
457 if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) {
458 log_fn(LOG_WARN, "Could not get maximum number of file descriptors: %s",
459 strerror(errno));
460 return -1;
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);
464 return -1;
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",
474 strerror(errno));
475 return -1;
477 /* leave some overhead for logs, etc, */
478 limit = most;
479 #endif
481 if (limit < ULIMIT_BUFFER) {
482 log_fn(LOG_WARN,"ConnLimit must be at least %d. Failing.", ULIMIT_BUFFER);
483 return -1;
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)
494 #ifndef MS_WINDOWS
495 struct passwd *pw = NULL;
496 struct group *gr = NULL;
498 if (user) {
499 pw = getpwnam(user);
500 if (pw == NULL) {
501 log_fn(LOG_ERR,"User '%s' not found.", user);
502 return -1;
506 /* switch the group first, while we still have the privileges to do so */
507 if (group) {
508 gr = getgrnam(group);
509 if (gr == NULL) {
510 log_fn(LOG_ERR,"Group '%s' not found.", group);
511 return -1;
514 if (setgid(gr->gr_gid) != 0) {
515 log_fn(LOG_ERR,"Error setting GID: %s", strerror(errno));
516 return -1;
518 } else if (user) {
519 if (setgid(pw->pw_gid) != 0) {
520 log_fn(LOG_ERR,"Error setting GID: %s", strerror(errno));
521 return -1;
525 /* now that the group is switched, we can switch users and lose
526 privileges */
527 if (user) {
528 if (setuid(pw->pw_uid) != 0) {
529 log_fn(LOG_ERR,"Error setting UID: %s", strerror(errno));
530 return -1;
534 return 0;
535 #endif
537 log_fn(LOG_ERR,
538 "User or group specified, but switching users is not supported.");
540 return -1;
543 #ifdef HAVE_PWD_H
544 /** Allocate and return a string containing the home directory for the
545 * user <b>username</b>. Only works on posix-like systems */
546 char *
547 get_user_homedir(const char *username)
549 struct passwd *pw;
550 tor_assert(username);
552 if (!(pw = getpwnam(username))) {
553 log_fn(LOG_ERR,"User \"%s\" not found.", username);
554 return NULL;
556 return tor_strdup(pw->pw_dir);
558 #endif
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);
569 #else
570 uint32_t r;
571 tor_assert(c);
572 tor_assert(addr);
573 if (strcmp(c, "255.255.255.255") == 0) {
574 addr->s_addr = 0xFFFFFFFFu;
575 return 1;
577 r = inet_addr(c);
578 if (r == INADDR_NONE)
579 return 0;
580 addr->s_addr = r;
581 return 1;
582 #endif
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
596 * something.
598 struct in_addr iaddr;
599 tor_assert(name);
600 tor_assert(addr);
601 if (!*name) {
602 /* Empty address is an error. */
603 return -1;
604 } else if (tor_inet_aton(name, &iaddr)) {
605 /* It's an IP. */
606 memcpy(addr, &iaddr.s_addr, 4);
607 return 0;
608 } else {
609 #ifdef HAVE_GETADDRINFO
610 int err;
611 struct addrinfo *res=NULL, *res_p;
612 struct addrinfo hints;
613 int result = -1;
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);
618 if (!err) {
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);
623 result = 0;
624 break;
627 freeaddrinfo(res);
628 return result;
630 return (err == EAI_AGAIN) ? 1 : -1;
631 #else
632 struct hostent *ent;
633 int err;
634 #ifdef HAVE_GETHOSTBYNAME_R_6_ARG
635 char buf[2048];
636 struct hostent hostent;
637 int r;
638 r = gethostbyname_r(name, &hostent, buf, sizeof(buf), &ent, &err);
639 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
640 char buf[2048];
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;
645 struct hostent hent;
646 memset(&data, 0, sizeof(data));
647 err = gethostbyname_r(name, &hent, &data);
648 ent = err ? NULL : &hent;
649 #else
650 ent = gethostbyname(name);
651 #ifdef MS_WINDOWS
652 err = WSAGetLastError();
653 #else
654 err = h_errno;
655 #endif
656 #endif
657 if (ent) {
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);
661 return 0;
663 memset(addr, 0, 4);
664 #ifdef MS_WINDOWS
665 return (err == WSATRY_AGAIN) ? 1 : -1;
666 #else
667 return (err == TRY_AGAIN) ? 1 : -1;
668 #endif
669 #endif
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.
680 const char *
681 get_uname(void)
683 #ifdef HAVE_UNAME
684 struct utsname u;
685 #endif
686 if (!uname_result_is_set) {
687 #ifdef HAVE_UNAME
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);
692 } else
693 #endif
695 #ifdef MS_WINDOWS
696 OSVERSIONINFO info;
697 int i;
698 const char *plat = NULL;
699 static struct {
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" },
710 { -1, -1, NULL }
712 info.dwOSVersionInfoSize = sizeof(info);
713 GetVersionEx(&info);
714 if (info.dwMajorVersion == 4 && info.dwMinorVersion == 0) {
715 if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
716 plat = "Windows NT 4.0";
717 else
718 plat = "Windows 95";
719 } else {
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;
724 break;
728 if (plat) {
729 strlcpy(uname_result, plat, sizeof(uname_result));
730 } else {
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);
736 else
737 tor_snprintf(uname_result, sizeof(uname_result),
738 "Unrecognized version of Windows [major=%d,minor=%d]",
739 (int)info.dwMajorVersion,(int)info.dwMinorVersion);
741 #else
742 strlcpy(uname_result, "Unknown platform", sizeof(uname_result));
743 #endif
745 uname_result_is_set = 1;
747 return uname_result;
751 * Process control
754 #if defined(USE_PTHREADS)
755 typedef struct tor_pthread_data_t {
756 int (*func)(void *);
757 void *data;
758 } tor_pthread_data_t;
759 static void *
760 tor_pthread_helper_fn(void *_data)
762 tor_pthread_data_t *data = _data;
763 int (*func)(void*);
764 void *arg;
765 func = data->func;
766 arg = data->data;
767 tor_free(_data);
768 func(arg);
769 return NULL;
771 #endif
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
780 * running.
783 spawn_func(int (*func)(void *), void *data)
785 #if defined(USE_WIN32_THREADS)
786 int rv;
787 rv = _beginthread(func, 0, data);
788 if (rv == (unsigned long) -1)
789 return -1;
790 return 0;
791 #elif defined(USE_PTHREADS)
792 pthread_t thread;
793 tor_pthread_data_t *d;
794 d = tor_malloc(sizeof(tor_pthread_data_t));
795 d->data = data;
796 d->func = func;
797 if (pthread_create(&thread,NULL,tor_pthread_helper_fn,d))
798 return -1;
799 if (pthread_detach(thread))
800 return -1;
801 return 0;
802 #else
803 pid_t pid;
804 pid = fork();
805 if (pid<0)
806 return -1;
807 if (pid==0) {
808 /* Child */
809 func(data);
810 tor_assert(0); /* Should never reach here. */
811 return 0; /* suppress "control-reaches-end-of-non-void" warning. */
812 } else {
813 /* Parent */
814 return 0;
816 #endif
819 /** End the current thread/process.
821 void
822 spawn_exit(void)
824 #if defined(USE_WIN32_THREADS)
825 _endthread();
826 #elif defined(USE_PTHREADS)
827 pthread_exit(NULL);
828 #else
829 /* http://www.erlenstar.demon.co.uk/unix/faq_2.html says we should
830 * call _exit, not exit, from child processes. */
831 _exit(0);
832 #endif
835 /** Set *timeval to the current time of day. On error, log and terminate.
836 * (Same as gettimeofday(timeval,NULL), but never returns -1.)
838 void
839 tor_gettimeofday(struct timeval *timeval)
841 #ifdef MS_WINDOWS
842 /* Epoch bias copied from perl: number of units between windows epoch and
843 * unix epoch. */
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)
848 union {
849 uint64_t ft_64;
850 FILETIME ft_ft;
851 } ft;
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.");
856 exit(1);
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),
865 or segfaulted.*/
866 exit(1);
868 #elif defined(HAVE_FTIME)
869 struct timeb tb;
870 ftime(&tb);
871 timeval->tv_sec = tb.time;
872 timeval->tv_usec = tb.millitm * 1000;
873 #else
874 #error "No way to get time."
875 #endif
876 return;
879 #if defined(TOR_IS_MULTITHREADED) && !defined(MS_WINDOWS)
880 #define TIME_FNS_NEED_LOCKS
881 #endif
883 #ifndef HAVE_LOCALTIME_R
884 #ifdef TIME_FNS_NEED_LOCKS
885 struct tm *
886 tor_localtime_r(const time_t *timep, struct tm *result)
888 struct tm *r;
889 static tor_mutex_t *m=NULL;
890 if (!m) { m=tor_mutex_new(); }
891 tor_assert(result);
892 tor_mutex_acquire(m);
893 r = localtime(timep);
894 memcpy(result, r, sizeof(struct tm));
895 tor_mutex_release(m);
896 return result;
898 #else
899 struct tm *
900 tor_localtime_r(const time_t *timep, struct tm *result)
902 struct tm *r;
903 tor_assert(result);
904 r = localtime(timep);
905 memcpy(result, r, sizeof(struct tm));
906 return result;
908 #endif
909 #endif
911 #ifndef HAVE_GMTIME_R
912 #ifdef TIME_FNS_NEED_LOCKS
913 struct tm *
914 tor_gmtime_r(const time_t *timep, struct tm *result)
916 struct tm *r;
917 static tor_mutex_t *m=NULL;
918 if (!m) { m=tor_mutex_new(); }
919 tor_assert(result);
920 tor_mutex_acquire(m);
921 r = gmtime(timep);
922 memcpy(result, r, sizeof(struct tm));
923 tor_mutex_release(m);
924 return result;
926 #else
927 struct tm *
928 tor_gmtime_r(const time_t *timep, struct tm *result)
930 struct tm *r;
931 tor_assert(result);
932 r = gmtime(timep);
933 memcpy(result, r, sizeof(struct tm));
934 return result;
936 #endif
937 #endif
939 #ifdef USE_WIN32_THREADS
940 struct tor_mutex_t {
941 HANDLE handle;
943 tor_mutex_t *
944 tor_mutex_new(void)
946 tor_mutex_t *m;
947 m = tor_malloc_zero(sizeof(tor_mutex_t));
948 m->handle = CreateMutex(NULL, FALSE, NULL);
949 tor_assert(m->handle != NULL);
950 return m;
952 void
953 tor_mutex_free(tor_mutex_t *m)
955 CloseHandle(m->handle);
956 tor_free(m);
958 void
959 tor_mutex_acquire(tor_mutex_t *m)
961 DWORD r;
962 r = WaitForSingleObject(m->handle, INFINITE);
963 switch (r) {
964 case WAIT_ABANDONED: /* holding thread exited. */
965 case WAIT_OBJECT_0: /* we got the mutex normally. */
966 break;
967 case WAIT_TIMEOUT: /* Should never happen. */
968 tor_assert(0);
969 break;
970 case WAIT_FAILED:
971 log_fn(LOG_WARN, "Failed to acquire mutex: %d", GetLastError());
974 void
975 tor_mutex_release(tor_mutex_t *m)
977 BOOL r;
978 r = ReleaseMutex(m->handle);
979 if (!r) {
980 log_fn(LOG_WARN, "Failed to release mutex: %d", GetLastError());
983 unsigned long
984 tor_get_thread_id(void)
986 return (unsigned long)GetCurrentThreadId();
988 #elif defined(USE_PTHREADS)
989 struct tor_mutex_t {
990 pthread_mutex_t mutex;
992 tor_mutex_t *
993 tor_mutex_new(void)
995 tor_mutex_t *mutex = tor_malloc_zero(sizeof(tor_mutex_t));
996 pthread_mutex_init(&mutex->mutex, NULL);
997 return mutex;
999 void
1000 tor_mutex_acquire(tor_mutex_t *m)
1002 tor_assert(m);
1003 pthread_mutex_lock(&m->mutex);
1005 void
1006 tor_mutex_release(tor_mutex_t *m)
1008 tor_assert(m);
1009 pthread_mutex_unlock(&m->mutex);
1011 void
1012 tor_mutex_free(tor_mutex_t *m)
1014 tor_assert(m);
1015 pthread_mutex_destroy(&m->mutex);
1016 tor_free(m);
1018 unsigned long
1019 tor_get_thread_id(void)
1021 union {
1022 pthread_t thr;
1023 unsigned long id;
1024 } r;
1025 r.thr = pthread_self();
1026 return r.id;
1028 #else
1029 struct tor_mutex_t {
1030 int _unused;
1032 #endif
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
1039 * WSAEWOULDBLOCKs.)
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.
1045 #ifdef MS_WINDOWS
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))
1053 return err;
1054 if (optval)
1055 return optval;
1057 return err;
1059 #endif
1061 #ifdef MS_WINDOWS
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"),
1106 #endif
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.
1120 { -1, NULL },
1122 /** There does not seem to be a strerror equivalent for winsock errors.
1123 * Naturally, we have to roll our own.
1125 const char *
1126 tor_socket_strerror(int e)
1128 int i;
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;
1133 return strerror(e);
1135 #endif
1137 /** Called before we make any calls to network-related functions.
1138 * (Some operating systems require their network libraries to be
1139 * initialized.) */
1141 network_init(void)
1143 #ifdef MS_WINDOWS
1144 /* This silly exercise is necessary before windows will allow
1145 * gethostbyname to work. */
1146 WSADATA WSAData;
1147 int r;
1148 r = WSAStartup(0x101,&WSAData);
1149 if (r) {
1150 log_fn(LOG_WARN,"Error initializing windows network layer: code was %d",r);
1151 return -1;
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. */
1156 #endif
1157 return 0;