compat.c 95 KB

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