fix typo
[tor.git] / src / common / compat.c
blob390cff7dba408e35500d13871cd042c9f66d19a1
1 /* Copyright (c) 2003-2004, Roger Dingledine
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2017, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
6 /**
7 * \file compat.c
8 * \brief Wrappers to make calls more portable. This code defines
9 * functions such as tor_snprintf, get/set various data types,
10 * renaming, setting socket options, switching user IDs. It is basically
11 * where the non-portable items are conditionally included depending on
12 * the platform.
13 **/
15 #define COMPAT_PRIVATE
16 #include "compat.h"
18 #ifdef _WIN32
19 #include <winsock2.h>
20 #include <windows.h>
21 #include <sys/locking.h>
22 #endif
24 #ifdef HAVE_UNAME
25 #include <sys/utsname.h>
26 #endif
27 #ifdef HAVE_SYS_TYPES_H
28 #include <sys/types.h>
29 #endif
30 #ifdef HAVE_SYS_SYSCTL_H
31 #include <sys/sysctl.h>
32 #endif
33 #ifdef HAVE_SYS_STAT_H
34 #include <sys/stat.h>
35 #endif
36 #ifdef HAVE_UTIME_H
37 #include <utime.h>
38 #endif
39 #ifdef HAVE_SYS_UTIME_H
40 #include <sys/utime.h>
41 #endif
42 #ifdef HAVE_UNISTD_H
43 #include <unistd.h>
44 #endif
45 #ifdef HAVE_SYS_FCNTL_H
46 #include <sys/fcntl.h>
47 #endif
48 #ifdef HAVE_PWD_H
49 #include <pwd.h>
50 #endif
51 #ifdef HAVE_GRP_H
52 #include <grp.h>
53 #endif
54 #ifdef HAVE_FCNTL_H
55 #include <fcntl.h>
56 #endif
57 #ifdef HAVE_ERRNO_H
58 #include <errno.h>
59 #endif
60 #ifdef HAVE_ARPA_INET_H
61 #include <arpa/inet.h>
62 #endif
63 #ifdef HAVE_CRT_EXTERNS_H
64 #include <crt_externs.h>
65 #endif
66 #ifdef HAVE_SYS_STATVFS_H
67 #include <sys/statvfs.h>
68 #endif
69 #ifdef HAVE_SYS_CAPABILITY_H
70 #include <sys/capability.h>
71 #endif
73 #ifdef _WIN32
74 #include <conio.h>
75 #include <wchar.h>
76 /* Some mingw headers lack these. :p */
77 #if defined(HAVE_DECL__GETWCH) && !HAVE_DECL__GETWCH
78 wint_t _getwch(void);
79 #endif
80 #ifndef WEOF
81 #define WEOF (wchar_t)(0xFFFF)
82 #endif
83 #if defined(HAVE_DECL_SECUREZEROMEMORY) && !HAVE_DECL_SECUREZEROMEMORY
84 static inline void
85 SecureZeroMemory(PVOID ptr, SIZE_T cnt)
87 volatile char *vcptr = (volatile char*)ptr;
88 while (cnt--)
89 *vcptr++ = 0;
91 #endif
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 /* Some MinGW builds have sys/mman.h, but not the corresponding symbols.
208 * Other configs rename the symbols using macros (including getpagesize).
209 * So check for sys/mman.h and unistd.h, and a getpagesize declaration. */
210 #if (defined(HAVE_SYS_MMAN_H) && defined(HAVE_UNISTD_H) && \
211 defined(HAVE_DECL_GETPAGESIZE))
212 #define COMPAT_HAS_MMAN_AND_PAGESIZE
213 #endif
215 #if defined(COMPAT_HAS_MMAN_AND_PAGESIZE) || defined(RUNNING_DOXYGEN)
216 /** Try to create a memory mapping for <b>filename</b> and return it. On
217 * failure, return NULL. Sets errno properly, using ERANGE to mean
218 * "empty file". */
219 tor_mmap_t *
220 tor_mmap_file(const char *filename)
222 int fd; /* router file */
223 char *string;
224 int page_size, result;
225 tor_mmap_t *res;
226 size_t size, filesize;
227 struct stat st;
229 tor_assert(filename);
231 fd = tor_open_cloexec(filename, O_RDONLY, 0);
232 if (fd<0) {
233 int save_errno = errno;
234 int severity = (errno == ENOENT) ? LOG_INFO : LOG_WARN;
235 log_fn(severity, LD_FS,"Could not open \"%s\" for mmap(): %s",filename,
236 strerror(errno));
237 errno = save_errno;
238 return NULL;
241 /* Get the size of the file */
242 result = fstat(fd, &st);
243 if (result != 0) {
244 int save_errno = errno;
245 log_warn(LD_FS,
246 "Couldn't fstat opened descriptor for \"%s\" during mmap: %s",
247 filename, strerror(errno));
248 close(fd);
249 errno = save_errno;
250 return NULL;
252 size = filesize = (size_t)(st.st_size);
254 * Should we check for weird crap like mmapping a named pipe here,
255 * or just wait for if (!size) below to fail?
257 /* ensure page alignment */
258 page_size = getpagesize();
259 size += (size%page_size) ? page_size-(size%page_size) : 0;
261 if (st.st_size > SSIZE_T_CEILING || (off_t)size < st.st_size) {
262 log_warn(LD_FS, "File \"%s\" is too large. Ignoring.",filename);
263 errno = EFBIG;
264 close(fd);
265 return NULL;
267 if (!size) {
268 /* Zero-length file. If we call mmap on it, it will succeed but
269 * return NULL, and bad things will happen. So just fail. */
270 log_info(LD_FS,"File \"%s\" is empty. Ignoring.",filename);
271 errno = ERANGE;
272 close(fd);
273 return NULL;
276 string = mmap(0, size, PROT_READ, MAP_PRIVATE, fd, 0);
277 close(fd);
278 if (string == MAP_FAILED) {
279 int save_errno = errno;
280 log_warn(LD_FS,"Could not mmap file \"%s\": %s", filename,
281 strerror(errno));
282 errno = save_errno;
283 return NULL;
286 res = tor_malloc_zero(sizeof(tor_mmap_t));
287 res->data = string;
288 res->size = filesize;
289 res->mapping_size = size;
291 return res;
293 /** Release storage held for a memory mapping; returns 0 on success,
294 * or -1 on failure (and logs a warning). */
296 tor_munmap_file(tor_mmap_t *handle)
298 int res;
300 if (handle == NULL)
301 return 0;
303 res = munmap((char*)handle->data, handle->mapping_size);
304 if (res == 0) {
305 /* munmap() succeeded */
306 tor_free(handle);
307 } else {
308 log_warn(LD_FS, "Failed to munmap() in tor_munmap_file(): %s",
309 strerror(errno));
310 res = -1;
313 return res;
315 #elif defined(_WIN32)
316 tor_mmap_t *
317 tor_mmap_file(const char *filename)
319 TCHAR tfilename[MAX_PATH]= {0};
320 tor_mmap_t *res = tor_malloc_zero(sizeof(tor_mmap_t));
321 int empty = 0;
322 HANDLE file_handle = INVALID_HANDLE_VALUE;
323 DWORD size_low, size_high;
324 uint64_t real_size;
325 res->mmap_handle = NULL;
326 #ifdef UNICODE
327 mbstowcs(tfilename,filename,MAX_PATH);
328 #else
329 strlcpy(tfilename,filename,MAX_PATH);
330 #endif
331 file_handle = CreateFile(tfilename,
332 GENERIC_READ, FILE_SHARE_READ,
333 NULL,
334 OPEN_EXISTING,
335 FILE_ATTRIBUTE_NORMAL,
338 if (file_handle == INVALID_HANDLE_VALUE)
339 goto win_err;
341 size_low = GetFileSize(file_handle, &size_high);
343 if (size_low == INVALID_FILE_SIZE && GetLastError() != NO_ERROR) {
344 log_warn(LD_FS,"Error getting size of \"%s\".",filename);
345 goto win_err;
347 if (size_low == 0 && size_high == 0) {
348 log_info(LD_FS,"File \"%s\" is empty. Ignoring.",filename);
349 empty = 1;
350 goto err;
352 real_size = (((uint64_t)size_high)<<32) | size_low;
353 if (real_size > SIZE_MAX) {
354 log_warn(LD_FS,"File \"%s\" is too big to map; not trying.",filename);
355 goto err;
357 res->size = real_size;
359 res->mmap_handle = CreateFileMapping(file_handle,
360 NULL,
361 PAGE_READONLY,
362 size_high,
363 size_low,
364 NULL);
365 if (res->mmap_handle == NULL)
366 goto win_err;
367 res->data = (char*) MapViewOfFile(res->mmap_handle,
368 FILE_MAP_READ,
369 0, 0, 0);
370 if (!res->data)
371 goto win_err;
373 CloseHandle(file_handle);
374 return res;
375 win_err: {
376 DWORD e = GetLastError();
377 int severity = (e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND) ?
378 LOG_INFO : LOG_WARN;
379 char *msg = format_win32_error(e);
380 log_fn(severity, LD_FS, "Couldn't mmap file \"%s\": %s", filename, msg);
381 tor_free(msg);
382 if (e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND)
383 errno = ENOENT;
384 else
385 errno = EINVAL;
387 err:
388 if (empty)
389 errno = ERANGE;
390 if (file_handle != INVALID_HANDLE_VALUE)
391 CloseHandle(file_handle);
392 tor_munmap_file(res);
393 return NULL;
396 /* Unmap the file, and return 0 for success or -1 for failure */
398 tor_munmap_file(tor_mmap_t *handle)
400 if (handle == NULL)
401 return 0;
403 if (handle->data) {
404 /* This is an ugly cast, but without it, "data" in struct tor_mmap_t would
405 have to be redefined as non-const. */
406 BOOL ok = UnmapViewOfFile( (LPVOID) handle->data);
407 if (!ok) {
408 log_warn(LD_FS, "Failed to UnmapViewOfFile() in tor_munmap_file(): %d",
409 (int)GetLastError());
413 if (handle->mmap_handle != NULL)
414 CloseHandle(handle->mmap_handle);
415 tor_free(handle);
417 return 0;
419 #else
420 tor_mmap_t *
421 tor_mmap_file(const char *filename)
423 struct stat st;
424 char *res = read_file_to_str(filename, RFTS_BIN|RFTS_IGNORE_MISSING, &st);
425 tor_mmap_t *handle;
426 if (! res)
427 return NULL;
428 handle = tor_malloc_zero(sizeof(tor_mmap_t));
429 handle->data = res;
430 handle->size = st.st_size;
431 return handle;
434 /** Unmap the file mapped with tor_mmap_file(), and return 0 for success
435 * or -1 for failure.
439 tor_munmap_file(tor_mmap_t *handle)
441 char *d = NULL;
442 if (handle == NULL)
443 return 0;
445 d = (char*)handle->data;
446 tor_free(d);
447 memwipe(handle, 0, sizeof(tor_mmap_t));
448 tor_free(handle);
450 /* Can't fail in this mmap()/munmap()-free case */
451 return 0;
453 #endif
455 /** Replacement for snprintf. Differs from platform snprintf in two
456 * ways: First, always NUL-terminates its output. Second, always
457 * returns -1 if the result is truncated. (Note that this return
458 * behavior does <i>not</i> conform to C99; it just happens to be
459 * easier to emulate "return -1" with conformant implementations than
460 * it is to emulate "return number that would be written" with
461 * non-conformant implementations.) */
463 tor_snprintf(char *str, size_t size, const char *format, ...)
465 va_list ap;
466 int r;
467 va_start(ap,format);
468 r = tor_vsnprintf(str,size,format,ap);
469 va_end(ap);
470 return r;
473 /** Replacement for vsnprintf; behavior differs as tor_snprintf differs from
474 * snprintf.
477 tor_vsnprintf(char *str, size_t size, const char *format, va_list args)
479 int r;
480 if (size == 0)
481 return -1; /* no place for the NUL */
482 if (size > SIZE_T_CEILING)
483 return -1;
484 #ifdef _WIN32
485 r = _vsnprintf(str, size, format, args);
486 #else
487 r = vsnprintf(str, size, format, args);
488 #endif
489 str[size-1] = '\0';
490 if (r < 0 || r >= (ssize_t)size)
491 return -1;
492 return r;
496 * Portable asprintf implementation. Does a printf() into a newly malloc'd
497 * string. Sets *<b>strp</b> to this string, and returns its length (not
498 * including the terminating NUL character).
500 * You can treat this function as if its implementation were something like
501 <pre>
502 char buf[_INFINITY_];
503 tor_snprintf(buf, sizeof(buf), fmt, args);
504 *strp = tor_strdup(buf);
505 return strlen(*strp):
506 </pre>
507 * Where _INFINITY_ is an imaginary constant so big that any string can fit
508 * into it.
511 tor_asprintf(char **strp, const char *fmt, ...)
513 int r;
514 va_list args;
515 va_start(args, fmt);
516 r = tor_vasprintf(strp, fmt, args);
517 va_end(args);
518 if (!*strp || r < 0) {
519 /* LCOV_EXCL_START */
520 log_err(LD_BUG, "Internal error in asprintf");
521 tor_assert(0);
522 /* LCOV_EXCL_STOP */
524 return r;
528 * Portable vasprintf implementation. Does a printf() into a newly malloc'd
529 * string. Differs from regular vasprintf in the same ways that
530 * tor_asprintf() differs from regular asprintf.
533 tor_vasprintf(char **strp, const char *fmt, va_list args)
535 /* use a temporary variable in case *strp is in args. */
536 char *strp_tmp=NULL;
537 #ifdef HAVE_VASPRINTF
538 /* If the platform gives us one, use it. */
539 int r = vasprintf(&strp_tmp, fmt, args);
540 if (r < 0)
541 *strp = NULL;
542 else
543 *strp = strp_tmp;
544 return r;
545 #elif defined(HAVE__VSCPRINTF)
546 /* On Windows, _vsnprintf won't tell us the length of the string if it
547 * overflows, so we need to use _vcsprintf to tell how much to allocate */
548 int len, r;
549 va_list tmp_args;
550 va_copy(tmp_args, args);
551 len = _vscprintf(fmt, tmp_args);
552 va_end(tmp_args);
553 if (len < 0) {
554 *strp = NULL;
555 return -1;
557 strp_tmp = tor_malloc(len + 1);
558 r = _vsnprintf(strp_tmp, len+1, fmt, args);
559 if (r != len) {
560 tor_free(strp_tmp);
561 *strp = NULL;
562 return -1;
564 *strp = strp_tmp;
565 return len;
566 #else
567 /* Everywhere else, we have a decent vsnprintf that tells us how many
568 * characters we need. We give it a try on a short buffer first, since
569 * it might be nice to avoid the second vsnprintf call.
571 char buf[128];
572 int len, r;
573 va_list tmp_args;
574 va_copy(tmp_args, args);
575 /* vsnprintf() was properly checked but tor_vsnprintf() available so
576 * why not use it? */
577 len = tor_vsnprintf(buf, sizeof(buf), fmt, tmp_args);
578 va_end(tmp_args);
579 if (len < (int)sizeof(buf)) {
580 *strp = tor_strdup(buf);
581 return len;
583 strp_tmp = tor_malloc(len+1);
584 /* use of tor_vsnprintf() will ensure string is null terminated */
585 r = tor_vsnprintf(strp_tmp, len+1, fmt, args);
586 if (r != len) {
587 tor_free(strp_tmp);
588 *strp = NULL;
589 return -1;
591 *strp = strp_tmp;
592 return len;
593 #endif
596 /** Given <b>hlen</b> bytes at <b>haystack</b> and <b>nlen</b> bytes at
597 * <b>needle</b>, return a pointer to the first occurrence of the needle
598 * within the haystack, or NULL if there is no such occurrence.
600 * This function is <em>not</em> timing-safe.
602 * Requires that <b>nlen</b> be greater than zero.
604 const void *
605 tor_memmem(const void *_haystack, size_t hlen,
606 const void *_needle, size_t nlen)
608 #if defined(HAVE_MEMMEM) && (!defined(__GNUC__) || __GNUC__ >= 2)
609 tor_assert(nlen);
610 return memmem(_haystack, hlen, _needle, nlen);
611 #else
612 /* This isn't as fast as the GLIBC implementation, but it doesn't need to
613 * be. */
614 const char *p, *last_possible_start;
615 const char *haystack = (const char*)_haystack;
616 const char *needle = (const char*)_needle;
617 char first;
618 tor_assert(nlen);
620 if (nlen > hlen)
621 return NULL;
623 p = haystack;
624 /* Last position at which the needle could start. */
625 last_possible_start = haystack + hlen - nlen;
626 first = *(const char*)needle;
627 while ((p = memchr(p, first, last_possible_start + 1 - p))) {
628 if (fast_memeq(p, needle, nlen))
629 return p;
630 if (++p > last_possible_start) {
631 /* This comparison shouldn't be necessary, since if p was previously
632 * equal to last_possible_start, the next memchr call would be
633 * "memchr(p, first, 0)", which will return NULL. But it clarifies the
634 * logic. */
635 return NULL;
638 return NULL;
639 #endif
643 * Tables to implement ctypes-replacement TOR_IS*() functions. Each table
644 * has 256 bits to look up whether a character is in some set or not. This
645 * fails on non-ASCII platforms, but it is hard to find a platform whose
646 * character set is not a superset of ASCII nowadays. */
648 /**@{*/
649 const uint32_t TOR_ISALPHA_TABLE[8] =
650 { 0, 0, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
651 const uint32_t TOR_ISALNUM_TABLE[8] =
652 { 0, 0x3ff0000, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
653 const uint32_t TOR_ISSPACE_TABLE[8] = { 0x3e00, 0x1, 0, 0, 0, 0, 0, 0 };
654 const uint32_t TOR_ISXDIGIT_TABLE[8] =
655 { 0, 0x3ff0000, 0x7e, 0x7e, 0, 0, 0, 0 };
656 const uint32_t TOR_ISDIGIT_TABLE[8] = { 0, 0x3ff0000, 0, 0, 0, 0, 0, 0 };
657 const uint32_t TOR_ISPRINT_TABLE[8] =
658 { 0, 0xffffffff, 0xffffffff, 0x7fffffff, 0, 0, 0, 0x0 };
659 const uint32_t TOR_ISUPPER_TABLE[8] = { 0, 0, 0x7fffffe, 0, 0, 0, 0, 0 };
660 const uint32_t TOR_ISLOWER_TABLE[8] = { 0, 0, 0, 0x7fffffe, 0, 0, 0, 0 };
662 /** Upper-casing and lowercasing tables to map characters to upper/lowercase
663 * equivalents. Used by tor_toupper() and tor_tolower(). */
664 /**@{*/
665 const uint8_t TOR_TOUPPER_TABLE[256] = {
666 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
667 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
668 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
669 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
670 64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
671 80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
672 96,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
673 80,81,82,83,84,85,86,87,88,89,90,123,124,125,126,127,
674 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
675 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
676 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
677 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
678 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
679 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
680 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
681 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
683 const uint8_t TOR_TOLOWER_TABLE[256] = {
684 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
685 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
686 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
687 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
688 64,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
689 112,113,114,115,116,117,118,119,120,121,122,91,92,93,94,95,
690 96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
691 112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
692 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
693 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
694 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
695 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
696 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
697 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
698 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
699 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
701 /**@}*/
703 /** Helper for tor_strtok_r_impl: Advances cp past all characters in
704 * <b>sep</b>, and returns its new value. */
705 static char *
706 strtok_helper(char *cp, const char *sep)
708 if (sep[1]) {
709 while (*cp && strchr(sep, *cp))
710 ++cp;
711 } else {
712 while (*cp && *cp == *sep)
713 ++cp;
715 return cp;
718 /** Implementation of strtok_r for platforms whose coders haven't figured out
719 * how to write one. Hey, retrograde libc developers! You can use this code
720 * here for free! */
721 char *
722 tor_strtok_r_impl(char *str, const char *sep, char **lasts)
724 char *cp, *start;
725 tor_assert(*sep);
726 if (str) {
727 str = strtok_helper(str, sep);
728 if (!*str)
729 return NULL;
730 start = cp = *lasts = str;
731 } else if (!*lasts || !**lasts) {
732 return NULL;
733 } else {
734 start = cp = *lasts;
737 if (sep[1]) {
738 while (*cp && !strchr(sep, *cp))
739 ++cp;
740 } else {
741 cp = strchr(cp, *sep);
744 if (!cp || !*cp) {
745 *lasts = NULL;
746 } else {
747 *cp++ = '\0';
748 *lasts = strtok_helper(cp, sep);
750 return start;
753 #ifdef _WIN32
754 /** Take a filename and return a pointer to its final element. This
755 * function is called on __FILE__ to fix a MSVC nit where __FILE__
756 * contains the full path to the file. This is bad, because it
757 * confuses users to find the home directory of the person who
758 * compiled the binary in their warning messages.
760 const char *
761 tor_fix_source_file(const char *fname)
763 const char *cp1, *cp2, *r;
764 cp1 = strrchr(fname, '/');
765 cp2 = strrchr(fname, '\\');
766 if (cp1 && cp2) {
767 r = (cp1<cp2)?(cp2+1):(cp1+1);
768 } else if (cp1) {
769 r = cp1+1;
770 } else if (cp2) {
771 r = cp2+1;
772 } else {
773 r = fname;
775 return r;
777 #endif
780 * Read a 16-bit value beginning at <b>cp</b>. Equivalent to
781 * *(uint16_t*)(cp), but will not cause segfaults on platforms that forbid
782 * unaligned memory access.
784 uint16_t
785 get_uint16(const void *cp)
787 uint16_t v;
788 memcpy(&v,cp,2);
789 return v;
792 * Read a 32-bit value beginning at <b>cp</b>. Equivalent to
793 * *(uint32_t*)(cp), but will not cause segfaults on platforms that forbid
794 * unaligned memory access.
796 uint32_t
797 get_uint32(const void *cp)
799 uint32_t v;
800 memcpy(&v,cp,4);
801 return v;
804 * Read a 64-bit value beginning at <b>cp</b>. Equivalent to
805 * *(uint64_t*)(cp), but will not cause segfaults on platforms that forbid
806 * unaligned memory access.
808 uint64_t
809 get_uint64(const void *cp)
811 uint64_t v;
812 memcpy(&v,cp,8);
813 return v;
817 * Set a 16-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
818 * *(uint16_t*)(cp) = v, but will not cause segfaults on platforms that forbid
819 * unaligned memory access. */
820 void
821 set_uint16(void *cp, uint16_t v)
823 memcpy(cp,&v,2);
826 * Set a 32-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
827 * *(uint32_t*)(cp) = v, but will not cause segfaults on platforms that forbid
828 * unaligned memory access. */
829 void
830 set_uint32(void *cp, uint32_t v)
832 memcpy(cp,&v,4);
835 * Set a 64-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
836 * *(uint64_t*)(cp) = v, but will not cause segfaults on platforms that forbid
837 * unaligned memory access. */
838 void
839 set_uint64(void *cp, uint64_t v)
841 memcpy(cp,&v,8);
845 * Rename the file <b>from</b> to the file <b>to</b>. On Unix, this is
846 * the same as rename(2). On windows, this removes <b>to</b> first if
847 * it already exists.
848 * Returns 0 on success. Returns -1 and sets errno on failure.
851 replace_file(const char *from, const char *to)
853 #ifndef _WIN32
854 return tor_rename(from, to);
855 #else
856 switch (file_status(to))
858 case FN_NOENT:
859 break;
860 case FN_FILE:
861 case FN_EMPTY:
862 if (unlink(to)) return -1;
863 break;
864 case FN_ERROR:
865 return -1;
866 case FN_DIR:
867 errno = EISDIR;
868 return -1;
870 return tor_rename(from,to);
871 #endif
874 /** Change <b>fname</b>'s modification time to now. */
876 touch_file(const char *fname)
878 if (utime(fname, NULL)!=0)
879 return -1;
880 return 0;
883 /** Represents a lockfile on which we hold the lock. */
884 struct tor_lockfile_t {
885 /** Name of the file */
886 char *filename;
887 /** File descriptor used to hold the file open */
888 int fd;
891 /** Try to get a lock on the lockfile <b>filename</b>, creating it as
892 * necessary. If someone else has the lock and <b>blocking</b> is true,
893 * wait until the lock is available. Otherwise return immediately whether
894 * we succeeded or not.
896 * Set *<b>locked_out</b> to true if somebody else had the lock, and to false
897 * otherwise.
899 * Return a <b>tor_lockfile_t</b> on success, NULL on failure.
901 * (Implementation note: because we need to fall back to fcntl on some
902 * platforms, these locks are per-process, not per-thread. If you want
903 * to do in-process locking, use tor_mutex_t like a normal person.
904 * On Windows, when <b>blocking</b> is true, the maximum time that
905 * is actually waited is 10 seconds, after which NULL is returned
906 * and <b>locked_out</b> is set to 1.)
908 tor_lockfile_t *
909 tor_lockfile_lock(const char *filename, int blocking, int *locked_out)
911 tor_lockfile_t *result;
912 int fd;
913 *locked_out = 0;
915 log_info(LD_FS, "Locking \"%s\"", filename);
916 fd = tor_open_cloexec(filename, O_RDWR|O_CREAT|O_TRUNC, 0600);
917 if (fd < 0) {
918 log_warn(LD_FS,"Couldn't open \"%s\" for locking: %s", filename,
919 strerror(errno));
920 return NULL;
923 #ifdef _WIN32
924 _lseek(fd, 0, SEEK_SET);
925 if (_locking(fd, blocking ? _LK_LOCK : _LK_NBLCK, 1) < 0) {
926 if (errno != EACCES && errno != EDEADLOCK)
927 log_warn(LD_FS,"Couldn't lock \"%s\": %s", filename, strerror(errno));
928 else
929 *locked_out = 1;
930 close(fd);
931 return NULL;
933 #elif defined(HAVE_FLOCK)
934 if (flock(fd, LOCK_EX|(blocking ? 0 : LOCK_NB)) < 0) {
935 if (errno != EWOULDBLOCK)
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;
942 #else
944 struct flock lock;
945 memset(&lock, 0, sizeof(lock));
946 lock.l_type = F_WRLCK;
947 lock.l_whence = SEEK_SET;
948 if (fcntl(fd, blocking ? F_SETLKW : F_SETLK, &lock) < 0) {
949 if (errno != EACCES && errno != EAGAIN)
950 log_warn(LD_FS, "Couldn't lock \"%s\": %s", filename, strerror(errno));
951 else
952 *locked_out = 1;
953 close(fd);
954 return NULL;
957 #endif
959 result = tor_malloc(sizeof(tor_lockfile_t));
960 result->filename = tor_strdup(filename);
961 result->fd = fd;
962 return result;
965 /** Release the lock held as <b>lockfile</b>. */
966 void
967 tor_lockfile_unlock(tor_lockfile_t *lockfile)
969 tor_assert(lockfile);
971 log_info(LD_FS, "Unlocking \"%s\"", lockfile->filename);
972 #ifdef _WIN32
973 _lseek(lockfile->fd, 0, SEEK_SET);
974 if (_locking(lockfile->fd, _LK_UNLCK, 1) < 0) {
975 log_warn(LD_FS,"Error unlocking \"%s\": %s", lockfile->filename,
976 strerror(errno));
978 #elif defined(HAVE_FLOCK)
979 if (flock(lockfile->fd, LOCK_UN) < 0) {
980 log_warn(LD_FS, "Error unlocking \"%s\": %s", lockfile->filename,
981 strerror(errno));
983 #else
984 /* Closing the lockfile is sufficient. */
985 #endif
987 close(lockfile->fd);
988 lockfile->fd = -1;
989 tor_free(lockfile->filename);
990 tor_free(lockfile);
993 /** @{ */
994 /** Some old versions of Unix didn't define constants for these values,
995 * and instead expect you to say 0, 1, or 2. */
996 #ifndef SEEK_SET
997 #define SEEK_SET 0
998 #endif
999 #ifndef SEEK_CUR
1000 #define SEEK_CUR 1
1001 #endif
1002 #ifndef SEEK_END
1003 #define SEEK_END 2
1004 #endif
1005 /** @} */
1007 /** Return the position of <b>fd</b> with respect to the start of the file. */
1008 off_t
1009 tor_fd_getpos(int fd)
1011 #ifdef _WIN32
1012 return (off_t) _lseek(fd, 0, SEEK_CUR);
1013 #else
1014 return (off_t) lseek(fd, 0, SEEK_CUR);
1015 #endif
1018 /** Move <b>fd</b> to the end of the file. Return -1 on error, 0 on success.
1019 * If the file is a pipe, do nothing and succeed.
1022 tor_fd_seekend(int fd)
1024 #ifdef _WIN32
1025 return _lseek(fd, 0, SEEK_END) < 0 ? -1 : 0;
1026 #else
1027 off_t rc = lseek(fd, 0, SEEK_END) < 0 ? -1 : 0;
1028 #ifdef ESPIPE
1029 /* If we get an error and ESPIPE, then it's a pipe or a socket of a fifo:
1030 * no need to worry. */
1031 if (rc < 0 && errno == ESPIPE)
1032 rc = 0;
1033 #endif
1034 return (rc < 0) ? -1 : 0;
1035 #endif
1038 /** Move <b>fd</b> to position <b>pos</b> in the file. Return -1 on error, 0
1039 * on success. */
1041 tor_fd_setpos(int fd, off_t pos)
1043 #ifdef _WIN32
1044 return _lseek(fd, pos, SEEK_SET) < 0 ? -1 : 0;
1045 #else
1046 return lseek(fd, pos, SEEK_SET) < 0 ? -1 : 0;
1047 #endif
1050 /** Replacement for ftruncate(fd, 0): move to the front of the file and remove
1051 * all the rest of the file. Return -1 on error, 0 on success. */
1053 tor_ftruncate(int fd)
1055 /* Rumor has it that some versions of ftruncate do not move the file pointer.
1057 if (tor_fd_setpos(fd, 0) < 0)
1058 return -1;
1060 #ifdef _WIN32
1061 return _chsize(fd, 0);
1062 #else
1063 return ftruncate(fd, 0);
1064 #endif
1067 #undef DEBUG_SOCKET_COUNTING
1068 #ifdef DEBUG_SOCKET_COUNTING
1069 /** A bitarray of all fds that should be passed to tor_socket_close(). Only
1070 * used if DEBUG_SOCKET_COUNTING is defined. */
1071 static bitarray_t *open_sockets = NULL;
1072 /** The size of <b>open_sockets</b>, in bits. */
1073 static int max_socket = -1;
1074 #endif
1076 /** Count of number of sockets currently open. (Undercounts sockets opened by
1077 * eventdns and libevent.) */
1078 static int n_sockets_open = 0;
1080 /** Mutex to protect open_sockets, max_socket, and n_sockets_open. */
1081 static tor_mutex_t *socket_accounting_mutex = NULL;
1083 /** Helper: acquire the socket accounting lock. */
1084 static inline void
1085 socket_accounting_lock(void)
1087 if (PREDICT_UNLIKELY(!socket_accounting_mutex))
1088 socket_accounting_mutex = tor_mutex_new();
1089 tor_mutex_acquire(socket_accounting_mutex);
1092 /** Helper: release the socket accounting lock. */
1093 static inline void
1094 socket_accounting_unlock(void)
1096 tor_mutex_release(socket_accounting_mutex);
1099 /** As close(), but guaranteed to work for sockets across platforms (including
1100 * Windows, where close()ing a socket doesn't work. Returns 0 on success and
1101 * the socket error code on failure. */
1103 tor_close_socket_simple(tor_socket_t s)
1105 int r = 0;
1107 /* On Windows, you have to call close() on fds returned by open(),
1108 * and closesocket() on fds returned by socket(). On Unix, everything
1109 * gets close()'d. We abstract this difference by always using
1110 * tor_close_socket to close sockets, and always using close() on
1111 * files.
1113 #if defined(_WIN32)
1114 r = closesocket(s);
1115 #else
1116 r = close(s);
1117 #endif
1119 if (r != 0) {
1120 int err = tor_socket_errno(-1);
1121 log_info(LD_NET, "Close returned an error: %s", tor_socket_strerror(err));
1122 return err;
1125 return r;
1128 /** As tor_close_socket_simple(), but keeps track of the number
1129 * of open sockets. Returns 0 on success, -1 on failure. */
1130 MOCK_IMPL(int,
1131 tor_close_socket,(tor_socket_t s))
1133 int r = tor_close_socket_simple(s);
1135 socket_accounting_lock();
1136 #ifdef DEBUG_SOCKET_COUNTING
1137 if (s > max_socket || ! bitarray_is_set(open_sockets, s)) {
1138 log_warn(LD_BUG, "Closing a socket (%d) that wasn't returned by tor_open_"
1139 "socket(), or that was already closed or something.", s);
1140 } else {
1141 tor_assert(open_sockets && s <= max_socket);
1142 bitarray_clear(open_sockets, s);
1144 #endif
1145 if (r == 0) {
1146 --n_sockets_open;
1147 } else {
1148 #ifdef _WIN32
1149 if (r != WSAENOTSOCK)
1150 --n_sockets_open;
1151 #else
1152 if (r != EBADF)
1153 --n_sockets_open; // LCOV_EXCL_LINE -- EIO and EINTR too hard to force.
1154 #endif
1155 r = -1;
1158 tor_assert_nonfatal(n_sockets_open >= 0);
1159 socket_accounting_unlock();
1160 return r;
1163 /** @{ */
1164 #ifdef DEBUG_SOCKET_COUNTING
1165 /** Helper: if DEBUG_SOCKET_COUNTING is enabled, remember that <b>s</b> is
1166 * now an open socket. */
1167 static inline void
1168 mark_socket_open(tor_socket_t s)
1170 /* XXXX This bitarray business will NOT work on windows: sockets aren't
1171 small ints there. */
1172 if (s > max_socket) {
1173 if (max_socket == -1) {
1174 open_sockets = bitarray_init_zero(s+128);
1175 max_socket = s+128;
1176 } else {
1177 open_sockets = bitarray_expand(open_sockets, max_socket, s+128);
1178 max_socket = s+128;
1181 if (bitarray_is_set(open_sockets, s)) {
1182 log_warn(LD_BUG, "I thought that %d was already open, but socket() just "
1183 "gave it to me!", s);
1185 bitarray_set(open_sockets, s);
1187 #else
1188 #define mark_socket_open(s) STMT_NIL
1189 #endif
1190 /** @} */
1192 /** As socket(), but counts the number of open sockets. */
1193 MOCK_IMPL(tor_socket_t,
1194 tor_open_socket,(int domain, int type, int protocol))
1196 return tor_open_socket_with_extensions(domain, type, protocol, 1, 0);
1199 /** Mockable wrapper for connect(). */
1200 MOCK_IMPL(tor_socket_t,
1201 tor_connect_socket,(tor_socket_t sock, const struct sockaddr *address,
1202 socklen_t address_len))
1204 return connect(sock,address,address_len);
1207 /** As socket(), but creates a nonblocking socket and
1208 * counts the number of open sockets. */
1209 tor_socket_t
1210 tor_open_socket_nonblocking(int domain, int type, int protocol)
1212 return tor_open_socket_with_extensions(domain, type, protocol, 1, 1);
1215 /** As socket(), but counts the number of open sockets and handles
1216 * socket creation with either of SOCK_CLOEXEC and SOCK_NONBLOCK specified.
1217 * <b>cloexec</b> and <b>nonblock</b> should be either 0 or 1 to indicate
1218 * if the corresponding extension should be used.*/
1219 tor_socket_t
1220 tor_open_socket_with_extensions(int domain, int type, int protocol,
1221 int cloexec, int nonblock)
1223 tor_socket_t s;
1225 /* We are about to create a new file descriptor so make sure we have
1226 * enough of them. */
1227 if (get_n_open_sockets() >= max_sockets - 1) {
1228 #ifdef _WIN32
1229 WSASetLastError(WSAEMFILE);
1230 #else
1231 errno = EMFILE;
1232 #endif
1233 return TOR_INVALID_SOCKET;
1236 #if defined(SOCK_CLOEXEC) && defined(SOCK_NONBLOCK)
1237 int ext_flags = (cloexec ? SOCK_CLOEXEC : 0) |
1238 (nonblock ? SOCK_NONBLOCK : 0);
1239 s = socket(domain, type|ext_flags, protocol);
1240 if (SOCKET_OK(s))
1241 goto socket_ok;
1242 /* If we got an error, see if it is EINVAL. EINVAL might indicate that,
1243 * even though we were built on a system with SOCK_CLOEXEC and SOCK_NONBLOCK
1244 * support, we are running on one without. */
1245 if (errno != EINVAL)
1246 return s;
1247 #endif /* SOCK_CLOEXEC && SOCK_NONBLOCK */
1249 s = socket(domain, type, protocol);
1250 if (! SOCKET_OK(s))
1251 return s;
1253 #if defined(FD_CLOEXEC)
1254 if (cloexec) {
1255 if (fcntl(s, F_SETFD, FD_CLOEXEC) == -1) {
1256 log_warn(LD_FS,"Couldn't set FD_CLOEXEC: %s", strerror(errno));
1257 tor_close_socket_simple(s);
1258 return TOR_INVALID_SOCKET;
1261 #else
1262 (void)cloexec;
1263 #endif
1265 if (nonblock) {
1266 if (set_socket_nonblocking(s) == -1) {
1267 tor_close_socket_simple(s);
1268 return TOR_INVALID_SOCKET;
1272 goto socket_ok; /* So that socket_ok will not be unused. */
1274 socket_ok:
1275 socket_accounting_lock();
1276 ++n_sockets_open;
1277 mark_socket_open(s);
1278 socket_accounting_unlock();
1279 return s;
1282 /** As accept(), but counts the number of open sockets. */
1283 tor_socket_t
1284 tor_accept_socket(tor_socket_t sockfd, struct sockaddr *addr, socklen_t *len)
1286 return tor_accept_socket_with_extensions(sockfd, addr, len, 1, 0);
1289 /** As accept(), but returns a nonblocking socket and
1290 * counts the number of open sockets. */
1291 tor_socket_t
1292 tor_accept_socket_nonblocking(tor_socket_t sockfd, struct sockaddr *addr,
1293 socklen_t *len)
1295 return tor_accept_socket_with_extensions(sockfd, addr, len, 1, 1);
1298 /** As accept(), but counts the number of open sockets and handles
1299 * socket creation with either of SOCK_CLOEXEC and SOCK_NONBLOCK specified.
1300 * <b>cloexec</b> and <b>nonblock</b> should be either 0 or 1 to indicate
1301 * if the corresponding extension should be used.*/
1302 tor_socket_t
1303 tor_accept_socket_with_extensions(tor_socket_t sockfd, struct sockaddr *addr,
1304 socklen_t *len, int cloexec, int nonblock)
1306 tor_socket_t s;
1308 /* We are about to create a new file descriptor so make sure we have
1309 * enough of them. */
1310 if (get_n_open_sockets() >= max_sockets - 1) {
1311 #ifdef _WIN32
1312 WSASetLastError(WSAEMFILE);
1313 #else
1314 errno = EMFILE;
1315 #endif
1316 return TOR_INVALID_SOCKET;
1319 #if defined(HAVE_ACCEPT4) && defined(SOCK_CLOEXEC) && defined(SOCK_NONBLOCK)
1320 int ext_flags = (cloexec ? SOCK_CLOEXEC : 0) |
1321 (nonblock ? SOCK_NONBLOCK : 0);
1322 s = accept4(sockfd, addr, len, ext_flags);
1323 if (SOCKET_OK(s))
1324 goto socket_ok;
1325 /* If we got an error, see if it is ENOSYS. ENOSYS indicates that,
1326 * even though we were built on a system with accept4 support, we
1327 * are running on one without. Also, check for EINVAL, which indicates that
1328 * we are missing SOCK_CLOEXEC/SOCK_NONBLOCK support. */
1329 if (errno != EINVAL && errno != ENOSYS)
1330 return s;
1331 #endif
1333 s = accept(sockfd, addr, len);
1334 if (!SOCKET_OK(s))
1335 return s;
1337 #if defined(FD_CLOEXEC)
1338 if (cloexec) {
1339 if (fcntl(s, F_SETFD, FD_CLOEXEC) == -1) {
1340 log_warn(LD_NET, "Couldn't set FD_CLOEXEC: %s", strerror(errno));
1341 tor_close_socket_simple(s);
1342 return TOR_INVALID_SOCKET;
1345 #else
1346 (void)cloexec;
1347 #endif
1349 if (nonblock) {
1350 if (set_socket_nonblocking(s) == -1) {
1351 tor_close_socket_simple(s);
1352 return TOR_INVALID_SOCKET;
1356 goto socket_ok; /* So that socket_ok will not be unused. */
1358 socket_ok:
1359 socket_accounting_lock();
1360 ++n_sockets_open;
1361 mark_socket_open(s);
1362 socket_accounting_unlock();
1363 return s;
1366 /** Return the number of sockets we currently have opened. */
1368 get_n_open_sockets(void)
1370 int n;
1371 socket_accounting_lock();
1372 n = n_sockets_open;
1373 socket_accounting_unlock();
1374 return n;
1377 /** Mockable wrapper for getsockname(). */
1378 MOCK_IMPL(int,
1379 tor_getsockname,(tor_socket_t sock, struct sockaddr *address,
1380 socklen_t *address_len))
1382 return getsockname(sock, address, address_len);
1385 /** Turn <b>socket</b> into a nonblocking socket. Return 0 on success, -1
1386 * on failure.
1389 set_socket_nonblocking(tor_socket_t sock)
1391 #if defined(_WIN32)
1392 unsigned long nonblocking = 1;
1393 ioctlsocket(sock, FIONBIO, (unsigned long*) &nonblocking);
1394 #else
1395 int flags;
1397 flags = fcntl(sock, F_GETFL, 0);
1398 if (flags == -1) {
1399 log_warn(LD_NET, "Couldn't get file status flags: %s", strerror(errno));
1400 return -1;
1402 flags |= O_NONBLOCK;
1403 if (fcntl(sock, F_SETFL, flags) == -1) {
1404 log_warn(LD_NET, "Couldn't set file status flags: %s", strerror(errno));
1405 return -1;
1407 #endif
1409 return 0;
1413 * Allocate a pair of connected sockets. (Like socketpair(family,
1414 * type,protocol,fd), but works on systems that don't have
1415 * socketpair.)
1417 * Currently, only (AF_UNIX, SOCK_STREAM, 0) sockets are supported.
1419 * Note that on systems without socketpair, this call will fail if
1420 * localhost is inaccessible (for example, if the networking
1421 * stack is down). And even if it succeeds, the socket pair will not
1422 * be able to read while localhost is down later (the socket pair may
1423 * even close, depending on OS-specific timeouts).
1425 * Returns 0 on success and -errno on failure; do not rely on the value
1426 * of errno or WSAGetLastError().
1428 /* It would be nicer just to set errno, but that won't work for windows. */
1430 tor_socketpair(int family, int type, int protocol, tor_socket_t fd[2])
1432 //don't use win32 socketpairs (they are always bad)
1433 #if defined(HAVE_SOCKETPAIR) && !defined(_WIN32)
1434 int r;
1436 #ifdef SOCK_CLOEXEC
1437 r = socketpair(family, type|SOCK_CLOEXEC, protocol, fd);
1438 if (r == 0)
1439 goto sockets_ok;
1440 /* If we got an error, see if it is EINVAL. EINVAL might indicate that,
1441 * even though we were built on a system with SOCK_CLOEXEC support, we
1442 * are running on one without. */
1443 if (errno != EINVAL)
1444 return -errno;
1445 #endif
1447 r = socketpair(family, type, protocol, fd);
1448 if (r < 0)
1449 return -errno;
1451 #if defined(FD_CLOEXEC)
1452 if (SOCKET_OK(fd[0])) {
1453 r = fcntl(fd[0], F_SETFD, FD_CLOEXEC);
1454 if (r == -1) {
1455 close(fd[0]);
1456 close(fd[1]);
1457 return -errno;
1460 if (SOCKET_OK(fd[1])) {
1461 r = fcntl(fd[1], F_SETFD, FD_CLOEXEC);
1462 if (r == -1) {
1463 close(fd[0]);
1464 close(fd[1]);
1465 return -errno;
1468 #endif
1469 goto sockets_ok; /* So that sockets_ok will not be unused. */
1471 sockets_ok:
1472 socket_accounting_lock();
1473 if (SOCKET_OK(fd[0])) {
1474 ++n_sockets_open;
1475 mark_socket_open(fd[0]);
1477 if (SOCKET_OK(fd[1])) {
1478 ++n_sockets_open;
1479 mark_socket_open(fd[1]);
1481 socket_accounting_unlock();
1483 return 0;
1484 #else
1485 return tor_ersatz_socketpair(family, type, protocol, fd);
1486 #endif
1489 #ifdef NEED_ERSATZ_SOCKETPAIR
1491 static inline socklen_t
1492 SIZEOF_SOCKADDR(int domain)
1494 switch (domain) {
1495 case AF_INET:
1496 return sizeof(struct sockaddr_in);
1497 case AF_INET6:
1498 return sizeof(struct sockaddr_in6);
1499 default:
1500 return 0;
1505 * Helper used to implement socketpair on systems that lack it, by
1506 * making a direct connection to localhost.
1508 STATIC int
1509 tor_ersatz_socketpair(int family, int type, int protocol, tor_socket_t fd[2])
1511 /* This socketpair does not work when localhost is down. So
1512 * it's really not the same thing at all. But it's close enough
1513 * for now, and really, when localhost is down sometimes, we
1514 * have other problems too.
1516 tor_socket_t listener = TOR_INVALID_SOCKET;
1517 tor_socket_t connector = TOR_INVALID_SOCKET;
1518 tor_socket_t acceptor = TOR_INVALID_SOCKET;
1519 tor_addr_t listen_tor_addr;
1520 struct sockaddr_storage connect_addr_ss, listen_addr_ss;
1521 struct sockaddr *listen_addr = (struct sockaddr *) &listen_addr_ss;
1522 uint16_t listen_port = 0;
1523 tor_addr_t connect_tor_addr;
1524 uint16_t connect_port = 0;
1525 struct sockaddr *connect_addr = (struct sockaddr *) &connect_addr_ss;
1526 socklen_t size;
1527 int saved_errno = -1;
1528 int ersatz_domain = AF_INET;
1530 memset(&connect_tor_addr, 0, sizeof(connect_tor_addr));
1531 memset(&connect_addr_ss, 0, sizeof(connect_addr_ss));
1532 memset(&listen_tor_addr, 0, sizeof(listen_tor_addr));
1533 memset(&listen_addr_ss, 0, sizeof(listen_addr_ss));
1535 if (protocol
1536 #ifdef AF_UNIX
1537 || family != AF_UNIX
1538 #endif
1540 #ifdef _WIN32
1541 return -WSAEAFNOSUPPORT;
1542 #else
1543 return -EAFNOSUPPORT;
1544 #endif
1546 if (!fd) {
1547 return -EINVAL;
1550 listener = tor_open_socket(ersatz_domain, type, 0);
1551 if (!SOCKET_OK(listener)) {
1552 int first_errno = tor_socket_errno(-1);
1553 if (first_errno == SOCK_ERRNO(EPROTONOSUPPORT)
1554 && ersatz_domain == AF_INET) {
1555 /* Assume we're on an IPv6-only system */
1556 ersatz_domain = AF_INET6;
1557 listener = tor_open_socket(ersatz_domain, type, 0);
1558 if (!SOCKET_OK(listener)) {
1559 /* Keep the previous behaviour, which was to return the IPv4 error.
1560 * (This may be less informative on IPv6-only systems.)
1561 * XX/teor - is there a better way to decide which errno to return?
1562 * (I doubt we care much either way, once there is an error.)
1564 return -first_errno;
1568 /* If there is no 127.0.0.1 or ::1, this will and must fail. Otherwise, we
1569 * risk exposing a socketpair on a routable IP address. (Some BSD jails
1570 * use a routable address for localhost. Fortunately, they have the real
1571 * AF_UNIX socketpair.) */
1572 if (ersatz_domain == AF_INET) {
1573 tor_addr_from_ipv4h(&listen_tor_addr, INADDR_LOOPBACK);
1574 } else {
1575 tor_addr_parse(&listen_tor_addr, "[::1]");
1577 tor_assert(tor_addr_is_loopback(&listen_tor_addr));
1578 size = tor_addr_to_sockaddr(&listen_tor_addr,
1579 0 /* kernel chooses port. */,
1580 listen_addr,
1581 sizeof(listen_addr_ss));
1582 if (bind(listener, listen_addr, size) == -1)
1583 goto tidy_up_and_fail;
1584 if (listen(listener, 1) == -1)
1585 goto tidy_up_and_fail;
1587 connector = tor_open_socket(ersatz_domain, type, 0);
1588 if (!SOCKET_OK(connector))
1589 goto tidy_up_and_fail;
1590 /* We want to find out the port number to connect to. */
1591 size = sizeof(connect_addr_ss);
1592 if (getsockname(listener, connect_addr, &size) == -1)
1593 goto tidy_up_and_fail;
1594 if (size != SIZEOF_SOCKADDR (connect_addr->sa_family))
1595 goto abort_tidy_up_and_fail;
1596 if (connect(connector, connect_addr, size) == -1)
1597 goto tidy_up_and_fail;
1599 size = sizeof(listen_addr_ss);
1600 acceptor = tor_accept_socket(listener, listen_addr, &size);
1601 if (!SOCKET_OK(acceptor))
1602 goto tidy_up_and_fail;
1603 if (size != SIZEOF_SOCKADDR(listen_addr->sa_family))
1604 goto abort_tidy_up_and_fail;
1605 /* Now check we are talking to ourself by matching port and host on the
1606 two sockets. */
1607 if (getsockname(connector, connect_addr, &size) == -1)
1608 goto tidy_up_and_fail;
1609 /* Set *_tor_addr and *_port to the address and port that was used */
1610 tor_addr_from_sockaddr(&listen_tor_addr, listen_addr, &listen_port);
1611 tor_addr_from_sockaddr(&connect_tor_addr, connect_addr, &connect_port);
1612 if (size != SIZEOF_SOCKADDR (connect_addr->sa_family)
1613 || tor_addr_compare(&listen_tor_addr, &connect_tor_addr, CMP_SEMANTIC)
1614 || listen_port != connect_port) {
1615 goto abort_tidy_up_and_fail;
1617 tor_close_socket(listener);
1618 fd[0] = connector;
1619 fd[1] = acceptor;
1621 return 0;
1623 abort_tidy_up_and_fail:
1624 #ifdef _WIN32
1625 saved_errno = WSAECONNABORTED;
1626 #else
1627 saved_errno = ECONNABORTED; /* I hope this is portable and appropriate. */
1628 #endif
1629 tidy_up_and_fail:
1630 if (saved_errno < 0)
1631 saved_errno = errno;
1632 if (SOCKET_OK(listener))
1633 tor_close_socket(listener);
1634 if (SOCKET_OK(connector))
1635 tor_close_socket(connector);
1636 if (SOCKET_OK(acceptor))
1637 tor_close_socket(acceptor);
1638 return -saved_errno;
1641 #undef SIZEOF_SOCKADDR
1643 #endif
1645 /* Return the maximum number of allowed sockets. */
1647 get_max_sockets(void)
1649 return max_sockets;
1652 /** Number of extra file descriptors to keep in reserve beyond those that we
1653 * tell Tor it's allowed to use. */
1654 #define ULIMIT_BUFFER 32 /* keep 32 extra fd's beyond ConnLimit_ */
1656 /** Learn the maximum allowed number of file descriptors, and tell the
1657 * system we want to use up to that number. (Some systems have a low soft
1658 * limit, and let us set it higher.) We compute this by finding the largest
1659 * number that we can use.
1661 * If the limit is below the reserved file descriptor value (ULIMIT_BUFFER),
1662 * return -1 and <b>max_out</b> is untouched.
1664 * If we can't find a number greater than or equal to <b>limit</b>, then we
1665 * fail by returning -1 and <b>max_out</b> is untouched.
1667 * If we are unable to set the limit value because of setrlimit() failing,
1668 * return -1 and <b>max_out</b> is set to the current maximum value returned
1669 * by getrlimit().
1671 * Otherwise, return 0 and store the maximum we found inside <b>max_out</b>
1672 * and set <b>max_sockets</b> with that value as well.*/
1674 set_max_file_descriptors(rlim_t limit, int *max_out)
1676 if (limit < ULIMIT_BUFFER) {
1677 log_warn(LD_CONFIG,
1678 "ConnLimit must be at least %d. Failing.", ULIMIT_BUFFER);
1679 return -1;
1682 /* Define some maximum connections values for systems where we cannot
1683 * automatically determine a limit. Re Cygwin, see
1684 * http://archives.seul.org/or/talk/Aug-2006/msg00210.html
1685 * For an iPhone, 9999 should work. For Windows and all other unknown
1686 * systems we use 15000 as the default. */
1687 #ifndef HAVE_GETRLIMIT
1688 #if defined(CYGWIN) || defined(__CYGWIN__)
1689 const char *platform = "Cygwin";
1690 const unsigned long MAX_CONNECTIONS = 3200;
1691 #elif defined(_WIN32)
1692 const char *platform = "Windows";
1693 const unsigned long MAX_CONNECTIONS = 15000;
1694 #else
1695 const char *platform = "unknown platforms with no getrlimit()";
1696 const unsigned long MAX_CONNECTIONS = 15000;
1697 #endif
1698 log_fn(LOG_INFO, LD_NET,
1699 "This platform is missing getrlimit(). Proceeding.");
1700 if (limit > MAX_CONNECTIONS) {
1701 log_warn(LD_CONFIG,
1702 "We do not support more than %lu file descriptors "
1703 "on %s. Tried to raise to %lu.",
1704 (unsigned long)MAX_CONNECTIONS, platform, (unsigned long)limit);
1705 return -1;
1707 limit = MAX_CONNECTIONS;
1708 #else /* HAVE_GETRLIMIT */
1709 struct rlimit rlim;
1711 if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) {
1712 log_warn(LD_NET, "Could not get maximum number of file descriptors: %s",
1713 strerror(errno));
1714 return -1;
1716 if (rlim.rlim_max < limit) {
1717 log_warn(LD_CONFIG,"We need %lu file descriptors available, and we're "
1718 "limited to %lu. Please change your ulimit -n.",
1719 (unsigned long)limit, (unsigned long)rlim.rlim_max);
1720 return -1;
1723 if (rlim.rlim_max > rlim.rlim_cur) {
1724 log_info(LD_NET,"Raising max file descriptors from %lu to %lu.",
1725 (unsigned long)rlim.rlim_cur, (unsigned long)rlim.rlim_max);
1727 /* Set the current limit value so if the attempt to set the limit to the
1728 * max fails at least we'll have a valid value of maximum sockets. */
1729 *max_out = max_sockets = (int)rlim.rlim_cur - ULIMIT_BUFFER;
1730 rlim.rlim_cur = rlim.rlim_max;
1732 if (setrlimit(RLIMIT_NOFILE, &rlim) != 0) {
1733 int bad = 1;
1734 #ifdef OPEN_MAX
1735 if (errno == EINVAL && OPEN_MAX < rlim.rlim_cur) {
1736 /* On some platforms, OPEN_MAX is the real limit, and getrlimit() is
1737 * full of nasty lies. I'm looking at you, OSX 10.5.... */
1738 rlim.rlim_cur = OPEN_MAX;
1739 if (setrlimit(RLIMIT_NOFILE, &rlim) == 0) {
1740 if (rlim.rlim_cur < (rlim_t)limit) {
1741 log_warn(LD_CONFIG, "We are limited to %lu file descriptors by "
1742 "OPEN_MAX, and ConnLimit is %lu. Changing ConnLimit; sorry.",
1743 (unsigned long)OPEN_MAX, (unsigned long)limit);
1744 } else {
1745 log_info(LD_CONFIG, "Dropped connection limit to OPEN_MAX (%lu); "
1746 "Apparently, %lu was too high and rlimit lied to us.",
1747 (unsigned long)OPEN_MAX, (unsigned long)rlim.rlim_max);
1749 bad = 0;
1752 #endif /* OPEN_MAX */
1753 if (bad) {
1754 log_warn(LD_CONFIG,"Couldn't set maximum number of file descriptors: %s",
1755 strerror(errno));
1756 return -1;
1759 /* leave some overhead for logs, etc, */
1760 limit = rlim.rlim_cur;
1761 #endif /* HAVE_GETRLIMIT */
1763 if (limit > INT_MAX)
1764 limit = INT_MAX;
1765 tor_assert(max_out);
1766 *max_out = max_sockets = (int)limit - ULIMIT_BUFFER;
1767 return 0;
1770 #ifndef _WIN32
1771 /** Log details of current user and group credentials. Return 0 on
1772 * success. Logs and return -1 on failure.
1774 static int
1775 log_credential_status(void)
1777 /** Log level to use when describing non-error UID/GID status. */
1778 #define CREDENTIAL_LOG_LEVEL LOG_INFO
1779 /* Real, effective and saved UIDs */
1780 uid_t ruid, euid, suid;
1781 /* Read, effective and saved GIDs */
1782 gid_t rgid, egid, sgid;
1783 /* Supplementary groups */
1784 gid_t *sup_gids = NULL;
1785 int sup_gids_size;
1786 /* Number of supplementary groups */
1787 int ngids;
1789 /* log UIDs */
1790 #ifdef HAVE_GETRESUID
1791 if (getresuid(&ruid, &euid, &suid) != 0 ) {
1792 log_warn(LD_GENERAL, "Error getting changed UIDs: %s", strerror(errno));
1793 return -1;
1794 } else {
1795 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
1796 "UID is %u (real), %u (effective), %u (saved)",
1797 (unsigned)ruid, (unsigned)euid, (unsigned)suid);
1799 #else
1800 /* getresuid is not present on MacOS X, so we can't get the saved (E)UID */
1801 ruid = getuid();
1802 euid = geteuid();
1803 (void)suid;
1805 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
1806 "UID is %u (real), %u (effective), unknown (saved)",
1807 (unsigned)ruid, (unsigned)euid);
1808 #endif
1810 /* log GIDs */
1811 #ifdef HAVE_GETRESGID
1812 if (getresgid(&rgid, &egid, &sgid) != 0 ) {
1813 log_warn(LD_GENERAL, "Error getting changed GIDs: %s", strerror(errno));
1814 return -1;
1815 } else {
1816 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
1817 "GID is %u (real), %u (effective), %u (saved)",
1818 (unsigned)rgid, (unsigned)egid, (unsigned)sgid);
1820 #else
1821 /* getresgid is not present on MacOS X, so we can't get the saved (E)GID */
1822 rgid = getgid();
1823 egid = getegid();
1824 (void)sgid;
1825 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
1826 "GID is %u (real), %u (effective), unknown (saved)",
1827 (unsigned)rgid, (unsigned)egid);
1828 #endif
1830 /* log supplementary groups */
1831 sup_gids_size = 64;
1832 sup_gids = tor_calloc(64, sizeof(gid_t));
1833 while ((ngids = getgroups(sup_gids_size, sup_gids)) < 0 &&
1834 errno == EINVAL &&
1835 sup_gids_size < NGROUPS_MAX) {
1836 sup_gids_size *= 2;
1837 sup_gids = tor_reallocarray(sup_gids, sizeof(gid_t), sup_gids_size);
1840 if (ngids < 0) {
1841 log_warn(LD_GENERAL, "Error getting supplementary GIDs: %s",
1842 strerror(errno));
1843 tor_free(sup_gids);
1844 return -1;
1845 } else {
1846 int i, retval = 0;
1847 char *s = NULL;
1848 smartlist_t *elts = smartlist_new();
1850 for (i = 0; i<ngids; i++) {
1851 smartlist_add_asprintf(elts, "%u", (unsigned)sup_gids[i]);
1854 s = smartlist_join_strings(elts, " ", 0, NULL);
1856 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL, "Supplementary groups are: %s",s);
1858 tor_free(s);
1859 SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
1860 smartlist_free(elts);
1861 tor_free(sup_gids);
1863 return retval;
1866 return 0;
1868 #endif
1870 #ifndef _WIN32
1871 /** Cached struct from the last getpwname() call we did successfully. */
1872 static struct passwd *passwd_cached = NULL;
1874 /** Helper: copy a struct passwd object.
1876 * We only copy the fields pw_uid, pw_gid, pw_name, pw_dir. Tor doesn't use
1877 * any others, and I don't want to run into incompatibilities.
1879 static struct passwd *
1880 tor_passwd_dup(const struct passwd *pw)
1882 struct passwd *new_pw = tor_malloc_zero(sizeof(struct passwd));
1883 if (pw->pw_name)
1884 new_pw->pw_name = tor_strdup(pw->pw_name);
1885 if (pw->pw_dir)
1886 new_pw->pw_dir = tor_strdup(pw->pw_dir);
1887 new_pw->pw_uid = pw->pw_uid;
1888 new_pw->pw_gid = pw->pw_gid;
1890 return new_pw;
1893 /** Helper: free one of our cached 'struct passwd' values. */
1894 static void
1895 tor_passwd_free(struct passwd *pw)
1897 if (!pw)
1898 return;
1900 tor_free(pw->pw_name);
1901 tor_free(pw->pw_dir);
1902 tor_free(pw);
1905 /** Wrapper around getpwnam() that caches result. Used so that we don't need
1906 * to give the sandbox access to /etc/passwd.
1908 * The following fields alone will definitely be copied in the output: pw_uid,
1909 * pw_gid, pw_name, pw_dir. Other fields are not present in cached values.
1911 * When called with a NULL argument, this function clears storage associated
1912 * with static variables it uses.
1914 const struct passwd *
1915 tor_getpwnam(const char *username)
1917 struct passwd *pw;
1919 if (username == NULL) {
1920 tor_passwd_free(passwd_cached);
1921 passwd_cached = NULL;
1922 return NULL;
1925 if ((pw = getpwnam(username))) {
1926 tor_passwd_free(passwd_cached);
1927 passwd_cached = tor_passwd_dup(pw);
1928 log_info(LD_GENERAL, "Caching new entry %s for %s",
1929 passwd_cached->pw_name, username);
1930 return pw;
1933 /* Lookup failed */
1934 if (! passwd_cached || ! passwd_cached->pw_name)
1935 return NULL;
1937 if (! strcmp(username, passwd_cached->pw_name))
1938 return passwd_cached; // LCOV_EXCL_LINE - would need to make getpwnam flaky
1940 return NULL;
1943 /** Wrapper around getpwnam() that can use cached result from
1944 * tor_getpwnam(). Used so that we don't need to give the sandbox access to
1945 * /etc/passwd.
1947 * The following fields alone will definitely be copied in the output: pw_uid,
1948 * pw_gid, pw_name, pw_dir. Other fields are not present in cached values.
1950 const struct passwd *
1951 tor_getpwuid(uid_t uid)
1953 struct passwd *pw;
1955 if ((pw = getpwuid(uid))) {
1956 return pw;
1959 /* Lookup failed */
1960 if (! passwd_cached)
1961 return NULL;
1963 if (uid == passwd_cached->pw_uid)
1964 return passwd_cached; // LCOV_EXCL_LINE - would need to make getpwnam flaky
1966 return NULL;
1968 #endif
1970 /** Return true iff we were compiled with capability support, and capabilities
1971 * seem to work. **/
1973 have_capability_support(void)
1975 #ifdef HAVE_LINUX_CAPABILITIES
1976 cap_t caps = cap_get_proc();
1977 if (caps == NULL)
1978 return 0;
1979 cap_free(caps);
1980 return 1;
1981 #else
1982 return 0;
1983 #endif
1986 #ifdef HAVE_LINUX_CAPABILITIES
1987 /** Helper. Drop all capabilities but a small set, and set PR_KEEPCAPS as
1988 * appropriate.
1990 * If pre_setuid, retain only CAP_NET_BIND_SERVICE, CAP_SETUID, and
1991 * CAP_SETGID, and use PR_KEEPCAPS to ensure that capabilities persist across
1992 * setuid().
1994 * If not pre_setuid, retain only CAP_NET_BIND_SERVICE, and disable
1995 * PR_KEEPCAPS.
1997 * Return 0 on success, and -1 on failure.
1999 static int
2000 drop_capabilities(int pre_setuid)
2002 /* We keep these three capabilities, and these only, as we setuid.
2003 * After we setuid, we drop all but the first. */
2004 const cap_value_t caplist[] = {
2005 CAP_NET_BIND_SERVICE, CAP_SETUID, CAP_SETGID
2007 const char *where = pre_setuid ? "pre-setuid" : "post-setuid";
2008 const int n_effective = pre_setuid ? 3 : 1;
2009 const int n_permitted = pre_setuid ? 3 : 1;
2010 const int n_inheritable = 1;
2011 const int keepcaps = pre_setuid ? 1 : 0;
2013 /* Sets whether we keep capabilities across a setuid. */
2014 if (prctl(PR_SET_KEEPCAPS, keepcaps) < 0) {
2015 log_warn(LD_CONFIG, "Unable to call prctl() %s: %s",
2016 where, strerror(errno));
2017 return -1;
2020 cap_t caps = cap_get_proc();
2021 if (!caps) {
2022 log_warn(LD_CONFIG, "Unable to call cap_get_proc() %s: %s",
2023 where, strerror(errno));
2024 return -1;
2026 cap_clear(caps);
2028 cap_set_flag(caps, CAP_EFFECTIVE, n_effective, caplist, CAP_SET);
2029 cap_set_flag(caps, CAP_PERMITTED, n_permitted, caplist, CAP_SET);
2030 cap_set_flag(caps, CAP_INHERITABLE, n_inheritable, caplist, CAP_SET);
2032 int r = cap_set_proc(caps);
2033 cap_free(caps);
2034 if (r < 0) {
2035 log_warn(LD_CONFIG, "No permission to set capabilities %s: %s",
2036 where, strerror(errno));
2037 return -1;
2040 return 0;
2042 #endif
2044 /** Call setuid and setgid to run as <b>user</b> and switch to their
2045 * primary group. Return 0 on success. On failure, log and return -1.
2047 * If SWITCH_ID_KEEP_BINDLOW is set in 'flags', try to use the capability
2048 * system to retain the abilitity to bind low ports.
2050 * If SWITCH_ID_WARN_IF_NO_CAPS is set in flags, also warn if we have
2051 * don't have capability support.
2054 switch_id(const char *user, const unsigned flags)
2056 #ifndef _WIN32
2057 const struct passwd *pw = NULL;
2058 uid_t old_uid;
2059 gid_t old_gid;
2060 static int have_already_switched_id = 0;
2061 const int keep_bindlow = !!(flags & SWITCH_ID_KEEP_BINDLOW);
2062 const int warn_if_no_caps = !!(flags & SWITCH_ID_WARN_IF_NO_CAPS);
2064 tor_assert(user);
2066 if (have_already_switched_id)
2067 return 0;
2069 /* Log the initial credential state */
2070 if (log_credential_status())
2071 return -1;
2073 log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL, "Changing user and groups");
2075 /* Get old UID/GID to check if we changed correctly */
2076 old_uid = getuid();
2077 old_gid = getgid();
2079 /* Lookup the user and group information, if we have a problem, bail out. */
2080 pw = tor_getpwnam(user);
2081 if (pw == NULL) {
2082 log_warn(LD_CONFIG, "Error setting configured user: %s not found", user);
2083 return -1;
2086 #ifdef HAVE_LINUX_CAPABILITIES
2087 (void) warn_if_no_caps;
2088 if (keep_bindlow) {
2089 if (drop_capabilities(1))
2090 return -1;
2092 #else
2093 (void) keep_bindlow;
2094 if (warn_if_no_caps) {
2095 log_warn(LD_CONFIG, "KeepBindCapabilities set, but no capability support "
2096 "on this system.");
2098 #endif
2100 /* Properly switch egid,gid,euid,uid here or bail out */
2101 if (setgroups(1, &pw->pw_gid)) {
2102 log_warn(LD_GENERAL, "Error setting groups to gid %d: \"%s\".",
2103 (int)pw->pw_gid, strerror(errno));
2104 if (old_uid == pw->pw_uid) {
2105 log_warn(LD_GENERAL, "Tor is already running as %s. You do not need "
2106 "the \"User\" option if you are already running as the user "
2107 "you want to be. (If you did not set the User option in your "
2108 "torrc, check whether it was specified on the command line "
2109 "by a startup script.)", user);
2110 } else {
2111 log_warn(LD_GENERAL, "If you set the \"User\" option, you must start Tor"
2112 " as root.");
2114 return -1;
2117 if (setegid(pw->pw_gid)) {
2118 log_warn(LD_GENERAL, "Error setting egid to %d: %s",
2119 (int)pw->pw_gid, strerror(errno));
2120 return -1;
2123 if (setgid(pw->pw_gid)) {
2124 log_warn(LD_GENERAL, "Error setting gid to %d: %s",
2125 (int)pw->pw_gid, strerror(errno));
2126 return -1;
2129 if (setuid(pw->pw_uid)) {
2130 log_warn(LD_GENERAL, "Error setting configured uid to %s (%d): %s",
2131 user, (int)pw->pw_uid, strerror(errno));
2132 return -1;
2135 if (seteuid(pw->pw_uid)) {
2136 log_warn(LD_GENERAL, "Error setting configured euid to %s (%d): %s",
2137 user, (int)pw->pw_uid, strerror(errno));
2138 return -1;
2141 /* This is how OpenBSD rolls:
2142 if (setgroups(1, &pw->pw_gid) || setegid(pw->pw_gid) ||
2143 setgid(pw->pw_gid) || setuid(pw->pw_uid) || seteuid(pw->pw_uid)) {
2144 setgid(pw->pw_gid) || seteuid(pw->pw_uid) || setuid(pw->pw_uid)) {
2145 log_warn(LD_GENERAL, "Error setting configured UID/GID: %s",
2146 strerror(errno));
2147 return -1;
2151 /* We've properly switched egid, gid, euid, uid, and supplementary groups if
2152 * we're here. */
2153 #ifdef HAVE_LINUX_CAPABILITIES
2154 if (keep_bindlow) {
2155 if (drop_capabilities(0))
2156 return -1;
2158 #endif
2160 #if !defined(CYGWIN) && !defined(__CYGWIN__)
2161 /* If we tried to drop privilege to a group/user other than root, attempt to
2162 * restore root (E)(U|G)ID, and abort if the operation succeeds */
2164 /* Only check for privilege dropping if we were asked to be non-root */
2165 if (pw->pw_uid) {
2166 /* Try changing GID/EGID */
2167 if (pw->pw_gid != old_gid &&
2168 (setgid(old_gid) != -1 || setegid(old_gid) != -1)) {
2169 log_warn(LD_GENERAL, "Was able to restore group credentials even after "
2170 "switching GID: this means that the setgid code didn't work.");
2171 return -1;
2174 /* Try changing UID/EUID */
2175 if (pw->pw_uid != old_uid &&
2176 (setuid(old_uid) != -1 || seteuid(old_uid) != -1)) {
2177 log_warn(LD_GENERAL, "Was able to restore user credentials even after "
2178 "switching UID: this means that the setuid code didn't work.");
2179 return -1;
2182 #endif
2184 /* Check what really happened */
2185 if (log_credential_status()) {
2186 return -1;
2189 have_already_switched_id = 1; /* mark success so we never try again */
2191 #if defined(__linux__) && defined(HAVE_SYS_PRCTL_H) && defined(HAVE_PRCTL)
2192 #ifdef PR_SET_DUMPABLE
2193 if (pw->pw_uid) {
2194 /* Re-enable core dumps if we're not running as root. */
2195 log_info(LD_CONFIG, "Re-enabling coredumps");
2196 if (prctl(PR_SET_DUMPABLE, 1)) {
2197 log_warn(LD_CONFIG, "Unable to re-enable coredumps: %s",strerror(errno));
2200 #endif
2201 #endif
2202 return 0;
2204 #else
2205 (void)user;
2206 (void)flags;
2208 log_warn(LD_CONFIG, "Switching users is unsupported on your OS.");
2209 return -1;
2210 #endif
2213 /* We only use the linux prctl for now. There is no Win32 support; this may
2214 * also work on various BSD systems and Mac OS X - send testing feedback!
2216 * On recent Gnu/Linux kernels it is possible to create a system-wide policy
2217 * that will prevent non-root processes from attaching to other processes
2218 * unless they are the parent process; thus gdb can attach to programs that
2219 * they execute but they cannot attach to other processes running as the same
2220 * user. The system wide policy may be set with the sysctl
2221 * kernel.yama.ptrace_scope or by inspecting
2222 * /proc/sys/kernel/yama/ptrace_scope and it is 1 by default on Ubuntu 11.04.
2224 * This ptrace scope will be ignored on Gnu/Linux for users with
2225 * CAP_SYS_PTRACE and so it is very likely that root will still be able to
2226 * attach to the Tor process.
2228 /** Attempt to disable debugger attachment: return 1 on success, -1 on
2229 * failure, and 0 if we don't know how to try on this platform. */
2231 tor_disable_debugger_attach(void)
2233 int r, attempted;
2234 r = -1;
2235 attempted = 0;
2236 log_debug(LD_CONFIG,
2237 "Attemping to disable debugger attachment to Tor for "
2238 "unprivileged users.");
2239 #if defined(__linux__) && defined(HAVE_SYS_PRCTL_H) && defined(HAVE_PRCTL)
2240 #ifdef PR_SET_DUMPABLE
2241 attempted = 1;
2242 r = prctl(PR_SET_DUMPABLE, 0);
2243 #endif
2244 #endif
2245 #if defined(__APPLE__) && defined(PT_DENY_ATTACH)
2246 if (r < 0) {
2247 attempted = 1;
2248 r = ptrace(PT_DENY_ATTACH, 0, 0, 0);
2250 #endif
2252 // XXX: TODO - Mac OS X has dtrace and this may be disabled.
2253 // XXX: TODO - Windows probably has something similar
2254 if (r == 0 && attempted) {
2255 log_debug(LD_CONFIG,"Debugger attachment disabled for "
2256 "unprivileged users.");
2257 return 1;
2258 } else if (attempted) {
2259 log_warn(LD_CONFIG, "Unable to disable debugger attaching: %s",
2260 strerror(errno));
2262 return r;
2265 #ifdef HAVE_PWD_H
2266 /** Allocate and return a string containing the home directory for the
2267 * user <b>username</b>. Only works on posix-like systems. */
2268 char *
2269 get_user_homedir(const char *username)
2271 const struct passwd *pw;
2272 tor_assert(username);
2274 if (!(pw = tor_getpwnam(username))) {
2275 log_err(LD_CONFIG,"User \"%s\" not found.", username);
2276 return NULL;
2278 return tor_strdup(pw->pw_dir);
2280 #endif
2282 /** Modify <b>fname</b> to contain the name of its parent directory. Doesn't
2283 * actually examine the filesystem; does a purely syntactic modification.
2285 * The parent of the root director is considered to be iteself.
2287 * Path separators are the forward slash (/) everywhere and additionally
2288 * the backslash (\) on Win32.
2290 * Cuts off any number of trailing path separators but otherwise ignores
2291 * them for purposes of finding the parent directory.
2293 * Returns 0 if a parent directory was successfully found, -1 otherwise (fname
2294 * did not have any path separators or only had them at the end).
2295 * */
2297 get_parent_directory(char *fname)
2299 char *cp;
2300 int at_end = 1;
2301 tor_assert(fname);
2302 #ifdef _WIN32
2303 /* If we start with, say, c:, then don't consider that the start of the path
2305 if (fname[0] && fname[1] == ':') {
2306 fname += 2;
2308 #endif
2309 /* Now we want to remove all path-separators at the end of the string,
2310 * and to remove the end of the string starting with the path separator
2311 * before the last non-path-separator. In perl, this would be
2312 * s#[/]*$##; s#/[^/]*$##;
2313 * on a unixy platform.
2315 cp = fname + strlen(fname);
2316 at_end = 1;
2317 while (--cp >= fname) {
2318 int is_sep = (*cp == '/'
2319 #ifdef _WIN32
2320 || *cp == '\\'
2321 #endif
2323 if (is_sep) {
2324 if (cp == fname) {
2325 /* This is the first separator in the file name; don't remove it! */
2326 cp[1] = '\0';
2327 return 0;
2329 *cp = '\0';
2330 if (! at_end)
2331 return 0;
2332 } else {
2333 at_end = 0;
2336 return -1;
2339 #ifndef _WIN32
2340 /** Return a newly allocated string containing the output of getcwd(). Return
2341 * NULL on failure. (We can't just use getcwd() into a PATH_MAX buffer, since
2342 * Hurd hasn't got a PATH_MAX.)
2344 static char *
2345 alloc_getcwd(void)
2347 #ifdef PATH_MAX
2348 #define MAX_CWD PATH_MAX
2349 #else
2350 #define MAX_CWD 4096
2351 #endif
2353 char path_buf[MAX_CWD];
2354 char *path = getcwd(path_buf, sizeof(path_buf));
2355 return path ? tor_strdup(path) : NULL;
2357 #endif
2359 /** Expand possibly relative path <b>fname</b> to an absolute path.
2360 * Return a newly allocated string, possibly equal to <b>fname</b>. */
2361 char *
2362 make_path_absolute(char *fname)
2364 #ifdef _WIN32
2365 char *absfname_malloced = _fullpath(NULL, fname, 1);
2367 /* We don't want to assume that tor_free can free a string allocated
2368 * with malloc. On failure, return fname (it's better than nothing). */
2369 char *absfname = tor_strdup(absfname_malloced ? absfname_malloced : fname);
2370 if (absfname_malloced) raw_free(absfname_malloced);
2372 return absfname;
2373 #else
2374 char *absfname = NULL, *path = NULL;
2376 tor_assert(fname);
2378 if (fname[0] == '/') {
2379 absfname = tor_strdup(fname);
2380 } else {
2381 path = alloc_getcwd();
2382 if (path) {
2383 tor_asprintf(&absfname, "%s/%s", path, fname);
2384 tor_free(path);
2385 } else {
2386 /* LCOV_EXCL_START Can't make getcwd fail. */
2387 /* If getcwd failed, the best we can do here is keep using the
2388 * relative path. (Perhaps / isn't readable by this UID/GID.) */
2389 log_warn(LD_GENERAL, "Unable to find current working directory: %s",
2390 strerror(errno));
2391 absfname = tor_strdup(fname);
2392 /* LCOV_EXCL_STOP */
2395 return absfname;
2396 #endif
2399 #ifndef HAVE__NSGETENVIRON
2400 #ifndef HAVE_EXTERN_ENVIRON_DECLARED
2401 /* Some platforms declare environ under some circumstances, others don't. */
2402 #ifndef RUNNING_DOXYGEN
2403 extern char **environ;
2404 #endif
2405 #endif
2406 #endif
2408 /** Return the current environment. This is a portable replacement for
2409 * 'environ'. */
2410 char **
2411 get_environment(void)
2413 #ifdef HAVE__NSGETENVIRON
2414 /* This is for compatibility between OSX versions. Otherwise (for example)
2415 * when we do a mostly-static build on OSX 10.7, the resulting binary won't
2416 * work on OSX 10.6. */
2417 return *_NSGetEnviron();
2418 #else
2419 return environ;
2420 #endif
2423 /** Get name of current host and write it to <b>name</b> array, whose
2424 * length is specified by <b>namelen</b> argument. Return 0 upon
2425 * successfull completion; otherwise return return -1. (Currently,
2426 * this function is merely a mockable wrapper for POSIX gethostname().)
2428 MOCK_IMPL(int,
2429 tor_gethostname,(char *name, size_t namelen))
2431 return gethostname(name,namelen);
2434 /** Set *addr to the IP address (in dotted-quad notation) stored in *str.
2435 * Return 1 on success, 0 if *str is badly formatted.
2436 * (Like inet_aton(str,addr), but works on Windows and Solaris.)
2439 tor_inet_aton(const char *str, struct in_addr* addr)
2441 unsigned a,b,c,d;
2442 char more;
2443 if (tor_sscanf(str, "%3u.%3u.%3u.%3u%c", &a,&b,&c,&d,&more) != 4)
2444 return 0;
2445 if (a > 255) return 0;
2446 if (b > 255) return 0;
2447 if (c > 255) return 0;
2448 if (d > 255) return 0;
2449 addr->s_addr = htonl((a<<24) | (b<<16) | (c<<8) | d);
2450 return 1;
2453 /** Given <b>af</b>==AF_INET and <b>src</b> a struct in_addr, or
2454 * <b>af</b>==AF_INET6 and <b>src</b> a struct in6_addr, try to format the
2455 * address and store it in the <b>len</b>-byte buffer <b>dst</b>. Returns
2456 * <b>dst</b> on success, NULL on failure.
2458 * (Like inet_ntop(af,src,dst,len), but works on platforms that don't have it:
2459 * Tor sometimes needs to format ipv6 addresses even on platforms without ipv6
2460 * support.) */
2461 const char *
2462 tor_inet_ntop(int af, const void *src, char *dst, size_t len)
2464 if (af == AF_INET) {
2465 if (tor_inet_ntoa(src, dst, len) < 0)
2466 return NULL;
2467 else
2468 return dst;
2469 } else if (af == AF_INET6) {
2470 const struct in6_addr *addr = src;
2471 char buf[64], *cp;
2472 int longestGapLen = 0, longestGapPos = -1, i,
2473 curGapPos = -1, curGapLen = 0;
2474 uint16_t words[8];
2475 for (i = 0; i < 8; ++i) {
2476 words[i] = (((uint16_t)addr->s6_addr[2*i])<<8) + addr->s6_addr[2*i+1];
2478 if (words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0 &&
2479 words[4] == 0 && ((words[5] == 0 && words[6] && words[7]) ||
2480 (words[5] == 0xffff))) {
2481 /* This is an IPv4 address. */
2482 if (words[5] == 0) {
2483 tor_snprintf(buf, sizeof(buf), "::%d.%d.%d.%d",
2484 addr->s6_addr[12], addr->s6_addr[13],
2485 addr->s6_addr[14], addr->s6_addr[15]);
2486 } else {
2487 tor_snprintf(buf, sizeof(buf), "::%x:%d.%d.%d.%d", words[5],
2488 addr->s6_addr[12], addr->s6_addr[13],
2489 addr->s6_addr[14], addr->s6_addr[15]);
2491 if ((strlen(buf) + 1) > len) /* +1 for \0 */
2492 return NULL;
2493 strlcpy(dst, buf, len);
2494 return dst;
2496 i = 0;
2497 while (i < 8) {
2498 if (words[i] == 0) {
2499 curGapPos = i++;
2500 curGapLen = 1;
2501 while (i<8 && words[i] == 0) {
2502 ++i; ++curGapLen;
2504 if (curGapLen > longestGapLen) {
2505 longestGapPos = curGapPos;
2506 longestGapLen = curGapLen;
2508 } else {
2509 ++i;
2512 if (longestGapLen<=1)
2513 longestGapPos = -1;
2515 cp = buf;
2516 for (i = 0; i < 8; ++i) {
2517 if (words[i] == 0 && longestGapPos == i) {
2518 if (i == 0)
2519 *cp++ = ':';
2520 *cp++ = ':';
2521 while (i < 8 && words[i] == 0)
2522 ++i;
2523 --i; /* to compensate for loop increment. */
2524 } else {
2525 tor_snprintf(cp, sizeof(buf)-(cp-buf), "%x", (unsigned)words[i]);
2526 cp += strlen(cp);
2527 if (i != 7)
2528 *cp++ = ':';
2531 *cp = '\0';
2532 if ((strlen(buf) + 1) > len) /* +1 for \0 */
2533 return NULL;
2534 strlcpy(dst, buf, len);
2535 return dst;
2536 } else {
2537 return NULL;
2541 /** Given <b>af</b>==AF_INET or <b>af</b>==AF_INET6, and a string <b>src</b>
2542 * encoding an IPv4 address or IPv6 address correspondingly, try to parse the
2543 * address and store the result in <b>dst</b> (which must have space for a
2544 * struct in_addr or a struct in6_addr, as appropriate). Return 1 on success,
2545 * 0 on a bad parse, and -1 on a bad <b>af</b>.
2547 * (Like inet_pton(af,src,dst) but works on platforms that don't have it: Tor
2548 * sometimes needs to format ipv6 addresses even on platforms without ipv6
2549 * support.) */
2551 tor_inet_pton(int af, const char *src, void *dst)
2553 if (af == AF_INET) {
2554 return tor_inet_aton(src, dst);
2555 } else if (af == AF_INET6) {
2556 struct in6_addr *out = dst;
2557 uint16_t words[8];
2558 int gapPos = -1, i, setWords=0;
2559 const char *dot = strchr(src, '.');
2560 const char *eow; /* end of words. */
2561 if (dot == src)
2562 return 0;
2563 else if (!dot)
2564 eow = src+strlen(src);
2565 else {
2566 unsigned byte1,byte2,byte3,byte4;
2567 char more;
2568 for (eow = dot-1; eow > src && TOR_ISDIGIT(*eow); --eow)
2570 if (*eow != ':')
2571 return 0;
2572 ++eow;
2574 /* We use "scanf" because some platform inet_aton()s are too lax
2575 * about IPv4 addresses of the form "1.2.3" */
2576 if (tor_sscanf(eow, "%3u.%3u.%3u.%3u%c",
2577 &byte1,&byte2,&byte3,&byte4,&more) != 4)
2578 return 0;
2580 if (byte1 > 255 || byte2 > 255 || byte3 > 255 || byte4 > 255)
2581 return 0;
2583 words[6] = (byte1<<8) | byte2;
2584 words[7] = (byte3<<8) | byte4;
2585 setWords += 2;
2588 i = 0;
2589 while (src < eow) {
2590 if (i > 7)
2591 return 0;
2592 if (TOR_ISXDIGIT(*src)) {
2593 char *next;
2594 ssize_t len;
2595 long r = strtol(src, &next, 16);
2596 tor_assert(next != NULL);
2597 tor_assert(next != src);
2599 len = *next == '\0' ? eow - src : next - src;
2600 if (len > 4)
2601 return 0;
2602 if (len > 1 && !TOR_ISXDIGIT(src[1]))
2603 return 0; /* 0x is not valid */
2605 tor_assert(r >= 0);
2606 tor_assert(r < 65536);
2607 words[i++] = (uint16_t)r;
2608 setWords++;
2609 src = next;
2610 if (*src != ':' && src != eow)
2611 return 0;
2612 ++src;
2613 } else if (*src == ':' && i > 0 && gapPos == -1) {
2614 gapPos = i;
2615 ++src;
2616 } else if (*src == ':' && i == 0 && src+1 < eow && src[1] == ':' &&
2617 gapPos == -1) {
2618 gapPos = i;
2619 src += 2;
2620 } else {
2621 return 0;
2625 if (setWords > 8 ||
2626 (setWords == 8 && gapPos != -1) ||
2627 (setWords < 8 && gapPos == -1))
2628 return 0;
2630 if (gapPos >= 0) {
2631 int nToMove = setWords - (dot ? 2 : 0) - gapPos;
2632 int gapLen = 8 - setWords;
2633 tor_assert(nToMove >= 0);
2634 memmove(&words[gapPos+gapLen], &words[gapPos],
2635 sizeof(uint16_t)*nToMove);
2636 memset(&words[gapPos], 0, sizeof(uint16_t)*gapLen);
2638 for (i = 0; i < 8; ++i) {
2639 out->s6_addr[2*i ] = words[i] >> 8;
2640 out->s6_addr[2*i+1] = words[i] & 0xff;
2643 return 1;
2644 } else {
2645 return -1;
2649 /** Similar behavior to Unix gethostbyname: resolve <b>name</b>, and set
2650 * *<b>addr</b> to the proper IP address, in host byte order. Returns 0
2651 * on success, -1 on failure; 1 on transient failure.
2653 * (This function exists because standard windows gethostbyname
2654 * doesn't treat raw IP addresses properly.)
2657 MOCK_IMPL(int,
2658 tor_lookup_hostname,(const char *name, uint32_t *addr))
2660 tor_addr_t myaddr;
2661 int ret;
2663 if ((ret = tor_addr_lookup(name, AF_INET, &myaddr)))
2664 return ret;
2666 if (tor_addr_family(&myaddr) == AF_INET) {
2667 *addr = tor_addr_to_ipv4h(&myaddr);
2668 return ret;
2671 return -1;
2674 /** Hold the result of our call to <b>uname</b>. */
2675 static char uname_result[256];
2676 /** True iff uname_result is set. */
2677 static int uname_result_is_set = 0;
2679 /** Return a pointer to a description of our platform.
2681 MOCK_IMPL(const char *, get_uname, (void))
2683 #ifdef HAVE_UNAME
2684 struct utsname u;
2685 #endif
2686 if (!uname_result_is_set) {
2687 #ifdef HAVE_UNAME
2688 if (uname(&u) != -1) {
2689 /* (Linux says 0 is success, Solaris says 1 is success) */
2690 strlcpy(uname_result, u.sysname, sizeof(uname_result));
2691 } else
2692 #endif
2694 #ifdef _WIN32
2695 OSVERSIONINFOEX info;
2696 int i;
2697 const char *plat = NULL;
2698 static struct {
2699 unsigned major; unsigned minor; const char *version;
2700 } win_version_table[] = {
2701 { 6, 2, "Windows 8" },
2702 { 6, 1, "Windows 7" },
2703 { 6, 0, "Windows Vista" },
2704 { 5, 2, "Windows Server 2003" },
2705 { 5, 1, "Windows XP" },
2706 { 5, 0, "Windows 2000" },
2707 /* { 4, 0, "Windows NT 4.0" }, */
2708 { 4, 90, "Windows Me" },
2709 { 4, 10, "Windows 98" },
2710 /* { 4, 0, "Windows 95" } */
2711 { 3, 51, "Windows NT 3.51" },
2712 { 0, 0, NULL }
2714 memset(&info, 0, sizeof(info));
2715 info.dwOSVersionInfoSize = sizeof(info);
2716 if (! GetVersionEx((LPOSVERSIONINFO)&info)) {
2717 strlcpy(uname_result, "Bizarre version of Windows where GetVersionEx"
2718 " doesn't work.", sizeof(uname_result));
2719 uname_result_is_set = 1;
2720 return uname_result;
2722 if (info.dwMajorVersion == 4 && info.dwMinorVersion == 0) {
2723 if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
2724 plat = "Windows NT 4.0";
2725 else
2726 plat = "Windows 95";
2727 } else {
2728 for (i=0; win_version_table[i].major>0; ++i) {
2729 if (win_version_table[i].major == info.dwMajorVersion &&
2730 win_version_table[i].minor == info.dwMinorVersion) {
2731 plat = win_version_table[i].version;
2732 break;
2736 if (plat) {
2737 strlcpy(uname_result, plat, sizeof(uname_result));
2738 } else {
2739 if (info.dwMajorVersion > 6 ||
2740 (info.dwMajorVersion==6 && info.dwMinorVersion>2))
2741 tor_snprintf(uname_result, sizeof(uname_result),
2742 "Very recent version of Windows [major=%d,minor=%d]",
2743 (int)info.dwMajorVersion,(int)info.dwMinorVersion);
2744 else
2745 tor_snprintf(uname_result, sizeof(uname_result),
2746 "Unrecognized version of Windows [major=%d,minor=%d]",
2747 (int)info.dwMajorVersion,(int)info.dwMinorVersion);
2749 #ifdef VER_NT_SERVER
2750 if (info.wProductType == VER_NT_SERVER ||
2751 info.wProductType == VER_NT_DOMAIN_CONTROLLER) {
2752 strlcat(uname_result, " [server]", sizeof(uname_result));
2754 #endif
2755 #else
2756 /* LCOV_EXCL_START -- can't provoke uname failure */
2757 strlcpy(uname_result, "Unknown platform", sizeof(uname_result));
2758 /* LCOV_EXCL_STOP */
2759 #endif
2761 uname_result_is_set = 1;
2763 return uname_result;
2767 * Process control
2770 /** Implementation logic for compute_num_cpus(). */
2771 static int
2772 compute_num_cpus_impl(void)
2774 #ifdef _WIN32
2775 SYSTEM_INFO info;
2776 memset(&info, 0, sizeof(info));
2777 GetSystemInfo(&info);
2778 if (info.dwNumberOfProcessors >= 1 && info.dwNumberOfProcessors < INT_MAX)
2779 return (int)info.dwNumberOfProcessors;
2780 else
2781 return -1;
2782 #elif defined(HAVE_SYSCONF)
2783 #ifdef _SC_NPROCESSORS_CONF
2784 long cpus_conf = sysconf(_SC_NPROCESSORS_CONF);
2785 #else
2786 long cpus_conf = -1;
2787 #endif
2788 #ifdef _SC_NPROCESSORS_ONLN
2789 long cpus_onln = sysconf(_SC_NPROCESSORS_ONLN);
2790 #else
2791 long cpus_onln = -1;
2792 #endif
2793 long cpus = -1;
2795 if (cpus_conf > 0 && cpus_onln < 0) {
2796 cpus = cpus_conf;
2797 } else if (cpus_onln > 0 && cpus_conf < 0) {
2798 cpus = cpus_onln;
2799 } else if (cpus_onln > 0 && cpus_conf > 0) {
2800 if (cpus_onln < cpus_conf) {
2801 log_notice(LD_GENERAL, "I think we have %ld CPUS, but only %ld of them "
2802 "are available. Telling Tor to only use %ld. You can over"
2803 "ride this with the NumCPUs option",
2804 cpus_conf, cpus_onln, cpus_onln);
2806 cpus = cpus_onln;
2809 if (cpus >= 1 && cpus < INT_MAX)
2810 return (int)cpus;
2811 else
2812 return -1;
2813 #else
2814 return -1;
2815 #endif
2818 #define MAX_DETECTABLE_CPUS 16
2820 /** Return how many CPUs we are running with. We assume that nobody is
2821 * using hot-swappable CPUs, so we don't recompute this after the first
2822 * time. Return -1 if we don't know how to tell the number of CPUs on this
2823 * system.
2826 compute_num_cpus(void)
2828 static int num_cpus = -2;
2829 if (num_cpus == -2) {
2830 num_cpus = compute_num_cpus_impl();
2831 tor_assert(num_cpus != -2);
2832 if (num_cpus > MAX_DETECTABLE_CPUS) {
2833 /* LCOV_EXCL_START */
2834 log_notice(LD_GENERAL, "Wow! I detected that you have %d CPUs. I "
2835 "will not autodetect any more than %d, though. If you "
2836 "want to configure more, set NumCPUs in your torrc",
2837 num_cpus, MAX_DETECTABLE_CPUS);
2838 num_cpus = MAX_DETECTABLE_CPUS;
2839 /* LCOV_EXCL_STOP */
2842 return num_cpus;
2845 #if !defined(_WIN32)
2846 /** Defined iff we need to add locks when defining fake versions of reentrant
2847 * versions of time-related functions. */
2848 #define TIME_FNS_NEED_LOCKS
2849 #endif
2851 /** Helper: Deal with confused or out-of-bounds values from localtime_r and
2852 * friends. (On some platforms, they can give out-of-bounds values or can
2853 * return NULL.) If <b>islocal</b>, this is a localtime result; otherwise
2854 * it's from gmtime. The function returned <b>r</b>, when given <b>timep</b>
2855 * as its input. If we need to store new results, store them in
2856 * <b>resultbuf</b>. */
2857 static struct tm *
2858 correct_tm(int islocal, const time_t *timep, struct tm *resultbuf,
2859 struct tm *r)
2861 const char *outcome;
2863 if (PREDICT_LIKELY(r)) {
2864 /* We can't strftime dates after 9999 CE, and we want to avoid dates
2865 * before 1 CE (avoiding the year 0 issue and negative years). */
2866 if (r->tm_year > 8099) {
2867 r->tm_year = 8099;
2868 r->tm_mon = 11;
2869 r->tm_mday = 31;
2870 r->tm_yday = 364;
2871 r->tm_wday = 6;
2872 r->tm_hour = 23;
2873 r->tm_min = 59;
2874 r->tm_sec = 59;
2875 } else if (r->tm_year < (1-1900)) {
2876 r->tm_year = (1-1900);
2877 r->tm_mon = 0;
2878 r->tm_mday = 1;
2879 r->tm_yday = 0;
2880 r->tm_wday = 0;
2881 r->tm_hour = 0;
2882 r->tm_min = 0;
2883 r->tm_sec = 0;
2885 return r;
2888 /* If we get here, gmtime or localtime returned NULL. It might have done
2889 * this because of overrun or underrun, or it might have done it because of
2890 * some other weird issue. */
2891 if (timep) {
2892 if (*timep < 0) {
2893 r = resultbuf;
2894 r->tm_year = 70; /* 1970 CE */
2895 r->tm_mon = 0;
2896 r->tm_mday = 1;
2897 r->tm_yday = 0;
2898 r->tm_wday = 0;
2899 r->tm_hour = 0;
2900 r->tm_min = 0 ;
2901 r->tm_sec = 0;
2902 outcome = "Rounding up to 1970";
2903 goto done;
2904 } else if (*timep >= INT32_MAX) {
2905 /* Rounding down to INT32_MAX isn't so great, but keep in mind that we
2906 * only do it if gmtime/localtime tells us NULL. */
2907 r = resultbuf;
2908 r->tm_year = 137; /* 2037 CE */
2909 r->tm_mon = 11;
2910 r->tm_mday = 31;
2911 r->tm_yday = 364;
2912 r->tm_wday = 6;
2913 r->tm_hour = 23;
2914 r->tm_min = 59;
2915 r->tm_sec = 59;
2916 outcome = "Rounding down to 2037";
2917 goto done;
2921 /* If we get here, then gmtime/localtime failed without getting an extreme
2922 * value for *timep */
2923 /* LCOV_EXCL_START */
2924 tor_fragile_assert();
2925 r = resultbuf;
2926 memset(resultbuf, 0, sizeof(struct tm));
2927 outcome="can't recover";
2928 /* LCOV_EXCL_STOP */
2929 done:
2930 log_warn(LD_BUG, "%s("I64_FORMAT") failed with error %s: %s",
2931 islocal?"localtime":"gmtime",
2932 timep?I64_PRINTF_ARG(*timep):0,
2933 strerror(errno),
2934 outcome);
2935 return r;
2938 /** @{ */
2939 /** As localtime_r, but defined for platforms that don't have it:
2941 * Convert *<b>timep</b> to a struct tm in local time, and store the value in
2942 * *<b>result</b>. Return the result on success, or NULL on failure.
2944 #ifdef HAVE_LOCALTIME_R
2945 struct tm *
2946 tor_localtime_r(const time_t *timep, struct tm *result)
2948 struct tm *r;
2949 r = localtime_r(timep, result);
2950 return correct_tm(1, timep, result, r);
2952 #elif defined(TIME_FNS_NEED_LOCKS)
2953 struct tm *
2954 tor_localtime_r(const time_t *timep, struct tm *result)
2956 struct tm *r;
2957 static tor_mutex_t *m=NULL;
2958 if (!m) { m=tor_mutex_new(); }
2959 tor_assert(result);
2960 tor_mutex_acquire(m);
2961 r = localtime(timep);
2962 if (r)
2963 memcpy(result, r, sizeof(struct tm));
2964 tor_mutex_release(m);
2965 return correct_tm(1, timep, result, r);
2967 #else
2968 struct tm *
2969 tor_localtime_r(const time_t *timep, struct tm *result)
2971 struct tm *r;
2972 tor_assert(result);
2973 r = localtime(timep);
2974 if (r)
2975 memcpy(result, r, sizeof(struct tm));
2976 return correct_tm(1, timep, result, r);
2978 #endif
2979 /** @} */
2981 /** @{ */
2982 /** As gmtime_r, but defined for platforms that don't have it:
2984 * Convert *<b>timep</b> to a struct tm in UTC, and store the value in
2985 * *<b>result</b>. Return the result on success, or NULL on failure.
2987 #ifdef HAVE_GMTIME_R
2988 struct tm *
2989 tor_gmtime_r(const time_t *timep, struct tm *result)
2991 struct tm *r;
2992 r = gmtime_r(timep, result);
2993 return correct_tm(0, timep, result, r);
2995 #elif defined(TIME_FNS_NEED_LOCKS)
2996 struct tm *
2997 tor_gmtime_r(const time_t *timep, struct tm *result)
2999 struct tm *r;
3000 static tor_mutex_t *m=NULL;
3001 if (!m) { m=tor_mutex_new(); }
3002 tor_assert(result);
3003 tor_mutex_acquire(m);
3004 r = gmtime(timep);
3005 if (r)
3006 memcpy(result, r, sizeof(struct tm));
3007 tor_mutex_release(m);
3008 return correct_tm(0, timep, result, r);
3010 #else
3011 struct tm *
3012 tor_gmtime_r(const time_t *timep, struct tm *result)
3014 struct tm *r;
3015 tor_assert(result);
3016 r = gmtime(timep);
3017 if (r)
3018 memcpy(result, r, sizeof(struct tm));
3019 return correct_tm(0, timep, result, r);
3021 #endif
3023 #if defined(HAVE_MLOCKALL) && HAVE_DECL_MLOCKALL && defined(RLIMIT_MEMLOCK)
3024 /** Attempt to raise the current and max rlimit to infinity for our process.
3025 * This only needs to be done once and can probably only be done when we have
3026 * not already dropped privileges.
3028 static int
3029 tor_set_max_memlock(void)
3031 /* Future consideration for Windows is probably SetProcessWorkingSetSize
3032 * This is similar to setting the memory rlimit of RLIMIT_MEMLOCK
3033 * http://msdn.microsoft.com/en-us/library/ms686234(VS.85).aspx
3036 struct rlimit limit;
3038 /* RLIM_INFINITY is -1 on some platforms. */
3039 limit.rlim_cur = RLIM_INFINITY;
3040 limit.rlim_max = RLIM_INFINITY;
3042 if (setrlimit(RLIMIT_MEMLOCK, &limit) == -1) {
3043 if (errno == EPERM) {
3044 log_warn(LD_GENERAL, "You appear to lack permissions to change memory "
3045 "limits. Are you root?");
3047 log_warn(LD_GENERAL, "Unable to raise RLIMIT_MEMLOCK: %s",
3048 strerror(errno));
3049 return -1;
3052 return 0;
3054 #endif
3056 /** Attempt to lock all current and all future memory pages.
3057 * This should only be called once and while we're privileged.
3058 * Like mlockall() we return 0 when we're successful and -1 when we're not.
3059 * Unlike mlockall() we return 1 if we've already attempted to lock memory.
3062 tor_mlockall(void)
3064 static int memory_lock_attempted = 0;
3066 if (memory_lock_attempted) {
3067 return 1;
3070 memory_lock_attempted = 1;
3073 * Future consideration for Windows may be VirtualLock
3074 * VirtualLock appears to implement mlock() but not mlockall()
3076 * http://msdn.microsoft.com/en-us/library/aa366895(VS.85).aspx
3079 #if defined(HAVE_MLOCKALL) && HAVE_DECL_MLOCKALL && defined(RLIMIT_MEMLOCK)
3080 if (tor_set_max_memlock() == 0) {
3081 log_debug(LD_GENERAL, "RLIMIT_MEMLOCK is now set to RLIM_INFINITY.");
3084 if (mlockall(MCL_CURRENT|MCL_FUTURE) == 0) {
3085 log_info(LD_GENERAL, "Insecure OS paging is effectively disabled.");
3086 return 0;
3087 } else {
3088 if (errno == ENOSYS) {
3089 /* Apple - it's 2009! I'm looking at you. Grrr. */
3090 log_notice(LD_GENERAL, "It appears that mlockall() is not available on "
3091 "your platform.");
3092 } else if (errno == EPERM) {
3093 log_notice(LD_GENERAL, "It appears that you lack the permissions to "
3094 "lock memory. Are you root?");
3096 log_notice(LD_GENERAL, "Unable to lock all current and future memory "
3097 "pages: %s", strerror(errno));
3098 return -1;
3100 #else
3101 log_warn(LD_GENERAL, "Unable to lock memory pages. mlockall() unsupported?");
3102 return -1;
3103 #endif
3107 * On Windows, WSAEWOULDBLOCK is not always correct: when you see it,
3108 * you need to ask the socket for its actual errno. Also, you need to
3109 * get your errors from WSAGetLastError, not errno. (If you supply a
3110 * socket of -1, we check WSAGetLastError, but don't correct
3111 * WSAEWOULDBLOCKs.)
3113 * The upshot of all of this is that when a socket call fails, you
3114 * should call tor_socket_errno <em>at most once</em> on the failing
3115 * socket to get the error.
3117 #if defined(_WIN32)
3119 tor_socket_errno(tor_socket_t sock)
3121 int optval, optvallen=sizeof(optval);
3122 int err = WSAGetLastError();
3123 if (err == WSAEWOULDBLOCK && SOCKET_OK(sock)) {
3124 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval, &optvallen))
3125 return err;
3126 if (optval)
3127 return optval;
3129 return err;
3131 #endif
3133 #if defined(_WIN32)
3134 #define E(code, s) { code, (s " [" #code " ]") }
3135 struct { int code; const char *msg; } windows_socket_errors[] = {
3136 E(WSAEINTR, "Interrupted function call"),
3137 E(WSAEACCES, "Permission denied"),
3138 E(WSAEFAULT, "Bad address"),
3139 E(WSAEINVAL, "Invalid argument"),
3140 E(WSAEMFILE, "Too many open files"),
3141 E(WSAEWOULDBLOCK, "Resource temporarily unavailable"),
3142 E(WSAEINPROGRESS, "Operation now in progress"),
3143 E(WSAEALREADY, "Operation already in progress"),
3144 E(WSAENOTSOCK, "Socket operation on nonsocket"),
3145 E(WSAEDESTADDRREQ, "Destination address required"),
3146 E(WSAEMSGSIZE, "Message too long"),
3147 E(WSAEPROTOTYPE, "Protocol wrong for socket"),
3148 E(WSAENOPROTOOPT, "Bad protocol option"),
3149 E(WSAEPROTONOSUPPORT, "Protocol not supported"),
3150 E(WSAESOCKTNOSUPPORT, "Socket type not supported"),
3151 /* What's the difference between NOTSUPP and NOSUPPORT? :) */
3152 E(WSAEOPNOTSUPP, "Operation not supported"),
3153 E(WSAEPFNOSUPPORT, "Protocol family not supported"),
3154 E(WSAEAFNOSUPPORT, "Address family not supported by protocol family"),
3155 E(WSAEADDRINUSE, "Address already in use"),
3156 E(WSAEADDRNOTAVAIL, "Cannot assign requested address"),
3157 E(WSAENETDOWN, "Network is down"),
3158 E(WSAENETUNREACH, "Network is unreachable"),
3159 E(WSAENETRESET, "Network dropped connection on reset"),
3160 E(WSAECONNABORTED, "Software caused connection abort"),
3161 E(WSAECONNRESET, "Connection reset by peer"),
3162 E(WSAENOBUFS, "No buffer space available"),
3163 E(WSAEISCONN, "Socket is already connected"),
3164 E(WSAENOTCONN, "Socket is not connected"),
3165 E(WSAESHUTDOWN, "Cannot send after socket shutdown"),
3166 E(WSAETIMEDOUT, "Connection timed out"),
3167 E(WSAECONNREFUSED, "Connection refused"),
3168 E(WSAEHOSTDOWN, "Host is down"),
3169 E(WSAEHOSTUNREACH, "No route to host"),
3170 E(WSAEPROCLIM, "Too many processes"),
3171 /* Yes, some of these start with WSA, not WSAE. No, I don't know why. */
3172 E(WSASYSNOTREADY, "Network subsystem is unavailable"),
3173 E(WSAVERNOTSUPPORTED, "Winsock.dll out of range"),
3174 E(WSANOTINITIALISED, "Successful WSAStartup not yet performed"),
3175 E(WSAEDISCON, "Graceful shutdown now in progress"),
3176 #ifdef WSATYPE_NOT_FOUND
3177 E(WSATYPE_NOT_FOUND, "Class type not found"),
3178 #endif
3179 E(WSAHOST_NOT_FOUND, "Host not found"),
3180 E(WSATRY_AGAIN, "Nonauthoritative host not found"),
3181 E(WSANO_RECOVERY, "This is a nonrecoverable error"),
3182 E(WSANO_DATA, "Valid name, no data record of requested type)"),
3184 /* There are some more error codes whose numeric values are marked
3185 * <b>OS dependent</b>. They start with WSA_, apparently for the same
3186 * reason that practitioners of some craft traditions deliberately
3187 * introduce imperfections into their baskets and rugs "to allow the
3188 * evil spirits to escape." If we catch them, then our binaries
3189 * might not report consistent results across versions of Windows.
3190 * Thus, I'm going to let them all fall through.
3192 { -1, NULL },
3194 /** There does not seem to be a strerror equivalent for Winsock errors.
3195 * Naturally, we have to roll our own.
3197 const char *
3198 tor_socket_strerror(int e)
3200 int i;
3201 for (i=0; windows_socket_errors[i].code >= 0; ++i) {
3202 if (e == windows_socket_errors[i].code)
3203 return windows_socket_errors[i].msg;
3205 return strerror(e);
3207 #endif
3209 /** Called before we make any calls to network-related functions.
3210 * (Some operating systems require their network libraries to be
3211 * initialized.) */
3213 network_init(void)
3215 #ifdef _WIN32
3216 /* This silly exercise is necessary before windows will allow
3217 * gethostbyname to work. */
3218 WSADATA WSAData;
3219 int r;
3220 r = WSAStartup(0x101,&WSAData);
3221 if (r) {
3222 log_warn(LD_NET,"Error initializing windows network layer: code was %d",r);
3223 return -1;
3225 if (sizeof(SOCKET) != sizeof(tor_socket_t)) {
3226 log_warn(LD_BUG,"The tor_socket_t type does not match SOCKET in size; Tor "
3227 "might not work. (Sizes are %d and %d respectively.)",
3228 (int)sizeof(tor_socket_t), (int)sizeof(SOCKET));
3230 /* WSAData.iMaxSockets might show the max sockets we're allowed to use.
3231 * We might use it to complain if we're trying to be a server but have
3232 * too few sockets available. */
3233 #endif
3234 return 0;
3237 #ifdef _WIN32
3238 /** Return a newly allocated string describing the windows system error code
3239 * <b>err</b>. Note that error codes are different from errno. Error codes
3240 * come from GetLastError() when a winapi call fails. errno is set only when
3241 * ANSI functions fail. Whee. */
3242 char *
3243 format_win32_error(DWORD err)
3245 TCHAR *str = NULL;
3246 char *result;
3247 DWORD n;
3249 /* Somebody once decided that this interface was better than strerror(). */
3250 n = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
3251 FORMAT_MESSAGE_FROM_SYSTEM |
3252 FORMAT_MESSAGE_IGNORE_INSERTS,
3253 NULL, err,
3254 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
3255 (LPVOID)&str,
3256 0, NULL);
3258 if (str && n) {
3259 #ifdef UNICODE
3260 size_t len;
3261 if (n > 128*1024)
3262 len = (128 * 1024) * 2 + 1; /* This shouldn't be possible, but let's
3263 * make sure. */
3264 else
3265 len = n * 2 + 1;
3266 result = tor_malloc(len);
3267 wcstombs(result,str,len);
3268 result[len-1] = '\0';
3269 #else
3270 result = tor_strdup(str);
3271 #endif
3272 } else {
3273 result = tor_strdup("<unformattable error>");
3275 if (str) {
3276 LocalFree(str); /* LocalFree != free() */
3278 return result;
3280 #endif
3282 #if defined(HW_PHYSMEM64)
3283 /* This appears to be an OpenBSD thing */
3284 #define INT64_HW_MEM HW_PHYSMEM64
3285 #elif defined(HW_MEMSIZE)
3286 /* OSX defines this one */
3287 #define INT64_HW_MEM HW_MEMSIZE
3288 #endif
3291 * Helper: try to detect the total system memory, and return it. On failure,
3292 * return 0.
3294 static uint64_t
3295 get_total_system_memory_impl(void)
3297 #if defined(__linux__)
3298 /* On linux, sysctl is deprecated. Because proc is so awesome that you
3299 * shouldn't _want_ to write portable code, I guess? */
3300 unsigned long long result=0;
3301 int fd = -1;
3302 char *s = NULL;
3303 const char *cp;
3304 size_t file_size=0;
3305 if (-1 == (fd = tor_open_cloexec("/proc/meminfo",O_RDONLY,0)))
3306 return 0;
3307 s = read_file_to_str_until_eof(fd, 65536, &file_size);
3308 if (!s)
3309 goto err;
3310 cp = strstr(s, "MemTotal:");
3311 if (!cp)
3312 goto err;
3313 /* Use the system sscanf so that space will match a wider number of space */
3314 if (sscanf(cp, "MemTotal: %llu kB\n", &result) != 1)
3315 goto err;
3317 close(fd);
3318 tor_free(s);
3319 return result * 1024;
3321 err:
3322 /* LCOV_EXCL_START Can't reach this unless proc is broken. */
3323 tor_free(s);
3324 close(fd);
3325 return 0;
3326 /* LCOV_EXCL_STOP */
3327 #elif defined (_WIN32)
3328 /* Windows has MEMORYSTATUSEX; pretty straightforward. */
3329 MEMORYSTATUSEX ms;
3330 memset(&ms, 0, sizeof(ms));
3331 ms.dwLength = sizeof(ms);
3332 if (! GlobalMemoryStatusEx(&ms))
3333 return 0;
3335 return ms.ullTotalPhys;
3337 #elif defined(HAVE_SYSCTL) && defined(INT64_HW_MEM)
3338 /* On many systems, HW_PYHSMEM is clipped to 32 bits; let's use a better
3339 * variant if we know about it. */
3340 uint64_t memsize = 0;
3341 size_t len = sizeof(memsize);
3342 int mib[2] = {CTL_HW, INT64_HW_MEM};
3343 if (sysctl(mib,2,&memsize,&len,NULL,0))
3344 return 0;
3346 return memsize;
3348 #elif defined(HAVE_SYSCTL) && defined(HW_PHYSMEM)
3349 /* On some systems (like FreeBSD I hope) you can use a size_t with
3350 * HW_PHYSMEM. */
3351 size_t memsize=0;
3352 size_t len = sizeof(memsize);
3353 int mib[2] = {CTL_HW, HW_USERMEM};
3354 if (sysctl(mib,2,&memsize,&len,NULL,0))
3355 return 0;
3357 return memsize;
3359 #else
3360 /* I have no clue. */
3361 return 0;
3362 #endif
3366 * Try to find out how much physical memory the system has. On success,
3367 * return 0 and set *<b>mem_out</b> to that value. On failure, return -1.
3370 get_total_system_memory(size_t *mem_out)
3372 static size_t mem_cached=0;
3373 uint64_t m = get_total_system_memory_impl();
3374 if (0 == m) {
3375 /* LCOV_EXCL_START -- can't make this happen without mocking. */
3376 /* We couldn't find our memory total */
3377 if (0 == mem_cached) {
3378 /* We have no cached value either */
3379 *mem_out = 0;
3380 return -1;
3383 *mem_out = mem_cached;
3384 return 0;
3385 /* LCOV_EXCL_STOP */
3388 #if SIZE_MAX != UINT64_MAX
3389 if (m > SIZE_MAX) {
3390 /* I think this could happen if we're a 32-bit Tor running on a 64-bit
3391 * system: we could have more system memory than would fit in a
3392 * size_t. */
3393 m = SIZE_MAX;
3395 #endif
3397 *mem_out = mem_cached = (size_t) m;
3399 return 0;
3402 /** Emit the password prompt <b>prompt</b>, then read up to <b>buflen</b>
3403 * bytes of passphrase into <b>output</b>. Return the number of bytes in
3404 * the passphrase, excluding terminating NUL.
3406 ssize_t
3407 tor_getpass(const char *prompt, char *output, size_t buflen)
3409 tor_assert(buflen <= SSIZE_MAX);
3410 tor_assert(buflen >= 1);
3411 #if defined(HAVE_READPASSPHRASE)
3412 char *pwd = readpassphrase(prompt, output, buflen, RPP_ECHO_OFF);
3413 if (pwd == NULL)
3414 return -1;
3415 return strlen(pwd);
3416 #elif defined(_WIN32)
3417 int r = -1;
3418 while (*prompt) {
3419 _putch(*prompt++);
3422 tor_assert(buflen <= INT_MAX);
3423 wchar_t *buf = tor_calloc(buflen, sizeof(wchar_t));
3425 wchar_t *ptr = buf, *lastch = buf + buflen - 1;
3426 while (ptr < lastch) {
3427 wint_t ch = _getwch();
3428 switch (ch) {
3429 case '\r':
3430 case '\n':
3431 case WEOF:
3432 goto done_reading;
3433 case 3:
3434 goto done; /* Can't actually read ctrl-c this way. */
3435 case '\b':
3436 if (ptr > buf)
3437 --ptr;
3438 continue;
3439 case 0:
3440 case 0xe0:
3441 ch = _getwch(); /* Ignore; this is a function or arrow key */
3442 break;
3443 default:
3444 *ptr++ = ch;
3445 break;
3448 done_reading:
3451 #ifndef WC_ERR_INVALID_CHARS
3452 #define WC_ERR_INVALID_CHARS 0x80
3453 #endif
3455 /* Now convert it to UTF-8 */
3456 r = WideCharToMultiByte(CP_UTF8,
3457 WC_NO_BEST_FIT_CHARS|WC_ERR_INVALID_CHARS,
3458 buf, (int)(ptr-buf),
3459 output, (int)(buflen-1),
3460 NULL, NULL);
3461 if (r <= 0) {
3462 r = -1;
3463 goto done;
3466 tor_assert(r < (int)buflen);
3468 output[r] = 0;
3470 done:
3471 SecureZeroMemory(buf, sizeof(wchar_t)*buflen);
3472 tor_free(buf);
3473 return r;
3474 #else
3475 #error "No implementation for tor_getpass found!"
3476 #endif
3479 /** Return the amount of free disk space we have permission to use, in
3480 * bytes. Return -1 if the amount of free space can't be determined. */
3481 int64_t
3482 tor_get_avail_disk_space(const char *path)
3484 #ifdef HAVE_STATVFS
3485 struct statvfs st;
3486 int r;
3487 memset(&st, 0, sizeof(st));
3489 r = statvfs(path, &st);
3490 if (r < 0)
3491 return -1;
3493 int64_t result = st.f_bavail;
3494 if (st.f_frsize) {
3495 result *= st.f_frsize;
3496 } else if (st.f_bsize) {
3497 result *= st.f_bsize;
3498 } else {
3499 return -1;
3502 return result;
3503 #elif defined(_WIN32)
3504 ULARGE_INTEGER freeBytesAvail;
3505 BOOL ok;
3507 ok = GetDiskFreeSpaceEx(path, &freeBytesAvail, NULL, NULL);
3508 if (!ok) {
3509 return -1;
3511 return (int64_t)freeBytesAvail.QuadPart;
3512 #else
3513 (void)path;
3514 errno = ENOSYS;
3515 return -1;
3516 #endif