compat.c 100 KB

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