compat.c 82 KB

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