compat.c 53 KB

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