compat.c 89 KB

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