Don't treat a setrlimit failure as fatal.
[tor/appveyor.git] / src / common / compat.c
bloba88e9b51456bd9683f33f146fe7987b400023449
1 /* Copyright (c) 2003-2004, Roger Dingledine
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2016, 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
92 #elif defined(HAVE_READPASSPHRASE_H)
93 #include <readpassphrase.h>
94 #else
95 #include "tor_readpassphrase.h"
96 #endif
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/types.h>
104 #include <sys/ptrace.h>
105 #endif
107 #ifdef HAVE_NETDB_H
108 #include <netdb.h>
109 #endif
110 #ifdef HAVE_SYS_PARAM_H
111 #include <sys/param.h> /* FreeBSD needs this to know what version it is */
112 #endif
113 #include <stdio.h>
114 #include <stdlib.h>
115 #include <assert.h>
116 #ifdef HAVE_SIGNAL_H
117 #include <signal.h>
118 #endif
119 #ifdef HAVE_SYS_MMAN_H
120 #include <sys/mman.h>
121 #endif
122 #ifdef HAVE_SYS_SYSLIMITS_H
123 #include <sys/syslimits.h>
124 #endif
125 #ifdef HAVE_SYS_FILE_H
126 #include <sys/file.h>
127 #endif
129 #include "torlog.h"
130 #include "util.h"
131 #include "container.h"
132 #include "address.h"
133 #include "sandbox.h"
135 /* Inline the strl functions if the platform doesn't have them. */
136 #ifndef HAVE_STRLCPY
137 #include "strlcpy.c"
138 #endif
139 #ifndef HAVE_STRLCAT
140 #include "strlcat.c"
141 #endif
143 /* When set_max_file_descriptors() is called, update this with the max file
144 * descriptor value so we can use it to check the limit when opening a new
145 * socket. Default value is what Debian sets as the default hard limit. */
146 static int max_sockets = 1024;
148 /** As open(path, flags, mode), but return an fd with the close-on-exec mode
149 * set. */
151 tor_open_cloexec(const char *path, int flags, unsigned mode)
153 int fd;
154 const char *p = sandbox_intern_string(path);
155 #ifdef O_CLOEXEC
156 fd = open(p, flags|O_CLOEXEC, mode);
157 if (fd >= 0)
158 return fd;
159 /* If we got an error, see if it is EINVAL. EINVAL might indicate that,
160 * even though we were built on a system with O_CLOEXEC support, we
161 * are running on one without. */
162 if (errno != EINVAL)
163 return -1;
164 #endif
166 log_debug(LD_FS, "Opening %s with flags %x", p, flags);
167 fd = open(p, flags, mode);
168 #ifdef FD_CLOEXEC
169 if (fd >= 0) {
170 if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1) {
171 log_warn(LD_FS,"Couldn't set FD_CLOEXEC: %s", strerror(errno));
172 close(fd);
173 return -1;
176 #endif
177 return fd;
180 /** As fopen(path,mode), but ensures that the O_CLOEXEC bit is set on the
181 * underlying file handle. */
182 FILE *
183 tor_fopen_cloexec(const char *path, const char *mode)
185 FILE *result = fopen(path, mode);
186 #ifdef FD_CLOEXEC
187 if (result != NULL) {
188 if (fcntl(fileno(result), F_SETFD, FD_CLOEXEC) == -1) {
189 log_warn(LD_FS,"Couldn't set FD_CLOEXEC: %s", strerror(errno));
190 fclose(result);
191 return NULL;
194 #endif
195 return result;
198 /** As rename(), but work correctly with the sandbox. */
200 tor_rename(const char *path_old, const char *path_new)
202 log_debug(LD_FS, "Renaming %s to %s", path_old, path_new);
203 return rename(sandbox_intern_string(path_old),
204 sandbox_intern_string(path_new));
207 #if defined(HAVE_SYS_MMAN_H) || defined(RUNNING_DOXYGEN)
208 /** Try to create a memory mapping for <b>filename</b> and return it. On
209 * failure, return NULL. Sets errno properly, using ERANGE to mean
210 * "empty file". */
211 tor_mmap_t *
212 tor_mmap_file(const char *filename)
214 int fd; /* router file */
215 char *string;
216 int page_size, 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 * Should we check for weird crap like mmapping a named pipe here,
247 * or just wait for if (!size) below to fail?
249 /* ensure page alignment */
250 page_size = getpagesize();
251 size += (size%page_size) ? page_size-(size%page_size) : 0;
253 if (!size) {
254 /* Zero-length file. If we call mmap on it, it will succeed but
255 * return NULL, and bad things will happen. So just fail. */
256 log_info(LD_FS,"File \"%s\" is empty. Ignoring.",filename);
257 errno = ERANGE;
258 close(fd);
259 return NULL;
262 string = mmap(0, size, PROT_READ, MAP_PRIVATE, fd, 0);
263 close(fd);
264 if (string == MAP_FAILED) {
265 int save_errno = errno;
266 log_warn(LD_FS,"Could not mmap file \"%s\": %s", filename,
267 strerror(errno));
268 errno = save_errno;
269 return NULL;
272 res = tor_malloc_zero(sizeof(tor_mmap_t));
273 res->data = string;
274 res->size = filesize;
275 res->mapping_size = size;
277 return res;
279 /** Release storage held for a memory mapping; returns 0 on success,
280 * or -1 on failure (and logs a warning). */
282 tor_munmap_file(tor_mmap_t *handle)
284 int res;
286 if (handle == NULL)
287 return 0;
289 res = munmap((char*)handle->data, handle->mapping_size);
290 if (res == 0) {
291 /* munmap() succeeded */
292 tor_free(handle);
293 } else {
294 log_warn(LD_FS, "Failed to munmap() in tor_munmap_file(): %s",
295 strerror(errno));
296 res = -1;
299 return res;
301 #elif defined(_WIN32)
302 tor_mmap_t *
303 tor_mmap_file(const char *filename)
305 TCHAR tfilename[MAX_PATH]= {0};
306 tor_mmap_t *res = tor_malloc_zero(sizeof(tor_mmap_t));
307 int empty = 0;
308 HANDLE file_handle = INVALID_HANDLE_VALUE;
309 DWORD size_low, size_high;
310 uint64_t real_size;
311 res->mmap_handle = NULL;
312 #ifdef UNICODE
313 mbstowcs(tfilename,filename,MAX_PATH);
314 #else
315 strlcpy(tfilename,filename,MAX_PATH);
316 #endif
317 file_handle = CreateFile(tfilename,
318 GENERIC_READ, FILE_SHARE_READ,
319 NULL,
320 OPEN_EXISTING,
321 FILE_ATTRIBUTE_NORMAL,
324 if (file_handle == INVALID_HANDLE_VALUE)
325 goto win_err;
327 size_low = GetFileSize(file_handle, &size_high);
329 if (size_low == INVALID_FILE_SIZE && GetLastError() != NO_ERROR) {
330 log_warn(LD_FS,"Error getting size of \"%s\".",filename);
331 goto win_err;
333 if (size_low == 0 && size_high == 0) {
334 log_info(LD_FS,"File \"%s\" is empty. Ignoring.",filename);
335 empty = 1;
336 goto err;
338 real_size = (((uint64_t)size_high)<<32) | size_low;
339 if (real_size > SIZE_MAX) {
340 log_warn(LD_FS,"File \"%s\" is too big to map; not trying.",filename);
341 goto err;
343 res->size = real_size;
345 res->mmap_handle = CreateFileMapping(file_handle,
346 NULL,
347 PAGE_READONLY,
348 size_high,
349 size_low,
350 NULL);
351 if (res->mmap_handle == NULL)
352 goto win_err;
353 res->data = (char*) MapViewOfFile(res->mmap_handle,
354 FILE_MAP_READ,
355 0, 0, 0);
356 if (!res->data)
357 goto win_err;
359 CloseHandle(file_handle);
360 return res;
361 win_err: {
362 DWORD e = GetLastError();
363 int severity = (e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND) ?
364 LOG_INFO : LOG_WARN;
365 char *msg = format_win32_error(e);
366 log_fn(severity, LD_FS, "Couldn't mmap file \"%s\": %s", filename, msg);
367 tor_free(msg);
368 if (e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND)
369 errno = ENOENT;
370 else
371 errno = EINVAL;
373 err:
374 if (empty)
375 errno = ERANGE;
376 if (file_handle != INVALID_HANDLE_VALUE)
377 CloseHandle(file_handle);
378 tor_munmap_file(res);
379 return NULL;
382 /* Unmap the file, and return 0 for success or -1 for failure */
384 tor_munmap_file(tor_mmap_t *handle)
386 if (handle == NULL)
387 return 0;
389 if (handle->data) {
390 /* This is an ugly cast, but without it, "data" in struct tor_mmap_t would
391 have to be redefined as non-const. */
392 BOOL ok = UnmapViewOfFile( (LPVOID) handle->data);
393 if (!ok) {
394 log_warn(LD_FS, "Failed to UnmapViewOfFile() in tor_munmap_file(): %d",
395 (int)GetLastError());
399 if (handle->mmap_handle != NULL)
400 CloseHandle(handle->mmap_handle);
401 tor_free(handle);
403 return 0;
405 #else
406 tor_mmap_t *
407 tor_mmap_file(const char *filename)
409 struct stat st;
410 char *res = read_file_to_str(filename, RFTS_BIN|RFTS_IGNORE_MISSING, &st);
411 tor_mmap_t *handle;
412 if (! res)
413 return NULL;
414 handle = tor_malloc_zero(sizeof(tor_mmap_t));
415 handle->data = res;
416 handle->size = st.st_size;
417 return handle;
420 /** Unmap the file mapped with tor_mmap_file(), and return 0 for success
421 * or -1 for failure.
425 tor_munmap_file(tor_mmap_t *handle)
427 char *d = NULL;
428 if (handle == NULL)
429 return 0;
431 d = (char*)handle->data;
432 tor_free(d);
433 memwipe(handle, 0, sizeof(tor_mmap_t));
434 tor_free(handle);
436 /* Can't fail in this mmap()/munmap()-free case */
437 return 0;
439 #endif
441 /** Replacement for snprintf. Differs from platform snprintf in two
442 * ways: First, always NUL-terminates its output. Second, always
443 * returns -1 if the result is truncated. (Note that this return
444 * behavior does <i>not</i> conform to C99; it just happens to be
445 * easier to emulate "return -1" with conformant implementations than
446 * it is to emulate "return number that would be written" with
447 * non-conformant implementations.) */
449 tor_snprintf(char *str, size_t size, const char *format, ...)
451 va_list ap;
452 int r;
453 va_start(ap,format);
454 r = tor_vsnprintf(str,size,format,ap);
455 va_end(ap);
456 return r;
459 /** Replacement for vsnprintf; behavior differs as tor_snprintf differs from
460 * snprintf.
463 tor_vsnprintf(char *str, size_t size, const char *format, va_list args)
465 int r;
466 if (size == 0)
467 return -1; /* no place for the NUL */
468 if (size > SIZE_T_CEILING)
469 return -1;
470 #ifdef _WIN32
471 r = _vsnprintf(str, size, format, args);
472 #else
473 r = vsnprintf(str, size, format, args);
474 #endif
475 str[size-1] = '\0';
476 if (r < 0 || r >= (ssize_t)size)
477 return -1;
478 return r;
482 * Portable asprintf implementation. Does a printf() into a newly malloc'd
483 * string. Sets *<b>strp</b> to this string, and returns its length (not
484 * including the terminating NUL character).
486 * You can treat this function as if its implementation were something like
487 <pre>
488 char buf[_INFINITY_];
489 tor_snprintf(buf, sizeof(buf), fmt, args);
490 *strp = tor_strdup(buf);
491 return strlen(*strp):
492 </pre>
493 * Where _INFINITY_ is an imaginary constant so big that any string can fit
494 * into it.
497 tor_asprintf(char **strp, const char *fmt, ...)
499 int r;
500 va_list args;
501 va_start(args, fmt);
502 r = tor_vasprintf(strp, fmt, args);
503 va_end(args);
504 if (!*strp || r < 0) {
505 /* LCOV_EXCL_START */
506 log_err(LD_BUG, "Internal error in asprintf");
507 tor_assert(0);
508 /* LCOV_EXCL_STOP */
510 return r;
514 * Portable vasprintf implementation. Does a printf() into a newly malloc'd
515 * string. Differs from regular vasprintf in the same ways that
516 * tor_asprintf() differs from regular asprintf.
519 tor_vasprintf(char **strp, const char *fmt, va_list args)
521 /* use a temporary variable in case *strp is in args. */
522 char *strp_tmp=NULL;
523 #ifdef HAVE_VASPRINTF
524 /* If the platform gives us one, use it. */
525 int r = vasprintf(&strp_tmp, fmt, args);
526 if (r < 0)
527 *strp = NULL;
528 else
529 *strp = strp_tmp;
530 return r;
531 #elif defined(HAVE__VSCPRINTF)
532 /* On Windows, _vsnprintf won't tell us the length of the string if it
533 * overflows, so we need to use _vcsprintf to tell how much to allocate */
534 int len, r;
535 va_list tmp_args;
536 va_copy(tmp_args, args);
537 len = _vscprintf(fmt, tmp_args);
538 va_end(tmp_args);
539 if (len < 0) {
540 *strp = NULL;
541 return -1;
543 strp_tmp = tor_malloc(len + 1);
544 r = _vsnprintf(strp_tmp, len+1, fmt, args);
545 if (r != len) {
546 tor_free(strp_tmp);
547 *strp = NULL;
548 return -1;
550 *strp = strp_tmp;
551 return len;
552 #else
553 /* Everywhere else, we have a decent vsnprintf that tells us how many
554 * characters we need. We give it a try on a short buffer first, since
555 * it might be nice to avoid the second vsnprintf call.
557 char buf[128];
558 int len, r;
559 va_list tmp_args;
560 va_copy(tmp_args, args);
561 /* vsnprintf() was properly checked but tor_vsnprintf() available so
562 * why not use it? */
563 len = tor_vsnprintf(buf, sizeof(buf), fmt, tmp_args);
564 va_end(tmp_args);
565 if (len < (int)sizeof(buf)) {
566 *strp = tor_strdup(buf);
567 return len;
569 strp_tmp = tor_malloc(len+1);
570 /* use of tor_vsnprintf() will ensure string is null terminated */
571 r = tor_vsnprintf(strp_tmp, len+1, fmt, args);
572 if (r != len) {
573 tor_free(strp_tmp);
574 *strp = NULL;
575 return -1;
577 *strp = strp_tmp;
578 return len;
579 #endif
582 /** Given <b>hlen</b> bytes at <b>haystack</b> and <b>nlen</b> bytes at
583 * <b>needle</b>, return a pointer to the first occurrence of the needle
584 * within the haystack, or NULL if there is no such occurrence.
586 * This function is <em>not</em> timing-safe.
588 * Requires that <b>nlen</b> be greater than zero.
590 const void *
591 tor_memmem(const void *_haystack, size_t hlen,
592 const void *_needle, size_t nlen)
594 #if defined(HAVE_MEMMEM) && (!defined(__GNUC__) || __GNUC__ >= 2)
595 tor_assert(nlen);
596 return memmem(_haystack, hlen, _needle, nlen);
597 #else
598 /* This isn't as fast as the GLIBC implementation, but it doesn't need to
599 * be. */
600 const char *p, *last_possible_start;
601 const char *haystack = (const char*)_haystack;
602 const char *needle = (const char*)_needle;
603 char first;
604 tor_assert(nlen);
606 if (nlen > hlen)
607 return NULL;
609 p = haystack;
610 /* Last position at which the needle could start. */
611 last_possible_start = haystack + hlen - nlen;
612 first = *(const char*)needle;
613 while ((p = memchr(p, first, last_possible_start + 1 - p))) {
614 if (fast_memeq(p, needle, nlen))
615 return p;
616 if (++p > last_possible_start) {
617 /* This comparison shouldn't be necessary, since if p was previously
618 * equal to last_possible_start, the next memchr call would be
619 * "memchr(p, first, 0)", which will return NULL. But it clarifies the
620 * logic. */
621 return NULL;
624 return NULL;
625 #endif
629 * Tables to implement ctypes-replacement TOR_IS*() functions. Each table
630 * has 256 bits to look up whether a character is in some set or not. This
631 * fails on non-ASCII platforms, but it is hard to find a platform whose
632 * character set is not a superset of ASCII nowadays. */
634 /**@{*/
635 const uint32_t TOR_ISALPHA_TABLE[8] =
636 { 0, 0, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
637 const uint32_t TOR_ISALNUM_TABLE[8] =
638 { 0, 0x3ff0000, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
639 const uint32_t TOR_ISSPACE_TABLE[8] = { 0x3e00, 0x1, 0, 0, 0, 0, 0, 0 };
640 const uint32_t TOR_ISXDIGIT_TABLE[8] =
641 { 0, 0x3ff0000, 0x7e, 0x7e, 0, 0, 0, 0 };
642 const uint32_t TOR_ISDIGIT_TABLE[8] = { 0, 0x3ff0000, 0, 0, 0, 0, 0, 0 };
643 const uint32_t TOR_ISPRINT_TABLE[8] =
644 { 0, 0xffffffff, 0xffffffff, 0x7fffffff, 0, 0, 0, 0x0 };
645 const uint32_t TOR_ISUPPER_TABLE[8] = { 0, 0, 0x7fffffe, 0, 0, 0, 0, 0 };
646 const uint32_t TOR_ISLOWER_TABLE[8] = { 0, 0, 0, 0x7fffffe, 0, 0, 0, 0 };
648 /** Upper-casing and lowercasing tables to map characters to upper/lowercase
649 * equivalents. Used by tor_toupper() and tor_tolower(). */
650 /**@{*/
651 const uint8_t TOR_TOUPPER_TABLE[256] = {
652 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
653 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
654 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
655 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
656 64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
657 80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
658 96,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
659 80,81,82,83,84,85,86,87,88,89,90,123,124,125,126,127,
660 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
661 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
662 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
663 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
664 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
665 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
666 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
667 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
669 const uint8_t TOR_TOLOWER_TABLE[256] = {
670 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
671 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
672 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
673 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
674 64,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
675 112,113,114,115,116,117,118,119,120,121,122,91,92,93,94,95,
676 96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
677 112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
678 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
679 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
680 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
681 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
682 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
683 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
684 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
685 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
687 /**@}*/
689 /** Helper for tor_strtok_r_impl: Advances cp past all characters in
690 * <b>sep</b>, and returns its new value. */
691 static char *
692 strtok_helper(char *cp, const char *sep)
694 if (sep[1]) {
695 while (*cp && strchr(sep, *cp))
696 ++cp;
697 } else {
698 while (*cp && *cp == *sep)
699 ++cp;
701 return cp;
704 /** Implementation of strtok_r for platforms whose coders haven't figured out
705 * how to write one. Hey, retrograde libc developers! You can use this code
706 * here for free! */
707 char *
708 tor_strtok_r_impl(char *str, const char *sep, char **lasts)
710 char *cp, *start;
711 tor_assert(*sep);
712 if (str) {
713 str = strtok_helper(str, sep);
714 if (!*str)
715 return NULL;
716 start = cp = *lasts = str;
717 } else if (!*lasts || !**lasts) {
718 return NULL;
719 } else {
720 start = cp = *lasts;
723 if (sep[1]) {
724 while (*cp && !strchr(sep, *cp))
725 ++cp;
726 } else {
727 cp = strchr(cp, *sep);
730 if (!cp || !*cp) {
731 *lasts = NULL;
732 } else {
733 *cp++ = '\0';
734 *lasts = strtok_helper(cp, sep);
736 return start;
739 #ifdef _WIN32
740 /** Take a filename and return a pointer to its final element. This
741 * function is called on __FILE__ to fix a MSVC nit where __FILE__
742 * contains the full path to the file. This is bad, because it
743 * confuses users to find the home directory of the person who
744 * compiled the binary in their warning messages.
746 const char *
747 tor_fix_source_file(const char *fname)
749 const char *cp1, *cp2, *r;
750 cp1 = strrchr(fname, '/');
751 cp2 = strrchr(fname, '\\');
752 if (cp1 && cp2) {
753 r = (cp1<cp2)?(cp2+1):(cp1+1);
754 } else if (cp1) {
755 r = cp1+1;
756 } else if (cp2) {
757 r = cp2+1;
758 } else {
759 r = fname;
761 return r;
763 #endif
766 * Read a 16-bit value beginning at <b>cp</b>. Equivalent to
767 * *(uint16_t*)(cp), but will not cause segfaults on platforms that forbid
768 * unaligned memory access.
770 uint16_t
771 get_uint16(const void *cp)
773 uint16_t v;
774 memcpy(&v,cp,2);
775 return v;
778 * Read a 32-bit value beginning at <b>cp</b>. Equivalent to
779 * *(uint32_t*)(cp), but will not cause segfaults on platforms that forbid
780 * unaligned memory access.
782 uint32_t
783 get_uint32(const void *cp)
785 uint32_t v;
786 memcpy(&v,cp,4);
787 return v;
790 * Read a 64-bit value beginning at <b>cp</b>. Equivalent to
791 * *(uint64_t*)(cp), but will not cause segfaults on platforms that forbid
792 * unaligned memory access.
794 uint64_t
795 get_uint64(const void *cp)
797 uint64_t v;
798 memcpy(&v,cp,8);
799 return v;
803 * Set a 16-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
804 * *(uint16_t*)(cp) = v, but will not cause segfaults on platforms that forbid
805 * unaligned memory access. */
806 void
807 set_uint16(void *cp, uint16_t v)
809 memcpy(cp,&v,2);
812 * Set a 32-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
813 * *(uint32_t*)(cp) = v, but will not cause segfaults on platforms that forbid
814 * unaligned memory access. */
815 void
816 set_uint32(void *cp, uint32_t v)
818 memcpy(cp,&v,4);
821 * Set a 64-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
822 * *(uint64_t*)(cp) = v, but will not cause segfaults on platforms that forbid
823 * unaligned memory access. */
824 void
825 set_uint64(void *cp, uint64_t v)
827 memcpy(cp,&v,8);
831 * Rename the file <b>from</b> to the file <b>to</b>. On Unix, this is
832 * the same as rename(2). On windows, this removes <b>to</b> first if
833 * it already exists.
834 * Returns 0 on success. Returns -1 and sets errno on failure.
837 replace_file(const char *from, const char *to)
839 #ifndef _WIN32
840 return tor_rename(from, to);
841 #else
842 switch (file_status(to))
844 case FN_NOENT:
845 break;
846 case FN_FILE:
847 case FN_EMPTY:
848 if (unlink(to)) return -1;
849 break;
850 case FN_ERROR:
851 return -1;
852 case FN_DIR:
853 errno = EISDIR;
854 return -1;
856 return tor_rename(from,to);
857 #endif
860 /** Change <b>fname</b>'s modification time to now. */
862 touch_file(const char *fname)
864 if (utime(fname, NULL)!=0)
865 return -1;
866 return 0;
869 /** Represents a lockfile on which we hold the lock. */
870 struct tor_lockfile_t {
871 /** Name of the file */
872 char *filename;
873 /** File descriptor used to hold the file open */
874 int fd;
877 /** Try to get a lock on the lockfile <b>filename</b>, creating it as
878 * necessary. If someone else has the lock and <b>blocking</b> is true,
879 * wait until the lock is available. Otherwise return immediately whether
880 * we succeeded or not.
882 * Set *<b>locked_out</b> to true if somebody else had the lock, and to false
883 * otherwise.
885 * Return a <b>tor_lockfile_t</b> on success, NULL on failure.
887 * (Implementation note: because we need to fall back to fcntl on some
888 * platforms, these locks are per-process, not per-thread. If you want
889 * to do in-process locking, use tor_mutex_t like a normal person.
890 * On Windows, when <b>blocking</b> is true, the maximum time that
891 * is actually waited is 10 seconds, after which NULL is returned
892 * and <b>locked_out</b> is set to 1.)
894 tor_lockfile_t *
895 tor_lockfile_lock(const char *filename, int blocking, int *locked_out)
897 tor_lockfile_t *result;
898 int fd;
899 *locked_out = 0;
901 log_info(LD_FS, "Locking \"%s\"", filename);
902 fd = tor_open_cloexec(filename, O_RDWR|O_CREAT|O_TRUNC, 0600);
903 if (fd < 0) {
904 log_warn(LD_FS,"Couldn't open \"%s\" for locking: %s", filename,
905 strerror(errno));
906 return NULL;
909 #ifdef _WIN32
910 _lseek(fd, 0, SEEK_SET);
911 if (_locking(fd, blocking ? _LK_LOCK : _LK_NBLCK, 1) < 0) {
912 if (errno != EACCES && errno != EDEADLOCK)
913 log_warn(LD_FS,"Couldn't lock \"%s\": %s", filename, strerror(errno));
914 else
915 *locked_out = 1;
916 close(fd);
917 return NULL;
919 #elif defined(HAVE_FLOCK)
920 if (flock(fd, LOCK_EX|(blocking ? 0 : LOCK_NB)) < 0) {
921 if (errno != EWOULDBLOCK)
922 log_warn(LD_FS,"Couldn't lock \"%s\": %s", filename, strerror(errno));
923 else
924 *locked_out = 1;
925 close(fd);
926 return NULL;
928 #else
930 struct flock lock;
931 memset(&lock, 0, sizeof(lock));
932 lock.l_type = F_WRLCK;
933 lock.l_whence = SEEK_SET;
934 if (fcntl(fd, blocking ? F_SETLKW : F_SETLK, &lock) < 0) {
935 if (errno != EACCES && errno != EAGAIN)
936 log_warn(LD_FS, "Couldn't lock \"%s\": %s", filename, strerror(errno));
937 else
938 *locked_out = 1;
939 close(fd);
940 return NULL;
943 #endif
945 result = tor_malloc(sizeof(tor_lockfile_t));
946 result->filename = tor_strdup(filename);
947 result->fd = fd;
948 return result;
951 /** Release the lock held as <b>lockfile</b>. */
952 void
953 tor_lockfile_unlock(tor_lockfile_t *lockfile)
955 tor_assert(lockfile);
957 log_info(LD_FS, "Unlocking \"%s\"", lockfile->filename);
958 #ifdef _WIN32
959 _lseek(lockfile->fd, 0, SEEK_SET);
960 if (_locking(lockfile->fd, _LK_UNLCK, 1) < 0) {
961 log_warn(LD_FS,"Error unlocking \"%s\": %s", lockfile->filename,
962 strerror(errno));
964 #elif defined(HAVE_FLOCK)
965 if (flock(lockfile->fd, LOCK_UN) < 0) {
966 log_warn(LD_FS, "Error unlocking \"%s\": %s", lockfile->filename,
967 strerror(errno));
969 #else
970 /* Closing the lockfile is sufficient. */
971 #endif
973 close(lockfile->fd);
974 lockfile->fd = -1;
975 tor_free(lockfile->filename);
976 tor_free(lockfile);
979 /** @{ */
980 /** Some old versions of Unix didn't define constants for these values,
981 * and instead expect you to say 0, 1, or 2. */
982 #ifndef SEEK_SET
983 #define SEEK_SET 0
984 #endif
985 #ifndef SEEK_CUR
986 #define SEEK_CUR 1
987 #endif
988 #ifndef SEEK_END
989 #define SEEK_END 2
990 #endif
991 /** @} */
993 /** Return the position of <b>fd</b> with respect to the start of the file. */
994 off_t
995 tor_fd_getpos(int fd)
997 #ifdef _WIN32
998 return (off_t) _lseek(fd, 0, SEEK_CUR);
999 #else
1000 return (off_t) lseek(fd, 0, SEEK_CUR);
1001 #endif
1004 /** Move <b>fd</b> to the end of the file. Return -1 on error, 0 on success.
1005 * If the file is a pipe, do nothing and succeed.
1008 tor_fd_seekend(int fd)
1010 #ifdef _WIN32
1011 return _lseek(fd, 0, SEEK_END) < 0 ? -1 : 0;
1012 #else
1013 off_t rc = lseek(fd, 0, SEEK_END) < 0 ? -1 : 0;
1014 #ifdef ESPIPE
1015 /* If we get an error and ESPIPE, then it's a pipe or a socket of a fifo:
1016 * no need to worry. */
1017 if (rc < 0 && errno == ESPIPE)
1018 rc = 0;
1019 #endif
1020 return (rc < 0) ? -1 : 0;
1021 #endif
1024 /** Move <b>fd</b> to position <b>pos</b> in the file. Return -1 on error, 0
1025 * on success. */
1027 tor_fd_setpos(int fd, off_t pos)
1029 #ifdef _WIN32
1030 return _lseek(fd, pos, SEEK_SET) < 0 ? -1 : 0;
1031 #else
1032 return lseek(fd, pos, SEEK_SET) < 0 ? -1 : 0;
1033 #endif
1036 /** Replacement for ftruncate(fd, 0): move to the front of the file and remove
1037 * all the rest of the file. Return -1 on error, 0 on success. */
1039 tor_ftruncate(int fd)
1041 /* Rumor has it that some versions of ftruncate do not move the file pointer.
1043 if (tor_fd_setpos(fd, 0) < 0)
1044 return -1;
1046 #ifdef _WIN32
1047 return _chsize(fd, 0);
1048 #else
1049 return ftruncate(fd, 0);
1050 #endif
1053 #undef DEBUG_SOCKET_COUNTING
1054 #ifdef DEBUG_SOCKET_COUNTING
1055 /** A bitarray of all fds that should be passed to tor_socket_close(). Only
1056 * used if DEBUG_SOCKET_COUNTING is defined. */
1057 static bitarray_t *open_sockets = NULL;
1058 /** The size of <b>open_sockets</b>, in bits. */
1059 static int max_socket = -1;
1060 #endif
1062 /** Count of number of sockets currently open. (Undercounts sockets opened by
1063 * eventdns and libevent.) */
1064 static int n_sockets_open = 0;
1066 /** Mutex to protect open_sockets, max_socket, and n_sockets_open. */
1067 static tor_mutex_t *socket_accounting_mutex = NULL;
1069 /** Helper: acquire the socket accounting lock. */
1070 static inline void
1071 socket_accounting_lock(void)
1073 if (PREDICT_UNLIKELY(!socket_accounting_mutex))
1074 socket_accounting_mutex = tor_mutex_new();
1075 tor_mutex_acquire(socket_accounting_mutex);
1078 /** Helper: release the socket accounting lock. */
1079 static inline void
1080 socket_accounting_unlock(void)
1082 tor_mutex_release(socket_accounting_mutex);
1085 /** As close(), but guaranteed to work for sockets across platforms (including
1086 * Windows, where close()ing a socket doesn't work. Returns 0 on success and
1087 * the socket error code on failure. */
1089 tor_close_socket_simple(tor_socket_t s)
1091 int r = 0;
1093 /* On Windows, you have to call close() on fds returned by open(),
1094 * and closesocket() on fds returned by socket(). On Unix, everything
1095 * gets close()'d. We abstract this difference by always using
1096 * tor_close_socket to close sockets, and always using close() on
1097 * files.
1099 #if defined(_WIN32)
1100 r = closesocket(s);
1101 #else
1102 r = close(s);
1103 #endif
1105 if (r != 0) {
1106 int err = tor_socket_errno(-1);
1107 log_info(LD_NET, "Close returned an error: %s", tor_socket_strerror(err));
1108 return err;
1111 return r;
1114 /** As tor_close_socket_simple(), but keeps track of the number
1115 * of open sockets. Returns 0 on success, -1 on failure. */
1116 MOCK_IMPL(int,
1117 tor_close_socket,(tor_socket_t s))
1119 int r = tor_close_socket_simple(s);
1121 socket_accounting_lock();
1122 #ifdef DEBUG_SOCKET_COUNTING
1123 if (s > max_socket || ! bitarray_is_set(open_sockets, s)) {
1124 log_warn(LD_BUG, "Closing a socket (%d) that wasn't returned by tor_open_"
1125 "socket(), or that was already closed or something.", s);
1126 } else {
1127 tor_assert(open_sockets && s <= max_socket);
1128 bitarray_clear(open_sockets, s);
1130 #endif
1131 if (r == 0) {
1132 --n_sockets_open;
1133 } else {
1134 #ifdef _WIN32
1135 if (r != WSAENOTSOCK)
1136 --n_sockets_open;
1137 #else
1138 if (r != EBADF)
1139 --n_sockets_open; // LCOV_EXCL_LINE -- EIO and EINTR too hard to force.
1140 #endif
1141 r = -1;
1144 tor_assert_nonfatal(n_sockets_open >= 0);
1145 socket_accounting_unlock();
1146 return r;
1149 /** @{ */
1150 #ifdef DEBUG_SOCKET_COUNTING
1151 /** Helper: if DEBUG_SOCKET_COUNTING is enabled, remember that <b>s</b> is
1152 * now an open socket. */
1153 static inline void
1154 mark_socket_open(tor_socket_t s)
1156 /* XXXX This bitarray business will NOT work on windows: sockets aren't
1157 small ints there. */
1158 if (s > max_socket) {
1159 if (max_socket == -1) {
1160 open_sockets = bitarray_init_zero(s+128);
1161 max_socket = s+128;
1162 } else {
1163 open_sockets = bitarray_expand(open_sockets, max_socket, s+128);
1164 max_socket = s+128;
1167 if (bitarray_is_set(open_sockets, s)) {
1168 log_warn(LD_BUG, "I thought that %d was already open, but socket() just "
1169 "gave it to me!", s);
1171 bitarray_set(open_sockets, s);
1173 #else
1174 #define mark_socket_open(s) STMT_NIL
1175 #endif
1176 /** @} */
1178 /** As socket(), but counts the number of open sockets. */
1179 MOCK_IMPL(tor_socket_t,
1180 tor_open_socket,(int domain, int type, int protocol))
1182 return tor_open_socket_with_extensions(domain, type, protocol, 1, 0);
1185 /** Mockable wrapper for connect(). */
1186 MOCK_IMPL(tor_socket_t,
1187 tor_connect_socket,(tor_socket_t sock, const struct sockaddr *address,
1188 socklen_t address_len))
1190 return connect(sock,address,address_len);
1193 /** As socket(), but creates a nonblocking socket and
1194 * counts the number of open sockets. */
1195 tor_socket_t
1196 tor_open_socket_nonblocking(int domain, int type, int protocol)
1198 return tor_open_socket_with_extensions(domain, type, protocol, 1, 1);
1201 /** As socket(), but counts the number of open sockets and handles
1202 * socket creation with either of SOCK_CLOEXEC and SOCK_NONBLOCK specified.
1203 * <b>cloexec</b> and <b>nonblock</b> should be either 0 or 1 to indicate
1204 * if the corresponding extension should be used.*/
1205 tor_socket_t
1206 tor_open_socket_with_extensions(int domain, int type, int protocol,
1207 int cloexec, int nonblock)
1209 tor_socket_t s;
1211 /* We are about to create a new file descriptor so make sure we have
1212 * enough of them. */
1213 if (get_n_open_sockets() >= max_sockets - 1) {
1214 #ifdef _WIN32
1215 WSASetLastError(WSAEMFILE);
1216 #else
1217 errno = EMFILE;
1218 #endif
1219 return TOR_INVALID_SOCKET;
1222 #if defined(SOCK_CLOEXEC) && defined(SOCK_NONBLOCK)
1223 int ext_flags = (cloexec ? SOCK_CLOEXEC : 0) |
1224 (nonblock ? SOCK_NONBLOCK : 0);
1225 s = socket(domain, type|ext_flags, protocol);
1226 if (SOCKET_OK(s))
1227 goto socket_ok;
1228 /* If we got an error, see if it is EINVAL. EINVAL might indicate that,
1229 * even though we were built on a system with SOCK_CLOEXEC and SOCK_NONBLOCK
1230 * support, we are running on one without. */
1231 if (errno != EINVAL)
1232 return s;
1233 #endif /* SOCK_CLOEXEC && SOCK_NONBLOCK */
1235 s = socket(domain, type, protocol);
1236 if (! SOCKET_OK(s))
1237 return s;
1239 #if defined(FD_CLOEXEC)
1240 if (cloexec) {
1241 if (fcntl(s, F_SETFD, FD_CLOEXEC) == -1) {
1242 log_warn(LD_FS,"Couldn't set FD_CLOEXEC: %s", strerror(errno));
1243 tor_close_socket_simple(s);
1244 return TOR_INVALID_SOCKET;
1247 #else
1248 (void)cloexec;
1249 #endif
1251 if (nonblock) {
1252 if (set_socket_nonblocking(s) == -1) {
1253 tor_close_socket_simple(s);
1254 return TOR_INVALID_SOCKET;
1258 goto socket_ok; /* So that socket_ok will not be unused. */
1260 socket_ok:
1261 socket_accounting_lock();
1262 ++n_sockets_open;
1263 mark_socket_open(s);
1264 socket_accounting_unlock();
1265 return s;
1268 /** As accept(), but counts the number of open sockets. */
1269 tor_socket_t
1270 tor_accept_socket(tor_socket_t sockfd, struct sockaddr *addr, socklen_t *len)
1272 return tor_accept_socket_with_extensions(sockfd, addr, len, 1, 0);
1275 /** As accept(), but returns a nonblocking socket and
1276 * counts the number of open sockets. */
1277 tor_socket_t
1278 tor_accept_socket_nonblocking(tor_socket_t sockfd, struct sockaddr *addr,
1279 socklen_t *len)
1281 return tor_accept_socket_with_extensions(sockfd, addr, len, 1, 1);
1284 /** As accept(), but counts the number of open sockets and handles
1285 * socket creation with either of SOCK_CLOEXEC and SOCK_NONBLOCK specified.
1286 * <b>cloexec</b> and <b>nonblock</b> should be either 0 or 1 to indicate
1287 * if the corresponding extension should be used.*/
1288 tor_socket_t
1289 tor_accept_socket_with_extensions(tor_socket_t sockfd, struct sockaddr *addr,
1290 socklen_t *len, int cloexec, int nonblock)
1292 tor_socket_t s;
1294 /* We are about to create a new file descriptor so make sure we have
1295 * enough of them. */
1296 if (get_n_open_sockets() >= max_sockets - 1) {
1297 #ifdef _WIN32
1298 WSASetLastError(WSAEMFILE);
1299 #else
1300 errno = EMFILE;
1301 #endif
1302 return TOR_INVALID_SOCKET;
1305 #if defined(HAVE_ACCEPT4) && defined(SOCK_CLOEXEC) && defined(SOCK_NONBLOCK)
1306 int ext_flags = (cloexec ? SOCK_CLOEXEC : 0) |
1307 (nonblock ? SOCK_NONBLOCK : 0);
1308 s = accept4(sockfd, addr, len, ext_flags);
1309 if (SOCKET_OK(s))
1310 goto socket_ok;
1311 /* If we got an error, see if it is ENOSYS. ENOSYS indicates that,
1312 * even though we were built on a system with accept4 support, we
1313 * are running on one without. Also, check for EINVAL, which indicates that
1314 * we are missing SOCK_CLOEXEC/SOCK_NONBLOCK support. */
1315 if (errno != EINVAL && errno != ENOSYS)
1316 return s;
1317 #endif
1319 s = accept(sockfd, addr, len);
1320 if (!SOCKET_OK(s))
1321 return s;
1323 #if defined(FD_CLOEXEC)
1324 if (cloexec) {
1325 if (fcntl(s, F_SETFD, FD_CLOEXEC) == -1) {
1326 log_warn(LD_NET, "Couldn't set FD_CLOEXEC: %s", strerror(errno));
1327 tor_close_socket_simple(s);
1328 return TOR_INVALID_SOCKET;
1331 #else
1332 (void)cloexec;
1333 #endif
1335 if (nonblock) {
1336 if (set_socket_nonblocking(s) == -1) {
1337 tor_close_socket_simple(s);
1338 return TOR_INVALID_SOCKET;
1342 goto socket_ok; /* So that socket_ok will not be unused. */
1344 socket_ok:
1345 socket_accounting_lock();
1346 ++n_sockets_open;
1347 mark_socket_open(s);
1348 socket_accounting_unlock();
1349 return s;
1352 /** Return the number of sockets we currently have opened. */
1354 get_n_open_sockets(void)
1356 int n;
1357 socket_accounting_lock();
1358 n = n_sockets_open;
1359 socket_accounting_unlock();
1360 return n;
1363 /** Mockable wrapper for getsockname(). */
1364 MOCK_IMPL(int,
1365 tor_getsockname,(tor_socket_t sock, struct sockaddr *address,
1366 socklen_t *address_len))
1368 return getsockname(sock, address, address_len);
1371 /** Turn <b>socket</b> into a nonblocking socket. Return 0 on success, -1
1372 * on failure.
1375 set_socket_nonblocking(tor_socket_t sock)
1377 #if defined(_WIN32)
1378 unsigned long nonblocking = 1;
1379 ioctlsocket(sock, FIONBIO, (unsigned long*) &nonblocking);
1380 #else
1381 int flags;
1383 flags = fcntl(sock, F_GETFL, 0);
1384 if (flags == -1) {
1385 log_warn(LD_NET, "Couldn't get file status flags: %s", strerror(errno));
1386 return -1;
1388 flags |= O_NONBLOCK;
1389 if (fcntl(sock, F_SETFL, flags) == -1) {
1390 log_warn(LD_NET, "Couldn't set file status flags: %s", strerror(errno));
1391 return -1;
1393 #endif
1395 return 0;
1399 * Allocate a pair of connected sockets. (Like socketpair(family,
1400 * type,protocol,fd), but works on systems that don't have
1401 * socketpair.)
1403 * Currently, only (AF_UNIX, SOCK_STREAM, 0) sockets are supported.
1405 * Note that on systems without socketpair, this call will fail if
1406 * localhost is inaccessible (for example, if the networking
1407 * stack is down). And even if it succeeds, the socket pair will not
1408 * be able to read while localhost is down later (the socket pair may
1409 * even close, depending on OS-specific timeouts).
1411 * Returns 0 on success and -errno on failure; do not rely on the value
1412 * of errno or WSAGetLastError().
1414 /* It would be nicer just to set errno, but that won't work for windows. */
1416 tor_socketpair(int family, int type, int protocol, tor_socket_t fd[2])
1418 //don't use win32 socketpairs (they are always bad)
1419 #if defined(HAVE_SOCKETPAIR) && !defined(_WIN32)
1420 int r;
1422 #ifdef SOCK_CLOEXEC
1423 r = socketpair(family, type|SOCK_CLOEXEC, protocol, fd);
1424 if (r == 0)
1425 goto sockets_ok;
1426 /* If we got an error, see if it is EINVAL. EINVAL might indicate that,
1427 * even though we were built on a system with SOCK_CLOEXEC support, we
1428 * are running on one without. */
1429 if (errno != EINVAL)
1430 return -errno;
1431 #endif
1433 r = socketpair(family, type, protocol, fd);
1434 if (r < 0)
1435 return -errno;
1437 #if defined(FD_CLOEXEC)
1438 if (SOCKET_OK(fd[0])) {
1439 r = fcntl(fd[0], F_SETFD, FD_CLOEXEC);
1440 if (r == -1) {
1441 close(fd[0]);
1442 close(fd[1]);
1443 return -errno;
1446 if (SOCKET_OK(fd[1])) {
1447 r = fcntl(fd[1], F_SETFD, FD_CLOEXEC);
1448 if (r == -1) {
1449 close(fd[0]);
1450 close(fd[1]);
1451 return -errno;
1454 #endif
1455 goto sockets_ok; /* So that sockets_ok will not be unused. */
1457 sockets_ok:
1458 socket_accounting_lock();
1459 if (SOCKET_OK(fd[0])) {
1460 ++n_sockets_open;
1461 mark_socket_open(fd[0]);
1463 if (SOCKET_OK(fd[1])) {
1464 ++n_sockets_open;
1465 mark_socket_open(fd[1]);
1467 socket_accounting_unlock();
1469 return 0;
1470 #else
1471 return tor_ersatz_socketpair(family, type, protocol, fd);
1472 #endif
1475 #ifdef NEED_ERSATZ_SOCKETPAIR
1477 static inline socklen_t
1478 SIZEOF_SOCKADDR(int domain)
1480 switch (domain) {
1481 case AF_INET:
1482 return sizeof(struct sockaddr_in);
1483 case AF_INET6:
1484 return sizeof(struct sockaddr_in6);
1485 default:
1486 return 0;
1491 * Helper used to implement socketpair on systems that lack it, by
1492 * making a direct connection to localhost.
1494 STATIC int
1495 tor_ersatz_socketpair(int family, int type, int protocol, tor_socket_t fd[2])
1497 /* This socketpair does not work when localhost is down. So
1498 * it's really not the same thing at all. But it's close enough
1499 * for now, and really, when localhost is down sometimes, we
1500 * have other problems too.
1502 tor_socket_t listener = TOR_INVALID_SOCKET;
1503 tor_socket_t connector = TOR_INVALID_SOCKET;
1504 tor_socket_t acceptor = TOR_INVALID_SOCKET;
1505 tor_addr_t listen_tor_addr;
1506 struct sockaddr_storage connect_addr_ss, listen_addr_ss;
1507 struct sockaddr *listen_addr = (struct sockaddr *) &listen_addr_ss;
1508 uint16_t listen_port = 0;
1509 tor_addr_t connect_tor_addr;
1510 uint16_t connect_port = 0;
1511 struct sockaddr *connect_addr = (struct sockaddr *) &connect_addr_ss;
1512 socklen_t size;
1513 int saved_errno = -1;
1514 int ersatz_domain = AF_INET;
1516 memset(&connect_tor_addr, 0, sizeof(connect_tor_addr));
1517 memset(&connect_addr_ss, 0, sizeof(connect_addr_ss));
1518 memset(&listen_tor_addr, 0, sizeof(listen_tor_addr));
1519 memset(&listen_addr_ss, 0, sizeof(listen_addr_ss));
1521 if (protocol
1522 #ifdef AF_UNIX
1523 || family != AF_UNIX
1524 #endif
1526 #ifdef _WIN32
1527 return -WSAEAFNOSUPPORT;
1528 #else
1529 return -EAFNOSUPPORT;
1530 #endif
1532 if (!fd) {
1533 return -EINVAL;
1536 listener = tor_open_socket(ersatz_domain, type, 0);
1537 if (!SOCKET_OK(listener)) {
1538 int first_errno = tor_socket_errno(-1);
1539 if (first_errno == SOCK_ERRNO(EPROTONOSUPPORT)
1540 && ersatz_domain == AF_INET) {
1541 /* Assume we're on an IPv6-only system */
1542 ersatz_domain = AF_INET6;
1543 listener = tor_open_socket(ersatz_domain, type, 0);
1544 if (!SOCKET_OK(listener)) {
1545 /* Keep the previous behaviour, which was to return the IPv4 error.
1546 * (This may be less informative on IPv6-only systems.)
1547 * XX/teor - is there a better way to decide which errno to return?
1548 * (I doubt we care much either way, once there is an error.)
1550 return -first_errno;
1554 /* If there is no 127.0.0.1 or ::1, this will and must fail. Otherwise, we
1555 * risk exposing a socketpair on a routable IP address. (Some BSD jails
1556 * use a routable address for localhost. Fortunately, they have the real
1557 * AF_UNIX socketpair.) */
1558 if (ersatz_domain == AF_INET) {
1559 tor_addr_from_ipv4h(&listen_tor_addr, INADDR_LOOPBACK);
1560 } else {
1561 tor_addr_parse(&listen_tor_addr, "[::1]");
1563 tor_assert(tor_addr_is_loopback(&listen_tor_addr));
1564 size = tor_addr_to_sockaddr(&listen_tor_addr,
1565 0 /* kernel chooses port. */,
1566 listen_addr,
1567 sizeof(listen_addr_ss));
1568 if (bind(listener, listen_addr, size) == -1)
1569 goto tidy_up_and_fail;
1570 if (listen(listener, 1) == -1)
1571 goto tidy_up_and_fail;
1573 connector = tor_open_socket(ersatz_domain, type, 0);
1574 if (!SOCKET_OK(connector))
1575 goto tidy_up_and_fail;
1576 /* We want to find out the port number to connect to. */
1577 size = sizeof(connect_addr_ss);
1578 if (getsockname(listener, connect_addr, &size) == -1)
1579 goto tidy_up_and_fail;
1580 if (size != SIZEOF_SOCKADDR (connect_addr->sa_family))
1581 goto abort_tidy_up_and_fail;
1582 if (connect(connector, connect_addr, size) == -1)
1583 goto tidy_up_and_fail;
1585 size = sizeof(listen_addr_ss);
1586 acceptor = tor_accept_socket(listener, listen_addr, &size);
1587 if (!SOCKET_OK(acceptor))
1588 goto tidy_up_and_fail;
1589 if (size != SIZEOF_SOCKADDR(listen_addr->sa_family))
1590 goto abort_tidy_up_and_fail;
1591 /* Now check we are talking to ourself by matching port and host on the
1592 two sockets. */
1593 if (getsockname(connector, connect_addr, &size) == -1)
1594 goto tidy_up_and_fail;
1595 /* Set *_tor_addr and *_port to the address and port that was used */
1596 tor_addr_from_sockaddr(&listen_tor_addr, listen_addr, &listen_port);
1597 tor_addr_from_sockaddr(&connect_tor_addr, connect_addr, &connect_port);
1598 if (size != SIZEOF_SOCKADDR (connect_addr->sa_family)
1599 || tor_addr_compare(&listen_tor_addr, &connect_tor_addr, CMP_SEMANTIC)
1600 || listen_port != connect_port) {
1601 goto abort_tidy_up_and_fail;
1603 tor_close_socket(listener);
1604 fd[0] = connector;
1605 fd[1] = acceptor;
1607 return 0;
1609 abort_tidy_up_and_fail:
1610 #ifdef _WIN32
1611 saved_errno = WSAECONNABORTED;
1612 #else
1613 saved_errno = ECONNABORTED; /* I hope this is portable and appropriate. */
1614 #endif
1615 tidy_up_and_fail:
1616 if (saved_errno < 0)
1617 saved_errno = errno;
1618 if (SOCKET_OK(listener))
1619 tor_close_socket(listener);
1620 if (SOCKET_OK(connector))
1621 tor_close_socket(connector);
1622 if (SOCKET_OK(acceptor))
1623 tor_close_socket(acceptor);
1624 return -saved_errno;
1627 #undef SIZEOF_SOCKADDR
1629 #endif
1631 /* Return the maximum number of allowed sockets. */
1633 get_max_sockets(void)
1635 return max_sockets;
1638 /** Number of extra file descriptors to keep in reserve beyond those that we
1639 * tell Tor it's allowed to use. */
1640 #define ULIMIT_BUFFER 32 /* keep 32 extra fd's beyond ConnLimit_ */
1642 /** Learn the maximum allowed number of file descriptors, and tell the
1643 * system we want to use up to that number. (Some systems have a low soft
1644 * limit, and let us set it higher.) We compute this by finding the largest
1645 * number that we can use.
1647 * If the limit is below the reserved file descriptor value (ULIMIT_BUFFER),
1648 * return -1 and <b>max_out</b> is untouched.
1650 * If we can't find a number greater than or equal to <b>limit</b>, then we
1651 * fail by returning -1 and <b>max_out</b> is untouched.
1653 * If we are unable to set the limit value because of setrlimit() failing,
1654 * return 0 and <b>max_out</b> is set to the current maximum value returned
1655 * by getrlimit().
1657 * Otherwise, return 0 and store the maximum we found inside <b>max_out</b>
1658 * and set <b>max_sockets</b> with that value as well.*/
1660 set_max_file_descriptors(rlim_t limit, int *max_out)
1662 if (limit < ULIMIT_BUFFER) {
1663 log_warn(LD_CONFIG,
1664 "ConnLimit must be at least %d. Failing.", ULIMIT_BUFFER);
1665 return -1;
1668 /* Define some maximum connections values for systems where we cannot
1669 * automatically determine a limit. Re Cygwin, see
1670 * http://archives.seul.org/or/talk/Aug-2006/msg00210.html
1671 * For an iPhone, 9999 should work. For Windows and all other unknown
1672 * systems we use 15000 as the default. */
1673 #ifndef HAVE_GETRLIMIT
1674 #if defined(CYGWIN) || defined(__CYGWIN__)
1675 const char *platform = "Cygwin";
1676 const unsigned long MAX_CONNECTIONS = 3200;
1677 #elif defined(_WIN32)
1678 const char *platform = "Windows";
1679 const unsigned long MAX_CONNECTIONS = 15000;
1680 #else
1681 const char *platform = "unknown platforms with no getrlimit()";
1682 const unsigned long MAX_CONNECTIONS = 15000;
1683 #endif
1684 log_fn(LOG_INFO, LD_NET,
1685 "This platform is missing getrlimit(). Proceeding.");
1686 if (limit > MAX_CONNECTIONS) {
1687 log_warn(LD_CONFIG,
1688 "We do not support more than %lu file descriptors "
1689 "on %s. Tried to raise to %lu.",
1690 (unsigned long)MAX_CONNECTIONS, platform, (unsigned long)limit);
1691 return -1;
1693 limit = MAX_CONNECTIONS;
1694 #else /* HAVE_GETRLIMIT */
1695 struct rlimit rlim;
1697 if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) {
1698 log_warn(LD_NET, "Could not get maximum number of file descriptors: %s",
1699 strerror(errno));
1700 return -1;
1702 if (rlim.rlim_max < limit) {
1703 log_warn(LD_CONFIG,"We need %lu file descriptors available, and we're "
1704 "limited to %lu. Please change your ulimit -n.",
1705 (unsigned long)limit, (unsigned long)rlim.rlim_max);
1706 return -1;
1709 if (rlim.rlim_max > rlim.rlim_cur) {
1710 log_info(LD_NET,"Raising max file descriptors from %lu to %lu.",
1711 (unsigned long)rlim.rlim_cur, (unsigned long)rlim.rlim_max);
1713 /* Set the current limit value so if the attempt to set the limit to the
1714 * max fails at least we'll have a valid value of maximum sockets. */
1715 *max_out = max_sockets = (int)rlim.rlim_cur - ULIMIT_BUFFER;
1716 rlim.rlim_cur = rlim.rlim_max;
1718 if (setrlimit(RLIMIT_NOFILE, &rlim) != 0) {
1719 int couldnt_set = 1;
1720 const int setrlimit_errno = errno;
1721 #ifdef OPEN_MAX
1722 uint64_t try_limit = OPEN_MAX - ULIMIT_BUFFER;
1723 if (errno == EINVAL && try_limit < (uint64_t) rlim.rlim_cur) {
1724 /* On some platforms, OPEN_MAX is the real limit, and getrlimit() is
1725 * full of nasty lies. I'm looking at you, OSX 10.5.... */
1726 rlim.rlim_cur = MIN(try_limit, rlim.rlim_cur);
1727 if (setrlimit(RLIMIT_NOFILE, &rlim) == 0) {
1728 if (rlim.rlim_cur < (rlim_t)limit) {
1729 log_warn(LD_CONFIG, "We are limited to %lu file descriptors by "
1730 "OPEN_MAX (%lu), and ConnLimit is %lu. Changing "
1731 "ConnLimit; sorry.",
1732 (unsigned long)try_limit, (unsigned long)OPEN_MAX,
1733 (unsigned long)limit);
1734 } else {
1735 log_info(LD_CONFIG, "Dropped connection limit to %lu based on "
1736 "OPEN_MAX (%lu); Apparently, %lu was too high and rlimit "
1737 "lied to us.",
1738 (unsigned long)try_limit, (unsigned long)OPEN_MAX,
1739 (unsigned long)rlim.rlim_max);
1741 couldnt_set = 0;
1744 #endif /* OPEN_MAX */
1745 if (couldnt_set) {
1746 log_warn(LD_CONFIG,"Couldn't set maximum number of file descriptors: %s",
1747 strerror(setrlimit_errno));
1750 /* leave some overhead for logs, etc, */
1751 limit = rlim.rlim_cur;
1752 #endif /* HAVE_GETRLIMIT */
1754 if (limit > INT_MAX)
1755 limit = INT_MAX;
1756 tor_assert(max_out);
1757 *max_out = max_sockets = (int)limit - ULIMIT_BUFFER;
1758 return 0;
1761 #ifndef _WIN32
1762 /** Log details of current user and group credentials. Return 0 on
1763 * success. Logs and return -1 on failure.
1765 static int
1766 log_credential_status(void)
1768 /** Log level to use when describing non-error UID/GID status. */
1769 #define CREDENTIAL_LOG_LEVEL LOG_INFO
1770 /* Real, effective and saved UIDs */
1771 uid_t ruid, euid, suid;
1772 /* Read, effective and saved GIDs */
1773 gid_t rgid, egid, sgid;
1774 /* Supplementary groups */
1775 gid_t *sup_gids = NULL;
1776 int sup_gids_size;
1777 /* Number of supplementary groups */
1778 int ngids;
1780 /* log UIDs */
1781 #ifdef HAVE_GETRESUID
1782 if (getresuid(&ruid, &euid, &suid) != 0 ) {
1783 log_warn(LD_GENERAL, "Error getting changed UIDs: %s", strerror(errno));
1784 return -1;
1785 } else {
1786 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
1787 "UID is %u (real), %u (effective), %u (saved)",
1788 (unsigned)ruid, (unsigned)euid, (unsigned)suid);
1790 #else
1791 /* getresuid is not present on MacOS X, so we can't get the saved (E)UID */
1792 ruid = getuid();
1793 euid = geteuid();
1794 (void)suid;
1796 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
1797 "UID is %u (real), %u (effective), unknown (saved)",
1798 (unsigned)ruid, (unsigned)euid);
1799 #endif
1801 /* log GIDs */
1802 #ifdef HAVE_GETRESGID
1803 if (getresgid(&rgid, &egid, &sgid) != 0 ) {
1804 log_warn(LD_GENERAL, "Error getting changed GIDs: %s", strerror(errno));
1805 return -1;
1806 } else {
1807 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
1808 "GID is %u (real), %u (effective), %u (saved)",
1809 (unsigned)rgid, (unsigned)egid, (unsigned)sgid);
1811 #else
1812 /* getresgid is not present on MacOS X, so we can't get the saved (E)GID */
1813 rgid = getgid();
1814 egid = getegid();
1815 (void)sgid;
1816 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
1817 "GID is %u (real), %u (effective), unknown (saved)",
1818 (unsigned)rgid, (unsigned)egid);
1819 #endif
1821 /* log supplementary groups */
1822 sup_gids_size = 64;
1823 sup_gids = tor_calloc(64, sizeof(gid_t));
1824 while ((ngids = getgroups(sup_gids_size, sup_gids)) < 0 &&
1825 errno == EINVAL &&
1826 sup_gids_size < NGROUPS_MAX) {
1827 sup_gids_size *= 2;
1828 sup_gids = tor_reallocarray(sup_gids, sizeof(gid_t), sup_gids_size);
1831 if (ngids < 0) {
1832 log_warn(LD_GENERAL, "Error getting supplementary GIDs: %s",
1833 strerror(errno));
1834 tor_free(sup_gids);
1835 return -1;
1836 } else {
1837 int i, retval = 0;
1838 char *s = NULL;
1839 smartlist_t *elts = smartlist_new();
1841 for (i = 0; i<ngids; i++) {
1842 smartlist_add_asprintf(elts, "%u", (unsigned)sup_gids[i]);
1845 s = smartlist_join_strings(elts, " ", 0, NULL);
1847 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL, "Supplementary groups are: %s",s);
1849 tor_free(s);
1850 SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
1851 smartlist_free(elts);
1852 tor_free(sup_gids);
1854 return retval;
1857 return 0;
1859 #endif
1861 #ifndef _WIN32
1862 /** Cached struct from the last getpwname() call we did successfully. */
1863 static struct passwd *passwd_cached = NULL;
1865 /** Helper: copy a struct passwd object.
1867 * We only copy the fields pw_uid, pw_gid, pw_name, pw_dir. Tor doesn't use
1868 * any others, and I don't want to run into incompatibilities.
1870 static struct passwd *
1871 tor_passwd_dup(const struct passwd *pw)
1873 struct passwd *new_pw = tor_malloc_zero(sizeof(struct passwd));
1874 if (pw->pw_name)
1875 new_pw->pw_name = tor_strdup(pw->pw_name);
1876 if (pw->pw_dir)
1877 new_pw->pw_dir = tor_strdup(pw->pw_dir);
1878 new_pw->pw_uid = pw->pw_uid;
1879 new_pw->pw_gid = pw->pw_gid;
1881 return new_pw;
1884 /** Helper: free one of our cached 'struct passwd' values. */
1885 static void
1886 tor_passwd_free(struct passwd *pw)
1888 if (!pw)
1889 return;
1891 tor_free(pw->pw_name);
1892 tor_free(pw->pw_dir);
1893 tor_free(pw);
1896 /** Wrapper around getpwnam() that caches result. Used so that we don't need
1897 * to give the sandbox access to /etc/passwd.
1899 * The following fields alone will definitely be copied in the output: pw_uid,
1900 * pw_gid, pw_name, pw_dir. Other fields are not present in cached values.
1902 * When called with a NULL argument, this function clears storage associated
1903 * with static variables it uses.
1905 const struct passwd *
1906 tor_getpwnam(const char *username)
1908 struct passwd *pw;
1910 if (username == NULL) {
1911 tor_passwd_free(passwd_cached);
1912 passwd_cached = NULL;
1913 return NULL;
1916 if ((pw = getpwnam(username))) {
1917 tor_passwd_free(passwd_cached);
1918 passwd_cached = tor_passwd_dup(pw);
1919 log_info(LD_GENERAL, "Caching new entry %s for %s",
1920 passwd_cached->pw_name, username);
1921 return pw;
1924 /* Lookup failed */
1925 if (! passwd_cached || ! passwd_cached->pw_name)
1926 return NULL;
1928 if (! strcmp(username, passwd_cached->pw_name))
1929 return passwd_cached; // LCOV_EXCL_LINE - would need to make getpwnam flaky
1931 return NULL;
1934 /** Wrapper around getpwnam() that can use cached result from
1935 * tor_getpwnam(). Used so that we don't need to give the sandbox access to
1936 * /etc/passwd.
1938 * The following fields alone will definitely be copied in the output: pw_uid,
1939 * pw_gid, pw_name, pw_dir. Other fields are not present in cached values.
1941 const struct passwd *
1942 tor_getpwuid(uid_t uid)
1944 struct passwd *pw;
1946 if ((pw = getpwuid(uid))) {
1947 return pw;
1950 /* Lookup failed */
1951 if (! passwd_cached)
1952 return NULL;
1954 if (uid == passwd_cached->pw_uid)
1955 return passwd_cached; // LCOV_EXCL_LINE - would need to make getpwnam flaky
1957 return NULL;
1959 #endif
1961 /** Return true iff we were compiled with capability support, and capabilities
1962 * seem to work. **/
1964 have_capability_support(void)
1966 #ifdef HAVE_LINUX_CAPABILITIES
1967 cap_t caps = cap_get_proc();
1968 if (caps == NULL)
1969 return 0;
1970 cap_free(caps);
1971 return 1;
1972 #else
1973 return 0;
1974 #endif
1977 #ifdef HAVE_LINUX_CAPABILITIES
1978 /** Helper. Drop all capabilities but a small set, and set PR_KEEPCAPS as
1979 * appropriate.
1981 * If pre_setuid, retain only CAP_NET_BIND_SERVICE, CAP_SETUID, and
1982 * CAP_SETGID, and use PR_KEEPCAPS to ensure that capabilities persist across
1983 * setuid().
1985 * If not pre_setuid, retain only CAP_NET_BIND_SERVICE, and disable
1986 * PR_KEEPCAPS.
1988 * Return 0 on success, and -1 on failure.
1990 static int
1991 drop_capabilities(int pre_setuid)
1993 /* We keep these three capabilities, and these only, as we setuid.
1994 * After we setuid, we drop all but the first. */
1995 const cap_value_t caplist[] = {
1996 CAP_NET_BIND_SERVICE, CAP_SETUID, CAP_SETGID
1998 const char *where = pre_setuid ? "pre-setuid" : "post-setuid";
1999 const int n_effective = pre_setuid ? 3 : 1;
2000 const int n_permitted = pre_setuid ? 3 : 1;
2001 const int n_inheritable = 1;
2002 const int keepcaps = pre_setuid ? 1 : 0;
2004 /* Sets whether we keep capabilities across a setuid. */
2005 if (prctl(PR_SET_KEEPCAPS, keepcaps) < 0) {
2006 log_warn(LD_CONFIG, "Unable to call prctl() %s: %s",
2007 where, strerror(errno));
2008 return -1;
2011 cap_t caps = cap_get_proc();
2012 if (!caps) {
2013 log_warn(LD_CONFIG, "Unable to call cap_get_proc() %s: %s",
2014 where, strerror(errno));
2015 return -1;
2017 cap_clear(caps);
2019 cap_set_flag(caps, CAP_EFFECTIVE, n_effective, caplist, CAP_SET);
2020 cap_set_flag(caps, CAP_PERMITTED, n_permitted, caplist, CAP_SET);
2021 cap_set_flag(caps, CAP_INHERITABLE, n_inheritable, caplist, CAP_SET);
2023 int r = cap_set_proc(caps);
2024 cap_free(caps);
2025 if (r < 0) {
2026 log_warn(LD_CONFIG, "No permission to set capabilities %s: %s",
2027 where, strerror(errno));
2028 return -1;
2031 return 0;
2033 #endif
2035 /** Call setuid and setgid to run as <b>user</b> and switch to their
2036 * primary group. Return 0 on success. On failure, log and return -1.
2038 * If SWITCH_ID_KEEP_BINDLOW is set in 'flags', try to use the capability
2039 * system to retain the abilitity to bind low ports.
2041 * If SWITCH_ID_WARN_IF_NO_CAPS is set in flags, also warn if we have
2042 * don't have capability support.
2045 switch_id(const char *user, const unsigned flags)
2047 #ifndef _WIN32
2048 const struct passwd *pw = NULL;
2049 uid_t old_uid;
2050 gid_t old_gid;
2051 static int have_already_switched_id = 0;
2052 const int keep_bindlow = !!(flags & SWITCH_ID_KEEP_BINDLOW);
2053 const int warn_if_no_caps = !!(flags & SWITCH_ID_WARN_IF_NO_CAPS);
2055 tor_assert(user);
2057 if (have_already_switched_id)
2058 return 0;
2060 /* Log the initial credential state */
2061 if (log_credential_status())
2062 return -1;
2064 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL, "Changing user and groups");
2066 /* Get old UID/GID to check if we changed correctly */
2067 old_uid = getuid();
2068 old_gid = getgid();
2070 /* Lookup the user and group information, if we have a problem, bail out. */
2071 pw = tor_getpwnam(user);
2072 if (pw == NULL) {
2073 log_warn(LD_CONFIG, "Error setting configured user: %s not found", user);
2074 return -1;
2077 #ifdef HAVE_LINUX_CAPABILITIES
2078 (void) warn_if_no_caps;
2079 if (keep_bindlow) {
2080 if (drop_capabilities(1))
2081 return -1;
2083 #else
2084 (void) keep_bindlow;
2085 if (warn_if_no_caps) {
2086 log_warn(LD_CONFIG, "KeepBindCapabilities set, but no capability support "
2087 "on this system.");
2089 #endif
2091 /* Properly switch egid,gid,euid,uid here or bail out */
2092 if (setgroups(1, &pw->pw_gid)) {
2093 log_warn(LD_GENERAL, "Error setting groups to gid %d: \"%s\".",
2094 (int)pw->pw_gid, strerror(errno));
2095 if (old_uid == pw->pw_uid) {
2096 log_warn(LD_GENERAL, "Tor is already running as %s. You do not need "
2097 "the \"User\" option if you are already running as the user "
2098 "you want to be. (If you did not set the User option in your "
2099 "torrc, check whether it was specified on the command line "
2100 "by a startup script.)", user);
2101 } else {
2102 log_warn(LD_GENERAL, "If you set the \"User\" option, you must start Tor"
2103 " as root.");
2105 return -1;
2108 if (setegid(pw->pw_gid)) {
2109 log_warn(LD_GENERAL, "Error setting egid to %d: %s",
2110 (int)pw->pw_gid, strerror(errno));
2111 return -1;
2114 if (setgid(pw->pw_gid)) {
2115 log_warn(LD_GENERAL, "Error setting gid to %d: %s",
2116 (int)pw->pw_gid, strerror(errno));
2117 return -1;
2120 if (setuid(pw->pw_uid)) {
2121 log_warn(LD_GENERAL, "Error setting configured uid to %s (%d): %s",
2122 user, (int)pw->pw_uid, strerror(errno));
2123 return -1;
2126 if (seteuid(pw->pw_uid)) {
2127 log_warn(LD_GENERAL, "Error setting configured euid to %s (%d): %s",
2128 user, (int)pw->pw_uid, strerror(errno));
2129 return -1;
2132 /* This is how OpenBSD rolls:
2133 if (setgroups(1, &pw->pw_gid) || setegid(pw->pw_gid) ||
2134 setgid(pw->pw_gid) || setuid(pw->pw_uid) || seteuid(pw->pw_uid)) {
2135 setgid(pw->pw_gid) || seteuid(pw->pw_uid) || setuid(pw->pw_uid)) {
2136 log_warn(LD_GENERAL, "Error setting configured UID/GID: %s",
2137 strerror(errno));
2138 return -1;
2142 /* We've properly switched egid, gid, euid, uid, and supplementary groups if
2143 * we're here. */
2144 #ifdef HAVE_LINUX_CAPABILITIES
2145 if (keep_bindlow) {
2146 if (drop_capabilities(0))
2147 return -1;
2149 #endif
2151 #if !defined(CYGWIN) && !defined(__CYGWIN__)
2152 /* If we tried to drop privilege to a group/user other than root, attempt to
2153 * restore root (E)(U|G)ID, and abort if the operation succeeds */
2155 /* Only check for privilege dropping if we were asked to be non-root */
2156 if (pw->pw_uid) {
2157 /* Try changing GID/EGID */
2158 if (pw->pw_gid != old_gid &&
2159 (setgid(old_gid) != -1 || setegid(old_gid) != -1)) {
2160 log_warn(LD_GENERAL, "Was able to restore group credentials even after "
2161 "switching GID: this means that the setgid code didn't work.");
2162 return -1;
2165 /* Try changing UID/EUID */
2166 if (pw->pw_uid != old_uid &&
2167 (setuid(old_uid) != -1 || seteuid(old_uid) != -1)) {
2168 log_warn(LD_GENERAL, "Was able to restore user credentials even after "
2169 "switching UID: this means that the setuid code didn't work.");
2170 return -1;
2173 #endif
2175 /* Check what really happened */
2176 if (log_credential_status()) {
2177 return -1;
2180 have_already_switched_id = 1; /* mark success so we never try again */
2182 #if defined(__linux__) && defined(HAVE_SYS_PRCTL_H) && defined(HAVE_PRCTL)
2183 #ifdef PR_SET_DUMPABLE
2184 if (pw->pw_uid) {
2185 /* Re-enable core dumps if we're not running as root. */
2186 log_info(LD_CONFIG, "Re-enabling coredumps");
2187 if (prctl(PR_SET_DUMPABLE, 1)) {
2188 log_warn(LD_CONFIG, "Unable to re-enable coredumps: %s",strerror(errno));
2191 #endif
2192 #endif
2193 return 0;
2195 #else
2196 (void)user;
2197 (void)flags;
2199 log_warn(LD_CONFIG, "Switching users is unsupported on your OS.");
2200 return -1;
2201 #endif
2204 /* We only use the linux prctl for now. There is no Win32 support; this may
2205 * also work on various BSD systems and Mac OS X - send testing feedback!
2207 * On recent Gnu/Linux kernels it is possible to create a system-wide policy
2208 * that will prevent non-root processes from attaching to other processes
2209 * unless they are the parent process; thus gdb can attach to programs that
2210 * they execute but they cannot attach to other processes running as the same
2211 * user. The system wide policy may be set with the sysctl
2212 * kernel.yama.ptrace_scope or by inspecting
2213 * /proc/sys/kernel/yama/ptrace_scope and it is 1 by default on Ubuntu 11.04.
2215 * This ptrace scope will be ignored on Gnu/Linux for users with
2216 * CAP_SYS_PTRACE and so it is very likely that root will still be able to
2217 * attach to the Tor process.
2219 /** Attempt to disable debugger attachment: return 1 on success, -1 on
2220 * failure, and 0 if we don't know how to try on this platform. */
2222 tor_disable_debugger_attach(void)
2224 int r, attempted;
2225 r = -1;
2226 attempted = 0;
2227 log_debug(LD_CONFIG,
2228 "Attemping to disable debugger attachment to Tor for "
2229 "unprivileged users.");
2230 #if defined(__linux__) && defined(HAVE_SYS_PRCTL_H) && defined(HAVE_PRCTL)
2231 #ifdef PR_SET_DUMPABLE
2232 attempted = 1;
2233 r = prctl(PR_SET_DUMPABLE, 0);
2234 #endif
2235 #endif
2236 #if defined(__APPLE__) && defined(PT_DENY_ATTACH)
2237 if (r < 0) {
2238 attempted = 1;
2239 r = ptrace(PT_DENY_ATTACH, 0, 0, 0);
2241 #endif
2243 // XXX: TODO - Mac OS X has dtrace and this may be disabled.
2244 // XXX: TODO - Windows probably has something similar
2245 if (r == 0 && attempted) {
2246 log_debug(LD_CONFIG,"Debugger attachment disabled for "
2247 "unprivileged users.");
2248 return 1;
2249 } else if (attempted) {
2250 log_warn(LD_CONFIG, "Unable to disable debugger attaching: %s",
2251 strerror(errno));
2253 return r;
2256 #ifdef HAVE_PWD_H
2257 /** Allocate and return a string containing the home directory for the
2258 * user <b>username</b>. Only works on posix-like systems. */
2259 char *
2260 get_user_homedir(const char *username)
2262 const struct passwd *pw;
2263 tor_assert(username);
2265 if (!(pw = tor_getpwnam(username))) {
2266 log_err(LD_CONFIG,"User \"%s\" not found.", username);
2267 return NULL;
2269 return tor_strdup(pw->pw_dir);
2271 #endif
2273 /** Modify <b>fname</b> to contain the name of its parent directory. Doesn't
2274 * actually examine the filesystem; does a purely syntactic modification.
2276 * The parent of the root director is considered to be iteself.
2278 * Path separators are the forward slash (/) everywhere and additionally
2279 * the backslash (\) on Win32.
2281 * Cuts off any number of trailing path separators but otherwise ignores
2282 * them for purposes of finding the parent directory.
2284 * Returns 0 if a parent directory was successfully found, -1 otherwise (fname
2285 * did not have any path separators or only had them at the end).
2286 * */
2288 get_parent_directory(char *fname)
2290 char *cp;
2291 int at_end = 1;
2292 tor_assert(fname);
2293 #ifdef _WIN32
2294 /* If we start with, say, c:, then don't consider that the start of the path
2296 if (fname[0] && fname[1] == ':') {
2297 fname += 2;
2299 #endif
2300 /* Now we want to remove all path-separators at the end of the string,
2301 * and to remove the end of the string starting with the path separator
2302 * before the last non-path-separator. In perl, this would be
2303 * s#[/]*$##; s#/[^/]*$##;
2304 * on a unixy platform.
2306 cp = fname + strlen(fname);
2307 at_end = 1;
2308 while (--cp >= fname) {
2309 int is_sep = (*cp == '/'
2310 #ifdef _WIN32
2311 || *cp == '\\'
2312 #endif
2314 if (is_sep) {
2315 if (cp == fname) {
2316 /* This is the first separator in the file name; don't remove it! */
2317 cp[1] = '\0';
2318 return 0;
2320 *cp = '\0';
2321 if (! at_end)
2322 return 0;
2323 } else {
2324 at_end = 0;
2327 return -1;
2330 #ifndef _WIN32
2331 /** Return a newly allocated string containing the output of getcwd(). Return
2332 * NULL on failure. (We can't just use getcwd() into a PATH_MAX buffer, since
2333 * Hurd hasn't got a PATH_MAX.)
2335 static char *
2336 alloc_getcwd(void)
2338 #ifdef PATH_MAX
2339 #define MAX_CWD PATH_MAX
2340 #else
2341 #define MAX_CWD 4096
2342 #endif
2344 char path_buf[MAX_CWD];
2345 char *path = getcwd(path_buf, sizeof(path_buf));
2346 return path ? tor_strdup(path) : NULL;
2348 #endif
2350 /** Expand possibly relative path <b>fname</b> to an absolute path.
2351 * Return a newly allocated string, possibly equal to <b>fname</b>. */
2352 char *
2353 make_path_absolute(char *fname)
2355 #ifdef _WIN32
2356 char *absfname_malloced = _fullpath(NULL, fname, 1);
2358 /* We don't want to assume that tor_free can free a string allocated
2359 * with malloc. On failure, return fname (it's better than nothing). */
2360 char *absfname = tor_strdup(absfname_malloced ? absfname_malloced : fname);
2361 if (absfname_malloced) raw_free(absfname_malloced);
2363 return absfname;
2364 #else
2365 char *absfname = NULL, *path = NULL;
2367 tor_assert(fname);
2369 if (fname[0] == '/') {
2370 absfname = tor_strdup(fname);
2371 } else {
2372 path = alloc_getcwd();
2373 if (path) {
2374 tor_asprintf(&absfname, "%s/%s", path, fname);
2375 tor_free(path);
2376 } else {
2377 /* LCOV_EXCL_START Can't make getcwd fail. */
2378 /* If getcwd failed, the best we can do here is keep using the
2379 * relative path. (Perhaps / isn't readable by this UID/GID.) */
2380 log_warn(LD_GENERAL, "Unable to find current working directory: %s",
2381 strerror(errno));
2382 absfname = tor_strdup(fname);
2383 /* LCOV_EXCL_STOP */
2386 return absfname;
2387 #endif
2390 #ifndef HAVE__NSGETENVIRON
2391 #ifndef HAVE_EXTERN_ENVIRON_DECLARED
2392 /* Some platforms declare environ under some circumstances, others don't. */
2393 #ifndef RUNNING_DOXYGEN
2394 extern char **environ;
2395 #endif
2396 #endif
2397 #endif
2399 /** Return the current environment. This is a portable replacement for
2400 * 'environ'. */
2401 char **
2402 get_environment(void)
2404 #ifdef HAVE__NSGETENVIRON
2405 /* This is for compatibility between OSX versions. Otherwise (for example)
2406 * when we do a mostly-static build on OSX 10.7, the resulting binary won't
2407 * work on OSX 10.6. */
2408 return *_NSGetEnviron();
2409 #else
2410 return environ;
2411 #endif
2414 /** Get name of current host and write it to <b>name</b> array, whose
2415 * length is specified by <b>namelen</b> argument. Return 0 upon
2416 * successfull completion; otherwise return return -1. (Currently,
2417 * this function is merely a mockable wrapper for POSIX gethostname().)
2419 MOCK_IMPL(int,
2420 tor_gethostname,(char *name, size_t namelen))
2422 return gethostname(name,namelen);
2425 /** Set *addr to the IP address (in dotted-quad notation) stored in *str.
2426 * Return 1 on success, 0 if *str is badly formatted.
2427 * (Like inet_aton(str,addr), but works on Windows and Solaris.)
2430 tor_inet_aton(const char *str, struct in_addr* addr)
2432 unsigned a,b,c,d;
2433 char more;
2434 if (tor_sscanf(str, "%3u.%3u.%3u.%3u%c", &a,&b,&c,&d,&more) != 4)
2435 return 0;
2436 if (a > 255) return 0;
2437 if (b > 255) return 0;
2438 if (c > 255) return 0;
2439 if (d > 255) return 0;
2440 addr->s_addr = htonl((a<<24) | (b<<16) | (c<<8) | d);
2441 return 1;
2444 /** Given <b>af</b>==AF_INET and <b>src</b> a struct in_addr, or
2445 * <b>af</b>==AF_INET6 and <b>src</b> a struct in6_addr, try to format the
2446 * address and store it in the <b>len</b>-byte buffer <b>dst</b>. Returns
2447 * <b>dst</b> on success, NULL on failure.
2449 * (Like inet_ntop(af,src,dst,len), but works on platforms that don't have it:
2450 * Tor sometimes needs to format ipv6 addresses even on platforms without ipv6
2451 * support.) */
2452 const char *
2453 tor_inet_ntop(int af, const void *src, char *dst, size_t len)
2455 if (af == AF_INET) {
2456 if (tor_inet_ntoa(src, dst, len) < 0)
2457 return NULL;
2458 else
2459 return dst;
2460 } else if (af == AF_INET6) {
2461 const struct in6_addr *addr = src;
2462 char buf[64], *cp;
2463 int longestGapLen = 0, longestGapPos = -1, i,
2464 curGapPos = -1, curGapLen = 0;
2465 uint16_t words[8];
2466 for (i = 0; i < 8; ++i) {
2467 words[i] = (((uint16_t)addr->s6_addr[2*i])<<8) + addr->s6_addr[2*i+1];
2469 if (words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0 &&
2470 words[4] == 0 && ((words[5] == 0 && words[6] && words[7]) ||
2471 (words[5] == 0xffff))) {
2472 /* This is an IPv4 address. */
2473 if (words[5] == 0) {
2474 tor_snprintf(buf, sizeof(buf), "::%d.%d.%d.%d",
2475 addr->s6_addr[12], addr->s6_addr[13],
2476 addr->s6_addr[14], addr->s6_addr[15]);
2477 } else {
2478 tor_snprintf(buf, sizeof(buf), "::%x:%d.%d.%d.%d", words[5],
2479 addr->s6_addr[12], addr->s6_addr[13],
2480 addr->s6_addr[14], addr->s6_addr[15]);
2482 if ((strlen(buf) + 1) > len) /* +1 for \0 */
2483 return NULL;
2484 strlcpy(dst, buf, len);
2485 return dst;
2487 i = 0;
2488 while (i < 8) {
2489 if (words[i] == 0) {
2490 curGapPos = i++;
2491 curGapLen = 1;
2492 while (i<8 && words[i] == 0) {
2493 ++i; ++curGapLen;
2495 if (curGapLen > longestGapLen) {
2496 longestGapPos = curGapPos;
2497 longestGapLen = curGapLen;
2499 } else {
2500 ++i;
2503 if (longestGapLen<=1)
2504 longestGapPos = -1;
2506 cp = buf;
2507 for (i = 0; i < 8; ++i) {
2508 if (words[i] == 0 && longestGapPos == i) {
2509 if (i == 0)
2510 *cp++ = ':';
2511 *cp++ = ':';
2512 while (i < 8 && words[i] == 0)
2513 ++i;
2514 --i; /* to compensate for loop increment. */
2515 } else {
2516 tor_snprintf(cp, sizeof(buf)-(cp-buf), "%x", (unsigned)words[i]);
2517 cp += strlen(cp);
2518 if (i != 7)
2519 *cp++ = ':';
2522 *cp = '\0';
2523 if ((strlen(buf) + 1) > len) /* +1 for \0 */
2524 return NULL;
2525 strlcpy(dst, buf, len);
2526 return dst;
2527 } else {
2528 return NULL;
2532 /** Given <b>af</b>==AF_INET or <b>af</b>==AF_INET6, and a string <b>src</b>
2533 * encoding an IPv4 address or IPv6 address correspondingly, try to parse the
2534 * address and store the result in <b>dst</b> (which must have space for a
2535 * struct in_addr or a struct in6_addr, as appropriate). Return 1 on success,
2536 * 0 on a bad parse, and -1 on a bad <b>af</b>.
2538 * (Like inet_pton(af,src,dst) but works on platforms that don't have it: Tor
2539 * sometimes needs to format ipv6 addresses even on platforms without ipv6
2540 * support.) */
2542 tor_inet_pton(int af, const char *src, void *dst)
2544 if (af == AF_INET) {
2545 return tor_inet_aton(src, dst);
2546 } else if (af == AF_INET6) {
2547 struct in6_addr *out = dst;
2548 uint16_t words[8];
2549 int gapPos = -1, i, setWords=0;
2550 const char *dot = strchr(src, '.');
2551 const char *eow; /* end of words. */
2552 if (dot == src)
2553 return 0;
2554 else if (!dot)
2555 eow = src+strlen(src);
2556 else {
2557 unsigned byte1,byte2,byte3,byte4;
2558 char more;
2559 for (eow = dot-1; eow > src && TOR_ISDIGIT(*eow); --eow)
2561 if (*eow != ':')
2562 return 0;
2563 ++eow;
2565 /* We use "scanf" because some platform inet_aton()s are too lax
2566 * about IPv4 addresses of the form "1.2.3" */
2567 if (tor_sscanf(eow, "%3u.%3u.%3u.%3u%c",
2568 &byte1,&byte2,&byte3,&byte4,&more) != 4)
2569 return 0;
2571 if (byte1 > 255 || byte2 > 255 || byte3 > 255 || byte4 > 255)
2572 return 0;
2574 words[6] = (byte1<<8) | byte2;
2575 words[7] = (byte3<<8) | byte4;
2576 setWords += 2;
2579 i = 0;
2580 while (src < eow) {
2581 if (i > 7)
2582 return 0;
2583 if (TOR_ISXDIGIT(*src)) {
2584 char *next;
2585 ssize_t len;
2586 long r = strtol(src, &next, 16);
2587 if (next == NULL || next == src) {
2588 /* The 'next == src' error case can happen on versions of openbsd
2589 * where treats "0xfoo" as an error, rather than as "0" followed by
2590 * "xfoo". */
2591 return 0;
2594 len = *next == '\0' ? eow - src : next - src;
2595 if (len > 4)
2596 return 0;
2597 if (len > 1 && !TOR_ISXDIGIT(src[1]))
2598 return 0; /* 0x is not valid */
2600 tor_assert(r >= 0);
2601 tor_assert(r < 65536);
2602 words[i++] = (uint16_t)r;
2603 setWords++;
2604 src = next;
2605 if (*src != ':' && src != eow)
2606 return 0;
2607 ++src;
2608 } else if (*src == ':' && i > 0 && gapPos == -1) {
2609 gapPos = i;
2610 ++src;
2611 } else if (*src == ':' && i == 0 && src+1 < eow && src[1] == ':' &&
2612 gapPos == -1) {
2613 gapPos = i;
2614 src += 2;
2615 } else {
2616 return 0;
2620 if (setWords > 8 ||
2621 (setWords == 8 && gapPos != -1) ||
2622 (setWords < 8 && gapPos == -1))
2623 return 0;
2625 if (gapPos >= 0) {
2626 int nToMove = setWords - (dot ? 2 : 0) - gapPos;
2627 int gapLen = 8 - setWords;
2628 tor_assert(nToMove >= 0);
2629 memmove(&words[gapPos+gapLen], &words[gapPos],
2630 sizeof(uint16_t)*nToMove);
2631 memset(&words[gapPos], 0, sizeof(uint16_t)*gapLen);
2633 for (i = 0; i < 8; ++i) {
2634 out->s6_addr[2*i ] = words[i] >> 8;
2635 out->s6_addr[2*i+1] = words[i] & 0xff;
2638 return 1;
2639 } else {
2640 return -1;
2644 /** Similar behavior to Unix gethostbyname: resolve <b>name</b>, and set
2645 * *<b>addr</b> to the proper IP address, in host byte order. Returns 0
2646 * on success, -1 on failure; 1 on transient failure.
2648 * (This function exists because standard windows gethostbyname
2649 * doesn't treat raw IP addresses properly.)
2652 MOCK_IMPL(int,
2653 tor_lookup_hostname,(const char *name, uint32_t *addr))
2655 tor_addr_t myaddr;
2656 int ret;
2658 if ((ret = tor_addr_lookup(name, AF_INET, &myaddr)))
2659 return ret;
2661 if (tor_addr_family(&myaddr) == AF_INET) {
2662 *addr = tor_addr_to_ipv4h(&myaddr);
2663 return ret;
2666 return -1;
2669 /** Hold the result of our call to <b>uname</b>. */
2670 static char uname_result[256];
2671 /** True iff uname_result is set. */
2672 static int uname_result_is_set = 0;
2674 /** Return a pointer to a description of our platform.
2676 MOCK_IMPL(const char *, get_uname, (void))
2678 #ifdef HAVE_UNAME
2679 struct utsname u;
2680 #endif
2681 if (!uname_result_is_set) {
2682 #ifdef HAVE_UNAME
2683 if (uname(&u) != -1) {
2684 /* (Linux says 0 is success, Solaris says 1 is success) */
2685 strlcpy(uname_result, u.sysname, sizeof(uname_result));
2686 } else
2687 #endif
2689 #ifdef _WIN32
2690 OSVERSIONINFOEX info;
2691 int i;
2692 const char *plat = NULL;
2693 static struct {
2694 unsigned major; unsigned minor; const char *version;
2695 } win_version_table[] = {
2696 { 6, 2, "Windows 8" },
2697 { 6, 1, "Windows 7" },
2698 { 6, 0, "Windows Vista" },
2699 { 5, 2, "Windows Server 2003" },
2700 { 5, 1, "Windows XP" },
2701 { 5, 0, "Windows 2000" },
2702 /* { 4, 0, "Windows NT 4.0" }, */
2703 { 4, 90, "Windows Me" },
2704 { 4, 10, "Windows 98" },
2705 /* { 4, 0, "Windows 95" } */
2706 { 3, 51, "Windows NT 3.51" },
2707 { 0, 0, NULL }
2709 memset(&info, 0, sizeof(info));
2710 info.dwOSVersionInfoSize = sizeof(info);
2711 if (! GetVersionEx((LPOSVERSIONINFO)&info)) {
2712 strlcpy(uname_result, "Bizarre version of Windows where GetVersionEx"
2713 " doesn't work.", sizeof(uname_result));
2714 uname_result_is_set = 1;
2715 return uname_result;
2717 if (info.dwMajorVersion == 4 && info.dwMinorVersion == 0) {
2718 if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
2719 plat = "Windows NT 4.0";
2720 else
2721 plat = "Windows 95";
2722 } else {
2723 for (i=0; win_version_table[i].major>0; ++i) {
2724 if (win_version_table[i].major == info.dwMajorVersion &&
2725 win_version_table[i].minor == info.dwMinorVersion) {
2726 plat = win_version_table[i].version;
2727 break;
2731 if (plat) {
2732 strlcpy(uname_result, plat, sizeof(uname_result));
2733 } else {
2734 if (info.dwMajorVersion > 6 ||
2735 (info.dwMajorVersion==6 && info.dwMinorVersion>2))
2736 tor_snprintf(uname_result, sizeof(uname_result),
2737 "Very recent version of Windows [major=%d,minor=%d]",
2738 (int)info.dwMajorVersion,(int)info.dwMinorVersion);
2739 else
2740 tor_snprintf(uname_result, sizeof(uname_result),
2741 "Unrecognized version of Windows [major=%d,minor=%d]",
2742 (int)info.dwMajorVersion,(int)info.dwMinorVersion);
2744 #ifdef VER_NT_SERVER
2745 if (info.wProductType == VER_NT_SERVER ||
2746 info.wProductType == VER_NT_DOMAIN_CONTROLLER) {
2747 strlcat(uname_result, " [server]", sizeof(uname_result));
2749 #endif
2750 #else
2751 /* LCOV_EXCL_START -- can't provoke uname failure */
2752 strlcpy(uname_result, "Unknown platform", sizeof(uname_result));
2753 /* LCOV_EXCL_STOP */
2754 #endif
2756 uname_result_is_set = 1;
2758 return uname_result;
2762 * Process control
2765 /** Implementation logic for compute_num_cpus(). */
2766 static int
2767 compute_num_cpus_impl(void)
2769 #ifdef _WIN32
2770 SYSTEM_INFO info;
2771 memset(&info, 0, sizeof(info));
2772 GetSystemInfo(&info);
2773 if (info.dwNumberOfProcessors >= 1 && info.dwNumberOfProcessors < INT_MAX)
2774 return (int)info.dwNumberOfProcessors;
2775 else
2776 return -1;
2777 #elif defined(HAVE_SYSCONF)
2778 #ifdef _SC_NPROCESSORS_CONF
2779 long cpus_conf = sysconf(_SC_NPROCESSORS_CONF);
2780 #else
2781 long cpus_conf = -1;
2782 #endif
2783 #ifdef _SC_NPROCESSORS_ONLN
2784 long cpus_onln = sysconf(_SC_NPROCESSORS_ONLN);
2785 #else
2786 long cpus_onln = -1;
2787 #endif
2788 long cpus = -1;
2790 if (cpus_conf > 0 && cpus_onln < 0) {
2791 cpus = cpus_conf;
2792 } else if (cpus_onln > 0 && cpus_conf < 0) {
2793 cpus = cpus_onln;
2794 } else if (cpus_onln > 0 && cpus_conf > 0) {
2795 if (cpus_onln < cpus_conf) {
2796 log_notice(LD_GENERAL, "I think we have %ld CPUS, but only %ld of them "
2797 "are available. Telling Tor to only use %ld. You can over"
2798 "ride this with the NumCPUs option",
2799 cpus_conf, cpus_onln, cpus_onln);
2801 cpus = cpus_onln;
2804 if (cpus >= 1 && cpus < INT_MAX)
2805 return (int)cpus;
2806 else
2807 return -1;
2808 #else
2809 return -1;
2810 #endif
2813 #define MAX_DETECTABLE_CPUS 16
2815 /** Return how many CPUs we are running with. We assume that nobody is
2816 * using hot-swappable CPUs, so we don't recompute this after the first
2817 * time. Return -1 if we don't know how to tell the number of CPUs on this
2818 * system.
2821 compute_num_cpus(void)
2823 static int num_cpus = -2;
2824 if (num_cpus == -2) {
2825 num_cpus = compute_num_cpus_impl();
2826 tor_assert(num_cpus != -2);
2827 if (num_cpus > MAX_DETECTABLE_CPUS) {
2828 /* LCOV_EXCL_START */
2829 log_notice(LD_GENERAL, "Wow! I detected that you have %d CPUs. I "
2830 "will not autodetect any more than %d, though. If you "
2831 "want to configure more, set NumCPUs in your torrc",
2832 num_cpus, MAX_DETECTABLE_CPUS);
2833 num_cpus = MAX_DETECTABLE_CPUS;
2834 /* LCOV_EXCL_STOP */
2837 return num_cpus;
2840 #if !defined(_WIN32)
2841 /** Defined iff we need to add locks when defining fake versions of reentrant
2842 * versions of time-related functions. */
2843 #define TIME_FNS_NEED_LOCKS
2844 #endif
2846 /** Helper: Deal with confused or out-of-bounds values from localtime_r and
2847 * friends. (On some platforms, they can give out-of-bounds values or can
2848 * return NULL.) If <b>islocal</b>, this is a localtime result; otherwise
2849 * it's from gmtime. The function returned <b>r</b>, when given <b>timep</b>
2850 * as its input. If we need to store new results, store them in
2851 * <b>resultbuf</b>. */
2852 static struct tm *
2853 correct_tm(int islocal, const time_t *timep, struct tm *resultbuf,
2854 struct tm *r)
2856 const char *outcome;
2858 if (PREDICT_LIKELY(r)) {
2859 /* We can't strftime dates after 9999 CE, and we want to avoid dates
2860 * before 1 CE (avoiding the year 0 issue and negative years). */
2861 if (r->tm_year > 8099) {
2862 r->tm_year = 8099;
2863 r->tm_mon = 11;
2864 r->tm_mday = 31;
2865 r->tm_yday = 364;
2866 r->tm_wday = 6;
2867 r->tm_hour = 23;
2868 r->tm_min = 59;
2869 r->tm_sec = 59;
2870 } else if (r->tm_year < (1-1900)) {
2871 r->tm_year = (1-1900);
2872 r->tm_mon = 0;
2873 r->tm_mday = 1;
2874 r->tm_yday = 0;
2875 r->tm_wday = 0;
2876 r->tm_hour = 0;
2877 r->tm_min = 0;
2878 r->tm_sec = 0;
2880 return r;
2883 /* If we get here, gmtime or localtime returned NULL. It might have done
2884 * this because of overrun or underrun, or it might have done it because of
2885 * some other weird issue. */
2886 if (timep) {
2887 if (*timep < 0) {
2888 r = resultbuf;
2889 r->tm_year = 70; /* 1970 CE */
2890 r->tm_mon = 0;
2891 r->tm_mday = 1;
2892 r->tm_yday = 0;
2893 r->tm_wday = 0;
2894 r->tm_hour = 0;
2895 r->tm_min = 0 ;
2896 r->tm_sec = 0;
2897 outcome = "Rounding up to 1970";
2898 goto done;
2899 } else if (*timep >= INT32_MAX) {
2900 /* Rounding down to INT32_MAX isn't so great, but keep in mind that we
2901 * only do it if gmtime/localtime tells us NULL. */
2902 r = resultbuf;
2903 r->tm_year = 137; /* 2037 CE */
2904 r->tm_mon = 11;
2905 r->tm_mday = 31;
2906 r->tm_yday = 364;
2907 r->tm_wday = 6;
2908 r->tm_hour = 23;
2909 r->tm_min = 59;
2910 r->tm_sec = 59;
2911 outcome = "Rounding down to 2037";
2912 goto done;
2916 /* If we get here, then gmtime/localtime failed without getting an extreme
2917 * value for *timep */
2918 /* LCOV_EXCL_START */
2919 tor_fragile_assert();
2920 r = resultbuf;
2921 memset(resultbuf, 0, sizeof(struct tm));
2922 outcome="can't recover";
2923 /* LCOV_EXCL_STOP */
2924 done:
2925 log_warn(LD_BUG, "%s("I64_FORMAT") failed with error %s: %s",
2926 islocal?"localtime":"gmtime",
2927 timep?I64_PRINTF_ARG(*timep):0,
2928 strerror(errno),
2929 outcome);
2930 return r;
2933 /** @{ */
2934 /** As localtime_r, but defined for platforms that don't have it:
2936 * Convert *<b>timep</b> to a struct tm in local time, and store the value in
2937 * *<b>result</b>. Return the result on success, or NULL on failure.
2939 #ifdef HAVE_LOCALTIME_R
2940 struct tm *
2941 tor_localtime_r(const time_t *timep, struct tm *result)
2943 struct tm *r;
2944 r = localtime_r(timep, result);
2945 return correct_tm(1, timep, result, r);
2947 #elif defined(TIME_FNS_NEED_LOCKS)
2948 struct tm *
2949 tor_localtime_r(const time_t *timep, struct tm *result)
2951 struct tm *r;
2952 static tor_mutex_t *m=NULL;
2953 if (!m) { m=tor_mutex_new(); }
2954 tor_assert(result);
2955 tor_mutex_acquire(m);
2956 r = localtime(timep);
2957 if (r)
2958 memcpy(result, r, sizeof(struct tm));
2959 tor_mutex_release(m);
2960 return correct_tm(1, timep, result, r);
2962 #else
2963 struct tm *
2964 tor_localtime_r(const time_t *timep, struct tm *result)
2966 struct tm *r;
2967 tor_assert(result);
2968 r = localtime(timep);
2969 if (r)
2970 memcpy(result, r, sizeof(struct tm));
2971 return correct_tm(1, timep, result, r);
2973 #endif
2974 /** @} */
2976 /** @{ */
2977 /** As gmtime_r, but defined for platforms that don't have it:
2979 * Convert *<b>timep</b> to a struct tm in UTC, and store the value in
2980 * *<b>result</b>. Return the result on success, or NULL on failure.
2982 #ifdef HAVE_GMTIME_R
2983 struct tm *
2984 tor_gmtime_r(const time_t *timep, struct tm *result)
2986 struct tm *r;
2987 r = gmtime_r(timep, result);
2988 return correct_tm(0, timep, result, r);
2990 #elif defined(TIME_FNS_NEED_LOCKS)
2991 struct tm *
2992 tor_gmtime_r(const time_t *timep, struct tm *result)
2994 struct tm *r;
2995 static tor_mutex_t *m=NULL;
2996 if (!m) { m=tor_mutex_new(); }
2997 tor_assert(result);
2998 tor_mutex_acquire(m);
2999 r = gmtime(timep);
3000 if (r)
3001 memcpy(result, r, sizeof(struct tm));
3002 tor_mutex_release(m);
3003 return correct_tm(0, timep, result, r);
3005 #else
3006 struct tm *
3007 tor_gmtime_r(const time_t *timep, struct tm *result)
3009 struct tm *r;
3010 tor_assert(result);
3011 r = gmtime(timep);
3012 if (r)
3013 memcpy(result, r, sizeof(struct tm));
3014 return correct_tm(0, timep, result, r);
3016 #endif
3018 #if defined(HAVE_MLOCKALL) && HAVE_DECL_MLOCKALL && defined(RLIMIT_MEMLOCK)
3019 /** Attempt to raise the current and max rlimit to infinity for our process.
3020 * This only needs to be done once and can probably only be done when we have
3021 * not already dropped privileges.
3023 static int
3024 tor_set_max_memlock(void)
3026 /* Future consideration for Windows is probably SetProcessWorkingSetSize
3027 * This is similar to setting the memory rlimit of RLIMIT_MEMLOCK
3028 * http://msdn.microsoft.com/en-us/library/ms686234(VS.85).aspx
3031 struct rlimit limit;
3033 /* RLIM_INFINITY is -1 on some platforms. */
3034 limit.rlim_cur = RLIM_INFINITY;
3035 limit.rlim_max = RLIM_INFINITY;
3037 if (setrlimit(RLIMIT_MEMLOCK, &limit) == -1) {
3038 if (errno == EPERM) {
3039 log_warn(LD_GENERAL, "You appear to lack permissions to change memory "
3040 "limits. Are you root?");
3042 log_warn(LD_GENERAL, "Unable to raise RLIMIT_MEMLOCK: %s",
3043 strerror(errno));
3044 return -1;
3047 return 0;
3049 #endif
3051 /** Attempt to lock all current and all future memory pages.
3052 * This should only be called once and while we're privileged.
3053 * Like mlockall() we return 0 when we're successful and -1 when we're not.
3054 * Unlike mlockall() we return 1 if we've already attempted to lock memory.
3057 tor_mlockall(void)
3059 static int memory_lock_attempted = 0;
3061 if (memory_lock_attempted) {
3062 return 1;
3065 memory_lock_attempted = 1;
3068 * Future consideration for Windows may be VirtualLock
3069 * VirtualLock appears to implement mlock() but not mlockall()
3071 * http://msdn.microsoft.com/en-us/library/aa366895(VS.85).aspx
3074 #if defined(HAVE_MLOCKALL) && HAVE_DECL_MLOCKALL && defined(RLIMIT_MEMLOCK)
3075 if (tor_set_max_memlock() == 0) {
3076 log_debug(LD_GENERAL, "RLIMIT_MEMLOCK is now set to RLIM_INFINITY.");
3079 if (mlockall(MCL_CURRENT|MCL_FUTURE) == 0) {
3080 log_info(LD_GENERAL, "Insecure OS paging is effectively disabled.");
3081 return 0;
3082 } else {
3083 if (errno == ENOSYS) {
3084 /* Apple - it's 2009! I'm looking at you. Grrr. */
3085 log_notice(LD_GENERAL, "It appears that mlockall() is not available on "
3086 "your platform.");
3087 } else if (errno == EPERM) {
3088 log_notice(LD_GENERAL, "It appears that you lack the permissions to "
3089 "lock memory. Are you root?");
3091 log_notice(LD_GENERAL, "Unable to lock all current and future memory "
3092 "pages: %s", strerror(errno));
3093 return -1;
3095 #else
3096 log_warn(LD_GENERAL, "Unable to lock memory pages. mlockall() unsupported?");
3097 return -1;
3098 #endif
3102 * On Windows, WSAEWOULDBLOCK is not always correct: when you see it,
3103 * you need to ask the socket for its actual errno. Also, you need to
3104 * get your errors from WSAGetLastError, not errno. (If you supply a
3105 * socket of -1, we check WSAGetLastError, but don't correct
3106 * WSAEWOULDBLOCKs.)
3108 * The upshot of all of this is that when a socket call fails, you
3109 * should call tor_socket_errno <em>at most once</em> on the failing
3110 * socket to get the error.
3112 #if defined(_WIN32)
3114 tor_socket_errno(tor_socket_t sock)
3116 int optval, optvallen=sizeof(optval);
3117 int err = WSAGetLastError();
3118 if (err == WSAEWOULDBLOCK && SOCKET_OK(sock)) {
3119 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval, &optvallen))
3120 return err;
3121 if (optval)
3122 return optval;
3124 return err;
3126 #endif
3128 #if defined(_WIN32)
3129 #define E(code, s) { code, (s " [" #code " ]") }
3130 struct { int code; const char *msg; } windows_socket_errors[] = {
3131 E(WSAEINTR, "Interrupted function call"),
3132 E(WSAEACCES, "Permission denied"),
3133 E(WSAEFAULT, "Bad address"),
3134 E(WSAEINVAL, "Invalid argument"),
3135 E(WSAEMFILE, "Too many open files"),
3136 E(WSAEWOULDBLOCK, "Resource temporarily unavailable"),
3137 E(WSAEINPROGRESS, "Operation now in progress"),
3138 E(WSAEALREADY, "Operation already in progress"),
3139 E(WSAENOTSOCK, "Socket operation on nonsocket"),
3140 E(WSAEDESTADDRREQ, "Destination address required"),
3141 E(WSAEMSGSIZE, "Message too long"),
3142 E(WSAEPROTOTYPE, "Protocol wrong for socket"),
3143 E(WSAENOPROTOOPT, "Bad protocol option"),
3144 E(WSAEPROTONOSUPPORT, "Protocol not supported"),
3145 E(WSAESOCKTNOSUPPORT, "Socket type not supported"),
3146 /* What's the difference between NOTSUPP and NOSUPPORT? :) */
3147 E(WSAEOPNOTSUPP, "Operation not supported"),
3148 E(WSAEPFNOSUPPORT, "Protocol family not supported"),
3149 E(WSAEAFNOSUPPORT, "Address family not supported by protocol family"),
3150 E(WSAEADDRINUSE, "Address already in use"),
3151 E(WSAEADDRNOTAVAIL, "Cannot assign requested address"),
3152 E(WSAENETDOWN, "Network is down"),
3153 E(WSAENETUNREACH, "Network is unreachable"),
3154 E(WSAENETRESET, "Network dropped connection on reset"),
3155 E(WSAECONNABORTED, "Software caused connection abort"),
3156 E(WSAECONNRESET, "Connection reset by peer"),
3157 E(WSAENOBUFS, "No buffer space available"),
3158 E(WSAEISCONN, "Socket is already connected"),
3159 E(WSAENOTCONN, "Socket is not connected"),
3160 E(WSAESHUTDOWN, "Cannot send after socket shutdown"),
3161 E(WSAETIMEDOUT, "Connection timed out"),
3162 E(WSAECONNREFUSED, "Connection refused"),
3163 E(WSAEHOSTDOWN, "Host is down"),
3164 E(WSAEHOSTUNREACH, "No route to host"),
3165 E(WSAEPROCLIM, "Too many processes"),
3166 /* Yes, some of these start with WSA, not WSAE. No, I don't know why. */
3167 E(WSASYSNOTREADY, "Network subsystem is unavailable"),
3168 E(WSAVERNOTSUPPORTED, "Winsock.dll out of range"),
3169 E(WSANOTINITIALISED, "Successful WSAStartup not yet performed"),
3170 E(WSAEDISCON, "Graceful shutdown now in progress"),
3171 #ifdef WSATYPE_NOT_FOUND
3172 E(WSATYPE_NOT_FOUND, "Class type not found"),
3173 #endif
3174 E(WSAHOST_NOT_FOUND, "Host not found"),
3175 E(WSATRY_AGAIN, "Nonauthoritative host not found"),
3176 E(WSANO_RECOVERY, "This is a nonrecoverable error"),
3177 E(WSANO_DATA, "Valid name, no data record of requested type)"),
3179 /* There are some more error codes whose numeric values are marked
3180 * <b>OS dependent</b>. They start with WSA_, apparently for the same
3181 * reason that practitioners of some craft traditions deliberately
3182 * introduce imperfections into their baskets and rugs "to allow the
3183 * evil spirits to escape." If we catch them, then our binaries
3184 * might not report consistent results across versions of Windows.
3185 * Thus, I'm going to let them all fall through.
3187 { -1, NULL },
3189 /** There does not seem to be a strerror equivalent for Winsock errors.
3190 * Naturally, we have to roll our own.
3192 const char *
3193 tor_socket_strerror(int e)
3195 int i;
3196 for (i=0; windows_socket_errors[i].code >= 0; ++i) {
3197 if (e == windows_socket_errors[i].code)
3198 return windows_socket_errors[i].msg;
3200 return strerror(e);
3202 #endif
3204 /** Called before we make any calls to network-related functions.
3205 * (Some operating systems require their network libraries to be
3206 * initialized.) */
3208 network_init(void)
3210 #ifdef _WIN32
3211 /* This silly exercise is necessary before windows will allow
3212 * gethostbyname to work. */
3213 WSADATA WSAData;
3214 int r;
3215 r = WSAStartup(0x101,&WSAData);
3216 if (r) {
3217 log_warn(LD_NET,"Error initializing windows network layer: code was %d",r);
3218 return -1;
3220 if (sizeof(SOCKET) != sizeof(tor_socket_t)) {
3221 log_warn(LD_BUG,"The tor_socket_t type does not match SOCKET in size; Tor "
3222 "might not work. (Sizes are %d and %d respectively.)",
3223 (int)sizeof(tor_socket_t), (int)sizeof(SOCKET));
3225 /* WSAData.iMaxSockets might show the max sockets we're allowed to use.
3226 * We might use it to complain if we're trying to be a server but have
3227 * too few sockets available. */
3228 #endif
3229 return 0;
3232 #ifdef _WIN32
3233 /** Return a newly allocated string describing the windows system error code
3234 * <b>err</b>. Note that error codes are different from errno. Error codes
3235 * come from GetLastError() when a winapi call fails. errno is set only when
3236 * ANSI functions fail. Whee. */
3237 char *
3238 format_win32_error(DWORD err)
3240 TCHAR *str = NULL;
3241 char *result;
3242 DWORD n;
3244 /* Somebody once decided that this interface was better than strerror(). */
3245 n = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
3246 FORMAT_MESSAGE_FROM_SYSTEM |
3247 FORMAT_MESSAGE_IGNORE_INSERTS,
3248 NULL, err,
3249 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
3250 (LPVOID)&str,
3251 0, NULL);
3253 if (str && n) {
3254 #ifdef UNICODE
3255 size_t len;
3256 if (n > 128*1024)
3257 len = (128 * 1024) * 2 + 1; /* This shouldn't be possible, but let's
3258 * make sure. */
3259 else
3260 len = n * 2 + 1;
3261 result = tor_malloc(len);
3262 wcstombs(result,str,len);
3263 result[len-1] = '\0';
3264 #else
3265 result = tor_strdup(str);
3266 #endif
3267 } else {
3268 result = tor_strdup("<unformattable error>");
3270 if (str) {
3271 LocalFree(str); /* LocalFree != free() */
3273 return result;
3275 #endif
3277 #if defined(HW_PHYSMEM64)
3278 /* This appears to be an OpenBSD thing */
3279 #define INT64_HW_MEM HW_PHYSMEM64
3280 #elif defined(HW_MEMSIZE)
3281 /* OSX defines this one */
3282 #define INT64_HW_MEM HW_MEMSIZE
3283 #endif
3286 * Helper: try to detect the total system memory, and return it. On failure,
3287 * return 0.
3289 static uint64_t
3290 get_total_system_memory_impl(void)
3292 #if defined(__linux__)
3293 /* On linux, sysctl is deprecated. Because proc is so awesome that you
3294 * shouldn't _want_ to write portable code, I guess? */
3295 unsigned long long result=0;
3296 int fd = -1;
3297 char *s = NULL;
3298 const char *cp;
3299 size_t file_size=0;
3300 if (-1 == (fd = tor_open_cloexec("/proc/meminfo",O_RDONLY,0)))
3301 return 0;
3302 s = read_file_to_str_until_eof(fd, 65536, &file_size);
3303 if (!s)
3304 goto err;
3305 cp = strstr(s, "MemTotal:");
3306 if (!cp)
3307 goto err;
3308 /* Use the system sscanf so that space will match a wider number of space */
3309 if (sscanf(cp, "MemTotal: %llu kB\n", &result) != 1)
3310 goto err;
3312 close(fd);
3313 tor_free(s);
3314 return result * 1024;
3316 err:
3317 /* LCOV_EXCL_START Can't reach this unless proc is broken. */
3318 tor_free(s);
3319 close(fd);
3320 return 0;
3321 /* LCOV_EXCL_STOP */
3322 #elif defined (_WIN32)
3323 /* Windows has MEMORYSTATUSEX; pretty straightforward. */
3324 MEMORYSTATUSEX ms;
3325 memset(&ms, 0, sizeof(ms));
3326 ms.dwLength = sizeof(ms);
3327 if (! GlobalMemoryStatusEx(&ms))
3328 return 0;
3330 return ms.ullTotalPhys;
3332 #elif defined(HAVE_SYSCTL) && defined(INT64_HW_MEM)
3333 /* On many systems, HW_PYHSMEM is clipped to 32 bits; let's use a better
3334 * variant if we know about it. */
3335 uint64_t memsize = 0;
3336 size_t len = sizeof(memsize);
3337 int mib[2] = {CTL_HW, INT64_HW_MEM};
3338 if (sysctl(mib,2,&memsize,&len,NULL,0))
3339 return 0;
3341 return memsize;
3343 #elif defined(HAVE_SYSCTL) && defined(HW_PHYSMEM)
3344 /* On some systems (like FreeBSD I hope) you can use a size_t with
3345 * HW_PHYSMEM. */
3346 size_t memsize=0;
3347 size_t len = sizeof(memsize);
3348 int mib[2] = {CTL_HW, HW_USERMEM};
3349 if (sysctl(mib,2,&memsize,&len,NULL,0))
3350 return 0;
3352 return memsize;
3354 #else
3355 /* I have no clue. */
3356 return 0;
3357 #endif
3361 * Try to find out how much physical memory the system has. On success,
3362 * return 0 and set *<b>mem_out</b> to that value. On failure, return -1.
3365 get_total_system_memory(size_t *mem_out)
3367 static size_t mem_cached=0;
3368 uint64_t m = get_total_system_memory_impl();
3369 if (0 == m) {
3370 /* LCOV_EXCL_START -- can't make this happen without mocking. */
3371 /* We couldn't find our memory total */
3372 if (0 == mem_cached) {
3373 /* We have no cached value either */
3374 *mem_out = 0;
3375 return -1;
3378 *mem_out = mem_cached;
3379 return 0;
3380 /* LCOV_EXCL_STOP */
3383 #if SIZE_MAX != UINT64_MAX
3384 if (m > SIZE_MAX) {
3385 /* I think this could happen if we're a 32-bit Tor running on a 64-bit
3386 * system: we could have more system memory than would fit in a
3387 * size_t. */
3388 m = SIZE_MAX;
3390 #endif
3392 *mem_out = mem_cached = (size_t) m;
3394 return 0;
3397 /** Emit the password prompt <b>prompt</b>, then read up to <b>buflen</b>
3398 * bytes of passphrase into <b>output</b>. Return the number of bytes in
3399 * the passphrase, excluding terminating NUL.
3401 ssize_t
3402 tor_getpass(const char *prompt, char *output, size_t buflen)
3404 tor_assert(buflen <= SSIZE_MAX);
3405 tor_assert(buflen >= 1);
3406 #if defined(HAVE_READPASSPHRASE)
3407 char *pwd = readpassphrase(prompt, output, buflen, RPP_ECHO_OFF);
3408 if (pwd == NULL)
3409 return -1;
3410 return strlen(pwd);
3411 #elif defined(_WIN32)
3412 int r = -1;
3413 while (*prompt) {
3414 _putch(*prompt++);
3417 tor_assert(buflen <= INT_MAX);
3418 wchar_t *buf = tor_calloc(buflen, sizeof(wchar_t));
3420 wchar_t *ptr = buf, *lastch = buf + buflen - 1;
3421 while (ptr < lastch) {
3422 wint_t ch = _getwch();
3423 switch (ch) {
3424 case '\r':
3425 case '\n':
3426 case WEOF:
3427 goto done_reading;
3428 case 3:
3429 goto done; /* Can't actually read ctrl-c this way. */
3430 case '\b':
3431 if (ptr > buf)
3432 --ptr;
3433 continue;
3434 case 0:
3435 case 0xe0:
3436 ch = _getwch(); /* Ignore; this is a function or arrow key */
3437 break;
3438 default:
3439 *ptr++ = ch;
3440 break;
3443 done_reading:
3446 #ifndef WC_ERR_INVALID_CHARS
3447 #define WC_ERR_INVALID_CHARS 0x80
3448 #endif
3450 /* Now convert it to UTF-8 */
3451 r = WideCharToMultiByte(CP_UTF8,
3452 WC_NO_BEST_FIT_CHARS|WC_ERR_INVALID_CHARS,
3453 buf, (int)(ptr-buf),
3454 output, (int)(buflen-1),
3455 NULL, NULL);
3456 if (r <= 0) {
3457 r = -1;
3458 goto done;
3461 tor_assert(r < (int)buflen);
3463 output[r] = 0;
3465 done:
3466 SecureZeroMemory(buf, sizeof(wchar_t)*buflen);
3467 tor_free(buf);
3468 return r;
3469 #else
3470 #error "No implementation for tor_getpass found!"
3471 #endif
3474 /** Return the amount of free disk space we have permission to use, in
3475 * bytes. Return -1 if the amount of free space can't be determined. */
3476 int64_t
3477 tor_get_avail_disk_space(const char *path)
3479 #ifdef HAVE_STATVFS
3480 struct statvfs st;
3481 int r;
3482 memset(&st, 0, sizeof(st));
3484 r = statvfs(path, &st);
3485 if (r < 0)
3486 return -1;
3488 int64_t result = st.f_bavail;
3489 if (st.f_frsize) {
3490 result *= st.f_frsize;
3491 } else if (st.f_bsize) {
3492 result *= st.f_bsize;
3493 } else {
3494 return -1;
3497 return result;
3498 #elif defined(_WIN32)
3499 ULARGE_INTEGER freeBytesAvail;
3500 BOOL ok;
3502 ok = GetDiskFreeSpaceEx(path, &freeBytesAvail, NULL, NULL);
3503 if (!ok) {
3504 return -1;
3506 return (int64_t)freeBytesAvail.QuadPart;
3507 #else
3508 (void)path;
3509 errno = ENOSYS;
3510 return -1;
3511 #endif