compat.c 100 KB

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