compat.c 101 KB

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