compat.c 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217
  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 "common/sandbox.h"
  125. /** As open(path, flags, mode), but return an fd with the close-on-exec mode
  126. * set. */
  127. int
  128. tor_open_cloexec(const char *path, int flags, unsigned mode)
  129. {
  130. int fd;
  131. const char *p = sandbox_intern_string(path);
  132. #ifdef O_CLOEXEC
  133. fd = open(p, flags|O_CLOEXEC, mode);
  134. if (fd >= 0)
  135. return fd;
  136. /* If we got an error, see if it is EINVAL. EINVAL might indicate that,
  137. * even though we were built on a system with O_CLOEXEC support, we
  138. * are running on one without. */
  139. if (errno != EINVAL)
  140. return -1;
  141. #endif /* defined(O_CLOEXEC) */
  142. log_debug(LD_FS, "Opening %s with flags %x", p, flags);
  143. fd = open(p, flags, mode);
  144. #ifdef FD_CLOEXEC
  145. if (fd >= 0) {
  146. if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1) {
  147. log_warn(LD_FS,"Couldn't set FD_CLOEXEC: %s", strerror(errno));
  148. close(fd);
  149. return -1;
  150. }
  151. }
  152. #endif /* defined(FD_CLOEXEC) */
  153. return fd;
  154. }
  155. /** As fopen(path,mode), but ensures that the O_CLOEXEC bit is set on the
  156. * underlying file handle. */
  157. FILE *
  158. tor_fopen_cloexec(const char *path, const char *mode)
  159. {
  160. FILE *result = fopen(path, mode);
  161. #ifdef FD_CLOEXEC
  162. if (result != NULL) {
  163. if (fcntl(fileno(result), F_SETFD, FD_CLOEXEC) == -1) {
  164. log_warn(LD_FS,"Couldn't set FD_CLOEXEC: %s", strerror(errno));
  165. fclose(result);
  166. return NULL;
  167. }
  168. }
  169. #endif /* defined(FD_CLOEXEC) */
  170. return result;
  171. }
  172. /** As rename(), but work correctly with the sandbox. */
  173. int
  174. tor_rename(const char *path_old, const char *path_new)
  175. {
  176. log_debug(LD_FS, "Renaming %s to %s", path_old, path_new);
  177. return rename(sandbox_intern_string(path_old),
  178. sandbox_intern_string(path_new));
  179. }
  180. #if defined(HAVE_MMAP) || defined(RUNNING_DOXYGEN)
  181. /** Try to create a memory mapping for <b>filename</b> and return it. On
  182. * failure, return NULL. Sets errno properly, using ERANGE to mean
  183. * "empty file". Must only be called on trusted Tor-owned files, as changing
  184. * the underlying file's size causes unspecified behavior. */
  185. tor_mmap_t *
  186. tor_mmap_file(const char *filename)
  187. {
  188. int fd; /* router file */
  189. char *string;
  190. int result;
  191. tor_mmap_t *res;
  192. size_t size, filesize;
  193. struct stat st;
  194. tor_assert(filename);
  195. fd = tor_open_cloexec(filename, O_RDONLY, 0);
  196. if (fd<0) {
  197. int save_errno = errno;
  198. int severity = (errno == ENOENT) ? LOG_INFO : LOG_WARN;
  199. log_fn(severity, LD_FS,"Could not open \"%s\" for mmap(): %s",filename,
  200. strerror(errno));
  201. errno = save_errno;
  202. return NULL;
  203. }
  204. /* Get the size of the file */
  205. result = fstat(fd, &st);
  206. if (result != 0) {
  207. int save_errno = errno;
  208. log_warn(LD_FS,
  209. "Couldn't fstat opened descriptor for \"%s\" during mmap: %s",
  210. filename, strerror(errno));
  211. close(fd);
  212. errno = save_errno;
  213. return NULL;
  214. }
  215. size = filesize = (size_t)(st.st_size);
  216. if (st.st_size > SSIZE_T_CEILING || (off_t)size < st.st_size) {
  217. log_warn(LD_FS, "File \"%s\" is too large. Ignoring.",filename);
  218. errno = EFBIG;
  219. close(fd);
  220. return NULL;
  221. }
  222. if (!size) {
  223. /* Zero-length file. If we call mmap on it, it will succeed but
  224. * return NULL, and bad things will happen. So just fail. */
  225. log_info(LD_FS,"File \"%s\" is empty. Ignoring.",filename);
  226. errno = ERANGE;
  227. close(fd);
  228. return NULL;
  229. }
  230. string = mmap(0, size, PROT_READ, MAP_PRIVATE, fd, 0);
  231. close(fd);
  232. if (string == MAP_FAILED) {
  233. int save_errno = errno;
  234. log_warn(LD_FS,"Could not mmap file \"%s\": %s", filename,
  235. strerror(errno));
  236. errno = save_errno;
  237. return NULL;
  238. }
  239. res = tor_malloc_zero(sizeof(tor_mmap_t));
  240. res->data = string;
  241. res->size = filesize;
  242. res->mapping_size = size;
  243. return res;
  244. }
  245. /** Release storage held for a memory mapping; returns 0 on success,
  246. * or -1 on failure (and logs a warning). */
  247. int
  248. tor_munmap_file(tor_mmap_t *handle)
  249. {
  250. int res;
  251. if (handle == NULL)
  252. return 0;
  253. res = munmap((char*)handle->data, handle->mapping_size);
  254. if (res == 0) {
  255. /* munmap() succeeded */
  256. tor_free(handle);
  257. } else {
  258. log_warn(LD_FS, "Failed to munmap() in tor_munmap_file(): %s",
  259. strerror(errno));
  260. res = -1;
  261. }
  262. return res;
  263. }
  264. #elif defined(_WIN32)
  265. tor_mmap_t *
  266. tor_mmap_file(const char *filename)
  267. {
  268. TCHAR tfilename[MAX_PATH]= {0};
  269. tor_mmap_t *res = tor_malloc_zero(sizeof(tor_mmap_t));
  270. int empty = 0;
  271. HANDLE file_handle = INVALID_HANDLE_VALUE;
  272. DWORD size_low, size_high;
  273. uint64_t real_size;
  274. res->mmap_handle = NULL;
  275. #ifdef UNICODE
  276. mbstowcs(tfilename,filename,MAX_PATH);
  277. #else
  278. strlcpy(tfilename,filename,MAX_PATH);
  279. #endif
  280. file_handle = CreateFile(tfilename,
  281. GENERIC_READ, FILE_SHARE_READ,
  282. NULL,
  283. OPEN_EXISTING,
  284. FILE_ATTRIBUTE_NORMAL,
  285. 0);
  286. if (file_handle == INVALID_HANDLE_VALUE)
  287. goto win_err;
  288. size_low = GetFileSize(file_handle, &size_high);
  289. if (size_low == INVALID_FILE_SIZE && GetLastError() != NO_ERROR) {
  290. log_warn(LD_FS,"Error getting size of \"%s\".",filename);
  291. goto win_err;
  292. }
  293. if (size_low == 0 && size_high == 0) {
  294. log_info(LD_FS,"File \"%s\" is empty. Ignoring.",filename);
  295. empty = 1;
  296. goto err;
  297. }
  298. real_size = (((uint64_t)size_high)<<32) | size_low;
  299. if (real_size > SIZE_MAX) {
  300. log_warn(LD_FS,"File \"%s\" is too big to map; not trying.",filename);
  301. goto err;
  302. }
  303. res->size = real_size;
  304. res->mmap_handle = CreateFileMapping(file_handle,
  305. NULL,
  306. PAGE_READONLY,
  307. size_high,
  308. size_low,
  309. NULL);
  310. if (res->mmap_handle == NULL)
  311. goto win_err;
  312. res->data = (char*) MapViewOfFile(res->mmap_handle,
  313. FILE_MAP_READ,
  314. 0, 0, 0);
  315. if (!res->data)
  316. goto win_err;
  317. CloseHandle(file_handle);
  318. return res;
  319. win_err: {
  320. DWORD e = GetLastError();
  321. int severity = (e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND) ?
  322. LOG_INFO : LOG_WARN;
  323. char *msg = format_win32_error(e);
  324. log_fn(severity, LD_FS, "Couldn't mmap file \"%s\": %s", filename, msg);
  325. tor_free(msg);
  326. if (e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND)
  327. errno = ENOENT;
  328. else
  329. errno = EINVAL;
  330. }
  331. err:
  332. if (empty)
  333. errno = ERANGE;
  334. if (file_handle != INVALID_HANDLE_VALUE)
  335. CloseHandle(file_handle);
  336. tor_munmap_file(res);
  337. return NULL;
  338. }
  339. /* Unmap the file, and return 0 for success or -1 for failure */
  340. int
  341. tor_munmap_file(tor_mmap_t *handle)
  342. {
  343. if (handle == NULL)
  344. return 0;
  345. if (handle->data) {
  346. /* This is an ugly cast, but without it, "data" in struct tor_mmap_t would
  347. have to be redefined as non-const. */
  348. BOOL ok = UnmapViewOfFile( (LPVOID) handle->data);
  349. if (!ok) {
  350. log_warn(LD_FS, "Failed to UnmapViewOfFile() in tor_munmap_file(): %d",
  351. (int)GetLastError());
  352. }
  353. }
  354. if (handle->mmap_handle != NULL)
  355. CloseHandle(handle->mmap_handle);
  356. tor_free(handle);
  357. return 0;
  358. }
  359. #else
  360. #error "cannot implement tor_mmap_file"
  361. #endif /* defined(HAVE_MMAP) || ... || ... */
  362. /** Given <b>hlen</b> bytes at <b>haystack</b> and <b>nlen</b> bytes at
  363. * <b>needle</b>, return a pointer to the first occurrence of the needle
  364. * within the haystack, or NULL if there is no such occurrence.
  365. *
  366. * This function is <em>not</em> timing-safe.
  367. *
  368. * Requires that <b>nlen</b> be greater than zero.
  369. */
  370. const void *
  371. tor_memmem(const void *_haystack, size_t hlen,
  372. const void *_needle, size_t nlen)
  373. {
  374. #if defined(HAVE_MEMMEM) && (!defined(__GNUC__) || __GNUC__ >= 2)
  375. tor_assert(nlen);
  376. return memmem(_haystack, hlen, _needle, nlen);
  377. #else
  378. /* This isn't as fast as the GLIBC implementation, but it doesn't need to
  379. * be. */
  380. const char *p, *last_possible_start;
  381. const char *haystack = (const char*)_haystack;
  382. const char *needle = (const char*)_needle;
  383. char first;
  384. tor_assert(nlen);
  385. if (nlen > hlen)
  386. return NULL;
  387. p = haystack;
  388. /* Last position at which the needle could start. */
  389. last_possible_start = haystack + hlen - nlen;
  390. first = *(const char*)needle;
  391. while ((p = memchr(p, first, last_possible_start + 1 - p))) {
  392. if (fast_memeq(p, needle, nlen))
  393. return p;
  394. if (++p > last_possible_start) {
  395. /* This comparison shouldn't be necessary, since if p was previously
  396. * equal to last_possible_start, the next memchr call would be
  397. * "memchr(p, first, 0)", which will return NULL. But it clarifies the
  398. * logic. */
  399. return NULL;
  400. }
  401. }
  402. return NULL;
  403. #endif /* defined(HAVE_MEMMEM) && (!defined(__GNUC__) || __GNUC__ >= 2) */
  404. }
  405. /** Helper for tor_strtok_r_impl: Advances cp past all characters in
  406. * <b>sep</b>, and returns its new value. */
  407. static char *
  408. strtok_helper(char *cp, const char *sep)
  409. {
  410. if (sep[1]) {
  411. while (*cp && strchr(sep, *cp))
  412. ++cp;
  413. } else {
  414. while (*cp && *cp == *sep)
  415. ++cp;
  416. }
  417. return cp;
  418. }
  419. /** Implementation of strtok_r for platforms whose coders haven't figured out
  420. * how to write one. Hey, retrograde libc developers! You can use this code
  421. * here for free! */
  422. char *
  423. tor_strtok_r_impl(char *str, const char *sep, char **lasts)
  424. {
  425. char *cp, *start;
  426. tor_assert(*sep);
  427. if (str) {
  428. str = strtok_helper(str, sep);
  429. if (!*str)
  430. return NULL;
  431. start = cp = *lasts = str;
  432. } else if (!*lasts || !**lasts) {
  433. return NULL;
  434. } else {
  435. start = cp = *lasts;
  436. }
  437. if (sep[1]) {
  438. while (*cp && !strchr(sep, *cp))
  439. ++cp;
  440. } else {
  441. cp = strchr(cp, *sep);
  442. }
  443. if (!cp || !*cp) {
  444. *lasts = NULL;
  445. } else {
  446. *cp++ = '\0';
  447. *lasts = strtok_helper(cp, sep);
  448. }
  449. return start;
  450. }
  451. /**
  452. * Read a 16-bit value beginning at <b>cp</b>. Equivalent to
  453. * *(uint16_t*)(cp), but will not cause segfaults on platforms that forbid
  454. * unaligned memory access.
  455. */
  456. uint16_t
  457. get_uint16(const void *cp)
  458. {
  459. uint16_t v;
  460. memcpy(&v,cp,2);
  461. return v;
  462. }
  463. /**
  464. * Read a 32-bit value beginning at <b>cp</b>. Equivalent to
  465. * *(uint32_t*)(cp), but will not cause segfaults on platforms that forbid
  466. * unaligned memory access.
  467. */
  468. uint32_t
  469. get_uint32(const void *cp)
  470. {
  471. uint32_t v;
  472. memcpy(&v,cp,4);
  473. return v;
  474. }
  475. /**
  476. * Read a 64-bit value beginning at <b>cp</b>. Equivalent to
  477. * *(uint64_t*)(cp), but will not cause segfaults on platforms that forbid
  478. * unaligned memory access.
  479. */
  480. uint64_t
  481. get_uint64(const void *cp)
  482. {
  483. uint64_t v;
  484. memcpy(&v,cp,8);
  485. return v;
  486. }
  487. /**
  488. * Set a 16-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
  489. * *(uint16_t*)(cp) = v, but will not cause segfaults on platforms that forbid
  490. * unaligned memory access. */
  491. void
  492. set_uint16(void *cp, uint16_t v)
  493. {
  494. memcpy(cp,&v,2);
  495. }
  496. /**
  497. * Set a 32-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
  498. * *(uint32_t*)(cp) = v, but will not cause segfaults on platforms that forbid
  499. * unaligned memory access. */
  500. void
  501. set_uint32(void *cp, uint32_t v)
  502. {
  503. memcpy(cp,&v,4);
  504. }
  505. /**
  506. * Set a 64-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
  507. * *(uint64_t*)(cp) = v, but will not cause segfaults on platforms that forbid
  508. * unaligned memory access. */
  509. void
  510. set_uint64(void *cp, uint64_t v)
  511. {
  512. memcpy(cp,&v,8);
  513. }
  514. /**
  515. * Rename the file <b>from</b> to the file <b>to</b>. On Unix, this is
  516. * the same as rename(2). On windows, this removes <b>to</b> first if
  517. * it already exists.
  518. * Returns 0 on success. Returns -1 and sets errno on failure.
  519. */
  520. int
  521. replace_file(const char *from, const char *to)
  522. {
  523. #ifndef _WIN32
  524. return tor_rename(from, to);
  525. #else
  526. switch (file_status(to))
  527. {
  528. case FN_NOENT:
  529. break;
  530. case FN_FILE:
  531. case FN_EMPTY:
  532. if (unlink(to)) return -1;
  533. break;
  534. case FN_ERROR:
  535. return -1;
  536. case FN_DIR:
  537. errno = EISDIR;
  538. return -1;
  539. }
  540. return tor_rename(from,to);
  541. #endif /* !defined(_WIN32) */
  542. }
  543. /** Change <b>fname</b>'s modification time to now. */
  544. int
  545. touch_file(const char *fname)
  546. {
  547. if (utime(fname, NULL)!=0)
  548. return -1;
  549. return 0;
  550. }
  551. /** Represents a lockfile on which we hold the lock. */
  552. struct tor_lockfile_t {
  553. /** Name of the file */
  554. char *filename;
  555. /** File descriptor used to hold the file open */
  556. int fd;
  557. };
  558. /** Try to get a lock on the lockfile <b>filename</b>, creating it as
  559. * necessary. If someone else has the lock and <b>blocking</b> is true,
  560. * wait until the lock is available. Otherwise return immediately whether
  561. * we succeeded or not.
  562. *
  563. * Set *<b>locked_out</b> to true if somebody else had the lock, and to false
  564. * otherwise.
  565. *
  566. * Return a <b>tor_lockfile_t</b> on success, NULL on failure.
  567. *
  568. * (Implementation note: because we need to fall back to fcntl on some
  569. * platforms, these locks are per-process, not per-thread. If you want
  570. * to do in-process locking, use tor_mutex_t like a normal person.
  571. * On Windows, when <b>blocking</b> is true, the maximum time that
  572. * is actually waited is 10 seconds, after which NULL is returned
  573. * and <b>locked_out</b> is set to 1.)
  574. */
  575. tor_lockfile_t *
  576. tor_lockfile_lock(const char *filename, int blocking, int *locked_out)
  577. {
  578. tor_lockfile_t *result;
  579. int fd;
  580. *locked_out = 0;
  581. log_info(LD_FS, "Locking \"%s\"", filename);
  582. fd = tor_open_cloexec(filename, O_RDWR|O_CREAT|O_TRUNC, 0600);
  583. if (fd < 0) {
  584. log_warn(LD_FS,"Couldn't open \"%s\" for locking: %s", filename,
  585. strerror(errno));
  586. return NULL;
  587. }
  588. #ifdef _WIN32
  589. _lseek(fd, 0, SEEK_SET);
  590. if (_locking(fd, blocking ? _LK_LOCK : _LK_NBLCK, 1) < 0) {
  591. if (errno != EACCES && errno != EDEADLOCK)
  592. log_warn(LD_FS,"Couldn't lock \"%s\": %s", filename, strerror(errno));
  593. else
  594. *locked_out = 1;
  595. close(fd);
  596. return NULL;
  597. }
  598. #elif defined(HAVE_FLOCK)
  599. if (flock(fd, LOCK_EX|(blocking ? 0 : LOCK_NB)) < 0) {
  600. if (errno != EWOULDBLOCK)
  601. log_warn(LD_FS,"Couldn't lock \"%s\": %s", filename, strerror(errno));
  602. else
  603. *locked_out = 1;
  604. close(fd);
  605. return NULL;
  606. }
  607. #else
  608. {
  609. struct flock lock;
  610. memset(&lock, 0, sizeof(lock));
  611. lock.l_type = F_WRLCK;
  612. lock.l_whence = SEEK_SET;
  613. if (fcntl(fd, blocking ? F_SETLKW : F_SETLK, &lock) < 0) {
  614. if (errno != EACCES && errno != EAGAIN)
  615. log_warn(LD_FS, "Couldn't lock \"%s\": %s", filename, strerror(errno));
  616. else
  617. *locked_out = 1;
  618. close(fd);
  619. return NULL;
  620. }
  621. }
  622. #endif /* defined(_WIN32) || ... */
  623. result = tor_malloc(sizeof(tor_lockfile_t));
  624. result->filename = tor_strdup(filename);
  625. result->fd = fd;
  626. return result;
  627. }
  628. /** Release the lock held as <b>lockfile</b>. */
  629. void
  630. tor_lockfile_unlock(tor_lockfile_t *lockfile)
  631. {
  632. tor_assert(lockfile);
  633. log_info(LD_FS, "Unlocking \"%s\"", lockfile->filename);
  634. #ifdef _WIN32
  635. _lseek(lockfile->fd, 0, SEEK_SET);
  636. if (_locking(lockfile->fd, _LK_UNLCK, 1) < 0) {
  637. log_warn(LD_FS,"Error unlocking \"%s\": %s", lockfile->filename,
  638. strerror(errno));
  639. }
  640. #elif defined(HAVE_FLOCK)
  641. if (flock(lockfile->fd, LOCK_UN) < 0) {
  642. log_warn(LD_FS, "Error unlocking \"%s\": %s", lockfile->filename,
  643. strerror(errno));
  644. }
  645. #else
  646. /* Closing the lockfile is sufficient. */
  647. #endif /* defined(_WIN32) || ... */
  648. close(lockfile->fd);
  649. lockfile->fd = -1;
  650. tor_free(lockfile->filename);
  651. tor_free(lockfile);
  652. }
  653. /** Number of extra file descriptors to keep in reserve beyond those that we
  654. * tell Tor it's allowed to use. */
  655. #define ULIMIT_BUFFER 32 /* keep 32 extra fd's beyond ConnLimit_ */
  656. /** Learn the maximum allowed number of file descriptors, and tell the
  657. * system we want to use up to that number. (Some systems have a low soft
  658. * limit, and let us set it higher.) We compute this by finding the largest
  659. * number that we can use.
  660. *
  661. * If the limit is below the reserved file descriptor value (ULIMIT_BUFFER),
  662. * return -1 and <b>max_out</b> is untouched.
  663. *
  664. * If we can't find a number greater than or equal to <b>limit</b>, then we
  665. * fail by returning -1 and <b>max_out</b> is untouched.
  666. *
  667. * If we are unable to set the limit value because of setrlimit() failing,
  668. * return 0 and <b>max_out</b> is set to the current maximum value returned
  669. * by getrlimit().
  670. *
  671. * Otherwise, return 0 and store the maximum we found inside <b>max_out</b>
  672. * and set <b>max_sockets</b> with that value as well.*/
  673. int
  674. set_max_file_descriptors(rlim_t limit, int *max_out)
  675. {
  676. if (limit < ULIMIT_BUFFER) {
  677. log_warn(LD_CONFIG,
  678. "ConnLimit must be at least %d. Failing.", ULIMIT_BUFFER);
  679. return -1;
  680. }
  681. /* Define some maximum connections values for systems where we cannot
  682. * automatically determine a limit. Re Cygwin, see
  683. * http://archives.seul.org/or/talk/Aug-2006/msg00210.html
  684. * For an iPhone, 9999 should work. For Windows and all other unknown
  685. * systems we use 15000 as the default. */
  686. #ifndef HAVE_GETRLIMIT
  687. #if defined(CYGWIN) || defined(__CYGWIN__)
  688. const char *platform = "Cygwin";
  689. const unsigned long MAX_CONNECTIONS = 3200;
  690. #elif defined(_WIN32)
  691. const char *platform = "Windows";
  692. const unsigned long MAX_CONNECTIONS = 15000;
  693. #else
  694. const char *platform = "unknown platforms with no getrlimit()";
  695. const unsigned long MAX_CONNECTIONS = 15000;
  696. #endif /* defined(CYGWIN) || defined(__CYGWIN__) || ... */
  697. log_fn(LOG_INFO, LD_NET,
  698. "This platform is missing getrlimit(). Proceeding.");
  699. if (limit > MAX_CONNECTIONS) {
  700. log_warn(LD_CONFIG,
  701. "We do not support more than %lu file descriptors "
  702. "on %s. Tried to raise to %lu.",
  703. (unsigned long)MAX_CONNECTIONS, platform, (unsigned long)limit);
  704. return -1;
  705. }
  706. limit = MAX_CONNECTIONS;
  707. #else /* !(!defined(HAVE_GETRLIMIT)) */
  708. struct rlimit rlim;
  709. if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) {
  710. log_warn(LD_NET, "Could not get maximum number of file descriptors: %s",
  711. strerror(errno));
  712. return -1;
  713. }
  714. if (rlim.rlim_max < limit) {
  715. log_warn(LD_CONFIG,"We need %lu file descriptors available, and we're "
  716. "limited to %lu. Please change your ulimit -n.",
  717. (unsigned long)limit, (unsigned long)rlim.rlim_max);
  718. return -1;
  719. }
  720. if (rlim.rlim_max > rlim.rlim_cur) {
  721. log_info(LD_NET,"Raising max file descriptors from %lu to %lu.",
  722. (unsigned long)rlim.rlim_cur, (unsigned long)rlim.rlim_max);
  723. }
  724. /* Set the current limit value so if the attempt to set the limit to the
  725. * max fails at least we'll have a valid value of maximum sockets. */
  726. *max_out = (int)rlim.rlim_cur - ULIMIT_BUFFER;
  727. set_max_sockets(*max_out);
  728. rlim.rlim_cur = rlim.rlim_max;
  729. if (setrlimit(RLIMIT_NOFILE, &rlim) != 0) {
  730. int couldnt_set = 1;
  731. const int setrlimit_errno = errno;
  732. #ifdef OPEN_MAX
  733. uint64_t try_limit = OPEN_MAX - ULIMIT_BUFFER;
  734. if (errno == EINVAL && try_limit < (uint64_t) rlim.rlim_cur) {
  735. /* On some platforms, OPEN_MAX is the real limit, and getrlimit() is
  736. * full of nasty lies. I'm looking at you, OSX 10.5.... */
  737. rlim.rlim_cur = MIN((rlim_t) try_limit, rlim.rlim_cur);
  738. if (setrlimit(RLIMIT_NOFILE, &rlim) == 0) {
  739. if (rlim.rlim_cur < (rlim_t)limit) {
  740. log_warn(LD_CONFIG, "We are limited to %lu file descriptors by "
  741. "OPEN_MAX (%lu), and ConnLimit is %lu. Changing "
  742. "ConnLimit; sorry.",
  743. (unsigned long)try_limit, (unsigned long)OPEN_MAX,
  744. (unsigned long)limit);
  745. } else {
  746. log_info(LD_CONFIG, "Dropped connection limit to %lu based on "
  747. "OPEN_MAX (%lu); Apparently, %lu was too high and rlimit "
  748. "lied to us.",
  749. (unsigned long)try_limit, (unsigned long)OPEN_MAX,
  750. (unsigned long)rlim.rlim_max);
  751. }
  752. couldnt_set = 0;
  753. }
  754. }
  755. #endif /* defined(OPEN_MAX) */
  756. if (couldnt_set) {
  757. log_warn(LD_CONFIG,"Couldn't set maximum number of file descriptors: %s",
  758. strerror(setrlimit_errno));
  759. }
  760. }
  761. /* leave some overhead for logs, etc, */
  762. limit = rlim.rlim_cur;
  763. #endif /* !defined(HAVE_GETRLIMIT) */
  764. if (limit > INT_MAX)
  765. limit = INT_MAX;
  766. tor_assert(max_out);
  767. *max_out = (int)limit - ULIMIT_BUFFER;
  768. set_max_sockets(*max_out);
  769. return 0;
  770. }
  771. #ifndef _WIN32
  772. /** Log details of current user and group credentials. Return 0 on
  773. * success. Logs and return -1 on failure.
  774. */
  775. static int
  776. log_credential_status(void)
  777. {
  778. /** Log level to use when describing non-error UID/GID status. */
  779. #define CREDENTIAL_LOG_LEVEL LOG_INFO
  780. /* Real, effective and saved UIDs */
  781. uid_t ruid, euid, suid;
  782. /* Read, effective and saved GIDs */
  783. gid_t rgid, egid, sgid;
  784. /* Supplementary groups */
  785. gid_t *sup_gids = NULL;
  786. int sup_gids_size;
  787. /* Number of supplementary groups */
  788. int ngids;
  789. /* log UIDs */
  790. #ifdef HAVE_GETRESUID
  791. if (getresuid(&ruid, &euid, &suid) != 0 ) {
  792. log_warn(LD_GENERAL, "Error getting changed UIDs: %s", strerror(errno));
  793. return -1;
  794. } else {
  795. log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
  796. "UID is %u (real), %u (effective), %u (saved)",
  797. (unsigned)ruid, (unsigned)euid, (unsigned)suid);
  798. }
  799. #else /* !(defined(HAVE_GETRESUID)) */
  800. /* getresuid is not present on MacOS X, so we can't get the saved (E)UID */
  801. ruid = getuid();
  802. euid = geteuid();
  803. (void)suid;
  804. log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
  805. "UID is %u (real), %u (effective), unknown (saved)",
  806. (unsigned)ruid, (unsigned)euid);
  807. #endif /* defined(HAVE_GETRESUID) */
  808. /* log GIDs */
  809. #ifdef HAVE_GETRESGID
  810. if (getresgid(&rgid, &egid, &sgid) != 0 ) {
  811. log_warn(LD_GENERAL, "Error getting changed GIDs: %s", strerror(errno));
  812. return -1;
  813. } else {
  814. log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
  815. "GID is %u (real), %u (effective), %u (saved)",
  816. (unsigned)rgid, (unsigned)egid, (unsigned)sgid);
  817. }
  818. #else /* !(defined(HAVE_GETRESGID)) */
  819. /* getresgid is not present on MacOS X, so we can't get the saved (E)GID */
  820. rgid = getgid();
  821. egid = getegid();
  822. (void)sgid;
  823. log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
  824. "GID is %u (real), %u (effective), unknown (saved)",
  825. (unsigned)rgid, (unsigned)egid);
  826. #endif /* defined(HAVE_GETRESGID) */
  827. /* log supplementary groups */
  828. sup_gids_size = 64;
  829. sup_gids = tor_calloc(64, sizeof(gid_t));
  830. while ((ngids = getgroups(sup_gids_size, sup_gids)) < 0 &&
  831. errno == EINVAL &&
  832. sup_gids_size < NGROUPS_MAX) {
  833. sup_gids_size *= 2;
  834. sup_gids = tor_reallocarray(sup_gids, sizeof(gid_t), sup_gids_size);
  835. }
  836. if (ngids < 0) {
  837. log_warn(LD_GENERAL, "Error getting supplementary GIDs: %s",
  838. strerror(errno));
  839. tor_free(sup_gids);
  840. return -1;
  841. } else {
  842. int i, retval = 0;
  843. char *s = NULL;
  844. smartlist_t *elts = smartlist_new();
  845. for (i = 0; i<ngids; i++) {
  846. smartlist_add_asprintf(elts, "%u", (unsigned)sup_gids[i]);
  847. }
  848. s = smartlist_join_strings(elts, " ", 0, NULL);
  849. log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL, "Supplementary groups are: %s",s);
  850. tor_free(s);
  851. SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
  852. smartlist_free(elts);
  853. tor_free(sup_gids);
  854. return retval;
  855. }
  856. return 0;
  857. }
  858. #endif /* !defined(_WIN32) */
  859. #ifndef _WIN32
  860. /** Cached struct from the last getpwname() call we did successfully. */
  861. static struct passwd *passwd_cached = NULL;
  862. /** Helper: copy a struct passwd object.
  863. *
  864. * We only copy the fields pw_uid, pw_gid, pw_name, pw_dir. Tor doesn't use
  865. * any others, and I don't want to run into incompatibilities.
  866. */
  867. static struct passwd *
  868. tor_passwd_dup(const struct passwd *pw)
  869. {
  870. struct passwd *new_pw = tor_malloc_zero(sizeof(struct passwd));
  871. if (pw->pw_name)
  872. new_pw->pw_name = tor_strdup(pw->pw_name);
  873. if (pw->pw_dir)
  874. new_pw->pw_dir = tor_strdup(pw->pw_dir);
  875. new_pw->pw_uid = pw->pw_uid;
  876. new_pw->pw_gid = pw->pw_gid;
  877. return new_pw;
  878. }
  879. #define tor_passwd_free(pw) \
  880. FREE_AND_NULL(struct passwd, tor_passwd_free_, (pw))
  881. /** Helper: free one of our cached 'struct passwd' values. */
  882. static void
  883. tor_passwd_free_(struct passwd *pw)
  884. {
  885. if (!pw)
  886. return;
  887. tor_free(pw->pw_name);
  888. tor_free(pw->pw_dir);
  889. tor_free(pw);
  890. }
  891. /** Wrapper around getpwnam() that caches result. Used so that we don't need
  892. * to give the sandbox access to /etc/passwd.
  893. *
  894. * The following fields alone will definitely be copied in the output: pw_uid,
  895. * pw_gid, pw_name, pw_dir. Other fields are not present in cached values.
  896. *
  897. * When called with a NULL argument, this function clears storage associated
  898. * with static variables it uses.
  899. **/
  900. const struct passwd *
  901. tor_getpwnam(const char *username)
  902. {
  903. struct passwd *pw;
  904. if (username == NULL) {
  905. tor_passwd_free(passwd_cached);
  906. passwd_cached = NULL;
  907. return NULL;
  908. }
  909. if ((pw = getpwnam(username))) {
  910. tor_passwd_free(passwd_cached);
  911. passwd_cached = tor_passwd_dup(pw);
  912. log_info(LD_GENERAL, "Caching new entry %s for %s",
  913. passwd_cached->pw_name, username);
  914. return pw;
  915. }
  916. /* Lookup failed */
  917. if (! passwd_cached || ! passwd_cached->pw_name)
  918. return NULL;
  919. if (! strcmp(username, passwd_cached->pw_name))
  920. return passwd_cached; // LCOV_EXCL_LINE - would need to make getpwnam flaky
  921. return NULL;
  922. }
  923. /** Wrapper around getpwnam() that can use cached result from
  924. * tor_getpwnam(). Used so that we don't need to give the sandbox access to
  925. * /etc/passwd.
  926. *
  927. * The following fields alone will definitely be copied in the output: pw_uid,
  928. * pw_gid, pw_name, pw_dir. Other fields are not present in cached values.
  929. */
  930. const struct passwd *
  931. tor_getpwuid(uid_t uid)
  932. {
  933. struct passwd *pw;
  934. if ((pw = getpwuid(uid))) {
  935. return pw;
  936. }
  937. /* Lookup failed */
  938. if (! passwd_cached)
  939. return NULL;
  940. if (uid == passwd_cached->pw_uid)
  941. return passwd_cached; // LCOV_EXCL_LINE - would need to make getpwnam flaky
  942. return NULL;
  943. }
  944. #endif /* !defined(_WIN32) */
  945. /** Return true iff we were compiled with capability support, and capabilities
  946. * seem to work. **/
  947. int
  948. have_capability_support(void)
  949. {
  950. #ifdef HAVE_LINUX_CAPABILITIES
  951. cap_t caps = cap_get_proc();
  952. if (caps == NULL)
  953. return 0;
  954. cap_free(caps);
  955. return 1;
  956. #else /* !(defined(HAVE_LINUX_CAPABILITIES)) */
  957. return 0;
  958. #endif /* defined(HAVE_LINUX_CAPABILITIES) */
  959. }
  960. #ifdef HAVE_LINUX_CAPABILITIES
  961. /** Helper. Drop all capabilities but a small set, and set PR_KEEPCAPS as
  962. * appropriate.
  963. *
  964. * If pre_setuid, retain only CAP_NET_BIND_SERVICE, CAP_SETUID, and
  965. * CAP_SETGID, and use PR_KEEPCAPS to ensure that capabilities persist across
  966. * setuid().
  967. *
  968. * If not pre_setuid, retain only CAP_NET_BIND_SERVICE, and disable
  969. * PR_KEEPCAPS.
  970. *
  971. * Return 0 on success, and -1 on failure.
  972. */
  973. static int
  974. drop_capabilities(int pre_setuid)
  975. {
  976. /* We keep these three capabilities, and these only, as we setuid.
  977. * After we setuid, we drop all but the first. */
  978. const cap_value_t caplist[] = {
  979. CAP_NET_BIND_SERVICE, CAP_SETUID, CAP_SETGID
  980. };
  981. const char *where = pre_setuid ? "pre-setuid" : "post-setuid";
  982. const int n_effective = pre_setuid ? 3 : 1;
  983. const int n_permitted = pre_setuid ? 3 : 1;
  984. const int n_inheritable = 1;
  985. const int keepcaps = pre_setuid ? 1 : 0;
  986. /* Sets whether we keep capabilities across a setuid. */
  987. if (prctl(PR_SET_KEEPCAPS, keepcaps) < 0) {
  988. log_warn(LD_CONFIG, "Unable to call prctl() %s: %s",
  989. where, strerror(errno));
  990. return -1;
  991. }
  992. cap_t caps = cap_get_proc();
  993. if (!caps) {
  994. log_warn(LD_CONFIG, "Unable to call cap_get_proc() %s: %s",
  995. where, strerror(errno));
  996. return -1;
  997. }
  998. cap_clear(caps);
  999. cap_set_flag(caps, CAP_EFFECTIVE, n_effective, caplist, CAP_SET);
  1000. cap_set_flag(caps, CAP_PERMITTED, n_permitted, caplist, CAP_SET);
  1001. cap_set_flag(caps, CAP_INHERITABLE, n_inheritable, caplist, CAP_SET);
  1002. int r = cap_set_proc(caps);
  1003. cap_free(caps);
  1004. if (r < 0) {
  1005. log_warn(LD_CONFIG, "No permission to set capabilities %s: %s",
  1006. where, strerror(errno));
  1007. return -1;
  1008. }
  1009. return 0;
  1010. }
  1011. #endif /* defined(HAVE_LINUX_CAPABILITIES) */
  1012. /** Call setuid and setgid to run as <b>user</b> and switch to their
  1013. * primary group. Return 0 on success. On failure, log and return -1.
  1014. *
  1015. * If SWITCH_ID_KEEP_BINDLOW is set in 'flags', try to use the capability
  1016. * system to retain the abilitity to bind low ports.
  1017. *
  1018. * If SWITCH_ID_WARN_IF_NO_CAPS is set in flags, also warn if we have
  1019. * don't have capability support.
  1020. */
  1021. int
  1022. switch_id(const char *user, const unsigned flags)
  1023. {
  1024. #ifndef _WIN32
  1025. const struct passwd *pw = NULL;
  1026. uid_t old_uid;
  1027. gid_t old_gid;
  1028. static int have_already_switched_id = 0;
  1029. const int keep_bindlow = !!(flags & SWITCH_ID_KEEP_BINDLOW);
  1030. const int warn_if_no_caps = !!(flags & SWITCH_ID_WARN_IF_NO_CAPS);
  1031. tor_assert(user);
  1032. if (have_already_switched_id)
  1033. return 0;
  1034. /* Log the initial credential state */
  1035. if (log_credential_status())
  1036. return -1;
  1037. log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL, "Changing user and groups");
  1038. /* Get old UID/GID to check if we changed correctly */
  1039. old_uid = getuid();
  1040. old_gid = getgid();
  1041. /* Lookup the user and group information, if we have a problem, bail out. */
  1042. pw = tor_getpwnam(user);
  1043. if (pw == NULL) {
  1044. log_warn(LD_CONFIG, "Error setting configured user: %s not found", user);
  1045. return -1;
  1046. }
  1047. #ifdef HAVE_LINUX_CAPABILITIES
  1048. (void) warn_if_no_caps;
  1049. if (keep_bindlow) {
  1050. if (drop_capabilities(1))
  1051. return -1;
  1052. }
  1053. #else /* !(defined(HAVE_LINUX_CAPABILITIES)) */
  1054. (void) keep_bindlow;
  1055. if (warn_if_no_caps) {
  1056. log_warn(LD_CONFIG, "KeepBindCapabilities set, but no capability support "
  1057. "on this system.");
  1058. }
  1059. #endif /* defined(HAVE_LINUX_CAPABILITIES) */
  1060. /* Properly switch egid,gid,euid,uid here or bail out */
  1061. if (setgroups(1, &pw->pw_gid)) {
  1062. log_warn(LD_GENERAL, "Error setting groups to gid %d: \"%s\".",
  1063. (int)pw->pw_gid, strerror(errno));
  1064. if (old_uid == pw->pw_uid) {
  1065. log_warn(LD_GENERAL, "Tor is already running as %s. You do not need "
  1066. "the \"User\" option if you are already running as the user "
  1067. "you want to be. (If you did not set the User option in your "
  1068. "torrc, check whether it was specified on the command line "
  1069. "by a startup script.)", user);
  1070. } else {
  1071. log_warn(LD_GENERAL, "If you set the \"User\" option, you must start Tor"
  1072. " as root.");
  1073. }
  1074. return -1;
  1075. }
  1076. if (setegid(pw->pw_gid)) {
  1077. log_warn(LD_GENERAL, "Error setting egid to %d: %s",
  1078. (int)pw->pw_gid, strerror(errno));
  1079. return -1;
  1080. }
  1081. if (setgid(pw->pw_gid)) {
  1082. log_warn(LD_GENERAL, "Error setting gid to %d: %s",
  1083. (int)pw->pw_gid, strerror(errno));
  1084. return -1;
  1085. }
  1086. if (setuid(pw->pw_uid)) {
  1087. log_warn(LD_GENERAL, "Error setting configured uid to %s (%d): %s",
  1088. user, (int)pw->pw_uid, strerror(errno));
  1089. return -1;
  1090. }
  1091. if (seteuid(pw->pw_uid)) {
  1092. log_warn(LD_GENERAL, "Error setting configured euid to %s (%d): %s",
  1093. user, (int)pw->pw_uid, strerror(errno));
  1094. return -1;
  1095. }
  1096. /* This is how OpenBSD rolls:
  1097. if (setgroups(1, &pw->pw_gid) || setegid(pw->pw_gid) ||
  1098. setgid(pw->pw_gid) || setuid(pw->pw_uid) || seteuid(pw->pw_uid)) {
  1099. setgid(pw->pw_gid) || seteuid(pw->pw_uid) || setuid(pw->pw_uid)) {
  1100. log_warn(LD_GENERAL, "Error setting configured UID/GID: %s",
  1101. strerror(errno));
  1102. return -1;
  1103. }
  1104. */
  1105. /* We've properly switched egid, gid, euid, uid, and supplementary groups if
  1106. * we're here. */
  1107. #ifdef HAVE_LINUX_CAPABILITIES
  1108. if (keep_bindlow) {
  1109. if (drop_capabilities(0))
  1110. return -1;
  1111. }
  1112. #endif /* defined(HAVE_LINUX_CAPABILITIES) */
  1113. #if !defined(CYGWIN) && !defined(__CYGWIN__)
  1114. /* If we tried to drop privilege to a group/user other than root, attempt to
  1115. * restore root (E)(U|G)ID, and abort if the operation succeeds */
  1116. /* Only check for privilege dropping if we were asked to be non-root */
  1117. if (pw->pw_uid) {
  1118. /* Try changing GID/EGID */
  1119. if (pw->pw_gid != old_gid &&
  1120. (setgid(old_gid) != -1 || setegid(old_gid) != -1)) {
  1121. log_warn(LD_GENERAL, "Was able to restore group credentials even after "
  1122. "switching GID: this means that the setgid code didn't work.");
  1123. return -1;
  1124. }
  1125. /* Try changing UID/EUID */
  1126. if (pw->pw_uid != old_uid &&
  1127. (setuid(old_uid) != -1 || seteuid(old_uid) != -1)) {
  1128. log_warn(LD_GENERAL, "Was able to restore user credentials even after "
  1129. "switching UID: this means that the setuid code didn't work.");
  1130. return -1;
  1131. }
  1132. }
  1133. #endif /* !defined(CYGWIN) && !defined(__CYGWIN__) */
  1134. /* Check what really happened */
  1135. if (log_credential_status()) {
  1136. return -1;
  1137. }
  1138. have_already_switched_id = 1; /* mark success so we never try again */
  1139. #if defined(__linux__) && defined(HAVE_SYS_PRCTL_H) && \
  1140. defined(HAVE_PRCTL) && defined(PR_SET_DUMPABLE)
  1141. if (pw->pw_uid) {
  1142. /* Re-enable core dumps if we're not running as root. */
  1143. log_info(LD_CONFIG, "Re-enabling coredumps");
  1144. if (prctl(PR_SET_DUMPABLE, 1)) {
  1145. log_warn(LD_CONFIG, "Unable to re-enable coredumps: %s",strerror(errno));
  1146. }
  1147. }
  1148. #endif /* defined(__linux__) && defined(HAVE_SYS_PRCTL_H) && ... */
  1149. return 0;
  1150. #else /* !(!defined(_WIN32)) */
  1151. (void)user;
  1152. (void)flags;
  1153. log_warn(LD_CONFIG, "Switching users is unsupported on your OS.");
  1154. return -1;
  1155. #endif /* !defined(_WIN32) */
  1156. }
  1157. /* We only use the linux prctl for now. There is no Win32 support; this may
  1158. * also work on various BSD systems and Mac OS X - send testing feedback!
  1159. *
  1160. * On recent Gnu/Linux kernels it is possible to create a system-wide policy
  1161. * that will prevent non-root processes from attaching to other processes
  1162. * unless they are the parent process; thus gdb can attach to programs that
  1163. * they execute but they cannot attach to other processes running as the same
  1164. * user. The system wide policy may be set with the sysctl
  1165. * kernel.yama.ptrace_scope or by inspecting
  1166. * /proc/sys/kernel/yama/ptrace_scope and it is 1 by default on Ubuntu 11.04.
  1167. *
  1168. * This ptrace scope will be ignored on Gnu/Linux for users with
  1169. * CAP_SYS_PTRACE and so it is very likely that root will still be able to
  1170. * attach to the Tor process.
  1171. */
  1172. /** Attempt to disable debugger attachment: return 1 on success, -1 on
  1173. * failure, and 0 if we don't know how to try on this platform. */
  1174. int
  1175. tor_disable_debugger_attach(void)
  1176. {
  1177. int r = -1;
  1178. log_debug(LD_CONFIG,
  1179. "Attemping to disable debugger attachment to Tor for "
  1180. "unprivileged users.");
  1181. #if defined(__linux__) && defined(HAVE_SYS_PRCTL_H) \
  1182. && defined(HAVE_PRCTL) && defined(PR_SET_DUMPABLE)
  1183. #define TRIED_TO_DISABLE
  1184. r = prctl(PR_SET_DUMPABLE, 0);
  1185. #elif defined(__APPLE__) && defined(PT_DENY_ATTACH)
  1186. #define TRIED_TO_ATTACH
  1187. r = ptrace(PT_DENY_ATTACH, 0, 0, 0);
  1188. #endif /* defined(__linux__) && defined(HAVE_SYS_PRCTL_H) ... || ... */
  1189. // XXX: TODO - Mac OS X has dtrace and this may be disabled.
  1190. // XXX: TODO - Windows probably has something similar
  1191. #ifdef TRIED_TO_DISABLE
  1192. if (r == 0) {
  1193. log_debug(LD_CONFIG,"Debugger attachment disabled for "
  1194. "unprivileged users.");
  1195. return 1;
  1196. } else {
  1197. log_warn(LD_CONFIG, "Unable to disable debugger attaching: %s",
  1198. strerror(errno));
  1199. }
  1200. #endif /* defined(TRIED_TO_DISABLE) */
  1201. #undef TRIED_TO_DISABLE
  1202. return r;
  1203. }
  1204. #ifdef HAVE_PWD_H
  1205. /** Allocate and return a string containing the home directory for the
  1206. * user <b>username</b>. Only works on posix-like systems. */
  1207. char *
  1208. get_user_homedir(const char *username)
  1209. {
  1210. const struct passwd *pw;
  1211. tor_assert(username);
  1212. if (!(pw = tor_getpwnam(username))) {
  1213. log_err(LD_CONFIG,"User \"%s\" not found.", username);
  1214. return NULL;
  1215. }
  1216. return tor_strdup(pw->pw_dir);
  1217. }
  1218. #endif /* defined(HAVE_PWD_H) */
  1219. /** Modify <b>fname</b> to contain the name of its parent directory. Doesn't
  1220. * actually examine the filesystem; does a purely syntactic modification.
  1221. *
  1222. * The parent of the root director is considered to be iteself.
  1223. *
  1224. * Path separators are the forward slash (/) everywhere and additionally
  1225. * the backslash (\) on Win32.
  1226. *
  1227. * Cuts off any number of trailing path separators but otherwise ignores
  1228. * them for purposes of finding the parent directory.
  1229. *
  1230. * Returns 0 if a parent directory was successfully found, -1 otherwise (fname
  1231. * did not have any path separators or only had them at the end).
  1232. * */
  1233. int
  1234. get_parent_directory(char *fname)
  1235. {
  1236. char *cp;
  1237. int at_end = 1;
  1238. tor_assert(fname);
  1239. #ifdef _WIN32
  1240. /* If we start with, say, c:, then don't consider that the start of the path
  1241. */
  1242. if (fname[0] && fname[1] == ':') {
  1243. fname += 2;
  1244. }
  1245. #endif /* defined(_WIN32) */
  1246. /* Now we want to remove all path-separators at the end of the string,
  1247. * and to remove the end of the string starting with the path separator
  1248. * before the last non-path-separator. In perl, this would be
  1249. * s#[/]*$##; s#/[^/]*$##;
  1250. * on a unixy platform.
  1251. */
  1252. cp = fname + strlen(fname);
  1253. at_end = 1;
  1254. while (--cp >= fname) {
  1255. int is_sep = (*cp == '/'
  1256. #ifdef _WIN32
  1257. || *cp == '\\'
  1258. #endif
  1259. );
  1260. if (is_sep) {
  1261. if (cp == fname) {
  1262. /* This is the first separator in the file name; don't remove it! */
  1263. cp[1] = '\0';
  1264. return 0;
  1265. }
  1266. *cp = '\0';
  1267. if (! at_end)
  1268. return 0;
  1269. } else {
  1270. at_end = 0;
  1271. }
  1272. }
  1273. return -1;
  1274. }
  1275. #ifndef _WIN32
  1276. /** Return a newly allocated string containing the output of getcwd(). Return
  1277. * NULL on failure. (We can't just use getcwd() into a PATH_MAX buffer, since
  1278. * Hurd hasn't got a PATH_MAX.)
  1279. */
  1280. static char *
  1281. alloc_getcwd(void)
  1282. {
  1283. #ifdef HAVE_GET_CURRENT_DIR_NAME
  1284. /* Glibc makes this nice and simple for us. */
  1285. char *cwd = get_current_dir_name();
  1286. char *result = NULL;
  1287. if (cwd) {
  1288. /* We make a copy here, in case tor_malloc() is not malloc(). */
  1289. result = tor_strdup(cwd);
  1290. raw_free(cwd); // alias for free to avoid tripping check-spaces.
  1291. }
  1292. return result;
  1293. #else /* !(defined(HAVE_GET_CURRENT_DIR_NAME)) */
  1294. size_t size = 1024;
  1295. char *buf = NULL;
  1296. char *ptr = NULL;
  1297. while (ptr == NULL) {
  1298. buf = tor_realloc(buf, size);
  1299. ptr = getcwd(buf, size);
  1300. if (ptr == NULL && errno != ERANGE) {
  1301. tor_free(buf);
  1302. return NULL;
  1303. }
  1304. size *= 2;
  1305. }
  1306. return buf;
  1307. #endif /* defined(HAVE_GET_CURRENT_DIR_NAME) */
  1308. }
  1309. #endif /* !defined(_WIN32) */
  1310. /** Expand possibly relative path <b>fname</b> to an absolute path.
  1311. * Return a newly allocated string, possibly equal to <b>fname</b>. */
  1312. char *
  1313. make_path_absolute(char *fname)
  1314. {
  1315. #ifdef _WIN32
  1316. char *absfname_malloced = _fullpath(NULL, fname, 1);
  1317. /* We don't want to assume that tor_free can free a string allocated
  1318. * with malloc. On failure, return fname (it's better than nothing). */
  1319. char *absfname = tor_strdup(absfname_malloced ? absfname_malloced : fname);
  1320. if (absfname_malloced) raw_free(absfname_malloced);
  1321. return absfname;
  1322. #else /* !(defined(_WIN32)) */
  1323. char *absfname = NULL, *path = NULL;
  1324. tor_assert(fname);
  1325. if (fname[0] == '/') {
  1326. absfname = tor_strdup(fname);
  1327. } else {
  1328. path = alloc_getcwd();
  1329. if (path) {
  1330. tor_asprintf(&absfname, "%s/%s", path, fname);
  1331. tor_free(path);
  1332. } else {
  1333. /* LCOV_EXCL_START Can't make getcwd fail. */
  1334. /* If getcwd failed, the best we can do here is keep using the
  1335. * relative path. (Perhaps / isn't readable by this UID/GID.) */
  1336. log_warn(LD_GENERAL, "Unable to find current working directory: %s",
  1337. strerror(errno));
  1338. absfname = tor_strdup(fname);
  1339. /* LCOV_EXCL_STOP */
  1340. }
  1341. }
  1342. return absfname;
  1343. #endif /* defined(_WIN32) */
  1344. }
  1345. #ifndef HAVE__NSGETENVIRON
  1346. #ifndef HAVE_EXTERN_ENVIRON_DECLARED
  1347. /* Some platforms declare environ under some circumstances, others don't. */
  1348. #ifndef RUNNING_DOXYGEN
  1349. extern char **environ;
  1350. #endif
  1351. #endif /* !defined(HAVE_EXTERN_ENVIRON_DECLARED) */
  1352. #endif /* !defined(HAVE__NSGETENVIRON) */
  1353. /** Return the current environment. This is a portable replacement for
  1354. * 'environ'. */
  1355. char **
  1356. get_environment(void)
  1357. {
  1358. #ifdef HAVE__NSGETENVIRON
  1359. /* This is for compatibility between OSX versions. Otherwise (for example)
  1360. * when we do a mostly-static build on OSX 10.7, the resulting binary won't
  1361. * work on OSX 10.6. */
  1362. return *_NSGetEnviron();
  1363. #else /* !(defined(HAVE__NSGETENVIRON)) */
  1364. return environ;
  1365. #endif /* defined(HAVE__NSGETENVIRON) */
  1366. }
  1367. /** Get name of current host and write it to <b>name</b> array, whose
  1368. * length is specified by <b>namelen</b> argument. Return 0 upon
  1369. * successful completion; otherwise return return -1. (Currently,
  1370. * this function is merely a mockable wrapper for POSIX gethostname().)
  1371. */
  1372. MOCK_IMPL(int,
  1373. tor_gethostname,(char *name, size_t namelen))
  1374. {
  1375. return gethostname(name,namelen);
  1376. }
  1377. /** Hold the result of our call to <b>uname</b>. */
  1378. static char uname_result[256];
  1379. /** True iff uname_result is set. */
  1380. static int uname_result_is_set = 0;
  1381. /** Return a pointer to a description of our platform.
  1382. */
  1383. MOCK_IMPL(const char *,
  1384. get_uname,(void))
  1385. {
  1386. #ifdef HAVE_UNAME
  1387. struct utsname u;
  1388. #endif
  1389. if (!uname_result_is_set) {
  1390. #ifdef HAVE_UNAME
  1391. if (uname(&u) != -1) {
  1392. /* (Linux says 0 is success, Solaris says 1 is success) */
  1393. strlcpy(uname_result, u.sysname, sizeof(uname_result));
  1394. } else
  1395. #endif /* defined(HAVE_UNAME) */
  1396. {
  1397. #ifdef _WIN32
  1398. OSVERSIONINFOEX info;
  1399. int i;
  1400. const char *plat = NULL;
  1401. static struct {
  1402. unsigned major; unsigned minor; const char *version;
  1403. } win_version_table[] = {
  1404. { 6, 2, "Windows 8" },
  1405. { 6, 1, "Windows 7" },
  1406. { 6, 0, "Windows Vista" },
  1407. { 5, 2, "Windows Server 2003" },
  1408. { 5, 1, "Windows XP" },
  1409. { 5, 0, "Windows 2000" },
  1410. /* { 4, 0, "Windows NT 4.0" }, */
  1411. { 4, 90, "Windows Me" },
  1412. { 4, 10, "Windows 98" },
  1413. /* { 4, 0, "Windows 95" } */
  1414. { 3, 51, "Windows NT 3.51" },
  1415. { 0, 0, NULL }
  1416. };
  1417. memset(&info, 0, sizeof(info));
  1418. info.dwOSVersionInfoSize = sizeof(info);
  1419. if (! GetVersionEx((LPOSVERSIONINFO)&info)) {
  1420. strlcpy(uname_result, "Bizarre version of Windows where GetVersionEx"
  1421. " doesn't work.", sizeof(uname_result));
  1422. uname_result_is_set = 1;
  1423. return uname_result;
  1424. }
  1425. if (info.dwMajorVersion == 4 && info.dwMinorVersion == 0) {
  1426. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  1427. plat = "Windows NT 4.0";
  1428. else
  1429. plat = "Windows 95";
  1430. } else {
  1431. for (i=0; win_version_table[i].major>0; ++i) {
  1432. if (win_version_table[i].major == info.dwMajorVersion &&
  1433. win_version_table[i].minor == info.dwMinorVersion) {
  1434. plat = win_version_table[i].version;
  1435. break;
  1436. }
  1437. }
  1438. }
  1439. if (plat) {
  1440. strlcpy(uname_result, plat, sizeof(uname_result));
  1441. } else {
  1442. if (info.dwMajorVersion > 6 ||
  1443. (info.dwMajorVersion==6 && info.dwMinorVersion>2))
  1444. tor_snprintf(uname_result, sizeof(uname_result),
  1445. "Very recent version of Windows [major=%d,minor=%d]",
  1446. (int)info.dwMajorVersion,(int)info.dwMinorVersion);
  1447. else
  1448. tor_snprintf(uname_result, sizeof(uname_result),
  1449. "Unrecognized version of Windows [major=%d,minor=%d]",
  1450. (int)info.dwMajorVersion,(int)info.dwMinorVersion);
  1451. }
  1452. #ifdef VER_NT_SERVER
  1453. if (info.wProductType == VER_NT_SERVER ||
  1454. info.wProductType == VER_NT_DOMAIN_CONTROLLER) {
  1455. strlcat(uname_result, " [server]", sizeof(uname_result));
  1456. }
  1457. #endif /* defined(VER_NT_SERVER) */
  1458. #else /* !(defined(_WIN32)) */
  1459. /* LCOV_EXCL_START -- can't provoke uname failure */
  1460. strlcpy(uname_result, "Unknown platform", sizeof(uname_result));
  1461. /* LCOV_EXCL_STOP */
  1462. #endif /* defined(_WIN32) */
  1463. }
  1464. uname_result_is_set = 1;
  1465. }
  1466. return uname_result;
  1467. }
  1468. /*
  1469. * Process control
  1470. */
  1471. /** Implementation logic for compute_num_cpus(). */
  1472. static int
  1473. compute_num_cpus_impl(void)
  1474. {
  1475. #ifdef _WIN32
  1476. SYSTEM_INFO info;
  1477. memset(&info, 0, sizeof(info));
  1478. GetSystemInfo(&info);
  1479. if (info.dwNumberOfProcessors >= 1 && info.dwNumberOfProcessors < INT_MAX)
  1480. return (int)info.dwNumberOfProcessors;
  1481. else
  1482. return -1;
  1483. #elif defined(HAVE_SYSCONF)
  1484. #ifdef _SC_NPROCESSORS_CONF
  1485. long cpus_conf = sysconf(_SC_NPROCESSORS_CONF);
  1486. #else
  1487. long cpus_conf = -1;
  1488. #endif
  1489. #ifdef _SC_NPROCESSORS_ONLN
  1490. long cpus_onln = sysconf(_SC_NPROCESSORS_ONLN);
  1491. #else
  1492. long cpus_onln = -1;
  1493. #endif
  1494. long cpus = -1;
  1495. if (cpus_conf > 0 && cpus_onln < 0) {
  1496. cpus = cpus_conf;
  1497. } else if (cpus_onln > 0 && cpus_conf < 0) {
  1498. cpus = cpus_onln;
  1499. } else if (cpus_onln > 0 && cpus_conf > 0) {
  1500. if (cpus_onln < cpus_conf) {
  1501. log_notice(LD_GENERAL, "I think we have %ld CPUS, but only %ld of them "
  1502. "are available. Telling Tor to only use %ld. You can over"
  1503. "ride this with the NumCPUs option",
  1504. cpus_conf, cpus_onln, cpus_onln);
  1505. }
  1506. cpus = cpus_onln;
  1507. }
  1508. if (cpus >= 1 && cpus < INT_MAX)
  1509. return (int)cpus;
  1510. else
  1511. return -1;
  1512. #else
  1513. return -1;
  1514. #endif /* defined(_WIN32) || ... */
  1515. }
  1516. #define MAX_DETECTABLE_CPUS 16
  1517. /** Return how many CPUs we are running with. We assume that nobody is
  1518. * using hot-swappable CPUs, so we don't recompute this after the first
  1519. * time. Return -1 if we don't know how to tell the number of CPUs on this
  1520. * system.
  1521. */
  1522. int
  1523. compute_num_cpus(void)
  1524. {
  1525. static int num_cpus = -2;
  1526. if (num_cpus == -2) {
  1527. num_cpus = compute_num_cpus_impl();
  1528. tor_assert(num_cpus != -2);
  1529. if (num_cpus > MAX_DETECTABLE_CPUS) {
  1530. /* LCOV_EXCL_START */
  1531. log_notice(LD_GENERAL, "Wow! I detected that you have %d CPUs. I "
  1532. "will not autodetect any more than %d, though. If you "
  1533. "want to configure more, set NumCPUs in your torrc",
  1534. num_cpus, MAX_DETECTABLE_CPUS);
  1535. num_cpus = MAX_DETECTABLE_CPUS;
  1536. /* LCOV_EXCL_STOP */
  1537. }
  1538. }
  1539. return num_cpus;
  1540. }
  1541. /** As localtime_r, but defined for platforms that don't have it:
  1542. *
  1543. * Convert *<b>timep</b> to a struct tm in local time, and store the value in
  1544. * *<b>result</b>. Return the result on success, or NULL on failure.
  1545. */
  1546. struct tm *
  1547. tor_localtime_r(const time_t *timep, struct tm *result)
  1548. {
  1549. char *err = NULL;
  1550. struct tm *r = tor_localtime_r_msg(timep, result, &err);
  1551. if (err) {
  1552. log_warn(LD_BUG, "%s", err);
  1553. tor_free(err);
  1554. }
  1555. return r;
  1556. }
  1557. /** As gmtime_r, but defined for platforms that don't have it:
  1558. *
  1559. * Convert *<b>timep</b> to a struct tm in UTC, and store the value in
  1560. * *<b>result</b>. Return the result on success, or NULL on failure.
  1561. */
  1562. struct tm *
  1563. tor_gmtime_r(const time_t *timep, struct tm *result)
  1564. {
  1565. char *err = NULL;
  1566. struct tm *r = tor_gmtime_r_msg(timep, result, &err);
  1567. if (err) {
  1568. log_warn(LD_BUG, "%s", err);
  1569. tor_free(err);
  1570. }
  1571. return r;
  1572. }
  1573. #if defined(HAVE_MLOCKALL) && HAVE_DECL_MLOCKALL && defined(RLIMIT_MEMLOCK)
  1574. #define HAVE_UNIX_MLOCKALL
  1575. #endif
  1576. #ifdef HAVE_UNIX_MLOCKALL
  1577. /** Attempt to raise the current and max rlimit to infinity for our process.
  1578. * This only needs to be done once and can probably only be done when we have
  1579. * not already dropped privileges.
  1580. */
  1581. static int
  1582. tor_set_max_memlock(void)
  1583. {
  1584. /* Future consideration for Windows is probably SetProcessWorkingSetSize
  1585. * This is similar to setting the memory rlimit of RLIMIT_MEMLOCK
  1586. * http://msdn.microsoft.com/en-us/library/ms686234(VS.85).aspx
  1587. */
  1588. struct rlimit limit;
  1589. /* RLIM_INFINITY is -1 on some platforms. */
  1590. limit.rlim_cur = RLIM_INFINITY;
  1591. limit.rlim_max = RLIM_INFINITY;
  1592. if (setrlimit(RLIMIT_MEMLOCK, &limit) == -1) {
  1593. if (errno == EPERM) {
  1594. log_warn(LD_GENERAL, "You appear to lack permissions to change memory "
  1595. "limits. Are you root?");
  1596. }
  1597. log_warn(LD_GENERAL, "Unable to raise RLIMIT_MEMLOCK: %s",
  1598. strerror(errno));
  1599. return -1;
  1600. }
  1601. return 0;
  1602. }
  1603. #endif /* defined(HAVE_UNIX_MLOCKALL) */
  1604. /** Attempt to lock all current and all future memory pages.
  1605. * This should only be called once and while we're privileged.
  1606. * Like mlockall() we return 0 when we're successful and -1 when we're not.
  1607. * Unlike mlockall() we return 1 if we've already attempted to lock memory.
  1608. */
  1609. int
  1610. tor_mlockall(void)
  1611. {
  1612. static int memory_lock_attempted = 0;
  1613. if (memory_lock_attempted) {
  1614. return 1;
  1615. }
  1616. memory_lock_attempted = 1;
  1617. /*
  1618. * Future consideration for Windows may be VirtualLock
  1619. * VirtualLock appears to implement mlock() but not mlockall()
  1620. *
  1621. * http://msdn.microsoft.com/en-us/library/aa366895(VS.85).aspx
  1622. */
  1623. #ifdef HAVE_UNIX_MLOCKALL
  1624. if (tor_set_max_memlock() == 0) {
  1625. log_debug(LD_GENERAL, "RLIMIT_MEMLOCK is now set to RLIM_INFINITY.");
  1626. }
  1627. if (mlockall(MCL_CURRENT|MCL_FUTURE) == 0) {
  1628. log_info(LD_GENERAL, "Insecure OS paging is effectively disabled.");
  1629. return 0;
  1630. } else {
  1631. if (errno == ENOSYS) {
  1632. /* Apple - it's 2009! I'm looking at you. Grrr. */
  1633. log_notice(LD_GENERAL, "It appears that mlockall() is not available on "
  1634. "your platform.");
  1635. } else if (errno == EPERM) {
  1636. log_notice(LD_GENERAL, "It appears that you lack the permissions to "
  1637. "lock memory. Are you root?");
  1638. }
  1639. log_notice(LD_GENERAL, "Unable to lock all current and future memory "
  1640. "pages: %s", strerror(errno));
  1641. return -1;
  1642. }
  1643. #else /* !(defined(HAVE_UNIX_MLOCKALL)) */
  1644. log_warn(LD_GENERAL, "Unable to lock memory pages. mlockall() unsupported?");
  1645. return -1;
  1646. #endif /* defined(HAVE_UNIX_MLOCKALL) */
  1647. }
  1648. /**
  1649. * On Windows, WSAEWOULDBLOCK is not always correct: when you see it,
  1650. * you need to ask the socket for its actual errno. Also, you need to
  1651. * get your errors from WSAGetLastError, not errno. (If you supply a
  1652. * socket of -1, we check WSAGetLastError, but don't correct
  1653. * WSAEWOULDBLOCKs.)
  1654. *
  1655. * The upshot of all of this is that when a socket call fails, you
  1656. * should call tor_socket_errno <em>at most once</em> on the failing
  1657. * socket to get the error.
  1658. */
  1659. #if defined(_WIN32)
  1660. int
  1661. tor_socket_errno(tor_socket_t sock)
  1662. {
  1663. int optval, optvallen=sizeof(optval);
  1664. int err = WSAGetLastError();
  1665. if (err == WSAEWOULDBLOCK && SOCKET_OK(sock)) {
  1666. if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval, &optvallen))
  1667. return err;
  1668. if (optval)
  1669. return optval;
  1670. }
  1671. return err;
  1672. }
  1673. #endif /* defined(_WIN32) */
  1674. #if defined(_WIN32)
  1675. #define E(code, s) { code, (s " [" #code " ]") }
  1676. struct { int code; const char *msg; } windows_socket_errors[] = {
  1677. E(WSAEINTR, "Interrupted function call"),
  1678. E(WSAEACCES, "Permission denied"),
  1679. E(WSAEFAULT, "Bad address"),
  1680. E(WSAEINVAL, "Invalid argument"),
  1681. E(WSAEMFILE, "Too many open files"),
  1682. E(WSAEWOULDBLOCK, "Resource temporarily unavailable"),
  1683. E(WSAEINPROGRESS, "Operation now in progress"),
  1684. E(WSAEALREADY, "Operation already in progress"),
  1685. E(WSAENOTSOCK, "Socket operation on nonsocket"),
  1686. E(WSAEDESTADDRREQ, "Destination address required"),
  1687. E(WSAEMSGSIZE, "Message too long"),
  1688. E(WSAEPROTOTYPE, "Protocol wrong for socket"),
  1689. E(WSAENOPROTOOPT, "Bad protocol option"),
  1690. E(WSAEPROTONOSUPPORT, "Protocol not supported"),
  1691. E(WSAESOCKTNOSUPPORT, "Socket type not supported"),
  1692. /* What's the difference between NOTSUPP and NOSUPPORT? :) */
  1693. E(WSAEOPNOTSUPP, "Operation not supported"),
  1694. E(WSAEPFNOSUPPORT, "Protocol family not supported"),
  1695. E(WSAEAFNOSUPPORT, "Address family not supported by protocol family"),
  1696. E(WSAEADDRINUSE, "Address already in use"),
  1697. E(WSAEADDRNOTAVAIL, "Cannot assign requested address"),
  1698. E(WSAENETDOWN, "Network is down"),
  1699. E(WSAENETUNREACH, "Network is unreachable"),
  1700. E(WSAENETRESET, "Network dropped connection on reset"),
  1701. E(WSAECONNABORTED, "Software caused connection abort"),
  1702. E(WSAECONNRESET, "Connection reset by peer"),
  1703. E(WSAENOBUFS, "No buffer space available"),
  1704. E(WSAEISCONN, "Socket is already connected"),
  1705. E(WSAENOTCONN, "Socket is not connected"),
  1706. E(WSAESHUTDOWN, "Cannot send after socket shutdown"),
  1707. E(WSAETIMEDOUT, "Connection timed out"),
  1708. E(WSAECONNREFUSED, "Connection refused"),
  1709. E(WSAEHOSTDOWN, "Host is down"),
  1710. E(WSAEHOSTUNREACH, "No route to host"),
  1711. E(WSAEPROCLIM, "Too many processes"),
  1712. /* Yes, some of these start with WSA, not WSAE. No, I don't know why. */
  1713. E(WSASYSNOTREADY, "Network subsystem is unavailable"),
  1714. E(WSAVERNOTSUPPORTED, "Winsock.dll out of range"),
  1715. E(WSANOTINITIALISED, "Successful WSAStartup not yet performed"),
  1716. E(WSAEDISCON, "Graceful shutdown now in progress"),
  1717. #ifdef WSATYPE_NOT_FOUND
  1718. E(WSATYPE_NOT_FOUND, "Class type not found"),
  1719. #endif
  1720. E(WSAHOST_NOT_FOUND, "Host not found"),
  1721. E(WSATRY_AGAIN, "Nonauthoritative host not found"),
  1722. E(WSANO_RECOVERY, "This is a nonrecoverable error"),
  1723. E(WSANO_DATA, "Valid name, no data record of requested type)"),
  1724. /* There are some more error codes whose numeric values are marked
  1725. * <b>OS dependent</b>. They start with WSA_, apparently for the same
  1726. * reason that practitioners of some craft traditions deliberately
  1727. * introduce imperfections into their baskets and rugs "to allow the
  1728. * evil spirits to escape." If we catch them, then our binaries
  1729. * might not report consistent results across versions of Windows.
  1730. * Thus, I'm going to let them all fall through.
  1731. */
  1732. { -1, NULL },
  1733. };
  1734. /** There does not seem to be a strerror equivalent for Winsock errors.
  1735. * Naturally, we have to roll our own.
  1736. */
  1737. const char *
  1738. tor_socket_strerror(int e)
  1739. {
  1740. int i;
  1741. for (i=0; windows_socket_errors[i].code >= 0; ++i) {
  1742. if (e == windows_socket_errors[i].code)
  1743. return windows_socket_errors[i].msg;
  1744. }
  1745. return strerror(e);
  1746. }
  1747. #endif /* defined(_WIN32) */
  1748. /** Called before we make any calls to network-related functions.
  1749. * (Some operating systems require their network libraries to be
  1750. * initialized.) */
  1751. int
  1752. network_init(void)
  1753. {
  1754. #ifdef _WIN32
  1755. /* This silly exercise is necessary before windows will allow
  1756. * gethostbyname to work. */
  1757. WSADATA WSAData;
  1758. int r;
  1759. r = WSAStartup(0x101,&WSAData);
  1760. if (r) {
  1761. log_warn(LD_NET,"Error initializing windows network layer: code was %d",r);
  1762. return -1;
  1763. }
  1764. if (sizeof(SOCKET) != sizeof(tor_socket_t)) {
  1765. log_warn(LD_BUG,"The tor_socket_t type does not match SOCKET in size; Tor "
  1766. "might not work. (Sizes are %d and %d respectively.)",
  1767. (int)sizeof(tor_socket_t), (int)sizeof(SOCKET));
  1768. }
  1769. /* WSAData.iMaxSockets might show the max sockets we're allowed to use.
  1770. * We might use it to complain if we're trying to be a server but have
  1771. * too few sockets available. */
  1772. #endif /* defined(_WIN32) */
  1773. return 0;
  1774. }
  1775. #ifdef _WIN32
  1776. /** Return a newly allocated string describing the windows system error code
  1777. * <b>err</b>. Note that error codes are different from errno. Error codes
  1778. * come from GetLastError() when a winapi call fails. errno is set only when
  1779. * ANSI functions fail. Whee. */
  1780. char *
  1781. format_win32_error(DWORD err)
  1782. {
  1783. TCHAR *str = NULL;
  1784. char *result;
  1785. DWORD n;
  1786. /* Somebody once decided that this interface was better than strerror(). */
  1787. n = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  1788. FORMAT_MESSAGE_FROM_SYSTEM |
  1789. FORMAT_MESSAGE_IGNORE_INSERTS,
  1790. NULL, err,
  1791. MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT),
  1792. (LPVOID)&str,
  1793. 0, NULL);
  1794. if (str && n) {
  1795. #ifdef UNICODE
  1796. size_t len;
  1797. if (n > 128*1024)
  1798. len = (128 * 1024) * 2 + 1; /* This shouldn't be possible, but let's
  1799. * make sure. */
  1800. else
  1801. len = n * 2 + 1;
  1802. result = tor_malloc(len);
  1803. wcstombs(result,str,len);
  1804. result[len-1] = '\0';
  1805. #else /* !(defined(UNICODE)) */
  1806. result = tor_strdup(str);
  1807. #endif /* defined(UNICODE) */
  1808. } else {
  1809. result = tor_strdup("<unformattable error>");
  1810. }
  1811. if (str) {
  1812. LocalFree(str); /* LocalFree != free() */
  1813. }
  1814. return result;
  1815. }
  1816. #endif /* defined(_WIN32) */
  1817. #if defined(HW_PHYSMEM64)
  1818. /* This appears to be an OpenBSD thing */
  1819. #define INT64_HW_MEM HW_PHYSMEM64
  1820. #elif defined(HW_MEMSIZE)
  1821. /* OSX defines this one */
  1822. #define INT64_HW_MEM HW_MEMSIZE
  1823. #endif /* defined(HW_PHYSMEM64) || ... */
  1824. /**
  1825. * Helper: try to detect the total system memory, and return it. On failure,
  1826. * return 0.
  1827. */
  1828. static uint64_t
  1829. get_total_system_memory_impl(void)
  1830. {
  1831. #if defined(__linux__)
  1832. /* On linux, sysctl is deprecated. Because proc is so awesome that you
  1833. * shouldn't _want_ to write portable code, I guess? */
  1834. unsigned long long result=0;
  1835. int fd = -1;
  1836. char *s = NULL;
  1837. const char *cp;
  1838. size_t file_size=0;
  1839. if (-1 == (fd = tor_open_cloexec("/proc/meminfo",O_RDONLY,0)))
  1840. return 0;
  1841. s = read_file_to_str_until_eof(fd, 65536, &file_size);
  1842. if (!s)
  1843. goto err;
  1844. cp = strstr(s, "MemTotal:");
  1845. if (!cp)
  1846. goto err;
  1847. /* Use the system sscanf so that space will match a wider number of space */
  1848. if (sscanf(cp, "MemTotal: %llu kB\n", &result) != 1)
  1849. goto err;
  1850. close(fd);
  1851. tor_free(s);
  1852. return result * 1024;
  1853. /* LCOV_EXCL_START Can't reach this unless proc is broken. */
  1854. err:
  1855. tor_free(s);
  1856. close(fd);
  1857. return 0;
  1858. /* LCOV_EXCL_STOP */
  1859. #elif defined (_WIN32)
  1860. /* Windows has MEMORYSTATUSEX; pretty straightforward. */
  1861. MEMORYSTATUSEX ms;
  1862. memset(&ms, 0, sizeof(ms));
  1863. ms.dwLength = sizeof(ms);
  1864. if (! GlobalMemoryStatusEx(&ms))
  1865. return 0;
  1866. return ms.ullTotalPhys;
  1867. #elif defined(HAVE_SYSCTL) && defined(INT64_HW_MEM)
  1868. /* On many systems, HW_PYHSMEM is clipped to 32 bits; let's use a better
  1869. * variant if we know about it. */
  1870. uint64_t memsize = 0;
  1871. size_t len = sizeof(memsize);
  1872. int mib[2] = {CTL_HW, INT64_HW_MEM};
  1873. if (sysctl(mib,2,&memsize,&len,NULL,0))
  1874. return 0;
  1875. return memsize;
  1876. #elif defined(HAVE_SYSCTL) && defined(HW_PHYSMEM)
  1877. /* On some systems (like FreeBSD I hope) you can use a size_t with
  1878. * HW_PHYSMEM. */
  1879. size_t memsize=0;
  1880. size_t len = sizeof(memsize);
  1881. int mib[2] = {CTL_HW, HW_USERMEM};
  1882. if (sysctl(mib,2,&memsize,&len,NULL,0))
  1883. return 0;
  1884. return memsize;
  1885. #else
  1886. /* I have no clue. */
  1887. return 0;
  1888. #endif /* defined(__linux__) || ... */
  1889. }
  1890. /**
  1891. * Try to find out how much physical memory the system has. On success,
  1892. * return 0 and set *<b>mem_out</b> to that value. On failure, return -1.
  1893. */
  1894. MOCK_IMPL(int,
  1895. get_total_system_memory, (size_t *mem_out))
  1896. {
  1897. static size_t mem_cached=0;
  1898. uint64_t m = get_total_system_memory_impl();
  1899. if (0 == m) {
  1900. /* LCOV_EXCL_START -- can't make this happen without mocking. */
  1901. /* We couldn't find our memory total */
  1902. if (0 == mem_cached) {
  1903. /* We have no cached value either */
  1904. *mem_out = 0;
  1905. return -1;
  1906. }
  1907. *mem_out = mem_cached;
  1908. return 0;
  1909. /* LCOV_EXCL_STOP */
  1910. }
  1911. #if SIZE_MAX != UINT64_MAX
  1912. if (m > SIZE_MAX) {
  1913. /* I think this could happen if we're a 32-bit Tor running on a 64-bit
  1914. * system: we could have more system memory than would fit in a
  1915. * size_t. */
  1916. m = SIZE_MAX;
  1917. }
  1918. #endif /* SIZE_MAX != UINT64_MAX */
  1919. *mem_out = mem_cached = (size_t) m;
  1920. return 0;
  1921. }
  1922. /** Emit the password prompt <b>prompt</b>, then read up to <b>buflen</b>
  1923. * bytes of passphrase into <b>output</b>. Return the number of bytes in
  1924. * the passphrase, excluding terminating NUL.
  1925. */
  1926. ssize_t
  1927. tor_getpass(const char *prompt, char *output, size_t buflen)
  1928. {
  1929. tor_assert(buflen <= SSIZE_MAX);
  1930. tor_assert(buflen >= 1);
  1931. #if defined(HAVE_READPASSPHRASE)
  1932. char *pwd = readpassphrase(prompt, output, buflen, RPP_ECHO_OFF);
  1933. if (pwd == NULL)
  1934. return -1;
  1935. return strlen(pwd);
  1936. #elif defined(_WIN32)
  1937. int r = -1;
  1938. while (*prompt) {
  1939. _putch(*prompt++);
  1940. }
  1941. tor_assert(buflen <= INT_MAX);
  1942. wchar_t *buf = tor_calloc(buflen, sizeof(wchar_t));
  1943. wchar_t *ptr = buf, *lastch = buf + buflen - 1;
  1944. while (ptr < lastch) {
  1945. wint_t ch = _getwch();
  1946. switch (ch) {
  1947. case '\r':
  1948. case '\n':
  1949. case WEOF:
  1950. goto done_reading;
  1951. case 3:
  1952. goto done; /* Can't actually read ctrl-c this way. */
  1953. case '\b':
  1954. if (ptr > buf)
  1955. --ptr;
  1956. continue;
  1957. case 0:
  1958. case 0xe0:
  1959. ch = _getwch(); /* Ignore; this is a function or arrow key */
  1960. break;
  1961. default:
  1962. *ptr++ = ch;
  1963. break;
  1964. }
  1965. }
  1966. done_reading:
  1967. ;
  1968. #ifndef WC_ERR_INVALID_CHARS
  1969. #define WC_ERR_INVALID_CHARS 0x80
  1970. #endif
  1971. /* Now convert it to UTF-8 */
  1972. r = WideCharToMultiByte(CP_UTF8,
  1973. WC_NO_BEST_FIT_CHARS|WC_ERR_INVALID_CHARS,
  1974. buf, (int)(ptr-buf),
  1975. output, (int)(buflen-1),
  1976. NULL, NULL);
  1977. if (r <= 0) {
  1978. r = -1;
  1979. goto done;
  1980. }
  1981. tor_assert(r < (int)buflen);
  1982. output[r] = 0;
  1983. done:
  1984. SecureZeroMemory(buf, sizeof(wchar_t)*buflen);
  1985. tor_free(buf);
  1986. return r;
  1987. #else
  1988. #error "No implementation for tor_getpass found!"
  1989. #endif /* defined(HAVE_READPASSPHRASE) || ... */
  1990. }
  1991. /** Return the amount of free disk space we have permission to use, in
  1992. * bytes. Return -1 if the amount of free space can't be determined. */
  1993. int64_t
  1994. tor_get_avail_disk_space(const char *path)
  1995. {
  1996. #ifdef HAVE_STATVFS
  1997. struct statvfs st;
  1998. int r;
  1999. memset(&st, 0, sizeof(st));
  2000. r = statvfs(path, &st);
  2001. if (r < 0)
  2002. return -1;
  2003. int64_t result = st.f_bavail;
  2004. if (st.f_frsize) {
  2005. result *= st.f_frsize;
  2006. } else if (st.f_bsize) {
  2007. result *= st.f_bsize;
  2008. } else {
  2009. return -1;
  2010. }
  2011. return result;
  2012. #elif defined(_WIN32)
  2013. ULARGE_INTEGER freeBytesAvail;
  2014. BOOL ok;
  2015. ok = GetDiskFreeSpaceEx(path, &freeBytesAvail, NULL, NULL);
  2016. if (!ok) {
  2017. return -1;
  2018. }
  2019. return (int64_t)freeBytesAvail.QuadPart;
  2020. #else
  2021. (void)path;
  2022. errno = ENOSYS;
  2023. return -1;
  2024. #endif /* defined(HAVE_STATVFS) || ... */
  2025. }