compat.c 91 KB

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