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