compat.c 86 KB

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