compat.c 92 KB

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