compat.c 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370
  1. /* Copyright 2003-2004 Roger Dingledine
  2. * Copyright 2004-2006 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_UTIME_H
  81. #include <utime.h>
  82. #endif
  83. #ifdef HAVE_SYS_UTIME_H
  84. #include <sys/utime.h>
  85. #endif
  86. #ifdef HAVE_SYS_MMAN_H
  87. #include <sys/mman.h>
  88. #endif
  89. #ifdef USE_BSOCKETS
  90. #include <bsocket.h>
  91. #endif
  92. #include "log.h"
  93. #include "util.h"
  94. /* Inline the strl functions if the platform doesn't have them. */
  95. #ifndef HAVE_STRLCPY
  96. #include "strlcpy.c"
  97. #endif
  98. #ifndef HAVE_STRLCAT
  99. #include "strlcat.c"
  100. #endif
  101. /* used by inet_addr, not defined on solaris anywhere!? */
  102. #ifndef INADDR_NONE
  103. #define INADDR_NONE ((unsigned long) -1)
  104. #endif
  105. #ifdef HAVE_SYS_MMAN_H
  106. typedef struct tor_mmap_impl_t {
  107. tor_mmap_t base;
  108. size_t mapping_size; /**< Size of the actual mapping. (This is this file
  109. * size, rounded up to the nearest page.) */
  110. } tor_mmap_impl_t;
  111. tor_mmap_t *
  112. tor_mmap_file(const char *filename)
  113. {
  114. int fd; /* router file */
  115. char *string;
  116. int page_size;
  117. tor_mmap_impl_t *res;
  118. size_t size, filesize;
  119. tor_assert(filename);
  120. fd = open(filename, O_RDONLY, 0);
  121. if (fd<0) {
  122. log_warn(LD_FS,"Could not open \"%s\" for mmap().",filename);
  123. return NULL;
  124. }
  125. size = filesize = lseek(fd, 0, SEEK_END);
  126. lseek(fd, 0, SEEK_SET);
  127. /* ensure page alignment */
  128. page_size = getpagesize();
  129. size += (size%page_size) ? page_size-(size%page_size) : 0;
  130. string = mmap(0, size, PROT_READ, MAP_PRIVATE, fd, 0);
  131. if (string == MAP_FAILED) {
  132. close(fd);
  133. log_warn(LD_FS,"Could not mmap file \"%s\": %s", filename,
  134. strerror(errno));
  135. return NULL;
  136. }
  137. close(fd);
  138. res = tor_malloc_zero(sizeof(tor_mmap_impl_t));
  139. res->base.data = string;
  140. res->base.size = filesize;
  141. res->mapping_size = size;
  142. return &(res->base);
  143. }
  144. void
  145. tor_munmap_file(tor_mmap_t *handle)
  146. {
  147. tor_mmap_impl_t *h = (tor_mmap_impl_t*)
  148. (((char*)handle) - STRUCT_OFFSET(tor_mmap_impl_t, base));
  149. munmap((char*)h->base.data, h->mapping_size);
  150. tor_free(h);
  151. }
  152. #elif defined(MS_WINDOWS)
  153. typedef struct win_mmap_t {
  154. tor_mmap_t base;
  155. HANDLE file_handle;
  156. HANDLE mmap_handle;
  157. } win_mmap_t;
  158. tor_mmap_t *
  159. tor_mmap_file(const char *filename)
  160. {
  161. win_mmap_t *res = tor_malloc_zero(sizeof(win_mmap_t));
  162. res->mmap_handle = res->file_handle = INVALID_HANDLE_VALUE;
  163. res->file_handle = CreateFile(filename,
  164. GENERIC_READ,
  165. 0, NULL,
  166. OPEN_EXISTING,
  167. FILE_ATTRIBUTE_NORMAL,
  168. 0);
  169. if (res->file_handle == INVALID_HANDLE_VALUE)
  170. goto err;
  171. res->base.size = GetFileSize(res->file_handle, NULL);
  172. res->mmap_handle = CreateFileMapping(res->file_handle,
  173. NULL,
  174. PAGE_READONLY,
  175. #if SIZEOF_SIZE_T > 4
  176. (res->base.size >> 32),
  177. #else
  178. 0,
  179. #endif
  180. (res->base.size & 0xfffffffful),
  181. NULL);
  182. if (res->mmap_handle != INVALID_HANDLE_VALUE)
  183. goto err;
  184. res->base.data = (char*) MapViewOfFile(res->mmap_handle,
  185. FILE_MAP_READ,
  186. 0, 0, 0);
  187. if (!res->base.data)
  188. goto err;
  189. return &(res->base);
  190. err:
  191. tor_munmap_file(&res->base);
  192. return NULL;
  193. }
  194. void
  195. tor_munmap_file(tor_mmap_t *handle)
  196. {
  197. win_mmap_t *h = (win_mmap_t*)
  198. (((char*)handle) - STRUCT_OFFSET(win_mmap_t, base));
  199. if (handle->data)
  200. /*this is an ugly cast, but without it, "data" in struct tor_mmap_t would
  201. have to be redefined as const*/
  202. UnmapViewOfFile( (LPVOID) handle->data);
  203. if (h->mmap_handle != INVALID_HANDLE_VALUE)
  204. CloseHandle(h->mmap_handle);
  205. if (h->file_handle != INVALID_HANDLE_VALUE)
  206. CloseHandle(h->file_handle);
  207. tor_free(h);
  208. }
  209. #else
  210. tor_mmap_t *
  211. tor_mmap_file(const char *filename)
  212. {
  213. size_t size;
  214. char *res = read_file_to_str(filename, 1, &size);
  215. tor_mmap_t *handle;
  216. if (! res)
  217. return NULL;
  218. handle = tor_malloc_zero(sizeof(tor_mmap_t));
  219. handle->data = res;
  220. handle->size = size;
  221. return handle;
  222. }
  223. void
  224. tor_munmap_file(tor_mmap_t *handle)
  225. {
  226. char *d = (char*)handle->data;
  227. tor_free(d);
  228. memset(handle, sizeof(tor_mmap_t), 0);
  229. tor_free(handle);
  230. }
  231. #endif
  232. /** Replacement for snprintf. Differs from platform snprintf in two
  233. * ways: First, always NUL-terminates its output. Second, always
  234. * returns -1 if the result is truncated. (Note that this return
  235. * behavior does <i>not</i> conform to C99; it just happens to be
  236. * easier to emulate "return -1" with conformant implementations than
  237. * it is to emulate "return number that would be written" with
  238. * non-conformant implementations.) */
  239. int
  240. tor_snprintf(char *str, size_t size, const char *format, ...)
  241. {
  242. va_list ap;
  243. int r;
  244. va_start(ap,format);
  245. r = tor_vsnprintf(str,size,format,ap);
  246. va_end(ap);
  247. return r;
  248. }
  249. /** Replacement for vsnprintf; behavior differs as tor_snprintf differs from
  250. * snprintf.
  251. */
  252. int
  253. tor_vsnprintf(char *str, size_t size, const char *format, va_list args)
  254. {
  255. int r;
  256. if (size == 0)
  257. return -1; /* no place for the NUL */
  258. if (size > SIZE_T_CEILING)
  259. return -1;
  260. #ifdef MS_WINDOWS
  261. r = _vsnprintf(str, size, format, args);
  262. #else
  263. r = vsnprintf(str, size, format, args);
  264. #endif
  265. str[size-1] = '\0';
  266. if (r < 0 || ((size_t)r) >= size)
  267. return -1;
  268. return r;
  269. }
  270. /** Given <b>hlen</b> bytes at <b>haystack</b> and <b>nlen</b> bytes at
  271. * <b>needle</b>, return a pointer to the first occurrence of the needle
  272. * within the haystack, or NULL if there is no such occurrence.
  273. *
  274. * Requires that nlen be greater than zero.
  275. */
  276. const void *
  277. tor_memmem(const void *_haystack, size_t hlen,
  278. const void *_needle, size_t nlen)
  279. {
  280. #if defined(HAVE_MEMMEM) && (!defined(__GNUC__) || __GNUC__ >= 2)
  281. tor_assert(nlen);
  282. return memmem(_haystack, hlen, _needle, nlen);
  283. #else
  284. /* This isn't as fast as the GLIBC implementation, but it doesn't need to
  285. * be. */
  286. const char *p, *end;
  287. const char *haystack = (const char*)_haystack;
  288. const char *needle = (const char*)_needle;
  289. char first;
  290. tor_assert(nlen);
  291. p = haystack;
  292. end = haystack + hlen;
  293. first = *(const char*)needle;
  294. while ((p = memchr(p, first, end-p))) {
  295. if (p+nlen > end)
  296. return NULL;
  297. if (!memcmp(p, needle, nlen))
  298. return p;
  299. ++p;
  300. }
  301. return NULL;
  302. #endif
  303. }
  304. #ifdef MS_WINDOWS
  305. /** Take a filename and return a pointer to its final element. This
  306. * function is called on __FILE__ to fix a MSVC nit where __FILE__
  307. * contains the full path to the file. This is bad, because it
  308. * confuses users to find the home directory of the person who
  309. * compiled the binary in their warrning messages.
  310. */
  311. const char *
  312. tor_fix_source_file(const char *fname)
  313. {
  314. const char *cp1, *cp2, *r;
  315. cp1 = strrchr(fname, '/');
  316. cp2 = strrchr(fname, '\\');
  317. if (cp1 && cp2) {
  318. r = (cp1<cp2)?(cp2+1):(cp1+1);
  319. } else if (cp1) {
  320. r = cp1+1;
  321. } else if (cp2) {
  322. r = cp2+1;
  323. } else {
  324. r = fname;
  325. }
  326. return r;
  327. }
  328. #endif
  329. /**
  330. * Read a 16-bit value beginning at <b>cp</b>. Equivalent to
  331. * *(uint16_t*)(cp), but will not cause segfaults on platforms that forbid
  332. * unaligned memory access.
  333. */
  334. uint16_t
  335. get_uint16(const char *cp)
  336. {
  337. uint16_t v;
  338. memcpy(&v,cp,2);
  339. return v;
  340. }
  341. /**
  342. * Read a 32-bit value beginning at <b>cp</b>. Equivalent to
  343. * *(uint32_t*)(cp), but will not cause segfaults on platforms that forbid
  344. * unaligned memory access.
  345. */
  346. uint32_t
  347. get_uint32(const char *cp)
  348. {
  349. uint32_t v;
  350. memcpy(&v,cp,4);
  351. return v;
  352. }
  353. /**
  354. * Set a 16-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
  355. * *(uint16_t)(cp) = v, but will not cause segfaults on platforms that forbid
  356. * unaligned memory access. */
  357. void
  358. set_uint16(char *cp, uint16_t v)
  359. {
  360. memcpy(cp,&v,2);
  361. }
  362. /**
  363. * Set a 32-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
  364. * *(uint32_t)(cp) = v, but will not cause segfaults on platforms that forbid
  365. * unaligned memory access. */
  366. void
  367. set_uint32(char *cp, uint32_t v)
  368. {
  369. memcpy(cp,&v,4);
  370. }
  371. /**
  372. * Rename the file <b>from</b> to the file <b>to</b>. On unix, this is
  373. * the same as rename(2). On windows, this removes <b>to</b> first if
  374. * it already exists.
  375. * Returns 0 on success. Returns -1 and sets errno on failure.
  376. */
  377. int
  378. replace_file(const char *from, const char *to)
  379. {
  380. #ifndef MS_WINDOWS
  381. return rename(from,to);
  382. #else
  383. switch (file_status(to))
  384. {
  385. case FN_NOENT:
  386. break;
  387. case FN_FILE:
  388. if (unlink(to)) return -1;
  389. break;
  390. case FN_ERROR:
  391. return -1;
  392. case FN_DIR:
  393. errno = EISDIR;
  394. return -1;
  395. }
  396. return rename(from,to);
  397. #endif
  398. }
  399. /** Change <b>fname</b>'s modification time to now. */
  400. int
  401. touch_file(const char *fname)
  402. {
  403. if (utime(fname, NULL)!=0)
  404. return -1;
  405. return 0;
  406. }
  407. /** Turn <b>socket</b> into a nonblocking socket.
  408. */
  409. void
  410. set_socket_nonblocking(int socket)
  411. {
  412. #if defined(MS_WINDOWS) && !defined(USE_BSOCKETS)
  413. unsigned long nonblocking = 1;
  414. ioctlsocket(socket, FIONBIO, (unsigned long*) &nonblocking);
  415. #else
  416. fcntl(socket, F_SETFL, O_NONBLOCK);
  417. #endif
  418. }
  419. /**
  420. * Allocate a pair of connected sockets. (Like socketpair(family,
  421. * type,protocol,fd), but works on systems that don't have
  422. * socketpair.)
  423. *
  424. * Currently, only (AF_UNIX, SOCK_STREAM, 0 ) sockets are supported.
  425. *
  426. * Note that on systems without socketpair, this call will fail if
  427. * localhost is inaccessible (for example, if the networking
  428. * stack is down). And even if it succeeds, the socket pair will not
  429. * be able to read while localhost is down later (the socket pair may
  430. * even close, depending on OS-specific timeouts).
  431. *
  432. * Returns 0 on success and -errno on failure; do not rely on the value
  433. * of errno or WSAGetLastSocketError().
  434. **/
  435. /* It would be nicer just to set errno, but that won't work for windows. */
  436. int
  437. tor_socketpair(int family, int type, int protocol, int fd[2])
  438. {
  439. //don't use win32 socketpairs (they are always bad)
  440. #if defined(HAVE_SOCKETPAIR) && !defined(MS_WINDOWS)
  441. int r;
  442. r = socketpair(family, type, protocol, fd);
  443. return r < 0 ? -errno : r;
  444. #elif defined(USE_BSOCKETS)
  445. return bsockepair(family, type, protocol, fd);
  446. #else
  447. /* This socketpair does not work when localhost is down. So
  448. * it's really not the same thing at all. But it's close enough
  449. * for now, and really, when localhost is down sometimes, we
  450. * have other problems too.
  451. */
  452. int listener = -1;
  453. int connector = -1;
  454. int acceptor = -1;
  455. struct sockaddr_in listen_addr;
  456. struct sockaddr_in connect_addr;
  457. int size;
  458. int saved_errno = -1;
  459. if (protocol
  460. #ifdef AF_UNIX
  461. || family != AF_UNIX
  462. #endif
  463. ) {
  464. #ifdef MS_WINDOWS
  465. return -WSAEAFNOSUPPORT;
  466. #else
  467. return -EAFNOSUPPORT;
  468. #endif
  469. }
  470. if (!fd) {
  471. return -EINVAL;
  472. }
  473. listener = socket(AF_INET, type, 0);
  474. if (listener < 0)
  475. return -tor_socket_errno(-1);
  476. memset(&listen_addr, 0, sizeof(listen_addr));
  477. listen_addr.sin_family = AF_INET;
  478. listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  479. listen_addr.sin_port = 0; /* kernel chooses port. */
  480. if (bind(listener, (struct sockaddr *) &listen_addr, sizeof (listen_addr))
  481. == -1)
  482. goto tidy_up_and_fail;
  483. if (listen(listener, 1) == -1)
  484. goto tidy_up_and_fail;
  485. connector = socket(AF_INET, type, 0);
  486. if (connector < 0)
  487. goto tidy_up_and_fail;
  488. /* We want to find out the port number to connect to. */
  489. size = sizeof(connect_addr);
  490. if (getsockname(listener, (struct sockaddr *) &connect_addr, &size) == -1)
  491. goto tidy_up_and_fail;
  492. if (size != sizeof (connect_addr))
  493. goto abort_tidy_up_and_fail;
  494. if (connect(connector, (struct sockaddr *) &connect_addr,
  495. sizeof(connect_addr)) == -1)
  496. goto tidy_up_and_fail;
  497. size = sizeof(listen_addr);
  498. acceptor = accept(listener, (struct sockaddr *) &listen_addr, &size);
  499. if (acceptor < 0)
  500. goto tidy_up_and_fail;
  501. if (size != sizeof(listen_addr))
  502. goto abort_tidy_up_and_fail;
  503. tor_close_socket(listener);
  504. /* Now check we are talking to ourself by matching port and host on the
  505. two sockets. */
  506. if (getsockname(connector, (struct sockaddr *) &connect_addr, &size) == -1)
  507. goto tidy_up_and_fail;
  508. if (size != sizeof (connect_addr)
  509. || listen_addr.sin_family != connect_addr.sin_family
  510. || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
  511. || listen_addr.sin_port != connect_addr.sin_port) {
  512. goto abort_tidy_up_and_fail;
  513. }
  514. fd[0] = connector;
  515. fd[1] = acceptor;
  516. return 0;
  517. abort_tidy_up_and_fail:
  518. #ifdef MS_WINDOWS
  519. saved_errno = WSAECONNABORTED;
  520. #else
  521. saved_errno = ECONNABORTED; /* I hope this is portable and appropriate. */
  522. #endif
  523. tidy_up_and_fail:
  524. if (saved_errno < 0)
  525. saved_errno = errno;
  526. if (listener != -1)
  527. tor_close_socket(listener);
  528. if (connector != -1)
  529. tor_close_socket(connector);
  530. if (acceptor != -1)
  531. tor_close_socket(acceptor);
  532. return -saved_errno;
  533. #endif
  534. }
  535. #define ULIMIT_BUFFER 32 /* keep 32 extra fd's beyond _ConnLimit */
  536. /** Learn the maximum allowed number of file descriptors. (Some systems
  537. * have a low soft limit.
  538. *
  539. * We compute this by finding the largest number between <b>limit</b>
  540. * and <b>cap</b> that we can use. If we can't find a number greater
  541. * than or equal to <b>limit</b>, then we fail: return -1.
  542. *
  543. * Otherwise, return the number minus some buffer to allow for other
  544. * file descriptors we'll want available for ordinary use. */
  545. int
  546. set_max_file_descriptors(unsigned long limit, unsigned long cap)
  547. {
  548. #ifndef HAVE_GETRLIMIT
  549. log_fn(LOG_INFO, LD_NET,
  550. "This platform is missing getrlimit(). Proceeding.");
  551. if (limit < cap) {
  552. log_info(LD_CONFIG, "ConnLimit must be at most %d. Using that.", (int)cap);
  553. limit = cap;
  554. }
  555. #else
  556. struct rlimit rlim;
  557. unsigned long most;
  558. tor_assert(limit > 0);
  559. tor_assert(cap > 0);
  560. if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) {
  561. log_warn(LD_NET, "Could not get maximum number of file descriptors: %s",
  562. strerror(errno));
  563. return -1;
  564. }
  565. if (rlim.rlim_max < limit) {
  566. log_warn(LD_CONFIG,"We need %lu file descriptors available, and we're "
  567. "limited to %lu. Please change your ulimit -n.",
  568. limit, (unsigned long)rlim.rlim_max);
  569. return -1;
  570. }
  571. most = (rlim.rlim_max > cap) ? cap : (unsigned) rlim.rlim_max;
  572. if (most > rlim.rlim_cur) {
  573. log_info(LD_NET,"Raising max file descriptors from %lu to %lu.",
  574. (unsigned long)rlim.rlim_cur, most);
  575. }
  576. rlim.rlim_cur = most;
  577. if (setrlimit(RLIMIT_NOFILE, &rlim) != 0) {
  578. log_warn(LD_CONFIG, "Could not set maximum number of file descriptors: %s",
  579. strerror(errno));
  580. return -1;
  581. }
  582. /* leave some overhead for logs, etc, */
  583. limit = most;
  584. #endif
  585. if (limit < ULIMIT_BUFFER) {
  586. log_warn(LD_CONFIG,
  587. "ConnLimit must be at least %d. Failing.", ULIMIT_BUFFER);
  588. return -1;
  589. }
  590. return limit - ULIMIT_BUFFER;
  591. }
  592. /** Call setuid and setgid to run as <b>user</b>:<b>group</b>. Return 0 on
  593. * success. On failure, log and return -1.
  594. */
  595. int
  596. switch_id(char *user, char *group)
  597. {
  598. #ifndef MS_WINDOWS
  599. struct passwd *pw = NULL;
  600. struct group *gr = NULL;
  601. if (user) {
  602. pw = getpwnam(user);
  603. if (pw == NULL) {
  604. log_warn(LD_CONFIG,"User '%s' not found.", user);
  605. return -1;
  606. }
  607. }
  608. /* switch the group first, while we still have the privileges to do so */
  609. if (group) {
  610. gr = getgrnam(group);
  611. if (gr == NULL) {
  612. log_warn(LD_CONFIG,"Group '%s' not found.", group);
  613. return -1;
  614. }
  615. if (setgid(gr->gr_gid) != 0) {
  616. log_warn(LD_GENERAL,"Error setting to configured GID: %s",
  617. strerror(errno));
  618. return -1;
  619. }
  620. } else if (user) {
  621. if (setgid(pw->pw_gid) != 0) {
  622. log_warn(LD_GENERAL,"Error setting to user GID: %s", strerror(errno));
  623. return -1;
  624. }
  625. }
  626. /* now that the group is switched, we can switch users and lose
  627. privileges */
  628. if (user) {
  629. if (setuid(pw->pw_uid) != 0) {
  630. log_warn(LD_GENERAL,"Error setting UID: %s", strerror(errno));
  631. return -1;
  632. }
  633. }
  634. return 0;
  635. #endif
  636. log_warn(LD_CONFIG,
  637. "User or group specified, but switching users is not supported.");
  638. return -1;
  639. }
  640. #ifdef HAVE_PWD_H
  641. /** Allocate and return a string containing the home directory for the
  642. * user <b>username</b>. Only works on posix-like systems */
  643. char *
  644. get_user_homedir(const char *username)
  645. {
  646. struct passwd *pw;
  647. tor_assert(username);
  648. if (!(pw = getpwnam(username))) {
  649. log_err(LD_CONFIG,"User \"%s\" not found.", username);
  650. return NULL;
  651. }
  652. return tor_strdup(pw->pw_dir);
  653. }
  654. #endif
  655. /** Set *addr to the IP address (in dotted-quad notation) stored in c.
  656. * Return 1 on success, 0 if c is badly formatted. (Like inet_aton(c,addr),
  657. * but works on Windows and Solaris.)
  658. */
  659. int
  660. tor_inet_aton(const char *c, struct in_addr* addr)
  661. {
  662. #ifdef HAVE_INET_ATON
  663. return inet_aton(c, addr);
  664. #else
  665. uint32_t r;
  666. tor_assert(c);
  667. tor_assert(addr);
  668. if (strcmp(c, "255.255.255.255") == 0) {
  669. addr->s_addr = 0xFFFFFFFFu;
  670. return 1;
  671. }
  672. r = inet_addr(c);
  673. if (r == INADDR_NONE)
  674. return 0;
  675. addr->s_addr = r;
  676. return 1;
  677. #endif
  678. }
  679. /** Similar behavior to Unix gethostbyname: resolve <b>name</b>, and set
  680. * *addr to the proper IP address, in network byte order. Returns 0
  681. * on success, -1 on failure; 1 on transient failure.
  682. *
  683. * (This function exists because standard windows gethostbyname
  684. * doesn't treat raw IP addresses properly.)
  685. */
  686. int
  687. tor_lookup_hostname(const char *name, uint32_t *addr)
  688. {
  689. /* Perhaps eventually this should be replaced by a tor_getaddrinfo or
  690. * something.
  691. */
  692. struct in_addr iaddr;
  693. tor_assert(name);
  694. tor_assert(addr);
  695. if (!*name) {
  696. /* Empty address is an error. */
  697. return -1;
  698. } else if (tor_inet_aton(name, &iaddr)) {
  699. /* It's an IP. */
  700. memcpy(addr, &iaddr.s_addr, 4);
  701. return 0;
  702. } else {
  703. #ifdef HAVE_GETADDRINFO
  704. int err;
  705. struct addrinfo *res=NULL, *res_p;
  706. struct addrinfo hints;
  707. int result = -1;
  708. memset(&hints, 0, sizeof(hints));
  709. hints.ai_family = PF_INET;
  710. hints.ai_socktype = SOCK_STREAM;
  711. err = getaddrinfo(name, NULL, &hints, &res);
  712. if (!err) {
  713. for (res_p = res; res_p; res_p = res_p->ai_next) {
  714. if (res_p->ai_family == AF_INET) {
  715. struct sockaddr_in *sin = (struct sockaddr_in *)res_p->ai_addr;
  716. memcpy(addr, &sin->sin_addr, 4);
  717. result = 0;
  718. break;
  719. }
  720. }
  721. freeaddrinfo(res);
  722. return result;
  723. }
  724. return (err == EAI_AGAIN) ? 1 : -1;
  725. #else
  726. struct hostent *ent;
  727. int err;
  728. #ifdef HAVE_GETHOSTBYNAME_R_6_ARG
  729. char buf[2048];
  730. struct hostent hostent;
  731. int r;
  732. r = gethostbyname_r(name, &hostent, buf, sizeof(buf), &ent, &err);
  733. #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
  734. char buf[2048];
  735. struct hostent hostent;
  736. ent = gethostbyname_r(name, &hostent, buf, sizeof(buf), &err);
  737. #elif defined(HAVE_GETHOSTBYNAME_R_3_ARG)
  738. struct hostent_data data;
  739. struct hostent hent;
  740. memset(&data, 0, sizeof(data));
  741. err = gethostbyname_r(name, &hent, &data);
  742. ent = err ? NULL : &hent;
  743. #else
  744. ent = gethostbyname(name);
  745. #ifdef MS_WINDOWS
  746. err = WSAGetLastError();
  747. #else
  748. err = h_errno;
  749. #endif
  750. #endif
  751. if (ent) {
  752. /* break to remind us if we move away from IPv4 */
  753. tor_assert(ent->h_length == 4);
  754. memcpy(addr, ent->h_addr, 4);
  755. return 0;
  756. }
  757. memset(addr, 0, 4);
  758. #ifdef MS_WINDOWS
  759. return (err == WSATRY_AGAIN) ? 1 : -1;
  760. #else
  761. return (err == TRY_AGAIN) ? 1 : -1;
  762. #endif
  763. #endif
  764. }
  765. }
  766. /** Hold the result of our call to <b>uname</b>. */
  767. static char uname_result[256];
  768. /** True iff uname_result is set. */
  769. static int uname_result_is_set = 0;
  770. /** Return a pointer to a description of our platform.
  771. */
  772. const char *
  773. get_uname(void)
  774. {
  775. #ifdef HAVE_UNAME
  776. struct utsname u;
  777. #endif
  778. if (!uname_result_is_set) {
  779. #ifdef HAVE_UNAME
  780. if (uname(&u) != -1) {
  781. /* (linux says 0 is success, solaris says 1 is success) */
  782. tor_snprintf(uname_result, sizeof(uname_result), "%s %s",
  783. u.sysname, u.machine);
  784. } else
  785. #endif
  786. {
  787. #ifdef MS_WINDOWS
  788. OSVERSIONINFOEX info;
  789. int i;
  790. unsigned int leftover_mask;
  791. const char *plat = NULL;
  792. static struct {
  793. int major; int minor; const char *version;
  794. } win_version_table[] = {
  795. { 6, 0, "Windows \"Longhorn\"" },
  796. { 5, 2, "Windows Server 2003" },
  797. { 5, 1, "Windows XP" },
  798. { 5, 0, "Windows 2000" },
  799. /* { 4, 0, "Windows NT 4.0" }, */
  800. { 4, 90, "Windows Me" },
  801. { 4, 10, "Windows 98" },
  802. /* { 4, 0, "Windows 95" } */
  803. { 3, 51, "Windows NT 3.51" },
  804. { -1, -1, NULL }
  805. };
  806. #ifdef VER_SUITE_BACKOFFICE
  807. static struct {
  808. unsigned int mask; const char *str;
  809. } win_mask_table[] = {
  810. { VER_SUITE_BACKOFFICE, " {backoffice}" },
  811. { VER_SUITE_BLADE, " {\"blade\" (2003, web edition)}" },
  812. { VER_SUITE_DATACENTER, " {datacenter}" },
  813. { VER_SUITE_ENTERPRISE, " {enterprise}" },
  814. { VER_SUITE_EMBEDDEDNT, " {embedded}" },
  815. { VER_SUITE_PERSONAL, " {personal}" },
  816. { VER_SUITE_SINGLEUSERTS,
  817. " {terminal services, single user}" },
  818. { VER_SUITE_SMALLBUSINESS, " {small business}" },
  819. { VER_SUITE_SMALLBUSINESS_RESTRICTED,
  820. " {small business, restricted}" },
  821. { VER_SUITE_TERMINAL, " {terminal services}" },
  822. { 0, NULL },
  823. };
  824. #endif
  825. memset(&info, 0, sizeof(info));
  826. info.dwOSVersionInfoSize = sizeof(info);
  827. if (! GetVersionEx((LPOSVERSIONINFO)&info)) {
  828. strlcpy(uname_result, "Bizarre version of Windows where GetVersionEx"
  829. " doesn't work.", sizeof(uname_result));
  830. uname_result_is_set = 1;
  831. return uname_result;
  832. }
  833. if (info.dwMajorVersion == 4 && info.dwMinorVersion == 0) {
  834. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  835. plat = "Windows NT 4.0";
  836. else
  837. plat = "Windows 95";
  838. } else {
  839. for (i=0; win_version_table[i].major>=0; ++i) {
  840. if (win_version_table[i].major == info.dwMajorVersion &&
  841. win_version_table[i].minor == info.dwMinorVersion) {
  842. plat = win_version_table[i].version;
  843. break;
  844. }
  845. }
  846. }
  847. if (plat) {
  848. tor_snprintf(uname_result, sizeof(uname_result), "%s %s",
  849. plat, info.szCSDVersion);
  850. } else {
  851. if (info.dwMajorVersion > 6 ||
  852. (info.dwMajorVersion==6 && info.dwMinorVersion>0))
  853. tor_snprintf(uname_result, sizeof(uname_result),
  854. "Very recent version of Windows [major=%d,minor=%d] %s",
  855. (int)info.dwMajorVersion,(int)info.dwMinorVersion,
  856. info.szCSDVersion);
  857. else
  858. tor_snprintf(uname_result, sizeof(uname_result),
  859. "Unrecognized version of Windows [major=%d,minor=%d] %s",
  860. (int)info.dwMajorVersion,(int)info.dwMinorVersion,
  861. info.szCSDVersion);
  862. }
  863. #ifdef VER_SUITE_BACKOFFICE
  864. if (info.wProductType == VER_NT_DOMAIN_CONTROLLER) {
  865. strlcat(uname_result, " [domain controller]", sizeof(uname_result));
  866. } else if (info.wProductType == VER_NT_SERVER) {
  867. strlcat(uname_result, " [server]", sizeof(uname_result));
  868. } else if (info.wProductType == VER_NT_WORKSTATION) {
  869. strlcat(uname_result, " [workstation]", sizeof(uname_result));
  870. }
  871. leftover_mask = info.wSuiteMask;
  872. for (i = 0; win_mask_table[i].mask; ++i) {
  873. if (info.wSuiteMask & win_mask_table[i].mask) {
  874. strlcat(uname_result, win_mask_table[i].str, sizeof(uname_result));
  875. leftover_mask &= ~win_mask_table[i].mask;
  876. }
  877. }
  878. if (leftover_mask) {
  879. size_t len = strlen(uname_result);
  880. tor_snprintf(uname_result+len, sizeof(uname_result)-len,
  881. " {0x%x}", info.wSuiteMask);
  882. }
  883. #endif
  884. #else
  885. strlcpy(uname_result, "Unknown platform", sizeof(uname_result));
  886. #endif
  887. }
  888. uname_result_is_set = 1;
  889. }
  890. return uname_result;
  891. }
  892. /*
  893. * Process control
  894. */
  895. #if defined(USE_PTHREADS)
  896. /** Wraps a an int (*)(void*) function and its argument so we can
  897. * invoke them in a way pthreads would expect.
  898. */
  899. typedef struct tor_pthread_data_t {
  900. void (*func)(void *);
  901. void *data;
  902. } tor_pthread_data_t;
  903. static void *
  904. tor_pthread_helper_fn(void *_data)
  905. {
  906. tor_pthread_data_t *data = _data;
  907. void (*func)(void*);
  908. void *arg;
  909. func = data->func;
  910. arg = data->data;
  911. tor_free(_data);
  912. func(arg);
  913. return NULL;
  914. }
  915. #endif
  916. /** Minimalist interface to run a void function in the background. On
  917. * unix calls fork, on win32 calls beginthread. Returns -1 on failure.
  918. * func should not return, but rather should call spawn_exit.
  919. *
  920. * NOTE: if <b>data</b> is used, it should not be allocated on the stack,
  921. * since in a multithreaded environment, there is no way to be sure that
  922. * the caller's stack will still be around when the called function is
  923. * running.
  924. */
  925. int
  926. spawn_func(void (*func)(void *), void *data)
  927. {
  928. #if defined(USE_WIN32_THREADS)
  929. int rv;
  930. rv = _beginthread(func, 0, data);
  931. if (rv == (unsigned long) -1)
  932. return -1;
  933. return 0;
  934. #elif defined(USE_PTHREADS)
  935. pthread_t thread;
  936. tor_pthread_data_t *d;
  937. d = tor_malloc(sizeof(tor_pthread_data_t));
  938. d->data = data;
  939. d->func = func;
  940. if (pthread_create(&thread,NULL,tor_pthread_helper_fn,d))
  941. return -1;
  942. if (pthread_detach(thread))
  943. return -1;
  944. return 0;
  945. #else
  946. pid_t pid;
  947. pid = fork();
  948. if (pid<0)
  949. return -1;
  950. if (pid==0) {
  951. /* Child */
  952. func(data);
  953. tor_assert(0); /* Should never reach here. */
  954. return 0; /* suppress "control-reaches-end-of-non-void" warning. */
  955. } else {
  956. /* Parent */
  957. return 0;
  958. }
  959. #endif
  960. }
  961. /** End the current thread/process.
  962. */
  963. void
  964. spawn_exit(void)
  965. {
  966. #if defined(USE_WIN32_THREADS)
  967. _endthread();
  968. //we should never get here. my compiler thinks that _endthread returns, this
  969. //is an attempt to fool it.
  970. tor_assert(0);
  971. _exit(0);
  972. #elif defined(USE_PTHREADS)
  973. pthread_exit(NULL);
  974. #else
  975. /* http://www.erlenstar.demon.co.uk/unix/faq_2.html says we should
  976. * call _exit, not exit, from child processes. */
  977. _exit(0);
  978. #endif
  979. }
  980. /** Set *timeval to the current time of day. On error, log and terminate.
  981. * (Same as gettimeofday(timeval,NULL), but never returns -1.)
  982. */
  983. void
  984. tor_gettimeofday(struct timeval *timeval)
  985. {
  986. #ifdef MS_WINDOWS
  987. /* Epoch bias copied from perl: number of units between windows epoch and
  988. * unix epoch. */
  989. #define EPOCH_BIAS U64_LITERAL(116444736000000000)
  990. #define UNITS_PER_SEC U64_LITERAL(10000000)
  991. #define USEC_PER_SEC U64_LITERAL(1000000)
  992. #define UNITS_PER_USEC U64_LITERAL(10)
  993. union {
  994. uint64_t ft_64;
  995. FILETIME ft_ft;
  996. } ft;
  997. /* number of 100-nsec units since Jan 1, 1601 */
  998. GetSystemTimeAsFileTime(&ft.ft_ft);
  999. if (ft.ft_64 < EPOCH_BIAS) {
  1000. log_err(LD_GENERAL,"System time is before 1970; failing.");
  1001. exit(1);
  1002. }
  1003. ft.ft_64 -= EPOCH_BIAS;
  1004. timeval->tv_sec = (unsigned) (ft.ft_64 / UNITS_PER_SEC);
  1005. timeval->tv_usec = (unsigned) ((ft.ft_64 / UNITS_PER_USEC) % USEC_PER_SEC);
  1006. #elif defined(HAVE_GETTIMEOFDAY)
  1007. if (gettimeofday(timeval, NULL)) {
  1008. log_err(LD_GENERAL,"gettimeofday failed.");
  1009. /* If gettimeofday dies, we have either given a bad timezone (we didn't),
  1010. or segfaulted.*/
  1011. exit(1);
  1012. }
  1013. #elif defined(HAVE_FTIME)
  1014. struct timeb tb;
  1015. ftime(&tb);
  1016. timeval->tv_sec = tb.time;
  1017. timeval->tv_usec = tb.millitm * 1000;
  1018. #else
  1019. #error "No way to get time."
  1020. #endif
  1021. return;
  1022. }
  1023. #if defined(TOR_IS_MULTITHREADED) && !defined(MS_WINDOWS)
  1024. #define TIME_FNS_NEED_LOCKS
  1025. #endif
  1026. #ifndef HAVE_LOCALTIME_R
  1027. #ifdef TIME_FNS_NEED_LOCKS
  1028. struct tm *
  1029. tor_localtime_r(const time_t *timep, struct tm *result)
  1030. {
  1031. struct tm *r;
  1032. static tor_mutex_t *m=NULL;
  1033. if (!m) { m=tor_mutex_new(); }
  1034. tor_assert(result);
  1035. tor_mutex_acquire(m);
  1036. r = localtime(timep);
  1037. memcpy(result, r, sizeof(struct tm));
  1038. tor_mutex_release(m);
  1039. return result;
  1040. }
  1041. #else
  1042. struct tm *
  1043. tor_localtime_r(const time_t *timep, struct tm *result)
  1044. {
  1045. struct tm *r;
  1046. tor_assert(result);
  1047. r = localtime(timep);
  1048. memcpy(result, r, sizeof(struct tm));
  1049. return result;
  1050. }
  1051. #endif
  1052. #endif
  1053. #ifndef HAVE_GMTIME_R
  1054. #ifdef TIME_FNS_NEED_LOCKS
  1055. struct tm *
  1056. tor_gmtime_r(const time_t *timep, struct tm *result)
  1057. {
  1058. struct tm *r;
  1059. static tor_mutex_t *m=NULL;
  1060. if (!m) { m=tor_mutex_new(); }
  1061. tor_assert(result);
  1062. tor_mutex_acquire(m);
  1063. r = gmtime(timep);
  1064. memcpy(result, r, sizeof(struct tm));
  1065. tor_mutex_release(m);
  1066. return result;
  1067. }
  1068. #else
  1069. struct tm *
  1070. tor_gmtime_r(const time_t *timep, struct tm *result)
  1071. {
  1072. struct tm *r;
  1073. tor_assert(result);
  1074. r = gmtime(timep);
  1075. memcpy(result, r, sizeof(struct tm));
  1076. return result;
  1077. }
  1078. #endif
  1079. #endif
  1080. #ifdef USE_WIN32_THREADS
  1081. /** A generic lock structure for multithreaded builds. */
  1082. struct tor_mutex_t {
  1083. HANDLE handle;
  1084. };
  1085. tor_mutex_t *
  1086. tor_mutex_new(void)
  1087. {
  1088. tor_mutex_t *m;
  1089. m = tor_malloc_zero(sizeof(tor_mutex_t));
  1090. m->handle = CreateMutex(NULL, FALSE, NULL);
  1091. tor_assert(m->handle != NULL);
  1092. return m;
  1093. }
  1094. void
  1095. tor_mutex_free(tor_mutex_t *m)
  1096. {
  1097. CloseHandle(m->handle);
  1098. tor_free(m);
  1099. }
  1100. void
  1101. tor_mutex_acquire(tor_mutex_t *m)
  1102. {
  1103. DWORD r;
  1104. r = WaitForSingleObject(m->handle, INFINITE);
  1105. switch (r) {
  1106. case WAIT_ABANDONED: /* holding thread exited. */
  1107. case WAIT_OBJECT_0: /* we got the mutex normally. */
  1108. break;
  1109. case WAIT_TIMEOUT: /* Should never happen. */
  1110. tor_assert(0);
  1111. break;
  1112. case WAIT_FAILED:
  1113. log_warn(LD_GENERAL, "Failed to acquire mutex: %d",(int) GetLastError());
  1114. }
  1115. }
  1116. void
  1117. tor_mutex_release(tor_mutex_t *m)
  1118. {
  1119. BOOL r;
  1120. r = ReleaseMutex(m->handle);
  1121. if (!r) {
  1122. log_warn(LD_GENERAL, "Failed to release mutex: %d", (int) GetLastError());
  1123. }
  1124. }
  1125. unsigned long
  1126. tor_get_thread_id(void)
  1127. {
  1128. return (unsigned long)GetCurrentThreadId();
  1129. }
  1130. #elif defined(USE_PTHREADS)
  1131. /** A generic lock structure for multithreaded builds. */
  1132. struct tor_mutex_t {
  1133. pthread_mutex_t mutex;
  1134. };
  1135. tor_mutex_t *
  1136. tor_mutex_new(void)
  1137. {
  1138. tor_mutex_t *mutex = tor_malloc_zero(sizeof(tor_mutex_t));
  1139. pthread_mutex_init(&mutex->mutex, NULL);
  1140. return mutex;
  1141. }
  1142. void
  1143. tor_mutex_acquire(tor_mutex_t *m)
  1144. {
  1145. tor_assert(m);
  1146. pthread_mutex_lock(&m->mutex);
  1147. }
  1148. void
  1149. tor_mutex_release(tor_mutex_t *m)
  1150. {
  1151. tor_assert(m);
  1152. pthread_mutex_unlock(&m->mutex);
  1153. }
  1154. void
  1155. tor_mutex_free(tor_mutex_t *m)
  1156. {
  1157. tor_assert(m);
  1158. pthread_mutex_destroy(&m->mutex);
  1159. tor_free(m);
  1160. }
  1161. unsigned long
  1162. tor_get_thread_id(void)
  1163. {
  1164. union {
  1165. pthread_t thr;
  1166. unsigned long id;
  1167. } r;
  1168. r.thr = pthread_self();
  1169. return r.id;
  1170. }
  1171. #else
  1172. /** A generic lock structure for multithreaded builds. */
  1173. struct tor_mutex_t {
  1174. int _unused;
  1175. };
  1176. #endif
  1177. /**
  1178. * On Windows, WSAEWOULDBLOCK is not always correct: when you see it,
  1179. * you need to ask the socket for its actual errno. Also, you need to
  1180. * get your errors from WSAGetLastError, not errno. (If you supply a
  1181. * socket of -1, we check WSAGetLastError, but don't correct
  1182. * WSAEWOULDBLOCKs.)
  1183. *
  1184. * The upshot of all of this is that when a socket call fails, you
  1185. * should call tor_socket_errno <em>at most once</em> on the failing
  1186. * socket to get the error.
  1187. */
  1188. #if defined(MS_WINDOWS) && !defined(USE_BSOCKETS)
  1189. int
  1190. tor_socket_errno(int sock)
  1191. {
  1192. int optval, optvallen=sizeof(optval);
  1193. int err = WSAGetLastError();
  1194. if (err == WSAEWOULDBLOCK && sock >= 0) {
  1195. if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval, &optvallen))
  1196. return err;
  1197. if (optval)
  1198. return optval;
  1199. }
  1200. return err;
  1201. }
  1202. #endif
  1203. #if defined(MS_WINDOWS) && !defined(USE_BSOCKETS)
  1204. #define E(code, s) { code, (s " [" #code " ]") }
  1205. struct { int code; const char *msg; } windows_socket_errors[] = {
  1206. E(WSAEINTR, "Interrupted function call"),
  1207. E(WSAEACCES, "Permission denied"),
  1208. E(WSAEFAULT, "Bad address"),
  1209. E(WSAEINVAL, "Invalid argument"),
  1210. E(WSAEMFILE, "Too many open files"),
  1211. E(WSAEWOULDBLOCK, "Resource temporarily unavailable"),
  1212. E(WSAEINPROGRESS, "Operation now in progress"),
  1213. E(WSAEALREADY, "Operation already in progress"),
  1214. E(WSAENOTSOCK, "Socket operation on nonsocket"),
  1215. E(WSAEDESTADDRREQ, "Destination address required"),
  1216. E(WSAEMSGSIZE, "Message too long"),
  1217. E(WSAEPROTOTYPE, "Protocol wrong for socket"),
  1218. E(WSAENOPROTOOPT, "Bad protocol option"),
  1219. E(WSAEPROTONOSUPPORT, "Protocol not supported"),
  1220. E(WSAESOCKTNOSUPPORT, "Socket type not supported"),
  1221. /* What's the difference between NOTSUPP and NOSUPPORT? :) */
  1222. E(WSAEOPNOTSUPP, "Operation not supported"),
  1223. E(WSAEPFNOSUPPORT, "Protocol family not supported"),
  1224. E(WSAEAFNOSUPPORT, "Address family not supported by protocol family"),
  1225. E(WSAEADDRINUSE, "Address already in use"),
  1226. E(WSAEADDRNOTAVAIL, "Cannot assign requested address"),
  1227. E(WSAENETDOWN, "Network is down"),
  1228. E(WSAENETUNREACH, "Network is unreachable"),
  1229. E(WSAENETRESET, "Network dropped connection on reset"),
  1230. E(WSAECONNABORTED, "Software caused connection abort"),
  1231. E(WSAECONNRESET, "Connection reset by peer"),
  1232. E(WSAENOBUFS, "No buffer space available"),
  1233. E(WSAEISCONN, "Socket is already connected"),
  1234. E(WSAENOTCONN, "Socket is not connected"),
  1235. E(WSAESHUTDOWN, "Cannot send after socket shutdown"),
  1236. E(WSAETIMEDOUT, "Connection timed out"),
  1237. E(WSAECONNREFUSED, "Connection refused"),
  1238. E(WSAEHOSTDOWN, "Host is down"),
  1239. E(WSAEHOSTUNREACH, "No route to host"),
  1240. E(WSAEPROCLIM, "Too many processes"),
  1241. /* Yes, some of these start with WSA, not WSAE. No, I don't know why. */
  1242. E(WSASYSNOTREADY, "Network subsystem is unavailable"),
  1243. E(WSAVERNOTSUPPORTED, "Winsock.dll out of range"),
  1244. E(WSANOTINITIALISED, "Successful WSAStartup not yet performed"),
  1245. E(WSAEDISCON, "Graceful shutdown now in progress"),
  1246. #ifdef WSATYPE_NOT_FOUND
  1247. E(WSATYPE_NOT_FOUND, "Class type not found"),
  1248. #endif
  1249. E(WSAHOST_NOT_FOUND, "Host not found"),
  1250. E(WSATRY_AGAIN, "Nonauthoritative host not found"),
  1251. E(WSANO_RECOVERY, "This is a nonrecoverable error"),
  1252. E(WSANO_DATA, "Valid name, no data record of requested type)"),
  1253. /* There are some more error codes whose numeric values are marked
  1254. * <b>OS dependent</b>. They start with WSA_, apparently for the same
  1255. * reason that practitioners of some craft traditions deliberately
  1256. * introduce imperfections into their baskets and rugs "to allow the
  1257. * evil spirits to escape." If we catch them, then our binaries
  1258. * might not report consistent results across versions of Windows.
  1259. * Thus, I'm going to let them all fall through.
  1260. */
  1261. { -1, NULL },
  1262. };
  1263. /** There does not seem to be a strerror equivalent for winsock errors.
  1264. * Naturally, we have to roll our own.
  1265. */
  1266. const char *
  1267. tor_socket_strerror(int e)
  1268. {
  1269. int i;
  1270. for (i=0; windows_socket_errors[i].code >= 0; ++i) {
  1271. if (e == windows_socket_errors[i].code)
  1272. return windows_socket_errors[i].msg;
  1273. }
  1274. return strerror(e);
  1275. }
  1276. #endif
  1277. /** Called before we make any calls to network-related functions.
  1278. * (Some operating systems require their network libraries to be
  1279. * initialized.) */
  1280. int
  1281. network_init(void)
  1282. {
  1283. #ifdef MS_WINDOWS
  1284. /* This silly exercise is necessary before windows will allow
  1285. * gethostbyname to work. */
  1286. WSADATA WSAData;
  1287. int r;
  1288. r = WSAStartup(0x101,&WSAData);
  1289. if (r) {
  1290. log_warn(LD_NET,"Error initializing windows network layer: code was %d",r);
  1291. return -1;
  1292. }
  1293. /* WSAData.iMaxSockets might show the max sockets we're allowed to use.
  1294. * We might use it to complain if we're trying to be a server but have
  1295. * too few sockets available. */
  1296. #endif
  1297. return 0;
  1298. }