compat.c 100 KB

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