compat.c 73 KB

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