compat.c 86 KB

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