compat.c 92 KB

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