compat.c 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218
  1. /* Copyright (c) 2003-2004, Roger Dingledine
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2008, 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_malloc, 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. /* This is required on rh7 to make strptime not complain.
  14. * We also need it to make memmem get defined (where available)
  15. */
  16. #define _GNU_SOURCE
  17. #include "compat.h"
  18. #ifdef MS_WINDOWS
  19. #include <process.h>
  20. #include <windows.h>
  21. #include <sys/locking.h>
  22. #endif
  23. #ifdef HAVE_UNAME
  24. #include <sys/utsname.h>
  25. #endif
  26. #ifdef HAVE_UNISTD_H
  27. #include <unistd.h>
  28. #endif
  29. #ifdef HAVE_SYS_FCNTL_H
  30. #include <sys/fcntl.h>
  31. #endif
  32. #ifdef HAVE_PWD_H
  33. #include <pwd.h>
  34. #endif
  35. #ifdef HAVE_GRP_H
  36. #include <grp.h>
  37. #endif
  38. #ifdef HAVE_FCNTL_H
  39. #include <fcntl.h>
  40. #endif
  41. #ifdef HAVE_ERRNO_H
  42. #include <errno.h>
  43. #endif
  44. #ifdef HAVE_ARPA_INET_H
  45. #include <arpa/inet.h>
  46. #endif
  47. #ifndef HAVE_GETTIMEOFDAY
  48. #ifdef HAVE_FTIME
  49. #include <sys/timeb.h>
  50. #endif
  51. #endif
  52. #ifdef HAVE_NETDB_H
  53. #include <netdb.h>
  54. #endif
  55. #ifdef HAVE_SYS_PARAM_H
  56. #include <sys/param.h> /* FreeBSD needs this to know what version it is */
  57. #endif
  58. #include <stdio.h>
  59. #include <stdlib.h>
  60. #include <assert.h>
  61. #ifdef HAVE_SIGNAL_H
  62. #include <signal.h>
  63. #endif
  64. #ifdef HAVE_UTIME_H
  65. #include <utime.h>
  66. #endif
  67. #ifdef HAVE_SYS_UTIME_H
  68. #include <sys/utime.h>
  69. #endif
  70. #ifdef HAVE_SYS_MMAN_H
  71. #include <sys/mman.h>
  72. #endif
  73. #ifdef HAVE_SYS_SYSLIMITS_H
  74. #include <sys/syslimits.h>
  75. #endif
  76. #ifdef HAVE_SYS_FILE_H
  77. #include <sys/file.h>
  78. #endif
  79. #include "log.h"
  80. #include "util.h"
  81. #include "container.h"
  82. #include "address.h"
  83. /* Inline the strl functions if the platform doesn't have them. */
  84. #ifndef HAVE_STRLCPY
  85. #include "strlcpy.c"
  86. #endif
  87. #ifndef HAVE_STRLCAT
  88. #include "strlcat.c"
  89. #endif
  90. #ifndef INADDR_NONE
  91. /* This is used by inet_addr, but apparently Solaris doesn't define it
  92. * anyplace. */
  93. #define INADDR_NONE ((unsigned long) -1)
  94. #endif
  95. #ifdef HAVE_SYS_MMAN_H
  96. /** Try to create a memory mapping for <b>filename</b> and return it. On
  97. * failure, return NULL. Sets errno properly, using ERANGE to mean
  98. * "empty file". */
  99. tor_mmap_t *
  100. tor_mmap_file(const char *filename)
  101. {
  102. int fd; /* router file */
  103. char *string;
  104. int page_size;
  105. tor_mmap_t *res;
  106. size_t size, filesize;
  107. tor_assert(filename);
  108. fd = open(filename, O_RDONLY, 0);
  109. if (fd<0) {
  110. int save_errno = errno;
  111. int severity = (errno == ENOENT) ? LOG_INFO : LOG_WARN;
  112. log_fn(severity, LD_FS,"Could not open \"%s\" for mmap(): %s",filename,
  113. strerror(errno));
  114. errno = save_errno;
  115. return NULL;
  116. }
  117. size = filesize = (size_t) lseek(fd, 0, SEEK_END);
  118. lseek(fd, 0, SEEK_SET);
  119. /* ensure page alignment */
  120. page_size = getpagesize();
  121. size += (size%page_size) ? page_size-(size%page_size) : 0;
  122. if (!size) {
  123. /* Zero-length file. If we call mmap on it, it will succeed but
  124. * return NULL, and bad things will happen. So just fail. */
  125. log_info(LD_FS,"File \"%s\" is empty. Ignoring.",filename);
  126. errno = ERANGE;
  127. close(fd);
  128. return NULL;
  129. }
  130. string = mmap(0, size, PROT_READ, MAP_PRIVATE, fd, 0);
  131. close(fd);
  132. if (string == MAP_FAILED) {
  133. int save_errno = errno;
  134. log_warn(LD_FS,"Could not mmap file \"%s\": %s", filename,
  135. strerror(errno));
  136. errno = save_errno;
  137. return NULL;
  138. }
  139. res = tor_malloc_zero(sizeof(tor_mmap_t));
  140. res->data = string;
  141. res->size = filesize;
  142. res->mapping_size = size;
  143. return res;
  144. }
  145. /** Release storage held for a memory mapping. */
  146. void
  147. tor_munmap_file(tor_mmap_t *handle)
  148. {
  149. munmap((char*)handle->data, handle->mapping_size);
  150. tor_free(handle);
  151. }
  152. #elif defined(MS_WINDOWS)
  153. tor_mmap_t *
  154. tor_mmap_file(const char *filename)
  155. {
  156. tor_mmap_t *res = tor_malloc_zero(sizeof(tor_mmap_t));
  157. int empty = 0;
  158. res->file_handle = INVALID_HANDLE_VALUE;
  159. res->mmap_handle = NULL;
  160. res->file_handle = CreateFile(filename,
  161. GENERIC_READ, FILE_SHARE_READ,
  162. NULL,
  163. OPEN_EXISTING,
  164. FILE_ATTRIBUTE_NORMAL,
  165. 0);
  166. if (res->file_handle == INVALID_HANDLE_VALUE)
  167. goto win_err;
  168. res->size = GetFileSize(res->file_handle, NULL);
  169. if (res->size == 0) {
  170. log_info(LD_FS,"File \"%s\" is empty. Ignoring.",filename);
  171. empty = 1;
  172. goto err;
  173. }
  174. res->mmap_handle = CreateFileMapping(res->file_handle,
  175. NULL,
  176. PAGE_READONLY,
  177. #if SIZEOF_SIZE_T > 4
  178. (res->base.size >> 32),
  179. #else
  180. 0,
  181. #endif
  182. (res->size & 0xfffffffful),
  183. NULL);
  184. if (res->mmap_handle == NULL)
  185. goto win_err;
  186. res->data = (char*) MapViewOfFile(res->mmap_handle,
  187. FILE_MAP_READ,
  188. 0, 0, 0);
  189. if (!res->data)
  190. goto win_err;
  191. return res;
  192. win_err: {
  193. DWORD e = GetLastError();
  194. int severity = (e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND) ?
  195. LOG_INFO : LOG_WARN;
  196. char *msg = format_win32_error(e);
  197. log_fn(severity, LD_FS, "Couldn't mmap file \"%s\": %s", filename, msg);
  198. tor_free(msg);
  199. if (e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND)
  200. errno = ENOENT;
  201. else
  202. errno = EINVAL;
  203. }
  204. err:
  205. if (empty)
  206. errno = ERANGE;
  207. tor_munmap_file(res);
  208. return NULL;
  209. }
  210. void
  211. tor_munmap_file(tor_mmap_t *handle)
  212. {
  213. if (handle->data)
  214. /* This is an ugly cast, but without it, "data" in struct tor_mmap_t would
  215. have to be redefined as non-const. */
  216. UnmapViewOfFile( (LPVOID) handle->data);
  217. if (handle->mmap_handle != NULL)
  218. CloseHandle(handle->mmap_handle);
  219. if (handle->file_handle != INVALID_HANDLE_VALUE)
  220. CloseHandle(handle->file_handle);
  221. tor_free(handle);
  222. }
  223. #else
  224. tor_mmap_t *
  225. tor_mmap_file(const char *filename)
  226. {
  227. struct stat st;
  228. char *res = read_file_to_str(filename, RFTS_BIN|RFTS_IGNORE_MISSING, &st);
  229. tor_mmap_t *handle;
  230. if (! res)
  231. return NULL;
  232. handle = tor_malloc_zero(sizeof(tor_mmap_t));
  233. handle->data = res;
  234. handle->size = st.st_size;
  235. return handle;
  236. }
  237. void
  238. tor_munmap_file(tor_mmap_t *handle)
  239. {
  240. char *d = (char*)handle->data;
  241. tor_free(d);
  242. memset(handle, 0, sizeof(tor_mmap_t));
  243. tor_free(handle);
  244. }
  245. #endif
  246. /** Replacement for snprintf. Differs from platform snprintf in two
  247. * ways: First, always NUL-terminates its output. Second, always
  248. * returns -1 if the result is truncated. (Note that this return
  249. * behavior does <i>not</i> conform to C99; it just happens to be
  250. * easier to emulate "return -1" with conformant implementations than
  251. * it is to emulate "return number that would be written" with
  252. * non-conformant implementations.) */
  253. int
  254. tor_snprintf(char *str, size_t size, const char *format, ...)
  255. {
  256. va_list ap;
  257. int r;
  258. va_start(ap,format);
  259. r = tor_vsnprintf(str,size,format,ap);
  260. va_end(ap);
  261. return r;
  262. }
  263. /** Replacement for vsnprintf; behavior differs as tor_snprintf differs from
  264. * snprintf.
  265. */
  266. int
  267. tor_vsnprintf(char *str, size_t size, const char *format, va_list args)
  268. {
  269. int r;
  270. if (size == 0)
  271. return -1; /* no place for the NUL */
  272. if (size > SSIZE_T_MAX-16)
  273. return -1;
  274. #ifdef MS_WINDOWS
  275. r = _vsnprintf(str, size, format, args);
  276. #else
  277. r = vsnprintf(str, size, format, args);
  278. #endif
  279. str[size-1] = '\0';
  280. if (r < 0 || r >= (ssize_t)size)
  281. return -1;
  282. return r;
  283. }
  284. /** Given <b>hlen</b> bytes at <b>haystack</b> and <b>nlen</b> bytes at
  285. * <b>needle</b>, return a pointer to the first occurrence of the needle
  286. * within the haystack, or NULL if there is no such occurrence.
  287. *
  288. * Requires that nlen be greater than zero.
  289. */
  290. const void *
  291. tor_memmem(const void *_haystack, size_t hlen,
  292. const void *_needle, size_t nlen)
  293. {
  294. #if defined(HAVE_MEMMEM) && (!defined(__GNUC__) || __GNUC__ >= 2)
  295. tor_assert(nlen);
  296. return memmem(_haystack, hlen, _needle, nlen);
  297. #else
  298. /* This isn't as fast as the GLIBC implementation, but it doesn't need to
  299. * be. */
  300. const char *p, *end;
  301. const char *haystack = (const char*)_haystack;
  302. const char *needle = (const char*)_needle;
  303. char first;
  304. tor_assert(nlen);
  305. p = haystack;
  306. end = haystack + hlen;
  307. first = *(const char*)needle;
  308. while ((p = memchr(p, first, end-p))) {
  309. if (p+nlen > end)
  310. return NULL;
  311. if (!memcmp(p, needle, nlen))
  312. return p;
  313. ++p;
  314. }
  315. return NULL;
  316. #endif
  317. }
  318. #ifdef MS_WINDOWS
  319. /** Take a filename and return a pointer to its final element. This
  320. * function is called on __FILE__ to fix a MSVC nit where __FILE__
  321. * contains the full path to the file. This is bad, because it
  322. * confuses users to find the home directory of the person who
  323. * compiled the binary in their warrning messages.
  324. */
  325. const char *
  326. tor_fix_source_file(const char *fname)
  327. {
  328. const char *cp1, *cp2, *r;
  329. cp1 = strrchr(fname, '/');
  330. cp2 = strrchr(fname, '\\');
  331. if (cp1 && cp2) {
  332. r = (cp1<cp2)?(cp2+1):(cp1+1);
  333. } else if (cp1) {
  334. r = cp1+1;
  335. } else if (cp2) {
  336. r = cp2+1;
  337. } else {
  338. r = fname;
  339. }
  340. return r;
  341. }
  342. #endif
  343. /**
  344. * Read a 16-bit value beginning at <b>cp</b>. Equivalent to
  345. * *(uint16_t*)(cp), but will not cause segfaults on platforms that forbid
  346. * unaligned memory access.
  347. */
  348. uint16_t
  349. get_uint16(const char *cp)
  350. {
  351. uint16_t v;
  352. memcpy(&v,cp,2);
  353. return v;
  354. }
  355. /**
  356. * Read a 32-bit value beginning at <b>cp</b>. Equivalent to
  357. * *(uint32_t*)(cp), but will not cause segfaults on platforms that forbid
  358. * unaligned memory access.
  359. */
  360. uint32_t
  361. get_uint32(const char *cp)
  362. {
  363. uint32_t v;
  364. memcpy(&v,cp,4);
  365. return v;
  366. }
  367. /**
  368. * Set a 16-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
  369. * *(uint16_t)(cp) = v, but will not cause segfaults on platforms that forbid
  370. * unaligned memory access. */
  371. void
  372. set_uint16(char *cp, uint16_t v)
  373. {
  374. memcpy(cp,&v,2);
  375. }
  376. /**
  377. * Set a 32-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
  378. * *(uint32_t)(cp) = v, but will not cause segfaults on platforms that forbid
  379. * unaligned memory access. */
  380. void
  381. set_uint32(char *cp, uint32_t v)
  382. {
  383. memcpy(cp,&v,4);
  384. }
  385. /**
  386. * Rename the file <b>from</b> to the file <b>to</b>. On unix, this is
  387. * the same as rename(2). On windows, this removes <b>to</b> first if
  388. * it already exists.
  389. * Returns 0 on success. Returns -1 and sets errno on failure.
  390. */
  391. int
  392. replace_file(const char *from, const char *to)
  393. {
  394. #ifndef MS_WINDOWS
  395. return rename(from,to);
  396. #else
  397. switch (file_status(to))
  398. {
  399. case FN_NOENT:
  400. break;
  401. case FN_FILE:
  402. if (unlink(to)) return -1;
  403. break;
  404. case FN_ERROR:
  405. return -1;
  406. case FN_DIR:
  407. errno = EISDIR;
  408. return -1;
  409. }
  410. return rename(from,to);
  411. #endif
  412. }
  413. /** Change <b>fname</b>'s modification time to now. */
  414. int
  415. touch_file(const char *fname)
  416. {
  417. if (utime(fname, NULL)!=0)
  418. return -1;
  419. return 0;
  420. }
  421. /** Represents a lockfile on which we hold the lock. */
  422. struct tor_lockfile_t {
  423. char *filename;
  424. int fd;
  425. };
  426. /** Try to get a lock on the lockfile <b>filename</b>, creating it as
  427. * necessary. If someone else has the lock and <b>blocking</b> is true,
  428. * wait until the lock is available. Otherwise return immediately whether
  429. * we succeeded or not.
  430. *
  431. * Set *<b>locked_out</b> to true if somebody else had the lock, and to false
  432. * otherwise.
  433. *
  434. * Return a <b>tor_lockfile_t</b> on success, NULL on failure.
  435. *
  436. * (Implementation note: because we need to fall back to fcntl on some
  437. * platforms, these locks are per-process, not per-thread. If you want
  438. * to do in-process locking, use tor_mutex_t like a normal person.)
  439. */
  440. tor_lockfile_t *
  441. tor_lockfile_lock(const char *filename, int blocking, int *locked_out)
  442. {
  443. tor_lockfile_t *result;
  444. int fd;
  445. *locked_out = 0;
  446. log_info(LD_FS, "Locking \"%s\"", filename);
  447. fd = open(filename, O_RDWR|O_CREAT|O_TRUNC, 0600);
  448. if (fd < 0) {
  449. log_warn(LD_FS,"Couldn't open \"%s\" for locking: %s", filename,
  450. strerror(errno));
  451. return NULL;
  452. }
  453. #ifdef WIN32
  454. _lseek(fd, 0, SEEK_SET);
  455. if (_locking(fd, blocking ? _LK_LOCK : _LK_NBLCK, 1) < 0) {
  456. if (errno != EDEADLOCK)
  457. log_warn(LD_FS,"Couldn't lock \"%s\": %s", filename, strerror(errno));
  458. else
  459. *locked_out = 1;
  460. close(fd);
  461. return NULL;
  462. }
  463. #elif defined(HAVE_FLOCK)
  464. if (flock(fd, LOCK_EX|(blocking ? 0 : LOCK_NB)) < 0) {
  465. if (errno != EWOULDBLOCK)
  466. log_warn(LD_FS,"Couldn't lock \"%s\": %s", filename, strerror(errno));
  467. else
  468. *locked_out = 1;
  469. close(fd);
  470. return NULL;
  471. }
  472. #else
  473. {
  474. struct flock lock;
  475. memset(&lock, 0, sizeof(lock));
  476. lock.l_type = F_WRLCK;
  477. lock.l_whence = SEEK_SET;
  478. if (fcntl(fd, blocking ? F_SETLKW : F_SETLK, &lock) < 0) {
  479. if (errno != EACCES && errno != EAGAIN)
  480. log_warn(LD_FS, "Couldn't lock \"%s\": %s", filename, strerror(errno));
  481. else
  482. *locked_out = 1;
  483. close(fd);
  484. return NULL;
  485. }
  486. }
  487. #endif
  488. result = tor_malloc(sizeof(tor_lockfile_t));
  489. result->filename = tor_strdup(filename);
  490. result->fd = fd;
  491. return result;
  492. }
  493. /** Release the lock held as <b>lockfile</b>. */
  494. void
  495. tor_lockfile_unlock(tor_lockfile_t *lockfile)
  496. {
  497. tor_assert(lockfile);
  498. log_info(LD_FS, "Unlocking \"%s\"", lockfile->filename);
  499. #ifdef WIN32
  500. _lseek(lockfile->fd, 0, SEEK_SET);
  501. if (_locking(lockfile->fd, _LK_UNLCK, 1) < 0) {
  502. log_warn(LD_FS,"Error unlocking \"%s\": %s", lockfile->filename,
  503. strerror(errno));
  504. }
  505. #elif defined(HAVE_FLOCK)
  506. if (flock(lockfile->fd, LOCK_UN) < 0) {
  507. log_warn(LD_FS, "Error unlocking \"%s\": %s", lockfile->filename,
  508. strerror(errno));
  509. }
  510. #else
  511. /* Closing the lockfile is sufficient. */
  512. #endif
  513. close(lockfile->fd);
  514. lockfile->fd = -1;
  515. tor_free(lockfile->filename);
  516. tor_free(lockfile);
  517. }
  518. /* Some old versions of unix didn't define constants for these values,
  519. * and instead expect you to say 0, 1, or 2. */
  520. #ifndef SEEK_CUR
  521. #define SEEK_CUR 1
  522. #endif
  523. #ifndef SEEK_END
  524. #define SEEK_END 2
  525. #endif
  526. /** Return the position of <b>fd</b> with respect to the start of the file. */
  527. off_t
  528. tor_fd_getpos(int fd)
  529. {
  530. #ifdef WIN32
  531. return (off_t) _lseek(fd, 0, SEEK_CUR);
  532. #else
  533. return (off_t) lseek(fd, 0, SEEK_CUR);
  534. #endif
  535. }
  536. /** Move <b>fd</b> to the end of the file. Return -1 on error, 0 on success. */
  537. int
  538. tor_fd_seekend(int fd)
  539. {
  540. #ifdef WIN32
  541. return _lseek(fd, 0, SEEK_END) < 0 ? -1 : 0;
  542. #else
  543. return lseek(fd, 0, SEEK_END) < 0 ? -1 : 0;
  544. #endif
  545. }
  546. #undef DEBUG_SOCKET_COUNTING
  547. #ifdef DEBUG_SOCKET_COUNTING
  548. /** A bitarray of all fds that should be passed to tor_socket_close(). Only
  549. * used if DEBUG_SOCKET_COUNTING is defined. */
  550. static bitarray_t *open_sockets = NULL;
  551. /** The size of <b>open_sockets</b>, in bits. */
  552. static int max_socket = -1;
  553. #endif
  554. /** Count of number of sockets currently open. (Undercounts sockets opened by
  555. * eventdns and libevent.) */
  556. static int n_sockets_open = 0;
  557. /** As close(), but guaranteed to work for sockets across platforms (including
  558. * Windows, where close()ing a socket doesn't work. Returns 0 on success, -1
  559. * on failure. */
  560. int
  561. tor_close_socket(int s)
  562. {
  563. int r = 0;
  564. #ifdef DEBUG_SOCKET_COUNTING
  565. if (s > max_socket || ! bitarray_is_set(open_sockets, s)) {
  566. log_warn(LD_BUG, "Closing a socket (%d) that wasn't returned by tor_open_"
  567. "socket(), or that was already closed or something.", s);
  568. } else {
  569. tor_assert(open_sockets && s <= max_socket);
  570. bitarray_clear(open_sockets, s);
  571. }
  572. #endif
  573. /* On Windows, you have to call close() on fds returned by open(),
  574. * and closesocket() on fds returned by socket(). On Unix, everything
  575. * gets close()'d. We abstract this difference by always using
  576. * tor_close_socket to close sockets, and always using close() on
  577. * files.
  578. */
  579. #if defined(MS_WINDOWS)
  580. r = closesocket(s);
  581. #else
  582. r = close(s);
  583. #endif
  584. if (r == 0) {
  585. --n_sockets_open;
  586. } else {
  587. int err = tor_socket_errno(-1);
  588. log_info(LD_NET, "Close returned an error: %s", tor_socket_strerror(err));
  589. #ifdef WIN32
  590. if (err != WSAENOTSOCK)
  591. --n_sockets_open;
  592. #else
  593. if (err != EBADF)
  594. --n_sockets_open;
  595. #endif
  596. r = -1;
  597. }
  598. if (n_sockets_open < 0)
  599. log_warn(LD_BUG, "Our socket count is below zero: %d. Please submit a "
  600. "bug report.", n_sockets_open);
  601. return r;
  602. }
  603. #ifdef DEBUG_SOCKET_COUNTING
  604. /** Helper: if DEBUG_SOCKET_COUNTING is enabled, remember that <b>s</b> is
  605. * now an open socket. */
  606. static INLINE void
  607. mark_socket_open(int s)
  608. {
  609. if (s > max_socket) {
  610. if (max_socket == -1) {
  611. open_sockets = bitarray_init_zero(s+128);
  612. max_socket = s+128;
  613. } else {
  614. open_sockets = bitarray_expand(open_sockets, max_socket, s+128);
  615. max_socket = s+128;
  616. }
  617. }
  618. if (bitarray_is_set(open_sockets, s)) {
  619. log_warn(LD_BUG, "I thought that %d was already open, but socket() just "
  620. "gave it to me!", s);
  621. }
  622. bitarray_set(open_sockets, s);
  623. }
  624. #else
  625. #define mark_socket_open(s) STMT_NIL
  626. #endif
  627. /** As socket(), but counts the number of open sockets. */
  628. int
  629. tor_open_socket(int domain, int type, int protocol)
  630. {
  631. int s = socket(domain, type, protocol);
  632. if (s >= 0) {
  633. ++n_sockets_open;
  634. mark_socket_open(s);
  635. }
  636. return s;
  637. }
  638. /** As socket(), but counts the number of open sockets. */
  639. int
  640. tor_accept_socket(int sockfd, struct sockaddr *addr, socklen_t *len)
  641. {
  642. int s = accept(sockfd, addr, len);
  643. if (s >= 0) {
  644. ++n_sockets_open;
  645. mark_socket_open(s);
  646. }
  647. return s;
  648. }
  649. /** Return the number of sockets we currently have opened. */
  650. int
  651. get_n_open_sockets(void)
  652. {
  653. return n_sockets_open;
  654. }
  655. /** Turn <b>socket</b> into a nonblocking socket.
  656. */
  657. void
  658. set_socket_nonblocking(int socket)
  659. {
  660. #if defined(MS_WINDOWS)
  661. unsigned long nonblocking = 1;
  662. ioctlsocket(socket, FIONBIO, (unsigned long*) &nonblocking);
  663. #else
  664. fcntl(socket, F_SETFL, O_NONBLOCK);
  665. #endif
  666. }
  667. /**
  668. * Allocate a pair of connected sockets. (Like socketpair(family,
  669. * type,protocol,fd), but works on systems that don't have
  670. * socketpair.)
  671. *
  672. * Currently, only (AF_UNIX, SOCK_STREAM, 0) sockets are supported.
  673. *
  674. * Note that on systems without socketpair, this call will fail if
  675. * localhost is inaccessible (for example, if the networking
  676. * stack is down). And even if it succeeds, the socket pair will not
  677. * be able to read while localhost is down later (the socket pair may
  678. * even close, depending on OS-specific timeouts).
  679. *
  680. * Returns 0 on success and -errno on failure; do not rely on the value
  681. * of errno or WSAGetLastError().
  682. **/
  683. /* It would be nicer just to set errno, but that won't work for windows. */
  684. int
  685. tor_socketpair(int family, int type, int protocol, int fd[2])
  686. {
  687. //don't use win32 socketpairs (they are always bad)
  688. #if defined(HAVE_SOCKETPAIR) && !defined(MS_WINDOWS)
  689. int r;
  690. r = socketpair(family, type, protocol, fd);
  691. if (r == 0) {
  692. if (fd[0] >= 0) {
  693. ++n_sockets_open;
  694. mark_socket_open(fd[0]);
  695. }
  696. if (fd[1] >= 0) {
  697. ++n_sockets_open;
  698. mark_socket_open(fd[1]);
  699. }
  700. }
  701. return r < 0 ? -errno : r;
  702. #else
  703. /* This socketpair does not work when localhost is down. So
  704. * it's really not the same thing at all. But it's close enough
  705. * for now, and really, when localhost is down sometimes, we
  706. * have other problems too.
  707. */
  708. int listener = -1;
  709. int connector = -1;
  710. int acceptor = -1;
  711. struct sockaddr_in listen_addr;
  712. struct sockaddr_in connect_addr;
  713. int size;
  714. int saved_errno = -1;
  715. if (protocol
  716. #ifdef AF_UNIX
  717. || family != AF_UNIX
  718. #endif
  719. ) {
  720. #ifdef MS_WINDOWS
  721. return -WSAEAFNOSUPPORT;
  722. #else
  723. return -EAFNOSUPPORT;
  724. #endif
  725. }
  726. if (!fd) {
  727. return -EINVAL;
  728. }
  729. listener = tor_open_socket(AF_INET, type, 0);
  730. if (listener < 0)
  731. return -tor_socket_errno(-1);
  732. memset(&listen_addr, 0, sizeof(listen_addr));
  733. listen_addr.sin_family = AF_INET;
  734. listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  735. listen_addr.sin_port = 0; /* kernel chooses port. */
  736. if (bind(listener, (struct sockaddr *) &listen_addr, sizeof (listen_addr))
  737. == -1)
  738. goto tidy_up_and_fail;
  739. if (listen(listener, 1) == -1)
  740. goto tidy_up_and_fail;
  741. connector = tor_open_socket(AF_INET, type, 0);
  742. if (connector < 0)
  743. goto tidy_up_and_fail;
  744. /* We want to find out the port number to connect to. */
  745. size = sizeof(connect_addr);
  746. if (getsockname(listener, (struct sockaddr *) &connect_addr, &size) == -1)
  747. goto tidy_up_and_fail;
  748. if (size != sizeof (connect_addr))
  749. goto abort_tidy_up_and_fail;
  750. if (connect(connector, (struct sockaddr *) &connect_addr,
  751. sizeof(connect_addr)) == -1)
  752. goto tidy_up_and_fail;
  753. size = sizeof(listen_addr);
  754. acceptor = tor_accept_socket(listener,
  755. (struct sockaddr *) &listen_addr, &size);
  756. if (acceptor < 0)
  757. goto tidy_up_and_fail;
  758. if (size != sizeof(listen_addr))
  759. goto abort_tidy_up_and_fail;
  760. tor_close_socket(listener);
  761. /* Now check we are talking to ourself by matching port and host on the
  762. two sockets. */
  763. if (getsockname(connector, (struct sockaddr *) &connect_addr, &size) == -1)
  764. goto tidy_up_and_fail;
  765. if (size != sizeof (connect_addr)
  766. || listen_addr.sin_family != connect_addr.sin_family
  767. || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
  768. || listen_addr.sin_port != connect_addr.sin_port) {
  769. goto abort_tidy_up_and_fail;
  770. }
  771. fd[0] = connector;
  772. fd[1] = acceptor;
  773. return 0;
  774. abort_tidy_up_and_fail:
  775. #ifdef MS_WINDOWS
  776. saved_errno = WSAECONNABORTED;
  777. #else
  778. saved_errno = ECONNABORTED; /* I hope this is portable and appropriate. */
  779. #endif
  780. tidy_up_and_fail:
  781. if (saved_errno < 0)
  782. saved_errno = errno;
  783. if (listener != -1)
  784. tor_close_socket(listener);
  785. if (connector != -1)
  786. tor_close_socket(connector);
  787. if (acceptor != -1)
  788. tor_close_socket(acceptor);
  789. return -saved_errno;
  790. #endif
  791. }
  792. #define ULIMIT_BUFFER 32 /* keep 32 extra fd's beyond _ConnLimit */
  793. /** Learn the maximum allowed number of file descriptors. (Some systems
  794. * have a low soft limit.
  795. *
  796. * We compute this by finding the largest number that we can use.
  797. * If we can't find a number greater than or equal to <b>limit</b>,
  798. * then we fail: return -1.
  799. *
  800. * Otherwise, return 0 and store the maximum we found inside <b>max_out</b>.*/
  801. int
  802. set_max_file_descriptors(rlim_t limit, int *max_out)
  803. {
  804. /* Define some maximum connections values for systems where we cannot
  805. * automatically determine a limit. Re Cygwin, see
  806. * http://archives.seul.org/or/talk/Aug-2006/msg00210.html
  807. * For an iPhone, 9999 should work. For Windows and all other unknown
  808. * systems we use 15000 as the default. */
  809. #ifndef HAVE_GETRLIMIT
  810. #if defined(CYGWIN) || defined(__CYGWIN__)
  811. const char *platform = "Cygwin";
  812. const unsigned long MAX_CONNECTIONS = 3200;
  813. #elif defined(IPHONE)
  814. const char *platform = "iPhone";
  815. const unsigned long MAX_CONNECTIONS = 9999;
  816. #elif defined(MS_WINDOWS)
  817. const char *platform = "Windows";
  818. const unsigned long MAX_CONNECTIONS = 15000;
  819. #else
  820. const char *platform = "unknown platforms with no getrlimit()";
  821. const unsigned long MAX_CONNECTIONS = 15000;
  822. #endif
  823. log_fn(LOG_INFO, LD_NET,
  824. "This platform is missing getrlimit(). Proceeding.");
  825. if (limit > MAX_CONNECTIONS) {
  826. log_warn(LD_CONFIG,
  827. "We do not support more than %lu file descriptors "
  828. "on %s. Tried to raise to %lu.",
  829. (unsigned long)MAX_CONNECTIONS, platform, (unsigned long)limit);
  830. return -1;
  831. }
  832. limit = MAX_CONNECTIONS;
  833. #else /* HAVE_GETRLIMIT */
  834. struct rlimit rlim;
  835. tor_assert(limit > 0);
  836. if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) {
  837. log_warn(LD_NET, "Could not get maximum number of file descriptors: %s",
  838. strerror(errno));
  839. return -1;
  840. }
  841. if (rlim.rlim_max < limit) {
  842. log_warn(LD_CONFIG,"We need %lu file descriptors available, and we're "
  843. "limited to %lu. Please change your ulimit -n.",
  844. (unsigned long)limit, (unsigned long)rlim.rlim_max);
  845. return -1;
  846. }
  847. if (rlim.rlim_max > rlim.rlim_cur) {
  848. log_info(LD_NET,"Raising max file descriptors from %lu to %lu.",
  849. (unsigned long)rlim.rlim_cur, (unsigned long)rlim.rlim_max);
  850. }
  851. rlim.rlim_cur = rlim.rlim_max;
  852. if (setrlimit(RLIMIT_NOFILE, &rlim) != 0) {
  853. int bad = 1;
  854. #ifdef OPEN_MAX
  855. if (errno == EINVAL && OPEN_MAX < rlim.rlim_cur) {
  856. /* On some platforms, OPEN_MAX is the real limit, and getrlimit() is
  857. * full of nasty lies. I'm looking at you, OSX 10.5.... */
  858. rlim.rlim_cur = OPEN_MAX;
  859. if (setrlimit(RLIMIT_NOFILE, &rlim) == 0) {
  860. if (rlim.rlim_cur < (rlim_t)limit) {
  861. log_warn(LD_CONFIG, "We are limited to %lu file descriptors by "
  862. "OPEN_MAX, and ConnLimit is %lu. Changing ConnLimit; sorry.",
  863. (unsigned long)OPEN_MAX, (unsigned long)limit);
  864. } else {
  865. log_info(LD_CONFIG, "Dropped connection limit to OPEN_MAX (%lu); "
  866. "Apparently, %lu was too high and rlimit lied to us.",
  867. (unsigned long)OPEN_MAX, (unsigned long)rlim.rlim_max);
  868. }
  869. bad = 0;
  870. }
  871. }
  872. #endif /* OPEN_MAX */
  873. if (bad) {
  874. log_warn(LD_CONFIG,"Couldn't set maximum number of file descriptors: %s",
  875. strerror(errno));
  876. return -1;
  877. }
  878. }
  879. /* leave some overhead for logs, etc, */
  880. limit = rlim.rlim_cur;
  881. #endif /* HAVE_GETRLIMIT */
  882. if (limit < ULIMIT_BUFFER) {
  883. log_warn(LD_CONFIG,
  884. "ConnLimit must be at least %d. Failing.", ULIMIT_BUFFER);
  885. return -1;
  886. }
  887. if (limit > INT_MAX)
  888. limit = INT_MAX;
  889. tor_assert(max_out);
  890. *max_out = (int)limit - ULIMIT_BUFFER;
  891. return 0;
  892. }
  893. #ifndef MS_WINDOWS
  894. /** Log details of current user and group credentials. Return 0 on
  895. * success. Logs and return -1 on failure.
  896. */
  897. static int
  898. log_credential_status(void)
  899. {
  900. #define CREDENTIAL_LOG_LEVEL LOG_INFO
  901. /* Real, effective and saved UIDs */
  902. uid_t ruid, euid, suid;
  903. /* Read, effective and saved GIDs */
  904. gid_t rgid, egid, sgid;
  905. /* Supplementary groups */
  906. gid_t sup_gids[NGROUPS_MAX + 1];
  907. /* Number of supplementary groups */
  908. int ngids;
  909. /* log UIDs */
  910. #ifdef HAVE_GETRESUID
  911. if (getresuid(&ruid, &euid, &suid) != 0 ) {
  912. log_warn(LD_GENERAL, "Error getting changed UIDs: %s", strerror(errno));
  913. return -1;
  914. } else {
  915. log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
  916. "UID is %u (real), %u (effective), %u (saved)",
  917. (unsigned)ruid, (unsigned)euid, (unsigned)suid);
  918. }
  919. #else
  920. /* getresuid is not present on MacOS X, so we can't get the saved (E)UID */
  921. ruid = getuid();
  922. euid = geteuid();
  923. (void)suid;
  924. log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
  925. "UID is %u (real), %u (effective), unknown (saved)",
  926. (unsigned)ruid, (unsigned)euid);
  927. #endif
  928. /* log GIDs */
  929. #ifdef HAVE_GETRESGID
  930. if (getresgid(&rgid, &egid, &sgid) != 0 ) {
  931. log_warn(LD_GENERAL, "Error getting changed GIDs: %s", strerror(errno));
  932. return -1;
  933. } else {
  934. log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
  935. "GID is %u (real), %u (effective), %u (saved)",
  936. (unsigned)rgid, (unsigned)egid, (unsigned)sgid);
  937. }
  938. #else
  939. /* getresgid is not present on MacOS X, so we can't get the saved (E)GID */
  940. rgid = getgid();
  941. egid = getegid();
  942. (void)sgid;
  943. log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
  944. "GID is %u (real), %u (effective), unknown (saved)",
  945. (unsigned)rgid, (unsigned)egid);
  946. #endif
  947. /* log supplementary groups */
  948. if ((ngids = getgroups(NGROUPS_MAX + 1, sup_gids)) < 0) {
  949. log_warn(LD_GENERAL, "Error getting supplementary GIDs: %s",
  950. strerror(errno));
  951. return -1;
  952. } else {
  953. int i, retval = 0;
  954. char *strgid;
  955. char *s = NULL;
  956. smartlist_t *elts = smartlist_create();
  957. for (i = 0; i<ngids; i++) {
  958. strgid = tor_malloc(11);
  959. if (tor_snprintf(strgid, 11, "%u", (unsigned)sup_gids[i]) < 0) {
  960. log_warn(LD_GENERAL, "Error printing supplementary GIDs");
  961. tor_free(strgid);
  962. retval = -1;
  963. goto error;
  964. }
  965. smartlist_add(elts, strgid);
  966. }
  967. s = smartlist_join_strings(elts, " ", 0, NULL);
  968. log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL, "Supplementary groups are: %s",s);
  969. error:
  970. tor_free(s);
  971. SMARTLIST_FOREACH(elts, char *, cp,
  972. {
  973. tor_free(cp);
  974. });
  975. smartlist_free(elts);
  976. return retval;
  977. }
  978. return 0;
  979. }
  980. #endif
  981. /** Call setuid and setgid to run as <b>user</b> and switch to their
  982. * primary group. Return 0 on success. On failure, log and return -1.
  983. */
  984. int
  985. switch_id(const char *user)
  986. {
  987. #ifndef MS_WINDOWS
  988. struct passwd *pw = NULL;
  989. uid_t old_uid;
  990. gid_t old_gid;
  991. static int have_already_switched_id = 0;
  992. tor_assert(user);
  993. if (have_already_switched_id)
  994. return 0;
  995. /* Log the initial credential state */
  996. if (log_credential_status())
  997. return -1;
  998. log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL, "Changing user and groups");
  999. /* Get old UID/GID to check if we changed correctly */
  1000. old_uid = getuid();
  1001. old_gid = getgid();
  1002. /* Lookup the user and group information, if we have a problem, bail out. */
  1003. pw = getpwnam(user);
  1004. if (pw == NULL) {
  1005. log_warn(LD_CONFIG, "Error setting configured user: %s not found", user);
  1006. return -1;
  1007. }
  1008. /* Properly switch egid,gid,euid,uid here or bail out */
  1009. if (setgroups(1, &pw->pw_gid)) {
  1010. log_warn(LD_GENERAL, "Error setting groups to gid %d: \"%s\".",
  1011. (int)pw->pw_gid, strerror(errno));
  1012. if (old_uid == pw->pw_uid) {
  1013. log_warn(LD_GENERAL, "Tor is already running as %s. You do not need "
  1014. "the \"User\" option if you are already running as the user "
  1015. "you want to be. (If you did not set the User option in your "
  1016. "torrc, check whether it was specified on the command line "
  1017. "by a startup script.)", user);
  1018. } else {
  1019. log_warn(LD_GENERAL, "If you set the \"User\" option, you must start Tor"
  1020. " as root.");
  1021. }
  1022. return -1;
  1023. }
  1024. if (setegid(pw->pw_gid)) {
  1025. log_warn(LD_GENERAL, "Error setting egid to %d: %s",
  1026. (int)pw->pw_gid, strerror(errno));
  1027. return -1;
  1028. }
  1029. if (setgid(pw->pw_gid)) {
  1030. log_warn(LD_GENERAL, "Error setting gid to %d: %s",
  1031. (int)pw->pw_gid, strerror(errno));
  1032. return -1;
  1033. }
  1034. if (setuid(pw->pw_uid)) {
  1035. log_warn(LD_GENERAL, "Error setting configured uid to %s (%d): %s",
  1036. user, (int)pw->pw_uid, strerror(errno));
  1037. return -1;
  1038. }
  1039. if (seteuid(pw->pw_uid)) {
  1040. log_warn(LD_GENERAL, "Error setting configured euid to %s (%d): %s",
  1041. user, (int)pw->pw_uid, strerror(errno));
  1042. return -1;
  1043. }
  1044. /* This is how OpenBSD rolls:
  1045. if (setgroups(1, &pw->pw_gid) || setegid(pw->pw_gid) ||
  1046. setgid(pw->pw_gid) || setuid(pw->pw_uid) || seteuid(pw->pw_uid)) {
  1047. setgid(pw->pw_gid) || seteuid(pw->pw_uid) || setuid(pw->pw_uid)) {
  1048. log_warn(LD_GENERAL, "Error setting configured UID/GID: %s",
  1049. strerror(errno));
  1050. return -1;
  1051. }
  1052. */
  1053. /* We've properly switched egid, gid, euid, uid, and supplementary groups if
  1054. * we're here. */
  1055. #if !defined(CYGWIN) && !defined(__CYGWIN__)
  1056. /* If we tried to drop privilege to a group/user other than root, attempt to
  1057. * restore root (E)(U|G)ID, and abort if the operation succeeds */
  1058. /* Only check for privilege dropping if we were asked to be non-root */
  1059. if (pw->pw_uid) {
  1060. /* Try changing GID/EGID */
  1061. if (pw->pw_gid != old_gid &&
  1062. (setgid(old_gid) != -1 || setegid(old_gid) != -1)) {
  1063. log_warn(LD_GENERAL, "Was able to restore group credentials even after "
  1064. "switching GID: this means that the setgid code didn't work.");
  1065. return -1;
  1066. }
  1067. /* Try changing UID/EUID */
  1068. if (pw->pw_uid != old_uid &&
  1069. (setuid(old_uid) != -1 || seteuid(old_uid) != -1)) {
  1070. log_warn(LD_GENERAL, "Was able to restore user credentials even after "
  1071. "switching UID: this means that the setuid code didn't work.");
  1072. return -1;
  1073. }
  1074. }
  1075. #endif
  1076. /* Check what really happened */
  1077. if (log_credential_status()) {
  1078. return -1;
  1079. }
  1080. have_already_switched_id = 1; /* mark success so we never try again */
  1081. return 0;
  1082. #else
  1083. (void)user;
  1084. log_warn(LD_CONFIG,
  1085. "User specified but switching users is unsupported on your OS.");
  1086. return -1;
  1087. #endif
  1088. }
  1089. #ifdef HAVE_PWD_H
  1090. /** Allocate and return a string containing the home directory for the
  1091. * user <b>username</b>. Only works on posix-like systems. */
  1092. char *
  1093. get_user_homedir(const char *username)
  1094. {
  1095. struct passwd *pw;
  1096. tor_assert(username);
  1097. if (!(pw = getpwnam(username))) {
  1098. log_err(LD_CONFIG,"User \"%s\" not found.", username);
  1099. return NULL;
  1100. }
  1101. return tor_strdup(pw->pw_dir);
  1102. }
  1103. #endif
  1104. /** Set *addr to the IP address (in dotted-quad notation) stored in c.
  1105. * Return 1 on success, 0 if c is badly formatted. (Like inet_aton(c,addr),
  1106. * but works on Windows and Solaris.)
  1107. */
  1108. int
  1109. tor_inet_aton(const char *c, struct in_addr* addr)
  1110. {
  1111. #ifdef HAVE_INET_ATON
  1112. return inet_aton(c, addr);
  1113. #else
  1114. uint32_t r;
  1115. tor_assert(c);
  1116. tor_assert(addr);
  1117. if (strcmp(c, "255.255.255.255") == 0) {
  1118. addr->s_addr = 0xFFFFFFFFu;
  1119. return 1;
  1120. }
  1121. r = inet_addr(c);
  1122. if (r == INADDR_NONE)
  1123. return 0;
  1124. addr->s_addr = r;
  1125. return 1;
  1126. #endif
  1127. }
  1128. /** Given <b>af</b>==AF_INET and <b>src</b> a struct in_addr, or
  1129. * <b>af</b>==AF_INET6 and <b>src</b> a struct in6_addr, try to format the
  1130. * address and store it in the <b>len</b>-byte buffer <b>dst</b>. Returns
  1131. * <b>dst</b> on success, NULL on failure.
  1132. *
  1133. * (Like inet_ntop(af,src,dst,len), but works on platforms that don't have it:
  1134. * Tor sometimes needs to format ipv6 addresses even on platforms without ipv6
  1135. * support.) */
  1136. const char *
  1137. tor_inet_ntop(int af, const void *src, char *dst, size_t len)
  1138. {
  1139. if (af == AF_INET) {
  1140. if (tor_inet_ntoa(src, dst, len) < 0)
  1141. return NULL;
  1142. else
  1143. return dst;
  1144. } else if (af == AF_INET6) {
  1145. const struct in6_addr *addr = src;
  1146. char buf[64], *cp;
  1147. int longestGapLen = 0, longestGapPos = -1, i,
  1148. curGapPos = -1, curGapLen = 0;
  1149. uint16_t words[8];
  1150. for (i = 0; i < 8; ++i) {
  1151. words[i] = (((uint16_t)addr->s6_addr[2*i])<<8) + addr->s6_addr[2*i+1];
  1152. }
  1153. if (words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0 &&
  1154. words[4] == 0 && ((words[5] == 0 && words[6] && words[7]) ||
  1155. (words[5] == 0xffff))) {
  1156. /* This is an IPv4 address. */
  1157. if (words[5] == 0) {
  1158. tor_snprintf(buf, sizeof(buf), "::%d.%d.%d.%d",
  1159. addr->s6_addr[12], addr->s6_addr[13],
  1160. addr->s6_addr[14], addr->s6_addr[15]);
  1161. } else {
  1162. tor_snprintf(buf, sizeof(buf), "::%x:%d.%d.%d.%d", words[5],
  1163. addr->s6_addr[12], addr->s6_addr[13],
  1164. addr->s6_addr[14], addr->s6_addr[15]);
  1165. }
  1166. if (strlen(buf) > len)
  1167. return NULL;
  1168. strlcpy(dst, buf, len);
  1169. return dst;
  1170. }
  1171. i = 0;
  1172. while (i < 8) {
  1173. if (words[i] == 0) {
  1174. curGapPos = i++;
  1175. curGapLen = 1;
  1176. while (i<8 && words[i] == 0) {
  1177. ++i; ++curGapLen;
  1178. }
  1179. if (curGapLen > longestGapLen) {
  1180. longestGapPos = curGapPos;
  1181. longestGapLen = curGapLen;
  1182. }
  1183. } else {
  1184. ++i;
  1185. }
  1186. }
  1187. if (longestGapLen<=1)
  1188. longestGapPos = -1;
  1189. cp = buf;
  1190. for (i = 0; i < 8; ++i) {
  1191. if (words[i] == 0 && longestGapPos == i) {
  1192. if (i == 0)
  1193. *cp++ = ':';
  1194. *cp++ = ':';
  1195. while (i < 8 && words[i] == 0)
  1196. ++i;
  1197. --i; /* to compensate for loop increment. */
  1198. } else {
  1199. tor_snprintf(cp, sizeof(buf)-(cp-buf), "%x", (unsigned)words[i]);
  1200. cp += strlen(cp);
  1201. if (i != 7)
  1202. *cp++ = ':';
  1203. }
  1204. }
  1205. *cp = '\0';
  1206. if (strlen(buf) > len)
  1207. return NULL;
  1208. strlcpy(dst, buf, len);
  1209. return dst;
  1210. } else {
  1211. return NULL;
  1212. }
  1213. }
  1214. /** Given <b>af</b>==AF_INET or <b>af</b>==AF_INET6, and a string <b>src</b>
  1215. * encoding an IPv4 address or IPv6 address correspondingly, try to parse the
  1216. * address and store the result in <b>dst</b> (which must have space for a
  1217. * struct in_addr or a struct in6_addr, as appropriate). Return 1 on success,
  1218. * 0 on a bad parse, and -1 on a bad <b>af</b>.
  1219. *
  1220. * (Like inet_pton(af,src,dst) but works on platforms that don't have it: Tor
  1221. * sometimes needs to format ipv6 addresses even on platforms without ipv6
  1222. * support.) */
  1223. int
  1224. tor_inet_pton(int af, const char *src, void *dst)
  1225. {
  1226. if (af == AF_INET) {
  1227. return tor_inet_aton(src, dst);
  1228. } else if (af == AF_INET6) {
  1229. struct in6_addr *out = dst;
  1230. uint16_t words[8];
  1231. int gapPos = -1, i, setWords=0;
  1232. const char *dot = strchr(src, '.');
  1233. const char *eow; /* end of words. */
  1234. if (dot == src)
  1235. return 0;
  1236. else if (!dot)
  1237. eow = src+strlen(src);
  1238. else {
  1239. int byte1,byte2,byte3,byte4;
  1240. char more;
  1241. for (eow = dot-1; eow >= src && TOR_ISDIGIT(*eow); --eow)
  1242. ;
  1243. ++eow;
  1244. /* We use "scanf" because some platform inet_aton()s are too lax
  1245. * about IPv4 addresses of the form "1.2.3" */
  1246. if (sscanf(eow, "%d.%d.%d.%d%c", &byte1,&byte2,&byte3,&byte4,&more) != 4)
  1247. return 0;
  1248. if (byte1 > 255 || byte1 < 0 ||
  1249. byte2 > 255 || byte2 < 0 ||
  1250. byte3 > 255 || byte3 < 0 ||
  1251. byte4 > 255 || byte4 < 0)
  1252. return 0;
  1253. words[6] = (byte1<<8) | byte2;
  1254. words[7] = (byte3<<8) | byte4;
  1255. setWords += 2;
  1256. }
  1257. i = 0;
  1258. while (src < eow) {
  1259. if (i > 7)
  1260. return 0;
  1261. if (TOR_ISXDIGIT(*src)) {
  1262. char *next;
  1263. long r = strtol(src, &next, 16);
  1264. if (next > 4+src)
  1265. return 0;
  1266. if (next == src)
  1267. return 0;
  1268. if (r<0 || r>65536)
  1269. return 0;
  1270. words[i++] = (uint16_t)r;
  1271. setWords++;
  1272. src = next;
  1273. if (*src != ':' && src != eow)
  1274. return 0;
  1275. ++src;
  1276. } else if (*src == ':' && i > 0 && gapPos==-1) {
  1277. gapPos = i;
  1278. ++src;
  1279. } else if (*src == ':' && i == 0 && src[1] == ':' && gapPos==-1) {
  1280. gapPos = i;
  1281. src += 2;
  1282. } else {
  1283. return 0;
  1284. }
  1285. }
  1286. if (setWords > 8 ||
  1287. (setWords == 8 && gapPos != -1) ||
  1288. (setWords < 8 && gapPos == -1))
  1289. return 0;
  1290. if (gapPos >= 0) {
  1291. int nToMove = setWords - (dot ? 2 : 0) - gapPos;
  1292. int gapLen = 8 - setWords;
  1293. tor_assert(nToMove >= 0);
  1294. memmove(&words[gapPos+gapLen], &words[gapPos],
  1295. sizeof(uint16_t)*nToMove);
  1296. memset(&words[gapPos], 0, sizeof(uint16_t)*gapLen);
  1297. }
  1298. for (i = 0; i < 8; ++i) {
  1299. out->s6_addr[2*i ] = words[i] >> 8;
  1300. out->s6_addr[2*i+1] = words[i] & 0xff;
  1301. }
  1302. return 1;
  1303. } else {
  1304. return -1;
  1305. }
  1306. }
  1307. /** Similar behavior to Unix gethostbyname: resolve <b>name</b>, and set
  1308. * *<b>addr</b> to the proper IP address, in host byte order. Returns 0
  1309. * on success, -1 on failure; 1 on transient failure.
  1310. *
  1311. * (This function exists because standard windows gethostbyname
  1312. * doesn't treat raw IP addresses properly.)
  1313. */
  1314. int
  1315. tor_lookup_hostname(const char *name, uint32_t *addr)
  1316. {
  1317. tor_addr_t myaddr;
  1318. int ret;
  1319. if ((ret = tor_addr_lookup(name, AF_INET, &myaddr)))
  1320. return ret;
  1321. if (tor_addr_family(&myaddr) == AF_INET) {
  1322. *addr = tor_addr_to_ipv4h(&myaddr);
  1323. return ret;
  1324. }
  1325. return -1;
  1326. }
  1327. /** Hold the result of our call to <b>uname</b>. */
  1328. static char uname_result[256];
  1329. /** True iff uname_result is set. */
  1330. static int uname_result_is_set = 0;
  1331. /** Return a pointer to a description of our platform.
  1332. */
  1333. const char *
  1334. get_uname(void)
  1335. {
  1336. #ifdef HAVE_UNAME
  1337. struct utsname u;
  1338. #endif
  1339. if (!uname_result_is_set) {
  1340. #ifdef HAVE_UNAME
  1341. if (uname(&u) != -1) {
  1342. /* (linux says 0 is success, solaris says 1 is success) */
  1343. tor_snprintf(uname_result, sizeof(uname_result), "%s %s",
  1344. u.sysname, u.machine);
  1345. } else
  1346. #endif
  1347. {
  1348. #ifdef MS_WINDOWS
  1349. OSVERSIONINFOEX info;
  1350. int i;
  1351. unsigned int leftover_mask;
  1352. const char *plat = NULL;
  1353. const char *extra = NULL;
  1354. static struct {
  1355. unsigned major; unsigned minor; const char *version;
  1356. } win_version_table[] = {
  1357. { 6, 0, "Windows \"Longhorn\"" },
  1358. { 5, 2, "Windows Server 2003" },
  1359. { 5, 1, "Windows XP" },
  1360. { 5, 0, "Windows 2000" },
  1361. /* { 4, 0, "Windows NT 4.0" }, */
  1362. { 4, 90, "Windows Me" },
  1363. { 4, 10, "Windows 98" },
  1364. /* { 4, 0, "Windows 95" } */
  1365. { 3, 51, "Windows NT 3.51" },
  1366. { 0, 0, NULL }
  1367. };
  1368. #ifdef VER_SUITE_BACKOFFICE
  1369. static struct {
  1370. unsigned int mask; const char *str;
  1371. } win_mask_table[] = {
  1372. { VER_SUITE_BACKOFFICE, " {backoffice}" },
  1373. { VER_SUITE_BLADE, " {\"blade\" (2003, web edition)}" },
  1374. { VER_SUITE_DATACENTER, " {datacenter}" },
  1375. { VER_SUITE_ENTERPRISE, " {enterprise}" },
  1376. { VER_SUITE_EMBEDDEDNT, " {embedded}" },
  1377. { VER_SUITE_PERSONAL, " {personal}" },
  1378. { VER_SUITE_SINGLEUSERTS,
  1379. " {terminal services, single user}" },
  1380. { VER_SUITE_SMALLBUSINESS, " {small business}" },
  1381. { VER_SUITE_SMALLBUSINESS_RESTRICTED,
  1382. " {small business, restricted}" },
  1383. { VER_SUITE_TERMINAL, " {terminal services}" },
  1384. { 0, NULL },
  1385. };
  1386. #endif
  1387. memset(&info, 0, sizeof(info));
  1388. info.dwOSVersionInfoSize = sizeof(info);
  1389. if (! GetVersionEx((LPOSVERSIONINFO)&info)) {
  1390. strlcpy(uname_result, "Bizarre version of Windows where GetVersionEx"
  1391. " doesn't work.", sizeof(uname_result));
  1392. uname_result_is_set = 1;
  1393. return uname_result;
  1394. }
  1395. if (info.dwMajorVersion == 4 && info.dwMinorVersion == 0) {
  1396. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  1397. plat = "Windows NT 4.0";
  1398. else
  1399. plat = "Windows 95";
  1400. if (info.szCSDVersion[1] == 'B')
  1401. extra = "OSR2 (B)";
  1402. else if (info.szCSDVersion[1] == 'C')
  1403. extra = "OSR2 (C)";
  1404. } else {
  1405. for (i=0; win_version_table[i].major>0; ++i) {
  1406. if (win_version_table[i].major == info.dwMajorVersion &&
  1407. win_version_table[i].minor == info.dwMinorVersion) {
  1408. plat = win_version_table[i].version;
  1409. break;
  1410. }
  1411. }
  1412. }
  1413. if (plat && !strcmp(plat, "Windows 98")) {
  1414. if (info.szCSDVersion[1] == 'A')
  1415. extra = "SE (A)";
  1416. else if (info.szCSDVersion[1] == 'B')
  1417. extra = "SE (B)";
  1418. }
  1419. if (plat) {
  1420. if (!extra)
  1421. extra = info.szCSDVersion;
  1422. tor_snprintf(uname_result, sizeof(uname_result), "%s %s",
  1423. plat, extra);
  1424. } else {
  1425. if (info.dwMajorVersion > 6 ||
  1426. (info.dwMajorVersion==6 && info.dwMinorVersion>0))
  1427. tor_snprintf(uname_result, sizeof(uname_result),
  1428. "Very recent version of Windows [major=%d,minor=%d] %s",
  1429. (int)info.dwMajorVersion,(int)info.dwMinorVersion,
  1430. info.szCSDVersion);
  1431. else
  1432. tor_snprintf(uname_result, sizeof(uname_result),
  1433. "Unrecognized version of Windows [major=%d,minor=%d] %s",
  1434. (int)info.dwMajorVersion,(int)info.dwMinorVersion,
  1435. info.szCSDVersion);
  1436. }
  1437. #ifdef VER_SUITE_BACKOFFICE
  1438. if (info.wProductType == VER_NT_DOMAIN_CONTROLLER) {
  1439. strlcat(uname_result, " [domain controller]", sizeof(uname_result));
  1440. } else if (info.wProductType == VER_NT_SERVER) {
  1441. strlcat(uname_result, " [server]", sizeof(uname_result));
  1442. } else if (info.wProductType == VER_NT_WORKSTATION) {
  1443. strlcat(uname_result, " [workstation]", sizeof(uname_result));
  1444. }
  1445. leftover_mask = info.wSuiteMask;
  1446. for (i = 0; win_mask_table[i].mask; ++i) {
  1447. if (info.wSuiteMask & win_mask_table[i].mask) {
  1448. strlcat(uname_result, win_mask_table[i].str, sizeof(uname_result));
  1449. leftover_mask &= ~win_mask_table[i].mask;
  1450. }
  1451. }
  1452. if (leftover_mask) {
  1453. size_t len = strlen(uname_result);
  1454. tor_snprintf(uname_result+len, sizeof(uname_result)-len,
  1455. " {0x%x}", info.wSuiteMask);
  1456. }
  1457. #endif
  1458. #else
  1459. strlcpy(uname_result, "Unknown platform", sizeof(uname_result));
  1460. #endif
  1461. }
  1462. uname_result_is_set = 1;
  1463. }
  1464. return uname_result;
  1465. }
  1466. /*
  1467. * Process control
  1468. */
  1469. #if defined(USE_PTHREADS)
  1470. /** Wraps a void (*)(void*) function and its argument so we can
  1471. * invoke them in a way pthreads would expect.
  1472. */
  1473. typedef struct tor_pthread_data_t {
  1474. void (*func)(void *);
  1475. void *data;
  1476. } tor_pthread_data_t;
  1477. /** Given a tor_pthread_data_t <b>_data</b>, call _data-&gt;func(d-&gt;data)
  1478. * and free _data. Used to make sure we can call functions the way pthread
  1479. * expects. */
  1480. static void *
  1481. tor_pthread_helper_fn(void *_data)
  1482. {
  1483. tor_pthread_data_t *data = _data;
  1484. void (*func)(void*);
  1485. void *arg;
  1486. /* mask signals to worker threads to avoid SIGPIPE, etc */
  1487. sigset_t sigs;
  1488. /* We're in a subthread; don't handle any signals here. */
  1489. sigfillset(&sigs);
  1490. pthread_sigmask(SIG_SETMASK, &sigs, NULL);
  1491. func = data->func;
  1492. arg = data->data;
  1493. tor_free(_data);
  1494. func(arg);
  1495. return NULL;
  1496. }
  1497. #endif
  1498. /** Minimalist interface to run a void function in the background. On
  1499. * unix calls fork, on win32 calls beginthread. Returns -1 on failure.
  1500. * func should not return, but rather should call spawn_exit.
  1501. *
  1502. * NOTE: if <b>data</b> is used, it should not be allocated on the stack,
  1503. * since in a multithreaded environment, there is no way to be sure that
  1504. * the caller's stack will still be around when the called function is
  1505. * running.
  1506. */
  1507. int
  1508. spawn_func(void (*func)(void *), void *data)
  1509. {
  1510. #if defined(USE_WIN32_THREADS)
  1511. int rv;
  1512. rv = (int)_beginthread(func, 0, data);
  1513. if (rv == (int)-1)
  1514. return -1;
  1515. return 0;
  1516. #elif defined(USE_PTHREADS)
  1517. pthread_t thread;
  1518. tor_pthread_data_t *d;
  1519. d = tor_malloc(sizeof(tor_pthread_data_t));
  1520. d->data = data;
  1521. d->func = func;
  1522. if (pthread_create(&thread,NULL,tor_pthread_helper_fn,d))
  1523. return -1;
  1524. if (pthread_detach(thread))
  1525. return -1;
  1526. return 0;
  1527. #else
  1528. pid_t pid;
  1529. pid = fork();
  1530. if (pid<0)
  1531. return -1;
  1532. if (pid==0) {
  1533. /* Child */
  1534. func(data);
  1535. tor_assert(0); /* Should never reach here. */
  1536. return 0; /* suppress "control-reaches-end-of-non-void" warning. */
  1537. } else {
  1538. /* Parent */
  1539. return 0;
  1540. }
  1541. #endif
  1542. }
  1543. /** End the current thread/process.
  1544. */
  1545. void
  1546. spawn_exit(void)
  1547. {
  1548. #if defined(USE_WIN32_THREADS)
  1549. _endthread();
  1550. //we should never get here. my compiler thinks that _endthread returns, this
  1551. //is an attempt to fool it.
  1552. tor_assert(0);
  1553. _exit(0);
  1554. #elif defined(USE_PTHREADS)
  1555. pthread_exit(NULL);
  1556. #else
  1557. /* http://www.erlenstar.demon.co.uk/unix/faq_2.html says we should
  1558. * call _exit, not exit, from child processes. */
  1559. _exit(0);
  1560. #endif
  1561. }
  1562. /** Set *timeval to the current time of day. On error, log and terminate.
  1563. * (Same as gettimeofday(timeval,NULL), but never returns -1.)
  1564. */
  1565. void
  1566. tor_gettimeofday(struct timeval *timeval)
  1567. {
  1568. #ifdef MS_WINDOWS
  1569. /* Epoch bias copied from perl: number of units between windows epoch and
  1570. * unix epoch. */
  1571. #define EPOCH_BIAS U64_LITERAL(116444736000000000)
  1572. #define UNITS_PER_SEC U64_LITERAL(10000000)
  1573. #define USEC_PER_SEC U64_LITERAL(1000000)
  1574. #define UNITS_PER_USEC U64_LITERAL(10)
  1575. union {
  1576. uint64_t ft_64;
  1577. FILETIME ft_ft;
  1578. } ft;
  1579. /* number of 100-nsec units since Jan 1, 1601 */
  1580. GetSystemTimeAsFileTime(&ft.ft_ft);
  1581. if (ft.ft_64 < EPOCH_BIAS) {
  1582. log_err(LD_GENERAL,"System time is before 1970; failing.");
  1583. exit(1);
  1584. }
  1585. ft.ft_64 -= EPOCH_BIAS;
  1586. timeval->tv_sec = (unsigned) (ft.ft_64 / UNITS_PER_SEC);
  1587. timeval->tv_usec = (unsigned) ((ft.ft_64 / UNITS_PER_USEC) % USEC_PER_SEC);
  1588. #elif defined(HAVE_GETTIMEOFDAY)
  1589. if (gettimeofday(timeval, NULL)) {
  1590. log_err(LD_GENERAL,"gettimeofday failed.");
  1591. /* If gettimeofday dies, we have either given a bad timezone (we didn't),
  1592. or segfaulted.*/
  1593. exit(1);
  1594. }
  1595. #elif defined(HAVE_FTIME)
  1596. struct timeb tb;
  1597. ftime(&tb);
  1598. timeval->tv_sec = tb.time;
  1599. timeval->tv_usec = tb.millitm * 1000;
  1600. #else
  1601. #error "No way to get time."
  1602. #endif
  1603. return;
  1604. }
  1605. #if defined(TOR_IS_MULTITHREADED) && !defined(MS_WINDOWS)
  1606. /** Defined iff we need to add locks when defining fake versions of reentrant
  1607. * versions of time-related functions. */
  1608. #define TIME_FNS_NEED_LOCKS
  1609. #endif
  1610. #ifndef HAVE_LOCALTIME_R
  1611. #ifdef TIME_FNS_NEED_LOCKS
  1612. struct tm *
  1613. tor_localtime_r(const time_t *timep, struct tm *result)
  1614. {
  1615. struct tm *r;
  1616. static tor_mutex_t *m=NULL;
  1617. if (!m) { m=tor_mutex_new(); }
  1618. tor_assert(result);
  1619. tor_mutex_acquire(m);
  1620. r = localtime(timep);
  1621. memcpy(result, r, sizeof(struct tm));
  1622. tor_mutex_release(m);
  1623. return result;
  1624. }
  1625. #else
  1626. struct tm *
  1627. tor_localtime_r(const time_t *timep, struct tm *result)
  1628. {
  1629. struct tm *r;
  1630. tor_assert(result);
  1631. r = localtime(timep);
  1632. memcpy(result, r, sizeof(struct tm));
  1633. return result;
  1634. }
  1635. #endif
  1636. #endif
  1637. #ifndef HAVE_GMTIME_R
  1638. #ifdef TIME_FNS_NEED_LOCKS
  1639. struct tm *
  1640. tor_gmtime_r(const time_t *timep, struct tm *result)
  1641. {
  1642. struct tm *r;
  1643. static tor_mutex_t *m=NULL;
  1644. if (!m) { m=tor_mutex_new(); }
  1645. tor_assert(result);
  1646. tor_mutex_acquire(m);
  1647. r = gmtime(timep);
  1648. memcpy(result, r, sizeof(struct tm));
  1649. tor_mutex_release(m);
  1650. return result;
  1651. }
  1652. #else
  1653. struct tm *
  1654. tor_gmtime_r(const time_t *timep, struct tm *result)
  1655. {
  1656. struct tm *r;
  1657. tor_assert(result);
  1658. r = gmtime(timep);
  1659. memcpy(result, r, sizeof(struct tm));
  1660. return result;
  1661. }
  1662. #endif
  1663. #endif
  1664. #if defined(USE_WIN32_THREADS)
  1665. void
  1666. tor_mutex_init(tor_mutex_t *m)
  1667. {
  1668. InitializeCriticalSection(&m->mutex);
  1669. }
  1670. void
  1671. tor_mutex_uninit(tor_mutex_t *m)
  1672. {
  1673. DeleteCriticalSection(&m->mutex);
  1674. }
  1675. void
  1676. tor_mutex_acquire(tor_mutex_t *m)
  1677. {
  1678. tor_assert(m);
  1679. EnterCriticalSection(&m->mutex);
  1680. }
  1681. void
  1682. tor_mutex_release(tor_mutex_t *m)
  1683. {
  1684. LeaveCriticalSection(&m->mutex);
  1685. }
  1686. unsigned long
  1687. tor_get_thread_id(void)
  1688. {
  1689. return (unsigned long)GetCurrentThreadId();
  1690. }
  1691. #elif defined(USE_PTHREADS)
  1692. /** A mutex attribute that we're going to use to tell pthreads that we want
  1693. * "reentrant" mutexes (i.e., once we can re-lock if we're already holding
  1694. * them.) */
  1695. static pthread_mutexattr_t attr_reentrant;
  1696. /** True iff we've called tor_threads_init() */
  1697. static int threads_initialized = 0;
  1698. /** Initialize <b>mutex</b> so it can be locked. Every mutex must be set
  1699. * up eith tor_mutex_init() or tor_mutex_new(); not both. */
  1700. void
  1701. tor_mutex_init(tor_mutex_t *mutex)
  1702. {
  1703. int err;
  1704. if (PREDICT_UNLIKELY(!threads_initialized))
  1705. tor_threads_init();
  1706. err = pthread_mutex_init(&mutex->mutex, &attr_reentrant);
  1707. if (PREDICT_UNLIKELY(err)) {
  1708. log_err(LD_GENERAL, "Error %d creating a mutex.", err);
  1709. tor_fragile_assert();
  1710. }
  1711. }
  1712. /** Wait until <b>m</b> is free, then acquire it. */
  1713. void
  1714. tor_mutex_acquire(tor_mutex_t *m)
  1715. {
  1716. int err;
  1717. tor_assert(m);
  1718. err = pthread_mutex_lock(&m->mutex);
  1719. if (PREDICT_UNLIKELY(err)) {
  1720. log_err(LD_GENERAL, "Error %d locking a mutex.", err);
  1721. tor_fragile_assert();
  1722. }
  1723. }
  1724. /** Release the lock <b>m</b> so another thread can have it. */
  1725. void
  1726. tor_mutex_release(tor_mutex_t *m)
  1727. {
  1728. int err;
  1729. tor_assert(m);
  1730. err = pthread_mutex_unlock(&m->mutex);
  1731. if (PREDICT_UNLIKELY(err)) {
  1732. log_err(LD_GENERAL, "Error %d unlocking a mutex.", err);
  1733. tor_fragile_assert();
  1734. }
  1735. }
  1736. /** Clean up the mutex <b>m</b> so that it no longer uses any system
  1737. * resources. Does not free <b>m</b>. This function must only be called on
  1738. * mutexes from tor_mutex_init(). */
  1739. void
  1740. tor_mutex_uninit(tor_mutex_t *m)
  1741. {
  1742. int err;
  1743. tor_assert(m);
  1744. err = pthread_mutex_destroy(&m->mutex);
  1745. if (PREDICT_UNLIKELY(err)) {
  1746. log_err(LD_GENERAL, "Error %d destroying a mutex.", err);
  1747. tor_fragile_assert();
  1748. }
  1749. }
  1750. /** Return an integer representing this thread. */
  1751. unsigned long
  1752. tor_get_thread_id(void)
  1753. {
  1754. union {
  1755. pthread_t thr;
  1756. unsigned long id;
  1757. } r;
  1758. r.thr = pthread_self();
  1759. return r.id;
  1760. }
  1761. #endif
  1762. #ifdef TOR_IS_MULTITHREADED
  1763. /** Return a newly allocated, ready-for-use mutex. */
  1764. tor_mutex_t *
  1765. tor_mutex_new(void)
  1766. {
  1767. tor_mutex_t *m = tor_malloc_zero(sizeof(tor_mutex_t));
  1768. tor_mutex_init(m);
  1769. return m;
  1770. }
  1771. /** Release all storage and system resources held by <b>m</b>. */
  1772. void
  1773. tor_mutex_free(tor_mutex_t *m)
  1774. {
  1775. tor_mutex_uninit(m);
  1776. tor_free(m);
  1777. }
  1778. #endif
  1779. /* Conditions. */
  1780. #ifdef USE_PTHREADS
  1781. #if 0
  1782. /** Cross-platform condition implementation. */
  1783. struct tor_cond_t {
  1784. pthread_cond_t cond;
  1785. };
  1786. /** Return a newly allocated condition, with nobody waiting on it. */
  1787. tor_cond_t *
  1788. tor_cond_new(void)
  1789. {
  1790. tor_cond_t *cond = tor_malloc_zero(sizeof(tor_cond_t));
  1791. if (pthread_cond_init(&cond->cond, NULL)) {
  1792. tor_free(cond);
  1793. return NULL;
  1794. }
  1795. return cond;
  1796. }
  1797. /** Release all resources held by <b>cond</b>. */
  1798. void
  1799. tor_cond_free(tor_cond_t *cond)
  1800. {
  1801. tor_assert(cond);
  1802. if (pthread_cond_destroy(&cond->cond)) {
  1803. log_warn(LD_GENERAL,"Error freeing condition: %s", strerror(errno));
  1804. return;
  1805. }
  1806. tor_free(cond);
  1807. }
  1808. /** Wait until one of the tor_cond_signal functions is called on <b>cond</b>.
  1809. * All waiters on the condition must wait holding the same <b>mutex</b>.
  1810. * Returns 0 on success, negative on failure. */
  1811. int
  1812. tor_cond_wait(tor_cond_t *cond, tor_mutex_t *mutex)
  1813. {
  1814. return pthread_cond_wait(&cond->cond, &mutex->mutex) ? -1 : 0;
  1815. }
  1816. /** Wake up one of the waiters on <b>cond</b>. */
  1817. void
  1818. tor_cond_signal_one(tor_cond_t *cond)
  1819. {
  1820. pthread_cond_signal(&cond->cond);
  1821. }
  1822. /** Wake up all of the waiters on <b>cond</b>. */
  1823. void
  1824. tor_cond_signal_all(tor_cond_t *cond)
  1825. {
  1826. pthread_cond_broadcast(&cond->cond);
  1827. }
  1828. #endif
  1829. /** Set up common structures for use by threading. */
  1830. void
  1831. tor_threads_init(void)
  1832. {
  1833. if (!threads_initialized) {
  1834. pthread_mutexattr_init(&attr_reentrant);
  1835. pthread_mutexattr_settype(&attr_reentrant, PTHREAD_MUTEX_RECURSIVE);
  1836. threads_initialized = 1;
  1837. }
  1838. }
  1839. #elif defined(USE_WIN32_THREADS)
  1840. #if 0
  1841. static DWORD cond_event_tls_index;
  1842. struct tor_cond_t {
  1843. CRITICAL_SECTION mutex;
  1844. smartlist_t *events;
  1845. };
  1846. tor_cond_t *
  1847. tor_cond_new(void)
  1848. {
  1849. tor_cond_t *cond = tor_malloc_zero(sizeof(tor_cond_t));
  1850. InitializeCriticalSection(&cond->mutex);
  1851. cond->events = smartlist_create();
  1852. return cond;
  1853. }
  1854. void
  1855. tor_cond_free(tor_cond_t *cond)
  1856. {
  1857. tor_assert(cond);
  1858. DeleteCriticalSection(&cond->mutex);
  1859. /* XXXX notify? */
  1860. smartlist_free(cond->events);
  1861. tor_free(cond);
  1862. }
  1863. int
  1864. tor_cond_wait(tor_cond_t *cond, tor_mutex_t *mutex)
  1865. {
  1866. HANDLE event;
  1867. int r;
  1868. tor_assert(cond);
  1869. tor_assert(mutex);
  1870. event = TlsGetValue(cond_event_tls_index);
  1871. if (!event) {
  1872. event = CreateEvent(0, FALSE, FALSE, NULL);
  1873. TlsSetValue(cond_event_tls_index, event);
  1874. }
  1875. EnterCriticalSection(&cond->mutex);
  1876. tor_assert(WaitForSingleObject(event, 0) == WAIT_TIMEOUT);
  1877. tor_assert(!smartlist_isin(cond->events, event));
  1878. smartlist_add(cond->events, event);
  1879. LeaveCriticalSection(&cond->mutex);
  1880. tor_mutex_release(mutex);
  1881. r = WaitForSingleObject(event, INFINITE);
  1882. tor_mutex_acquire(mutex);
  1883. switch (r) {
  1884. case WAIT_OBJECT_0: /* we got the mutex normally. */
  1885. break;
  1886. case WAIT_ABANDONED: /* holding thread exited. */
  1887. case WAIT_TIMEOUT: /* Should never happen. */
  1888. tor_assert(0);
  1889. break;
  1890. case WAIT_FAILED:
  1891. log_warn(LD_GENERAL, "Failed to acquire mutex: %d",(int) GetLastError());
  1892. }
  1893. return 0;
  1894. }
  1895. void
  1896. tor_cond_signal_one(tor_cond_t *cond)
  1897. {
  1898. HANDLE event;
  1899. tor_assert(cond);
  1900. EnterCriticalSection(&cond->mutex);
  1901. if ((event = smartlist_pop_last(cond->events)))
  1902. SetEvent(event);
  1903. LeaveCriticalSection(&cond->mutex);
  1904. }
  1905. void
  1906. tor_cond_signal_all(tor_cond_t *cond)
  1907. {
  1908. tor_assert(cond);
  1909. EnterCriticalSection(&cond->mutex);
  1910. SMARTLIST_FOREACH(cond->events, HANDLE, event, SetEvent(event));
  1911. smartlist_clear(cond->events);
  1912. LeaveCriticalSection(&cond->mutex);
  1913. }
  1914. #endif
  1915. void
  1916. tor_threads_init(void)
  1917. {
  1918. #if 0
  1919. cond_event_tls_index = TlsAlloc();
  1920. #endif
  1921. }
  1922. #endif
  1923. /**
  1924. * On Windows, WSAEWOULDBLOCK is not always correct: when you see it,
  1925. * you need to ask the socket for its actual errno. Also, you need to
  1926. * get your errors from WSAGetLastError, not errno. (If you supply a
  1927. * socket of -1, we check WSAGetLastError, but don't correct
  1928. * WSAEWOULDBLOCKs.)
  1929. *
  1930. * The upshot of all of this is that when a socket call fails, you
  1931. * should call tor_socket_errno <em>at most once</em> on the failing
  1932. * socket to get the error.
  1933. */
  1934. #if defined(MS_WINDOWS)
  1935. int
  1936. tor_socket_errno(int sock)
  1937. {
  1938. int optval, optvallen=sizeof(optval);
  1939. int err = WSAGetLastError();
  1940. if (err == WSAEWOULDBLOCK && sock >= 0) {
  1941. if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval, &optvallen))
  1942. return err;
  1943. if (optval)
  1944. return optval;
  1945. }
  1946. return err;
  1947. }
  1948. #endif
  1949. #if defined(MS_WINDOWS)
  1950. #define E(code, s) { code, (s " [" #code " ]") }
  1951. struct { int code; const char *msg; } windows_socket_errors[] = {
  1952. E(WSAEINTR, "Interrupted function call"),
  1953. E(WSAEACCES, "Permission denied"),
  1954. E(WSAEFAULT, "Bad address"),
  1955. E(WSAEINVAL, "Invalid argument"),
  1956. E(WSAEMFILE, "Too many open files"),
  1957. E(WSAEWOULDBLOCK, "Resource temporarily unavailable"),
  1958. E(WSAEINPROGRESS, "Operation now in progress"),
  1959. E(WSAEALREADY, "Operation already in progress"),
  1960. E(WSAENOTSOCK, "Socket operation on nonsocket"),
  1961. E(WSAEDESTADDRREQ, "Destination address required"),
  1962. E(WSAEMSGSIZE, "Message too long"),
  1963. E(WSAEPROTOTYPE, "Protocol wrong for socket"),
  1964. E(WSAENOPROTOOPT, "Bad protocol option"),
  1965. E(WSAEPROTONOSUPPORT, "Protocol not supported"),
  1966. E(WSAESOCKTNOSUPPORT, "Socket type not supported"),
  1967. /* What's the difference between NOTSUPP and NOSUPPORT? :) */
  1968. E(WSAEOPNOTSUPP, "Operation not supported"),
  1969. E(WSAEPFNOSUPPORT, "Protocol family not supported"),
  1970. E(WSAEAFNOSUPPORT, "Address family not supported by protocol family"),
  1971. E(WSAEADDRINUSE, "Address already in use"),
  1972. E(WSAEADDRNOTAVAIL, "Cannot assign requested address"),
  1973. E(WSAENETDOWN, "Network is down"),
  1974. E(WSAENETUNREACH, "Network is unreachable"),
  1975. E(WSAENETRESET, "Network dropped connection on reset"),
  1976. E(WSAECONNABORTED, "Software caused connection abort"),
  1977. E(WSAECONNRESET, "Connection reset by peer"),
  1978. E(WSAENOBUFS, "No buffer space available"),
  1979. E(WSAEISCONN, "Socket is already connected"),
  1980. E(WSAENOTCONN, "Socket is not connected"),
  1981. E(WSAESHUTDOWN, "Cannot send after socket shutdown"),
  1982. E(WSAETIMEDOUT, "Connection timed out"),
  1983. E(WSAECONNREFUSED, "Connection refused"),
  1984. E(WSAEHOSTDOWN, "Host is down"),
  1985. E(WSAEHOSTUNREACH, "No route to host"),
  1986. E(WSAEPROCLIM, "Too many processes"),
  1987. /* Yes, some of these start with WSA, not WSAE. No, I don't know why. */
  1988. E(WSASYSNOTREADY, "Network subsystem is unavailable"),
  1989. E(WSAVERNOTSUPPORTED, "Winsock.dll out of range"),
  1990. E(WSANOTINITIALISED, "Successful WSAStartup not yet performed"),
  1991. E(WSAEDISCON, "Graceful shutdown now in progress"),
  1992. #ifdef WSATYPE_NOT_FOUND
  1993. E(WSATYPE_NOT_FOUND, "Class type not found"),
  1994. #endif
  1995. E(WSAHOST_NOT_FOUND, "Host not found"),
  1996. E(WSATRY_AGAIN, "Nonauthoritative host not found"),
  1997. E(WSANO_RECOVERY, "This is a nonrecoverable error"),
  1998. E(WSANO_DATA, "Valid name, no data record of requested type)"),
  1999. /* There are some more error codes whose numeric values are marked
  2000. * <b>OS dependent</b>. They start with WSA_, apparently for the same
  2001. * reason that practitioners of some craft traditions deliberately
  2002. * introduce imperfections into their baskets and rugs "to allow the
  2003. * evil spirits to escape." If we catch them, then our binaries
  2004. * might not report consistent results across versions of Windows.
  2005. * Thus, I'm going to let them all fall through.
  2006. */
  2007. { -1, NULL },
  2008. };
  2009. /** There does not seem to be a strerror equivalent for winsock errors.
  2010. * Naturally, we have to roll our own.
  2011. */
  2012. const char *
  2013. tor_socket_strerror(int e)
  2014. {
  2015. int i;
  2016. for (i=0; windows_socket_errors[i].code >= 0; ++i) {
  2017. if (e == windows_socket_errors[i].code)
  2018. return windows_socket_errors[i].msg;
  2019. }
  2020. return strerror(e);
  2021. }
  2022. #endif
  2023. /** Called before we make any calls to network-related functions.
  2024. * (Some operating systems require their network libraries to be
  2025. * initialized.) */
  2026. int
  2027. network_init(void)
  2028. {
  2029. #ifdef MS_WINDOWS
  2030. /* This silly exercise is necessary before windows will allow
  2031. * gethostbyname to work. */
  2032. WSADATA WSAData;
  2033. int r;
  2034. r = WSAStartup(0x101,&WSAData);
  2035. if (r) {
  2036. log_warn(LD_NET,"Error initializing windows network layer: code was %d",r);
  2037. return -1;
  2038. }
  2039. /* WSAData.iMaxSockets might show the max sockets we're allowed to use.
  2040. * We might use it to complain if we're trying to be a server but have
  2041. * too few sockets available. */
  2042. #endif
  2043. return 0;
  2044. }
  2045. #ifdef MS_WINDOWS
  2046. /** Return a newly allocated string describing the windows system error code
  2047. * <b>err</b>. Note that error codes are different from errno. Error codes
  2048. * come from GetLastError() when a winapi call fails. errno is set only when
  2049. * ansi functions fail. Whee. */
  2050. char *
  2051. format_win32_error(DWORD err)
  2052. {
  2053. LPVOID str = NULL;
  2054. char *result;
  2055. /* Somebody once decided that this interface was better than strerror(). */
  2056. FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  2057. FORMAT_MESSAGE_FROM_SYSTEM |
  2058. FORMAT_MESSAGE_IGNORE_INSERTS,
  2059. NULL, err,
  2060. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  2061. (LPTSTR) &str,
  2062. 0, NULL);
  2063. if (str) {
  2064. result = tor_strdup((char*)str);
  2065. LocalFree(str); /* LocalFree != free() */
  2066. } else {
  2067. result = tor_strdup("<unformattable error>");
  2068. }
  2069. return result;
  2070. }
  2071. #endif