compat.c 100 KB

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