compat.c 91 KB

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