util.c 43 KB

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