compat.c 93 KB

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