compat.c 93 KB

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