compat.c 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579
  1. /* Copyright (c) 2003-2004, Roger Dingledine
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2011, 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. * On Windows, when <b>blocking</b> is true, the maximum time that
  641. * is actually waited is 10 seconds, after which NULL is returned
  642. * and <b>locked_out</b> is set to 1.)
  643. */
  644. tor_lockfile_t *
  645. tor_lockfile_lock(const char *filename, int blocking, int *locked_out)
  646. {
  647. tor_lockfile_t *result;
  648. int fd;
  649. *locked_out = 0;
  650. log_info(LD_FS, "Locking \"%s\"", filename);
  651. fd = open(filename, O_RDWR|O_CREAT|O_TRUNC, 0600);
  652. if (fd < 0) {
  653. log_warn(LD_FS,"Couldn't open \"%s\" for locking: %s", filename,
  654. strerror(errno));
  655. return NULL;
  656. }
  657. #ifdef WIN32
  658. _lseek(fd, 0, SEEK_SET);
  659. if (_locking(fd, blocking ? _LK_LOCK : _LK_NBLCK, 1) < 0) {
  660. if (errno != EACCES && errno != EDEADLOCK)
  661. log_warn(LD_FS,"Couldn't lock \"%s\": %s", filename, strerror(errno));
  662. else
  663. *locked_out = 1;
  664. close(fd);
  665. return NULL;
  666. }
  667. #elif defined(HAVE_FLOCK)
  668. if (flock(fd, LOCK_EX|(blocking ? 0 : LOCK_NB)) < 0) {
  669. if (errno != EWOULDBLOCK)
  670. log_warn(LD_FS,"Couldn't lock \"%s\": %s", filename, strerror(errno));
  671. else
  672. *locked_out = 1;
  673. close(fd);
  674. return NULL;
  675. }
  676. #else
  677. {
  678. struct flock lock;
  679. memset(&lock, 0, sizeof(lock));
  680. lock.l_type = F_WRLCK;
  681. lock.l_whence = SEEK_SET;
  682. if (fcntl(fd, blocking ? F_SETLKW : F_SETLK, &lock) < 0) {
  683. if (errno != EACCES && errno != EAGAIN)
  684. log_warn(LD_FS, "Couldn't lock \"%s\": %s", filename, strerror(errno));
  685. else
  686. *locked_out = 1;
  687. close(fd);
  688. return NULL;
  689. }
  690. }
  691. #endif
  692. result = tor_malloc(sizeof(tor_lockfile_t));
  693. result->filename = tor_strdup(filename);
  694. result->fd = fd;
  695. return result;
  696. }
  697. /** Release the lock held as <b>lockfile</b>. */
  698. void
  699. tor_lockfile_unlock(tor_lockfile_t *lockfile)
  700. {
  701. tor_assert(lockfile);
  702. log_info(LD_FS, "Unlocking \"%s\"", lockfile->filename);
  703. #ifdef WIN32
  704. _lseek(lockfile->fd, 0, SEEK_SET);
  705. if (_locking(lockfile->fd, _LK_UNLCK, 1) < 0) {
  706. log_warn(LD_FS,"Error unlocking \"%s\": %s", lockfile->filename,
  707. strerror(errno));
  708. }
  709. #elif defined(HAVE_FLOCK)
  710. if (flock(lockfile->fd, LOCK_UN) < 0) {
  711. log_warn(LD_FS, "Error unlocking \"%s\": %s", lockfile->filename,
  712. strerror(errno));
  713. }
  714. #else
  715. /* Closing the lockfile is sufficient. */
  716. #endif
  717. close(lockfile->fd);
  718. lockfile->fd = -1;
  719. tor_free(lockfile->filename);
  720. tor_free(lockfile);
  721. }
  722. /* Some old versions of Unix didn't define constants for these values,
  723. * and instead expect you to say 0, 1, or 2. */
  724. #ifndef SEEK_CUR
  725. #define SEEK_CUR 1
  726. #endif
  727. #ifndef SEEK_END
  728. #define SEEK_END 2
  729. #endif
  730. /** Return the position of <b>fd</b> with respect to the start of the file. */
  731. off_t
  732. tor_fd_getpos(int fd)
  733. {
  734. #ifdef WIN32
  735. return (off_t) _lseek(fd, 0, SEEK_CUR);
  736. #else
  737. return (off_t) lseek(fd, 0, SEEK_CUR);
  738. #endif
  739. }
  740. /** Move <b>fd</b> to the end of the file. Return -1 on error, 0 on success. */
  741. int
  742. tor_fd_seekend(int fd)
  743. {
  744. #ifdef WIN32
  745. return _lseek(fd, 0, SEEK_END) < 0 ? -1 : 0;
  746. #else
  747. return lseek(fd, 0, SEEK_END) < 0 ? -1 : 0;
  748. #endif
  749. }
  750. #undef DEBUG_SOCKET_COUNTING
  751. #ifdef DEBUG_SOCKET_COUNTING
  752. /** A bitarray of all fds that should be passed to tor_socket_close(). Only
  753. * used if DEBUG_SOCKET_COUNTING is defined. */
  754. static bitarray_t *open_sockets = NULL;
  755. /** The size of <b>open_sockets</b>, in bits. */
  756. static int max_socket = -1;
  757. #endif
  758. /** Count of number of sockets currently open. (Undercounts sockets opened by
  759. * eventdns and libevent.) */
  760. static int n_sockets_open = 0;
  761. /** Mutex to protect open_sockets, max_socket, and n_sockets_open. */
  762. static tor_mutex_t *socket_accounting_mutex = NULL;
  763. static INLINE void
  764. socket_accounting_lock(void)
  765. {
  766. if (PREDICT_UNLIKELY(!socket_accounting_mutex))
  767. socket_accounting_mutex = tor_mutex_new();
  768. tor_mutex_acquire(socket_accounting_mutex);
  769. }
  770. static INLINE void
  771. socket_accounting_unlock(void)
  772. {
  773. tor_mutex_release(socket_accounting_mutex);
  774. }
  775. /** As close(), but guaranteed to work for sockets across platforms (including
  776. * Windows, where close()ing a socket doesn't work. Returns 0 on success, -1
  777. * on failure. */
  778. int
  779. tor_close_socket(int s)
  780. {
  781. int r = 0;
  782. /* On Windows, you have to call close() on fds returned by open(),
  783. * and closesocket() on fds returned by socket(). On Unix, everything
  784. * gets close()'d. We abstract this difference by always using
  785. * tor_close_socket to close sockets, and always using close() on
  786. * files.
  787. */
  788. #if defined(MS_WINDOWS)
  789. r = closesocket(s);
  790. #else
  791. r = close(s);
  792. #endif
  793. socket_accounting_lock();
  794. #ifdef DEBUG_SOCKET_COUNTING
  795. if (s > max_socket || ! bitarray_is_set(open_sockets, s)) {
  796. log_warn(LD_BUG, "Closing a socket (%d) that wasn't returned by tor_open_"
  797. "socket(), or that was already closed or something.", s);
  798. } else {
  799. tor_assert(open_sockets && s <= max_socket);
  800. bitarray_clear(open_sockets, s);
  801. }
  802. #endif
  803. if (r == 0) {
  804. --n_sockets_open;
  805. } else {
  806. int err = tor_socket_errno(-1);
  807. log_info(LD_NET, "Close returned an error: %s", tor_socket_strerror(err));
  808. #ifdef WIN32
  809. if (err != WSAENOTSOCK)
  810. --n_sockets_open;
  811. #else
  812. if (err != EBADF)
  813. --n_sockets_open;
  814. #endif
  815. r = -1;
  816. }
  817. if (n_sockets_open < 0)
  818. log_warn(LD_BUG, "Our socket count is below zero: %d. Please submit a "
  819. "bug report.", n_sockets_open);
  820. socket_accounting_unlock();
  821. return r;
  822. }
  823. #ifdef DEBUG_SOCKET_COUNTING
  824. /** Helper: if DEBUG_SOCKET_COUNTING is enabled, remember that <b>s</b> is
  825. * now an open socket. */
  826. static INLINE void
  827. mark_socket_open(int s)
  828. {
  829. if (s > max_socket) {
  830. if (max_socket == -1) {
  831. open_sockets = bitarray_init_zero(s+128);
  832. max_socket = s+128;
  833. } else {
  834. open_sockets = bitarray_expand(open_sockets, max_socket, s+128);
  835. max_socket = s+128;
  836. }
  837. }
  838. if (bitarray_is_set(open_sockets, s)) {
  839. log_warn(LD_BUG, "I thought that %d was already open, but socket() just "
  840. "gave it to me!", s);
  841. }
  842. bitarray_set(open_sockets, s);
  843. }
  844. #else
  845. #define mark_socket_open(s) STMT_NIL
  846. #endif
  847. /** As socket(), but counts the number of open sockets. */
  848. int
  849. tor_open_socket(int domain, int type, int protocol)
  850. {
  851. int s = socket(domain, type, protocol);
  852. if (s >= 0) {
  853. socket_accounting_lock();
  854. ++n_sockets_open;
  855. mark_socket_open(s);
  856. socket_accounting_unlock();
  857. }
  858. return s;
  859. }
  860. /** As socket(), but counts the number of open sockets. */
  861. int
  862. tor_accept_socket(int sockfd, struct sockaddr *addr, socklen_t *len)
  863. {
  864. int s = accept(sockfd, addr, len);
  865. if (s >= 0) {
  866. socket_accounting_lock();
  867. ++n_sockets_open;
  868. mark_socket_open(s);
  869. socket_accounting_unlock();
  870. }
  871. return s;
  872. }
  873. /** Return the number of sockets we currently have opened. */
  874. int
  875. get_n_open_sockets(void)
  876. {
  877. int n;
  878. socket_accounting_lock();
  879. n = n_sockets_open;
  880. socket_accounting_unlock();
  881. return n;
  882. }
  883. /** Turn <b>socket</b> into a nonblocking socket.
  884. */
  885. void
  886. set_socket_nonblocking(int socket)
  887. {
  888. #if defined(MS_WINDOWS)
  889. unsigned long nonblocking = 1;
  890. ioctlsocket(socket, FIONBIO, (unsigned long*) &nonblocking);
  891. #else
  892. fcntl(socket, F_SETFL, O_NONBLOCK);
  893. #endif
  894. }
  895. /**
  896. * Allocate a pair of connected sockets. (Like socketpair(family,
  897. * type,protocol,fd), but works on systems that don't have
  898. * socketpair.)
  899. *
  900. * Currently, only (AF_UNIX, SOCK_STREAM, 0) sockets are supported.
  901. *
  902. * Note that on systems without socketpair, this call will fail if
  903. * localhost is inaccessible (for example, if the networking
  904. * stack is down). And even if it succeeds, the socket pair will not
  905. * be able to read while localhost is down later (the socket pair may
  906. * even close, depending on OS-specific timeouts).
  907. *
  908. * Returns 0 on success and -errno on failure; do not rely on the value
  909. * of errno or WSAGetLastError().
  910. **/
  911. /* It would be nicer just to set errno, but that won't work for windows. */
  912. int
  913. tor_socketpair(int family, int type, int protocol, int fd[2])
  914. {
  915. //don't use win32 socketpairs (they are always bad)
  916. #if defined(HAVE_SOCKETPAIR) && !defined(MS_WINDOWS)
  917. int r;
  918. r = socketpair(family, type, protocol, fd);
  919. if (r == 0) {
  920. socket_accounting_lock();
  921. if (fd[0] >= 0) {
  922. ++n_sockets_open;
  923. mark_socket_open(fd[0]);
  924. }
  925. if (fd[1] >= 0) {
  926. ++n_sockets_open;
  927. mark_socket_open(fd[1]);
  928. }
  929. socket_accounting_unlock();
  930. }
  931. return r < 0 ? -errno : r;
  932. #else
  933. /* This socketpair does not work when localhost is down. So
  934. * it's really not the same thing at all. But it's close enough
  935. * for now, and really, when localhost is down sometimes, we
  936. * have other problems too.
  937. */
  938. int listener = -1;
  939. int connector = -1;
  940. int acceptor = -1;
  941. struct sockaddr_in listen_addr;
  942. struct sockaddr_in connect_addr;
  943. int size;
  944. int saved_errno = -1;
  945. if (protocol
  946. #ifdef AF_UNIX
  947. || family != AF_UNIX
  948. #endif
  949. ) {
  950. #ifdef MS_WINDOWS
  951. return -WSAEAFNOSUPPORT;
  952. #else
  953. return -EAFNOSUPPORT;
  954. #endif
  955. }
  956. if (!fd) {
  957. return -EINVAL;
  958. }
  959. listener = tor_open_socket(AF_INET, type, 0);
  960. if (listener < 0)
  961. return -tor_socket_errno(-1);
  962. memset(&listen_addr, 0, sizeof(listen_addr));
  963. listen_addr.sin_family = AF_INET;
  964. listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  965. listen_addr.sin_port = 0; /* kernel chooses port. */
  966. if (bind(listener, (struct sockaddr *) &listen_addr, sizeof (listen_addr))
  967. == -1)
  968. goto tidy_up_and_fail;
  969. if (listen(listener, 1) == -1)
  970. goto tidy_up_and_fail;
  971. connector = tor_open_socket(AF_INET, type, 0);
  972. if (connector < 0)
  973. goto tidy_up_and_fail;
  974. /* We want to find out the port number to connect to. */
  975. size = sizeof(connect_addr);
  976. if (getsockname(listener, (struct sockaddr *) &connect_addr, &size) == -1)
  977. goto tidy_up_and_fail;
  978. if (size != sizeof (connect_addr))
  979. goto abort_tidy_up_and_fail;
  980. if (connect(connector, (struct sockaddr *) &connect_addr,
  981. sizeof(connect_addr)) == -1)
  982. goto tidy_up_and_fail;
  983. size = sizeof(listen_addr);
  984. acceptor = tor_accept_socket(listener,
  985. (struct sockaddr *) &listen_addr, &size);
  986. if (acceptor < 0)
  987. goto tidy_up_and_fail;
  988. if (size != sizeof(listen_addr))
  989. goto abort_tidy_up_and_fail;
  990. tor_close_socket(listener);
  991. /* Now check we are talking to ourself by matching port and host on the
  992. two sockets. */
  993. if (getsockname(connector, (struct sockaddr *) &connect_addr, &size) == -1)
  994. goto tidy_up_and_fail;
  995. if (size != sizeof (connect_addr)
  996. || listen_addr.sin_family != connect_addr.sin_family
  997. || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
  998. || listen_addr.sin_port != connect_addr.sin_port) {
  999. goto abort_tidy_up_and_fail;
  1000. }
  1001. fd[0] = connector;
  1002. fd[1] = acceptor;
  1003. return 0;
  1004. abort_tidy_up_and_fail:
  1005. #ifdef MS_WINDOWS
  1006. saved_errno = WSAECONNABORTED;
  1007. #else
  1008. saved_errno = ECONNABORTED; /* I hope this is portable and appropriate. */
  1009. #endif
  1010. tidy_up_and_fail:
  1011. if (saved_errno < 0)
  1012. saved_errno = errno;
  1013. if (listener != -1)
  1014. tor_close_socket(listener);
  1015. if (connector != -1)
  1016. tor_close_socket(connector);
  1017. if (acceptor != -1)
  1018. tor_close_socket(acceptor);
  1019. return -saved_errno;
  1020. #endif
  1021. }
  1022. #define ULIMIT_BUFFER 32 /* keep 32 extra fd's beyond _ConnLimit */
  1023. /** Learn the maximum allowed number of file descriptors. (Some systems
  1024. * have a low soft limit.
  1025. *
  1026. * We compute this by finding the largest number that we can use.
  1027. * If we can't find a number greater than or equal to <b>limit</b>,
  1028. * then we fail: return -1.
  1029. *
  1030. * Otherwise, return 0 and store the maximum we found inside <b>max_out</b>.*/
  1031. int
  1032. set_max_file_descriptors(rlim_t limit, int *max_out)
  1033. {
  1034. /* Define some maximum connections values for systems where we cannot
  1035. * automatically determine a limit. Re Cygwin, see
  1036. * http://archives.seul.org/or/talk/Aug-2006/msg00210.html
  1037. * For an iPhone, 9999 should work. For Windows and all other unknown
  1038. * systems we use 15000 as the default. */
  1039. #ifndef HAVE_GETRLIMIT
  1040. #if defined(CYGWIN) || defined(__CYGWIN__)
  1041. const char *platform = "Cygwin";
  1042. const unsigned long MAX_CONNECTIONS = 3200;
  1043. #elif defined(MS_WINDOWS)
  1044. const char *platform = "Windows";
  1045. const unsigned long MAX_CONNECTIONS = 15000;
  1046. #else
  1047. const char *platform = "unknown platforms with no getrlimit()";
  1048. const unsigned long MAX_CONNECTIONS = 15000;
  1049. #endif
  1050. log_fn(LOG_INFO, LD_NET,
  1051. "This platform is missing getrlimit(). Proceeding.");
  1052. if (limit > MAX_CONNECTIONS) {
  1053. log_warn(LD_CONFIG,
  1054. "We do not support more than %lu file descriptors "
  1055. "on %s. Tried to raise to %lu.",
  1056. (unsigned long)MAX_CONNECTIONS, platform, (unsigned long)limit);
  1057. return -1;
  1058. }
  1059. limit = MAX_CONNECTIONS;
  1060. #else /* HAVE_GETRLIMIT */
  1061. struct rlimit rlim;
  1062. tor_assert(limit > 0);
  1063. if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) {
  1064. log_warn(LD_NET, "Could not get maximum number of file descriptors: %s",
  1065. strerror(errno));
  1066. return -1;
  1067. }
  1068. if (rlim.rlim_max < limit) {
  1069. log_warn(LD_CONFIG,"We need %lu file descriptors available, and we're "
  1070. "limited to %lu. Please change your ulimit -n.",
  1071. (unsigned long)limit, (unsigned long)rlim.rlim_max);
  1072. return -1;
  1073. }
  1074. if (rlim.rlim_max > rlim.rlim_cur) {
  1075. log_info(LD_NET,"Raising max file descriptors from %lu to %lu.",
  1076. (unsigned long)rlim.rlim_cur, (unsigned long)rlim.rlim_max);
  1077. }
  1078. rlim.rlim_cur = rlim.rlim_max;
  1079. if (setrlimit(RLIMIT_NOFILE, &rlim) != 0) {
  1080. int bad = 1;
  1081. #ifdef OPEN_MAX
  1082. if (errno == EINVAL && OPEN_MAX < rlim.rlim_cur) {
  1083. /* On some platforms, OPEN_MAX is the real limit, and getrlimit() is
  1084. * full of nasty lies. I'm looking at you, OSX 10.5.... */
  1085. rlim.rlim_cur = OPEN_MAX;
  1086. if (setrlimit(RLIMIT_NOFILE, &rlim) == 0) {
  1087. if (rlim.rlim_cur < (rlim_t)limit) {
  1088. log_warn(LD_CONFIG, "We are limited to %lu file descriptors by "
  1089. "OPEN_MAX, and ConnLimit is %lu. Changing ConnLimit; sorry.",
  1090. (unsigned long)OPEN_MAX, (unsigned long)limit);
  1091. } else {
  1092. log_info(LD_CONFIG, "Dropped connection limit to OPEN_MAX (%lu); "
  1093. "Apparently, %lu was too high and rlimit lied to us.",
  1094. (unsigned long)OPEN_MAX, (unsigned long)rlim.rlim_max);
  1095. }
  1096. bad = 0;
  1097. }
  1098. }
  1099. #endif /* OPEN_MAX */
  1100. if (bad) {
  1101. log_warn(LD_CONFIG,"Couldn't set maximum number of file descriptors: %s",
  1102. strerror(errno));
  1103. return -1;
  1104. }
  1105. }
  1106. /* leave some overhead for logs, etc, */
  1107. limit = rlim.rlim_cur;
  1108. #endif /* HAVE_GETRLIMIT */
  1109. if (limit < ULIMIT_BUFFER) {
  1110. log_warn(LD_CONFIG,
  1111. "ConnLimit must be at least %d. Failing.", ULIMIT_BUFFER);
  1112. return -1;
  1113. }
  1114. if (limit > INT_MAX)
  1115. limit = INT_MAX;
  1116. tor_assert(max_out);
  1117. *max_out = (int)limit - ULIMIT_BUFFER;
  1118. return 0;
  1119. }
  1120. #ifndef MS_WINDOWS
  1121. /** Log details of current user and group credentials. Return 0 on
  1122. * success. Logs and return -1 on failure.
  1123. */
  1124. static int
  1125. log_credential_status(void)
  1126. {
  1127. #define CREDENTIAL_LOG_LEVEL LOG_INFO
  1128. /* Real, effective and saved UIDs */
  1129. uid_t ruid, euid, suid;
  1130. /* Read, effective and saved GIDs */
  1131. gid_t rgid, egid, sgid;
  1132. /* Supplementary groups */
  1133. gid_t sup_gids[NGROUPS_MAX + 1];
  1134. /* Number of supplementary groups */
  1135. int ngids;
  1136. /* log UIDs */
  1137. #ifdef HAVE_GETRESUID
  1138. if (getresuid(&ruid, &euid, &suid) != 0 ) {
  1139. log_warn(LD_GENERAL, "Error getting changed UIDs: %s", strerror(errno));
  1140. return -1;
  1141. } else {
  1142. log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
  1143. "UID is %u (real), %u (effective), %u (saved)",
  1144. (unsigned)ruid, (unsigned)euid, (unsigned)suid);
  1145. }
  1146. #else
  1147. /* getresuid is not present on MacOS X, so we can't get the saved (E)UID */
  1148. ruid = getuid();
  1149. euid = geteuid();
  1150. (void)suid;
  1151. log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
  1152. "UID is %u (real), %u (effective), unknown (saved)",
  1153. (unsigned)ruid, (unsigned)euid);
  1154. #endif
  1155. /* log GIDs */
  1156. #ifdef HAVE_GETRESGID
  1157. if (getresgid(&rgid, &egid, &sgid) != 0 ) {
  1158. log_warn(LD_GENERAL, "Error getting changed GIDs: %s", strerror(errno));
  1159. return -1;
  1160. } else {
  1161. log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
  1162. "GID is %u (real), %u (effective), %u (saved)",
  1163. (unsigned)rgid, (unsigned)egid, (unsigned)sgid);
  1164. }
  1165. #else
  1166. /* getresgid is not present on MacOS X, so we can't get the saved (E)GID */
  1167. rgid = getgid();
  1168. egid = getegid();
  1169. (void)sgid;
  1170. log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
  1171. "GID is %u (real), %u (effective), unknown (saved)",
  1172. (unsigned)rgid, (unsigned)egid);
  1173. #endif
  1174. /* log supplementary groups */
  1175. if ((ngids = getgroups(NGROUPS_MAX + 1, sup_gids)) < 0) {
  1176. log_warn(LD_GENERAL, "Error getting supplementary GIDs: %s",
  1177. strerror(errno));
  1178. return -1;
  1179. } else {
  1180. int i, retval = 0;
  1181. char *strgid;
  1182. char *s = NULL;
  1183. smartlist_t *elts = smartlist_create();
  1184. for (i = 0; i<ngids; i++) {
  1185. strgid = tor_malloc(11);
  1186. if (tor_snprintf(strgid, 11, "%u", (unsigned)sup_gids[i]) < 0) {
  1187. log_warn(LD_GENERAL, "Error printing supplementary GIDs");
  1188. tor_free(strgid);
  1189. retval = -1;
  1190. goto error;
  1191. }
  1192. smartlist_add(elts, strgid);
  1193. }
  1194. s = smartlist_join_strings(elts, " ", 0, NULL);
  1195. log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL, "Supplementary groups are: %s",s);
  1196. error:
  1197. tor_free(s);
  1198. SMARTLIST_FOREACH(elts, char *, cp,
  1199. {
  1200. tor_free(cp);
  1201. });
  1202. smartlist_free(elts);
  1203. return retval;
  1204. }
  1205. return 0;
  1206. }
  1207. #endif
  1208. /** Call setuid and setgid to run as <b>user</b> and switch to their
  1209. * primary group. Return 0 on success. On failure, log and return -1.
  1210. */
  1211. int
  1212. switch_id(const char *user)
  1213. {
  1214. #ifndef MS_WINDOWS
  1215. struct passwd *pw = NULL;
  1216. uid_t old_uid;
  1217. gid_t old_gid;
  1218. static int have_already_switched_id = 0;
  1219. tor_assert(user);
  1220. if (have_already_switched_id)
  1221. return 0;
  1222. /* Log the initial credential state */
  1223. if (log_credential_status())
  1224. return -1;
  1225. log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL, "Changing user and groups");
  1226. /* Get old UID/GID to check if we changed correctly */
  1227. old_uid = getuid();
  1228. old_gid = getgid();
  1229. /* Lookup the user and group information, if we have a problem, bail out. */
  1230. pw = getpwnam(user);
  1231. if (pw == NULL) {
  1232. log_warn(LD_CONFIG, "Error setting configured user: %s not found", user);
  1233. return -1;
  1234. }
  1235. /* Properly switch egid,gid,euid,uid here or bail out */
  1236. if (setgroups(1, &pw->pw_gid)) {
  1237. log_warn(LD_GENERAL, "Error setting groups to gid %d: \"%s\".",
  1238. (int)pw->pw_gid, strerror(errno));
  1239. if (old_uid == pw->pw_uid) {
  1240. log_warn(LD_GENERAL, "Tor is already running as %s. You do not need "
  1241. "the \"User\" option if you are already running as the user "
  1242. "you want to be. (If you did not set the User option in your "
  1243. "torrc, check whether it was specified on the command line "
  1244. "by a startup script.)", user);
  1245. } else {
  1246. log_warn(LD_GENERAL, "If you set the \"User\" option, you must start Tor"
  1247. " as root.");
  1248. }
  1249. return -1;
  1250. }
  1251. if (setegid(pw->pw_gid)) {
  1252. log_warn(LD_GENERAL, "Error setting egid to %d: %s",
  1253. (int)pw->pw_gid, strerror(errno));
  1254. return -1;
  1255. }
  1256. if (setgid(pw->pw_gid)) {
  1257. log_warn(LD_GENERAL, "Error setting gid to %d: %s",
  1258. (int)pw->pw_gid, strerror(errno));
  1259. return -1;
  1260. }
  1261. if (setuid(pw->pw_uid)) {
  1262. log_warn(LD_GENERAL, "Error setting configured uid to %s (%d): %s",
  1263. user, (int)pw->pw_uid, strerror(errno));
  1264. return -1;
  1265. }
  1266. if (seteuid(pw->pw_uid)) {
  1267. log_warn(LD_GENERAL, "Error setting configured euid to %s (%d): %s",
  1268. user, (int)pw->pw_uid, strerror(errno));
  1269. return -1;
  1270. }
  1271. /* This is how OpenBSD rolls:
  1272. if (setgroups(1, &pw->pw_gid) || setegid(pw->pw_gid) ||
  1273. setgid(pw->pw_gid) || setuid(pw->pw_uid) || seteuid(pw->pw_uid)) {
  1274. setgid(pw->pw_gid) || seteuid(pw->pw_uid) || setuid(pw->pw_uid)) {
  1275. log_warn(LD_GENERAL, "Error setting configured UID/GID: %s",
  1276. strerror(errno));
  1277. return -1;
  1278. }
  1279. */
  1280. /* We've properly switched egid, gid, euid, uid, and supplementary groups if
  1281. * we're here. */
  1282. #if !defined(CYGWIN) && !defined(__CYGWIN__)
  1283. /* If we tried to drop privilege to a group/user other than root, attempt to
  1284. * restore root (E)(U|G)ID, and abort if the operation succeeds */
  1285. /* Only check for privilege dropping if we were asked to be non-root */
  1286. if (pw->pw_uid) {
  1287. /* Try changing GID/EGID */
  1288. if (pw->pw_gid != old_gid &&
  1289. (setgid(old_gid) != -1 || setegid(old_gid) != -1)) {
  1290. log_warn(LD_GENERAL, "Was able to restore group credentials even after "
  1291. "switching GID: this means that the setgid code didn't work.");
  1292. return -1;
  1293. }
  1294. /* Try changing UID/EUID */
  1295. if (pw->pw_uid != old_uid &&
  1296. (setuid(old_uid) != -1 || seteuid(old_uid) != -1)) {
  1297. log_warn(LD_GENERAL, "Was able to restore user credentials even after "
  1298. "switching UID: this means that the setuid code didn't work.");
  1299. return -1;
  1300. }
  1301. }
  1302. #endif
  1303. /* Check what really happened */
  1304. if (log_credential_status()) {
  1305. return -1;
  1306. }
  1307. have_already_switched_id = 1; /* mark success so we never try again */
  1308. #if defined(__linux__) && defined(HAVE_SYS_PRCTL_H) && defined(HAVE_PRCTL)
  1309. #ifdef PR_SET_DUMPABLE
  1310. if (pw->pw_uid) {
  1311. /* Re-enable core dumps if we're not running as root. */
  1312. log_info(LD_CONFIG, "Re-enabling coredumps");
  1313. if (prctl(PR_SET_DUMPABLE, 1)) {
  1314. log_warn(LD_CONFIG, "Unable to re-enable coredumps: %s",strerror(errno));
  1315. }
  1316. }
  1317. #endif
  1318. #endif
  1319. return 0;
  1320. #else
  1321. (void)user;
  1322. log_warn(LD_CONFIG,
  1323. "User specified but switching users is unsupported on your OS.");
  1324. return -1;
  1325. #endif
  1326. }
  1327. #ifdef HAVE_PWD_H
  1328. /** Allocate and return a string containing the home directory for the
  1329. * user <b>username</b>. Only works on posix-like systems. */
  1330. char *
  1331. get_user_homedir(const char *username)
  1332. {
  1333. struct passwd *pw;
  1334. tor_assert(username);
  1335. if (!(pw = getpwnam(username))) {
  1336. log_err(LD_CONFIG,"User \"%s\" not found.", username);
  1337. return NULL;
  1338. }
  1339. return tor_strdup(pw->pw_dir);
  1340. }
  1341. #endif
  1342. /** Set *addr to the IP address (in dotted-quad notation) stored in c.
  1343. * Return 1 on success, 0 if c is badly formatted. (Like inet_aton(c,addr),
  1344. * but works on Windows and Solaris.)
  1345. */
  1346. int
  1347. tor_inet_aton(const char *str, struct in_addr* addr)
  1348. {
  1349. unsigned a,b,c,d;
  1350. char more;
  1351. if (tor_sscanf(str, "%3u.%3u.%3u.%3u%c", &a,&b,&c,&d,&more) != 4)
  1352. return 0;
  1353. if (a > 255) return 0;
  1354. if (b > 255) return 0;
  1355. if (c > 255) return 0;
  1356. if (d > 255) return 0;
  1357. addr->s_addr = htonl((a<<24) | (b<<16) | (c<<8) | d);
  1358. return 1;
  1359. }
  1360. /** Given <b>af</b>==AF_INET and <b>src</b> a struct in_addr, or
  1361. * <b>af</b>==AF_INET6 and <b>src</b> a struct in6_addr, try to format the
  1362. * address and store it in the <b>len</b>-byte buffer <b>dst</b>. Returns
  1363. * <b>dst</b> on success, NULL on failure.
  1364. *
  1365. * (Like inet_ntop(af,src,dst,len), but works on platforms that don't have it:
  1366. * Tor sometimes needs to format ipv6 addresses even on platforms without ipv6
  1367. * support.) */
  1368. const char *
  1369. tor_inet_ntop(int af, const void *src, char *dst, size_t len)
  1370. {
  1371. if (af == AF_INET) {
  1372. if (tor_inet_ntoa(src, dst, len) < 0)
  1373. return NULL;
  1374. else
  1375. return dst;
  1376. } else if (af == AF_INET6) {
  1377. const struct in6_addr *addr = src;
  1378. char buf[64], *cp;
  1379. int longestGapLen = 0, longestGapPos = -1, i,
  1380. curGapPos = -1, curGapLen = 0;
  1381. uint16_t words[8];
  1382. for (i = 0; i < 8; ++i) {
  1383. words[i] = (((uint16_t)addr->s6_addr[2*i])<<8) + addr->s6_addr[2*i+1];
  1384. }
  1385. if (words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0 &&
  1386. words[4] == 0 && ((words[5] == 0 && words[6] && words[7]) ||
  1387. (words[5] == 0xffff))) {
  1388. /* This is an IPv4 address. */
  1389. if (words[5] == 0) {
  1390. tor_snprintf(buf, sizeof(buf), "::%d.%d.%d.%d",
  1391. addr->s6_addr[12], addr->s6_addr[13],
  1392. addr->s6_addr[14], addr->s6_addr[15]);
  1393. } else {
  1394. tor_snprintf(buf, sizeof(buf), "::%x:%d.%d.%d.%d", words[5],
  1395. addr->s6_addr[12], addr->s6_addr[13],
  1396. addr->s6_addr[14], addr->s6_addr[15]);
  1397. }
  1398. if (strlen(buf) > len)
  1399. return NULL;
  1400. strlcpy(dst, buf, len);
  1401. return dst;
  1402. }
  1403. i = 0;
  1404. while (i < 8) {
  1405. if (words[i] == 0) {
  1406. curGapPos = i++;
  1407. curGapLen = 1;
  1408. while (i<8 && words[i] == 0) {
  1409. ++i; ++curGapLen;
  1410. }
  1411. if (curGapLen > longestGapLen) {
  1412. longestGapPos = curGapPos;
  1413. longestGapLen = curGapLen;
  1414. }
  1415. } else {
  1416. ++i;
  1417. }
  1418. }
  1419. if (longestGapLen<=1)
  1420. longestGapPos = -1;
  1421. cp = buf;
  1422. for (i = 0; i < 8; ++i) {
  1423. if (words[i] == 0 && longestGapPos == i) {
  1424. if (i == 0)
  1425. *cp++ = ':';
  1426. *cp++ = ':';
  1427. while (i < 8 && words[i] == 0)
  1428. ++i;
  1429. --i; /* to compensate for loop increment. */
  1430. } else {
  1431. tor_snprintf(cp, sizeof(buf)-(cp-buf), "%x", (unsigned)words[i]);
  1432. cp += strlen(cp);
  1433. if (i != 7)
  1434. *cp++ = ':';
  1435. }
  1436. }
  1437. *cp = '\0';
  1438. if (strlen(buf) > len)
  1439. return NULL;
  1440. strlcpy(dst, buf, len);
  1441. return dst;
  1442. } else {
  1443. return NULL;
  1444. }
  1445. }
  1446. /** Given <b>af</b>==AF_INET or <b>af</b>==AF_INET6, and a string <b>src</b>
  1447. * encoding an IPv4 address or IPv6 address correspondingly, try to parse the
  1448. * address and store the result in <b>dst</b> (which must have space for a
  1449. * struct in_addr or a struct in6_addr, as appropriate). Return 1 on success,
  1450. * 0 on a bad parse, and -1 on a bad <b>af</b>.
  1451. *
  1452. * (Like inet_pton(af,src,dst) but works on platforms that don't have it: Tor
  1453. * sometimes needs to format ipv6 addresses even on platforms without ipv6
  1454. * support.) */
  1455. int
  1456. tor_inet_pton(int af, const char *src, void *dst)
  1457. {
  1458. if (af == AF_INET) {
  1459. return tor_inet_aton(src, dst);
  1460. } else if (af == AF_INET6) {
  1461. struct in6_addr *out = dst;
  1462. uint16_t words[8];
  1463. int gapPos = -1, i, setWords=0;
  1464. const char *dot = strchr(src, '.');
  1465. const char *eow; /* end of words. */
  1466. if (dot == src)
  1467. return 0;
  1468. else if (!dot)
  1469. eow = src+strlen(src);
  1470. else {
  1471. unsigned byte1,byte2,byte3,byte4;
  1472. char more;
  1473. for (eow = dot-1; eow >= src && TOR_ISDIGIT(*eow); --eow)
  1474. ;
  1475. ++eow;
  1476. /* We use "scanf" because some platform inet_aton()s are too lax
  1477. * about IPv4 addresses of the form "1.2.3" */
  1478. if (tor_sscanf(eow, "%3u.%3u.%3u.%3u%c",
  1479. &byte1,&byte2,&byte3,&byte4,&more) != 4)
  1480. return 0;
  1481. if (byte1 > 255 || byte2 > 255 || byte3 > 255 || byte4 > 255)
  1482. return 0;
  1483. words[6] = (byte1<<8) | byte2;
  1484. words[7] = (byte3<<8) | byte4;
  1485. setWords += 2;
  1486. }
  1487. i = 0;
  1488. while (src < eow) {
  1489. if (i > 7)
  1490. return 0;
  1491. if (TOR_ISXDIGIT(*src)) {
  1492. char *next;
  1493. long r = strtol(src, &next, 16);
  1494. if (next > 4+src)
  1495. return 0;
  1496. if (next == src)
  1497. return 0;
  1498. if (r<0 || r>65536)
  1499. return 0;
  1500. words[i++] = (uint16_t)r;
  1501. setWords++;
  1502. src = next;
  1503. if (*src != ':' && src != eow)
  1504. return 0;
  1505. ++src;
  1506. } else if (*src == ':' && i > 0 && gapPos==-1) {
  1507. gapPos = i;
  1508. ++src;
  1509. } else if (*src == ':' && i == 0 && src[1] == ':' && gapPos==-1) {
  1510. gapPos = i;
  1511. src += 2;
  1512. } else {
  1513. return 0;
  1514. }
  1515. }
  1516. if (setWords > 8 ||
  1517. (setWords == 8 && gapPos != -1) ||
  1518. (setWords < 8 && gapPos == -1))
  1519. return 0;
  1520. if (gapPos >= 0) {
  1521. int nToMove = setWords - (dot ? 2 : 0) - gapPos;
  1522. int gapLen = 8 - setWords;
  1523. tor_assert(nToMove >= 0);
  1524. memmove(&words[gapPos+gapLen], &words[gapPos],
  1525. sizeof(uint16_t)*nToMove);
  1526. memset(&words[gapPos], 0, sizeof(uint16_t)*gapLen);
  1527. }
  1528. for (i = 0; i < 8; ++i) {
  1529. out->s6_addr[2*i ] = words[i] >> 8;
  1530. out->s6_addr[2*i+1] = words[i] & 0xff;
  1531. }
  1532. return 1;
  1533. } else {
  1534. return -1;
  1535. }
  1536. }
  1537. /** Similar behavior to Unix gethostbyname: resolve <b>name</b>, and set
  1538. * *<b>addr</b> to the proper IP address, in host byte order. Returns 0
  1539. * on success, -1 on failure; 1 on transient failure.
  1540. *
  1541. * (This function exists because standard windows gethostbyname
  1542. * doesn't treat raw IP addresses properly.)
  1543. */
  1544. int
  1545. tor_lookup_hostname(const char *name, uint32_t *addr)
  1546. {
  1547. tor_addr_t myaddr;
  1548. int ret;
  1549. if ((ret = tor_addr_lookup(name, AF_INET, &myaddr)))
  1550. return ret;
  1551. if (tor_addr_family(&myaddr) == AF_INET) {
  1552. *addr = tor_addr_to_ipv4h(&myaddr);
  1553. return ret;
  1554. }
  1555. return -1;
  1556. }
  1557. /** Initialize the insecure libc RNG. */
  1558. void
  1559. tor_init_weak_random(unsigned seed)
  1560. {
  1561. #ifdef MS_WINDOWS
  1562. srand(seed);
  1563. #else
  1564. srandom(seed);
  1565. #endif
  1566. }
  1567. /** Return a randomly chosen value in the range 0..TOR_RAND_MAX. This
  1568. * entropy will not be cryptographically strong; do not rely on it
  1569. * for anything an adversary should not be able to predict. */
  1570. long
  1571. tor_weak_random(void)
  1572. {
  1573. #ifdef MS_WINDOWS
  1574. return rand();
  1575. #else
  1576. return random();
  1577. #endif
  1578. }
  1579. /** Hold the result of our call to <b>uname</b>. */
  1580. static char uname_result[256];
  1581. /** True iff uname_result is set. */
  1582. static int uname_result_is_set = 0;
  1583. /** Return a pointer to a description of our platform.
  1584. */
  1585. const char *
  1586. get_uname(void)
  1587. {
  1588. #ifdef HAVE_UNAME
  1589. struct utsname u;
  1590. #endif
  1591. if (!uname_result_is_set) {
  1592. #ifdef HAVE_UNAME
  1593. if (uname(&u) != -1) {
  1594. /* (Linux says 0 is success, Solaris says 1 is success) */
  1595. tor_snprintf(uname_result, sizeof(uname_result), "%s %s",
  1596. u.sysname, u.machine);
  1597. } else
  1598. #endif
  1599. {
  1600. #ifdef MS_WINDOWS
  1601. OSVERSIONINFOEX info;
  1602. int i;
  1603. const char *plat = NULL;
  1604. const char *extra = NULL;
  1605. char acsd[MAX_PATH] = {0};
  1606. static struct {
  1607. unsigned major; unsigned minor; const char *version;
  1608. } win_version_table[] = {
  1609. { 6, 1, "Windows 7" },
  1610. { 6, 0, "Windows Vista" },
  1611. { 5, 2, "Windows Server 2003" },
  1612. { 5, 1, "Windows XP" },
  1613. { 5, 0, "Windows 2000" },
  1614. /* { 4, 0, "Windows NT 4.0" }, */
  1615. { 4, 90, "Windows Me" },
  1616. { 4, 10, "Windows 98" },
  1617. /* { 4, 0, "Windows 95" } */
  1618. { 3, 51, "Windows NT 3.51" },
  1619. { 0, 0, NULL }
  1620. };
  1621. memset(&info, 0, sizeof(info));
  1622. info.dwOSVersionInfoSize = sizeof(info);
  1623. if (! GetVersionEx((LPOSVERSIONINFO)&info)) {
  1624. strlcpy(uname_result, "Bizarre version of Windows where GetVersionEx"
  1625. " doesn't work.", sizeof(uname_result));
  1626. uname_result_is_set = 1;
  1627. return uname_result;
  1628. }
  1629. #ifdef UNICODE
  1630. wcstombs(acsd, info.szCSDVersion, MAX_PATH);
  1631. #else
  1632. strlcpy(acsd, info.szCSDVersion, sizeof(acsd));
  1633. #endif
  1634. if (info.dwMajorVersion == 4 && info.dwMinorVersion == 0) {
  1635. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  1636. plat = "Windows NT 4.0";
  1637. else
  1638. plat = "Windows 95";
  1639. if (acsd[1] == 'B')
  1640. extra = "OSR2 (B)";
  1641. else if (acsd[1] == 'C')
  1642. extra = "OSR2 (C)";
  1643. } else {
  1644. for (i=0; win_version_table[i].major>0; ++i) {
  1645. if (win_version_table[i].major == info.dwMajorVersion &&
  1646. win_version_table[i].minor == info.dwMinorVersion) {
  1647. plat = win_version_table[i].version;
  1648. break;
  1649. }
  1650. }
  1651. }
  1652. if (plat && !strcmp(plat, "Windows 98")) {
  1653. if (acsd[1] == 'A')
  1654. extra = "SE (A)";
  1655. else if (acsd[1] == 'B')
  1656. extra = "SE (B)";
  1657. }
  1658. if (plat) {
  1659. if (!extra)
  1660. extra = acsd;
  1661. tor_snprintf(uname_result, sizeof(uname_result), "%s %s",
  1662. plat, extra);
  1663. } else {
  1664. if (info.dwMajorVersion > 6 ||
  1665. (info.dwMajorVersion==6 && info.dwMinorVersion>1))
  1666. tor_snprintf(uname_result, sizeof(uname_result),
  1667. "Very recent version of Windows [major=%d,minor=%d] %s",
  1668. (int)info.dwMajorVersion,(int)info.dwMinorVersion,
  1669. acsd);
  1670. else
  1671. tor_snprintf(uname_result, sizeof(uname_result),
  1672. "Unrecognized version of Windows [major=%d,minor=%d] %s",
  1673. (int)info.dwMajorVersion,(int)info.dwMinorVersion,
  1674. acsd);
  1675. }
  1676. #if !defined (WINCE)
  1677. #ifdef VER_SUITE_BACKOFFICE
  1678. if (info.wProductType == VER_NT_DOMAIN_CONTROLLER) {
  1679. strlcat(uname_result, " [domain controller]", sizeof(uname_result));
  1680. } else if (info.wProductType == VER_NT_SERVER) {
  1681. strlcat(uname_result, " [server]", sizeof(uname_result));
  1682. } else if (info.wProductType == VER_NT_WORKSTATION) {
  1683. strlcat(uname_result, " [workstation]", sizeof(uname_result));
  1684. }
  1685. #endif
  1686. #endif
  1687. #else
  1688. strlcpy(uname_result, "Unknown platform", sizeof(uname_result));
  1689. #endif
  1690. }
  1691. uname_result_is_set = 1;
  1692. }
  1693. return uname_result;
  1694. }
  1695. /*
  1696. * Process control
  1697. */
  1698. #if defined(USE_PTHREADS)
  1699. /** Wraps a void (*)(void*) function and its argument so we can
  1700. * invoke them in a way pthreads would expect.
  1701. */
  1702. typedef struct tor_pthread_data_t {
  1703. void (*func)(void *);
  1704. void *data;
  1705. } tor_pthread_data_t;
  1706. /** Given a tor_pthread_data_t <b>_data</b>, call _data-&gt;func(d-&gt;data)
  1707. * and free _data. Used to make sure we can call functions the way pthread
  1708. * expects. */
  1709. static void *
  1710. tor_pthread_helper_fn(void *_data)
  1711. {
  1712. tor_pthread_data_t *data = _data;
  1713. void (*func)(void*);
  1714. void *arg;
  1715. /* mask signals to worker threads to avoid SIGPIPE, etc */
  1716. sigset_t sigs;
  1717. /* We're in a subthread; don't handle any signals here. */
  1718. sigfillset(&sigs);
  1719. pthread_sigmask(SIG_SETMASK, &sigs, NULL);
  1720. func = data->func;
  1721. arg = data->data;
  1722. tor_free(_data);
  1723. func(arg);
  1724. return NULL;
  1725. }
  1726. #endif
  1727. /** Minimalist interface to run a void function in the background. On
  1728. * Unix calls fork, on win32 calls beginthread. Returns -1 on failure.
  1729. * func should not return, but rather should call spawn_exit.
  1730. *
  1731. * NOTE: if <b>data</b> is used, it should not be allocated on the stack,
  1732. * since in a multithreaded environment, there is no way to be sure that
  1733. * the caller's stack will still be around when the called function is
  1734. * running.
  1735. */
  1736. int
  1737. spawn_func(void (*func)(void *), void *data)
  1738. {
  1739. #if defined(USE_WIN32_THREADS)
  1740. int rv;
  1741. rv = (int)_beginthread(func, 0, data);
  1742. if (rv == (int)-1)
  1743. return -1;
  1744. return 0;
  1745. #elif defined(USE_PTHREADS)
  1746. pthread_t thread;
  1747. tor_pthread_data_t *d;
  1748. d = tor_malloc(sizeof(tor_pthread_data_t));
  1749. d->data = data;
  1750. d->func = func;
  1751. if (pthread_create(&thread,NULL,tor_pthread_helper_fn,d))
  1752. return -1;
  1753. if (pthread_detach(thread))
  1754. return -1;
  1755. return 0;
  1756. #else
  1757. pid_t pid;
  1758. pid = fork();
  1759. if (pid<0)
  1760. return -1;
  1761. if (pid==0) {
  1762. /* Child */
  1763. func(data);
  1764. tor_assert(0); /* Should never reach here. */
  1765. return 0; /* suppress "control-reaches-end-of-non-void" warning. */
  1766. } else {
  1767. /* Parent */
  1768. return 0;
  1769. }
  1770. #endif
  1771. }
  1772. /** End the current thread/process.
  1773. */
  1774. void
  1775. spawn_exit(void)
  1776. {
  1777. #if defined(USE_WIN32_THREADS)
  1778. _endthread();
  1779. //we should never get here. my compiler thinks that _endthread returns, this
  1780. //is an attempt to fool it.
  1781. tor_assert(0);
  1782. _exit(0);
  1783. #elif defined(USE_PTHREADS)
  1784. pthread_exit(NULL);
  1785. #else
  1786. /* http://www.erlenstar.demon.co.uk/unix/faq_2.html says we should
  1787. * call _exit, not exit, from child processes. */
  1788. _exit(0);
  1789. #endif
  1790. }
  1791. /** Set *timeval to the current time of day. On error, log and terminate.
  1792. * (Same as gettimeofday(timeval,NULL), but never returns -1.)
  1793. */
  1794. void
  1795. tor_gettimeofday(struct timeval *timeval)
  1796. {
  1797. #ifdef MS_WINDOWS
  1798. /* Epoch bias copied from perl: number of units between windows epoch and
  1799. * Unix epoch. */
  1800. #define EPOCH_BIAS U64_LITERAL(116444736000000000)
  1801. #define UNITS_PER_SEC U64_LITERAL(10000000)
  1802. #define USEC_PER_SEC U64_LITERAL(1000000)
  1803. #define UNITS_PER_USEC U64_LITERAL(10)
  1804. union {
  1805. uint64_t ft_64;
  1806. FILETIME ft_ft;
  1807. } ft;
  1808. #if defined (WINCE)
  1809. /* wince do not have GetSystemTimeAsFileTime */
  1810. SYSTEMTIME stime;
  1811. GetSystemTime(&stime);
  1812. SystemTimeToFileTime(&stime,&ft.ft_ft);
  1813. #else
  1814. /* number of 100-nsec units since Jan 1, 1601 */
  1815. GetSystemTimeAsFileTime(&ft.ft_ft);
  1816. #endif
  1817. if (ft.ft_64 < EPOCH_BIAS) {
  1818. log_err(LD_GENERAL,"System time is before 1970; failing.");
  1819. exit(1);
  1820. }
  1821. ft.ft_64 -= EPOCH_BIAS;
  1822. timeval->tv_sec = (unsigned) (ft.ft_64 / UNITS_PER_SEC);
  1823. timeval->tv_usec = (unsigned) ((ft.ft_64 / UNITS_PER_USEC) % USEC_PER_SEC);
  1824. #elif defined(HAVE_GETTIMEOFDAY)
  1825. if (gettimeofday(timeval, NULL)) {
  1826. log_err(LD_GENERAL,"gettimeofday failed.");
  1827. /* If gettimeofday dies, we have either given a bad timezone (we didn't),
  1828. or segfaulted.*/
  1829. exit(1);
  1830. }
  1831. #elif defined(HAVE_FTIME)
  1832. struct timeb tb;
  1833. ftime(&tb);
  1834. timeval->tv_sec = tb.time;
  1835. timeval->tv_usec = tb.millitm * 1000;
  1836. #else
  1837. #error "No way to get time."
  1838. #endif
  1839. return;
  1840. }
  1841. #if defined(TOR_IS_MULTITHREADED) && !defined(MS_WINDOWS)
  1842. /** Defined iff we need to add locks when defining fake versions of reentrant
  1843. * versions of time-related functions. */
  1844. #define TIME_FNS_NEED_LOCKS
  1845. #endif
  1846. #ifndef HAVE_LOCALTIME_R
  1847. #ifdef TIME_FNS_NEED_LOCKS
  1848. struct tm *
  1849. tor_localtime_r(const time_t *timep, struct tm *result)
  1850. {
  1851. struct tm *r;
  1852. static tor_mutex_t *m=NULL;
  1853. if (!m) { m=tor_mutex_new(); }
  1854. tor_assert(result);
  1855. tor_mutex_acquire(m);
  1856. r = localtime(timep);
  1857. memcpy(result, r, sizeof(struct tm));
  1858. tor_mutex_release(m);
  1859. return result;
  1860. }
  1861. #else
  1862. struct tm *
  1863. tor_localtime_r(const time_t *timep, struct tm *result)
  1864. {
  1865. struct tm *r;
  1866. tor_assert(result);
  1867. r = localtime(timep);
  1868. memcpy(result, r, sizeof(struct tm));
  1869. return result;
  1870. }
  1871. #endif
  1872. #endif
  1873. #ifndef HAVE_GMTIME_R
  1874. #ifdef TIME_FNS_NEED_LOCKS
  1875. struct tm *
  1876. tor_gmtime_r(const time_t *timep, struct tm *result)
  1877. {
  1878. struct tm *r;
  1879. static tor_mutex_t *m=NULL;
  1880. if (!m) { m=tor_mutex_new(); }
  1881. tor_assert(result);
  1882. tor_mutex_acquire(m);
  1883. r = gmtime(timep);
  1884. memcpy(result, r, sizeof(struct tm));
  1885. tor_mutex_release(m);
  1886. return result;
  1887. }
  1888. #else
  1889. struct tm *
  1890. tor_gmtime_r(const time_t *timep, struct tm *result)
  1891. {
  1892. struct tm *r;
  1893. tor_assert(result);
  1894. r = gmtime(timep);
  1895. memcpy(result, r, sizeof(struct tm));
  1896. return result;
  1897. }
  1898. #endif
  1899. #endif
  1900. #if defined(USE_WIN32_THREADS)
  1901. void
  1902. tor_mutex_init(tor_mutex_t *m)
  1903. {
  1904. InitializeCriticalSection(&m->mutex);
  1905. }
  1906. void
  1907. tor_mutex_uninit(tor_mutex_t *m)
  1908. {
  1909. DeleteCriticalSection(&m->mutex);
  1910. }
  1911. void
  1912. tor_mutex_acquire(tor_mutex_t *m)
  1913. {
  1914. tor_assert(m);
  1915. EnterCriticalSection(&m->mutex);
  1916. }
  1917. void
  1918. tor_mutex_release(tor_mutex_t *m)
  1919. {
  1920. LeaveCriticalSection(&m->mutex);
  1921. }
  1922. unsigned long
  1923. tor_get_thread_id(void)
  1924. {
  1925. return (unsigned long)GetCurrentThreadId();
  1926. }
  1927. #elif defined(USE_PTHREADS)
  1928. /** A mutex attribute that we're going to use to tell pthreads that we want
  1929. * "reentrant" mutexes (i.e., once we can re-lock if we're already holding
  1930. * them.) */
  1931. static pthread_mutexattr_t attr_reentrant;
  1932. /** True iff we've called tor_threads_init() */
  1933. static int threads_initialized = 0;
  1934. /** Initialize <b>mutex</b> so it can be locked. Every mutex must be set
  1935. * up with tor_mutex_init() or tor_mutex_new(); not both. */
  1936. void
  1937. tor_mutex_init(tor_mutex_t *mutex)
  1938. {
  1939. int err;
  1940. if (PREDICT_UNLIKELY(!threads_initialized))
  1941. tor_threads_init();
  1942. err = pthread_mutex_init(&mutex->mutex, &attr_reentrant);
  1943. if (PREDICT_UNLIKELY(err)) {
  1944. log_err(LD_GENERAL, "Error %d creating a mutex.", err);
  1945. tor_fragile_assert();
  1946. }
  1947. }
  1948. /** Wait until <b>m</b> is free, then acquire it. */
  1949. void
  1950. tor_mutex_acquire(tor_mutex_t *m)
  1951. {
  1952. int err;
  1953. tor_assert(m);
  1954. err = pthread_mutex_lock(&m->mutex);
  1955. if (PREDICT_UNLIKELY(err)) {
  1956. log_err(LD_GENERAL, "Error %d locking a mutex.", err);
  1957. tor_fragile_assert();
  1958. }
  1959. }
  1960. /** Release the lock <b>m</b> so another thread can have it. */
  1961. void
  1962. tor_mutex_release(tor_mutex_t *m)
  1963. {
  1964. int err;
  1965. tor_assert(m);
  1966. err = pthread_mutex_unlock(&m->mutex);
  1967. if (PREDICT_UNLIKELY(err)) {
  1968. log_err(LD_GENERAL, "Error %d unlocking a mutex.", err);
  1969. tor_fragile_assert();
  1970. }
  1971. }
  1972. /** Clean up the mutex <b>m</b> so that it no longer uses any system
  1973. * resources. Does not free <b>m</b>. This function must only be called on
  1974. * mutexes from tor_mutex_init(). */
  1975. void
  1976. tor_mutex_uninit(tor_mutex_t *m)
  1977. {
  1978. int err;
  1979. tor_assert(m);
  1980. err = pthread_mutex_destroy(&m->mutex);
  1981. if (PREDICT_UNLIKELY(err)) {
  1982. log_err(LD_GENERAL, "Error %d destroying a mutex.", err);
  1983. tor_fragile_assert();
  1984. }
  1985. }
  1986. /** Return an integer representing this thread. */
  1987. unsigned long
  1988. tor_get_thread_id(void)
  1989. {
  1990. union {
  1991. pthread_t thr;
  1992. unsigned long id;
  1993. } r;
  1994. r.thr = pthread_self();
  1995. return r.id;
  1996. }
  1997. #endif
  1998. #ifdef TOR_IS_MULTITHREADED
  1999. /** Return a newly allocated, ready-for-use mutex. */
  2000. tor_mutex_t *
  2001. tor_mutex_new(void)
  2002. {
  2003. tor_mutex_t *m = tor_malloc_zero(sizeof(tor_mutex_t));
  2004. tor_mutex_init(m);
  2005. return m;
  2006. }
  2007. /** Release all storage and system resources held by <b>m</b>. */
  2008. void
  2009. tor_mutex_free(tor_mutex_t *m)
  2010. {
  2011. if (!m)
  2012. return;
  2013. tor_mutex_uninit(m);
  2014. tor_free(m);
  2015. }
  2016. #endif
  2017. /* Conditions. */
  2018. #ifdef USE_PTHREADS
  2019. #if 0
  2020. /** Cross-platform condition implementation. */
  2021. struct tor_cond_t {
  2022. pthread_cond_t cond;
  2023. };
  2024. /** Return a newly allocated condition, with nobody waiting on it. */
  2025. tor_cond_t *
  2026. tor_cond_new(void)
  2027. {
  2028. tor_cond_t *cond = tor_malloc_zero(sizeof(tor_cond_t));
  2029. if (pthread_cond_init(&cond->cond, NULL)) {
  2030. tor_free(cond);
  2031. return NULL;
  2032. }
  2033. return cond;
  2034. }
  2035. /** Release all resources held by <b>cond</b>. */
  2036. void
  2037. tor_cond_free(tor_cond_t *cond)
  2038. {
  2039. if (!cond)
  2040. return;
  2041. if (pthread_cond_destroy(&cond->cond)) {
  2042. log_warn(LD_GENERAL,"Error freeing condition: %s", strerror(errno));
  2043. return;
  2044. }
  2045. tor_free(cond);
  2046. }
  2047. /** Wait until one of the tor_cond_signal functions is called on <b>cond</b>.
  2048. * All waiters on the condition must wait holding the same <b>mutex</b>.
  2049. * Returns 0 on success, negative on failure. */
  2050. int
  2051. tor_cond_wait(tor_cond_t *cond, tor_mutex_t *mutex)
  2052. {
  2053. return pthread_cond_wait(&cond->cond, &mutex->mutex) ? -1 : 0;
  2054. }
  2055. /** Wake up one of the waiters on <b>cond</b>. */
  2056. void
  2057. tor_cond_signal_one(tor_cond_t *cond)
  2058. {
  2059. pthread_cond_signal(&cond->cond);
  2060. }
  2061. /** Wake up all of the waiters on <b>cond</b>. */
  2062. void
  2063. tor_cond_signal_all(tor_cond_t *cond)
  2064. {
  2065. pthread_cond_broadcast(&cond->cond);
  2066. }
  2067. #endif
  2068. /** Set up common structures for use by threading. */
  2069. void
  2070. tor_threads_init(void)
  2071. {
  2072. if (!threads_initialized) {
  2073. pthread_mutexattr_init(&attr_reentrant);
  2074. pthread_mutexattr_settype(&attr_reentrant, PTHREAD_MUTEX_RECURSIVE);
  2075. threads_initialized = 1;
  2076. set_main_thread();
  2077. }
  2078. }
  2079. #elif defined(USE_WIN32_THREADS)
  2080. #if 0
  2081. static DWORD cond_event_tls_index;
  2082. struct tor_cond_t {
  2083. CRITICAL_SECTION mutex;
  2084. smartlist_t *events;
  2085. };
  2086. tor_cond_t *
  2087. tor_cond_new(void)
  2088. {
  2089. tor_cond_t *cond = tor_malloc_zero(sizeof(tor_cond_t));
  2090. InitializeCriticalSection(&cond->mutex);
  2091. cond->events = smartlist_create();
  2092. return cond;
  2093. }
  2094. void
  2095. tor_cond_free(tor_cond_t *cond)
  2096. {
  2097. if (!cond)
  2098. return;
  2099. DeleteCriticalSection(&cond->mutex);
  2100. /* XXXX notify? */
  2101. smartlist_free(cond->events);
  2102. tor_free(cond);
  2103. }
  2104. int
  2105. tor_cond_wait(tor_cond_t *cond, tor_mutex_t *mutex)
  2106. {
  2107. HANDLE event;
  2108. int r;
  2109. tor_assert(cond);
  2110. tor_assert(mutex);
  2111. event = TlsGetValue(cond_event_tls_index);
  2112. if (!event) {
  2113. event = CreateEvent(0, FALSE, FALSE, NULL);
  2114. TlsSetValue(cond_event_tls_index, event);
  2115. }
  2116. EnterCriticalSection(&cond->mutex);
  2117. tor_assert(WaitForSingleObject(event, 0) == WAIT_TIMEOUT);
  2118. tor_assert(!smartlist_isin(cond->events, event));
  2119. smartlist_add(cond->events, event);
  2120. LeaveCriticalSection(&cond->mutex);
  2121. tor_mutex_release(mutex);
  2122. r = WaitForSingleObject(event, INFINITE);
  2123. tor_mutex_acquire(mutex);
  2124. switch (r) {
  2125. case WAIT_OBJECT_0: /* we got the mutex normally. */
  2126. break;
  2127. case WAIT_ABANDONED: /* holding thread exited. */
  2128. case WAIT_TIMEOUT: /* Should never happen. */
  2129. tor_assert(0);
  2130. break;
  2131. case WAIT_FAILED:
  2132. log_warn(LD_GENERAL, "Failed to acquire mutex: %d",(int) GetLastError());
  2133. }
  2134. return 0;
  2135. }
  2136. void
  2137. tor_cond_signal_one(tor_cond_t *cond)
  2138. {
  2139. HANDLE event;
  2140. tor_assert(cond);
  2141. EnterCriticalSection(&cond->mutex);
  2142. if ((event = smartlist_pop_last(cond->events)))
  2143. SetEvent(event);
  2144. LeaveCriticalSection(&cond->mutex);
  2145. }
  2146. void
  2147. tor_cond_signal_all(tor_cond_t *cond)
  2148. {
  2149. tor_assert(cond);
  2150. EnterCriticalSection(&cond->mutex);
  2151. SMARTLIST_FOREACH(cond->events, HANDLE, event, SetEvent(event));
  2152. smartlist_clear(cond->events);
  2153. LeaveCriticalSection(&cond->mutex);
  2154. }
  2155. #endif
  2156. void
  2157. tor_threads_init(void)
  2158. {
  2159. #if 0
  2160. cond_event_tls_index = TlsAlloc();
  2161. #endif
  2162. set_main_thread();
  2163. }
  2164. #endif
  2165. #if defined(HAVE_MLOCKALL) && HAVE_DECL_MLOCKALL && defined(RLIMIT_MEMLOCK)
  2166. /** Attempt to raise the current and max rlimit to infinity for our process.
  2167. * This only needs to be done once and can probably only be done when we have
  2168. * not already dropped privileges.
  2169. */
  2170. static int
  2171. tor_set_max_memlock(void)
  2172. {
  2173. /* Future consideration for Windows is probably SetProcessWorkingSetSize
  2174. * This is similar to setting the memory rlimit of RLIMIT_MEMLOCK
  2175. * http://msdn.microsoft.com/en-us/library/ms686234(VS.85).aspx
  2176. */
  2177. struct rlimit limit;
  2178. /* RLIM_INFINITY is -1 on some platforms. */
  2179. limit.rlim_cur = RLIM_INFINITY;
  2180. limit.rlim_max = RLIM_INFINITY;
  2181. if (setrlimit(RLIMIT_MEMLOCK, &limit) == -1) {
  2182. if (errno == EPERM) {
  2183. log_warn(LD_GENERAL, "You appear to lack permissions to change memory "
  2184. "limits. Are you root?");
  2185. }
  2186. log_warn(LD_GENERAL, "Unable to raise RLIMIT_MEMLOCK: %s",
  2187. strerror(errno));
  2188. return -1;
  2189. }
  2190. return 0;
  2191. }
  2192. #endif
  2193. /** Attempt to lock all current and all future memory pages.
  2194. * This should only be called once and while we're privileged.
  2195. * Like mlockall() we return 0 when we're successful and -1 when we're not.
  2196. * Unlike mlockall() we return 1 if we've already attempted to lock memory.
  2197. */
  2198. int
  2199. tor_mlockall(void)
  2200. {
  2201. static int memory_lock_attempted = 0;
  2202. if (memory_lock_attempted) {
  2203. return 1;
  2204. }
  2205. memory_lock_attempted = 1;
  2206. /*
  2207. * Future consideration for Windows may be VirtualLock
  2208. * VirtualLock appears to implement mlock() but not mlockall()
  2209. *
  2210. * http://msdn.microsoft.com/en-us/library/aa366895(VS.85).aspx
  2211. */
  2212. #if defined(HAVE_MLOCKALL) && HAVE_DECL_MLOCKALL && defined(RLIMIT_MEMLOCK)
  2213. if (tor_set_max_memlock() == 0) {
  2214. log_debug(LD_GENERAL, "RLIMIT_MEMLOCK is now set to RLIM_INFINITY.");
  2215. }
  2216. if (mlockall(MCL_CURRENT|MCL_FUTURE) == 0) {
  2217. log_info(LD_GENERAL, "Insecure OS paging is effectively disabled.");
  2218. return 0;
  2219. } else {
  2220. if (errno == ENOSYS) {
  2221. /* Apple - it's 2009! I'm looking at you. Grrr. */
  2222. log_notice(LD_GENERAL, "It appears that mlockall() is not available on "
  2223. "your platform.");
  2224. } else if (errno == EPERM) {
  2225. log_notice(LD_GENERAL, "It appears that you lack the permissions to "
  2226. "lock memory. Are you root?");
  2227. }
  2228. log_notice(LD_GENERAL, "Unable to lock all current and future memory "
  2229. "pages: %s", strerror(errno));
  2230. return -1;
  2231. }
  2232. #else
  2233. log_warn(LD_GENERAL, "Unable to lock memory pages. mlockall() unsupported?");
  2234. return -1;
  2235. #endif
  2236. }
  2237. /** Identity of the "main" thread */
  2238. static unsigned long main_thread_id = -1;
  2239. /** Start considering the current thread to be the 'main thread'. This has
  2240. * no effect on anything besides in_main_thread(). */
  2241. void
  2242. set_main_thread(void)
  2243. {
  2244. main_thread_id = tor_get_thread_id();
  2245. }
  2246. /** Return true iff called from the main thread. */
  2247. int
  2248. in_main_thread(void)
  2249. {
  2250. return main_thread_id == tor_get_thread_id();
  2251. }
  2252. /**
  2253. * On Windows, WSAEWOULDBLOCK is not always correct: when you see it,
  2254. * you need to ask the socket for its actual errno. Also, you need to
  2255. * get your errors from WSAGetLastError, not errno. (If you supply a
  2256. * socket of -1, we check WSAGetLastError, but don't correct
  2257. * WSAEWOULDBLOCKs.)
  2258. *
  2259. * The upshot of all of this is that when a socket call fails, you
  2260. * should call tor_socket_errno <em>at most once</em> on the failing
  2261. * socket to get the error.
  2262. */
  2263. #if defined(MS_WINDOWS)
  2264. int
  2265. tor_socket_errno(int sock)
  2266. {
  2267. int optval, optvallen=sizeof(optval);
  2268. int err = WSAGetLastError();
  2269. if (err == WSAEWOULDBLOCK && sock >= 0) {
  2270. if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval, &optvallen))
  2271. return err;
  2272. if (optval)
  2273. return optval;
  2274. }
  2275. return err;
  2276. }
  2277. #endif
  2278. #if defined(MS_WINDOWS)
  2279. #define E(code, s) { code, (s " [" #code " ]") }
  2280. struct { int code; const char *msg; } windows_socket_errors[] = {
  2281. E(WSAEINTR, "Interrupted function call"),
  2282. E(WSAEACCES, "Permission denied"),
  2283. E(WSAEFAULT, "Bad address"),
  2284. E(WSAEINVAL, "Invalid argument"),
  2285. E(WSAEMFILE, "Too many open files"),
  2286. E(WSAEWOULDBLOCK, "Resource temporarily unavailable"),
  2287. E(WSAEINPROGRESS, "Operation now in progress"),
  2288. E(WSAEALREADY, "Operation already in progress"),
  2289. E(WSAENOTSOCK, "Socket operation on nonsocket"),
  2290. E(WSAEDESTADDRREQ, "Destination address required"),
  2291. E(WSAEMSGSIZE, "Message too long"),
  2292. E(WSAEPROTOTYPE, "Protocol wrong for socket"),
  2293. E(WSAENOPROTOOPT, "Bad protocol option"),
  2294. E(WSAEPROTONOSUPPORT, "Protocol not supported"),
  2295. E(WSAESOCKTNOSUPPORT, "Socket type not supported"),
  2296. /* What's the difference between NOTSUPP and NOSUPPORT? :) */
  2297. E(WSAEOPNOTSUPP, "Operation not supported"),
  2298. E(WSAEPFNOSUPPORT, "Protocol family not supported"),
  2299. E(WSAEAFNOSUPPORT, "Address family not supported by protocol family"),
  2300. E(WSAEADDRINUSE, "Address already in use"),
  2301. E(WSAEADDRNOTAVAIL, "Cannot assign requested address"),
  2302. E(WSAENETDOWN, "Network is down"),
  2303. E(WSAENETUNREACH, "Network is unreachable"),
  2304. E(WSAENETRESET, "Network dropped connection on reset"),
  2305. E(WSAECONNABORTED, "Software caused connection abort"),
  2306. E(WSAECONNRESET, "Connection reset by peer"),
  2307. E(WSAENOBUFS, "No buffer space available"),
  2308. E(WSAEISCONN, "Socket is already connected"),
  2309. E(WSAENOTCONN, "Socket is not connected"),
  2310. E(WSAESHUTDOWN, "Cannot send after socket shutdown"),
  2311. E(WSAETIMEDOUT, "Connection timed out"),
  2312. E(WSAECONNREFUSED, "Connection refused"),
  2313. E(WSAEHOSTDOWN, "Host is down"),
  2314. E(WSAEHOSTUNREACH, "No route to host"),
  2315. E(WSAEPROCLIM, "Too many processes"),
  2316. /* Yes, some of these start with WSA, not WSAE. No, I don't know why. */
  2317. E(WSASYSNOTREADY, "Network subsystem is unavailable"),
  2318. E(WSAVERNOTSUPPORTED, "Winsock.dll out of range"),
  2319. E(WSANOTINITIALISED, "Successful WSAStartup not yet performed"),
  2320. E(WSAEDISCON, "Graceful shutdown now in progress"),
  2321. #ifdef WSATYPE_NOT_FOUND
  2322. E(WSATYPE_NOT_FOUND, "Class type not found"),
  2323. #endif
  2324. E(WSAHOST_NOT_FOUND, "Host not found"),
  2325. E(WSATRY_AGAIN, "Nonauthoritative host not found"),
  2326. E(WSANO_RECOVERY, "This is a nonrecoverable error"),
  2327. E(WSANO_DATA, "Valid name, no data record of requested type)"),
  2328. /* There are some more error codes whose numeric values are marked
  2329. * <b>OS dependent</b>. They start with WSA_, apparently for the same
  2330. * reason that practitioners of some craft traditions deliberately
  2331. * introduce imperfections into their baskets and rugs "to allow the
  2332. * evil spirits to escape." If we catch them, then our binaries
  2333. * might not report consistent results across versions of Windows.
  2334. * Thus, I'm going to let them all fall through.
  2335. */
  2336. { -1, NULL },
  2337. };
  2338. /** There does not seem to be a strerror equivalent for Winsock errors.
  2339. * Naturally, we have to roll our own.
  2340. */
  2341. const char *
  2342. tor_socket_strerror(int e)
  2343. {
  2344. int i;
  2345. for (i=0; windows_socket_errors[i].code >= 0; ++i) {
  2346. if (e == windows_socket_errors[i].code)
  2347. return windows_socket_errors[i].msg;
  2348. }
  2349. return strerror(e);
  2350. }
  2351. #endif
  2352. /** Called before we make any calls to network-related functions.
  2353. * (Some operating systems require their network libraries to be
  2354. * initialized.) */
  2355. int
  2356. network_init(void)
  2357. {
  2358. #ifdef MS_WINDOWS
  2359. /* This silly exercise is necessary before windows will allow
  2360. * gethostbyname to work. */
  2361. WSADATA WSAData;
  2362. int r;
  2363. r = WSAStartup(0x101,&WSAData);
  2364. if (r) {
  2365. log_warn(LD_NET,"Error initializing windows network layer: code was %d",r);
  2366. return -1;
  2367. }
  2368. /* WSAData.iMaxSockets might show the max sockets we're allowed to use.
  2369. * We might use it to complain if we're trying to be a server but have
  2370. * too few sockets available. */
  2371. #endif
  2372. return 0;
  2373. }
  2374. #ifdef MS_WINDOWS
  2375. /** Return a newly allocated string describing the windows system error code
  2376. * <b>err</b>. Note that error codes are different from errno. Error codes
  2377. * come from GetLastError() when a winapi call fails. errno is set only when
  2378. * ANSI functions fail. Whee. */
  2379. char *
  2380. format_win32_error(DWORD err)
  2381. {
  2382. TCHAR *str = NULL;
  2383. char *result;
  2384. /* Somebody once decided that this interface was better than strerror(). */
  2385. FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  2386. FORMAT_MESSAGE_FROM_SYSTEM |
  2387. FORMAT_MESSAGE_IGNORE_INSERTS,
  2388. NULL, err,
  2389. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  2390. (LPVOID)&str,
  2391. 0, NULL);
  2392. if (str) {
  2393. #ifdef UNICODE
  2394. char abuf[1024] = {0};
  2395. wcstombs(abuf,str,1024);
  2396. result = tor_strdup(abuf);
  2397. #else
  2398. result = tor_strdup(str);
  2399. #endif
  2400. LocalFree(str); /* LocalFree != free() */
  2401. } else {
  2402. result = tor_strdup("<unformattable error>");
  2403. }
  2404. return result;
  2405. }
  2406. #endif