Make payloads into uint8_t.
[tor/rransom.git] / src / common / compat.c
blob4cc8d997948646d26a7f4fa1c354b734fb12e0e5
1 /* Copyright (c) 2003-2004, Roger Dingledine
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2010, 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 /* XXXX why not just do fstat here? */
130 size = filesize = (size_t) lseek(fd, 0, SEEK_END);
131 lseek(fd, 0, SEEK_SET);
132 /* ensure page alignment */
133 page_size = getpagesize();
134 size += (size%page_size) ? page_size-(size%page_size) : 0;
136 if (!size) {
137 /* Zero-length file. If we call mmap on it, it will succeed but
138 * return NULL, and bad things will happen. So just fail. */
139 log_info(LD_FS,"File \"%s\" is empty. Ignoring.",filename);
140 errno = ERANGE;
141 close(fd);
142 return NULL;
145 string = mmap(0, size, PROT_READ, MAP_PRIVATE, fd, 0);
146 close(fd);
147 if (string == MAP_FAILED) {
148 int save_errno = errno;
149 log_warn(LD_FS,"Could not mmap file \"%s\": %s", filename,
150 strerror(errno));
151 errno = save_errno;
152 return NULL;
155 res = tor_malloc_zero(sizeof(tor_mmap_t));
156 res->data = string;
157 res->size = filesize;
158 res->mapping_size = size;
160 return res;
162 /** Release storage held for a memory mapping. */
163 void
164 tor_munmap_file(tor_mmap_t *handle)
166 munmap((char*)handle->data, handle->mapping_size);
167 tor_free(handle);
169 #elif defined(MS_WINDOWS)
170 tor_mmap_t *
171 tor_mmap_file(const char *filename)
173 tor_mmap_t *res = tor_malloc_zero(sizeof(tor_mmap_t));
174 int empty = 0;
175 res->file_handle = INVALID_HANDLE_VALUE;
176 res->mmap_handle = NULL;
178 res->file_handle = CreateFile(filename,
179 GENERIC_READ, FILE_SHARE_READ,
180 NULL,
181 OPEN_EXISTING,
182 FILE_ATTRIBUTE_NORMAL,
185 if (res->file_handle == INVALID_HANDLE_VALUE)
186 goto win_err;
188 res->size = GetFileSize(res->file_handle, NULL);
190 if (res->size == 0) {
191 log_info(LD_FS,"File \"%s\" is empty. Ignoring.",filename);
192 empty = 1;
193 goto err;
196 res->mmap_handle = CreateFileMapping(res->file_handle,
197 NULL,
198 PAGE_READONLY,
199 #if SIZEOF_SIZE_T > 4
200 (res->base.size >> 32),
201 #else
203 #endif
204 (res->size & 0xfffffffful),
205 NULL);
206 if (res->mmap_handle == NULL)
207 goto win_err;
208 res->data = (char*) MapViewOfFile(res->mmap_handle,
209 FILE_MAP_READ,
210 0, 0, 0);
211 if (!res->data)
212 goto win_err;
214 return res;
215 win_err: {
216 DWORD e = GetLastError();
217 int severity = (e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND) ?
218 LOG_INFO : LOG_WARN;
219 char *msg = format_win32_error(e);
220 log_fn(severity, LD_FS, "Couldn't mmap file \"%s\": %s", filename, msg);
221 tor_free(msg);
222 if (e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND)
223 errno = ENOENT;
224 else
225 errno = EINVAL;
227 err:
228 if (empty)
229 errno = ERANGE;
230 tor_munmap_file(res);
231 return NULL;
233 void
234 tor_munmap_file(tor_mmap_t *handle)
236 if (handle->data)
237 /* This is an ugly cast, but without it, "data" in struct tor_mmap_t would
238 have to be redefined as non-const. */
239 UnmapViewOfFile( (LPVOID) handle->data);
241 if (handle->mmap_handle != NULL)
242 CloseHandle(handle->mmap_handle);
243 if (handle->file_handle != INVALID_HANDLE_VALUE)
244 CloseHandle(handle->file_handle);
245 tor_free(handle);
247 #else
248 tor_mmap_t *
249 tor_mmap_file(const char *filename)
251 struct stat st;
252 char *res = read_file_to_str(filename, RFTS_BIN|RFTS_IGNORE_MISSING, &st);
253 tor_mmap_t *handle;
254 if (! res)
255 return NULL;
256 handle = tor_malloc_zero(sizeof(tor_mmap_t));
257 handle->data = res;
258 handle->size = st.st_size;
259 return handle;
261 void
262 tor_munmap_file(tor_mmap_t *handle)
264 char *d = (char*)handle->data;
265 tor_free(d);
266 memset(handle, 0, sizeof(tor_mmap_t));
267 tor_free(handle);
269 #endif
271 /** Replacement for snprintf. Differs from platform snprintf in two
272 * ways: First, always NUL-terminates its output. Second, always
273 * returns -1 if the result is truncated. (Note that this return
274 * behavior does <i>not</i> conform to C99; it just happens to be
275 * easier to emulate "return -1" with conformant implementations than
276 * it is to emulate "return number that would be written" with
277 * non-conformant implementations.) */
279 tor_snprintf(char *str, size_t size, const char *format, ...)
281 va_list ap;
282 int r;
283 va_start(ap,format);
284 r = tor_vsnprintf(str,size,format,ap);
285 va_end(ap);
286 return r;
289 /** Replacement for vsnprintf; behavior differs as tor_snprintf differs from
290 * snprintf.
293 tor_vsnprintf(char *str, size_t size, const char *format, va_list args)
295 int r;
296 if (size == 0)
297 return -1; /* no place for the NUL */
298 if (size > SIZE_T_CEILING)
299 return -1;
300 #ifdef MS_WINDOWS
301 r = _vsnprintf(str, size, format, args);
302 #else
303 r = vsnprintf(str, size, format, args);
304 #endif
305 str[size-1] = '\0';
306 if (r < 0 || r >= (ssize_t)size)
307 return -1;
308 return r;
311 /** Given <b>hlen</b> bytes at <b>haystack</b> and <b>nlen</b> bytes at
312 * <b>needle</b>, return a pointer to the first occurrence of the needle
313 * within the haystack, or NULL if there is no such occurrence.
315 * Requires that nlen be greater than zero.
317 const void *
318 tor_memmem(const void *_haystack, size_t hlen,
319 const void *_needle, size_t nlen)
321 #if defined(HAVE_MEMMEM) && (!defined(__GNUC__) || __GNUC__ >= 2)
322 tor_assert(nlen);
323 return memmem(_haystack, hlen, _needle, nlen);
324 #else
325 /* This isn't as fast as the GLIBC implementation, but it doesn't need to
326 * be. */
327 const char *p, *end;
328 const char *haystack = (const char*)_haystack;
329 const char *needle = (const char*)_needle;
330 char first;
331 tor_assert(nlen);
333 p = haystack;
334 end = haystack + hlen;
335 first = *(const char*)needle;
336 while ((p = memchr(p, first, end-p))) {
337 if (p+nlen > end)
338 return NULL;
339 if (!memcmp(p, needle, nlen))
340 return p;
341 ++p;
343 return NULL;
344 #endif
347 /* Tables to implement ctypes-replacement TOR_IS*() functions. Each table
348 * has 256 bits to look up whether a character is in some set or not. This
349 * fails on non-ASCII platforms, but it is hard to find a platform whose
350 * character set is not a superset of ASCII nowadays. */
351 const uint32_t TOR_ISALPHA_TABLE[8] =
352 { 0, 0, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
353 const uint32_t TOR_ISALNUM_TABLE[8] =
354 { 0, 0x3ff0000, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
355 const uint32_t TOR_ISSPACE_TABLE[8] = { 0x3e00, 0x1, 0, 0, 0, 0, 0, 0 };
356 const uint32_t TOR_ISXDIGIT_TABLE[8] =
357 { 0, 0x3ff0000, 0x7e, 0x7e, 0, 0, 0, 0 };
358 const uint32_t TOR_ISDIGIT_TABLE[8] = { 0, 0x3ff0000, 0, 0, 0, 0, 0, 0 };
359 const uint32_t TOR_ISPRINT_TABLE[8] =
360 { 0, 0xffffffff, 0xffffffff, 0x7fffffff, 0, 0, 0, 0x0 };
361 const uint32_t TOR_ISUPPER_TABLE[8] = { 0, 0, 0x7fffffe, 0, 0, 0, 0, 0 };
362 const uint32_t TOR_ISLOWER_TABLE[8] = { 0, 0, 0, 0x7fffffe, 0, 0, 0, 0 };
363 /* Upper-casing and lowercasing tables to map characters to upper/lowercase
364 * equivalents. */
365 const char TOR_TOUPPER_TABLE[256] = {
366 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
367 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
368 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
369 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
370 64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
371 80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
372 96,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
373 80,81,82,83,84,85,86,87,88,89,90,123,124,125,126,127,
374 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
375 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
376 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
377 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
378 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
379 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
380 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
381 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
383 const char TOR_TOLOWER_TABLE[256] = {
384 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
385 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
386 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
387 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
388 64,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
389 112,113,114,115,116,117,118,119,120,121,122,91,92,93,94,95,
390 96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
391 112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
392 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
393 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
394 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
395 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
396 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
397 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
398 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
399 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
402 #ifdef MS_WINDOWS
403 /** Take a filename and return a pointer to its final element. This
404 * function is called on __FILE__ to fix a MSVC nit where __FILE__
405 * contains the full path to the file. This is bad, because it
406 * confuses users to find the home directory of the person who
407 * compiled the binary in their warning messages.
409 const char *
410 tor_fix_source_file(const char *fname)
412 const char *cp1, *cp2, *r;
413 cp1 = strrchr(fname, '/');
414 cp2 = strrchr(fname, '\\');
415 if (cp1 && cp2) {
416 r = (cp1<cp2)?(cp2+1):(cp1+1);
417 } else if (cp1) {
418 r = cp1+1;
419 } else if (cp2) {
420 r = cp2+1;
421 } else {
422 r = fname;
424 return r;
426 #endif
429 * Read a 16-bit value beginning at <b>cp</b>. Equivalent to
430 * *(uint16_t*)(cp), but will not cause segfaults on platforms that forbid
431 * unaligned memory access.
433 uint16_t
434 get_uint16(const void *cp)
436 uint16_t v;
437 memcpy(&v,cp,2);
438 return v;
441 * Read a 32-bit value beginning at <b>cp</b>. Equivalent to
442 * *(uint32_t*)(cp), but will not cause segfaults on platforms that forbid
443 * unaligned memory access.
445 uint32_t
446 get_uint32(const void *cp)
448 uint32_t v;
449 memcpy(&v,cp,4);
450 return v;
453 * Read a 32-bit value beginning at <b>cp</b>. Equivalent to
454 * *(uint32_t*)(cp), but will not cause segfaults on platforms that forbid
455 * unaligned memory access.
457 uint64_t
458 get_uint64(const void *cp)
460 uint64_t v;
461 memcpy(&v,cp,8);
462 return v;
466 * Set a 16-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
467 * *(uint16_t*)(cp) = v, but will not cause segfaults on platforms that forbid
468 * unaligned memory access. */
469 void
470 set_uint16(void *cp, uint16_t v)
472 memcpy(cp,&v,2);
475 * Set a 32-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
476 * *(uint32_t*)(cp) = v, but will not cause segfaults on platforms that forbid
477 * unaligned memory access. */
478 void
479 set_uint32(void *cp, uint32_t v)
481 memcpy(cp,&v,4);
484 * Set a 64-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
485 * *(uint64_t*)(cp) = v, but will not cause segfaults on platforms that forbid
486 * unaligned memory access. */
487 void
488 set_uint64(void *cp, uint64_t v)
490 memcpy(cp,&v,8);
494 * Rename the file <b>from</b> to the file <b>to</b>. On Unix, this is
495 * the same as rename(2). On windows, this removes <b>to</b> first if
496 * it already exists.
497 * Returns 0 on success. Returns -1 and sets errno on failure.
500 replace_file(const char *from, const char *to)
502 #ifndef MS_WINDOWS
503 return rename(from,to);
504 #else
505 switch (file_status(to))
507 case FN_NOENT:
508 break;
509 case FN_FILE:
510 if (unlink(to)) return -1;
511 break;
512 case FN_ERROR:
513 return -1;
514 case FN_DIR:
515 errno = EISDIR;
516 return -1;
518 return rename(from,to);
519 #endif
522 /** Change <b>fname</b>'s modification time to now. */
524 touch_file(const char *fname)
526 if (utime(fname, NULL)!=0)
527 return -1;
528 return 0;
531 /** Represents a lockfile on which we hold the lock. */
532 struct tor_lockfile_t {
533 char *filename;
534 int fd;
537 /** Try to get a lock on the lockfile <b>filename</b>, creating it as
538 * necessary. If someone else has the lock and <b>blocking</b> is true,
539 * wait until the lock is available. Otherwise return immediately whether
540 * we succeeded or not.
542 * Set *<b>locked_out</b> to true if somebody else had the lock, and to false
543 * otherwise.
545 * Return a <b>tor_lockfile_t</b> on success, NULL on failure.
547 * (Implementation note: because we need to fall back to fcntl on some
548 * platforms, these locks are per-process, not per-thread. If you want
549 * to do in-process locking, use tor_mutex_t like a normal person.)
551 tor_lockfile_t *
552 tor_lockfile_lock(const char *filename, int blocking, int *locked_out)
554 tor_lockfile_t *result;
555 int fd;
556 *locked_out = 0;
558 log_info(LD_FS, "Locking \"%s\"", filename);
559 fd = open(filename, O_RDWR|O_CREAT|O_TRUNC, 0600);
560 if (fd < 0) {
561 log_warn(LD_FS,"Couldn't open \"%s\" for locking: %s", filename,
562 strerror(errno));
563 return NULL;
566 #ifdef WIN32
567 _lseek(fd, 0, SEEK_SET);
568 if (_locking(fd, blocking ? _LK_LOCK : _LK_NBLCK, 1) < 0) {
569 if (errno != EDEADLOCK)
570 log_warn(LD_FS,"Couldn't lock \"%s\": %s", filename, strerror(errno));
571 else
572 *locked_out = 1;
573 close(fd);
574 return NULL;
576 #elif defined(HAVE_FLOCK)
577 if (flock(fd, LOCK_EX|(blocking ? 0 : LOCK_NB)) < 0) {
578 if (errno != EWOULDBLOCK)
579 log_warn(LD_FS,"Couldn't lock \"%s\": %s", filename, strerror(errno));
580 else
581 *locked_out = 1;
582 close(fd);
583 return NULL;
585 #else
587 struct flock lock;
588 memset(&lock, 0, sizeof(lock));
589 lock.l_type = F_WRLCK;
590 lock.l_whence = SEEK_SET;
591 if (fcntl(fd, blocking ? F_SETLKW : F_SETLK, &lock) < 0) {
592 if (errno != EACCES && errno != EAGAIN)
593 log_warn(LD_FS, "Couldn't lock \"%s\": %s", filename, strerror(errno));
594 else
595 *locked_out = 1;
596 close(fd);
597 return NULL;
600 #endif
602 result = tor_malloc(sizeof(tor_lockfile_t));
603 result->filename = tor_strdup(filename);
604 result->fd = fd;
605 return result;
608 /** Release the lock held as <b>lockfile</b>. */
609 void
610 tor_lockfile_unlock(tor_lockfile_t *lockfile)
612 tor_assert(lockfile);
614 log_info(LD_FS, "Unlocking \"%s\"", lockfile->filename);
615 #ifdef WIN32
616 _lseek(lockfile->fd, 0, SEEK_SET);
617 if (_locking(lockfile->fd, _LK_UNLCK, 1) < 0) {
618 log_warn(LD_FS,"Error unlocking \"%s\": %s", lockfile->filename,
619 strerror(errno));
621 #elif defined(HAVE_FLOCK)
622 if (flock(lockfile->fd, LOCK_UN) < 0) {
623 log_warn(LD_FS, "Error unlocking \"%s\": %s", lockfile->filename,
624 strerror(errno));
626 #else
627 /* Closing the lockfile is sufficient. */
628 #endif
630 close(lockfile->fd);
631 lockfile->fd = -1;
632 tor_free(lockfile->filename);
633 tor_free(lockfile);
636 /* Some old versions of Unix didn't define constants for these values,
637 * and instead expect you to say 0, 1, or 2. */
638 #ifndef SEEK_CUR
639 #define SEEK_CUR 1
640 #endif
641 #ifndef SEEK_END
642 #define SEEK_END 2
643 #endif
645 /** Return the position of <b>fd</b> with respect to the start of the file. */
646 off_t
647 tor_fd_getpos(int fd)
649 #ifdef WIN32
650 return (off_t) _lseek(fd, 0, SEEK_CUR);
651 #else
652 return (off_t) lseek(fd, 0, SEEK_CUR);
653 #endif
656 /** Move <b>fd</b> to the end of the file. Return -1 on error, 0 on success. */
658 tor_fd_seekend(int fd)
660 #ifdef WIN32
661 return _lseek(fd, 0, SEEK_END) < 0 ? -1 : 0;
662 #else
663 return lseek(fd, 0, SEEK_END) < 0 ? -1 : 0;
664 #endif
667 #undef DEBUG_SOCKET_COUNTING
668 #ifdef DEBUG_SOCKET_COUNTING
669 /** A bitarray of all fds that should be passed to tor_socket_close(). Only
670 * used if DEBUG_SOCKET_COUNTING is defined. */
671 static bitarray_t *open_sockets = NULL;
672 /** The size of <b>open_sockets</b>, in bits. */
673 static int max_socket = -1;
674 #endif
676 /** Count of number of sockets currently open. (Undercounts sockets opened by
677 * eventdns and libevent.) */
678 static int n_sockets_open = 0;
680 /** Mutex to protect open_sockets, max_socket, and n_sockets_open. */
681 static tor_mutex_t *socket_accounting_mutex = NULL;
683 static INLINE void
684 socket_accounting_lock(void)
686 if (PREDICT_UNLIKELY(!socket_accounting_mutex))
687 socket_accounting_mutex = tor_mutex_new();
688 tor_mutex_acquire(socket_accounting_mutex);
691 static INLINE void
692 socket_accounting_unlock(void)
694 tor_mutex_release(socket_accounting_mutex);
697 /** As close(), but guaranteed to work for sockets across platforms (including
698 * Windows, where close()ing a socket doesn't work. Returns 0 on success, -1
699 * on failure. */
701 tor_close_socket(int s)
703 int r = 0;
705 /* On Windows, you have to call close() on fds returned by open(),
706 * and closesocket() on fds returned by socket(). On Unix, everything
707 * gets close()'d. We abstract this difference by always using
708 * tor_close_socket to close sockets, and always using close() on
709 * files.
711 #if defined(MS_WINDOWS)
712 r = closesocket(s);
713 #else
714 r = close(s);
715 #endif
717 socket_accounting_lock();
718 #ifdef DEBUG_SOCKET_COUNTING
719 if (s > max_socket || ! bitarray_is_set(open_sockets, s)) {
720 log_warn(LD_BUG, "Closing a socket (%d) that wasn't returned by tor_open_"
721 "socket(), or that was already closed or something.", s);
722 } else {
723 tor_assert(open_sockets && s <= max_socket);
724 bitarray_clear(open_sockets, s);
726 #endif
727 if (r == 0) {
728 --n_sockets_open;
729 } else {
730 int err = tor_socket_errno(-1);
731 log_info(LD_NET, "Close returned an error: %s", tor_socket_strerror(err));
732 #ifdef WIN32
733 if (err != WSAENOTSOCK)
734 --n_sockets_open;
735 #else
736 if (err != EBADF)
737 --n_sockets_open;
738 #endif
739 r = -1;
742 if (n_sockets_open < 0)
743 log_warn(LD_BUG, "Our socket count is below zero: %d. Please submit a "
744 "bug report.", n_sockets_open);
745 socket_accounting_unlock();
746 return r;
749 #ifdef DEBUG_SOCKET_COUNTING
750 /** Helper: if DEBUG_SOCKET_COUNTING is enabled, remember that <b>s</b> is
751 * now an open socket. */
752 static INLINE void
753 mark_socket_open(int s)
755 if (s > max_socket) {
756 if (max_socket == -1) {
757 open_sockets = bitarray_init_zero(s+128);
758 max_socket = s+128;
759 } else {
760 open_sockets = bitarray_expand(open_sockets, max_socket, s+128);
761 max_socket = s+128;
764 if (bitarray_is_set(open_sockets, s)) {
765 log_warn(LD_BUG, "I thought that %d was already open, but socket() just "
766 "gave it to me!", s);
768 bitarray_set(open_sockets, s);
770 #else
771 #define mark_socket_open(s) STMT_NIL
772 #endif
774 /** As socket(), but counts the number of open sockets. */
776 tor_open_socket(int domain, int type, int protocol)
778 int s = socket(domain, type, protocol);
779 if (s >= 0) {
780 socket_accounting_lock();
781 ++n_sockets_open;
782 mark_socket_open(s);
783 socket_accounting_unlock();
785 return s;
788 /** As socket(), but counts the number of open sockets. */
790 tor_accept_socket(int sockfd, struct sockaddr *addr, socklen_t *len)
792 int s = accept(sockfd, addr, len);
793 if (s >= 0) {
794 socket_accounting_lock();
795 ++n_sockets_open;
796 mark_socket_open(s);
797 socket_accounting_unlock();
799 return s;
802 /** Return the number of sockets we currently have opened. */
804 get_n_open_sockets(void)
806 int n;
807 socket_accounting_lock();
808 n = n_sockets_open;
809 socket_accounting_unlock();
810 return n;
813 /** Turn <b>socket</b> into a nonblocking socket.
815 void
816 set_socket_nonblocking(int socket)
818 #if defined(MS_WINDOWS)
819 unsigned long nonblocking = 1;
820 ioctlsocket(socket, FIONBIO, (unsigned long*) &nonblocking);
821 #else
822 fcntl(socket, F_SETFL, O_NONBLOCK);
823 #endif
827 * Allocate a pair of connected sockets. (Like socketpair(family,
828 * type,protocol,fd), but works on systems that don't have
829 * socketpair.)
831 * Currently, only (AF_UNIX, SOCK_STREAM, 0) sockets are supported.
833 * Note that on systems without socketpair, this call will fail if
834 * localhost is inaccessible (for example, if the networking
835 * stack is down). And even if it succeeds, the socket pair will not
836 * be able to read while localhost is down later (the socket pair may
837 * even close, depending on OS-specific timeouts).
839 * Returns 0 on success and -errno on failure; do not rely on the value
840 * of errno or WSAGetLastError().
842 /* It would be nicer just to set errno, but that won't work for windows. */
844 tor_socketpair(int family, int type, int protocol, int fd[2])
846 //don't use win32 socketpairs (they are always bad)
847 #if defined(HAVE_SOCKETPAIR) && !defined(MS_WINDOWS)
848 int r;
849 r = socketpair(family, type, protocol, fd);
850 if (r == 0) {
851 socket_accounting_lock();
852 if (fd[0] >= 0) {
853 ++n_sockets_open;
854 mark_socket_open(fd[0]);
856 if (fd[1] >= 0) {
857 ++n_sockets_open;
858 mark_socket_open(fd[1]);
860 socket_accounting_unlock();
862 return r < 0 ? -errno : r;
863 #else
864 /* This socketpair does not work when localhost is down. So
865 * it's really not the same thing at all. But it's close enough
866 * for now, and really, when localhost is down sometimes, we
867 * have other problems too.
869 int listener = -1;
870 int connector = -1;
871 int acceptor = -1;
872 struct sockaddr_in listen_addr;
873 struct sockaddr_in connect_addr;
874 int size;
875 int saved_errno = -1;
877 if (protocol
878 #ifdef AF_UNIX
879 || family != AF_UNIX
880 #endif
882 #ifdef MS_WINDOWS
883 return -WSAEAFNOSUPPORT;
884 #else
885 return -EAFNOSUPPORT;
886 #endif
888 if (!fd) {
889 return -EINVAL;
892 listener = tor_open_socket(AF_INET, type, 0);
893 if (listener < 0)
894 return -tor_socket_errno(-1);
895 memset(&listen_addr, 0, sizeof(listen_addr));
896 listen_addr.sin_family = AF_INET;
897 listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
898 listen_addr.sin_port = 0; /* kernel chooses port. */
899 if (bind(listener, (struct sockaddr *) &listen_addr, sizeof (listen_addr))
900 == -1)
901 goto tidy_up_and_fail;
902 if (listen(listener, 1) == -1)
903 goto tidy_up_and_fail;
905 connector = tor_open_socket(AF_INET, type, 0);
906 if (connector < 0)
907 goto tidy_up_and_fail;
908 /* We want to find out the port number to connect to. */
909 size = sizeof(connect_addr);
910 if (getsockname(listener, (struct sockaddr *) &connect_addr, &size) == -1)
911 goto tidy_up_and_fail;
912 if (size != sizeof (connect_addr))
913 goto abort_tidy_up_and_fail;
914 if (connect(connector, (struct sockaddr *) &connect_addr,
915 sizeof(connect_addr)) == -1)
916 goto tidy_up_and_fail;
918 size = sizeof(listen_addr);
919 acceptor = tor_accept_socket(listener,
920 (struct sockaddr *) &listen_addr, &size);
921 if (acceptor < 0)
922 goto tidy_up_and_fail;
923 if (size != sizeof(listen_addr))
924 goto abort_tidy_up_and_fail;
925 tor_close_socket(listener);
926 /* Now check we are talking to ourself by matching port and host on the
927 two sockets. */
928 if (getsockname(connector, (struct sockaddr *) &connect_addr, &size) == -1)
929 goto tidy_up_and_fail;
930 if (size != sizeof (connect_addr)
931 || listen_addr.sin_family != connect_addr.sin_family
932 || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
933 || listen_addr.sin_port != connect_addr.sin_port) {
934 goto abort_tidy_up_and_fail;
936 fd[0] = connector;
937 fd[1] = acceptor;
939 return 0;
941 abort_tidy_up_and_fail:
942 #ifdef MS_WINDOWS
943 saved_errno = WSAECONNABORTED;
944 #else
945 saved_errno = ECONNABORTED; /* I hope this is portable and appropriate. */
946 #endif
947 tidy_up_and_fail:
948 if (saved_errno < 0)
949 saved_errno = errno;
950 if (listener != -1)
951 tor_close_socket(listener);
952 if (connector != -1)
953 tor_close_socket(connector);
954 if (acceptor != -1)
955 tor_close_socket(acceptor);
956 return -saved_errno;
957 #endif
960 #define ULIMIT_BUFFER 32 /* keep 32 extra fd's beyond _ConnLimit */
962 /** Learn the maximum allowed number of file descriptors. (Some systems
963 * have a low soft limit.
965 * We compute this by finding the largest number that we can use.
966 * If we can't find a number greater than or equal to <b>limit</b>,
967 * then we fail: return -1.
969 * Otherwise, return 0 and store the maximum we found inside <b>max_out</b>.*/
971 set_max_file_descriptors(rlim_t limit, int *max_out)
973 /* Define some maximum connections values for systems where we cannot
974 * automatically determine a limit. Re Cygwin, see
975 * http://archives.seul.org/or/talk/Aug-2006/msg00210.html
976 * For an iPhone, 9999 should work. For Windows and all other unknown
977 * systems we use 15000 as the default. */
978 #ifndef HAVE_GETRLIMIT
979 #if defined(CYGWIN) || defined(__CYGWIN__)
980 const char *platform = "Cygwin";
981 const unsigned long MAX_CONNECTIONS = 3200;
982 #elif defined(IPHONE)
983 const char *platform = "iPhone";
984 const unsigned long MAX_CONNECTIONS = 9999;
985 #elif defined(MS_WINDOWS)
986 const char *platform = "Windows";
987 const unsigned long MAX_CONNECTIONS = 15000;
988 #else
989 const char *platform = "unknown platforms with no getrlimit()";
990 const unsigned long MAX_CONNECTIONS = 15000;
991 #endif
992 log_fn(LOG_INFO, LD_NET,
993 "This platform is missing getrlimit(). Proceeding.");
994 if (limit > MAX_CONNECTIONS) {
995 log_warn(LD_CONFIG,
996 "We do not support more than %lu file descriptors "
997 "on %s. Tried to raise to %lu.",
998 (unsigned long)MAX_CONNECTIONS, platform, (unsigned long)limit);
999 return -1;
1001 limit = MAX_CONNECTIONS;
1002 #else /* HAVE_GETRLIMIT */
1003 struct rlimit rlim;
1004 tor_assert(limit > 0);
1006 if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) {
1007 log_warn(LD_NET, "Could not get maximum number of file descriptors: %s",
1008 strerror(errno));
1009 return -1;
1012 if (rlim.rlim_max < limit) {
1013 log_warn(LD_CONFIG,"We need %lu file descriptors available, and we're "
1014 "limited to %lu. Please change your ulimit -n.",
1015 (unsigned long)limit, (unsigned long)rlim.rlim_max);
1016 return -1;
1019 if (rlim.rlim_max > rlim.rlim_cur) {
1020 log_info(LD_NET,"Raising max file descriptors from %lu to %lu.",
1021 (unsigned long)rlim.rlim_cur, (unsigned long)rlim.rlim_max);
1023 rlim.rlim_cur = rlim.rlim_max;
1025 if (setrlimit(RLIMIT_NOFILE, &rlim) != 0) {
1026 int bad = 1;
1027 #ifdef OPEN_MAX
1028 if (errno == EINVAL && OPEN_MAX < rlim.rlim_cur) {
1029 /* On some platforms, OPEN_MAX is the real limit, and getrlimit() is
1030 * full of nasty lies. I'm looking at you, OSX 10.5.... */
1031 rlim.rlim_cur = OPEN_MAX;
1032 if (setrlimit(RLIMIT_NOFILE, &rlim) == 0) {
1033 if (rlim.rlim_cur < (rlim_t)limit) {
1034 log_warn(LD_CONFIG, "We are limited to %lu file descriptors by "
1035 "OPEN_MAX, and ConnLimit is %lu. Changing ConnLimit; sorry.",
1036 (unsigned long)OPEN_MAX, (unsigned long)limit);
1037 } else {
1038 log_info(LD_CONFIG, "Dropped connection limit to OPEN_MAX (%lu); "
1039 "Apparently, %lu was too high and rlimit lied to us.",
1040 (unsigned long)OPEN_MAX, (unsigned long)rlim.rlim_max);
1042 bad = 0;
1045 #endif /* OPEN_MAX */
1046 if (bad) {
1047 log_warn(LD_CONFIG,"Couldn't set maximum number of file descriptors: %s",
1048 strerror(errno));
1049 return -1;
1052 /* leave some overhead for logs, etc, */
1053 limit = rlim.rlim_cur;
1054 #endif /* HAVE_GETRLIMIT */
1056 if (limit < ULIMIT_BUFFER) {
1057 log_warn(LD_CONFIG,
1058 "ConnLimit must be at least %d. Failing.", ULIMIT_BUFFER);
1059 return -1;
1061 if (limit > INT_MAX)
1062 limit = INT_MAX;
1063 tor_assert(max_out);
1064 *max_out = (int)limit - ULIMIT_BUFFER;
1065 return 0;
1068 #ifndef MS_WINDOWS
1069 /** Log details of current user and group credentials. Return 0 on
1070 * success. Logs and return -1 on failure.
1072 static int
1073 log_credential_status(void)
1075 #define CREDENTIAL_LOG_LEVEL LOG_INFO
1076 /* Real, effective and saved UIDs */
1077 uid_t ruid, euid, suid;
1078 /* Read, effective and saved GIDs */
1079 gid_t rgid, egid, sgid;
1080 /* Supplementary groups */
1081 gid_t sup_gids[NGROUPS_MAX + 1];
1082 /* Number of supplementary groups */
1083 int ngids;
1085 /* log UIDs */
1086 #ifdef HAVE_GETRESUID
1087 if (getresuid(&ruid, &euid, &suid) != 0 ) {
1088 log_warn(LD_GENERAL, "Error getting changed UIDs: %s", strerror(errno));
1089 return -1;
1090 } else {
1091 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
1092 "UID is %u (real), %u (effective), %u (saved)",
1093 (unsigned)ruid, (unsigned)euid, (unsigned)suid);
1095 #else
1096 /* getresuid is not present on MacOS X, so we can't get the saved (E)UID */
1097 ruid = getuid();
1098 euid = geteuid();
1099 (void)suid;
1101 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
1102 "UID is %u (real), %u (effective), unknown (saved)",
1103 (unsigned)ruid, (unsigned)euid);
1104 #endif
1106 /* log GIDs */
1107 #ifdef HAVE_GETRESGID
1108 if (getresgid(&rgid, &egid, &sgid) != 0 ) {
1109 log_warn(LD_GENERAL, "Error getting changed GIDs: %s", strerror(errno));
1110 return -1;
1111 } else {
1112 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
1113 "GID is %u (real), %u (effective), %u (saved)",
1114 (unsigned)rgid, (unsigned)egid, (unsigned)sgid);
1116 #else
1117 /* getresgid is not present on MacOS X, so we can't get the saved (E)GID */
1118 rgid = getgid();
1119 egid = getegid();
1120 (void)sgid;
1121 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
1122 "GID is %u (real), %u (effective), unknown (saved)",
1123 (unsigned)rgid, (unsigned)egid);
1124 #endif
1126 /* log supplementary groups */
1127 if ((ngids = getgroups(NGROUPS_MAX + 1, sup_gids)) < 0) {
1128 log_warn(LD_GENERAL, "Error getting supplementary GIDs: %s",
1129 strerror(errno));
1130 return -1;
1131 } else {
1132 int i, retval = 0;
1133 char *strgid;
1134 char *s = NULL;
1135 smartlist_t *elts = smartlist_create();
1137 for (i = 0; i<ngids; i++) {
1138 strgid = tor_malloc(11);
1139 if (tor_snprintf(strgid, 11, "%u", (unsigned)sup_gids[i]) < 0) {
1140 log_warn(LD_GENERAL, "Error printing supplementary GIDs");
1141 tor_free(strgid);
1142 retval = -1;
1143 goto error;
1145 smartlist_add(elts, strgid);
1148 s = smartlist_join_strings(elts, " ", 0, NULL);
1150 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL, "Supplementary groups are: %s",s);
1152 error:
1153 tor_free(s);
1154 SMARTLIST_FOREACH(elts, char *, cp,
1156 tor_free(cp);
1158 smartlist_free(elts);
1160 return retval;
1163 return 0;
1165 #endif
1167 /** Call setuid and setgid to run as <b>user</b> and switch to their
1168 * primary group. Return 0 on success. On failure, log and return -1.
1171 switch_id(const char *user)
1173 #ifndef MS_WINDOWS
1174 struct passwd *pw = NULL;
1175 uid_t old_uid;
1176 gid_t old_gid;
1177 static int have_already_switched_id = 0;
1179 tor_assert(user);
1181 if (have_already_switched_id)
1182 return 0;
1184 /* Log the initial credential state */
1185 if (log_credential_status())
1186 return -1;
1188 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL, "Changing user and groups");
1190 /* Get old UID/GID to check if we changed correctly */
1191 old_uid = getuid();
1192 old_gid = getgid();
1194 /* Lookup the user and group information, if we have a problem, bail out. */
1195 pw = getpwnam(user);
1196 if (pw == NULL) {
1197 log_warn(LD_CONFIG, "Error setting configured user: %s not found", user);
1198 return -1;
1201 /* Properly switch egid,gid,euid,uid here or bail out */
1202 if (setgroups(1, &pw->pw_gid)) {
1203 log_warn(LD_GENERAL, "Error setting groups to gid %d: \"%s\".",
1204 (int)pw->pw_gid, strerror(errno));
1205 if (old_uid == pw->pw_uid) {
1206 log_warn(LD_GENERAL, "Tor is already running as %s. You do not need "
1207 "the \"User\" option if you are already running as the user "
1208 "you want to be. (If you did not set the User option in your "
1209 "torrc, check whether it was specified on the command line "
1210 "by a startup script.)", user);
1211 } else {
1212 log_warn(LD_GENERAL, "If you set the \"User\" option, you must start Tor"
1213 " as root.");
1215 return -1;
1218 if (setegid(pw->pw_gid)) {
1219 log_warn(LD_GENERAL, "Error setting egid to %d: %s",
1220 (int)pw->pw_gid, strerror(errno));
1221 return -1;
1224 if (setgid(pw->pw_gid)) {
1225 log_warn(LD_GENERAL, "Error setting gid to %d: %s",
1226 (int)pw->pw_gid, strerror(errno));
1227 return -1;
1230 if (setuid(pw->pw_uid)) {
1231 log_warn(LD_GENERAL, "Error setting configured uid to %s (%d): %s",
1232 user, (int)pw->pw_uid, strerror(errno));
1233 return -1;
1236 if (seteuid(pw->pw_uid)) {
1237 log_warn(LD_GENERAL, "Error setting configured euid to %s (%d): %s",
1238 user, (int)pw->pw_uid, strerror(errno));
1239 return -1;
1242 /* This is how OpenBSD rolls:
1243 if (setgroups(1, &pw->pw_gid) || setegid(pw->pw_gid) ||
1244 setgid(pw->pw_gid) || setuid(pw->pw_uid) || seteuid(pw->pw_uid)) {
1245 setgid(pw->pw_gid) || seteuid(pw->pw_uid) || setuid(pw->pw_uid)) {
1246 log_warn(LD_GENERAL, "Error setting configured UID/GID: %s",
1247 strerror(errno));
1248 return -1;
1252 /* We've properly switched egid, gid, euid, uid, and supplementary groups if
1253 * we're here. */
1255 #if !defined(CYGWIN) && !defined(__CYGWIN__)
1256 /* If we tried to drop privilege to a group/user other than root, attempt to
1257 * restore root (E)(U|G)ID, and abort if the operation succeeds */
1259 /* Only check for privilege dropping if we were asked to be non-root */
1260 if (pw->pw_uid) {
1261 /* Try changing GID/EGID */
1262 if (pw->pw_gid != old_gid &&
1263 (setgid(old_gid) != -1 || setegid(old_gid) != -1)) {
1264 log_warn(LD_GENERAL, "Was able to restore group credentials even after "
1265 "switching GID: this means that the setgid code didn't work.");
1266 return -1;
1269 /* Try changing UID/EUID */
1270 if (pw->pw_uid != old_uid &&
1271 (setuid(old_uid) != -1 || seteuid(old_uid) != -1)) {
1272 log_warn(LD_GENERAL, "Was able to restore user credentials even after "
1273 "switching UID: this means that the setuid code didn't work.");
1274 return -1;
1277 #endif
1279 /* Check what really happened */
1280 if (log_credential_status()) {
1281 return -1;
1284 have_already_switched_id = 1; /* mark success so we never try again */
1286 #if defined(__linux__) && defined(HAVE_SYS_PRCTL_H) && defined(HAVE_PRCTL)
1287 #ifdef PR_SET_DUMPABLE
1288 if (pw->pw_uid) {
1289 /* Re-enable core dumps if we're not running as root. */
1290 log_info(LD_CONFIG, "Re-enabling coredumps");
1291 if (prctl(PR_SET_DUMPABLE, 1)) {
1292 log_warn(LD_CONFIG, "Unable to re-enable coredumps: %s",strerror(errno));
1295 #endif
1296 #endif
1297 return 0;
1299 #else
1300 (void)user;
1302 log_warn(LD_CONFIG,
1303 "User specified but switching users is unsupported on your OS.");
1304 return -1;
1305 #endif
1308 #ifdef HAVE_PWD_H
1309 /** Allocate and return a string containing the home directory for the
1310 * user <b>username</b>. Only works on posix-like systems. */
1311 char *
1312 get_user_homedir(const char *username)
1314 struct passwd *pw;
1315 tor_assert(username);
1317 if (!(pw = getpwnam(username))) {
1318 log_err(LD_CONFIG,"User \"%s\" not found.", username);
1319 return NULL;
1321 return tor_strdup(pw->pw_dir);
1323 #endif
1325 /** Set *addr to the IP address (in dotted-quad notation) stored in c.
1326 * Return 1 on success, 0 if c is badly formatted. (Like inet_aton(c,addr),
1327 * but works on Windows and Solaris.)
1330 tor_inet_aton(const char *str, struct in_addr* addr)
1332 unsigned a,b,c,d;
1333 char more;
1334 if (tor_sscanf(str, "%3u.%3u.%3u.%3u%c", &a,&b,&c,&d,&more) != 4)
1335 return 0;
1336 if (a > 255) return 0;
1337 if (b > 255) return 0;
1338 if (c > 255) return 0;
1339 if (d > 255) return 0;
1340 addr->s_addr = htonl((a<<24) | (b<<16) | (c<<8) | d);
1341 return 1;
1344 /** Given <b>af</b>==AF_INET and <b>src</b> a struct in_addr, or
1345 * <b>af</b>==AF_INET6 and <b>src</b> a struct in6_addr, try to format the
1346 * address and store it in the <b>len</b>-byte buffer <b>dst</b>. Returns
1347 * <b>dst</b> on success, NULL on failure.
1349 * (Like inet_ntop(af,src,dst,len), but works on platforms that don't have it:
1350 * Tor sometimes needs to format ipv6 addresses even on platforms without ipv6
1351 * support.) */
1352 const char *
1353 tor_inet_ntop(int af, const void *src, char *dst, size_t len)
1355 if (af == AF_INET) {
1356 if (tor_inet_ntoa(src, dst, len) < 0)
1357 return NULL;
1358 else
1359 return dst;
1360 } else if (af == AF_INET6) {
1361 const struct in6_addr *addr = src;
1362 char buf[64], *cp;
1363 int longestGapLen = 0, longestGapPos = -1, i,
1364 curGapPos = -1, curGapLen = 0;
1365 uint16_t words[8];
1366 for (i = 0; i < 8; ++i) {
1367 words[i] = (((uint16_t)addr->s6_addr[2*i])<<8) + addr->s6_addr[2*i+1];
1369 if (words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0 &&
1370 words[4] == 0 && ((words[5] == 0 && words[6] && words[7]) ||
1371 (words[5] == 0xffff))) {
1372 /* This is an IPv4 address. */
1373 if (words[5] == 0) {
1374 tor_snprintf(buf, sizeof(buf), "::%d.%d.%d.%d",
1375 addr->s6_addr[12], addr->s6_addr[13],
1376 addr->s6_addr[14], addr->s6_addr[15]);
1377 } else {
1378 tor_snprintf(buf, sizeof(buf), "::%x:%d.%d.%d.%d", words[5],
1379 addr->s6_addr[12], addr->s6_addr[13],
1380 addr->s6_addr[14], addr->s6_addr[15]);
1382 if (strlen(buf) > len)
1383 return NULL;
1384 strlcpy(dst, buf, len);
1385 return dst;
1387 i = 0;
1388 while (i < 8) {
1389 if (words[i] == 0) {
1390 curGapPos = i++;
1391 curGapLen = 1;
1392 while (i<8 && words[i] == 0) {
1393 ++i; ++curGapLen;
1395 if (curGapLen > longestGapLen) {
1396 longestGapPos = curGapPos;
1397 longestGapLen = curGapLen;
1399 } else {
1400 ++i;
1403 if (longestGapLen<=1)
1404 longestGapPos = -1;
1406 cp = buf;
1407 for (i = 0; i < 8; ++i) {
1408 if (words[i] == 0 && longestGapPos == i) {
1409 if (i == 0)
1410 *cp++ = ':';
1411 *cp++ = ':';
1412 while (i < 8 && words[i] == 0)
1413 ++i;
1414 --i; /* to compensate for loop increment. */
1415 } else {
1416 tor_snprintf(cp, sizeof(buf)-(cp-buf), "%x", (unsigned)words[i]);
1417 cp += strlen(cp);
1418 if (i != 7)
1419 *cp++ = ':';
1422 *cp = '\0';
1423 if (strlen(buf) > len)
1424 return NULL;
1425 strlcpy(dst, buf, len);
1426 return dst;
1427 } else {
1428 return NULL;
1432 /** Given <b>af</b>==AF_INET or <b>af</b>==AF_INET6, and a string <b>src</b>
1433 * encoding an IPv4 address or IPv6 address correspondingly, try to parse the
1434 * address and store the result in <b>dst</b> (which must have space for a
1435 * struct in_addr or a struct in6_addr, as appropriate). Return 1 on success,
1436 * 0 on a bad parse, and -1 on a bad <b>af</b>.
1438 * (Like inet_pton(af,src,dst) but works on platforms that don't have it: Tor
1439 * sometimes needs to format ipv6 addresses even on platforms without ipv6
1440 * support.) */
1442 tor_inet_pton(int af, const char *src, void *dst)
1444 if (af == AF_INET) {
1445 return tor_inet_aton(src, dst);
1446 } else if (af == AF_INET6) {
1447 struct in6_addr *out = dst;
1448 uint16_t words[8];
1449 int gapPos = -1, i, setWords=0;
1450 const char *dot = strchr(src, '.');
1451 const char *eow; /* end of words. */
1452 if (dot == src)
1453 return 0;
1454 else if (!dot)
1455 eow = src+strlen(src);
1456 else {
1457 unsigned byte1,byte2,byte3,byte4;
1458 char more;
1459 for (eow = dot-1; eow >= src && TOR_ISDIGIT(*eow); --eow)
1461 ++eow;
1463 /* We use "scanf" because some platform inet_aton()s are too lax
1464 * about IPv4 addresses of the form "1.2.3" */
1465 if (tor_sscanf(eow, "%3u.%3u.%3u.%3u%c",
1466 &byte1,&byte2,&byte3,&byte4,&more) != 4)
1467 return 0;
1469 if (byte1 > 255 || byte2 > 255 || byte3 > 255 || byte4 > 255)
1470 return 0;
1472 words[6] = (byte1<<8) | byte2;
1473 words[7] = (byte3<<8) | byte4;
1474 setWords += 2;
1477 i = 0;
1478 while (src < eow) {
1479 if (i > 7)
1480 return 0;
1481 if (TOR_ISXDIGIT(*src)) {
1482 char *next;
1483 long r = strtol(src, &next, 16);
1484 if (next > 4+src)
1485 return 0;
1486 if (next == src)
1487 return 0;
1488 if (r<0 || r>65536)
1489 return 0;
1491 words[i++] = (uint16_t)r;
1492 setWords++;
1493 src = next;
1494 if (*src != ':' && src != eow)
1495 return 0;
1496 ++src;
1497 } else if (*src == ':' && i > 0 && gapPos==-1) {
1498 gapPos = i;
1499 ++src;
1500 } else if (*src == ':' && i == 0 && src[1] == ':' && gapPos==-1) {
1501 gapPos = i;
1502 src += 2;
1503 } else {
1504 return 0;
1508 if (setWords > 8 ||
1509 (setWords == 8 && gapPos != -1) ||
1510 (setWords < 8 && gapPos == -1))
1511 return 0;
1513 if (gapPos >= 0) {
1514 int nToMove = setWords - (dot ? 2 : 0) - gapPos;
1515 int gapLen = 8 - setWords;
1516 tor_assert(nToMove >= 0);
1517 memmove(&words[gapPos+gapLen], &words[gapPos],
1518 sizeof(uint16_t)*nToMove);
1519 memset(&words[gapPos], 0, sizeof(uint16_t)*gapLen);
1521 for (i = 0; i < 8; ++i) {
1522 out->s6_addr[2*i ] = words[i] >> 8;
1523 out->s6_addr[2*i+1] = words[i] & 0xff;
1526 return 1;
1527 } else {
1528 return -1;
1532 /** Similar behavior to Unix gethostbyname: resolve <b>name</b>, and set
1533 * *<b>addr</b> to the proper IP address, in host byte order. Returns 0
1534 * on success, -1 on failure; 1 on transient failure.
1536 * (This function exists because standard windows gethostbyname
1537 * doesn't treat raw IP addresses properly.)
1540 tor_lookup_hostname(const char *name, uint32_t *addr)
1542 tor_addr_t myaddr;
1543 int ret;
1545 if ((ret = tor_addr_lookup(name, AF_INET, &myaddr)))
1546 return ret;
1548 if (tor_addr_family(&myaddr) == AF_INET) {
1549 *addr = tor_addr_to_ipv4h(&myaddr);
1550 return ret;
1553 return -1;
1556 /** Hold the result of our call to <b>uname</b>. */
1557 static char uname_result[256];
1558 /** True iff uname_result is set. */
1559 static int uname_result_is_set = 0;
1561 /** Return a pointer to a description of our platform.
1563 const char *
1564 get_uname(void)
1566 #ifdef HAVE_UNAME
1567 struct utsname u;
1568 #endif
1569 if (!uname_result_is_set) {
1570 #ifdef HAVE_UNAME
1571 if (uname(&u) != -1) {
1572 /* (Linux says 0 is success, Solaris says 1 is success) */
1573 tor_snprintf(uname_result, sizeof(uname_result), "%s %s",
1574 u.sysname, u.machine);
1575 } else
1576 #endif
1578 #ifdef MS_WINDOWS
1579 OSVERSIONINFOEX info;
1580 int i;
1581 unsigned int leftover_mask;
1582 const char *plat = NULL;
1583 const char *extra = NULL;
1584 static struct {
1585 unsigned major; unsigned minor; const char *version;
1586 } win_version_table[] = {
1587 { 6, 0, "Windows \"Longhorn\"" },
1588 { 5, 2, "Windows Server 2003" },
1589 { 5, 1, "Windows XP" },
1590 { 5, 0, "Windows 2000" },
1591 /* { 4, 0, "Windows NT 4.0" }, */
1592 { 4, 90, "Windows Me" },
1593 { 4, 10, "Windows 98" },
1594 /* { 4, 0, "Windows 95" } */
1595 { 3, 51, "Windows NT 3.51" },
1596 { 0, 0, NULL }
1598 #ifdef VER_SUITE_BACKOFFICE
1599 static struct {
1600 unsigned int mask; const char *str;
1601 } win_mask_table[] = {
1602 { VER_SUITE_BACKOFFICE, " {backoffice}" },
1603 { VER_SUITE_BLADE, " {\"blade\" (2003, web edition)}" },
1604 { VER_SUITE_DATACENTER, " {datacenter}" },
1605 { VER_SUITE_ENTERPRISE, " {enterprise}" },
1606 { VER_SUITE_EMBEDDEDNT, " {embedded}" },
1607 { VER_SUITE_PERSONAL, " {personal}" },
1608 { VER_SUITE_SINGLEUSERTS,
1609 " {terminal services, single user}" },
1610 { VER_SUITE_SMALLBUSINESS, " {small business}" },
1611 { VER_SUITE_SMALLBUSINESS_RESTRICTED,
1612 " {small business, restricted}" },
1613 { VER_SUITE_TERMINAL, " {terminal services}" },
1614 { 0, NULL },
1616 #endif
1617 memset(&info, 0, sizeof(info));
1618 info.dwOSVersionInfoSize = sizeof(info);
1619 if (! GetVersionEx((LPOSVERSIONINFO)&info)) {
1620 strlcpy(uname_result, "Bizarre version of Windows where GetVersionEx"
1621 " doesn't work.", sizeof(uname_result));
1622 uname_result_is_set = 1;
1623 return uname_result;
1625 if (info.dwMajorVersion == 4 && info.dwMinorVersion == 0) {
1626 if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
1627 plat = "Windows NT 4.0";
1628 else
1629 plat = "Windows 95";
1630 if (info.szCSDVersion[1] == 'B')
1631 extra = "OSR2 (B)";
1632 else if (info.szCSDVersion[1] == 'C')
1633 extra = "OSR2 (C)";
1634 } else {
1635 for (i=0; win_version_table[i].major>0; ++i) {
1636 if (win_version_table[i].major == info.dwMajorVersion &&
1637 win_version_table[i].minor == info.dwMinorVersion) {
1638 plat = win_version_table[i].version;
1639 break;
1643 if (plat && !strcmp(plat, "Windows 98")) {
1644 if (info.szCSDVersion[1] == 'A')
1645 extra = "SE (A)";
1646 else if (info.szCSDVersion[1] == 'B')
1647 extra = "SE (B)";
1649 if (plat) {
1650 if (!extra)
1651 extra = info.szCSDVersion;
1652 tor_snprintf(uname_result, sizeof(uname_result), "%s %s",
1653 plat, extra);
1654 } else {
1655 if (info.dwMajorVersion > 6 ||
1656 (info.dwMajorVersion==6 && info.dwMinorVersion>0))
1657 tor_snprintf(uname_result, sizeof(uname_result),
1658 "Very recent version of Windows [major=%d,minor=%d] %s",
1659 (int)info.dwMajorVersion,(int)info.dwMinorVersion,
1660 info.szCSDVersion);
1661 else
1662 tor_snprintf(uname_result, sizeof(uname_result),
1663 "Unrecognized version of Windows [major=%d,minor=%d] %s",
1664 (int)info.dwMajorVersion,(int)info.dwMinorVersion,
1665 info.szCSDVersion);
1667 #ifdef VER_SUITE_BACKOFFICE
1668 if (info.wProductType == VER_NT_DOMAIN_CONTROLLER) {
1669 strlcat(uname_result, " [domain controller]", sizeof(uname_result));
1670 } else if (info.wProductType == VER_NT_SERVER) {
1671 strlcat(uname_result, " [server]", sizeof(uname_result));
1672 } else if (info.wProductType == VER_NT_WORKSTATION) {
1673 strlcat(uname_result, " [workstation]", sizeof(uname_result));
1675 leftover_mask = info.wSuiteMask;
1676 for (i = 0; win_mask_table[i].mask; ++i) {
1677 if (info.wSuiteMask & win_mask_table[i].mask) {
1678 strlcat(uname_result, win_mask_table[i].str, sizeof(uname_result));
1679 leftover_mask &= ~win_mask_table[i].mask;
1682 if (leftover_mask) {
1683 size_t len = strlen(uname_result);
1684 tor_snprintf(uname_result+len, sizeof(uname_result)-len,
1685 " {0x%x}", info.wSuiteMask);
1687 #endif
1688 #else
1689 strlcpy(uname_result, "Unknown platform", sizeof(uname_result));
1690 #endif
1692 uname_result_is_set = 1;
1694 return uname_result;
1698 * Process control
1701 #if defined(USE_PTHREADS)
1702 /** Wraps a void (*)(void*) function and its argument so we can
1703 * invoke them in a way pthreads would expect.
1705 typedef struct tor_pthread_data_t {
1706 void (*func)(void *);
1707 void *data;
1708 } tor_pthread_data_t;
1709 /** Given a tor_pthread_data_t <b>_data</b>, call _data-&gt;func(d-&gt;data)
1710 * and free _data. Used to make sure we can call functions the way pthread
1711 * expects. */
1712 static void *
1713 tor_pthread_helper_fn(void *_data)
1715 tor_pthread_data_t *data = _data;
1716 void (*func)(void*);
1717 void *arg;
1718 /* mask signals to worker threads to avoid SIGPIPE, etc */
1719 sigset_t sigs;
1720 /* We're in a subthread; don't handle any signals here. */
1721 sigfillset(&sigs);
1722 pthread_sigmask(SIG_SETMASK, &sigs, NULL);
1724 func = data->func;
1725 arg = data->data;
1726 tor_free(_data);
1727 func(arg);
1728 return NULL;
1730 #endif
1732 /** Minimalist interface to run a void function in the background. On
1733 * Unix calls fork, on win32 calls beginthread. Returns -1 on failure.
1734 * func should not return, but rather should call spawn_exit.
1736 * NOTE: if <b>data</b> is used, it should not be allocated on the stack,
1737 * since in a multithreaded environment, there is no way to be sure that
1738 * the caller's stack will still be around when the called function is
1739 * running.
1742 spawn_func(void (*func)(void *), void *data)
1744 #if defined(USE_WIN32_THREADS)
1745 int rv;
1746 rv = (int)_beginthread(func, 0, data);
1747 if (rv == (int)-1)
1748 return -1;
1749 return 0;
1750 #elif defined(USE_PTHREADS)
1751 pthread_t thread;
1752 tor_pthread_data_t *d;
1753 d = tor_malloc(sizeof(tor_pthread_data_t));
1754 d->data = data;
1755 d->func = func;
1756 if (pthread_create(&thread,NULL,tor_pthread_helper_fn,d))
1757 return -1;
1758 if (pthread_detach(thread))
1759 return -1;
1760 return 0;
1761 #else
1762 pid_t pid;
1763 pid = fork();
1764 if (pid<0)
1765 return -1;
1766 if (pid==0) {
1767 /* Child */
1768 func(data);
1769 tor_assert(0); /* Should never reach here. */
1770 return 0; /* suppress "control-reaches-end-of-non-void" warning. */
1771 } else {
1772 /* Parent */
1773 return 0;
1775 #endif
1778 /** End the current thread/process.
1780 void
1781 spawn_exit(void)
1783 #if defined(USE_WIN32_THREADS)
1784 _endthread();
1785 //we should never get here. my compiler thinks that _endthread returns, this
1786 //is an attempt to fool it.
1787 tor_assert(0);
1788 _exit(0);
1789 #elif defined(USE_PTHREADS)
1790 pthread_exit(NULL);
1791 #else
1792 /* http://www.erlenstar.demon.co.uk/unix/faq_2.html says we should
1793 * call _exit, not exit, from child processes. */
1794 _exit(0);
1795 #endif
1799 /** Set *timeval to the current time of day. On error, log and terminate.
1800 * (Same as gettimeofday(timeval,NULL), but never returns -1.)
1802 void
1803 tor_gettimeofday(struct timeval *timeval)
1805 #ifdef MS_WINDOWS
1806 /* Epoch bias copied from perl: number of units between windows epoch and
1807 * Unix epoch. */
1808 #define EPOCH_BIAS U64_LITERAL(116444736000000000)
1809 #define UNITS_PER_SEC U64_LITERAL(10000000)
1810 #define USEC_PER_SEC U64_LITERAL(1000000)
1811 #define UNITS_PER_USEC U64_LITERAL(10)
1812 union {
1813 uint64_t ft_64;
1814 FILETIME ft_ft;
1815 } ft;
1816 /* number of 100-nsec units since Jan 1, 1601 */
1817 GetSystemTimeAsFileTime(&ft.ft_ft);
1818 if (ft.ft_64 < EPOCH_BIAS) {
1819 log_err(LD_GENERAL,"System time is before 1970; failing.");
1820 exit(1);
1822 ft.ft_64 -= EPOCH_BIAS;
1823 timeval->tv_sec = (unsigned) (ft.ft_64 / UNITS_PER_SEC);
1824 timeval->tv_usec = (unsigned) ((ft.ft_64 / UNITS_PER_USEC) % USEC_PER_SEC);
1825 #elif defined(HAVE_GETTIMEOFDAY)
1826 if (gettimeofday(timeval, NULL)) {
1827 log_err(LD_GENERAL,"gettimeofday failed.");
1828 /* If gettimeofday dies, we have either given a bad timezone (we didn't),
1829 or segfaulted.*/
1830 exit(1);
1832 #elif defined(HAVE_FTIME)
1833 struct timeb tb;
1834 ftime(&tb);
1835 timeval->tv_sec = tb.time;
1836 timeval->tv_usec = tb.millitm * 1000;
1837 #else
1838 #error "No way to get time."
1839 #endif
1840 return;
1843 #if defined(TOR_IS_MULTITHREADED) && !defined(MS_WINDOWS)
1844 /** Defined iff we need to add locks when defining fake versions of reentrant
1845 * versions of time-related functions. */
1846 #define TIME_FNS_NEED_LOCKS
1847 #endif
1849 #ifndef HAVE_LOCALTIME_R
1850 #ifdef TIME_FNS_NEED_LOCKS
1851 struct tm *
1852 tor_localtime_r(const time_t *timep, struct tm *result)
1854 struct tm *r;
1855 static tor_mutex_t *m=NULL;
1856 if (!m) { m=tor_mutex_new(); }
1857 tor_assert(result);
1858 tor_mutex_acquire(m);
1859 r = localtime(timep);
1860 memcpy(result, r, sizeof(struct tm));
1861 tor_mutex_release(m);
1862 return result;
1864 #else
1865 struct tm *
1866 tor_localtime_r(const time_t *timep, struct tm *result)
1868 struct tm *r;
1869 tor_assert(result);
1870 r = localtime(timep);
1871 memcpy(result, r, sizeof(struct tm));
1872 return result;
1874 #endif
1875 #endif
1877 #ifndef HAVE_GMTIME_R
1878 #ifdef TIME_FNS_NEED_LOCKS
1879 struct tm *
1880 tor_gmtime_r(const time_t *timep, struct tm *result)
1882 struct tm *r;
1883 static tor_mutex_t *m=NULL;
1884 if (!m) { m=tor_mutex_new(); }
1885 tor_assert(result);
1886 tor_mutex_acquire(m);
1887 r = gmtime(timep);
1888 memcpy(result, r, sizeof(struct tm));
1889 tor_mutex_release(m);
1890 return result;
1892 #else
1893 struct tm *
1894 tor_gmtime_r(const time_t *timep, struct tm *result)
1896 struct tm *r;
1897 tor_assert(result);
1898 r = gmtime(timep);
1899 memcpy(result, r, sizeof(struct tm));
1900 return result;
1902 #endif
1903 #endif
1905 #if defined(USE_WIN32_THREADS)
1906 void
1907 tor_mutex_init(tor_mutex_t *m)
1909 InitializeCriticalSection(&m->mutex);
1911 void
1912 tor_mutex_uninit(tor_mutex_t *m)
1914 DeleteCriticalSection(&m->mutex);
1916 void
1917 tor_mutex_acquire(tor_mutex_t *m)
1919 tor_assert(m);
1920 EnterCriticalSection(&m->mutex);
1922 void
1923 tor_mutex_release(tor_mutex_t *m)
1925 LeaveCriticalSection(&m->mutex);
1927 unsigned long
1928 tor_get_thread_id(void)
1930 return (unsigned long)GetCurrentThreadId();
1932 #elif defined(USE_PTHREADS)
1933 /** A mutex attribute that we're going to use to tell pthreads that we want
1934 * "reentrant" mutexes (i.e., once we can re-lock if we're already holding
1935 * them.) */
1936 static pthread_mutexattr_t attr_reentrant;
1937 /** True iff we've called tor_threads_init() */
1938 static int threads_initialized = 0;
1939 /** Initialize <b>mutex</b> so it can be locked. Every mutex must be set
1940 * up with tor_mutex_init() or tor_mutex_new(); not both. */
1941 void
1942 tor_mutex_init(tor_mutex_t *mutex)
1944 int err;
1945 if (PREDICT_UNLIKELY(!threads_initialized))
1946 tor_threads_init();
1947 err = pthread_mutex_init(&mutex->mutex, &attr_reentrant);
1948 if (PREDICT_UNLIKELY(err)) {
1949 log_err(LD_GENERAL, "Error %d creating a mutex.", err);
1950 tor_fragile_assert();
1953 /** Wait until <b>m</b> is free, then acquire it. */
1954 void
1955 tor_mutex_acquire(tor_mutex_t *m)
1957 int err;
1958 tor_assert(m);
1959 err = pthread_mutex_lock(&m->mutex);
1960 if (PREDICT_UNLIKELY(err)) {
1961 log_err(LD_GENERAL, "Error %d locking a mutex.", err);
1962 tor_fragile_assert();
1965 /** Release the lock <b>m</b> so another thread can have it. */
1966 void
1967 tor_mutex_release(tor_mutex_t *m)
1969 int err;
1970 tor_assert(m);
1971 err = pthread_mutex_unlock(&m->mutex);
1972 if (PREDICT_UNLIKELY(err)) {
1973 log_err(LD_GENERAL, "Error %d unlocking a mutex.", err);
1974 tor_fragile_assert();
1977 /** Clean up the mutex <b>m</b> so that it no longer uses any system
1978 * resources. Does not free <b>m</b>. This function must only be called on
1979 * mutexes from tor_mutex_init(). */
1980 void
1981 tor_mutex_uninit(tor_mutex_t *m)
1983 int err;
1984 tor_assert(m);
1985 err = pthread_mutex_destroy(&m->mutex);
1986 if (PREDICT_UNLIKELY(err)) {
1987 log_err(LD_GENERAL, "Error %d destroying a mutex.", err);
1988 tor_fragile_assert();
1991 /** Return an integer representing this thread. */
1992 unsigned long
1993 tor_get_thread_id(void)
1995 union {
1996 pthread_t thr;
1997 unsigned long id;
1998 } r;
1999 r.thr = pthread_self();
2000 return r.id;
2002 #endif
2004 #ifdef TOR_IS_MULTITHREADED
2005 /** Return a newly allocated, ready-for-use mutex. */
2006 tor_mutex_t *
2007 tor_mutex_new(void)
2009 tor_mutex_t *m = tor_malloc_zero(sizeof(tor_mutex_t));
2010 tor_mutex_init(m);
2011 return m;
2013 /** Release all storage and system resources held by <b>m</b>. */
2014 void
2015 tor_mutex_free(tor_mutex_t *m)
2017 tor_mutex_uninit(m);
2018 tor_free(m);
2020 #endif
2022 /* Conditions. */
2023 #ifdef USE_PTHREADS
2024 #if 0
2025 /** Cross-platform condition implementation. */
2026 struct tor_cond_t {
2027 pthread_cond_t cond;
2029 /** Return a newly allocated condition, with nobody waiting on it. */
2030 tor_cond_t *
2031 tor_cond_new(void)
2033 tor_cond_t *cond = tor_malloc_zero(sizeof(tor_cond_t));
2034 if (pthread_cond_init(&cond->cond, NULL)) {
2035 tor_free(cond);
2036 return NULL;
2038 return cond;
2040 /** Release all resources held by <b>cond</b>. */
2041 void
2042 tor_cond_free(tor_cond_t *cond)
2044 tor_assert(cond);
2045 if (pthread_cond_destroy(&cond->cond)) {
2046 log_warn(LD_GENERAL,"Error freeing condition: %s", strerror(errno));
2047 return;
2049 tor_free(cond);
2051 /** Wait until one of the tor_cond_signal functions is called on <b>cond</b>.
2052 * All waiters on the condition must wait holding the same <b>mutex</b>.
2053 * Returns 0 on success, negative on failure. */
2055 tor_cond_wait(tor_cond_t *cond, tor_mutex_t *mutex)
2057 return pthread_cond_wait(&cond->cond, &mutex->mutex) ? -1 : 0;
2059 /** Wake up one of the waiters on <b>cond</b>. */
2060 void
2061 tor_cond_signal_one(tor_cond_t *cond)
2063 pthread_cond_signal(&cond->cond);
2065 /** Wake up all of the waiters on <b>cond</b>. */
2066 void
2067 tor_cond_signal_all(tor_cond_t *cond)
2069 pthread_cond_broadcast(&cond->cond);
2071 #endif
2072 /** Set up common structures for use by threading. */
2073 void
2074 tor_threads_init(void)
2076 if (!threads_initialized) {
2077 pthread_mutexattr_init(&attr_reentrant);
2078 pthread_mutexattr_settype(&attr_reentrant, PTHREAD_MUTEX_RECURSIVE);
2079 threads_initialized = 1;
2080 set_main_thread();
2083 #elif defined(USE_WIN32_THREADS)
2084 #if 0
2085 static DWORD cond_event_tls_index;
2086 struct tor_cond_t {
2087 CRITICAL_SECTION mutex;
2088 smartlist_t *events;
2090 tor_cond_t *
2091 tor_cond_new(void)
2093 tor_cond_t *cond = tor_malloc_zero(sizeof(tor_cond_t));
2094 InitializeCriticalSection(&cond->mutex);
2095 cond->events = smartlist_create();
2096 return cond;
2098 void
2099 tor_cond_free(tor_cond_t *cond)
2101 tor_assert(cond);
2102 DeleteCriticalSection(&cond->mutex);
2103 /* XXXX notify? */
2104 smartlist_free(cond->events);
2105 tor_free(cond);
2108 tor_cond_wait(tor_cond_t *cond, tor_mutex_t *mutex)
2110 HANDLE event;
2111 int r;
2112 tor_assert(cond);
2113 tor_assert(mutex);
2114 event = TlsGetValue(cond_event_tls_index);
2115 if (!event) {
2116 event = CreateEvent(0, FALSE, FALSE, NULL);
2117 TlsSetValue(cond_event_tls_index, event);
2119 EnterCriticalSection(&cond->mutex);
2121 tor_assert(WaitForSingleObject(event, 0) == WAIT_TIMEOUT);
2122 tor_assert(!smartlist_isin(cond->events, event));
2123 smartlist_add(cond->events, event);
2125 LeaveCriticalSection(&cond->mutex);
2127 tor_mutex_release(mutex);
2128 r = WaitForSingleObject(event, INFINITE);
2129 tor_mutex_acquire(mutex);
2131 switch (r) {
2132 case WAIT_OBJECT_0: /* we got the mutex normally. */
2133 break;
2134 case WAIT_ABANDONED: /* holding thread exited. */
2135 case WAIT_TIMEOUT: /* Should never happen. */
2136 tor_assert(0);
2137 break;
2138 case WAIT_FAILED:
2139 log_warn(LD_GENERAL, "Failed to acquire mutex: %d",(int) GetLastError());
2141 return 0;
2143 void
2144 tor_cond_signal_one(tor_cond_t *cond)
2146 HANDLE event;
2147 tor_assert(cond);
2149 EnterCriticalSection(&cond->mutex);
2151 if ((event = smartlist_pop_last(cond->events)))
2152 SetEvent(event);
2154 LeaveCriticalSection(&cond->mutex);
2156 void
2157 tor_cond_signal_all(tor_cond_t *cond)
2159 tor_assert(cond);
2161 EnterCriticalSection(&cond->mutex);
2162 SMARTLIST_FOREACH(cond->events, HANDLE, event, SetEvent(event));
2163 smartlist_clear(cond->events);
2164 LeaveCriticalSection(&cond->mutex);
2166 #endif
2167 void
2168 tor_threads_init(void)
2170 #if 0
2171 cond_event_tls_index = TlsAlloc();
2172 #endif
2173 set_main_thread();
2175 #endif
2177 /** Identity of the "main" thread */
2178 static unsigned long main_thread_id = -1;
2180 /** Start considering the current thread to be the 'main thread'. This has
2181 * no effect on anything besides in_main_thread(). */
2182 void
2183 set_main_thread(void)
2185 main_thread_id = tor_get_thread_id();
2187 /** Return true iff called from the main thread. */
2189 in_main_thread(void)
2191 return main_thread_id == tor_get_thread_id();
2195 * On Windows, WSAEWOULDBLOCK is not always correct: when you see it,
2196 * you need to ask the socket for its actual errno. Also, you need to
2197 * get your errors from WSAGetLastError, not errno. (If you supply a
2198 * socket of -1, we check WSAGetLastError, but don't correct
2199 * WSAEWOULDBLOCKs.)
2201 * The upshot of all of this is that when a socket call fails, you
2202 * should call tor_socket_errno <em>at most once</em> on the failing
2203 * socket to get the error.
2205 #if defined(MS_WINDOWS)
2207 tor_socket_errno(int sock)
2209 int optval, optvallen=sizeof(optval);
2210 int err = WSAGetLastError();
2211 if (err == WSAEWOULDBLOCK && sock >= 0) {
2212 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval, &optvallen))
2213 return err;
2214 if (optval)
2215 return optval;
2217 return err;
2219 #endif
2221 #if defined(MS_WINDOWS)
2222 #define E(code, s) { code, (s " [" #code " ]") }
2223 struct { int code; const char *msg; } windows_socket_errors[] = {
2224 E(WSAEINTR, "Interrupted function call"),
2225 E(WSAEACCES, "Permission denied"),
2226 E(WSAEFAULT, "Bad address"),
2227 E(WSAEINVAL, "Invalid argument"),
2228 E(WSAEMFILE, "Too many open files"),
2229 E(WSAEWOULDBLOCK, "Resource temporarily unavailable"),
2230 E(WSAEINPROGRESS, "Operation now in progress"),
2231 E(WSAEALREADY, "Operation already in progress"),
2232 E(WSAENOTSOCK, "Socket operation on nonsocket"),
2233 E(WSAEDESTADDRREQ, "Destination address required"),
2234 E(WSAEMSGSIZE, "Message too long"),
2235 E(WSAEPROTOTYPE, "Protocol wrong for socket"),
2236 E(WSAENOPROTOOPT, "Bad protocol option"),
2237 E(WSAEPROTONOSUPPORT, "Protocol not supported"),
2238 E(WSAESOCKTNOSUPPORT, "Socket type not supported"),
2239 /* What's the difference between NOTSUPP and NOSUPPORT? :) */
2240 E(WSAEOPNOTSUPP, "Operation not supported"),
2241 E(WSAEPFNOSUPPORT, "Protocol family not supported"),
2242 E(WSAEAFNOSUPPORT, "Address family not supported by protocol family"),
2243 E(WSAEADDRINUSE, "Address already in use"),
2244 E(WSAEADDRNOTAVAIL, "Cannot assign requested address"),
2245 E(WSAENETDOWN, "Network is down"),
2246 E(WSAENETUNREACH, "Network is unreachable"),
2247 E(WSAENETRESET, "Network dropped connection on reset"),
2248 E(WSAECONNABORTED, "Software caused connection abort"),
2249 E(WSAECONNRESET, "Connection reset by peer"),
2250 E(WSAENOBUFS, "No buffer space available"),
2251 E(WSAEISCONN, "Socket is already connected"),
2252 E(WSAENOTCONN, "Socket is not connected"),
2253 E(WSAESHUTDOWN, "Cannot send after socket shutdown"),
2254 E(WSAETIMEDOUT, "Connection timed out"),
2255 E(WSAECONNREFUSED, "Connection refused"),
2256 E(WSAEHOSTDOWN, "Host is down"),
2257 E(WSAEHOSTUNREACH, "No route to host"),
2258 E(WSAEPROCLIM, "Too many processes"),
2259 /* Yes, some of these start with WSA, not WSAE. No, I don't know why. */
2260 E(WSASYSNOTREADY, "Network subsystem is unavailable"),
2261 E(WSAVERNOTSUPPORTED, "Winsock.dll out of range"),
2262 E(WSANOTINITIALISED, "Successful WSAStartup not yet performed"),
2263 E(WSAEDISCON, "Graceful shutdown now in progress"),
2264 #ifdef WSATYPE_NOT_FOUND
2265 E(WSATYPE_NOT_FOUND, "Class type not found"),
2266 #endif
2267 E(WSAHOST_NOT_FOUND, "Host not found"),
2268 E(WSATRY_AGAIN, "Nonauthoritative host not found"),
2269 E(WSANO_RECOVERY, "This is a nonrecoverable error"),
2270 E(WSANO_DATA, "Valid name, no data record of requested type)"),
2272 /* There are some more error codes whose numeric values are marked
2273 * <b>OS dependent</b>. They start with WSA_, apparently for the same
2274 * reason that practitioners of some craft traditions deliberately
2275 * introduce imperfections into their baskets and rugs "to allow the
2276 * evil spirits to escape." If we catch them, then our binaries
2277 * might not report consistent results across versions of Windows.
2278 * Thus, I'm going to let them all fall through.
2280 { -1, NULL },
2282 /** There does not seem to be a strerror equivalent for Winsock errors.
2283 * Naturally, we have to roll our own.
2285 const char *
2286 tor_socket_strerror(int e)
2288 int i;
2289 for (i=0; windows_socket_errors[i].code >= 0; ++i) {
2290 if (e == windows_socket_errors[i].code)
2291 return windows_socket_errors[i].msg;
2293 return strerror(e);
2295 #endif
2297 /** Called before we make any calls to network-related functions.
2298 * (Some operating systems require their network libraries to be
2299 * initialized.) */
2301 network_init(void)
2303 #ifdef MS_WINDOWS
2304 /* This silly exercise is necessary before windows will allow
2305 * gethostbyname to work. */
2306 WSADATA WSAData;
2307 int r;
2308 r = WSAStartup(0x101,&WSAData);
2309 if (r) {
2310 log_warn(LD_NET,"Error initializing windows network layer: code was %d",r);
2311 return -1;
2313 /* WSAData.iMaxSockets might show the max sockets we're allowed to use.
2314 * We might use it to complain if we're trying to be a server but have
2315 * too few sockets available. */
2316 #endif
2317 return 0;
2320 #ifdef MS_WINDOWS
2321 /** Return a newly allocated string describing the windows system error code
2322 * <b>err</b>. Note that error codes are different from errno. Error codes
2323 * come from GetLastError() when a winapi call fails. errno is set only when
2324 * ANSI functions fail. Whee. */
2325 char *
2326 format_win32_error(DWORD err)
2328 LPVOID str = NULL;
2329 char *result;
2331 /* Somebody once decided that this interface was better than strerror(). */
2332 FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
2333 FORMAT_MESSAGE_FROM_SYSTEM |
2334 FORMAT_MESSAGE_IGNORE_INSERTS,
2335 NULL, err,
2336 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
2337 (LPTSTR) &str,
2338 0, NULL);
2340 if (str) {
2341 result = tor_strdup((char*)str);
2342 LocalFree(str); /* LocalFree != free() */
2343 } else {
2344 result = tor_strdup("<unformattable error>");
2346 return result;
2348 #endif