compat.c 70 KB

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