compat.c 68 KB

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