compat.c 71 KB

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