compat.c 94 KB

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