compat.c 100 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622
  1. /* Copyright (c) 2003-2004, Roger Dingledine
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2015, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. /**
  6. * \file compat.c
  7. * \brief Wrappers to make calls more portable. This code defines
  8. * functions such as tor_malloc, tor_snprintf, get/set various data types,
  9. * renaming, setting socket options, switching user IDs. It is basically
  10. * where the non-portable items are conditionally included depending on
  11. * the platform.
  12. **/
  13. /* This is required on rh7 to make strptime not complain.
  14. * We also need it to make memmem get defined (where available)
  15. */
  16. /* XXXX024 We should just use AC_USE_SYSTEM_EXTENSIONS in our autoconf,
  17. * and get this (and other important stuff!) automatically. Once we do that,
  18. * make sure to also change the extern char **environ detection in
  19. * configure.ac, because whether that is declared or not depends on whether
  20. * we have _GNU_SOURCE defined! Maybe that means that once we take this out,
  21. * we can also take out the configure check. */
  22. #define _GNU_SOURCE
  23. #define COMPAT_PRIVATE
  24. #include "compat.h"
  25. #ifdef _WIN32
  26. #include <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(64, sizeof(gid_t));
  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. /** Get name of current host and write it to <b>name</b> array, whose
  2012. * length is specified by <b>namelen</b> argument. Return 0 upon
  2013. * successfull completion; otherwise return return -1. (Currently,
  2014. * this function is merely a mockable wrapper for POSIX gethostname().)
  2015. */
  2016. MOCK_IMPL(int,
  2017. tor_gethostname,(char *name, size_t namelen))
  2018. {
  2019. return gethostname(name,namelen);
  2020. }
  2021. /** Set *addr to the IP address (in dotted-quad notation) stored in *str.
  2022. * Return 1 on success, 0 if *str is badly formatted.
  2023. * (Like inet_aton(str,addr), but works on Windows and Solaris.)
  2024. */
  2025. int
  2026. tor_inet_aton(const char *str, struct in_addr* addr)
  2027. {
  2028. unsigned a,b,c,d;
  2029. char more;
  2030. if (tor_sscanf(str, "%3u.%3u.%3u.%3u%c", &a,&b,&c,&d,&more) != 4)
  2031. return 0;
  2032. if (a > 255) return 0;
  2033. if (b > 255) return 0;
  2034. if (c > 255) return 0;
  2035. if (d > 255) return 0;
  2036. addr->s_addr = htonl((a<<24) | (b<<16) | (c<<8) | d);
  2037. return 1;
  2038. }
  2039. /** Given <b>af</b>==AF_INET and <b>src</b> a struct in_addr, or
  2040. * <b>af</b>==AF_INET6 and <b>src</b> a struct in6_addr, try to format the
  2041. * address and store it in the <b>len</b>-byte buffer <b>dst</b>. Returns
  2042. * <b>dst</b> on success, NULL on failure.
  2043. *
  2044. * (Like inet_ntop(af,src,dst,len), but works on platforms that don't have it:
  2045. * Tor sometimes needs to format ipv6 addresses even on platforms without ipv6
  2046. * support.) */
  2047. const char *
  2048. tor_inet_ntop(int af, const void *src, char *dst, size_t len)
  2049. {
  2050. if (af == AF_INET) {
  2051. if (tor_inet_ntoa(src, dst, len) < 0)
  2052. return NULL;
  2053. else
  2054. return dst;
  2055. } else if (af == AF_INET6) {
  2056. const struct in6_addr *addr = src;
  2057. char buf[64], *cp;
  2058. int longestGapLen = 0, longestGapPos = -1, i,
  2059. curGapPos = -1, curGapLen = 0;
  2060. uint16_t words[8];
  2061. for (i = 0; i < 8; ++i) {
  2062. words[i] = (((uint16_t)addr->s6_addr[2*i])<<8) + addr->s6_addr[2*i+1];
  2063. }
  2064. if (words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0 &&
  2065. words[4] == 0 && ((words[5] == 0 && words[6] && words[7]) ||
  2066. (words[5] == 0xffff))) {
  2067. /* This is an IPv4 address. */
  2068. if (words[5] == 0) {
  2069. tor_snprintf(buf, sizeof(buf), "::%d.%d.%d.%d",
  2070. addr->s6_addr[12], addr->s6_addr[13],
  2071. addr->s6_addr[14], addr->s6_addr[15]);
  2072. } else {
  2073. tor_snprintf(buf, sizeof(buf), "::%x:%d.%d.%d.%d", words[5],
  2074. addr->s6_addr[12], addr->s6_addr[13],
  2075. addr->s6_addr[14], addr->s6_addr[15]);
  2076. }
  2077. if ((strlen(buf) + 1) > len) /* +1 for \0 */
  2078. return NULL;
  2079. strlcpy(dst, buf, len);
  2080. return dst;
  2081. }
  2082. i = 0;
  2083. while (i < 8) {
  2084. if (words[i] == 0) {
  2085. curGapPos = i++;
  2086. curGapLen = 1;
  2087. while (i<8 && words[i] == 0) {
  2088. ++i; ++curGapLen;
  2089. }
  2090. if (curGapLen > longestGapLen) {
  2091. longestGapPos = curGapPos;
  2092. longestGapLen = curGapLen;
  2093. }
  2094. } else {
  2095. ++i;
  2096. }
  2097. }
  2098. if (longestGapLen<=1)
  2099. longestGapPos = -1;
  2100. cp = buf;
  2101. for (i = 0; i < 8; ++i) {
  2102. if (words[i] == 0 && longestGapPos == i) {
  2103. if (i == 0)
  2104. *cp++ = ':';
  2105. *cp++ = ':';
  2106. while (i < 8 && words[i] == 0)
  2107. ++i;
  2108. --i; /* to compensate for loop increment. */
  2109. } else {
  2110. tor_snprintf(cp, sizeof(buf)-(cp-buf), "%x", (unsigned)words[i]);
  2111. cp += strlen(cp);
  2112. if (i != 7)
  2113. *cp++ = ':';
  2114. }
  2115. }
  2116. *cp = '\0';
  2117. if ((strlen(buf) + 1) > len) /* +1 for \0 */
  2118. return NULL;
  2119. strlcpy(dst, buf, len);
  2120. return dst;
  2121. } else {
  2122. return NULL;
  2123. }
  2124. }
  2125. /** Given <b>af</b>==AF_INET or <b>af</b>==AF_INET6, and a string <b>src</b>
  2126. * encoding an IPv4 address or IPv6 address correspondingly, try to parse the
  2127. * address and store the result in <b>dst</b> (which must have space for a
  2128. * struct in_addr or a struct in6_addr, as appropriate). Return 1 on success,
  2129. * 0 on a bad parse, and -1 on a bad <b>af</b>.
  2130. *
  2131. * (Like inet_pton(af,src,dst) but works on platforms that don't have it: Tor
  2132. * sometimes needs to format ipv6 addresses even on platforms without ipv6
  2133. * support.) */
  2134. int
  2135. tor_inet_pton(int af, const char *src, void *dst)
  2136. {
  2137. if (af == AF_INET) {
  2138. return tor_inet_aton(src, dst);
  2139. } else if (af == AF_INET6) {
  2140. struct in6_addr *out = dst;
  2141. uint16_t words[8];
  2142. int gapPos = -1, i, setWords=0;
  2143. const char *dot = strchr(src, '.');
  2144. const char *eow; /* end of words. */
  2145. if (dot == src)
  2146. return 0;
  2147. else if (!dot)
  2148. eow = src+strlen(src);
  2149. else {
  2150. unsigned byte1,byte2,byte3,byte4;
  2151. char more;
  2152. for (eow = dot-1; eow > src && TOR_ISDIGIT(*eow); --eow)
  2153. ;
  2154. if (*eow != ':')
  2155. return 0;
  2156. ++eow;
  2157. /* We use "scanf" because some platform inet_aton()s are too lax
  2158. * about IPv4 addresses of the form "1.2.3" */
  2159. if (tor_sscanf(eow, "%3u.%3u.%3u.%3u%c",
  2160. &byte1,&byte2,&byte3,&byte4,&more) != 4)
  2161. return 0;
  2162. if (byte1 > 255 || byte2 > 255 || byte3 > 255 || byte4 > 255)
  2163. return 0;
  2164. words[6] = (byte1<<8) | byte2;
  2165. words[7] = (byte3<<8) | byte4;
  2166. setWords += 2;
  2167. }
  2168. i = 0;
  2169. while (src < eow) {
  2170. if (i > 7)
  2171. return 0;
  2172. if (TOR_ISXDIGIT(*src)) {
  2173. char *next;
  2174. ssize_t len;
  2175. long r = strtol(src, &next, 16);
  2176. tor_assert(next != NULL);
  2177. tor_assert(next != src);
  2178. len = *next == '\0' ? eow - src : next - src;
  2179. if (len > 4)
  2180. return 0;
  2181. if (len > 1 && !TOR_ISXDIGIT(src[1]))
  2182. return 0; /* 0x is not valid */
  2183. tor_assert(r >= 0);
  2184. tor_assert(r < 65536);
  2185. words[i++] = (uint16_t)r;
  2186. setWords++;
  2187. src = next;
  2188. if (*src != ':' && src != eow)
  2189. return 0;
  2190. ++src;
  2191. } else if (*src == ':' && i > 0 && gapPos == -1) {
  2192. gapPos = i;
  2193. ++src;
  2194. } else if (*src == ':' && i == 0 && src+1 < eow && src[1] == ':' &&
  2195. gapPos == -1) {
  2196. gapPos = i;
  2197. src += 2;
  2198. } else {
  2199. return 0;
  2200. }
  2201. }
  2202. if (setWords > 8 ||
  2203. (setWords == 8 && gapPos != -1) ||
  2204. (setWords < 8 && gapPos == -1))
  2205. return 0;
  2206. if (gapPos >= 0) {
  2207. int nToMove = setWords - (dot ? 2 : 0) - gapPos;
  2208. int gapLen = 8 - setWords;
  2209. tor_assert(nToMove >= 0);
  2210. memmove(&words[gapPos+gapLen], &words[gapPos],
  2211. sizeof(uint16_t)*nToMove);
  2212. memset(&words[gapPos], 0, sizeof(uint16_t)*gapLen);
  2213. }
  2214. for (i = 0; i < 8; ++i) {
  2215. out->s6_addr[2*i ] = words[i] >> 8;
  2216. out->s6_addr[2*i+1] = words[i] & 0xff;
  2217. }
  2218. return 1;
  2219. } else {
  2220. return -1;
  2221. }
  2222. }
  2223. /** Similar behavior to Unix gethostbyname: resolve <b>name</b>, and set
  2224. * *<b>addr</b> to the proper IP address, in host byte order. Returns 0
  2225. * on success, -1 on failure; 1 on transient failure.
  2226. *
  2227. * (This function exists because standard windows gethostbyname
  2228. * doesn't treat raw IP addresses properly.)
  2229. */
  2230. MOCK_IMPL(int,
  2231. tor_lookup_hostname,(const char *name, uint32_t *addr))
  2232. {
  2233. tor_addr_t myaddr;
  2234. int ret;
  2235. if ((ret = tor_addr_lookup(name, AF_INET, &myaddr)))
  2236. return ret;
  2237. if (tor_addr_family(&myaddr) == AF_INET) {
  2238. *addr = tor_addr_to_ipv4h(&myaddr);
  2239. return ret;
  2240. }
  2241. return -1;
  2242. }
  2243. /** Hold the result of our call to <b>uname</b>. */
  2244. static char uname_result[256];
  2245. /** True iff uname_result is set. */
  2246. static int uname_result_is_set = 0;
  2247. /** Return a pointer to a description of our platform.
  2248. */
  2249. const char *
  2250. get_uname(void)
  2251. {
  2252. #ifdef HAVE_UNAME
  2253. struct utsname u;
  2254. #endif
  2255. if (!uname_result_is_set) {
  2256. #ifdef HAVE_UNAME
  2257. if (uname(&u) != -1) {
  2258. /* (Linux says 0 is success, Solaris says 1 is success) */
  2259. strlcpy(uname_result, u.sysname, sizeof(uname_result));
  2260. } else
  2261. #endif
  2262. {
  2263. #ifdef _WIN32
  2264. OSVERSIONINFOEX info;
  2265. int i;
  2266. const char *plat = NULL;
  2267. static struct {
  2268. unsigned major; unsigned minor; const char *version;
  2269. } win_version_table[] = {
  2270. { 6, 2, "Windows 8" },
  2271. { 6, 1, "Windows 7" },
  2272. { 6, 0, "Windows Vista" },
  2273. { 5, 2, "Windows Server 2003" },
  2274. { 5, 1, "Windows XP" },
  2275. { 5, 0, "Windows 2000" },
  2276. /* { 4, 0, "Windows NT 4.0" }, */
  2277. { 4, 90, "Windows Me" },
  2278. { 4, 10, "Windows 98" },
  2279. /* { 4, 0, "Windows 95" } */
  2280. { 3, 51, "Windows NT 3.51" },
  2281. { 0, 0, NULL }
  2282. };
  2283. memset(&info, 0, sizeof(info));
  2284. info.dwOSVersionInfoSize = sizeof(info);
  2285. if (! GetVersionEx((LPOSVERSIONINFO)&info)) {
  2286. strlcpy(uname_result, "Bizarre version of Windows where GetVersionEx"
  2287. " doesn't work.", sizeof(uname_result));
  2288. uname_result_is_set = 1;
  2289. return uname_result;
  2290. }
  2291. if (info.dwMajorVersion == 4 && info.dwMinorVersion == 0) {
  2292. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  2293. plat = "Windows NT 4.0";
  2294. else
  2295. plat = "Windows 95";
  2296. } else {
  2297. for (i=0; win_version_table[i].major>0; ++i) {
  2298. if (win_version_table[i].major == info.dwMajorVersion &&
  2299. win_version_table[i].minor == info.dwMinorVersion) {
  2300. plat = win_version_table[i].version;
  2301. break;
  2302. }
  2303. }
  2304. }
  2305. if (plat) {
  2306. strlcpy(uname_result, plat, sizeof(uname_result));
  2307. } else {
  2308. if (info.dwMajorVersion > 6 ||
  2309. (info.dwMajorVersion==6 && info.dwMinorVersion>2))
  2310. tor_snprintf(uname_result, sizeof(uname_result),
  2311. "Very recent version of Windows [major=%d,minor=%d]",
  2312. (int)info.dwMajorVersion,(int)info.dwMinorVersion);
  2313. else
  2314. tor_snprintf(uname_result, sizeof(uname_result),
  2315. "Unrecognized version of Windows [major=%d,minor=%d]",
  2316. (int)info.dwMajorVersion,(int)info.dwMinorVersion);
  2317. }
  2318. #ifdef VER_NT_SERVER
  2319. if (info.wProductType == VER_NT_SERVER ||
  2320. info.wProductType == VER_NT_DOMAIN_CONTROLLER) {
  2321. strlcat(uname_result, " [server]", sizeof(uname_result));
  2322. }
  2323. #endif
  2324. #else
  2325. strlcpy(uname_result, "Unknown platform", sizeof(uname_result));
  2326. #endif
  2327. }
  2328. uname_result_is_set = 1;
  2329. }
  2330. return uname_result;
  2331. }
  2332. /*
  2333. * Process control
  2334. */
  2335. #if defined(USE_PTHREADS)
  2336. /** Wraps a void (*)(void*) function and its argument so we can
  2337. * invoke them in a way pthreads would expect.
  2338. */
  2339. typedef struct tor_pthread_data_t {
  2340. void (*func)(void *);
  2341. void *data;
  2342. } tor_pthread_data_t;
  2343. /** Given a tor_pthread_data_t <b>_data</b>, call _data-&gt;func(d-&gt;data)
  2344. * and free _data. Used to make sure we can call functions the way pthread
  2345. * expects. */
  2346. static void *
  2347. tor_pthread_helper_fn(void *_data)
  2348. {
  2349. tor_pthread_data_t *data = _data;
  2350. void (*func)(void*);
  2351. void *arg;
  2352. /* mask signals to worker threads to avoid SIGPIPE, etc */
  2353. sigset_t sigs;
  2354. /* We're in a subthread; don't handle any signals here. */
  2355. sigfillset(&sigs);
  2356. pthread_sigmask(SIG_SETMASK, &sigs, NULL);
  2357. func = data->func;
  2358. arg = data->data;
  2359. tor_free(_data);
  2360. func(arg);
  2361. return NULL;
  2362. }
  2363. /**
  2364. * A pthread attribute to make threads start detached.
  2365. */
  2366. static pthread_attr_t attr_detached;
  2367. /** True iff we've called tor_threads_init() */
  2368. static int threads_initialized = 0;
  2369. #endif
  2370. /** Minimalist interface to run a void function in the background. On
  2371. * Unix calls fork, on win32 calls beginthread. Returns -1 on failure.
  2372. * func should not return, but rather should call spawn_exit.
  2373. *
  2374. * NOTE: if <b>data</b> is used, it should not be allocated on the stack,
  2375. * since in a multithreaded environment, there is no way to be sure that
  2376. * the caller's stack will still be around when the called function is
  2377. * running.
  2378. */
  2379. int
  2380. spawn_func(void (*func)(void *), void *data)
  2381. {
  2382. #if defined(USE_WIN32_THREADS)
  2383. int rv;
  2384. rv = (int)_beginthread(func, 0, data);
  2385. if (rv == (int)-1)
  2386. return -1;
  2387. return 0;
  2388. #elif defined(USE_PTHREADS)
  2389. pthread_t thread;
  2390. tor_pthread_data_t *d;
  2391. if (PREDICT_UNLIKELY(!threads_initialized))
  2392. tor_threads_init();
  2393. d = tor_malloc(sizeof(tor_pthread_data_t));
  2394. d->data = data;
  2395. d->func = func;
  2396. if (pthread_create(&thread,&attr_detached,tor_pthread_helper_fn,d))
  2397. return -1;
  2398. return 0;
  2399. #else
  2400. pid_t pid;
  2401. pid = fork();
  2402. if (pid<0)
  2403. return -1;
  2404. if (pid==0) {
  2405. /* Child */
  2406. func(data);
  2407. tor_assert(0); /* Should never reach here. */
  2408. return 0; /* suppress "control-reaches-end-of-non-void" warning. */
  2409. } else {
  2410. /* Parent */
  2411. return 0;
  2412. }
  2413. #endif
  2414. }
  2415. /** End the current thread/process.
  2416. */
  2417. void
  2418. spawn_exit(void)
  2419. {
  2420. #if defined(USE_WIN32_THREADS)
  2421. _endthread();
  2422. //we should never get here. my compiler thinks that _endthread returns, this
  2423. //is an attempt to fool it.
  2424. tor_assert(0);
  2425. _exit(0);
  2426. #elif defined(USE_PTHREADS)
  2427. pthread_exit(NULL);
  2428. #else
  2429. /* http://www.erlenstar.demon.co.uk/unix/faq_2.html says we should
  2430. * call _exit, not exit, from child processes. */
  2431. _exit(0);
  2432. #endif
  2433. }
  2434. /** Implementation logic for compute_num_cpus(). */
  2435. static int
  2436. compute_num_cpus_impl(void)
  2437. {
  2438. #ifdef _WIN32
  2439. SYSTEM_INFO info;
  2440. memset(&info, 0, sizeof(info));
  2441. GetSystemInfo(&info);
  2442. if (info.dwNumberOfProcessors >= 1 && info.dwNumberOfProcessors < INT_MAX)
  2443. return (int)info.dwNumberOfProcessors;
  2444. else
  2445. return -1;
  2446. #elif defined(HAVE_SYSCONF)
  2447. #ifdef _SC_NPROCESSORS_CONF
  2448. long cpus_conf = sysconf(_SC_NPROCESSORS_CONF);
  2449. #else
  2450. long cpus_conf = -1;
  2451. #endif
  2452. #ifdef _SC_NPROCESSORS_ONLN
  2453. long cpus_onln = sysconf(_SC_NPROCESSORS_ONLN);
  2454. #else
  2455. long cpus_onln = -1;
  2456. #endif
  2457. long cpus = -1;
  2458. if (cpus_conf > 0 && cpus_onln < 0) {
  2459. cpus = cpus_conf;
  2460. } else if (cpus_onln > 0 && cpus_conf < 0) {
  2461. cpus = cpus_onln;
  2462. } else if (cpus_onln > 0 && cpus_conf > 0) {
  2463. if (cpus_onln < cpus_conf) {
  2464. log_notice(LD_GENERAL, "I think we have %ld CPUS, but only %ld of them "
  2465. "are available. Telling Tor to only use %ld. You can over"
  2466. "ride this with the NumCPUs option",
  2467. cpus_conf, cpus_onln, cpus_onln);
  2468. }
  2469. cpus = cpus_onln;
  2470. }
  2471. if (cpus >= 1 && cpus < INT_MAX)
  2472. return (int)cpus;
  2473. else
  2474. return -1;
  2475. #else
  2476. return -1;
  2477. #endif
  2478. }
  2479. #define MAX_DETECTABLE_CPUS 16
  2480. /** Return how many CPUs we are running with. We assume that nobody is
  2481. * using hot-swappable CPUs, so we don't recompute this after the first
  2482. * time. Return -1 if we don't know how to tell the number of CPUs on this
  2483. * system.
  2484. */
  2485. int
  2486. compute_num_cpus(void)
  2487. {
  2488. static int num_cpus = -2;
  2489. if (num_cpus == -2) {
  2490. num_cpus = compute_num_cpus_impl();
  2491. tor_assert(num_cpus != -2);
  2492. if (num_cpus > MAX_DETECTABLE_CPUS)
  2493. log_notice(LD_GENERAL, "Wow! I detected that you have %d CPUs. I "
  2494. "will not autodetect any more than %d, though. If you "
  2495. "want to configure more, set NumCPUs in your torrc",
  2496. num_cpus, MAX_DETECTABLE_CPUS);
  2497. }
  2498. return num_cpus;
  2499. }
  2500. /** Set *timeval to the current time of day. On error, log and terminate.
  2501. * (Same as gettimeofday(timeval,NULL), but never returns -1.)
  2502. */
  2503. void
  2504. tor_gettimeofday(struct timeval *timeval)
  2505. {
  2506. #ifdef _WIN32
  2507. /* Epoch bias copied from perl: number of units between windows epoch and
  2508. * Unix epoch. */
  2509. #define EPOCH_BIAS U64_LITERAL(116444736000000000)
  2510. #define UNITS_PER_SEC U64_LITERAL(10000000)
  2511. #define USEC_PER_SEC U64_LITERAL(1000000)
  2512. #define UNITS_PER_USEC U64_LITERAL(10)
  2513. union {
  2514. uint64_t ft_64;
  2515. FILETIME ft_ft;
  2516. } ft;
  2517. /* number of 100-nsec units since Jan 1, 1601 */
  2518. GetSystemTimeAsFileTime(&ft.ft_ft);
  2519. if (ft.ft_64 < EPOCH_BIAS) {
  2520. log_err(LD_GENERAL,"System time is before 1970; failing.");
  2521. exit(1);
  2522. }
  2523. ft.ft_64 -= EPOCH_BIAS;
  2524. timeval->tv_sec = (unsigned) (ft.ft_64 / UNITS_PER_SEC);
  2525. timeval->tv_usec = (unsigned) ((ft.ft_64 / UNITS_PER_USEC) % USEC_PER_SEC);
  2526. #elif defined(HAVE_GETTIMEOFDAY)
  2527. if (gettimeofday(timeval, NULL)) {
  2528. log_err(LD_GENERAL,"gettimeofday failed.");
  2529. /* If gettimeofday dies, we have either given a bad timezone (we didn't),
  2530. or segfaulted.*/
  2531. exit(1);
  2532. }
  2533. #elif defined(HAVE_FTIME)
  2534. struct timeb tb;
  2535. ftime(&tb);
  2536. timeval->tv_sec = tb.time;
  2537. timeval->tv_usec = tb.millitm * 1000;
  2538. #else
  2539. #error "No way to get time."
  2540. #endif
  2541. return;
  2542. }
  2543. #if !defined(_WIN32)
  2544. /** Defined iff we need to add locks when defining fake versions of reentrant
  2545. * versions of time-related functions. */
  2546. #define TIME_FNS_NEED_LOCKS
  2547. #endif
  2548. /** Helper: Deal with confused or out-of-bounds values from localtime_r and
  2549. * friends. (On some platforms, they can give out-of-bounds values or can
  2550. * return NULL.) If <b>islocal</b>, this is a localtime result; otherwise
  2551. * it's from gmtime. The function returned <b>r</b>, when given <b>timep</b>
  2552. * as its input. If we need to store new results, store them in
  2553. * <b>resultbuf</b>. */
  2554. static struct tm *
  2555. correct_tm(int islocal, const time_t *timep, struct tm *resultbuf,
  2556. struct tm *r)
  2557. {
  2558. const char *outcome;
  2559. if (PREDICT_LIKELY(r)) {
  2560. /* We can't strftime dates after 9999 CE, and we want to avoid dates
  2561. * before 1 CE (avoiding the year 0 issue and negative years). */
  2562. if (r->tm_year > 8099) {
  2563. r->tm_year = 8099;
  2564. r->tm_mon = 11;
  2565. r->tm_mday = 31;
  2566. r->tm_yday = 364;
  2567. r->tm_hour = 23;
  2568. r->tm_min = 59;
  2569. r->tm_sec = 59;
  2570. } else if (r->tm_year < (1-1900)) {
  2571. r->tm_year = (1-1900);
  2572. r->tm_mon = 0;
  2573. r->tm_mday = 1;
  2574. r->tm_yday = 0;
  2575. r->tm_hour = 0;
  2576. r->tm_min = 0;
  2577. r->tm_sec = 0;
  2578. }
  2579. return r;
  2580. }
  2581. /* If we get here, gmtime or localtime returned NULL. It might have done
  2582. * this because of overrun or underrun, or it might have done it because of
  2583. * some other weird issue. */
  2584. if (timep) {
  2585. if (*timep < 0) {
  2586. r = resultbuf;
  2587. r->tm_year = 70; /* 1970 CE */
  2588. r->tm_mon = 0;
  2589. r->tm_mday = 1;
  2590. r->tm_yday = 0;
  2591. r->tm_hour = 0;
  2592. r->tm_min = 0 ;
  2593. r->tm_sec = 0;
  2594. outcome = "Rounding up to 1970";
  2595. goto done;
  2596. } else if (*timep >= INT32_MAX) {
  2597. /* Rounding down to INT32_MAX isn't so great, but keep in mind that we
  2598. * only do it if gmtime/localtime tells us NULL. */
  2599. r = resultbuf;
  2600. r->tm_year = 137; /* 2037 CE */
  2601. r->tm_mon = 11;
  2602. r->tm_mday = 31;
  2603. r->tm_yday = 364;
  2604. r->tm_hour = 23;
  2605. r->tm_min = 59;
  2606. r->tm_sec = 59;
  2607. outcome = "Rounding down to 2037";
  2608. goto done;
  2609. }
  2610. }
  2611. /* If we get here, then gmtime/localtime failed without getting an extreme
  2612. * value for *timep */
  2613. tor_fragile_assert();
  2614. r = resultbuf;
  2615. memset(resultbuf, 0, sizeof(struct tm));
  2616. outcome="can't recover";
  2617. done:
  2618. log_warn(LD_BUG, "%s("I64_FORMAT") failed with error %s: %s",
  2619. islocal?"localtime":"gmtime",
  2620. timep?I64_PRINTF_ARG(*timep):0,
  2621. strerror(errno),
  2622. outcome);
  2623. return r;
  2624. }
  2625. /** @{ */
  2626. /** As localtime_r, but defined for platforms that don't have it:
  2627. *
  2628. * Convert *<b>timep</b> to a struct tm in local time, and store the value in
  2629. * *<b>result</b>. Return the result on success, or NULL on failure.
  2630. */
  2631. #ifdef HAVE_LOCALTIME_R
  2632. struct tm *
  2633. tor_localtime_r(const time_t *timep, struct tm *result)
  2634. {
  2635. struct tm *r;
  2636. r = localtime_r(timep, result);
  2637. return correct_tm(1, timep, result, r);
  2638. }
  2639. #elif defined(TIME_FNS_NEED_LOCKS)
  2640. struct tm *
  2641. tor_localtime_r(const time_t *timep, struct tm *result)
  2642. {
  2643. struct tm *r;
  2644. static tor_mutex_t *m=NULL;
  2645. if (!m) { m=tor_mutex_new(); }
  2646. tor_assert(result);
  2647. tor_mutex_acquire(m);
  2648. r = localtime(timep);
  2649. if (r)
  2650. memcpy(result, r, sizeof(struct tm));
  2651. tor_mutex_release(m);
  2652. return correct_tm(1, timep, result, r);
  2653. }
  2654. #else
  2655. struct tm *
  2656. tor_localtime_r(const time_t *timep, struct tm *result)
  2657. {
  2658. struct tm *r;
  2659. tor_assert(result);
  2660. r = localtime(timep);
  2661. if (r)
  2662. memcpy(result, r, sizeof(struct tm));
  2663. return correct_tm(1, timep, result, r);
  2664. }
  2665. #endif
  2666. /** @} */
  2667. /** @{ */
  2668. /** As gmtime_r, but defined for platforms that don't have it:
  2669. *
  2670. * Convert *<b>timep</b> to a struct tm in UTC, and store the value in
  2671. * *<b>result</b>. Return the result on success, or NULL on failure.
  2672. */
  2673. #ifdef HAVE_GMTIME_R
  2674. struct tm *
  2675. tor_gmtime_r(const time_t *timep, struct tm *result)
  2676. {
  2677. struct tm *r;
  2678. r = gmtime_r(timep, result);
  2679. return correct_tm(0, timep, result, r);
  2680. }
  2681. #elif defined(TIME_FNS_NEED_LOCKS)
  2682. struct tm *
  2683. tor_gmtime_r(const time_t *timep, struct tm *result)
  2684. {
  2685. struct tm *r;
  2686. static tor_mutex_t *m=NULL;
  2687. if (!m) { m=tor_mutex_new(); }
  2688. tor_assert(result);
  2689. tor_mutex_acquire(m);
  2690. r = gmtime(timep);
  2691. if (r)
  2692. memcpy(result, r, sizeof(struct tm));
  2693. tor_mutex_release(m);
  2694. return correct_tm(0, timep, result, r);
  2695. }
  2696. #else
  2697. struct tm *
  2698. tor_gmtime_r(const time_t *timep, struct tm *result)
  2699. {
  2700. struct tm *r;
  2701. tor_assert(result);
  2702. r = gmtime(timep);
  2703. if (r)
  2704. memcpy(result, r, sizeof(struct tm));
  2705. return correct_tm(0, timep, result, r);
  2706. }
  2707. #endif
  2708. #if defined(USE_WIN32_THREADS)
  2709. void
  2710. tor_mutex_init(tor_mutex_t *m)
  2711. {
  2712. InitializeCriticalSection(&m->mutex);
  2713. }
  2714. void
  2715. tor_mutex_uninit(tor_mutex_t *m)
  2716. {
  2717. DeleteCriticalSection(&m->mutex);
  2718. }
  2719. void
  2720. tor_mutex_acquire(tor_mutex_t *m)
  2721. {
  2722. tor_assert(m);
  2723. EnterCriticalSection(&m->mutex);
  2724. }
  2725. void
  2726. tor_mutex_release(tor_mutex_t *m)
  2727. {
  2728. LeaveCriticalSection(&m->mutex);
  2729. }
  2730. unsigned long
  2731. tor_get_thread_id(void)
  2732. {
  2733. return (unsigned long)GetCurrentThreadId();
  2734. }
  2735. #elif defined(USE_PTHREADS)
  2736. /** A mutex attribute that we're going to use to tell pthreads that we want
  2737. * "reentrant" mutexes (i.e., once we can re-lock if we're already holding
  2738. * them.) */
  2739. static pthread_mutexattr_t attr_reentrant;
  2740. /** Initialize <b>mutex</b> so it can be locked. Every mutex must be set
  2741. * up with tor_mutex_init() or tor_mutex_new(); not both. */
  2742. void
  2743. tor_mutex_init(tor_mutex_t *mutex)
  2744. {
  2745. int err;
  2746. if (PREDICT_UNLIKELY(!threads_initialized))
  2747. tor_threads_init();
  2748. err = pthread_mutex_init(&mutex->mutex, &attr_reentrant);
  2749. if (PREDICT_UNLIKELY(err)) {
  2750. log_err(LD_GENERAL, "Error %d creating a mutex.", err);
  2751. tor_fragile_assert();
  2752. }
  2753. }
  2754. /** Wait until <b>m</b> is free, then acquire it. */
  2755. void
  2756. tor_mutex_acquire(tor_mutex_t *m)
  2757. {
  2758. int err;
  2759. tor_assert(m);
  2760. err = pthread_mutex_lock(&m->mutex);
  2761. if (PREDICT_UNLIKELY(err)) {
  2762. log_err(LD_GENERAL, "Error %d locking a mutex.", err);
  2763. tor_fragile_assert();
  2764. }
  2765. }
  2766. /** Release the lock <b>m</b> so another thread can have it. */
  2767. void
  2768. tor_mutex_release(tor_mutex_t *m)
  2769. {
  2770. int err;
  2771. tor_assert(m);
  2772. err = pthread_mutex_unlock(&m->mutex);
  2773. if (PREDICT_UNLIKELY(err)) {
  2774. log_err(LD_GENERAL, "Error %d unlocking a mutex.", err);
  2775. tor_fragile_assert();
  2776. }
  2777. }
  2778. /** Clean up the mutex <b>m</b> so that it no longer uses any system
  2779. * resources. Does not free <b>m</b>. This function must only be called on
  2780. * mutexes from tor_mutex_init(). */
  2781. void
  2782. tor_mutex_uninit(tor_mutex_t *m)
  2783. {
  2784. int err;
  2785. tor_assert(m);
  2786. err = pthread_mutex_destroy(&m->mutex);
  2787. if (PREDICT_UNLIKELY(err)) {
  2788. log_err(LD_GENERAL, "Error %d destroying a mutex.", err);
  2789. tor_fragile_assert();
  2790. }
  2791. }
  2792. /** Return an integer representing this thread. */
  2793. unsigned long
  2794. tor_get_thread_id(void)
  2795. {
  2796. union {
  2797. pthread_t thr;
  2798. unsigned long id;
  2799. } r;
  2800. r.thr = pthread_self();
  2801. return r.id;
  2802. }
  2803. #endif
  2804. /** Return a newly allocated, ready-for-use mutex. */
  2805. tor_mutex_t *
  2806. tor_mutex_new(void)
  2807. {
  2808. tor_mutex_t *m = tor_malloc_zero(sizeof(tor_mutex_t));
  2809. tor_mutex_init(m);
  2810. return m;
  2811. }
  2812. /** Release all storage and system resources held by <b>m</b>. */
  2813. void
  2814. tor_mutex_free(tor_mutex_t *m)
  2815. {
  2816. if (!m)
  2817. return;
  2818. tor_mutex_uninit(m);
  2819. tor_free(m);
  2820. }
  2821. /* Conditions. */
  2822. #ifdef USE_PTHREADS
  2823. #if 0
  2824. /** Cross-platform condition implementation. */
  2825. struct tor_cond_t {
  2826. pthread_cond_t cond;
  2827. };
  2828. /** Return a newly allocated condition, with nobody waiting on it. */
  2829. tor_cond_t *
  2830. tor_cond_new(void)
  2831. {
  2832. tor_cond_t *cond = tor_malloc_zero(sizeof(tor_cond_t));
  2833. if (pthread_cond_init(&cond->cond, NULL)) {
  2834. tor_free(cond);
  2835. return NULL;
  2836. }
  2837. return cond;
  2838. }
  2839. /** Release all resources held by <b>cond</b>. */
  2840. void
  2841. tor_cond_free(tor_cond_t *cond)
  2842. {
  2843. if (!cond)
  2844. return;
  2845. if (pthread_cond_destroy(&cond->cond)) {
  2846. log_warn(LD_GENERAL,"Error freeing condition: %s", strerror(errno));
  2847. return;
  2848. }
  2849. tor_free(cond);
  2850. }
  2851. /** Wait until one of the tor_cond_signal functions is called on <b>cond</b>.
  2852. * All waiters on the condition must wait holding the same <b>mutex</b>.
  2853. * Returns 0 on success, negative on failure. */
  2854. int
  2855. tor_cond_wait(tor_cond_t *cond, tor_mutex_t *mutex)
  2856. {
  2857. return pthread_cond_wait(&cond->cond, &mutex->mutex) ? -1 : 0;
  2858. }
  2859. /** Wake up one of the waiters on <b>cond</b>. */
  2860. void
  2861. tor_cond_signal_one(tor_cond_t *cond)
  2862. {
  2863. pthread_cond_signal(&cond->cond);
  2864. }
  2865. /** Wake up all of the waiters on <b>cond</b>. */
  2866. void
  2867. tor_cond_signal_all(tor_cond_t *cond)
  2868. {
  2869. pthread_cond_broadcast(&cond->cond);
  2870. }
  2871. #endif
  2872. /** Set up common structures for use by threading. */
  2873. void
  2874. tor_threads_init(void)
  2875. {
  2876. if (!threads_initialized) {
  2877. pthread_mutexattr_init(&attr_reentrant);
  2878. pthread_mutexattr_settype(&attr_reentrant, PTHREAD_MUTEX_RECURSIVE);
  2879. tor_assert(0==pthread_attr_init(&attr_detached));
  2880. tor_assert(0==pthread_attr_setdetachstate(&attr_detached, 1));
  2881. threads_initialized = 1;
  2882. set_main_thread();
  2883. }
  2884. }
  2885. #elif defined(USE_WIN32_THREADS)
  2886. #if 0
  2887. static DWORD cond_event_tls_index;
  2888. struct tor_cond_t {
  2889. CRITICAL_SECTION mutex;
  2890. smartlist_t *events;
  2891. };
  2892. tor_cond_t *
  2893. tor_cond_new(void)
  2894. {
  2895. tor_cond_t *cond = tor_malloc_zero(sizeof(tor_cond_t));
  2896. InitializeCriticalSection(&cond->mutex);
  2897. cond->events = smartlist_new();
  2898. return cond;
  2899. }
  2900. void
  2901. tor_cond_free(tor_cond_t *cond)
  2902. {
  2903. if (!cond)
  2904. return;
  2905. DeleteCriticalSection(&cond->mutex);
  2906. /* XXXX notify? */
  2907. smartlist_free(cond->events);
  2908. tor_free(cond);
  2909. }
  2910. int
  2911. tor_cond_wait(tor_cond_t *cond, tor_mutex_t *mutex)
  2912. {
  2913. HANDLE event;
  2914. int r;
  2915. tor_assert(cond);
  2916. tor_assert(mutex);
  2917. event = TlsGetValue(cond_event_tls_index);
  2918. if (!event) {
  2919. event = CreateEvent(0, FALSE, FALSE, NULL);
  2920. TlsSetValue(cond_event_tls_index, event);
  2921. }
  2922. EnterCriticalSection(&cond->mutex);
  2923. tor_assert(WaitForSingleObject(event, 0) == WAIT_TIMEOUT);
  2924. tor_assert(!smartlist_contains(cond->events, event));
  2925. smartlist_add(cond->events, event);
  2926. LeaveCriticalSection(&cond->mutex);
  2927. tor_mutex_release(mutex);
  2928. r = WaitForSingleObject(event, INFINITE);
  2929. tor_mutex_acquire(mutex);
  2930. switch (r) {
  2931. case WAIT_OBJECT_0: /* we got the mutex normally. */
  2932. break;
  2933. case WAIT_ABANDONED: /* holding thread exited. */
  2934. case WAIT_TIMEOUT: /* Should never happen. */
  2935. tor_assert(0);
  2936. break;
  2937. case WAIT_FAILED:
  2938. log_warn(LD_GENERAL, "Failed to acquire mutex: %d",(int) GetLastError());
  2939. }
  2940. return 0;
  2941. }
  2942. void
  2943. tor_cond_signal_one(tor_cond_t *cond)
  2944. {
  2945. HANDLE event;
  2946. tor_assert(cond);
  2947. EnterCriticalSection(&cond->mutex);
  2948. if ((event = smartlist_pop_last(cond->events)))
  2949. SetEvent(event);
  2950. LeaveCriticalSection(&cond->mutex);
  2951. }
  2952. void
  2953. tor_cond_signal_all(tor_cond_t *cond)
  2954. {
  2955. tor_assert(cond);
  2956. EnterCriticalSection(&cond->mutex);
  2957. SMARTLIST_FOREACH(cond->events, HANDLE, event, SetEvent(event));
  2958. smartlist_clear(cond->events);
  2959. LeaveCriticalSection(&cond->mutex);
  2960. }
  2961. #endif
  2962. void
  2963. tor_threads_init(void)
  2964. {
  2965. #if 0
  2966. cond_event_tls_index = TlsAlloc();
  2967. #endif
  2968. set_main_thread();
  2969. }
  2970. #endif
  2971. #if defined(HAVE_MLOCKALL) && HAVE_DECL_MLOCKALL && defined(RLIMIT_MEMLOCK)
  2972. /** Attempt to raise the current and max rlimit to infinity for our process.
  2973. * This only needs to be done once and can probably only be done when we have
  2974. * not already dropped privileges.
  2975. */
  2976. static int
  2977. tor_set_max_memlock(void)
  2978. {
  2979. /* Future consideration for Windows is probably SetProcessWorkingSetSize
  2980. * This is similar to setting the memory rlimit of RLIMIT_MEMLOCK
  2981. * http://msdn.microsoft.com/en-us/library/ms686234(VS.85).aspx
  2982. */
  2983. struct rlimit limit;
  2984. /* RLIM_INFINITY is -1 on some platforms. */
  2985. limit.rlim_cur = RLIM_INFINITY;
  2986. limit.rlim_max = RLIM_INFINITY;
  2987. if (setrlimit(RLIMIT_MEMLOCK, &limit) == -1) {
  2988. if (errno == EPERM) {
  2989. log_warn(LD_GENERAL, "You appear to lack permissions to change memory "
  2990. "limits. Are you root?");
  2991. }
  2992. log_warn(LD_GENERAL, "Unable to raise RLIMIT_MEMLOCK: %s",
  2993. strerror(errno));
  2994. return -1;
  2995. }
  2996. return 0;
  2997. }
  2998. #endif
  2999. /** Attempt to lock all current and all future memory pages.
  3000. * This should only be called once and while we're privileged.
  3001. * Like mlockall() we return 0 when we're successful and -1 when we're not.
  3002. * Unlike mlockall() we return 1 if we've already attempted to lock memory.
  3003. */
  3004. int
  3005. tor_mlockall(void)
  3006. {
  3007. static int memory_lock_attempted = 0;
  3008. if (memory_lock_attempted) {
  3009. return 1;
  3010. }
  3011. memory_lock_attempted = 1;
  3012. /*
  3013. * Future consideration for Windows may be VirtualLock
  3014. * VirtualLock appears to implement mlock() but not mlockall()
  3015. *
  3016. * http://msdn.microsoft.com/en-us/library/aa366895(VS.85).aspx
  3017. */
  3018. #if defined(HAVE_MLOCKALL) && HAVE_DECL_MLOCKALL && defined(RLIMIT_MEMLOCK)
  3019. if (tor_set_max_memlock() == 0) {
  3020. log_debug(LD_GENERAL, "RLIMIT_MEMLOCK is now set to RLIM_INFINITY.");
  3021. }
  3022. if (mlockall(MCL_CURRENT|MCL_FUTURE) == 0) {
  3023. log_info(LD_GENERAL, "Insecure OS paging is effectively disabled.");
  3024. return 0;
  3025. } else {
  3026. if (errno == ENOSYS) {
  3027. /* Apple - it's 2009! I'm looking at you. Grrr. */
  3028. log_notice(LD_GENERAL, "It appears that mlockall() is not available on "
  3029. "your platform.");
  3030. } else if (errno == EPERM) {
  3031. log_notice(LD_GENERAL, "It appears that you lack the permissions to "
  3032. "lock memory. Are you root?");
  3033. }
  3034. log_notice(LD_GENERAL, "Unable to lock all current and future memory "
  3035. "pages: %s", strerror(errno));
  3036. return -1;
  3037. }
  3038. #else
  3039. log_warn(LD_GENERAL, "Unable to lock memory pages. mlockall() unsupported?");
  3040. return -1;
  3041. #endif
  3042. }
  3043. /** Identity of the "main" thread */
  3044. static unsigned long main_thread_id = -1;
  3045. /** Start considering the current thread to be the 'main thread'. This has
  3046. * no effect on anything besides in_main_thread(). */
  3047. void
  3048. set_main_thread(void)
  3049. {
  3050. main_thread_id = tor_get_thread_id();
  3051. }
  3052. /** Return true iff called from the main thread. */
  3053. int
  3054. in_main_thread(void)
  3055. {
  3056. return main_thread_id == tor_get_thread_id();
  3057. }
  3058. /**
  3059. * On Windows, WSAEWOULDBLOCK is not always correct: when you see it,
  3060. * you need to ask the socket for its actual errno. Also, you need to
  3061. * get your errors from WSAGetLastError, not errno. (If you supply a
  3062. * socket of -1, we check WSAGetLastError, but don't correct
  3063. * WSAEWOULDBLOCKs.)
  3064. *
  3065. * The upshot of all of this is that when a socket call fails, you
  3066. * should call tor_socket_errno <em>at most once</em> on the failing
  3067. * socket to get the error.
  3068. */
  3069. #if defined(_WIN32)
  3070. int
  3071. tor_socket_errno(tor_socket_t sock)
  3072. {
  3073. int optval, optvallen=sizeof(optval);
  3074. int err = WSAGetLastError();
  3075. if (err == WSAEWOULDBLOCK && SOCKET_OK(sock)) {
  3076. if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval, &optvallen))
  3077. return err;
  3078. if (optval)
  3079. return optval;
  3080. }
  3081. return err;
  3082. }
  3083. #endif
  3084. #if defined(_WIN32)
  3085. #define E(code, s) { code, (s " [" #code " ]") }
  3086. struct { int code; const char *msg; } windows_socket_errors[] = {
  3087. E(WSAEINTR, "Interrupted function call"),
  3088. E(WSAEACCES, "Permission denied"),
  3089. E(WSAEFAULT, "Bad address"),
  3090. E(WSAEINVAL, "Invalid argument"),
  3091. E(WSAEMFILE, "Too many open files"),
  3092. E(WSAEWOULDBLOCK, "Resource temporarily unavailable"),
  3093. E(WSAEINPROGRESS, "Operation now in progress"),
  3094. E(WSAEALREADY, "Operation already in progress"),
  3095. E(WSAENOTSOCK, "Socket operation on nonsocket"),
  3096. E(WSAEDESTADDRREQ, "Destination address required"),
  3097. E(WSAEMSGSIZE, "Message too long"),
  3098. E(WSAEPROTOTYPE, "Protocol wrong for socket"),
  3099. E(WSAENOPROTOOPT, "Bad protocol option"),
  3100. E(WSAEPROTONOSUPPORT, "Protocol not supported"),
  3101. E(WSAESOCKTNOSUPPORT, "Socket type not supported"),
  3102. /* What's the difference between NOTSUPP and NOSUPPORT? :) */
  3103. E(WSAEOPNOTSUPP, "Operation not supported"),
  3104. E(WSAEPFNOSUPPORT, "Protocol family not supported"),
  3105. E(WSAEAFNOSUPPORT, "Address family not supported by protocol family"),
  3106. E(WSAEADDRINUSE, "Address already in use"),
  3107. E(WSAEADDRNOTAVAIL, "Cannot assign requested address"),
  3108. E(WSAENETDOWN, "Network is down"),
  3109. E(WSAENETUNREACH, "Network is unreachable"),
  3110. E(WSAENETRESET, "Network dropped connection on reset"),
  3111. E(WSAECONNABORTED, "Software caused connection abort"),
  3112. E(WSAECONNRESET, "Connection reset by peer"),
  3113. E(WSAENOBUFS, "No buffer space available"),
  3114. E(WSAEISCONN, "Socket is already connected"),
  3115. E(WSAENOTCONN, "Socket is not connected"),
  3116. E(WSAESHUTDOWN, "Cannot send after socket shutdown"),
  3117. E(WSAETIMEDOUT, "Connection timed out"),
  3118. E(WSAECONNREFUSED, "Connection refused"),
  3119. E(WSAEHOSTDOWN, "Host is down"),
  3120. E(WSAEHOSTUNREACH, "No route to host"),
  3121. E(WSAEPROCLIM, "Too many processes"),
  3122. /* Yes, some of these start with WSA, not WSAE. No, I don't know why. */
  3123. E(WSASYSNOTREADY, "Network subsystem is unavailable"),
  3124. E(WSAVERNOTSUPPORTED, "Winsock.dll out of range"),
  3125. E(WSANOTINITIALISED, "Successful WSAStartup not yet performed"),
  3126. E(WSAEDISCON, "Graceful shutdown now in progress"),
  3127. #ifdef WSATYPE_NOT_FOUND
  3128. E(WSATYPE_NOT_FOUND, "Class type not found"),
  3129. #endif
  3130. E(WSAHOST_NOT_FOUND, "Host not found"),
  3131. E(WSATRY_AGAIN, "Nonauthoritative host not found"),
  3132. E(WSANO_RECOVERY, "This is a nonrecoverable error"),
  3133. E(WSANO_DATA, "Valid name, no data record of requested type)"),
  3134. /* There are some more error codes whose numeric values are marked
  3135. * <b>OS dependent</b>. They start with WSA_, apparently for the same
  3136. * reason that practitioners of some craft traditions deliberately
  3137. * introduce imperfections into their baskets and rugs "to allow the
  3138. * evil spirits to escape." If we catch them, then our binaries
  3139. * might not report consistent results across versions of Windows.
  3140. * Thus, I'm going to let them all fall through.
  3141. */
  3142. { -1, NULL },
  3143. };
  3144. /** There does not seem to be a strerror equivalent for Winsock errors.
  3145. * Naturally, we have to roll our own.
  3146. */
  3147. const char *
  3148. tor_socket_strerror(int e)
  3149. {
  3150. int i;
  3151. for (i=0; windows_socket_errors[i].code >= 0; ++i) {
  3152. if (e == windows_socket_errors[i].code)
  3153. return windows_socket_errors[i].msg;
  3154. }
  3155. return strerror(e);
  3156. }
  3157. #endif
  3158. /** Called before we make any calls to network-related functions.
  3159. * (Some operating systems require their network libraries to be
  3160. * initialized.) */
  3161. int
  3162. network_init(void)
  3163. {
  3164. #ifdef _WIN32
  3165. /* This silly exercise is necessary before windows will allow
  3166. * gethostbyname to work. */
  3167. WSADATA WSAData;
  3168. int r;
  3169. r = WSAStartup(0x101,&WSAData);
  3170. if (r) {
  3171. log_warn(LD_NET,"Error initializing windows network layer: code was %d",r);
  3172. return -1;
  3173. }
  3174. if (sizeof(SOCKET) != sizeof(tor_socket_t)) {
  3175. log_warn(LD_BUG,"The tor_socket_t type does not match SOCKET in size; Tor "
  3176. "might not work. (Sizes are %d and %d respectively.)",
  3177. (int)sizeof(tor_socket_t), (int)sizeof(SOCKET));
  3178. }
  3179. /* WSAData.iMaxSockets might show the max sockets we're allowed to use.
  3180. * We might use it to complain if we're trying to be a server but have
  3181. * too few sockets available. */
  3182. #endif
  3183. return 0;
  3184. }
  3185. #ifdef _WIN32
  3186. /** Return a newly allocated string describing the windows system error code
  3187. * <b>err</b>. Note that error codes are different from errno. Error codes
  3188. * come from GetLastError() when a winapi call fails. errno is set only when
  3189. * ANSI functions fail. Whee. */
  3190. char *
  3191. format_win32_error(DWORD err)
  3192. {
  3193. TCHAR *str = NULL;
  3194. char *result;
  3195. DWORD n;
  3196. /* Somebody once decided that this interface was better than strerror(). */
  3197. n = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  3198. FORMAT_MESSAGE_FROM_SYSTEM |
  3199. FORMAT_MESSAGE_IGNORE_INSERTS,
  3200. NULL, err,
  3201. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  3202. (LPVOID)&str,
  3203. 0, NULL);
  3204. if (str && n) {
  3205. #ifdef UNICODE
  3206. size_t len;
  3207. if (n > 128*1024)
  3208. len = (128 * 1024) * 2 + 1; /* This shouldn't be possible, but let's
  3209. * make sure. */
  3210. else
  3211. len = n * 2 + 1;
  3212. result = tor_malloc(len);
  3213. wcstombs(result,str,len);
  3214. result[len-1] = '\0';
  3215. #else
  3216. result = tor_strdup(str);
  3217. #endif
  3218. } else {
  3219. result = tor_strdup("<unformattable error>");
  3220. }
  3221. if (str) {
  3222. LocalFree(str); /* LocalFree != free() */
  3223. }
  3224. return result;
  3225. }
  3226. #endif
  3227. #if defined(HW_PHYSMEM64)
  3228. /* This appears to be an OpenBSD thing */
  3229. #define INT64_HW_MEM HW_PHYSMEM64
  3230. #elif defined(HW_MEMSIZE)
  3231. /* OSX defines this one */
  3232. #define INT64_HW_MEM HW_MEMSIZE
  3233. #endif
  3234. /**
  3235. * Helper: try to detect the total system memory, and return it. On failure,
  3236. * return 0.
  3237. */
  3238. static uint64_t
  3239. get_total_system_memory_impl(void)
  3240. {
  3241. #if defined(__linux__)
  3242. /* On linux, sysctl is deprecated. Because proc is so awesome that you
  3243. * shouldn't _want_ to write portable code, I guess? */
  3244. unsigned long long result=0;
  3245. int fd = -1;
  3246. char *s = NULL;
  3247. const char *cp;
  3248. size_t file_size=0;
  3249. if (-1 == (fd = tor_open_cloexec("/proc/meminfo",O_RDONLY,0)))
  3250. return 0;
  3251. s = read_file_to_str_until_eof(fd, 65536, &file_size);
  3252. if (!s)
  3253. goto err;
  3254. cp = strstr(s, "MemTotal:");
  3255. if (!cp)
  3256. goto err;
  3257. /* Use the system sscanf so that space will match a wider number of space */
  3258. if (sscanf(cp, "MemTotal: %llu kB\n", &result) != 1)
  3259. goto err;
  3260. close(fd);
  3261. tor_free(s);
  3262. return result * 1024;
  3263. err:
  3264. tor_free(s);
  3265. close(fd);
  3266. return 0;
  3267. #elif defined (_WIN32)
  3268. /* Windows has MEMORYSTATUSEX; pretty straightforward. */
  3269. MEMORYSTATUSEX ms;
  3270. memset(&ms, 0, sizeof(ms));
  3271. ms.dwLength = sizeof(ms);
  3272. if (! GlobalMemoryStatusEx(&ms))
  3273. return 0;
  3274. return ms.ullTotalPhys;
  3275. #elif defined(HAVE_SYSCTL) && defined(INT64_HW_MEM)
  3276. /* On many systems, HW_PYHSMEM is clipped to 32 bits; let's use a better
  3277. * variant if we know about it. */
  3278. uint64_t memsize = 0;
  3279. size_t len = sizeof(memsize);
  3280. int mib[2] = {CTL_HW, INT64_HW_MEM};
  3281. if (sysctl(mib,2,&memsize,&len,NULL,0))
  3282. return 0;
  3283. return memsize;
  3284. #elif defined(HAVE_SYSCTL) && defined(HW_PHYSMEM)
  3285. /* On some systems (like FreeBSD I hope) you can use a size_t with
  3286. * HW_PHYSMEM. */
  3287. size_t memsize=0;
  3288. size_t len = sizeof(memsize);
  3289. int mib[2] = {CTL_HW, HW_USERMEM};
  3290. if (sysctl(mib,2,&memsize,&len,NULL,0))
  3291. return -1;
  3292. return memsize;
  3293. #else
  3294. /* I have no clue. */
  3295. return 0;
  3296. #endif
  3297. }
  3298. /**
  3299. * Try to find out how much physical memory the system has. On success,
  3300. * return 0 and set *<b>mem_out</b> to that value. On failure, return -1.
  3301. */
  3302. int
  3303. get_total_system_memory(size_t *mem_out)
  3304. {
  3305. static size_t mem_cached=0;
  3306. uint64_t m = get_total_system_memory_impl();
  3307. if (0 == m) {
  3308. /* We couldn't find our memory total */
  3309. if (0 == mem_cached) {
  3310. /* We have no cached value either */
  3311. *mem_out = 0;
  3312. return -1;
  3313. }
  3314. *mem_out = mem_cached;
  3315. return 0;
  3316. }
  3317. #if SIZE_MAX != UINT64_MAX
  3318. if (m > SIZE_MAX) {
  3319. /* I think this could happen if we're a 32-bit Tor running on a 64-bit
  3320. * system: we could have more system memory than would fit in a
  3321. * size_t. */
  3322. m = SIZE_MAX;
  3323. }
  3324. #endif
  3325. *mem_out = mem_cached = (size_t) m;
  3326. return 0;
  3327. }
  3328. #ifdef TOR_UNIT_TESTS
  3329. /** Delay for <b>msec</b> milliseconds. Only used in tests. */
  3330. void
  3331. tor_sleep_msec(int msec)
  3332. {
  3333. #ifdef _WIN32
  3334. Sleep(msec);
  3335. #elif defined(HAVE_USLEEP)
  3336. sleep(msec / 1000);
  3337. /* Some usleep()s hate sleeping more than 1 sec */
  3338. usleep((msec % 1000) * 1000);
  3339. #elif defined(HAVE_SYS_SELECT_H)
  3340. struct timeval tv = { msec / 1000, (msec % 1000) * 1000};
  3341. select(0, NULL, NULL, NULL, &tv);
  3342. #else
  3343. sleep(CEIL_DIV(msec, 1000));
  3344. #endif
  3345. }
  3346. #endif