Use a mutex to protect the count of open sockets.
[tor/rransom.git] / src / common / compat.c
blob51794c762c871e3d712c4664a56e7696dd58e8b5
1 /* Copyright (c) 2003-2004, Roger Dingledine
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2009, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
6 /**
7 * \file compat.c
8 * \brief Wrappers to make calls more portable. This code defines
9 * functions such as tor_malloc, tor_snprintf, get/set various data types,
10 * renaming, setting socket options, switching user IDs. It is basically
11 * where the non-portable items are conditionally included depending on
12 * the platform.
13 **/
15 /* This is required on rh7 to make strptime not complain.
16 * We also need it to make memmem get defined (where available)
18 #define _GNU_SOURCE
20 #include "compat.h"
22 #ifdef MS_WINDOWS
23 #include <process.h>
24 #include <windows.h>
25 #include <sys/locking.h>
26 #endif
28 #ifdef HAVE_UNAME
29 #include <sys/utsname.h>
30 #endif
31 #ifdef HAVE_UNISTD_H
32 #include <unistd.h>
33 #endif
34 #ifdef HAVE_SYS_FCNTL_H
35 #include <sys/fcntl.h>
36 #endif
37 #ifdef HAVE_PWD_H
38 #include <pwd.h>
39 #endif
40 #ifdef HAVE_GRP_H
41 #include <grp.h>
42 #endif
43 #ifdef HAVE_FCNTL_H
44 #include <fcntl.h>
45 #endif
46 #ifdef HAVE_ERRNO_H
47 #include <errno.h>
48 #endif
49 #ifdef HAVE_ARPA_INET_H
50 #include <arpa/inet.h>
51 #endif
53 #ifndef HAVE_GETTIMEOFDAY
54 #ifdef HAVE_FTIME
55 #include <sys/timeb.h>
56 #endif
57 #endif
59 #ifdef HAVE_NETDB_H
60 #include <netdb.h>
61 #endif
62 #ifdef HAVE_SYS_PARAM_H
63 #include <sys/param.h> /* FreeBSD needs this to know what version it is */
64 #endif
65 #include <stdio.h>
66 #include <stdlib.h>
67 #include <assert.h>
68 #ifdef HAVE_SIGNAL_H
69 #include <signal.h>
70 #endif
71 #ifdef HAVE_UTIME_H
72 #include <utime.h>
73 #endif
74 #ifdef HAVE_SYS_UTIME_H
75 #include <sys/utime.h>
76 #endif
77 #ifdef HAVE_SYS_MMAN_H
78 #include <sys/mman.h>
79 #endif
80 #ifdef HAVE_SYS_SYSLIMITS_H
81 #include <sys/syslimits.h>
82 #endif
83 #ifdef HAVE_SYS_FILE_H
84 #include <sys/file.h>
85 #endif
86 #if defined(HAVE_SYS_PRCTL_H) && defined(__linux__)
87 /* Only use the linux prctl; the IRIX prctl is totally different */
88 #include <sys/prctl.h>
89 #endif
91 #include "log.h"
92 #include "util.h"
93 #include "container.h"
94 #include "address.h"
96 /* Inline the strl functions if the platform doesn't have them. */
97 #ifndef HAVE_STRLCPY
98 #include "strlcpy.c"
99 #endif
100 #ifndef HAVE_STRLCAT
101 #include "strlcat.c"
102 #endif
104 #ifdef HAVE_SYS_MMAN_H
105 /** Try to create a memory mapping for <b>filename</b> and return it. On
106 * failure, return NULL. Sets errno properly, using ERANGE to mean
107 * "empty file". */
108 tor_mmap_t *
109 tor_mmap_file(const char *filename)
111 int fd; /* router file */
112 char *string;
113 int page_size;
114 tor_mmap_t *res;
115 size_t size, filesize;
117 tor_assert(filename);
119 fd = open(filename, O_RDONLY, 0);
120 if (fd<0) {
121 int save_errno = errno;
122 int severity = (errno == ENOENT) ? LOG_INFO : LOG_WARN;
123 log_fn(severity, LD_FS,"Could not open \"%s\" for mmap(): %s",filename,
124 strerror(errno));
125 errno = save_errno;
126 return NULL;
129 size = filesize = (size_t) lseek(fd, 0, SEEK_END);
130 lseek(fd, 0, SEEK_SET);
131 /* ensure page alignment */
132 page_size = getpagesize();
133 size += (size%page_size) ? page_size-(size%page_size) : 0;
135 if (!size) {
136 /* Zero-length file. If we call mmap on it, it will succeed but
137 * return NULL, and bad things will happen. So just fail. */
138 log_info(LD_FS,"File \"%s\" is empty. Ignoring.",filename);
139 errno = ERANGE;
140 close(fd);
141 return NULL;
144 string = mmap(0, size, PROT_READ, MAP_PRIVATE, fd, 0);
145 close(fd);
146 if (string == MAP_FAILED) {
147 int save_errno = errno;
148 log_warn(LD_FS,"Could not mmap file \"%s\": %s", filename,
149 strerror(errno));
150 errno = save_errno;
151 return NULL;
154 res = tor_malloc_zero(sizeof(tor_mmap_t));
155 res->data = string;
156 res->size = filesize;
157 res->mapping_size = size;
159 return res;
161 /** Release storage held for a memory mapping. */
162 void
163 tor_munmap_file(tor_mmap_t *handle)
165 munmap((char*)handle->data, handle->mapping_size);
166 tor_free(handle);
168 #elif defined(MS_WINDOWS)
169 tor_mmap_t *
170 tor_mmap_file(const char *filename)
172 tor_mmap_t *res = tor_malloc_zero(sizeof(tor_mmap_t));
173 int empty = 0;
174 res->file_handle = INVALID_HANDLE_VALUE;
175 res->mmap_handle = NULL;
177 res->file_handle = CreateFile(filename,
178 GENERIC_READ, FILE_SHARE_READ,
179 NULL,
180 OPEN_EXISTING,
181 FILE_ATTRIBUTE_NORMAL,
184 if (res->file_handle == INVALID_HANDLE_VALUE)
185 goto win_err;
187 res->size = GetFileSize(res->file_handle, NULL);
189 if (res->size == 0) {
190 log_info(LD_FS,"File \"%s\" is empty. Ignoring.",filename);
191 empty = 1;
192 goto err;
195 res->mmap_handle = CreateFileMapping(res->file_handle,
196 NULL,
197 PAGE_READONLY,
198 #if SIZEOF_SIZE_T > 4
199 (res->base.size >> 32),
200 #else
202 #endif
203 (res->size & 0xfffffffful),
204 NULL);
205 if (res->mmap_handle == NULL)
206 goto win_err;
207 res->data = (char*) MapViewOfFile(res->mmap_handle,
208 FILE_MAP_READ,
209 0, 0, 0);
210 if (!res->data)
211 goto win_err;
213 return res;
214 win_err: {
215 DWORD e = GetLastError();
216 int severity = (e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND) ?
217 LOG_INFO : LOG_WARN;
218 char *msg = format_win32_error(e);
219 log_fn(severity, LD_FS, "Couldn't mmap file \"%s\": %s", filename, msg);
220 tor_free(msg);
221 if (e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND)
222 errno = ENOENT;
223 else
224 errno = EINVAL;
226 err:
227 if (empty)
228 errno = ERANGE;
229 tor_munmap_file(res);
230 return NULL;
232 void
233 tor_munmap_file(tor_mmap_t *handle)
235 if (handle->data)
236 /* This is an ugly cast, but without it, "data" in struct tor_mmap_t would
237 have to be redefined as non-const. */
238 UnmapViewOfFile( (LPVOID) handle->data);
240 if (handle->mmap_handle != NULL)
241 CloseHandle(handle->mmap_handle);
242 if (handle->file_handle != INVALID_HANDLE_VALUE)
243 CloseHandle(handle->file_handle);
244 tor_free(handle);
246 #else
247 tor_mmap_t *
248 tor_mmap_file(const char *filename)
250 struct stat st;
251 char *res = read_file_to_str(filename, RFTS_BIN|RFTS_IGNORE_MISSING, &st);
252 tor_mmap_t *handle;
253 if (! res)
254 return NULL;
255 handle = tor_malloc_zero(sizeof(tor_mmap_t));
256 handle->data = res;
257 handle->size = st.st_size;
258 return handle;
260 void
261 tor_munmap_file(tor_mmap_t *handle)
263 char *d = (char*)handle->data;
264 tor_free(d);
265 memset(handle, 0, sizeof(tor_mmap_t));
266 tor_free(handle);
268 #endif
270 /** Replacement for snprintf. Differs from platform snprintf in two
271 * ways: First, always NUL-terminates its output. Second, always
272 * returns -1 if the result is truncated. (Note that this return
273 * behavior does <i>not</i> conform to C99; it just happens to be
274 * easier to emulate "return -1" with conformant implementations than
275 * it is to emulate "return number that would be written" with
276 * non-conformant implementations.) */
278 tor_snprintf(char *str, size_t size, const char *format, ...)
280 va_list ap;
281 int r;
282 va_start(ap,format);
283 r = tor_vsnprintf(str,size,format,ap);
284 va_end(ap);
285 return r;
288 /** Replacement for vsnprintf; behavior differs as tor_snprintf differs from
289 * snprintf.
292 tor_vsnprintf(char *str, size_t size, const char *format, va_list args)
294 int r;
295 if (size == 0)
296 return -1; /* no place for the NUL */
297 if (size > SSIZE_T_MAX-16)
298 return -1;
299 #ifdef MS_WINDOWS
300 r = _vsnprintf(str, size, format, args);
301 #else
302 r = vsnprintf(str, size, format, args);
303 #endif
304 str[size-1] = '\0';
305 if (r < 0 || r >= (ssize_t)size)
306 return -1;
307 return r;
310 /** Given <b>hlen</b> bytes at <b>haystack</b> and <b>nlen</b> bytes at
311 * <b>needle</b>, return a pointer to the first occurrence of the needle
312 * within the haystack, or NULL if there is no such occurrence.
314 * Requires that nlen be greater than zero.
316 const void *
317 tor_memmem(const void *_haystack, size_t hlen,
318 const void *_needle, size_t nlen)
320 #if defined(HAVE_MEMMEM) && (!defined(__GNUC__) || __GNUC__ >= 2)
321 tor_assert(nlen);
322 return memmem(_haystack, hlen, _needle, nlen);
323 #else
324 /* This isn't as fast as the GLIBC implementation, but it doesn't need to
325 * be. */
326 const char *p, *end;
327 const char *haystack = (const char*)_haystack;
328 const char *needle = (const char*)_needle;
329 char first;
330 tor_assert(nlen);
332 p = haystack;
333 end = haystack + hlen;
334 first = *(const char*)needle;
335 while ((p = memchr(p, first, end-p))) {
336 if (p+nlen > end)
337 return NULL;
338 if (!memcmp(p, needle, nlen))
339 return p;
340 ++p;
342 return NULL;
343 #endif
346 /* Tables to implement ctypes-replacement TOR_IS*() functions. Each table
347 * has 256 bits to look up whether a character is in some set or not. This
348 * fails on non-ASCII platforms, but it is hard to find a platform whose
349 * character set is not a superset of ASCII nowadays. */
350 const uint32_t TOR_ISALPHA_TABLE[8] =
351 { 0, 0, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
352 const uint32_t TOR_ISALNUM_TABLE[8] =
353 { 0, 0x3ff0000, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
354 const uint32_t TOR_ISSPACE_TABLE[8] = { 0x3e00, 0x1, 0, 0, 0, 0, 0, 0 };
355 const uint32_t TOR_ISXDIGIT_TABLE[8] =
356 { 0, 0x3ff0000, 0x7e, 0x7e, 0, 0, 0, 0 };
357 const uint32_t TOR_ISDIGIT_TABLE[8] = { 0, 0x3ff0000, 0, 0, 0, 0, 0, 0 };
358 const uint32_t TOR_ISPRINT_TABLE[8] =
359 { 0, 0xffffffff, 0xffffffff, 0x7fffffff, 0, 0, 0, 0x0 };
360 const uint32_t TOR_ISUPPER_TABLE[8] = { 0, 0, 0x7fffffe, 0, 0, 0, 0, 0 };
361 const uint32_t TOR_ISLOWER_TABLE[8] = { 0, 0, 0, 0x7fffffe, 0, 0, 0, 0 };
362 /* Upper-casing and lowercasing tables to map characters to upper/lowercase
363 * equivalents. */
364 const char TOR_TOUPPER_TABLE[256] = {
365 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
366 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
367 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
368 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
369 64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
370 80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
371 96,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
372 80,81,82,83,84,85,86,87,88,89,90,123,124,125,126,127,
373 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
374 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
375 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
376 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
377 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
378 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
379 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
380 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
382 const char TOR_TOLOWER_TABLE[256] = {
383 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
384 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
385 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
386 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
387 64,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
388 112,113,114,115,116,117,118,119,120,121,122,91,92,93,94,95,
389 96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
390 112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
391 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
392 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
393 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
394 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
395 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
396 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
397 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
398 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
401 #ifdef MS_WINDOWS
402 /** Take a filename and return a pointer to its final element. This
403 * function is called on __FILE__ to fix a MSVC nit where __FILE__
404 * contains the full path to the file. This is bad, because it
405 * confuses users to find the home directory of the person who
406 * compiled the binary in their warrning messages.
408 const char *
409 tor_fix_source_file(const char *fname)
411 const char *cp1, *cp2, *r;
412 cp1 = strrchr(fname, '/');
413 cp2 = strrchr(fname, '\\');
414 if (cp1 && cp2) {
415 r = (cp1<cp2)?(cp2+1):(cp1+1);
416 } else if (cp1) {
417 r = cp1+1;
418 } else if (cp2) {
419 r = cp2+1;
420 } else {
421 r = fname;
423 return r;
425 #endif
428 * Read a 16-bit value beginning at <b>cp</b>. Equivalent to
429 * *(uint16_t*)(cp), but will not cause segfaults on platforms that forbid
430 * unaligned memory access.
432 uint16_t
433 get_uint16(const char *cp)
435 uint16_t v;
436 memcpy(&v,cp,2);
437 return v;
440 * Read a 32-bit value beginning at <b>cp</b>. Equivalent to
441 * *(uint32_t*)(cp), but will not cause segfaults on platforms that forbid
442 * unaligned memory access.
444 uint32_t
445 get_uint32(const char *cp)
447 uint32_t v;
448 memcpy(&v,cp,4);
449 return v;
452 * Read a 32-bit value beginning at <b>cp</b>. Equivalent to
453 * *(uint32_t*)(cp), but will not cause segfaults on platforms that forbid
454 * unaligned memory access.
456 uint64_t
457 get_uint64(const char *cp)
459 uint64_t v;
460 memcpy(&v,cp,8);
461 return v;
465 * Set a 16-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
466 * *(uint16_t*)(cp) = v, but will not cause segfaults on platforms that forbid
467 * unaligned memory access. */
468 void
469 set_uint16(char *cp, uint16_t v)
471 memcpy(cp,&v,2);
474 * Set a 32-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
475 * *(uint32_t*)(cp) = v, but will not cause segfaults on platforms that forbid
476 * unaligned memory access. */
477 void
478 set_uint32(char *cp, uint32_t v)
480 memcpy(cp,&v,4);
483 * Set a 64-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
484 * *(uint64_t*)(cp) = v, but will not cause segfaults on platforms that forbid
485 * unaligned memory access. */
486 void
487 set_uint64(char *cp, uint64_t v)
489 memcpy(cp,&v,8);
493 * Rename the file <b>from</b> to the file <b>to</b>. On unix, this is
494 * the same as rename(2). On windows, this removes <b>to</b> first if
495 * it already exists.
496 * Returns 0 on success. Returns -1 and sets errno on failure.
499 replace_file(const char *from, const char *to)
501 #ifndef MS_WINDOWS
502 return rename(from,to);
503 #else
504 switch (file_status(to))
506 case FN_NOENT:
507 break;
508 case FN_FILE:
509 if (unlink(to)) return -1;
510 break;
511 case FN_ERROR:
512 return -1;
513 case FN_DIR:
514 errno = EISDIR;
515 return -1;
517 return rename(from,to);
518 #endif
521 /** Change <b>fname</b>'s modification time to now. */
523 touch_file(const char *fname)
525 if (utime(fname, NULL)!=0)
526 return -1;
527 return 0;
530 /** Represents a lockfile on which we hold the lock. */
531 struct tor_lockfile_t {
532 char *filename;
533 int fd;
536 /** Try to get a lock on the lockfile <b>filename</b>, creating it as
537 * necessary. If someone else has the lock and <b>blocking</b> is true,
538 * wait until the lock is available. Otherwise return immediately whether
539 * we succeeded or not.
541 * Set *<b>locked_out</b> to true if somebody else had the lock, and to false
542 * otherwise.
544 * Return a <b>tor_lockfile_t</b> on success, NULL on failure.
546 * (Implementation note: because we need to fall back to fcntl on some
547 * platforms, these locks are per-process, not per-thread. If you want
548 * to do in-process locking, use tor_mutex_t like a normal person.)
550 tor_lockfile_t *
551 tor_lockfile_lock(const char *filename, int blocking, int *locked_out)
553 tor_lockfile_t *result;
554 int fd;
555 *locked_out = 0;
557 log_info(LD_FS, "Locking \"%s\"", filename);
558 fd = open(filename, O_RDWR|O_CREAT|O_TRUNC, 0600);
559 if (fd < 0) {
560 log_warn(LD_FS,"Couldn't open \"%s\" for locking: %s", filename,
561 strerror(errno));
562 return NULL;
565 #ifdef WIN32
566 _lseek(fd, 0, SEEK_SET);
567 if (_locking(fd, blocking ? _LK_LOCK : _LK_NBLCK, 1) < 0) {
568 if (errno != EDEADLOCK)
569 log_warn(LD_FS,"Couldn't lock \"%s\": %s", filename, strerror(errno));
570 else
571 *locked_out = 1;
572 close(fd);
573 return NULL;
575 #elif defined(HAVE_FLOCK)
576 if (flock(fd, LOCK_EX|(blocking ? 0 : LOCK_NB)) < 0) {
577 if (errno != EWOULDBLOCK)
578 log_warn(LD_FS,"Couldn't lock \"%s\": %s", filename, strerror(errno));
579 else
580 *locked_out = 1;
581 close(fd);
582 return NULL;
584 #else
586 struct flock lock;
587 memset(&lock, 0, sizeof(lock));
588 lock.l_type = F_WRLCK;
589 lock.l_whence = SEEK_SET;
590 if (fcntl(fd, blocking ? F_SETLKW : F_SETLK, &lock) < 0) {
591 if (errno != EACCES && errno != EAGAIN)
592 log_warn(LD_FS, "Couldn't lock \"%s\": %s", filename, strerror(errno));
593 else
594 *locked_out = 1;
595 close(fd);
596 return NULL;
599 #endif
601 result = tor_malloc(sizeof(tor_lockfile_t));
602 result->filename = tor_strdup(filename);
603 result->fd = fd;
604 return result;
607 /** Release the lock held as <b>lockfile</b>. */
608 void
609 tor_lockfile_unlock(tor_lockfile_t *lockfile)
611 tor_assert(lockfile);
613 log_info(LD_FS, "Unlocking \"%s\"", lockfile->filename);
614 #ifdef WIN32
615 _lseek(lockfile->fd, 0, SEEK_SET);
616 if (_locking(lockfile->fd, _LK_UNLCK, 1) < 0) {
617 log_warn(LD_FS,"Error unlocking \"%s\": %s", lockfile->filename,
618 strerror(errno));
620 #elif defined(HAVE_FLOCK)
621 if (flock(lockfile->fd, LOCK_UN) < 0) {
622 log_warn(LD_FS, "Error unlocking \"%s\": %s", lockfile->filename,
623 strerror(errno));
625 #else
626 /* Closing the lockfile is sufficient. */
627 #endif
629 close(lockfile->fd);
630 lockfile->fd = -1;
631 tor_free(lockfile->filename);
632 tor_free(lockfile);
635 /* Some old versions of unix didn't define constants for these values,
636 * and instead expect you to say 0, 1, or 2. */
637 #ifndef SEEK_CUR
638 #define SEEK_CUR 1
639 #endif
640 #ifndef SEEK_END
641 #define SEEK_END 2
642 #endif
644 /** Return the position of <b>fd</b> with respect to the start of the file. */
645 off_t
646 tor_fd_getpos(int fd)
648 #ifdef WIN32
649 return (off_t) _lseek(fd, 0, SEEK_CUR);
650 #else
651 return (off_t) lseek(fd, 0, SEEK_CUR);
652 #endif
655 /** Move <b>fd</b> to the end of the file. Return -1 on error, 0 on success. */
657 tor_fd_seekend(int fd)
659 #ifdef WIN32
660 return _lseek(fd, 0, SEEK_END) < 0 ? -1 : 0;
661 #else
662 return lseek(fd, 0, SEEK_END) < 0 ? -1 : 0;
663 #endif
666 #undef DEBUG_SOCKET_COUNTING
667 #ifdef DEBUG_SOCKET_COUNTING
668 /** A bitarray of all fds that should be passed to tor_socket_close(). Only
669 * used if DEBUG_SOCKET_COUNTING is defined. */
670 static bitarray_t *open_sockets = NULL;
671 /** The size of <b>open_sockets</b>, in bits. */
672 static int max_socket = -1;
673 #endif
675 /** Count of number of sockets currently open. (Undercounts sockets opened by
676 * eventdns and libevent.) */
677 static int n_sockets_open = 0;
679 /** Mutex to protect open_sockets, max_socket, and n_sockets_open. */
680 static tor_mutex_t *socket_accounting_mutex = NULL;
682 static INLINE void
683 socket_accounting_lock(void)
685 if (PREDICT_UNLIKELY(!socket_accounting_mutex))
686 socket_accounting_mutex = tor_mutex_new();
687 tor_mutex_acquire(socket_accounting_mutex);
690 static INLINE void
691 socket_accounting_unlock(void)
693 tor_mutex_release(socket_accounting_mutex);
696 /** As close(), but guaranteed to work for sockets across platforms (including
697 * Windows, where close()ing a socket doesn't work. Returns 0 on success, -1
698 * on failure. */
700 tor_close_socket(int s)
702 int r = 0;
704 /* On Windows, you have to call close() on fds returned by open(),
705 * and closesocket() on fds returned by socket(). On Unix, everything
706 * gets close()'d. We abstract this difference by always using
707 * tor_close_socket to close sockets, and always using close() on
708 * files.
710 #if defined(MS_WINDOWS)
711 r = closesocket(s);
712 #else
713 r = close(s);
714 #endif
716 socket_accounting_lock();
717 #ifdef DEBUG_SOCKET_COUNTING
718 if (s > max_socket || ! bitarray_is_set(open_sockets, s)) {
719 log_warn(LD_BUG, "Closing a socket (%d) that wasn't returned by tor_open_"
720 "socket(), or that was already closed or something.", s);
721 } else {
722 tor_assert(open_sockets && s <= max_socket);
723 bitarray_clear(open_sockets, s);
725 #endif
726 if (r == 0) {
727 --n_sockets_open;
728 } else {
729 int err = tor_socket_errno(-1);
730 log_info(LD_NET, "Close returned an error: %s", tor_socket_strerror(err));
731 #ifdef WIN32
732 if (err != WSAENOTSOCK)
733 --n_sockets_open;
734 #else
735 if (err != EBADF)
736 --n_sockets_open;
737 #endif
738 r = -1;
741 if (n_sockets_open < 0)
742 log_warn(LD_BUG, "Our socket count is below zero: %d. Please submit a "
743 "bug report.", n_sockets_open);
744 socket_accounting_unlock();
745 return r;
748 #ifdef DEBUG_SOCKET_COUNTING
749 /** Helper: if DEBUG_SOCKET_COUNTING is enabled, remember that <b>s</b> is
750 * now an open socket. */
751 static INLINE void
752 mark_socket_open(int s)
754 if (s > max_socket) {
755 if (max_socket == -1) {
756 open_sockets = bitarray_init_zero(s+128);
757 max_socket = s+128;
758 } else {
759 open_sockets = bitarray_expand(open_sockets, max_socket, s+128);
760 max_socket = s+128;
763 if (bitarray_is_set(open_sockets, s)) {
764 log_warn(LD_BUG, "I thought that %d was already open, but socket() just "
765 "gave it to me!", s);
767 bitarray_set(open_sockets, s);
769 #else
770 #define mark_socket_open(s) STMT_NIL
771 #endif
773 /** As socket(), but counts the number of open sockets. */
775 tor_open_socket(int domain, int type, int protocol)
777 int s = socket(domain, type, protocol);
778 if (s >= 0) {
779 socket_accounting_lock();
780 ++n_sockets_open;
781 mark_socket_open(s);
782 socket_accounting_unlock();
784 return s;
787 /** As socket(), but counts the number of open sockets. */
789 tor_accept_socket(int sockfd, struct sockaddr *addr, socklen_t *len)
791 int s = accept(sockfd, addr, len);
792 if (s >= 0) {
793 socket_accounting_lock();
794 ++n_sockets_open;
795 mark_socket_open(s);
796 socket_accounting_unlock();
798 return s;
801 /** Return the number of sockets we currently have opened. */
803 get_n_open_sockets(void)
805 int n;
806 socket_accounting_lock();
807 n = n_sockets_open;
808 socket_accounting_unlock();
809 return n;
812 /** Turn <b>socket</b> into a nonblocking socket.
814 void
815 set_socket_nonblocking(int socket)
817 #if defined(MS_WINDOWS)
818 unsigned long nonblocking = 1;
819 ioctlsocket(socket, FIONBIO, (unsigned long*) &nonblocking);
820 #else
821 fcntl(socket, F_SETFL, O_NONBLOCK);
822 #endif
826 * Allocate a pair of connected sockets. (Like socketpair(family,
827 * type,protocol,fd), but works on systems that don't have
828 * socketpair.)
830 * Currently, only (AF_UNIX, SOCK_STREAM, 0) sockets are supported.
832 * Note that on systems without socketpair, this call will fail if
833 * localhost is inaccessible (for example, if the networking
834 * stack is down). And even if it succeeds, the socket pair will not
835 * be able to read while localhost is down later (the socket pair may
836 * even close, depending on OS-specific timeouts).
838 * Returns 0 on success and -errno on failure; do not rely on the value
839 * of errno or WSAGetLastError().
841 /* It would be nicer just to set errno, but that won't work for windows. */
843 tor_socketpair(int family, int type, int protocol, int fd[2])
845 //don't use win32 socketpairs (they are always bad)
846 #if defined(HAVE_SOCKETPAIR) && !defined(MS_WINDOWS)
847 int r;
848 r = socketpair(family, type, protocol, fd);
849 if (r == 0) {
850 socket_accounting_lock();
851 if (fd[0] >= 0) {
852 ++n_sockets_open;
853 mark_socket_open(fd[0]);
855 if (fd[1] >= 0) {
856 ++n_sockets_open;
857 mark_socket_open(fd[1]);
859 socket_accounting_unlock();
861 return r < 0 ? -errno : r;
862 #else
863 /* This socketpair does not work when localhost is down. So
864 * it's really not the same thing at all. But it's close enough
865 * for now, and really, when localhost is down sometimes, we
866 * have other problems too.
868 int listener = -1;
869 int connector = -1;
870 int acceptor = -1;
871 struct sockaddr_in listen_addr;
872 struct sockaddr_in connect_addr;
873 int size;
874 int saved_errno = -1;
876 if (protocol
877 #ifdef AF_UNIX
878 || family != AF_UNIX
879 #endif
881 #ifdef MS_WINDOWS
882 return -WSAEAFNOSUPPORT;
883 #else
884 return -EAFNOSUPPORT;
885 #endif
887 if (!fd) {
888 return -EINVAL;
891 listener = tor_open_socket(AF_INET, type, 0);
892 if (listener < 0)
893 return -tor_socket_errno(-1);
894 memset(&listen_addr, 0, sizeof(listen_addr));
895 listen_addr.sin_family = AF_INET;
896 listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
897 listen_addr.sin_port = 0; /* kernel chooses port. */
898 if (bind(listener, (struct sockaddr *) &listen_addr, sizeof (listen_addr))
899 == -1)
900 goto tidy_up_and_fail;
901 if (listen(listener, 1) == -1)
902 goto tidy_up_and_fail;
904 connector = tor_open_socket(AF_INET, type, 0);
905 if (connector < 0)
906 goto tidy_up_and_fail;
907 /* We want to find out the port number to connect to. */
908 size = sizeof(connect_addr);
909 if (getsockname(listener, (struct sockaddr *) &connect_addr, &size) == -1)
910 goto tidy_up_and_fail;
911 if (size != sizeof (connect_addr))
912 goto abort_tidy_up_and_fail;
913 if (connect(connector, (struct sockaddr *) &connect_addr,
914 sizeof(connect_addr)) == -1)
915 goto tidy_up_and_fail;
917 size = sizeof(listen_addr);
918 acceptor = tor_accept_socket(listener,
919 (struct sockaddr *) &listen_addr, &size);
920 if (acceptor < 0)
921 goto tidy_up_and_fail;
922 if (size != sizeof(listen_addr))
923 goto abort_tidy_up_and_fail;
924 tor_close_socket(listener);
925 /* Now check we are talking to ourself by matching port and host on the
926 two sockets. */
927 if (getsockname(connector, (struct sockaddr *) &connect_addr, &size) == -1)
928 goto tidy_up_and_fail;
929 if (size != sizeof (connect_addr)
930 || listen_addr.sin_family != connect_addr.sin_family
931 || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
932 || listen_addr.sin_port != connect_addr.sin_port) {
933 goto abort_tidy_up_and_fail;
935 fd[0] = connector;
936 fd[1] = acceptor;
938 return 0;
940 abort_tidy_up_and_fail:
941 #ifdef MS_WINDOWS
942 saved_errno = WSAECONNABORTED;
943 #else
944 saved_errno = ECONNABORTED; /* I hope this is portable and appropriate. */
945 #endif
946 tidy_up_and_fail:
947 if (saved_errno < 0)
948 saved_errno = errno;
949 if (listener != -1)
950 tor_close_socket(listener);
951 if (connector != -1)
952 tor_close_socket(connector);
953 if (acceptor != -1)
954 tor_close_socket(acceptor);
955 return -saved_errno;
956 #endif
959 #define ULIMIT_BUFFER 32 /* keep 32 extra fd's beyond _ConnLimit */
961 /** Learn the maximum allowed number of file descriptors. (Some systems
962 * have a low soft limit.
964 * We compute this by finding the largest number that we can use.
965 * If we can't find a number greater than or equal to <b>limit</b>,
966 * then we fail: return -1.
968 * Otherwise, return 0 and store the maximum we found inside <b>max_out</b>.*/
970 set_max_file_descriptors(rlim_t limit, int *max_out)
972 /* Define some maximum connections values for systems where we cannot
973 * automatically determine a limit. Re Cygwin, see
974 * http://archives.seul.org/or/talk/Aug-2006/msg00210.html
975 * For an iPhone, 9999 should work. For Windows and all other unknown
976 * systems we use 15000 as the default. */
977 #ifndef HAVE_GETRLIMIT
978 #if defined(CYGWIN) || defined(__CYGWIN__)
979 const char *platform = "Cygwin";
980 const unsigned long MAX_CONNECTIONS = 3200;
981 #elif defined(IPHONE)
982 const char *platform = "iPhone";
983 const unsigned long MAX_CONNECTIONS = 9999;
984 #elif defined(MS_WINDOWS)
985 const char *platform = "Windows";
986 const unsigned long MAX_CONNECTIONS = 15000;
987 #else
988 const char *platform = "unknown platforms with no getrlimit()";
989 const unsigned long MAX_CONNECTIONS = 15000;
990 #endif
991 log_fn(LOG_INFO, LD_NET,
992 "This platform is missing getrlimit(). Proceeding.");
993 if (limit > MAX_CONNECTIONS) {
994 log_warn(LD_CONFIG,
995 "We do not support more than %lu file descriptors "
996 "on %s. Tried to raise to %lu.",
997 (unsigned long)MAX_CONNECTIONS, platform, (unsigned long)limit);
998 return -1;
1000 limit = MAX_CONNECTIONS;
1001 #else /* HAVE_GETRLIMIT */
1002 struct rlimit rlim;
1003 tor_assert(limit > 0);
1005 if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) {
1006 log_warn(LD_NET, "Could not get maximum number of file descriptors: %s",
1007 strerror(errno));
1008 return -1;
1011 if (rlim.rlim_max < limit) {
1012 log_warn(LD_CONFIG,"We need %lu file descriptors available, and we're "
1013 "limited to %lu. Please change your ulimit -n.",
1014 (unsigned long)limit, (unsigned long)rlim.rlim_max);
1015 return -1;
1018 if (rlim.rlim_max > rlim.rlim_cur) {
1019 log_info(LD_NET,"Raising max file descriptors from %lu to %lu.",
1020 (unsigned long)rlim.rlim_cur, (unsigned long)rlim.rlim_max);
1022 rlim.rlim_cur = rlim.rlim_max;
1024 if (setrlimit(RLIMIT_NOFILE, &rlim) != 0) {
1025 int bad = 1;
1026 #ifdef OPEN_MAX
1027 if (errno == EINVAL && OPEN_MAX < rlim.rlim_cur) {
1028 /* On some platforms, OPEN_MAX is the real limit, and getrlimit() is
1029 * full of nasty lies. I'm looking at you, OSX 10.5.... */
1030 rlim.rlim_cur = OPEN_MAX;
1031 if (setrlimit(RLIMIT_NOFILE, &rlim) == 0) {
1032 if (rlim.rlim_cur < (rlim_t)limit) {
1033 log_warn(LD_CONFIG, "We are limited to %lu file descriptors by "
1034 "OPEN_MAX, and ConnLimit is %lu. Changing ConnLimit; sorry.",
1035 (unsigned long)OPEN_MAX, (unsigned long)limit);
1036 } else {
1037 log_info(LD_CONFIG, "Dropped connection limit to OPEN_MAX (%lu); "
1038 "Apparently, %lu was too high and rlimit lied to us.",
1039 (unsigned long)OPEN_MAX, (unsigned long)rlim.rlim_max);
1041 bad = 0;
1044 #endif /* OPEN_MAX */
1045 if (bad) {
1046 log_warn(LD_CONFIG,"Couldn't set maximum number of file descriptors: %s",
1047 strerror(errno));
1048 return -1;
1051 /* leave some overhead for logs, etc, */
1052 limit = rlim.rlim_cur;
1053 #endif /* HAVE_GETRLIMIT */
1055 if (limit < ULIMIT_BUFFER) {
1056 log_warn(LD_CONFIG,
1057 "ConnLimit must be at least %d. Failing.", ULIMIT_BUFFER);
1058 return -1;
1060 if (limit > INT_MAX)
1061 limit = INT_MAX;
1062 tor_assert(max_out);
1063 *max_out = (int)limit - ULIMIT_BUFFER;
1064 return 0;
1067 #ifndef MS_WINDOWS
1068 /** Log details of current user and group credentials. Return 0 on
1069 * success. Logs and return -1 on failure.
1071 static int
1072 log_credential_status(void)
1074 #define CREDENTIAL_LOG_LEVEL LOG_INFO
1075 /* Real, effective and saved UIDs */
1076 uid_t ruid, euid, suid;
1077 /* Read, effective and saved GIDs */
1078 gid_t rgid, egid, sgid;
1079 /* Supplementary groups */
1080 gid_t sup_gids[NGROUPS_MAX + 1];
1081 /* Number of supplementary groups */
1082 int ngids;
1084 /* log UIDs */
1085 #ifdef HAVE_GETRESUID
1086 if (getresuid(&ruid, &euid, &suid) != 0 ) {
1087 log_warn(LD_GENERAL, "Error getting changed UIDs: %s", strerror(errno));
1088 return -1;
1089 } else {
1090 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
1091 "UID is %u (real), %u (effective), %u (saved)",
1092 (unsigned)ruid, (unsigned)euid, (unsigned)suid);
1094 #else
1095 /* getresuid is not present on MacOS X, so we can't get the saved (E)UID */
1096 ruid = getuid();
1097 euid = geteuid();
1098 (void)suid;
1100 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
1101 "UID is %u (real), %u (effective), unknown (saved)",
1102 (unsigned)ruid, (unsigned)euid);
1103 #endif
1105 /* log GIDs */
1106 #ifdef HAVE_GETRESGID
1107 if (getresgid(&rgid, &egid, &sgid) != 0 ) {
1108 log_warn(LD_GENERAL, "Error getting changed GIDs: %s", strerror(errno));
1109 return -1;
1110 } else {
1111 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
1112 "GID is %u (real), %u (effective), %u (saved)",
1113 (unsigned)rgid, (unsigned)egid, (unsigned)sgid);
1115 #else
1116 /* getresgid is not present on MacOS X, so we can't get the saved (E)GID */
1117 rgid = getgid();
1118 egid = getegid();
1119 (void)sgid;
1120 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
1121 "GID is %u (real), %u (effective), unknown (saved)",
1122 (unsigned)rgid, (unsigned)egid);
1123 #endif
1125 /* log supplementary groups */
1126 if ((ngids = getgroups(NGROUPS_MAX + 1, sup_gids)) < 0) {
1127 log_warn(LD_GENERAL, "Error getting supplementary GIDs: %s",
1128 strerror(errno));
1129 return -1;
1130 } else {
1131 int i, retval = 0;
1132 char *strgid;
1133 char *s = NULL;
1134 smartlist_t *elts = smartlist_create();
1136 for (i = 0; i<ngids; i++) {
1137 strgid = tor_malloc(11);
1138 if (tor_snprintf(strgid, 11, "%u", (unsigned)sup_gids[i]) < 0) {
1139 log_warn(LD_GENERAL, "Error printing supplementary GIDs");
1140 tor_free(strgid);
1141 retval = -1;
1142 goto error;
1144 smartlist_add(elts, strgid);
1147 s = smartlist_join_strings(elts, " ", 0, NULL);
1149 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL, "Supplementary groups are: %s",s);
1151 error:
1152 tor_free(s);
1153 SMARTLIST_FOREACH(elts, char *, cp,
1155 tor_free(cp);
1157 smartlist_free(elts);
1159 return retval;
1162 return 0;
1164 #endif
1166 /** Call setuid and setgid to run as <b>user</b> and switch to their
1167 * primary group. Return 0 on success. On failure, log and return -1.
1170 switch_id(const char *user)
1172 #ifndef MS_WINDOWS
1173 struct passwd *pw = NULL;
1174 uid_t old_uid;
1175 gid_t old_gid;
1176 static int have_already_switched_id = 0;
1178 tor_assert(user);
1180 if (have_already_switched_id)
1181 return 0;
1183 /* Log the initial credential state */
1184 if (log_credential_status())
1185 return -1;
1187 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL, "Changing user and groups");
1189 /* Get old UID/GID to check if we changed correctly */
1190 old_uid = getuid();
1191 old_gid = getgid();
1193 /* Lookup the user and group information, if we have a problem, bail out. */
1194 pw = getpwnam(user);
1195 if (pw == NULL) {
1196 log_warn(LD_CONFIG, "Error setting configured user: %s not found", user);
1197 return -1;
1200 /* Properly switch egid,gid,euid,uid here or bail out */
1201 if (setgroups(1, &pw->pw_gid)) {
1202 log_warn(LD_GENERAL, "Error setting groups to gid %d: \"%s\".",
1203 (int)pw->pw_gid, strerror(errno));
1204 if (old_uid == pw->pw_uid) {
1205 log_warn(LD_GENERAL, "Tor is already running as %s. You do not need "
1206 "the \"User\" option if you are already running as the user "
1207 "you want to be. (If you did not set the User option in your "
1208 "torrc, check whether it was specified on the command line "
1209 "by a startup script.)", user);
1210 } else {
1211 log_warn(LD_GENERAL, "If you set the \"User\" option, you must start Tor"
1212 " as root.");
1214 return -1;
1217 if (setegid(pw->pw_gid)) {
1218 log_warn(LD_GENERAL, "Error setting egid to %d: %s",
1219 (int)pw->pw_gid, strerror(errno));
1220 return -1;
1223 if (setgid(pw->pw_gid)) {
1224 log_warn(LD_GENERAL, "Error setting gid to %d: %s",
1225 (int)pw->pw_gid, strerror(errno));
1226 return -1;
1229 if (setuid(pw->pw_uid)) {
1230 log_warn(LD_GENERAL, "Error setting configured uid to %s (%d): %s",
1231 user, (int)pw->pw_uid, strerror(errno));
1232 return -1;
1235 if (seteuid(pw->pw_uid)) {
1236 log_warn(LD_GENERAL, "Error setting configured euid to %s (%d): %s",
1237 user, (int)pw->pw_uid, strerror(errno));
1238 return -1;
1241 /* This is how OpenBSD rolls:
1242 if (setgroups(1, &pw->pw_gid) || setegid(pw->pw_gid) ||
1243 setgid(pw->pw_gid) || setuid(pw->pw_uid) || seteuid(pw->pw_uid)) {
1244 setgid(pw->pw_gid) || seteuid(pw->pw_uid) || setuid(pw->pw_uid)) {
1245 log_warn(LD_GENERAL, "Error setting configured UID/GID: %s",
1246 strerror(errno));
1247 return -1;
1251 /* We've properly switched egid, gid, euid, uid, and supplementary groups if
1252 * we're here. */
1254 #if !defined(CYGWIN) && !defined(__CYGWIN__)
1255 /* If we tried to drop privilege to a group/user other than root, attempt to
1256 * restore root (E)(U|G)ID, and abort if the operation succeeds */
1258 /* Only check for privilege dropping if we were asked to be non-root */
1259 if (pw->pw_uid) {
1260 /* Try changing GID/EGID */
1261 if (pw->pw_gid != old_gid &&
1262 (setgid(old_gid) != -1 || setegid(old_gid) != -1)) {
1263 log_warn(LD_GENERAL, "Was able to restore group credentials even after "
1264 "switching GID: this means that the setgid code didn't work.");
1265 return -1;
1268 /* Try changing UID/EUID */
1269 if (pw->pw_uid != old_uid &&
1270 (setuid(old_uid) != -1 || seteuid(old_uid) != -1)) {
1271 log_warn(LD_GENERAL, "Was able to restore user credentials even after "
1272 "switching UID: this means that the setuid code didn't work.");
1273 return -1;
1276 #endif
1278 /* Check what really happened */
1279 if (log_credential_status()) {
1280 return -1;
1283 have_already_switched_id = 1; /* mark success so we never try again */
1285 #if defined(__linux__) && defined(HAVE_SYS_PRCTL_H) && defined(HAVE_PRCTL)
1286 #ifdef PR_SET_DUMPABLE
1287 if (pw->pw_uid) {
1288 /* Re-enable core dumps if we're not running as root. */
1289 log_info(LD_CONFIG, "Re-enabling coredumps");
1290 if (prctl(PR_SET_DUMPABLE, 1)) {
1291 log_warn(LD_CONFIG, "Unable to re-enable coredumps: %s",strerror(errno));
1294 #endif
1295 #endif
1296 return 0;
1298 #else
1299 (void)user;
1301 log_warn(LD_CONFIG,
1302 "User specified but switching users is unsupported on your OS.");
1303 return -1;
1304 #endif
1307 #ifdef HAVE_PWD_H
1308 /** Allocate and return a string containing the home directory for the
1309 * user <b>username</b>. Only works on posix-like systems. */
1310 char *
1311 get_user_homedir(const char *username)
1313 struct passwd *pw;
1314 tor_assert(username);
1316 if (!(pw = getpwnam(username))) {
1317 log_err(LD_CONFIG,"User \"%s\" not found.", username);
1318 return NULL;
1320 return tor_strdup(pw->pw_dir);
1322 #endif
1324 /** Set *addr to the IP address (in dotted-quad notation) stored in c.
1325 * Return 1 on success, 0 if c is badly formatted. (Like inet_aton(c,addr),
1326 * but works on Windows and Solaris.)
1329 tor_inet_aton(const char *str, struct in_addr* addr)
1331 unsigned a,b,c,d;
1332 char more;
1333 if (tor_sscanf(str, "%3u.%3u.%3u.%3u%c", &a,&b,&c,&d,&more) != 4)
1334 return 0;
1335 if (a > 255) return 0;
1336 if (b > 255) return 0;
1337 if (c > 255) return 0;
1338 if (d > 255) return 0;
1339 addr->s_addr = htonl((a<<24) | (b<<16) | (c<<8) | d);
1340 return 1;
1343 /** Given <b>af</b>==AF_INET and <b>src</b> a struct in_addr, or
1344 * <b>af</b>==AF_INET6 and <b>src</b> a struct in6_addr, try to format the
1345 * address and store it in the <b>len</b>-byte buffer <b>dst</b>. Returns
1346 * <b>dst</b> on success, NULL on failure.
1348 * (Like inet_ntop(af,src,dst,len), but works on platforms that don't have it:
1349 * Tor sometimes needs to format ipv6 addresses even on platforms without ipv6
1350 * support.) */
1351 const char *
1352 tor_inet_ntop(int af, const void *src, char *dst, size_t len)
1354 if (af == AF_INET) {
1355 if (tor_inet_ntoa(src, dst, len) < 0)
1356 return NULL;
1357 else
1358 return dst;
1359 } else if (af == AF_INET6) {
1360 const struct in6_addr *addr = src;
1361 char buf[64], *cp;
1362 int longestGapLen = 0, longestGapPos = -1, i,
1363 curGapPos = -1, curGapLen = 0;
1364 uint16_t words[8];
1365 for (i = 0; i < 8; ++i) {
1366 words[i] = (((uint16_t)addr->s6_addr[2*i])<<8) + addr->s6_addr[2*i+1];
1368 if (words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0 &&
1369 words[4] == 0 && ((words[5] == 0 && words[6] && words[7]) ||
1370 (words[5] == 0xffff))) {
1371 /* This is an IPv4 address. */
1372 if (words[5] == 0) {
1373 tor_snprintf(buf, sizeof(buf), "::%d.%d.%d.%d",
1374 addr->s6_addr[12], addr->s6_addr[13],
1375 addr->s6_addr[14], addr->s6_addr[15]);
1376 } else {
1377 tor_snprintf(buf, sizeof(buf), "::%x:%d.%d.%d.%d", words[5],
1378 addr->s6_addr[12], addr->s6_addr[13],
1379 addr->s6_addr[14], addr->s6_addr[15]);
1381 if (strlen(buf) > len)
1382 return NULL;
1383 strlcpy(dst, buf, len);
1384 return dst;
1386 i = 0;
1387 while (i < 8) {
1388 if (words[i] == 0) {
1389 curGapPos = i++;
1390 curGapLen = 1;
1391 while (i<8 && words[i] == 0) {
1392 ++i; ++curGapLen;
1394 if (curGapLen > longestGapLen) {
1395 longestGapPos = curGapPos;
1396 longestGapLen = curGapLen;
1398 } else {
1399 ++i;
1402 if (longestGapLen<=1)
1403 longestGapPos = -1;
1405 cp = buf;
1406 for (i = 0; i < 8; ++i) {
1407 if (words[i] == 0 && longestGapPos == i) {
1408 if (i == 0)
1409 *cp++ = ':';
1410 *cp++ = ':';
1411 while (i < 8 && words[i] == 0)
1412 ++i;
1413 --i; /* to compensate for loop increment. */
1414 } else {
1415 tor_snprintf(cp, sizeof(buf)-(cp-buf), "%x", (unsigned)words[i]);
1416 cp += strlen(cp);
1417 if (i != 7)
1418 *cp++ = ':';
1421 *cp = '\0';
1422 if (strlen(buf) > len)
1423 return NULL;
1424 strlcpy(dst, buf, len);
1425 return dst;
1426 } else {
1427 return NULL;
1431 /** Given <b>af</b>==AF_INET or <b>af</b>==AF_INET6, and a string <b>src</b>
1432 * encoding an IPv4 address or IPv6 address correspondingly, try to parse the
1433 * address and store the result in <b>dst</b> (which must have space for a
1434 * struct in_addr or a struct in6_addr, as appropriate). Return 1 on success,
1435 * 0 on a bad parse, and -1 on a bad <b>af</b>.
1437 * (Like inet_pton(af,src,dst) but works on platforms that don't have it: Tor
1438 * sometimes needs to format ipv6 addresses even on platforms without ipv6
1439 * support.) */
1441 tor_inet_pton(int af, const char *src, void *dst)
1443 if (af == AF_INET) {
1444 return tor_inet_aton(src, dst);
1445 } else if (af == AF_INET6) {
1446 struct in6_addr *out = dst;
1447 uint16_t words[8];
1448 int gapPos = -1, i, setWords=0;
1449 const char *dot = strchr(src, '.');
1450 const char *eow; /* end of words. */
1451 if (dot == src)
1452 return 0;
1453 else if (!dot)
1454 eow = src+strlen(src);
1455 else {
1456 unsigned byte1,byte2,byte3,byte4;
1457 char more;
1458 for (eow = dot-1; eow >= src && TOR_ISDIGIT(*eow); --eow)
1460 ++eow;
1462 /* We use "scanf" because some platform inet_aton()s are too lax
1463 * about IPv4 addresses of the form "1.2.3" */
1464 if (tor_sscanf(eow, "%3u.%3u.%3u.%3u%c",
1465 &byte1,&byte2,&byte3,&byte4,&more) != 4)
1466 return 0;
1468 if (byte1 > 255 || byte2 > 255 || byte3 > 255 || byte4 > 255)
1469 return 0;
1471 words[6] = (byte1<<8) | byte2;
1472 words[7] = (byte3<<8) | byte4;
1473 setWords += 2;
1476 i = 0;
1477 while (src < eow) {
1478 if (i > 7)
1479 return 0;
1480 if (TOR_ISXDIGIT(*src)) {
1481 char *next;
1482 long r = strtol(src, &next, 16);
1483 if (next > 4+src)
1484 return 0;
1485 if (next == src)
1486 return 0;
1487 if (r<0 || r>65536)
1488 return 0;
1490 words[i++] = (uint16_t)r;
1491 setWords++;
1492 src = next;
1493 if (*src != ':' && src != eow)
1494 return 0;
1495 ++src;
1496 } else if (*src == ':' && i > 0 && gapPos==-1) {
1497 gapPos = i;
1498 ++src;
1499 } else if (*src == ':' && i == 0 && src[1] == ':' && gapPos==-1) {
1500 gapPos = i;
1501 src += 2;
1502 } else {
1503 return 0;
1507 if (setWords > 8 ||
1508 (setWords == 8 && gapPos != -1) ||
1509 (setWords < 8 && gapPos == -1))
1510 return 0;
1512 if (gapPos >= 0) {
1513 int nToMove = setWords - (dot ? 2 : 0) - gapPos;
1514 int gapLen = 8 - setWords;
1515 tor_assert(nToMove >= 0);
1516 memmove(&words[gapPos+gapLen], &words[gapPos],
1517 sizeof(uint16_t)*nToMove);
1518 memset(&words[gapPos], 0, sizeof(uint16_t)*gapLen);
1520 for (i = 0; i < 8; ++i) {
1521 out->s6_addr[2*i ] = words[i] >> 8;
1522 out->s6_addr[2*i+1] = words[i] & 0xff;
1525 return 1;
1526 } else {
1527 return -1;
1531 /** Similar behavior to Unix gethostbyname: resolve <b>name</b>, and set
1532 * *<b>addr</b> to the proper IP address, in host byte order. Returns 0
1533 * on success, -1 on failure; 1 on transient failure.
1535 * (This function exists because standard windows gethostbyname
1536 * doesn't treat raw IP addresses properly.)
1539 tor_lookup_hostname(const char *name, uint32_t *addr)
1541 tor_addr_t myaddr;
1542 int ret;
1544 if ((ret = tor_addr_lookup(name, AF_INET, &myaddr)))
1545 return ret;
1547 if (tor_addr_family(&myaddr) == AF_INET) {
1548 *addr = tor_addr_to_ipv4h(&myaddr);
1549 return ret;
1552 return -1;
1555 /** Hold the result of our call to <b>uname</b>. */
1556 static char uname_result[256];
1557 /** True iff uname_result is set. */
1558 static int uname_result_is_set = 0;
1560 /** Return a pointer to a description of our platform.
1562 const char *
1563 get_uname(void)
1565 #ifdef HAVE_UNAME
1566 struct utsname u;
1567 #endif
1568 if (!uname_result_is_set) {
1569 #ifdef HAVE_UNAME
1570 if (uname(&u) != -1) {
1571 /* (linux says 0 is success, solaris says 1 is success) */
1572 tor_snprintf(uname_result, sizeof(uname_result), "%s %s",
1573 u.sysname, u.machine);
1574 } else
1575 #endif
1577 #ifdef MS_WINDOWS
1578 OSVERSIONINFOEX info;
1579 int i;
1580 unsigned int leftover_mask;
1581 const char *plat = NULL;
1582 const char *extra = NULL;
1583 static struct {
1584 unsigned major; unsigned minor; const char *version;
1585 } win_version_table[] = {
1586 { 6, 0, "Windows \"Longhorn\"" },
1587 { 5, 2, "Windows Server 2003" },
1588 { 5, 1, "Windows XP" },
1589 { 5, 0, "Windows 2000" },
1590 /* { 4, 0, "Windows NT 4.0" }, */
1591 { 4, 90, "Windows Me" },
1592 { 4, 10, "Windows 98" },
1593 /* { 4, 0, "Windows 95" } */
1594 { 3, 51, "Windows NT 3.51" },
1595 { 0, 0, NULL }
1597 #ifdef VER_SUITE_BACKOFFICE
1598 static struct {
1599 unsigned int mask; const char *str;
1600 } win_mask_table[] = {
1601 { VER_SUITE_BACKOFFICE, " {backoffice}" },
1602 { VER_SUITE_BLADE, " {\"blade\" (2003, web edition)}" },
1603 { VER_SUITE_DATACENTER, " {datacenter}" },
1604 { VER_SUITE_ENTERPRISE, " {enterprise}" },
1605 { VER_SUITE_EMBEDDEDNT, " {embedded}" },
1606 { VER_SUITE_PERSONAL, " {personal}" },
1607 { VER_SUITE_SINGLEUSERTS,
1608 " {terminal services, single user}" },
1609 { VER_SUITE_SMALLBUSINESS, " {small business}" },
1610 { VER_SUITE_SMALLBUSINESS_RESTRICTED,
1611 " {small business, restricted}" },
1612 { VER_SUITE_TERMINAL, " {terminal services}" },
1613 { 0, NULL },
1615 #endif
1616 memset(&info, 0, sizeof(info));
1617 info.dwOSVersionInfoSize = sizeof(info);
1618 if (! GetVersionEx((LPOSVERSIONINFO)&info)) {
1619 strlcpy(uname_result, "Bizarre version of Windows where GetVersionEx"
1620 " doesn't work.", sizeof(uname_result));
1621 uname_result_is_set = 1;
1622 return uname_result;
1624 if (info.dwMajorVersion == 4 && info.dwMinorVersion == 0) {
1625 if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
1626 plat = "Windows NT 4.0";
1627 else
1628 plat = "Windows 95";
1629 if (info.szCSDVersion[1] == 'B')
1630 extra = "OSR2 (B)";
1631 else if (info.szCSDVersion[1] == 'C')
1632 extra = "OSR2 (C)";
1633 } else {
1634 for (i=0; win_version_table[i].major>0; ++i) {
1635 if (win_version_table[i].major == info.dwMajorVersion &&
1636 win_version_table[i].minor == info.dwMinorVersion) {
1637 plat = win_version_table[i].version;
1638 break;
1642 if (plat && !strcmp(plat, "Windows 98")) {
1643 if (info.szCSDVersion[1] == 'A')
1644 extra = "SE (A)";
1645 else if (info.szCSDVersion[1] == 'B')
1646 extra = "SE (B)";
1648 if (plat) {
1649 if (!extra)
1650 extra = info.szCSDVersion;
1651 tor_snprintf(uname_result, sizeof(uname_result), "%s %s",
1652 plat, extra);
1653 } else {
1654 if (info.dwMajorVersion > 6 ||
1655 (info.dwMajorVersion==6 && info.dwMinorVersion>0))
1656 tor_snprintf(uname_result, sizeof(uname_result),
1657 "Very recent version of Windows [major=%d,minor=%d] %s",
1658 (int)info.dwMajorVersion,(int)info.dwMinorVersion,
1659 info.szCSDVersion);
1660 else
1661 tor_snprintf(uname_result, sizeof(uname_result),
1662 "Unrecognized version of Windows [major=%d,minor=%d] %s",
1663 (int)info.dwMajorVersion,(int)info.dwMinorVersion,
1664 info.szCSDVersion);
1666 #ifdef VER_SUITE_BACKOFFICE
1667 if (info.wProductType == VER_NT_DOMAIN_CONTROLLER) {
1668 strlcat(uname_result, " [domain controller]", sizeof(uname_result));
1669 } else if (info.wProductType == VER_NT_SERVER) {
1670 strlcat(uname_result, " [server]", sizeof(uname_result));
1671 } else if (info.wProductType == VER_NT_WORKSTATION) {
1672 strlcat(uname_result, " [workstation]", sizeof(uname_result));
1674 leftover_mask = info.wSuiteMask;
1675 for (i = 0; win_mask_table[i].mask; ++i) {
1676 if (info.wSuiteMask & win_mask_table[i].mask) {
1677 strlcat(uname_result, win_mask_table[i].str, sizeof(uname_result));
1678 leftover_mask &= ~win_mask_table[i].mask;
1681 if (leftover_mask) {
1682 size_t len = strlen(uname_result);
1683 tor_snprintf(uname_result+len, sizeof(uname_result)-len,
1684 " {0x%x}", info.wSuiteMask);
1686 #endif
1687 #else
1688 strlcpy(uname_result, "Unknown platform", sizeof(uname_result));
1689 #endif
1691 uname_result_is_set = 1;
1693 return uname_result;
1697 * Process control
1700 #if defined(USE_PTHREADS)
1701 /** Wraps a void (*)(void*) function and its argument so we can
1702 * invoke them in a way pthreads would expect.
1704 typedef struct tor_pthread_data_t {
1705 void (*func)(void *);
1706 void *data;
1707 } tor_pthread_data_t;
1708 /** Given a tor_pthread_data_t <b>_data</b>, call _data-&gt;func(d-&gt;data)
1709 * and free _data. Used to make sure we can call functions the way pthread
1710 * expects. */
1711 static void *
1712 tor_pthread_helper_fn(void *_data)
1714 tor_pthread_data_t *data = _data;
1715 void (*func)(void*);
1716 void *arg;
1717 /* mask signals to worker threads to avoid SIGPIPE, etc */
1718 sigset_t sigs;
1719 /* We're in a subthread; don't handle any signals here. */
1720 sigfillset(&sigs);
1721 pthread_sigmask(SIG_SETMASK, &sigs, NULL);
1723 func = data->func;
1724 arg = data->data;
1725 tor_free(_data);
1726 func(arg);
1727 return NULL;
1729 #endif
1731 /** Minimalist interface to run a void function in the background. On
1732 * unix calls fork, on win32 calls beginthread. Returns -1 on failure.
1733 * func should not return, but rather should call spawn_exit.
1735 * NOTE: if <b>data</b> is used, it should not be allocated on the stack,
1736 * since in a multithreaded environment, there is no way to be sure that
1737 * the caller's stack will still be around when the called function is
1738 * running.
1741 spawn_func(void (*func)(void *), void *data)
1743 #if defined(USE_WIN32_THREADS)
1744 int rv;
1745 rv = (int)_beginthread(func, 0, data);
1746 if (rv == (int)-1)
1747 return -1;
1748 return 0;
1749 #elif defined(USE_PTHREADS)
1750 pthread_t thread;
1751 tor_pthread_data_t *d;
1752 d = tor_malloc(sizeof(tor_pthread_data_t));
1753 d->data = data;
1754 d->func = func;
1755 if (pthread_create(&thread,NULL,tor_pthread_helper_fn,d))
1756 return -1;
1757 if (pthread_detach(thread))
1758 return -1;
1759 return 0;
1760 #else
1761 pid_t pid;
1762 pid = fork();
1763 if (pid<0)
1764 return -1;
1765 if (pid==0) {
1766 /* Child */
1767 func(data);
1768 tor_assert(0); /* Should never reach here. */
1769 return 0; /* suppress "control-reaches-end-of-non-void" warning. */
1770 } else {
1771 /* Parent */
1772 return 0;
1774 #endif
1777 /** End the current thread/process.
1779 void
1780 spawn_exit(void)
1782 #if defined(USE_WIN32_THREADS)
1783 _endthread();
1784 //we should never get here. my compiler thinks that _endthread returns, this
1785 //is an attempt to fool it.
1786 tor_assert(0);
1787 _exit(0);
1788 #elif defined(USE_PTHREADS)
1789 pthread_exit(NULL);
1790 #else
1791 /* http://www.erlenstar.demon.co.uk/unix/faq_2.html says we should
1792 * call _exit, not exit, from child processes. */
1793 _exit(0);
1794 #endif
1798 /** Set *timeval to the current time of day. On error, log and terminate.
1799 * (Same as gettimeofday(timeval,NULL), but never returns -1.)
1801 void
1802 tor_gettimeofday(struct timeval *timeval)
1804 #ifdef MS_WINDOWS
1805 /* Epoch bias copied from perl: number of units between windows epoch and
1806 * unix epoch. */
1807 #define EPOCH_BIAS U64_LITERAL(116444736000000000)
1808 #define UNITS_PER_SEC U64_LITERAL(10000000)
1809 #define USEC_PER_SEC U64_LITERAL(1000000)
1810 #define UNITS_PER_USEC U64_LITERAL(10)
1811 union {
1812 uint64_t ft_64;
1813 FILETIME ft_ft;
1814 } ft;
1815 /* number of 100-nsec units since Jan 1, 1601 */
1816 GetSystemTimeAsFileTime(&ft.ft_ft);
1817 if (ft.ft_64 < EPOCH_BIAS) {
1818 log_err(LD_GENERAL,"System time is before 1970; failing.");
1819 exit(1);
1821 ft.ft_64 -= EPOCH_BIAS;
1822 timeval->tv_sec = (unsigned) (ft.ft_64 / UNITS_PER_SEC);
1823 timeval->tv_usec = (unsigned) ((ft.ft_64 / UNITS_PER_USEC) % USEC_PER_SEC);
1824 #elif defined(HAVE_GETTIMEOFDAY)
1825 if (gettimeofday(timeval, NULL)) {
1826 log_err(LD_GENERAL,"gettimeofday failed.");
1827 /* If gettimeofday dies, we have either given a bad timezone (we didn't),
1828 or segfaulted.*/
1829 exit(1);
1831 #elif defined(HAVE_FTIME)
1832 struct timeb tb;
1833 ftime(&tb);
1834 timeval->tv_sec = tb.time;
1835 timeval->tv_usec = tb.millitm * 1000;
1836 #else
1837 #error "No way to get time."
1838 #endif
1839 return;
1842 #if defined(TOR_IS_MULTITHREADED) && !defined(MS_WINDOWS)
1843 /** Defined iff we need to add locks when defining fake versions of reentrant
1844 * versions of time-related functions. */
1845 #define TIME_FNS_NEED_LOCKS
1846 #endif
1848 #ifndef HAVE_LOCALTIME_R
1849 #ifdef TIME_FNS_NEED_LOCKS
1850 struct tm *
1851 tor_localtime_r(const time_t *timep, struct tm *result)
1853 struct tm *r;
1854 static tor_mutex_t *m=NULL;
1855 if (!m) { m=tor_mutex_new(); }
1856 tor_assert(result);
1857 tor_mutex_acquire(m);
1858 r = localtime(timep);
1859 memcpy(result, r, sizeof(struct tm));
1860 tor_mutex_release(m);
1861 return result;
1863 #else
1864 struct tm *
1865 tor_localtime_r(const time_t *timep, struct tm *result)
1867 struct tm *r;
1868 tor_assert(result);
1869 r = localtime(timep);
1870 memcpy(result, r, sizeof(struct tm));
1871 return result;
1873 #endif
1874 #endif
1876 #ifndef HAVE_GMTIME_R
1877 #ifdef TIME_FNS_NEED_LOCKS
1878 struct tm *
1879 tor_gmtime_r(const time_t *timep, struct tm *result)
1881 struct tm *r;
1882 static tor_mutex_t *m=NULL;
1883 if (!m) { m=tor_mutex_new(); }
1884 tor_assert(result);
1885 tor_mutex_acquire(m);
1886 r = gmtime(timep);
1887 memcpy(result, r, sizeof(struct tm));
1888 tor_mutex_release(m);
1889 return result;
1891 #else
1892 struct tm *
1893 tor_gmtime_r(const time_t *timep, struct tm *result)
1895 struct tm *r;
1896 tor_assert(result);
1897 r = gmtime(timep);
1898 memcpy(result, r, sizeof(struct tm));
1899 return result;
1901 #endif
1902 #endif
1904 #if defined(USE_WIN32_THREADS)
1905 void
1906 tor_mutex_init(tor_mutex_t *m)
1908 InitializeCriticalSection(&m->mutex);
1910 void
1911 tor_mutex_uninit(tor_mutex_t *m)
1913 DeleteCriticalSection(&m->mutex);
1915 void
1916 tor_mutex_acquire(tor_mutex_t *m)
1918 tor_assert(m);
1919 EnterCriticalSection(&m->mutex);
1921 void
1922 tor_mutex_release(tor_mutex_t *m)
1924 LeaveCriticalSection(&m->mutex);
1926 unsigned long
1927 tor_get_thread_id(void)
1929 return (unsigned long)GetCurrentThreadId();
1931 #elif defined(USE_PTHREADS)
1932 /** A mutex attribute that we're going to use to tell pthreads that we want
1933 * "reentrant" mutexes (i.e., once we can re-lock if we're already holding
1934 * them.) */
1935 static pthread_mutexattr_t attr_reentrant;
1936 /** True iff we've called tor_threads_init() */
1937 static int threads_initialized = 0;
1938 /** Initialize <b>mutex</b> so it can be locked. Every mutex must be set
1939 * up eith tor_mutex_init() or tor_mutex_new(); not both. */
1940 void
1941 tor_mutex_init(tor_mutex_t *mutex)
1943 int err;
1944 if (PREDICT_UNLIKELY(!threads_initialized))
1945 tor_threads_init();
1946 err = pthread_mutex_init(&mutex->mutex, &attr_reentrant);
1947 if (PREDICT_UNLIKELY(err)) {
1948 log_err(LD_GENERAL, "Error %d creating a mutex.", err);
1949 tor_fragile_assert();
1952 /** Wait until <b>m</b> is free, then acquire it. */
1953 void
1954 tor_mutex_acquire(tor_mutex_t *m)
1956 int err;
1957 tor_assert(m);
1958 err = pthread_mutex_lock(&m->mutex);
1959 if (PREDICT_UNLIKELY(err)) {
1960 log_err(LD_GENERAL, "Error %d locking a mutex.", err);
1961 tor_fragile_assert();
1964 /** Release the lock <b>m</b> so another thread can have it. */
1965 void
1966 tor_mutex_release(tor_mutex_t *m)
1968 int err;
1969 tor_assert(m);
1970 err = pthread_mutex_unlock(&m->mutex);
1971 if (PREDICT_UNLIKELY(err)) {
1972 log_err(LD_GENERAL, "Error %d unlocking a mutex.", err);
1973 tor_fragile_assert();
1976 /** Clean up the mutex <b>m</b> so that it no longer uses any system
1977 * resources. Does not free <b>m</b>. This function must only be called on
1978 * mutexes from tor_mutex_init(). */
1979 void
1980 tor_mutex_uninit(tor_mutex_t *m)
1982 int err;
1983 tor_assert(m);
1984 err = pthread_mutex_destroy(&m->mutex);
1985 if (PREDICT_UNLIKELY(err)) {
1986 log_err(LD_GENERAL, "Error %d destroying a mutex.", err);
1987 tor_fragile_assert();
1990 /** Return an integer representing this thread. */
1991 unsigned long
1992 tor_get_thread_id(void)
1994 union {
1995 pthread_t thr;
1996 unsigned long id;
1997 } r;
1998 r.thr = pthread_self();
1999 return r.id;
2001 #endif
2003 #ifdef TOR_IS_MULTITHREADED
2004 /** Return a newly allocated, ready-for-use mutex. */
2005 tor_mutex_t *
2006 tor_mutex_new(void)
2008 tor_mutex_t *m = tor_malloc_zero(sizeof(tor_mutex_t));
2009 tor_mutex_init(m);
2010 return m;
2012 /** Release all storage and system resources held by <b>m</b>. */
2013 void
2014 tor_mutex_free(tor_mutex_t *m)
2016 tor_mutex_uninit(m);
2017 tor_free(m);
2019 #endif
2021 /* Conditions. */
2022 #ifdef USE_PTHREADS
2023 #if 0
2024 /** Cross-platform condition implementation. */
2025 struct tor_cond_t {
2026 pthread_cond_t cond;
2028 /** Return a newly allocated condition, with nobody waiting on it. */
2029 tor_cond_t *
2030 tor_cond_new(void)
2032 tor_cond_t *cond = tor_malloc_zero(sizeof(tor_cond_t));
2033 if (pthread_cond_init(&cond->cond, NULL)) {
2034 tor_free(cond);
2035 return NULL;
2037 return cond;
2039 /** Release all resources held by <b>cond</b>. */
2040 void
2041 tor_cond_free(tor_cond_t *cond)
2043 tor_assert(cond);
2044 if (pthread_cond_destroy(&cond->cond)) {
2045 log_warn(LD_GENERAL,"Error freeing condition: %s", strerror(errno));
2046 return;
2048 tor_free(cond);
2050 /** Wait until one of the tor_cond_signal functions is called on <b>cond</b>.
2051 * All waiters on the condition must wait holding the same <b>mutex</b>.
2052 * Returns 0 on success, negative on failure. */
2054 tor_cond_wait(tor_cond_t *cond, tor_mutex_t *mutex)
2056 return pthread_cond_wait(&cond->cond, &mutex->mutex) ? -1 : 0;
2058 /** Wake up one of the waiters on <b>cond</b>. */
2059 void
2060 tor_cond_signal_one(tor_cond_t *cond)
2062 pthread_cond_signal(&cond->cond);
2064 /** Wake up all of the waiters on <b>cond</b>. */
2065 void
2066 tor_cond_signal_all(tor_cond_t *cond)
2068 pthread_cond_broadcast(&cond->cond);
2070 #endif
2071 /** Set up common structures for use by threading. */
2072 void
2073 tor_threads_init(void)
2075 if (!threads_initialized) {
2076 pthread_mutexattr_init(&attr_reentrant);
2077 pthread_mutexattr_settype(&attr_reentrant, PTHREAD_MUTEX_RECURSIVE);
2078 threads_initialized = 1;
2081 #elif defined(USE_WIN32_THREADS)
2082 #if 0
2083 static DWORD cond_event_tls_index;
2084 struct tor_cond_t {
2085 CRITICAL_SECTION mutex;
2086 smartlist_t *events;
2088 tor_cond_t *
2089 tor_cond_new(void)
2091 tor_cond_t *cond = tor_malloc_zero(sizeof(tor_cond_t));
2092 InitializeCriticalSection(&cond->mutex);
2093 cond->events = smartlist_create();
2094 return cond;
2096 void
2097 tor_cond_free(tor_cond_t *cond)
2099 tor_assert(cond);
2100 DeleteCriticalSection(&cond->mutex);
2101 /* XXXX notify? */
2102 smartlist_free(cond->events);
2103 tor_free(cond);
2106 tor_cond_wait(tor_cond_t *cond, tor_mutex_t *mutex)
2108 HANDLE event;
2109 int r;
2110 tor_assert(cond);
2111 tor_assert(mutex);
2112 event = TlsGetValue(cond_event_tls_index);
2113 if (!event) {
2114 event = CreateEvent(0, FALSE, FALSE, NULL);
2115 TlsSetValue(cond_event_tls_index, event);
2117 EnterCriticalSection(&cond->mutex);
2119 tor_assert(WaitForSingleObject(event, 0) == WAIT_TIMEOUT);
2120 tor_assert(!smartlist_isin(cond->events, event));
2121 smartlist_add(cond->events, event);
2123 LeaveCriticalSection(&cond->mutex);
2125 tor_mutex_release(mutex);
2126 r = WaitForSingleObject(event, INFINITE);
2127 tor_mutex_acquire(mutex);
2129 switch (r) {
2130 case WAIT_OBJECT_0: /* we got the mutex normally. */
2131 break;
2132 case WAIT_ABANDONED: /* holding thread exited. */
2133 case WAIT_TIMEOUT: /* Should never happen. */
2134 tor_assert(0);
2135 break;
2136 case WAIT_FAILED:
2137 log_warn(LD_GENERAL, "Failed to acquire mutex: %d",(int) GetLastError());
2139 return 0;
2141 void
2142 tor_cond_signal_one(tor_cond_t *cond)
2144 HANDLE event;
2145 tor_assert(cond);
2147 EnterCriticalSection(&cond->mutex);
2149 if ((event = smartlist_pop_last(cond->events)))
2150 SetEvent(event);
2152 LeaveCriticalSection(&cond->mutex);
2154 void
2155 tor_cond_signal_all(tor_cond_t *cond)
2157 tor_assert(cond);
2159 EnterCriticalSection(&cond->mutex);
2160 SMARTLIST_FOREACH(cond->events, HANDLE, event, SetEvent(event));
2161 smartlist_clear(cond->events);
2162 LeaveCriticalSection(&cond->mutex);
2164 #endif
2165 void
2166 tor_threads_init(void)
2168 #if 0
2169 cond_event_tls_index = TlsAlloc();
2170 #endif
2172 #endif
2175 * On Windows, WSAEWOULDBLOCK is not always correct: when you see it,
2176 * you need to ask the socket for its actual errno. Also, you need to
2177 * get your errors from WSAGetLastError, not errno. (If you supply a
2178 * socket of -1, we check WSAGetLastError, but don't correct
2179 * WSAEWOULDBLOCKs.)
2181 * The upshot of all of this is that when a socket call fails, you
2182 * should call tor_socket_errno <em>at most once</em> on the failing
2183 * socket to get the error.
2185 #if defined(MS_WINDOWS)
2187 tor_socket_errno(int sock)
2189 int optval, optvallen=sizeof(optval);
2190 int err = WSAGetLastError();
2191 if (err == WSAEWOULDBLOCK && sock >= 0) {
2192 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval, &optvallen))
2193 return err;
2194 if (optval)
2195 return optval;
2197 return err;
2199 #endif
2201 #if defined(MS_WINDOWS)
2202 #define E(code, s) { code, (s " [" #code " ]") }
2203 struct { int code; const char *msg; } windows_socket_errors[] = {
2204 E(WSAEINTR, "Interrupted function call"),
2205 E(WSAEACCES, "Permission denied"),
2206 E(WSAEFAULT, "Bad address"),
2207 E(WSAEINVAL, "Invalid argument"),
2208 E(WSAEMFILE, "Too many open files"),
2209 E(WSAEWOULDBLOCK, "Resource temporarily unavailable"),
2210 E(WSAEINPROGRESS, "Operation now in progress"),
2211 E(WSAEALREADY, "Operation already in progress"),
2212 E(WSAENOTSOCK, "Socket operation on nonsocket"),
2213 E(WSAEDESTADDRREQ, "Destination address required"),
2214 E(WSAEMSGSIZE, "Message too long"),
2215 E(WSAEPROTOTYPE, "Protocol wrong for socket"),
2216 E(WSAENOPROTOOPT, "Bad protocol option"),
2217 E(WSAEPROTONOSUPPORT, "Protocol not supported"),
2218 E(WSAESOCKTNOSUPPORT, "Socket type not supported"),
2219 /* What's the difference between NOTSUPP and NOSUPPORT? :) */
2220 E(WSAEOPNOTSUPP, "Operation not supported"),
2221 E(WSAEPFNOSUPPORT, "Protocol family not supported"),
2222 E(WSAEAFNOSUPPORT, "Address family not supported by protocol family"),
2223 E(WSAEADDRINUSE, "Address already in use"),
2224 E(WSAEADDRNOTAVAIL, "Cannot assign requested address"),
2225 E(WSAENETDOWN, "Network is down"),
2226 E(WSAENETUNREACH, "Network is unreachable"),
2227 E(WSAENETRESET, "Network dropped connection on reset"),
2228 E(WSAECONNABORTED, "Software caused connection abort"),
2229 E(WSAECONNRESET, "Connection reset by peer"),
2230 E(WSAENOBUFS, "No buffer space available"),
2231 E(WSAEISCONN, "Socket is already connected"),
2232 E(WSAENOTCONN, "Socket is not connected"),
2233 E(WSAESHUTDOWN, "Cannot send after socket shutdown"),
2234 E(WSAETIMEDOUT, "Connection timed out"),
2235 E(WSAECONNREFUSED, "Connection refused"),
2236 E(WSAEHOSTDOWN, "Host is down"),
2237 E(WSAEHOSTUNREACH, "No route to host"),
2238 E(WSAEPROCLIM, "Too many processes"),
2239 /* Yes, some of these start with WSA, not WSAE. No, I don't know why. */
2240 E(WSASYSNOTREADY, "Network subsystem is unavailable"),
2241 E(WSAVERNOTSUPPORTED, "Winsock.dll out of range"),
2242 E(WSANOTINITIALISED, "Successful WSAStartup not yet performed"),
2243 E(WSAEDISCON, "Graceful shutdown now in progress"),
2244 #ifdef WSATYPE_NOT_FOUND
2245 E(WSATYPE_NOT_FOUND, "Class type not found"),
2246 #endif
2247 E(WSAHOST_NOT_FOUND, "Host not found"),
2248 E(WSATRY_AGAIN, "Nonauthoritative host not found"),
2249 E(WSANO_RECOVERY, "This is a nonrecoverable error"),
2250 E(WSANO_DATA, "Valid name, no data record of requested type)"),
2252 /* There are some more error codes whose numeric values are marked
2253 * <b>OS dependent</b>. They start with WSA_, apparently for the same
2254 * reason that practitioners of some craft traditions deliberately
2255 * introduce imperfections into their baskets and rugs "to allow the
2256 * evil spirits to escape." If we catch them, then our binaries
2257 * might not report consistent results across versions of Windows.
2258 * Thus, I'm going to let them all fall through.
2260 { -1, NULL },
2262 /** There does not seem to be a strerror equivalent for winsock errors.
2263 * Naturally, we have to roll our own.
2265 const char *
2266 tor_socket_strerror(int e)
2268 int i;
2269 for (i=0; windows_socket_errors[i].code >= 0; ++i) {
2270 if (e == windows_socket_errors[i].code)
2271 return windows_socket_errors[i].msg;
2273 return strerror(e);
2275 #endif
2277 /** Called before we make any calls to network-related functions.
2278 * (Some operating systems require their network libraries to be
2279 * initialized.) */
2281 network_init(void)
2283 #ifdef MS_WINDOWS
2284 /* This silly exercise is necessary before windows will allow
2285 * gethostbyname to work. */
2286 WSADATA WSAData;
2287 int r;
2288 r = WSAStartup(0x101,&WSAData);
2289 if (r) {
2290 log_warn(LD_NET,"Error initializing windows network layer: code was %d",r);
2291 return -1;
2293 /* WSAData.iMaxSockets might show the max sockets we're allowed to use.
2294 * We might use it to complain if we're trying to be a server but have
2295 * too few sockets available. */
2296 #endif
2297 return 0;
2300 #ifdef MS_WINDOWS
2301 /** Return a newly allocated string describing the windows system error code
2302 * <b>err</b>. Note that error codes are different from errno. Error codes
2303 * come from GetLastError() when a winapi call fails. errno is set only when
2304 * ansi functions fail. Whee. */
2305 char *
2306 format_win32_error(DWORD err)
2308 LPVOID str = NULL;
2309 char *result;
2311 /* Somebody once decided that this interface was better than strerror(). */
2312 FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
2313 FORMAT_MESSAGE_FROM_SYSTEM |
2314 FORMAT_MESSAGE_IGNORE_INSERTS,
2315 NULL, err,
2316 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
2317 (LPTSTR) &str,
2318 0, NULL);
2320 if (str) {
2321 result = tor_strdup((char*)str);
2322 LocalFree(str); /* LocalFree != free() */
2323 } else {
2324 result = tor_strdup("<unformattable error>");
2326 return result;
2328 #endif