util.c 53 KB

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