util.c 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127
  1. /* Copyright 2003 Roger Dingledine
  2. * Copyright 2004-2007 Roger Dingledine, Nick Mathewson */
  3. /* See LICENSE for licensing information */
  4. /* $Id$ */
  5. const char util_c_id[] = "$Id$";
  6. /**
  7. * \file util.c
  8. * \brief Common functions for strings, IO, network, data structures,
  9. * process control.
  10. **/
  11. /* This is required on rh7 to make strptime not complain.
  12. */
  13. #define _GNU_SOURCE
  14. #include "orconfig.h"
  15. #include "util.h"
  16. #include "log.h"
  17. #include "crypto.h"
  18. #include "torint.h"
  19. #include "container.h"
  20. #ifdef MS_WINDOWS
  21. #include <io.h>
  22. #include <direct.h>
  23. #include <process.h>
  24. #else
  25. #include <dirent.h>
  26. #include <pwd.h>
  27. #endif
  28. #ifdef HAVE_CTYPE_H
  29. #include <ctype.h>
  30. #endif
  31. #include <stdlib.h>
  32. #include <stdio.h>
  33. #include <string.h>
  34. #include <assert.h>
  35. #ifdef HAVE_NETINET_IN_H
  36. #include <netinet/in.h>
  37. #endif
  38. #ifdef HAVE_ARPA_INET_H
  39. #include <arpa/inet.h>
  40. #endif
  41. #ifdef HAVE_ERRNO_H
  42. #include <errno.h>
  43. #endif
  44. #ifdef HAVE_SYS_SOCKET_H
  45. #include <sys/socket.h>
  46. #endif
  47. #ifdef HAVE_SYS_TIME_H
  48. #include <sys/time.h>
  49. #endif
  50. #ifdef HAVE_UNISTD_H
  51. #include <unistd.h>
  52. #endif
  53. #ifdef HAVE_SYS_STAT_H
  54. #include <sys/stat.h>
  55. #endif
  56. #ifdef HAVE_SYS_FCNTL_H
  57. #include <sys/fcntl.h>
  58. #endif
  59. #ifdef HAVE_FCNTL_H
  60. #include <fcntl.h>
  61. #endif
  62. #ifdef HAVE_TIME_H
  63. #include <time.h>
  64. #endif
  65. #ifndef O_BINARY
  66. #define O_BINARY 0
  67. #endif
  68. #ifndef O_TEXT
  69. #define O_TEXT 0
  70. #endif
  71. /* =====
  72. * Memory management
  73. * ===== */
  74. #ifdef USE_DMALLOC
  75. #include <dmalloc.h>
  76. #define DMALLOC_FN_ARGS , file, line
  77. #else
  78. #define dmalloc_strdup(file, line, string, xalloc_b) strdup(string)
  79. #define dmalloc_malloc(file, line, size, func_id, alignment, xalloc_b) \
  80. malloc(size)
  81. #define DMALLOC_FUNC_MALLOC 0
  82. #define dmalloc_realloc(file, line, old_pnt, new_size, func_id, xalloc_b) \
  83. realloc((old_pnt), (new_size))
  84. #define DMALLOC_FUNC_REALLOC 0
  85. #define DMALLOC_FN_ARGS
  86. #endif
  87. /** Allocate a chunk of <b>size</b> bytes of memory, and return a pointer to
  88. * result. On error, log and terminate the process. (Same as malloc(size),
  89. * but never returns NULL.)
  90. *
  91. * <b>file</b> and <b>line</b> are used if dmalloc is enabled, and
  92. * ignored otherwise.
  93. */
  94. void *
  95. _tor_malloc(size_t size DMALLOC_PARAMS)
  96. {
  97. void *result;
  98. #ifndef MALLOC_ZERO_WORKS
  99. /* Some libcs don't do the right thing on size==0. Override them. */
  100. if (size==0) {
  101. size=1;
  102. }
  103. #endif
  104. result = dmalloc_malloc(file, line, size, DMALLOC_FUNC_MALLOC, 0, 0);
  105. if (PREDICT_UNLIKELY(result == NULL)) {
  106. log_err(LD_MM,"Out of memory on malloc(). Dying.");
  107. /* If these functions die within a worker process, they won't call
  108. * spawn_exit, but that's ok, since the parent will run out of memory soon
  109. * anyway. */
  110. exit(1);
  111. }
  112. return result;
  113. }
  114. /** Allocate a chunk of <b>size</b> bytes of memory, fill the memory with
  115. * zero bytes, and return a pointer to the result. Log and terminate
  116. * the process on error. (Same as calloc(size,1), but never returns NULL.)
  117. */
  118. void *
  119. _tor_malloc_zero(size_t size DMALLOC_PARAMS)
  120. {
  121. void *result = _tor_malloc(size DMALLOC_FN_ARGS);
  122. memset(result, 0, size);
  123. return result;
  124. }
  125. /** Change the size of the memory block pointed to by <b>ptr</b> to <b>size</b>
  126. * bytes long; return the new memory block. On error, log and
  127. * terminate. (Like realloc(ptr,size), but never returns NULL.)
  128. */
  129. void *
  130. _tor_realloc(void *ptr, size_t size DMALLOC_PARAMS)
  131. {
  132. void *result;
  133. result = dmalloc_realloc(file, line, ptr, size, DMALLOC_FUNC_REALLOC, 0);
  134. if (PREDICT_UNLIKELY(result == NULL)) {
  135. log_err(LD_MM,"Out of memory on realloc(). Dying.");
  136. exit(1);
  137. }
  138. return result;
  139. }
  140. /** Return a newly allocated copy of the NUL-terminated string s. On
  141. * error, log and terminate. (Like strdup(s), but never returns
  142. * NULL.)
  143. */
  144. char *
  145. _tor_strdup(const char *s DMALLOC_PARAMS)
  146. {
  147. char *dup;
  148. tor_assert(s);
  149. dup = dmalloc_strdup(file, line, s, 0);
  150. if (PREDICT_UNLIKELY(dup == NULL)) {
  151. log_err(LD_MM,"Out of memory on strdup(). Dying.");
  152. exit(1);
  153. }
  154. return dup;
  155. }
  156. /** Allocate and return a new string containing the first <b>n</b>
  157. * characters of <b>s</b>. If <b>s</b> is longer than <b>n</b>
  158. * characters, only the first <b>n</b> are copied. The result is
  159. * always NUL-terminated. (Like strndup(s,n), but never returns
  160. * NULL.)
  161. */
  162. char *
  163. _tor_strndup(const char *s, size_t n DMALLOC_PARAMS)
  164. {
  165. char *dup;
  166. tor_assert(s);
  167. dup = _tor_malloc((n+1) DMALLOC_FN_ARGS);
  168. /* Performance note: Ordinarily we prefer strlcpy to strncpy. But
  169. * this function gets called a whole lot, and platform strncpy is
  170. * much faster than strlcpy when strlen(s) is much longer than n.
  171. */
  172. strncpy(dup, s, n);
  173. dup[n]='\0';
  174. return dup;
  175. }
  176. /** Allocate a chunk of <b>len</b> bytes, with the same contents starting at
  177. * <b>mem</b>. */
  178. void *
  179. _tor_memdup(const void *mem, size_t len DMALLOC_PARAMS)
  180. {
  181. char *dup;
  182. tor_assert(mem);
  183. dup = _tor_malloc(len DMALLOC_FN_ARGS);
  184. memcpy(dup, mem, len);
  185. return dup;
  186. }
  187. /** Helper for places that need to take a function pointer to the right
  188. * spelling of "free()". */
  189. void
  190. _tor_free(void *mem)
  191. {
  192. tor_free(mem);
  193. }
  194. /* =====
  195. * String manipulation
  196. * ===== */
  197. /** Remove from the string <b>s</b> every character which appears in
  198. * <b>strip</b>. Return the number of characters removed. */
  199. int
  200. tor_strstrip(char *s, const char *strip)
  201. {
  202. char *read = s;
  203. while (*read) {
  204. if (strchr(strip, *read)) {
  205. ++read;
  206. } else {
  207. *s++ = *read++;
  208. }
  209. }
  210. *s = '\0';
  211. return read-s;
  212. }
  213. /** Set the <b>dest_len</b>-byte buffer <b>buf</b> to contain the
  214. * string <b>s</b>, with the string <b>insert</b> inserted after every
  215. * <b>n</b> characters. Return 0 on success, -1 on failure.
  216. *
  217. * Never end the string with <b>insert</b>, even if its length <i>is</i> a
  218. * multiple of <b>n</b>.
  219. */
  220. int
  221. tor_strpartition(char *dest, size_t dest_len,
  222. const char *s, const char *insert, size_t n)
  223. {
  224. char *destp;
  225. size_t len_in, len_out, len_ins;
  226. int is_even, remaining;
  227. tor_assert(s);
  228. tor_assert(insert);
  229. tor_assert(n > 0);
  230. tor_assert(n < SIZE_T_CEILING);
  231. tor_assert(dest_len < SIZE_T_CEILING);
  232. len_in = strlen(s);
  233. len_ins = strlen(insert);
  234. tor_assert(len_in < SIZE_T_CEILING);
  235. tor_assert(len_in/n < SIZE_T_CEILING/len_ins); /* avoid overflow */
  236. len_out = len_in + (len_in/n)*len_ins;
  237. is_even = (len_in%n) == 0;
  238. if (is_even && len_in)
  239. len_out -= len_ins;
  240. if (dest_len < len_out+1)
  241. return -1;
  242. destp = dest;
  243. remaining = len_in;
  244. while (remaining) {
  245. strncpy(destp, s, n);
  246. remaining -= n;
  247. if (remaining < 0) {
  248. break;
  249. } else if (remaining == 0) {
  250. *(destp+n) = '\0';
  251. break;
  252. }
  253. strncpy(destp+n, insert, len_ins+1);
  254. s += n;
  255. destp += n+len_ins;
  256. }
  257. tor_assert(len_out == strlen(dest));
  258. return 0;
  259. }
  260. /** Return a pointer to a NUL-terminated hexadecimal string encoding
  261. * the first <b>fromlen</b> bytes of <b>from</b>. (fromlen must be \<= 32.) The
  262. * result does not need to be deallocated, but repeated calls to
  263. * hex_str will trash old results.
  264. */
  265. const char *
  266. hex_str(const char *from, size_t fromlen)
  267. {
  268. static char buf[65];
  269. if (fromlen>(sizeof(buf)-1)/2)
  270. fromlen = (sizeof(buf)-1)/2;
  271. base16_encode(buf,sizeof(buf),from,fromlen);
  272. return buf;
  273. }
  274. /** Convert all alphabetic characters in the nul-terminated string <b>s</b> to
  275. * lowercase. */
  276. void
  277. tor_strlower(char *s)
  278. {
  279. while (*s) {
  280. *s = TOR_TOLOWER(*s);
  281. ++s;
  282. }
  283. }
  284. /** Convert all alphabetic characters in the nul-terminated string <b>s</b> to
  285. * lowercase. */
  286. void
  287. tor_strupper(char *s)
  288. {
  289. while (*s) {
  290. *s = TOR_TOUPPER(*s);
  291. ++s;
  292. }
  293. }
  294. /** Return 1 if every character in <b>s</b> is printable, else return 0.
  295. */
  296. int
  297. tor_strisprint(const char *s)
  298. {
  299. while (*s) {
  300. if (!TOR_ISPRINT(*s))
  301. return 0;
  302. s++;
  303. }
  304. return 1;
  305. }
  306. /** Return 1 if no character in <b>s</b> is uppercase, else return 0.
  307. */
  308. int
  309. tor_strisnonupper(const char *s)
  310. {
  311. while (*s) {
  312. if (TOR_ISUPPER(*s))
  313. return 0;
  314. s++;
  315. }
  316. return 1;
  317. }
  318. /** Compares the first strlen(s2) characters of s1 with s2. Returns as for
  319. * strcmp.
  320. */
  321. int
  322. strcmpstart(const char *s1, const char *s2)
  323. {
  324. size_t n = strlen(s2);
  325. return strncmp(s1, s2, n);
  326. }
  327. /** Compares the first strlen(s2) characters of s1 with s2. Returns as for
  328. * strcasecmp.
  329. */
  330. int
  331. strcasecmpstart(const char *s1, const char *s2)
  332. {
  333. size_t n = strlen(s2);
  334. return strncasecmp(s1, s2, n);
  335. }
  336. /** Compares the last strlen(s2) characters of s1 with s2. Returns as for
  337. * strcmp.
  338. */
  339. int
  340. strcmpend(const char *s1, const char *s2)
  341. {
  342. size_t n1 = strlen(s1), n2 = strlen(s2);
  343. if (n2>n1)
  344. return strcmp(s1,s2);
  345. else
  346. return strncmp(s1+(n1-n2), s2, n2);
  347. }
  348. /** Compares the last strlen(s2) characters of s1 with s2. Returns as for
  349. * strcasecmp.
  350. */
  351. int
  352. strcasecmpend(const char *s1, const char *s2)
  353. {
  354. size_t n1 = strlen(s1), n2 = strlen(s2);
  355. if (n2>n1) /* then they can't be the same; figure out which is bigger */
  356. return strcasecmp(s1,s2);
  357. else
  358. return strncasecmp(s1+(n1-n2), s2, n2);
  359. }
  360. /** Return a pointer to the first char of s that is not whitespace and
  361. * not a comment, or to the terminating NUL if no such character exists.
  362. */
  363. const char *
  364. eat_whitespace(const char *s)
  365. {
  366. tor_assert(s);
  367. while (1) {
  368. switch (*s) {
  369. case '\0':
  370. default:
  371. return s;
  372. case ' ':
  373. case '\t':
  374. case '\n':
  375. case '\r':
  376. ++s;
  377. break;
  378. case '#':
  379. ++s;
  380. while (*s && *s != '\n')
  381. ++s;
  382. }
  383. }
  384. }
  385. /** Return a pointer to the first char of s that is not whitespace and
  386. * not a comment, or to the terminating NUL if no such character exists.
  387. */
  388. const char *
  389. eat_whitespace_eos(const char *s, const char *eos)
  390. {
  391. tor_assert(s);
  392. tor_assert(eos && s <= eos);
  393. while (s < eos) {
  394. switch (*s) {
  395. case '\0':
  396. default:
  397. return s;
  398. case ' ':
  399. case '\t':
  400. case '\n':
  401. case '\r':
  402. ++s;
  403. break;
  404. case '#':
  405. ++s;
  406. while (s < eos && *s && *s != '\n')
  407. ++s;
  408. }
  409. }
  410. return s;
  411. }
  412. /** Return a pointer to the first char of s that is not a space or a tab,
  413. * or to the terminating NUL if no such character exists. */
  414. const char *
  415. eat_whitespace_no_nl(const char *s)
  416. {
  417. while (*s == ' ' || *s == '\t')
  418. ++s;
  419. return s;
  420. }
  421. /** Return a pointer to the first char of s that is whitespace or <b>#</b>,
  422. * or to the terminating NUL if no such character exists.
  423. */
  424. const char *
  425. find_whitespace(const char *s)
  426. {
  427. /* tor_assert(s); */
  428. while (1) {
  429. switch (*s)
  430. {
  431. case '\0':
  432. case '#':
  433. case ' ':
  434. case '\r':
  435. case '\n':
  436. case '\t':
  437. return s;
  438. default:
  439. ++s;
  440. }
  441. }
  442. }
  443. /** Return true iff the 'len' bytes at 'mem' are all zero. */
  444. int
  445. tor_mem_is_zero(const char *mem, size_t len)
  446. {
  447. static const char ZERO[] = {
  448. 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
  449. };
  450. while (len >= sizeof(ZERO)) {
  451. if (memcmp(mem, ZERO, sizeof(ZERO)))
  452. return 0;
  453. len -= sizeof(ZERO);
  454. mem += sizeof(ZERO);
  455. }
  456. /* Deal with leftover bytes. */
  457. if (len)
  458. return ! memcmp(mem, ZERO, len);
  459. return 1;
  460. }
  461. /** Return true iff the DIGEST_LEN bytes in digest are all zero. */
  462. int
  463. tor_digest_is_zero(const char *digest)
  464. {
  465. return tor_mem_is_zero(digest, DIGEST_LEN);
  466. }
  467. /* Helper: common code to check whether the result of a strtol or strtoul or
  468. * strtoll is correct. */
  469. #define CHECK_STRTOX_RESULT() \
  470. /* Was at least one character converted? */ \
  471. if (endptr == s) \
  472. goto err; \
  473. /* Were there unexpected unconverted characters? */ \
  474. if (!next && *endptr) \
  475. goto err; \
  476. /* Is r within limits? */ \
  477. if (r < min || r > max) \
  478. goto err; \
  479. if (ok) *ok = 1; \
  480. if (next) *next = endptr; \
  481. return r; \
  482. err: \
  483. if (ok) *ok = 0; \
  484. if (next) *next = endptr; \
  485. return 0
  486. /** Extract a long from the start of s, in the given numeric base. If
  487. * there is unconverted data and next is provided, set *next to the
  488. * first unconverted character. An error has occurred if no characters
  489. * are converted; or if there are unconverted characters and next is NULL; or
  490. * if the parsed value is not between min and max. When no error occurs,
  491. * return the parsed value and set *ok (if provided) to 1. When an error
  492. * occurs, return 0 and set *ok (if provided) to 0.
  493. */
  494. long
  495. tor_parse_long(const char *s, int base, long min, long max,
  496. int *ok, char **next)
  497. {
  498. char *endptr;
  499. long r;
  500. r = strtol(s, &endptr, base);
  501. CHECK_STRTOX_RESULT();
  502. }
  503. /** As tor_parse_long, but return an unsigned long. */
  504. unsigned long
  505. tor_parse_ulong(const char *s, int base, unsigned long min,
  506. unsigned long max, int *ok, char **next)
  507. {
  508. char *endptr;
  509. unsigned long r;
  510. r = strtoul(s, &endptr, base);
  511. CHECK_STRTOX_RESULT();
  512. }
  513. /** As tor_parse_log, but return a unit64_t. Only base 10 is guaranteed to
  514. * work for now. */
  515. uint64_t
  516. tor_parse_uint64(const char *s, int base, uint64_t min,
  517. uint64_t max, int *ok, char **next)
  518. {
  519. char *endptr;
  520. uint64_t r;
  521. #ifdef HAVE_STRTOULL
  522. r = (uint64_t)strtoull(s, &endptr, base);
  523. #elif defined(MS_WINDOWS)
  524. #if defined(_MSC_VER) && _MSC_VER < 1300
  525. tor_assert(base <= 10);
  526. r = (uint64_t)_atoi64(s);
  527. endptr = (char*)s;
  528. while (TOR_ISSPACE(*endptr)) endptr++;
  529. while (TOR_ISDIGIT(*endptr)) endptr++;
  530. #else
  531. r = (uint64_t)_strtoui64(s, &endptr, base);
  532. #endif
  533. #elif SIZEOF_LONG == 8
  534. r = (uint64_t)strtoul(s, &endptr, base);
  535. #else
  536. #error "I don't know how to parse 64-bit numbers."
  537. #endif
  538. CHECK_STRTOX_RESULT();
  539. }
  540. /** Encode the <b>srclen</b> bytes at <b>src</b> in a NUL-terminated,
  541. * uppercase hexadecimal string; store it in the <b>destlen</b>-byte buffer
  542. * <b>dest</b>.
  543. */
  544. void
  545. base16_encode(char *dest, size_t destlen, const char *src, size_t srclen)
  546. {
  547. const char *end;
  548. char *cp;
  549. tor_assert(destlen >= srclen*2+1);
  550. tor_assert(destlen < SIZE_T_CEILING);
  551. cp = dest;
  552. end = src+srclen;
  553. while (src<end) {
  554. *cp++ = "0123456789ABCDEF"[ (*(const uint8_t*)src) >> 4 ];
  555. *cp++ = "0123456789ABCDEF"[ (*(const uint8_t*)src) & 0xf ];
  556. ++src;
  557. }
  558. *cp = '\0';
  559. }
  560. /** Helper: given a hex digit, return its value, or -1 if it isn't hex. */
  561. static INLINE int
  562. hex_decode_digit(char c)
  563. {
  564. switch (c) {
  565. case '0': return 0;
  566. case '1': return 1;
  567. case '2': return 2;
  568. case '3': return 3;
  569. case '4': return 4;
  570. case '5': return 5;
  571. case '6': return 6;
  572. case '7': return 7;
  573. case '8': return 8;
  574. case '9': return 9;
  575. case 'A': case 'a': return 10;
  576. case 'B': case 'b': return 11;
  577. case 'C': case 'c': return 12;
  578. case 'D': case 'd': return 13;
  579. case 'E': case 'e': return 14;
  580. case 'F': case 'f': return 15;
  581. default:
  582. return -1;
  583. }
  584. }
  585. /** Given a hexadecimal string of <b>srclen</b> bytes in <b>src</b>, decode it
  586. * and store the result in the <b>destlen</b>-byte buffer at <b>dest</b>.
  587. * Return 0 on success, -1 on failure. */
  588. int
  589. base16_decode(char *dest, size_t destlen, const char *src, size_t srclen)
  590. {
  591. const char *end;
  592. int v1,v2;
  593. if ((srclen % 2) != 0)
  594. return -1;
  595. if (destlen < srclen/2 || destlen > SIZE_T_CEILING)
  596. return -1;
  597. end = src+srclen;
  598. while (src<end) {
  599. v1 = hex_decode_digit(*src);
  600. v2 = hex_decode_digit(*(src+1));
  601. if (v1<0||v2<0)
  602. return -1;
  603. *(uint8_t*)dest = (v1<<4)|v2;
  604. ++dest;
  605. src+=2;
  606. }
  607. return 0;
  608. }
  609. /** Allocate and return a new string representing the contents of <b>s</b>,
  610. * surrounded by quotes and using standard C escapes.
  611. *
  612. * Generally, we use this for logging values that come in over the network to
  613. * keep them from tricking users, and for sending certain values to the
  614. * controller.
  615. *
  616. * We trust values from the resolver, OS, configuration file, and command line
  617. * to not be maliciously ill-formed. We validate incoming routerdescs and
  618. * SOCKS requests and addresses from BEGIN cells as they're parsed;
  619. * afterwards, we trust them as non-malicious.
  620. */
  621. char *
  622. esc_for_log(const char *s)
  623. {
  624. const char *cp;
  625. char *result, *outp;
  626. size_t len = 3;
  627. if (!s) {
  628. return tor_strdup("");
  629. }
  630. for (cp = s; *cp; ++cp) {
  631. switch (*cp) {
  632. case '\\':
  633. case '\"':
  634. case '\'':
  635. len += 2;
  636. break;
  637. default:
  638. if (TOR_ISPRINT(*cp) && ((uint8_t)*cp)<127)
  639. ++len;
  640. else
  641. len += 4;
  642. break;
  643. }
  644. }
  645. result = outp = tor_malloc(len);
  646. *outp++ = '\"';
  647. for (cp = s; *cp; ++cp) {
  648. switch (*cp) {
  649. case '\\':
  650. case '\"':
  651. case '\'':
  652. *outp++ = '\\';
  653. *outp++ = *cp;
  654. break;
  655. case '\n':
  656. *outp++ = '\\';
  657. *outp++ = 'n';
  658. break;
  659. case '\t':
  660. *outp++ = '\\';
  661. *outp++ = 't';
  662. break;
  663. case '\r':
  664. *outp++ = '\\';
  665. *outp++ = 'r';
  666. break;
  667. default:
  668. if (TOR_ISPRINT(*cp) && ((uint8_t)*cp)<127) {
  669. *outp++ = *cp;
  670. } else {
  671. tor_snprintf(outp, 5, "\\%03o", (int)(uint8_t) *cp);
  672. outp += 4;
  673. }
  674. break;
  675. }
  676. }
  677. *outp++ = '\"';
  678. *outp++ = 0;
  679. return result;
  680. }
  681. /** Allocate and return a new string representing the contents of <b>s</b>,
  682. * surrounded by quotes and using standard C escapes.
  683. *
  684. * THIS FUNCTION IS NOT REENTRANT. Don't call it from outside the main
  685. * thread. Also, each call invalidates the last-returned value, so don't
  686. * try log_warn(LD_GENERAL, "%s %s", escaped(a), escaped(b));
  687. */
  688. const char *
  689. escaped(const char *s)
  690. {
  691. static char *_escaped_val = NULL;
  692. if (_escaped_val)
  693. tor_free(_escaped_val);
  694. if (s)
  695. _escaped_val = esc_for_log(s);
  696. else
  697. _escaped_val = NULL;
  698. return _escaped_val;
  699. }
  700. /** Rudimentary string wrapping code: given a un-wrapped <b>string</b> (no
  701. * newlines!), break the string into newline-terminated lines of no more than
  702. * <b>width</b> characters long (not counting newline) and insert them into
  703. * <b>out</b> in order. Precede the first line with prefix0, and subsequent
  704. * lines with prefixRest.
  705. */
  706. /* This uses a stupid greedy wrapping algorithm right now:
  707. * - For each line:
  708. * - Try to fit as much stuff as possible, but break on a space.
  709. * - If the first "word" of the line will extend beyond the allowable
  710. * width, break the word at the end of the width.
  711. */
  712. void
  713. wrap_string(smartlist_t *out, const char *string, size_t width,
  714. const char *prefix0, const char *prefixRest)
  715. {
  716. size_t p0Len, pRestLen, pCurLen;
  717. const char *eos, *prefixCur;
  718. tor_assert(out);
  719. tor_assert(string);
  720. tor_assert(width);
  721. if (!prefix0)
  722. prefix0 = "";
  723. if (!prefixRest)
  724. prefixRest = "";
  725. p0Len = strlen(prefix0);
  726. pRestLen = strlen(prefixRest);
  727. tor_assert(width > p0Len && width > pRestLen);
  728. eos = strchr(string, '\0');
  729. tor_assert(eos);
  730. pCurLen = p0Len;
  731. prefixCur = prefix0;
  732. while ((eos-string)+pCurLen > width) {
  733. const char *eol = string + width - pCurLen;
  734. while (eol > string && *eol != ' ')
  735. --eol;
  736. /* eol is now the last space that can fit, or the start of the string. */
  737. if (eol > string) {
  738. size_t line_len = (eol-string) + pCurLen + 2;
  739. char *line = tor_malloc(line_len);
  740. memcpy(line, prefixCur, pCurLen);
  741. memcpy(line+pCurLen, string, eol-string);
  742. line[line_len-2] = '\n';
  743. line[line_len-1] = '\0';
  744. smartlist_add(out, line);
  745. string = eol + 1;
  746. } else {
  747. size_t line_len = width + 2;
  748. char *line = tor_malloc(line_len);
  749. memcpy(line, prefixCur, pCurLen);
  750. memcpy(line+pCurLen, string, width - pCurLen);
  751. line[line_len-2] = '\n';
  752. line[line_len-1] = '\0';
  753. smartlist_add(out, line);
  754. string += width-pCurLen;
  755. }
  756. prefixCur = prefixRest;
  757. pCurLen = pRestLen;
  758. }
  759. if (string < eos) {
  760. size_t line_len = (eos-string) + pCurLen + 2;
  761. char *line = tor_malloc(line_len);
  762. memcpy(line, prefixCur, pCurLen);
  763. memcpy(line+pCurLen, string, eos-string);
  764. line[line_len-2] = '\n';
  765. line[line_len-1] = '\0';
  766. smartlist_add(out, line);
  767. }
  768. }
  769. /* =====
  770. * Time
  771. * ===== */
  772. /** Return the number of microseconds elapsed between *start and *end.
  773. */
  774. long
  775. tv_udiff(const struct timeval *start, const struct timeval *end)
  776. {
  777. long udiff;
  778. long secdiff = end->tv_sec - start->tv_sec;
  779. if (labs(secdiff+1) > LONG_MAX/1000000) {
  780. log_warn(LD_GENERAL, "comparing times too far apart.");
  781. return LONG_MAX;
  782. }
  783. udiff = secdiff*1000000L + (end->tv_usec - start->tv_usec);
  784. return udiff;
  785. }
  786. /** Return -1 if *a \< *b, 0 if *a==*b, and 1 if *a \> *b.
  787. */
  788. int
  789. tv_cmp(const struct timeval *a, const struct timeval *b)
  790. {
  791. if (a->tv_sec > b->tv_sec)
  792. return 1;
  793. if (a->tv_sec < b->tv_sec)
  794. return -1;
  795. if (a->tv_usec > b->tv_usec)
  796. return 1;
  797. if (a->tv_usec < b->tv_usec)
  798. return -1;
  799. return 0;
  800. }
  801. /** Increment *a by the number of seconds and microseconds in *b.
  802. */
  803. void
  804. tv_add(struct timeval *a, const struct timeval *b)
  805. {
  806. a->tv_usec += b->tv_usec;
  807. a->tv_sec += b->tv_sec + (a->tv_usec / 1000000);
  808. a->tv_usec %= 1000000;
  809. }
  810. /** Increment *a by <b>ms</b> milliseconds.
  811. */
  812. void
  813. tv_addms(struct timeval *a, long ms)
  814. {
  815. uint64_t us = ms * 1000;
  816. a->tv_usec += us % 1000000;
  817. a->tv_sec += (us / 1000000) + (a->tv_usec / 1000000);
  818. a->tv_usec %= 1000000;
  819. }
  820. /** Yield true iff <b>y</b> is a leap-year. */
  821. #define IS_LEAPYEAR(y) (!(y % 4) && ((y % 100) || !(y % 400)))
  822. /** Helper: Return the number of leap-days between Jan 1, y1 and Jan 1, y2. */
  823. static int
  824. n_leapdays(int y1, int y2)
  825. {
  826. --y1;
  827. --y2;
  828. return (y2/4 - y1/4) - (y2/100 - y1/100) + (y2/400 - y1/400);
  829. }
  830. /** Number of days per month in non-leap year; used by tor_timegm. */
  831. static const int days_per_month[] =
  832. { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
  833. /** Return a time_t given a struct tm. The result is given in GMT, and
  834. * does not account for leap seconds.
  835. */
  836. time_t
  837. tor_timegm(struct tm *tm)
  838. {
  839. /* This is a pretty ironclad timegm implementation, snarfed from Python2.2.
  840. * It's way more brute-force than fiddling with tzset().
  841. */
  842. time_t ret;
  843. unsigned long year, days, hours, minutes;
  844. int i;
  845. year = tm->tm_year + 1900;
  846. if (year < 1970 || tm->tm_mon < 0 || tm->tm_mon > 11) {
  847. log_warn(LD_BUG, "Out-of-range argument to tor_timegm");
  848. return -1;
  849. }
  850. days = 365 * (year-1970) + n_leapdays(1970,year);
  851. for (i = 0; i < tm->tm_mon; ++i)
  852. days += days_per_month[i];
  853. if (tm->tm_mon > 1 && IS_LEAPYEAR(year))
  854. ++days;
  855. days += tm->tm_mday - 1;
  856. hours = days*24 + tm->tm_hour;
  857. minutes = hours*60 + tm->tm_min;
  858. ret = minutes*60 + tm->tm_sec;
  859. return ret;
  860. }
  861. /* strftime is locale-specific, so we need to replace those parts */
  862. static const char *WEEKDAY_NAMES[] =
  863. { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  864. static const char *MONTH_NAMES[] =
  865. { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  866. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  867. /** Set <b>buf</b> to the RFC1123 encoding of the GMT value of <b>t</b>.
  868. * The buffer must be at least RFC1123_TIME_LEN+1 bytes long.
  869. *
  870. * (RFC1123 format is Fri, 29 Sep 2006 15:54:20 GMT)
  871. */
  872. void
  873. format_rfc1123_time(char *buf, time_t t)
  874. {
  875. struct tm tm;
  876. tor_gmtime_r(&t, &tm);
  877. strftime(buf, RFC1123_TIME_LEN+1, "___, %d ___ %Y %H:%M:%S GMT", &tm);
  878. tor_assert(tm.tm_wday >= 0);
  879. tor_assert(tm.tm_wday <= 6);
  880. memcpy(buf, WEEKDAY_NAMES[tm.tm_wday], 3);
  881. tor_assert(tm.tm_wday >= 0);
  882. tor_assert(tm.tm_mon <= 11);
  883. memcpy(buf+8, MONTH_NAMES[tm.tm_mon], 3);
  884. }
  885. /** Parse the the RFC1123 encoding of some time (in GMT) from <b>buf</b>,
  886. * and store the result in *<b>t</b>.
  887. *
  888. * Return 0 on succcess, -1 on failure.
  889. */
  890. int
  891. parse_rfc1123_time(const char *buf, time_t *t)
  892. {
  893. struct tm tm;
  894. char month[4];
  895. char weekday[4];
  896. int i, m;
  897. if (strlen(buf) != RFC1123_TIME_LEN)
  898. return -1;
  899. memset(&tm, 0, sizeof(tm));
  900. if (sscanf(buf, "%3s, %d %3s %d %d:%d:%d GMT", weekday,
  901. &tm.tm_mday, month, &tm.tm_year, &tm.tm_hour,
  902. &tm.tm_min, &tm.tm_sec) < 7) {
  903. char *esc = esc_for_log(buf);
  904. log_warn(LD_GENERAL, "Got invalid RFC1123 time %s", esc);
  905. tor_free(esc);
  906. return -1;
  907. }
  908. m = -1;
  909. for (i = 0; i < 12; ++i) {
  910. if (!strcmp(month, MONTH_NAMES[i])) {
  911. m = i;
  912. break;
  913. }
  914. }
  915. if (m<0) {
  916. char *esc = esc_for_log(buf);
  917. log_warn(LD_GENERAL, "Got invalid RFC1123 time %s: No such month", esc);
  918. tor_free(esc);
  919. return -1;
  920. }
  921. tm.tm_mon = m;
  922. if (tm.tm_year < 1970) {
  923. char *esc = esc_for_log(buf);
  924. log_warn(LD_GENERAL,
  925. "Got invalid RFC1123 time %s. (Before 1970)", esc);
  926. tor_free(esc);
  927. return -1;
  928. }
  929. tm.tm_year -= 1900;
  930. *t = tor_timegm(&tm);
  931. return 0;
  932. }
  933. /** Set <b>buf</b> to the ISO8601 encoding of the local value of <b>t</b>.
  934. * The buffer must be at least ISO_TIME_LEN+1 bytes long.
  935. *
  936. * (ISO8601 format is 2006-10-29 10:57:20)
  937. */
  938. void
  939. format_local_iso_time(char *buf, time_t t)
  940. {
  941. struct tm tm;
  942. strftime(buf, ISO_TIME_LEN+1, "%Y-%m-%d %H:%M:%S", tor_localtime_r(&t, &tm));
  943. }
  944. /** Set <b>buf</b> to the ISO8601 encoding of the GMT value of <b>t</b>.
  945. * The buffer must be at least ISO_TIME_LEN+1 bytes long.
  946. */
  947. void
  948. format_iso_time(char *buf, time_t t)
  949. {
  950. struct tm tm;
  951. strftime(buf, ISO_TIME_LEN+1, "%Y-%m-%d %H:%M:%S", tor_gmtime_r(&t, &tm));
  952. }
  953. /** Given an ISO-formatted UTC time value (after the epoch) in <b>cp</b>,
  954. * parse it and store its value in *<b>t</b>. Return 0 on success, -1 on
  955. * failure. Ignore extraneous stuff in <b>cp</b> separated by whitespace from
  956. * the end of the time string. */
  957. int
  958. parse_iso_time(const char *cp, time_t *t)
  959. {
  960. struct tm st_tm;
  961. #ifdef HAVE_STRPTIME
  962. if (!strptime(cp, "%Y-%m-%d %H:%M:%S", &st_tm)) {
  963. log_warn(LD_GENERAL, "ISO time was unparseable by strptime"); return -1;
  964. }
  965. #else
  966. unsigned int year=0, month=0, day=0, hour=100, minute=100, second=100;
  967. if (sscanf(cp, "%u-%u-%u %u:%u:%u", &year, &month,
  968. &day, &hour, &minute, &second) < 6) {
  969. log_warn(LD_GENERAL, "ISO time was unparseable"); return -1;
  970. }
  971. if (year < 1970 || month < 1 || month > 12 || day < 1 || day > 31 ||
  972. hour > 23 || minute > 59 || second > 61) {
  973. log_warn(LD_GENERAL, "ISO time was nonsensical"); return -1;
  974. }
  975. st_tm.tm_year = year-1900;
  976. st_tm.tm_mon = month-1;
  977. st_tm.tm_mday = day;
  978. st_tm.tm_hour = hour;
  979. st_tm.tm_min = minute;
  980. st_tm.tm_sec = second;
  981. #endif
  982. if (st_tm.tm_year < 70) {
  983. char *esc = esc_for_log(cp);
  984. log_warn(LD_GENERAL, "Got invalid ISO time %s. (Before 1970)", esc);
  985. tor_free(esc);
  986. return -1;
  987. }
  988. *t = tor_timegm(&st_tm);
  989. return 0;
  990. }
  991. /* =====
  992. * File helpers
  993. * ===== */
  994. /** Write <b>count</b> bytes from <b>buf</b> to <b>fd</b>. <b>isSocket</b>
  995. * must be 1 if fd was returned by socket() or accept(), and 0 if fd
  996. * was returned by open(). Return the number of bytes written, or -1
  997. * on error. Only use if fd is a blocking fd. */
  998. int
  999. write_all(int fd, const char *buf, size_t count, int isSocket)
  1000. {
  1001. size_t written = 0;
  1002. int result;
  1003. while (written != count) {
  1004. if (isSocket)
  1005. result = tor_socket_send(fd, buf+written, count-written, 0);
  1006. else
  1007. result = write(fd, buf+written, count-written);
  1008. if (result<0)
  1009. return -1;
  1010. written += result;
  1011. }
  1012. return count;
  1013. }
  1014. /** Read from <b>fd</b> to <b>buf</b>, until we get <b>count</b> bytes
  1015. * or reach the end of the file. <b>isSocket</b> must be 1 if fd
  1016. * was returned by socket() or accept(), and 0 if fd was returned by
  1017. * open(). Return the number of bytes read, or -1 on error. Only use
  1018. * if fd is a blocking fd. */
  1019. int
  1020. read_all(int fd, char *buf, size_t count, int isSocket)
  1021. {
  1022. size_t numread = 0;
  1023. int result;
  1024. if (count > SIZE_T_CEILING)
  1025. return -1;
  1026. while (numread != count) {
  1027. if (isSocket)
  1028. result = tor_socket_recv(fd, buf+numread, count-numread, 0);
  1029. else
  1030. result = read(fd, buf+numread, count-numread);
  1031. if (result<0)
  1032. return -1;
  1033. else if (result == 0)
  1034. break;
  1035. numread += result;
  1036. }
  1037. return numread;
  1038. }
  1039. /*
  1040. * Filesystem operations.
  1041. */
  1042. /** Clean up <b>name</b> so that we can use it in a call to "stat". On Unix,
  1043. * we do nothing. On Windows, we remove a trailing slash, unless the path is
  1044. * the root of a disk. */
  1045. static void
  1046. clean_name_for_stat(char *name)
  1047. {
  1048. #ifdef MS_WINDOWS
  1049. size_t len = strlen(name);
  1050. if (!len)
  1051. return;
  1052. if (name[len-1]=='\\' || name[len-1]=='/') {
  1053. if (len == 1 || (len==3 && name[1]==':'))
  1054. return;
  1055. name[len-1]='\0';
  1056. }
  1057. #else
  1058. (void)name;
  1059. #endif
  1060. }
  1061. /** Return FN_ERROR if filename can't be read, FN_NOENT if it doesn't
  1062. * exist, FN_FILE if it is a regular file, or FN_DIR if it's a
  1063. * directory. */
  1064. file_status_t
  1065. file_status(const char *fname)
  1066. {
  1067. struct stat st;
  1068. char *f;
  1069. int r;
  1070. f = tor_strdup(fname);
  1071. clean_name_for_stat(f);
  1072. r = stat(f, &st);
  1073. tor_free(f);
  1074. if (r) {
  1075. if (errno == ENOENT) {
  1076. return FN_NOENT;
  1077. }
  1078. return FN_ERROR;
  1079. }
  1080. if (st.st_mode & S_IFDIR)
  1081. return FN_DIR;
  1082. else if (st.st_mode & S_IFREG)
  1083. return FN_FILE;
  1084. else
  1085. return FN_ERROR;
  1086. }
  1087. /** Check whether dirname exists and is private. If yes return 0. If
  1088. * it does not exist, and check==CPD_CREATE is set, try to create it
  1089. * and return 0 on success. If it does not exist, and
  1090. * check==CPD_CHECK, and we think we can create it, return 0. Else
  1091. * return -1. */
  1092. int
  1093. check_private_dir(const char *dirname, cpd_check_t check)
  1094. {
  1095. int r;
  1096. struct stat st;
  1097. char *f;
  1098. tor_assert(dirname);
  1099. f = tor_strdup(dirname);
  1100. clean_name_for_stat(f);
  1101. r = stat(f, &st);
  1102. tor_free(f);
  1103. if (r) {
  1104. if (errno != ENOENT) {
  1105. log(LOG_WARN, LD_FS, "Directory %s cannot be read: %s", dirname,
  1106. strerror(errno));
  1107. return -1;
  1108. }
  1109. if (check == CPD_NONE) {
  1110. log(LOG_WARN, LD_FS, "Directory %s does not exist.", dirname);
  1111. return -1;
  1112. } else if (check == CPD_CREATE) {
  1113. log_info(LD_GENERAL, "Creating directory %s", dirname);
  1114. #ifdef MS_WINDOWS
  1115. r = mkdir(dirname);
  1116. #else
  1117. r = mkdir(dirname, 0700);
  1118. #endif
  1119. if (r) {
  1120. log(LOG_WARN, LD_FS, "Error creating directory %s: %s", dirname,
  1121. strerror(errno));
  1122. return -1;
  1123. }
  1124. }
  1125. /* XXXX In the case where check==CPD_CHECK, we should look at the
  1126. * parent directory a little harder. */
  1127. return 0;
  1128. }
  1129. if (!(st.st_mode & S_IFDIR)) {
  1130. log(LOG_WARN, LD_FS, "%s is not a directory", dirname);
  1131. return -1;
  1132. }
  1133. #ifndef MS_WINDOWS
  1134. if (st.st_uid != getuid()) {
  1135. struct passwd *pw = NULL;
  1136. char *process_ownername = NULL;
  1137. pw = getpwuid(getuid());
  1138. process_ownername = pw ? tor_strdup(pw->pw_name) : tor_strdup("<unknown>");
  1139. pw = getpwuid(st.st_uid);
  1140. log(LOG_WARN, LD_FS, "%s is not owned by this user (%s, %d) but by "
  1141. "%s (%d). Perhaps you are running Tor as the wrong user?",
  1142. dirname, process_ownername, (int)getuid(),
  1143. pw ? pw->pw_name : "<unknown>", (int)st.st_uid);
  1144. tor_free(process_ownername);
  1145. return -1;
  1146. }
  1147. if (st.st_mode & 0077) {
  1148. log(LOG_WARN, LD_FS, "Fixing permissions on directory %s", dirname);
  1149. if (chmod(dirname, 0700)) {
  1150. log(LOG_WARN, LD_FS, "Could not chmod directory %s: %s", dirname,
  1151. strerror(errno));
  1152. return -1;
  1153. } else {
  1154. return 0;
  1155. }
  1156. }
  1157. #endif
  1158. return 0;
  1159. }
  1160. /** Create a file named <b>fname</b> with the contents <b>str</b>. Overwrite
  1161. * the previous <b>fname</b> if possible. Return 0 on success, -1 on failure.
  1162. *
  1163. * This function replaces the old file atomically, if possible.
  1164. */
  1165. int
  1166. write_str_to_file(const char *fname, const char *str, int bin)
  1167. {
  1168. #ifdef MS_WINDOWS
  1169. if (!bin && strchr(str, '\r')) {
  1170. log_warn(LD_BUG,
  1171. "We're writing a text string that already contains a CR.");
  1172. }
  1173. #endif
  1174. return write_bytes_to_file(fname, str, strlen(str), bin);
  1175. }
  1176. /** Helper: given a set of flags as passed to open(2), open the file
  1177. * <b>fname</b> and write all the sized_chunk_t structs in <b>chunks</b> to
  1178. * the file. Do so as atomically as possible e.g. by opening temp files and
  1179. * renaming. */
  1180. static int
  1181. write_chunks_to_file_impl(const char *fname, const smartlist_t *chunks,
  1182. int open_flags)
  1183. {
  1184. size_t tempname_len;
  1185. char *tempname;
  1186. int fd;
  1187. int result;
  1188. tempname_len = strlen(fname)+16;
  1189. tor_assert(tempname_len > strlen(fname)); /*check for overflow*/
  1190. tempname = tor_malloc(tempname_len);
  1191. if (open_flags & O_APPEND) {
  1192. strlcpy(tempname, fname, tempname_len);
  1193. } else {
  1194. if (tor_snprintf(tempname, tempname_len, "%s.tmp", fname)<0) {
  1195. log(LOG_WARN, LD_GENERAL, "Failed to generate filename");
  1196. goto err;
  1197. }
  1198. }
  1199. if ((fd = open(tempname, open_flags, 0600))
  1200. < 0) {
  1201. log(LOG_WARN, LD_FS, "Couldn't open \"%s\" for writing: %s", tempname,
  1202. strerror(errno));
  1203. goto err;
  1204. }
  1205. SMARTLIST_FOREACH(chunks, sized_chunk_t *, chunk,
  1206. {
  1207. result = write_all(fd, chunk->bytes, chunk->len, 0);
  1208. if (result < 0 || (size_t)result != chunk->len) {
  1209. log(LOG_WARN, LD_FS, "Error writing to \"%s\": %s", tempname,
  1210. strerror(errno));
  1211. close(fd);
  1212. goto err;
  1213. }
  1214. });
  1215. if (close(fd)) {
  1216. log(LOG_WARN, LD_FS, "Error flushing to \"%s\": %s", tempname,
  1217. strerror(errno));
  1218. goto err;
  1219. }
  1220. if (!(open_flags & O_APPEND)) {
  1221. if (replace_file(tempname, fname)) {
  1222. log(LOG_WARN, LD_FS, "Error replacing \"%s\": %s", fname,
  1223. strerror(errno));
  1224. goto err;
  1225. }
  1226. }
  1227. tor_free(tempname);
  1228. return 0;
  1229. err:
  1230. tor_free(tempname);
  1231. return -1;
  1232. }
  1233. /** Given a smartlist of sized_chunk_t, write them atomically to a file
  1234. * <b>fname</b>, overwriting or creating the file as necessary. */
  1235. int
  1236. write_chunks_to_file(const char *fname, const smartlist_t *chunks, int bin)
  1237. {
  1238. int flags = O_WRONLY|O_CREAT|O_TRUNC|(bin?O_BINARY:O_TEXT);
  1239. return write_chunks_to_file_impl(fname, chunks, flags);
  1240. }
  1241. /** As write_str_to_file, but does not assume a NUL-terminated
  1242. * string. Instead, we write <b>len</b> bytes, starting at <b>str</b>. */
  1243. int
  1244. write_bytes_to_file(const char *fname, const char *str, size_t len,
  1245. int bin)
  1246. {
  1247. int flags = O_WRONLY|O_CREAT|O_TRUNC|(bin?O_BINARY:O_TEXT);
  1248. int r;
  1249. sized_chunk_t c = { str, len };
  1250. smartlist_t *chunks = smartlist_create();
  1251. smartlist_add(chunks, &c);
  1252. r = write_chunks_to_file_impl(fname, chunks, flags);
  1253. smartlist_free(chunks);
  1254. return r;
  1255. }
  1256. /** As write_bytes_to_file, but if the file already exists, append the bytes
  1257. * to the end of the file instead of overwriting it. */
  1258. int
  1259. append_bytes_to_file(const char *fname, const char *str, size_t len,
  1260. int bin)
  1261. {
  1262. int flags = O_WRONLY|O_CREAT|O_APPEND|(bin?O_BINARY:O_TEXT);
  1263. int r;
  1264. sized_chunk_t c = { str, len };
  1265. smartlist_t *chunks = smartlist_create();
  1266. smartlist_add(chunks, &c);
  1267. r = write_chunks_to_file_impl(fname, chunks, flags);
  1268. smartlist_free(chunks);
  1269. return r;
  1270. }
  1271. /** Read the contents of <b>filename</b> into a newly allocated
  1272. * string; return the string on success or NULL on failure.
  1273. *
  1274. * If <b>stat_out</b> is provided, store the result of stat()ing the
  1275. * file into <b>stat_out</b>.
  1276. *
  1277. * If <b>flags</b> &amp; RFTS_BIN, open the file in binary mode.
  1278. * If <b>flags</b> &amp; RFTS_IGNORE_MISSING, don't warn if the file
  1279. * doesn't exist.
  1280. */
  1281. /*
  1282. * This function <em>may</em> return an erroneous result if the file
  1283. * is modified while it is running, but must not crash or overflow.
  1284. * Right now, the error case occurs when the file length grows between
  1285. * the call to stat and the call to read_all: the resulting string will
  1286. * be truncated.
  1287. */
  1288. char *
  1289. read_file_to_str(const char *filename, int flags, struct stat *stat_out)
  1290. {
  1291. int fd; /* router file */
  1292. struct stat statbuf;
  1293. char *string;
  1294. int r;
  1295. int bin = flags & RFTS_BIN;
  1296. tor_assert(filename);
  1297. fd = open(filename,O_RDONLY|(bin?O_BINARY:O_TEXT),0);
  1298. if (fd<0) {
  1299. int severity = LOG_WARN;
  1300. if (errno == ENOENT && (flags & RFTS_IGNORE_MISSING))
  1301. severity = LOG_INFO;
  1302. log_fn(severity, LD_FS,"Could not open \"%s\": %s ",filename,
  1303. strerror(errno));
  1304. return NULL;
  1305. }
  1306. if (fstat(fd, &statbuf)<0) {
  1307. close(fd);
  1308. log_warn(LD_FS,"Could not fstat \"%s\".",filename);
  1309. return NULL;
  1310. }
  1311. if ((uint64_t)(statbuf.st_size)+1 > SIZE_T_MAX)
  1312. return NULL;
  1313. string = tor_malloc((size_t)(statbuf.st_size+1));
  1314. r = read_all(fd,string,(size_t)statbuf.st_size,0);
  1315. if (r<0) {
  1316. log_warn(LD_FS,"Error reading from file \"%s\": %s", filename,
  1317. strerror(errno));
  1318. tor_free(string);
  1319. close(fd);
  1320. return NULL;
  1321. }
  1322. string[r] = '\0'; /* NUL-terminate the result. */
  1323. #ifdef MS_WINDOWS
  1324. if (!bin && strchr(string, '\r')) {
  1325. log_debug(LD_FS, "We didn't convert CRLF to LF as well as we hoped "
  1326. "when reading %s. Coping.",
  1327. filename);
  1328. tor_strstrip(string, "\r");
  1329. r = strlen(string);
  1330. }
  1331. if (!bin) {
  1332. statbuf.st_size = (size_t) r;
  1333. } else
  1334. #endif
  1335. if (r != statbuf.st_size) {
  1336. /* Unless we're using text mode on win32, we'd better have an exact
  1337. * match for size. */
  1338. log_warn(LD_FS,"Could read only %d of %ld bytes of file \"%s\".",
  1339. r, (long)statbuf.st_size,filename);
  1340. tor_free(string);
  1341. close(fd);
  1342. return NULL;
  1343. }
  1344. close(fd);
  1345. if (stat_out) {
  1346. memcpy(stat_out, &statbuf, sizeof(struct stat));
  1347. }
  1348. return string;
  1349. }
  1350. /** Given a string containing part of a configuration file or similar format,
  1351. * advance past comments and whitespace and try to parse a single line. If we
  1352. * parse a line successfully, set *<b>key_out</b> to the key portion and
  1353. * *<b>value_out</b> to the value portion of the line, and return a pointer to
  1354. * the start of the next line. If we run out of data, return a pointer to the
  1355. * end of the string. If we encounter an error, return NULL.
  1356. *
  1357. * NOTE: We modify <b>line</b> as we parse it, by inserting NULs to terminate
  1358. * the key and value.
  1359. */
  1360. char *
  1361. parse_line_from_str(char *line, char **key_out, char **value_out)
  1362. {
  1363. char *key, *val, *cp;
  1364. tor_assert(key_out);
  1365. tor_assert(value_out);
  1366. *key_out = *value_out = key = val = NULL;
  1367. /* Skip until the first keyword. */
  1368. while (1) {
  1369. while (TOR_ISSPACE(*line))
  1370. ++line;
  1371. if (*line == '#') {
  1372. while (*line && *line != '\n')
  1373. ++line;
  1374. } else {
  1375. break;
  1376. }
  1377. }
  1378. if (!*line) { /* End of string? */
  1379. *key_out = *value_out = NULL;
  1380. return line;
  1381. }
  1382. /* Skip until the next space. */
  1383. key = line;
  1384. while (*line && !TOR_ISSPACE(*line) && *line != '#')
  1385. ++line;
  1386. /* Skip until the value */
  1387. while (*line == ' ' || *line == '\t')
  1388. *line++ = '\0';
  1389. val = line;
  1390. /* Find the end of the line. */
  1391. while (*line && *line != '\n' && *line != '#')
  1392. ++line;
  1393. if (*line == '\n')
  1394. cp = line++;
  1395. else {
  1396. cp = line-1;
  1397. }
  1398. while (cp>=val && TOR_ISSPACE(*cp))
  1399. *cp-- = '\0';
  1400. if (*line == '#') {
  1401. do {
  1402. *line++ = '\0';
  1403. } while (*line && *line != '\n');
  1404. if (*line == '\n')
  1405. ++line;
  1406. }
  1407. *key_out = key;
  1408. *value_out = val;
  1409. return line;
  1410. }
  1411. /** Expand any homedir prefix on 'filename'; return a newly allocated
  1412. * string. */
  1413. char *
  1414. expand_filename(const char *filename)
  1415. {
  1416. tor_assert(filename);
  1417. if (*filename == '~') {
  1418. size_t len;
  1419. char *home, *result;
  1420. const char *rest;
  1421. if (filename[1] == '/' || filename[1] == '\0') {
  1422. home = getenv("HOME");
  1423. if (!home) {
  1424. log_warn(LD_CONFIG, "Couldn't find $HOME environment variable while "
  1425. "expanding \"%s\"", filename);
  1426. return NULL;
  1427. }
  1428. home = tor_strdup(home);
  1429. rest = strlen(filename)>=2?(filename+2):NULL;
  1430. } else {
  1431. #ifdef HAVE_PWD_H
  1432. char *username, *slash;
  1433. slash = strchr(filename, '/');
  1434. if (slash)
  1435. username = tor_strndup(filename+1,slash-filename-1);
  1436. else
  1437. username = tor_strdup(filename+1);
  1438. if (!(home = get_user_homedir(username))) {
  1439. log_warn(LD_CONFIG,"Couldn't get homedir for \"%s\"",username);
  1440. tor_free(username);
  1441. return NULL;
  1442. }
  1443. tor_free(username);
  1444. rest = slash ? (slash+1) : NULL;
  1445. #else
  1446. log_warn(LD_CONFIG, "Couldn't expend homedir on system without pwd.h");
  1447. return tor_strdup(filename);
  1448. #endif
  1449. }
  1450. tor_assert(home);
  1451. /* Remove trailing slash. */
  1452. if (strlen(home)>1 && !strcmpend(home,PATH_SEPARATOR)) {
  1453. home[strlen(home)-1] = '\0';
  1454. }
  1455. /* Plus one for /, plus one for NUL.
  1456. * Round up to 16 in case we can't do math. */
  1457. len = strlen(home)+strlen(rest)+16;
  1458. result = tor_malloc(len);
  1459. tor_snprintf(result,len,"%s"PATH_SEPARATOR"%s",home,rest?rest:"");
  1460. tor_free(home);
  1461. return result;
  1462. } else {
  1463. return tor_strdup(filename);
  1464. }
  1465. }
  1466. /** Return a new list containing the filenames in the directory <b>dirname</b>.
  1467. * Return NULL on error or if <b>dirname</b> is not a directory.
  1468. */
  1469. smartlist_t *
  1470. tor_listdir(const char *dirname)
  1471. {
  1472. smartlist_t *result;
  1473. #ifdef MS_WINDOWS
  1474. char *pattern;
  1475. HANDLE handle;
  1476. WIN32_FIND_DATA findData;
  1477. size_t pattern_len = strlen(dirname)+16;
  1478. pattern = tor_malloc(pattern_len);
  1479. tor_snprintf(pattern, pattern_len, "%s\\*", dirname);
  1480. if (!(handle = FindFirstFile(pattern, &findData))) {
  1481. tor_free(pattern);
  1482. return NULL;
  1483. }
  1484. result = smartlist_create();
  1485. while (1) {
  1486. if (strcmp(findData.cFileName, ".") &&
  1487. strcmp(findData.cFileName, "..")) {
  1488. smartlist_add(result, tor_strdup(findData.cFileName));
  1489. }
  1490. if (!FindNextFile(handle, &findData)) {
  1491. if (GetLastError() != ERROR_NO_MORE_FILES) {
  1492. log_warn(LD_FS, "Error reading directory.");
  1493. }
  1494. break;
  1495. }
  1496. }
  1497. FindClose(handle);
  1498. tor_free(pattern);
  1499. #else
  1500. DIR *d;
  1501. struct dirent *de;
  1502. if (!(d = opendir(dirname)))
  1503. return NULL;
  1504. result = smartlist_create();
  1505. while ((de = readdir(d))) {
  1506. if (!strcmp(de->d_name, ".") ||
  1507. !strcmp(de->d_name, ".."))
  1508. continue;
  1509. smartlist_add(result, tor_strdup(de->d_name));
  1510. }
  1511. closedir(d);
  1512. #endif
  1513. return result;
  1514. }
  1515. /** Return true iff <b>filename</b> is a relative path. */
  1516. int
  1517. path_is_relative(const char *filename)
  1518. {
  1519. if (filename && filename[0] == '/')
  1520. return 0;
  1521. #ifdef MS_WINDOWS
  1522. else if (filename && filename[0] == '\\')
  1523. return 0;
  1524. else if (filename && strlen(filename)>3 && TOR_ISALPHA(filename[0]) &&
  1525. filename[1] == ':' && filename[2] == '\\')
  1526. return 0;
  1527. #endif
  1528. else
  1529. return 1;
  1530. }
  1531. /* =====
  1532. * Net helpers
  1533. * ===== */
  1534. /** Return true iff <b>ip</b> (in host order) is an IP reserved to localhost,
  1535. * or reserved for local networks by RFC 1918.
  1536. */
  1537. int
  1538. is_internal_IP(uint32_t ip, int for_listening)
  1539. {
  1540. if (for_listening && !ip) /* special case for binding to 0.0.0.0 */
  1541. return 0;
  1542. if (((ip & 0xff000000) == 0x0a000000) || /* 10/8 */
  1543. ((ip & 0xff000000) == 0x00000000) || /* 0/8 */
  1544. ((ip & 0xff000000) == 0x7f000000) || /* 127/8 */
  1545. ((ip & 0xffff0000) == 0xa9fe0000) || /* 169.254/16 */
  1546. ((ip & 0xfff00000) == 0xac100000) || /* 172.16/12 */
  1547. ((ip & 0xffff0000) == 0xc0a80000)) /* 192.168/16 */
  1548. return 1;
  1549. return 0;
  1550. }
  1551. /** Parse a string of the form "host[:port]" from <b>addrport</b>. If
  1552. * <b>address</b> is provided, set *<b>address</b> to a copy of the
  1553. * host portion of the string. If <b>addr</b> is provided, try to
  1554. * resolve the host portion of the string and store it into
  1555. * *<b>addr</b> (in host byte order). If <b>port_out</b> is provided,
  1556. * store the port number into *<b>port_out</b>, or 0 if no port is given.
  1557. * If <b>port_out</b> is NULL, then there must be no port number in
  1558. * <b>addrport</b>.
  1559. * Return 0 on success, -1 on failure.
  1560. */
  1561. int
  1562. parse_addr_port(int severity, const char *addrport, char **address,
  1563. uint32_t *addr, uint16_t *port_out)
  1564. {
  1565. const char *colon;
  1566. char *_address = NULL;
  1567. int _port;
  1568. int ok = 1;
  1569. tor_assert(addrport);
  1570. colon = strchr(addrport, ':');
  1571. if (colon) {
  1572. _address = tor_strndup(addrport, colon-addrport);
  1573. _port = (int) tor_parse_long(colon+1,10,1,65535,NULL,NULL);
  1574. if (!_port) {
  1575. log_fn(severity, LD_GENERAL, "Port %s out of range", escaped(colon+1));
  1576. ok = 0;
  1577. }
  1578. if (!port_out) {
  1579. char *esc_addrport = esc_for_log(addrport);
  1580. log_fn(severity, LD_GENERAL,
  1581. "Port %s given on %s when not required",
  1582. escaped(colon+1), esc_addrport);
  1583. tor_free(esc_addrport);
  1584. ok = 0;
  1585. }
  1586. } else {
  1587. _address = tor_strdup(addrport);
  1588. _port = 0;
  1589. }
  1590. if (addr) {
  1591. /* There's an addr pointer, so we need to resolve the hostname. */
  1592. if (tor_lookup_hostname(_address,addr)) {
  1593. log_fn(severity, LD_NET, "Couldn't look up %s", escaped(_address));
  1594. ok = 0;
  1595. *addr = 0;
  1596. }
  1597. *addr = ntohl(*addr);
  1598. }
  1599. if (address && ok) {
  1600. *address = _address;
  1601. } else {
  1602. if (address)
  1603. *address = NULL;
  1604. tor_free(_address);
  1605. }
  1606. if (port_out)
  1607. *port_out = ok ? ((uint16_t) _port) : 0;
  1608. return ok ? 0 : -1;
  1609. }
  1610. /** If <b>mask</b> is an address mask for a bit-prefix, return the number of
  1611. * bits. Otherwise, return -1. */
  1612. int
  1613. addr_mask_get_bits(uint32_t mask)
  1614. {
  1615. int i;
  1616. if (mask == 0)
  1617. return 0;
  1618. if (mask == 0xFFFFFFFFu)
  1619. return 32;
  1620. for (i=0; i<=32; ++i) {
  1621. if (mask == (uint32_t) ~((1u<<(32-i))-1)) {
  1622. return i;
  1623. }
  1624. }
  1625. return -1;
  1626. }
  1627. /** Parse a string <b>s</b> in the format of (*|port(-maxport)?)?, setting the
  1628. * various *out pointers as appropriate. Return 0 on success, -1 on failure.
  1629. */
  1630. int
  1631. parse_port_range(const char *port, uint16_t *port_min_out,
  1632. uint16_t *port_max_out)
  1633. {
  1634. int port_min, port_max, ok;
  1635. tor_assert(port_min_out);
  1636. tor_assert(port_max_out);
  1637. if (!port || *port == '\0' || strcmp(port, "*") == 0) {
  1638. port_min = 1;
  1639. port_max = 65535;
  1640. } else {
  1641. char *endptr = NULL;
  1642. port_min = tor_parse_long(port, 10, 0, 65535, &ok, &endptr);
  1643. if (!ok) {
  1644. log_warn(LD_GENERAL,
  1645. "Malformed port %s on address range; rejecting.",
  1646. escaped(port));
  1647. return -1;
  1648. } else if (endptr && *endptr == '-') {
  1649. port = endptr+1;
  1650. endptr = NULL;
  1651. port_max = tor_parse_long(port, 10, 1, 65536, &ok, &endptr);
  1652. if (!ok) {
  1653. log_warn(LD_GENERAL,
  1654. "Malformed port %s on address range; rejecting.",
  1655. escaped(port));
  1656. return -1;
  1657. }
  1658. } else {
  1659. port_max = port_min;
  1660. }
  1661. if (port_min > port_max) {
  1662. log_warn(LD_GENERAL, "Insane port range on address policy; rejecting.");
  1663. return -1;
  1664. }
  1665. }
  1666. if (port_min < 1)
  1667. port_min = 1;
  1668. if (port_max > 65535)
  1669. port_max = 65535;
  1670. *port_min_out = (uint16_t) port_min;
  1671. *port_max_out = (uint16_t) port_max;
  1672. return 0;
  1673. }
  1674. /** Parse a string <b>s</b> in the format of
  1675. * (IP(/mask|/mask-bits)?|*)(:*|port(-maxport)?)?, setting the various
  1676. * *out pointers as appropriate. Return 0 on success, -1 on failure.
  1677. */
  1678. int
  1679. parse_addr_and_port_range(const char *s, uint32_t *addr_out,
  1680. uint32_t *mask_out, uint16_t *port_min_out,
  1681. uint16_t *port_max_out)
  1682. {
  1683. char *address;
  1684. char *mask, *port, *endptr;
  1685. struct in_addr in;
  1686. int bits;
  1687. tor_assert(s);
  1688. tor_assert(addr_out);
  1689. tor_assert(mask_out);
  1690. tor_assert(port_min_out);
  1691. tor_assert(port_max_out);
  1692. address = tor_strdup(s);
  1693. /* Break 'address' into separate strings.
  1694. */
  1695. mask = strchr(address,'/');
  1696. port = strchr(mask?mask:address,':');
  1697. if (mask)
  1698. *mask++ = '\0';
  1699. if (port)
  1700. *port++ = '\0';
  1701. /* Now "address" is the IP|'*' part...
  1702. * "mask" is the Mask|Maskbits part...
  1703. * and "port" is the *|port|min-max part.
  1704. */
  1705. if (strcmp(address,"*")==0) {
  1706. *addr_out = 0;
  1707. } else if (tor_inet_aton(address, &in) != 0) {
  1708. *addr_out = ntohl(in.s_addr);
  1709. } else {
  1710. log_warn(LD_GENERAL, "Malformed IP %s in address pattern; rejecting.",
  1711. escaped(address));
  1712. goto err;
  1713. }
  1714. if (!mask) {
  1715. if (strcmp(address,"*")==0)
  1716. *mask_out = 0;
  1717. else
  1718. *mask_out = 0xFFFFFFFFu;
  1719. } else {
  1720. endptr = NULL;
  1721. bits = (int) strtol(mask, &endptr, 10);
  1722. if (!*endptr) {
  1723. /* strtol handled the whole mask. */
  1724. if (bits < 0 || bits > 32) {
  1725. log_warn(LD_GENERAL,
  1726. "Bad number of mask bits on address range; rejecting.");
  1727. goto err;
  1728. }
  1729. *mask_out = ~((1u<<(32-bits))-1);
  1730. } else if (tor_inet_aton(mask, &in) != 0) {
  1731. *mask_out = ntohl(in.s_addr);
  1732. } else {
  1733. log_warn(LD_GENERAL,
  1734. "Malformed mask %s on address range; rejecting.",
  1735. escaped(mask));
  1736. goto err;
  1737. }
  1738. }
  1739. if (parse_port_range(port, port_min_out, port_max_out)<0)
  1740. goto err;
  1741. tor_free(address);
  1742. return 0;
  1743. err:
  1744. tor_free(address);
  1745. return -1;
  1746. }
  1747. /** Given an IPv4 address <b>in</b> (in network order, as usual),
  1748. * write it as a string into the <b>buf_len</b>-byte buffer in
  1749. * <b>buf</b>.
  1750. */
  1751. int
  1752. tor_inet_ntoa(struct in_addr *in, char *buf, size_t buf_len)
  1753. {
  1754. uint32_t a = ntohl(in->s_addr);
  1755. return tor_snprintf(buf, buf_len, "%d.%d.%d.%d",
  1756. (int)(uint8_t)((a>>24)&0xff),
  1757. (int)(uint8_t)((a>>16)&0xff),
  1758. (int)(uint8_t)((a>>8 )&0xff),
  1759. (int)(uint8_t)((a )&0xff));
  1760. }
  1761. /** Given a host-order <b>addr</b>, call tor_inet_ntoa() on it
  1762. * and return a strdup of the resulting address.
  1763. */
  1764. char *
  1765. tor_dup_addr(uint32_t addr)
  1766. {
  1767. char buf[INET_NTOA_BUF_LEN];
  1768. struct in_addr in;
  1769. in.s_addr = htonl(addr);
  1770. tor_inet_ntoa(&in, buf, sizeof(buf));
  1771. return tor_strdup(buf);
  1772. }
  1773. /**
  1774. * Set *<b>addr</b> to the host-order IPv4 address (if any) of whatever
  1775. * interface connects to the internet. This address should only be used in
  1776. * checking whether our address has changed. Return 0 on success, -1 on
  1777. * failure.
  1778. */
  1779. int
  1780. get_interface_address(int severity, uint32_t *addr)
  1781. {
  1782. int sock=-1, r=-1;
  1783. struct sockaddr_in target_addr, my_addr;
  1784. socklen_t my_addr_len = sizeof(my_addr);
  1785. tor_assert(addr);
  1786. *addr = 0;
  1787. sock = tor_open_socket(PF_INET,SOCK_DGRAM,IPPROTO_UDP);
  1788. if (sock < 0) {
  1789. int e = tor_socket_errno(-1);
  1790. log_fn(severity, LD_NET, "unable to create socket: %s",
  1791. tor_socket_strerror(e));
  1792. goto err;
  1793. }
  1794. memset(&target_addr, 0, sizeof(target_addr));
  1795. target_addr.sin_family = AF_INET;
  1796. /* discard port */
  1797. target_addr.sin_port = 9;
  1798. /* 18.0.0.1 (Don't worry: no packets are sent. We just need a real address
  1799. * on the internet.) */
  1800. target_addr.sin_addr.s_addr = htonl(0x12000001);
  1801. if (connect(sock,(struct sockaddr *)&target_addr,sizeof(target_addr))<0) {
  1802. int e = tor_socket_errno(sock);
  1803. log_fn(severity, LD_NET, "connect() failed: %s", tor_socket_strerror(e));
  1804. goto err;
  1805. }
  1806. if (getsockname(sock, (struct sockaddr*)&my_addr, &my_addr_len)) {
  1807. int e = tor_socket_errno(sock);
  1808. log_fn(severity, LD_NET, "getsockname() to determine interface failed: %s",
  1809. tor_socket_strerror(e));
  1810. goto err;
  1811. }
  1812. *addr = ntohl(my_addr.sin_addr.s_addr);
  1813. r=0;
  1814. err:
  1815. if (sock >= 0)
  1816. tor_close_socket(sock);
  1817. return r;
  1818. }
  1819. /* =====
  1820. * Process helpers
  1821. * ===== */
  1822. #ifndef MS_WINDOWS
  1823. /* Based on code contributed by christian grothoff */
  1824. /** True iff we've called start_daemon(). */
  1825. static int start_daemon_called = 0;
  1826. /** True iff we've called finish_daemon(). */
  1827. static int finish_daemon_called = 0;
  1828. /** Socketpair used to communicate between parent and child process while
  1829. * daemonizing. */
  1830. static int daemon_filedes[2];
  1831. /** Start putting the process into daemon mode: fork and drop all resources
  1832. * except standard fds. The parent process never returns, but stays around
  1833. * until finish_daemon is called. (Note: it's safe to call this more
  1834. * than once: calls after the first are ignored.)
  1835. */
  1836. void
  1837. start_daemon(void)
  1838. {
  1839. pid_t pid;
  1840. if (start_daemon_called)
  1841. return;
  1842. start_daemon_called = 1;
  1843. pipe(daemon_filedes);
  1844. pid = fork();
  1845. if (pid < 0) {
  1846. log_err(LD_GENERAL,"fork failed. Exiting.");
  1847. exit(1);
  1848. }
  1849. if (pid) { /* Parent */
  1850. int ok;
  1851. char c;
  1852. close(daemon_filedes[1]); /* we only read */
  1853. ok = -1;
  1854. while (0 < read(daemon_filedes[0], &c, sizeof(char))) {
  1855. if (c == '.')
  1856. ok = 1;
  1857. }
  1858. fflush(stdout);
  1859. if (ok == 1)
  1860. exit(0);
  1861. else
  1862. exit(1); /* child reported error */
  1863. } else { /* Child */
  1864. close(daemon_filedes[0]); /* we only write */
  1865. pid = setsid(); /* Detach from controlling terminal */
  1866. /*
  1867. * Fork one more time, so the parent (the session group leader) can exit.
  1868. * This means that we, as a non-session group leader, can never regain a
  1869. * controlling terminal. This part is recommended by Stevens's
  1870. * _Advanced Programming in the Unix Environment_.
  1871. */
  1872. if (fork() != 0) {
  1873. exit(0);
  1874. }
  1875. return;
  1876. }
  1877. }
  1878. /** Finish putting the process into daemon mode: drop standard fds, and tell
  1879. * the parent process to exit. (Note: it's safe to call this more than once:
  1880. * calls after the first are ignored. Calls start_daemon first if it hasn't
  1881. * been called already.)
  1882. */
  1883. void
  1884. finish_daemon(const char *desired_cwd)
  1885. {
  1886. int nullfd;
  1887. char c = '.';
  1888. if (finish_daemon_called)
  1889. return;
  1890. if (!start_daemon_called)
  1891. start_daemon();
  1892. finish_daemon_called = 1;
  1893. if (!desired_cwd)
  1894. desired_cwd = "/";
  1895. /* Don't hold the wrong FS mounted */
  1896. if (chdir(desired_cwd) < 0) {
  1897. log_err(LD_GENERAL,"chdir to \"%s\" failed. Exiting.",desired_cwd);
  1898. exit(1);
  1899. }
  1900. nullfd = open("/dev/null",
  1901. O_CREAT | O_RDWR | O_APPEND);
  1902. if (nullfd < 0) {
  1903. log_err(LD_GENERAL,"/dev/null can't be opened. Exiting.");
  1904. exit(1);
  1905. }
  1906. /* close fds linking to invoking terminal, but
  1907. * close usual incoming fds, but redirect them somewhere
  1908. * useful so the fds don't get reallocated elsewhere.
  1909. */
  1910. if (dup2(nullfd,0) < 0 ||
  1911. dup2(nullfd,1) < 0 ||
  1912. dup2(nullfd,2) < 0) {
  1913. log_err(LD_GENERAL,"dup2 failed. Exiting.");
  1914. exit(1);
  1915. }
  1916. if (nullfd > 2)
  1917. close(nullfd);
  1918. write(daemon_filedes[1], &c, sizeof(char)); /* signal success */
  1919. close(daemon_filedes[1]);
  1920. }
  1921. #else
  1922. /* defined(MS_WINDOWS) */
  1923. void
  1924. start_daemon(void)
  1925. {
  1926. }
  1927. void
  1928. finish_daemon(const char *cp)
  1929. {
  1930. (void)cp;
  1931. }
  1932. #endif
  1933. /** Write the current process ID, followed by NL, into <b>filename</b>.
  1934. */
  1935. void
  1936. write_pidfile(char *filename)
  1937. {
  1938. FILE *pidfile;
  1939. if ((pidfile = fopen(filename, "w")) == NULL) {
  1940. log_warn(LD_FS, "Unable to open \"%s\" for writing: %s", filename,
  1941. strerror(errno));
  1942. } else {
  1943. #ifdef MS_WINDOWS
  1944. fprintf(pidfile, "%d\n", (int)_getpid());
  1945. #else
  1946. fprintf(pidfile, "%d\n", (int)getpid());
  1947. #endif
  1948. fclose(pidfile);
  1949. }
  1950. }