compat.c 89 KB

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