compat.c 99 KB

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