1 /* Copyright (c) 2003-2004, Roger Dingledine
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2016, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
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 #if defined(HAVE_SYS_MMAN_H) || defined(RUNNING_DOXYGEN)
208 /** Try to create a memory mapping for <b>filename</b> and return it. On
209 * failure, return NULL. Sets errno properly, using ERANGE to mean
212 tor_mmap_file(const char *filename
)
214 int fd
; /* router file */
216 int page_size
, result
;
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 * Should we check for weird crap like mmapping a named pipe here,
247 * or just wait for if (!size) below to fail?
249 /* ensure page alignment */
250 page_size
= getpagesize();
251 size
+= (size
%page_size
) ? page_size
-(size
%page_size
) : 0;
254 /* Zero-length file. If we call mmap on it, it will succeed but
255 * return NULL, and bad things will happen. So just fail. */
256 log_info(LD_FS
,"File \"%s\" is empty. Ignoring.",filename
);
262 string
= mmap(0, size
, PROT_READ
, MAP_PRIVATE
, fd
, 0);
264 if (string
== MAP_FAILED
) {
265 int save_errno
= errno
;
266 log_warn(LD_FS
,"Could not mmap file \"%s\": %s", filename
,
272 res
= tor_malloc_zero(sizeof(tor_mmap_t
));
274 res
->size
= filesize
;
275 res
->mapping_size
= size
;
279 /** Release storage held for a memory mapping; returns 0 on success,
280 * or -1 on failure (and logs a warning). */
282 tor_munmap_file(tor_mmap_t
*handle
)
289 res
= munmap((char*)handle
->data
, handle
->mapping_size
);
291 /* munmap() succeeded */
294 log_warn(LD_FS
, "Failed to munmap() in tor_munmap_file(): %s",
301 #elif defined(_WIN32)
303 tor_mmap_file(const char *filename
)
305 TCHAR tfilename
[MAX_PATH
]= {0};
306 tor_mmap_t
*res
= tor_malloc_zero(sizeof(tor_mmap_t
));
308 HANDLE file_handle
= INVALID_HANDLE_VALUE
;
309 DWORD size_low
, size_high
;
311 res
->mmap_handle
= NULL
;
313 mbstowcs(tfilename
,filename
,MAX_PATH
);
315 strlcpy(tfilename
,filename
,MAX_PATH
);
317 file_handle
= CreateFile(tfilename
,
318 GENERIC_READ
, FILE_SHARE_READ
,
321 FILE_ATTRIBUTE_NORMAL
,
324 if (file_handle
== INVALID_HANDLE_VALUE
)
327 size_low
= GetFileSize(file_handle
, &size_high
);
329 if (size_low
== INVALID_FILE_SIZE
&& GetLastError() != NO_ERROR
) {
330 log_warn(LD_FS
,"Error getting size of \"%s\".",filename
);
333 if (size_low
== 0 && size_high
== 0) {
334 log_info(LD_FS
,"File \"%s\" is empty. Ignoring.",filename
);
338 real_size
= (((uint64_t)size_high
)<<32) | size_low
;
339 if (real_size
> SIZE_MAX
) {
340 log_warn(LD_FS
,"File \"%s\" is too big to map; not trying.",filename
);
343 res
->size
= real_size
;
345 res
->mmap_handle
= CreateFileMapping(file_handle
,
351 if (res
->mmap_handle
== NULL
)
353 res
->data
= (char*) MapViewOfFile(res
->mmap_handle
,
359 CloseHandle(file_handle
);
362 DWORD e
= GetLastError();
363 int severity
= (e
== ERROR_FILE_NOT_FOUND
|| e
== ERROR_PATH_NOT_FOUND
) ?
365 char *msg
= format_win32_error(e
);
366 log_fn(severity
, LD_FS
, "Couldn't mmap file \"%s\": %s", filename
, msg
);
368 if (e
== ERROR_FILE_NOT_FOUND
|| e
== ERROR_PATH_NOT_FOUND
)
376 if (file_handle
!= INVALID_HANDLE_VALUE
)
377 CloseHandle(file_handle
);
378 tor_munmap_file(res
);
382 /* Unmap the file, and return 0 for success or -1 for failure */
384 tor_munmap_file(tor_mmap_t
*handle
)
390 /* This is an ugly cast, but without it, "data" in struct tor_mmap_t would
391 have to be redefined as non-const. */
392 BOOL ok
= UnmapViewOfFile( (LPVOID
) handle
->data
);
394 log_warn(LD_FS
, "Failed to UnmapViewOfFile() in tor_munmap_file(): %d",
395 (int)GetLastError());
399 if (handle
->mmap_handle
!= NULL
)
400 CloseHandle(handle
->mmap_handle
);
407 tor_mmap_file(const char *filename
)
410 char *res
= read_file_to_str(filename
, RFTS_BIN
|RFTS_IGNORE_MISSING
, &st
);
414 handle
= tor_malloc_zero(sizeof(tor_mmap_t
));
416 handle
->size
= st
.st_size
;
420 /** Unmap the file mapped with tor_mmap_file(), and return 0 for success
425 tor_munmap_file(tor_mmap_t
*handle
)
431 d
= (char*)handle
->data
;
433 memwipe(handle
, 0, sizeof(tor_mmap_t
));
436 /* Can't fail in this mmap()/munmap()-free case */
441 /** Replacement for snprintf. Differs from platform snprintf in two
442 * ways: First, always NUL-terminates its output. Second, always
443 * returns -1 if the result is truncated. (Note that this return
444 * behavior does <i>not</i> conform to C99; it just happens to be
445 * easier to emulate "return -1" with conformant implementations than
446 * it is to emulate "return number that would be written" with
447 * non-conformant implementations.) */
449 tor_snprintf(char *str
, size_t size
, const char *format
, ...)
454 r
= tor_vsnprintf(str
,size
,format
,ap
);
459 /** Replacement for vsnprintf; behavior differs as tor_snprintf differs from
463 tor_vsnprintf(char *str
, size_t size
, const char *format
, va_list args
)
467 return -1; /* no place for the NUL */
468 if (size
> SIZE_T_CEILING
)
471 r
= _vsnprintf(str
, size
, format
, args
);
473 r
= vsnprintf(str
, size
, format
, args
);
476 if (r
< 0 || r
>= (ssize_t
)size
)
482 * Portable asprintf implementation. Does a printf() into a newly malloc'd
483 * string. Sets *<b>strp</b> to this string, and returns its length (not
484 * including the terminating NUL character).
486 * You can treat this function as if its implementation were something like
488 char buf[_INFINITY_];
489 tor_snprintf(buf, sizeof(buf), fmt, args);
490 *strp = tor_strdup(buf);
491 return strlen(*strp):
493 * Where _INFINITY_ is an imaginary constant so big that any string can fit
497 tor_asprintf(char **strp
, const char *fmt
, ...)
502 r
= tor_vasprintf(strp
, fmt
, args
);
504 if (!*strp
|| r
< 0) {
505 /* LCOV_EXCL_START */
506 log_err(LD_BUG
, "Internal error in asprintf");
514 * Portable vasprintf implementation. Does a printf() into a newly malloc'd
515 * string. Differs from regular vasprintf in the same ways that
516 * tor_asprintf() differs from regular asprintf.
519 tor_vasprintf(char **strp
, const char *fmt
, va_list args
)
521 /* use a temporary variable in case *strp is in args. */
523 #ifdef HAVE_VASPRINTF
524 /* If the platform gives us one, use it. */
525 int r
= vasprintf(&strp_tmp
, fmt
, args
);
531 #elif defined(HAVE__VSCPRINTF)
532 /* On Windows, _vsnprintf won't tell us the length of the string if it
533 * overflows, so we need to use _vcsprintf to tell how much to allocate */
536 va_copy(tmp_args
, args
);
537 len
= _vscprintf(fmt
, tmp_args
);
543 strp_tmp
= tor_malloc(len
+ 1);
544 r
= _vsnprintf(strp_tmp
, len
+1, fmt
, args
);
553 /* Everywhere else, we have a decent vsnprintf that tells us how many
554 * characters we need. We give it a try on a short buffer first, since
555 * it might be nice to avoid the second vsnprintf call.
560 va_copy(tmp_args
, args
);
561 /* vsnprintf() was properly checked but tor_vsnprintf() available so
563 len
= tor_vsnprintf(buf
, sizeof(buf
), fmt
, tmp_args
);
565 if (len
< (int)sizeof(buf
)) {
566 *strp
= tor_strdup(buf
);
569 strp_tmp
= tor_malloc(len
+1);
570 /* use of tor_vsnprintf() will ensure string is null terminated */
571 r
= tor_vsnprintf(strp_tmp
, len
+1, fmt
, args
);
582 /** Given <b>hlen</b> bytes at <b>haystack</b> and <b>nlen</b> bytes at
583 * <b>needle</b>, return a pointer to the first occurrence of the needle
584 * within the haystack, or NULL if there is no such occurrence.
586 * This function is <em>not</em> timing-safe.
588 * Requires that <b>nlen</b> be greater than zero.
591 tor_memmem(const void *_haystack
, size_t hlen
,
592 const void *_needle
, size_t nlen
)
594 #if defined(HAVE_MEMMEM) && (!defined(__GNUC__) || __GNUC__ >= 2)
596 return memmem(_haystack
, hlen
, _needle
, nlen
);
598 /* This isn't as fast as the GLIBC implementation, but it doesn't need to
600 const char *p
, *last_possible_start
;
601 const char *haystack
= (const char*)_haystack
;
602 const char *needle
= (const char*)_needle
;
610 /* Last position at which the needle could start. */
611 last_possible_start
= haystack
+ hlen
- nlen
;
612 first
= *(const char*)needle
;
613 while ((p
= memchr(p
, first
, last_possible_start
+ 1 - p
))) {
614 if (fast_memeq(p
, needle
, nlen
))
616 if (++p
> last_possible_start
) {
617 /* This comparison shouldn't be necessary, since if p was previously
618 * equal to last_possible_start, the next memchr call would be
619 * "memchr(p, first, 0)", which will return NULL. But it clarifies the
629 * Tables to implement ctypes-replacement TOR_IS*() functions. Each table
630 * has 256 bits to look up whether a character is in some set or not. This
631 * fails on non-ASCII platforms, but it is hard to find a platform whose
632 * character set is not a superset of ASCII nowadays. */
635 const uint32_t TOR_ISALPHA_TABLE
[8] =
636 { 0, 0, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
637 const uint32_t TOR_ISALNUM_TABLE
[8] =
638 { 0, 0x3ff0000, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
639 const uint32_t TOR_ISSPACE_TABLE
[8] = { 0x3e00, 0x1, 0, 0, 0, 0, 0, 0 };
640 const uint32_t TOR_ISXDIGIT_TABLE
[8] =
641 { 0, 0x3ff0000, 0x7e, 0x7e, 0, 0, 0, 0 };
642 const uint32_t TOR_ISDIGIT_TABLE
[8] = { 0, 0x3ff0000, 0, 0, 0, 0, 0, 0 };
643 const uint32_t TOR_ISPRINT_TABLE
[8] =
644 { 0, 0xffffffff, 0xffffffff, 0x7fffffff, 0, 0, 0, 0x0 };
645 const uint32_t TOR_ISUPPER_TABLE
[8] = { 0, 0, 0x7fffffe, 0, 0, 0, 0, 0 };
646 const uint32_t TOR_ISLOWER_TABLE
[8] = { 0, 0, 0, 0x7fffffe, 0, 0, 0, 0 };
648 /** Upper-casing and lowercasing tables to map characters to upper/lowercase
649 * equivalents. Used by tor_toupper() and tor_tolower(). */
651 const uint8_t TOR_TOUPPER_TABLE
[256] = {
652 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
653 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
654 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
655 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
656 64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
657 80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
658 96,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
659 80,81,82,83,84,85,86,87,88,89,90,123,124,125,126,127,
660 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
661 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
662 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
663 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
664 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
665 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
666 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
667 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
669 const uint8_t TOR_TOLOWER_TABLE
[256] = {
670 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
671 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
672 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
673 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
674 64,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
675 112,113,114,115,116,117,118,119,120,121,122,91,92,93,94,95,
676 96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
677 112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
678 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
679 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
680 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
681 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
682 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
683 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
684 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
685 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
689 /** Helper for tor_strtok_r_impl: Advances cp past all characters in
690 * <b>sep</b>, and returns its new value. */
692 strtok_helper(char *cp
, const char *sep
)
695 while (*cp
&& strchr(sep
, *cp
))
698 while (*cp
&& *cp
== *sep
)
704 /** Implementation of strtok_r for platforms whose coders haven't figured out
705 * how to write one. Hey, retrograde libc developers! You can use this code
708 tor_strtok_r_impl(char *str
, const char *sep
, char **lasts
)
713 str
= strtok_helper(str
, sep
);
716 start
= cp
= *lasts
= str
;
717 } else if (!*lasts
|| !**lasts
) {
724 while (*cp
&& !strchr(sep
, *cp
))
727 cp
= strchr(cp
, *sep
);
734 *lasts
= strtok_helper(cp
, sep
);
740 /** Take a filename and return a pointer to its final element. This
741 * function is called on __FILE__ to fix a MSVC nit where __FILE__
742 * contains the full path to the file. This is bad, because it
743 * confuses users to find the home directory of the person who
744 * compiled the binary in their warning messages.
747 tor_fix_source_file(const char *fname
)
749 const char *cp1
, *cp2
, *r
;
750 cp1
= strrchr(fname
, '/');
751 cp2
= strrchr(fname
, '\\');
753 r
= (cp1
<cp2
)?(cp2
+1):(cp1
+1);
766 * Read a 16-bit value beginning at <b>cp</b>. Equivalent to
767 * *(uint16_t*)(cp), but will not cause segfaults on platforms that forbid
768 * unaligned memory access.
771 get_uint16(const void *cp
)
778 * Read a 32-bit value beginning at <b>cp</b>. Equivalent to
779 * *(uint32_t*)(cp), but will not cause segfaults on platforms that forbid
780 * unaligned memory access.
783 get_uint32(const void *cp
)
790 * Read a 64-bit value beginning at <b>cp</b>. Equivalent to
791 * *(uint64_t*)(cp), but will not cause segfaults on platforms that forbid
792 * unaligned memory access.
795 get_uint64(const void *cp
)
803 * Set a 16-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
804 * *(uint16_t*)(cp) = v, but will not cause segfaults on platforms that forbid
805 * unaligned memory access. */
807 set_uint16(void *cp
, uint16_t v
)
812 * Set a 32-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
813 * *(uint32_t*)(cp) = v, but will not cause segfaults on platforms that forbid
814 * unaligned memory access. */
816 set_uint32(void *cp
, uint32_t v
)
821 * Set a 64-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
822 * *(uint64_t*)(cp) = v, but will not cause segfaults on platforms that forbid
823 * unaligned memory access. */
825 set_uint64(void *cp
, uint64_t v
)
831 * Rename the file <b>from</b> to the file <b>to</b>. On Unix, this is
832 * the same as rename(2). On windows, this removes <b>to</b> first if
834 * Returns 0 on success. Returns -1 and sets errno on failure.
837 replace_file(const char *from
, const char *to
)
840 return tor_rename(from
, to
);
842 switch (file_status(to
))
848 if (unlink(to
)) return -1;
856 return tor_rename(from
,to
);
860 /** Change <b>fname</b>'s modification time to now. */
862 touch_file(const char *fname
)
864 if (utime(fname
, NULL
)!=0)
869 /** Represents a lockfile on which we hold the lock. */
870 struct tor_lockfile_t
{
871 /** Name of the file */
873 /** File descriptor used to hold the file open */
877 /** Try to get a lock on the lockfile <b>filename</b>, creating it as
878 * necessary. If someone else has the lock and <b>blocking</b> is true,
879 * wait until the lock is available. Otherwise return immediately whether
880 * we succeeded or not.
882 * Set *<b>locked_out</b> to true if somebody else had the lock, and to false
885 * Return a <b>tor_lockfile_t</b> on success, NULL on failure.
887 * (Implementation note: because we need to fall back to fcntl on some
888 * platforms, these locks are per-process, not per-thread. If you want
889 * to do in-process locking, use tor_mutex_t like a normal person.
890 * On Windows, when <b>blocking</b> is true, the maximum time that
891 * is actually waited is 10 seconds, after which NULL is returned
892 * and <b>locked_out</b> is set to 1.)
895 tor_lockfile_lock(const char *filename
, int blocking
, int *locked_out
)
897 tor_lockfile_t
*result
;
901 log_info(LD_FS
, "Locking \"%s\"", filename
);
902 fd
= tor_open_cloexec(filename
, O_RDWR
|O_CREAT
|O_TRUNC
, 0600);
904 log_warn(LD_FS
,"Couldn't open \"%s\" for locking: %s", filename
,
910 _lseek(fd
, 0, SEEK_SET
);
911 if (_locking(fd
, blocking
? _LK_LOCK
: _LK_NBLCK
, 1) < 0) {
912 if (errno
!= EACCES
&& errno
!= EDEADLOCK
)
913 log_warn(LD_FS
,"Couldn't lock \"%s\": %s", filename
, strerror(errno
));
919 #elif defined(HAVE_FLOCK)
920 if (flock(fd
, LOCK_EX
|(blocking
? 0 : LOCK_NB
)) < 0) {
921 if (errno
!= EWOULDBLOCK
)
922 log_warn(LD_FS
,"Couldn't lock \"%s\": %s", filename
, strerror(errno
));
931 memset(&lock
, 0, sizeof(lock
));
932 lock
.l_type
= F_WRLCK
;
933 lock
.l_whence
= SEEK_SET
;
934 if (fcntl(fd
, blocking
? F_SETLKW
: F_SETLK
, &lock
) < 0) {
935 if (errno
!= EACCES
&& errno
!= EAGAIN
)
936 log_warn(LD_FS
, "Couldn't lock \"%s\": %s", filename
, strerror(errno
));
945 result
= tor_malloc(sizeof(tor_lockfile_t
));
946 result
->filename
= tor_strdup(filename
);
951 /** Release the lock held as <b>lockfile</b>. */
953 tor_lockfile_unlock(tor_lockfile_t
*lockfile
)
955 tor_assert(lockfile
);
957 log_info(LD_FS
, "Unlocking \"%s\"", lockfile
->filename
);
959 _lseek(lockfile
->fd
, 0, SEEK_SET
);
960 if (_locking(lockfile
->fd
, _LK_UNLCK
, 1) < 0) {
961 log_warn(LD_FS
,"Error unlocking \"%s\": %s", lockfile
->filename
,
964 #elif defined(HAVE_FLOCK)
965 if (flock(lockfile
->fd
, LOCK_UN
) < 0) {
966 log_warn(LD_FS
, "Error unlocking \"%s\": %s", lockfile
->filename
,
970 /* Closing the lockfile is sufficient. */
975 tor_free(lockfile
->filename
);
980 /** Some old versions of Unix didn't define constants for these values,
981 * and instead expect you to say 0, 1, or 2. */
993 /** Return the position of <b>fd</b> with respect to the start of the file. */
995 tor_fd_getpos(int fd
)
998 return (off_t
) _lseek(fd
, 0, SEEK_CUR
);
1000 return (off_t
) lseek(fd
, 0, SEEK_CUR
);
1004 /** Move <b>fd</b> to the end of the file. Return -1 on error, 0 on success.
1005 * If the file is a pipe, do nothing and succeed.
1008 tor_fd_seekend(int fd
)
1011 return _lseek(fd
, 0, SEEK_END
) < 0 ? -1 : 0;
1013 off_t rc
= lseek(fd
, 0, SEEK_END
) < 0 ? -1 : 0;
1015 /* If we get an error and ESPIPE, then it's a pipe or a socket of a fifo:
1016 * no need to worry. */
1017 if (rc
< 0 && errno
== ESPIPE
)
1020 return (rc
< 0) ? -1 : 0;
1024 /** Move <b>fd</b> to position <b>pos</b> in the file. Return -1 on error, 0
1027 tor_fd_setpos(int fd
, off_t pos
)
1030 return _lseek(fd
, pos
, SEEK_SET
) < 0 ? -1 : 0;
1032 return lseek(fd
, pos
, SEEK_SET
) < 0 ? -1 : 0;
1036 /** Replacement for ftruncate(fd, 0): move to the front of the file and remove
1037 * all the rest of the file. Return -1 on error, 0 on success. */
1039 tor_ftruncate(int fd
)
1041 /* Rumor has it that some versions of ftruncate do not move the file pointer.
1043 if (tor_fd_setpos(fd
, 0) < 0)
1047 return _chsize(fd
, 0);
1049 return ftruncate(fd
, 0);
1053 #undef DEBUG_SOCKET_COUNTING
1054 #ifdef DEBUG_SOCKET_COUNTING
1055 /** A bitarray of all fds that should be passed to tor_socket_close(). Only
1056 * used if DEBUG_SOCKET_COUNTING is defined. */
1057 static bitarray_t
*open_sockets
= NULL
;
1058 /** The size of <b>open_sockets</b>, in bits. */
1059 static int max_socket
= -1;
1062 /** Count of number of sockets currently open. (Undercounts sockets opened by
1063 * eventdns and libevent.) */
1064 static int n_sockets_open
= 0;
1066 /** Mutex to protect open_sockets, max_socket, and n_sockets_open. */
1067 static tor_mutex_t
*socket_accounting_mutex
= NULL
;
1069 /** Helper: acquire the socket accounting lock. */
1071 socket_accounting_lock(void)
1073 if (PREDICT_UNLIKELY(!socket_accounting_mutex
))
1074 socket_accounting_mutex
= tor_mutex_new();
1075 tor_mutex_acquire(socket_accounting_mutex
);
1078 /** Helper: release the socket accounting lock. */
1080 socket_accounting_unlock(void)
1082 tor_mutex_release(socket_accounting_mutex
);
1085 /** As close(), but guaranteed to work for sockets across platforms (including
1086 * Windows, where close()ing a socket doesn't work. Returns 0 on success and
1087 * the socket error code on failure. */
1089 tor_close_socket_simple(tor_socket_t s
)
1093 /* On Windows, you have to call close() on fds returned by open(),
1094 * and closesocket() on fds returned by socket(). On Unix, everything
1095 * gets close()'d. We abstract this difference by always using
1096 * tor_close_socket to close sockets, and always using close() on
1106 int err
= tor_socket_errno(-1);
1107 log_info(LD_NET
, "Close returned an error: %s", tor_socket_strerror(err
));
1114 /** As tor_close_socket_simple(), but keeps track of the number
1115 * of open sockets. Returns 0 on success, -1 on failure. */
1117 tor_close_socket
,(tor_socket_t s
))
1119 int r
= tor_close_socket_simple(s
);
1121 socket_accounting_lock();
1122 #ifdef DEBUG_SOCKET_COUNTING
1123 if (s
> max_socket
|| ! bitarray_is_set(open_sockets
, s
)) {
1124 log_warn(LD_BUG
, "Closing a socket (%d) that wasn't returned by tor_open_"
1125 "socket(), or that was already closed or something.", s
);
1127 tor_assert(open_sockets
&& s
<= max_socket
);
1128 bitarray_clear(open_sockets
, s
);
1135 if (r
!= WSAENOTSOCK
)
1139 --n_sockets_open
; // LCOV_EXCL_LINE -- EIO and EINTR too hard to force.
1144 tor_assert_nonfatal(n_sockets_open
>= 0);
1145 socket_accounting_unlock();
1150 #ifdef DEBUG_SOCKET_COUNTING
1151 /** Helper: if DEBUG_SOCKET_COUNTING is enabled, remember that <b>s</b> is
1152 * now an open socket. */
1154 mark_socket_open(tor_socket_t s
)
1156 /* XXXX This bitarray business will NOT work on windows: sockets aren't
1157 small ints there. */
1158 if (s
> max_socket
) {
1159 if (max_socket
== -1) {
1160 open_sockets
= bitarray_init_zero(s
+128);
1163 open_sockets
= bitarray_expand(open_sockets
, max_socket
, s
+128);
1167 if (bitarray_is_set(open_sockets
, s
)) {
1168 log_warn(LD_BUG
, "I thought that %d was already open, but socket() just "
1169 "gave it to me!", s
);
1171 bitarray_set(open_sockets
, s
);
1174 #define mark_socket_open(s) STMT_NIL
1178 /** As socket(), but counts the number of open sockets. */
1179 MOCK_IMPL(tor_socket_t
,
1180 tor_open_socket
,(int domain
, int type
, int protocol
))
1182 return tor_open_socket_with_extensions(domain
, type
, protocol
, 1, 0);
1185 /** Mockable wrapper for connect(). */
1186 MOCK_IMPL(tor_socket_t
,
1187 tor_connect_socket
,(tor_socket_t sock
, const struct sockaddr
*address
,
1188 socklen_t address_len
))
1190 return connect(sock
,address
,address_len
);
1193 /** As socket(), but creates a nonblocking socket and
1194 * counts the number of open sockets. */
1196 tor_open_socket_nonblocking(int domain
, int type
, int protocol
)
1198 return tor_open_socket_with_extensions(domain
, type
, protocol
, 1, 1);
1201 /** As socket(), but counts the number of open sockets and handles
1202 * socket creation with either of SOCK_CLOEXEC and SOCK_NONBLOCK specified.
1203 * <b>cloexec</b> and <b>nonblock</b> should be either 0 or 1 to indicate
1204 * if the corresponding extension should be used.*/
1206 tor_open_socket_with_extensions(int domain
, int type
, int protocol
,
1207 int cloexec
, int nonblock
)
1211 /* We are about to create a new file descriptor so make sure we have
1212 * enough of them. */
1213 if (get_n_open_sockets() >= max_sockets
- 1) {
1215 WSASetLastError(WSAEMFILE
);
1219 return TOR_INVALID_SOCKET
;
1222 #if defined(SOCK_CLOEXEC) && defined(SOCK_NONBLOCK)
1223 int ext_flags
= (cloexec
? SOCK_CLOEXEC
: 0) |
1224 (nonblock
? SOCK_NONBLOCK
: 0);
1225 s
= socket(domain
, type
|ext_flags
, protocol
);
1228 /* If we got an error, see if it is EINVAL. EINVAL might indicate that,
1229 * even though we were built on a system with SOCK_CLOEXEC and SOCK_NONBLOCK
1230 * support, we are running on one without. */
1231 if (errno
!= EINVAL
)
1233 #endif /* SOCK_CLOEXEC && SOCK_NONBLOCK */
1235 s
= socket(domain
, type
, protocol
);
1239 #if defined(FD_CLOEXEC)
1241 if (fcntl(s
, F_SETFD
, FD_CLOEXEC
) == -1) {
1242 log_warn(LD_FS
,"Couldn't set FD_CLOEXEC: %s", strerror(errno
));
1243 tor_close_socket_simple(s
);
1244 return TOR_INVALID_SOCKET
;
1252 if (set_socket_nonblocking(s
) == -1) {
1253 tor_close_socket_simple(s
);
1254 return TOR_INVALID_SOCKET
;
1258 goto socket_ok
; /* So that socket_ok will not be unused. */
1261 socket_accounting_lock();
1263 mark_socket_open(s
);
1264 socket_accounting_unlock();
1268 /** As accept(), but counts the number of open sockets. */
1270 tor_accept_socket(tor_socket_t sockfd
, struct sockaddr
*addr
, socklen_t
*len
)
1272 return tor_accept_socket_with_extensions(sockfd
, addr
, len
, 1, 0);
1275 /** As accept(), but returns a nonblocking socket and
1276 * counts the number of open sockets. */
1278 tor_accept_socket_nonblocking(tor_socket_t sockfd
, struct sockaddr
*addr
,
1281 return tor_accept_socket_with_extensions(sockfd
, addr
, len
, 1, 1);
1284 /** As accept(), but counts the number of open sockets and handles
1285 * socket creation with either of SOCK_CLOEXEC and SOCK_NONBLOCK specified.
1286 * <b>cloexec</b> and <b>nonblock</b> should be either 0 or 1 to indicate
1287 * if the corresponding extension should be used.*/
1289 tor_accept_socket_with_extensions(tor_socket_t sockfd
, struct sockaddr
*addr
,
1290 socklen_t
*len
, int cloexec
, int nonblock
)
1294 /* We are about to create a new file descriptor so make sure we have
1295 * enough of them. */
1296 if (get_n_open_sockets() >= max_sockets
- 1) {
1298 WSASetLastError(WSAEMFILE
);
1302 return TOR_INVALID_SOCKET
;
1305 #if defined(HAVE_ACCEPT4) && defined(SOCK_CLOEXEC) && defined(SOCK_NONBLOCK)
1306 int ext_flags
= (cloexec
? SOCK_CLOEXEC
: 0) |
1307 (nonblock
? SOCK_NONBLOCK
: 0);
1308 s
= accept4(sockfd
, addr
, len
, ext_flags
);
1311 /* If we got an error, see if it is ENOSYS. ENOSYS indicates that,
1312 * even though we were built on a system with accept4 support, we
1313 * are running on one without. Also, check for EINVAL, which indicates that
1314 * we are missing SOCK_CLOEXEC/SOCK_NONBLOCK support. */
1315 if (errno
!= EINVAL
&& errno
!= ENOSYS
)
1319 s
= accept(sockfd
, addr
, len
);
1323 #if defined(FD_CLOEXEC)
1325 if (fcntl(s
, F_SETFD
, FD_CLOEXEC
) == -1) {
1326 log_warn(LD_NET
, "Couldn't set FD_CLOEXEC: %s", strerror(errno
));
1327 tor_close_socket_simple(s
);
1328 return TOR_INVALID_SOCKET
;
1336 if (set_socket_nonblocking(s
) == -1) {
1337 tor_close_socket_simple(s
);
1338 return TOR_INVALID_SOCKET
;
1342 goto socket_ok
; /* So that socket_ok will not be unused. */
1345 socket_accounting_lock();
1347 mark_socket_open(s
);
1348 socket_accounting_unlock();
1352 /** Return the number of sockets we currently have opened. */
1354 get_n_open_sockets(void)
1357 socket_accounting_lock();
1359 socket_accounting_unlock();
1363 /** Mockable wrapper for getsockname(). */
1365 tor_getsockname
,(tor_socket_t sock
, struct sockaddr
*address
,
1366 socklen_t
*address_len
))
1368 return getsockname(sock
, address
, address_len
);
1371 /** Turn <b>socket</b> into a nonblocking socket. Return 0 on success, -1
1375 set_socket_nonblocking(tor_socket_t sock
)
1378 unsigned long nonblocking
= 1;
1379 ioctlsocket(sock
, FIONBIO
, (unsigned long*) &nonblocking
);
1383 flags
= fcntl(sock
, F_GETFL
, 0);
1385 log_warn(LD_NET
, "Couldn't get file status flags: %s", strerror(errno
));
1388 flags
|= O_NONBLOCK
;
1389 if (fcntl(sock
, F_SETFL
, flags
) == -1) {
1390 log_warn(LD_NET
, "Couldn't set file status flags: %s", strerror(errno
));
1399 * Allocate a pair of connected sockets. (Like socketpair(family,
1400 * type,protocol,fd), but works on systems that don't have
1403 * Currently, only (AF_UNIX, SOCK_STREAM, 0) sockets are supported.
1405 * Note that on systems without socketpair, this call will fail if
1406 * localhost is inaccessible (for example, if the networking
1407 * stack is down). And even if it succeeds, the socket pair will not
1408 * be able to read while localhost is down later (the socket pair may
1409 * even close, depending on OS-specific timeouts).
1411 * Returns 0 on success and -errno on failure; do not rely on the value
1412 * of errno or WSAGetLastError().
1414 /* It would be nicer just to set errno, but that won't work for windows. */
1416 tor_socketpair(int family
, int type
, int protocol
, tor_socket_t fd
[2])
1418 //don't use win32 socketpairs (they are always bad)
1419 #if defined(HAVE_SOCKETPAIR) && !defined(_WIN32)
1423 r
= socketpair(family
, type
|SOCK_CLOEXEC
, protocol
, fd
);
1426 /* If we got an error, see if it is EINVAL. EINVAL might indicate that,
1427 * even though we were built on a system with SOCK_CLOEXEC support, we
1428 * are running on one without. */
1429 if (errno
!= EINVAL
)
1433 r
= socketpair(family
, type
, protocol
, fd
);
1437 #if defined(FD_CLOEXEC)
1438 if (SOCKET_OK(fd
[0])) {
1439 r
= fcntl(fd
[0], F_SETFD
, FD_CLOEXEC
);
1446 if (SOCKET_OK(fd
[1])) {
1447 r
= fcntl(fd
[1], F_SETFD
, FD_CLOEXEC
);
1455 goto sockets_ok
; /* So that sockets_ok will not be unused. */
1458 socket_accounting_lock();
1459 if (SOCKET_OK(fd
[0])) {
1461 mark_socket_open(fd
[0]);
1463 if (SOCKET_OK(fd
[1])) {
1465 mark_socket_open(fd
[1]);
1467 socket_accounting_unlock();
1471 return tor_ersatz_socketpair(family
, type
, protocol
, fd
);
1475 #ifdef NEED_ERSATZ_SOCKETPAIR
1477 static inline socklen_t
1478 SIZEOF_SOCKADDR(int domain
)
1482 return sizeof(struct sockaddr_in
);
1484 return sizeof(struct sockaddr_in6
);
1491 * Helper used to implement socketpair on systems that lack it, by
1492 * making a direct connection to localhost.
1495 tor_ersatz_socketpair(int family
, int type
, int protocol
, tor_socket_t fd
[2])
1497 /* This socketpair does not work when localhost is down. So
1498 * it's really not the same thing at all. But it's close enough
1499 * for now, and really, when localhost is down sometimes, we
1500 * have other problems too.
1502 tor_socket_t listener
= TOR_INVALID_SOCKET
;
1503 tor_socket_t connector
= TOR_INVALID_SOCKET
;
1504 tor_socket_t acceptor
= TOR_INVALID_SOCKET
;
1505 tor_addr_t listen_tor_addr
;
1506 struct sockaddr_storage connect_addr_ss
, listen_addr_ss
;
1507 struct sockaddr
*listen_addr
= (struct sockaddr
*) &listen_addr_ss
;
1508 uint16_t listen_port
= 0;
1509 tor_addr_t connect_tor_addr
;
1510 uint16_t connect_port
= 0;
1511 struct sockaddr
*connect_addr
= (struct sockaddr
*) &connect_addr_ss
;
1513 int saved_errno
= -1;
1514 int ersatz_domain
= AF_INET
;
1516 memset(&connect_tor_addr
, 0, sizeof(connect_tor_addr
));
1517 memset(&connect_addr_ss
, 0, sizeof(connect_addr_ss
));
1518 memset(&listen_tor_addr
, 0, sizeof(listen_tor_addr
));
1519 memset(&listen_addr_ss
, 0, sizeof(listen_addr_ss
));
1523 || family
!= AF_UNIX
1527 return -WSAEAFNOSUPPORT
;
1529 return -EAFNOSUPPORT
;
1536 listener
= tor_open_socket(ersatz_domain
, type
, 0);
1537 if (!SOCKET_OK(listener
)) {
1538 int first_errno
= tor_socket_errno(-1);
1539 if (first_errno
== SOCK_ERRNO(EPROTONOSUPPORT
)
1540 && ersatz_domain
== AF_INET
) {
1541 /* Assume we're on an IPv6-only system */
1542 ersatz_domain
= AF_INET6
;
1543 listener
= tor_open_socket(ersatz_domain
, type
, 0);
1544 if (!SOCKET_OK(listener
)) {
1545 /* Keep the previous behaviour, which was to return the IPv4 error.
1546 * (This may be less informative on IPv6-only systems.)
1547 * XX/teor - is there a better way to decide which errno to return?
1548 * (I doubt we care much either way, once there is an error.)
1550 return -first_errno
;
1554 /* If there is no 127.0.0.1 or ::1, this will and must fail. Otherwise, we
1555 * risk exposing a socketpair on a routable IP address. (Some BSD jails
1556 * use a routable address for localhost. Fortunately, they have the real
1557 * AF_UNIX socketpair.) */
1558 if (ersatz_domain
== AF_INET
) {
1559 tor_addr_from_ipv4h(&listen_tor_addr
, INADDR_LOOPBACK
);
1561 tor_addr_parse(&listen_tor_addr
, "[::1]");
1563 tor_assert(tor_addr_is_loopback(&listen_tor_addr
));
1564 size
= tor_addr_to_sockaddr(&listen_tor_addr
,
1565 0 /* kernel chooses port. */,
1567 sizeof(listen_addr_ss
));
1568 if (bind(listener
, listen_addr
, size
) == -1)
1569 goto tidy_up_and_fail
;
1570 if (listen(listener
, 1) == -1)
1571 goto tidy_up_and_fail
;
1573 connector
= tor_open_socket(ersatz_domain
, type
, 0);
1574 if (!SOCKET_OK(connector
))
1575 goto tidy_up_and_fail
;
1576 /* We want to find out the port number to connect to. */
1577 size
= sizeof(connect_addr_ss
);
1578 if (getsockname(listener
, connect_addr
, &size
) == -1)
1579 goto tidy_up_and_fail
;
1580 if (size
!= SIZEOF_SOCKADDR (connect_addr
->sa_family
))
1581 goto abort_tidy_up_and_fail
;
1582 if (connect(connector
, connect_addr
, size
) == -1)
1583 goto tidy_up_and_fail
;
1585 size
= sizeof(listen_addr_ss
);
1586 acceptor
= tor_accept_socket(listener
, listen_addr
, &size
);
1587 if (!SOCKET_OK(acceptor
))
1588 goto tidy_up_and_fail
;
1589 if (size
!= SIZEOF_SOCKADDR(listen_addr
->sa_family
))
1590 goto abort_tidy_up_and_fail
;
1591 /* Now check we are talking to ourself by matching port and host on the
1593 if (getsockname(connector
, connect_addr
, &size
) == -1)
1594 goto tidy_up_and_fail
;
1595 /* Set *_tor_addr and *_port to the address and port that was used */
1596 tor_addr_from_sockaddr(&listen_tor_addr
, listen_addr
, &listen_port
);
1597 tor_addr_from_sockaddr(&connect_tor_addr
, connect_addr
, &connect_port
);
1598 if (size
!= SIZEOF_SOCKADDR (connect_addr
->sa_family
)
1599 || tor_addr_compare(&listen_tor_addr
, &connect_tor_addr
, CMP_SEMANTIC
)
1600 || listen_port
!= connect_port
) {
1601 goto abort_tidy_up_and_fail
;
1603 tor_close_socket(listener
);
1609 abort_tidy_up_and_fail
:
1611 saved_errno
= WSAECONNABORTED
;
1613 saved_errno
= ECONNABORTED
; /* I hope this is portable and appropriate. */
1616 if (saved_errno
< 0)
1617 saved_errno
= errno
;
1618 if (SOCKET_OK(listener
))
1619 tor_close_socket(listener
);
1620 if (SOCKET_OK(connector
))
1621 tor_close_socket(connector
);
1622 if (SOCKET_OK(acceptor
))
1623 tor_close_socket(acceptor
);
1624 return -saved_errno
;
1627 #undef SIZEOF_SOCKADDR
1631 /* Return the maximum number of allowed sockets. */
1633 get_max_sockets(void)
1638 /** Number of extra file descriptors to keep in reserve beyond those that we
1639 * tell Tor it's allowed to use. */
1640 #define ULIMIT_BUFFER 32 /* keep 32 extra fd's beyond ConnLimit_ */
1642 /** Learn the maximum allowed number of file descriptors, and tell the
1643 * system we want to use up to that number. (Some systems have a low soft
1644 * limit, and let us set it higher.) We compute this by finding the largest
1645 * number that we can use.
1647 * If the limit is below the reserved file descriptor value (ULIMIT_BUFFER),
1648 * return -1 and <b>max_out</b> is untouched.
1650 * If we can't find a number greater than or equal to <b>limit</b>, then we
1651 * fail by returning -1 and <b>max_out</b> is untouched.
1653 * If we are unable to set the limit value because of setrlimit() failing,
1654 * return 0 and <b>max_out</b> is set to the current maximum value returned
1657 * Otherwise, return 0 and store the maximum we found inside <b>max_out</b>
1658 * and set <b>max_sockets</b> with that value as well.*/
1660 set_max_file_descriptors(rlim_t limit
, int *max_out
)
1662 if (limit
< ULIMIT_BUFFER
) {
1664 "ConnLimit must be at least %d. Failing.", ULIMIT_BUFFER
);
1668 /* Define some maximum connections values for systems where we cannot
1669 * automatically determine a limit. Re Cygwin, see
1670 * http://archives.seul.org/or/talk/Aug-2006/msg00210.html
1671 * For an iPhone, 9999 should work. For Windows and all other unknown
1672 * systems we use 15000 as the default. */
1673 #ifndef HAVE_GETRLIMIT
1674 #if defined(CYGWIN) || defined(__CYGWIN__)
1675 const char *platform
= "Cygwin";
1676 const unsigned long MAX_CONNECTIONS
= 3200;
1677 #elif defined(_WIN32)
1678 const char *platform
= "Windows";
1679 const unsigned long MAX_CONNECTIONS
= 15000;
1681 const char *platform
= "unknown platforms with no getrlimit()";
1682 const unsigned long MAX_CONNECTIONS
= 15000;
1684 log_fn(LOG_INFO
, LD_NET
,
1685 "This platform is missing getrlimit(). Proceeding.");
1686 if (limit
> MAX_CONNECTIONS
) {
1688 "We do not support more than %lu file descriptors "
1689 "on %s. Tried to raise to %lu.",
1690 (unsigned long)MAX_CONNECTIONS
, platform
, (unsigned long)limit
);
1693 limit
= MAX_CONNECTIONS
;
1694 #else /* HAVE_GETRLIMIT */
1697 if (getrlimit(RLIMIT_NOFILE
, &rlim
) != 0) {
1698 log_warn(LD_NET
, "Could not get maximum number of file descriptors: %s",
1702 if (rlim
.rlim_max
< limit
) {
1703 log_warn(LD_CONFIG
,"We need %lu file descriptors available, and we're "
1704 "limited to %lu. Please change your ulimit -n.",
1705 (unsigned long)limit
, (unsigned long)rlim
.rlim_max
);
1709 if (rlim
.rlim_max
> rlim
.rlim_cur
) {
1710 log_info(LD_NET
,"Raising max file descriptors from %lu to %lu.",
1711 (unsigned long)rlim
.rlim_cur
, (unsigned long)rlim
.rlim_max
);
1713 /* Set the current limit value so if the attempt to set the limit to the
1714 * max fails at least we'll have a valid value of maximum sockets. */
1715 *max_out
= max_sockets
= (int)rlim
.rlim_cur
- ULIMIT_BUFFER
;
1716 rlim
.rlim_cur
= rlim
.rlim_max
;
1718 if (setrlimit(RLIMIT_NOFILE
, &rlim
) != 0) {
1719 int couldnt_set
= 1;
1720 const int setrlimit_errno
= errno
;
1722 uint64_t try_limit
= OPEN_MAX
- ULIMIT_BUFFER
;
1723 if (errno
== EINVAL
&& try_limit
< (uint64_t) rlim
.rlim_cur
) {
1724 /* On some platforms, OPEN_MAX is the real limit, and getrlimit() is
1725 * full of nasty lies. I'm looking at you, OSX 10.5.... */
1726 rlim
.rlim_cur
= MIN(try_limit
, rlim
.rlim_cur
);
1727 if (setrlimit(RLIMIT_NOFILE
, &rlim
) == 0) {
1728 if (rlim
.rlim_cur
< (rlim_t
)limit
) {
1729 log_warn(LD_CONFIG
, "We are limited to %lu file descriptors by "
1730 "OPEN_MAX (%lu), and ConnLimit is %lu. Changing "
1731 "ConnLimit; sorry.",
1732 (unsigned long)try_limit
, (unsigned long)OPEN_MAX
,
1733 (unsigned long)limit
);
1735 log_info(LD_CONFIG
, "Dropped connection limit to %lu based on "
1736 "OPEN_MAX (%lu); Apparently, %lu was too high and rlimit "
1738 (unsigned long)try_limit
, (unsigned long)OPEN_MAX
,
1739 (unsigned long)rlim
.rlim_max
);
1744 #endif /* OPEN_MAX */
1746 log_warn(LD_CONFIG
,"Couldn't set maximum number of file descriptors: %s",
1747 strerror(setrlimit_errno
));
1750 /* leave some overhead for logs, etc, */
1751 limit
= rlim
.rlim_cur
;
1752 #endif /* HAVE_GETRLIMIT */
1754 if (limit
> INT_MAX
)
1756 tor_assert(max_out
);
1757 *max_out
= max_sockets
= (int)limit
- ULIMIT_BUFFER
;
1762 /** Log details of current user and group credentials. Return 0 on
1763 * success. Logs and return -1 on failure.
1766 log_credential_status(void)
1768 /** Log level to use when describing non-error UID/GID status. */
1769 #define CREDENTIAL_LOG_LEVEL LOG_INFO
1770 /* Real, effective and saved UIDs */
1771 uid_t ruid
, euid
, suid
;
1772 /* Read, effective and saved GIDs */
1773 gid_t rgid
, egid
, sgid
;
1774 /* Supplementary groups */
1775 gid_t
*sup_gids
= NULL
;
1777 /* Number of supplementary groups */
1781 #ifdef HAVE_GETRESUID
1782 if (getresuid(&ruid
, &euid
, &suid
) != 0 ) {
1783 log_warn(LD_GENERAL
, "Error getting changed UIDs: %s", strerror(errno
));
1786 log_fn(CREDENTIAL_LOG_LEVEL
, LD_GENERAL
,
1787 "UID is %u (real), %u (effective), %u (saved)",
1788 (unsigned)ruid
, (unsigned)euid
, (unsigned)suid
);
1791 /* getresuid is not present on MacOS X, so we can't get the saved (E)UID */
1796 log_fn(CREDENTIAL_LOG_LEVEL
, LD_GENERAL
,
1797 "UID is %u (real), %u (effective), unknown (saved)",
1798 (unsigned)ruid
, (unsigned)euid
);
1802 #ifdef HAVE_GETRESGID
1803 if (getresgid(&rgid
, &egid
, &sgid
) != 0 ) {
1804 log_warn(LD_GENERAL
, "Error getting changed GIDs: %s", strerror(errno
));
1807 log_fn(CREDENTIAL_LOG_LEVEL
, LD_GENERAL
,
1808 "GID is %u (real), %u (effective), %u (saved)",
1809 (unsigned)rgid
, (unsigned)egid
, (unsigned)sgid
);
1812 /* getresgid is not present on MacOS X, so we can't get the saved (E)GID */
1816 log_fn(CREDENTIAL_LOG_LEVEL
, LD_GENERAL
,
1817 "GID is %u (real), %u (effective), unknown (saved)",
1818 (unsigned)rgid
, (unsigned)egid
);
1821 /* log supplementary groups */
1823 sup_gids
= tor_calloc(64, sizeof(gid_t
));
1824 while ((ngids
= getgroups(sup_gids_size
, sup_gids
)) < 0 &&
1826 sup_gids_size
< NGROUPS_MAX
) {
1828 sup_gids
= tor_reallocarray(sup_gids
, sizeof(gid_t
), sup_gids_size
);
1832 log_warn(LD_GENERAL
, "Error getting supplementary GIDs: %s",
1839 smartlist_t
*elts
= smartlist_new();
1841 for (i
= 0; i
<ngids
; i
++) {
1842 smartlist_add_asprintf(elts
, "%u", (unsigned)sup_gids
[i
]);
1845 s
= smartlist_join_strings(elts
, " ", 0, NULL
);
1847 log_fn(CREDENTIAL_LOG_LEVEL
, LD_GENERAL
, "Supplementary groups are: %s",s
);
1850 SMARTLIST_FOREACH(elts
, char *, cp
, tor_free(cp
));
1851 smartlist_free(elts
);
1862 /** Cached struct from the last getpwname() call we did successfully. */
1863 static struct passwd
*passwd_cached
= NULL
;
1865 /** Helper: copy a struct passwd object.
1867 * We only copy the fields pw_uid, pw_gid, pw_name, pw_dir. Tor doesn't use
1868 * any others, and I don't want to run into incompatibilities.
1870 static struct passwd
*
1871 tor_passwd_dup(const struct passwd
*pw
)
1873 struct passwd
*new_pw
= tor_malloc_zero(sizeof(struct passwd
));
1875 new_pw
->pw_name
= tor_strdup(pw
->pw_name
);
1877 new_pw
->pw_dir
= tor_strdup(pw
->pw_dir
);
1878 new_pw
->pw_uid
= pw
->pw_uid
;
1879 new_pw
->pw_gid
= pw
->pw_gid
;
1884 /** Helper: free one of our cached 'struct passwd' values. */
1886 tor_passwd_free(struct passwd
*pw
)
1891 tor_free(pw
->pw_name
);
1892 tor_free(pw
->pw_dir
);
1896 /** Wrapper around getpwnam() that caches result. Used so that we don't need
1897 * to give the sandbox access to /etc/passwd.
1899 * The following fields alone will definitely be copied in the output: pw_uid,
1900 * pw_gid, pw_name, pw_dir. Other fields are not present in cached values.
1902 * When called with a NULL argument, this function clears storage associated
1903 * with static variables it uses.
1905 const struct passwd
*
1906 tor_getpwnam(const char *username
)
1910 if (username
== NULL
) {
1911 tor_passwd_free(passwd_cached
);
1912 passwd_cached
= NULL
;
1916 if ((pw
= getpwnam(username
))) {
1917 tor_passwd_free(passwd_cached
);
1918 passwd_cached
= tor_passwd_dup(pw
);
1919 log_info(LD_GENERAL
, "Caching new entry %s for %s",
1920 passwd_cached
->pw_name
, username
);
1925 if (! passwd_cached
|| ! passwd_cached
->pw_name
)
1928 if (! strcmp(username
, passwd_cached
->pw_name
))
1929 return passwd_cached
; // LCOV_EXCL_LINE - would need to make getpwnam flaky
1934 /** Wrapper around getpwnam() that can use cached result from
1935 * tor_getpwnam(). Used so that we don't need to give the sandbox access to
1938 * The following fields alone will definitely be copied in the output: pw_uid,
1939 * pw_gid, pw_name, pw_dir. Other fields are not present in cached values.
1941 const struct passwd
*
1942 tor_getpwuid(uid_t uid
)
1946 if ((pw
= getpwuid(uid
))) {
1951 if (! passwd_cached
)
1954 if (uid
== passwd_cached
->pw_uid
)
1955 return passwd_cached
; // LCOV_EXCL_LINE - would need to make getpwnam flaky
1961 /** Return true iff we were compiled with capability support, and capabilities
1964 have_capability_support(void)
1966 #ifdef HAVE_LINUX_CAPABILITIES
1967 cap_t caps
= cap_get_proc();
1977 #ifdef HAVE_LINUX_CAPABILITIES
1978 /** Helper. Drop all capabilities but a small set, and set PR_KEEPCAPS as
1981 * If pre_setuid, retain only CAP_NET_BIND_SERVICE, CAP_SETUID, and
1982 * CAP_SETGID, and use PR_KEEPCAPS to ensure that capabilities persist across
1985 * If not pre_setuid, retain only CAP_NET_BIND_SERVICE, and disable
1988 * Return 0 on success, and -1 on failure.
1991 drop_capabilities(int pre_setuid
)
1993 /* We keep these three capabilities, and these only, as we setuid.
1994 * After we setuid, we drop all but the first. */
1995 const cap_value_t caplist
[] = {
1996 CAP_NET_BIND_SERVICE
, CAP_SETUID
, CAP_SETGID
1998 const char *where
= pre_setuid
? "pre-setuid" : "post-setuid";
1999 const int n_effective
= pre_setuid
? 3 : 1;
2000 const int n_permitted
= pre_setuid
? 3 : 1;
2001 const int n_inheritable
= 1;
2002 const int keepcaps
= pre_setuid
? 1 : 0;
2004 /* Sets whether we keep capabilities across a setuid. */
2005 if (prctl(PR_SET_KEEPCAPS
, keepcaps
) < 0) {
2006 log_warn(LD_CONFIG
, "Unable to call prctl() %s: %s",
2007 where
, strerror(errno
));
2011 cap_t caps
= cap_get_proc();
2013 log_warn(LD_CONFIG
, "Unable to call cap_get_proc() %s: %s",
2014 where
, strerror(errno
));
2019 cap_set_flag(caps
, CAP_EFFECTIVE
, n_effective
, caplist
, CAP_SET
);
2020 cap_set_flag(caps
, CAP_PERMITTED
, n_permitted
, caplist
, CAP_SET
);
2021 cap_set_flag(caps
, CAP_INHERITABLE
, n_inheritable
, caplist
, CAP_SET
);
2023 int r
= cap_set_proc(caps
);
2026 log_warn(LD_CONFIG
, "No permission to set capabilities %s: %s",
2027 where
, strerror(errno
));
2035 /** Call setuid and setgid to run as <b>user</b> and switch to their
2036 * primary group. Return 0 on success. On failure, log and return -1.
2038 * If SWITCH_ID_KEEP_BINDLOW is set in 'flags', try to use the capability
2039 * system to retain the abilitity to bind low ports.
2041 * If SWITCH_ID_WARN_IF_NO_CAPS is set in flags, also warn if we have
2042 * don't have capability support.
2045 switch_id(const char *user
, const unsigned flags
)
2048 const struct passwd
*pw
= NULL
;
2051 static int have_already_switched_id
= 0;
2052 const int keep_bindlow
= !!(flags
& SWITCH_ID_KEEP_BINDLOW
);
2053 const int warn_if_no_caps
= !!(flags
& SWITCH_ID_WARN_IF_NO_CAPS
);
2057 if (have_already_switched_id
)
2060 /* Log the initial credential state */
2061 if (log_credential_status())
2064 log_fn(CREDENTIAL_LOG_LEVEL
, LD_GENERAL
, "Changing user and groups");
2066 /* Get old UID/GID to check if we changed correctly */
2070 /* Lookup the user and group information, if we have a problem, bail out. */
2071 pw
= tor_getpwnam(user
);
2073 log_warn(LD_CONFIG
, "Error setting configured user: %s not found", user
);
2077 #ifdef HAVE_LINUX_CAPABILITIES
2078 (void) warn_if_no_caps
;
2080 if (drop_capabilities(1))
2084 (void) keep_bindlow
;
2085 if (warn_if_no_caps
) {
2086 log_warn(LD_CONFIG
, "KeepBindCapabilities set, but no capability support "
2091 /* Properly switch egid,gid,euid,uid here or bail out */
2092 if (setgroups(1, &pw
->pw_gid
)) {
2093 log_warn(LD_GENERAL
, "Error setting groups to gid %d: \"%s\".",
2094 (int)pw
->pw_gid
, strerror(errno
));
2095 if (old_uid
== pw
->pw_uid
) {
2096 log_warn(LD_GENERAL
, "Tor is already running as %s. You do not need "
2097 "the \"User\" option if you are already running as the user "
2098 "you want to be. (If you did not set the User option in your "
2099 "torrc, check whether it was specified on the command line "
2100 "by a startup script.)", user
);
2102 log_warn(LD_GENERAL
, "If you set the \"User\" option, you must start Tor"
2108 if (setegid(pw
->pw_gid
)) {
2109 log_warn(LD_GENERAL
, "Error setting egid to %d: %s",
2110 (int)pw
->pw_gid
, strerror(errno
));
2114 if (setgid(pw
->pw_gid
)) {
2115 log_warn(LD_GENERAL
, "Error setting gid to %d: %s",
2116 (int)pw
->pw_gid
, strerror(errno
));
2120 if (setuid(pw
->pw_uid
)) {
2121 log_warn(LD_GENERAL
, "Error setting configured uid to %s (%d): %s",
2122 user
, (int)pw
->pw_uid
, strerror(errno
));
2126 if (seteuid(pw
->pw_uid
)) {
2127 log_warn(LD_GENERAL
, "Error setting configured euid to %s (%d): %s",
2128 user
, (int)pw
->pw_uid
, strerror(errno
));
2132 /* This is how OpenBSD rolls:
2133 if (setgroups(1, &pw->pw_gid) || setegid(pw->pw_gid) ||
2134 setgid(pw->pw_gid) || setuid(pw->pw_uid) || seteuid(pw->pw_uid)) {
2135 setgid(pw->pw_gid) || seteuid(pw->pw_uid) || setuid(pw->pw_uid)) {
2136 log_warn(LD_GENERAL, "Error setting configured UID/GID: %s",
2142 /* We've properly switched egid, gid, euid, uid, and supplementary groups if
2144 #ifdef HAVE_LINUX_CAPABILITIES
2146 if (drop_capabilities(0))
2151 #if !defined(CYGWIN) && !defined(__CYGWIN__)
2152 /* If we tried to drop privilege to a group/user other than root, attempt to
2153 * restore root (E)(U|G)ID, and abort if the operation succeeds */
2155 /* Only check for privilege dropping if we were asked to be non-root */
2157 /* Try changing GID/EGID */
2158 if (pw
->pw_gid
!= old_gid
&&
2159 (setgid(old_gid
) != -1 || setegid(old_gid
) != -1)) {
2160 log_warn(LD_GENERAL
, "Was able to restore group credentials even after "
2161 "switching GID: this means that the setgid code didn't work.");
2165 /* Try changing UID/EUID */
2166 if (pw
->pw_uid
!= old_uid
&&
2167 (setuid(old_uid
) != -1 || seteuid(old_uid
) != -1)) {
2168 log_warn(LD_GENERAL
, "Was able to restore user credentials even after "
2169 "switching UID: this means that the setuid code didn't work.");
2175 /* Check what really happened */
2176 if (log_credential_status()) {
2180 have_already_switched_id
= 1; /* mark success so we never try again */
2182 #if defined(__linux__) && defined(HAVE_SYS_PRCTL_H) && defined(HAVE_PRCTL)
2183 #ifdef PR_SET_DUMPABLE
2185 /* Re-enable core dumps if we're not running as root. */
2186 log_info(LD_CONFIG
, "Re-enabling coredumps");
2187 if (prctl(PR_SET_DUMPABLE
, 1)) {
2188 log_warn(LD_CONFIG
, "Unable to re-enable coredumps: %s",strerror(errno
));
2199 log_warn(LD_CONFIG
, "Switching users is unsupported on your OS.");
2204 /* We only use the linux prctl for now. There is no Win32 support; this may
2205 * also work on various BSD systems and Mac OS X - send testing feedback!
2207 * On recent Gnu/Linux kernels it is possible to create a system-wide policy
2208 * that will prevent non-root processes from attaching to other processes
2209 * unless they are the parent process; thus gdb can attach to programs that
2210 * they execute but they cannot attach to other processes running as the same
2211 * user. The system wide policy may be set with the sysctl
2212 * kernel.yama.ptrace_scope or by inspecting
2213 * /proc/sys/kernel/yama/ptrace_scope and it is 1 by default on Ubuntu 11.04.
2215 * This ptrace scope will be ignored on Gnu/Linux for users with
2216 * CAP_SYS_PTRACE and so it is very likely that root will still be able to
2217 * attach to the Tor process.
2219 /** Attempt to disable debugger attachment: return 1 on success, -1 on
2220 * failure, and 0 if we don't know how to try on this platform. */
2222 tor_disable_debugger_attach(void)
2227 log_debug(LD_CONFIG
,
2228 "Attemping to disable debugger attachment to Tor for "
2229 "unprivileged users.");
2230 #if defined(__linux__) && defined(HAVE_SYS_PRCTL_H) && defined(HAVE_PRCTL)
2231 #ifdef PR_SET_DUMPABLE
2233 r
= prctl(PR_SET_DUMPABLE
, 0);
2236 #if defined(__APPLE__) && defined(PT_DENY_ATTACH)
2239 r
= ptrace(PT_DENY_ATTACH
, 0, 0, 0);
2243 // XXX: TODO - Mac OS X has dtrace and this may be disabled.
2244 // XXX: TODO - Windows probably has something similar
2245 if (r
== 0 && attempted
) {
2246 log_debug(LD_CONFIG
,"Debugger attachment disabled for "
2247 "unprivileged users.");
2249 } else if (attempted
) {
2250 log_warn(LD_CONFIG
, "Unable to disable debugger attaching: %s",
2257 /** Allocate and return a string containing the home directory for the
2258 * user <b>username</b>. Only works on posix-like systems. */
2260 get_user_homedir(const char *username
)
2262 const struct passwd
*pw
;
2263 tor_assert(username
);
2265 if (!(pw
= tor_getpwnam(username
))) {
2266 log_err(LD_CONFIG
,"User \"%s\" not found.", username
);
2269 return tor_strdup(pw
->pw_dir
);
2273 /** Modify <b>fname</b> to contain the name of its parent directory. Doesn't
2274 * actually examine the filesystem; does a purely syntactic modification.
2276 * The parent of the root director is considered to be iteself.
2278 * Path separators are the forward slash (/) everywhere and additionally
2279 * the backslash (\) on Win32.
2281 * Cuts off any number of trailing path separators but otherwise ignores
2282 * them for purposes of finding the parent directory.
2284 * Returns 0 if a parent directory was successfully found, -1 otherwise (fname
2285 * did not have any path separators or only had them at the end).
2288 get_parent_directory(char *fname
)
2294 /* If we start with, say, c:, then don't consider that the start of the path
2296 if (fname
[0] && fname
[1] == ':') {
2300 /* Now we want to remove all path-separators at the end of the string,
2301 * and to remove the end of the string starting with the path separator
2302 * before the last non-path-separator. In perl, this would be
2303 * s#[/]*$##; s#/[^/]*$##;
2304 * on a unixy platform.
2306 cp
= fname
+ strlen(fname
);
2308 while (--cp
>= fname
) {
2309 int is_sep
= (*cp
== '/'
2316 /* This is the first separator in the file name; don't remove it! */
2331 /** Return a newly allocated string containing the output of getcwd(). Return
2332 * NULL on failure. (We can't just use getcwd() into a PATH_MAX buffer, since
2333 * Hurd hasn't got a PATH_MAX.)
2339 #define MAX_CWD PATH_MAX
2341 #define MAX_CWD 4096
2344 char path_buf
[MAX_CWD
];
2345 char *path
= getcwd(path_buf
, sizeof(path_buf
));
2346 return path
? tor_strdup(path
) : NULL
;
2350 /** Expand possibly relative path <b>fname</b> to an absolute path.
2351 * Return a newly allocated string, possibly equal to <b>fname</b>. */
2353 make_path_absolute(char *fname
)
2356 char *absfname_malloced
= _fullpath(NULL
, fname
, 1);
2358 /* We don't want to assume that tor_free can free a string allocated
2359 * with malloc. On failure, return fname (it's better than nothing). */
2360 char *absfname
= tor_strdup(absfname_malloced
? absfname_malloced
: fname
);
2361 if (absfname_malloced
) raw_free(absfname_malloced
);
2365 char *absfname
= NULL
, *path
= NULL
;
2369 if (fname
[0] == '/') {
2370 absfname
= tor_strdup(fname
);
2372 path
= alloc_getcwd();
2374 tor_asprintf(&absfname
, "%s/%s", path
, fname
);
2377 /* LCOV_EXCL_START Can't make getcwd fail. */
2378 /* If getcwd failed, the best we can do here is keep using the
2379 * relative path. (Perhaps / isn't readable by this UID/GID.) */
2380 log_warn(LD_GENERAL
, "Unable to find current working directory: %s",
2382 absfname
= tor_strdup(fname
);
2383 /* LCOV_EXCL_STOP */
2390 #ifndef HAVE__NSGETENVIRON
2391 #ifndef HAVE_EXTERN_ENVIRON_DECLARED
2392 /* Some platforms declare environ under some circumstances, others don't. */
2393 #ifndef RUNNING_DOXYGEN
2394 extern char **environ
;
2399 /** Return the current environment. This is a portable replacement for
2402 get_environment(void)
2404 #ifdef HAVE__NSGETENVIRON
2405 /* This is for compatibility between OSX versions. Otherwise (for example)
2406 * when we do a mostly-static build on OSX 10.7, the resulting binary won't
2407 * work on OSX 10.6. */
2408 return *_NSGetEnviron();
2414 /** Get name of current host and write it to <b>name</b> array, whose
2415 * length is specified by <b>namelen</b> argument. Return 0 upon
2416 * successfull completion; otherwise return return -1. (Currently,
2417 * this function is merely a mockable wrapper for POSIX gethostname().)
2420 tor_gethostname
,(char *name
, size_t namelen
))
2422 return gethostname(name
,namelen
);
2425 /** Set *addr to the IP address (in dotted-quad notation) stored in *str.
2426 * Return 1 on success, 0 if *str is badly formatted.
2427 * (Like inet_aton(str,addr), but works on Windows and Solaris.)
2430 tor_inet_aton(const char *str
, struct in_addr
* addr
)
2434 if (tor_sscanf(str
, "%3u.%3u.%3u.%3u%c", &a
,&b
,&c
,&d
,&more
) != 4)
2436 if (a
> 255) return 0;
2437 if (b
> 255) return 0;
2438 if (c
> 255) return 0;
2439 if (d
> 255) return 0;
2440 addr
->s_addr
= htonl((a
<<24) | (b
<<16) | (c
<<8) | d
);
2444 /** Given <b>af</b>==AF_INET and <b>src</b> a struct in_addr, or
2445 * <b>af</b>==AF_INET6 and <b>src</b> a struct in6_addr, try to format the
2446 * address and store it in the <b>len</b>-byte buffer <b>dst</b>. Returns
2447 * <b>dst</b> on success, NULL on failure.
2449 * (Like inet_ntop(af,src,dst,len), but works on platforms that don't have it:
2450 * Tor sometimes needs to format ipv6 addresses even on platforms without ipv6
2453 tor_inet_ntop(int af
, const void *src
, char *dst
, size_t len
)
2455 if (af
== AF_INET
) {
2456 if (tor_inet_ntoa(src
, dst
, len
) < 0)
2460 } else if (af
== AF_INET6
) {
2461 const struct in6_addr
*addr
= src
;
2463 int longestGapLen
= 0, longestGapPos
= -1, i
,
2464 curGapPos
= -1, curGapLen
= 0;
2466 for (i
= 0; i
< 8; ++i
) {
2467 words
[i
] = (((uint16_t)addr
->s6_addr
[2*i
])<<8) + addr
->s6_addr
[2*i
+1];
2469 if (words
[0] == 0 && words
[1] == 0 && words
[2] == 0 && words
[3] == 0 &&
2470 words
[4] == 0 && ((words
[5] == 0 && words
[6] && words
[7]) ||
2471 (words
[5] == 0xffff))) {
2472 /* This is an IPv4 address. */
2473 if (words
[5] == 0) {
2474 tor_snprintf(buf
, sizeof(buf
), "::%d.%d.%d.%d",
2475 addr
->s6_addr
[12], addr
->s6_addr
[13],
2476 addr
->s6_addr
[14], addr
->s6_addr
[15]);
2478 tor_snprintf(buf
, sizeof(buf
), "::%x:%d.%d.%d.%d", words
[5],
2479 addr
->s6_addr
[12], addr
->s6_addr
[13],
2480 addr
->s6_addr
[14], addr
->s6_addr
[15]);
2482 if ((strlen(buf
) + 1) > len
) /* +1 for \0 */
2484 strlcpy(dst
, buf
, len
);
2489 if (words
[i
] == 0) {
2492 while (i
<8 && words
[i
] == 0) {
2495 if (curGapLen
> longestGapLen
) {
2496 longestGapPos
= curGapPos
;
2497 longestGapLen
= curGapLen
;
2503 if (longestGapLen
<=1)
2507 for (i
= 0; i
< 8; ++i
) {
2508 if (words
[i
] == 0 && longestGapPos
== i
) {
2512 while (i
< 8 && words
[i
] == 0)
2514 --i
; /* to compensate for loop increment. */
2516 tor_snprintf(cp
, sizeof(buf
)-(cp
-buf
), "%x", (unsigned)words
[i
]);
2523 if ((strlen(buf
) + 1) > len
) /* +1 for \0 */
2525 strlcpy(dst
, buf
, len
);
2532 /** Given <b>af</b>==AF_INET or <b>af</b>==AF_INET6, and a string <b>src</b>
2533 * encoding an IPv4 address or IPv6 address correspondingly, try to parse the
2534 * address and store the result in <b>dst</b> (which must have space for a
2535 * struct in_addr or a struct in6_addr, as appropriate). Return 1 on success,
2536 * 0 on a bad parse, and -1 on a bad <b>af</b>.
2538 * (Like inet_pton(af,src,dst) but works on platforms that don't have it: Tor
2539 * sometimes needs to format ipv6 addresses even on platforms without ipv6
2542 tor_inet_pton(int af
, const char *src
, void *dst
)
2544 if (af
== AF_INET
) {
2545 return tor_inet_aton(src
, dst
);
2546 } else if (af
== AF_INET6
) {
2547 struct in6_addr
*out
= dst
;
2549 int gapPos
= -1, i
, setWords
=0;
2550 const char *dot
= strchr(src
, '.');
2551 const char *eow
; /* end of words. */
2555 eow
= src
+strlen(src
);
2557 unsigned byte1
,byte2
,byte3
,byte4
;
2559 for (eow
= dot
-1; eow
> src
&& TOR_ISDIGIT(*eow
); --eow
)
2565 /* We use "scanf" because some platform inet_aton()s are too lax
2566 * about IPv4 addresses of the form "1.2.3" */
2567 if (tor_sscanf(eow
, "%3u.%3u.%3u.%3u%c",
2568 &byte1
,&byte2
,&byte3
,&byte4
,&more
) != 4)
2571 if (byte1
> 255 || byte2
> 255 || byte3
> 255 || byte4
> 255)
2574 words
[6] = (byte1
<<8) | byte2
;
2575 words
[7] = (byte3
<<8) | byte4
;
2583 if (TOR_ISXDIGIT(*src
)) {
2586 long r
= strtol(src
, &next
, 16);
2587 if (next
== NULL
|| next
== src
) {
2588 /* The 'next == src' error case can happen on versions of openbsd
2589 * where treats "0xfoo" as an error, rather than as "0" followed by
2594 len
= *next
== '\0' ? eow
- src
: next
- src
;
2597 if (len
> 1 && !TOR_ISXDIGIT(src
[1]))
2598 return 0; /* 0x is not valid */
2601 tor_assert(r
< 65536);
2602 words
[i
++] = (uint16_t)r
;
2605 if (*src
!= ':' && src
!= eow
)
2608 } else if (*src
== ':' && i
> 0 && gapPos
== -1) {
2611 } else if (*src
== ':' && i
== 0 && src
+1 < eow
&& src
[1] == ':' &&
2621 (setWords
== 8 && gapPos
!= -1) ||
2622 (setWords
< 8 && gapPos
== -1))
2626 int nToMove
= setWords
- (dot
? 2 : 0) - gapPos
;
2627 int gapLen
= 8 - setWords
;
2628 tor_assert(nToMove
>= 0);
2629 memmove(&words
[gapPos
+gapLen
], &words
[gapPos
],
2630 sizeof(uint16_t)*nToMove
);
2631 memset(&words
[gapPos
], 0, sizeof(uint16_t)*gapLen
);
2633 for (i
= 0; i
< 8; ++i
) {
2634 out
->s6_addr
[2*i
] = words
[i
] >> 8;
2635 out
->s6_addr
[2*i
+1] = words
[i
] & 0xff;
2644 /** Similar behavior to Unix gethostbyname: resolve <b>name</b>, and set
2645 * *<b>addr</b> to the proper IP address, in host byte order. Returns 0
2646 * on success, -1 on failure; 1 on transient failure.
2648 * (This function exists because standard windows gethostbyname
2649 * doesn't treat raw IP addresses properly.)
2653 tor_lookup_hostname
,(const char *name
, uint32_t *addr
))
2658 if ((ret
= tor_addr_lookup(name
, AF_INET
, &myaddr
)))
2661 if (tor_addr_family(&myaddr
) == AF_INET
) {
2662 *addr
= tor_addr_to_ipv4h(&myaddr
);
2669 /** Hold the result of our call to <b>uname</b>. */
2670 static char uname_result
[256];
2671 /** True iff uname_result is set. */
2672 static int uname_result_is_set
= 0;
2674 /** Return a pointer to a description of our platform.
2676 MOCK_IMPL(const char *, get_uname
, (void))
2681 if (!uname_result_is_set
) {
2683 if (uname(&u
) != -1) {
2684 /* (Linux says 0 is success, Solaris says 1 is success) */
2685 strlcpy(uname_result
, u
.sysname
, sizeof(uname_result
));
2690 OSVERSIONINFOEX info
;
2692 const char *plat
= NULL
;
2694 unsigned major
; unsigned minor
; const char *version
;
2695 } win_version_table
[] = {
2696 { 6, 2, "Windows 8" },
2697 { 6, 1, "Windows 7" },
2698 { 6, 0, "Windows Vista" },
2699 { 5, 2, "Windows Server 2003" },
2700 { 5, 1, "Windows XP" },
2701 { 5, 0, "Windows 2000" },
2702 /* { 4, 0, "Windows NT 4.0" }, */
2703 { 4, 90, "Windows Me" },
2704 { 4, 10, "Windows 98" },
2705 /* { 4, 0, "Windows 95" } */
2706 { 3, 51, "Windows NT 3.51" },
2709 memset(&info
, 0, sizeof(info
));
2710 info
.dwOSVersionInfoSize
= sizeof(info
);
2711 if (! GetVersionEx((LPOSVERSIONINFO
)&info
)) {
2712 strlcpy(uname_result
, "Bizarre version of Windows where GetVersionEx"
2713 " doesn't work.", sizeof(uname_result
));
2714 uname_result_is_set
= 1;
2715 return uname_result
;
2717 if (info
.dwMajorVersion
== 4 && info
.dwMinorVersion
== 0) {
2718 if (info
.dwPlatformId
== VER_PLATFORM_WIN32_NT
)
2719 plat
= "Windows NT 4.0";
2721 plat
= "Windows 95";
2723 for (i
=0; win_version_table
[i
].major
>0; ++i
) {
2724 if (win_version_table
[i
].major
== info
.dwMajorVersion
&&
2725 win_version_table
[i
].minor
== info
.dwMinorVersion
) {
2726 plat
= win_version_table
[i
].version
;
2732 strlcpy(uname_result
, plat
, sizeof(uname_result
));
2734 if (info
.dwMajorVersion
> 6 ||
2735 (info
.dwMajorVersion
==6 && info
.dwMinorVersion
>2))
2736 tor_snprintf(uname_result
, sizeof(uname_result
),
2737 "Very recent version of Windows [major=%d,minor=%d]",
2738 (int)info
.dwMajorVersion
,(int)info
.dwMinorVersion
);
2740 tor_snprintf(uname_result
, sizeof(uname_result
),
2741 "Unrecognized version of Windows [major=%d,minor=%d]",
2742 (int)info
.dwMajorVersion
,(int)info
.dwMinorVersion
);
2744 #ifdef VER_NT_SERVER
2745 if (info
.wProductType
== VER_NT_SERVER
||
2746 info
.wProductType
== VER_NT_DOMAIN_CONTROLLER
) {
2747 strlcat(uname_result
, " [server]", sizeof(uname_result
));
2751 /* LCOV_EXCL_START -- can't provoke uname failure */
2752 strlcpy(uname_result
, "Unknown platform", sizeof(uname_result
));
2753 /* LCOV_EXCL_STOP */
2756 uname_result_is_set
= 1;
2758 return uname_result
;
2765 /** Implementation logic for compute_num_cpus(). */
2767 compute_num_cpus_impl(void)
2771 memset(&info
, 0, sizeof(info
));
2772 GetSystemInfo(&info
);
2773 if (info
.dwNumberOfProcessors
>= 1 && info
.dwNumberOfProcessors
< INT_MAX
)
2774 return (int)info
.dwNumberOfProcessors
;
2777 #elif defined(HAVE_SYSCONF)
2778 #ifdef _SC_NPROCESSORS_CONF
2779 long cpus_conf
= sysconf(_SC_NPROCESSORS_CONF
);
2781 long cpus_conf
= -1;
2783 #ifdef _SC_NPROCESSORS_ONLN
2784 long cpus_onln
= sysconf(_SC_NPROCESSORS_ONLN
);
2786 long cpus_onln
= -1;
2790 if (cpus_conf
> 0 && cpus_onln
< 0) {
2792 } else if (cpus_onln
> 0 && cpus_conf
< 0) {
2794 } else if (cpus_onln
> 0 && cpus_conf
> 0) {
2795 if (cpus_onln
< cpus_conf
) {
2796 log_notice(LD_GENERAL
, "I think we have %ld CPUS, but only %ld of them "
2797 "are available. Telling Tor to only use %ld. You can over"
2798 "ride this with the NumCPUs option",
2799 cpus_conf
, cpus_onln
, cpus_onln
);
2804 if (cpus
>= 1 && cpus
< INT_MAX
)
2813 #define MAX_DETECTABLE_CPUS 16
2815 /** Return how many CPUs we are running with. We assume that nobody is
2816 * using hot-swappable CPUs, so we don't recompute this after the first
2817 * time. Return -1 if we don't know how to tell the number of CPUs on this
2821 compute_num_cpus(void)
2823 static int num_cpus
= -2;
2824 if (num_cpus
== -2) {
2825 num_cpus
= compute_num_cpus_impl();
2826 tor_assert(num_cpus
!= -2);
2827 if (num_cpus
> MAX_DETECTABLE_CPUS
) {
2828 /* LCOV_EXCL_START */
2829 log_notice(LD_GENERAL
, "Wow! I detected that you have %d CPUs. I "
2830 "will not autodetect any more than %d, though. If you "
2831 "want to configure more, set NumCPUs in your torrc",
2832 num_cpus
, MAX_DETECTABLE_CPUS
);
2833 num_cpus
= MAX_DETECTABLE_CPUS
;
2834 /* LCOV_EXCL_STOP */
2840 #if !defined(_WIN32)
2841 /** Defined iff we need to add locks when defining fake versions of reentrant
2842 * versions of time-related functions. */
2843 #define TIME_FNS_NEED_LOCKS
2846 /** Helper: Deal with confused or out-of-bounds values from localtime_r and
2847 * friends. (On some platforms, they can give out-of-bounds values or can
2848 * return NULL.) If <b>islocal</b>, this is a localtime result; otherwise
2849 * it's from gmtime. The function returned <b>r</b>, when given <b>timep</b>
2850 * as its input. If we need to store new results, store them in
2851 * <b>resultbuf</b>. */
2853 correct_tm(int islocal
, const time_t *timep
, struct tm
*resultbuf
,
2856 const char *outcome
;
2858 if (PREDICT_LIKELY(r
)) {
2859 /* We can't strftime dates after 9999 CE, and we want to avoid dates
2860 * before 1 CE (avoiding the year 0 issue and negative years). */
2861 if (r
->tm_year
> 8099) {
2870 } else if (r
->tm_year
< (1-1900)) {
2871 r
->tm_year
= (1-1900);
2883 /* If we get here, gmtime or localtime returned NULL. It might have done
2884 * this because of overrun or underrun, or it might have done it because of
2885 * some other weird issue. */
2889 r
->tm_year
= 70; /* 1970 CE */
2897 outcome
= "Rounding up to 1970";
2899 } else if (*timep
>= INT32_MAX
) {
2900 /* Rounding down to INT32_MAX isn't so great, but keep in mind that we
2901 * only do it if gmtime/localtime tells us NULL. */
2903 r
->tm_year
= 137; /* 2037 CE */
2911 outcome
= "Rounding down to 2037";
2916 /* If we get here, then gmtime/localtime failed without getting an extreme
2917 * value for *timep */
2918 /* LCOV_EXCL_START */
2919 tor_fragile_assert();
2921 memset(resultbuf
, 0, sizeof(struct tm
));
2922 outcome
="can't recover";
2923 /* LCOV_EXCL_STOP */
2925 log_warn(LD_BUG
, "%s("I64_FORMAT
") failed with error %s: %s",
2926 islocal
?"localtime":"gmtime",
2927 timep
?I64_PRINTF_ARG(*timep
):0,
2934 /** As localtime_r, but defined for platforms that don't have it:
2936 * Convert *<b>timep</b> to a struct tm in local time, and store the value in
2937 * *<b>result</b>. Return the result on success, or NULL on failure.
2939 #ifdef HAVE_LOCALTIME_R
2941 tor_localtime_r(const time_t *timep
, struct tm
*result
)
2944 r
= localtime_r(timep
, result
);
2945 return correct_tm(1, timep
, result
, r
);
2947 #elif defined(TIME_FNS_NEED_LOCKS)
2949 tor_localtime_r(const time_t *timep
, struct tm
*result
)
2952 static tor_mutex_t
*m
=NULL
;
2953 if (!m
) { m
=tor_mutex_new(); }
2955 tor_mutex_acquire(m
);
2956 r
= localtime(timep
);
2958 memcpy(result
, r
, sizeof(struct tm
));
2959 tor_mutex_release(m
);
2960 return correct_tm(1, timep
, result
, r
);
2964 tor_localtime_r(const time_t *timep
, struct tm
*result
)
2968 r
= localtime(timep
);
2970 memcpy(result
, r
, sizeof(struct tm
));
2971 return correct_tm(1, timep
, result
, r
);
2977 /** As gmtime_r, but defined for platforms that don't have it:
2979 * Convert *<b>timep</b> to a struct tm in UTC, and store the value in
2980 * *<b>result</b>. Return the result on success, or NULL on failure.
2982 #ifdef HAVE_GMTIME_R
2984 tor_gmtime_r(const time_t *timep
, struct tm
*result
)
2987 r
= gmtime_r(timep
, result
);
2988 return correct_tm(0, timep
, result
, r
);
2990 #elif defined(TIME_FNS_NEED_LOCKS)
2992 tor_gmtime_r(const time_t *timep
, struct tm
*result
)
2995 static tor_mutex_t
*m
=NULL
;
2996 if (!m
) { m
=tor_mutex_new(); }
2998 tor_mutex_acquire(m
);
3001 memcpy(result
, r
, sizeof(struct tm
));
3002 tor_mutex_release(m
);
3003 return correct_tm(0, timep
, result
, r
);
3007 tor_gmtime_r(const time_t *timep
, struct tm
*result
)
3013 memcpy(result
, r
, sizeof(struct tm
));
3014 return correct_tm(0, timep
, result
, r
);
3018 #if defined(HAVE_MLOCKALL) && HAVE_DECL_MLOCKALL && defined(RLIMIT_MEMLOCK)
3019 /** Attempt to raise the current and max rlimit to infinity for our process.
3020 * This only needs to be done once and can probably only be done when we have
3021 * not already dropped privileges.
3024 tor_set_max_memlock(void)
3026 /* Future consideration for Windows is probably SetProcessWorkingSetSize
3027 * This is similar to setting the memory rlimit of RLIMIT_MEMLOCK
3028 * http://msdn.microsoft.com/en-us/library/ms686234(VS.85).aspx
3031 struct rlimit limit
;
3033 /* RLIM_INFINITY is -1 on some platforms. */
3034 limit
.rlim_cur
= RLIM_INFINITY
;
3035 limit
.rlim_max
= RLIM_INFINITY
;
3037 if (setrlimit(RLIMIT_MEMLOCK
, &limit
) == -1) {
3038 if (errno
== EPERM
) {
3039 log_warn(LD_GENERAL
, "You appear to lack permissions to change memory "
3040 "limits. Are you root?");
3042 log_warn(LD_GENERAL
, "Unable to raise RLIMIT_MEMLOCK: %s",
3051 /** Attempt to lock all current and all future memory pages.
3052 * This should only be called once and while we're privileged.
3053 * Like mlockall() we return 0 when we're successful and -1 when we're not.
3054 * Unlike mlockall() we return 1 if we've already attempted to lock memory.
3059 static int memory_lock_attempted
= 0;
3061 if (memory_lock_attempted
) {
3065 memory_lock_attempted
= 1;
3068 * Future consideration for Windows may be VirtualLock
3069 * VirtualLock appears to implement mlock() but not mlockall()
3071 * http://msdn.microsoft.com/en-us/library/aa366895(VS.85).aspx
3074 #if defined(HAVE_MLOCKALL) && HAVE_DECL_MLOCKALL && defined(RLIMIT_MEMLOCK)
3075 if (tor_set_max_memlock() == 0) {
3076 log_debug(LD_GENERAL
, "RLIMIT_MEMLOCK is now set to RLIM_INFINITY.");
3079 if (mlockall(MCL_CURRENT
|MCL_FUTURE
) == 0) {
3080 log_info(LD_GENERAL
, "Insecure OS paging is effectively disabled.");
3083 if (errno
== ENOSYS
) {
3084 /* Apple - it's 2009! I'm looking at you. Grrr. */
3085 log_notice(LD_GENERAL
, "It appears that mlockall() is not available on "
3087 } else if (errno
== EPERM
) {
3088 log_notice(LD_GENERAL
, "It appears that you lack the permissions to "
3089 "lock memory. Are you root?");
3091 log_notice(LD_GENERAL
, "Unable to lock all current and future memory "
3092 "pages: %s", strerror(errno
));
3096 log_warn(LD_GENERAL
, "Unable to lock memory pages. mlockall() unsupported?");
3102 * On Windows, WSAEWOULDBLOCK is not always correct: when you see it,
3103 * you need to ask the socket for its actual errno. Also, you need to
3104 * get your errors from WSAGetLastError, not errno. (If you supply a
3105 * socket of -1, we check WSAGetLastError, but don't correct
3108 * The upshot of all of this is that when a socket call fails, you
3109 * should call tor_socket_errno <em>at most once</em> on the failing
3110 * socket to get the error.
3114 tor_socket_errno(tor_socket_t sock
)
3116 int optval
, optvallen
=sizeof(optval
);
3117 int err
= WSAGetLastError();
3118 if (err
== WSAEWOULDBLOCK
&& SOCKET_OK(sock
)) {
3119 if (getsockopt(sock
, SOL_SOCKET
, SO_ERROR
, (void*)&optval
, &optvallen
))
3129 #define E(code, s) { code, (s " [" #code " ]") }
3130 struct { int code
; const char *msg
; } windows_socket_errors
[] = {
3131 E(WSAEINTR
, "Interrupted function call"),
3132 E(WSAEACCES
, "Permission denied"),
3133 E(WSAEFAULT
, "Bad address"),
3134 E(WSAEINVAL
, "Invalid argument"),
3135 E(WSAEMFILE
, "Too many open files"),
3136 E(WSAEWOULDBLOCK
, "Resource temporarily unavailable"),
3137 E(WSAEINPROGRESS
, "Operation now in progress"),
3138 E(WSAEALREADY
, "Operation already in progress"),
3139 E(WSAENOTSOCK
, "Socket operation on nonsocket"),
3140 E(WSAEDESTADDRREQ
, "Destination address required"),
3141 E(WSAEMSGSIZE
, "Message too long"),
3142 E(WSAEPROTOTYPE
, "Protocol wrong for socket"),
3143 E(WSAENOPROTOOPT
, "Bad protocol option"),
3144 E(WSAEPROTONOSUPPORT
, "Protocol not supported"),
3145 E(WSAESOCKTNOSUPPORT
, "Socket type not supported"),
3146 /* What's the difference between NOTSUPP and NOSUPPORT? :) */
3147 E(WSAEOPNOTSUPP
, "Operation not supported"),
3148 E(WSAEPFNOSUPPORT
, "Protocol family not supported"),
3149 E(WSAEAFNOSUPPORT
, "Address family not supported by protocol family"),
3150 E(WSAEADDRINUSE
, "Address already in use"),
3151 E(WSAEADDRNOTAVAIL
, "Cannot assign requested address"),
3152 E(WSAENETDOWN
, "Network is down"),
3153 E(WSAENETUNREACH
, "Network is unreachable"),
3154 E(WSAENETRESET
, "Network dropped connection on reset"),
3155 E(WSAECONNABORTED
, "Software caused connection abort"),
3156 E(WSAECONNRESET
, "Connection reset by peer"),
3157 E(WSAENOBUFS
, "No buffer space available"),
3158 E(WSAEISCONN
, "Socket is already connected"),
3159 E(WSAENOTCONN
, "Socket is not connected"),
3160 E(WSAESHUTDOWN
, "Cannot send after socket shutdown"),
3161 E(WSAETIMEDOUT
, "Connection timed out"),
3162 E(WSAECONNREFUSED
, "Connection refused"),
3163 E(WSAEHOSTDOWN
, "Host is down"),
3164 E(WSAEHOSTUNREACH
, "No route to host"),
3165 E(WSAEPROCLIM
, "Too many processes"),
3166 /* Yes, some of these start with WSA, not WSAE. No, I don't know why. */
3167 E(WSASYSNOTREADY
, "Network subsystem is unavailable"),
3168 E(WSAVERNOTSUPPORTED
, "Winsock.dll out of range"),
3169 E(WSANOTINITIALISED
, "Successful WSAStartup not yet performed"),
3170 E(WSAEDISCON
, "Graceful shutdown now in progress"),
3171 #ifdef WSATYPE_NOT_FOUND
3172 E(WSATYPE_NOT_FOUND
, "Class type not found"),
3174 E(WSAHOST_NOT_FOUND
, "Host not found"),
3175 E(WSATRY_AGAIN
, "Nonauthoritative host not found"),
3176 E(WSANO_RECOVERY
, "This is a nonrecoverable error"),
3177 E(WSANO_DATA
, "Valid name, no data record of requested type)"),
3179 /* There are some more error codes whose numeric values are marked
3180 * <b>OS dependent</b>. They start with WSA_, apparently for the same
3181 * reason that practitioners of some craft traditions deliberately
3182 * introduce imperfections into their baskets and rugs "to allow the
3183 * evil spirits to escape." If we catch them, then our binaries
3184 * might not report consistent results across versions of Windows.
3185 * Thus, I'm going to let them all fall through.
3189 /** There does not seem to be a strerror equivalent for Winsock errors.
3190 * Naturally, we have to roll our own.
3193 tor_socket_strerror(int e
)
3196 for (i
=0; windows_socket_errors
[i
].code
>= 0; ++i
) {
3197 if (e
== windows_socket_errors
[i
].code
)
3198 return windows_socket_errors
[i
].msg
;
3204 /** Called before we make any calls to network-related functions.
3205 * (Some operating systems require their network libraries to be
3211 /* This silly exercise is necessary before windows will allow
3212 * gethostbyname to work. */
3215 r
= WSAStartup(0x101,&WSAData
);
3217 log_warn(LD_NET
,"Error initializing windows network layer: code was %d",r
);
3220 if (sizeof(SOCKET
) != sizeof(tor_socket_t
)) {
3221 log_warn(LD_BUG
,"The tor_socket_t type does not match SOCKET in size; Tor "
3222 "might not work. (Sizes are %d and %d respectively.)",
3223 (int)sizeof(tor_socket_t
), (int)sizeof(SOCKET
));
3225 /* WSAData.iMaxSockets might show the max sockets we're allowed to use.
3226 * We might use it to complain if we're trying to be a server but have
3227 * too few sockets available. */
3233 /** Return a newly allocated string describing the windows system error code
3234 * <b>err</b>. Note that error codes are different from errno. Error codes
3235 * come from GetLastError() when a winapi call fails. errno is set only when
3236 * ANSI functions fail. Whee. */
3238 format_win32_error(DWORD err
)
3244 /* Somebody once decided that this interface was better than strerror(). */
3245 n
= FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
|
3246 FORMAT_MESSAGE_FROM_SYSTEM
|
3247 FORMAT_MESSAGE_IGNORE_INSERTS
,
3249 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
3257 len
= (128 * 1024) * 2 + 1; /* This shouldn't be possible, but let's
3261 result
= tor_malloc(len
);
3262 wcstombs(result
,str
,len
);
3263 result
[len
-1] = '\0';
3265 result
= tor_strdup(str
);
3268 result
= tor_strdup("<unformattable error>");
3271 LocalFree(str
); /* LocalFree != free() */
3277 #if defined(HW_PHYSMEM64)
3278 /* This appears to be an OpenBSD thing */
3279 #define INT64_HW_MEM HW_PHYSMEM64
3280 #elif defined(HW_MEMSIZE)
3281 /* OSX defines this one */
3282 #define INT64_HW_MEM HW_MEMSIZE
3286 * Helper: try to detect the total system memory, and return it. On failure,
3290 get_total_system_memory_impl(void)
3292 #if defined(__linux__)
3293 /* On linux, sysctl is deprecated. Because proc is so awesome that you
3294 * shouldn't _want_ to write portable code, I guess? */
3295 unsigned long long result
=0;
3300 if (-1 == (fd
= tor_open_cloexec("/proc/meminfo",O_RDONLY
,0)))
3302 s
= read_file_to_str_until_eof(fd
, 65536, &file_size
);
3305 cp
= strstr(s
, "MemTotal:");
3308 /* Use the system sscanf so that space will match a wider number of space */
3309 if (sscanf(cp
, "MemTotal: %llu kB\n", &result
) != 1)
3314 return result
* 1024;
3317 /* LCOV_EXCL_START Can't reach this unless proc is broken. */
3321 /* LCOV_EXCL_STOP */
3322 #elif defined (_WIN32)
3323 /* Windows has MEMORYSTATUSEX; pretty straightforward. */
3325 memset(&ms
, 0, sizeof(ms
));
3326 ms
.dwLength
= sizeof(ms
);
3327 if (! GlobalMemoryStatusEx(&ms
))
3330 return ms
.ullTotalPhys
;
3332 #elif defined(HAVE_SYSCTL) && defined(INT64_HW_MEM)
3333 /* On many systems, HW_PYHSMEM is clipped to 32 bits; let's use a better
3334 * variant if we know about it. */
3335 uint64_t memsize
= 0;
3336 size_t len
= sizeof(memsize
);
3337 int mib
[2] = {CTL_HW
, INT64_HW_MEM
};
3338 if (sysctl(mib
,2,&memsize
,&len
,NULL
,0))
3343 #elif defined(HAVE_SYSCTL) && defined(HW_PHYSMEM)
3344 /* On some systems (like FreeBSD I hope) you can use a size_t with
3347 size_t len
= sizeof(memsize
);
3348 int mib
[2] = {CTL_HW
, HW_USERMEM
};
3349 if (sysctl(mib
,2,&memsize
,&len
,NULL
,0))
3355 /* I have no clue. */
3361 * Try to find out how much physical memory the system has. On success,
3362 * return 0 and set *<b>mem_out</b> to that value. On failure, return -1.
3365 get_total_system_memory(size_t *mem_out
)
3367 static size_t mem_cached
=0;
3368 uint64_t m
= get_total_system_memory_impl();
3370 /* LCOV_EXCL_START -- can't make this happen without mocking. */
3371 /* We couldn't find our memory total */
3372 if (0 == mem_cached
) {
3373 /* We have no cached value either */
3378 *mem_out
= mem_cached
;
3380 /* LCOV_EXCL_STOP */
3383 #if SIZE_MAX != UINT64_MAX
3385 /* I think this could happen if we're a 32-bit Tor running on a 64-bit
3386 * system: we could have more system memory than would fit in a
3392 *mem_out
= mem_cached
= (size_t) m
;
3397 /** Emit the password prompt <b>prompt</b>, then read up to <b>buflen</b>
3398 * bytes of passphrase into <b>output</b>. Return the number of bytes in
3399 * the passphrase, excluding terminating NUL.
3402 tor_getpass(const char *prompt
, char *output
, size_t buflen
)
3404 tor_assert(buflen
<= SSIZE_MAX
);
3405 tor_assert(buflen
>= 1);
3406 #if defined(HAVE_READPASSPHRASE)
3407 char *pwd
= readpassphrase(prompt
, output
, buflen
, RPP_ECHO_OFF
);
3411 #elif defined(_WIN32)
3417 tor_assert(buflen
<= INT_MAX
);
3418 wchar_t *buf
= tor_calloc(buflen
, sizeof(wchar_t));
3420 wchar_t *ptr
= buf
, *lastch
= buf
+ buflen
- 1;
3421 while (ptr
< lastch
) {
3422 wint_t ch
= _getwch();
3429 goto done
; /* Can't actually read ctrl-c this way. */
3436 ch
= _getwch(); /* Ignore; this is a function or arrow key */
3446 #ifndef WC_ERR_INVALID_CHARS
3447 #define WC_ERR_INVALID_CHARS 0x80
3450 /* Now convert it to UTF-8 */
3451 r
= WideCharToMultiByte(CP_UTF8
,
3452 WC_NO_BEST_FIT_CHARS
|WC_ERR_INVALID_CHARS
,
3453 buf
, (int)(ptr
-buf
),
3454 output
, (int)(buflen
-1),
3461 tor_assert(r
< (int)buflen
);
3466 SecureZeroMemory(buf
, sizeof(wchar_t)*buflen
);
3470 #error "No implementation for tor_getpass found!"
3474 /** Return the amount of free disk space we have permission to use, in
3475 * bytes. Return -1 if the amount of free space can't be determined. */
3477 tor_get_avail_disk_space(const char *path
)
3482 memset(&st
, 0, sizeof(st
));
3484 r
= statvfs(path
, &st
);
3488 int64_t result
= st
.f_bavail
;
3490 result
*= st
.f_frsize
;
3491 } else if (st
.f_bsize
) {
3492 result
*= st
.f_bsize
;
3498 #elif defined(_WIN32)
3499 ULARGE_INTEGER freeBytesAvail
;
3502 ok
= GetDiskFreeSpaceEx(path
, &freeBytesAvail
, NULL
, NULL
);
3506 return (int64_t)freeBytesAvail
.QuadPart
;