compat.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919
  1. /* Copyright (c) 2003-2004, Roger Dingledine
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2018, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. /**
  6. * \file compat.c
  7. * \brief Wrappers to make calls more portable. This code defines
  8. * functions such as tor_snprintf, get/set various data types,
  9. * renaming, setting socket options, switching user IDs. It is basically
  10. * where the non-portable items are conditionally included depending on
  11. * the platform.
  12. **/
  13. #define COMPAT_PRIVATE
  14. #include "common/compat.h"
  15. #ifdef _WIN32
  16. #include <winsock2.h>
  17. #include <windows.h>
  18. #include <sys/locking.h>
  19. #endif
  20. #ifdef HAVE_UNAME
  21. #include <sys/utsname.h>
  22. #endif
  23. #ifdef HAVE_SYS_TYPES_H
  24. #include <sys/types.h>
  25. #endif
  26. #ifdef HAVE_SYS_SYSCTL_H
  27. #include <sys/sysctl.h>
  28. #endif
  29. #ifdef HAVE_SYS_STAT_H
  30. #include <sys/stat.h>
  31. #endif
  32. #ifdef HAVE_UTIME_H
  33. #include <utime.h>
  34. #endif
  35. #ifdef HAVE_SYS_UTIME_H
  36. #include <sys/utime.h>
  37. #endif
  38. #ifdef HAVE_UNISTD_H
  39. #include <unistd.h>
  40. #endif
  41. #ifdef HAVE_SYS_FCNTL_H
  42. #include <sys/fcntl.h>
  43. #endif
  44. #ifdef HAVE_PWD_H
  45. #include <pwd.h>
  46. #endif
  47. #ifdef HAVE_GRP_H
  48. #include <grp.h>
  49. #endif
  50. #ifdef HAVE_FCNTL_H
  51. #include <fcntl.h>
  52. #endif
  53. #ifdef HAVE_ERRNO_H
  54. #include <errno.h>
  55. #endif
  56. #ifdef HAVE_ARPA_INET_H
  57. #include <arpa/inet.h>
  58. #endif
  59. #ifdef HAVE_CRT_EXTERNS_H
  60. #include <crt_externs.h>
  61. #endif
  62. #ifdef HAVE_SYS_STATVFS_H
  63. #include <sys/statvfs.h>
  64. #endif
  65. #ifdef HAVE_SYS_CAPABILITY_H
  66. #include <sys/capability.h>
  67. #endif
  68. #ifdef _WIN32
  69. #include <conio.h>
  70. #include <wchar.h>
  71. /* Some mingw headers lack these. :p */
  72. #if defined(HAVE_DECL__GETWCH) && !HAVE_DECL__GETWCH
  73. wint_t _getwch(void);
  74. #endif
  75. #ifndef WEOF
  76. #define WEOF (wchar_t)(0xFFFF)
  77. #endif
  78. #if defined(HAVE_DECL_SECUREZEROMEMORY) && !HAVE_DECL_SECUREZEROMEMORY
  79. static inline void
  80. SecureZeroMemory(PVOID ptr, SIZE_T cnt)
  81. {
  82. volatile char *vcptr = (volatile char*)ptr;
  83. while (cnt--)
  84. *vcptr++ = 0;
  85. }
  86. #endif /* defined(HAVE_DECL_SECUREZEROMEMORY) && !HAVE_DECL_SECUREZEROMEMORY */
  87. #elif defined(HAVE_READPASSPHRASE_H)
  88. #include <readpassphrase.h>
  89. #else
  90. #include "tor_readpassphrase.h"
  91. #endif /* defined(_WIN32) || ... */
  92. /* Includes for the process attaching prevention */
  93. #if defined(HAVE_SYS_PRCTL_H) && defined(__linux__)
  94. /* Only use the linux prctl; the IRIX prctl is totally different */
  95. #include <sys/prctl.h>
  96. #elif defined(__APPLE__)
  97. #include <sys/ptrace.h>
  98. #endif /* defined(HAVE_SYS_PRCTL_H) && defined(__linux__) || ... */
  99. #ifdef HAVE_NETDB_H
  100. #include <netdb.h>
  101. #endif
  102. #ifdef HAVE_SYS_PARAM_H
  103. #include <sys/param.h> /* FreeBSD needs this to know what version it is */
  104. #endif
  105. #include <stdio.h>
  106. #include <stdlib.h>
  107. #ifdef HAVE_SIGNAL_H
  108. #include <signal.h>
  109. #endif
  110. #ifdef HAVE_MMAP
  111. #include <sys/mman.h>
  112. #endif
  113. #ifdef HAVE_SYS_SYSLIMITS_H
  114. #include <sys/syslimits.h>
  115. #endif
  116. #ifdef HAVE_SYS_FILE_H
  117. #include <sys/file.h>
  118. #endif
  119. #include "lib/log/torlog.h"
  120. #include "common/util.h"
  121. #include "lib/container/smartlist.h"
  122. #include "lib/wallclock/tm_cvt.h"
  123. #include "lib/net/address.h"
  124. #include "lib/sandbox/sandbox.h"
  125. /** Represents a lockfile on which we hold the lock. */
  126. struct tor_lockfile_t {
  127. /** Name of the file */
  128. char *filename;
  129. /** File descriptor used to hold the file open */
  130. int fd;
  131. };
  132. /** Try to get a lock on the lockfile <b>filename</b>, creating it as
  133. * necessary. If someone else has the lock and <b>blocking</b> is true,
  134. * wait until the lock is available. Otherwise return immediately whether
  135. * we succeeded or not.
  136. *
  137. * Set *<b>locked_out</b> to true if somebody else had the lock, and to false
  138. * otherwise.
  139. *
  140. * Return a <b>tor_lockfile_t</b> on success, NULL on failure.
  141. *
  142. * (Implementation note: because we need to fall back to fcntl on some
  143. * platforms, these locks are per-process, not per-thread. If you want
  144. * to do in-process locking, use tor_mutex_t like a normal person.
  145. * On Windows, when <b>blocking</b> is true, the maximum time that
  146. * is actually waited is 10 seconds, after which NULL is returned
  147. * and <b>locked_out</b> is set to 1.)
  148. */
  149. tor_lockfile_t *
  150. tor_lockfile_lock(const char *filename, int blocking, int *locked_out)
  151. {
  152. tor_lockfile_t *result;
  153. int fd;
  154. *locked_out = 0;
  155. log_info(LD_FS, "Locking \"%s\"", filename);
  156. fd = tor_open_cloexec(filename, O_RDWR|O_CREAT|O_TRUNC, 0600);
  157. if (fd < 0) {
  158. log_warn(LD_FS,"Couldn't open \"%s\" for locking: %s", filename,
  159. strerror(errno));
  160. return NULL;
  161. }
  162. #ifdef _WIN32
  163. _lseek(fd, 0, SEEK_SET);
  164. if (_locking(fd, blocking ? _LK_LOCK : _LK_NBLCK, 1) < 0) {
  165. if (errno != EACCES && errno != EDEADLOCK)
  166. log_warn(LD_FS,"Couldn't lock \"%s\": %s", filename, strerror(errno));
  167. else
  168. *locked_out = 1;
  169. close(fd);
  170. return NULL;
  171. }
  172. #elif defined(HAVE_FLOCK)
  173. if (flock(fd, LOCK_EX|(blocking ? 0 : LOCK_NB)) < 0) {
  174. if (errno != EWOULDBLOCK)
  175. log_warn(LD_FS,"Couldn't lock \"%s\": %s", filename, strerror(errno));
  176. else
  177. *locked_out = 1;
  178. close(fd);
  179. return NULL;
  180. }
  181. #else
  182. {
  183. struct flock lock;
  184. memset(&lock, 0, sizeof(lock));
  185. lock.l_type = F_WRLCK;
  186. lock.l_whence = SEEK_SET;
  187. if (fcntl(fd, blocking ? F_SETLKW : F_SETLK, &lock) < 0) {
  188. if (errno != EACCES && errno != EAGAIN)
  189. log_warn(LD_FS, "Couldn't lock \"%s\": %s", filename, strerror(errno));
  190. else
  191. *locked_out = 1;
  192. close(fd);
  193. return NULL;
  194. }
  195. }
  196. #endif /* defined(_WIN32) || ... */
  197. result = tor_malloc(sizeof(tor_lockfile_t));
  198. result->filename = tor_strdup(filename);
  199. result->fd = fd;
  200. return result;
  201. }
  202. /** Release the lock held as <b>lockfile</b>. */
  203. void
  204. tor_lockfile_unlock(tor_lockfile_t *lockfile)
  205. {
  206. tor_assert(lockfile);
  207. log_info(LD_FS, "Unlocking \"%s\"", lockfile->filename);
  208. #ifdef _WIN32
  209. _lseek(lockfile->fd, 0, SEEK_SET);
  210. if (_locking(lockfile->fd, _LK_UNLCK, 1) < 0) {
  211. log_warn(LD_FS,"Error unlocking \"%s\": %s", lockfile->filename,
  212. strerror(errno));
  213. }
  214. #elif defined(HAVE_FLOCK)
  215. if (flock(lockfile->fd, LOCK_UN) < 0) {
  216. log_warn(LD_FS, "Error unlocking \"%s\": %s", lockfile->filename,
  217. strerror(errno));
  218. }
  219. #else
  220. /* Closing the lockfile is sufficient. */
  221. #endif /* defined(_WIN32) || ... */
  222. close(lockfile->fd);
  223. lockfile->fd = -1;
  224. tor_free(lockfile->filename);
  225. tor_free(lockfile);
  226. }
  227. /** Number of extra file descriptors to keep in reserve beyond those that we
  228. * tell Tor it's allowed to use. */
  229. #define ULIMIT_BUFFER 32 /* keep 32 extra fd's beyond ConnLimit_ */
  230. /** Learn the maximum allowed number of file descriptors, and tell the
  231. * system we want to use up to that number. (Some systems have a low soft
  232. * limit, and let us set it higher.) We compute this by finding the largest
  233. * number that we can use.
  234. *
  235. * If the limit is below the reserved file descriptor value (ULIMIT_BUFFER),
  236. * return -1 and <b>max_out</b> is untouched.
  237. *
  238. * If we can't find a number greater than or equal to <b>limit</b>, then we
  239. * fail by returning -1 and <b>max_out</b> is untouched.
  240. *
  241. * If we are unable to set the limit value because of setrlimit() failing,
  242. * return 0 and <b>max_out</b> is set to the current maximum value returned
  243. * by getrlimit().
  244. *
  245. * Otherwise, return 0 and store the maximum we found inside <b>max_out</b>
  246. * and set <b>max_sockets</b> with that value as well.*/
  247. int
  248. set_max_file_descriptors(rlim_t limit, int *max_out)
  249. {
  250. if (limit < ULIMIT_BUFFER) {
  251. log_warn(LD_CONFIG,
  252. "ConnLimit must be at least %d. Failing.", ULIMIT_BUFFER);
  253. return -1;
  254. }
  255. /* Define some maximum connections values for systems where we cannot
  256. * automatically determine a limit. Re Cygwin, see
  257. * http://archives.seul.org/or/talk/Aug-2006/msg00210.html
  258. * For an iPhone, 9999 should work. For Windows and all other unknown
  259. * systems we use 15000 as the default. */
  260. #ifndef HAVE_GETRLIMIT
  261. #if defined(CYGWIN) || defined(__CYGWIN__)
  262. const char *platform = "Cygwin";
  263. const unsigned long MAX_CONNECTIONS = 3200;
  264. #elif defined(_WIN32)
  265. const char *platform = "Windows";
  266. const unsigned long MAX_CONNECTIONS = 15000;
  267. #else
  268. const char *platform = "unknown platforms with no getrlimit()";
  269. const unsigned long MAX_CONNECTIONS = 15000;
  270. #endif /* defined(CYGWIN) || defined(__CYGWIN__) || ... */
  271. log_fn(LOG_INFO, LD_NET,
  272. "This platform is missing getrlimit(). Proceeding.");
  273. if (limit > MAX_CONNECTIONS) {
  274. log_warn(LD_CONFIG,
  275. "We do not support more than %lu file descriptors "
  276. "on %s. Tried to raise to %lu.",
  277. (unsigned long)MAX_CONNECTIONS, platform, (unsigned long)limit);
  278. return -1;
  279. }
  280. limit = MAX_CONNECTIONS;
  281. #else /* !(!defined(HAVE_GETRLIMIT)) */
  282. struct rlimit rlim;
  283. if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) {
  284. log_warn(LD_NET, "Could not get maximum number of file descriptors: %s",
  285. strerror(errno));
  286. return -1;
  287. }
  288. if (rlim.rlim_max < limit) {
  289. log_warn(LD_CONFIG,"We need %lu file descriptors available, and we're "
  290. "limited to %lu. Please change your ulimit -n.",
  291. (unsigned long)limit, (unsigned long)rlim.rlim_max);
  292. return -1;
  293. }
  294. if (rlim.rlim_max > rlim.rlim_cur) {
  295. log_info(LD_NET,"Raising max file descriptors from %lu to %lu.",
  296. (unsigned long)rlim.rlim_cur, (unsigned long)rlim.rlim_max);
  297. }
  298. /* Set the current limit value so if the attempt to set the limit to the
  299. * max fails at least we'll have a valid value of maximum sockets. */
  300. *max_out = (int)rlim.rlim_cur - ULIMIT_BUFFER;
  301. set_max_sockets(*max_out);
  302. rlim.rlim_cur = rlim.rlim_max;
  303. if (setrlimit(RLIMIT_NOFILE, &rlim) != 0) {
  304. int couldnt_set = 1;
  305. const int setrlimit_errno = errno;
  306. #ifdef OPEN_MAX
  307. uint64_t try_limit = OPEN_MAX - ULIMIT_BUFFER;
  308. if (errno == EINVAL && try_limit < (uint64_t) rlim.rlim_cur) {
  309. /* On some platforms, OPEN_MAX is the real limit, and getrlimit() is
  310. * full of nasty lies. I'm looking at you, OSX 10.5.... */
  311. rlim.rlim_cur = MIN((rlim_t) try_limit, rlim.rlim_cur);
  312. if (setrlimit(RLIMIT_NOFILE, &rlim) == 0) {
  313. if (rlim.rlim_cur < (rlim_t)limit) {
  314. log_warn(LD_CONFIG, "We are limited to %lu file descriptors by "
  315. "OPEN_MAX (%lu), and ConnLimit is %lu. Changing "
  316. "ConnLimit; sorry.",
  317. (unsigned long)try_limit, (unsigned long)OPEN_MAX,
  318. (unsigned long)limit);
  319. } else {
  320. log_info(LD_CONFIG, "Dropped connection limit to %lu based on "
  321. "OPEN_MAX (%lu); Apparently, %lu was too high and rlimit "
  322. "lied to us.",
  323. (unsigned long)try_limit, (unsigned long)OPEN_MAX,
  324. (unsigned long)rlim.rlim_max);
  325. }
  326. couldnt_set = 0;
  327. }
  328. }
  329. #endif /* defined(OPEN_MAX) */
  330. if (couldnt_set) {
  331. log_warn(LD_CONFIG,"Couldn't set maximum number of file descriptors: %s",
  332. strerror(setrlimit_errno));
  333. }
  334. }
  335. /* leave some overhead for logs, etc, */
  336. limit = rlim.rlim_cur;
  337. #endif /* !defined(HAVE_GETRLIMIT) */
  338. if (limit > INT_MAX)
  339. limit = INT_MAX;
  340. tor_assert(max_out);
  341. *max_out = (int)limit - ULIMIT_BUFFER;
  342. set_max_sockets(*max_out);
  343. return 0;
  344. }
  345. /** Get name of current host and write it to <b>name</b> array, whose
  346. * length is specified by <b>namelen</b> argument. Return 0 upon
  347. * successful completion; otherwise return return -1. (Currently,
  348. * this function is merely a mockable wrapper for POSIX gethostname().)
  349. */
  350. MOCK_IMPL(int,
  351. tor_gethostname,(char *name, size_t namelen))
  352. {
  353. return gethostname(name,namelen);
  354. }
  355. /** Hold the result of our call to <b>uname</b>. */
  356. static char uname_result[256];
  357. /** True iff uname_result is set. */
  358. static int uname_result_is_set = 0;
  359. /** Return a pointer to a description of our platform.
  360. */
  361. MOCK_IMPL(const char *,
  362. get_uname,(void))
  363. {
  364. #ifdef HAVE_UNAME
  365. struct utsname u;
  366. #endif
  367. if (!uname_result_is_set) {
  368. #ifdef HAVE_UNAME
  369. if (uname(&u) != -1) {
  370. /* (Linux says 0 is success, Solaris says 1 is success) */
  371. strlcpy(uname_result, u.sysname, sizeof(uname_result));
  372. } else
  373. #endif /* defined(HAVE_UNAME) */
  374. {
  375. #ifdef _WIN32
  376. OSVERSIONINFOEX info;
  377. int i;
  378. const char *plat = NULL;
  379. static struct {
  380. unsigned major; unsigned minor; const char *version;
  381. } win_version_table[] = {
  382. { 6, 2, "Windows 8" },
  383. { 6, 1, "Windows 7" },
  384. { 6, 0, "Windows Vista" },
  385. { 5, 2, "Windows Server 2003" },
  386. { 5, 1, "Windows XP" },
  387. { 5, 0, "Windows 2000" },
  388. /* { 4, 0, "Windows NT 4.0" }, */
  389. { 4, 90, "Windows Me" },
  390. { 4, 10, "Windows 98" },
  391. /* { 4, 0, "Windows 95" } */
  392. { 3, 51, "Windows NT 3.51" },
  393. { 0, 0, NULL }
  394. };
  395. memset(&info, 0, sizeof(info));
  396. info.dwOSVersionInfoSize = sizeof(info);
  397. if (! GetVersionEx((LPOSVERSIONINFO)&info)) {
  398. strlcpy(uname_result, "Bizarre version of Windows where GetVersionEx"
  399. " doesn't work.", sizeof(uname_result));
  400. uname_result_is_set = 1;
  401. return uname_result;
  402. }
  403. if (info.dwMajorVersion == 4 && info.dwMinorVersion == 0) {
  404. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  405. plat = "Windows NT 4.0";
  406. else
  407. plat = "Windows 95";
  408. } else {
  409. for (i=0; win_version_table[i].major>0; ++i) {
  410. if (win_version_table[i].major == info.dwMajorVersion &&
  411. win_version_table[i].minor == info.dwMinorVersion) {
  412. plat = win_version_table[i].version;
  413. break;
  414. }
  415. }
  416. }
  417. if (plat) {
  418. strlcpy(uname_result, plat, sizeof(uname_result));
  419. } else {
  420. if (info.dwMajorVersion > 6 ||
  421. (info.dwMajorVersion==6 && info.dwMinorVersion>2))
  422. tor_snprintf(uname_result, sizeof(uname_result),
  423. "Very recent version of Windows [major=%d,minor=%d]",
  424. (int)info.dwMajorVersion,(int)info.dwMinorVersion);
  425. else
  426. tor_snprintf(uname_result, sizeof(uname_result),
  427. "Unrecognized version of Windows [major=%d,minor=%d]",
  428. (int)info.dwMajorVersion,(int)info.dwMinorVersion);
  429. }
  430. #ifdef VER_NT_SERVER
  431. if (info.wProductType == VER_NT_SERVER ||
  432. info.wProductType == VER_NT_DOMAIN_CONTROLLER) {
  433. strlcat(uname_result, " [server]", sizeof(uname_result));
  434. }
  435. #endif /* defined(VER_NT_SERVER) */
  436. #else /* !(defined(_WIN32)) */
  437. /* LCOV_EXCL_START -- can't provoke uname failure */
  438. strlcpy(uname_result, "Unknown platform", sizeof(uname_result));
  439. /* LCOV_EXCL_STOP */
  440. #endif /* defined(_WIN32) */
  441. }
  442. uname_result_is_set = 1;
  443. }
  444. return uname_result;
  445. }
  446. /*
  447. * Process control
  448. */
  449. /** Implementation logic for compute_num_cpus(). */
  450. static int
  451. compute_num_cpus_impl(void)
  452. {
  453. #ifdef _WIN32
  454. SYSTEM_INFO info;
  455. memset(&info, 0, sizeof(info));
  456. GetSystemInfo(&info);
  457. if (info.dwNumberOfProcessors >= 1 && info.dwNumberOfProcessors < INT_MAX)
  458. return (int)info.dwNumberOfProcessors;
  459. else
  460. return -1;
  461. #elif defined(HAVE_SYSCONF)
  462. #ifdef _SC_NPROCESSORS_CONF
  463. long cpus_conf = sysconf(_SC_NPROCESSORS_CONF);
  464. #else
  465. long cpus_conf = -1;
  466. #endif
  467. #ifdef _SC_NPROCESSORS_ONLN
  468. long cpus_onln = sysconf(_SC_NPROCESSORS_ONLN);
  469. #else
  470. long cpus_onln = -1;
  471. #endif
  472. long cpus = -1;
  473. if (cpus_conf > 0 && cpus_onln < 0) {
  474. cpus = cpus_conf;
  475. } else if (cpus_onln > 0 && cpus_conf < 0) {
  476. cpus = cpus_onln;
  477. } else if (cpus_onln > 0 && cpus_conf > 0) {
  478. if (cpus_onln < cpus_conf) {
  479. log_notice(LD_GENERAL, "I think we have %ld CPUS, but only %ld of them "
  480. "are available. Telling Tor to only use %ld. You can over"
  481. "ride this with the NumCPUs option",
  482. cpus_conf, cpus_onln, cpus_onln);
  483. }
  484. cpus = cpus_onln;
  485. }
  486. if (cpus >= 1 && cpus < INT_MAX)
  487. return (int)cpus;
  488. else
  489. return -1;
  490. #else
  491. return -1;
  492. #endif /* defined(_WIN32) || ... */
  493. }
  494. #define MAX_DETECTABLE_CPUS 16
  495. /** Return how many CPUs we are running with. We assume that nobody is
  496. * using hot-swappable CPUs, so we don't recompute this after the first
  497. * time. Return -1 if we don't know how to tell the number of CPUs on this
  498. * system.
  499. */
  500. int
  501. compute_num_cpus(void)
  502. {
  503. static int num_cpus = -2;
  504. if (num_cpus == -2) {
  505. num_cpus = compute_num_cpus_impl();
  506. tor_assert(num_cpus != -2);
  507. if (num_cpus > MAX_DETECTABLE_CPUS) {
  508. /* LCOV_EXCL_START */
  509. log_notice(LD_GENERAL, "Wow! I detected that you have %d CPUs. I "
  510. "will not autodetect any more than %d, though. If you "
  511. "want to configure more, set NumCPUs in your torrc",
  512. num_cpus, MAX_DETECTABLE_CPUS);
  513. num_cpus = MAX_DETECTABLE_CPUS;
  514. /* LCOV_EXCL_STOP */
  515. }
  516. }
  517. return num_cpus;
  518. }
  519. /**
  520. * On Windows, WSAEWOULDBLOCK is not always correct: when you see it,
  521. * you need to ask the socket for its actual errno. Also, you need to
  522. * get your errors from WSAGetLastError, not errno. (If you supply a
  523. * socket of -1, we check WSAGetLastError, but don't correct
  524. * WSAEWOULDBLOCKs.)
  525. *
  526. * The upshot of all of this is that when a socket call fails, you
  527. * should call tor_socket_errno <em>at most once</em> on the failing
  528. * socket to get the error.
  529. */
  530. #if defined(_WIN32)
  531. int
  532. tor_socket_errno(tor_socket_t sock)
  533. {
  534. int optval, optvallen=sizeof(optval);
  535. int err = WSAGetLastError();
  536. if (err == WSAEWOULDBLOCK && SOCKET_OK(sock)) {
  537. if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval, &optvallen))
  538. return err;
  539. if (optval)
  540. return optval;
  541. }
  542. return err;
  543. }
  544. #endif /* defined(_WIN32) */
  545. #if defined(_WIN32)
  546. #define E(code, s) { code, (s " [" #code " ]") }
  547. struct { int code; const char *msg; } windows_socket_errors[] = {
  548. E(WSAEINTR, "Interrupted function call"),
  549. E(WSAEACCES, "Permission denied"),
  550. E(WSAEFAULT, "Bad address"),
  551. E(WSAEINVAL, "Invalid argument"),
  552. E(WSAEMFILE, "Too many open files"),
  553. E(WSAEWOULDBLOCK, "Resource temporarily unavailable"),
  554. E(WSAEINPROGRESS, "Operation now in progress"),
  555. E(WSAEALREADY, "Operation already in progress"),
  556. E(WSAENOTSOCK, "Socket operation on nonsocket"),
  557. E(WSAEDESTADDRREQ, "Destination address required"),
  558. E(WSAEMSGSIZE, "Message too long"),
  559. E(WSAEPROTOTYPE, "Protocol wrong for socket"),
  560. E(WSAENOPROTOOPT, "Bad protocol option"),
  561. E(WSAEPROTONOSUPPORT, "Protocol not supported"),
  562. E(WSAESOCKTNOSUPPORT, "Socket type not supported"),
  563. /* What's the difference between NOTSUPP and NOSUPPORT? :) */
  564. E(WSAEOPNOTSUPP, "Operation not supported"),
  565. E(WSAEPFNOSUPPORT, "Protocol family not supported"),
  566. E(WSAEAFNOSUPPORT, "Address family not supported by protocol family"),
  567. E(WSAEADDRINUSE, "Address already in use"),
  568. E(WSAEADDRNOTAVAIL, "Cannot assign requested address"),
  569. E(WSAENETDOWN, "Network is down"),
  570. E(WSAENETUNREACH, "Network is unreachable"),
  571. E(WSAENETRESET, "Network dropped connection on reset"),
  572. E(WSAECONNABORTED, "Software caused connection abort"),
  573. E(WSAECONNRESET, "Connection reset by peer"),
  574. E(WSAENOBUFS, "No buffer space available"),
  575. E(WSAEISCONN, "Socket is already connected"),
  576. E(WSAENOTCONN, "Socket is not connected"),
  577. E(WSAESHUTDOWN, "Cannot send after socket shutdown"),
  578. E(WSAETIMEDOUT, "Connection timed out"),
  579. E(WSAECONNREFUSED, "Connection refused"),
  580. E(WSAEHOSTDOWN, "Host is down"),
  581. E(WSAEHOSTUNREACH, "No route to host"),
  582. E(WSAEPROCLIM, "Too many processes"),
  583. /* Yes, some of these start with WSA, not WSAE. No, I don't know why. */
  584. E(WSASYSNOTREADY, "Network subsystem is unavailable"),
  585. E(WSAVERNOTSUPPORTED, "Winsock.dll out of range"),
  586. E(WSANOTINITIALISED, "Successful WSAStartup not yet performed"),
  587. E(WSAEDISCON, "Graceful shutdown now in progress"),
  588. #ifdef WSATYPE_NOT_FOUND
  589. E(WSATYPE_NOT_FOUND, "Class type not found"),
  590. #endif
  591. E(WSAHOST_NOT_FOUND, "Host not found"),
  592. E(WSATRY_AGAIN, "Nonauthoritative host not found"),
  593. E(WSANO_RECOVERY, "This is a nonrecoverable error"),
  594. E(WSANO_DATA, "Valid name, no data record of requested type)"),
  595. /* There are some more error codes whose numeric values are marked
  596. * <b>OS dependent</b>. They start with WSA_, apparently for the same
  597. * reason that practitioners of some craft traditions deliberately
  598. * introduce imperfections into their baskets and rugs "to allow the
  599. * evil spirits to escape." If we catch them, then our binaries
  600. * might not report consistent results across versions of Windows.
  601. * Thus, I'm going to let them all fall through.
  602. */
  603. { -1, NULL },
  604. };
  605. /** There does not seem to be a strerror equivalent for Winsock errors.
  606. * Naturally, we have to roll our own.
  607. */
  608. const char *
  609. tor_socket_strerror(int e)
  610. {
  611. int i;
  612. for (i=0; windows_socket_errors[i].code >= 0; ++i) {
  613. if (e == windows_socket_errors[i].code)
  614. return windows_socket_errors[i].msg;
  615. }
  616. return strerror(e);
  617. }
  618. #endif /* defined(_WIN32) */
  619. /** Called before we make any calls to network-related functions.
  620. * (Some operating systems require their network libraries to be
  621. * initialized.) */
  622. int
  623. network_init(void)
  624. {
  625. #ifdef _WIN32
  626. /* This silly exercise is necessary before windows will allow
  627. * gethostbyname to work. */
  628. WSADATA WSAData;
  629. int r;
  630. r = WSAStartup(0x101,&WSAData);
  631. if (r) {
  632. log_warn(LD_NET,"Error initializing windows network layer: code was %d",r);
  633. return -1;
  634. }
  635. if (sizeof(SOCKET) != sizeof(tor_socket_t)) {
  636. log_warn(LD_BUG,"The tor_socket_t type does not match SOCKET in size; Tor "
  637. "might not work. (Sizes are %d and %d respectively.)",
  638. (int)sizeof(tor_socket_t), (int)sizeof(SOCKET));
  639. }
  640. /* WSAData.iMaxSockets might show the max sockets we're allowed to use.
  641. * We might use it to complain if we're trying to be a server but have
  642. * too few sockets available. */
  643. #endif /* defined(_WIN32) */
  644. return 0;
  645. }
  646. #if defined(HW_PHYSMEM64)
  647. /* This appears to be an OpenBSD thing */
  648. #define INT64_HW_MEM HW_PHYSMEM64
  649. #elif defined(HW_MEMSIZE)
  650. /* OSX defines this one */
  651. #define INT64_HW_MEM HW_MEMSIZE
  652. #endif /* defined(HW_PHYSMEM64) || ... */
  653. /**
  654. * Helper: try to detect the total system memory, and return it. On failure,
  655. * return 0.
  656. */
  657. static uint64_t
  658. get_total_system_memory_impl(void)
  659. {
  660. #if defined(__linux__)
  661. /* On linux, sysctl is deprecated. Because proc is so awesome that you
  662. * shouldn't _want_ to write portable code, I guess? */
  663. unsigned long long result=0;
  664. int fd = -1;
  665. char *s = NULL;
  666. const char *cp;
  667. size_t file_size=0;
  668. if (-1 == (fd = tor_open_cloexec("/proc/meminfo",O_RDONLY,0)))
  669. return 0;
  670. s = read_file_to_str_until_eof(fd, 65536, &file_size);
  671. if (!s)
  672. goto err;
  673. cp = strstr(s, "MemTotal:");
  674. if (!cp)
  675. goto err;
  676. /* Use the system sscanf so that space will match a wider number of space */
  677. if (sscanf(cp, "MemTotal: %llu kB\n", &result) != 1)
  678. goto err;
  679. close(fd);
  680. tor_free(s);
  681. return result * 1024;
  682. /* LCOV_EXCL_START Can't reach this unless proc is broken. */
  683. err:
  684. tor_free(s);
  685. close(fd);
  686. return 0;
  687. /* LCOV_EXCL_STOP */
  688. #elif defined (_WIN32)
  689. /* Windows has MEMORYSTATUSEX; pretty straightforward. */
  690. MEMORYSTATUSEX ms;
  691. memset(&ms, 0, sizeof(ms));
  692. ms.dwLength = sizeof(ms);
  693. if (! GlobalMemoryStatusEx(&ms))
  694. return 0;
  695. return ms.ullTotalPhys;
  696. #elif defined(HAVE_SYSCTL) && defined(INT64_HW_MEM)
  697. /* On many systems, HW_PYHSMEM is clipped to 32 bits; let's use a better
  698. * variant if we know about it. */
  699. uint64_t memsize = 0;
  700. size_t len = sizeof(memsize);
  701. int mib[2] = {CTL_HW, INT64_HW_MEM};
  702. if (sysctl(mib,2,&memsize,&len,NULL,0))
  703. return 0;
  704. return memsize;
  705. #elif defined(HAVE_SYSCTL) && defined(HW_PHYSMEM)
  706. /* On some systems (like FreeBSD I hope) you can use a size_t with
  707. * HW_PHYSMEM. */
  708. size_t memsize=0;
  709. size_t len = sizeof(memsize);
  710. int mib[2] = {CTL_HW, HW_USERMEM};
  711. if (sysctl(mib,2,&memsize,&len,NULL,0))
  712. return 0;
  713. return memsize;
  714. #else
  715. /* I have no clue. */
  716. return 0;
  717. #endif /* defined(__linux__) || ... */
  718. }
  719. /**
  720. * Try to find out how much physical memory the system has. On success,
  721. * return 0 and set *<b>mem_out</b> to that value. On failure, return -1.
  722. */
  723. MOCK_IMPL(int,
  724. get_total_system_memory, (size_t *mem_out))
  725. {
  726. static size_t mem_cached=0;
  727. uint64_t m = get_total_system_memory_impl();
  728. if (0 == m) {
  729. /* LCOV_EXCL_START -- can't make this happen without mocking. */
  730. /* We couldn't find our memory total */
  731. if (0 == mem_cached) {
  732. /* We have no cached value either */
  733. *mem_out = 0;
  734. return -1;
  735. }
  736. *mem_out = mem_cached;
  737. return 0;
  738. /* LCOV_EXCL_STOP */
  739. }
  740. #if SIZE_MAX != UINT64_MAX
  741. if (m > SIZE_MAX) {
  742. /* I think this could happen if we're a 32-bit Tor running on a 64-bit
  743. * system: we could have more system memory than would fit in a
  744. * size_t. */
  745. m = SIZE_MAX;
  746. }
  747. #endif /* SIZE_MAX != UINT64_MAX */
  748. *mem_out = mem_cached = (size_t) m;
  749. return 0;
  750. }
  751. /** Emit the password prompt <b>prompt</b>, then read up to <b>buflen</b>
  752. * bytes of passphrase into <b>output</b>. Return the number of bytes in
  753. * the passphrase, excluding terminating NUL.
  754. */
  755. ssize_t
  756. tor_getpass(const char *prompt, char *output, size_t buflen)
  757. {
  758. tor_assert(buflen <= SSIZE_MAX);
  759. tor_assert(buflen >= 1);
  760. #if defined(HAVE_READPASSPHRASE)
  761. char *pwd = readpassphrase(prompt, output, buflen, RPP_ECHO_OFF);
  762. if (pwd == NULL)
  763. return -1;
  764. return strlen(pwd);
  765. #elif defined(_WIN32)
  766. int r = -1;
  767. while (*prompt) {
  768. _putch(*prompt++);
  769. }
  770. tor_assert(buflen <= INT_MAX);
  771. wchar_t *buf = tor_calloc(buflen, sizeof(wchar_t));
  772. wchar_t *ptr = buf, *lastch = buf + buflen - 1;
  773. while (ptr < lastch) {
  774. wint_t ch = _getwch();
  775. switch (ch) {
  776. case '\r':
  777. case '\n':
  778. case WEOF:
  779. goto done_reading;
  780. case 3:
  781. goto done; /* Can't actually read ctrl-c this way. */
  782. case '\b':
  783. if (ptr > buf)
  784. --ptr;
  785. continue;
  786. case 0:
  787. case 0xe0:
  788. ch = _getwch(); /* Ignore; this is a function or arrow key */
  789. break;
  790. default:
  791. *ptr++ = ch;
  792. break;
  793. }
  794. }
  795. done_reading:
  796. ;
  797. #ifndef WC_ERR_INVALID_CHARS
  798. #define WC_ERR_INVALID_CHARS 0x80
  799. #endif
  800. /* Now convert it to UTF-8 */
  801. r = WideCharToMultiByte(CP_UTF8,
  802. WC_NO_BEST_FIT_CHARS|WC_ERR_INVALID_CHARS,
  803. buf, (int)(ptr-buf),
  804. output, (int)(buflen-1),
  805. NULL, NULL);
  806. if (r <= 0) {
  807. r = -1;
  808. goto done;
  809. }
  810. tor_assert(r < (int)buflen);
  811. output[r] = 0;
  812. done:
  813. SecureZeroMemory(buf, sizeof(wchar_t)*buflen);
  814. tor_free(buf);
  815. return r;
  816. #else
  817. #error "No implementation for tor_getpass found!"
  818. #endif /* defined(HAVE_READPASSPHRASE) || ... */
  819. }
  820. /** Return the amount of free disk space we have permission to use, in
  821. * bytes. Return -1 if the amount of free space can't be determined. */
  822. int64_t
  823. tor_get_avail_disk_space(const char *path)
  824. {
  825. #ifdef HAVE_STATVFS
  826. struct statvfs st;
  827. int r;
  828. memset(&st, 0, sizeof(st));
  829. r = statvfs(path, &st);
  830. if (r < 0)
  831. return -1;
  832. int64_t result = st.f_bavail;
  833. if (st.f_frsize) {
  834. result *= st.f_frsize;
  835. } else if (st.f_bsize) {
  836. result *= st.f_bsize;
  837. } else {
  838. return -1;
  839. }
  840. return result;
  841. #elif defined(_WIN32)
  842. ULARGE_INTEGER freeBytesAvail;
  843. BOOL ok;
  844. ok = GetDiskFreeSpaceEx(path, &freeBytesAvail, NULL, NULL);
  845. if (!ok) {
  846. return -1;
  847. }
  848. return (int64_t)freeBytesAvail.QuadPart;
  849. #else
  850. (void)path;
  851. errno = ENOSYS;
  852. return -1;
  853. #endif /* defined(HAVE_STATVFS) || ... */
  854. }