Cache control file
[tor/appveyor.git] / src / common / compat.c
blob693fca70ea4b907df2e546d802469040b79d0470
1 /* Copyright (c) 2003-2004, Roger Dingledine
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2017, 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_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 #define COMPAT_PRIVATE
16 #include "compat.h"
18 #ifdef _WIN32
19 #include <winsock2.h>
20 #include <windows.h>
21 #include <sys/locking.h>
22 #endif
24 #ifdef HAVE_UNAME
25 #include <sys/utsname.h>
26 #endif
27 #ifdef HAVE_SYS_TYPES_H
28 #include <sys/types.h>
29 #endif
30 #ifdef HAVE_SYS_SYSCTL_H
31 #include <sys/sysctl.h>
32 #endif
33 #ifdef HAVE_SYS_STAT_H
34 #include <sys/stat.h>
35 #endif
36 #ifdef HAVE_UTIME_H
37 #include <utime.h>
38 #endif
39 #ifdef HAVE_SYS_UTIME_H
40 #include <sys/utime.h>
41 #endif
42 #ifdef HAVE_UNISTD_H
43 #include <unistd.h>
44 #endif
45 #ifdef HAVE_SYS_FCNTL_H
46 #include <sys/fcntl.h>
47 #endif
48 #ifdef HAVE_PWD_H
49 #include <pwd.h>
50 #endif
51 #ifdef HAVE_GRP_H
52 #include <grp.h>
53 #endif
54 #ifdef HAVE_FCNTL_H
55 #include <fcntl.h>
56 #endif
57 #ifdef HAVE_ERRNO_H
58 #include <errno.h>
59 #endif
60 #ifdef HAVE_ARPA_INET_H
61 #include <arpa/inet.h>
62 #endif
63 #ifdef HAVE_CRT_EXTERNS_H
64 #include <crt_externs.h>
65 #endif
66 #ifdef HAVE_SYS_STATVFS_H
67 #include <sys/statvfs.h>
68 #endif
69 #ifdef HAVE_SYS_CAPABILITY_H
70 #include <sys/capability.h>
71 #endif
73 #ifdef _WIN32
74 #include <conio.h>
75 #include <wchar.h>
76 /* Some mingw headers lack these. :p */
77 #if defined(HAVE_DECL__GETWCH) && !HAVE_DECL__GETWCH
78 wint_t _getwch(void);
79 #endif
80 #ifndef WEOF
81 #define WEOF (wchar_t)(0xFFFF)
82 #endif
83 #if defined(HAVE_DECL_SECUREZEROMEMORY) && !HAVE_DECL_SECUREZEROMEMORY
84 static inline void
85 SecureZeroMemory(PVOID ptr, SIZE_T cnt)
87 volatile char *vcptr = (volatile char*)ptr;
88 while (cnt--)
89 *vcptr++ = 0;
91 #endif /* defined(HAVE_DECL_SECUREZEROMEMORY) && !HAVE_DECL_SECUREZEROMEMORY */
92 #elif defined(HAVE_READPASSPHRASE_H)
93 #include <readpassphrase.h>
94 #else
95 #include "tor_readpassphrase.h"
96 #endif /* defined(_WIN32) || ... */
98 /* Includes for the process attaching prevention */
99 #if defined(HAVE_SYS_PRCTL_H) && defined(__linux__)
100 /* Only use the linux prctl; the IRIX prctl is totally different */
101 #include <sys/prctl.h>
102 #elif defined(__APPLE__)
103 #include <sys/ptrace.h>
104 #endif /* defined(HAVE_SYS_PRCTL_H) && defined(__linux__) || ... */
106 #ifdef HAVE_NETDB_H
107 #include <netdb.h>
108 #endif
109 #ifdef HAVE_SYS_PARAM_H
110 #include <sys/param.h> /* FreeBSD needs this to know what version it is */
111 #endif
112 #include <stdio.h>
113 #include <stdlib.h>
114 #include <assert.h>
115 #ifdef HAVE_SIGNAL_H
116 #include <signal.h>
117 #endif
118 #ifdef HAVE_MMAP
119 #include <sys/mman.h>
120 #endif
121 #ifdef HAVE_SYS_SYSLIMITS_H
122 #include <sys/syslimits.h>
123 #endif
124 #ifdef HAVE_SYS_FILE_H
125 #include <sys/file.h>
126 #endif
128 #include "torlog.h"
129 #include "util.h"
130 #include "container.h"
131 #include "address.h"
132 #include "sandbox.h"
134 /* Inline the strl functions if the platform doesn't have them. */
135 #ifndef HAVE_STRLCPY
136 #include "strlcpy.c"
137 #endif
138 #ifndef HAVE_STRLCAT
139 #include "strlcat.c"
140 #endif
142 /* When set_max_file_descriptors() is called, update this with the max file
143 * descriptor value so we can use it to check the limit when opening a new
144 * socket. Default value is what Debian sets as the default hard limit. */
145 static int max_sockets = 1024;
147 /** As open(path, flags, mode), but return an fd with the close-on-exec mode
148 * set. */
150 tor_open_cloexec(const char *path, int flags, unsigned mode)
152 int fd;
153 const char *p = sandbox_intern_string(path);
154 #ifdef O_CLOEXEC
155 fd = open(p, flags|O_CLOEXEC, mode);
156 if (fd >= 0)
157 return fd;
158 /* If we got an error, see if it is EINVAL. EINVAL might indicate that,
159 * even though we were built on a system with O_CLOEXEC support, we
160 * are running on one without. */
161 if (errno != EINVAL)
162 return -1;
163 #endif /* defined(O_CLOEXEC) */
165 log_debug(LD_FS, "Opening %s with flags %x", p, flags);
166 fd = open(p, flags, mode);
167 #ifdef FD_CLOEXEC
168 if (fd >= 0) {
169 if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1) {
170 log_warn(LD_FS,"Couldn't set FD_CLOEXEC: %s", strerror(errno));
171 close(fd);
172 return -1;
175 #endif /* defined(FD_CLOEXEC) */
176 return fd;
179 /** As fopen(path,mode), but ensures that the O_CLOEXEC bit is set on the
180 * underlying file handle. */
181 FILE *
182 tor_fopen_cloexec(const char *path, const char *mode)
184 FILE *result = fopen(path, mode);
185 #ifdef FD_CLOEXEC
186 if (result != NULL) {
187 if (fcntl(fileno(result), F_SETFD, FD_CLOEXEC) == -1) {
188 log_warn(LD_FS,"Couldn't set FD_CLOEXEC: %s", strerror(errno));
189 fclose(result);
190 return NULL;
193 #endif /* defined(FD_CLOEXEC) */
194 return result;
197 /** As rename(), but work correctly with the sandbox. */
199 tor_rename(const char *path_old, const char *path_new)
201 log_debug(LD_FS, "Renaming %s to %s", path_old, path_new);
202 return rename(sandbox_intern_string(path_old),
203 sandbox_intern_string(path_new));
206 #if defined(HAVE_MMAP) || defined(RUNNING_DOXYGEN)
207 /** Try to create a memory mapping for <b>filename</b> and return it. On
208 * failure, return NULL. Sets errno properly, using ERANGE to mean
209 * "empty file". Must only be called on trusted Tor-owned files, as changing
210 * the underlying file's size causes unspecified behavior. */
211 tor_mmap_t *
212 tor_mmap_file(const char *filename)
214 int fd; /* router file */
215 char *string;
216 int result;
217 tor_mmap_t *res;
218 size_t size, filesize;
219 struct stat st;
221 tor_assert(filename);
223 fd = tor_open_cloexec(filename, O_RDONLY, 0);
224 if (fd<0) {
225 int save_errno = errno;
226 int severity = (errno == ENOENT) ? LOG_INFO : LOG_WARN;
227 log_fn(severity, LD_FS,"Could not open \"%s\" for mmap(): %s",filename,
228 strerror(errno));
229 errno = save_errno;
230 return NULL;
233 /* Get the size of the file */
234 result = fstat(fd, &st);
235 if (result != 0) {
236 int save_errno = errno;
237 log_warn(LD_FS,
238 "Couldn't fstat opened descriptor for \"%s\" during mmap: %s",
239 filename, strerror(errno));
240 close(fd);
241 errno = save_errno;
242 return NULL;
244 size = filesize = (size_t)(st.st_size);
246 if (st.st_size > SSIZE_T_CEILING || (off_t)size < st.st_size) {
247 log_warn(LD_FS, "File \"%s\" is too large. Ignoring.",filename);
248 errno = EFBIG;
249 close(fd);
250 return NULL;
252 if (!size) {
253 /* Zero-length file. If we call mmap on it, it will succeed but
254 * return NULL, and bad things will happen. So just fail. */
255 log_info(LD_FS,"File \"%s\" is empty. Ignoring.",filename);
256 errno = ERANGE;
257 close(fd);
258 return NULL;
261 string = mmap(0, size, PROT_READ, MAP_PRIVATE, fd, 0);
262 close(fd);
263 if (string == MAP_FAILED) {
264 int save_errno = errno;
265 log_warn(LD_FS,"Could not mmap file \"%s\": %s", filename,
266 strerror(errno));
267 errno = save_errno;
268 return NULL;
271 res = tor_malloc_zero(sizeof(tor_mmap_t));
272 res->data = string;
273 res->size = filesize;
274 res->mapping_size = size;
276 return res;
278 /** Release storage held for a memory mapping; returns 0 on success,
279 * or -1 on failure (and logs a warning). */
281 tor_munmap_file(tor_mmap_t *handle)
283 int res;
285 if (handle == NULL)
286 return 0;
288 res = munmap((char*)handle->data, handle->mapping_size);
289 if (res == 0) {
290 /* munmap() succeeded */
291 tor_free(handle);
292 } else {
293 log_warn(LD_FS, "Failed to munmap() in tor_munmap_file(): %s",
294 strerror(errno));
295 res = -1;
298 return res;
300 #elif defined(_WIN32)
301 tor_mmap_t *
302 tor_mmap_file(const char *filename)
304 TCHAR tfilename[MAX_PATH]= {0};
305 tor_mmap_t *res = tor_malloc_zero(sizeof(tor_mmap_t));
306 int empty = 0;
307 HANDLE file_handle = INVALID_HANDLE_VALUE;
308 DWORD size_low, size_high;
309 uint64_t real_size;
310 res->mmap_handle = NULL;
311 #ifdef UNICODE
312 mbstowcs(tfilename,filename,MAX_PATH);
313 #else
314 strlcpy(tfilename,filename,MAX_PATH);
315 #endif
316 file_handle = CreateFile(tfilename,
317 GENERIC_READ, FILE_SHARE_READ,
318 NULL,
319 OPEN_EXISTING,
320 FILE_ATTRIBUTE_NORMAL,
323 if (file_handle == INVALID_HANDLE_VALUE)
324 goto win_err;
326 size_low = GetFileSize(file_handle, &size_high);
328 if (size_low == INVALID_FILE_SIZE && GetLastError() != NO_ERROR) {
329 log_warn(LD_FS,"Error getting size of \"%s\".",filename);
330 goto win_err;
332 if (size_low == 0 && size_high == 0) {
333 log_info(LD_FS,"File \"%s\" is empty. Ignoring.",filename);
334 empty = 1;
335 goto err;
337 real_size = (((uint64_t)size_high)<<32) | size_low;
338 if (real_size > SIZE_MAX) {
339 log_warn(LD_FS,"File \"%s\" is too big to map; not trying.",filename);
340 goto err;
342 res->size = real_size;
344 res->mmap_handle = CreateFileMapping(file_handle,
345 NULL,
346 PAGE_READONLY,
347 size_high,
348 size_low,
349 NULL);
350 if (res->mmap_handle == NULL)
351 goto win_err;
352 res->data = (char*) MapViewOfFile(res->mmap_handle,
353 FILE_MAP_READ,
354 0, 0, 0);
355 if (!res->data)
356 goto win_err;
358 CloseHandle(file_handle);
359 return res;
360 win_err: {
361 DWORD e = GetLastError();
362 int severity = (e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND) ?
363 LOG_INFO : LOG_WARN;
364 char *msg = format_win32_error(e);
365 log_fn(severity, LD_FS, "Couldn't mmap file \"%s\": %s", filename, msg);
366 tor_free(msg);
367 if (e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND)
368 errno = ENOENT;
369 else
370 errno = EINVAL;
372 err:
373 if (empty)
374 errno = ERANGE;
375 if (file_handle != INVALID_HANDLE_VALUE)
376 CloseHandle(file_handle);
377 tor_munmap_file(res);
378 return NULL;
381 /* Unmap the file, and return 0 for success or -1 for failure */
383 tor_munmap_file(tor_mmap_t *handle)
385 if (handle == NULL)
386 return 0;
388 if (handle->data) {
389 /* This is an ugly cast, but without it, "data" in struct tor_mmap_t would
390 have to be redefined as non-const. */
391 BOOL ok = UnmapViewOfFile( (LPVOID) handle->data);
392 if (!ok) {
393 log_warn(LD_FS, "Failed to UnmapViewOfFile() in tor_munmap_file(): %d",
394 (int)GetLastError());
398 if (handle->mmap_handle != NULL)
399 CloseHandle(handle->mmap_handle);
400 tor_free(handle);
402 return 0;
404 #else
405 #error "cannot implement tor_mmap_file"
406 #endif /* defined(HAVE_MMAP) || ... || ... */
408 /** Replacement for snprintf. Differs from platform snprintf in two
409 * ways: First, always NUL-terminates its output. Second, always
410 * returns -1 if the result is truncated. (Note that this return
411 * behavior does <i>not</i> conform to C99; it just happens to be
412 * easier to emulate "return -1" with conformant implementations than
413 * it is to emulate "return number that would be written" with
414 * non-conformant implementations.) */
416 tor_snprintf(char *str, size_t size, const char *format, ...)
418 va_list ap;
419 int r;
420 va_start(ap,format);
421 r = tor_vsnprintf(str,size,format,ap);
422 va_end(ap);
423 return r;
426 /** Replacement for vsnprintf; behavior differs as tor_snprintf differs from
427 * snprintf.
430 tor_vsnprintf(char *str, size_t size, const char *format, va_list args)
432 int r;
433 if (size == 0)
434 return -1; /* no place for the NUL */
435 if (size > SIZE_T_CEILING)
436 return -1;
437 #ifdef _WIN32
438 r = _vsnprintf(str, size, format, args);
439 #else
440 r = vsnprintf(str, size, format, args);
441 #endif
442 str[size-1] = '\0';
443 if (r < 0 || r >= (ssize_t)size)
444 return -1;
445 return r;
449 * Portable asprintf implementation. Does a printf() into a newly malloc'd
450 * string. Sets *<b>strp</b> to this string, and returns its length (not
451 * including the terminating NUL character).
453 * You can treat this function as if its implementation were something like
454 <pre>
455 char buf[_INFINITY_];
456 tor_snprintf(buf, sizeof(buf), fmt, args);
457 *strp = tor_strdup(buf);
458 return strlen(*strp):
459 </pre>
460 * Where _INFINITY_ is an imaginary constant so big that any string can fit
461 * into it.
464 tor_asprintf(char **strp, const char *fmt, ...)
466 int r;
467 va_list args;
468 va_start(args, fmt);
469 r = tor_vasprintf(strp, fmt, args);
470 va_end(args);
471 if (!*strp || r < 0) {
472 /* LCOV_EXCL_START */
473 log_err(LD_BUG, "Internal error in asprintf");
474 tor_assert(0);
475 /* LCOV_EXCL_STOP */
477 return r;
481 * Portable vasprintf implementation. Does a printf() into a newly malloc'd
482 * string. Differs from regular vasprintf in the same ways that
483 * tor_asprintf() differs from regular asprintf.
486 tor_vasprintf(char **strp, const char *fmt, va_list args)
488 /* use a temporary variable in case *strp is in args. */
489 char *strp_tmp=NULL;
490 #ifdef HAVE_VASPRINTF
491 /* If the platform gives us one, use it. */
492 int r = vasprintf(&strp_tmp, fmt, args);
493 if (r < 0)
494 *strp = NULL;
495 else
496 *strp = strp_tmp;
497 return r;
498 #elif defined(HAVE__VSCPRINTF)
499 /* On Windows, _vsnprintf won't tell us the length of the string if it
500 * overflows, so we need to use _vcsprintf to tell how much to allocate */
501 int len, r;
502 va_list tmp_args;
503 va_copy(tmp_args, args);
504 len = _vscprintf(fmt, tmp_args);
505 va_end(tmp_args);
506 if (len < 0) {
507 *strp = NULL;
508 return -1;
510 strp_tmp = tor_malloc(len + 1);
511 r = _vsnprintf(strp_tmp, len+1, fmt, args);
512 if (r != len) {
513 tor_free(strp_tmp);
514 *strp = NULL;
515 return -1;
517 *strp = strp_tmp;
518 return len;
519 #else
520 /* Everywhere else, we have a decent vsnprintf that tells us how many
521 * characters we need. We give it a try on a short buffer first, since
522 * it might be nice to avoid the second vsnprintf call.
524 char buf[128];
525 int len, r;
526 va_list tmp_args;
527 va_copy(tmp_args, args);
528 /* vsnprintf() was properly checked but tor_vsnprintf() available so
529 * why not use it? */
530 len = tor_vsnprintf(buf, sizeof(buf), fmt, tmp_args);
531 va_end(tmp_args);
532 if (len < (int)sizeof(buf)) {
533 *strp = tor_strdup(buf);
534 return len;
536 strp_tmp = tor_malloc(len+1);
537 /* use of tor_vsnprintf() will ensure string is null terminated */
538 r = tor_vsnprintf(strp_tmp, len+1, fmt, args);
539 if (r != len) {
540 tor_free(strp_tmp);
541 *strp = NULL;
542 return -1;
544 *strp = strp_tmp;
545 return len;
546 #endif /* defined(HAVE_VASPRINTF) || ... */
549 /** Given <b>hlen</b> bytes at <b>haystack</b> and <b>nlen</b> bytes at
550 * <b>needle</b>, return a pointer to the first occurrence of the needle
551 * within the haystack, or NULL if there is no such occurrence.
553 * This function is <em>not</em> timing-safe.
555 * Requires that <b>nlen</b> be greater than zero.
557 const void *
558 tor_memmem(const void *_haystack, size_t hlen,
559 const void *_needle, size_t nlen)
561 #if defined(HAVE_MEMMEM) && (!defined(__GNUC__) || __GNUC__ >= 2)
562 tor_assert(nlen);
563 return memmem(_haystack, hlen, _needle, nlen);
564 #else
565 /* This isn't as fast as the GLIBC implementation, but it doesn't need to
566 * be. */
567 const char *p, *last_possible_start;
568 const char *haystack = (const char*)_haystack;
569 const char *needle = (const char*)_needle;
570 char first;
571 tor_assert(nlen);
573 if (nlen > hlen)
574 return NULL;
576 p = haystack;
577 /* Last position at which the needle could start. */
578 last_possible_start = haystack + hlen - nlen;
579 first = *(const char*)needle;
580 while ((p = memchr(p, first, last_possible_start + 1 - p))) {
581 if (fast_memeq(p, needle, nlen))
582 return p;
583 if (++p > last_possible_start) {
584 /* This comparison shouldn't be necessary, since if p was previously
585 * equal to last_possible_start, the next memchr call would be
586 * "memchr(p, first, 0)", which will return NULL. But it clarifies the
587 * logic. */
588 return NULL;
591 return NULL;
592 #endif /* defined(HAVE_MEMMEM) && (!defined(__GNUC__) || __GNUC__ >= 2) */
596 * Tables to implement ctypes-replacement TOR_IS*() functions. Each table
597 * has 256 bits to look up whether a character is in some set or not. This
598 * fails on non-ASCII platforms, but it is hard to find a platform whose
599 * character set is not a superset of ASCII nowadays. */
601 /**@{*/
602 const uint32_t TOR_ISALPHA_TABLE[8] =
603 { 0, 0, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
604 const uint32_t TOR_ISALNUM_TABLE[8] =
605 { 0, 0x3ff0000, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
606 const uint32_t TOR_ISSPACE_TABLE[8] = { 0x3e00, 0x1, 0, 0, 0, 0, 0, 0 };
607 const uint32_t TOR_ISXDIGIT_TABLE[8] =
608 { 0, 0x3ff0000, 0x7e, 0x7e, 0, 0, 0, 0 };
609 const uint32_t TOR_ISDIGIT_TABLE[8] = { 0, 0x3ff0000, 0, 0, 0, 0, 0, 0 };
610 const uint32_t TOR_ISPRINT_TABLE[8] =
611 { 0, 0xffffffff, 0xffffffff, 0x7fffffff, 0, 0, 0, 0x0 };
612 const uint32_t TOR_ISUPPER_TABLE[8] = { 0, 0, 0x7fffffe, 0, 0, 0, 0, 0 };
613 const uint32_t TOR_ISLOWER_TABLE[8] = { 0, 0, 0, 0x7fffffe, 0, 0, 0, 0 };
615 /** Upper-casing and lowercasing tables to map characters to upper/lowercase
616 * equivalents. Used by tor_toupper() and tor_tolower(). */
617 /**@{*/
618 const uint8_t TOR_TOUPPER_TABLE[256] = {
619 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
620 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
621 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
622 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
623 64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
624 80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
625 96,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
626 80,81,82,83,84,85,86,87,88,89,90,123,124,125,126,127,
627 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
628 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
629 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
630 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
631 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
632 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
633 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
634 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
636 const uint8_t TOR_TOLOWER_TABLE[256] = {
637 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
638 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
639 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
640 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
641 64,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
642 112,113,114,115,116,117,118,119,120,121,122,91,92,93,94,95,
643 96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
644 112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
645 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
646 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
647 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
648 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
649 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
650 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
651 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
652 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
654 /**@}*/
656 /** Helper for tor_strtok_r_impl: Advances cp past all characters in
657 * <b>sep</b>, and returns its new value. */
658 static char *
659 strtok_helper(char *cp, const char *sep)
661 if (sep[1]) {
662 while (*cp && strchr(sep, *cp))
663 ++cp;
664 } else {
665 while (*cp && *cp == *sep)
666 ++cp;
668 return cp;
671 /** Implementation of strtok_r for platforms whose coders haven't figured out
672 * how to write one. Hey, retrograde libc developers! You can use this code
673 * here for free! */
674 char *
675 tor_strtok_r_impl(char *str, const char *sep, char **lasts)
677 char *cp, *start;
678 tor_assert(*sep);
679 if (str) {
680 str = strtok_helper(str, sep);
681 if (!*str)
682 return NULL;
683 start = cp = *lasts = str;
684 } else if (!*lasts || !**lasts) {
685 return NULL;
686 } else {
687 start = cp = *lasts;
690 if (sep[1]) {
691 while (*cp && !strchr(sep, *cp))
692 ++cp;
693 } else {
694 cp = strchr(cp, *sep);
697 if (!cp || !*cp) {
698 *lasts = NULL;
699 } else {
700 *cp++ = '\0';
701 *lasts = strtok_helper(cp, sep);
703 return start;
706 #ifdef _WIN32
707 /** Take a filename and return a pointer to its final element. This
708 * function is called on __FILE__ to fix a MSVC nit where __FILE__
709 * contains the full path to the file. This is bad, because it
710 * confuses users to find the home directory of the person who
711 * compiled the binary in their warning messages.
713 const char *
714 tor_fix_source_file(const char *fname)
716 const char *cp1, *cp2, *r;
717 cp1 = strrchr(fname, '/');
718 cp2 = strrchr(fname, '\\');
719 if (cp1 && cp2) {
720 r = (cp1<cp2)?(cp2+1):(cp1+1);
721 } else if (cp1) {
722 r = cp1+1;
723 } else if (cp2) {
724 r = cp2+1;
725 } else {
726 r = fname;
728 return r;
730 #endif /* defined(_WIN32) */
733 * Read a 16-bit value beginning at <b>cp</b>. Equivalent to
734 * *(uint16_t*)(cp), but will not cause segfaults on platforms that forbid
735 * unaligned memory access.
737 uint16_t
738 get_uint16(const void *cp)
740 uint16_t v;
741 memcpy(&v,cp,2);
742 return v;
745 * Read a 32-bit value beginning at <b>cp</b>. Equivalent to
746 * *(uint32_t*)(cp), but will not cause segfaults on platforms that forbid
747 * unaligned memory access.
749 uint32_t
750 get_uint32(const void *cp)
752 uint32_t v;
753 memcpy(&v,cp,4);
754 return v;
757 * Read a 64-bit value beginning at <b>cp</b>. Equivalent to
758 * *(uint64_t*)(cp), but will not cause segfaults on platforms that forbid
759 * unaligned memory access.
761 uint64_t
762 get_uint64(const void *cp)
764 uint64_t v;
765 memcpy(&v,cp,8);
766 return v;
770 * Set a 16-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
771 * *(uint16_t*)(cp) = v, but will not cause segfaults on platforms that forbid
772 * unaligned memory access. */
773 void
774 set_uint16(void *cp, uint16_t v)
776 memcpy(cp,&v,2);
779 * Set a 32-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
780 * *(uint32_t*)(cp) = v, but will not cause segfaults on platforms that forbid
781 * unaligned memory access. */
782 void
783 set_uint32(void *cp, uint32_t v)
785 memcpy(cp,&v,4);
788 * Set a 64-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
789 * *(uint64_t*)(cp) = v, but will not cause segfaults on platforms that forbid
790 * unaligned memory access. */
791 void
792 set_uint64(void *cp, uint64_t v)
794 memcpy(cp,&v,8);
798 * Rename the file <b>from</b> to the file <b>to</b>. On Unix, this is
799 * the same as rename(2). On windows, this removes <b>to</b> first if
800 * it already exists.
801 * Returns 0 on success. Returns -1 and sets errno on failure.
804 replace_file(const char *from, const char *to)
806 #ifndef _WIN32
807 return tor_rename(from, to);
808 #else
809 switch (file_status(to))
811 case FN_NOENT:
812 break;
813 case FN_FILE:
814 case FN_EMPTY:
815 if (unlink(to)) return -1;
816 break;
817 case FN_ERROR:
818 return -1;
819 case FN_DIR:
820 errno = EISDIR;
821 return -1;
823 return tor_rename(from,to);
824 #endif /* !defined(_WIN32) */
827 /** Change <b>fname</b>'s modification time to now. */
829 touch_file(const char *fname)
831 if (utime(fname, NULL)!=0)
832 return -1;
833 return 0;
836 /** Represents a lockfile on which we hold the lock. */
837 struct tor_lockfile_t {
838 /** Name of the file */
839 char *filename;
840 /** File descriptor used to hold the file open */
841 int fd;
844 /** Try to get a lock on the lockfile <b>filename</b>, creating it as
845 * necessary. If someone else has the lock and <b>blocking</b> is true,
846 * wait until the lock is available. Otherwise return immediately whether
847 * we succeeded or not.
849 * Set *<b>locked_out</b> to true if somebody else had the lock, and to false
850 * otherwise.
852 * Return a <b>tor_lockfile_t</b> on success, NULL on failure.
854 * (Implementation note: because we need to fall back to fcntl on some
855 * platforms, these locks are per-process, not per-thread. If you want
856 * to do in-process locking, use tor_mutex_t like a normal person.
857 * On Windows, when <b>blocking</b> is true, the maximum time that
858 * is actually waited is 10 seconds, after which NULL is returned
859 * and <b>locked_out</b> is set to 1.)
861 tor_lockfile_t *
862 tor_lockfile_lock(const char *filename, int blocking, int *locked_out)
864 tor_lockfile_t *result;
865 int fd;
866 *locked_out = 0;
868 log_info(LD_FS, "Locking \"%s\"", filename);
869 fd = tor_open_cloexec(filename, O_RDWR|O_CREAT|O_TRUNC, 0600);
870 if (fd < 0) {
871 log_warn(LD_FS,"Couldn't open \"%s\" for locking: %s", filename,
872 strerror(errno));
873 return NULL;
876 #ifdef _WIN32
877 _lseek(fd, 0, SEEK_SET);
878 if (_locking(fd, blocking ? _LK_LOCK : _LK_NBLCK, 1) < 0) {
879 if (errno != EACCES && errno != EDEADLOCK)
880 log_warn(LD_FS,"Couldn't lock \"%s\": %s", filename, strerror(errno));
881 else
882 *locked_out = 1;
883 close(fd);
884 return NULL;
886 #elif defined(HAVE_FLOCK)
887 if (flock(fd, LOCK_EX|(blocking ? 0 : LOCK_NB)) < 0) {
888 if (errno != EWOULDBLOCK)
889 log_warn(LD_FS,"Couldn't lock \"%s\": %s", filename, strerror(errno));
890 else
891 *locked_out = 1;
892 close(fd);
893 return NULL;
895 #else
897 struct flock lock;
898 memset(&lock, 0, sizeof(lock));
899 lock.l_type = F_WRLCK;
900 lock.l_whence = SEEK_SET;
901 if (fcntl(fd, blocking ? F_SETLKW : F_SETLK, &lock) < 0) {
902 if (errno != EACCES && errno != EAGAIN)
903 log_warn(LD_FS, "Couldn't lock \"%s\": %s", filename, strerror(errno));
904 else
905 *locked_out = 1;
906 close(fd);
907 return NULL;
910 #endif /* defined(_WIN32) || ... */
912 result = tor_malloc(sizeof(tor_lockfile_t));
913 result->filename = tor_strdup(filename);
914 result->fd = fd;
915 return result;
918 /** Release the lock held as <b>lockfile</b>. */
919 void
920 tor_lockfile_unlock(tor_lockfile_t *lockfile)
922 tor_assert(lockfile);
924 log_info(LD_FS, "Unlocking \"%s\"", lockfile->filename);
925 #ifdef _WIN32
926 _lseek(lockfile->fd, 0, SEEK_SET);
927 if (_locking(lockfile->fd, _LK_UNLCK, 1) < 0) {
928 log_warn(LD_FS,"Error unlocking \"%s\": %s", lockfile->filename,
929 strerror(errno));
931 #elif defined(HAVE_FLOCK)
932 if (flock(lockfile->fd, LOCK_UN) < 0) {
933 log_warn(LD_FS, "Error unlocking \"%s\": %s", lockfile->filename,
934 strerror(errno));
936 #else
937 /* Closing the lockfile is sufficient. */
938 #endif /* defined(_WIN32) || ... */
940 close(lockfile->fd);
941 lockfile->fd = -1;
942 tor_free(lockfile->filename);
943 tor_free(lockfile);
946 /** @{ */
947 /** Some old versions of Unix didn't define constants for these values,
948 * and instead expect you to say 0, 1, or 2. */
949 #ifndef SEEK_SET
950 #define SEEK_SET 0
951 #endif
952 #ifndef SEEK_CUR
953 #define SEEK_CUR 1
954 #endif
955 #ifndef SEEK_END
956 #define SEEK_END 2
957 #endif
958 /** @} */
960 /** Return the position of <b>fd</b> with respect to the start of the file. */
961 off_t
962 tor_fd_getpos(int fd)
964 #ifdef _WIN32
965 return (off_t) _lseek(fd, 0, SEEK_CUR);
966 #else
967 return (off_t) lseek(fd, 0, SEEK_CUR);
968 #endif
971 /** Move <b>fd</b> to the end of the file. Return -1 on error, 0 on success.
972 * If the file is a pipe, do nothing and succeed.
975 tor_fd_seekend(int fd)
977 #ifdef _WIN32
978 return _lseek(fd, 0, SEEK_END) < 0 ? -1 : 0;
979 #else
980 off_t rc = lseek(fd, 0, SEEK_END) < 0 ? -1 : 0;
981 #ifdef ESPIPE
982 /* If we get an error and ESPIPE, then it's a pipe or a socket of a fifo:
983 * no need to worry. */
984 if (rc < 0 && errno == ESPIPE)
985 rc = 0;
986 #endif /* defined(ESPIPE) */
987 return (rc < 0) ? -1 : 0;
988 #endif /* defined(_WIN32) */
991 /** Move <b>fd</b> to position <b>pos</b> in the file. Return -1 on error, 0
992 * on success. */
994 tor_fd_setpos(int fd, off_t pos)
996 #ifdef _WIN32
997 return _lseek(fd, pos, SEEK_SET) < 0 ? -1 : 0;
998 #else
999 return lseek(fd, pos, SEEK_SET) < 0 ? -1 : 0;
1000 #endif
1003 /** Replacement for ftruncate(fd, 0): move to the front of the file and remove
1004 * all the rest of the file. Return -1 on error, 0 on success. */
1006 tor_ftruncate(int fd)
1008 /* Rumor has it that some versions of ftruncate do not move the file pointer.
1010 if (tor_fd_setpos(fd, 0) < 0)
1011 return -1;
1013 #ifdef _WIN32
1014 return _chsize(fd, 0);
1015 #else
1016 return ftruncate(fd, 0);
1017 #endif
1020 #undef DEBUG_SOCKET_COUNTING
1021 #ifdef DEBUG_SOCKET_COUNTING
1022 /** A bitarray of all fds that should be passed to tor_socket_close(). Only
1023 * used if DEBUG_SOCKET_COUNTING is defined. */
1024 static bitarray_t *open_sockets = NULL;
1025 /** The size of <b>open_sockets</b>, in bits. */
1026 static int max_socket = -1;
1027 #endif /* defined(DEBUG_SOCKET_COUNTING) */
1029 /** Count of number of sockets currently open. (Undercounts sockets opened by
1030 * eventdns and libevent.) */
1031 static int n_sockets_open = 0;
1033 /** Mutex to protect open_sockets, max_socket, and n_sockets_open. */
1034 static tor_mutex_t *socket_accounting_mutex = NULL;
1036 /** Helper: acquire the socket accounting lock. */
1037 static inline void
1038 socket_accounting_lock(void)
1040 if (PREDICT_UNLIKELY(!socket_accounting_mutex))
1041 socket_accounting_mutex = tor_mutex_new();
1042 tor_mutex_acquire(socket_accounting_mutex);
1045 /** Helper: release the socket accounting lock. */
1046 static inline void
1047 socket_accounting_unlock(void)
1049 tor_mutex_release(socket_accounting_mutex);
1052 /** As close(), but guaranteed to work for sockets across platforms (including
1053 * Windows, where close()ing a socket doesn't work. Returns 0 on success and
1054 * the socket error code on failure. */
1056 tor_close_socket_simple(tor_socket_t s)
1058 int r = 0;
1060 /* On Windows, you have to call close() on fds returned by open(),
1061 * and closesocket() on fds returned by socket(). On Unix, everything
1062 * gets close()'d. We abstract this difference by always using
1063 * tor_close_socket to close sockets, and always using close() on
1064 * files.
1066 #if defined(_WIN32)
1067 r = closesocket(s);
1068 #else
1069 r = close(s);
1070 #endif
1072 if (r != 0) {
1073 int err = tor_socket_errno(-1);
1074 log_info(LD_NET, "Close returned an error: %s", tor_socket_strerror(err));
1075 return err;
1078 return r;
1081 /** As tor_close_socket_simple(), but keeps track of the number
1082 * of open sockets. Returns 0 on success, -1 on failure. */
1083 MOCK_IMPL(int,
1084 tor_close_socket,(tor_socket_t s))
1086 int r = tor_close_socket_simple(s);
1088 socket_accounting_lock();
1089 #ifdef DEBUG_SOCKET_COUNTING
1090 if (s > max_socket || ! bitarray_is_set(open_sockets, s)) {
1091 log_warn(LD_BUG, "Closing a socket (%d) that wasn't returned by tor_open_"
1092 "socket(), or that was already closed or something.", s);
1093 } else {
1094 tor_assert(open_sockets && s <= max_socket);
1095 bitarray_clear(open_sockets, s);
1097 #endif /* defined(DEBUG_SOCKET_COUNTING) */
1098 if (r == 0) {
1099 --n_sockets_open;
1100 } else {
1101 #ifdef _WIN32
1102 if (r != WSAENOTSOCK)
1103 --n_sockets_open;
1104 #else
1105 if (r != EBADF)
1106 --n_sockets_open; // LCOV_EXCL_LINE -- EIO and EINTR too hard to force.
1107 #endif /* defined(_WIN32) */
1108 r = -1;
1111 tor_assert_nonfatal(n_sockets_open >= 0);
1112 socket_accounting_unlock();
1113 return r;
1116 /** @{ */
1117 #ifdef DEBUG_SOCKET_COUNTING
1118 /** Helper: if DEBUG_SOCKET_COUNTING is enabled, remember that <b>s</b> is
1119 * now an open socket. */
1120 static inline void
1121 mark_socket_open(tor_socket_t s)
1123 /* XXXX This bitarray business will NOT work on windows: sockets aren't
1124 small ints there. */
1125 if (s > max_socket) {
1126 if (max_socket == -1) {
1127 open_sockets = bitarray_init_zero(s+128);
1128 max_socket = s+128;
1129 } else {
1130 open_sockets = bitarray_expand(open_sockets, max_socket, s+128);
1131 max_socket = s+128;
1134 if (bitarray_is_set(open_sockets, s)) {
1135 log_warn(LD_BUG, "I thought that %d was already open, but socket() just "
1136 "gave it to me!", s);
1138 bitarray_set(open_sockets, s);
1140 #else /* !(defined(DEBUG_SOCKET_COUNTING)) */
1141 #define mark_socket_open(s) ((void) (s))
1142 #endif /* defined(DEBUG_SOCKET_COUNTING) */
1143 /** @} */
1145 /** As socket(), but counts the number of open sockets. */
1146 MOCK_IMPL(tor_socket_t,
1147 tor_open_socket,(int domain, int type, int protocol))
1149 return tor_open_socket_with_extensions(domain, type, protocol, 1, 0);
1152 /** Mockable wrapper for connect(). */
1153 MOCK_IMPL(tor_socket_t,
1154 tor_connect_socket,(tor_socket_t sock, const struct sockaddr *address,
1155 socklen_t address_len))
1157 return connect(sock,address,address_len);
1160 /** As socket(), but creates a nonblocking socket and
1161 * counts the number of open sockets. */
1162 tor_socket_t
1163 tor_open_socket_nonblocking(int domain, int type, int protocol)
1165 return tor_open_socket_with_extensions(domain, type, protocol, 1, 1);
1168 /** As socket(), but counts the number of open sockets and handles
1169 * socket creation with either of SOCK_CLOEXEC and SOCK_NONBLOCK specified.
1170 * <b>cloexec</b> and <b>nonblock</b> should be either 0 or 1 to indicate
1171 * if the corresponding extension should be used.*/
1172 tor_socket_t
1173 tor_open_socket_with_extensions(int domain, int type, int protocol,
1174 int cloexec, int nonblock)
1176 tor_socket_t s;
1178 /* We are about to create a new file descriptor so make sure we have
1179 * enough of them. */
1180 if (get_n_open_sockets() >= max_sockets - 1) {
1181 #ifdef _WIN32
1182 WSASetLastError(WSAEMFILE);
1183 #else
1184 errno = EMFILE;
1185 #endif
1186 return TOR_INVALID_SOCKET;
1189 #if defined(SOCK_CLOEXEC) && defined(SOCK_NONBLOCK)
1190 int ext_flags = (cloexec ? SOCK_CLOEXEC : 0) |
1191 (nonblock ? SOCK_NONBLOCK : 0);
1192 s = socket(domain, type|ext_flags, protocol);
1193 if (SOCKET_OK(s))
1194 goto socket_ok;
1195 /* If we got an error, see if it is EINVAL. EINVAL might indicate that,
1196 * even though we were built on a system with SOCK_CLOEXEC and SOCK_NONBLOCK
1197 * support, we are running on one without. */
1198 if (errno != EINVAL)
1199 return s;
1200 #endif /* defined(SOCK_CLOEXEC) && defined(SOCK_NONBLOCK) */
1202 s = socket(domain, type, protocol);
1203 if (! SOCKET_OK(s))
1204 return s;
1206 #if defined(FD_CLOEXEC)
1207 if (cloexec) {
1208 if (fcntl(s, F_SETFD, FD_CLOEXEC) == -1) {
1209 log_warn(LD_FS,"Couldn't set FD_CLOEXEC: %s", strerror(errno));
1210 tor_close_socket_simple(s);
1211 return TOR_INVALID_SOCKET;
1214 #else /* !(defined(FD_CLOEXEC)) */
1215 (void)cloexec;
1216 #endif /* defined(FD_CLOEXEC) */
1218 if (nonblock) {
1219 if (set_socket_nonblocking(s) == -1) {
1220 tor_close_socket_simple(s);
1221 return TOR_INVALID_SOCKET;
1225 goto socket_ok; /* So that socket_ok will not be unused. */
1227 socket_ok:
1228 tor_take_socket_ownership(s);
1229 return s;
1233 * For socket accounting: remember that we are the owner of the socket
1234 * <b>s</b>. This will prevent us from overallocating sockets, and prevent us
1235 * from asserting later when we close the socket <b>s</b>.
1237 void
1238 tor_take_socket_ownership(tor_socket_t s)
1240 socket_accounting_lock();
1241 ++n_sockets_open;
1242 mark_socket_open(s);
1243 socket_accounting_unlock();
1246 /** As accept(), but counts the number of open sockets. */
1247 tor_socket_t
1248 tor_accept_socket(tor_socket_t sockfd, struct sockaddr *addr, socklen_t *len)
1250 return tor_accept_socket_with_extensions(sockfd, addr, len, 1, 0);
1253 /** As accept(), but returns a nonblocking socket and
1254 * counts the number of open sockets. */
1255 tor_socket_t
1256 tor_accept_socket_nonblocking(tor_socket_t sockfd, struct sockaddr *addr,
1257 socklen_t *len)
1259 return tor_accept_socket_with_extensions(sockfd, addr, len, 1, 1);
1262 /** As accept(), but counts the number of open sockets and handles
1263 * socket creation with either of SOCK_CLOEXEC and SOCK_NONBLOCK specified.
1264 * <b>cloexec</b> and <b>nonblock</b> should be either 0 or 1 to indicate
1265 * if the corresponding extension should be used.*/
1266 tor_socket_t
1267 tor_accept_socket_with_extensions(tor_socket_t sockfd, struct sockaddr *addr,
1268 socklen_t *len, int cloexec, int nonblock)
1270 tor_socket_t s;
1272 /* We are about to create a new file descriptor so make sure we have
1273 * enough of them. */
1274 if (get_n_open_sockets() >= max_sockets - 1) {
1275 #ifdef _WIN32
1276 WSASetLastError(WSAEMFILE);
1277 #else
1278 errno = EMFILE;
1279 #endif
1280 return TOR_INVALID_SOCKET;
1283 #if defined(HAVE_ACCEPT4) && defined(SOCK_CLOEXEC) \
1284 && defined(SOCK_NONBLOCK)
1285 int ext_flags = (cloexec ? SOCK_CLOEXEC : 0) |
1286 (nonblock ? SOCK_NONBLOCK : 0);
1287 s = accept4(sockfd, addr, len, ext_flags);
1288 if (SOCKET_OK(s))
1289 goto socket_ok;
1290 /* If we got an error, see if it is ENOSYS. ENOSYS indicates that,
1291 * even though we were built on a system with accept4 support, we
1292 * are running on one without. Also, check for EINVAL, which indicates that
1293 * we are missing SOCK_CLOEXEC/SOCK_NONBLOCK support. */
1294 if (errno != EINVAL && errno != ENOSYS)
1295 return s;
1296 #endif /* defined(HAVE_ACCEPT4) && defined(SOCK_CLOEXEC) ... */
1298 s = accept(sockfd, addr, len);
1299 if (!SOCKET_OK(s))
1300 return s;
1302 #if defined(FD_CLOEXEC)
1303 if (cloexec) {
1304 if (fcntl(s, F_SETFD, FD_CLOEXEC) == -1) {
1305 log_warn(LD_NET, "Couldn't set FD_CLOEXEC: %s", strerror(errno));
1306 tor_close_socket_simple(s);
1307 return TOR_INVALID_SOCKET;
1310 #else /* !(defined(FD_CLOEXEC)) */
1311 (void)cloexec;
1312 #endif /* defined(FD_CLOEXEC) */
1314 if (nonblock) {
1315 if (set_socket_nonblocking(s) == -1) {
1316 tor_close_socket_simple(s);
1317 return TOR_INVALID_SOCKET;
1321 goto socket_ok; /* So that socket_ok will not be unused. */
1323 socket_ok:
1324 tor_take_socket_ownership(s);
1325 return s;
1328 /** Return the number of sockets we currently have opened. */
1330 get_n_open_sockets(void)
1332 int n;
1333 socket_accounting_lock();
1334 n = n_sockets_open;
1335 socket_accounting_unlock();
1336 return n;
1339 /** Mockable wrapper for getsockname(). */
1340 MOCK_IMPL(int,
1341 tor_getsockname,(tor_socket_t sock, struct sockaddr *address,
1342 socklen_t *address_len))
1344 return getsockname(sock, address, address_len);
1348 * Find the local address associated with the socket <b>sock</b>, and
1349 * place it in *<b>addr_out</b>. Return 0 on success, -1 on failure.
1351 * (As tor_getsockname, but instead places the result in a tor_addr_t.) */
1353 tor_addr_from_getsockname(tor_addr_t *addr_out, tor_socket_t sock)
1355 struct sockaddr_storage ss;
1356 socklen_t ss_len = sizeof(ss);
1357 memset(&ss, 0, sizeof(ss));
1359 if (tor_getsockname(sock, (struct sockaddr *) &ss, &ss_len) < 0)
1360 return -1;
1362 return tor_addr_from_sockaddr(addr_out, (struct sockaddr *)&ss, NULL);
1365 /** Turn <b>socket</b> into a nonblocking socket. Return 0 on success, -1
1366 * on failure.
1369 set_socket_nonblocking(tor_socket_t sock)
1371 #if defined(_WIN32)
1372 unsigned long nonblocking = 1;
1373 ioctlsocket(sock, FIONBIO, (unsigned long*) &nonblocking);
1374 #else
1375 int flags;
1377 flags = fcntl(sock, F_GETFL, 0);
1378 if (flags == -1) {
1379 log_warn(LD_NET, "Couldn't get file status flags: %s", strerror(errno));
1380 return -1;
1382 flags |= O_NONBLOCK;
1383 if (fcntl(sock, F_SETFL, flags) == -1) {
1384 log_warn(LD_NET, "Couldn't set file status flags: %s", strerror(errno));
1385 return -1;
1387 #endif /* defined(_WIN32) */
1389 return 0;
1393 * Allocate a pair of connected sockets. (Like socketpair(family,
1394 * type,protocol,fd), but works on systems that don't have
1395 * socketpair.)
1397 * Currently, only (AF_UNIX, SOCK_STREAM, 0) sockets are supported.
1399 * Note that on systems without socketpair, this call will fail if
1400 * localhost is inaccessible (for example, if the networking
1401 * stack is down). And even if it succeeds, the socket pair will not
1402 * be able to read while localhost is down later (the socket pair may
1403 * even close, depending on OS-specific timeouts).
1405 * Returns 0 on success and -errno on failure; do not rely on the value
1406 * of errno or WSAGetLastError().
1408 /* It would be nicer just to set errno, but that won't work for windows. */
1410 tor_socketpair(int family, int type, int protocol, tor_socket_t fd[2])
1412 //don't use win32 socketpairs (they are always bad)
1413 #if defined(HAVE_SOCKETPAIR) && !defined(_WIN32)
1414 int r;
1416 #ifdef SOCK_CLOEXEC
1417 r = socketpair(family, type|SOCK_CLOEXEC, protocol, fd);
1418 if (r == 0)
1419 goto sockets_ok;
1420 /* If we got an error, see if it is EINVAL. EINVAL might indicate that,
1421 * even though we were built on a system with SOCK_CLOEXEC support, we
1422 * are running on one without. */
1423 if (errno != EINVAL)
1424 return -errno;
1425 #endif /* defined(SOCK_CLOEXEC) */
1427 r = socketpair(family, type, protocol, fd);
1428 if (r < 0)
1429 return -errno;
1431 #if defined(FD_CLOEXEC)
1432 if (SOCKET_OK(fd[0])) {
1433 r = fcntl(fd[0], F_SETFD, FD_CLOEXEC);
1434 if (r == -1) {
1435 close(fd[0]);
1436 close(fd[1]);
1437 return -errno;
1440 if (SOCKET_OK(fd[1])) {
1441 r = fcntl(fd[1], F_SETFD, FD_CLOEXEC);
1442 if (r == -1) {
1443 close(fd[0]);
1444 close(fd[1]);
1445 return -errno;
1448 #endif /* defined(FD_CLOEXEC) */
1449 goto sockets_ok; /* So that sockets_ok will not be unused. */
1451 sockets_ok:
1452 socket_accounting_lock();
1453 if (SOCKET_OK(fd[0])) {
1454 ++n_sockets_open;
1455 mark_socket_open(fd[0]);
1457 if (SOCKET_OK(fd[1])) {
1458 ++n_sockets_open;
1459 mark_socket_open(fd[1]);
1461 socket_accounting_unlock();
1463 return 0;
1464 #else /* !(defined(HAVE_SOCKETPAIR) && !defined(_WIN32)) */
1465 return tor_ersatz_socketpair(family, type, protocol, fd);
1466 #endif /* defined(HAVE_SOCKETPAIR) && !defined(_WIN32) */
1469 #ifdef NEED_ERSATZ_SOCKETPAIR
1471 static inline socklen_t
1472 SIZEOF_SOCKADDR(int domain)
1474 switch (domain) {
1475 case AF_INET:
1476 return sizeof(struct sockaddr_in);
1477 case AF_INET6:
1478 return sizeof(struct sockaddr_in6);
1479 default:
1480 return 0;
1485 * Helper used to implement socketpair on systems that lack it, by
1486 * making a direct connection to localhost.
1488 STATIC int
1489 tor_ersatz_socketpair(int family, int type, int protocol, tor_socket_t fd[2])
1491 /* This socketpair does not work when localhost is down. So
1492 * it's really not the same thing at all. But it's close enough
1493 * for now, and really, when localhost is down sometimes, we
1494 * have other problems too.
1496 tor_socket_t listener = TOR_INVALID_SOCKET;
1497 tor_socket_t connector = TOR_INVALID_SOCKET;
1498 tor_socket_t acceptor = TOR_INVALID_SOCKET;
1499 tor_addr_t listen_tor_addr;
1500 struct sockaddr_storage connect_addr_ss, listen_addr_ss;
1501 struct sockaddr *listen_addr = (struct sockaddr *) &listen_addr_ss;
1502 uint16_t listen_port = 0;
1503 tor_addr_t connect_tor_addr;
1504 uint16_t connect_port = 0;
1505 struct sockaddr *connect_addr = (struct sockaddr *) &connect_addr_ss;
1506 socklen_t size;
1507 int saved_errno = -1;
1508 int ersatz_domain = AF_INET;
1510 memset(&connect_tor_addr, 0, sizeof(connect_tor_addr));
1511 memset(&connect_addr_ss, 0, sizeof(connect_addr_ss));
1512 memset(&listen_tor_addr, 0, sizeof(listen_tor_addr));
1513 memset(&listen_addr_ss, 0, sizeof(listen_addr_ss));
1515 if (protocol
1516 #ifdef AF_UNIX
1517 || family != AF_UNIX
1518 #endif
1520 #ifdef _WIN32
1521 return -WSAEAFNOSUPPORT;
1522 #else
1523 return -EAFNOSUPPORT;
1524 #endif
1526 if (!fd) {
1527 return -EINVAL;
1530 listener = tor_open_socket(ersatz_domain, type, 0);
1531 if (!SOCKET_OK(listener)) {
1532 int first_errno = tor_socket_errno(-1);
1533 if (first_errno == SOCK_ERRNO(EPROTONOSUPPORT)
1534 && ersatz_domain == AF_INET) {
1535 /* Assume we're on an IPv6-only system */
1536 ersatz_domain = AF_INET6;
1537 listener = tor_open_socket(ersatz_domain, type, 0);
1538 if (!SOCKET_OK(listener)) {
1539 /* Keep the previous behaviour, which was to return the IPv4 error.
1540 * (This may be less informative on IPv6-only systems.)
1541 * XX/teor - is there a better way to decide which errno to return?
1542 * (I doubt we care much either way, once there is an error.)
1544 return -first_errno;
1548 /* If there is no 127.0.0.1 or ::1, this will and must fail. Otherwise, we
1549 * risk exposing a socketpair on a routable IP address. (Some BSD jails
1550 * use a routable address for localhost. Fortunately, they have the real
1551 * AF_UNIX socketpair.) */
1552 if (ersatz_domain == AF_INET) {
1553 tor_addr_from_ipv4h(&listen_tor_addr, INADDR_LOOPBACK);
1554 } else {
1555 tor_addr_parse(&listen_tor_addr, "[::1]");
1557 tor_assert(tor_addr_is_loopback(&listen_tor_addr));
1558 size = tor_addr_to_sockaddr(&listen_tor_addr,
1559 0 /* kernel chooses port. */,
1560 listen_addr,
1561 sizeof(listen_addr_ss));
1562 if (bind(listener, listen_addr, size) == -1)
1563 goto tidy_up_and_fail;
1564 if (listen(listener, 1) == -1)
1565 goto tidy_up_and_fail;
1567 connector = tor_open_socket(ersatz_domain, type, 0);
1568 if (!SOCKET_OK(connector))
1569 goto tidy_up_and_fail;
1570 /* We want to find out the port number to connect to. */
1571 size = sizeof(connect_addr_ss);
1572 if (getsockname(listener, connect_addr, &size) == -1)
1573 goto tidy_up_and_fail;
1574 if (size != SIZEOF_SOCKADDR (connect_addr->sa_family))
1575 goto abort_tidy_up_and_fail;
1576 if (connect(connector, connect_addr, size) == -1)
1577 goto tidy_up_and_fail;
1579 size = sizeof(listen_addr_ss);
1580 acceptor = tor_accept_socket(listener, listen_addr, &size);
1581 if (!SOCKET_OK(acceptor))
1582 goto tidy_up_and_fail;
1583 if (size != SIZEOF_SOCKADDR(listen_addr->sa_family))
1584 goto abort_tidy_up_and_fail;
1585 /* Now check we are talking to ourself by matching port and host on the
1586 two sockets. */
1587 if (getsockname(connector, connect_addr, &size) == -1)
1588 goto tidy_up_and_fail;
1589 /* Set *_tor_addr and *_port to the address and port that was used */
1590 tor_addr_from_sockaddr(&listen_tor_addr, listen_addr, &listen_port);
1591 tor_addr_from_sockaddr(&connect_tor_addr, connect_addr, &connect_port);
1592 if (size != SIZEOF_SOCKADDR (connect_addr->sa_family)
1593 || tor_addr_compare(&listen_tor_addr, &connect_tor_addr, CMP_SEMANTIC)
1594 || listen_port != connect_port) {
1595 goto abort_tidy_up_and_fail;
1597 tor_close_socket(listener);
1598 fd[0] = connector;
1599 fd[1] = acceptor;
1601 return 0;
1603 abort_tidy_up_and_fail:
1604 #ifdef _WIN32
1605 saved_errno = WSAECONNABORTED;
1606 #else
1607 saved_errno = ECONNABORTED; /* I hope this is portable and appropriate. */
1608 #endif
1609 tidy_up_and_fail:
1610 if (saved_errno < 0)
1611 saved_errno = errno;
1612 if (SOCKET_OK(listener))
1613 tor_close_socket(listener);
1614 if (SOCKET_OK(connector))
1615 tor_close_socket(connector);
1616 if (SOCKET_OK(acceptor))
1617 tor_close_socket(acceptor);
1618 return -saved_errno;
1621 #undef SIZEOF_SOCKADDR
1623 #endif /* defined(NEED_ERSATZ_SOCKETPAIR) */
1625 /* Return the maximum number of allowed sockets. */
1627 get_max_sockets(void)
1629 return max_sockets;
1632 /** Number of extra file descriptors to keep in reserve beyond those that we
1633 * tell Tor it's allowed to use. */
1634 #define ULIMIT_BUFFER 32 /* keep 32 extra fd's beyond ConnLimit_ */
1636 /** Learn the maximum allowed number of file descriptors, and tell the
1637 * system we want to use up to that number. (Some systems have a low soft
1638 * limit, and let us set it higher.) We compute this by finding the largest
1639 * number that we can use.
1641 * If the limit is below the reserved file descriptor value (ULIMIT_BUFFER),
1642 * return -1 and <b>max_out</b> is untouched.
1644 * If we can't find a number greater than or equal to <b>limit</b>, then we
1645 * fail by returning -1 and <b>max_out</b> is untouched.
1647 * If we are unable to set the limit value because of setrlimit() failing,
1648 * return 0 and <b>max_out</b> is set to the current maximum value returned
1649 * by getrlimit().
1651 * Otherwise, return 0 and store the maximum we found inside <b>max_out</b>
1652 * and set <b>max_sockets</b> with that value as well.*/
1654 set_max_file_descriptors(rlim_t limit, int *max_out)
1656 if (limit < ULIMIT_BUFFER) {
1657 log_warn(LD_CONFIG,
1658 "ConnLimit must be at least %d. Failing.", ULIMIT_BUFFER);
1659 return -1;
1662 /* Define some maximum connections values for systems where we cannot
1663 * automatically determine a limit. Re Cygwin, see
1664 * http://archives.seul.org/or/talk/Aug-2006/msg00210.html
1665 * For an iPhone, 9999 should work. For Windows and all other unknown
1666 * systems we use 15000 as the default. */
1667 #ifndef HAVE_GETRLIMIT
1668 #if defined(CYGWIN) || defined(__CYGWIN__)
1669 const char *platform = "Cygwin";
1670 const unsigned long MAX_CONNECTIONS = 3200;
1671 #elif defined(_WIN32)
1672 const char *platform = "Windows";
1673 const unsigned long MAX_CONNECTIONS = 15000;
1674 #else
1675 const char *platform = "unknown platforms with no getrlimit()";
1676 const unsigned long MAX_CONNECTIONS = 15000;
1677 #endif /* defined(CYGWIN) || defined(__CYGWIN__) || ... */
1678 log_fn(LOG_INFO, LD_NET,
1679 "This platform is missing getrlimit(). Proceeding.");
1680 if (limit > MAX_CONNECTIONS) {
1681 log_warn(LD_CONFIG,
1682 "We do not support more than %lu file descriptors "
1683 "on %s. Tried to raise to %lu.",
1684 (unsigned long)MAX_CONNECTIONS, platform, (unsigned long)limit);
1685 return -1;
1687 limit = MAX_CONNECTIONS;
1688 #else /* !(!defined(HAVE_GETRLIMIT)) */
1689 struct rlimit rlim;
1691 if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) {
1692 log_warn(LD_NET, "Could not get maximum number of file descriptors: %s",
1693 strerror(errno));
1694 return -1;
1696 if (rlim.rlim_max < limit) {
1697 log_warn(LD_CONFIG,"We need %lu file descriptors available, and we're "
1698 "limited to %lu. Please change your ulimit -n.",
1699 (unsigned long)limit, (unsigned long)rlim.rlim_max);
1700 return -1;
1703 if (rlim.rlim_max > rlim.rlim_cur) {
1704 log_info(LD_NET,"Raising max file descriptors from %lu to %lu.",
1705 (unsigned long)rlim.rlim_cur, (unsigned long)rlim.rlim_max);
1707 /* Set the current limit value so if the attempt to set the limit to the
1708 * max fails at least we'll have a valid value of maximum sockets. */
1709 *max_out = max_sockets = (int)rlim.rlim_cur - ULIMIT_BUFFER;
1710 rlim.rlim_cur = rlim.rlim_max;
1712 if (setrlimit(RLIMIT_NOFILE, &rlim) != 0) {
1713 int couldnt_set = 1;
1714 const int setrlimit_errno = errno;
1715 #ifdef OPEN_MAX
1716 uint64_t try_limit = OPEN_MAX - ULIMIT_BUFFER;
1717 if (errno == EINVAL && try_limit < (uint64_t) rlim.rlim_cur) {
1718 /* On some platforms, OPEN_MAX is the real limit, and getrlimit() is
1719 * full of nasty lies. I'm looking at you, OSX 10.5.... */
1720 rlim.rlim_cur = MIN((rlim_t) try_limit, rlim.rlim_cur);
1721 if (setrlimit(RLIMIT_NOFILE, &rlim) == 0) {
1722 if (rlim.rlim_cur < (rlim_t)limit) {
1723 log_warn(LD_CONFIG, "We are limited to %lu file descriptors by "
1724 "OPEN_MAX (%lu), and ConnLimit is %lu. Changing "
1725 "ConnLimit; sorry.",
1726 (unsigned long)try_limit, (unsigned long)OPEN_MAX,
1727 (unsigned long)limit);
1728 } else {
1729 log_info(LD_CONFIG, "Dropped connection limit to %lu based on "
1730 "OPEN_MAX (%lu); Apparently, %lu was too high and rlimit "
1731 "lied to us.",
1732 (unsigned long)try_limit, (unsigned long)OPEN_MAX,
1733 (unsigned long)rlim.rlim_max);
1735 couldnt_set = 0;
1738 #endif /* defined(OPEN_MAX) */
1739 if (couldnt_set) {
1740 log_warn(LD_CONFIG,"Couldn't set maximum number of file descriptors: %s",
1741 strerror(setrlimit_errno));
1744 /* leave some overhead for logs, etc, */
1745 limit = rlim.rlim_cur;
1746 #endif /* !defined(HAVE_GETRLIMIT) */
1748 if (limit > INT_MAX)
1749 limit = INT_MAX;
1750 tor_assert(max_out);
1751 *max_out = max_sockets = (int)limit - ULIMIT_BUFFER;
1752 return 0;
1755 #ifndef _WIN32
1756 /** Log details of current user and group credentials. Return 0 on
1757 * success. Logs and return -1 on failure.
1759 static int
1760 log_credential_status(void)
1762 /** Log level to use when describing non-error UID/GID status. */
1763 #define CREDENTIAL_LOG_LEVEL LOG_INFO
1764 /* Real, effective and saved UIDs */
1765 uid_t ruid, euid, suid;
1766 /* Read, effective and saved GIDs */
1767 gid_t rgid, egid, sgid;
1768 /* Supplementary groups */
1769 gid_t *sup_gids = NULL;
1770 int sup_gids_size;
1771 /* Number of supplementary groups */
1772 int ngids;
1774 /* log UIDs */
1775 #ifdef HAVE_GETRESUID
1776 if (getresuid(&ruid, &euid, &suid) != 0 ) {
1777 log_warn(LD_GENERAL, "Error getting changed UIDs: %s", strerror(errno));
1778 return -1;
1779 } else {
1780 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
1781 "UID is %u (real), %u (effective), %u (saved)",
1782 (unsigned)ruid, (unsigned)euid, (unsigned)suid);
1784 #else /* !(defined(HAVE_GETRESUID)) */
1785 /* getresuid is not present on MacOS X, so we can't get the saved (E)UID */
1786 ruid = getuid();
1787 euid = geteuid();
1788 (void)suid;
1790 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
1791 "UID is %u (real), %u (effective), unknown (saved)",
1792 (unsigned)ruid, (unsigned)euid);
1793 #endif /* defined(HAVE_GETRESUID) */
1795 /* log GIDs */
1796 #ifdef HAVE_GETRESGID
1797 if (getresgid(&rgid, &egid, &sgid) != 0 ) {
1798 log_warn(LD_GENERAL, "Error getting changed GIDs: %s", strerror(errno));
1799 return -1;
1800 } else {
1801 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
1802 "GID is %u (real), %u (effective), %u (saved)",
1803 (unsigned)rgid, (unsigned)egid, (unsigned)sgid);
1805 #else /* !(defined(HAVE_GETRESGID)) */
1806 /* getresgid is not present on MacOS X, so we can't get the saved (E)GID */
1807 rgid = getgid();
1808 egid = getegid();
1809 (void)sgid;
1810 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
1811 "GID is %u (real), %u (effective), unknown (saved)",
1812 (unsigned)rgid, (unsigned)egid);
1813 #endif /* defined(HAVE_GETRESGID) */
1815 /* log supplementary groups */
1816 sup_gids_size = 64;
1817 sup_gids = tor_calloc(64, sizeof(gid_t));
1818 while ((ngids = getgroups(sup_gids_size, sup_gids)) < 0 &&
1819 errno == EINVAL &&
1820 sup_gids_size < NGROUPS_MAX) {
1821 sup_gids_size *= 2;
1822 sup_gids = tor_reallocarray(sup_gids, sizeof(gid_t), sup_gids_size);
1825 if (ngids < 0) {
1826 log_warn(LD_GENERAL, "Error getting supplementary GIDs: %s",
1827 strerror(errno));
1828 tor_free(sup_gids);
1829 return -1;
1830 } else {
1831 int i, retval = 0;
1832 char *s = NULL;
1833 smartlist_t *elts = smartlist_new();
1835 for (i = 0; i<ngids; i++) {
1836 smartlist_add_asprintf(elts, "%u", (unsigned)sup_gids[i]);
1839 s = smartlist_join_strings(elts, " ", 0, NULL);
1841 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL, "Supplementary groups are: %s",s);
1843 tor_free(s);
1844 SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
1845 smartlist_free(elts);
1846 tor_free(sup_gids);
1848 return retval;
1851 return 0;
1853 #endif /* !defined(_WIN32) */
1855 #ifndef _WIN32
1856 /** Cached struct from the last getpwname() call we did successfully. */
1857 static struct passwd *passwd_cached = NULL;
1859 /** Helper: copy a struct passwd object.
1861 * We only copy the fields pw_uid, pw_gid, pw_name, pw_dir. Tor doesn't use
1862 * any others, and I don't want to run into incompatibilities.
1864 static struct passwd *
1865 tor_passwd_dup(const struct passwd *pw)
1867 struct passwd *new_pw = tor_malloc_zero(sizeof(struct passwd));
1868 if (pw->pw_name)
1869 new_pw->pw_name = tor_strdup(pw->pw_name);
1870 if (pw->pw_dir)
1871 new_pw->pw_dir = tor_strdup(pw->pw_dir);
1872 new_pw->pw_uid = pw->pw_uid;
1873 new_pw->pw_gid = pw->pw_gid;
1875 return new_pw;
1878 #define tor_passwd_free(pw) \
1879 FREE_AND_NULL(struct passwd, tor_passwd_free_, (pw))
1881 /** Helper: free one of our cached 'struct passwd' values. */
1882 static void
1883 tor_passwd_free_(struct passwd *pw)
1885 if (!pw)
1886 return;
1888 tor_free(pw->pw_name);
1889 tor_free(pw->pw_dir);
1890 tor_free(pw);
1893 /** Wrapper around getpwnam() that caches result. Used so that we don't need
1894 * to give the sandbox access to /etc/passwd.
1896 * The following fields alone will definitely be copied in the output: pw_uid,
1897 * pw_gid, pw_name, pw_dir. Other fields are not present in cached values.
1899 * When called with a NULL argument, this function clears storage associated
1900 * with static variables it uses.
1902 const struct passwd *
1903 tor_getpwnam(const char *username)
1905 struct passwd *pw;
1907 if (username == NULL) {
1908 tor_passwd_free(passwd_cached);
1909 passwd_cached = NULL;
1910 return NULL;
1913 if ((pw = getpwnam(username))) {
1914 tor_passwd_free(passwd_cached);
1915 passwd_cached = tor_passwd_dup(pw);
1916 log_info(LD_GENERAL, "Caching new entry %s for %s",
1917 passwd_cached->pw_name, username);
1918 return pw;
1921 /* Lookup failed */
1922 if (! passwd_cached || ! passwd_cached->pw_name)
1923 return NULL;
1925 if (! strcmp(username, passwd_cached->pw_name))
1926 return passwd_cached; // LCOV_EXCL_LINE - would need to make getpwnam flaky
1928 return NULL;
1931 /** Wrapper around getpwnam() that can use cached result from
1932 * tor_getpwnam(). Used so that we don't need to give the sandbox access to
1933 * /etc/passwd.
1935 * The following fields alone will definitely be copied in the output: pw_uid,
1936 * pw_gid, pw_name, pw_dir. Other fields are not present in cached values.
1938 const struct passwd *
1939 tor_getpwuid(uid_t uid)
1941 struct passwd *pw;
1943 if ((pw = getpwuid(uid))) {
1944 return pw;
1947 /* Lookup failed */
1948 if (! passwd_cached)
1949 return NULL;
1951 if (uid == passwd_cached->pw_uid)
1952 return passwd_cached; // LCOV_EXCL_LINE - would need to make getpwnam flaky
1954 return NULL;
1956 #endif /* !defined(_WIN32) */
1958 /** Return true iff we were compiled with capability support, and capabilities
1959 * seem to work. **/
1961 have_capability_support(void)
1963 #ifdef HAVE_LINUX_CAPABILITIES
1964 cap_t caps = cap_get_proc();
1965 if (caps == NULL)
1966 return 0;
1967 cap_free(caps);
1968 return 1;
1969 #else /* !(defined(HAVE_LINUX_CAPABILITIES)) */
1970 return 0;
1971 #endif /* defined(HAVE_LINUX_CAPABILITIES) */
1974 #ifdef HAVE_LINUX_CAPABILITIES
1975 /** Helper. Drop all capabilities but a small set, and set PR_KEEPCAPS as
1976 * appropriate.
1978 * If pre_setuid, retain only CAP_NET_BIND_SERVICE, CAP_SETUID, and
1979 * CAP_SETGID, and use PR_KEEPCAPS to ensure that capabilities persist across
1980 * setuid().
1982 * If not pre_setuid, retain only CAP_NET_BIND_SERVICE, and disable
1983 * PR_KEEPCAPS.
1985 * Return 0 on success, and -1 on failure.
1987 static int
1988 drop_capabilities(int pre_setuid)
1990 /* We keep these three capabilities, and these only, as we setuid.
1991 * After we setuid, we drop all but the first. */
1992 const cap_value_t caplist[] = {
1993 CAP_NET_BIND_SERVICE, CAP_SETUID, CAP_SETGID
1995 const char *where = pre_setuid ? "pre-setuid" : "post-setuid";
1996 const int n_effective = pre_setuid ? 3 : 1;
1997 const int n_permitted = pre_setuid ? 3 : 1;
1998 const int n_inheritable = 1;
1999 const int keepcaps = pre_setuid ? 1 : 0;
2001 /* Sets whether we keep capabilities across a setuid. */
2002 if (prctl(PR_SET_KEEPCAPS, keepcaps) < 0) {
2003 log_warn(LD_CONFIG, "Unable to call prctl() %s: %s",
2004 where, strerror(errno));
2005 return -1;
2008 cap_t caps = cap_get_proc();
2009 if (!caps) {
2010 log_warn(LD_CONFIG, "Unable to call cap_get_proc() %s: %s",
2011 where, strerror(errno));
2012 return -1;
2014 cap_clear(caps);
2016 cap_set_flag(caps, CAP_EFFECTIVE, n_effective, caplist, CAP_SET);
2017 cap_set_flag(caps, CAP_PERMITTED, n_permitted, caplist, CAP_SET);
2018 cap_set_flag(caps, CAP_INHERITABLE, n_inheritable, caplist, CAP_SET);
2020 int r = cap_set_proc(caps);
2021 cap_free(caps);
2022 if (r < 0) {
2023 log_warn(LD_CONFIG, "No permission to set capabilities %s: %s",
2024 where, strerror(errno));
2025 return -1;
2028 return 0;
2030 #endif /* defined(HAVE_LINUX_CAPABILITIES) */
2032 /** Call setuid and setgid to run as <b>user</b> and switch to their
2033 * primary group. Return 0 on success. On failure, log and return -1.
2035 * If SWITCH_ID_KEEP_BINDLOW is set in 'flags', try to use the capability
2036 * system to retain the abilitity to bind low ports.
2038 * If SWITCH_ID_WARN_IF_NO_CAPS is set in flags, also warn if we have
2039 * don't have capability support.
2042 switch_id(const char *user, const unsigned flags)
2044 #ifndef _WIN32
2045 const struct passwd *pw = NULL;
2046 uid_t old_uid;
2047 gid_t old_gid;
2048 static int have_already_switched_id = 0;
2049 const int keep_bindlow = !!(flags & SWITCH_ID_KEEP_BINDLOW);
2050 const int warn_if_no_caps = !!(flags & SWITCH_ID_WARN_IF_NO_CAPS);
2052 tor_assert(user);
2054 if (have_already_switched_id)
2055 return 0;
2057 /* Log the initial credential state */
2058 if (log_credential_status())
2059 return -1;
2061 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL, "Changing user and groups");
2063 /* Get old UID/GID to check if we changed correctly */
2064 old_uid = getuid();
2065 old_gid = getgid();
2067 /* Lookup the user and group information, if we have a problem, bail out. */
2068 pw = tor_getpwnam(user);
2069 if (pw == NULL) {
2070 log_warn(LD_CONFIG, "Error setting configured user: %s not found", user);
2071 return -1;
2074 #ifdef HAVE_LINUX_CAPABILITIES
2075 (void) warn_if_no_caps;
2076 if (keep_bindlow) {
2077 if (drop_capabilities(1))
2078 return -1;
2080 #else /* !(defined(HAVE_LINUX_CAPABILITIES)) */
2081 (void) keep_bindlow;
2082 if (warn_if_no_caps) {
2083 log_warn(LD_CONFIG, "KeepBindCapabilities set, but no capability support "
2084 "on this system.");
2086 #endif /* defined(HAVE_LINUX_CAPABILITIES) */
2088 /* Properly switch egid,gid,euid,uid here or bail out */
2089 if (setgroups(1, &pw->pw_gid)) {
2090 log_warn(LD_GENERAL, "Error setting groups to gid %d: \"%s\".",
2091 (int)pw->pw_gid, strerror(errno));
2092 if (old_uid == pw->pw_uid) {
2093 log_warn(LD_GENERAL, "Tor is already running as %s. You do not need "
2094 "the \"User\" option if you are already running as the user "
2095 "you want to be. (If you did not set the User option in your "
2096 "torrc, check whether it was specified on the command line "
2097 "by a startup script.)", user);
2098 } else {
2099 log_warn(LD_GENERAL, "If you set the \"User\" option, you must start Tor"
2100 " as root.");
2102 return -1;
2105 if (setegid(pw->pw_gid)) {
2106 log_warn(LD_GENERAL, "Error setting egid to %d: %s",
2107 (int)pw->pw_gid, strerror(errno));
2108 return -1;
2111 if (setgid(pw->pw_gid)) {
2112 log_warn(LD_GENERAL, "Error setting gid to %d: %s",
2113 (int)pw->pw_gid, strerror(errno));
2114 return -1;
2117 if (setuid(pw->pw_uid)) {
2118 log_warn(LD_GENERAL, "Error setting configured uid to %s (%d): %s",
2119 user, (int)pw->pw_uid, strerror(errno));
2120 return -1;
2123 if (seteuid(pw->pw_uid)) {
2124 log_warn(LD_GENERAL, "Error setting configured euid to %s (%d): %s",
2125 user, (int)pw->pw_uid, strerror(errno));
2126 return -1;
2129 /* This is how OpenBSD rolls:
2130 if (setgroups(1, &pw->pw_gid) || setegid(pw->pw_gid) ||
2131 setgid(pw->pw_gid) || setuid(pw->pw_uid) || seteuid(pw->pw_uid)) {
2132 setgid(pw->pw_gid) || seteuid(pw->pw_uid) || setuid(pw->pw_uid)) {
2133 log_warn(LD_GENERAL, "Error setting configured UID/GID: %s",
2134 strerror(errno));
2135 return -1;
2139 /* We've properly switched egid, gid, euid, uid, and supplementary groups if
2140 * we're here. */
2141 #ifdef HAVE_LINUX_CAPABILITIES
2142 if (keep_bindlow) {
2143 if (drop_capabilities(0))
2144 return -1;
2146 #endif /* defined(HAVE_LINUX_CAPABILITIES) */
2148 #if !defined(CYGWIN) && !defined(__CYGWIN__)
2149 /* If we tried to drop privilege to a group/user other than root, attempt to
2150 * restore root (E)(U|G)ID, and abort if the operation succeeds */
2152 /* Only check for privilege dropping if we were asked to be non-root */
2153 if (pw->pw_uid) {
2154 /* Try changing GID/EGID */
2155 if (pw->pw_gid != old_gid &&
2156 (setgid(old_gid) != -1 || setegid(old_gid) != -1)) {
2157 log_warn(LD_GENERAL, "Was able to restore group credentials even after "
2158 "switching GID: this means that the setgid code didn't work.");
2159 return -1;
2162 /* Try changing UID/EUID */
2163 if (pw->pw_uid != old_uid &&
2164 (setuid(old_uid) != -1 || seteuid(old_uid) != -1)) {
2165 log_warn(LD_GENERAL, "Was able to restore user credentials even after "
2166 "switching UID: this means that the setuid code didn't work.");
2167 return -1;
2170 #endif /* !defined(CYGWIN) && !defined(__CYGWIN__) */
2172 /* Check what really happened */
2173 if (log_credential_status()) {
2174 return -1;
2177 have_already_switched_id = 1; /* mark success so we never try again */
2179 #if defined(__linux__) && defined(HAVE_SYS_PRCTL_H) && \
2180 defined(HAVE_PRCTL) && defined(PR_SET_DUMPABLE)
2181 if (pw->pw_uid) {
2182 /* Re-enable core dumps if we're not running as root. */
2183 log_info(LD_CONFIG, "Re-enabling coredumps");
2184 if (prctl(PR_SET_DUMPABLE, 1)) {
2185 log_warn(LD_CONFIG, "Unable to re-enable coredumps: %s",strerror(errno));
2188 #endif /* defined(__linux__) && defined(HAVE_SYS_PRCTL_H) && ... */
2189 return 0;
2191 #else /* !(!defined(_WIN32)) */
2192 (void)user;
2193 (void)flags;
2195 log_warn(LD_CONFIG, "Switching users is unsupported on your OS.");
2196 return -1;
2197 #endif /* !defined(_WIN32) */
2200 /* We only use the linux prctl for now. There is no Win32 support; this may
2201 * also work on various BSD systems and Mac OS X - send testing feedback!
2203 * On recent Gnu/Linux kernels it is possible to create a system-wide policy
2204 * that will prevent non-root processes from attaching to other processes
2205 * unless they are the parent process; thus gdb can attach to programs that
2206 * they execute but they cannot attach to other processes running as the same
2207 * user. The system wide policy may be set with the sysctl
2208 * kernel.yama.ptrace_scope or by inspecting
2209 * /proc/sys/kernel/yama/ptrace_scope and it is 1 by default on Ubuntu 11.04.
2211 * This ptrace scope will be ignored on Gnu/Linux for users with
2212 * CAP_SYS_PTRACE and so it is very likely that root will still be able to
2213 * attach to the Tor process.
2215 /** Attempt to disable debugger attachment: return 1 on success, -1 on
2216 * failure, and 0 if we don't know how to try on this platform. */
2218 tor_disable_debugger_attach(void)
2220 int r = -1;
2221 log_debug(LD_CONFIG,
2222 "Attemping to disable debugger attachment to Tor for "
2223 "unprivileged users.");
2224 #if defined(__linux__) && defined(HAVE_SYS_PRCTL_H) \
2225 && defined(HAVE_PRCTL) && defined(PR_SET_DUMPABLE)
2226 #define TRIED_TO_DISABLE
2227 r = prctl(PR_SET_DUMPABLE, 0);
2228 #elif defined(__APPLE__) && defined(PT_DENY_ATTACH)
2229 #define TRIED_TO_ATTACH
2230 r = ptrace(PT_DENY_ATTACH, 0, 0, 0);
2231 #endif /* defined(__linux__) && defined(HAVE_SYS_PRCTL_H) ... || ... */
2233 // XXX: TODO - Mac OS X has dtrace and this may be disabled.
2234 // XXX: TODO - Windows probably has something similar
2235 #ifdef TRIED_TO_DISABLE
2236 if (r == 0) {
2237 log_debug(LD_CONFIG,"Debugger attachment disabled for "
2238 "unprivileged users.");
2239 return 1;
2240 } else {
2241 log_warn(LD_CONFIG, "Unable to disable debugger attaching: %s",
2242 strerror(errno));
2244 #endif /* defined(TRIED_TO_DISABLE) */
2245 #undef TRIED_TO_DISABLE
2246 return r;
2249 #ifdef HAVE_PWD_H
2250 /** Allocate and return a string containing the home directory for the
2251 * user <b>username</b>. Only works on posix-like systems. */
2252 char *
2253 get_user_homedir(const char *username)
2255 const struct passwd *pw;
2256 tor_assert(username);
2258 if (!(pw = tor_getpwnam(username))) {
2259 log_err(LD_CONFIG,"User \"%s\" not found.", username);
2260 return NULL;
2262 return tor_strdup(pw->pw_dir);
2264 #endif /* defined(HAVE_PWD_H) */
2266 /** Modify <b>fname</b> to contain the name of its parent directory. Doesn't
2267 * actually examine the filesystem; does a purely syntactic modification.
2269 * The parent of the root director is considered to be iteself.
2271 * Path separators are the forward slash (/) everywhere and additionally
2272 * the backslash (\) on Win32.
2274 * Cuts off any number of trailing path separators but otherwise ignores
2275 * them for purposes of finding the parent directory.
2277 * Returns 0 if a parent directory was successfully found, -1 otherwise (fname
2278 * did not have any path separators or only had them at the end).
2279 * */
2281 get_parent_directory(char *fname)
2283 char *cp;
2284 int at_end = 1;
2285 tor_assert(fname);
2286 #ifdef _WIN32
2287 /* If we start with, say, c:, then don't consider that the start of the path
2289 if (fname[0] && fname[1] == ':') {
2290 fname += 2;
2292 #endif /* defined(_WIN32) */
2293 /* Now we want to remove all path-separators at the end of the string,
2294 * and to remove the end of the string starting with the path separator
2295 * before the last non-path-separator. In perl, this would be
2296 * s#[/]*$##; s#/[^/]*$##;
2297 * on a unixy platform.
2299 cp = fname + strlen(fname);
2300 at_end = 1;
2301 while (--cp >= fname) {
2302 int is_sep = (*cp == '/'
2303 #ifdef _WIN32
2304 || *cp == '\\'
2305 #endif
2307 if (is_sep) {
2308 if (cp == fname) {
2309 /* This is the first separator in the file name; don't remove it! */
2310 cp[1] = '\0';
2311 return 0;
2313 *cp = '\0';
2314 if (! at_end)
2315 return 0;
2316 } else {
2317 at_end = 0;
2320 return -1;
2323 #ifndef _WIN32
2324 /** Return a newly allocated string containing the output of getcwd(). Return
2325 * NULL on failure. (We can't just use getcwd() into a PATH_MAX buffer, since
2326 * Hurd hasn't got a PATH_MAX.)
2328 static char *
2329 alloc_getcwd(void)
2331 #ifdef HAVE_GET_CURRENT_DIR_NAME
2332 /* Glibc makes this nice and simple for us. */
2333 char *cwd = get_current_dir_name();
2334 char *result = NULL;
2335 if (cwd) {
2336 /* We make a copy here, in case tor_malloc() is not malloc(). */
2337 result = tor_strdup(cwd);
2338 raw_free(cwd); // alias for free to avoid tripping check-spaces.
2340 return result;
2341 #else /* !(defined(HAVE_GET_CURRENT_DIR_NAME)) */
2342 size_t size = 1024;
2343 char *buf = NULL;
2344 char *ptr = NULL;
2346 while (ptr == NULL) {
2347 buf = tor_realloc(buf, size);
2348 ptr = getcwd(buf, size);
2350 if (ptr == NULL && errno != ERANGE) {
2351 tor_free(buf);
2352 return NULL;
2355 size *= 2;
2357 return buf;
2358 #endif /* defined(HAVE_GET_CURRENT_DIR_NAME) */
2360 #endif /* !defined(_WIN32) */
2362 /** Expand possibly relative path <b>fname</b> to an absolute path.
2363 * Return a newly allocated string, possibly equal to <b>fname</b>. */
2364 char *
2365 make_path_absolute(char *fname)
2367 #ifdef _WIN32
2368 char *absfname_malloced = _fullpath(NULL, fname, 1);
2370 /* We don't want to assume that tor_free can free a string allocated
2371 * with malloc. On failure, return fname (it's better than nothing). */
2372 char *absfname = tor_strdup(absfname_malloced ? absfname_malloced : fname);
2373 if (absfname_malloced) raw_free(absfname_malloced);
2375 return absfname;
2376 #else /* !(defined(_WIN32)) */
2377 char *absfname = NULL, *path = NULL;
2379 tor_assert(fname);
2381 if (fname[0] == '/') {
2382 absfname = tor_strdup(fname);
2383 } else {
2384 path = alloc_getcwd();
2385 if (path) {
2386 tor_asprintf(&absfname, "%s/%s", path, fname);
2387 tor_free(path);
2388 } else {
2389 /* LCOV_EXCL_START Can't make getcwd fail. */
2390 /* If getcwd failed, the best we can do here is keep using the
2391 * relative path. (Perhaps / isn't readable by this UID/GID.) */
2392 log_warn(LD_GENERAL, "Unable to find current working directory: %s",
2393 strerror(errno));
2394 absfname = tor_strdup(fname);
2395 /* LCOV_EXCL_STOP */
2398 return absfname;
2399 #endif /* defined(_WIN32) */
2402 #ifndef HAVE__NSGETENVIRON
2403 #ifndef HAVE_EXTERN_ENVIRON_DECLARED
2404 /* Some platforms declare environ under some circumstances, others don't. */
2405 #ifndef RUNNING_DOXYGEN
2406 extern char **environ;
2407 #endif
2408 #endif /* !defined(HAVE_EXTERN_ENVIRON_DECLARED) */
2409 #endif /* !defined(HAVE__NSGETENVIRON) */
2411 /** Return the current environment. This is a portable replacement for
2412 * 'environ'. */
2413 char **
2414 get_environment(void)
2416 #ifdef HAVE__NSGETENVIRON
2417 /* This is for compatibility between OSX versions. Otherwise (for example)
2418 * when we do a mostly-static build on OSX 10.7, the resulting binary won't
2419 * work on OSX 10.6. */
2420 return *_NSGetEnviron();
2421 #else /* !(defined(HAVE__NSGETENVIRON)) */
2422 return environ;
2423 #endif /* defined(HAVE__NSGETENVIRON) */
2426 /** Get name of current host and write it to <b>name</b> array, whose
2427 * length is specified by <b>namelen</b> argument. Return 0 upon
2428 * successful completion; otherwise return return -1. (Currently,
2429 * this function is merely a mockable wrapper for POSIX gethostname().)
2431 MOCK_IMPL(int,
2432 tor_gethostname,(char *name, size_t namelen))
2434 return gethostname(name,namelen);
2437 /** Set *addr to the IP address (in dotted-quad notation) stored in *str.
2438 * Return 1 on success, 0 if *str is badly formatted.
2439 * (Like inet_aton(str,addr), but works on Windows and Solaris.)
2442 tor_inet_aton(const char *str, struct in_addr* addr)
2444 unsigned a,b,c,d;
2445 char more;
2446 if (tor_sscanf(str, "%3u.%3u.%3u.%3u%c", &a,&b,&c,&d,&more) != 4)
2447 return 0;
2448 if (a > 255) return 0;
2449 if (b > 255) return 0;
2450 if (c > 255) return 0;
2451 if (d > 255) return 0;
2452 addr->s_addr = htonl((a<<24) | (b<<16) | (c<<8) | d);
2453 return 1;
2456 /** Given <b>af</b>==AF_INET and <b>src</b> a struct in_addr, or
2457 * <b>af</b>==AF_INET6 and <b>src</b> a struct in6_addr, try to format the
2458 * address and store it in the <b>len</b>-byte buffer <b>dst</b>. Returns
2459 * <b>dst</b> on success, NULL on failure.
2461 * (Like inet_ntop(af,src,dst,len), but works on platforms that don't have it:
2462 * Tor sometimes needs to format ipv6 addresses even on platforms without ipv6
2463 * support.) */
2464 const char *
2465 tor_inet_ntop(int af, const void *src, char *dst, size_t len)
2467 if (af == AF_INET) {
2468 if (tor_inet_ntoa(src, dst, len) < 0)
2469 return NULL;
2470 else
2471 return dst;
2472 } else if (af == AF_INET6) {
2473 const struct in6_addr *addr = src;
2474 char buf[64], *cp;
2475 int longestGapLen = 0, longestGapPos = -1, i,
2476 curGapPos = -1, curGapLen = 0;
2477 uint16_t words[8];
2478 for (i = 0; i < 8; ++i) {
2479 words[i] = (((uint16_t)addr->s6_addr[2*i])<<8) + addr->s6_addr[2*i+1];
2481 if (words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0 &&
2482 words[4] == 0 && ((words[5] == 0 && words[6] && words[7]) ||
2483 (words[5] == 0xffff))) {
2484 /* This is an IPv4 address. */
2485 if (words[5] == 0) {
2486 tor_snprintf(buf, sizeof(buf), "::%d.%d.%d.%d",
2487 addr->s6_addr[12], addr->s6_addr[13],
2488 addr->s6_addr[14], addr->s6_addr[15]);
2489 } else {
2490 tor_snprintf(buf, sizeof(buf), "::%x:%d.%d.%d.%d", words[5],
2491 addr->s6_addr[12], addr->s6_addr[13],
2492 addr->s6_addr[14], addr->s6_addr[15]);
2494 if ((strlen(buf) + 1) > len) /* +1 for \0 */
2495 return NULL;
2496 strlcpy(dst, buf, len);
2497 return dst;
2499 i = 0;
2500 while (i < 8) {
2501 if (words[i] == 0) {
2502 curGapPos = i++;
2503 curGapLen = 1;
2504 while (i<8 && words[i] == 0) {
2505 ++i; ++curGapLen;
2507 if (curGapLen > longestGapLen) {
2508 longestGapPos = curGapPos;
2509 longestGapLen = curGapLen;
2511 } else {
2512 ++i;
2515 if (longestGapLen<=1)
2516 longestGapPos = -1;
2518 cp = buf;
2519 for (i = 0; i < 8; ++i) {
2520 if (words[i] == 0 && longestGapPos == i) {
2521 if (i == 0)
2522 *cp++ = ':';
2523 *cp++ = ':';
2524 while (i < 8 && words[i] == 0)
2525 ++i;
2526 --i; /* to compensate for loop increment. */
2527 } else {
2528 tor_snprintf(cp, sizeof(buf)-(cp-buf), "%x", (unsigned)words[i]);
2529 cp += strlen(cp);
2530 if (i != 7)
2531 *cp++ = ':';
2534 *cp = '\0';
2535 if ((strlen(buf) + 1) > len) /* +1 for \0 */
2536 return NULL;
2537 strlcpy(dst, buf, len);
2538 return dst;
2539 } else {
2540 return NULL;
2544 /** Given <b>af</b>==AF_INET or <b>af</b>==AF_INET6, and a string <b>src</b>
2545 * encoding an IPv4 address or IPv6 address correspondingly, try to parse the
2546 * address and store the result in <b>dst</b> (which must have space for a
2547 * struct in_addr or a struct in6_addr, as appropriate). Return 1 on success,
2548 * 0 on a bad parse, and -1 on a bad <b>af</b>.
2550 * (Like inet_pton(af,src,dst) but works on platforms that don't have it: Tor
2551 * sometimes needs to format ipv6 addresses even on platforms without ipv6
2552 * support.) */
2554 tor_inet_pton(int af, const char *src, void *dst)
2556 if (af == AF_INET) {
2557 return tor_inet_aton(src, dst);
2558 } else if (af == AF_INET6) {
2559 struct in6_addr *out = dst;
2560 uint16_t words[8];
2561 int gapPos = -1, i, setWords=0;
2562 const char *dot = strchr(src, '.');
2563 const char *eow; /* end of words. */
2564 memset(words, 0xf8, sizeof(words));
2565 if (dot == src)
2566 return 0;
2567 else if (!dot)
2568 eow = src+strlen(src);
2569 else {
2570 unsigned byte1,byte2,byte3,byte4;
2571 char more;
2572 for (eow = dot-1; eow > src && TOR_ISDIGIT(*eow); --eow)
2574 if (*eow != ':')
2575 return 0;
2576 ++eow;
2578 /* We use "scanf" because some platform inet_aton()s are too lax
2579 * about IPv4 addresses of the form "1.2.3" */
2580 if (tor_sscanf(eow, "%3u.%3u.%3u.%3u%c",
2581 &byte1,&byte2,&byte3,&byte4,&more) != 4)
2582 return 0;
2584 if (byte1 > 255 || byte2 > 255 || byte3 > 255 || byte4 > 255)
2585 return 0;
2587 words[6] = (byte1<<8) | byte2;
2588 words[7] = (byte3<<8) | byte4;
2589 setWords += 2;
2592 i = 0;
2593 while (src < eow) {
2594 if (i > 7)
2595 return 0;
2596 if (TOR_ISXDIGIT(*src)) {
2597 char *next;
2598 ssize_t len;
2599 long r = strtol(src, &next, 16);
2600 if (next == NULL || next == src) {
2601 /* The 'next == src' error case can happen on versions of openbsd
2602 * which treat "0xfoo" as an error, rather than as "0" followed by
2603 * "xfoo". */
2604 return 0;
2607 len = *next == '\0' ? eow - src : next - src;
2608 if (len > 4)
2609 return 0;
2610 if (len > 1 && !TOR_ISXDIGIT(src[1]))
2611 return 0; /* 0x is not valid */
2613 tor_assert(r >= 0);
2614 tor_assert(r < 65536);
2615 words[i++] = (uint16_t)r;
2616 setWords++;
2617 src = next;
2618 if (*src != ':' && src != eow)
2619 return 0;
2620 ++src;
2621 } else if (*src == ':' && i > 0 && gapPos == -1) {
2622 gapPos = i;
2623 ++src;
2624 } else if (*src == ':' && i == 0 && src+1 < eow && src[1] == ':' &&
2625 gapPos == -1) {
2626 gapPos = i;
2627 src += 2;
2628 } else {
2629 return 0;
2633 if (setWords > 8 ||
2634 (setWords == 8 && gapPos != -1) ||
2635 (setWords < 8 && gapPos == -1))
2636 return 0;
2638 if (gapPos >= 0) {
2639 int nToMove = setWords - (dot ? 2 : 0) - gapPos;
2640 int gapLen = 8 - setWords;
2641 tor_assert(nToMove >= 0);
2642 memmove(&words[gapPos+gapLen], &words[gapPos],
2643 sizeof(uint16_t)*nToMove);
2644 memset(&words[gapPos], 0, sizeof(uint16_t)*gapLen);
2646 for (i = 0; i < 8; ++i) {
2647 out->s6_addr[2*i ] = words[i] >> 8;
2648 out->s6_addr[2*i+1] = words[i] & 0xff;
2651 return 1;
2652 } else {
2653 return -1;
2657 /** Similar behavior to Unix gethostbyname: resolve <b>name</b>, and set
2658 * *<b>addr</b> to the proper IP address, in host byte order. Returns 0
2659 * on success, -1 on failure; 1 on transient failure.
2661 * (This function exists because standard windows gethostbyname
2662 * doesn't treat raw IP addresses properly.)
2665 MOCK_IMPL(int,
2666 tor_lookup_hostname,(const char *name, uint32_t *addr))
2668 tor_addr_t myaddr;
2669 int ret;
2671 if ((ret = tor_addr_lookup(name, AF_INET, &myaddr)))
2672 return ret;
2674 if (tor_addr_family(&myaddr) == AF_INET) {
2675 *addr = tor_addr_to_ipv4h(&myaddr);
2676 return ret;
2679 return -1;
2682 /** Hold the result of our call to <b>uname</b>. */
2683 static char uname_result[256];
2684 /** True iff uname_result is set. */
2685 static int uname_result_is_set = 0;
2687 /** Return a pointer to a description of our platform.
2689 MOCK_IMPL(const char *,
2690 get_uname,(void))
2692 #ifdef HAVE_UNAME
2693 struct utsname u;
2694 #endif
2695 if (!uname_result_is_set) {
2696 #ifdef HAVE_UNAME
2697 if (uname(&u) != -1) {
2698 /* (Linux says 0 is success, Solaris says 1 is success) */
2699 strlcpy(uname_result, u.sysname, sizeof(uname_result));
2700 } else
2701 #endif /* defined(HAVE_UNAME) */
2703 #ifdef _WIN32
2704 OSVERSIONINFOEX info;
2705 int i;
2706 const char *plat = NULL;
2707 static struct {
2708 unsigned major; unsigned minor; const char *version;
2709 } win_version_table[] = {
2710 { 6, 2, "Windows 8" },
2711 { 6, 1, "Windows 7" },
2712 { 6, 0, "Windows Vista" },
2713 { 5, 2, "Windows Server 2003" },
2714 { 5, 1, "Windows XP" },
2715 { 5, 0, "Windows 2000" },
2716 /* { 4, 0, "Windows NT 4.0" }, */
2717 { 4, 90, "Windows Me" },
2718 { 4, 10, "Windows 98" },
2719 /* { 4, 0, "Windows 95" } */
2720 { 3, 51, "Windows NT 3.51" },
2721 { 0, 0, NULL }
2723 memset(&info, 0, sizeof(info));
2724 info.dwOSVersionInfoSize = sizeof(info);
2725 if (! GetVersionEx((LPOSVERSIONINFO)&info)) {
2726 strlcpy(uname_result, "Bizarre version of Windows where GetVersionEx"
2727 " doesn't work.", sizeof(uname_result));
2728 uname_result_is_set = 1;
2729 return uname_result;
2731 if (info.dwMajorVersion == 4 && info.dwMinorVersion == 0) {
2732 if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
2733 plat = "Windows NT 4.0";
2734 else
2735 plat = "Windows 95";
2736 } else {
2737 for (i=0; win_version_table[i].major>0; ++i) {
2738 if (win_version_table[i].major == info.dwMajorVersion &&
2739 win_version_table[i].minor == info.dwMinorVersion) {
2740 plat = win_version_table[i].version;
2741 break;
2745 if (plat) {
2746 strlcpy(uname_result, plat, sizeof(uname_result));
2747 } else {
2748 if (info.dwMajorVersion > 6 ||
2749 (info.dwMajorVersion==6 && info.dwMinorVersion>2))
2750 tor_snprintf(uname_result, sizeof(uname_result),
2751 "Very recent version of Windows [major=%d,minor=%d]",
2752 (int)info.dwMajorVersion,(int)info.dwMinorVersion);
2753 else
2754 tor_snprintf(uname_result, sizeof(uname_result),
2755 "Unrecognized version of Windows [major=%d,minor=%d]",
2756 (int)info.dwMajorVersion,(int)info.dwMinorVersion);
2758 #ifdef VER_NT_SERVER
2759 if (info.wProductType == VER_NT_SERVER ||
2760 info.wProductType == VER_NT_DOMAIN_CONTROLLER) {
2761 strlcat(uname_result, " [server]", sizeof(uname_result));
2763 #endif /* defined(VER_NT_SERVER) */
2764 #else /* !(defined(_WIN32)) */
2765 /* LCOV_EXCL_START -- can't provoke uname failure */
2766 strlcpy(uname_result, "Unknown platform", sizeof(uname_result));
2767 /* LCOV_EXCL_STOP */
2768 #endif /* defined(_WIN32) */
2770 uname_result_is_set = 1;
2772 return uname_result;
2776 * Process control
2779 /** Implementation logic for compute_num_cpus(). */
2780 static int
2781 compute_num_cpus_impl(void)
2783 #ifdef _WIN32
2784 SYSTEM_INFO info;
2785 memset(&info, 0, sizeof(info));
2786 GetSystemInfo(&info);
2787 if (info.dwNumberOfProcessors >= 1 && info.dwNumberOfProcessors < INT_MAX)
2788 return (int)info.dwNumberOfProcessors;
2789 else
2790 return -1;
2791 #elif defined(HAVE_SYSCONF)
2792 #ifdef _SC_NPROCESSORS_CONF
2793 long cpus_conf = sysconf(_SC_NPROCESSORS_CONF);
2794 #else
2795 long cpus_conf = -1;
2796 #endif
2797 #ifdef _SC_NPROCESSORS_ONLN
2798 long cpus_onln = sysconf(_SC_NPROCESSORS_ONLN);
2799 #else
2800 long cpus_onln = -1;
2801 #endif
2802 long cpus = -1;
2804 if (cpus_conf > 0 && cpus_onln < 0) {
2805 cpus = cpus_conf;
2806 } else if (cpus_onln > 0 && cpus_conf < 0) {
2807 cpus = cpus_onln;
2808 } else if (cpus_onln > 0 && cpus_conf > 0) {
2809 if (cpus_onln < cpus_conf) {
2810 log_notice(LD_GENERAL, "I think we have %ld CPUS, but only %ld of them "
2811 "are available. Telling Tor to only use %ld. You can over"
2812 "ride this with the NumCPUs option",
2813 cpus_conf, cpus_onln, cpus_onln);
2815 cpus = cpus_onln;
2818 if (cpus >= 1 && cpus < INT_MAX)
2819 return (int)cpus;
2820 else
2821 return -1;
2822 #else
2823 return -1;
2824 #endif /* defined(_WIN32) || ... */
2827 #define MAX_DETECTABLE_CPUS 16
2829 /** Return how many CPUs we are running with. We assume that nobody is
2830 * using hot-swappable CPUs, so we don't recompute this after the first
2831 * time. Return -1 if we don't know how to tell the number of CPUs on this
2832 * system.
2835 compute_num_cpus(void)
2837 static int num_cpus = -2;
2838 if (num_cpus == -2) {
2839 num_cpus = compute_num_cpus_impl();
2840 tor_assert(num_cpus != -2);
2841 if (num_cpus > MAX_DETECTABLE_CPUS) {
2842 /* LCOV_EXCL_START */
2843 log_notice(LD_GENERAL, "Wow! I detected that you have %d CPUs. I "
2844 "will not autodetect any more than %d, though. If you "
2845 "want to configure more, set NumCPUs in your torrc",
2846 num_cpus, MAX_DETECTABLE_CPUS);
2847 num_cpus = MAX_DETECTABLE_CPUS;
2848 /* LCOV_EXCL_STOP */
2851 return num_cpus;
2854 #if !defined(_WIN32)
2855 /** Defined iff we need to add locks when defining fake versions of reentrant
2856 * versions of time-related functions. */
2857 #define TIME_FNS_NEED_LOCKS
2858 #endif
2860 /** Helper: Deal with confused or out-of-bounds values from localtime_r and
2861 * friends. (On some platforms, they can give out-of-bounds values or can
2862 * return NULL.) If <b>islocal</b>, this is a localtime result; otherwise
2863 * it's from gmtime. The function returns <b>r</b>, when given <b>timep</b>
2864 * as its input. If we need to store new results, store them in
2865 * <b>resultbuf</b>. */
2866 static struct tm *
2867 correct_tm(int islocal, const time_t *timep, struct tm *resultbuf,
2868 struct tm *r)
2870 const char *outcome;
2872 if (PREDICT_LIKELY(r)) {
2873 /* We can't strftime dates after 9999 CE, and we want to avoid dates
2874 * before 1 CE (avoiding the year 0 issue and negative years). */
2875 if (r->tm_year > 8099) {
2876 r->tm_year = 8099;
2877 r->tm_mon = 11;
2878 r->tm_mday = 31;
2879 r->tm_yday = 364;
2880 r->tm_wday = 6;
2881 r->tm_hour = 23;
2882 r->tm_min = 59;
2883 r->tm_sec = 59;
2884 } else if (r->tm_year < (1-1900)) {
2885 r->tm_year = (1-1900);
2886 r->tm_mon = 0;
2887 r->tm_mday = 1;
2888 r->tm_yday = 0;
2889 r->tm_wday = 0;
2890 r->tm_hour = 0;
2891 r->tm_min = 0;
2892 r->tm_sec = 0;
2894 return r;
2897 /* If we get here, gmtime or localtime returned NULL. It might have done
2898 * this because of overrun or underrun, or it might have done it because of
2899 * some other weird issue. */
2900 if (timep) {
2901 if (*timep < 0) {
2902 r = resultbuf;
2903 r->tm_year = 70; /* 1970 CE */
2904 r->tm_mon = 0;
2905 r->tm_mday = 1;
2906 r->tm_yday = 0;
2907 r->tm_wday = 0;
2908 r->tm_hour = 0;
2909 r->tm_min = 0 ;
2910 r->tm_sec = 0;
2911 outcome = "Rounding up to 1970";
2912 goto done;
2913 } else if (*timep >= INT32_MAX) {
2914 /* Rounding down to INT32_MAX isn't so great, but keep in mind that we
2915 * only do it if gmtime/localtime tells us NULL. */
2916 r = resultbuf;
2917 r->tm_year = 137; /* 2037 CE */
2918 r->tm_mon = 11;
2919 r->tm_mday = 31;
2920 r->tm_yday = 364;
2921 r->tm_wday = 6;
2922 r->tm_hour = 23;
2923 r->tm_min = 59;
2924 r->tm_sec = 59;
2925 outcome = "Rounding down to 2037";
2926 goto done;
2930 /* If we get here, then gmtime/localtime failed without getting an extreme
2931 * value for *timep */
2932 /* LCOV_EXCL_START */
2933 tor_fragile_assert();
2934 r = resultbuf;
2935 memset(resultbuf, 0, sizeof(struct tm));
2936 outcome="can't recover";
2937 /* LCOV_EXCL_STOP */
2938 done:
2939 log_warn(LD_BUG, "%s("I64_FORMAT") failed with error %s: %s",
2940 islocal?"localtime":"gmtime",
2941 timep?I64_PRINTF_ARG(*timep):0,
2942 strerror(errno),
2943 outcome);
2944 return r;
2947 /** @{ */
2948 /** As localtime_r, but defined for platforms that don't have it:
2950 * Convert *<b>timep</b> to a struct tm in local time, and store the value in
2951 * *<b>result</b>. Return the result on success, or NULL on failure.
2953 #ifdef HAVE_LOCALTIME_R
2954 struct tm *
2955 tor_localtime_r(const time_t *timep, struct tm *result)
2957 struct tm *r;
2958 r = localtime_r(timep, result);
2959 return correct_tm(1, timep, result, r);
2961 #elif defined(TIME_FNS_NEED_LOCKS)
2962 struct tm *
2963 tor_localtime_r(const time_t *timep, struct tm *result)
2965 struct tm *r;
2966 static tor_mutex_t *m=NULL;
2967 if (!m) { m=tor_mutex_new(); }
2968 tor_assert(result);
2969 tor_mutex_acquire(m);
2970 r = localtime(timep);
2971 if (r)
2972 memcpy(result, r, sizeof(struct tm));
2973 tor_mutex_release(m);
2974 return correct_tm(1, timep, result, r);
2976 #else
2977 struct tm *
2978 tor_localtime_r(const time_t *timep, struct tm *result)
2980 struct tm *r;
2981 tor_assert(result);
2982 r = localtime(timep);
2983 if (r)
2984 memcpy(result, r, sizeof(struct tm));
2985 return correct_tm(1, timep, result, r);
2987 #endif /* defined(HAVE_LOCALTIME_R) || ... */
2988 /** @} */
2990 /** @{ */
2991 /** As gmtime_r, but defined for platforms that don't have it:
2993 * Convert *<b>timep</b> to a struct tm in UTC, and store the value in
2994 * *<b>result</b>. Return the result on success, or NULL on failure.
2996 #ifdef HAVE_GMTIME_R
2997 struct tm *
2998 tor_gmtime_r(const time_t *timep, struct tm *result)
3000 struct tm *r;
3001 r = gmtime_r(timep, result);
3002 return correct_tm(0, timep, result, r);
3004 #elif defined(TIME_FNS_NEED_LOCKS)
3005 struct tm *
3006 tor_gmtime_r(const time_t *timep, struct tm *result)
3008 struct tm *r;
3009 static tor_mutex_t *m=NULL;
3010 if (!m) { m=tor_mutex_new(); }
3011 tor_assert(result);
3012 tor_mutex_acquire(m);
3013 r = gmtime(timep);
3014 if (r)
3015 memcpy(result, r, sizeof(struct tm));
3016 tor_mutex_release(m);
3017 return correct_tm(0, timep, result, r);
3019 #else
3020 struct tm *
3021 tor_gmtime_r(const time_t *timep, struct tm *result)
3023 struct tm *r;
3024 tor_assert(result);
3025 r = gmtime(timep);
3026 if (r)
3027 memcpy(result, r, sizeof(struct tm));
3028 return correct_tm(0, timep, result, r);
3030 #endif /* defined(HAVE_GMTIME_R) || ... */
3032 #if defined(HAVE_MLOCKALL) && HAVE_DECL_MLOCKALL && defined(RLIMIT_MEMLOCK)
3033 #define HAVE_UNIX_MLOCKALL
3034 #endif
3036 #ifdef HAVE_UNIX_MLOCKALL
3037 /** Attempt to raise the current and max rlimit to infinity for our process.
3038 * This only needs to be done once and can probably only be done when we have
3039 * not already dropped privileges.
3041 static int
3042 tor_set_max_memlock(void)
3044 /* Future consideration for Windows is probably SetProcessWorkingSetSize
3045 * This is similar to setting the memory rlimit of RLIMIT_MEMLOCK
3046 * http://msdn.microsoft.com/en-us/library/ms686234(VS.85).aspx
3049 struct rlimit limit;
3051 /* RLIM_INFINITY is -1 on some platforms. */
3052 limit.rlim_cur = RLIM_INFINITY;
3053 limit.rlim_max = RLIM_INFINITY;
3055 if (setrlimit(RLIMIT_MEMLOCK, &limit) == -1) {
3056 if (errno == EPERM) {
3057 log_warn(LD_GENERAL, "You appear to lack permissions to change memory "
3058 "limits. Are you root?");
3060 log_warn(LD_GENERAL, "Unable to raise RLIMIT_MEMLOCK: %s",
3061 strerror(errno));
3062 return -1;
3065 return 0;
3067 #endif /* defined(HAVE_UNIX_MLOCKALL) */
3069 /** Attempt to lock all current and all future memory pages.
3070 * This should only be called once and while we're privileged.
3071 * Like mlockall() we return 0 when we're successful and -1 when we're not.
3072 * Unlike mlockall() we return 1 if we've already attempted to lock memory.
3075 tor_mlockall(void)
3077 static int memory_lock_attempted = 0;
3079 if (memory_lock_attempted) {
3080 return 1;
3083 memory_lock_attempted = 1;
3086 * Future consideration for Windows may be VirtualLock
3087 * VirtualLock appears to implement mlock() but not mlockall()
3089 * http://msdn.microsoft.com/en-us/library/aa366895(VS.85).aspx
3092 #ifdef HAVE_UNIX_MLOCKALL
3093 if (tor_set_max_memlock() == 0) {
3094 log_debug(LD_GENERAL, "RLIMIT_MEMLOCK is now set to RLIM_INFINITY.");
3097 if (mlockall(MCL_CURRENT|MCL_FUTURE) == 0) {
3098 log_info(LD_GENERAL, "Insecure OS paging is effectively disabled.");
3099 return 0;
3100 } else {
3101 if (errno == ENOSYS) {
3102 /* Apple - it's 2009! I'm looking at you. Grrr. */
3103 log_notice(LD_GENERAL, "It appears that mlockall() is not available on "
3104 "your platform.");
3105 } else if (errno == EPERM) {
3106 log_notice(LD_GENERAL, "It appears that you lack the permissions to "
3107 "lock memory. Are you root?");
3109 log_notice(LD_GENERAL, "Unable to lock all current and future memory "
3110 "pages: %s", strerror(errno));
3111 return -1;
3113 #else /* !(defined(HAVE_UNIX_MLOCKALL)) */
3114 log_warn(LD_GENERAL, "Unable to lock memory pages. mlockall() unsupported?");
3115 return -1;
3116 #endif /* defined(HAVE_UNIX_MLOCKALL) */
3120 * On Windows, WSAEWOULDBLOCK is not always correct: when you see it,
3121 * you need to ask the socket for its actual errno. Also, you need to
3122 * get your errors from WSAGetLastError, not errno. (If you supply a
3123 * socket of -1, we check WSAGetLastError, but don't correct
3124 * WSAEWOULDBLOCKs.)
3126 * The upshot of all of this is that when a socket call fails, you
3127 * should call tor_socket_errno <em>at most once</em> on the failing
3128 * socket to get the error.
3130 #if defined(_WIN32)
3132 tor_socket_errno(tor_socket_t sock)
3134 int optval, optvallen=sizeof(optval);
3135 int err = WSAGetLastError();
3136 if (err == WSAEWOULDBLOCK && SOCKET_OK(sock)) {
3137 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval, &optvallen))
3138 return err;
3139 if (optval)
3140 return optval;
3142 return err;
3144 #endif /* defined(_WIN32) */
3146 #if defined(_WIN32)
3147 #define E(code, s) { code, (s " [" #code " ]") }
3148 struct { int code; const char *msg; } windows_socket_errors[] = {
3149 E(WSAEINTR, "Interrupted function call"),
3150 E(WSAEACCES, "Permission denied"),
3151 E(WSAEFAULT, "Bad address"),
3152 E(WSAEINVAL, "Invalid argument"),
3153 E(WSAEMFILE, "Too many open files"),
3154 E(WSAEWOULDBLOCK, "Resource temporarily unavailable"),
3155 E(WSAEINPROGRESS, "Operation now in progress"),
3156 E(WSAEALREADY, "Operation already in progress"),
3157 E(WSAENOTSOCK, "Socket operation on nonsocket"),
3158 E(WSAEDESTADDRREQ, "Destination address required"),
3159 E(WSAEMSGSIZE, "Message too long"),
3160 E(WSAEPROTOTYPE, "Protocol wrong for socket"),
3161 E(WSAENOPROTOOPT, "Bad protocol option"),
3162 E(WSAEPROTONOSUPPORT, "Protocol not supported"),
3163 E(WSAESOCKTNOSUPPORT, "Socket type not supported"),
3164 /* What's the difference between NOTSUPP and NOSUPPORT? :) */
3165 E(WSAEOPNOTSUPP, "Operation not supported"),
3166 E(WSAEPFNOSUPPORT, "Protocol family not supported"),
3167 E(WSAEAFNOSUPPORT, "Address family not supported by protocol family"),
3168 E(WSAEADDRINUSE, "Address already in use"),
3169 E(WSAEADDRNOTAVAIL, "Cannot assign requested address"),
3170 E(WSAENETDOWN, "Network is down"),
3171 E(WSAENETUNREACH, "Network is unreachable"),
3172 E(WSAENETRESET, "Network dropped connection on reset"),
3173 E(WSAECONNABORTED, "Software caused connection abort"),
3174 E(WSAECONNRESET, "Connection reset by peer"),
3175 E(WSAENOBUFS, "No buffer space available"),
3176 E(WSAEISCONN, "Socket is already connected"),
3177 E(WSAENOTCONN, "Socket is not connected"),
3178 E(WSAESHUTDOWN, "Cannot send after socket shutdown"),
3179 E(WSAETIMEDOUT, "Connection timed out"),
3180 E(WSAECONNREFUSED, "Connection refused"),
3181 E(WSAEHOSTDOWN, "Host is down"),
3182 E(WSAEHOSTUNREACH, "No route to host"),
3183 E(WSAEPROCLIM, "Too many processes"),
3184 /* Yes, some of these start with WSA, not WSAE. No, I don't know why. */
3185 E(WSASYSNOTREADY, "Network subsystem is unavailable"),
3186 E(WSAVERNOTSUPPORTED, "Winsock.dll out of range"),
3187 E(WSANOTINITIALISED, "Successful WSAStartup not yet performed"),
3188 E(WSAEDISCON, "Graceful shutdown now in progress"),
3189 #ifdef WSATYPE_NOT_FOUND
3190 E(WSATYPE_NOT_FOUND, "Class type not found"),
3191 #endif
3192 E(WSAHOST_NOT_FOUND, "Host not found"),
3193 E(WSATRY_AGAIN, "Nonauthoritative host not found"),
3194 E(WSANO_RECOVERY, "This is a nonrecoverable error"),
3195 E(WSANO_DATA, "Valid name, no data record of requested type)"),
3197 /* There are some more error codes whose numeric values are marked
3198 * <b>OS dependent</b>. They start with WSA_, apparently for the same
3199 * reason that practitioners of some craft traditions deliberately
3200 * introduce imperfections into their baskets and rugs "to allow the
3201 * evil spirits to escape." If we catch them, then our binaries
3202 * might not report consistent results across versions of Windows.
3203 * Thus, I'm going to let them all fall through.
3205 { -1, NULL },
3207 /** There does not seem to be a strerror equivalent for Winsock errors.
3208 * Naturally, we have to roll our own.
3210 const char *
3211 tor_socket_strerror(int e)
3213 int i;
3214 for (i=0; windows_socket_errors[i].code >= 0; ++i) {
3215 if (e == windows_socket_errors[i].code)
3216 return windows_socket_errors[i].msg;
3218 return strerror(e);
3220 #endif /* defined(_WIN32) */
3222 /** Called before we make any calls to network-related functions.
3223 * (Some operating systems require their network libraries to be
3224 * initialized.) */
3226 network_init(void)
3228 #ifdef _WIN32
3229 /* This silly exercise is necessary before windows will allow
3230 * gethostbyname to work. */
3231 WSADATA WSAData;
3232 int r;
3233 r = WSAStartup(0x101,&WSAData);
3234 if (r) {
3235 log_warn(LD_NET,"Error initializing windows network layer: code was %d",r);
3236 return -1;
3238 if (sizeof(SOCKET) != sizeof(tor_socket_t)) {
3239 log_warn(LD_BUG,"The tor_socket_t type does not match SOCKET in size; Tor "
3240 "might not work. (Sizes are %d and %d respectively.)",
3241 (int)sizeof(tor_socket_t), (int)sizeof(SOCKET));
3243 /* WSAData.iMaxSockets might show the max sockets we're allowed to use.
3244 * We might use it to complain if we're trying to be a server but have
3245 * too few sockets available. */
3246 #endif /* defined(_WIN32) */
3247 return 0;
3250 #ifdef _WIN32
3251 /** Return a newly allocated string describing the windows system error code
3252 * <b>err</b>. Note that error codes are different from errno. Error codes
3253 * come from GetLastError() when a winapi call fails. errno is set only when
3254 * ANSI functions fail. Whee. */
3255 char *
3256 format_win32_error(DWORD err)
3258 TCHAR *str = NULL;
3259 char *result;
3260 DWORD n;
3262 /* Somebody once decided that this interface was better than strerror(). */
3263 n = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
3264 FORMAT_MESSAGE_FROM_SYSTEM |
3265 FORMAT_MESSAGE_IGNORE_INSERTS,
3266 NULL, err,
3267 MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT),
3268 (LPVOID)&str,
3269 0, NULL);
3271 if (str && n) {
3272 #ifdef UNICODE
3273 size_t len;
3274 if (n > 128*1024)
3275 len = (128 * 1024) * 2 + 1; /* This shouldn't be possible, but let's
3276 * make sure. */
3277 else
3278 len = n * 2 + 1;
3279 result = tor_malloc(len);
3280 wcstombs(result,str,len);
3281 result[len-1] = '\0';
3282 #else /* !(defined(UNICODE)) */
3283 result = tor_strdup(str);
3284 #endif /* defined(UNICODE) */
3285 } else {
3286 result = tor_strdup("<unformattable error>");
3288 if (str) {
3289 LocalFree(str); /* LocalFree != free() */
3291 return result;
3293 #endif /* defined(_WIN32) */
3295 #if defined(HW_PHYSMEM64)
3296 /* This appears to be an OpenBSD thing */
3297 #define INT64_HW_MEM HW_PHYSMEM64
3298 #elif defined(HW_MEMSIZE)
3299 /* OSX defines this one */
3300 #define INT64_HW_MEM HW_MEMSIZE
3301 #endif /* defined(HW_PHYSMEM64) || ... */
3304 * Helper: try to detect the total system memory, and return it. On failure,
3305 * return 0.
3307 static uint64_t
3308 get_total_system_memory_impl(void)
3310 #if defined(__linux__)
3311 /* On linux, sysctl is deprecated. Because proc is so awesome that you
3312 * shouldn't _want_ to write portable code, I guess? */
3313 unsigned long long result=0;
3314 int fd = -1;
3315 char *s = NULL;
3316 const char *cp;
3317 size_t file_size=0;
3318 if (-1 == (fd = tor_open_cloexec("/proc/meminfo",O_RDONLY,0)))
3319 return 0;
3320 s = read_file_to_str_until_eof(fd, 65536, &file_size);
3321 if (!s)
3322 goto err;
3323 cp = strstr(s, "MemTotal:");
3324 if (!cp)
3325 goto err;
3326 /* Use the system sscanf so that space will match a wider number of space */
3327 if (sscanf(cp, "MemTotal: %llu kB\n", &result) != 1)
3328 goto err;
3330 close(fd);
3331 tor_free(s);
3332 return result * 1024;
3334 /* LCOV_EXCL_START Can't reach this unless proc is broken. */
3335 err:
3336 tor_free(s);
3337 close(fd);
3338 return 0;
3339 /* LCOV_EXCL_STOP */
3340 #elif defined (_WIN32)
3341 /* Windows has MEMORYSTATUSEX; pretty straightforward. */
3342 MEMORYSTATUSEX ms;
3343 memset(&ms, 0, sizeof(ms));
3344 ms.dwLength = sizeof(ms);
3345 if (! GlobalMemoryStatusEx(&ms))
3346 return 0;
3348 return ms.ullTotalPhys;
3350 #elif defined(HAVE_SYSCTL) && defined(INT64_HW_MEM)
3351 /* On many systems, HW_PYHSMEM is clipped to 32 bits; let's use a better
3352 * variant if we know about it. */
3353 uint64_t memsize = 0;
3354 size_t len = sizeof(memsize);
3355 int mib[2] = {CTL_HW, INT64_HW_MEM};
3356 if (sysctl(mib,2,&memsize,&len,NULL,0))
3357 return 0;
3359 return memsize;
3361 #elif defined(HAVE_SYSCTL) && defined(HW_PHYSMEM)
3362 /* On some systems (like FreeBSD I hope) you can use a size_t with
3363 * HW_PHYSMEM. */
3364 size_t memsize=0;
3365 size_t len = sizeof(memsize);
3366 int mib[2] = {CTL_HW, HW_USERMEM};
3367 if (sysctl(mib,2,&memsize,&len,NULL,0))
3368 return 0;
3370 return memsize;
3372 #else
3373 /* I have no clue. */
3374 return 0;
3375 #endif /* defined(__linux__) || ... */
3379 * Try to find out how much physical memory the system has. On success,
3380 * return 0 and set *<b>mem_out</b> to that value. On failure, return -1.
3383 get_total_system_memory(size_t *mem_out)
3385 static size_t mem_cached=0;
3386 uint64_t m = get_total_system_memory_impl();
3387 if (0 == m) {
3388 /* LCOV_EXCL_START -- can't make this happen without mocking. */
3389 /* We couldn't find our memory total */
3390 if (0 == mem_cached) {
3391 /* We have no cached value either */
3392 *mem_out = 0;
3393 return -1;
3396 *mem_out = mem_cached;
3397 return 0;
3398 /* LCOV_EXCL_STOP */
3401 #if SIZE_MAX != UINT64_MAX
3402 if (m > SIZE_MAX) {
3403 /* I think this could happen if we're a 32-bit Tor running on a 64-bit
3404 * system: we could have more system memory than would fit in a
3405 * size_t. */
3406 m = SIZE_MAX;
3408 #endif /* SIZE_MAX != UINT64_MAX */
3410 *mem_out = mem_cached = (size_t) m;
3412 return 0;
3415 /** Emit the password prompt <b>prompt</b>, then read up to <b>buflen</b>
3416 * bytes of passphrase into <b>output</b>. Return the number of bytes in
3417 * the passphrase, excluding terminating NUL.
3419 ssize_t
3420 tor_getpass(const char *prompt, char *output, size_t buflen)
3422 tor_assert(buflen <= SSIZE_MAX);
3423 tor_assert(buflen >= 1);
3424 #if defined(HAVE_READPASSPHRASE)
3425 char *pwd = readpassphrase(prompt, output, buflen, RPP_ECHO_OFF);
3426 if (pwd == NULL)
3427 return -1;
3428 return strlen(pwd);
3429 #elif defined(_WIN32)
3430 int r = -1;
3431 while (*prompt) {
3432 _putch(*prompt++);
3435 tor_assert(buflen <= INT_MAX);
3436 wchar_t *buf = tor_calloc(buflen, sizeof(wchar_t));
3438 wchar_t *ptr = buf, *lastch = buf + buflen - 1;
3439 while (ptr < lastch) {
3440 wint_t ch = _getwch();
3441 switch (ch) {
3442 case '\r':
3443 case '\n':
3444 case WEOF:
3445 goto done_reading;
3446 case 3:
3447 goto done; /* Can't actually read ctrl-c this way. */
3448 case '\b':
3449 if (ptr > buf)
3450 --ptr;
3451 continue;
3452 case 0:
3453 case 0xe0:
3454 ch = _getwch(); /* Ignore; this is a function or arrow key */
3455 break;
3456 default:
3457 *ptr++ = ch;
3458 break;
3461 done_reading:
3464 #ifndef WC_ERR_INVALID_CHARS
3465 #define WC_ERR_INVALID_CHARS 0x80
3466 #endif
3468 /* Now convert it to UTF-8 */
3469 r = WideCharToMultiByte(CP_UTF8,
3470 WC_NO_BEST_FIT_CHARS|WC_ERR_INVALID_CHARS,
3471 buf, (int)(ptr-buf),
3472 output, (int)(buflen-1),
3473 NULL, NULL);
3474 if (r <= 0) {
3475 r = -1;
3476 goto done;
3479 tor_assert(r < (int)buflen);
3481 output[r] = 0;
3483 done:
3484 SecureZeroMemory(buf, sizeof(wchar_t)*buflen);
3485 tor_free(buf);
3486 return r;
3487 #else
3488 #error "No implementation for tor_getpass found!"
3489 #endif /* defined(HAVE_READPASSPHRASE) || ... */
3492 /** Return the amount of free disk space we have permission to use, in
3493 * bytes. Return -1 if the amount of free space can't be determined. */
3494 int64_t
3495 tor_get_avail_disk_space(const char *path)
3497 #ifdef HAVE_STATVFS
3498 struct statvfs st;
3499 int r;
3500 memset(&st, 0, sizeof(st));
3502 r = statvfs(path, &st);
3503 if (r < 0)
3504 return -1;
3506 int64_t result = st.f_bavail;
3507 if (st.f_frsize) {
3508 result *= st.f_frsize;
3509 } else if (st.f_bsize) {
3510 result *= st.f_bsize;
3511 } else {
3512 return -1;
3515 return result;
3516 #elif defined(_WIN32)
3517 ULARGE_INTEGER freeBytesAvail;
3518 BOOL ok;
3520 ok = GetDiskFreeSpaceEx(path, &freeBytesAvail, NULL, NULL);
3521 if (!ok) {
3522 return -1;
3524 return (int64_t)freeBytesAvail.QuadPart;
3525 #else
3526 (void)path;
3527 errno = ENOSYS;
3528 return -1;
3529 #endif /* defined(HAVE_STATVFS) || ... */