compat.c 84 KB

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