compat.c 72 KB

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