compat.c 82 KB

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