compat.c 74 KB

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