compat.c 95 KB

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