clean up the socket counting thing. third time's a charm.
[tor.git] / src / common / compat.c
blob018600e251eee0b10475d7c92be9b71e4607f4d1
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 */
5 /* $Id$ */
6 const char compat_c_id[] =
7 "$Id$";
9 /**
10 * \file compat.c
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
15 * the platform.
16 **/
18 /* This is required on rh7 to make strptime not complain.
19 * We also need it to make memmem get defined (where available)
21 #define _GNU_SOURCE
23 #include "orconfig.h"
24 #include "compat.h"
26 #ifdef MS_WINDOWS
27 #include <process.h>
28 #include <windows.h>
29 #endif
31 #ifdef HAVE_UNAME
32 #include <sys/utsname.h>
33 #endif
34 #ifdef HAVE_SYS_TIME_H
35 #include <sys/time.h>
36 #endif
37 #ifdef HAVE_UNISTD_H
38 #include <unistd.h>
39 #endif
40 #ifdef HAVE_SYS_FCNTL_H
41 #include <sys/fcntl.h>
42 #endif
43 #ifdef HAVE_PWD_H
44 #include <pwd.h>
45 #endif
46 #ifdef HAVE_GRP_H
47 #include <grp.h>
48 #endif
49 #ifdef HAVE_FCNTL_H
50 #include <fcntl.h>
51 #endif
52 #ifdef HAVE_SYS_RESOURCE_H
53 #include <sys/resource.h>
54 #endif
55 #ifdef HAVE_ERRNO_H
56 #include <errno.h>
57 #endif
58 #ifdef HAVE_NETINET_IN_H
59 #include <netinet/in.h>
60 #endif
61 #ifdef HAVE_ARPA_INET_H
62 #include <arpa/inet.h>
63 #endif
64 #ifndef HAVE_GETTIMEOFDAY
65 #ifdef HAVE_FTIME
66 #include <sys/timeb.h>
67 #endif
68 #endif
69 #ifdef HAVE_SYS_SOCKET_H
70 #include <sys/socket.h>
71 #endif
72 #ifdef HAVE_NETDB_H
73 #include <netdb.h>
74 #endif
75 #ifdef HAVE_SYS_PARAM_H
76 #include <sys/param.h> /* FreeBSD needs this to know what version it is */
77 #endif
78 #include <stdarg.h>
79 #include <stdio.h>
80 #include <stdlib.h>
81 #include <string.h>
82 #include <assert.h>
83 #ifdef HAVE_PTHREAD_H
84 #include <pthread.h>
85 #endif
86 #ifdef HAVE_SIGNAL_H
87 #include <signal.h>
88 #endif
89 #ifdef HAVE_UTIME_H
90 #include <utime.h>
91 #endif
92 #ifdef HAVE_SYS_UTIME_H
93 #include <sys/utime.h>
94 #endif
95 #ifdef HAVE_SYS_MMAN_H
96 #include <sys/mman.h>
97 #endif
98 #ifdef HAVE_SYS_SYSLIMITS_H
99 #include <sys/syslimits.h>
100 #endif
102 #ifdef USE_BSOCKETS
103 #include <bsocket.h>
104 #endif
106 #include "log.h"
107 #include "util.h"
108 #include "container.h"
110 /* Inline the strl functions if the platform doesn't have them. */
111 #ifndef HAVE_STRLCPY
112 #include "strlcpy.c"
113 #endif
114 #ifndef HAVE_STRLCAT
115 #include "strlcat.c"
116 #endif
118 #ifndef INADDR_NONE
119 /* This is used by inet_addr, but apparently Solaris doesn't define it
120 * anyplace. */
121 #define INADDR_NONE ((unsigned long) -1)
122 #endif
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 {
128 tor_mmap_t base;
129 size_t mapping_size; /**< Size of the actual mapping. (This is this file
130 * size, rounded up to the nearest page.) */
131 } tor_mmap_impl_t;
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
135 * "empty file". */
136 tor_mmap_t *
137 tor_mmap_file(const char *filename)
139 int fd; /* router file */
140 char *string;
141 int page_size;
142 tor_mmap_impl_t *res;
143 size_t size, filesize;
145 tor_assert(filename);
147 fd = open(filename, O_RDONLY, 0);
148 if (fd<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,
152 strerror(errno));
153 errno = save_errno;
154 return NULL;
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;
163 if (!size) {
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);
167 errno = ERANGE;
168 close(fd);
169 return NULL;
172 string = mmap(0, size, PROT_READ, MAP_PRIVATE, fd, 0);
173 close(fd);
174 if (string == MAP_FAILED) {
175 int save_errno = errno;
176 log_warn(LD_FS,"Could not mmap file \"%s\": %s", filename,
177 strerror(errno));
178 errno = save_errno;
179 return NULL;
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;
187 return &(res->base);
189 /** Release storage held for a memory mapping. */
190 void
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);
195 tor_free(h);
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 {
201 tor_mmap_t base;
202 HANDLE file_handle;
203 HANDLE mmap_handle;
204 } win_mmap_t;
205 tor_mmap_t *
206 tor_mmap_file(const char *filename)
208 win_mmap_t *res = tor_malloc_zero(sizeof(win_mmap_t));
209 int empty = 0;
210 res->file_handle = INVALID_HANDLE_VALUE;
211 res->mmap_handle = NULL;
213 res->file_handle = CreateFile(filename,
214 GENERIC_READ, FILE_SHARE_READ,
215 NULL,
216 OPEN_EXISTING,
217 FILE_ATTRIBUTE_NORMAL,
220 if (res->file_handle == INVALID_HANDLE_VALUE)
221 goto win_err;
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);
227 empty = 1;
228 goto err;
231 res->mmap_handle = CreateFileMapping(res->file_handle,
232 NULL,
233 PAGE_READONLY,
234 #if SIZEOF_SIZE_T > 4
235 (res->base.size >> 32),
236 #else
238 #endif
239 (res->base.size & 0xfffffffful),
240 NULL);
241 if (res->mmap_handle == NULL)
242 goto win_err;
243 res->base.data = (char*) MapViewOfFile(res->mmap_handle,
244 FILE_MAP_READ,
245 0, 0, 0);
246 if (!res->base.data)
247 goto win_err;
249 return &(res->base);
250 win_err: {
251 DWORD e = GetLastError();
252 int severity = (e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND) ?
253 LOG_INFO : LOG_WARN;
254 char *msg = format_win32_error(e);
255 log_fn(severity, LD_FS, "Couldn't mmap file \"%s\": %s", filename, msg);
256 tor_free(msg);
257 if (e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND)
258 errno = ENOENT;
259 else
260 errno = EINVAL;
262 err:
263 if (empty)
264 errno = ERANGE;
265 tor_munmap_file(&res->base);
266 return NULL;
268 void
269 tor_munmap_file(tor_mmap_t *handle)
271 win_mmap_t *h = SUBTYPE_P(handle, win_mmap_t, base);
272 if (handle->data)
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);
281 tor_free(h);
283 #else
284 tor_mmap_t *
285 tor_mmap_file(const char *filename)
287 struct stat st;
288 char *res = read_file_to_str(filename, RFTS_BIN|RFTS_IGNORE_MISSING, &st);
289 tor_mmap_t *handle;
290 if (! res)
291 return NULL;
292 handle = tor_malloc_zero(sizeof(tor_mmap_t));
293 handle->data = res;
294 handle->size = st.st_size;
295 return handle;
297 void
298 tor_munmap_file(tor_mmap_t *handle)
300 char *d = (char*)handle->data;
301 tor_free(d);
302 memset(handle, 0, sizeof(tor_mmap_t));
303 tor_free(handle);
305 #endif
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, ...)
317 va_list ap;
318 int r;
319 va_start(ap,format);
320 r = tor_vsnprintf(str,size,format,ap);
321 va_end(ap);
322 return r;
325 /** Replacement for vsnprintf; behavior differs as tor_snprintf differs from
326 * snprintf.
329 tor_vsnprintf(char *str, size_t size, const char *format, va_list args)
331 int r;
332 if (size == 0)
333 return -1; /* no place for the NUL */
334 if (size > SIZE_T_CEILING)
335 return -1;
336 #ifdef MS_WINDOWS
337 r = _vsnprintf(str, size, format, args);
338 #else
339 r = vsnprintf(str, size, format, args);
340 #endif
341 str[size-1] = '\0';
342 if (r < 0 || ((size_t)r) >= size)
343 return -1;
344 return r;
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.
353 const void *
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)
358 tor_assert(nlen);
359 return memmem(_haystack, hlen, _needle, nlen);
360 #else
361 /* This isn't as fast as the GLIBC implementation, but it doesn't need to
362 * be. */
363 const char *p, *end;
364 const char *haystack = (const char*)_haystack;
365 const char *needle = (const char*)_needle;
366 char first;
367 tor_assert(nlen);
369 p = haystack;
370 end = haystack + hlen;
371 first = *(const char*)needle;
372 while ((p = memchr(p, first, end-p))) {
373 if (p+nlen > end)
374 return NULL;
375 if (!memcmp(p, needle, nlen))
376 return p;
377 ++p;
379 return NULL;
380 #endif
383 #ifdef MS_WINDOWS
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.
390 const char *
391 tor_fix_source_file(const char *fname)
393 const char *cp1, *cp2, *r;
394 cp1 = strrchr(fname, '/');
395 cp2 = strrchr(fname, '\\');
396 if (cp1 && cp2) {
397 r = (cp1<cp2)?(cp2+1):(cp1+1);
398 } else if (cp1) {
399 r = cp1+1;
400 } else if (cp2) {
401 r = cp2+1;
402 } else {
403 r = fname;
405 return r;
407 #endif
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.
414 uint16_t
415 get_uint16(const char *cp)
417 uint16_t v;
418 memcpy(&v,cp,2);
419 return v;
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.
426 uint32_t
427 get_uint32(const char *cp)
429 uint32_t v;
430 memcpy(&v,cp,4);
431 return v;
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. */
437 void
438 set_uint16(char *cp, uint16_t v)
440 memcpy(cp,&v,2);
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. */
446 void
447 set_uint32(char *cp, uint32_t v)
449 memcpy(cp,&v,4);
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
455 * it already exists.
456 * Returns 0 on success. Returns -1 and sets errno on failure.
459 replace_file(const char *from, const char *to)
461 #ifndef MS_WINDOWS
462 return rename(from,to);
463 #else
464 switch (file_status(to))
466 case FN_NOENT:
467 break;
468 case FN_FILE:
469 if (unlink(to)) return -1;
470 break;
471 case FN_ERROR:
472 return -1;
473 case FN_DIR:
474 errno = EISDIR;
475 return -1;
477 return rename(from,to);
478 #endif
481 /** Change <b>fname</b>'s modification time to now. */
483 touch_file(const char *fname)
485 if (utime(fname, NULL)!=0)
486 return -1;
487 return 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
496 * on failure. */
498 tor_close_socket(int s)
500 int r = 0;
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
505 * files.
507 #ifdef USE_BSOCKETS
508 r = bclose(s);
509 #elif defined(MS_WINDOWS)
510 r = closesocket(s);
511 #else
512 r = close(s);
513 #endif
514 if (r == 0) {
515 --n_sockets_open;
516 } else {
517 int err = tor_socket_errno(-1);
518 log_info(LD_NET, "Close returned an error: %s", tor_socket_strerror(err));
519 #ifdef WIN32
520 if (err != WSAENOTSOCK)
521 --n_sockets_open;
522 #else
523 if (err != EBADF)
524 --n_sockets_open;
525 #endif
526 r = -1;
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);
531 return r;
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);
539 if (s >= 0)
540 ++n_sockets_open;
541 return s;
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.
553 void
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);
559 #else
560 fcntl(socket, F_SETFL, O_NONBLOCK);
561 #endif
565 * Allocate a pair of connected sockets. (Like socketpair(family,
566 * type,protocol,fd), but works on systems that don't have
567 * socketpair.)
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)
586 int r;
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);
591 #else
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.
597 int listener = -1;
598 int connector = -1;
599 int acceptor = -1;
600 struct sockaddr_in listen_addr;
601 struct sockaddr_in connect_addr;
602 int size;
603 int saved_errno = -1;
605 if (protocol
606 #ifdef AF_UNIX
607 || family != AF_UNIX
608 #endif
610 #ifdef MS_WINDOWS
611 return -WSAEAFNOSUPPORT;
612 #else
613 return -EAFNOSUPPORT;
614 #endif
616 if (!fd) {
617 return -EINVAL;
620 listener = tor_open_socket(AF_INET, type, 0);
621 if (listener < 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))
628 == -1)
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);
634 if (connector < 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);
648 if (acceptor < 0)
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
654 two sockets. */
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;
663 fd[0] = connector;
664 fd[1] = acceptor;
666 return 0;
668 abort_tidy_up_and_fail:
669 #ifdef MS_WINDOWS
670 saved_errno = WSAECONNABORTED;
671 #else
672 saved_errno = ECONNABORTED; /* I hope this is portable and appropriate. */
673 #endif
674 tidy_up_and_fail:
675 if (saved_errno < 0)
676 saved_errno = errno;
677 if (listener != -1)
678 tor_close_socket(listener);
679 if (connector != -1)
680 tor_close_socket(connector);
681 if (acceptor != -1)
682 tor_close_socket(acceptor);
683 return -saved_errno;
684 #endif
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;
691 #endif
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.");
708 if (limit < cap) {
709 log_info(LD_CONFIG, "ConnLimit must be at most %d. Using that.", (int)cap);
710 limit = cap;
712 #else
713 struct rlimit rlim;
714 rlim_t most;
715 tor_assert(limit > 0);
716 tor_assert(cap > 0);
718 if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) {
719 log_warn(LD_NET, "Could not get maximum number of file descriptors: %s",
720 strerror(errno));
721 return -1;
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);
728 return -1;
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) {
738 int bad = 1;
739 #ifdef OPEN_MAX
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);
749 } else {
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;
755 bad = 0;
758 #endif
759 if (bad) {
760 log_warn(LD_CONFIG,"Couldn't set maximum number of file descriptors: %s",
761 strerror(errno));
762 return -1;
765 /* leave some overhead for logs, etc, */
766 limit = most;
767 #endif
769 if (limit < ULIMIT_BUFFER) {
770 log_warn(LD_CONFIG,
771 "ConnLimit must be at least %d. Failing.", ULIMIT_BUFFER);
772 return -1;
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)
783 #ifndef MS_WINDOWS
784 struct passwd *pw = NULL;
785 struct group *gr = NULL;
787 if (user) {
788 pw = getpwnam(user);
789 if (pw == NULL) {
790 log_warn(LD_CONFIG,"User '%s' not found.", user);
791 return -1;
795 /* switch the group first, while we still have the privileges to do so */
796 if (group) {
797 gr = getgrnam(group);
798 if (gr == NULL) {
799 log_warn(LD_CONFIG,"Group '%s' not found.", group);
800 return -1;
803 if (setgid(gr->gr_gid) != 0) {
804 log_warn(LD_GENERAL,"Error setting to configured GID: %s",
805 strerror(errno));
806 return -1;
808 } else if (user) {
809 if (setgid(pw->pw_gid) != 0) {
810 log_warn(LD_GENERAL,"Error setting to user GID: %s", strerror(errno));
811 return -1;
815 /* now that the group is switched, we can switch users and lose
816 privileges */
817 if (user) {
818 if (setuid(pw->pw_uid) != 0) {
819 log_warn(LD_GENERAL,"Error setting UID: %s", strerror(errno));
820 return -1;
824 return 0;
825 #else
826 (void)user;
827 (void)group;
828 #endif
830 log_warn(LD_CONFIG,
831 "User or group specified, but switching users is not supported.");
832 return -1;
835 #ifdef HAVE_PWD_H
836 /** Allocate and return a string containing the home directory for the
837 * user <b>username</b>. Only works on posix-like systems. */
838 char *
839 get_user_homedir(const char *username)
841 struct passwd *pw;
842 tor_assert(username);
844 if (!(pw = getpwnam(username))) {
845 log_err(LD_CONFIG,"User \"%s\" not found.", username);
846 return NULL;
848 return tor_strdup(pw->pw_dir);
850 #endif
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);
861 #else
862 uint32_t r;
863 tor_assert(c);
864 tor_assert(addr);
865 if (strcmp(c, "255.255.255.255") == 0) {
866 addr->s_addr = 0xFFFFFFFFu;
867 return 1;
869 r = inet_addr(c);
870 if (r == INADDR_NONE)
871 return 0;
872 addr->s_addr = r;
873 return 1;
874 #endif
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
884 * support.) */
885 const char *
886 tor_inet_ntop(int af, const void *src, char *dst, size_t len)
888 if (af == AF_INET) {
889 if (tor_inet_ntoa(src, dst, len) < 0)
890 return NULL;
891 else
892 return dst;
893 } else if (af == AF_INET6) {
894 const struct in6_addr *addr = src;
895 char buf[64], *cp;
896 int longestGapLen = 0, longestGapPos = -1, i,
897 curGapPos = -1, curGapLen = 0;
898 uint16_t words[8];
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. */
906 if (words[5] == 0) {
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]);
910 } else {
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)
916 return NULL;
917 strlcpy(dst, buf, len);
918 return dst;
920 i = 0;
921 while (i < 8) {
922 if (words[i] == 0) {
923 curGapPos = i++;
924 curGapLen = 1;
925 while (i<8 && words[i] == 0) {
926 ++i; ++curGapLen;
928 if (curGapLen > longestGapLen) {
929 longestGapPos = curGapPos;
930 longestGapLen = curGapLen;
932 } else {
933 ++i;
936 if (longestGapLen<=1)
937 longestGapPos = -1;
939 cp = buf;
940 for (i = 0; i < 8; ++i) {
941 if (words[i] == 0 && longestGapPos == i) {
942 if (i == 0)
943 *cp++ = ':';
944 *cp++ = ':';
945 while (i < 8 && words[i] == 0)
946 ++i;
947 --i; /* to compensate for loop increment. */
948 } else {
949 tor_snprintf(cp, sizeof(buf)-(cp-buf), "%x", (unsigned)words[i]);
950 cp += strlen(cp);
951 if (i != 7)
952 *cp++ = ':';
955 *cp = '\0';
956 if (strlen(buf) > len)
957 return NULL;
958 strlcpy(dst, buf, len);
959 return dst;
960 } else {
961 return NULL;
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
973 * support.) */
975 tor_inet_pton(int af, const char *src, void *dst)
977 if (af == AF_INET) {
978 return tor_inet_aton(src, dst);
979 } else if (af == AF_INET6) {
980 struct in6_addr *out = dst;
981 uint16_t words[8];
982 int gapPos = -1, i, setWords=0;
983 const char *dot = strchr(src, '.');
984 const char *eow; /* end of words. */
985 if (dot == src)
986 return 0;
987 else if (!dot)
988 eow = src+strlen(src);
989 else {
990 int byte1,byte2,byte3,byte4;
991 char more;
992 for (eow = dot-1; eow >= src && TOR_ISDIGIT(*eow); --eow)
994 ++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)
999 return 0;
1001 if (byte1 > 255 || byte1 < 0 ||
1002 byte2 > 255 || byte2 < 0 ||
1003 byte3 > 255 || byte3 < 0 ||
1004 byte4 > 255 || byte4 < 0)
1005 return 0;
1007 words[6] = (byte1<<8) | byte2;
1008 words[7] = (byte3<<8) | byte4;
1009 setWords += 2;
1012 i = 0;
1013 while (src < eow) {
1014 if (i > 7)
1015 return 0;
1016 if (TOR_ISXDIGIT(*src)) {
1017 char *next;
1018 int r = strtol(src, &next, 16);
1019 if (next > 4+src)
1020 return 0;
1021 if (next == src)
1022 return 0;
1023 if (r<0 || r>65536)
1024 return 0;
1026 words[i++] = (uint16_t)r;
1027 setWords++;
1028 src = next;
1029 if (*src != ':' && src != eow)
1030 return 0;
1031 ++src;
1032 } else if (*src == ':' && i > 0 && gapPos==-1) {
1033 gapPos = i;
1034 ++src;
1035 } else if (*src == ':' && i == 0 && src[1] == ':' && gapPos==-1) {
1036 gapPos = i;
1037 src += 2;
1038 } else {
1039 return 0;
1043 if (setWords > 8 ||
1044 (setWords == 8 && gapPos != -1) ||
1045 (setWords < 8 && gapPos == -1))
1046 return 0;
1048 if (gapPos >= 0) {
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;
1061 return 1;
1062 } else {
1063 return -1;
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)
1077 tor_addr_t myaddr;
1078 int ret;
1080 if ((ret = tor_addr_lookup(name, AF_INET, &myaddr)))
1081 return ret;
1083 if (IN_FAMILY(&myaddr) == AF_INET) {
1084 *addr = IPV4IPh(&myaddr);
1085 return ret;
1088 return -1;
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
1103 * something.
1105 struct in_addr iaddr;
1106 struct in6_addr iaddr6;
1107 tor_assert(name);
1108 tor_assert(addr);
1109 tor_assert(family == AF_INET || family == AF_UNSPEC);
1110 memset(addr, 0, sizeof(addr)); /* Clear the extraneous fields. */
1111 if (!*name) {
1112 /* Empty address is an error. */
1113 return -1;
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));
1118 return 0;
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));
1122 return 0;
1123 } else {
1124 #ifdef HAVE_GETADDRINFO
1125 int err;
1126 struct addrinfo *res=NULL, *res_p;
1127 struct addrinfo *best=NULL;
1128 struct addrinfo hints;
1129 int result = -1;
1130 memset(&hints, 0, sizeof(hints));
1131 hints.ai_family = family;
1132 hints.ai_socktype = SOCK_STREAM;
1133 err = getaddrinfo(name, NULL, &hints, &res);
1134 if (!err) {
1135 best = NULL;
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) {
1139 best = res_p;
1140 break;
1141 } else if (res_p->ai_family == AF_INET6 && !best) {
1142 best = res_p;
1144 } else if (family == res_p->ai_family) {
1145 best = res_p;
1146 break;
1149 if (!best)
1150 best = res;
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));
1156 result = 0;
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));
1162 result = 0;
1164 freeaddrinfo(res);
1165 return result;
1167 return (err == EAI_AGAIN) ? 1 : -1;
1168 #else
1169 struct hostent *ent;
1170 int err;
1171 #ifdef HAVE_GETHOSTBYNAME_R_6_ARG
1172 char buf[2048];
1173 struct hostent hostent;
1174 int r;
1175 r = gethostbyname_r(name, &hostent, buf, sizeof(buf), &ent, &err);
1176 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
1177 char buf[2048];
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;
1186 #else
1187 ent = gethostbyname(name);
1188 #ifdef MS_WINDOWS
1189 err = WSAGetLastError();
1190 #else
1191 err = h_errno;
1192 #endif
1193 #endif /* endif HAVE_GETHOSTBYNAME_R_6_ARG. */
1194 if (ent) {
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));
1200 } else {
1201 tor_assert(0); /* gethostbyname() returned a bizarre addrtype */
1203 return 0;
1205 #ifdef MS_WINDOWS
1206 return (err == WSATRY_AGAIN) ? 1 : -1;
1207 #else
1208 return (err == TRY_AGAIN) ? 1 : -1;
1209 #endif
1210 #endif
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.
1221 const char *
1222 get_uname(void)
1224 #ifdef HAVE_UNAME
1225 struct utsname u;
1226 #endif
1227 if (!uname_result_is_set) {
1228 #ifdef HAVE_UNAME
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);
1233 } else
1234 #endif
1236 #ifdef MS_WINDOWS
1237 OSVERSIONINFOEX info;
1238 int i;
1239 unsigned int leftover_mask;
1240 const char *plat = NULL;
1241 const char *extra = NULL;
1242 static struct {
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" },
1254 { 0, 0, NULL }
1256 #ifdef VER_SUITE_BACKOFFICE
1257 static struct {
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}" },
1272 { 0, NULL },
1274 #endif
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";
1286 else
1287 plat = "Windows 95";
1288 if (info.szCSDVersion[1] == 'B')
1289 extra = "OSR2 (B)";
1290 else if (info.szCSDVersion[1] == 'C')
1291 extra = "OSR2 (C)";
1292 } else {
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;
1297 break;
1301 if (plat && !strcmp(plat, "Windows 98")) {
1302 if (info.szCSDVersion[1] == 'A')
1303 extra = "SE (A)";
1304 else if (info.szCSDVersion[1] == 'B')
1305 extra = "SE (B)";
1307 if (plat) {
1308 if (!extra)
1309 extra = info.szCSDVersion;
1310 tor_snprintf(uname_result, sizeof(uname_result), "%s %s",
1311 plat, extra);
1312 } else {
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,
1318 info.szCSDVersion);
1319 else
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,
1323 info.szCSDVersion);
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);
1345 #endif
1346 #else
1347 strlcpy(uname_result, "Unknown platform", sizeof(uname_result));
1348 #endif
1350 uname_result_is_set = 1;
1352 return uname_result;
1356 * Process control
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 *);
1365 void *data;
1366 } tor_pthread_data_t;
1367 /** Given a tor_pthread_data_t <b>_data</b>, call _data-&gt;func(d-&gt;data)
1368 * and free _data. Used to make sure we can call functions the way pthread
1369 * expects. */
1370 static void *
1371 tor_pthread_helper_fn(void *_data)
1373 tor_pthread_data_t *data = _data;
1374 void (*func)(void*);
1375 void *arg;
1376 /* mask signals to worker threads to avoid SIGPIPE, etc */
1377 sigset_t sigs;
1378 /* We're in a subthread; don't handle any signals here. */
1379 sigfillset(&sigs);
1380 pthread_sigmask(SIG_SETMASK, &sigs, NULL);
1382 func = data->func;
1383 arg = data->data;
1384 tor_free(_data);
1385 func(arg);
1386 return NULL;
1388 #endif
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
1397 * running.
1400 spawn_func(void (*func)(void *), void *data)
1402 #if defined(USE_WIN32_THREADS)
1403 int rv;
1404 rv = (int)_beginthread(func, 0, data);
1405 if (rv == (int)-1)
1406 return -1;
1407 return 0;
1408 #elif defined(USE_PTHREADS)
1409 pthread_t thread;
1410 tor_pthread_data_t *d;
1411 d = tor_malloc(sizeof(tor_pthread_data_t));
1412 d->data = data;
1413 d->func = func;
1414 if (pthread_create(&thread,NULL,tor_pthread_helper_fn,d))
1415 return -1;
1416 if (pthread_detach(thread))
1417 return -1;
1418 return 0;
1419 #else
1420 pid_t pid;
1421 pid = fork();
1422 if (pid<0)
1423 return -1;
1424 if (pid==0) {
1425 /* Child */
1426 func(data);
1427 tor_assert(0); /* Should never reach here. */
1428 return 0; /* suppress "control-reaches-end-of-non-void" warning. */
1429 } else {
1430 /* Parent */
1431 return 0;
1433 #endif
1436 /** End the current thread/process.
1438 void
1439 spawn_exit(void)
1441 #if defined(USE_WIN32_THREADS)
1442 _endthread();
1443 //we should never get here. my compiler thinks that _endthread returns, this
1444 //is an attempt to fool it.
1445 tor_assert(0);
1446 _exit(0);
1447 #elif defined(USE_PTHREADS)
1448 pthread_exit(NULL);
1449 #else
1450 /* http://www.erlenstar.demon.co.uk/unix/faq_2.html says we should
1451 * call _exit, not exit, from child processes. */
1452 _exit(0);
1453 #endif
1457 /** Set *timeval to the current time of day. On error, log and terminate.
1458 * (Same as gettimeofday(timeval,NULL), but never returns -1.)
1460 void
1461 tor_gettimeofday(struct timeval *timeval)
1463 #ifdef MS_WINDOWS
1464 /* Epoch bias copied from perl: number of units between windows epoch and
1465 * unix epoch. */
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)
1470 union {
1471 uint64_t ft_64;
1472 FILETIME ft_ft;
1473 } ft;
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.");
1478 exit(1);
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),
1487 or segfaulted.*/
1488 exit(1);
1490 #elif defined(HAVE_FTIME)
1491 struct timeb tb;
1492 ftime(&tb);
1493 timeval->tv_sec = tb.time;
1494 timeval->tv_usec = tb.millitm * 1000;
1495 #else
1496 #error "No way to get time."
1497 #endif
1498 return;
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
1505 #endif
1507 #ifndef HAVE_LOCALTIME_R
1508 #ifdef TIME_FNS_NEED_LOCKS
1509 struct tm *
1510 tor_localtime_r(const time_t *timep, struct tm *result)
1512 struct tm *r;
1513 static tor_mutex_t *m=NULL;
1514 if (!m) { m=tor_mutex_new(); }
1515 tor_assert(result);
1516 tor_mutex_acquire(m);
1517 r = localtime(timep);
1518 memcpy(result, r, sizeof(struct tm));
1519 tor_mutex_release(m);
1520 return result;
1522 #else
1523 struct tm *
1524 tor_localtime_r(const time_t *timep, struct tm *result)
1526 struct tm *r;
1527 tor_assert(result);
1528 r = localtime(timep);
1529 memcpy(result, r, sizeof(struct tm));
1530 return result;
1532 #endif
1533 #endif
1535 #ifndef HAVE_GMTIME_R
1536 #ifdef TIME_FNS_NEED_LOCKS
1537 struct tm *
1538 tor_gmtime_r(const time_t *timep, struct tm *result)
1540 struct tm *r;
1541 static tor_mutex_t *m=NULL;
1542 if (!m) { m=tor_mutex_new(); }
1543 tor_assert(result);
1544 tor_mutex_acquire(m);
1545 r = gmtime(timep);
1546 memcpy(result, r, sizeof(struct tm));
1547 tor_mutex_release(m);
1548 return result;
1550 #else
1551 struct tm *
1552 tor_gmtime_r(const time_t *timep, struct tm *result)
1554 struct tm *r;
1555 tor_assert(result);
1556 r = gmtime(timep);
1557 memcpy(result, r, sizeof(struct tm));
1558 return result;
1560 #endif
1561 #endif
1563 #if defined(USE_WIN32_THREADS) && 0
1564 /** A generic lock structure for multithreaded builds. */
1565 struct tor_mutex_t {
1566 HANDLE handle;
1568 tor_mutex_t *
1569 tor_mutex_new(void)
1571 tor_mutex_t *m;
1572 m = tor_malloc_zero(sizeof(tor_mutex_t));
1573 m->handle = CreateMutex(NULL, FALSE, NULL);
1574 tor_assert(m->handle != NULL);
1575 return m;
1577 void
1578 tor_mutex_free(tor_mutex_t *m)
1580 CloseHandle(m->handle);
1581 tor_free(m);
1583 void
1584 tor_mutex_acquire(tor_mutex_t *m)
1586 DWORD r;
1587 r = WaitForSingleObject(m->handle, INFINITE);
1588 switch (r) {
1589 case WAIT_ABANDONED: /* holding thread exited. */
1590 case WAIT_OBJECT_0: /* we got the mutex normally. */
1591 break;
1592 case WAIT_TIMEOUT: /* Should never happen. */
1593 tor_assert(0);
1594 break;
1595 case WAIT_FAILED:
1596 log_warn(LD_GENERAL, "Failed to acquire mutex: %d",(int) GetLastError());
1599 void
1600 tor_mutex_release(tor_mutex_t *m)
1602 BOOL r;
1603 r = ReleaseMutex(m->handle);
1604 if (!r) {
1605 log_warn(LD_GENERAL, "Failed to release mutex: %d", (int) GetLastError());
1608 unsigned long
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;
1618 tor_mutex_t *
1619 tor_mutex_new(void)
1621 tor_mutex_t *m = tor_malloc_zero(sizeof(tor_mutex_t));
1622 InitializeCriticalSection(&m->mutex);
1623 return m;
1625 void
1626 tor_mutex_free(tor_mutex_t *m)
1628 DeleteCriticalSection(&m->mutex);
1629 tor_free(m);
1631 void
1632 tor_mutex_acquire(tor_mutex_t *m)
1634 tor_assert(m);
1635 EnterCriticalSection(&m->mutex);
1637 void
1638 tor_mutex_release(tor_mutex_t *m)
1640 LeaveCriticalSection(&m->mutex);
1642 unsigned long
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. */
1653 tor_mutex_t *
1654 tor_mutex_new(void)
1656 int err;
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();
1663 return mutex;
1665 /** Wait until <b>m</b> is free, then acquire it. */
1666 void
1667 tor_mutex_acquire(tor_mutex_t *m)
1669 int err;
1670 tor_assert(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. */
1678 void
1679 tor_mutex_release(tor_mutex_t *m)
1681 int err;
1682 tor_assert(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>. */
1690 void
1691 tor_mutex_free(tor_mutex_t *m)
1693 int err;
1694 tor_assert(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();
1700 tor_free(m);
1702 /** Return an integer representing this thread. */
1703 unsigned long
1704 tor_get_thread_id(void)
1706 union {
1707 pthread_t thr;
1708 unsigned long id;
1709 } r;
1710 r.thr = pthread_self();
1711 return r.id;
1713 #else
1714 /** A generic lock structure for multithreaded builds. */
1715 struct tor_mutex_t {
1716 int _unused;
1718 #endif
1720 /* Conditions. */
1721 #ifdef USE_PTHREADS
1722 #if 0
1723 /** Cross-platform condition implementation. */
1724 struct tor_cond_t {
1725 pthread_cond_t cond;
1727 /** Return a newly allocated condition, with nobody waiting on it. */
1728 tor_cond_t *
1729 tor_cond_new(void)
1731 tor_cond_t *cond = tor_malloc_zero(sizeof(tor_cond_t));
1732 if (pthread_cond_init(&cond->cond, NULL)) {
1733 tor_free(cond);
1734 return NULL;
1736 return cond;
1738 /** Release all resources held by <b>cond</b>. */
1739 void
1740 tor_cond_free(tor_cond_t *cond)
1742 tor_assert(cond);
1743 if (pthread_cond_destroy(&cond->cond)) {
1744 log_warn(LD_GENERAL,"Error freeing condition: %s", strerror(errno));
1745 return;
1747 tor_free(cond);
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>. */
1758 void
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>. */
1764 void
1765 tor_cond_signal_all(tor_cond_t *cond)
1767 pthread_cond_broadcast(&cond->cond);
1769 #endif
1770 /** Set up common structures for use by threading. */
1771 void
1772 tor_threads_init(void)
1775 #elif defined(USE_WIN32_THREADS)
1776 #if 0
1777 static DWORD cond_event_tls_index;
1778 struct tor_cond_t {
1779 CRITICAL_SECTION mutex;
1780 smartlist_t *events;
1782 tor_cond_t *
1783 tor_cond_new(void)
1785 tor_cond_t *cond = tor_malloc_zero(sizeof(tor_cond_t));
1786 InitializeCriticalSection(&cond->mutex);
1787 cond->events = smartlist_create();
1788 return cond;
1790 void
1791 tor_cond_free(tor_cond_t *cond)
1793 tor_assert(cond);
1794 DeleteCriticalSection(&cond->mutex);
1795 /* XXXX notify? */
1796 smartlist_free(cond->events);
1797 tor_free(cond);
1800 tor_cond_wait(tor_cond_t *cond, tor_mutex_t *mutex)
1802 HANDLE event;
1803 int r;
1804 tor_assert(cond);
1805 tor_assert(mutex);
1806 event = TlsGetValue(cond_event_tls_index);
1807 if (!event) {
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);
1823 switch (r) {
1824 case WAIT_OBJECT_0: /* we got the mutex normally. */
1825 break;
1826 case WAIT_ABANDONED: /* holding thread exited. */
1827 case WAIT_TIMEOUT: /* Should never happen. */
1828 tor_assert(0);
1829 break;
1830 case WAIT_FAILED:
1831 log_warn(LD_GENERAL, "Failed to acquire mutex: %d",(int) GetLastError());
1833 return 0;
1835 void
1836 tor_cond_signal_one(tor_cond_t *cond)
1838 HANDLE event;
1839 tor_assert(cond);
1841 EnterCriticalSection(&cond->mutex);
1843 if ((event = smartlist_pop_last(cond->events)))
1844 SetEvent(event);
1846 LeaveCriticalSection(&cond->mutex);
1848 void
1849 tor_cond_signal_all(tor_cond_t *cond)
1851 tor_assert(cond);
1853 EnterCriticalSection(&cond->mutex);
1854 SMARTLIST_FOREACH(cond->events, HANDLE, event, SetEvent(event));
1855 smartlist_clear(cond->events);
1856 LeaveCriticalSection(&cond->mutex);
1858 #endif
1859 void
1860 tor_threads_init(void)
1862 #if 0
1863 cond_event_tls_index = TlsAlloc();
1864 #endif
1866 #endif
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
1873 * WSAEWOULDBLOCKs.)
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))
1887 return err;
1888 if (optval)
1889 return optval;
1891 return err;
1893 #endif
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"),
1940 #endif
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.
1954 { -1, NULL },
1956 /** There does not seem to be a strerror equivalent for winsock errors.
1957 * Naturally, we have to roll our own.
1959 const char *
1960 tor_socket_strerror(int e)
1962 int i;
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;
1967 return strerror(e);
1969 #endif
1971 /** Called before we make any calls to network-related functions.
1972 * (Some operating systems require their network libraries to be
1973 * initialized.) */
1975 network_init(void)
1977 #ifdef MS_WINDOWS
1978 /* This silly exercise is necessary before windows will allow
1979 * gethostbyname to work. */
1980 WSADATA WSAData;
1981 int r;
1982 r = WSAStartup(0x101,&WSAData);
1983 if (r) {
1984 log_warn(LD_NET,"Error initializing windows network layer: code was %d",r);
1985 return -1;
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. */
1990 #endif
1991 return 0;
1994 #ifdef MS_WINDOWS
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. */
1999 char *
2000 format_win32_error(DWORD err)
2002 LPVOID str = NULL;
2003 char *result;
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,
2009 NULL, err,
2010 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
2011 (LPTSTR) &str,
2012 0, NULL);
2014 if (str) {
2015 result = tor_strdup((char*)str);
2016 LocalFree(str); /* LocalFree != free() */
2017 } else {
2018 result = tor_strdup("<unformattable error>");
2020 return result;
2022 #endif