compat.c 84 KB

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