compat.c 65 KB

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