compat.c 88 KB

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