compat.c 66 KB

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