compat.c 85 KB

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