compat.c 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455
  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. #ifndef _WIN32
  346. /** Log details of current user and group credentials. Return 0 on
  347. * success. Logs and return -1 on failure.
  348. */
  349. static int
  350. log_credential_status(void)
  351. {
  352. /** Log level to use when describing non-error UID/GID status. */
  353. #define CREDENTIAL_LOG_LEVEL LOG_INFO
  354. /* Real, effective and saved UIDs */
  355. uid_t ruid, euid, suid;
  356. /* Read, effective and saved GIDs */
  357. gid_t rgid, egid, sgid;
  358. /* Supplementary groups */
  359. gid_t *sup_gids = NULL;
  360. int sup_gids_size;
  361. /* Number of supplementary groups */
  362. int ngids;
  363. /* log UIDs */
  364. #ifdef HAVE_GETRESUID
  365. if (getresuid(&ruid, &euid, &suid) != 0 ) {
  366. log_warn(LD_GENERAL, "Error getting changed UIDs: %s", strerror(errno));
  367. return -1;
  368. } else {
  369. log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
  370. "UID is %u (real), %u (effective), %u (saved)",
  371. (unsigned)ruid, (unsigned)euid, (unsigned)suid);
  372. }
  373. #else /* !(defined(HAVE_GETRESUID)) */
  374. /* getresuid is not present on MacOS X, so we can't get the saved (E)UID */
  375. ruid = getuid();
  376. euid = geteuid();
  377. (void)suid;
  378. log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
  379. "UID is %u (real), %u (effective), unknown (saved)",
  380. (unsigned)ruid, (unsigned)euid);
  381. #endif /* defined(HAVE_GETRESUID) */
  382. /* log GIDs */
  383. #ifdef HAVE_GETRESGID
  384. if (getresgid(&rgid, &egid, &sgid) != 0 ) {
  385. log_warn(LD_GENERAL, "Error getting changed GIDs: %s", strerror(errno));
  386. return -1;
  387. } else {
  388. log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
  389. "GID is %u (real), %u (effective), %u (saved)",
  390. (unsigned)rgid, (unsigned)egid, (unsigned)sgid);
  391. }
  392. #else /* !(defined(HAVE_GETRESGID)) */
  393. /* getresgid is not present on MacOS X, so we can't get the saved (E)GID */
  394. rgid = getgid();
  395. egid = getegid();
  396. (void)sgid;
  397. log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
  398. "GID is %u (real), %u (effective), unknown (saved)",
  399. (unsigned)rgid, (unsigned)egid);
  400. #endif /* defined(HAVE_GETRESGID) */
  401. /* log supplementary groups */
  402. sup_gids_size = 64;
  403. sup_gids = tor_calloc(64, sizeof(gid_t));
  404. while ((ngids = getgroups(sup_gids_size, sup_gids)) < 0 &&
  405. errno == EINVAL &&
  406. sup_gids_size < NGROUPS_MAX) {
  407. sup_gids_size *= 2;
  408. sup_gids = tor_reallocarray(sup_gids, sizeof(gid_t), sup_gids_size);
  409. }
  410. if (ngids < 0) {
  411. log_warn(LD_GENERAL, "Error getting supplementary GIDs: %s",
  412. strerror(errno));
  413. tor_free(sup_gids);
  414. return -1;
  415. } else {
  416. int i, retval = 0;
  417. char *s = NULL;
  418. smartlist_t *elts = smartlist_new();
  419. for (i = 0; i<ngids; i++) {
  420. smartlist_add_asprintf(elts, "%u", (unsigned)sup_gids[i]);
  421. }
  422. s = smartlist_join_strings(elts, " ", 0, NULL);
  423. log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL, "Supplementary groups are: %s",s);
  424. tor_free(s);
  425. SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
  426. smartlist_free(elts);
  427. tor_free(sup_gids);
  428. return retval;
  429. }
  430. return 0;
  431. }
  432. #endif /* !defined(_WIN32) */
  433. /** Return true iff we were compiled with capability support, and capabilities
  434. * seem to work. **/
  435. int
  436. have_capability_support(void)
  437. {
  438. #ifdef HAVE_LINUX_CAPABILITIES
  439. cap_t caps = cap_get_proc();
  440. if (caps == NULL)
  441. return 0;
  442. cap_free(caps);
  443. return 1;
  444. #else /* !(defined(HAVE_LINUX_CAPABILITIES)) */
  445. return 0;
  446. #endif /* defined(HAVE_LINUX_CAPABILITIES) */
  447. }
  448. #ifdef HAVE_LINUX_CAPABILITIES
  449. /** Helper. Drop all capabilities but a small set, and set PR_KEEPCAPS as
  450. * appropriate.
  451. *
  452. * If pre_setuid, retain only CAP_NET_BIND_SERVICE, CAP_SETUID, and
  453. * CAP_SETGID, and use PR_KEEPCAPS to ensure that capabilities persist across
  454. * setuid().
  455. *
  456. * If not pre_setuid, retain only CAP_NET_BIND_SERVICE, and disable
  457. * PR_KEEPCAPS.
  458. *
  459. * Return 0 on success, and -1 on failure.
  460. */
  461. static int
  462. drop_capabilities(int pre_setuid)
  463. {
  464. /* We keep these three capabilities, and these only, as we setuid.
  465. * After we setuid, we drop all but the first. */
  466. const cap_value_t caplist[] = {
  467. CAP_NET_BIND_SERVICE, CAP_SETUID, CAP_SETGID
  468. };
  469. const char *where = pre_setuid ? "pre-setuid" : "post-setuid";
  470. const int n_effective = pre_setuid ? 3 : 1;
  471. const int n_permitted = pre_setuid ? 3 : 1;
  472. const int n_inheritable = 1;
  473. const int keepcaps = pre_setuid ? 1 : 0;
  474. /* Sets whether we keep capabilities across a setuid. */
  475. if (prctl(PR_SET_KEEPCAPS, keepcaps) < 0) {
  476. log_warn(LD_CONFIG, "Unable to call prctl() %s: %s",
  477. where, strerror(errno));
  478. return -1;
  479. }
  480. cap_t caps = cap_get_proc();
  481. if (!caps) {
  482. log_warn(LD_CONFIG, "Unable to call cap_get_proc() %s: %s",
  483. where, strerror(errno));
  484. return -1;
  485. }
  486. cap_clear(caps);
  487. cap_set_flag(caps, CAP_EFFECTIVE, n_effective, caplist, CAP_SET);
  488. cap_set_flag(caps, CAP_PERMITTED, n_permitted, caplist, CAP_SET);
  489. cap_set_flag(caps, CAP_INHERITABLE, n_inheritable, caplist, CAP_SET);
  490. int r = cap_set_proc(caps);
  491. cap_free(caps);
  492. if (r < 0) {
  493. log_warn(LD_CONFIG, "No permission to set capabilities %s: %s",
  494. where, strerror(errno));
  495. return -1;
  496. }
  497. return 0;
  498. }
  499. #endif /* defined(HAVE_LINUX_CAPABILITIES) */
  500. /** Call setuid and setgid to run as <b>user</b> and switch to their
  501. * primary group. Return 0 on success. On failure, log and return -1.
  502. *
  503. * If SWITCH_ID_KEEP_BINDLOW is set in 'flags', try to use the capability
  504. * system to retain the abilitity to bind low ports.
  505. *
  506. * If SWITCH_ID_WARN_IF_NO_CAPS is set in flags, also warn if we have
  507. * don't have capability support.
  508. */
  509. int
  510. switch_id(const char *user, const unsigned flags)
  511. {
  512. #ifndef _WIN32
  513. const struct passwd *pw = NULL;
  514. uid_t old_uid;
  515. gid_t old_gid;
  516. static int have_already_switched_id = 0;
  517. const int keep_bindlow = !!(flags & SWITCH_ID_KEEP_BINDLOW);
  518. const int warn_if_no_caps = !!(flags & SWITCH_ID_WARN_IF_NO_CAPS);
  519. tor_assert(user);
  520. if (have_already_switched_id)
  521. return 0;
  522. /* Log the initial credential state */
  523. if (log_credential_status())
  524. return -1;
  525. log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL, "Changing user and groups");
  526. /* Get old UID/GID to check if we changed correctly */
  527. old_uid = getuid();
  528. old_gid = getgid();
  529. /* Lookup the user and group information, if we have a problem, bail out. */
  530. pw = tor_getpwnam(user);
  531. if (pw == NULL) {
  532. log_warn(LD_CONFIG, "Error setting configured user: %s not found", user);
  533. return -1;
  534. }
  535. #ifdef HAVE_LINUX_CAPABILITIES
  536. (void) warn_if_no_caps;
  537. if (keep_bindlow) {
  538. if (drop_capabilities(1))
  539. return -1;
  540. }
  541. #else /* !(defined(HAVE_LINUX_CAPABILITIES)) */
  542. (void) keep_bindlow;
  543. if (warn_if_no_caps) {
  544. log_warn(LD_CONFIG, "KeepBindCapabilities set, but no capability support "
  545. "on this system.");
  546. }
  547. #endif /* defined(HAVE_LINUX_CAPABILITIES) */
  548. /* Properly switch egid,gid,euid,uid here or bail out */
  549. if (setgroups(1, &pw->pw_gid)) {
  550. log_warn(LD_GENERAL, "Error setting groups to gid %d: \"%s\".",
  551. (int)pw->pw_gid, strerror(errno));
  552. if (old_uid == pw->pw_uid) {
  553. log_warn(LD_GENERAL, "Tor is already running as %s. You do not need "
  554. "the \"User\" option if you are already running as the user "
  555. "you want to be. (If you did not set the User option in your "
  556. "torrc, check whether it was specified on the command line "
  557. "by a startup script.)", user);
  558. } else {
  559. log_warn(LD_GENERAL, "If you set the \"User\" option, you must start Tor"
  560. " as root.");
  561. }
  562. return -1;
  563. }
  564. if (setegid(pw->pw_gid)) {
  565. log_warn(LD_GENERAL, "Error setting egid to %d: %s",
  566. (int)pw->pw_gid, strerror(errno));
  567. return -1;
  568. }
  569. if (setgid(pw->pw_gid)) {
  570. log_warn(LD_GENERAL, "Error setting gid to %d: %s",
  571. (int)pw->pw_gid, strerror(errno));
  572. return -1;
  573. }
  574. if (setuid(pw->pw_uid)) {
  575. log_warn(LD_GENERAL, "Error setting configured uid to %s (%d): %s",
  576. user, (int)pw->pw_uid, strerror(errno));
  577. return -1;
  578. }
  579. if (seteuid(pw->pw_uid)) {
  580. log_warn(LD_GENERAL, "Error setting configured euid to %s (%d): %s",
  581. user, (int)pw->pw_uid, strerror(errno));
  582. return -1;
  583. }
  584. /* This is how OpenBSD rolls:
  585. if (setgroups(1, &pw->pw_gid) || setegid(pw->pw_gid) ||
  586. setgid(pw->pw_gid) || setuid(pw->pw_uid) || seteuid(pw->pw_uid)) {
  587. setgid(pw->pw_gid) || seteuid(pw->pw_uid) || setuid(pw->pw_uid)) {
  588. log_warn(LD_GENERAL, "Error setting configured UID/GID: %s",
  589. strerror(errno));
  590. return -1;
  591. }
  592. */
  593. /* We've properly switched egid, gid, euid, uid, and supplementary groups if
  594. * we're here. */
  595. #ifdef HAVE_LINUX_CAPABILITIES
  596. if (keep_bindlow) {
  597. if (drop_capabilities(0))
  598. return -1;
  599. }
  600. #endif /* defined(HAVE_LINUX_CAPABILITIES) */
  601. #if !defined(CYGWIN) && !defined(__CYGWIN__)
  602. /* If we tried to drop privilege to a group/user other than root, attempt to
  603. * restore root (E)(U|G)ID, and abort if the operation succeeds */
  604. /* Only check for privilege dropping if we were asked to be non-root */
  605. if (pw->pw_uid) {
  606. /* Try changing GID/EGID */
  607. if (pw->pw_gid != old_gid &&
  608. (setgid(old_gid) != -1 || setegid(old_gid) != -1)) {
  609. log_warn(LD_GENERAL, "Was able to restore group credentials even after "
  610. "switching GID: this means that the setgid code didn't work.");
  611. return -1;
  612. }
  613. /* Try changing UID/EUID */
  614. if (pw->pw_uid != old_uid &&
  615. (setuid(old_uid) != -1 || seteuid(old_uid) != -1)) {
  616. log_warn(LD_GENERAL, "Was able to restore user credentials even after "
  617. "switching UID: this means that the setuid code didn't work.");
  618. return -1;
  619. }
  620. }
  621. #endif /* !defined(CYGWIN) && !defined(__CYGWIN__) */
  622. /* Check what really happened */
  623. if (log_credential_status()) {
  624. return -1;
  625. }
  626. have_already_switched_id = 1; /* mark success so we never try again */
  627. #if defined(__linux__) && defined(HAVE_SYS_PRCTL_H) && \
  628. defined(HAVE_PRCTL) && defined(PR_SET_DUMPABLE)
  629. if (pw->pw_uid) {
  630. /* Re-enable core dumps if we're not running as root. */
  631. log_info(LD_CONFIG, "Re-enabling coredumps");
  632. if (prctl(PR_SET_DUMPABLE, 1)) {
  633. log_warn(LD_CONFIG, "Unable to re-enable coredumps: %s",strerror(errno));
  634. }
  635. }
  636. #endif /* defined(__linux__) && defined(HAVE_SYS_PRCTL_H) && ... */
  637. return 0;
  638. #else /* !(!defined(_WIN32)) */
  639. (void)user;
  640. (void)flags;
  641. log_warn(LD_CONFIG, "Switching users is unsupported on your OS.");
  642. return -1;
  643. #endif /* !defined(_WIN32) */
  644. }
  645. /* We only use the linux prctl for now. There is no Win32 support; this may
  646. * also work on various BSD systems and Mac OS X - send testing feedback!
  647. *
  648. * On recent Gnu/Linux kernels it is possible to create a system-wide policy
  649. * that will prevent non-root processes from attaching to other processes
  650. * unless they are the parent process; thus gdb can attach to programs that
  651. * they execute but they cannot attach to other processes running as the same
  652. * user. The system wide policy may be set with the sysctl
  653. * kernel.yama.ptrace_scope or by inspecting
  654. * /proc/sys/kernel/yama/ptrace_scope and it is 1 by default on Ubuntu 11.04.
  655. *
  656. * This ptrace scope will be ignored on Gnu/Linux for users with
  657. * CAP_SYS_PTRACE and so it is very likely that root will still be able to
  658. * attach to the Tor process.
  659. */
  660. /** Attempt to disable debugger attachment: return 1 on success, -1 on
  661. * failure, and 0 if we don't know how to try on this platform. */
  662. int
  663. tor_disable_debugger_attach(void)
  664. {
  665. int r = -1;
  666. log_debug(LD_CONFIG,
  667. "Attemping to disable debugger attachment to Tor for "
  668. "unprivileged users.");
  669. #if defined(__linux__) && defined(HAVE_SYS_PRCTL_H) \
  670. && defined(HAVE_PRCTL) && defined(PR_SET_DUMPABLE)
  671. #define TRIED_TO_DISABLE
  672. r = prctl(PR_SET_DUMPABLE, 0);
  673. #elif defined(__APPLE__) && defined(PT_DENY_ATTACH)
  674. #define TRIED_TO_ATTACH
  675. r = ptrace(PT_DENY_ATTACH, 0, 0, 0);
  676. #endif /* defined(__linux__) && defined(HAVE_SYS_PRCTL_H) ... || ... */
  677. // XXX: TODO - Mac OS X has dtrace and this may be disabled.
  678. // XXX: TODO - Windows probably has something similar
  679. #ifdef TRIED_TO_DISABLE
  680. if (r == 0) {
  681. log_debug(LD_CONFIG,"Debugger attachment disabled for "
  682. "unprivileged users.");
  683. return 1;
  684. } else {
  685. log_warn(LD_CONFIG, "Unable to disable debugger attaching: %s",
  686. strerror(errno));
  687. }
  688. #endif /* defined(TRIED_TO_DISABLE) */
  689. #undef TRIED_TO_DISABLE
  690. return r;
  691. }
  692. #ifndef HAVE__NSGETENVIRON
  693. #ifndef HAVE_EXTERN_ENVIRON_DECLARED
  694. /* Some platforms declare environ under some circumstances, others don't. */
  695. #ifndef RUNNING_DOXYGEN
  696. extern char **environ;
  697. #endif
  698. #endif /* !defined(HAVE_EXTERN_ENVIRON_DECLARED) */
  699. #endif /* !defined(HAVE__NSGETENVIRON) */
  700. /** Return the current environment. This is a portable replacement for
  701. * 'environ'. */
  702. char **
  703. get_environment(void)
  704. {
  705. #ifdef HAVE__NSGETENVIRON
  706. /* This is for compatibility between OSX versions. Otherwise (for example)
  707. * when we do a mostly-static build on OSX 10.7, the resulting binary won't
  708. * work on OSX 10.6. */
  709. return *_NSGetEnviron();
  710. #else /* !(defined(HAVE__NSGETENVIRON)) */
  711. return environ;
  712. #endif /* defined(HAVE__NSGETENVIRON) */
  713. }
  714. /** Get name of current host and write it to <b>name</b> array, whose
  715. * length is specified by <b>namelen</b> argument. Return 0 upon
  716. * successful completion; otherwise return return -1. (Currently,
  717. * this function is merely a mockable wrapper for POSIX gethostname().)
  718. */
  719. MOCK_IMPL(int,
  720. tor_gethostname,(char *name, size_t namelen))
  721. {
  722. return gethostname(name,namelen);
  723. }
  724. /** Hold the result of our call to <b>uname</b>. */
  725. static char uname_result[256];
  726. /** True iff uname_result is set. */
  727. static int uname_result_is_set = 0;
  728. /** Return a pointer to a description of our platform.
  729. */
  730. MOCK_IMPL(const char *,
  731. get_uname,(void))
  732. {
  733. #ifdef HAVE_UNAME
  734. struct utsname u;
  735. #endif
  736. if (!uname_result_is_set) {
  737. #ifdef HAVE_UNAME
  738. if (uname(&u) != -1) {
  739. /* (Linux says 0 is success, Solaris says 1 is success) */
  740. strlcpy(uname_result, u.sysname, sizeof(uname_result));
  741. } else
  742. #endif /* defined(HAVE_UNAME) */
  743. {
  744. #ifdef _WIN32
  745. OSVERSIONINFOEX info;
  746. int i;
  747. const char *plat = NULL;
  748. static struct {
  749. unsigned major; unsigned minor; const char *version;
  750. } win_version_table[] = {
  751. { 6, 2, "Windows 8" },
  752. { 6, 1, "Windows 7" },
  753. { 6, 0, "Windows Vista" },
  754. { 5, 2, "Windows Server 2003" },
  755. { 5, 1, "Windows XP" },
  756. { 5, 0, "Windows 2000" },
  757. /* { 4, 0, "Windows NT 4.0" }, */
  758. { 4, 90, "Windows Me" },
  759. { 4, 10, "Windows 98" },
  760. /* { 4, 0, "Windows 95" } */
  761. { 3, 51, "Windows NT 3.51" },
  762. { 0, 0, NULL }
  763. };
  764. memset(&info, 0, sizeof(info));
  765. info.dwOSVersionInfoSize = sizeof(info);
  766. if (! GetVersionEx((LPOSVERSIONINFO)&info)) {
  767. strlcpy(uname_result, "Bizarre version of Windows where GetVersionEx"
  768. " doesn't work.", sizeof(uname_result));
  769. uname_result_is_set = 1;
  770. return uname_result;
  771. }
  772. if (info.dwMajorVersion == 4 && info.dwMinorVersion == 0) {
  773. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  774. plat = "Windows NT 4.0";
  775. else
  776. plat = "Windows 95";
  777. } else {
  778. for (i=0; win_version_table[i].major>0; ++i) {
  779. if (win_version_table[i].major == info.dwMajorVersion &&
  780. win_version_table[i].minor == info.dwMinorVersion) {
  781. plat = win_version_table[i].version;
  782. break;
  783. }
  784. }
  785. }
  786. if (plat) {
  787. strlcpy(uname_result, plat, sizeof(uname_result));
  788. } else {
  789. if (info.dwMajorVersion > 6 ||
  790. (info.dwMajorVersion==6 && info.dwMinorVersion>2))
  791. tor_snprintf(uname_result, sizeof(uname_result),
  792. "Very recent version of Windows [major=%d,minor=%d]",
  793. (int)info.dwMajorVersion,(int)info.dwMinorVersion);
  794. else
  795. tor_snprintf(uname_result, sizeof(uname_result),
  796. "Unrecognized version of Windows [major=%d,minor=%d]",
  797. (int)info.dwMajorVersion,(int)info.dwMinorVersion);
  798. }
  799. #ifdef VER_NT_SERVER
  800. if (info.wProductType == VER_NT_SERVER ||
  801. info.wProductType == VER_NT_DOMAIN_CONTROLLER) {
  802. strlcat(uname_result, " [server]", sizeof(uname_result));
  803. }
  804. #endif /* defined(VER_NT_SERVER) */
  805. #else /* !(defined(_WIN32)) */
  806. /* LCOV_EXCL_START -- can't provoke uname failure */
  807. strlcpy(uname_result, "Unknown platform", sizeof(uname_result));
  808. /* LCOV_EXCL_STOP */
  809. #endif /* defined(_WIN32) */
  810. }
  811. uname_result_is_set = 1;
  812. }
  813. return uname_result;
  814. }
  815. /*
  816. * Process control
  817. */
  818. /** Implementation logic for compute_num_cpus(). */
  819. static int
  820. compute_num_cpus_impl(void)
  821. {
  822. #ifdef _WIN32
  823. SYSTEM_INFO info;
  824. memset(&info, 0, sizeof(info));
  825. GetSystemInfo(&info);
  826. if (info.dwNumberOfProcessors >= 1 && info.dwNumberOfProcessors < INT_MAX)
  827. return (int)info.dwNumberOfProcessors;
  828. else
  829. return -1;
  830. #elif defined(HAVE_SYSCONF)
  831. #ifdef _SC_NPROCESSORS_CONF
  832. long cpus_conf = sysconf(_SC_NPROCESSORS_CONF);
  833. #else
  834. long cpus_conf = -1;
  835. #endif
  836. #ifdef _SC_NPROCESSORS_ONLN
  837. long cpus_onln = sysconf(_SC_NPROCESSORS_ONLN);
  838. #else
  839. long cpus_onln = -1;
  840. #endif
  841. long cpus = -1;
  842. if (cpus_conf > 0 && cpus_onln < 0) {
  843. cpus = cpus_conf;
  844. } else if (cpus_onln > 0 && cpus_conf < 0) {
  845. cpus = cpus_onln;
  846. } else if (cpus_onln > 0 && cpus_conf > 0) {
  847. if (cpus_onln < cpus_conf) {
  848. log_notice(LD_GENERAL, "I think we have %ld CPUS, but only %ld of them "
  849. "are available. Telling Tor to only use %ld. You can over"
  850. "ride this with the NumCPUs option",
  851. cpus_conf, cpus_onln, cpus_onln);
  852. }
  853. cpus = cpus_onln;
  854. }
  855. if (cpus >= 1 && cpus < INT_MAX)
  856. return (int)cpus;
  857. else
  858. return -1;
  859. #else
  860. return -1;
  861. #endif /* defined(_WIN32) || ... */
  862. }
  863. #define MAX_DETECTABLE_CPUS 16
  864. /** Return how many CPUs we are running with. We assume that nobody is
  865. * using hot-swappable CPUs, so we don't recompute this after the first
  866. * time. Return -1 if we don't know how to tell the number of CPUs on this
  867. * system.
  868. */
  869. int
  870. compute_num_cpus(void)
  871. {
  872. static int num_cpus = -2;
  873. if (num_cpus == -2) {
  874. num_cpus = compute_num_cpus_impl();
  875. tor_assert(num_cpus != -2);
  876. if (num_cpus > MAX_DETECTABLE_CPUS) {
  877. /* LCOV_EXCL_START */
  878. log_notice(LD_GENERAL, "Wow! I detected that you have %d CPUs. I "
  879. "will not autodetect any more than %d, though. If you "
  880. "want to configure more, set NumCPUs in your torrc",
  881. num_cpus, MAX_DETECTABLE_CPUS);
  882. num_cpus = MAX_DETECTABLE_CPUS;
  883. /* LCOV_EXCL_STOP */
  884. }
  885. }
  886. return num_cpus;
  887. }
  888. /** As localtime_r, but defined for platforms that don't have it:
  889. *
  890. * Convert *<b>timep</b> to a struct tm in local time, and store the value in
  891. * *<b>result</b>. Return the result on success, or NULL on failure.
  892. */
  893. struct tm *
  894. tor_localtime_r(const time_t *timep, struct tm *result)
  895. {
  896. char *err = NULL;
  897. struct tm *r = tor_localtime_r_msg(timep, result, &err);
  898. if (err) {
  899. log_warn(LD_BUG, "%s", err);
  900. tor_free(err);
  901. }
  902. return r;
  903. }
  904. /** As gmtime_r, but defined for platforms that don't have it:
  905. *
  906. * Convert *<b>timep</b> to a struct tm in UTC, and store the value in
  907. * *<b>result</b>. Return the result on success, or NULL on failure.
  908. */
  909. struct tm *
  910. tor_gmtime_r(const time_t *timep, struct tm *result)
  911. {
  912. char *err = NULL;
  913. struct tm *r = tor_gmtime_r_msg(timep, result, &err);
  914. if (err) {
  915. log_warn(LD_BUG, "%s", err);
  916. tor_free(err);
  917. }
  918. return r;
  919. }
  920. #if defined(HAVE_MLOCKALL) && HAVE_DECL_MLOCKALL && defined(RLIMIT_MEMLOCK)
  921. #define HAVE_UNIX_MLOCKALL
  922. #endif
  923. #ifdef HAVE_UNIX_MLOCKALL
  924. /** Attempt to raise the current and max rlimit to infinity for our process.
  925. * This only needs to be done once and can probably only be done when we have
  926. * not already dropped privileges.
  927. */
  928. static int
  929. tor_set_max_memlock(void)
  930. {
  931. /* Future consideration for Windows is probably SetProcessWorkingSetSize
  932. * This is similar to setting the memory rlimit of RLIMIT_MEMLOCK
  933. * http://msdn.microsoft.com/en-us/library/ms686234(VS.85).aspx
  934. */
  935. struct rlimit limit;
  936. /* RLIM_INFINITY is -1 on some platforms. */
  937. limit.rlim_cur = RLIM_INFINITY;
  938. limit.rlim_max = RLIM_INFINITY;
  939. if (setrlimit(RLIMIT_MEMLOCK, &limit) == -1) {
  940. if (errno == EPERM) {
  941. log_warn(LD_GENERAL, "You appear to lack permissions to change memory "
  942. "limits. Are you root?");
  943. }
  944. log_warn(LD_GENERAL, "Unable to raise RLIMIT_MEMLOCK: %s",
  945. strerror(errno));
  946. return -1;
  947. }
  948. return 0;
  949. }
  950. #endif /* defined(HAVE_UNIX_MLOCKALL) */
  951. /** Attempt to lock all current and all future memory pages.
  952. * This should only be called once and while we're privileged.
  953. * Like mlockall() we return 0 when we're successful and -1 when we're not.
  954. * Unlike mlockall() we return 1 if we've already attempted to lock memory.
  955. */
  956. int
  957. tor_mlockall(void)
  958. {
  959. static int memory_lock_attempted = 0;
  960. if (memory_lock_attempted) {
  961. return 1;
  962. }
  963. memory_lock_attempted = 1;
  964. /*
  965. * Future consideration for Windows may be VirtualLock
  966. * VirtualLock appears to implement mlock() but not mlockall()
  967. *
  968. * http://msdn.microsoft.com/en-us/library/aa366895(VS.85).aspx
  969. */
  970. #ifdef HAVE_UNIX_MLOCKALL
  971. if (tor_set_max_memlock() == 0) {
  972. log_debug(LD_GENERAL, "RLIMIT_MEMLOCK is now set to RLIM_INFINITY.");
  973. }
  974. if (mlockall(MCL_CURRENT|MCL_FUTURE) == 0) {
  975. log_info(LD_GENERAL, "Insecure OS paging is effectively disabled.");
  976. return 0;
  977. } else {
  978. if (errno == ENOSYS) {
  979. /* Apple - it's 2009! I'm looking at you. Grrr. */
  980. log_notice(LD_GENERAL, "It appears that mlockall() is not available on "
  981. "your platform.");
  982. } else if (errno == EPERM) {
  983. log_notice(LD_GENERAL, "It appears that you lack the permissions to "
  984. "lock memory. Are you root?");
  985. }
  986. log_notice(LD_GENERAL, "Unable to lock all current and future memory "
  987. "pages: %s", strerror(errno));
  988. return -1;
  989. }
  990. #else /* !(defined(HAVE_UNIX_MLOCKALL)) */
  991. log_warn(LD_GENERAL, "Unable to lock memory pages. mlockall() unsupported?");
  992. return -1;
  993. #endif /* defined(HAVE_UNIX_MLOCKALL) */
  994. }
  995. /**
  996. * On Windows, WSAEWOULDBLOCK is not always correct: when you see it,
  997. * you need to ask the socket for its actual errno. Also, you need to
  998. * get your errors from WSAGetLastError, not errno. (If you supply a
  999. * socket of -1, we check WSAGetLastError, but don't correct
  1000. * WSAEWOULDBLOCKs.)
  1001. *
  1002. * The upshot of all of this is that when a socket call fails, you
  1003. * should call tor_socket_errno <em>at most once</em> on the failing
  1004. * socket to get the error.
  1005. */
  1006. #if defined(_WIN32)
  1007. int
  1008. tor_socket_errno(tor_socket_t sock)
  1009. {
  1010. int optval, optvallen=sizeof(optval);
  1011. int err = WSAGetLastError();
  1012. if (err == WSAEWOULDBLOCK && SOCKET_OK(sock)) {
  1013. if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval, &optvallen))
  1014. return err;
  1015. if (optval)
  1016. return optval;
  1017. }
  1018. return err;
  1019. }
  1020. #endif /* defined(_WIN32) */
  1021. #if defined(_WIN32)
  1022. #define E(code, s) { code, (s " [" #code " ]") }
  1023. struct { int code; const char *msg; } windows_socket_errors[] = {
  1024. E(WSAEINTR, "Interrupted function call"),
  1025. E(WSAEACCES, "Permission denied"),
  1026. E(WSAEFAULT, "Bad address"),
  1027. E(WSAEINVAL, "Invalid argument"),
  1028. E(WSAEMFILE, "Too many open files"),
  1029. E(WSAEWOULDBLOCK, "Resource temporarily unavailable"),
  1030. E(WSAEINPROGRESS, "Operation now in progress"),
  1031. E(WSAEALREADY, "Operation already in progress"),
  1032. E(WSAENOTSOCK, "Socket operation on nonsocket"),
  1033. E(WSAEDESTADDRREQ, "Destination address required"),
  1034. E(WSAEMSGSIZE, "Message too long"),
  1035. E(WSAEPROTOTYPE, "Protocol wrong for socket"),
  1036. E(WSAENOPROTOOPT, "Bad protocol option"),
  1037. E(WSAEPROTONOSUPPORT, "Protocol not supported"),
  1038. E(WSAESOCKTNOSUPPORT, "Socket type not supported"),
  1039. /* What's the difference between NOTSUPP and NOSUPPORT? :) */
  1040. E(WSAEOPNOTSUPP, "Operation not supported"),
  1041. E(WSAEPFNOSUPPORT, "Protocol family not supported"),
  1042. E(WSAEAFNOSUPPORT, "Address family not supported by protocol family"),
  1043. E(WSAEADDRINUSE, "Address already in use"),
  1044. E(WSAEADDRNOTAVAIL, "Cannot assign requested address"),
  1045. E(WSAENETDOWN, "Network is down"),
  1046. E(WSAENETUNREACH, "Network is unreachable"),
  1047. E(WSAENETRESET, "Network dropped connection on reset"),
  1048. E(WSAECONNABORTED, "Software caused connection abort"),
  1049. E(WSAECONNRESET, "Connection reset by peer"),
  1050. E(WSAENOBUFS, "No buffer space available"),
  1051. E(WSAEISCONN, "Socket is already connected"),
  1052. E(WSAENOTCONN, "Socket is not connected"),
  1053. E(WSAESHUTDOWN, "Cannot send after socket shutdown"),
  1054. E(WSAETIMEDOUT, "Connection timed out"),
  1055. E(WSAECONNREFUSED, "Connection refused"),
  1056. E(WSAEHOSTDOWN, "Host is down"),
  1057. E(WSAEHOSTUNREACH, "No route to host"),
  1058. E(WSAEPROCLIM, "Too many processes"),
  1059. /* Yes, some of these start with WSA, not WSAE. No, I don't know why. */
  1060. E(WSASYSNOTREADY, "Network subsystem is unavailable"),
  1061. E(WSAVERNOTSUPPORTED, "Winsock.dll out of range"),
  1062. E(WSANOTINITIALISED, "Successful WSAStartup not yet performed"),
  1063. E(WSAEDISCON, "Graceful shutdown now in progress"),
  1064. #ifdef WSATYPE_NOT_FOUND
  1065. E(WSATYPE_NOT_FOUND, "Class type not found"),
  1066. #endif
  1067. E(WSAHOST_NOT_FOUND, "Host not found"),
  1068. E(WSATRY_AGAIN, "Nonauthoritative host not found"),
  1069. E(WSANO_RECOVERY, "This is a nonrecoverable error"),
  1070. E(WSANO_DATA, "Valid name, no data record of requested type)"),
  1071. /* There are some more error codes whose numeric values are marked
  1072. * <b>OS dependent</b>. They start with WSA_, apparently for the same
  1073. * reason that practitioners of some craft traditions deliberately
  1074. * introduce imperfections into their baskets and rugs "to allow the
  1075. * evil spirits to escape." If we catch them, then our binaries
  1076. * might not report consistent results across versions of Windows.
  1077. * Thus, I'm going to let them all fall through.
  1078. */
  1079. { -1, NULL },
  1080. };
  1081. /** There does not seem to be a strerror equivalent for Winsock errors.
  1082. * Naturally, we have to roll our own.
  1083. */
  1084. const char *
  1085. tor_socket_strerror(int e)
  1086. {
  1087. int i;
  1088. for (i=0; windows_socket_errors[i].code >= 0; ++i) {
  1089. if (e == windows_socket_errors[i].code)
  1090. return windows_socket_errors[i].msg;
  1091. }
  1092. return strerror(e);
  1093. }
  1094. #endif /* defined(_WIN32) */
  1095. /** Called before we make any calls to network-related functions.
  1096. * (Some operating systems require their network libraries to be
  1097. * initialized.) */
  1098. int
  1099. network_init(void)
  1100. {
  1101. #ifdef _WIN32
  1102. /* This silly exercise is necessary before windows will allow
  1103. * gethostbyname to work. */
  1104. WSADATA WSAData;
  1105. int r;
  1106. r = WSAStartup(0x101,&WSAData);
  1107. if (r) {
  1108. log_warn(LD_NET,"Error initializing windows network layer: code was %d",r);
  1109. return -1;
  1110. }
  1111. if (sizeof(SOCKET) != sizeof(tor_socket_t)) {
  1112. log_warn(LD_BUG,"The tor_socket_t type does not match SOCKET in size; Tor "
  1113. "might not work. (Sizes are %d and %d respectively.)",
  1114. (int)sizeof(tor_socket_t), (int)sizeof(SOCKET));
  1115. }
  1116. /* WSAData.iMaxSockets might show the max sockets we're allowed to use.
  1117. * We might use it to complain if we're trying to be a server but have
  1118. * too few sockets available. */
  1119. #endif /* defined(_WIN32) */
  1120. return 0;
  1121. }
  1122. #if defined(HW_PHYSMEM64)
  1123. /* This appears to be an OpenBSD thing */
  1124. #define INT64_HW_MEM HW_PHYSMEM64
  1125. #elif defined(HW_MEMSIZE)
  1126. /* OSX defines this one */
  1127. #define INT64_HW_MEM HW_MEMSIZE
  1128. #endif /* defined(HW_PHYSMEM64) || ... */
  1129. /**
  1130. * Helper: try to detect the total system memory, and return it. On failure,
  1131. * return 0.
  1132. */
  1133. static uint64_t
  1134. get_total_system_memory_impl(void)
  1135. {
  1136. #if defined(__linux__)
  1137. /* On linux, sysctl is deprecated. Because proc is so awesome that you
  1138. * shouldn't _want_ to write portable code, I guess? */
  1139. unsigned long long result=0;
  1140. int fd = -1;
  1141. char *s = NULL;
  1142. const char *cp;
  1143. size_t file_size=0;
  1144. if (-1 == (fd = tor_open_cloexec("/proc/meminfo",O_RDONLY,0)))
  1145. return 0;
  1146. s = read_file_to_str_until_eof(fd, 65536, &file_size);
  1147. if (!s)
  1148. goto err;
  1149. cp = strstr(s, "MemTotal:");
  1150. if (!cp)
  1151. goto err;
  1152. /* Use the system sscanf so that space will match a wider number of space */
  1153. if (sscanf(cp, "MemTotal: %llu kB\n", &result) != 1)
  1154. goto err;
  1155. close(fd);
  1156. tor_free(s);
  1157. return result * 1024;
  1158. /* LCOV_EXCL_START Can't reach this unless proc is broken. */
  1159. err:
  1160. tor_free(s);
  1161. close(fd);
  1162. return 0;
  1163. /* LCOV_EXCL_STOP */
  1164. #elif defined (_WIN32)
  1165. /* Windows has MEMORYSTATUSEX; pretty straightforward. */
  1166. MEMORYSTATUSEX ms;
  1167. memset(&ms, 0, sizeof(ms));
  1168. ms.dwLength = sizeof(ms);
  1169. if (! GlobalMemoryStatusEx(&ms))
  1170. return 0;
  1171. return ms.ullTotalPhys;
  1172. #elif defined(HAVE_SYSCTL) && defined(INT64_HW_MEM)
  1173. /* On many systems, HW_PYHSMEM is clipped to 32 bits; let's use a better
  1174. * variant if we know about it. */
  1175. uint64_t memsize = 0;
  1176. size_t len = sizeof(memsize);
  1177. int mib[2] = {CTL_HW, INT64_HW_MEM};
  1178. if (sysctl(mib,2,&memsize,&len,NULL,0))
  1179. return 0;
  1180. return memsize;
  1181. #elif defined(HAVE_SYSCTL) && defined(HW_PHYSMEM)
  1182. /* On some systems (like FreeBSD I hope) you can use a size_t with
  1183. * HW_PHYSMEM. */
  1184. size_t memsize=0;
  1185. size_t len = sizeof(memsize);
  1186. int mib[2] = {CTL_HW, HW_USERMEM};
  1187. if (sysctl(mib,2,&memsize,&len,NULL,0))
  1188. return 0;
  1189. return memsize;
  1190. #else
  1191. /* I have no clue. */
  1192. return 0;
  1193. #endif /* defined(__linux__) || ... */
  1194. }
  1195. /**
  1196. * Try to find out how much physical memory the system has. On success,
  1197. * return 0 and set *<b>mem_out</b> to that value. On failure, return -1.
  1198. */
  1199. MOCK_IMPL(int,
  1200. get_total_system_memory, (size_t *mem_out))
  1201. {
  1202. static size_t mem_cached=0;
  1203. uint64_t m = get_total_system_memory_impl();
  1204. if (0 == m) {
  1205. /* LCOV_EXCL_START -- can't make this happen without mocking. */
  1206. /* We couldn't find our memory total */
  1207. if (0 == mem_cached) {
  1208. /* We have no cached value either */
  1209. *mem_out = 0;
  1210. return -1;
  1211. }
  1212. *mem_out = mem_cached;
  1213. return 0;
  1214. /* LCOV_EXCL_STOP */
  1215. }
  1216. #if SIZE_MAX != UINT64_MAX
  1217. if (m > SIZE_MAX) {
  1218. /* I think this could happen if we're a 32-bit Tor running on a 64-bit
  1219. * system: we could have more system memory than would fit in a
  1220. * size_t. */
  1221. m = SIZE_MAX;
  1222. }
  1223. #endif /* SIZE_MAX != UINT64_MAX */
  1224. *mem_out = mem_cached = (size_t) m;
  1225. return 0;
  1226. }
  1227. /** Emit the password prompt <b>prompt</b>, then read up to <b>buflen</b>
  1228. * bytes of passphrase into <b>output</b>. Return the number of bytes in
  1229. * the passphrase, excluding terminating NUL.
  1230. */
  1231. ssize_t
  1232. tor_getpass(const char *prompt, char *output, size_t buflen)
  1233. {
  1234. tor_assert(buflen <= SSIZE_MAX);
  1235. tor_assert(buflen >= 1);
  1236. #if defined(HAVE_READPASSPHRASE)
  1237. char *pwd = readpassphrase(prompt, output, buflen, RPP_ECHO_OFF);
  1238. if (pwd == NULL)
  1239. return -1;
  1240. return strlen(pwd);
  1241. #elif defined(_WIN32)
  1242. int r = -1;
  1243. while (*prompt) {
  1244. _putch(*prompt++);
  1245. }
  1246. tor_assert(buflen <= INT_MAX);
  1247. wchar_t *buf = tor_calloc(buflen, sizeof(wchar_t));
  1248. wchar_t *ptr = buf, *lastch = buf + buflen - 1;
  1249. while (ptr < lastch) {
  1250. wint_t ch = _getwch();
  1251. switch (ch) {
  1252. case '\r':
  1253. case '\n':
  1254. case WEOF:
  1255. goto done_reading;
  1256. case 3:
  1257. goto done; /* Can't actually read ctrl-c this way. */
  1258. case '\b':
  1259. if (ptr > buf)
  1260. --ptr;
  1261. continue;
  1262. case 0:
  1263. case 0xe0:
  1264. ch = _getwch(); /* Ignore; this is a function or arrow key */
  1265. break;
  1266. default:
  1267. *ptr++ = ch;
  1268. break;
  1269. }
  1270. }
  1271. done_reading:
  1272. ;
  1273. #ifndef WC_ERR_INVALID_CHARS
  1274. #define WC_ERR_INVALID_CHARS 0x80
  1275. #endif
  1276. /* Now convert it to UTF-8 */
  1277. r = WideCharToMultiByte(CP_UTF8,
  1278. WC_NO_BEST_FIT_CHARS|WC_ERR_INVALID_CHARS,
  1279. buf, (int)(ptr-buf),
  1280. output, (int)(buflen-1),
  1281. NULL, NULL);
  1282. if (r <= 0) {
  1283. r = -1;
  1284. goto done;
  1285. }
  1286. tor_assert(r < (int)buflen);
  1287. output[r] = 0;
  1288. done:
  1289. SecureZeroMemory(buf, sizeof(wchar_t)*buflen);
  1290. tor_free(buf);
  1291. return r;
  1292. #else
  1293. #error "No implementation for tor_getpass found!"
  1294. #endif /* defined(HAVE_READPASSPHRASE) || ... */
  1295. }
  1296. /** Return the amount of free disk space we have permission to use, in
  1297. * bytes. Return -1 if the amount of free space can't be determined. */
  1298. int64_t
  1299. tor_get_avail_disk_space(const char *path)
  1300. {
  1301. #ifdef HAVE_STATVFS
  1302. struct statvfs st;
  1303. int r;
  1304. memset(&st, 0, sizeof(st));
  1305. r = statvfs(path, &st);
  1306. if (r < 0)
  1307. return -1;
  1308. int64_t result = st.f_bavail;
  1309. if (st.f_frsize) {
  1310. result *= st.f_frsize;
  1311. } else if (st.f_bsize) {
  1312. result *= st.f_bsize;
  1313. } else {
  1314. return -1;
  1315. }
  1316. return result;
  1317. #elif defined(_WIN32)
  1318. ULARGE_INTEGER freeBytesAvail;
  1319. BOOL ok;
  1320. ok = GetDiskFreeSpaceEx(path, &freeBytesAvail, NULL, NULL);
  1321. if (!ok) {
  1322. return -1;
  1323. }
  1324. return (int64_t)freeBytesAvail.QuadPart;
  1325. #else
  1326. (void)path;
  1327. errno = ENOSYS;
  1328. return -1;
  1329. #endif /* defined(HAVE_STATVFS) || ... */
  1330. }