compat.c 99 KB

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