compat.c 75 KB

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