compat.c 92 KB

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