compat.c 51 KB

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