compat.c 94 KB

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