compat.c 98 KB

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