compat.c 95 KB

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