compat.c 86 KB

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