compat.c 91 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177
  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. /** @{ */
  683. /** Some old versions of Unix didn't define constants for these values,
  684. * and instead expect you to say 0, 1, or 2. */
  685. #ifndef SEEK_SET
  686. #define SEEK_SET 0
  687. #endif
  688. #ifndef SEEK_CUR
  689. #define SEEK_CUR 1
  690. #endif
  691. #ifndef SEEK_END
  692. #define SEEK_END 2
  693. #endif
  694. /** @} */
  695. /** Return the position of <b>fd</b> with respect to the start of the file. */
  696. off_t
  697. tor_fd_getpos(int fd)
  698. {
  699. #ifdef _WIN32
  700. return (off_t) _lseek(fd, 0, SEEK_CUR);
  701. #else
  702. return (off_t) lseek(fd, 0, SEEK_CUR);
  703. #endif
  704. }
  705. /** Move <b>fd</b> to the end of the file. Return -1 on error, 0 on success.
  706. * If the file is a pipe, do nothing and succeed.
  707. **/
  708. int
  709. tor_fd_seekend(int fd)
  710. {
  711. #ifdef _WIN32
  712. return _lseek(fd, 0, SEEK_END) < 0 ? -1 : 0;
  713. #else
  714. off_t rc = lseek(fd, 0, SEEK_END) < 0 ? -1 : 0;
  715. #ifdef ESPIPE
  716. /* If we get an error and ESPIPE, then it's a pipe or a socket of a fifo:
  717. * no need to worry. */
  718. if (rc < 0 && errno == ESPIPE)
  719. rc = 0;
  720. #endif /* defined(ESPIPE) */
  721. return (rc < 0) ? -1 : 0;
  722. #endif /* defined(_WIN32) */
  723. }
  724. /** Move <b>fd</b> to position <b>pos</b> in the file. Return -1 on error, 0
  725. * on success. */
  726. int
  727. tor_fd_setpos(int fd, off_t pos)
  728. {
  729. #ifdef _WIN32
  730. return _lseek(fd, pos, SEEK_SET) < 0 ? -1 : 0;
  731. #else
  732. return lseek(fd, pos, SEEK_SET) < 0 ? -1 : 0;
  733. #endif
  734. }
  735. /** Replacement for ftruncate(fd, 0): move to the front of the file and remove
  736. * all the rest of the file. Return -1 on error, 0 on success. */
  737. int
  738. tor_ftruncate(int fd)
  739. {
  740. /* Rumor has it that some versions of ftruncate do not move the file pointer.
  741. */
  742. if (tor_fd_setpos(fd, 0) < 0)
  743. return -1;
  744. #ifdef _WIN32
  745. return _chsize(fd, 0);
  746. #else
  747. return ftruncate(fd, 0);
  748. #endif
  749. }
  750. #undef DEBUG_SOCKET_COUNTING
  751. #ifdef DEBUG_SOCKET_COUNTING
  752. /** A bitarray of all fds that should be passed to tor_socket_close(). Only
  753. * used if DEBUG_SOCKET_COUNTING is defined. */
  754. static bitarray_t *open_sockets = NULL;
  755. /** The size of <b>open_sockets</b>, in bits. */
  756. static int max_socket = -1;
  757. #endif /* defined(DEBUG_SOCKET_COUNTING) */
  758. /** Count of number of sockets currently open. (Undercounts sockets opened by
  759. * eventdns and libevent.) */
  760. static int n_sockets_open = 0;
  761. /** Mutex to protect open_sockets, max_socket, and n_sockets_open. */
  762. static tor_mutex_t *socket_accounting_mutex = NULL;
  763. /** Helper: acquire the socket accounting lock. */
  764. static inline void
  765. socket_accounting_lock(void)
  766. {
  767. if (PREDICT_UNLIKELY(!socket_accounting_mutex))
  768. socket_accounting_mutex = tor_mutex_new();
  769. tor_mutex_acquire(socket_accounting_mutex);
  770. }
  771. /** Helper: release the socket accounting lock. */
  772. static inline void
  773. socket_accounting_unlock(void)
  774. {
  775. tor_mutex_release(socket_accounting_mutex);
  776. }
  777. /** As close(), but guaranteed to work for sockets across platforms (including
  778. * Windows, where close()ing a socket doesn't work. Returns 0 on success and
  779. * the socket error code on failure. */
  780. int
  781. tor_close_socket_simple(tor_socket_t s)
  782. {
  783. int r = 0;
  784. /* On Windows, you have to call close() on fds returned by open(),
  785. * and closesocket() on fds returned by socket(). On Unix, everything
  786. * gets close()'d. We abstract this difference by always using
  787. * tor_close_socket to close sockets, and always using close() on
  788. * files.
  789. */
  790. #if defined(_WIN32)
  791. r = closesocket(s);
  792. #else
  793. r = close(s);
  794. #endif
  795. if (r != 0) {
  796. int err = tor_socket_errno(-1);
  797. log_info(LD_NET, "Close returned an error: %s", tor_socket_strerror(err));
  798. return err;
  799. }
  800. return r;
  801. }
  802. /** As tor_close_socket_simple(), but keeps track of the number
  803. * of open sockets. Returns 0 on success, -1 on failure. */
  804. MOCK_IMPL(int,
  805. tor_close_socket,(tor_socket_t s))
  806. {
  807. int r = tor_close_socket_simple(s);
  808. socket_accounting_lock();
  809. #ifdef DEBUG_SOCKET_COUNTING
  810. if (s > max_socket || ! bitarray_is_set(open_sockets, s)) {
  811. log_warn(LD_BUG, "Closing a socket (%d) that wasn't returned by tor_open_"
  812. "socket(), or that was already closed or something.", s);
  813. } else {
  814. tor_assert(open_sockets && s <= max_socket);
  815. bitarray_clear(open_sockets, s);
  816. }
  817. #endif /* defined(DEBUG_SOCKET_COUNTING) */
  818. if (r == 0) {
  819. --n_sockets_open;
  820. } else {
  821. #ifdef _WIN32
  822. if (r != WSAENOTSOCK)
  823. --n_sockets_open;
  824. #else
  825. if (r != EBADF)
  826. --n_sockets_open; // LCOV_EXCL_LINE -- EIO and EINTR too hard to force.
  827. #endif /* defined(_WIN32) */
  828. r = -1;
  829. }
  830. tor_assert_nonfatal(n_sockets_open >= 0);
  831. socket_accounting_unlock();
  832. return r;
  833. }
  834. /** @{ */
  835. #ifdef DEBUG_SOCKET_COUNTING
  836. /** Helper: if DEBUG_SOCKET_COUNTING is enabled, remember that <b>s</b> is
  837. * now an open socket. */
  838. static inline void
  839. mark_socket_open(tor_socket_t s)
  840. {
  841. /* XXXX This bitarray business will NOT work on windows: sockets aren't
  842. small ints there. */
  843. if (s > max_socket) {
  844. if (max_socket == -1) {
  845. open_sockets = bitarray_init_zero(s+128);
  846. max_socket = s+128;
  847. } else {
  848. open_sockets = bitarray_expand(open_sockets, max_socket, s+128);
  849. max_socket = s+128;
  850. }
  851. }
  852. if (bitarray_is_set(open_sockets, s)) {
  853. log_warn(LD_BUG, "I thought that %d was already open, but socket() just "
  854. "gave it to me!", s);
  855. }
  856. bitarray_set(open_sockets, s);
  857. }
  858. #else /* !(defined(DEBUG_SOCKET_COUNTING)) */
  859. #define mark_socket_open(s) ((void) (s))
  860. #endif /* defined(DEBUG_SOCKET_COUNTING) */
  861. /** @} */
  862. /** As socket(), but counts the number of open sockets. */
  863. MOCK_IMPL(tor_socket_t,
  864. tor_open_socket,(int domain, int type, int protocol))
  865. {
  866. return tor_open_socket_with_extensions(domain, type, protocol, 1, 0);
  867. }
  868. /** Mockable wrapper for connect(). */
  869. MOCK_IMPL(tor_socket_t,
  870. tor_connect_socket,(tor_socket_t sock, const struct sockaddr *address,
  871. socklen_t address_len))
  872. {
  873. return connect(sock,address,address_len);
  874. }
  875. /** As socket(), but creates a nonblocking socket and
  876. * counts the number of open sockets. */
  877. tor_socket_t
  878. tor_open_socket_nonblocking(int domain, int type, int protocol)
  879. {
  880. return tor_open_socket_with_extensions(domain, type, protocol, 1, 1);
  881. }
  882. /** As socket(), but counts the number of open sockets and handles
  883. * socket creation with either of SOCK_CLOEXEC and SOCK_NONBLOCK specified.
  884. * <b>cloexec</b> and <b>nonblock</b> should be either 0 or 1 to indicate
  885. * if the corresponding extension should be used.*/
  886. tor_socket_t
  887. tor_open_socket_with_extensions(int domain, int type, int protocol,
  888. int cloexec, int nonblock)
  889. {
  890. tor_socket_t s;
  891. /* We are about to create a new file descriptor so make sure we have
  892. * enough of them. */
  893. if (get_n_open_sockets() >= max_sockets - 1) {
  894. #ifdef _WIN32
  895. WSASetLastError(WSAEMFILE);
  896. #else
  897. errno = EMFILE;
  898. #endif
  899. return TOR_INVALID_SOCKET;
  900. }
  901. #if defined(SOCK_CLOEXEC) && defined(SOCK_NONBLOCK)
  902. int ext_flags = (cloexec ? SOCK_CLOEXEC : 0) |
  903. (nonblock ? SOCK_NONBLOCK : 0);
  904. s = socket(domain, type|ext_flags, protocol);
  905. if (SOCKET_OK(s))
  906. goto socket_ok;
  907. /* If we got an error, see if it is EINVAL. EINVAL might indicate that,
  908. * even though we were built on a system with SOCK_CLOEXEC and SOCK_NONBLOCK
  909. * support, we are running on one without. */
  910. if (errno != EINVAL)
  911. return s;
  912. #endif /* defined(SOCK_CLOEXEC) && defined(SOCK_NONBLOCK) */
  913. s = socket(domain, type, protocol);
  914. if (! SOCKET_OK(s))
  915. return s;
  916. #if defined(FD_CLOEXEC)
  917. if (cloexec) {
  918. if (fcntl(s, F_SETFD, FD_CLOEXEC) == -1) {
  919. log_warn(LD_FS,"Couldn't set FD_CLOEXEC: %s", strerror(errno));
  920. tor_close_socket_simple(s);
  921. return TOR_INVALID_SOCKET;
  922. }
  923. }
  924. #else /* !(defined(FD_CLOEXEC)) */
  925. (void)cloexec;
  926. #endif /* defined(FD_CLOEXEC) */
  927. if (nonblock) {
  928. if (set_socket_nonblocking(s) == -1) {
  929. tor_close_socket_simple(s);
  930. return TOR_INVALID_SOCKET;
  931. }
  932. }
  933. goto socket_ok; /* So that socket_ok will not be unused. */
  934. socket_ok:
  935. tor_take_socket_ownership(s);
  936. return s;
  937. }
  938. /**
  939. * For socket accounting: remember that we are the owner of the socket
  940. * <b>s</b>. This will prevent us from overallocating sockets, and prevent us
  941. * from asserting later when we close the socket <b>s</b>.
  942. */
  943. void
  944. tor_take_socket_ownership(tor_socket_t s)
  945. {
  946. socket_accounting_lock();
  947. ++n_sockets_open;
  948. mark_socket_open(s);
  949. socket_accounting_unlock();
  950. }
  951. /** As accept(), but counts the number of open sockets. */
  952. tor_socket_t
  953. tor_accept_socket(tor_socket_t sockfd, struct sockaddr *addr, socklen_t *len)
  954. {
  955. return tor_accept_socket_with_extensions(sockfd, addr, len, 1, 0);
  956. }
  957. /** As accept(), but returns a nonblocking socket and
  958. * counts the number of open sockets. */
  959. tor_socket_t
  960. tor_accept_socket_nonblocking(tor_socket_t sockfd, struct sockaddr *addr,
  961. socklen_t *len)
  962. {
  963. return tor_accept_socket_with_extensions(sockfd, addr, len, 1, 1);
  964. }
  965. /** As accept(), but counts the number of open sockets and handles
  966. * socket creation with either of SOCK_CLOEXEC and SOCK_NONBLOCK specified.
  967. * <b>cloexec</b> and <b>nonblock</b> should be either 0 or 1 to indicate
  968. * if the corresponding extension should be used.*/
  969. tor_socket_t
  970. tor_accept_socket_with_extensions(tor_socket_t sockfd, struct sockaddr *addr,
  971. socklen_t *len, int cloexec, int nonblock)
  972. {
  973. tor_socket_t s;
  974. /* We are about to create a new file descriptor so make sure we have
  975. * enough of them. */
  976. if (get_n_open_sockets() >= max_sockets - 1) {
  977. #ifdef _WIN32
  978. WSASetLastError(WSAEMFILE);
  979. #else
  980. errno = EMFILE;
  981. #endif
  982. return TOR_INVALID_SOCKET;
  983. }
  984. #if defined(HAVE_ACCEPT4) && defined(SOCK_CLOEXEC) \
  985. && defined(SOCK_NONBLOCK)
  986. int ext_flags = (cloexec ? SOCK_CLOEXEC : 0) |
  987. (nonblock ? SOCK_NONBLOCK : 0);
  988. s = accept4(sockfd, addr, len, ext_flags);
  989. if (SOCKET_OK(s))
  990. goto socket_ok;
  991. /* If we got an error, see if it is ENOSYS. ENOSYS indicates that,
  992. * even though we were built on a system with accept4 support, we
  993. * are running on one without. Also, check for EINVAL, which indicates that
  994. * we are missing SOCK_CLOEXEC/SOCK_NONBLOCK support. */
  995. if (errno != EINVAL && errno != ENOSYS)
  996. return s;
  997. #endif /* defined(HAVE_ACCEPT4) && defined(SOCK_CLOEXEC) ... */
  998. s = accept(sockfd, addr, len);
  999. if (!SOCKET_OK(s))
  1000. return s;
  1001. #if defined(FD_CLOEXEC)
  1002. if (cloexec) {
  1003. if (fcntl(s, F_SETFD, FD_CLOEXEC) == -1) {
  1004. log_warn(LD_NET, "Couldn't set FD_CLOEXEC: %s", strerror(errno));
  1005. tor_close_socket_simple(s);
  1006. return TOR_INVALID_SOCKET;
  1007. }
  1008. }
  1009. #else /* !(defined(FD_CLOEXEC)) */
  1010. (void)cloexec;
  1011. #endif /* defined(FD_CLOEXEC) */
  1012. if (nonblock) {
  1013. if (set_socket_nonblocking(s) == -1) {
  1014. tor_close_socket_simple(s);
  1015. return TOR_INVALID_SOCKET;
  1016. }
  1017. }
  1018. goto socket_ok; /* So that socket_ok will not be unused. */
  1019. socket_ok:
  1020. tor_take_socket_ownership(s);
  1021. return s;
  1022. }
  1023. /** Return the number of sockets we currently have opened. */
  1024. int
  1025. get_n_open_sockets(void)
  1026. {
  1027. int n;
  1028. socket_accounting_lock();
  1029. n = n_sockets_open;
  1030. socket_accounting_unlock();
  1031. return n;
  1032. }
  1033. /** Mockable wrapper for getsockname(). */
  1034. MOCK_IMPL(int,
  1035. tor_getsockname,(tor_socket_t sock, struct sockaddr *address,
  1036. socklen_t *address_len))
  1037. {
  1038. return getsockname(sock, address, address_len);
  1039. }
  1040. /**
  1041. * Find the local address associated with the socket <b>sock</b>, and
  1042. * place it in *<b>addr_out</b>. Return 0 on success, -1 on failure.
  1043. *
  1044. * (As tor_getsockname, but instead places the result in a tor_addr_t.) */
  1045. int
  1046. tor_addr_from_getsockname(tor_addr_t *addr_out, tor_socket_t sock)
  1047. {
  1048. struct sockaddr_storage ss;
  1049. socklen_t ss_len = sizeof(ss);
  1050. memset(&ss, 0, sizeof(ss));
  1051. if (tor_getsockname(sock, (struct sockaddr *) &ss, &ss_len) < 0)
  1052. return -1;
  1053. return tor_addr_from_sockaddr(addr_out, (struct sockaddr *)&ss, NULL);
  1054. }
  1055. /** Turn <b>socket</b> into a nonblocking socket. Return 0 on success, -1
  1056. * on failure.
  1057. */
  1058. int
  1059. set_socket_nonblocking(tor_socket_t sock)
  1060. {
  1061. #if defined(_WIN32)
  1062. unsigned long nonblocking = 1;
  1063. ioctlsocket(sock, FIONBIO, (unsigned long*) &nonblocking);
  1064. #else
  1065. int flags;
  1066. flags = fcntl(sock, F_GETFL, 0);
  1067. if (flags == -1) {
  1068. log_warn(LD_NET, "Couldn't get file status flags: %s", strerror(errno));
  1069. return -1;
  1070. }
  1071. flags |= O_NONBLOCK;
  1072. if (fcntl(sock, F_SETFL, flags) == -1) {
  1073. log_warn(LD_NET, "Couldn't set file status flags: %s", strerror(errno));
  1074. return -1;
  1075. }
  1076. #endif /* defined(_WIN32) */
  1077. return 0;
  1078. }
  1079. /**
  1080. * Allocate a pair of connected sockets. (Like socketpair(family,
  1081. * type,protocol,fd), but works on systems that don't have
  1082. * socketpair.)
  1083. *
  1084. * Currently, only (AF_UNIX, SOCK_STREAM, 0) sockets are supported.
  1085. *
  1086. * Note that on systems without socketpair, this call will fail if
  1087. * localhost is inaccessible (for example, if the networking
  1088. * stack is down). And even if it succeeds, the socket pair will not
  1089. * be able to read while localhost is down later (the socket pair may
  1090. * even close, depending on OS-specific timeouts).
  1091. *
  1092. * Returns 0 on success and -errno on failure; do not rely on the value
  1093. * of errno or WSAGetLastError().
  1094. **/
  1095. /* It would be nicer just to set errno, but that won't work for windows. */
  1096. int
  1097. tor_socketpair(int family, int type, int protocol, tor_socket_t fd[2])
  1098. {
  1099. //don't use win32 socketpairs (they are always bad)
  1100. #if defined(HAVE_SOCKETPAIR) && !defined(_WIN32)
  1101. int r;
  1102. #ifdef SOCK_CLOEXEC
  1103. r = socketpair(family, type|SOCK_CLOEXEC, protocol, fd);
  1104. if (r == 0)
  1105. goto sockets_ok;
  1106. /* If we got an error, see if it is EINVAL. EINVAL might indicate that,
  1107. * even though we were built on a system with SOCK_CLOEXEC support, we
  1108. * are running on one without. */
  1109. if (errno != EINVAL)
  1110. return -errno;
  1111. #endif /* defined(SOCK_CLOEXEC) */
  1112. r = socketpair(family, type, protocol, fd);
  1113. if (r < 0)
  1114. return -errno;
  1115. #if defined(FD_CLOEXEC)
  1116. if (SOCKET_OK(fd[0])) {
  1117. r = fcntl(fd[0], F_SETFD, FD_CLOEXEC);
  1118. if (r == -1) {
  1119. close(fd[0]);
  1120. close(fd[1]);
  1121. return -errno;
  1122. }
  1123. }
  1124. if (SOCKET_OK(fd[1])) {
  1125. r = fcntl(fd[1], F_SETFD, FD_CLOEXEC);
  1126. if (r == -1) {
  1127. close(fd[0]);
  1128. close(fd[1]);
  1129. return -errno;
  1130. }
  1131. }
  1132. #endif /* defined(FD_CLOEXEC) */
  1133. goto sockets_ok; /* So that sockets_ok will not be unused. */
  1134. sockets_ok:
  1135. socket_accounting_lock();
  1136. if (SOCKET_OK(fd[0])) {
  1137. ++n_sockets_open;
  1138. mark_socket_open(fd[0]);
  1139. }
  1140. if (SOCKET_OK(fd[1])) {
  1141. ++n_sockets_open;
  1142. mark_socket_open(fd[1]);
  1143. }
  1144. socket_accounting_unlock();
  1145. return 0;
  1146. #else /* !(defined(HAVE_SOCKETPAIR) && !defined(_WIN32)) */
  1147. return tor_ersatz_socketpair(family, type, protocol, fd);
  1148. #endif /* defined(HAVE_SOCKETPAIR) && !defined(_WIN32) */
  1149. }
  1150. #ifdef NEED_ERSATZ_SOCKETPAIR
  1151. static inline socklen_t
  1152. SIZEOF_SOCKADDR(int domain)
  1153. {
  1154. switch (domain) {
  1155. case AF_INET:
  1156. return sizeof(struct sockaddr_in);
  1157. case AF_INET6:
  1158. return sizeof(struct sockaddr_in6);
  1159. default:
  1160. return 0;
  1161. }
  1162. }
  1163. /**
  1164. * Helper used to implement socketpair on systems that lack it, by
  1165. * making a direct connection to localhost.
  1166. */
  1167. STATIC int
  1168. tor_ersatz_socketpair(int family, int type, int protocol, tor_socket_t fd[2])
  1169. {
  1170. /* This socketpair does not work when localhost is down. So
  1171. * it's really not the same thing at all. But it's close enough
  1172. * for now, and really, when localhost is down sometimes, we
  1173. * have other problems too.
  1174. */
  1175. tor_socket_t listener = TOR_INVALID_SOCKET;
  1176. tor_socket_t connector = TOR_INVALID_SOCKET;
  1177. tor_socket_t acceptor = TOR_INVALID_SOCKET;
  1178. tor_addr_t listen_tor_addr;
  1179. struct sockaddr_storage connect_addr_ss, listen_addr_ss;
  1180. struct sockaddr *listen_addr = (struct sockaddr *) &listen_addr_ss;
  1181. uint16_t listen_port = 0;
  1182. tor_addr_t connect_tor_addr;
  1183. uint16_t connect_port = 0;
  1184. struct sockaddr *connect_addr = (struct sockaddr *) &connect_addr_ss;
  1185. socklen_t size;
  1186. int saved_errno = -1;
  1187. int ersatz_domain = AF_INET;
  1188. memset(&connect_tor_addr, 0, sizeof(connect_tor_addr));
  1189. memset(&connect_addr_ss, 0, sizeof(connect_addr_ss));
  1190. memset(&listen_tor_addr, 0, sizeof(listen_tor_addr));
  1191. memset(&listen_addr_ss, 0, sizeof(listen_addr_ss));
  1192. if (protocol
  1193. #ifdef AF_UNIX
  1194. || family != AF_UNIX
  1195. #endif
  1196. ) {
  1197. #ifdef _WIN32
  1198. return -WSAEAFNOSUPPORT;
  1199. #else
  1200. return -EAFNOSUPPORT;
  1201. #endif
  1202. }
  1203. if (!fd) {
  1204. return -EINVAL;
  1205. }
  1206. listener = tor_open_socket(ersatz_domain, type, 0);
  1207. if (!SOCKET_OK(listener)) {
  1208. int first_errno = tor_socket_errno(-1);
  1209. if (first_errno == SOCK_ERRNO(EPROTONOSUPPORT)
  1210. && ersatz_domain == AF_INET) {
  1211. /* Assume we're on an IPv6-only system */
  1212. ersatz_domain = AF_INET6;
  1213. listener = tor_open_socket(ersatz_domain, type, 0);
  1214. if (!SOCKET_OK(listener)) {
  1215. /* Keep the previous behaviour, which was to return the IPv4 error.
  1216. * (This may be less informative on IPv6-only systems.)
  1217. * XX/teor - is there a better way to decide which errno to return?
  1218. * (I doubt we care much either way, once there is an error.)
  1219. */
  1220. return -first_errno;
  1221. }
  1222. }
  1223. }
  1224. /* If there is no 127.0.0.1 or ::1, this will and must fail. Otherwise, we
  1225. * risk exposing a socketpair on a routable IP address. (Some BSD jails
  1226. * use a routable address for localhost. Fortunately, they have the real
  1227. * AF_UNIX socketpair.) */
  1228. if (ersatz_domain == AF_INET) {
  1229. tor_addr_from_ipv4h(&listen_tor_addr, INADDR_LOOPBACK);
  1230. } else {
  1231. tor_addr_parse(&listen_tor_addr, "[::1]");
  1232. }
  1233. tor_assert(tor_addr_is_loopback(&listen_tor_addr));
  1234. size = tor_addr_to_sockaddr(&listen_tor_addr,
  1235. 0 /* kernel chooses port. */,
  1236. listen_addr,
  1237. sizeof(listen_addr_ss));
  1238. if (bind(listener, listen_addr, size) == -1)
  1239. goto tidy_up_and_fail;
  1240. if (listen(listener, 1) == -1)
  1241. goto tidy_up_and_fail;
  1242. connector = tor_open_socket(ersatz_domain, type, 0);
  1243. if (!SOCKET_OK(connector))
  1244. goto tidy_up_and_fail;
  1245. /* We want to find out the port number to connect to. */
  1246. size = sizeof(connect_addr_ss);
  1247. if (getsockname(listener, connect_addr, &size) == -1)
  1248. goto tidy_up_and_fail;
  1249. if (size != SIZEOF_SOCKADDR (connect_addr->sa_family))
  1250. goto abort_tidy_up_and_fail;
  1251. if (connect(connector, connect_addr, size) == -1)
  1252. goto tidy_up_and_fail;
  1253. size = sizeof(listen_addr_ss);
  1254. acceptor = tor_accept_socket(listener, listen_addr, &size);
  1255. if (!SOCKET_OK(acceptor))
  1256. goto tidy_up_and_fail;
  1257. if (size != SIZEOF_SOCKADDR(listen_addr->sa_family))
  1258. goto abort_tidy_up_and_fail;
  1259. /* Now check we are talking to ourself by matching port and host on the
  1260. two sockets. */
  1261. if (getsockname(connector, connect_addr, &size) == -1)
  1262. goto tidy_up_and_fail;
  1263. /* Set *_tor_addr and *_port to the address and port that was used */
  1264. tor_addr_from_sockaddr(&listen_tor_addr, listen_addr, &listen_port);
  1265. tor_addr_from_sockaddr(&connect_tor_addr, connect_addr, &connect_port);
  1266. if (size != SIZEOF_SOCKADDR (connect_addr->sa_family)
  1267. || tor_addr_compare(&listen_tor_addr, &connect_tor_addr, CMP_SEMANTIC)
  1268. || listen_port != connect_port) {
  1269. goto abort_tidy_up_and_fail;
  1270. }
  1271. tor_close_socket(listener);
  1272. fd[0] = connector;
  1273. fd[1] = acceptor;
  1274. return 0;
  1275. abort_tidy_up_and_fail:
  1276. #ifdef _WIN32
  1277. saved_errno = WSAECONNABORTED;
  1278. #else
  1279. saved_errno = ECONNABORTED; /* I hope this is portable and appropriate. */
  1280. #endif
  1281. tidy_up_and_fail:
  1282. if (saved_errno < 0)
  1283. saved_errno = errno;
  1284. if (SOCKET_OK(listener))
  1285. tor_close_socket(listener);
  1286. if (SOCKET_OK(connector))
  1287. tor_close_socket(connector);
  1288. if (SOCKET_OK(acceptor))
  1289. tor_close_socket(acceptor);
  1290. return -saved_errno;
  1291. }
  1292. #undef SIZEOF_SOCKADDR
  1293. #endif /* defined(NEED_ERSATZ_SOCKETPAIR) */
  1294. /* Return the maximum number of allowed sockets. */
  1295. int
  1296. get_max_sockets(void)
  1297. {
  1298. return max_sockets;
  1299. }
  1300. /** Number of extra file descriptors to keep in reserve beyond those that we
  1301. * tell Tor it's allowed to use. */
  1302. #define ULIMIT_BUFFER 32 /* keep 32 extra fd's beyond ConnLimit_ */
  1303. /** Learn the maximum allowed number of file descriptors, and tell the
  1304. * system we want to use up to that number. (Some systems have a low soft
  1305. * limit, and let us set it higher.) We compute this by finding the largest
  1306. * number that we can use.
  1307. *
  1308. * If the limit is below the reserved file descriptor value (ULIMIT_BUFFER),
  1309. * return -1 and <b>max_out</b> is untouched.
  1310. *
  1311. * If we can't find a number greater than or equal to <b>limit</b>, then we
  1312. * fail by returning -1 and <b>max_out</b> is untouched.
  1313. *
  1314. * If we are unable to set the limit value because of setrlimit() failing,
  1315. * return 0 and <b>max_out</b> is set to the current maximum value returned
  1316. * by getrlimit().
  1317. *
  1318. * Otherwise, return 0 and store the maximum we found inside <b>max_out</b>
  1319. * and set <b>max_sockets</b> with that value as well.*/
  1320. int
  1321. set_max_file_descriptors(rlim_t limit, int *max_out)
  1322. {
  1323. if (limit < ULIMIT_BUFFER) {
  1324. log_warn(LD_CONFIG,
  1325. "ConnLimit must be at least %d. Failing.", ULIMIT_BUFFER);
  1326. return -1;
  1327. }
  1328. /* Define some maximum connections values for systems where we cannot
  1329. * automatically determine a limit. Re Cygwin, see
  1330. * http://archives.seul.org/or/talk/Aug-2006/msg00210.html
  1331. * For an iPhone, 9999 should work. For Windows and all other unknown
  1332. * systems we use 15000 as the default. */
  1333. #ifndef HAVE_GETRLIMIT
  1334. #if defined(CYGWIN) || defined(__CYGWIN__)
  1335. const char *platform = "Cygwin";
  1336. const unsigned long MAX_CONNECTIONS = 3200;
  1337. #elif defined(_WIN32)
  1338. const char *platform = "Windows";
  1339. const unsigned long MAX_CONNECTIONS = 15000;
  1340. #else
  1341. const char *platform = "unknown platforms with no getrlimit()";
  1342. const unsigned long MAX_CONNECTIONS = 15000;
  1343. #endif /* defined(CYGWIN) || defined(__CYGWIN__) || ... */
  1344. log_fn(LOG_INFO, LD_NET,
  1345. "This platform is missing getrlimit(). Proceeding.");
  1346. if (limit > MAX_CONNECTIONS) {
  1347. log_warn(LD_CONFIG,
  1348. "We do not support more than %lu file descriptors "
  1349. "on %s. Tried to raise to %lu.",
  1350. (unsigned long)MAX_CONNECTIONS, platform, (unsigned long)limit);
  1351. return -1;
  1352. }
  1353. limit = MAX_CONNECTIONS;
  1354. #else /* !(!defined(HAVE_GETRLIMIT)) */
  1355. struct rlimit rlim;
  1356. if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) {
  1357. log_warn(LD_NET, "Could not get maximum number of file descriptors: %s",
  1358. strerror(errno));
  1359. return -1;
  1360. }
  1361. if (rlim.rlim_max < limit) {
  1362. log_warn(LD_CONFIG,"We need %lu file descriptors available, and we're "
  1363. "limited to %lu. Please change your ulimit -n.",
  1364. (unsigned long)limit, (unsigned long)rlim.rlim_max);
  1365. return -1;
  1366. }
  1367. if (rlim.rlim_max > rlim.rlim_cur) {
  1368. log_info(LD_NET,"Raising max file descriptors from %lu to %lu.",
  1369. (unsigned long)rlim.rlim_cur, (unsigned long)rlim.rlim_max);
  1370. }
  1371. /* Set the current limit value so if the attempt to set the limit to the
  1372. * max fails at least we'll have a valid value of maximum sockets. */
  1373. *max_out = max_sockets = (int)rlim.rlim_cur - ULIMIT_BUFFER;
  1374. rlim.rlim_cur = rlim.rlim_max;
  1375. if (setrlimit(RLIMIT_NOFILE, &rlim) != 0) {
  1376. int couldnt_set = 1;
  1377. const int setrlimit_errno = errno;
  1378. #ifdef OPEN_MAX
  1379. uint64_t try_limit = OPEN_MAX - ULIMIT_BUFFER;
  1380. if (errno == EINVAL && try_limit < (uint64_t) rlim.rlim_cur) {
  1381. /* On some platforms, OPEN_MAX is the real limit, and getrlimit() is
  1382. * full of nasty lies. I'm looking at you, OSX 10.5.... */
  1383. rlim.rlim_cur = MIN((rlim_t) try_limit, rlim.rlim_cur);
  1384. if (setrlimit(RLIMIT_NOFILE, &rlim) == 0) {
  1385. if (rlim.rlim_cur < (rlim_t)limit) {
  1386. log_warn(LD_CONFIG, "We are limited to %lu file descriptors by "
  1387. "OPEN_MAX (%lu), and ConnLimit is %lu. Changing "
  1388. "ConnLimit; sorry.",
  1389. (unsigned long)try_limit, (unsigned long)OPEN_MAX,
  1390. (unsigned long)limit);
  1391. } else {
  1392. log_info(LD_CONFIG, "Dropped connection limit to %lu based on "
  1393. "OPEN_MAX (%lu); Apparently, %lu was too high and rlimit "
  1394. "lied to us.",
  1395. (unsigned long)try_limit, (unsigned long)OPEN_MAX,
  1396. (unsigned long)rlim.rlim_max);
  1397. }
  1398. couldnt_set = 0;
  1399. }
  1400. }
  1401. #endif /* defined(OPEN_MAX) */
  1402. if (couldnt_set) {
  1403. log_warn(LD_CONFIG,"Couldn't set maximum number of file descriptors: %s",
  1404. strerror(setrlimit_errno));
  1405. }
  1406. }
  1407. /* leave some overhead for logs, etc, */
  1408. limit = rlim.rlim_cur;
  1409. #endif /* !defined(HAVE_GETRLIMIT) */
  1410. if (limit > INT_MAX)
  1411. limit = INT_MAX;
  1412. tor_assert(max_out);
  1413. *max_out = max_sockets = (int)limit - ULIMIT_BUFFER;
  1414. return 0;
  1415. }
  1416. #ifndef _WIN32
  1417. /** Log details of current user and group credentials. Return 0 on
  1418. * success. Logs and return -1 on failure.
  1419. */
  1420. static int
  1421. log_credential_status(void)
  1422. {
  1423. /** Log level to use when describing non-error UID/GID status. */
  1424. #define CREDENTIAL_LOG_LEVEL LOG_INFO
  1425. /* Real, effective and saved UIDs */
  1426. uid_t ruid, euid, suid;
  1427. /* Read, effective and saved GIDs */
  1428. gid_t rgid, egid, sgid;
  1429. /* Supplementary groups */
  1430. gid_t *sup_gids = NULL;
  1431. int sup_gids_size;
  1432. /* Number of supplementary groups */
  1433. int ngids;
  1434. /* log UIDs */
  1435. #ifdef HAVE_GETRESUID
  1436. if (getresuid(&ruid, &euid, &suid) != 0 ) {
  1437. log_warn(LD_GENERAL, "Error getting changed UIDs: %s", strerror(errno));
  1438. return -1;
  1439. } else {
  1440. log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
  1441. "UID is %u (real), %u (effective), %u (saved)",
  1442. (unsigned)ruid, (unsigned)euid, (unsigned)suid);
  1443. }
  1444. #else /* !(defined(HAVE_GETRESUID)) */
  1445. /* getresuid is not present on MacOS X, so we can't get the saved (E)UID */
  1446. ruid = getuid();
  1447. euid = geteuid();
  1448. (void)suid;
  1449. log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
  1450. "UID is %u (real), %u (effective), unknown (saved)",
  1451. (unsigned)ruid, (unsigned)euid);
  1452. #endif /* defined(HAVE_GETRESUID) */
  1453. /* log GIDs */
  1454. #ifdef HAVE_GETRESGID
  1455. if (getresgid(&rgid, &egid, &sgid) != 0 ) {
  1456. log_warn(LD_GENERAL, "Error getting changed GIDs: %s", strerror(errno));
  1457. return -1;
  1458. } else {
  1459. log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
  1460. "GID is %u (real), %u (effective), %u (saved)",
  1461. (unsigned)rgid, (unsigned)egid, (unsigned)sgid);
  1462. }
  1463. #else /* !(defined(HAVE_GETRESGID)) */
  1464. /* getresgid is not present on MacOS X, so we can't get the saved (E)GID */
  1465. rgid = getgid();
  1466. egid = getegid();
  1467. (void)sgid;
  1468. log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
  1469. "GID is %u (real), %u (effective), unknown (saved)",
  1470. (unsigned)rgid, (unsigned)egid);
  1471. #endif /* defined(HAVE_GETRESGID) */
  1472. /* log supplementary groups */
  1473. sup_gids_size = 64;
  1474. sup_gids = tor_calloc(64, sizeof(gid_t));
  1475. while ((ngids = getgroups(sup_gids_size, sup_gids)) < 0 &&
  1476. errno == EINVAL &&
  1477. sup_gids_size < NGROUPS_MAX) {
  1478. sup_gids_size *= 2;
  1479. sup_gids = tor_reallocarray(sup_gids, sizeof(gid_t), sup_gids_size);
  1480. }
  1481. if (ngids < 0) {
  1482. log_warn(LD_GENERAL, "Error getting supplementary GIDs: %s",
  1483. strerror(errno));
  1484. tor_free(sup_gids);
  1485. return -1;
  1486. } else {
  1487. int i, retval = 0;
  1488. char *s = NULL;
  1489. smartlist_t *elts = smartlist_new();
  1490. for (i = 0; i<ngids; i++) {
  1491. smartlist_add_asprintf(elts, "%u", (unsigned)sup_gids[i]);
  1492. }
  1493. s = smartlist_join_strings(elts, " ", 0, NULL);
  1494. log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL, "Supplementary groups are: %s",s);
  1495. tor_free(s);
  1496. SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
  1497. smartlist_free(elts);
  1498. tor_free(sup_gids);
  1499. return retval;
  1500. }
  1501. return 0;
  1502. }
  1503. #endif /* !defined(_WIN32) */
  1504. #ifndef _WIN32
  1505. /** Cached struct from the last getpwname() call we did successfully. */
  1506. static struct passwd *passwd_cached = NULL;
  1507. /** Helper: copy a struct passwd object.
  1508. *
  1509. * We only copy the fields pw_uid, pw_gid, pw_name, pw_dir. Tor doesn't use
  1510. * any others, and I don't want to run into incompatibilities.
  1511. */
  1512. static struct passwd *
  1513. tor_passwd_dup(const struct passwd *pw)
  1514. {
  1515. struct passwd *new_pw = tor_malloc_zero(sizeof(struct passwd));
  1516. if (pw->pw_name)
  1517. new_pw->pw_name = tor_strdup(pw->pw_name);
  1518. if (pw->pw_dir)
  1519. new_pw->pw_dir = tor_strdup(pw->pw_dir);
  1520. new_pw->pw_uid = pw->pw_uid;
  1521. new_pw->pw_gid = pw->pw_gid;
  1522. return new_pw;
  1523. }
  1524. #define tor_passwd_free(pw) \
  1525. FREE_AND_NULL(struct passwd, tor_passwd_free_, (pw))
  1526. /** Helper: free one of our cached 'struct passwd' values. */
  1527. static void
  1528. tor_passwd_free_(struct passwd *pw)
  1529. {
  1530. if (!pw)
  1531. return;
  1532. tor_free(pw->pw_name);
  1533. tor_free(pw->pw_dir);
  1534. tor_free(pw);
  1535. }
  1536. /** Wrapper around getpwnam() that caches result. Used so that we don't need
  1537. * to give the sandbox access to /etc/passwd.
  1538. *
  1539. * The following fields alone will definitely be copied in the output: pw_uid,
  1540. * pw_gid, pw_name, pw_dir. Other fields are not present in cached values.
  1541. *
  1542. * When called with a NULL argument, this function clears storage associated
  1543. * with static variables it uses.
  1544. **/
  1545. const struct passwd *
  1546. tor_getpwnam(const char *username)
  1547. {
  1548. struct passwd *pw;
  1549. if (username == NULL) {
  1550. tor_passwd_free(passwd_cached);
  1551. passwd_cached = NULL;
  1552. return NULL;
  1553. }
  1554. if ((pw = getpwnam(username))) {
  1555. tor_passwd_free(passwd_cached);
  1556. passwd_cached = tor_passwd_dup(pw);
  1557. log_info(LD_GENERAL, "Caching new entry %s for %s",
  1558. passwd_cached->pw_name, username);
  1559. return pw;
  1560. }
  1561. /* Lookup failed */
  1562. if (! passwd_cached || ! passwd_cached->pw_name)
  1563. return NULL;
  1564. if (! strcmp(username, passwd_cached->pw_name))
  1565. return passwd_cached; // LCOV_EXCL_LINE - would need to make getpwnam flaky
  1566. return NULL;
  1567. }
  1568. /** Wrapper around getpwnam() that can use cached result from
  1569. * tor_getpwnam(). Used so that we don't need to give the sandbox access to
  1570. * /etc/passwd.
  1571. *
  1572. * The following fields alone will definitely be copied in the output: pw_uid,
  1573. * pw_gid, pw_name, pw_dir. Other fields are not present in cached values.
  1574. */
  1575. const struct passwd *
  1576. tor_getpwuid(uid_t uid)
  1577. {
  1578. struct passwd *pw;
  1579. if ((pw = getpwuid(uid))) {
  1580. return pw;
  1581. }
  1582. /* Lookup failed */
  1583. if (! passwd_cached)
  1584. return NULL;
  1585. if (uid == passwd_cached->pw_uid)
  1586. return passwd_cached; // LCOV_EXCL_LINE - would need to make getpwnam flaky
  1587. return NULL;
  1588. }
  1589. #endif /* !defined(_WIN32) */
  1590. /** Return true iff we were compiled with capability support, and capabilities
  1591. * seem to work. **/
  1592. int
  1593. have_capability_support(void)
  1594. {
  1595. #ifdef HAVE_LINUX_CAPABILITIES
  1596. cap_t caps = cap_get_proc();
  1597. if (caps == NULL)
  1598. return 0;
  1599. cap_free(caps);
  1600. return 1;
  1601. #else /* !(defined(HAVE_LINUX_CAPABILITIES)) */
  1602. return 0;
  1603. #endif /* defined(HAVE_LINUX_CAPABILITIES) */
  1604. }
  1605. #ifdef HAVE_LINUX_CAPABILITIES
  1606. /** Helper. Drop all capabilities but a small set, and set PR_KEEPCAPS as
  1607. * appropriate.
  1608. *
  1609. * If pre_setuid, retain only CAP_NET_BIND_SERVICE, CAP_SETUID, and
  1610. * CAP_SETGID, and use PR_KEEPCAPS to ensure that capabilities persist across
  1611. * setuid().
  1612. *
  1613. * If not pre_setuid, retain only CAP_NET_BIND_SERVICE, and disable
  1614. * PR_KEEPCAPS.
  1615. *
  1616. * Return 0 on success, and -1 on failure.
  1617. */
  1618. static int
  1619. drop_capabilities(int pre_setuid)
  1620. {
  1621. /* We keep these three capabilities, and these only, as we setuid.
  1622. * After we setuid, we drop all but the first. */
  1623. const cap_value_t caplist[] = {
  1624. CAP_NET_BIND_SERVICE, CAP_SETUID, CAP_SETGID
  1625. };
  1626. const char *where = pre_setuid ? "pre-setuid" : "post-setuid";
  1627. const int n_effective = pre_setuid ? 3 : 1;
  1628. const int n_permitted = pre_setuid ? 3 : 1;
  1629. const int n_inheritable = 1;
  1630. const int keepcaps = pre_setuid ? 1 : 0;
  1631. /* Sets whether we keep capabilities across a setuid. */
  1632. if (prctl(PR_SET_KEEPCAPS, keepcaps) < 0) {
  1633. log_warn(LD_CONFIG, "Unable to call prctl() %s: %s",
  1634. where, strerror(errno));
  1635. return -1;
  1636. }
  1637. cap_t caps = cap_get_proc();
  1638. if (!caps) {
  1639. log_warn(LD_CONFIG, "Unable to call cap_get_proc() %s: %s",
  1640. where, strerror(errno));
  1641. return -1;
  1642. }
  1643. cap_clear(caps);
  1644. cap_set_flag(caps, CAP_EFFECTIVE, n_effective, caplist, CAP_SET);
  1645. cap_set_flag(caps, CAP_PERMITTED, n_permitted, caplist, CAP_SET);
  1646. cap_set_flag(caps, CAP_INHERITABLE, n_inheritable, caplist, CAP_SET);
  1647. int r = cap_set_proc(caps);
  1648. cap_free(caps);
  1649. if (r < 0) {
  1650. log_warn(LD_CONFIG, "No permission to set capabilities %s: %s",
  1651. where, strerror(errno));
  1652. return -1;
  1653. }
  1654. return 0;
  1655. }
  1656. #endif /* defined(HAVE_LINUX_CAPABILITIES) */
  1657. /** Call setuid and setgid to run as <b>user</b> and switch to their
  1658. * primary group. Return 0 on success. On failure, log and return -1.
  1659. *
  1660. * If SWITCH_ID_KEEP_BINDLOW is set in 'flags', try to use the capability
  1661. * system to retain the abilitity to bind low ports.
  1662. *
  1663. * If SWITCH_ID_WARN_IF_NO_CAPS is set in flags, also warn if we have
  1664. * don't have capability support.
  1665. */
  1666. int
  1667. switch_id(const char *user, const unsigned flags)
  1668. {
  1669. #ifndef _WIN32
  1670. const struct passwd *pw = NULL;
  1671. uid_t old_uid;
  1672. gid_t old_gid;
  1673. static int have_already_switched_id = 0;
  1674. const int keep_bindlow = !!(flags & SWITCH_ID_KEEP_BINDLOW);
  1675. const int warn_if_no_caps = !!(flags & SWITCH_ID_WARN_IF_NO_CAPS);
  1676. tor_assert(user);
  1677. if (have_already_switched_id)
  1678. return 0;
  1679. /* Log the initial credential state */
  1680. if (log_credential_status())
  1681. return -1;
  1682. log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL, "Changing user and groups");
  1683. /* Get old UID/GID to check if we changed correctly */
  1684. old_uid = getuid();
  1685. old_gid = getgid();
  1686. /* Lookup the user and group information, if we have a problem, bail out. */
  1687. pw = tor_getpwnam(user);
  1688. if (pw == NULL) {
  1689. log_warn(LD_CONFIG, "Error setting configured user: %s not found", user);
  1690. return -1;
  1691. }
  1692. #ifdef HAVE_LINUX_CAPABILITIES
  1693. (void) warn_if_no_caps;
  1694. if (keep_bindlow) {
  1695. if (drop_capabilities(1))
  1696. return -1;
  1697. }
  1698. #else /* !(defined(HAVE_LINUX_CAPABILITIES)) */
  1699. (void) keep_bindlow;
  1700. if (warn_if_no_caps) {
  1701. log_warn(LD_CONFIG, "KeepBindCapabilities set, but no capability support "
  1702. "on this system.");
  1703. }
  1704. #endif /* defined(HAVE_LINUX_CAPABILITIES) */
  1705. /* Properly switch egid,gid,euid,uid here or bail out */
  1706. if (setgroups(1, &pw->pw_gid)) {
  1707. log_warn(LD_GENERAL, "Error setting groups to gid %d: \"%s\".",
  1708. (int)pw->pw_gid, strerror(errno));
  1709. if (old_uid == pw->pw_uid) {
  1710. log_warn(LD_GENERAL, "Tor is already running as %s. You do not need "
  1711. "the \"User\" option if you are already running as the user "
  1712. "you want to be. (If you did not set the User option in your "
  1713. "torrc, check whether it was specified on the command line "
  1714. "by a startup script.)", user);
  1715. } else {
  1716. log_warn(LD_GENERAL, "If you set the \"User\" option, you must start Tor"
  1717. " as root.");
  1718. }
  1719. return -1;
  1720. }
  1721. if (setegid(pw->pw_gid)) {
  1722. log_warn(LD_GENERAL, "Error setting egid to %d: %s",
  1723. (int)pw->pw_gid, strerror(errno));
  1724. return -1;
  1725. }
  1726. if (setgid(pw->pw_gid)) {
  1727. log_warn(LD_GENERAL, "Error setting gid to %d: %s",
  1728. (int)pw->pw_gid, strerror(errno));
  1729. return -1;
  1730. }
  1731. if (setuid(pw->pw_uid)) {
  1732. log_warn(LD_GENERAL, "Error setting configured uid to %s (%d): %s",
  1733. user, (int)pw->pw_uid, strerror(errno));
  1734. return -1;
  1735. }
  1736. if (seteuid(pw->pw_uid)) {
  1737. log_warn(LD_GENERAL, "Error setting configured euid to %s (%d): %s",
  1738. user, (int)pw->pw_uid, strerror(errno));
  1739. return -1;
  1740. }
  1741. /* This is how OpenBSD rolls:
  1742. if (setgroups(1, &pw->pw_gid) || setegid(pw->pw_gid) ||
  1743. setgid(pw->pw_gid) || setuid(pw->pw_uid) || seteuid(pw->pw_uid)) {
  1744. setgid(pw->pw_gid) || seteuid(pw->pw_uid) || setuid(pw->pw_uid)) {
  1745. log_warn(LD_GENERAL, "Error setting configured UID/GID: %s",
  1746. strerror(errno));
  1747. return -1;
  1748. }
  1749. */
  1750. /* We've properly switched egid, gid, euid, uid, and supplementary groups if
  1751. * we're here. */
  1752. #ifdef HAVE_LINUX_CAPABILITIES
  1753. if (keep_bindlow) {
  1754. if (drop_capabilities(0))
  1755. return -1;
  1756. }
  1757. #endif /* defined(HAVE_LINUX_CAPABILITIES) */
  1758. #if !defined(CYGWIN) && !defined(__CYGWIN__)
  1759. /* If we tried to drop privilege to a group/user other than root, attempt to
  1760. * restore root (E)(U|G)ID, and abort if the operation succeeds */
  1761. /* Only check for privilege dropping if we were asked to be non-root */
  1762. if (pw->pw_uid) {
  1763. /* Try changing GID/EGID */
  1764. if (pw->pw_gid != old_gid &&
  1765. (setgid(old_gid) != -1 || setegid(old_gid) != -1)) {
  1766. log_warn(LD_GENERAL, "Was able to restore group credentials even after "
  1767. "switching GID: this means that the setgid code didn't work.");
  1768. return -1;
  1769. }
  1770. /* Try changing UID/EUID */
  1771. if (pw->pw_uid != old_uid &&
  1772. (setuid(old_uid) != -1 || seteuid(old_uid) != -1)) {
  1773. log_warn(LD_GENERAL, "Was able to restore user credentials even after "
  1774. "switching UID: this means that the setuid code didn't work.");
  1775. return -1;
  1776. }
  1777. }
  1778. #endif /* !defined(CYGWIN) && !defined(__CYGWIN__) */
  1779. /* Check what really happened */
  1780. if (log_credential_status()) {
  1781. return -1;
  1782. }
  1783. have_already_switched_id = 1; /* mark success so we never try again */
  1784. #if defined(__linux__) && defined(HAVE_SYS_PRCTL_H) && \
  1785. defined(HAVE_PRCTL) && defined(PR_SET_DUMPABLE)
  1786. if (pw->pw_uid) {
  1787. /* Re-enable core dumps if we're not running as root. */
  1788. log_info(LD_CONFIG, "Re-enabling coredumps");
  1789. if (prctl(PR_SET_DUMPABLE, 1)) {
  1790. log_warn(LD_CONFIG, "Unable to re-enable coredumps: %s",strerror(errno));
  1791. }
  1792. }
  1793. #endif /* defined(__linux__) && defined(HAVE_SYS_PRCTL_H) && ... */
  1794. return 0;
  1795. #else /* !(!defined(_WIN32)) */
  1796. (void)user;
  1797. (void)flags;
  1798. log_warn(LD_CONFIG, "Switching users is unsupported on your OS.");
  1799. return -1;
  1800. #endif /* !defined(_WIN32) */
  1801. }
  1802. /* We only use the linux prctl for now. There is no Win32 support; this may
  1803. * also work on various BSD systems and Mac OS X - send testing feedback!
  1804. *
  1805. * On recent Gnu/Linux kernels it is possible to create a system-wide policy
  1806. * that will prevent non-root processes from attaching to other processes
  1807. * unless they are the parent process; thus gdb can attach to programs that
  1808. * they execute but they cannot attach to other processes running as the same
  1809. * user. The system wide policy may be set with the sysctl
  1810. * kernel.yama.ptrace_scope or by inspecting
  1811. * /proc/sys/kernel/yama/ptrace_scope and it is 1 by default on Ubuntu 11.04.
  1812. *
  1813. * This ptrace scope will be ignored on Gnu/Linux for users with
  1814. * CAP_SYS_PTRACE and so it is very likely that root will still be able to
  1815. * attach to the Tor process.
  1816. */
  1817. /** Attempt to disable debugger attachment: return 1 on success, -1 on
  1818. * failure, and 0 if we don't know how to try on this platform. */
  1819. int
  1820. tor_disable_debugger_attach(void)
  1821. {
  1822. int r = -1;
  1823. log_debug(LD_CONFIG,
  1824. "Attemping to disable debugger attachment to Tor for "
  1825. "unprivileged users.");
  1826. #if defined(__linux__) && defined(HAVE_SYS_PRCTL_H) \
  1827. && defined(HAVE_PRCTL) && defined(PR_SET_DUMPABLE)
  1828. #define TRIED_TO_DISABLE
  1829. r = prctl(PR_SET_DUMPABLE, 0);
  1830. #elif defined(__APPLE__) && defined(PT_DENY_ATTACH)
  1831. #define TRIED_TO_ATTACH
  1832. r = ptrace(PT_DENY_ATTACH, 0, 0, 0);
  1833. #endif /* defined(__linux__) && defined(HAVE_SYS_PRCTL_H) ... || ... */
  1834. // XXX: TODO - Mac OS X has dtrace and this may be disabled.
  1835. // XXX: TODO - Windows probably has something similar
  1836. #ifdef TRIED_TO_DISABLE
  1837. if (r == 0) {
  1838. log_debug(LD_CONFIG,"Debugger attachment disabled for "
  1839. "unprivileged users.");
  1840. return 1;
  1841. } else {
  1842. log_warn(LD_CONFIG, "Unable to disable debugger attaching: %s",
  1843. strerror(errno));
  1844. }
  1845. #endif /* defined(TRIED_TO_DISABLE) */
  1846. #undef TRIED_TO_DISABLE
  1847. return r;
  1848. }
  1849. #ifdef HAVE_PWD_H
  1850. /** Allocate and return a string containing the home directory for the
  1851. * user <b>username</b>. Only works on posix-like systems. */
  1852. char *
  1853. get_user_homedir(const char *username)
  1854. {
  1855. const struct passwd *pw;
  1856. tor_assert(username);
  1857. if (!(pw = tor_getpwnam(username))) {
  1858. log_err(LD_CONFIG,"User \"%s\" not found.", username);
  1859. return NULL;
  1860. }
  1861. return tor_strdup(pw->pw_dir);
  1862. }
  1863. #endif /* defined(HAVE_PWD_H) */
  1864. /** Modify <b>fname</b> to contain the name of its parent directory. Doesn't
  1865. * actually examine the filesystem; does a purely syntactic modification.
  1866. *
  1867. * The parent of the root director is considered to be iteself.
  1868. *
  1869. * Path separators are the forward slash (/) everywhere and additionally
  1870. * the backslash (\) on Win32.
  1871. *
  1872. * Cuts off any number of trailing path separators but otherwise ignores
  1873. * them for purposes of finding the parent directory.
  1874. *
  1875. * Returns 0 if a parent directory was successfully found, -1 otherwise (fname
  1876. * did not have any path separators or only had them at the end).
  1877. * */
  1878. int
  1879. get_parent_directory(char *fname)
  1880. {
  1881. char *cp;
  1882. int at_end = 1;
  1883. tor_assert(fname);
  1884. #ifdef _WIN32
  1885. /* If we start with, say, c:, then don't consider that the start of the path
  1886. */
  1887. if (fname[0] && fname[1] == ':') {
  1888. fname += 2;
  1889. }
  1890. #endif /* defined(_WIN32) */
  1891. /* Now we want to remove all path-separators at the end of the string,
  1892. * and to remove the end of the string starting with the path separator
  1893. * before the last non-path-separator. In perl, this would be
  1894. * s#[/]*$##; s#/[^/]*$##;
  1895. * on a unixy platform.
  1896. */
  1897. cp = fname + strlen(fname);
  1898. at_end = 1;
  1899. while (--cp >= fname) {
  1900. int is_sep = (*cp == '/'
  1901. #ifdef _WIN32
  1902. || *cp == '\\'
  1903. #endif
  1904. );
  1905. if (is_sep) {
  1906. if (cp == fname) {
  1907. /* This is the first separator in the file name; don't remove it! */
  1908. cp[1] = '\0';
  1909. return 0;
  1910. }
  1911. *cp = '\0';
  1912. if (! at_end)
  1913. return 0;
  1914. } else {
  1915. at_end = 0;
  1916. }
  1917. }
  1918. return -1;
  1919. }
  1920. #ifndef _WIN32
  1921. /** Return a newly allocated string containing the output of getcwd(). Return
  1922. * NULL on failure. (We can't just use getcwd() into a PATH_MAX buffer, since
  1923. * Hurd hasn't got a PATH_MAX.)
  1924. */
  1925. static char *
  1926. alloc_getcwd(void)
  1927. {
  1928. #ifdef HAVE_GET_CURRENT_DIR_NAME
  1929. /* Glibc makes this nice and simple for us. */
  1930. char *cwd = get_current_dir_name();
  1931. char *result = NULL;
  1932. if (cwd) {
  1933. /* We make a copy here, in case tor_malloc() is not malloc(). */
  1934. result = tor_strdup(cwd);
  1935. raw_free(cwd); // alias for free to avoid tripping check-spaces.
  1936. }
  1937. return result;
  1938. #else /* !(defined(HAVE_GET_CURRENT_DIR_NAME)) */
  1939. size_t size = 1024;
  1940. char *buf = NULL;
  1941. char *ptr = NULL;
  1942. while (ptr == NULL) {
  1943. buf = tor_realloc(buf, size);
  1944. ptr = getcwd(buf, size);
  1945. if (ptr == NULL && errno != ERANGE) {
  1946. tor_free(buf);
  1947. return NULL;
  1948. }
  1949. size *= 2;
  1950. }
  1951. return buf;
  1952. #endif /* defined(HAVE_GET_CURRENT_DIR_NAME) */
  1953. }
  1954. #endif /* !defined(_WIN32) */
  1955. /** Expand possibly relative path <b>fname</b> to an absolute path.
  1956. * Return a newly allocated string, possibly equal to <b>fname</b>. */
  1957. char *
  1958. make_path_absolute(char *fname)
  1959. {
  1960. #ifdef _WIN32
  1961. char *absfname_malloced = _fullpath(NULL, fname, 1);
  1962. /* We don't want to assume that tor_free can free a string allocated
  1963. * with malloc. On failure, return fname (it's better than nothing). */
  1964. char *absfname = tor_strdup(absfname_malloced ? absfname_malloced : fname);
  1965. if (absfname_malloced) raw_free(absfname_malloced);
  1966. return absfname;
  1967. #else /* !(defined(_WIN32)) */
  1968. char *absfname = NULL, *path = NULL;
  1969. tor_assert(fname);
  1970. if (fname[0] == '/') {
  1971. absfname = tor_strdup(fname);
  1972. } else {
  1973. path = alloc_getcwd();
  1974. if (path) {
  1975. tor_asprintf(&absfname, "%s/%s", path, fname);
  1976. tor_free(path);
  1977. } else {
  1978. /* LCOV_EXCL_START Can't make getcwd fail. */
  1979. /* If getcwd failed, the best we can do here is keep using the
  1980. * relative path. (Perhaps / isn't readable by this UID/GID.) */
  1981. log_warn(LD_GENERAL, "Unable to find current working directory: %s",
  1982. strerror(errno));
  1983. absfname = tor_strdup(fname);
  1984. /* LCOV_EXCL_STOP */
  1985. }
  1986. }
  1987. return absfname;
  1988. #endif /* defined(_WIN32) */
  1989. }
  1990. #ifndef HAVE__NSGETENVIRON
  1991. #ifndef HAVE_EXTERN_ENVIRON_DECLARED
  1992. /* Some platforms declare environ under some circumstances, others don't. */
  1993. #ifndef RUNNING_DOXYGEN
  1994. extern char **environ;
  1995. #endif
  1996. #endif /* !defined(HAVE_EXTERN_ENVIRON_DECLARED) */
  1997. #endif /* !defined(HAVE__NSGETENVIRON) */
  1998. /** Return the current environment. This is a portable replacement for
  1999. * 'environ'. */
  2000. char **
  2001. get_environment(void)
  2002. {
  2003. #ifdef HAVE__NSGETENVIRON
  2004. /* This is for compatibility between OSX versions. Otherwise (for example)
  2005. * when we do a mostly-static build on OSX 10.7, the resulting binary won't
  2006. * work on OSX 10.6. */
  2007. return *_NSGetEnviron();
  2008. #else /* !(defined(HAVE__NSGETENVIRON)) */
  2009. return environ;
  2010. #endif /* defined(HAVE__NSGETENVIRON) */
  2011. }
  2012. /** Get name of current host and write it to <b>name</b> array, whose
  2013. * length is specified by <b>namelen</b> argument. Return 0 upon
  2014. * successful completion; otherwise return return -1. (Currently,
  2015. * this function is merely a mockable wrapper for POSIX gethostname().)
  2016. */
  2017. MOCK_IMPL(int,
  2018. tor_gethostname,(char *name, size_t namelen))
  2019. {
  2020. return gethostname(name,namelen);
  2021. }
  2022. /** Set *addr to the IP address (in dotted-quad notation) stored in *str.
  2023. * Return 1 on success, 0 if *str is badly formatted.
  2024. * (Like inet_aton(str,addr), but works on Windows and Solaris.)
  2025. */
  2026. int
  2027. tor_inet_aton(const char *str, struct in_addr* addr)
  2028. {
  2029. unsigned a,b,c,d;
  2030. char more;
  2031. if (tor_sscanf(str, "%3u.%3u.%3u.%3u%c", &a,&b,&c,&d,&more) != 4)
  2032. return 0;
  2033. if (a > 255) return 0;
  2034. if (b > 255) return 0;
  2035. if (c > 255) return 0;
  2036. if (d > 255) return 0;
  2037. addr->s_addr = htonl((a<<24) | (b<<16) | (c<<8) | d);
  2038. return 1;
  2039. }
  2040. /** Given <b>af</b>==AF_INET and <b>src</b> a struct in_addr, or
  2041. * <b>af</b>==AF_INET6 and <b>src</b> a struct in6_addr, try to format the
  2042. * address and store it in the <b>len</b>-byte buffer <b>dst</b>. Returns
  2043. * <b>dst</b> on success, NULL on failure.
  2044. *
  2045. * (Like inet_ntop(af,src,dst,len), but works on platforms that don't have it:
  2046. * Tor sometimes needs to format ipv6 addresses even on platforms without ipv6
  2047. * support.) */
  2048. const char *
  2049. tor_inet_ntop(int af, const void *src, char *dst, size_t len)
  2050. {
  2051. if (af == AF_INET) {
  2052. if (tor_inet_ntoa(src, dst, len) < 0)
  2053. return NULL;
  2054. else
  2055. return dst;
  2056. } else if (af == AF_INET6) {
  2057. const struct in6_addr *addr = src;
  2058. char buf[64], *cp;
  2059. int longestGapLen = 0, longestGapPos = -1, i,
  2060. curGapPos = -1, curGapLen = 0;
  2061. uint16_t words[8];
  2062. for (i = 0; i < 8; ++i) {
  2063. words[i] = (((uint16_t)addr->s6_addr[2*i])<<8) + addr->s6_addr[2*i+1];
  2064. }
  2065. if (words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0 &&
  2066. words[4] == 0 && ((words[5] == 0 && words[6] && words[7]) ||
  2067. (words[5] == 0xffff))) {
  2068. /* This is an IPv4 address. */
  2069. if (words[5] == 0) {
  2070. tor_snprintf(buf, sizeof(buf), "::%d.%d.%d.%d",
  2071. addr->s6_addr[12], addr->s6_addr[13],
  2072. addr->s6_addr[14], addr->s6_addr[15]);
  2073. } else {
  2074. tor_snprintf(buf, sizeof(buf), "::%x:%d.%d.%d.%d", words[5],
  2075. addr->s6_addr[12], addr->s6_addr[13],
  2076. addr->s6_addr[14], addr->s6_addr[15]);
  2077. }
  2078. if ((strlen(buf) + 1) > len) /* +1 for \0 */
  2079. return NULL;
  2080. strlcpy(dst, buf, len);
  2081. return dst;
  2082. }
  2083. i = 0;
  2084. while (i < 8) {
  2085. if (words[i] == 0) {
  2086. curGapPos = i++;
  2087. curGapLen = 1;
  2088. while (i<8 && words[i] == 0) {
  2089. ++i; ++curGapLen;
  2090. }
  2091. if (curGapLen > longestGapLen) {
  2092. longestGapPos = curGapPos;
  2093. longestGapLen = curGapLen;
  2094. }
  2095. } else {
  2096. ++i;
  2097. }
  2098. }
  2099. if (longestGapLen<=1)
  2100. longestGapPos = -1;
  2101. cp = buf;
  2102. for (i = 0; i < 8; ++i) {
  2103. if (words[i] == 0 && longestGapPos == i) {
  2104. if (i == 0)
  2105. *cp++ = ':';
  2106. *cp++ = ':';
  2107. while (i < 8 && words[i] == 0)
  2108. ++i;
  2109. --i; /* to compensate for loop increment. */
  2110. } else {
  2111. tor_snprintf(cp, sizeof(buf)-(cp-buf), "%x", (unsigned)words[i]);
  2112. cp += strlen(cp);
  2113. if (i != 7)
  2114. *cp++ = ':';
  2115. }
  2116. }
  2117. *cp = '\0';
  2118. if ((strlen(buf) + 1) > len) /* +1 for \0 */
  2119. return NULL;
  2120. strlcpy(dst, buf, len);
  2121. return dst;
  2122. } else {
  2123. return NULL;
  2124. }
  2125. }
  2126. /** Given <b>af</b>==AF_INET or <b>af</b>==AF_INET6, and a string <b>src</b>
  2127. * encoding an IPv4 address or IPv6 address correspondingly, try to parse the
  2128. * address and store the result in <b>dst</b> (which must have space for a
  2129. * struct in_addr or a struct in6_addr, as appropriate). Return 1 on success,
  2130. * 0 on a bad parse, and -1 on a bad <b>af</b>.
  2131. *
  2132. * (Like inet_pton(af,src,dst) but works on platforms that don't have it: Tor
  2133. * sometimes needs to format ipv6 addresses even on platforms without ipv6
  2134. * support.) */
  2135. int
  2136. tor_inet_pton(int af, const char *src, void *dst)
  2137. {
  2138. if (af == AF_INET) {
  2139. return tor_inet_aton(src, dst);
  2140. } else if (af == AF_INET6) {
  2141. struct in6_addr *out = dst;
  2142. uint16_t words[8];
  2143. int gapPos = -1, i, setWords=0;
  2144. const char *dot = strchr(src, '.');
  2145. const char *eow; /* end of words. */
  2146. memset(words, 0xf8, sizeof(words));
  2147. if (dot == src)
  2148. return 0;
  2149. else if (!dot)
  2150. eow = src+strlen(src);
  2151. else {
  2152. unsigned byte1,byte2,byte3,byte4;
  2153. char more;
  2154. for (eow = dot-1; eow > src && TOR_ISDIGIT(*eow); --eow)
  2155. ;
  2156. if (*eow != ':')
  2157. return 0;
  2158. ++eow;
  2159. /* We use "scanf" because some platform inet_aton()s are too lax
  2160. * about IPv4 addresses of the form "1.2.3" */
  2161. if (tor_sscanf(eow, "%3u.%3u.%3u.%3u%c",
  2162. &byte1,&byte2,&byte3,&byte4,&more) != 4)
  2163. return 0;
  2164. if (byte1 > 255 || byte2 > 255 || byte3 > 255 || byte4 > 255)
  2165. return 0;
  2166. words[6] = (byte1<<8) | byte2;
  2167. words[7] = (byte3<<8) | byte4;
  2168. setWords += 2;
  2169. }
  2170. i = 0;
  2171. while (src < eow) {
  2172. if (i > 7)
  2173. return 0;
  2174. if (TOR_ISXDIGIT(*src)) {
  2175. char *next;
  2176. ssize_t len;
  2177. long r = strtol(src, &next, 16);
  2178. if (next == NULL || next == src) {
  2179. /* The 'next == src' error case can happen on versions of openbsd
  2180. * which treat "0xfoo" as an error, rather than as "0" followed by
  2181. * "xfoo". */
  2182. return 0;
  2183. }
  2184. len = *next == '\0' ? eow - src : next - src;
  2185. if (len > 4)
  2186. return 0;
  2187. if (len > 1 && !TOR_ISXDIGIT(src[1]))
  2188. return 0; /* 0x is not valid */
  2189. tor_assert(r >= 0);
  2190. tor_assert(r < 65536);
  2191. words[i++] = (uint16_t)r;
  2192. setWords++;
  2193. src = next;
  2194. if (*src != ':' && src != eow)
  2195. return 0;
  2196. ++src;
  2197. } else if (*src == ':' && i > 0 && gapPos == -1) {
  2198. gapPos = i;
  2199. ++src;
  2200. } else if (*src == ':' && i == 0 && src+1 < eow && src[1] == ':' &&
  2201. gapPos == -1) {
  2202. gapPos = i;
  2203. src += 2;
  2204. } else {
  2205. return 0;
  2206. }
  2207. }
  2208. if (setWords > 8 ||
  2209. (setWords == 8 && gapPos != -1) ||
  2210. (setWords < 8 && gapPos == -1))
  2211. return 0;
  2212. if (gapPos >= 0) {
  2213. int nToMove = setWords - (dot ? 2 : 0) - gapPos;
  2214. int gapLen = 8 - setWords;
  2215. tor_assert(nToMove >= 0);
  2216. memmove(&words[gapPos+gapLen], &words[gapPos],
  2217. sizeof(uint16_t)*nToMove);
  2218. memset(&words[gapPos], 0, sizeof(uint16_t)*gapLen);
  2219. }
  2220. for (i = 0; i < 8; ++i) {
  2221. out->s6_addr[2*i ] = words[i] >> 8;
  2222. out->s6_addr[2*i+1] = words[i] & 0xff;
  2223. }
  2224. return 1;
  2225. } else {
  2226. return -1;
  2227. }
  2228. }
  2229. /** Similar behavior to Unix gethostbyname: resolve <b>name</b>, and set
  2230. * *<b>addr</b> to the proper IP address, in host byte order. Returns 0
  2231. * on success, -1 on failure; 1 on transient failure.
  2232. *
  2233. * (This function exists because standard windows gethostbyname
  2234. * doesn't treat raw IP addresses properly.)
  2235. */
  2236. MOCK_IMPL(int,
  2237. tor_lookup_hostname,(const char *name, uint32_t *addr))
  2238. {
  2239. tor_addr_t myaddr;
  2240. int ret;
  2241. if ((ret = tor_addr_lookup(name, AF_INET, &myaddr)))
  2242. return ret;
  2243. if (tor_addr_family(&myaddr) == AF_INET) {
  2244. *addr = tor_addr_to_ipv4h(&myaddr);
  2245. return ret;
  2246. }
  2247. return -1;
  2248. }
  2249. /** Hold the result of our call to <b>uname</b>. */
  2250. static char uname_result[256];
  2251. /** True iff uname_result is set. */
  2252. static int uname_result_is_set = 0;
  2253. /** Return a pointer to a description of our platform.
  2254. */
  2255. MOCK_IMPL(const char *,
  2256. get_uname,(void))
  2257. {
  2258. #ifdef HAVE_UNAME
  2259. struct utsname u;
  2260. #endif
  2261. if (!uname_result_is_set) {
  2262. #ifdef HAVE_UNAME
  2263. if (uname(&u) != -1) {
  2264. /* (Linux says 0 is success, Solaris says 1 is success) */
  2265. strlcpy(uname_result, u.sysname, sizeof(uname_result));
  2266. } else
  2267. #endif /* defined(HAVE_UNAME) */
  2268. {
  2269. #ifdef _WIN32
  2270. OSVERSIONINFOEX info;
  2271. int i;
  2272. const char *plat = NULL;
  2273. static struct {
  2274. unsigned major; unsigned minor; const char *version;
  2275. } win_version_table[] = {
  2276. { 6, 2, "Windows 8" },
  2277. { 6, 1, "Windows 7" },
  2278. { 6, 0, "Windows Vista" },
  2279. { 5, 2, "Windows Server 2003" },
  2280. { 5, 1, "Windows XP" },
  2281. { 5, 0, "Windows 2000" },
  2282. /* { 4, 0, "Windows NT 4.0" }, */
  2283. { 4, 90, "Windows Me" },
  2284. { 4, 10, "Windows 98" },
  2285. /* { 4, 0, "Windows 95" } */
  2286. { 3, 51, "Windows NT 3.51" },
  2287. { 0, 0, NULL }
  2288. };
  2289. memset(&info, 0, sizeof(info));
  2290. info.dwOSVersionInfoSize = sizeof(info);
  2291. if (! GetVersionEx((LPOSVERSIONINFO)&info)) {
  2292. strlcpy(uname_result, "Bizarre version of Windows where GetVersionEx"
  2293. " doesn't work.", sizeof(uname_result));
  2294. uname_result_is_set = 1;
  2295. return uname_result;
  2296. }
  2297. if (info.dwMajorVersion == 4 && info.dwMinorVersion == 0) {
  2298. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  2299. plat = "Windows NT 4.0";
  2300. else
  2301. plat = "Windows 95";
  2302. } else {
  2303. for (i=0; win_version_table[i].major>0; ++i) {
  2304. if (win_version_table[i].major == info.dwMajorVersion &&
  2305. win_version_table[i].minor == info.dwMinorVersion) {
  2306. plat = win_version_table[i].version;
  2307. break;
  2308. }
  2309. }
  2310. }
  2311. if (plat) {
  2312. strlcpy(uname_result, plat, sizeof(uname_result));
  2313. } else {
  2314. if (info.dwMajorVersion > 6 ||
  2315. (info.dwMajorVersion==6 && info.dwMinorVersion>2))
  2316. tor_snprintf(uname_result, sizeof(uname_result),
  2317. "Very recent version of Windows [major=%d,minor=%d]",
  2318. (int)info.dwMajorVersion,(int)info.dwMinorVersion);
  2319. else
  2320. tor_snprintf(uname_result, sizeof(uname_result),
  2321. "Unrecognized version of Windows [major=%d,minor=%d]",
  2322. (int)info.dwMajorVersion,(int)info.dwMinorVersion);
  2323. }
  2324. #ifdef VER_NT_SERVER
  2325. if (info.wProductType == VER_NT_SERVER ||
  2326. info.wProductType == VER_NT_DOMAIN_CONTROLLER) {
  2327. strlcat(uname_result, " [server]", sizeof(uname_result));
  2328. }
  2329. #endif /* defined(VER_NT_SERVER) */
  2330. #else /* !(defined(_WIN32)) */
  2331. /* LCOV_EXCL_START -- can't provoke uname failure */
  2332. strlcpy(uname_result, "Unknown platform", sizeof(uname_result));
  2333. /* LCOV_EXCL_STOP */
  2334. #endif /* defined(_WIN32) */
  2335. }
  2336. uname_result_is_set = 1;
  2337. }
  2338. return uname_result;
  2339. }
  2340. /*
  2341. * Process control
  2342. */
  2343. /** Implementation logic for compute_num_cpus(). */
  2344. static int
  2345. compute_num_cpus_impl(void)
  2346. {
  2347. #ifdef _WIN32
  2348. SYSTEM_INFO info;
  2349. memset(&info, 0, sizeof(info));
  2350. GetSystemInfo(&info);
  2351. if (info.dwNumberOfProcessors >= 1 && info.dwNumberOfProcessors < INT_MAX)
  2352. return (int)info.dwNumberOfProcessors;
  2353. else
  2354. return -1;
  2355. #elif defined(HAVE_SYSCONF)
  2356. #ifdef _SC_NPROCESSORS_CONF
  2357. long cpus_conf = sysconf(_SC_NPROCESSORS_CONF);
  2358. #else
  2359. long cpus_conf = -1;
  2360. #endif
  2361. #ifdef _SC_NPROCESSORS_ONLN
  2362. long cpus_onln = sysconf(_SC_NPROCESSORS_ONLN);
  2363. #else
  2364. long cpus_onln = -1;
  2365. #endif
  2366. long cpus = -1;
  2367. if (cpus_conf > 0 && cpus_onln < 0) {
  2368. cpus = cpus_conf;
  2369. } else if (cpus_onln > 0 && cpus_conf < 0) {
  2370. cpus = cpus_onln;
  2371. } else if (cpus_onln > 0 && cpus_conf > 0) {
  2372. if (cpus_onln < cpus_conf) {
  2373. log_notice(LD_GENERAL, "I think we have %ld CPUS, but only %ld of them "
  2374. "are available. Telling Tor to only use %ld. You can over"
  2375. "ride this with the NumCPUs option",
  2376. cpus_conf, cpus_onln, cpus_onln);
  2377. }
  2378. cpus = cpus_onln;
  2379. }
  2380. if (cpus >= 1 && cpus < INT_MAX)
  2381. return (int)cpus;
  2382. else
  2383. return -1;
  2384. #else
  2385. return -1;
  2386. #endif /* defined(_WIN32) || ... */
  2387. }
  2388. #define MAX_DETECTABLE_CPUS 16
  2389. /** Return how many CPUs we are running with. We assume that nobody is
  2390. * using hot-swappable CPUs, so we don't recompute this after the first
  2391. * time. Return -1 if we don't know how to tell the number of CPUs on this
  2392. * system.
  2393. */
  2394. int
  2395. compute_num_cpus(void)
  2396. {
  2397. static int num_cpus = -2;
  2398. if (num_cpus == -2) {
  2399. num_cpus = compute_num_cpus_impl();
  2400. tor_assert(num_cpus != -2);
  2401. if (num_cpus > MAX_DETECTABLE_CPUS) {
  2402. /* LCOV_EXCL_START */
  2403. log_notice(LD_GENERAL, "Wow! I detected that you have %d CPUs. I "
  2404. "will not autodetect any more than %d, though. If you "
  2405. "want to configure more, set NumCPUs in your torrc",
  2406. num_cpus, MAX_DETECTABLE_CPUS);
  2407. num_cpus = MAX_DETECTABLE_CPUS;
  2408. /* LCOV_EXCL_STOP */
  2409. }
  2410. }
  2411. return num_cpus;
  2412. }
  2413. /** As localtime_r, but defined for platforms that don't have it:
  2414. *
  2415. * Convert *<b>timep</b> to a struct tm in local time, and store the value in
  2416. * *<b>result</b>. Return the result on success, or NULL on failure.
  2417. */
  2418. struct tm *
  2419. tor_localtime_r(const time_t *timep, struct tm *result)
  2420. {
  2421. char *err = NULL;
  2422. struct tm *r = tor_localtime_r_msg(timep, result, &err);
  2423. if (err) {
  2424. log_warn(LD_BUG, "%s", err);
  2425. tor_free(err);
  2426. }
  2427. return r;
  2428. }
  2429. /** As gmtime_r, but defined for platforms that don't have it:
  2430. *
  2431. * Convert *<b>timep</b> to a struct tm in UTC, and store the value in
  2432. * *<b>result</b>. Return the result on success, or NULL on failure.
  2433. */
  2434. struct tm *
  2435. tor_gmtime_r(const time_t *timep, struct tm *result)
  2436. {
  2437. char *err = NULL;
  2438. struct tm *r = tor_gmtime_r_msg(timep, result, &err);
  2439. if (err) {
  2440. log_warn(LD_BUG, "%s", err);
  2441. tor_free(err);
  2442. }
  2443. return r;
  2444. }
  2445. #if defined(HAVE_MLOCKALL) && HAVE_DECL_MLOCKALL && defined(RLIMIT_MEMLOCK)
  2446. #define HAVE_UNIX_MLOCKALL
  2447. #endif
  2448. #ifdef HAVE_UNIX_MLOCKALL
  2449. /** Attempt to raise the current and max rlimit to infinity for our process.
  2450. * This only needs to be done once and can probably only be done when we have
  2451. * not already dropped privileges.
  2452. */
  2453. static int
  2454. tor_set_max_memlock(void)
  2455. {
  2456. /* Future consideration for Windows is probably SetProcessWorkingSetSize
  2457. * This is similar to setting the memory rlimit of RLIMIT_MEMLOCK
  2458. * http://msdn.microsoft.com/en-us/library/ms686234(VS.85).aspx
  2459. */
  2460. struct rlimit limit;
  2461. /* RLIM_INFINITY is -1 on some platforms. */
  2462. limit.rlim_cur = RLIM_INFINITY;
  2463. limit.rlim_max = RLIM_INFINITY;
  2464. if (setrlimit(RLIMIT_MEMLOCK, &limit) == -1) {
  2465. if (errno == EPERM) {
  2466. log_warn(LD_GENERAL, "You appear to lack permissions to change memory "
  2467. "limits. Are you root?");
  2468. }
  2469. log_warn(LD_GENERAL, "Unable to raise RLIMIT_MEMLOCK: %s",
  2470. strerror(errno));
  2471. return -1;
  2472. }
  2473. return 0;
  2474. }
  2475. #endif /* defined(HAVE_UNIX_MLOCKALL) */
  2476. /** Attempt to lock all current and all future memory pages.
  2477. * This should only be called once and while we're privileged.
  2478. * Like mlockall() we return 0 when we're successful and -1 when we're not.
  2479. * Unlike mlockall() we return 1 if we've already attempted to lock memory.
  2480. */
  2481. int
  2482. tor_mlockall(void)
  2483. {
  2484. static int memory_lock_attempted = 0;
  2485. if (memory_lock_attempted) {
  2486. return 1;
  2487. }
  2488. memory_lock_attempted = 1;
  2489. /*
  2490. * Future consideration for Windows may be VirtualLock
  2491. * VirtualLock appears to implement mlock() but not mlockall()
  2492. *
  2493. * http://msdn.microsoft.com/en-us/library/aa366895(VS.85).aspx
  2494. */
  2495. #ifdef HAVE_UNIX_MLOCKALL
  2496. if (tor_set_max_memlock() == 0) {
  2497. log_debug(LD_GENERAL, "RLIMIT_MEMLOCK is now set to RLIM_INFINITY.");
  2498. }
  2499. if (mlockall(MCL_CURRENT|MCL_FUTURE) == 0) {
  2500. log_info(LD_GENERAL, "Insecure OS paging is effectively disabled.");
  2501. return 0;
  2502. } else {
  2503. if (errno == ENOSYS) {
  2504. /* Apple - it's 2009! I'm looking at you. Grrr. */
  2505. log_notice(LD_GENERAL, "It appears that mlockall() is not available on "
  2506. "your platform.");
  2507. } else if (errno == EPERM) {
  2508. log_notice(LD_GENERAL, "It appears that you lack the permissions to "
  2509. "lock memory. Are you root?");
  2510. }
  2511. log_notice(LD_GENERAL, "Unable to lock all current and future memory "
  2512. "pages: %s", strerror(errno));
  2513. return -1;
  2514. }
  2515. #else /* !(defined(HAVE_UNIX_MLOCKALL)) */
  2516. log_warn(LD_GENERAL, "Unable to lock memory pages. mlockall() unsupported?");
  2517. return -1;
  2518. #endif /* defined(HAVE_UNIX_MLOCKALL) */
  2519. }
  2520. /**
  2521. * On Windows, WSAEWOULDBLOCK is not always correct: when you see it,
  2522. * you need to ask the socket for its actual errno. Also, you need to
  2523. * get your errors from WSAGetLastError, not errno. (If you supply a
  2524. * socket of -1, we check WSAGetLastError, but don't correct
  2525. * WSAEWOULDBLOCKs.)
  2526. *
  2527. * The upshot of all of this is that when a socket call fails, you
  2528. * should call tor_socket_errno <em>at most once</em> on the failing
  2529. * socket to get the error.
  2530. */
  2531. #if defined(_WIN32)
  2532. int
  2533. tor_socket_errno(tor_socket_t sock)
  2534. {
  2535. int optval, optvallen=sizeof(optval);
  2536. int err = WSAGetLastError();
  2537. if (err == WSAEWOULDBLOCK && SOCKET_OK(sock)) {
  2538. if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval, &optvallen))
  2539. return err;
  2540. if (optval)
  2541. return optval;
  2542. }
  2543. return err;
  2544. }
  2545. #endif /* defined(_WIN32) */
  2546. #if defined(_WIN32)
  2547. #define E(code, s) { code, (s " [" #code " ]") }
  2548. struct { int code; const char *msg; } windows_socket_errors[] = {
  2549. E(WSAEINTR, "Interrupted function call"),
  2550. E(WSAEACCES, "Permission denied"),
  2551. E(WSAEFAULT, "Bad address"),
  2552. E(WSAEINVAL, "Invalid argument"),
  2553. E(WSAEMFILE, "Too many open files"),
  2554. E(WSAEWOULDBLOCK, "Resource temporarily unavailable"),
  2555. E(WSAEINPROGRESS, "Operation now in progress"),
  2556. E(WSAEALREADY, "Operation already in progress"),
  2557. E(WSAENOTSOCK, "Socket operation on nonsocket"),
  2558. E(WSAEDESTADDRREQ, "Destination address required"),
  2559. E(WSAEMSGSIZE, "Message too long"),
  2560. E(WSAEPROTOTYPE, "Protocol wrong for socket"),
  2561. E(WSAENOPROTOOPT, "Bad protocol option"),
  2562. E(WSAEPROTONOSUPPORT, "Protocol not supported"),
  2563. E(WSAESOCKTNOSUPPORT, "Socket type not supported"),
  2564. /* What's the difference between NOTSUPP and NOSUPPORT? :) */
  2565. E(WSAEOPNOTSUPP, "Operation not supported"),
  2566. E(WSAEPFNOSUPPORT, "Protocol family not supported"),
  2567. E(WSAEAFNOSUPPORT, "Address family not supported by protocol family"),
  2568. E(WSAEADDRINUSE, "Address already in use"),
  2569. E(WSAEADDRNOTAVAIL, "Cannot assign requested address"),
  2570. E(WSAENETDOWN, "Network is down"),
  2571. E(WSAENETUNREACH, "Network is unreachable"),
  2572. E(WSAENETRESET, "Network dropped connection on reset"),
  2573. E(WSAECONNABORTED, "Software caused connection abort"),
  2574. E(WSAECONNRESET, "Connection reset by peer"),
  2575. E(WSAENOBUFS, "No buffer space available"),
  2576. E(WSAEISCONN, "Socket is already connected"),
  2577. E(WSAENOTCONN, "Socket is not connected"),
  2578. E(WSAESHUTDOWN, "Cannot send after socket shutdown"),
  2579. E(WSAETIMEDOUT, "Connection timed out"),
  2580. E(WSAECONNREFUSED, "Connection refused"),
  2581. E(WSAEHOSTDOWN, "Host is down"),
  2582. E(WSAEHOSTUNREACH, "No route to host"),
  2583. E(WSAEPROCLIM, "Too many processes"),
  2584. /* Yes, some of these start with WSA, not WSAE. No, I don't know why. */
  2585. E(WSASYSNOTREADY, "Network subsystem is unavailable"),
  2586. E(WSAVERNOTSUPPORTED, "Winsock.dll out of range"),
  2587. E(WSANOTINITIALISED, "Successful WSAStartup not yet performed"),
  2588. E(WSAEDISCON, "Graceful shutdown now in progress"),
  2589. #ifdef WSATYPE_NOT_FOUND
  2590. E(WSATYPE_NOT_FOUND, "Class type not found"),
  2591. #endif
  2592. E(WSAHOST_NOT_FOUND, "Host not found"),
  2593. E(WSATRY_AGAIN, "Nonauthoritative host not found"),
  2594. E(WSANO_RECOVERY, "This is a nonrecoverable error"),
  2595. E(WSANO_DATA, "Valid name, no data record of requested type)"),
  2596. /* There are some more error codes whose numeric values are marked
  2597. * <b>OS dependent</b>. They start with WSA_, apparently for the same
  2598. * reason that practitioners of some craft traditions deliberately
  2599. * introduce imperfections into their baskets and rugs "to allow the
  2600. * evil spirits to escape." If we catch them, then our binaries
  2601. * might not report consistent results across versions of Windows.
  2602. * Thus, I'm going to let them all fall through.
  2603. */
  2604. { -1, NULL },
  2605. };
  2606. /** There does not seem to be a strerror equivalent for Winsock errors.
  2607. * Naturally, we have to roll our own.
  2608. */
  2609. const char *
  2610. tor_socket_strerror(int e)
  2611. {
  2612. int i;
  2613. for (i=0; windows_socket_errors[i].code >= 0; ++i) {
  2614. if (e == windows_socket_errors[i].code)
  2615. return windows_socket_errors[i].msg;
  2616. }
  2617. return strerror(e);
  2618. }
  2619. #endif /* defined(_WIN32) */
  2620. /** Called before we make any calls to network-related functions.
  2621. * (Some operating systems require their network libraries to be
  2622. * initialized.) */
  2623. int
  2624. network_init(void)
  2625. {
  2626. #ifdef _WIN32
  2627. /* This silly exercise is necessary before windows will allow
  2628. * gethostbyname to work. */
  2629. WSADATA WSAData;
  2630. int r;
  2631. r = WSAStartup(0x101,&WSAData);
  2632. if (r) {
  2633. log_warn(LD_NET,"Error initializing windows network layer: code was %d",r);
  2634. return -1;
  2635. }
  2636. if (sizeof(SOCKET) != sizeof(tor_socket_t)) {
  2637. log_warn(LD_BUG,"The tor_socket_t type does not match SOCKET in size; Tor "
  2638. "might not work. (Sizes are %d and %d respectively.)",
  2639. (int)sizeof(tor_socket_t), (int)sizeof(SOCKET));
  2640. }
  2641. /* WSAData.iMaxSockets might show the max sockets we're allowed to use.
  2642. * We might use it to complain if we're trying to be a server but have
  2643. * too few sockets available. */
  2644. #endif /* defined(_WIN32) */
  2645. return 0;
  2646. }
  2647. #ifdef _WIN32
  2648. /** Return a newly allocated string describing the windows system error code
  2649. * <b>err</b>. Note that error codes are different from errno. Error codes
  2650. * come from GetLastError() when a winapi call fails. errno is set only when
  2651. * ANSI functions fail. Whee. */
  2652. char *
  2653. format_win32_error(DWORD err)
  2654. {
  2655. TCHAR *str = NULL;
  2656. char *result;
  2657. DWORD n;
  2658. /* Somebody once decided that this interface was better than strerror(). */
  2659. n = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  2660. FORMAT_MESSAGE_FROM_SYSTEM |
  2661. FORMAT_MESSAGE_IGNORE_INSERTS,
  2662. NULL, err,
  2663. MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT),
  2664. (LPVOID)&str,
  2665. 0, NULL);
  2666. if (str && n) {
  2667. #ifdef UNICODE
  2668. size_t len;
  2669. if (n > 128*1024)
  2670. len = (128 * 1024) * 2 + 1; /* This shouldn't be possible, but let's
  2671. * make sure. */
  2672. else
  2673. len = n * 2 + 1;
  2674. result = tor_malloc(len);
  2675. wcstombs(result,str,len);
  2676. result[len-1] = '\0';
  2677. #else /* !(defined(UNICODE)) */
  2678. result = tor_strdup(str);
  2679. #endif /* defined(UNICODE) */
  2680. } else {
  2681. result = tor_strdup("<unformattable error>");
  2682. }
  2683. if (str) {
  2684. LocalFree(str); /* LocalFree != free() */
  2685. }
  2686. return result;
  2687. }
  2688. #endif /* defined(_WIN32) */
  2689. #if defined(HW_PHYSMEM64)
  2690. /* This appears to be an OpenBSD thing */
  2691. #define INT64_HW_MEM HW_PHYSMEM64
  2692. #elif defined(HW_MEMSIZE)
  2693. /* OSX defines this one */
  2694. #define INT64_HW_MEM HW_MEMSIZE
  2695. #endif /* defined(HW_PHYSMEM64) || ... */
  2696. /**
  2697. * Helper: try to detect the total system memory, and return it. On failure,
  2698. * return 0.
  2699. */
  2700. static uint64_t
  2701. get_total_system_memory_impl(void)
  2702. {
  2703. #if defined(__linux__)
  2704. /* On linux, sysctl is deprecated. Because proc is so awesome that you
  2705. * shouldn't _want_ to write portable code, I guess? */
  2706. unsigned long long result=0;
  2707. int fd = -1;
  2708. char *s = NULL;
  2709. const char *cp;
  2710. size_t file_size=0;
  2711. if (-1 == (fd = tor_open_cloexec("/proc/meminfo",O_RDONLY,0)))
  2712. return 0;
  2713. s = read_file_to_str_until_eof(fd, 65536, &file_size);
  2714. if (!s)
  2715. goto err;
  2716. cp = strstr(s, "MemTotal:");
  2717. if (!cp)
  2718. goto err;
  2719. /* Use the system sscanf so that space will match a wider number of space */
  2720. if (sscanf(cp, "MemTotal: %llu kB\n", &result) != 1)
  2721. goto err;
  2722. close(fd);
  2723. tor_free(s);
  2724. return result * 1024;
  2725. /* LCOV_EXCL_START Can't reach this unless proc is broken. */
  2726. err:
  2727. tor_free(s);
  2728. close(fd);
  2729. return 0;
  2730. /* LCOV_EXCL_STOP */
  2731. #elif defined (_WIN32)
  2732. /* Windows has MEMORYSTATUSEX; pretty straightforward. */
  2733. MEMORYSTATUSEX ms;
  2734. memset(&ms, 0, sizeof(ms));
  2735. ms.dwLength = sizeof(ms);
  2736. if (! GlobalMemoryStatusEx(&ms))
  2737. return 0;
  2738. return ms.ullTotalPhys;
  2739. #elif defined(HAVE_SYSCTL) && defined(INT64_HW_MEM)
  2740. /* On many systems, HW_PYHSMEM is clipped to 32 bits; let's use a better
  2741. * variant if we know about it. */
  2742. uint64_t memsize = 0;
  2743. size_t len = sizeof(memsize);
  2744. int mib[2] = {CTL_HW, INT64_HW_MEM};
  2745. if (sysctl(mib,2,&memsize,&len,NULL,0))
  2746. return 0;
  2747. return memsize;
  2748. #elif defined(HAVE_SYSCTL) && defined(HW_PHYSMEM)
  2749. /* On some systems (like FreeBSD I hope) you can use a size_t with
  2750. * HW_PHYSMEM. */
  2751. size_t memsize=0;
  2752. size_t len = sizeof(memsize);
  2753. int mib[2] = {CTL_HW, HW_USERMEM};
  2754. if (sysctl(mib,2,&memsize,&len,NULL,0))
  2755. return 0;
  2756. return memsize;
  2757. #else
  2758. /* I have no clue. */
  2759. return 0;
  2760. #endif /* defined(__linux__) || ... */
  2761. }
  2762. /**
  2763. * Try to find out how much physical memory the system has. On success,
  2764. * return 0 and set *<b>mem_out</b> to that value. On failure, return -1.
  2765. */
  2766. MOCK_IMPL(int,
  2767. get_total_system_memory, (size_t *mem_out))
  2768. {
  2769. static size_t mem_cached=0;
  2770. uint64_t m = get_total_system_memory_impl();
  2771. if (0 == m) {
  2772. /* LCOV_EXCL_START -- can't make this happen without mocking. */
  2773. /* We couldn't find our memory total */
  2774. if (0 == mem_cached) {
  2775. /* We have no cached value either */
  2776. *mem_out = 0;
  2777. return -1;
  2778. }
  2779. *mem_out = mem_cached;
  2780. return 0;
  2781. /* LCOV_EXCL_STOP */
  2782. }
  2783. #if SIZE_MAX != UINT64_MAX
  2784. if (m > SIZE_MAX) {
  2785. /* I think this could happen if we're a 32-bit Tor running on a 64-bit
  2786. * system: we could have more system memory than would fit in a
  2787. * size_t. */
  2788. m = SIZE_MAX;
  2789. }
  2790. #endif /* SIZE_MAX != UINT64_MAX */
  2791. *mem_out = mem_cached = (size_t) m;
  2792. return 0;
  2793. }
  2794. /** Emit the password prompt <b>prompt</b>, then read up to <b>buflen</b>
  2795. * bytes of passphrase into <b>output</b>. Return the number of bytes in
  2796. * the passphrase, excluding terminating NUL.
  2797. */
  2798. ssize_t
  2799. tor_getpass(const char *prompt, char *output, size_t buflen)
  2800. {
  2801. tor_assert(buflen <= SSIZE_MAX);
  2802. tor_assert(buflen >= 1);
  2803. #if defined(HAVE_READPASSPHRASE)
  2804. char *pwd = readpassphrase(prompt, output, buflen, RPP_ECHO_OFF);
  2805. if (pwd == NULL)
  2806. return -1;
  2807. return strlen(pwd);
  2808. #elif defined(_WIN32)
  2809. int r = -1;
  2810. while (*prompt) {
  2811. _putch(*prompt++);
  2812. }
  2813. tor_assert(buflen <= INT_MAX);
  2814. wchar_t *buf = tor_calloc(buflen, sizeof(wchar_t));
  2815. wchar_t *ptr = buf, *lastch = buf + buflen - 1;
  2816. while (ptr < lastch) {
  2817. wint_t ch = _getwch();
  2818. switch (ch) {
  2819. case '\r':
  2820. case '\n':
  2821. case WEOF:
  2822. goto done_reading;
  2823. case 3:
  2824. goto done; /* Can't actually read ctrl-c this way. */
  2825. case '\b':
  2826. if (ptr > buf)
  2827. --ptr;
  2828. continue;
  2829. case 0:
  2830. case 0xe0:
  2831. ch = _getwch(); /* Ignore; this is a function or arrow key */
  2832. break;
  2833. default:
  2834. *ptr++ = ch;
  2835. break;
  2836. }
  2837. }
  2838. done_reading:
  2839. ;
  2840. #ifndef WC_ERR_INVALID_CHARS
  2841. #define WC_ERR_INVALID_CHARS 0x80
  2842. #endif
  2843. /* Now convert it to UTF-8 */
  2844. r = WideCharToMultiByte(CP_UTF8,
  2845. WC_NO_BEST_FIT_CHARS|WC_ERR_INVALID_CHARS,
  2846. buf, (int)(ptr-buf),
  2847. output, (int)(buflen-1),
  2848. NULL, NULL);
  2849. if (r <= 0) {
  2850. r = -1;
  2851. goto done;
  2852. }
  2853. tor_assert(r < (int)buflen);
  2854. output[r] = 0;
  2855. done:
  2856. SecureZeroMemory(buf, sizeof(wchar_t)*buflen);
  2857. tor_free(buf);
  2858. return r;
  2859. #else
  2860. #error "No implementation for tor_getpass found!"
  2861. #endif /* defined(HAVE_READPASSPHRASE) || ... */
  2862. }
  2863. /** Return the amount of free disk space we have permission to use, in
  2864. * bytes. Return -1 if the amount of free space can't be determined. */
  2865. int64_t
  2866. tor_get_avail_disk_space(const char *path)
  2867. {
  2868. #ifdef HAVE_STATVFS
  2869. struct statvfs st;
  2870. int r;
  2871. memset(&st, 0, sizeof(st));
  2872. r = statvfs(path, &st);
  2873. if (r < 0)
  2874. return -1;
  2875. int64_t result = st.f_bavail;
  2876. if (st.f_frsize) {
  2877. result *= st.f_frsize;
  2878. } else if (st.f_bsize) {
  2879. result *= st.f_bsize;
  2880. } else {
  2881. return -1;
  2882. }
  2883. return result;
  2884. #elif defined(_WIN32)
  2885. ULARGE_INTEGER freeBytesAvail;
  2886. BOOL ok;
  2887. ok = GetDiskFreeSpaceEx(path, &freeBytesAvail, NULL, NULL);
  2888. if (!ok) {
  2889. return -1;
  2890. }
  2891. return (int64_t)freeBytesAvail.QuadPart;
  2892. #else
  2893. (void)path;
  2894. errno = ENOSYS;
  2895. return -1;
  2896. #endif /* defined(HAVE_STATVFS) || ... */
  2897. }