util.c 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740
  1. /* Copyright 2003 Roger Dingledine
  2. * Copyright 2004-2005 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. #else
  24. #include <dirent.h>
  25. #include <pwd.h>
  26. #endif
  27. #ifdef HAVE_CTYPE_H
  28. #include <ctype.h>
  29. #endif
  30. #include <stdlib.h>
  31. #include <stdio.h>
  32. #include <string.h>
  33. #include <assert.h>
  34. #ifdef HAVE_NETINET_IN_H
  35. #include <netinet/in.h>
  36. #endif
  37. #ifdef HAVE_ARPA_INET_H
  38. #include <arpa/inet.h>
  39. #endif
  40. #ifdef HAVE_ERRNO_H
  41. #include <errno.h>
  42. #endif
  43. #ifdef HAVE_LIMITS_H
  44. #include <limits.h>
  45. #endif
  46. #ifdef HAVE_SYS_LIMITS_H
  47. #include <sys/limits.h>
  48. #endif
  49. #ifdef HAVE_MACHINE_LIMITS_H
  50. #ifndef __FreeBSD__
  51. /* FreeBSD has a bug where it complains that this file is obsolete,
  52. and I should migrate to using sys/limits. It complains even when
  53. I include both. */
  54. #include <machine/limits.h>
  55. #endif
  56. #endif
  57. #ifdef HAVE_SYS_TYPES_H
  58. #include <sys/types.h> /* Must be included before sys/stat.h for Ultrix */
  59. #endif
  60. #ifdef HAVE_SYS_SOCKET_H
  61. #include <sys/socket.h>
  62. #endif
  63. #ifdef HAVE_SYS_TIME_H
  64. #include <sys/time.h>
  65. #endif
  66. #ifdef HAVE_UNISTD_H
  67. #include <unistd.h>
  68. #endif
  69. #ifdef HAVE_SYS_STAT_H
  70. #include <sys/stat.h>
  71. #endif
  72. #ifdef HAVE_SYS_FCNTL_H
  73. #include <sys/fcntl.h>
  74. #endif
  75. #ifdef HAVE_FCNTL_H
  76. #include <fcntl.h>
  77. #endif
  78. #ifdef HAVE_TIME_H
  79. #include <time.h>
  80. #endif
  81. #ifndef O_BINARY
  82. #define O_BINARY 0
  83. #endif
  84. #ifndef O_TEXT
  85. #define O_TEXT 0
  86. #endif
  87. /* =====
  88. * Memory management
  89. * ===== */
  90. #ifdef USE_DMALLOC
  91. #include <dmalloc.h>
  92. #define DMALLOC_FN_ARGS , file, line
  93. #else
  94. #define dmalloc_strdup(file, line, string, xalloc_b) strdup(string)
  95. #define dmalloc_malloc(file, line, size, func_id, alignment, xalloc_b) \
  96. malloc(size)
  97. #define DMALLOC_FUNC_MALLOC 0
  98. #define dmalloc_realloc(file, line, old_pnt, new_size, func_id, xalloc_b) \
  99. realloc((old_pnt), (new_size))
  100. #define DMALLOC_FUNC_REALLOC 0
  101. #define DMALLOC_FN_ARGS
  102. #endif
  103. /** Allocate a chunk of <b>size</b> bytes of memory, and return a pointer to
  104. * result. On error, log and terminate the process. (Same as malloc(size),
  105. * but never returns NULL.)
  106. *
  107. * <b>file</b> and <b>line</b> are used if dmalloc is enabled, and
  108. * ignored otherwise.
  109. */
  110. void *
  111. _tor_malloc(size_t size DMALLOC_PARAMS)
  112. {
  113. void *result;
  114. /* Some libcs don't do the right thing on size==0. Override them. */
  115. if (size==0) {
  116. size=1;
  117. }
  118. result = dmalloc_malloc(file, line, size, DMALLOC_FUNC_MALLOC, 0, 0);
  119. if (!result) {
  120. err(LD_MM,"Out of memory. Dying.");
  121. /* XXX if these functions die within a worker process, they won't
  122. * call spawn_exit */
  123. exit(1);
  124. }
  125. // memset(result,'X',size); /* deadbeef to encourage bugs */
  126. return result;
  127. }
  128. /* Allocate a chunk of <b>size</b> bytes of memory, fill the memory with
  129. * zero bytes, and return a pointer to the result. Log and terminate
  130. * the process on error. (Same as calloc(size,1), but never returns NULL.)
  131. */
  132. void *
  133. _tor_malloc_zero(size_t size DMALLOC_PARAMS)
  134. {
  135. void *result = _tor_malloc(size DMALLOC_FN_ARGS);
  136. memset(result, 0, size);
  137. return result;
  138. }
  139. /** Change the size of the memory block pointed to by <b>ptr</b> to <b>size</b>
  140. * bytes long; return the new memory block. On error, log and
  141. * terminate. (Like realloc(ptr,size), but never returns NULL.)
  142. */
  143. void *
  144. _tor_realloc(void *ptr, size_t size DMALLOC_PARAMS)
  145. {
  146. void *result;
  147. result = dmalloc_realloc(file, line, ptr, size, DMALLOC_FUNC_REALLOC, 0);
  148. if (!result) {
  149. err(LD_MM,"Out of memory. Dying.");
  150. exit(1);
  151. }
  152. return result;
  153. }
  154. /** Return a newly allocated copy of the NUL-terminated string s. On
  155. * error, log and terminate. (Like strdup(s), but never returns
  156. * NULL.)
  157. */
  158. char *
  159. _tor_strdup(const char *s DMALLOC_PARAMS)
  160. {
  161. char *dup;
  162. tor_assert(s);
  163. dup = dmalloc_strdup(file, line, s, 0);
  164. if (!dup) {
  165. err(LD_MM,"Out of memory. Dying.");
  166. exit(1);
  167. }
  168. return dup;
  169. }
  170. /** Allocate and return a new string containing the first <b>n</b>
  171. * characters of <b>s</b>. If <b>s</b> is longer than <b>n</b>
  172. * characters, only the first <b>n</b> are copied. The result is
  173. * always NUL-terminated. (Like strndup(s,n), but never returns
  174. * NULL.)
  175. */
  176. char *
  177. _tor_strndup(const char *s, size_t n DMALLOC_PARAMS)
  178. {
  179. char *dup;
  180. tor_assert(s);
  181. dup = _tor_malloc((n+1) DMALLOC_FN_ARGS);
  182. /* Performance note: Ordinarily we prefer strlcpy to strncpy. But
  183. * this function gets called a whole lot, and platform strncpy is
  184. * much faster than strlcpy when strlen(s) is much longer than n.
  185. */
  186. strncpy(dup, s, n);
  187. dup[n]='\0';
  188. return dup;
  189. }
  190. /* =====
  191. * String manipulation
  192. * ===== */
  193. /** Remove from the string <b>s</b> every character which appears in
  194. * <b>strip</b>. Return the number of characters removed. */
  195. int
  196. tor_strstrip(char *s, const char *strip)
  197. {
  198. char *read = s;
  199. while (*read) {
  200. if (strchr(strip, *read)) {
  201. ++read;
  202. } else {
  203. *s++ = *read++;
  204. }
  205. }
  206. *s = '\0';
  207. return read-s;
  208. }
  209. /** Set the <b>dest_len</b>-byte buffer <b>buf</b> to contain the
  210. * string <b>s</b>, with the string <b>insert</b> inserted after every
  211. * <b>n</b> characters. Return 0 on success, -1 on failure.
  212. *
  213. * If <b>rule</b> is ALWAYS_TERMINATE, then always end the string with
  214. * <b>insert</b>, even if its length is not a multiple of <b>n</b>. If
  215. * <b>rule</b> is NEVER_TERMINATE, then never end the string with
  216. * <b>insert</b>, even if its length <i>is</i> a multiple of <b>n</b>.
  217. * If <b>rule</b> is TERMINATE_IF_EVEN, then end the string with <b>insert</b>
  218. * exactly when its length <i>is</i> a 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. part_finish_rule_t rule)
  224. {
  225. char *destp;
  226. size_t len_in, len_out, len_ins;
  227. int is_even, remaining;
  228. tor_assert(s);
  229. tor_assert(insert);
  230. tor_assert(n > 0);
  231. tor_assert(n < SIZE_T_CEILING);
  232. tor_assert(dest_len < SIZE_T_CEILING);
  233. len_in = strlen(s);
  234. len_ins = strlen(insert);
  235. tor_assert(len_in < SIZE_T_CEILING);
  236. tor_assert(len_in/n < SIZE_T_CEILING/len_ins); /* avoid overflow */
  237. len_out = len_in + (len_in/n)*len_ins;
  238. is_even = (len_in%n) == 0;
  239. switch (rule)
  240. {
  241. case ALWAYS_TERMINATE:
  242. if (!is_even) len_out += len_ins;
  243. break;
  244. case NEVER_TERMINATE:
  245. if (is_even && len_in) len_out -= len_ins;
  246. break;
  247. case TERMINATE_IF_EVEN:
  248. break;
  249. }
  250. if (dest_len < len_out+1)
  251. return -1;
  252. destp = dest;
  253. remaining = len_in;
  254. while (remaining) {
  255. strncpy(destp, s, n);
  256. remaining -= n;
  257. if (remaining < 0) {
  258. if (rule == ALWAYS_TERMINATE)
  259. strcpy(destp+n+remaining,insert);
  260. break;
  261. } else if (remaining == 0 && rule == NEVER_TERMINATE) {
  262. *(destp+n) = '\0';
  263. break;
  264. }
  265. strcpy(destp+n, insert);
  266. s += n;
  267. destp += n+len_ins;
  268. }
  269. tor_assert(len_out == strlen(dest));
  270. return 0;
  271. }
  272. /** Return a pointer to a NUL-terminated hexadecimal string encoding
  273. * the first <b>fromlen</b> bytes of <b>from</b>. (fromlen must be \<= 32.) The
  274. * result does not need to be deallocated, but repeated calls to
  275. * hex_str will trash old results.
  276. */
  277. const char *
  278. hex_str(const char *from, size_t fromlen)
  279. {
  280. static char buf[65];
  281. if (fromlen>(sizeof(buf)-1)/2)
  282. fromlen = (sizeof(buf)-1)/2;
  283. base16_encode(buf,sizeof(buf),from,fromlen);
  284. return buf;
  285. }
  286. /** Convert all alphabetic characters in the nul-terminated string <b>s</b> to
  287. * lowercase. */
  288. void
  289. tor_strlower(char *s)
  290. {
  291. while (*s) {
  292. *s = tolower(*s);
  293. ++s;
  294. }
  295. }
  296. /** Convert all alphabetic characters in the nul-terminated string <b>s</b> to
  297. * lowercase. */
  298. void
  299. tor_strupper(char *s)
  300. {
  301. while (*s) {
  302. *s = toupper(*s);
  303. ++s;
  304. }
  305. }
  306. /* Compares the first strlen(s2) characters of s1 with s2. Returns as for
  307. * strcmp.
  308. */
  309. int
  310. strcmpstart(const char *s1, const char *s2)
  311. {
  312. size_t n = strlen(s2);
  313. return strncmp(s1, s2, n);
  314. }
  315. /* Compares the first strlen(s2) characters of s1 with s2. Returns as for
  316. * strcasecmp.
  317. */
  318. int
  319. strcasecmpstart(const char *s1, const char *s2)
  320. {
  321. size_t n = strlen(s2);
  322. return strncasecmp(s1, s2, n);
  323. }
  324. /* Compares the last strlen(s2) characters of s1 with s2. Returns as for
  325. * strcmp.
  326. */
  327. int
  328. strcmpend(const char *s1, const char *s2)
  329. {
  330. size_t n1 = strlen(s1), n2 = strlen(s2);
  331. if (n2>n1)
  332. return strcmp(s1,s2);
  333. else
  334. return strncmp(s1+(n1-n2), s2, n2);
  335. }
  336. /* Compares the last strlen(s2) characters of s1 with s2. Returns as for
  337. * strcasecmp.
  338. */
  339. int
  340. strcasecmpend(const char *s1, const char *s2)
  341. {
  342. size_t n1 = strlen(s1), n2 = strlen(s2);
  343. if (n2>n1) /* then they can't be the same; figure out which is bigger */
  344. return strcasecmp(s1,s2);
  345. else
  346. return strncasecmp(s1+(n1-n2), s2, n2);
  347. }
  348. /** Return a pointer to the first char of s that is not whitespace and
  349. * not a comment, or to the terminating NUL if no such character exists.
  350. */
  351. const char *
  352. eat_whitespace(const char *s)
  353. {
  354. tor_assert(s);
  355. while (TOR_ISSPACE(*s) || *s == '#') {
  356. while (TOR_ISSPACE(*s))
  357. s++;
  358. if (*s == '#') { /* read to a \n or \0 */
  359. while (*s && *s != '\n')
  360. s++;
  361. if (!*s)
  362. return s;
  363. }
  364. }
  365. return s;
  366. }
  367. /** Return a pointer to the first char of s that is not a space or a tab,
  368. * or to the terminating NUL if no such character exists. */
  369. const char *
  370. eat_whitespace_no_nl(const char *s)
  371. {
  372. while (*s == ' ' || *s == '\t')
  373. ++s;
  374. return s;
  375. }
  376. /** Return a pointer to the first char of s that is whitespace or <b>#</b>,
  377. * or to the terminating NUL if no such character exists.
  378. */
  379. const char *
  380. find_whitespace(const char *s)
  381. {
  382. /* tor_assert(s); */
  383. while (*s && !TOR_ISSPACE(*s) && *s != '#')
  384. s++;
  385. return s;
  386. }
  387. /** Return true iff the DIGEST_LEN bytes in digest are all zero. */
  388. int
  389. tor_digest_is_zero(const char *digest)
  390. {
  391. static char ZERO_DIGEST[] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 };
  392. return !memcmp(digest, ZERO_DIGEST, DIGEST_LEN);
  393. }
  394. #define CHECK_STRTOX_RESULT() \
  395. /* Was at least one character converted? */ \
  396. if (endptr == s) \
  397. goto err; \
  398. /* Were there unexpected unconverted characters? */ \
  399. if (!next && *endptr) \
  400. goto err; \
  401. /* Is r within limits? */ \
  402. if (r < min || r > max) \
  403. goto err; \
  404. if (ok) *ok = 1; \
  405. if (next) *next = endptr; \
  406. return r; \
  407. err: \
  408. if (ok) *ok = 0; \
  409. if (next) *next = endptr; \
  410. return 0
  411. /** Extract a long from the start of s, in the given numeric base. If
  412. * there is unconverted data and next is provided, set *next to the
  413. * first unconverted character. An error has occurred if no characters
  414. * are converted; or if there are unconverted characters and next is NULL; or
  415. * if the parsed value is not between min and max. When no error occurs,
  416. * return the parsed value and set *ok (if provided) to 1. When an error
  417. * occurs, return 0 and set *ok (if provided) to 0.
  418. */
  419. long
  420. tor_parse_long(const char *s, int base, long min, long max,
  421. int *ok, char **next)
  422. {
  423. char *endptr;
  424. long r;
  425. r = strtol(s, &endptr, base);
  426. CHECK_STRTOX_RESULT();
  427. }
  428. unsigned long
  429. tor_parse_ulong(const char *s, int base, unsigned long min,
  430. unsigned long max, int *ok, char **next)
  431. {
  432. char *endptr;
  433. unsigned long r;
  434. r = strtoul(s, &endptr, base);
  435. CHECK_STRTOX_RESULT();
  436. }
  437. /** Only base 10 is guaranteed to work for now. */
  438. uint64_t
  439. tor_parse_uint64(const char *s, int base, uint64_t min,
  440. uint64_t max, int *ok, char **next)
  441. {
  442. char *endptr;
  443. uint64_t r;
  444. #ifdef HAVE_STRTOULL
  445. r = (uint64_t)strtoull(s, &endptr, base);
  446. #elif defined(MS_WINDOWS)
  447. #if _MSC_VER < 1300
  448. tor_assert(base <= 10);
  449. r = (uint64_t)_atoi64(s);
  450. endptr = (char*)s;
  451. while (TOR_ISSPACE(*endptr)) endptr++;
  452. while (TOR_ISDIGIT(*endptr)) endptr++;
  453. #else
  454. r = (uint64_t)_strtoui64(s, &endptr, base);
  455. #endif
  456. #elif SIZEOF_LONG == 8
  457. r = (uint64_t)strtoul(s, &endptr, base);
  458. #else
  459. #error "I don't know how to parse 64-bit numbers."
  460. #endif
  461. CHECK_STRTOX_RESULT();
  462. }
  463. void
  464. base16_encode(char *dest, size_t destlen, const char *src, size_t srclen)
  465. {
  466. const char *end;
  467. char *cp;
  468. tor_assert(destlen >= srclen*2+1);
  469. tor_assert(destlen < SIZE_T_CEILING);
  470. cp = dest;
  471. end = src+srclen;
  472. while (src<end) {
  473. sprintf(cp,"%02X",*(const uint8_t*)src);
  474. ++src;
  475. cp += 2;
  476. }
  477. *cp = '\0';
  478. }
  479. static const char HEX_DIGITS[] = "0123456789ABCDEFabcdef";
  480. static INLINE int
  481. hex_decode_digit(char c)
  482. {
  483. const char *cp;
  484. int n;
  485. cp = strchr(HEX_DIGITS, c);
  486. if (!cp)
  487. return -1;
  488. n = cp-HEX_DIGITS;
  489. if (n<=15)
  490. return n; /* digit or uppercase */
  491. else
  492. return n-6; /* lowercase */
  493. }
  494. int
  495. base16_decode(char *dest, size_t destlen, const char *src, size_t srclen)
  496. {
  497. const char *end;
  498. int v1,v2;
  499. if ((srclen % 2) != 0)
  500. return -1;
  501. if (destlen < srclen/2 || destlen > SIZE_T_CEILING)
  502. return -1;
  503. end = src+srclen;
  504. while (src<end) {
  505. v1 = hex_decode_digit(*src);
  506. v2 = hex_decode_digit(*(src+1));
  507. if (v1<0||v2<0)
  508. return -1;
  509. *(uint8_t*)dest = (v1<<4)|v2;
  510. ++dest;
  511. src+=2;
  512. }
  513. return 0;
  514. }
  515. /* =====
  516. * Time
  517. * ===== */
  518. /** Return the number of microseconds elapsed between *start and *end.
  519. */
  520. long
  521. tv_udiff(struct timeval *start, struct timeval *end)
  522. {
  523. long udiff;
  524. long secdiff = end->tv_sec - start->tv_sec;
  525. if (labs(secdiff+1) > LONG_MAX/1000000) {
  526. warn(LD_GENERAL, "comparing times too far apart.");
  527. return LONG_MAX;
  528. }
  529. udiff = secdiff*1000000L + (end->tv_usec - start->tv_usec);
  530. return udiff;
  531. }
  532. /** Return -1 if *a \< *b, 0 if *a==*b, and 1 if *a \> *b.
  533. */
  534. int
  535. tv_cmp(struct timeval *a, struct timeval *b)
  536. {
  537. if (a->tv_sec > b->tv_sec)
  538. return 1;
  539. if (a->tv_sec < b->tv_sec)
  540. return -1;
  541. if (a->tv_usec > b->tv_usec)
  542. return 1;
  543. if (a->tv_usec < b->tv_usec)
  544. return -1;
  545. return 0;
  546. }
  547. /** Increment *a by the number of seconds and microseconds in *b.
  548. */
  549. void
  550. tv_add(struct timeval *a, struct timeval *b)
  551. {
  552. a->tv_usec += b->tv_usec;
  553. a->tv_sec += b->tv_sec + (a->tv_usec / 1000000);
  554. a->tv_usec %= 1000000;
  555. }
  556. /** Increment *a by <b>ms</b> milliseconds.
  557. */
  558. void
  559. tv_addms(struct timeval *a, long ms)
  560. {
  561. a->tv_usec += (ms * 1000) % 1000000;
  562. a->tv_sec += ((ms * 1000) / 1000000) + (a->tv_usec / 1000000);
  563. a->tv_usec %= 1000000;
  564. }
  565. #define IS_LEAPYEAR(y) (!(y % 4) && ((y % 100) || !(y % 400)))
  566. static int
  567. n_leapdays(int y1, int y2)
  568. {
  569. --y1;
  570. --y2;
  571. return (y2/4 - y1/4) - (y2/100 - y1/100) + (y2/400 - y1/400);
  572. }
  573. /** Number of days per month in non-leap year; used by tor_timegm. */
  574. static const int days_per_month[] =
  575. { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
  576. /** Return a time_t given a struct tm. The result is given in GMT, and
  577. * does not account for leap seconds.
  578. */
  579. time_t
  580. tor_timegm(struct tm *tm)
  581. {
  582. /* This is a pretty ironclad timegm implementation, snarfed from Python2.2.
  583. * It's way more brute-force than fiddling with tzset().
  584. */
  585. time_t ret;
  586. unsigned long year, days, hours, minutes;
  587. int i;
  588. year = tm->tm_year + 1900;
  589. tor_assert(year >= 1970);
  590. tor_assert(tm->tm_mon >= 0);
  591. tor_assert(tm->tm_mon <= 11);
  592. days = 365 * (year-1970) + n_leapdays(1970,year);
  593. for (i = 0; i < tm->tm_mon; ++i)
  594. days += days_per_month[i];
  595. if (tm->tm_mon > 1 && IS_LEAPYEAR(year))
  596. ++days;
  597. days += tm->tm_mday - 1;
  598. hours = days*24 + tm->tm_hour;
  599. minutes = hours*60 + tm->tm_min;
  600. ret = minutes*60 + tm->tm_sec;
  601. return ret;
  602. }
  603. /* strftime is locale-specific, so we need to replace those parts */
  604. static const char *WEEKDAY_NAMES[] =
  605. { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  606. static const char *MONTH_NAMES[] =
  607. { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  608. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  609. void
  610. format_rfc1123_time(char *buf, time_t t)
  611. {
  612. struct tm tm;
  613. tor_gmtime_r(&t, &tm);
  614. strftime(buf, RFC1123_TIME_LEN+1, "___, %d ___ %Y %H:%M:%S GMT", &tm);
  615. tor_assert(tm.tm_wday >= 0);
  616. tor_assert(tm.tm_wday <= 6);
  617. memcpy(buf, WEEKDAY_NAMES[tm.tm_wday], 3);
  618. tor_assert(tm.tm_wday >= 0);
  619. tor_assert(tm.tm_mon <= 11);
  620. memcpy(buf+8, MONTH_NAMES[tm.tm_mon], 3);
  621. }
  622. int
  623. parse_rfc1123_time(const char *buf, time_t *t)
  624. {
  625. struct tm tm;
  626. char month[4];
  627. char weekday[4];
  628. int i, m;
  629. if (strlen(buf) != RFC1123_TIME_LEN)
  630. return -1;
  631. memset(&tm, 0, sizeof(tm));
  632. if (sscanf(buf, "%3s, %d %3s %d %d:%d:%d GMT", weekday,
  633. &tm.tm_mday, month, &tm.tm_year, &tm.tm_hour,
  634. &tm.tm_min, &tm.tm_sec) < 7) {
  635. warn(LD_GENERAL, "Got invalid RFC1123 time \"%s\"", buf);
  636. return -1;
  637. }
  638. m = -1;
  639. for (i = 0; i < 12; ++i) {
  640. if (!strcmp(month, MONTH_NAMES[i])) {
  641. m = i;
  642. break;
  643. }
  644. }
  645. if (m<0) {
  646. warn(LD_GENERAL, "Got invalid RFC1123 time \"%s\"", buf);
  647. return -1;
  648. }
  649. tm.tm_mon = m;
  650. tm.tm_year -= 1900;
  651. *t = tor_timegm(&tm);
  652. return 0;
  653. }
  654. void
  655. format_local_iso_time(char *buf, time_t t)
  656. {
  657. struct tm tm;
  658. strftime(buf, ISO_TIME_LEN+1, "%Y-%m-%d %H:%M:%S", tor_localtime_r(&t, &tm));
  659. }
  660. void
  661. format_iso_time(char *buf, time_t t)
  662. {
  663. struct tm tm;
  664. strftime(buf, ISO_TIME_LEN+1, "%Y-%m-%d %H:%M:%S", tor_gmtime_r(&t, &tm));
  665. }
  666. int
  667. parse_iso_time(const char *cp, time_t *t)
  668. {
  669. struct tm st_tm;
  670. #ifdef HAVE_STRPTIME
  671. if (!strptime(cp, "%Y-%m-%d %H:%M:%S", &st_tm)) {
  672. warn(LD_GENERAL, "Published time was unparseable"); return -1;
  673. }
  674. #else
  675. unsigned int year=0, month=0, day=0, hour=100, minute=100, second=100;
  676. if (sscanf(cp, "%u-%u-%u %u:%u:%u", &year, &month,
  677. &day, &hour, &minute, &second) < 6) {
  678. warn(LD_GENERAL, "Published time was unparseable"); return -1;
  679. }
  680. if (year < 1970 || month < 1 || month > 12 || day < 1 || day > 31 ||
  681. hour > 23 || minute > 59 || second > 61) {
  682. warn(LD_GENERAL, "Published time was nonsensical"); return -1;
  683. }
  684. st_tm.tm_year = year-1900;
  685. st_tm.tm_mon = month-1;
  686. st_tm.tm_mday = day;
  687. st_tm.tm_hour = hour;
  688. st_tm.tm_min = minute;
  689. st_tm.tm_sec = second;
  690. #endif
  691. *t = tor_timegm(&st_tm);
  692. return 0;
  693. }
  694. /* =====
  695. * File helpers
  696. * ===== */
  697. /** Write <b>count</b> bytes from <b>buf</b> to <b>fd</b>. <b>isSocket</b>
  698. * must be 1 if fd was returned by socket() or accept(), and 0 if fd
  699. * was returned by open(). Return the number of bytes written, or -1
  700. * on error. Only use if fd is a blocking fd. */
  701. int
  702. write_all(int fd, const char *buf, size_t count, int isSocket)
  703. {
  704. size_t written = 0;
  705. int result;
  706. while (written != count) {
  707. if (isSocket)
  708. result = send(fd, buf+written, count-written, 0);
  709. else
  710. result = write(fd, buf+written, count-written);
  711. if (result<0)
  712. return -1;
  713. written += result;
  714. }
  715. return count;
  716. }
  717. /** Read from <b>fd</b> to <b>buf</b>, until we get <b>count</b> bytes
  718. * or reach the end of the file. <b>isSocket</b> must be 1 if fd
  719. * was returned by socket() or accept(), and 0 if fd was returned by
  720. * open(). Return the number of bytes read, or -1 on error. Only use
  721. * if fd is a blocking fd. */
  722. int
  723. read_all(int fd, char *buf, size_t count, int isSocket)
  724. {
  725. size_t numread = 0;
  726. int result;
  727. if (count > SIZE_T_CEILING)
  728. return -1;
  729. while (numread != count) {
  730. if (isSocket)
  731. result = recv(fd, buf+numread, count-numread, 0);
  732. else
  733. result = read(fd, buf+numread, count-numread);
  734. if (result<0)
  735. return -1;
  736. else if (result == 0)
  737. break;
  738. numread += result;
  739. }
  740. return numread;
  741. }
  742. /*
  743. * Filesystem operations.
  744. */
  745. /** Clean up <b>name</b> so that we can use it in a call to "stat". On Unix,
  746. * we do nothing. On Windows, we remove a trailing slash, unless the path is
  747. * the root of a disk. */
  748. static void
  749. clean_name_for_stat(char *name)
  750. {
  751. #ifdef MS_WINDOWS
  752. size_t len = strlen(name);
  753. if (!len)
  754. return;
  755. if (name[len-1]=='\\' || name[len-1]=='/') {
  756. if (len == 1 || (len==3 && name[1]==':'))
  757. return;
  758. name[len-1]='\0';
  759. }
  760. #endif
  761. }
  762. /** Return FN_ERROR if filename can't be read, FN_NOENT if it doesn't
  763. * exist, FN_FILE if it is a regular file, or FN_DIR if it's a
  764. * directory. */
  765. file_status_t
  766. file_status(const char *fname)
  767. {
  768. struct stat st;
  769. char *f;
  770. int r;
  771. f = tor_strdup(fname);
  772. clean_name_for_stat(f);
  773. r = stat(f, &st);
  774. tor_free(f);
  775. if (r) {
  776. if (errno == ENOENT) {
  777. return FN_NOENT;
  778. }
  779. return FN_ERROR;
  780. }
  781. if (st.st_mode & S_IFDIR)
  782. return FN_DIR;
  783. else if (st.st_mode & S_IFREG)
  784. return FN_FILE;
  785. else
  786. return FN_ERROR;
  787. }
  788. /** Check whether dirname exists and is private. If yes return 0. If
  789. * it does not exist, and check==CPD_CREATE is set, try to create it
  790. * and return 0 on success. If it does not exist, and
  791. * check==CPD_CHECK, and we think we can create it, return 0. Else
  792. * return -1. */
  793. int
  794. check_private_dir(const char *dirname, cpd_check_t check)
  795. {
  796. int r;
  797. struct stat st;
  798. char *f;
  799. tor_assert(dirname);
  800. f = tor_strdup(dirname);
  801. clean_name_for_stat(f);
  802. r = stat(f, &st);
  803. tor_free(f);
  804. if (r) {
  805. if (errno != ENOENT) {
  806. log(LOG_WARN, LD_FS, "Directory %s cannot be read: %s", dirname,
  807. strerror(errno));
  808. return -1;
  809. }
  810. if (check == CPD_NONE) {
  811. log(LOG_WARN, LD_FS, "Directory %s does not exist.", dirname);
  812. return -1;
  813. } else if (check == CPD_CREATE) {
  814. info(LD_GENERAL, "Creating directory %s", dirname);
  815. #ifdef MS_WINDOWS
  816. r = mkdir(dirname);
  817. #else
  818. r = mkdir(dirname, 0700);
  819. #endif
  820. if (r) {
  821. log(LOG_WARN, LD_FS, "Error creating directory %s: %s", dirname,
  822. strerror(errno));
  823. return -1;
  824. }
  825. }
  826. /* XXXX In the case where check==CPD_CHECK, we should look at the
  827. * parent directory a little harder. */
  828. return 0;
  829. }
  830. if (!(st.st_mode & S_IFDIR)) {
  831. log(LOG_WARN, LD_FS, "%s is not a directory", dirname);
  832. return -1;
  833. }
  834. #ifndef MS_WINDOWS
  835. if (st.st_uid != getuid()) {
  836. struct passwd *pw = NULL;
  837. char *process_ownername = NULL;
  838. pw = getpwuid(getuid());
  839. process_ownername = pw ? tor_strdup(pw->pw_name) : tor_strdup("<unknown>");
  840. pw = getpwuid(st.st_uid);
  841. log(LOG_WARN, LD_FS, "%s is not owned by this user (%s, %d) but by "
  842. "%s (%d). Perhaps you are running Tor as the wrong user?",
  843. dirname, process_ownername, (int)getuid(),
  844. pw ? pw->pw_name : "<unknown>", (int)st.st_uid);
  845. tor_free(process_ownername);
  846. return -1;
  847. }
  848. if (st.st_mode & 0077) {
  849. log(LOG_WARN, LD_FS, "Fixing permissions on directory %s", dirname);
  850. if (chmod(dirname, 0700)) {
  851. log(LOG_WARN, LD_FS, "Could not chmod directory %s: %s", dirname,
  852. strerror(errno));
  853. return -1;
  854. } else {
  855. return 0;
  856. }
  857. }
  858. #endif
  859. return 0;
  860. }
  861. /** Create a file named <b>fname</b> with the contents <b>str</b>. Overwrite
  862. * the previous <b>fname</b> if possible. Return 0 on success, -1 on failure.
  863. *
  864. * This function replaces the old file atomically, if possible.
  865. */
  866. int
  867. write_str_to_file(const char *fname, const char *str, int bin)
  868. {
  869. #ifdef MS_WINDOWS
  870. if (!bin && strchr(str, '\r')) {
  871. warn(LD_BUG,
  872. "Bug: we're writing a text string that already contains a CR.");
  873. }
  874. #endif
  875. return write_bytes_to_file(fname, str, strlen(str), bin);
  876. }
  877. /* DOCDOC */
  878. static int
  879. write_chunks_to_file_impl(const char *fname, const smartlist_t *chunks,
  880. int open_flags)
  881. {
  882. size_t tempname_len;
  883. char *tempname;
  884. int fd;
  885. int result;
  886. tempname_len = strlen(fname)+16;
  887. tor_assert(tempname_len > strlen(fname)); /*check for overflow*/
  888. tempname = tor_malloc(tempname_len);
  889. if (open_flags & O_APPEND) {
  890. strlcpy(tempname, fname, tempname_len);
  891. } else {
  892. if (tor_snprintf(tempname, tempname_len, "%s.tmp", fname)<0) {
  893. log(LOG_WARN, LD_GENERAL, "Failed to generate filename");
  894. goto err;
  895. }
  896. }
  897. if ((fd = open(tempname, open_flags, 0600))
  898. < 0) {
  899. log(LOG_WARN, LD_FS, "Couldn't open \"%s\" for writing: %s", tempname,
  900. strerror(errno));
  901. goto err;
  902. }
  903. SMARTLIST_FOREACH(chunks, sized_chunk_t *, chunk,
  904. {
  905. result = write_all(fd, chunk->bytes, chunk->len, 0);
  906. if (result < 0 || (size_t)result != chunk->len) {
  907. log(LOG_WARN, LD_FS, "Error writing to \"%s\": %s", tempname,
  908. strerror(errno));
  909. close(fd);
  910. goto err;
  911. }
  912. });
  913. if (close(fd)) {
  914. log(LOG_WARN, LD_FS, "Error flushing to \"%s\": %s", tempname,
  915. strerror(errno));
  916. goto err;
  917. }
  918. if (!(open_flags & O_APPEND)) {
  919. if (replace_file(tempname, fname)) {
  920. log(LOG_WARN, LD_FS, "Error replacing \"%s\": %s", fname,
  921. strerror(errno));
  922. goto err;
  923. }
  924. }
  925. tor_free(tempname);
  926. return 0;
  927. err:
  928. tor_free(tempname);
  929. return -1;
  930. }
  931. /* DOCDOC */
  932. int
  933. write_chunks_to_file(const char *fname, const smartlist_t *chunks, int bin)
  934. {
  935. int flags = O_WRONLY|O_CREAT|O_TRUNC|(bin?O_BINARY:O_TEXT);
  936. return write_chunks_to_file_impl(fname, chunks, flags);
  937. }
  938. /** As write_str_to_file, but does not assume a NUL-terminated *
  939. * string. Instead, we write <b>len</b> bytes, starting at <b>str</b>. */
  940. int
  941. write_bytes_to_file(const char *fname, const char *str, size_t len,
  942. int bin)
  943. {
  944. int flags = O_WRONLY|O_CREAT|O_TRUNC|(bin?O_BINARY:O_TEXT);
  945. int r;
  946. sized_chunk_t c = { str, len };
  947. smartlist_t *chunks = smartlist_create();
  948. smartlist_add(chunks, &c);
  949. r = write_chunks_to_file_impl(fname, chunks, flags);
  950. smartlist_free(chunks);
  951. return r;
  952. }
  953. /* DOCDOC */
  954. int
  955. append_bytes_to_file(const char *fname, const char *str, size_t len,
  956. int bin)
  957. {
  958. int flags = O_WRONLY|O_CREAT|O_APPEND|(bin?O_BINARY:O_TEXT);
  959. int r;
  960. sized_chunk_t c = { str, len };
  961. smartlist_t *chunks = smartlist_create();
  962. smartlist_add(chunks, &c);
  963. r = write_chunks_to_file_impl(fname, chunks, flags);
  964. smartlist_free(chunks);
  965. return r;
  966. }
  967. /** Read the contents of <b>filename</b> into a newly allocated
  968. * string; return the string on success or NULL on failure.
  969. */
  970. /*
  971. * This function <em>may</em> return an erroneous result if the file
  972. * is modified while it is running, but must not crash or overflow.
  973. * Right now, the error case occurs when the file length grows between
  974. * the call to stat and the call to read_all: the resulting string will
  975. * be truncated.
  976. */
  977. char *
  978. read_file_to_str(const char *filename, int bin)
  979. {
  980. int fd; /* router file */
  981. struct stat statbuf;
  982. char *string, *f;
  983. int r;
  984. tor_assert(filename);
  985. f = tor_strdup(filename);
  986. clean_name_for_stat(f);
  987. r = stat(f, &statbuf);
  988. tor_free(f);
  989. if (r < 0) {
  990. info(LD_FS,"Could not stat \"%s\".",filename);
  991. return NULL;
  992. }
  993. fd = open(filename,O_RDONLY|(bin?O_BINARY:O_TEXT),0);
  994. if (fd<0) {
  995. warn(LD_FS,"Could not open \"%s\".",filename);
  996. return NULL;
  997. }
  998. string = tor_malloc(statbuf.st_size+1);
  999. r = read_all(fd,string,statbuf.st_size,0);
  1000. if (r<0) {
  1001. warn(LD_FS,"Error reading from file \"%s\": %s", filename,
  1002. strerror(errno));
  1003. tor_free(string);
  1004. close(fd);
  1005. return NULL;
  1006. }
  1007. string[r] = '\0'; /* NUL-terminate the result. */
  1008. if (bin && r != statbuf.st_size) {
  1009. /* If we're in binary mode, then we'd better have an exact match for
  1010. * size. Otherwise, win32 encoding may throw us off, and that's okay. */
  1011. warn(LD_FS,"Could read only %d of %ld bytes of file \"%s\".",
  1012. r, (long)statbuf.st_size,filename);
  1013. tor_free(string);
  1014. close(fd);
  1015. return NULL;
  1016. }
  1017. #ifdef MS_WINDOWS
  1018. if (!bin && strchr(string, '\r')) {
  1019. debug(LD_FS, "We didn't convert CRLF to LF as well as we hoped "
  1020. "when reading %s. Coping.",
  1021. filename);
  1022. tor_strstrip(string, "\r");
  1023. }
  1024. #endif
  1025. close(fd);
  1026. return string;
  1027. }
  1028. /** Given a string containing part of a configuration file or similar format,
  1029. * advance past comments and whitespace and try to parse a single line. If we
  1030. * parse a line successfully, set *<b>key_out</b> to the key portion and
  1031. * *<b>value_out</b> to the value portion of the line, and return a pointer to
  1032. * the start of the next line. If we run out of data, return a pointer to the
  1033. * end of the string. If we encounter an error, return NULL.
  1034. *
  1035. * NOTE: We modify <b>line</b> as we parse it, by inserting NULs to terminate
  1036. * the key and value.
  1037. */
  1038. char *
  1039. parse_line_from_str(char *line, char **key_out, char **value_out)
  1040. {
  1041. char *key, *val, *cp;
  1042. tor_assert(key_out);
  1043. tor_assert(value_out);
  1044. *key_out = *value_out = key = val = NULL;
  1045. /* Skip until the first keyword. */
  1046. while (1) {
  1047. while (TOR_ISSPACE(*line))
  1048. ++line;
  1049. if (*line == '#') {
  1050. while (*line && *line != '\n')
  1051. ++line;
  1052. } else {
  1053. break;
  1054. }
  1055. }
  1056. if (!*line) { /* End of string? */
  1057. *key_out = *value_out = NULL;
  1058. return line;
  1059. }
  1060. /* Skip until the next space. */
  1061. key = line;
  1062. while (*line && !TOR_ISSPACE(*line) && *line != '#')
  1063. ++line;
  1064. /* Skip until the value */
  1065. while (*line == ' ' || *line == '\t')
  1066. *line++ = '\0';
  1067. val = line;
  1068. /* Find the end of the line. */
  1069. while (*line && *line != '\n' && *line != '#')
  1070. ++line;
  1071. if (*line == '\n')
  1072. cp = line++;
  1073. else {
  1074. cp = line-1;
  1075. }
  1076. while (cp>=val && TOR_ISSPACE(*cp))
  1077. *cp-- = '\0';
  1078. if (*line == '#') {
  1079. do {
  1080. *line++ = '\0';
  1081. } while (*line && *line != '\n');
  1082. if (*line == '\n')
  1083. ++line;
  1084. }
  1085. *key_out = key;
  1086. *value_out = val;
  1087. return line;
  1088. }
  1089. /** Expand any homedir prefix on 'filename'; return a newly allocated
  1090. * string. */
  1091. char *
  1092. expand_filename(const char *filename)
  1093. {
  1094. tor_assert(filename);
  1095. if (*filename == '~') {
  1096. size_t len;
  1097. char *home, *result;
  1098. const char *rest;
  1099. if (filename[1] == '/' || filename[1] == '\0') {
  1100. home = getenv("HOME");
  1101. if (!home) {
  1102. warn(LD_CONFIG, "Couldn't find $HOME environment variable while "
  1103. "expanding %s", filename);
  1104. return NULL;
  1105. }
  1106. home = tor_strdup(home);
  1107. rest = strlen(filename)>=2?(filename+2):NULL;
  1108. } else {
  1109. #ifdef HAVE_PWD_H
  1110. char *username, *slash;
  1111. slash = strchr(filename, '/');
  1112. if (slash)
  1113. username = tor_strndup(filename+1,slash-filename-1);
  1114. else
  1115. username = tor_strdup(filename+1);
  1116. if (!(home = get_user_homedir(username))) {
  1117. warn(LD_CONFIG,"Couldn't get homedir for \"%s\"",username);
  1118. tor_free(username);
  1119. return NULL;
  1120. }
  1121. tor_free(username);
  1122. rest = slash ? (slash+1) : NULL;
  1123. #else
  1124. warn(LD_CONFIG, "Couldn't expend homedir on system without pwd.h");
  1125. return tor_strdup(filename);
  1126. #endif
  1127. }
  1128. tor_assert(home);
  1129. /* Remove trailing slash. */
  1130. if (strlen(home)>1 && !strcmpend(home,"/")) {
  1131. home[strlen(home)-1] = '\0';
  1132. }
  1133. /* Plus one for /, plus one for NUL.
  1134. * Round up to 16 in case we can't do math. */
  1135. len = strlen(home)+strlen(rest)+16;
  1136. result = tor_malloc(len);
  1137. tor_snprintf(result,len,"%s/%s",home,rest?rest:"");
  1138. tor_free(home);
  1139. return result;
  1140. } else {
  1141. return tor_strdup(filename);
  1142. }
  1143. }
  1144. /** Return a new list containing the filenames in the directory <b>dirname</b>.
  1145. * Return NULL on error or if <b>dirname</b> is not a directory.
  1146. */
  1147. smartlist_t *
  1148. tor_listdir(const char *dirname)
  1149. {
  1150. smartlist_t *result;
  1151. #ifdef MS_WINDOWS
  1152. char *pattern;
  1153. HANDLE handle;
  1154. WIN32_FIND_DATA findData;
  1155. size_t pattern_len = strlen(dirname)+16;
  1156. pattern = tor_malloc(pattern_len);
  1157. tor_snprintf(pattern, pattern_len, "%s\\*", dirname);
  1158. if (!(handle = FindFirstFile(pattern, &findData))) {
  1159. tor_free(pattern);
  1160. return NULL;
  1161. }
  1162. result = smartlist_create();
  1163. while (1) {
  1164. if (strcmp(findData.cFileName, ".") &&
  1165. strcmp(findData.cFileName, "..")) {
  1166. smartlist_add(result, tor_strdup(findData.cFileName));
  1167. }
  1168. if (!FindNextFile(handle, &findData)) {
  1169. if (GetLastError() != ERROR_NO_MORE_FILES) {
  1170. warn(LD_FS, "Error reading directory.");
  1171. }
  1172. break;
  1173. }
  1174. }
  1175. FindClose(handle);
  1176. tor_free(pattern);
  1177. #else
  1178. DIR *d;
  1179. struct dirent *de;
  1180. if (!(d = opendir(dirname)))
  1181. return NULL;
  1182. result = smartlist_create();
  1183. while ((de = readdir(d))) {
  1184. if (!strcmp(de->d_name, ".") ||
  1185. !strcmp(de->d_name, ".."))
  1186. continue;
  1187. smartlist_add(result, tor_strdup(de->d_name));
  1188. }
  1189. closedir(d);
  1190. #endif
  1191. return result;
  1192. }
  1193. /* =====
  1194. * Net helpers
  1195. * ===== */
  1196. /** Return true iff <b>ip</b> (in host order) is an IP reserved to localhost,
  1197. * or reserved for local networks by RFC 1918.
  1198. */
  1199. int
  1200. is_internal_IP(uint32_t ip, int for_listening)
  1201. {
  1202. if (for_listening && !ip) /* special case for binding to 0.0.0.0 */
  1203. return 0;
  1204. if (((ip & 0xff000000) == 0x0a000000) || /* 10/8 */
  1205. ((ip & 0xff000000) == 0x00000000) || /* 0/8 */
  1206. ((ip & 0xff000000) == 0x7f000000) || /* 127/8 */
  1207. ((ip & 0xffff0000) == 0xa9fe0000) || /* 169.254/16 */
  1208. ((ip & 0xfff00000) == 0xac100000) || /* 172.16/12 */
  1209. ((ip & 0xffff0000) == 0xc0a80000)) /* 192.168/16 */
  1210. return 1;
  1211. return 0;
  1212. }
  1213. /** Return true iff <b>ip</b> (in host order) is judged to be on the
  1214. * same network as us. For now, check if it's an internal IP.
  1215. *
  1216. * XXX Also check if it's on the same class C network as our public IP.
  1217. */
  1218. int
  1219. is_local_IP(uint32_t ip)
  1220. {
  1221. return is_internal_IP(ip, 0);
  1222. }
  1223. /** Parse a string of the form "host[:port]" from <b>addrport</b>. If
  1224. * <b>address</b> is provided, set *<b>address</b> to a copy of the
  1225. * host portion of the string. If <b>addr</b> is provided, try to
  1226. * resolve the host portion of the string and store it into
  1227. * *<b>addr</b> (in host byte order). If <b>port_out</b> is provided,
  1228. * store the port number into *<b>port_out</b>, or 0 if no port is given.
  1229. * If <b>port_out</b> is NULL, then there must be no port number in
  1230. * <b>addrport</b>.
  1231. * Return 0 on success, -1 on failure.
  1232. */
  1233. int
  1234. parse_addr_port(const char *addrport, char **address, uint32_t *addr,
  1235. uint16_t *port_out)
  1236. {
  1237. const char *colon;
  1238. char *_address = NULL;
  1239. int _port;
  1240. int ok = 1;
  1241. tor_assert(addrport);
  1242. colon = strchr(addrport, ':');
  1243. if (colon) {
  1244. _address = tor_strndup(addrport, colon-addrport);
  1245. _port = (int) tor_parse_long(colon+1,10,1,65535,NULL,NULL);
  1246. if (!_port) {
  1247. warn(LD_GENERAL, "Port '%s' out of range", colon+1);
  1248. ok = 0;
  1249. }
  1250. if (!port_out) {
  1251. warn(LD_GENERAL, "Port '%s' given on '%s' when not required", colon+1,
  1252. addrport);
  1253. ok = 0;
  1254. }
  1255. } else {
  1256. _address = tor_strdup(addrport);
  1257. _port = 0;
  1258. }
  1259. if (addr) {
  1260. /* There's an addr pointer, so we need to resolve the hostname. */
  1261. if (tor_lookup_hostname(_address,addr)) {
  1262. warn(LD_NET, "Couldn't look up '%s'", _address);
  1263. ok = 0;
  1264. *addr = 0;
  1265. }
  1266. *addr = ntohl(*addr);
  1267. }
  1268. if (address && ok) {
  1269. *address = _address;
  1270. } else {
  1271. if (address)
  1272. *address = NULL;
  1273. tor_free(_address);
  1274. }
  1275. if (port_out)
  1276. *port_out = ok ? ((uint16_t) _port) : 0;
  1277. return ok ? 0 : -1;
  1278. }
  1279. /** Parse a string <b>s</b> in the format of
  1280. * (IP(/mask|/mask-bits)?|*):(*|port(-maxport)?), setting the various
  1281. * *out pointers as appropriate. Return 0 on success, -1 on failure.
  1282. */
  1283. int
  1284. parse_addr_and_port_range(const char *s, uint32_t *addr_out,
  1285. uint32_t *mask_out, uint16_t *port_min_out,
  1286. uint16_t *port_max_out)
  1287. {
  1288. char *address;
  1289. char *mask, *port, *endptr;
  1290. struct in_addr in;
  1291. int bits;
  1292. tor_assert(s);
  1293. tor_assert(addr_out);
  1294. tor_assert(mask_out);
  1295. tor_assert(port_min_out);
  1296. tor_assert(port_max_out);
  1297. address = tor_strdup(s);
  1298. /* Break 'address' into separate strings.
  1299. */
  1300. mask = strchr(address,'/');
  1301. port = strchr(mask?mask:address,':');
  1302. if (mask)
  1303. *mask++ = '\0';
  1304. if (port)
  1305. *port++ = '\0';
  1306. /* Now "address" is the IP|'*' part...
  1307. * "mask" is the Mask|Maskbits part...
  1308. * and "port" is the *|port|min-max part.
  1309. */
  1310. if (strcmp(address,"*")==0) {
  1311. *addr_out = 0;
  1312. } else if (tor_inet_aton(address, &in) != 0) {
  1313. *addr_out = ntohl(in.s_addr);
  1314. } else {
  1315. warn(LD_GENERAL, "Malformed IP \"%s\" in address pattern; rejecting.",
  1316. address);
  1317. goto err;
  1318. }
  1319. if (!mask) {
  1320. if (strcmp(address,"*")==0)
  1321. *mask_out = 0;
  1322. else
  1323. *mask_out = 0xFFFFFFFFu;
  1324. } else {
  1325. endptr = NULL;
  1326. bits = (int) strtol(mask, &endptr, 10);
  1327. if (!*endptr) {
  1328. /* strtol handled the whole mask. */
  1329. if (bits < 0 || bits > 32) {
  1330. warn(LD_GENERAL,
  1331. "Bad number of mask bits on address range; rejecting.");
  1332. goto err;
  1333. }
  1334. *mask_out = ~((1<<(32-bits))-1);
  1335. } else if (tor_inet_aton(mask, &in) != 0) {
  1336. *mask_out = ntohl(in.s_addr);
  1337. } else {
  1338. warn(LD_GENERAL, "Malformed mask \"%s\" on address range; rejecting.",
  1339. mask);
  1340. goto err;
  1341. }
  1342. }
  1343. if (!port || strcmp(port, "*") == 0) {
  1344. *port_min_out = 1;
  1345. *port_max_out = 65535;
  1346. } else {
  1347. endptr = NULL;
  1348. *port_min_out = (uint16_t) tor_parse_long(port, 10, 1, 65535,
  1349. NULL, &endptr);
  1350. if (*endptr == '-') {
  1351. port = endptr+1;
  1352. endptr = NULL;
  1353. *port_max_out = (uint16_t) tor_parse_long(port, 10, 1, 65535, NULL,
  1354. &endptr);
  1355. if (*endptr || !*port_max_out) {
  1356. warn(LD_GENERAL, "Malformed port \"%s\" on address range rejecting.",
  1357. port);
  1358. }
  1359. } else if (*endptr || !*port_min_out) {
  1360. warn(LD_GENERAL, "Malformed port \"%s\" on address range; rejecting.",
  1361. port);
  1362. goto err;
  1363. } else {
  1364. *port_max_out = *port_min_out;
  1365. }
  1366. if (*port_min_out > *port_max_out) {
  1367. warn(LD_GENERAL, "Insane port range on address policy; rejecting.");
  1368. goto err;
  1369. }
  1370. }
  1371. tor_free(address);
  1372. return 0;
  1373. err:
  1374. tor_free(address);
  1375. return -1;
  1376. }
  1377. /** Given an IPv4 address <b>in</b> (in network order, as usual),
  1378. * write it as a string into the <b>buf_len</b>-byte buffer in
  1379. * <b>buf</b>.
  1380. */
  1381. int
  1382. tor_inet_ntoa(struct in_addr *in, char *buf, size_t buf_len)
  1383. {
  1384. uint32_t a = ntohl(in->s_addr);
  1385. return tor_snprintf(buf, buf_len, "%d.%d.%d.%d",
  1386. (int)(uint8_t)((a>>24)&0xff),
  1387. (int)(uint8_t)((a>>16)&0xff),
  1388. (int)(uint8_t)((a>>8 )&0xff),
  1389. (int)(uint8_t)((a )&0xff));
  1390. }
  1391. /** Given a host-order <b>addr</b>, call tor_inet_ntoa() on it
  1392. * and return a strdup of the resulting address.
  1393. */
  1394. char *
  1395. tor_dup_addr(uint32_t addr)
  1396. {
  1397. char buf[INET_NTOA_BUF_LEN];
  1398. struct in_addr in;
  1399. in.s_addr = htonl(addr);
  1400. tor_inet_ntoa(&in, buf, sizeof(buf));
  1401. return tor_strdup(buf);
  1402. }
  1403. /* Return true iff <b>name</b> looks like it might be a hostname or IP
  1404. * address of some kind. */
  1405. int
  1406. is_plausible_address(const char *name)
  1407. {
  1408. const char *cp;
  1409. tor_assert(name);
  1410. /* We could check better here. */
  1411. for (cp=name; *cp; cp++) {
  1412. if (*cp != '.' && *cp != '-' && !TOR_ISALNUM(*cp))
  1413. return 0;
  1414. }
  1415. return 1;
  1416. }
  1417. /**
  1418. * Set *<b>addr</b> to the host-order IPv4 address (if any) of whatever
  1419. * interface connects to the internet. This address should only be used in
  1420. * checking whether our address has changed. Return 0 on success, -1 on
  1421. * failure.
  1422. */
  1423. int
  1424. get_interface_address(uint32_t *addr)
  1425. {
  1426. int sock=-1, r=-1;
  1427. struct sockaddr_in target_addr, my_addr;
  1428. socklen_t my_addr_len = sizeof(my_addr);
  1429. tor_assert(addr);
  1430. *addr = 0;
  1431. sock = socket(PF_INET,SOCK_DGRAM,IPPROTO_UDP);
  1432. if (sock < 0) {
  1433. int e = tor_socket_errno(-1);
  1434. warn(LD_NET, "unable to create socket: %s", tor_socket_strerror(e));
  1435. goto err;
  1436. }
  1437. memset(&target_addr, 0, sizeof(target_addr));
  1438. target_addr.sin_family = AF_INET;
  1439. /* discard port */
  1440. target_addr.sin_port = 9;
  1441. /* 18.0.0.1 (Don't worry: no packets are sent. We just need a real address
  1442. * on the internet.) */
  1443. target_addr.sin_addr.s_addr = htonl(0x12000001);
  1444. if (connect(sock,(struct sockaddr *)&target_addr,sizeof(target_addr))<0) {
  1445. int e = tor_socket_errno(sock);
  1446. warn(LD_NET, "connnect() failed: %s", tor_socket_strerror(e));
  1447. goto err;
  1448. }
  1449. /* XXXX Can this be right on IPv6 clients? */
  1450. if (getsockname(sock, (struct sockaddr*)&my_addr, &my_addr_len)) {
  1451. int e = tor_socket_errno(sock);
  1452. warn(LD_NET, "getsockname() failed: %s", tor_socket_strerror(e));
  1453. goto err;
  1454. }
  1455. *addr = ntohl(my_addr.sin_addr.s_addr);
  1456. r=0;
  1457. err:
  1458. if (sock >= 0)
  1459. tor_close_socket(sock);
  1460. return r;
  1461. }
  1462. /* =====
  1463. * Process helpers
  1464. * ===== */
  1465. #ifndef MS_WINDOWS
  1466. /* Based on code contributed by christian grothoff */
  1467. static int start_daemon_called = 0;
  1468. static int finish_daemon_called = 0;
  1469. static int daemon_filedes[2];
  1470. /** Start putting the process into daemon mode: fork and drop all resources
  1471. * except standard fds. The parent process never returns, but stays around
  1472. * until finish_daemon is called. (Note: it's safe to call this more
  1473. * than once: calls after the first are ignored.)
  1474. */
  1475. void
  1476. start_daemon(void)
  1477. {
  1478. pid_t pid;
  1479. if (start_daemon_called)
  1480. return;
  1481. start_daemon_called = 1;
  1482. pipe(daemon_filedes);
  1483. pid = fork();
  1484. if (pid < 0) {
  1485. err(LD_GENERAL,"fork failed. Exiting.");
  1486. exit(1);
  1487. }
  1488. if (pid) { /* Parent */
  1489. int ok;
  1490. char c;
  1491. close(daemon_filedes[1]); /* we only read */
  1492. ok = -1;
  1493. while (0 < read(daemon_filedes[0], &c, sizeof(char))) {
  1494. if (c == '.')
  1495. ok = 1;
  1496. }
  1497. fflush(stdout);
  1498. if (ok == 1)
  1499. exit(0);
  1500. else
  1501. exit(1); /* child reported error */
  1502. } else { /* Child */
  1503. close(daemon_filedes[0]); /* we only write */
  1504. pid = setsid(); /* Detach from controlling terminal */
  1505. /*
  1506. * Fork one more time, so the parent (the session group leader) can exit.
  1507. * This means that we, as a non-session group leader, can never regain a
  1508. * controlling terminal. This part is recommended by Stevens's
  1509. * _Advanced Programming in the Unix Environment_.
  1510. */
  1511. if (fork() != 0) {
  1512. exit(0);
  1513. }
  1514. return;
  1515. }
  1516. }
  1517. /** Finish putting the process into daemon mode: drop standard fds, and tell
  1518. * the parent process to exit. (Note: it's safe to call this more than once:
  1519. * calls after the first are ignored. Calls start_daemon first if it hasn't
  1520. * been called already.)
  1521. */
  1522. void
  1523. finish_daemon(const char *desired_cwd)
  1524. {
  1525. int nullfd;
  1526. char c = '.';
  1527. if (finish_daemon_called)
  1528. return;
  1529. if (!start_daemon_called)
  1530. start_daemon();
  1531. finish_daemon_called = 1;
  1532. if (!desired_cwd)
  1533. desired_cwd = "/";
  1534. /* Don't hold the wrong FS mounted */
  1535. if (chdir(desired_cwd) < 0) {
  1536. err(LD_GENERAL,"chdir to \"%s\" failed. Exiting.",desired_cwd);
  1537. exit(1);
  1538. }
  1539. nullfd = open("/dev/null",
  1540. O_CREAT | O_RDWR | O_APPEND);
  1541. if (nullfd < 0) {
  1542. err(LD_GENERAL,"/dev/null can't be opened. Exiting.");
  1543. exit(1);
  1544. }
  1545. /* close fds linking to invoking terminal, but
  1546. * close usual incoming fds, but redirect them somewhere
  1547. * useful so the fds don't get reallocated elsewhere.
  1548. */
  1549. if (dup2(nullfd,0) < 0 ||
  1550. dup2(nullfd,1) < 0 ||
  1551. dup2(nullfd,2) < 0) {
  1552. err(LD_GENERAL,"dup2 failed. Exiting.");
  1553. exit(1);
  1554. }
  1555. if (nullfd > 2)
  1556. close(nullfd);
  1557. write(daemon_filedes[1], &c, sizeof(char)); /* signal success */
  1558. close(daemon_filedes[1]);
  1559. }
  1560. #else
  1561. /* defined(MS_WINDOWS) */
  1562. void
  1563. start_daemon(void)
  1564. {
  1565. }
  1566. void
  1567. finish_daemon(const char *cp)
  1568. {
  1569. }
  1570. #endif
  1571. /** Write the current process ID, followed by NL, into <b>filename</b>.
  1572. */
  1573. void
  1574. write_pidfile(char *filename)
  1575. {
  1576. #ifndef MS_WINDOWS
  1577. FILE *pidfile;
  1578. if ((pidfile = fopen(filename, "w")) == NULL) {
  1579. warn(LD_FS, "Unable to open \"%s\" for writing: %s", filename,
  1580. strerror(errno));
  1581. } else {
  1582. fprintf(pidfile, "%d\n", (int)getpid());
  1583. fclose(pidfile);
  1584. }
  1585. #endif
  1586. }