util.c 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323
  1. /* Copyright 2003 Roger Dingledine */
  2. /* See LICENSE for licensing information */
  3. /* $Id$ */
  4. /**
  5. * \file util.c
  6. *
  7. * \brief Common functions for strings, IO, network, data structures,
  8. * process control.
  9. **/
  10. /* This is required on rh7 to make strptime not complain.
  11. */
  12. #define _GNU_SOURCE
  13. #include "orconfig.h"
  14. #include "util.h"
  15. #include "log.h"
  16. #include "crypto.h"
  17. /* XXXX probably some of these are unneeded. find out which. */
  18. #ifdef MS_WINDOWS
  19. #include <io.h>
  20. #include <process.h>
  21. #include <direct.h>
  22. #include <windows.h>
  23. #endif
  24. #ifdef HAVE_CTYPE_H
  25. #include <ctype.h>
  26. #endif
  27. #include <stdlib.h>
  28. #include <stdio.h>
  29. #include <string.h>
  30. #include <assert.h>
  31. #ifdef HAVE_NETINET_IN_H
  32. #include <netinet/in.h>
  33. #endif
  34. #ifdef HAVE_ARPA_INET_H
  35. #include <arpa/inet.h>
  36. #endif
  37. #ifdef HAVE_ERRNO_H
  38. #include <errno.h>
  39. #endif
  40. #ifdef HAVE_LIMITS_H
  41. #include <limits.h>
  42. #endif
  43. #ifdef HAVE_SYS_LIMITS_H
  44. #include <sys/limits.h>
  45. #endif
  46. #ifdef HAVE_MACHINE_LIMITS_H
  47. #ifndef __FreeBSD__
  48. /* FreeBSD has a bug where it complains that this file is obsolete,
  49. and I should migrate to using sys/limits. It complains even when
  50. I include both. */
  51. #include <machine/limits.h>
  52. #endif
  53. #endif
  54. #ifdef HAVE_SYS_TYPES_H
  55. #include <sys/types.h> /* Must be included before sys/stat.h for Ultrix */
  56. #endif
  57. #ifdef HAVE_SYS_SOCKET_H
  58. #include <sys/socket.h>
  59. #endif
  60. #ifdef HAVE_NETDB_H
  61. #include <netdb.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. /* used by inet_addr, not defined on solaris anywhere!? */
  79. #ifndef INADDR_NONE
  80. #define INADDR_NONE ((unsigned long) -1)
  81. #endif
  82. #ifndef O_BINARY
  83. #define O_BINARY 0
  84. #endif
  85. /* =====
  86. * Memory management
  87. * ===== */
  88. /** Allocate a chunk of <b>size</b> bytes of memory, and return a pointer to
  89. * result. On error, log and terminate the process. (Same as malloc(size),
  90. * but never returns NULL.)
  91. */
  92. void *tor_malloc(size_t size) {
  93. void *result;
  94. /* Some libcs don't do the right thing on size==0. Override them. */
  95. if (size==0) {
  96. size=1;
  97. }
  98. result = malloc(size);
  99. if(!result) {
  100. log_fn(LOG_ERR, "Out of memory. Dying.");
  101. exit(1);
  102. }
  103. // memset(result,'X',size); /* deadbeef to encourage bugs */
  104. return result;
  105. }
  106. /* Allocate a chunk of <b>size</b> bytes of memory, fill the memory with
  107. * zero bytes, and return a pointer to the result. Log and terminate
  108. * the process on error. (Same as calloc(size,1), but never returns NULL.)
  109. */
  110. void *tor_malloc_zero(size_t size) {
  111. void *result = tor_malloc(size);
  112. memset(result, 0, size);
  113. return result;
  114. }
  115. /** Change the size of the memory block pointed to by <b>ptr</b> to <b>size</b>
  116. * bytes long; return the new memory block. On error, log and
  117. * terminate. (Like realloc(ptr,size), but never returns NULL.)
  118. */
  119. void *tor_realloc(void *ptr, size_t size) {
  120. void *result;
  121. result = realloc(ptr, size);
  122. if (!result) {
  123. log_fn(LOG_ERR, "Out of memory. Dying.");
  124. exit(1);
  125. }
  126. return result;
  127. }
  128. /** Return a newly allocated copy of the NUL-terminated string s. On
  129. * error, log and terminate. (Like strdup(s), but never returns
  130. * NULL.)
  131. */
  132. char *tor_strdup(const char *s) {
  133. char *dup;
  134. tor_assert(s);
  135. dup = strdup(s);
  136. if(!dup) {
  137. log_fn(LOG_ERR,"Out of memory. Dying.");
  138. exit(1);
  139. }
  140. return dup;
  141. }
  142. /** Allocate and return a new string containing the first <b>n</b>
  143. * characters of <b>s</b>. If <b>s</b> is longer than <b>n</b>
  144. * characters, only the first <b>n</b> are copied. The result is
  145. * always NUL-terminated. (Like strndup(s,n), but never returns
  146. * NULL.)
  147. */
  148. char *tor_strndup(const char *s, size_t n) {
  149. char *dup;
  150. tor_assert(s);
  151. dup = tor_malloc(n+1);
  152. strlcpy(dup, s, n+1);
  153. return dup;
  154. }
  155. /* =====
  156. * String manipulation
  157. * ===== */
  158. /** Remove from the string <b>s</b> every character which appears in
  159. * <b>strip</b>. Return the number of characters removed. */
  160. int tor_strstrip(char *s, const char *strip)
  161. {
  162. char *read = s;
  163. while (*read) {
  164. if (strchr(strip, *read)) {
  165. ++read;
  166. } else {
  167. *s++ = *read++;
  168. }
  169. }
  170. *s = '\0';
  171. return read-s;
  172. }
  173. /** Set the <b>dest_len</b>-byte buffer <b>buf</b> to contain the
  174. * string <b>s</b>, with the string <b>insert</b> inserted after every
  175. * <b>n</b> characters. Return 0 on success, -1 on failure.
  176. *
  177. * If <b>rule</b> is ALWAYS_TERMINATE, then always end the string with
  178. * <b>insert</b>, even if its length is not a multiple of <b>n</b>. If
  179. * <b>rule</b> is NEVER_TERMINATE, then never end the string with
  180. * <b>insert</b>, even if its length <i>is</i> a multiple of <b>n</b>.
  181. * If <b>rule</b> is TERMINATE_IF_EVEN, then end the string with <b>insert</b>
  182. * exactly when its length <i>is</i> a multiple of <b>n</b>.
  183. */
  184. int tor_strpartition(char *dest, size_t dest_len,
  185. const char *s, const char *insert, size_t n,
  186. part_finish_rule_t rule)
  187. {
  188. char *destp;
  189. size_t len_in, len_out, len_ins;
  190. int is_even, remaining;
  191. tor_assert(s);
  192. tor_assert(insert);
  193. tor_assert(n > 0);
  194. len_in = strlen(s);
  195. len_ins = strlen(insert);
  196. len_out = len_in + (len_in/n)*len_ins;
  197. is_even = (len_in%n) == 0;
  198. switch(rule)
  199. {
  200. case ALWAYS_TERMINATE:
  201. if (!is_even) len_out += len_ins;
  202. break;
  203. case NEVER_TERMINATE:
  204. if (is_even && len_in) len_out -= len_ins;
  205. break;
  206. case TERMINATE_IF_EVEN:
  207. break;
  208. }
  209. if (dest_len < len_out+1)
  210. return -1;
  211. destp = dest;
  212. remaining = len_in;
  213. while(remaining) {
  214. strncpy(destp, s, n);
  215. remaining -= n;
  216. if (remaining < 0) {
  217. if (rule == ALWAYS_TERMINATE)
  218. strcpy(destp+n+remaining,insert);
  219. break;
  220. } else if (remaining == 0 && rule == NEVER_TERMINATE) {
  221. *(destp+n) = '\0';
  222. break;
  223. }
  224. strcpy(destp+n, insert);
  225. s += n;
  226. destp += n+len_ins;
  227. }
  228. tor_assert(len_out == strlen(dest));
  229. return 0;
  230. }
  231. /** Return a pointer to a NUL-terminated hexidecimal string encoding
  232. * the first <b>fromlen</b> bytes of <b>from</b>. (fromlen must be \<= 32.) The
  233. * result does not need to be deallocated, but repeated calls to
  234. * hex_str will trash old results.
  235. */
  236. const char *hex_str(const char *from, size_t fromlen)
  237. {
  238. static char buf[65];
  239. if (fromlen>(sizeof(buf)-1)/2)
  240. fromlen = (sizeof(buf)-1)/2;
  241. base16_encode(buf,sizeof(buf),from,fromlen);
  242. return buf;
  243. }
  244. /** Convert all alphabetic characters in the nul-terminated string <b>s</b> to
  245. * lowercase. */
  246. void tor_strlower(char *s)
  247. {
  248. while (*s) {
  249. *s = tolower(*s);
  250. ++s;
  251. }
  252. }
  253. /* Compares the first strlen(s2) characters of s1 with s2. Returns as for
  254. * strcmp.
  255. */
  256. int strcmpstart(const char *s1, const char *s2)
  257. {
  258. size_t n = strlen(s2);
  259. return strncmp(s1, s2, n);
  260. }
  261. /** Return a pointer to the first char of s that is not whitespace and
  262. * not a comment, or to the terminating NUL if no such character exists.
  263. */
  264. const char *eat_whitespace(const char *s) {
  265. tor_assert(s);
  266. while(isspace((int)*s) || *s == '#') {
  267. while(isspace((int)*s))
  268. s++;
  269. if(*s == '#') { /* read to a \n or \0 */
  270. while(*s && *s != '\n')
  271. s++;
  272. if(!*s)
  273. return s;
  274. }
  275. }
  276. return s;
  277. }
  278. /** Return a pointer to the first char of s that is not a space or a tab,
  279. * or to the terminating NUL if no such character exists. */
  280. const char *eat_whitespace_no_nl(const char *s) {
  281. while(*s == ' ' || *s == '\t')
  282. ++s;
  283. return s;
  284. }
  285. /** Return a pointer to the first char of s that is whitespace or <b>#</b>,
  286. * or to the terminating NUL if no such character exists.
  287. */
  288. const char *find_whitespace(const char *s) {
  289. tor_assert(s);
  290. while(*s && !isspace((int)*s) && *s != '#')
  291. s++;
  292. return s;
  293. }
  294. #define CHECK_STRTOX_RESULT() \
  295. /* Was at least one character converted? */ \
  296. if (endptr == s) \
  297. goto err; \
  298. /* Were there unexpected unconverted characters? */ \
  299. if (!next && *endptr) \
  300. goto err; \
  301. /* Is r within limits? */ \
  302. if (r < min || r > max) \
  303. goto err; \
  304. if (ok) *ok = 1; \
  305. if (next) *next = endptr; \
  306. return r; \
  307. err: \
  308. if (ok) *ok = 0; \
  309. if (next) *next = endptr; \
  310. return 0; \
  311. /** Extract a long from the start of s, in the given numeric base. If
  312. * there is unconverted data and next is provided, set *next to the
  313. * first unconverted character. An error has occurred if no characters
  314. * are converted; or if there are unconverted characters and next is NULL; or
  315. * if the parsed value is not between min and max. When no error occurs,
  316. * return the parsed value and set *ok (if provided) to 1. When an error
  317. * ocurs, return 0 and set *ok (if provided) to 0.
  318. */
  319. long
  320. tor_parse_long(const char *s, int base, long min, long max,
  321. int *ok, char **next)
  322. {
  323. char *endptr;
  324. long r;
  325. r = strtol(s, &endptr, base);
  326. CHECK_STRTOX_RESULT();
  327. }
  328. unsigned long
  329. tor_parse_ulong(const char *s, int base, unsigned long min,
  330. unsigned long max, int *ok, char **next)
  331. {
  332. char *endptr;
  333. unsigned long r;
  334. r = strtoul(s, &endptr, base);
  335. CHECK_STRTOX_RESULT();
  336. }
  337. uint64_t
  338. tor_parse_uint64(const char *s, int base, uint64_t min,
  339. uint64_t max, int *ok, char **next)
  340. {
  341. char *endptr;
  342. uint64_t r;
  343. #ifdef HAVE_STRTOULL
  344. r = (uint64_t)strtoull(s, &endptr, base);
  345. #elif defined(MS_WINDOWS)
  346. r = (uint64_t)_strtoui64(s, &endptr, base);
  347. #elif SIZEOF_LONG == 8
  348. r = (uint64_t)strtoul(s, &endptr, base);
  349. #else
  350. #error "I don't know how to parse 64-bit numbers."
  351. #endif
  352. CHECK_STRTOX_RESULT();
  353. }
  354. void base16_encode(char *dest, size_t destlen, const char *src, size_t srclen)
  355. {
  356. const char *end;
  357. char *cp;
  358. tor_assert(destlen >= srclen*2+1);
  359. cp = dest;
  360. end = src+srclen;
  361. while (src<end) {
  362. sprintf(cp,"%02X",*(const uint8_t*)src);
  363. ++src;
  364. cp += 2;
  365. }
  366. *cp = '\0';
  367. }
  368. static const char HEX_DIGITS[] = "0123456789ABCDEFabcdef";
  369. static INLINE int hex_decode_digit(char c)
  370. {
  371. const char *cp;
  372. int n;
  373. cp = strchr(HEX_DIGITS, c);
  374. if (!cp)
  375. return -1;
  376. n = cp-HEX_DIGITS;
  377. if (n<=15)
  378. return n; /* digit or uppercase */
  379. else
  380. return n-6; /* lowercase */
  381. }
  382. int base16_decode(char *dest, size_t destlen, const char *src, size_t srclen)
  383. {
  384. const char *end;
  385. int v1,v2;
  386. if ((srclen % 2) != 0)
  387. return -1;
  388. if (destlen < srclen/2)
  389. return -1;
  390. end = src+srclen;
  391. while (src<end) {
  392. v1 = hex_decode_digit(*src);
  393. v2 = hex_decode_digit(*(src+1));
  394. if(v1<0||v2<0)
  395. return -1;
  396. *(uint8_t*)dest = (v1<<4)|v2;
  397. ++dest;
  398. src+=2;
  399. }
  400. return 0;
  401. }
  402. /* =====
  403. * Time
  404. * ===== */
  405. /** Return the number of microseconds elapsed between *start and *end.
  406. * If start is after end, return 0.
  407. */
  408. long
  409. tv_udiff(struct timeval *start, struct timeval *end)
  410. {
  411. long udiff;
  412. long secdiff = end->tv_sec - start->tv_sec;
  413. if (secdiff+1 > LONG_MAX/1000000) {
  414. log_fn(LOG_WARN, "comparing times too far apart.");
  415. return LONG_MAX;
  416. }
  417. udiff = secdiff*1000000L + (end->tv_usec - start->tv_usec);
  418. if(udiff < 0) {
  419. log_fn(LOG_INFO, "start (%ld.%ld) is after end (%ld.%ld). Returning 0.",
  420. (long)start->tv_sec, (long)start->tv_usec, (long)end->tv_sec, (long)end->tv_usec);
  421. return 0;
  422. }
  423. return udiff;
  424. }
  425. /** Return -1 if *a \< *b, 0 if *a==*b, and 1 if *a \> *b.
  426. */
  427. int tv_cmp(struct timeval *a, struct timeval *b) {
  428. if (a->tv_sec > b->tv_sec)
  429. return 1;
  430. if (a->tv_sec < b->tv_sec)
  431. return -1;
  432. if (a->tv_usec > b->tv_usec)
  433. return 1;
  434. if (a->tv_usec < b->tv_usec)
  435. return -1;
  436. return 0;
  437. }
  438. /** Increment *a by the number of seconds and microseconds in *b.
  439. */
  440. void tv_add(struct timeval *a, struct timeval *b) {
  441. a->tv_usec += b->tv_usec;
  442. a->tv_sec += b->tv_sec + (a->tv_usec / 1000000);
  443. a->tv_usec %= 1000000;
  444. }
  445. /** Increment *a by <b>ms</b> milliseconds.
  446. */
  447. void tv_addms(struct timeval *a, long ms) {
  448. a->tv_usec += (ms * 1000) % 1000000;
  449. a->tv_sec += ((ms * 1000) / 1000000) + (a->tv_usec / 1000000);
  450. a->tv_usec %= 1000000;
  451. }
  452. #define IS_LEAPYEAR(y) (!(y % 4) && ((y % 100) || !(y % 400)))
  453. static int n_leapdays(int y1, int y2) {
  454. --y1;
  455. --y2;
  456. return (y2/4 - y1/4) - (y2/100 - y1/100) + (y2/400 - y1/400);
  457. }
  458. /** Number of days per month in non-leap year; used by tor_timegm. */
  459. static const int days_per_month[] =
  460. { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
  461. /** Return a time_t given a struct tm. The result is given in GMT, and
  462. * does not account for leap seconds.
  463. */
  464. time_t tor_timegm (struct tm *tm) {
  465. /* This is a pretty ironclad timegm implementation, snarfed from Python2.2.
  466. * It's way more brute-force than fiddling with tzset().
  467. */
  468. time_t ret;
  469. unsigned long year, days, hours, minutes;
  470. int i;
  471. year = tm->tm_year + 1900;
  472. tor_assert(year >= 1970);
  473. tor_assert(tm->tm_mon >= 0);
  474. tor_assert(tm->tm_mon <= 11);
  475. days = 365 * (year-1970) + n_leapdays(1970,year);
  476. for (i = 0; i < tm->tm_mon; ++i)
  477. days += days_per_month[i];
  478. if (tm->tm_mon > 1 && IS_LEAPYEAR(year))
  479. ++days;
  480. days += tm->tm_mday - 1;
  481. hours = days*24 + tm->tm_hour;
  482. minutes = hours*60 + tm->tm_min;
  483. ret = minutes*60 + tm->tm_sec;
  484. return ret;
  485. }
  486. /* strftime is locale-specific, so we need to replace those parts */
  487. static const char *WEEKDAY_NAMES[] =
  488. { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  489. static const char *MONTH_NAMES[] =
  490. { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  491. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  492. void format_rfc1123_time(char *buf, time_t t) {
  493. struct tm *tm = gmtime(&t);
  494. strftime(buf, RFC1123_TIME_LEN+1, "XXX, %d XXX %Y %H:%M:%S GMT", tm);
  495. tor_assert(tm->tm_wday >= 0);
  496. tor_assert(tm->tm_wday <= 6);
  497. memcpy(buf, WEEKDAY_NAMES[tm->tm_wday], 3);
  498. tor_assert(tm->tm_wday >= 0);
  499. tor_assert(tm->tm_mon <= 11);
  500. memcpy(buf+8, MONTH_NAMES[tm->tm_mon], 3);
  501. }
  502. int parse_rfc1123_time(const char *buf, time_t *t) {
  503. struct tm tm;
  504. char month[4];
  505. char weekday[4];
  506. int i, m;
  507. if (strlen(buf) != RFC1123_TIME_LEN)
  508. return -1;
  509. memset(&tm, 0, sizeof(tm));
  510. if (sscanf(buf, "%3s, %d %3s %d %d:%d:%d GMT", weekday,
  511. &tm.tm_mday, month, &tm.tm_year, &tm.tm_hour,
  512. &tm.tm_min, &tm.tm_sec) < 7) {
  513. log_fn(LOG_WARN, "Got invalid RFC1123 time \"%s\"", buf);
  514. return -1;
  515. }
  516. m = -1;
  517. for (i = 0; i < 12; ++i) {
  518. if (!strcmp(month, MONTH_NAMES[i])) {
  519. m = i;
  520. break;
  521. }
  522. }
  523. if (m<0) {
  524. log_fn(LOG_WARN, "Got invalid RFC1123 time \"%s\"", buf);
  525. return -1;
  526. }
  527. tm.tm_mon = m;
  528. tm.tm_year -= 1900;
  529. *t = tor_timegm(&tm);
  530. return 0;
  531. }
  532. void format_iso_time(char *buf, time_t t) {
  533. strftime(buf, ISO_TIME_LEN+1, "%Y-%m-%d %H:%M:%S", gmtime(&t));
  534. }
  535. int parse_iso_time(const char *cp, time_t *t) {
  536. struct tm st_tm;
  537. #ifdef HAVE_STRPTIME
  538. if (!strptime(cp, "%Y-%m-%d %H:%M:%S", &st_tm)) {
  539. log_fn(LOG_WARN, "Published time was unparseable"); return -1;
  540. }
  541. #else
  542. unsigned int year=0, month=0, day=0, hour=100, minute=100, second=100;
  543. if (sscanf(cp, "%u-%u-%u %u:%u:%u", &year, &month,
  544. &day, &hour, &minute, &second) < 6) {
  545. log_fn(LOG_WARN, "Published time was unparseable"); return -1;
  546. }
  547. if (year < 1970 || month < 1 || month > 12 || day < 1 || day > 31 ||
  548. hour > 23 || minute > 59 || second > 61) {
  549. log_fn(LOG_WARN, "Published time was nonsensical"); return -1;
  550. }
  551. st_tm.tm_year = year;
  552. st_tm.tm_mon = month-1;
  553. st_tm.tm_mday = day;
  554. st_tm.tm_hour = hour;
  555. st_tm.tm_min = minute;
  556. st_tm.tm_sec = second;
  557. #endif
  558. *t = tor_timegm(&st_tm);
  559. return 0;
  560. }
  561. /* =====
  562. * File helpers
  563. * ===== */
  564. /** Write <b>count</b> bytes from <b>buf</b> to <b>fd</b>. <b>isSocket</b>
  565. * must be 1 if fd was returned by socket() or accept(), and 0 if fd
  566. * was returned by open(). Return the number of bytes written, or -1
  567. * on error. Only use if fd is a blocking fd. */
  568. int write_all(int fd, const char *buf, size_t count, int isSocket) {
  569. size_t written = 0;
  570. int result;
  571. while(written != count) {
  572. if (isSocket)
  573. result = send(fd, buf+written, count-written, 0);
  574. else
  575. result = write(fd, buf+written, count-written);
  576. if(result<0)
  577. return -1;
  578. written += result;
  579. }
  580. return count;
  581. }
  582. /** Read from <b>fd</b> to <b>buf</b>, until we get <b>count</b> bytes
  583. * or reach the end of the file.
  584. * isSocket must be 1 if fd
  585. * was returned by socket() or accept(), and 0 if fd was returned by
  586. * open(). Return the number of bytes read, or -1 on error. Only use
  587. * if fd is a blocking fd. */
  588. int read_all(int fd, char *buf, size_t count, int isSocket) {
  589. size_t numread = 0;
  590. int result;
  591. while(numread != count) {
  592. if (isSocket)
  593. result = recv(fd, buf+numread, count-numread, 0);
  594. else
  595. result = read(fd, buf+numread, count-numread);
  596. if(result<0)
  597. return -1;
  598. else if (result == 0)
  599. break;
  600. numread += result;
  601. }
  602. return count;
  603. }
  604. /*
  605. * Filesystem operations.
  606. */
  607. /** Return FN_ERROR if filename can't be read, FN_NOENT if it doesn't
  608. * exist, FN_FILE if it is a regular file, or FN_DIR if it's a
  609. * directory. */
  610. file_status_t file_status(const char *fname)
  611. {
  612. struct stat st;
  613. if (stat(fname, &st)) {
  614. if (errno == ENOENT) {
  615. return FN_NOENT;
  616. }
  617. return FN_ERROR;
  618. }
  619. if (st.st_mode & S_IFDIR)
  620. return FN_DIR;
  621. else if (st.st_mode & S_IFREG)
  622. return FN_FILE;
  623. else
  624. return FN_ERROR;
  625. }
  626. /** Check whether dirname exists and is private. If yes return 0. If
  627. * it does not exist, and check==CPD_CREATE is set, try to create it
  628. * and return 0 on success. If it does not exist, and
  629. * check==CPD_CHECK, and we think we can create it, return 0. Else
  630. * return -1. */
  631. int check_private_dir(const char *dirname, cpd_check_t check)
  632. {
  633. int r;
  634. struct stat st;
  635. tor_assert(dirname);
  636. if (stat(dirname, &st)) {
  637. if (errno != ENOENT) {
  638. log(LOG_WARN, "Directory %s cannot be read: %s", dirname,
  639. strerror(errno));
  640. return -1;
  641. }
  642. if (check == CPD_NONE) {
  643. log(LOG_WARN, "Directory %s does not exist.", dirname);
  644. return -1;
  645. } else if (check == CPD_CREATE) {
  646. log(LOG_INFO, "Creating directory %s", dirname);
  647. #ifdef MS_WINDOWS
  648. r = mkdir(dirname);
  649. #else
  650. r = mkdir(dirname, 0700);
  651. #endif
  652. if (r) {
  653. log(LOG_WARN, "Error creating directory %s: %s", dirname,
  654. strerror(errno));
  655. return -1;
  656. }
  657. }
  658. /* XXXX In the case where check==CPD_CHECK, we should look at the
  659. * parent directory a little harder. */
  660. return 0;
  661. }
  662. if (!(st.st_mode & S_IFDIR)) {
  663. log(LOG_WARN, "%s is not a directory", dirname);
  664. return -1;
  665. }
  666. #ifndef MS_WINDOWS
  667. if (st.st_uid != getuid()) {
  668. log(LOG_WARN, "%s is not owned by this UID (%d). You must fix this to proceed.", dirname, (int)getuid());
  669. return -1;
  670. }
  671. if (st.st_mode & 0077) {
  672. log(LOG_WARN, "Fixing permissions on directory %s", dirname);
  673. if (chmod(dirname, 0700)) {
  674. log(LOG_WARN, "Could not chmod directory %s: %s", dirname,
  675. strerror(errno));
  676. return -1;
  677. } else {
  678. return 0;
  679. }
  680. }
  681. #endif
  682. return 0;
  683. }
  684. /** Create a file named <b>fname</b> with the contents <b>str</b>. Overwrite the
  685. * previous <b>fname</b> if possible. Return 0 on success, -1 on failure.
  686. *
  687. * This function replaces the old file atomically, if possible.
  688. */
  689. int
  690. write_str_to_file(const char *fname, const char *str, int bin)
  691. {
  692. return write_bytes_to_file(fname, str, strlen(str), bin);
  693. }
  694. /* DOCDOC */
  695. int write_bytes_to_file(const char *fname, const char *str, size_t len,
  696. int bin)
  697. {
  698. char tempname[1024];
  699. int fd;
  700. int result;
  701. if ((strlcpy(tempname,fname,1024) >= 1024) ||
  702. (strlcat(tempname,".tmp",1024) >= 1024)) {
  703. log(LOG_WARN, "Filename %s.tmp too long (>1024 chars)", fname);
  704. return -1;
  705. }
  706. if ((fd = open(tempname, O_WRONLY|O_CREAT|O_TRUNC|(bin?O_BINARY:0), 0600))
  707. < 0) {
  708. log(LOG_WARN, "Couldn't open %s for writing: %s", tempname,
  709. strerror(errno));
  710. return -1;
  711. }
  712. result = write_all(fd, str, len, 0);
  713. if(result < 0 || (size_t)result != len) {
  714. log(LOG_WARN, "Error writing to %s: %s", tempname, strerror(errno));
  715. close(fd);
  716. return -1;
  717. }
  718. if (close(fd)) {
  719. log(LOG_WARN,"Error flushing to %s: %s", tempname, strerror(errno));
  720. return -1;
  721. }
  722. /* XXXX use replace_file() instead. */
  723. #ifdef MS_WINDOWS
  724. /* On Windows, rename doesn't replace. We could call ReplaceFile, but
  725. * that's hard, and we can probably sneak by without atomicity. */
  726. switch (file_status(fname)) {
  727. case FN_ERROR:
  728. log(LOG_WARN, "Error replacing %s: %s", fname, strerror(errno));
  729. return -1;
  730. case FN_DIR:
  731. log(LOG_WARN, "Error replacing %s: is directory", fname);
  732. return -1;
  733. case FN_FILE:
  734. if (unlink(fname)) {
  735. log(LOG_WARN, "Error replacing %s while removing old copy: %s",
  736. fname, strerror(errno));
  737. return -1;
  738. }
  739. break;
  740. case FN_NOENT:
  741. ;
  742. }
  743. #endif
  744. if (rename(tempname, fname)) {
  745. log(LOG_WARN, "Error replacing %s: %s", fname, strerror(errno));
  746. return -1;
  747. }
  748. return 0;
  749. }
  750. /** Read the contents of <b>filename</b> into a newly allocated string; return the
  751. * string on success or NULL on failure.
  752. */
  753. char *read_file_to_str(const char *filename, int bin) {
  754. int fd; /* router file */
  755. struct stat statbuf;
  756. char *string;
  757. int r;
  758. tor_assert(filename);
  759. if(stat(filename, &statbuf) < 0) {
  760. log_fn(LOG_INFO,"Could not stat %s.",filename);
  761. return NULL;
  762. }
  763. fd = open(filename,O_RDONLY|(bin?O_BINARY:0),0);
  764. if (fd<0) {
  765. log_fn(LOG_WARN,"Could not open %s.",filename);
  766. return NULL;
  767. }
  768. string = tor_malloc(statbuf.st_size+1);
  769. r = read_all(fd,string,statbuf.st_size,0);
  770. if (r<0) {
  771. log_fn(LOG_WARN,"Error reading from file '%s': %s", filename,
  772. strerror(errno));
  773. tor_free(string);
  774. close(fd);
  775. return NULL;
  776. } else if (bin && r != statbuf.st_size) {
  777. /* If we're in binary mode, then we'd better have an exact match for
  778. * size. Otherwise, win32 encoding may throw us off, and that's okay. */
  779. log_fn(LOG_WARN,"Could read only %d of %ld bytes of file '%s'.",
  780. r, (long)statbuf.st_size,filename);
  781. tor_free(string);
  782. close(fd);
  783. return NULL;
  784. }
  785. close(fd);
  786. string[statbuf.st_size] = 0; /* null terminate it */
  787. return string;
  788. }
  789. /** DOCDOC.
  790. *
  791. * Return next line or end of string on success, NULL on failure.
  792. */
  793. char *
  794. parse_line_from_str(char *line, char **key_out, char **value_out)
  795. {
  796. char *key, *val, *cp;
  797. tor_assert(key_out);
  798. tor_assert(value_out);
  799. *key_out = *value_out = key = val = NULL;
  800. /* Skip until the first keyword. */
  801. while (1) {
  802. while (isspace(*line))
  803. ++line;
  804. if (*line == '#') {
  805. while (*line && *line != '\n')
  806. ++line;
  807. } else {
  808. break;
  809. }
  810. }
  811. if (!*line) { /* End of string? */
  812. *key_out = *value_out = NULL;
  813. return line;
  814. }
  815. /* Skip until the next space. */
  816. key = line;
  817. while (*line && !isspace(*line) && *line != '#')
  818. ++line;
  819. /* Skip until the value */
  820. while (*line == ' ' || *line == '\t')
  821. *line++ = '\0';
  822. val = line;
  823. /* Find the end of the line. */
  824. while (*line && *line != '\n' && *line != '#')
  825. ++line;
  826. if (*line == '\n')
  827. cp = line++;
  828. else {
  829. cp = line-1;
  830. }
  831. while (cp>=val && isspace(*cp))
  832. *cp-- = '\0';
  833. if (*line == '#') {
  834. do {
  835. *line++ = '\0';
  836. } while (*line && *line != '\n');
  837. if (*line == '\n')
  838. ++line;
  839. }
  840. *key_out = key;
  841. *value_out = val;
  842. return line;
  843. }
  844. /** Expand any homedir prefix on 'filename'; return a newly allocated
  845. * string. */
  846. char *expand_filename(const char *filename)
  847. {
  848. tor_assert(filename);
  849. /* XXXX Should eventually check for ~username/ */
  850. if (!strncmp(filename,"~/",2)) {
  851. size_t len;
  852. const char *home = getenv("HOME");
  853. char *result;
  854. if (!home) {
  855. log_fn(LOG_WARN, "Couldn't find $HOME environment variable while expanding %s", filename);
  856. return NULL;
  857. }
  858. /* minus two characters for ~/, plus one for /, plus one for NUL.
  859. * Round up to 16 in case we can't do math. */
  860. len = strlen(home)+strlen(filename)+16;
  861. result = tor_malloc(len);
  862. tor_snprintf(result,len,"%s/%s",home,filename+2);
  863. return result;
  864. } else {
  865. return tor_strdup(filename);
  866. }
  867. }
  868. /* =====
  869. * Net helpers
  870. * ===== */
  871. /** Return true iff <b>ip</b> (in host order) is an IP reserved to localhost,
  872. * or reserved for local networks by RFC 1918.
  873. */
  874. int is_internal_IP(uint32_t ip) {
  875. if (((ip & 0xff000000) == 0x0a000000) || /* 10/8 */
  876. ((ip & 0xff000000) == 0x00000000) || /* 0/8 */
  877. ((ip & 0xff000000) == 0x7f000000) || /* 127/8 */
  878. ((ip & 0xffff0000) == 0xa9fe0000) || /* 169.254/16 */
  879. ((ip & 0xfff00000) == 0xac100000) || /* 172.16/12 */
  880. ((ip & 0xffff0000) == 0xc0a80000)) /* 192.168/16 */
  881. return 1;
  882. return 0;
  883. }
  884. /** Return true iff <b>ip</b> (in host order) is judged to be on the
  885. * same network as us. For now, check if it's an internal IP. For XXX008,
  886. * also check if it's on the same class C network as our public IP.
  887. */
  888. int is_local_IP(uint32_t ip) {
  889. return is_internal_IP(ip);
  890. }
  891. /** Similar behavior to Unix gethostbyname: resolve <b>name</b>, and set
  892. * *addr to the proper IP address, in network byte order. Returns 0
  893. * on success, -1 on failure; 1 on transient failure.
  894. *
  895. * (This function exists because standard windows gethostbyname
  896. * doesn't treat raw IP addresses properly.)
  897. */
  898. int tor_lookup_hostname(const char *name, uint32_t *addr)
  899. {
  900. /* Perhaps eventually this should be replaced by a tor_getaddrinfo or
  901. * something.
  902. */
  903. struct in_addr iaddr;
  904. struct hostent *ent;
  905. tor_assert(addr);
  906. if (!*name) {
  907. /* Empty address is an error. */
  908. return -1;
  909. } else if (tor_inet_aton(name, &iaddr)) {
  910. /* It's an IP. */
  911. memcpy(addr, &iaddr.s_addr, 4);
  912. return 0;
  913. } else {
  914. ent = gethostbyname(name);
  915. if (ent) {
  916. /* break to remind us if we move away from IPv4 */
  917. tor_assert(ent->h_length == 4);
  918. memcpy(addr, ent->h_addr, 4);
  919. return 0;
  920. }
  921. memset(addr, 0, 4);
  922. #ifdef MS_WINDOWS
  923. return (WSAGetLastError() == WSATRY_AGAIN) ? 1 : -1;
  924. #else
  925. return (h_errno == TRY_AGAIN) ? 1 : -1;
  926. #endif
  927. }
  928. }
  929. /** Parse a string of the form "host[:port]" from <b>addrport</b>. If
  930. * <b>address</b> is provided, set *<b>address</b> to a copy of the
  931. * host portion of the string. If <b>addr</b> is provided, try to
  932. * resolve the host portion of the string and store it into
  933. * *<b>addr</b> (in host byte order). If <b>port</b> is provided,
  934. * store the port number into *<b>port</b>, or 0 if no port is given.
  935. * Return 0 on success, -1 on failure.
  936. */
  937. int
  938. parse_addr_port(const char *addrport, char **address, uint32_t *addr,
  939. uint16_t *port)
  940. {
  941. const char *colon;
  942. char *_address = NULL;
  943. int _port;
  944. int ok = 1;
  945. tor_assert(addrport);
  946. tor_assert(port);
  947. colon = strchr(addrport, ':');
  948. if (colon) {
  949. _address = tor_strndup(addrport, colon-addrport);
  950. _port = (int) tor_parse_long(colon+1,10,1,65535,NULL,NULL);
  951. if (!_port) {
  952. log_fn(LOG_WARN, "Port '%s' out of range", colon+1);
  953. ok = 0;
  954. }
  955. } else {
  956. _address = tor_strdup(addrport);
  957. _port = 0;
  958. }
  959. if (addr) {
  960. /* There's an addr pointer, so we need to resolve the hostname. */
  961. if (tor_lookup_hostname(_address,addr)) {
  962. log_fn(LOG_WARN, "Couldn't look up '%s'", _address);
  963. ok = 0;
  964. *addr = 0;
  965. }
  966. *addr = ntohl(*addr);
  967. }
  968. if (address && ok) {
  969. *address = _address;
  970. } else {
  971. if (address)
  972. *address = NULL;
  973. tor_free(_address);
  974. }
  975. if (port)
  976. *port = ok ? ((uint16_t) _port) : 0;
  977. return ok ? 0 : -1;
  978. }
  979. /** Parse a string <b>s</b> in the format of
  980. * (IP(/mask|/mask-bits)?|*):(*|port(-maxport)?), setting the various
  981. * *out pointers as appropriate. Return 0 on success, -1 on failure.
  982. */
  983. int
  984. parse_addr_and_port_range(const char *s, uint32_t *addr_out,
  985. uint32_t *mask_out, uint16_t *port_min_out,
  986. uint16_t *port_max_out)
  987. {
  988. char *address;
  989. char *mask, *port, *endptr;
  990. struct in_addr in;
  991. int bits;
  992. tor_assert(s);
  993. tor_assert(addr_out);
  994. tor_assert(mask_out);
  995. tor_assert(port_min_out);
  996. tor_assert(port_max_out);
  997. address = tor_strdup(s);
  998. /* Break 'address' into separate strings.
  999. */
  1000. mask = strchr(address,'/');
  1001. port = strchr(mask?mask:address,':');
  1002. if (mask)
  1003. *mask++ = '\0';
  1004. if (port)
  1005. *port++ = '\0';
  1006. /* Now "address" is the IP|'*' part...
  1007. * "mask" is the Mask|Maskbits part...
  1008. * and "port" is the *|port|min-max part.
  1009. */
  1010. if (strcmp(address,"*")==0) {
  1011. *addr_out = 0;
  1012. } else if (tor_inet_aton(address, &in) != 0) {
  1013. *addr_out = ntohl(in.s_addr);
  1014. } else {
  1015. log_fn(LOG_WARN, "Malformed IP %s in address pattern; rejecting.",address);
  1016. goto err;
  1017. }
  1018. if (!mask) {
  1019. if (strcmp(address,"*")==0)
  1020. *mask_out = 0;
  1021. else
  1022. *mask_out = 0xFFFFFFFFu;
  1023. } else {
  1024. endptr = NULL;
  1025. bits = (int) strtol(mask, &endptr, 10);
  1026. if (!*endptr) {
  1027. /* strtol handled the whole mask. */
  1028. if (bits < 0 || bits > 32) {
  1029. log_fn(LOG_WARN, "Bad number of mask bits on address range; rejecting.");
  1030. goto err;
  1031. }
  1032. *mask_out = ~((1<<(32-bits))-1);
  1033. } else if (tor_inet_aton(mask, &in) != 0) {
  1034. *mask_out = ntohl(in.s_addr);
  1035. } else {
  1036. log_fn(LOG_WARN, "Malformed mask %s on address range; rejecting.",
  1037. mask);
  1038. goto err;
  1039. }
  1040. }
  1041. if (!port || strcmp(port, "*") == 0) {
  1042. *port_min_out = 1;
  1043. *port_max_out = 65535;
  1044. } else {
  1045. endptr = NULL;
  1046. *port_min_out = (uint16_t) tor_parse_long(port, 10, 1, 65535,
  1047. NULL, &endptr);
  1048. if (*endptr == '-') {
  1049. port = endptr+1;
  1050. endptr = NULL;
  1051. *port_max_out = (uint16_t) tor_parse_long(port, 10, 1, 65535, NULL,
  1052. &endptr);
  1053. if (*endptr || !*port_max_out) {
  1054. log_fn(LOG_WARN, "Malformed port %s on address range rejecting.",
  1055. port);
  1056. }
  1057. } else if (*endptr || !*port_min_out) {
  1058. log_fn(LOG_WARN, "Malformed port %s on address range; rejecting.",
  1059. port);
  1060. goto err;
  1061. } else {
  1062. *port_max_out = *port_min_out;
  1063. }
  1064. if (*port_min_out > *port_max_out) {
  1065. log_fn(LOG_WARN,"Insane port range on address policy; rejecting.");
  1066. goto err;
  1067. }
  1068. }
  1069. tor_free(address);
  1070. return 0;
  1071. err:
  1072. tor_free(address);
  1073. return -1;
  1074. }
  1075. /* =====
  1076. * Process helpers
  1077. * ===== */
  1078. #ifndef MS_WINDOWS
  1079. /* Based on code contributed by christian grothoff */
  1080. static int start_daemon_called = 0;
  1081. static int finish_daemon_called = 0;
  1082. static int daemon_filedes[2];
  1083. /** Start putting the process into daemon mode: fork and drop all resources
  1084. * except standard fds. The parent process never returns, but stays around
  1085. * until finish_daemon is called. (Note: it's safe to call this more
  1086. * than once: calls after the first are ignored.)
  1087. */
  1088. void start_daemon(const char *desired_cwd)
  1089. {
  1090. pid_t pid;
  1091. if (start_daemon_called)
  1092. return;
  1093. start_daemon_called = 1;
  1094. if(!desired_cwd)
  1095. desired_cwd = "/";
  1096. /* Don't hold the wrong FS mounted */
  1097. if (chdir(desired_cwd) < 0) {
  1098. log_fn(LOG_ERR,"chdir to %s failed. Exiting.",desired_cwd);
  1099. exit(1);
  1100. }
  1101. pipe(daemon_filedes);
  1102. pid = fork();
  1103. if (pid < 0) {
  1104. log_fn(LOG_ERR,"fork failed. Exiting.");
  1105. exit(1);
  1106. }
  1107. if (pid) { /* Parent */
  1108. int ok;
  1109. char c;
  1110. close(daemon_filedes[1]); /* we only read */
  1111. ok = -1;
  1112. while (0 < read(daemon_filedes[0], &c, sizeof(char))) {
  1113. if (c == '.')
  1114. ok = 1;
  1115. }
  1116. fflush(stdout);
  1117. if (ok == 1)
  1118. exit(0);
  1119. else
  1120. exit(1); /* child reported error */
  1121. } else { /* Child */
  1122. close(daemon_filedes[0]); /* we only write */
  1123. pid = setsid(); /* Detach from controlling terminal */
  1124. /*
  1125. * Fork one more time, so the parent (the session group leader) can exit.
  1126. * This means that we, as a non-session group leader, can never regain a
  1127. * controlling terminal. This part is recommended by Stevens's
  1128. * _Advanced Programming in the Unix Environment_.
  1129. */
  1130. if (fork() != 0) {
  1131. exit(0);
  1132. }
  1133. return;
  1134. }
  1135. }
  1136. /** Finish putting the process into daemon mode: drop standard fds, and tell
  1137. * the parent process to exit. (Note: it's safe to call this more than once:
  1138. * calls after the first are ignored. Calls start_daemon first if it hasn't
  1139. * been called already.)
  1140. */
  1141. void finish_daemon(void)
  1142. {
  1143. int nullfd;
  1144. char c = '.';
  1145. if (finish_daemon_called)
  1146. return;
  1147. if (!start_daemon_called)
  1148. start_daemon(NULL);
  1149. finish_daemon_called = 1;
  1150. nullfd = open("/dev/null",
  1151. O_CREAT | O_RDWR | O_APPEND);
  1152. if (nullfd < 0) {
  1153. log_fn(LOG_ERR,"/dev/null can't be opened. Exiting.");
  1154. exit(1);
  1155. }
  1156. /* close fds linking to invoking terminal, but
  1157. * close usual incoming fds, but redirect them somewhere
  1158. * useful so the fds don't get reallocated elsewhere.
  1159. */
  1160. if (dup2(nullfd,0) < 0 ||
  1161. dup2(nullfd,1) < 0 ||
  1162. dup2(nullfd,2) < 0) {
  1163. log_fn(LOG_ERR,"dup2 failed. Exiting.");
  1164. exit(1);
  1165. }
  1166. write(daemon_filedes[1], &c, sizeof(char)); /* signal success */
  1167. close(daemon_filedes[1]);
  1168. }
  1169. #else
  1170. /* defined(MS_WINDOWS) */
  1171. void start_daemon(const char *cp) {}
  1172. void finish_daemon(void) {}
  1173. #endif
  1174. /** Write the current process ID, followed by NL, into <b>filename</b>.
  1175. */
  1176. void write_pidfile(char *filename) {
  1177. #ifndef MS_WINDOWS
  1178. FILE *pidfile;
  1179. if ((pidfile = fopen(filename, "w")) == NULL) {
  1180. log_fn(LOG_WARN, "Unable to open %s for writing: %s", filename,
  1181. strerror(errno));
  1182. } else {
  1183. fprintf(pidfile, "%d\n", (int)getpid());
  1184. fclose(pidfile);
  1185. }
  1186. #endif
  1187. }
  1188. /*
  1189. Local Variables:
  1190. mode:c
  1191. indent-tabs-mode:nil
  1192. c-basic-offset:2
  1193. End:
  1194. */