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
;
92 #elif defined(HAVE_READPASSPHRASE_H)
93 #include <readpassphrase.h>
95 #include "tor_readpassphrase.h"
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>
110 #ifdef HAVE_SYS_PARAM_H
111 #include <sys/param.h> /* FreeBSD needs this to know what version it is */
119 #ifdef HAVE_SYS_MMAN_H
120 #include <sys/mman.h>
122 #ifdef HAVE_SYS_SYSLIMITS_H
123 #include <sys/syslimits.h>
125 #ifdef HAVE_SYS_FILE_H
126 #include <sys/file.h>
131 #include "container.h"
135 /* Inline the strl functions if the platform doesn't have them. */
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
151 tor_open_cloexec(const char *path
, int flags
, unsigned mode
)
154 const char *p
= sandbox_intern_string(path
);
156 fd
= open(p
, flags
|O_CLOEXEC
, mode
);
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. */
166 log_debug(LD_FS
, "Opening %s with flags %x", p
, flags
);
167 fd
= open(p
, flags
, mode
);
170 if (fcntl(fd
, F_SETFD
, FD_CLOEXEC
) == -1) {
171 log_warn(LD_FS
,"Couldn't set FD_CLOEXEC: %s", strerror(errno
));
180 /** As fopen(path,mode), but ensures that the O_CLOEXEC bit is set on the
181 * underlying file handle. */
183 tor_fopen_cloexec(const char *path
, const char *mode
)
185 FILE *result
= fopen(path
, mode
);
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
));
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
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
220 tor_mmap_file(const char *filename
)
222 int fd
; /* router file */
224 int page_size
, result
;
226 size_t size
, filesize
;
229 tor_assert(filename
);
231 fd
= tor_open_cloexec(filename
, O_RDONLY
, 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
,
241 /* Get the size of the file */
242 result
= fstat(fd
, &st
);
244 int save_errno
= errno
;
246 "Couldn't fstat opened descriptor for \"%s\" during mmap: %s",
247 filename
, strerror(errno
));
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
);
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
);
276 string
= mmap(0, size
, PROT_READ
, MAP_PRIVATE
, fd
, 0);
278 if (string
== MAP_FAILED
) {
279 int save_errno
= errno
;
280 log_warn(LD_FS
,"Could not mmap file \"%s\": %s", filename
,
286 res
= tor_malloc_zero(sizeof(tor_mmap_t
));
288 res
->size
= filesize
;
289 res
->mapping_size
= size
;
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
)
303 res
= munmap((char*)handle
->data
, handle
->mapping_size
);
305 /* munmap() succeeded */
308 log_warn(LD_FS
, "Failed to munmap() in tor_munmap_file(): %s",
315 #elif defined(_WIN32)
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
));
322 HANDLE file_handle
= INVALID_HANDLE_VALUE
;
323 DWORD size_low
, size_high
;
325 res
->mmap_handle
= NULL
;
327 mbstowcs(tfilename
,filename
,MAX_PATH
);
329 strlcpy(tfilename
,filename
,MAX_PATH
);
331 file_handle
= CreateFile(tfilename
,
332 GENERIC_READ
, FILE_SHARE_READ
,
335 FILE_ATTRIBUTE_NORMAL
,
338 if (file_handle
== INVALID_HANDLE_VALUE
)
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
);
347 if (size_low
== 0 && size_high
== 0) {
348 log_info(LD_FS
,"File \"%s\" is empty. Ignoring.",filename
);
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
);
357 res
->size
= real_size
;
359 res
->mmap_handle
= CreateFileMapping(file_handle
,
365 if (res
->mmap_handle
== NULL
)
367 res
->data
= (char*) MapViewOfFile(res
->mmap_handle
,
373 CloseHandle(file_handle
);
376 DWORD e
= GetLastError();
377 int severity
= (e
== ERROR_FILE_NOT_FOUND
|| e
== ERROR_PATH_NOT_FOUND
) ?
379 char *msg
= format_win32_error(e
);
380 log_fn(severity
, LD_FS
, "Couldn't mmap file \"%s\": %s", filename
, msg
);
382 if (e
== ERROR_FILE_NOT_FOUND
|| e
== ERROR_PATH_NOT_FOUND
)
390 if (file_handle
!= INVALID_HANDLE_VALUE
)
391 CloseHandle(file_handle
);
392 tor_munmap_file(res
);
396 /* Unmap the file, and return 0 for success or -1 for failure */
398 tor_munmap_file(tor_mmap_t
*handle
)
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
);
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
);
421 tor_mmap_file(const char *filename
)
424 char *res
= read_file_to_str(filename
, RFTS_BIN
|RFTS_IGNORE_MISSING
, &st
);
428 handle
= tor_malloc_zero(sizeof(tor_mmap_t
));
430 handle
->size
= st
.st_size
;
434 /** Unmap the file mapped with tor_mmap_file(), and return 0 for success
439 tor_munmap_file(tor_mmap_t
*handle
)
445 d
= (char*)handle
->data
;
447 memwipe(handle
, 0, sizeof(tor_mmap_t
));
450 /* Can't fail in this mmap()/munmap()-free case */
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
, ...)
468 r
= tor_vsnprintf(str
,size
,format
,ap
);
473 /** Replacement for vsnprintf; behavior differs as tor_snprintf differs from
477 tor_vsnprintf(char *str
, size_t size
, const char *format
, va_list args
)
481 return -1; /* no place for the NUL */
482 if (size
> SIZE_T_CEILING
)
485 r
= _vsnprintf(str
, size
, format
, args
);
487 r
= vsnprintf(str
, size
, format
, args
);
490 if (r
< 0 || r
>= (ssize_t
)size
)
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
502 char buf[_INFINITY_];
503 tor_snprintf(buf, sizeof(buf), fmt, args);
504 *strp = tor_strdup(buf);
505 return strlen(*strp):
507 * Where _INFINITY_ is an imaginary constant so big that any string can fit
511 tor_asprintf(char **strp
, const char *fmt
, ...)
516 r
= tor_vasprintf(strp
, fmt
, args
);
518 if (!*strp
|| r
< 0) {
519 /* LCOV_EXCL_START */
520 log_err(LD_BUG
, "Internal error in asprintf");
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. */
537 #ifdef HAVE_VASPRINTF
538 /* If the platform gives us one, use it. */
539 int r
= vasprintf(&strp_tmp
, fmt
, args
);
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 */
550 va_copy(tmp_args
, args
);
551 len
= _vscprintf(fmt
, tmp_args
);
557 strp_tmp
= tor_malloc(len
+ 1);
558 r
= _vsnprintf(strp_tmp
, len
+1, fmt
, args
);
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.
574 va_copy(tmp_args
, args
);
575 /* vsnprintf() was properly checked but tor_vsnprintf() available so
577 len
= tor_vsnprintf(buf
, sizeof(buf
), fmt
, tmp_args
);
579 if (len
< (int)sizeof(buf
)) {
580 *strp
= tor_strdup(buf
);
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
);
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.
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)
610 return memmem(_haystack
, hlen
, _needle
, nlen
);
612 /* This isn't as fast as the GLIBC implementation, but it doesn't need to
614 const char *p
, *last_possible_start
;
615 const char *haystack
= (const char*)_haystack
;
616 const char *needle
= (const char*)_needle
;
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
))
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
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. */
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(). */
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,
703 /** Helper for tor_strtok_r_impl: Advances cp past all characters in
704 * <b>sep</b>, and returns its new value. */
706 strtok_helper(char *cp
, const char *sep
)
709 while (*cp
&& strchr(sep
, *cp
))
712 while (*cp
&& *cp
== *sep
)
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
722 tor_strtok_r_impl(char *str
, const char *sep
, char **lasts
)
727 str
= strtok_helper(str
, sep
);
730 start
= cp
= *lasts
= str
;
731 } else if (!*lasts
|| !**lasts
) {
738 while (*cp
&& !strchr(sep
, *cp
))
741 cp
= strchr(cp
, *sep
);
748 *lasts
= strtok_helper(cp
, sep
);
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.
761 tor_fix_source_file(const char *fname
)
763 const char *cp1
, *cp2
, *r
;
764 cp1
= strrchr(fname
, '/');
765 cp2
= strrchr(fname
, '\\');
767 r
= (cp1
<cp2
)?(cp2
+1):(cp1
+1);
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.
785 get_uint16(const void *cp
)
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.
797 get_uint32(const void *cp
)
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.
809 get_uint64(const void *cp
)
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. */
821 set_uint16(void *cp
, uint16_t v
)
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. */
830 set_uint32(void *cp
, uint32_t v
)
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. */
839 set_uint64(void *cp
, uint64_t v
)
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
848 * Returns 0 on success. Returns -1 and sets errno on failure.
851 replace_file(const char *from
, const char *to
)
854 return tor_rename(from
, to
);
856 switch (file_status(to
))
862 if (unlink(to
)) return -1;
870 return tor_rename(from
,to
);
874 /** Change <b>fname</b>'s modification time to now. */
876 touch_file(const char *fname
)
878 if (utime(fname
, NULL
)!=0)
883 /** Represents a lockfile on which we hold the lock. */
884 struct tor_lockfile_t
{
885 /** Name of the file */
887 /** File descriptor used to hold the file open */
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
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.)
909 tor_lockfile_lock(const char *filename
, int blocking
, int *locked_out
)
911 tor_lockfile_t
*result
;
915 log_info(LD_FS
, "Locking \"%s\"", filename
);
916 fd
= tor_open_cloexec(filename
, O_RDWR
|O_CREAT
|O_TRUNC
, 0600);
918 log_warn(LD_FS
,"Couldn't open \"%s\" for locking: %s", filename
,
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
));
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
));
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
));
959 result
= tor_malloc(sizeof(tor_lockfile_t
));
960 result
->filename
= tor_strdup(filename
);
965 /** Release the lock held as <b>lockfile</b>. */
967 tor_lockfile_unlock(tor_lockfile_t
*lockfile
)
969 tor_assert(lockfile
);
971 log_info(LD_FS
, "Unlocking \"%s\"", lockfile
->filename
);
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
,
978 #elif defined(HAVE_FLOCK)
979 if (flock(lockfile
->fd
, LOCK_UN
) < 0) {
980 log_warn(LD_FS
, "Error unlocking \"%s\": %s", lockfile
->filename
,
984 /* Closing the lockfile is sufficient. */
989 tor_free(lockfile
->filename
);
994 /** Some old versions of Unix didn't define constants for these values,
995 * and instead expect you to say 0, 1, or 2. */
1007 /** Return the position of <b>fd</b> with respect to the start of the file. */
1009 tor_fd_getpos(int fd
)
1012 return (off_t
) _lseek(fd
, 0, SEEK_CUR
);
1014 return (off_t
) lseek(fd
, 0, SEEK_CUR
);
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
)
1025 return _lseek(fd
, 0, SEEK_END
) < 0 ? -1 : 0;
1027 off_t rc
= lseek(fd
, 0, SEEK_END
) < 0 ? -1 : 0;
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
)
1034 return (rc
< 0) ? -1 : 0;
1038 /** Move <b>fd</b> to position <b>pos</b> in the file. Return -1 on error, 0
1041 tor_fd_setpos(int fd
, off_t pos
)
1044 return _lseek(fd
, pos
, SEEK_SET
) < 0 ? -1 : 0;
1046 return lseek(fd
, pos
, SEEK_SET
) < 0 ? -1 : 0;
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)
1061 return _chsize(fd
, 0);
1063 return ftruncate(fd
, 0);
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;
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. */
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. */
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
)
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
1120 int err
= tor_socket_errno(-1);
1121 log_info(LD_NET
, "Close returned an error: %s", tor_socket_strerror(err
));
1128 /** As tor_close_socket_simple(), but keeps track of the number
1129 * of open sockets. Returns 0 on success, -1 on failure. */
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
);
1141 tor_assert(open_sockets
&& s
<= max_socket
);
1142 bitarray_clear(open_sockets
, s
);
1149 if (r
!= WSAENOTSOCK
)
1153 --n_sockets_open
; // LCOV_EXCL_LINE -- EIO and EINTR too hard to force.
1158 tor_assert_nonfatal(n_sockets_open
>= 0);
1159 socket_accounting_unlock();
1164 #ifdef DEBUG_SOCKET_COUNTING
1165 /** Helper: if DEBUG_SOCKET_COUNTING is enabled, remember that <b>s</b> is
1166 * now an open socket. */
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);
1177 open_sockets
= bitarray_expand(open_sockets
, 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
);
1188 #define mark_socket_open(s) STMT_NIL
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. */
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.*/
1220 tor_open_socket_with_extensions(int domain
, int type
, int protocol
,
1221 int cloexec
, int nonblock
)
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) {
1229 WSASetLastError(WSAEMFILE
);
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
);
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
)
1247 #endif /* SOCK_CLOEXEC && SOCK_NONBLOCK */
1249 s
= socket(domain
, type
, protocol
);
1253 #if defined(FD_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
;
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. */
1275 socket_accounting_lock();
1277 mark_socket_open(s
);
1278 socket_accounting_unlock();
1282 /** As accept(), but counts the number of open sockets. */
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. */
1292 tor_accept_socket_nonblocking(tor_socket_t sockfd
, struct sockaddr
*addr
,
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.*/
1303 tor_accept_socket_with_extensions(tor_socket_t sockfd
, struct sockaddr
*addr
,
1304 socklen_t
*len
, int cloexec
, int nonblock
)
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) {
1312 WSASetLastError(WSAEMFILE
);
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
);
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
)
1333 s
= accept(sockfd
, addr
, len
);
1337 #if defined(FD_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
;
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. */
1359 socket_accounting_lock();
1361 mark_socket_open(s
);
1362 socket_accounting_unlock();
1366 /** Return the number of sockets we currently have opened. */
1368 get_n_open_sockets(void)
1371 socket_accounting_lock();
1373 socket_accounting_unlock();
1377 /** Mockable wrapper for getsockname(). */
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
1389 set_socket_nonblocking(tor_socket_t sock
)
1392 unsigned long nonblocking
= 1;
1393 ioctlsocket(sock
, FIONBIO
, (unsigned long*) &nonblocking
);
1397 flags
= fcntl(sock
, F_GETFL
, 0);
1399 log_warn(LD_NET
, "Couldn't get file status flags: %s", strerror(errno
));
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
));
1413 * Allocate a pair of connected sockets. (Like socketpair(family,
1414 * type,protocol,fd), but works on systems that don't have
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)
1437 r
= socketpair(family
, type
|SOCK_CLOEXEC
, protocol
, fd
);
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
)
1447 r
= socketpair(family
, type
, protocol
, fd
);
1451 #if defined(FD_CLOEXEC)
1452 if (SOCKET_OK(fd
[0])) {
1453 r
= fcntl(fd
[0], F_SETFD
, FD_CLOEXEC
);
1460 if (SOCKET_OK(fd
[1])) {
1461 r
= fcntl(fd
[1], F_SETFD
, FD_CLOEXEC
);
1469 goto sockets_ok
; /* So that sockets_ok will not be unused. */
1472 socket_accounting_lock();
1473 if (SOCKET_OK(fd
[0])) {
1475 mark_socket_open(fd
[0]);
1477 if (SOCKET_OK(fd
[1])) {
1479 mark_socket_open(fd
[1]);
1481 socket_accounting_unlock();
1485 return tor_ersatz_socketpair(family
, type
, protocol
, fd
);
1489 #ifdef NEED_ERSATZ_SOCKETPAIR
1491 static inline socklen_t
1492 SIZEOF_SOCKADDR(int domain
)
1496 return sizeof(struct sockaddr_in
);
1498 return sizeof(struct sockaddr_in6
);
1505 * Helper used to implement socketpair on systems that lack it, by
1506 * making a direct connection to localhost.
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
;
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
));
1537 || family
!= AF_UNIX
1541 return -WSAEAFNOSUPPORT
;
1543 return -EAFNOSUPPORT
;
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
);
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. */,
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
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
);
1623 abort_tidy_up_and_fail
:
1625 saved_errno
= WSAECONNABORTED
;
1627 saved_errno
= ECONNABORTED
; /* I hope this is portable and appropriate. */
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
1645 /* Return the maximum number of allowed sockets. */
1647 get_max_sockets(void)
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
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
) {
1678 "ConnLimit must be at least %d. Failing.", ULIMIT_BUFFER
);
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;
1695 const char *platform
= "unknown platforms with no getrlimit()";
1696 const unsigned long MAX_CONNECTIONS
= 15000;
1698 log_fn(LOG_INFO
, LD_NET
,
1699 "This platform is missing getrlimit(). Proceeding.");
1700 if (limit
> MAX_CONNECTIONS
) {
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
);
1707 limit
= MAX_CONNECTIONS
;
1708 #else /* HAVE_GETRLIMIT */
1711 if (getrlimit(RLIMIT_NOFILE
, &rlim
) != 0) {
1712 log_warn(LD_NET
, "Could not get maximum number of file descriptors: %s",
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
);
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) {
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
);
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
);
1752 #endif /* OPEN_MAX */
1754 log_warn(LD_CONFIG
,"Couldn't set maximum number of file descriptors: %s",
1759 /* leave some overhead for logs, etc, */
1760 limit
= rlim
.rlim_cur
;
1761 #endif /* HAVE_GETRLIMIT */
1763 if (limit
> INT_MAX
)
1765 tor_assert(max_out
);
1766 *max_out
= max_sockets
= (int)limit
- ULIMIT_BUFFER
;
1771 /** Log details of current user and group credentials. Return 0 on
1772 * success. Logs and return -1 on failure.
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
;
1786 /* Number of supplementary groups */
1790 #ifdef HAVE_GETRESUID
1791 if (getresuid(&ruid
, &euid
, &suid
) != 0 ) {
1792 log_warn(LD_GENERAL
, "Error getting changed UIDs: %s", strerror(errno
));
1795 log_fn(CREDENTIAL_LOG_LEVEL
, LD_GENERAL
,
1796 "UID is %u (real), %u (effective), %u (saved)",
1797 (unsigned)ruid
, (unsigned)euid
, (unsigned)suid
);
1800 /* getresuid is not present on MacOS X, so we can't get the saved (E)UID */
1805 log_fn(CREDENTIAL_LOG_LEVEL
, LD_GENERAL
,
1806 "UID is %u (real), %u (effective), unknown (saved)",
1807 (unsigned)ruid
, (unsigned)euid
);
1811 #ifdef HAVE_GETRESGID
1812 if (getresgid(&rgid
, &egid
, &sgid
) != 0 ) {
1813 log_warn(LD_GENERAL
, "Error getting changed GIDs: %s", strerror(errno
));
1816 log_fn(CREDENTIAL_LOG_LEVEL
, LD_GENERAL
,
1817 "GID is %u (real), %u (effective), %u (saved)",
1818 (unsigned)rgid
, (unsigned)egid
, (unsigned)sgid
);
1821 /* getresgid is not present on MacOS X, so we can't get the saved (E)GID */
1825 log_fn(CREDENTIAL_LOG_LEVEL
, LD_GENERAL
,
1826 "GID is %u (real), %u (effective), unknown (saved)",
1827 (unsigned)rgid
, (unsigned)egid
);
1830 /* log supplementary groups */
1832 sup_gids
= tor_calloc(64, sizeof(gid_t
));
1833 while ((ngids
= getgroups(sup_gids_size
, sup_gids
)) < 0 &&
1835 sup_gids_size
< NGROUPS_MAX
) {
1837 sup_gids
= tor_reallocarray(sup_gids
, sizeof(gid_t
), sup_gids_size
);
1841 log_warn(LD_GENERAL
, "Error getting supplementary GIDs: %s",
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
);
1859 SMARTLIST_FOREACH(elts
, char *, cp
, tor_free(cp
));
1860 smartlist_free(elts
);
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
));
1884 new_pw
->pw_name
= tor_strdup(pw
->pw_name
);
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
;
1893 /** Helper: free one of our cached 'struct passwd' values. */
1895 tor_passwd_free(struct passwd
*pw
)
1900 tor_free(pw
->pw_name
);
1901 tor_free(pw
->pw_dir
);
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
)
1919 if (username
== NULL
) {
1920 tor_passwd_free(passwd_cached
);
1921 passwd_cached
= 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
);
1934 if (! passwd_cached
|| ! passwd_cached
->pw_name
)
1937 if (! strcmp(username
, passwd_cached
->pw_name
))
1938 return passwd_cached
; // LCOV_EXCL_LINE - would need to make getpwnam flaky
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
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
)
1955 if ((pw
= getpwuid(uid
))) {
1960 if (! passwd_cached
)
1963 if (uid
== passwd_cached
->pw_uid
)
1964 return passwd_cached
; // LCOV_EXCL_LINE - would need to make getpwnam flaky
1970 /** Return true iff we were compiled with capability support, and capabilities
1973 have_capability_support(void)
1975 #ifdef HAVE_LINUX_CAPABILITIES
1976 cap_t caps
= cap_get_proc();
1986 #ifdef HAVE_LINUX_CAPABILITIES
1987 /** Helper. Drop all capabilities but a small set, and set PR_KEEPCAPS as
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
1994 * If not pre_setuid, retain only CAP_NET_BIND_SERVICE, and disable
1997 * Return 0 on success, and -1 on failure.
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
));
2020 cap_t caps
= cap_get_proc();
2022 log_warn(LD_CONFIG
, "Unable to call cap_get_proc() %s: %s",
2023 where
, strerror(errno
));
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
);
2035 log_warn(LD_CONFIG
, "No permission to set capabilities %s: %s",
2036 where
, strerror(errno
));
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
)
2057 const struct passwd
*pw
= NULL
;
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
);
2066 if (have_already_switched_id
)
2069 /* Log the initial credential state */
2070 if (log_credential_status())
2073 log_fn(CREDENTIAL_LOG_LEVEL
, LD_GENERAL
, "Changing user and groups");
2075 /* Get old UID/GID to check if we changed correctly */
2079 /* Lookup the user and group information, if we have a problem, bail out. */
2080 pw
= tor_getpwnam(user
);
2082 log_warn(LD_CONFIG
, "Error setting configured user: %s not found", user
);
2086 #ifdef HAVE_LINUX_CAPABILITIES
2087 (void) warn_if_no_caps
;
2089 if (drop_capabilities(1))
2093 (void) keep_bindlow
;
2094 if (warn_if_no_caps
) {
2095 log_warn(LD_CONFIG
, "KeepBindCapabilities set, but no capability support "
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
);
2111 log_warn(LD_GENERAL
, "If you set the \"User\" option, you must start Tor"
2117 if (setegid(pw
->pw_gid
)) {
2118 log_warn(LD_GENERAL
, "Error setting egid to %d: %s",
2119 (int)pw
->pw_gid
, strerror(errno
));
2123 if (setgid(pw
->pw_gid
)) {
2124 log_warn(LD_GENERAL
, "Error setting gid to %d: %s",
2125 (int)pw
->pw_gid
, strerror(errno
));
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
));
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
));
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",
2151 /* We've properly switched egid, gid, euid, uid, and supplementary groups if
2153 #ifdef HAVE_LINUX_CAPABILITIES
2155 if (drop_capabilities(0))
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 */
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.");
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.");
2184 /* Check what really happened */
2185 if (log_credential_status()) {
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
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
));
2208 log_warn(LD_CONFIG
, "Switching users is unsupported on your OS.");
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)
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
2242 r
= prctl(PR_SET_DUMPABLE
, 0);
2245 #if defined(__APPLE__) && defined(PT_DENY_ATTACH)
2248 r
= ptrace(PT_DENY_ATTACH
, 0, 0, 0);
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.");
2258 } else if (attempted
) {
2259 log_warn(LD_CONFIG
, "Unable to disable debugger attaching: %s",
2266 /** Allocate and return a string containing the home directory for the
2267 * user <b>username</b>. Only works on posix-like systems. */
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
);
2278 return tor_strdup(pw
->pw_dir
);
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).
2297 get_parent_directory(char *fname
)
2303 /* If we start with, say, c:, then don't consider that the start of the path
2305 if (fname
[0] && fname
[1] == ':') {
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
);
2317 while (--cp
>= fname
) {
2318 int is_sep
= (*cp
== '/'
2325 /* This is the first separator in the file name; don't remove it! */
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.)
2348 #define MAX_CWD PATH_MAX
2350 #define MAX_CWD 4096
2353 char path_buf
[MAX_CWD
];
2354 char *path
= getcwd(path_buf
, sizeof(path_buf
));
2355 return path
? tor_strdup(path
) : NULL
;
2359 /** Expand possibly relative path <b>fname</b> to an absolute path.
2360 * Return a newly allocated string, possibly equal to <b>fname</b>. */
2362 make_path_absolute(char *fname
)
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
);
2374 char *absfname
= NULL
, *path
= NULL
;
2378 if (fname
[0] == '/') {
2379 absfname
= tor_strdup(fname
);
2381 path
= alloc_getcwd();
2383 tor_asprintf(&absfname
, "%s/%s", path
, fname
);
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",
2391 absfname
= tor_strdup(fname
);
2392 /* LCOV_EXCL_STOP */
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
;
2408 /** Return the current environment. This is a portable replacement for
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();
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().)
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
)
2443 if (tor_sscanf(str
, "%3u.%3u.%3u.%3u%c", &a
,&b
,&c
,&d
,&more
) != 4)
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
);
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
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)
2469 } else if (af
== AF_INET6
) {
2470 const struct in6_addr
*addr
= src
;
2472 int longestGapLen
= 0, longestGapPos
= -1, i
,
2473 curGapPos
= -1, curGapLen
= 0;
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]);
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 */
2493 strlcpy(dst
, buf
, len
);
2498 if (words
[i
] == 0) {
2501 while (i
<8 && words
[i
] == 0) {
2504 if (curGapLen
> longestGapLen
) {
2505 longestGapPos
= curGapPos
;
2506 longestGapLen
= curGapLen
;
2512 if (longestGapLen
<=1)
2516 for (i
= 0; i
< 8; ++i
) {
2517 if (words
[i
] == 0 && longestGapPos
== i
) {
2521 while (i
< 8 && words
[i
] == 0)
2523 --i
; /* to compensate for loop increment. */
2525 tor_snprintf(cp
, sizeof(buf
)-(cp
-buf
), "%x", (unsigned)words
[i
]);
2532 if ((strlen(buf
) + 1) > len
) /* +1 for \0 */
2534 strlcpy(dst
, buf
, len
);
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
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
;
2558 int gapPos
= -1, i
, setWords
=0;
2559 const char *dot
= strchr(src
, '.');
2560 const char *eow
; /* end of words. */
2564 eow
= src
+strlen(src
);
2566 unsigned byte1
,byte2
,byte3
,byte4
;
2568 for (eow
= dot
-1; eow
> src
&& TOR_ISDIGIT(*eow
); --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)
2580 if (byte1
> 255 || byte2
> 255 || byte3
> 255 || byte4
> 255)
2583 words
[6] = (byte1
<<8) | byte2
;
2584 words
[7] = (byte3
<<8) | byte4
;
2592 if (TOR_ISXDIGIT(*src
)) {
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
;
2602 if (len
> 1 && !TOR_ISXDIGIT(src
[1]))
2603 return 0; /* 0x is not valid */
2606 tor_assert(r
< 65536);
2607 words
[i
++] = (uint16_t)r
;
2610 if (*src
!= ':' && src
!= eow
)
2613 } else if (*src
== ':' && i
> 0 && gapPos
== -1) {
2616 } else if (*src
== ':' && i
== 0 && src
+1 < eow
&& src
[1] == ':' &&
2626 (setWords
== 8 && gapPos
!= -1) ||
2627 (setWords
< 8 && gapPos
== -1))
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;
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.)
2658 tor_lookup_hostname
,(const char *name
, uint32_t *addr
))
2663 if ((ret
= tor_addr_lookup(name
, AF_INET
, &myaddr
)))
2666 if (tor_addr_family(&myaddr
) == AF_INET
) {
2667 *addr
= tor_addr_to_ipv4h(&myaddr
);
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))
2686 if (!uname_result_is_set
) {
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
));
2695 OSVERSIONINFOEX info
;
2697 const char *plat
= NULL
;
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" },
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";
2726 plat
= "Windows 95";
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
;
2737 strlcpy(uname_result
, plat
, sizeof(uname_result
));
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
);
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
));
2756 /* LCOV_EXCL_START -- can't provoke uname failure */
2757 strlcpy(uname_result
, "Unknown platform", sizeof(uname_result
));
2758 /* LCOV_EXCL_STOP */
2761 uname_result_is_set
= 1;
2763 return uname_result
;
2770 /** Implementation logic for compute_num_cpus(). */
2772 compute_num_cpus_impl(void)
2776 memset(&info
, 0, sizeof(info
));
2777 GetSystemInfo(&info
);
2778 if (info
.dwNumberOfProcessors
>= 1 && info
.dwNumberOfProcessors
< INT_MAX
)
2779 return (int)info
.dwNumberOfProcessors
;
2782 #elif defined(HAVE_SYSCONF)
2783 #ifdef _SC_NPROCESSORS_CONF
2784 long cpus_conf
= sysconf(_SC_NPROCESSORS_CONF
);
2786 long cpus_conf
= -1;
2788 #ifdef _SC_NPROCESSORS_ONLN
2789 long cpus_onln
= sysconf(_SC_NPROCESSORS_ONLN
);
2791 long cpus_onln
= -1;
2795 if (cpus_conf
> 0 && cpus_onln
< 0) {
2797 } else if (cpus_onln
> 0 && cpus_conf
< 0) {
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
);
2809 if (cpus
>= 1 && cpus
< INT_MAX
)
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
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 */
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
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>. */
2858 correct_tm(int islocal
, const time_t *timep
, struct tm
*resultbuf
,
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) {
2875 } else if (r
->tm_year
< (1-1900)) {
2876 r
->tm_year
= (1-1900);
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. */
2894 r
->tm_year
= 70; /* 1970 CE */
2902 outcome
= "Rounding up to 1970";
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. */
2908 r
->tm_year
= 137; /* 2037 CE */
2916 outcome
= "Rounding down to 2037";
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();
2926 memset(resultbuf
, 0, sizeof(struct tm
));
2927 outcome
="can't recover";
2928 /* LCOV_EXCL_STOP */
2930 log_warn(LD_BUG
, "%s("I64_FORMAT
") failed with error %s: %s",
2931 islocal
?"localtime":"gmtime",
2932 timep
?I64_PRINTF_ARG(*timep
):0,
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
2946 tor_localtime_r(const time_t *timep
, struct tm
*result
)
2949 r
= localtime_r(timep
, result
);
2950 return correct_tm(1, timep
, result
, r
);
2952 #elif defined(TIME_FNS_NEED_LOCKS)
2954 tor_localtime_r(const time_t *timep
, struct tm
*result
)
2957 static tor_mutex_t
*m
=NULL
;
2958 if (!m
) { m
=tor_mutex_new(); }
2960 tor_mutex_acquire(m
);
2961 r
= localtime(timep
);
2963 memcpy(result
, r
, sizeof(struct tm
));
2964 tor_mutex_release(m
);
2965 return correct_tm(1, timep
, result
, r
);
2969 tor_localtime_r(const time_t *timep
, struct tm
*result
)
2973 r
= localtime(timep
);
2975 memcpy(result
, r
, sizeof(struct tm
));
2976 return correct_tm(1, timep
, result
, r
);
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
2989 tor_gmtime_r(const time_t *timep
, struct tm
*result
)
2992 r
= gmtime_r(timep
, result
);
2993 return correct_tm(0, timep
, result
, r
);
2995 #elif defined(TIME_FNS_NEED_LOCKS)
2997 tor_gmtime_r(const time_t *timep
, struct tm
*result
)
3000 static tor_mutex_t
*m
=NULL
;
3001 if (!m
) { m
=tor_mutex_new(); }
3003 tor_mutex_acquire(m
);
3006 memcpy(result
, r
, sizeof(struct tm
));
3007 tor_mutex_release(m
);
3008 return correct_tm(0, timep
, result
, r
);
3012 tor_gmtime_r(const time_t *timep
, struct tm
*result
)
3018 memcpy(result
, r
, sizeof(struct tm
));
3019 return correct_tm(0, timep
, result
, r
);
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.
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",
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.
3064 static int memory_lock_attempted
= 0;
3066 if (memory_lock_attempted
) {
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.");
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 "
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
));
3101 log_warn(LD_GENERAL
, "Unable to lock memory pages. mlockall() unsupported?");
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
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.
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
))
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"),
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.
3194 /** There does not seem to be a strerror equivalent for Winsock errors.
3195 * Naturally, we have to roll our own.
3198 tor_socket_strerror(int e
)
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
;
3209 /** Called before we make any calls to network-related functions.
3210 * (Some operating systems require their network libraries to be
3216 /* This silly exercise is necessary before windows will allow
3217 * gethostbyname to work. */
3220 r
= WSAStartup(0x101,&WSAData
);
3222 log_warn(LD_NET
,"Error initializing windows network layer: code was %d",r
);
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. */
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. */
3243 format_win32_error(DWORD err
)
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
,
3254 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
3262 len
= (128 * 1024) * 2 + 1; /* This shouldn't be possible, but let's
3266 result
= tor_malloc(len
);
3267 wcstombs(result
,str
,len
);
3268 result
[len
-1] = '\0';
3270 result
= tor_strdup(str
);
3273 result
= tor_strdup("<unformattable error>");
3276 LocalFree(str
); /* LocalFree != free() */
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
3291 * Helper: try to detect the total system memory, and return it. On failure,
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;
3305 if (-1 == (fd
= tor_open_cloexec("/proc/meminfo",O_RDONLY
,0)))
3307 s
= read_file_to_str_until_eof(fd
, 65536, &file_size
);
3310 cp
= strstr(s
, "MemTotal:");
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)
3319 return result
* 1024;
3322 /* LCOV_EXCL_START Can't reach this unless proc is broken. */
3326 /* LCOV_EXCL_STOP */
3327 #elif defined (_WIN32)
3328 /* Windows has MEMORYSTATUSEX; pretty straightforward. */
3330 memset(&ms
, 0, sizeof(ms
));
3331 ms
.dwLength
= sizeof(ms
);
3332 if (! GlobalMemoryStatusEx(&ms
))
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))
3348 #elif defined(HAVE_SYSCTL) && defined(HW_PHYSMEM)
3349 /* On some systems (like FreeBSD I hope) you can use a size_t with
3352 size_t len
= sizeof(memsize
);
3353 int mib
[2] = {CTL_HW
, HW_USERMEM
};
3354 if (sysctl(mib
,2,&memsize
,&len
,NULL
,0))
3360 /* I have no clue. */
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();
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 */
3383 *mem_out
= mem_cached
;
3385 /* LCOV_EXCL_STOP */
3388 #if SIZE_MAX != UINT64_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
3397 *mem_out
= mem_cached
= (size_t) m
;
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.
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
);
3416 #elif defined(_WIN32)
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();
3434 goto done
; /* Can't actually read ctrl-c this way. */
3441 ch
= _getwch(); /* Ignore; this is a function or arrow key */
3451 #ifndef WC_ERR_INVALID_CHARS
3452 #define WC_ERR_INVALID_CHARS 0x80
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),
3466 tor_assert(r
< (int)buflen
);
3471 SecureZeroMemory(buf
, sizeof(wchar_t)*buflen
);
3475 #error "No implementation for tor_getpass found!"
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. */
3482 tor_get_avail_disk_space(const char *path
)
3487 memset(&st
, 0, sizeof(st
));
3489 r
= statvfs(path
, &st
);
3493 int64_t result
= st
.f_bavail
;
3495 result
*= st
.f_frsize
;
3496 } else if (st
.f_bsize
) {
3497 result
*= st
.f_bsize
;
3503 #elif defined(_WIN32)
3504 ULARGE_INTEGER freeBytesAvail
;
3507 ok
= GetDiskFreeSpaceEx(path
, &freeBytesAvail
, NULL
, NULL
);
3511 return (int64_t)freeBytesAvail
.QuadPart
;