compat.c 95 KB

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