compat.c 96 KB

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