compat.c 61 KB

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