compat.c 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616
  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. /** Given <b>hlen</b> bytes at <b>haystack</b> and <b>nlen</b> bytes at
  126. * <b>needle</b>, return a pointer to the first occurrence of the needle
  127. * within the haystack, or NULL if there is no such occurrence.
  128. *
  129. * This function is <em>not</em> timing-safe.
  130. *
  131. * Requires that <b>nlen</b> be greater than zero.
  132. */
  133. const void *
  134. tor_memmem(const void *_haystack, size_t hlen,
  135. const void *_needle, size_t nlen)
  136. {
  137. #if defined(HAVE_MEMMEM) && (!defined(__GNUC__) || __GNUC__ >= 2)
  138. tor_assert(nlen);
  139. return memmem(_haystack, hlen, _needle, nlen);
  140. #else
  141. /* This isn't as fast as the GLIBC implementation, but it doesn't need to
  142. * be. */
  143. const char *p, *last_possible_start;
  144. const char *haystack = (const char*)_haystack;
  145. const char *needle = (const char*)_needle;
  146. char first;
  147. tor_assert(nlen);
  148. if (nlen > hlen)
  149. return NULL;
  150. p = haystack;
  151. /* Last position at which the needle could start. */
  152. last_possible_start = haystack + hlen - nlen;
  153. first = *(const char*)needle;
  154. while ((p = memchr(p, first, last_possible_start + 1 - p))) {
  155. if (fast_memeq(p, needle, nlen))
  156. return p;
  157. if (++p > last_possible_start) {
  158. /* This comparison shouldn't be necessary, since if p was previously
  159. * equal to last_possible_start, the next memchr call would be
  160. * "memchr(p, first, 0)", which will return NULL. But it clarifies the
  161. * logic. */
  162. return NULL;
  163. }
  164. }
  165. return NULL;
  166. #endif /* defined(HAVE_MEMMEM) && (!defined(__GNUC__) || __GNUC__ >= 2) */
  167. }
  168. /** Helper for tor_strtok_r_impl: Advances cp past all characters in
  169. * <b>sep</b>, and returns its new value. */
  170. static char *
  171. strtok_helper(char *cp, const char *sep)
  172. {
  173. if (sep[1]) {
  174. while (*cp && strchr(sep, *cp))
  175. ++cp;
  176. } else {
  177. while (*cp && *cp == *sep)
  178. ++cp;
  179. }
  180. return cp;
  181. }
  182. /** Implementation of strtok_r for platforms whose coders haven't figured out
  183. * how to write one. Hey, retrograde libc developers! You can use this code
  184. * here for free! */
  185. char *
  186. tor_strtok_r_impl(char *str, const char *sep, char **lasts)
  187. {
  188. char *cp, *start;
  189. tor_assert(*sep);
  190. if (str) {
  191. str = strtok_helper(str, sep);
  192. if (!*str)
  193. return NULL;
  194. start = cp = *lasts = str;
  195. } else if (!*lasts || !**lasts) {
  196. return NULL;
  197. } else {
  198. start = cp = *lasts;
  199. }
  200. if (sep[1]) {
  201. while (*cp && !strchr(sep, *cp))
  202. ++cp;
  203. } else {
  204. cp = strchr(cp, *sep);
  205. }
  206. if (!cp || !*cp) {
  207. *lasts = NULL;
  208. } else {
  209. *cp++ = '\0';
  210. *lasts = strtok_helper(cp, sep);
  211. }
  212. return start;
  213. }
  214. /**
  215. * Read a 16-bit value beginning at <b>cp</b>. Equivalent to
  216. * *(uint16_t*)(cp), but will not cause segfaults on platforms that forbid
  217. * unaligned memory access.
  218. */
  219. uint16_t
  220. get_uint16(const void *cp)
  221. {
  222. uint16_t v;
  223. memcpy(&v,cp,2);
  224. return v;
  225. }
  226. /**
  227. * Read a 32-bit value beginning at <b>cp</b>. Equivalent to
  228. * *(uint32_t*)(cp), but will not cause segfaults on platforms that forbid
  229. * unaligned memory access.
  230. */
  231. uint32_t
  232. get_uint32(const void *cp)
  233. {
  234. uint32_t v;
  235. memcpy(&v,cp,4);
  236. return v;
  237. }
  238. /**
  239. * Read a 64-bit value beginning at <b>cp</b>. Equivalent to
  240. * *(uint64_t*)(cp), but will not cause segfaults on platforms that forbid
  241. * unaligned memory access.
  242. */
  243. uint64_t
  244. get_uint64(const void *cp)
  245. {
  246. uint64_t v;
  247. memcpy(&v,cp,8);
  248. return v;
  249. }
  250. /**
  251. * Set a 16-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
  252. * *(uint16_t*)(cp) = v, but will not cause segfaults on platforms that forbid
  253. * unaligned memory access. */
  254. void
  255. set_uint16(void *cp, uint16_t v)
  256. {
  257. memcpy(cp,&v,2);
  258. }
  259. /**
  260. * Set a 32-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
  261. * *(uint32_t*)(cp) = v, but will not cause segfaults on platforms that forbid
  262. * unaligned memory access. */
  263. void
  264. set_uint32(void *cp, uint32_t v)
  265. {
  266. memcpy(cp,&v,4);
  267. }
  268. /**
  269. * Set a 64-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
  270. * *(uint64_t*)(cp) = v, but will not cause segfaults on platforms that forbid
  271. * unaligned memory access. */
  272. void
  273. set_uint64(void *cp, uint64_t v)
  274. {
  275. memcpy(cp,&v,8);
  276. }
  277. /** Represents a lockfile on which we hold the lock. */
  278. struct tor_lockfile_t {
  279. /** Name of the file */
  280. char *filename;
  281. /** File descriptor used to hold the file open */
  282. int fd;
  283. };
  284. /** Try to get a lock on the lockfile <b>filename</b>, creating it as
  285. * necessary. If someone else has the lock and <b>blocking</b> is true,
  286. * wait until the lock is available. Otherwise return immediately whether
  287. * we succeeded or not.
  288. *
  289. * Set *<b>locked_out</b> to true if somebody else had the lock, and to false
  290. * otherwise.
  291. *
  292. * Return a <b>tor_lockfile_t</b> on success, NULL on failure.
  293. *
  294. * (Implementation note: because we need to fall back to fcntl on some
  295. * platforms, these locks are per-process, not per-thread. If you want
  296. * to do in-process locking, use tor_mutex_t like a normal person.
  297. * On Windows, when <b>blocking</b> is true, the maximum time that
  298. * is actually waited is 10 seconds, after which NULL is returned
  299. * and <b>locked_out</b> is set to 1.)
  300. */
  301. tor_lockfile_t *
  302. tor_lockfile_lock(const char *filename, int blocking, int *locked_out)
  303. {
  304. tor_lockfile_t *result;
  305. int fd;
  306. *locked_out = 0;
  307. log_info(LD_FS, "Locking \"%s\"", filename);
  308. fd = tor_open_cloexec(filename, O_RDWR|O_CREAT|O_TRUNC, 0600);
  309. if (fd < 0) {
  310. log_warn(LD_FS,"Couldn't open \"%s\" for locking: %s", filename,
  311. strerror(errno));
  312. return NULL;
  313. }
  314. #ifdef _WIN32
  315. _lseek(fd, 0, SEEK_SET);
  316. if (_locking(fd, blocking ? _LK_LOCK : _LK_NBLCK, 1) < 0) {
  317. if (errno != EACCES && errno != EDEADLOCK)
  318. log_warn(LD_FS,"Couldn't lock \"%s\": %s", filename, strerror(errno));
  319. else
  320. *locked_out = 1;
  321. close(fd);
  322. return NULL;
  323. }
  324. #elif defined(HAVE_FLOCK)
  325. if (flock(fd, LOCK_EX|(blocking ? 0 : LOCK_NB)) < 0) {
  326. if (errno != EWOULDBLOCK)
  327. log_warn(LD_FS,"Couldn't lock \"%s\": %s", filename, strerror(errno));
  328. else
  329. *locked_out = 1;
  330. close(fd);
  331. return NULL;
  332. }
  333. #else
  334. {
  335. struct flock lock;
  336. memset(&lock, 0, sizeof(lock));
  337. lock.l_type = F_WRLCK;
  338. lock.l_whence = SEEK_SET;
  339. if (fcntl(fd, blocking ? F_SETLKW : F_SETLK, &lock) < 0) {
  340. if (errno != EACCES && errno != EAGAIN)
  341. log_warn(LD_FS, "Couldn't lock \"%s\": %s", filename, strerror(errno));
  342. else
  343. *locked_out = 1;
  344. close(fd);
  345. return NULL;
  346. }
  347. }
  348. #endif /* defined(_WIN32) || ... */
  349. result = tor_malloc(sizeof(tor_lockfile_t));
  350. result->filename = tor_strdup(filename);
  351. result->fd = fd;
  352. return result;
  353. }
  354. /** Release the lock held as <b>lockfile</b>. */
  355. void
  356. tor_lockfile_unlock(tor_lockfile_t *lockfile)
  357. {
  358. tor_assert(lockfile);
  359. log_info(LD_FS, "Unlocking \"%s\"", lockfile->filename);
  360. #ifdef _WIN32
  361. _lseek(lockfile->fd, 0, SEEK_SET);
  362. if (_locking(lockfile->fd, _LK_UNLCK, 1) < 0) {
  363. log_warn(LD_FS,"Error unlocking \"%s\": %s", lockfile->filename,
  364. strerror(errno));
  365. }
  366. #elif defined(HAVE_FLOCK)
  367. if (flock(lockfile->fd, LOCK_UN) < 0) {
  368. log_warn(LD_FS, "Error unlocking \"%s\": %s", lockfile->filename,
  369. strerror(errno));
  370. }
  371. #else
  372. /* Closing the lockfile is sufficient. */
  373. #endif /* defined(_WIN32) || ... */
  374. close(lockfile->fd);
  375. lockfile->fd = -1;
  376. tor_free(lockfile->filename);
  377. tor_free(lockfile);
  378. }
  379. /** Number of extra file descriptors to keep in reserve beyond those that we
  380. * tell Tor it's allowed to use. */
  381. #define ULIMIT_BUFFER 32 /* keep 32 extra fd's beyond ConnLimit_ */
  382. /** Learn the maximum allowed number of file descriptors, and tell the
  383. * system we want to use up to that number. (Some systems have a low soft
  384. * limit, and let us set it higher.) We compute this by finding the largest
  385. * number that we can use.
  386. *
  387. * If the limit is below the reserved file descriptor value (ULIMIT_BUFFER),
  388. * return -1 and <b>max_out</b> is untouched.
  389. *
  390. * If we can't find a number greater than or equal to <b>limit</b>, then we
  391. * fail by returning -1 and <b>max_out</b> is untouched.
  392. *
  393. * If we are unable to set the limit value because of setrlimit() failing,
  394. * return 0 and <b>max_out</b> is set to the current maximum value returned
  395. * by getrlimit().
  396. *
  397. * Otherwise, return 0 and store the maximum we found inside <b>max_out</b>
  398. * and set <b>max_sockets</b> with that value as well.*/
  399. int
  400. set_max_file_descriptors(rlim_t limit, int *max_out)
  401. {
  402. if (limit < ULIMIT_BUFFER) {
  403. log_warn(LD_CONFIG,
  404. "ConnLimit must be at least %d. Failing.", ULIMIT_BUFFER);
  405. return -1;
  406. }
  407. /* Define some maximum connections values for systems where we cannot
  408. * automatically determine a limit. Re Cygwin, see
  409. * http://archives.seul.org/or/talk/Aug-2006/msg00210.html
  410. * For an iPhone, 9999 should work. For Windows and all other unknown
  411. * systems we use 15000 as the default. */
  412. #ifndef HAVE_GETRLIMIT
  413. #if defined(CYGWIN) || defined(__CYGWIN__)
  414. const char *platform = "Cygwin";
  415. const unsigned long MAX_CONNECTIONS = 3200;
  416. #elif defined(_WIN32)
  417. const char *platform = "Windows";
  418. const unsigned long MAX_CONNECTIONS = 15000;
  419. #else
  420. const char *platform = "unknown platforms with no getrlimit()";
  421. const unsigned long MAX_CONNECTIONS = 15000;
  422. #endif /* defined(CYGWIN) || defined(__CYGWIN__) || ... */
  423. log_fn(LOG_INFO, LD_NET,
  424. "This platform is missing getrlimit(). Proceeding.");
  425. if (limit > MAX_CONNECTIONS) {
  426. log_warn(LD_CONFIG,
  427. "We do not support more than %lu file descriptors "
  428. "on %s. Tried to raise to %lu.",
  429. (unsigned long)MAX_CONNECTIONS, platform, (unsigned long)limit);
  430. return -1;
  431. }
  432. limit = MAX_CONNECTIONS;
  433. #else /* !(!defined(HAVE_GETRLIMIT)) */
  434. struct rlimit rlim;
  435. if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) {
  436. log_warn(LD_NET, "Could not get maximum number of file descriptors: %s",
  437. strerror(errno));
  438. return -1;
  439. }
  440. if (rlim.rlim_max < limit) {
  441. log_warn(LD_CONFIG,"We need %lu file descriptors available, and we're "
  442. "limited to %lu. Please change your ulimit -n.",
  443. (unsigned long)limit, (unsigned long)rlim.rlim_max);
  444. return -1;
  445. }
  446. if (rlim.rlim_max > rlim.rlim_cur) {
  447. log_info(LD_NET,"Raising max file descriptors from %lu to %lu.",
  448. (unsigned long)rlim.rlim_cur, (unsigned long)rlim.rlim_max);
  449. }
  450. /* Set the current limit value so if the attempt to set the limit to the
  451. * max fails at least we'll have a valid value of maximum sockets. */
  452. *max_out = (int)rlim.rlim_cur - ULIMIT_BUFFER;
  453. set_max_sockets(*max_out);
  454. rlim.rlim_cur = rlim.rlim_max;
  455. if (setrlimit(RLIMIT_NOFILE, &rlim) != 0) {
  456. int couldnt_set = 1;
  457. const int setrlimit_errno = errno;
  458. #ifdef OPEN_MAX
  459. uint64_t try_limit = OPEN_MAX - ULIMIT_BUFFER;
  460. if (errno == EINVAL && try_limit < (uint64_t) rlim.rlim_cur) {
  461. /* On some platforms, OPEN_MAX is the real limit, and getrlimit() is
  462. * full of nasty lies. I'm looking at you, OSX 10.5.... */
  463. rlim.rlim_cur = MIN((rlim_t) try_limit, rlim.rlim_cur);
  464. if (setrlimit(RLIMIT_NOFILE, &rlim) == 0) {
  465. if (rlim.rlim_cur < (rlim_t)limit) {
  466. log_warn(LD_CONFIG, "We are limited to %lu file descriptors by "
  467. "OPEN_MAX (%lu), and ConnLimit is %lu. Changing "
  468. "ConnLimit; sorry.",
  469. (unsigned long)try_limit, (unsigned long)OPEN_MAX,
  470. (unsigned long)limit);
  471. } else {
  472. log_info(LD_CONFIG, "Dropped connection limit to %lu based on "
  473. "OPEN_MAX (%lu); Apparently, %lu was too high and rlimit "
  474. "lied to us.",
  475. (unsigned long)try_limit, (unsigned long)OPEN_MAX,
  476. (unsigned long)rlim.rlim_max);
  477. }
  478. couldnt_set = 0;
  479. }
  480. }
  481. #endif /* defined(OPEN_MAX) */
  482. if (couldnt_set) {
  483. log_warn(LD_CONFIG,"Couldn't set maximum number of file descriptors: %s",
  484. strerror(setrlimit_errno));
  485. }
  486. }
  487. /* leave some overhead for logs, etc, */
  488. limit = rlim.rlim_cur;
  489. #endif /* !defined(HAVE_GETRLIMIT) */
  490. if (limit > INT_MAX)
  491. limit = INT_MAX;
  492. tor_assert(max_out);
  493. *max_out = (int)limit - ULIMIT_BUFFER;
  494. set_max_sockets(*max_out);
  495. return 0;
  496. }
  497. #ifndef _WIN32
  498. /** Log details of current user and group credentials. Return 0 on
  499. * success. Logs and return -1 on failure.
  500. */
  501. static int
  502. log_credential_status(void)
  503. {
  504. /** Log level to use when describing non-error UID/GID status. */
  505. #define CREDENTIAL_LOG_LEVEL LOG_INFO
  506. /* Real, effective and saved UIDs */
  507. uid_t ruid, euid, suid;
  508. /* Read, effective and saved GIDs */
  509. gid_t rgid, egid, sgid;
  510. /* Supplementary groups */
  511. gid_t *sup_gids = NULL;
  512. int sup_gids_size;
  513. /* Number of supplementary groups */
  514. int ngids;
  515. /* log UIDs */
  516. #ifdef HAVE_GETRESUID
  517. if (getresuid(&ruid, &euid, &suid) != 0 ) {
  518. log_warn(LD_GENERAL, "Error getting changed UIDs: %s", strerror(errno));
  519. return -1;
  520. } else {
  521. log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
  522. "UID is %u (real), %u (effective), %u (saved)",
  523. (unsigned)ruid, (unsigned)euid, (unsigned)suid);
  524. }
  525. #else /* !(defined(HAVE_GETRESUID)) */
  526. /* getresuid is not present on MacOS X, so we can't get the saved (E)UID */
  527. ruid = getuid();
  528. euid = geteuid();
  529. (void)suid;
  530. log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
  531. "UID is %u (real), %u (effective), unknown (saved)",
  532. (unsigned)ruid, (unsigned)euid);
  533. #endif /* defined(HAVE_GETRESUID) */
  534. /* log GIDs */
  535. #ifdef HAVE_GETRESGID
  536. if (getresgid(&rgid, &egid, &sgid) != 0 ) {
  537. log_warn(LD_GENERAL, "Error getting changed GIDs: %s", strerror(errno));
  538. return -1;
  539. } else {
  540. log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
  541. "GID is %u (real), %u (effective), %u (saved)",
  542. (unsigned)rgid, (unsigned)egid, (unsigned)sgid);
  543. }
  544. #else /* !(defined(HAVE_GETRESGID)) */
  545. /* getresgid is not present on MacOS X, so we can't get the saved (E)GID */
  546. rgid = getgid();
  547. egid = getegid();
  548. (void)sgid;
  549. log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
  550. "GID is %u (real), %u (effective), unknown (saved)",
  551. (unsigned)rgid, (unsigned)egid);
  552. #endif /* defined(HAVE_GETRESGID) */
  553. /* log supplementary groups */
  554. sup_gids_size = 64;
  555. sup_gids = tor_calloc(64, sizeof(gid_t));
  556. while ((ngids = getgroups(sup_gids_size, sup_gids)) < 0 &&
  557. errno == EINVAL &&
  558. sup_gids_size < NGROUPS_MAX) {
  559. sup_gids_size *= 2;
  560. sup_gids = tor_reallocarray(sup_gids, sizeof(gid_t), sup_gids_size);
  561. }
  562. if (ngids < 0) {
  563. log_warn(LD_GENERAL, "Error getting supplementary GIDs: %s",
  564. strerror(errno));
  565. tor_free(sup_gids);
  566. return -1;
  567. } else {
  568. int i, retval = 0;
  569. char *s = NULL;
  570. smartlist_t *elts = smartlist_new();
  571. for (i = 0; i<ngids; i++) {
  572. smartlist_add_asprintf(elts, "%u", (unsigned)sup_gids[i]);
  573. }
  574. s = smartlist_join_strings(elts, " ", 0, NULL);
  575. log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL, "Supplementary groups are: %s",s);
  576. tor_free(s);
  577. SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
  578. smartlist_free(elts);
  579. tor_free(sup_gids);
  580. return retval;
  581. }
  582. return 0;
  583. }
  584. #endif /* !defined(_WIN32) */
  585. /** Return true iff we were compiled with capability support, and capabilities
  586. * seem to work. **/
  587. int
  588. have_capability_support(void)
  589. {
  590. #ifdef HAVE_LINUX_CAPABILITIES
  591. cap_t caps = cap_get_proc();
  592. if (caps == NULL)
  593. return 0;
  594. cap_free(caps);
  595. return 1;
  596. #else /* !(defined(HAVE_LINUX_CAPABILITIES)) */
  597. return 0;
  598. #endif /* defined(HAVE_LINUX_CAPABILITIES) */
  599. }
  600. #ifdef HAVE_LINUX_CAPABILITIES
  601. /** Helper. Drop all capabilities but a small set, and set PR_KEEPCAPS as
  602. * appropriate.
  603. *
  604. * If pre_setuid, retain only CAP_NET_BIND_SERVICE, CAP_SETUID, and
  605. * CAP_SETGID, and use PR_KEEPCAPS to ensure that capabilities persist across
  606. * setuid().
  607. *
  608. * If not pre_setuid, retain only CAP_NET_BIND_SERVICE, and disable
  609. * PR_KEEPCAPS.
  610. *
  611. * Return 0 on success, and -1 on failure.
  612. */
  613. static int
  614. drop_capabilities(int pre_setuid)
  615. {
  616. /* We keep these three capabilities, and these only, as we setuid.
  617. * After we setuid, we drop all but the first. */
  618. const cap_value_t caplist[] = {
  619. CAP_NET_BIND_SERVICE, CAP_SETUID, CAP_SETGID
  620. };
  621. const char *where = pre_setuid ? "pre-setuid" : "post-setuid";
  622. const int n_effective = pre_setuid ? 3 : 1;
  623. const int n_permitted = pre_setuid ? 3 : 1;
  624. const int n_inheritable = 1;
  625. const int keepcaps = pre_setuid ? 1 : 0;
  626. /* Sets whether we keep capabilities across a setuid. */
  627. if (prctl(PR_SET_KEEPCAPS, keepcaps) < 0) {
  628. log_warn(LD_CONFIG, "Unable to call prctl() %s: %s",
  629. where, strerror(errno));
  630. return -1;
  631. }
  632. cap_t caps = cap_get_proc();
  633. if (!caps) {
  634. log_warn(LD_CONFIG, "Unable to call cap_get_proc() %s: %s",
  635. where, strerror(errno));
  636. return -1;
  637. }
  638. cap_clear(caps);
  639. cap_set_flag(caps, CAP_EFFECTIVE, n_effective, caplist, CAP_SET);
  640. cap_set_flag(caps, CAP_PERMITTED, n_permitted, caplist, CAP_SET);
  641. cap_set_flag(caps, CAP_INHERITABLE, n_inheritable, caplist, CAP_SET);
  642. int r = cap_set_proc(caps);
  643. cap_free(caps);
  644. if (r < 0) {
  645. log_warn(LD_CONFIG, "No permission to set capabilities %s: %s",
  646. where, strerror(errno));
  647. return -1;
  648. }
  649. return 0;
  650. }
  651. #endif /* defined(HAVE_LINUX_CAPABILITIES) */
  652. /** Call setuid and setgid to run as <b>user</b> and switch to their
  653. * primary group. Return 0 on success. On failure, log and return -1.
  654. *
  655. * If SWITCH_ID_KEEP_BINDLOW is set in 'flags', try to use the capability
  656. * system to retain the abilitity to bind low ports.
  657. *
  658. * If SWITCH_ID_WARN_IF_NO_CAPS is set in flags, also warn if we have
  659. * don't have capability support.
  660. */
  661. int
  662. switch_id(const char *user, const unsigned flags)
  663. {
  664. #ifndef _WIN32
  665. const struct passwd *pw = NULL;
  666. uid_t old_uid;
  667. gid_t old_gid;
  668. static int have_already_switched_id = 0;
  669. const int keep_bindlow = !!(flags & SWITCH_ID_KEEP_BINDLOW);
  670. const int warn_if_no_caps = !!(flags & SWITCH_ID_WARN_IF_NO_CAPS);
  671. tor_assert(user);
  672. if (have_already_switched_id)
  673. return 0;
  674. /* Log the initial credential state */
  675. if (log_credential_status())
  676. return -1;
  677. log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL, "Changing user and groups");
  678. /* Get old UID/GID to check if we changed correctly */
  679. old_uid = getuid();
  680. old_gid = getgid();
  681. /* Lookup the user and group information, if we have a problem, bail out. */
  682. pw = tor_getpwnam(user);
  683. if (pw == NULL) {
  684. log_warn(LD_CONFIG, "Error setting configured user: %s not found", user);
  685. return -1;
  686. }
  687. #ifdef HAVE_LINUX_CAPABILITIES
  688. (void) warn_if_no_caps;
  689. if (keep_bindlow) {
  690. if (drop_capabilities(1))
  691. return -1;
  692. }
  693. #else /* !(defined(HAVE_LINUX_CAPABILITIES)) */
  694. (void) keep_bindlow;
  695. if (warn_if_no_caps) {
  696. log_warn(LD_CONFIG, "KeepBindCapabilities set, but no capability support "
  697. "on this system.");
  698. }
  699. #endif /* defined(HAVE_LINUX_CAPABILITIES) */
  700. /* Properly switch egid,gid,euid,uid here or bail out */
  701. if (setgroups(1, &pw->pw_gid)) {
  702. log_warn(LD_GENERAL, "Error setting groups to gid %d: \"%s\".",
  703. (int)pw->pw_gid, strerror(errno));
  704. if (old_uid == pw->pw_uid) {
  705. log_warn(LD_GENERAL, "Tor is already running as %s. You do not need "
  706. "the \"User\" option if you are already running as the user "
  707. "you want to be. (If you did not set the User option in your "
  708. "torrc, check whether it was specified on the command line "
  709. "by a startup script.)", user);
  710. } else {
  711. log_warn(LD_GENERAL, "If you set the \"User\" option, you must start Tor"
  712. " as root.");
  713. }
  714. return -1;
  715. }
  716. if (setegid(pw->pw_gid)) {
  717. log_warn(LD_GENERAL, "Error setting egid to %d: %s",
  718. (int)pw->pw_gid, strerror(errno));
  719. return -1;
  720. }
  721. if (setgid(pw->pw_gid)) {
  722. log_warn(LD_GENERAL, "Error setting gid to %d: %s",
  723. (int)pw->pw_gid, strerror(errno));
  724. return -1;
  725. }
  726. if (setuid(pw->pw_uid)) {
  727. log_warn(LD_GENERAL, "Error setting configured uid to %s (%d): %s",
  728. user, (int)pw->pw_uid, strerror(errno));
  729. return -1;
  730. }
  731. if (seteuid(pw->pw_uid)) {
  732. log_warn(LD_GENERAL, "Error setting configured euid to %s (%d): %s",
  733. user, (int)pw->pw_uid, strerror(errno));
  734. return -1;
  735. }
  736. /* This is how OpenBSD rolls:
  737. if (setgroups(1, &pw->pw_gid) || setegid(pw->pw_gid) ||
  738. setgid(pw->pw_gid) || setuid(pw->pw_uid) || seteuid(pw->pw_uid)) {
  739. setgid(pw->pw_gid) || seteuid(pw->pw_uid) || setuid(pw->pw_uid)) {
  740. log_warn(LD_GENERAL, "Error setting configured UID/GID: %s",
  741. strerror(errno));
  742. return -1;
  743. }
  744. */
  745. /* We've properly switched egid, gid, euid, uid, and supplementary groups if
  746. * we're here. */
  747. #ifdef HAVE_LINUX_CAPABILITIES
  748. if (keep_bindlow) {
  749. if (drop_capabilities(0))
  750. return -1;
  751. }
  752. #endif /* defined(HAVE_LINUX_CAPABILITIES) */
  753. #if !defined(CYGWIN) && !defined(__CYGWIN__)
  754. /* If we tried to drop privilege to a group/user other than root, attempt to
  755. * restore root (E)(U|G)ID, and abort if the operation succeeds */
  756. /* Only check for privilege dropping if we were asked to be non-root */
  757. if (pw->pw_uid) {
  758. /* Try changing GID/EGID */
  759. if (pw->pw_gid != old_gid &&
  760. (setgid(old_gid) != -1 || setegid(old_gid) != -1)) {
  761. log_warn(LD_GENERAL, "Was able to restore group credentials even after "
  762. "switching GID: this means that the setgid code didn't work.");
  763. return -1;
  764. }
  765. /* Try changing UID/EUID */
  766. if (pw->pw_uid != old_uid &&
  767. (setuid(old_uid) != -1 || seteuid(old_uid) != -1)) {
  768. log_warn(LD_GENERAL, "Was able to restore user credentials even after "
  769. "switching UID: this means that the setuid code didn't work.");
  770. return -1;
  771. }
  772. }
  773. #endif /* !defined(CYGWIN) && !defined(__CYGWIN__) */
  774. /* Check what really happened */
  775. if (log_credential_status()) {
  776. return -1;
  777. }
  778. have_already_switched_id = 1; /* mark success so we never try again */
  779. #if defined(__linux__) && defined(HAVE_SYS_PRCTL_H) && \
  780. defined(HAVE_PRCTL) && defined(PR_SET_DUMPABLE)
  781. if (pw->pw_uid) {
  782. /* Re-enable core dumps if we're not running as root. */
  783. log_info(LD_CONFIG, "Re-enabling coredumps");
  784. if (prctl(PR_SET_DUMPABLE, 1)) {
  785. log_warn(LD_CONFIG, "Unable to re-enable coredumps: %s",strerror(errno));
  786. }
  787. }
  788. #endif /* defined(__linux__) && defined(HAVE_SYS_PRCTL_H) && ... */
  789. return 0;
  790. #else /* !(!defined(_WIN32)) */
  791. (void)user;
  792. (void)flags;
  793. log_warn(LD_CONFIG, "Switching users is unsupported on your OS.");
  794. return -1;
  795. #endif /* !defined(_WIN32) */
  796. }
  797. /* We only use the linux prctl for now. There is no Win32 support; this may
  798. * also work on various BSD systems and Mac OS X - send testing feedback!
  799. *
  800. * On recent Gnu/Linux kernels it is possible to create a system-wide policy
  801. * that will prevent non-root processes from attaching to other processes
  802. * unless they are the parent process; thus gdb can attach to programs that
  803. * they execute but they cannot attach to other processes running as the same
  804. * user. The system wide policy may be set with the sysctl
  805. * kernel.yama.ptrace_scope or by inspecting
  806. * /proc/sys/kernel/yama/ptrace_scope and it is 1 by default on Ubuntu 11.04.
  807. *
  808. * This ptrace scope will be ignored on Gnu/Linux for users with
  809. * CAP_SYS_PTRACE and so it is very likely that root will still be able to
  810. * attach to the Tor process.
  811. */
  812. /** Attempt to disable debugger attachment: return 1 on success, -1 on
  813. * failure, and 0 if we don't know how to try on this platform. */
  814. int
  815. tor_disable_debugger_attach(void)
  816. {
  817. int r = -1;
  818. log_debug(LD_CONFIG,
  819. "Attemping to disable debugger attachment to Tor for "
  820. "unprivileged users.");
  821. #if defined(__linux__) && defined(HAVE_SYS_PRCTL_H) \
  822. && defined(HAVE_PRCTL) && defined(PR_SET_DUMPABLE)
  823. #define TRIED_TO_DISABLE
  824. r = prctl(PR_SET_DUMPABLE, 0);
  825. #elif defined(__APPLE__) && defined(PT_DENY_ATTACH)
  826. #define TRIED_TO_ATTACH
  827. r = ptrace(PT_DENY_ATTACH, 0, 0, 0);
  828. #endif /* defined(__linux__) && defined(HAVE_SYS_PRCTL_H) ... || ... */
  829. // XXX: TODO - Mac OS X has dtrace and this may be disabled.
  830. // XXX: TODO - Windows probably has something similar
  831. #ifdef TRIED_TO_DISABLE
  832. if (r == 0) {
  833. log_debug(LD_CONFIG,"Debugger attachment disabled for "
  834. "unprivileged users.");
  835. return 1;
  836. } else {
  837. log_warn(LD_CONFIG, "Unable to disable debugger attaching: %s",
  838. strerror(errno));
  839. }
  840. #endif /* defined(TRIED_TO_DISABLE) */
  841. #undef TRIED_TO_DISABLE
  842. return r;
  843. }
  844. #ifndef HAVE__NSGETENVIRON
  845. #ifndef HAVE_EXTERN_ENVIRON_DECLARED
  846. /* Some platforms declare environ under some circumstances, others don't. */
  847. #ifndef RUNNING_DOXYGEN
  848. extern char **environ;
  849. #endif
  850. #endif /* !defined(HAVE_EXTERN_ENVIRON_DECLARED) */
  851. #endif /* !defined(HAVE__NSGETENVIRON) */
  852. /** Return the current environment. This is a portable replacement for
  853. * 'environ'. */
  854. char **
  855. get_environment(void)
  856. {
  857. #ifdef HAVE__NSGETENVIRON
  858. /* This is for compatibility between OSX versions. Otherwise (for example)
  859. * when we do a mostly-static build on OSX 10.7, the resulting binary won't
  860. * work on OSX 10.6. */
  861. return *_NSGetEnviron();
  862. #else /* !(defined(HAVE__NSGETENVIRON)) */
  863. return environ;
  864. #endif /* defined(HAVE__NSGETENVIRON) */
  865. }
  866. /** Get name of current host and write it to <b>name</b> array, whose
  867. * length is specified by <b>namelen</b> argument. Return 0 upon
  868. * successful completion; otherwise return return -1. (Currently,
  869. * this function is merely a mockable wrapper for POSIX gethostname().)
  870. */
  871. MOCK_IMPL(int,
  872. tor_gethostname,(char *name, size_t namelen))
  873. {
  874. return gethostname(name,namelen);
  875. }
  876. /** Hold the result of our call to <b>uname</b>. */
  877. static char uname_result[256];
  878. /** True iff uname_result is set. */
  879. static int uname_result_is_set = 0;
  880. /** Return a pointer to a description of our platform.
  881. */
  882. MOCK_IMPL(const char *,
  883. get_uname,(void))
  884. {
  885. #ifdef HAVE_UNAME
  886. struct utsname u;
  887. #endif
  888. if (!uname_result_is_set) {
  889. #ifdef HAVE_UNAME
  890. if (uname(&u) != -1) {
  891. /* (Linux says 0 is success, Solaris says 1 is success) */
  892. strlcpy(uname_result, u.sysname, sizeof(uname_result));
  893. } else
  894. #endif /* defined(HAVE_UNAME) */
  895. {
  896. #ifdef _WIN32
  897. OSVERSIONINFOEX info;
  898. int i;
  899. const char *plat = NULL;
  900. static struct {
  901. unsigned major; unsigned minor; const char *version;
  902. } win_version_table[] = {
  903. { 6, 2, "Windows 8" },
  904. { 6, 1, "Windows 7" },
  905. { 6, 0, "Windows Vista" },
  906. { 5, 2, "Windows Server 2003" },
  907. { 5, 1, "Windows XP" },
  908. { 5, 0, "Windows 2000" },
  909. /* { 4, 0, "Windows NT 4.0" }, */
  910. { 4, 90, "Windows Me" },
  911. { 4, 10, "Windows 98" },
  912. /* { 4, 0, "Windows 95" } */
  913. { 3, 51, "Windows NT 3.51" },
  914. { 0, 0, NULL }
  915. };
  916. memset(&info, 0, sizeof(info));
  917. info.dwOSVersionInfoSize = sizeof(info);
  918. if (! GetVersionEx((LPOSVERSIONINFO)&info)) {
  919. strlcpy(uname_result, "Bizarre version of Windows where GetVersionEx"
  920. " doesn't work.", sizeof(uname_result));
  921. uname_result_is_set = 1;
  922. return uname_result;
  923. }
  924. if (info.dwMajorVersion == 4 && info.dwMinorVersion == 0) {
  925. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  926. plat = "Windows NT 4.0";
  927. else
  928. plat = "Windows 95";
  929. } else {
  930. for (i=0; win_version_table[i].major>0; ++i) {
  931. if (win_version_table[i].major == info.dwMajorVersion &&
  932. win_version_table[i].minor == info.dwMinorVersion) {
  933. plat = win_version_table[i].version;
  934. break;
  935. }
  936. }
  937. }
  938. if (plat) {
  939. strlcpy(uname_result, plat, sizeof(uname_result));
  940. } else {
  941. if (info.dwMajorVersion > 6 ||
  942. (info.dwMajorVersion==6 && info.dwMinorVersion>2))
  943. tor_snprintf(uname_result, sizeof(uname_result),
  944. "Very recent version of Windows [major=%d,minor=%d]",
  945. (int)info.dwMajorVersion,(int)info.dwMinorVersion);
  946. else
  947. tor_snprintf(uname_result, sizeof(uname_result),
  948. "Unrecognized version of Windows [major=%d,minor=%d]",
  949. (int)info.dwMajorVersion,(int)info.dwMinorVersion);
  950. }
  951. #ifdef VER_NT_SERVER
  952. if (info.wProductType == VER_NT_SERVER ||
  953. info.wProductType == VER_NT_DOMAIN_CONTROLLER) {
  954. strlcat(uname_result, " [server]", sizeof(uname_result));
  955. }
  956. #endif /* defined(VER_NT_SERVER) */
  957. #else /* !(defined(_WIN32)) */
  958. /* LCOV_EXCL_START -- can't provoke uname failure */
  959. strlcpy(uname_result, "Unknown platform", sizeof(uname_result));
  960. /* LCOV_EXCL_STOP */
  961. #endif /* defined(_WIN32) */
  962. }
  963. uname_result_is_set = 1;
  964. }
  965. return uname_result;
  966. }
  967. /*
  968. * Process control
  969. */
  970. /** Implementation logic for compute_num_cpus(). */
  971. static int
  972. compute_num_cpus_impl(void)
  973. {
  974. #ifdef _WIN32
  975. SYSTEM_INFO info;
  976. memset(&info, 0, sizeof(info));
  977. GetSystemInfo(&info);
  978. if (info.dwNumberOfProcessors >= 1 && info.dwNumberOfProcessors < INT_MAX)
  979. return (int)info.dwNumberOfProcessors;
  980. else
  981. return -1;
  982. #elif defined(HAVE_SYSCONF)
  983. #ifdef _SC_NPROCESSORS_CONF
  984. long cpus_conf = sysconf(_SC_NPROCESSORS_CONF);
  985. #else
  986. long cpus_conf = -1;
  987. #endif
  988. #ifdef _SC_NPROCESSORS_ONLN
  989. long cpus_onln = sysconf(_SC_NPROCESSORS_ONLN);
  990. #else
  991. long cpus_onln = -1;
  992. #endif
  993. long cpus = -1;
  994. if (cpus_conf > 0 && cpus_onln < 0) {
  995. cpus = cpus_conf;
  996. } else if (cpus_onln > 0 && cpus_conf < 0) {
  997. cpus = cpus_onln;
  998. } else if (cpus_onln > 0 && cpus_conf > 0) {
  999. if (cpus_onln < cpus_conf) {
  1000. log_notice(LD_GENERAL, "I think we have %ld CPUS, but only %ld of them "
  1001. "are available. Telling Tor to only use %ld. You can over"
  1002. "ride this with the NumCPUs option",
  1003. cpus_conf, cpus_onln, cpus_onln);
  1004. }
  1005. cpus = cpus_onln;
  1006. }
  1007. if (cpus >= 1 && cpus < INT_MAX)
  1008. return (int)cpus;
  1009. else
  1010. return -1;
  1011. #else
  1012. return -1;
  1013. #endif /* defined(_WIN32) || ... */
  1014. }
  1015. #define MAX_DETECTABLE_CPUS 16
  1016. /** Return how many CPUs we are running with. We assume that nobody is
  1017. * using hot-swappable CPUs, so we don't recompute this after the first
  1018. * time. Return -1 if we don't know how to tell the number of CPUs on this
  1019. * system.
  1020. */
  1021. int
  1022. compute_num_cpus(void)
  1023. {
  1024. static int num_cpus = -2;
  1025. if (num_cpus == -2) {
  1026. num_cpus = compute_num_cpus_impl();
  1027. tor_assert(num_cpus != -2);
  1028. if (num_cpus > MAX_DETECTABLE_CPUS) {
  1029. /* LCOV_EXCL_START */
  1030. log_notice(LD_GENERAL, "Wow! I detected that you have %d CPUs. I "
  1031. "will not autodetect any more than %d, though. If you "
  1032. "want to configure more, set NumCPUs in your torrc",
  1033. num_cpus, MAX_DETECTABLE_CPUS);
  1034. num_cpus = MAX_DETECTABLE_CPUS;
  1035. /* LCOV_EXCL_STOP */
  1036. }
  1037. }
  1038. return num_cpus;
  1039. }
  1040. /** As localtime_r, but defined for platforms that don't have it:
  1041. *
  1042. * Convert *<b>timep</b> to a struct tm in local time, and store the value in
  1043. * *<b>result</b>. Return the result on success, or NULL on failure.
  1044. */
  1045. struct tm *
  1046. tor_localtime_r(const time_t *timep, struct tm *result)
  1047. {
  1048. char *err = NULL;
  1049. struct tm *r = tor_localtime_r_msg(timep, result, &err);
  1050. if (err) {
  1051. log_warn(LD_BUG, "%s", err);
  1052. tor_free(err);
  1053. }
  1054. return r;
  1055. }
  1056. /** As gmtime_r, but defined for platforms that don't have it:
  1057. *
  1058. * Convert *<b>timep</b> to a struct tm in UTC, and store the value in
  1059. * *<b>result</b>. Return the result on success, or NULL on failure.
  1060. */
  1061. struct tm *
  1062. tor_gmtime_r(const time_t *timep, struct tm *result)
  1063. {
  1064. char *err = NULL;
  1065. struct tm *r = tor_gmtime_r_msg(timep, result, &err);
  1066. if (err) {
  1067. log_warn(LD_BUG, "%s", err);
  1068. tor_free(err);
  1069. }
  1070. return r;
  1071. }
  1072. #if defined(HAVE_MLOCKALL) && HAVE_DECL_MLOCKALL && defined(RLIMIT_MEMLOCK)
  1073. #define HAVE_UNIX_MLOCKALL
  1074. #endif
  1075. #ifdef HAVE_UNIX_MLOCKALL
  1076. /** Attempt to raise the current and max rlimit to infinity for our process.
  1077. * This only needs to be done once and can probably only be done when we have
  1078. * not already dropped privileges.
  1079. */
  1080. static int
  1081. tor_set_max_memlock(void)
  1082. {
  1083. /* Future consideration for Windows is probably SetProcessWorkingSetSize
  1084. * This is similar to setting the memory rlimit of RLIMIT_MEMLOCK
  1085. * http://msdn.microsoft.com/en-us/library/ms686234(VS.85).aspx
  1086. */
  1087. struct rlimit limit;
  1088. /* RLIM_INFINITY is -1 on some platforms. */
  1089. limit.rlim_cur = RLIM_INFINITY;
  1090. limit.rlim_max = RLIM_INFINITY;
  1091. if (setrlimit(RLIMIT_MEMLOCK, &limit) == -1) {
  1092. if (errno == EPERM) {
  1093. log_warn(LD_GENERAL, "You appear to lack permissions to change memory "
  1094. "limits. Are you root?");
  1095. }
  1096. log_warn(LD_GENERAL, "Unable to raise RLIMIT_MEMLOCK: %s",
  1097. strerror(errno));
  1098. return -1;
  1099. }
  1100. return 0;
  1101. }
  1102. #endif /* defined(HAVE_UNIX_MLOCKALL) */
  1103. /** Attempt to lock all current and all future memory pages.
  1104. * This should only be called once and while we're privileged.
  1105. * Like mlockall() we return 0 when we're successful and -1 when we're not.
  1106. * Unlike mlockall() we return 1 if we've already attempted to lock memory.
  1107. */
  1108. int
  1109. tor_mlockall(void)
  1110. {
  1111. static int memory_lock_attempted = 0;
  1112. if (memory_lock_attempted) {
  1113. return 1;
  1114. }
  1115. memory_lock_attempted = 1;
  1116. /*
  1117. * Future consideration for Windows may be VirtualLock
  1118. * VirtualLock appears to implement mlock() but not mlockall()
  1119. *
  1120. * http://msdn.microsoft.com/en-us/library/aa366895(VS.85).aspx
  1121. */
  1122. #ifdef HAVE_UNIX_MLOCKALL
  1123. if (tor_set_max_memlock() == 0) {
  1124. log_debug(LD_GENERAL, "RLIMIT_MEMLOCK is now set to RLIM_INFINITY.");
  1125. }
  1126. if (mlockall(MCL_CURRENT|MCL_FUTURE) == 0) {
  1127. log_info(LD_GENERAL, "Insecure OS paging is effectively disabled.");
  1128. return 0;
  1129. } else {
  1130. if (errno == ENOSYS) {
  1131. /* Apple - it's 2009! I'm looking at you. Grrr. */
  1132. log_notice(LD_GENERAL, "It appears that mlockall() is not available on "
  1133. "your platform.");
  1134. } else if (errno == EPERM) {
  1135. log_notice(LD_GENERAL, "It appears that you lack the permissions to "
  1136. "lock memory. Are you root?");
  1137. }
  1138. log_notice(LD_GENERAL, "Unable to lock all current and future memory "
  1139. "pages: %s", strerror(errno));
  1140. return -1;
  1141. }
  1142. #else /* !(defined(HAVE_UNIX_MLOCKALL)) */
  1143. log_warn(LD_GENERAL, "Unable to lock memory pages. mlockall() unsupported?");
  1144. return -1;
  1145. #endif /* defined(HAVE_UNIX_MLOCKALL) */
  1146. }
  1147. /**
  1148. * On Windows, WSAEWOULDBLOCK is not always correct: when you see it,
  1149. * you need to ask the socket for its actual errno. Also, you need to
  1150. * get your errors from WSAGetLastError, not errno. (If you supply a
  1151. * socket of -1, we check WSAGetLastError, but don't correct
  1152. * WSAEWOULDBLOCKs.)
  1153. *
  1154. * The upshot of all of this is that when a socket call fails, you
  1155. * should call tor_socket_errno <em>at most once</em> on the failing
  1156. * socket to get the error.
  1157. */
  1158. #if defined(_WIN32)
  1159. int
  1160. tor_socket_errno(tor_socket_t sock)
  1161. {
  1162. int optval, optvallen=sizeof(optval);
  1163. int err = WSAGetLastError();
  1164. if (err == WSAEWOULDBLOCK && SOCKET_OK(sock)) {
  1165. if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval, &optvallen))
  1166. return err;
  1167. if (optval)
  1168. return optval;
  1169. }
  1170. return err;
  1171. }
  1172. #endif /* defined(_WIN32) */
  1173. #if defined(_WIN32)
  1174. #define E(code, s) { code, (s " [" #code " ]") }
  1175. struct { int code; const char *msg; } windows_socket_errors[] = {
  1176. E(WSAEINTR, "Interrupted function call"),
  1177. E(WSAEACCES, "Permission denied"),
  1178. E(WSAEFAULT, "Bad address"),
  1179. E(WSAEINVAL, "Invalid argument"),
  1180. E(WSAEMFILE, "Too many open files"),
  1181. E(WSAEWOULDBLOCK, "Resource temporarily unavailable"),
  1182. E(WSAEINPROGRESS, "Operation now in progress"),
  1183. E(WSAEALREADY, "Operation already in progress"),
  1184. E(WSAENOTSOCK, "Socket operation on nonsocket"),
  1185. E(WSAEDESTADDRREQ, "Destination address required"),
  1186. E(WSAEMSGSIZE, "Message too long"),
  1187. E(WSAEPROTOTYPE, "Protocol wrong for socket"),
  1188. E(WSAENOPROTOOPT, "Bad protocol option"),
  1189. E(WSAEPROTONOSUPPORT, "Protocol not supported"),
  1190. E(WSAESOCKTNOSUPPORT, "Socket type not supported"),
  1191. /* What's the difference between NOTSUPP and NOSUPPORT? :) */
  1192. E(WSAEOPNOTSUPP, "Operation not supported"),
  1193. E(WSAEPFNOSUPPORT, "Protocol family not supported"),
  1194. E(WSAEAFNOSUPPORT, "Address family not supported by protocol family"),
  1195. E(WSAEADDRINUSE, "Address already in use"),
  1196. E(WSAEADDRNOTAVAIL, "Cannot assign requested address"),
  1197. E(WSAENETDOWN, "Network is down"),
  1198. E(WSAENETUNREACH, "Network is unreachable"),
  1199. E(WSAENETRESET, "Network dropped connection on reset"),
  1200. E(WSAECONNABORTED, "Software caused connection abort"),
  1201. E(WSAECONNRESET, "Connection reset by peer"),
  1202. E(WSAENOBUFS, "No buffer space available"),
  1203. E(WSAEISCONN, "Socket is already connected"),
  1204. E(WSAENOTCONN, "Socket is not connected"),
  1205. E(WSAESHUTDOWN, "Cannot send after socket shutdown"),
  1206. E(WSAETIMEDOUT, "Connection timed out"),
  1207. E(WSAECONNREFUSED, "Connection refused"),
  1208. E(WSAEHOSTDOWN, "Host is down"),
  1209. E(WSAEHOSTUNREACH, "No route to host"),
  1210. E(WSAEPROCLIM, "Too many processes"),
  1211. /* Yes, some of these start with WSA, not WSAE. No, I don't know why. */
  1212. E(WSASYSNOTREADY, "Network subsystem is unavailable"),
  1213. E(WSAVERNOTSUPPORTED, "Winsock.dll out of range"),
  1214. E(WSANOTINITIALISED, "Successful WSAStartup not yet performed"),
  1215. E(WSAEDISCON, "Graceful shutdown now in progress"),
  1216. #ifdef WSATYPE_NOT_FOUND
  1217. E(WSATYPE_NOT_FOUND, "Class type not found"),
  1218. #endif
  1219. E(WSAHOST_NOT_FOUND, "Host not found"),
  1220. E(WSATRY_AGAIN, "Nonauthoritative host not found"),
  1221. E(WSANO_RECOVERY, "This is a nonrecoverable error"),
  1222. E(WSANO_DATA, "Valid name, no data record of requested type)"),
  1223. /* There are some more error codes whose numeric values are marked
  1224. * <b>OS dependent</b>. They start with WSA_, apparently for the same
  1225. * reason that practitioners of some craft traditions deliberately
  1226. * introduce imperfections into their baskets and rugs "to allow the
  1227. * evil spirits to escape." If we catch them, then our binaries
  1228. * might not report consistent results across versions of Windows.
  1229. * Thus, I'm going to let them all fall through.
  1230. */
  1231. { -1, NULL },
  1232. };
  1233. /** There does not seem to be a strerror equivalent for Winsock errors.
  1234. * Naturally, we have to roll our own.
  1235. */
  1236. const char *
  1237. tor_socket_strerror(int e)
  1238. {
  1239. int i;
  1240. for (i=0; windows_socket_errors[i].code >= 0; ++i) {
  1241. if (e == windows_socket_errors[i].code)
  1242. return windows_socket_errors[i].msg;
  1243. }
  1244. return strerror(e);
  1245. }
  1246. #endif /* defined(_WIN32) */
  1247. /** Called before we make any calls to network-related functions.
  1248. * (Some operating systems require their network libraries to be
  1249. * initialized.) */
  1250. int
  1251. network_init(void)
  1252. {
  1253. #ifdef _WIN32
  1254. /* This silly exercise is necessary before windows will allow
  1255. * gethostbyname to work. */
  1256. WSADATA WSAData;
  1257. int r;
  1258. r = WSAStartup(0x101,&WSAData);
  1259. if (r) {
  1260. log_warn(LD_NET,"Error initializing windows network layer: code was %d",r);
  1261. return -1;
  1262. }
  1263. if (sizeof(SOCKET) != sizeof(tor_socket_t)) {
  1264. log_warn(LD_BUG,"The tor_socket_t type does not match SOCKET in size; Tor "
  1265. "might not work. (Sizes are %d and %d respectively.)",
  1266. (int)sizeof(tor_socket_t), (int)sizeof(SOCKET));
  1267. }
  1268. /* WSAData.iMaxSockets might show the max sockets we're allowed to use.
  1269. * We might use it to complain if we're trying to be a server but have
  1270. * too few sockets available. */
  1271. #endif /* defined(_WIN32) */
  1272. return 0;
  1273. }
  1274. #if defined(HW_PHYSMEM64)
  1275. /* This appears to be an OpenBSD thing */
  1276. #define INT64_HW_MEM HW_PHYSMEM64
  1277. #elif defined(HW_MEMSIZE)
  1278. /* OSX defines this one */
  1279. #define INT64_HW_MEM HW_MEMSIZE
  1280. #endif /* defined(HW_PHYSMEM64) || ... */
  1281. /**
  1282. * Helper: try to detect the total system memory, and return it. On failure,
  1283. * return 0.
  1284. */
  1285. static uint64_t
  1286. get_total_system_memory_impl(void)
  1287. {
  1288. #if defined(__linux__)
  1289. /* On linux, sysctl is deprecated. Because proc is so awesome that you
  1290. * shouldn't _want_ to write portable code, I guess? */
  1291. unsigned long long result=0;
  1292. int fd = -1;
  1293. char *s = NULL;
  1294. const char *cp;
  1295. size_t file_size=0;
  1296. if (-1 == (fd = tor_open_cloexec("/proc/meminfo",O_RDONLY,0)))
  1297. return 0;
  1298. s = read_file_to_str_until_eof(fd, 65536, &file_size);
  1299. if (!s)
  1300. goto err;
  1301. cp = strstr(s, "MemTotal:");
  1302. if (!cp)
  1303. goto err;
  1304. /* Use the system sscanf so that space will match a wider number of space */
  1305. if (sscanf(cp, "MemTotal: %llu kB\n", &result) != 1)
  1306. goto err;
  1307. close(fd);
  1308. tor_free(s);
  1309. return result * 1024;
  1310. /* LCOV_EXCL_START Can't reach this unless proc is broken. */
  1311. err:
  1312. tor_free(s);
  1313. close(fd);
  1314. return 0;
  1315. /* LCOV_EXCL_STOP */
  1316. #elif defined (_WIN32)
  1317. /* Windows has MEMORYSTATUSEX; pretty straightforward. */
  1318. MEMORYSTATUSEX ms;
  1319. memset(&ms, 0, sizeof(ms));
  1320. ms.dwLength = sizeof(ms);
  1321. if (! GlobalMemoryStatusEx(&ms))
  1322. return 0;
  1323. return ms.ullTotalPhys;
  1324. #elif defined(HAVE_SYSCTL) && defined(INT64_HW_MEM)
  1325. /* On many systems, HW_PYHSMEM is clipped to 32 bits; let's use a better
  1326. * variant if we know about it. */
  1327. uint64_t memsize = 0;
  1328. size_t len = sizeof(memsize);
  1329. int mib[2] = {CTL_HW, INT64_HW_MEM};
  1330. if (sysctl(mib,2,&memsize,&len,NULL,0))
  1331. return 0;
  1332. return memsize;
  1333. #elif defined(HAVE_SYSCTL) && defined(HW_PHYSMEM)
  1334. /* On some systems (like FreeBSD I hope) you can use a size_t with
  1335. * HW_PHYSMEM. */
  1336. size_t memsize=0;
  1337. size_t len = sizeof(memsize);
  1338. int mib[2] = {CTL_HW, HW_USERMEM};
  1339. if (sysctl(mib,2,&memsize,&len,NULL,0))
  1340. return 0;
  1341. return memsize;
  1342. #else
  1343. /* I have no clue. */
  1344. return 0;
  1345. #endif /* defined(__linux__) || ... */
  1346. }
  1347. /**
  1348. * Try to find out how much physical memory the system has. On success,
  1349. * return 0 and set *<b>mem_out</b> to that value. On failure, return -1.
  1350. */
  1351. MOCK_IMPL(int,
  1352. get_total_system_memory, (size_t *mem_out))
  1353. {
  1354. static size_t mem_cached=0;
  1355. uint64_t m = get_total_system_memory_impl();
  1356. if (0 == m) {
  1357. /* LCOV_EXCL_START -- can't make this happen without mocking. */
  1358. /* We couldn't find our memory total */
  1359. if (0 == mem_cached) {
  1360. /* We have no cached value either */
  1361. *mem_out = 0;
  1362. return -1;
  1363. }
  1364. *mem_out = mem_cached;
  1365. return 0;
  1366. /* LCOV_EXCL_STOP */
  1367. }
  1368. #if SIZE_MAX != UINT64_MAX
  1369. if (m > SIZE_MAX) {
  1370. /* I think this could happen if we're a 32-bit Tor running on a 64-bit
  1371. * system: we could have more system memory than would fit in a
  1372. * size_t. */
  1373. m = SIZE_MAX;
  1374. }
  1375. #endif /* SIZE_MAX != UINT64_MAX */
  1376. *mem_out = mem_cached = (size_t) m;
  1377. return 0;
  1378. }
  1379. /** Emit the password prompt <b>prompt</b>, then read up to <b>buflen</b>
  1380. * bytes of passphrase into <b>output</b>. Return the number of bytes in
  1381. * the passphrase, excluding terminating NUL.
  1382. */
  1383. ssize_t
  1384. tor_getpass(const char *prompt, char *output, size_t buflen)
  1385. {
  1386. tor_assert(buflen <= SSIZE_MAX);
  1387. tor_assert(buflen >= 1);
  1388. #if defined(HAVE_READPASSPHRASE)
  1389. char *pwd = readpassphrase(prompt, output, buflen, RPP_ECHO_OFF);
  1390. if (pwd == NULL)
  1391. return -1;
  1392. return strlen(pwd);
  1393. #elif defined(_WIN32)
  1394. int r = -1;
  1395. while (*prompt) {
  1396. _putch(*prompt++);
  1397. }
  1398. tor_assert(buflen <= INT_MAX);
  1399. wchar_t *buf = tor_calloc(buflen, sizeof(wchar_t));
  1400. wchar_t *ptr = buf, *lastch = buf + buflen - 1;
  1401. while (ptr < lastch) {
  1402. wint_t ch = _getwch();
  1403. switch (ch) {
  1404. case '\r':
  1405. case '\n':
  1406. case WEOF:
  1407. goto done_reading;
  1408. case 3:
  1409. goto done; /* Can't actually read ctrl-c this way. */
  1410. case '\b':
  1411. if (ptr > buf)
  1412. --ptr;
  1413. continue;
  1414. case 0:
  1415. case 0xe0:
  1416. ch = _getwch(); /* Ignore; this is a function or arrow key */
  1417. break;
  1418. default:
  1419. *ptr++ = ch;
  1420. break;
  1421. }
  1422. }
  1423. done_reading:
  1424. ;
  1425. #ifndef WC_ERR_INVALID_CHARS
  1426. #define WC_ERR_INVALID_CHARS 0x80
  1427. #endif
  1428. /* Now convert it to UTF-8 */
  1429. r = WideCharToMultiByte(CP_UTF8,
  1430. WC_NO_BEST_FIT_CHARS|WC_ERR_INVALID_CHARS,
  1431. buf, (int)(ptr-buf),
  1432. output, (int)(buflen-1),
  1433. NULL, NULL);
  1434. if (r <= 0) {
  1435. r = -1;
  1436. goto done;
  1437. }
  1438. tor_assert(r < (int)buflen);
  1439. output[r] = 0;
  1440. done:
  1441. SecureZeroMemory(buf, sizeof(wchar_t)*buflen);
  1442. tor_free(buf);
  1443. return r;
  1444. #else
  1445. #error "No implementation for tor_getpass found!"
  1446. #endif /* defined(HAVE_READPASSPHRASE) || ... */
  1447. }
  1448. /** Return the amount of free disk space we have permission to use, in
  1449. * bytes. Return -1 if the amount of free space can't be determined. */
  1450. int64_t
  1451. tor_get_avail_disk_space(const char *path)
  1452. {
  1453. #ifdef HAVE_STATVFS
  1454. struct statvfs st;
  1455. int r;
  1456. memset(&st, 0, sizeof(st));
  1457. r = statvfs(path, &st);
  1458. if (r < 0)
  1459. return -1;
  1460. int64_t result = st.f_bavail;
  1461. if (st.f_frsize) {
  1462. result *= st.f_frsize;
  1463. } else if (st.f_bsize) {
  1464. result *= st.f_bsize;
  1465. } else {
  1466. return -1;
  1467. }
  1468. return result;
  1469. #elif defined(_WIN32)
  1470. ULARGE_INTEGER freeBytesAvail;
  1471. BOOL ok;
  1472. ok = GetDiskFreeSpaceEx(path, &freeBytesAvail, NULL, NULL);
  1473. if (!ok) {
  1474. return -1;
  1475. }
  1476. return (int64_t)freeBytesAvail.QuadPart;
  1477. #else
  1478. (void)path;
  1479. errno = ENOSYS;
  1480. return -1;
  1481. #endif /* defined(HAVE_STATVFS) || ... */
  1482. }