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