compat.c 98 KB

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