compat.c 100 KB

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