util.c 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306
  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. /* XXXX probably some of these are unneeded. find out which. */
  15. #ifdef MS_WINDOWS
  16. #include <io.h>
  17. #include <process.h>
  18. #include <direct.h>
  19. #include <windows.h>
  20. #endif
  21. #ifdef HAVE_CTYPE_H
  22. #include <ctype.h>
  23. #endif
  24. #include <stdlib.h>
  25. #include <stdio.h>
  26. #include <string.h>
  27. #include <assert.h>
  28. #include "util.h"
  29. #include "log.h"
  30. #include "crypto.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. /** Extract a long from the start of s, in the given numeric base. If
  295. * there is unconverted data and next is provided, set *next to the
  296. * first unconverted character. An error has occurred if no characters
  297. * are converted; or if there are unconverted characters and next is NULL; or
  298. * if the parsed value is not between min and max. When no error occurs,
  299. * return the parsed value and set *ok (if provided) to 1. When an error
  300. * ocurs, return 0 and set *ok (if provided) to 0.
  301. */
  302. long
  303. tor_parse_long(const char *s, int base, long min, long max,
  304. int *ok, char **next)
  305. {
  306. char *endptr;
  307. long r;
  308. r = strtol(s, &endptr, base);
  309. /* Was at least one character converted? */
  310. if (endptr == s)
  311. goto err;
  312. /* Were there unexpected unconverted characters? */
  313. if (!next && *endptr)
  314. goto err;
  315. /* Is r within limits? */
  316. if (r < min || r > max)
  317. goto err;
  318. if (ok) *ok = 1;
  319. if (next) *next = endptr;
  320. return r;
  321. err:
  322. if (ok) *ok = 0;
  323. if (next) *next = endptr;
  324. return 0;
  325. }
  326. #if 0
  327. unsigned long
  328. tor_parse_ulong(const char *s, int base, unsigned long min,
  329. unsigned long max, int *ok, char **next)
  330. {
  331. char *endptr;
  332. unsigned long r;
  333. r = strtol(s, &endptr, base);
  334. /* Was at least one character converted? */
  335. if (endptr == s)
  336. goto err;
  337. /* Were there unexpected unconverted characters? */
  338. if (!next && *endptr)
  339. goto err;
  340. /* Is r within limits? */
  341. if (r < min || r > max)
  342. goto err;
  343. if (ok) *ok = 1;
  344. if (next) *next = endptr;
  345. return r;
  346. err:
  347. if (ok) *ok = 0;
  348. if (next) *next = endptr;
  349. return 0;
  350. }
  351. #endif
  352. void base16_encode(char *dest, size_t destlen, const char *src, size_t srclen)
  353. {
  354. const char *end;
  355. char *cp;
  356. tor_assert(destlen >= srclen*2+1);
  357. cp = dest;
  358. end = src+srclen;
  359. while (src<end) {
  360. sprintf(cp,"%02X",*(const uint8_t*)src);
  361. ++src;
  362. cp += 2;
  363. }
  364. *cp = '\0';
  365. }
  366. static const char HEX_DIGITS[] = "0123456789ABCDEFabcdef";
  367. static INLINE int hex_decode_digit(char c)
  368. {
  369. const char *cp;
  370. int n;
  371. cp = strchr(HEX_DIGITS, c);
  372. if (!cp)
  373. return -1;
  374. n = cp-HEX_DIGITS;
  375. if (n<=15)
  376. return n; /* digit or uppercase */
  377. else
  378. return n-6; /* lowercase */
  379. }
  380. int base16_decode(char *dest, size_t destlen, const char *src, size_t srclen)
  381. {
  382. const char *end;
  383. int v1,v2;
  384. if ((srclen % 2) != 0)
  385. return -1;
  386. if (destlen < srclen/2)
  387. return -1;
  388. end = src+srclen;
  389. while (src<end) {
  390. v1 = hex_decode_digit(*src);
  391. v2 = hex_decode_digit(*(src+1));
  392. if(v1<0||v2<0)
  393. return -1;
  394. *(uint8_t*)dest = (v1<<4)|v2;
  395. ++dest;
  396. src+=2;
  397. }
  398. return 0;
  399. }
  400. /* =====
  401. * Time
  402. * ===== */
  403. /** Return the number of microseconds elapsed between *start and *end.
  404. * If start is after end, return 0.
  405. */
  406. long
  407. tv_udiff(struct timeval *start, struct timeval *end)
  408. {
  409. long udiff;
  410. long secdiff = end->tv_sec - start->tv_sec;
  411. if (secdiff+1 > LONG_MAX/1000000) {
  412. log_fn(LOG_WARN, "comparing times too far apart.");
  413. return LONG_MAX;
  414. }
  415. udiff = secdiff*1000000L + (end->tv_usec - start->tv_usec);
  416. if(udiff < 0) {
  417. log_fn(LOG_INFO, "start (%ld.%ld) is after end (%ld.%ld). Returning 0.",
  418. (long)start->tv_sec, (long)start->tv_usec, (long)end->tv_sec, (long)end->tv_usec);
  419. return 0;
  420. }
  421. return udiff;
  422. }
  423. /** Return -1 if *a \< *b, 0 if *a==*b, and 1 if *a \> *b.
  424. */
  425. int tv_cmp(struct timeval *a, struct timeval *b) {
  426. if (a->tv_sec > b->tv_sec)
  427. return 1;
  428. if (a->tv_sec < b->tv_sec)
  429. return -1;
  430. if (a->tv_usec > b->tv_usec)
  431. return 1;
  432. if (a->tv_usec < b->tv_usec)
  433. return -1;
  434. return 0;
  435. }
  436. /** Increment *a by the number of seconds and microseconds in *b.
  437. */
  438. void tv_add(struct timeval *a, struct timeval *b) {
  439. a->tv_usec += b->tv_usec;
  440. a->tv_sec += b->tv_sec + (a->tv_usec / 1000000);
  441. a->tv_usec %= 1000000;
  442. }
  443. /** Increment *a by <b>ms</b> milliseconds.
  444. */
  445. void tv_addms(struct timeval *a, long ms) {
  446. a->tv_usec += (ms * 1000) % 1000000;
  447. a->tv_sec += ((ms * 1000) / 1000000) + (a->tv_usec / 1000000);
  448. a->tv_usec %= 1000000;
  449. }
  450. #define IS_LEAPYEAR(y) (!(y % 4) && ((y % 100) || !(y % 400)))
  451. static int n_leapdays(int y1, int y2) {
  452. --y1;
  453. --y2;
  454. return (y2/4 - y1/4) - (y2/100 - y1/100) + (y2/400 - y1/400);
  455. }
  456. /** Number of days per month in non-leap year; used by tor_timegm. */
  457. static const int days_per_month[] =
  458. { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
  459. /** Return a time_t given a struct tm. The result is given in GMT, and
  460. * does not account for leap seconds.
  461. */
  462. time_t tor_timegm (struct tm *tm) {
  463. /* This is a pretty ironclad timegm implementation, snarfed from Python2.2.
  464. * It's way more brute-force than fiddling with tzset().
  465. */
  466. time_t ret;
  467. unsigned long year, days, hours, minutes;
  468. int i;
  469. year = tm->tm_year + 1900;
  470. tor_assert(year >= 1970);
  471. tor_assert(tm->tm_mon >= 0);
  472. tor_assert(tm->tm_mon <= 11);
  473. days = 365 * (year-1970) + n_leapdays(1970,year);
  474. for (i = 0; i < tm->tm_mon; ++i)
  475. days += days_per_month[i];
  476. if (tm->tm_mon > 1 && IS_LEAPYEAR(year))
  477. ++days;
  478. days += tm->tm_mday - 1;
  479. hours = days*24 + tm->tm_hour;
  480. minutes = hours*60 + tm->tm_min;
  481. ret = minutes*60 + tm->tm_sec;
  482. return ret;
  483. }
  484. /* strftime is locale-specific, so we need to replace those parts */
  485. static const char *WEEKDAY_NAMES[] =
  486. { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  487. static const char *MONTH_NAMES[] =
  488. { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  489. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  490. void format_rfc1123_time(char *buf, time_t t) {
  491. struct tm *tm = gmtime(&t);
  492. strftime(buf, RFC1123_TIME_LEN+1, "XXX, %d XXX %Y %H:%M:%S GMT", tm);
  493. tor_assert(tm->tm_wday >= 0);
  494. tor_assert(tm->tm_wday <= 6);
  495. memcpy(buf, WEEKDAY_NAMES[tm->tm_wday], 3);
  496. tor_assert(tm->tm_wday >= 0);
  497. tor_assert(tm->tm_mon <= 11);
  498. memcpy(buf+8, MONTH_NAMES[tm->tm_mon], 3);
  499. }
  500. int parse_rfc1123_time(const char *buf, time_t *t) {
  501. struct tm tm;
  502. char month[4];
  503. char weekday[4];
  504. int i, m;
  505. if (strlen(buf) != RFC1123_TIME_LEN)
  506. return -1;
  507. memset(&tm, 0, sizeof(tm));
  508. if (sscanf(buf, "%3s, %d %3s %d %d:%d:%d GMT", weekday,
  509. &tm.tm_mday, month, &tm.tm_year, &tm.tm_hour,
  510. &tm.tm_min, &tm.tm_sec) < 7) {
  511. log_fn(LOG_WARN, "Got invalid RFC1123 time \"%s\"", buf);
  512. return -1;
  513. }
  514. m = -1;
  515. for (i = 0; i < 12; ++i) {
  516. if (!strcmp(month, MONTH_NAMES[i])) {
  517. m = i;
  518. break;
  519. }
  520. }
  521. if (m<0) {
  522. log_fn(LOG_WARN, "Got invalid RFC1123 time \"%s\"", buf);
  523. return -1;
  524. }
  525. tm.tm_mon = m;
  526. tm.tm_year -= 1900;
  527. *t = tor_timegm(&tm);
  528. return 0;
  529. }
  530. void format_iso_time(char *buf, time_t t) {
  531. strftime(buf, ISO_TIME_LEN+1, "%Y-%m-%d %H:%M:%S", gmtime(&t));
  532. }
  533. int parse_iso_time(const char *cp, time_t *t) {
  534. struct tm st_tm;
  535. #ifdef HAVE_STRPTIME
  536. if (!strptime(cp, "%Y-%m-%d %H:%M:%S", &st_tm)) {
  537. log_fn(LOG_WARN, "Published time was unparseable"); return -1;
  538. }
  539. #else
  540. unsigned int year=0, month=0, day=0, hour=100, minute=100, second=100;
  541. if (sscanf(cp, "%u-%u-%u %u:%u:%u", &year, &month,
  542. &day, &hour, &minute, &second) < 6) {
  543. log_fn(LOG_WARN, "Published time was unparseable"); return -1;
  544. }
  545. if (year < 1970 || month < 1 || month > 12 || day < 1 || day > 31 ||
  546. hour > 23 || minute > 59 || second > 61) {
  547. log_fn(LOG_WARN, "Published time was nonsensical"); return -1;
  548. }
  549. st_tm.tm_year = year;
  550. st_tm.tm_mon = month-1;
  551. st_tm.tm_mday = day;
  552. st_tm.tm_hour = hour;
  553. st_tm.tm_min = minute;
  554. st_tm.tm_sec = second;
  555. #endif
  556. *t = tor_timegm(&st_tm);
  557. return 0;
  558. }
  559. /* =====
  560. * File helpers
  561. * ===== */
  562. /** Write <b>count</b> bytes from <b>buf</b> to <b>fd</b>. <b>isSocket</b>
  563. * must be 1 if fd was returned by socket() or accept(), and 0 if fd
  564. * was returned by open(). Return the number of bytes written, or -1
  565. * on error. Only use if fd is a blocking fd. */
  566. int write_all(int fd, const char *buf, size_t count, int isSocket) {
  567. size_t written = 0;
  568. int result;
  569. while(written != count) {
  570. if (isSocket)
  571. result = send(fd, buf+written, count-written, 0);
  572. else
  573. result = write(fd, buf+written, count-written);
  574. if(result<0)
  575. return -1;
  576. written += result;
  577. }
  578. return count;
  579. }
  580. /** Read from <b>fd</b> to <b>buf</b>, until we get <b>count</b> bytes
  581. * or reach the end of the file.
  582. * isSocket must be 1 if fd
  583. * was returned by socket() or accept(), and 0 if fd was returned by
  584. * open(). Return the number of bytes read, or -1 on error. Only use
  585. * if fd is a blocking fd. */
  586. int read_all(int fd, char *buf, size_t count, int isSocket) {
  587. size_t numread = 0;
  588. int result;
  589. while(numread != count) {
  590. if (isSocket)
  591. result = recv(fd, buf+numread, count-numread, 0);
  592. else
  593. result = read(fd, buf+numread, count-numread);
  594. if(result<0)
  595. return -1;
  596. else if (result == 0)
  597. break;
  598. numread += result;
  599. }
  600. return count;
  601. }
  602. /*
  603. * Filesystem operations.
  604. */
  605. /** Return FN_ERROR if filename can't be read, FN_NOENT if it doesn't
  606. * exist, FN_FILE if it is a regular file, or FN_DIR if it's a
  607. * directory. */
  608. file_status_t file_status(const char *fname)
  609. {
  610. struct stat st;
  611. if (stat(fname, &st)) {
  612. if (errno == ENOENT) {
  613. return FN_NOENT;
  614. }
  615. return FN_ERROR;
  616. }
  617. if (st.st_mode & S_IFDIR)
  618. return FN_DIR;
  619. else if (st.st_mode & S_IFREG)
  620. return FN_FILE;
  621. else
  622. return FN_ERROR;
  623. }
  624. /** Check whether dirname exists and is private. If yes return 0. If
  625. * it does not exist, and create is set, try to create it and return 0
  626. * on success. Else return -1. */
  627. int check_private_dir(const char *dirname, int create)
  628. {
  629. int r;
  630. struct stat st;
  631. tor_assert(dirname);
  632. if (stat(dirname, &st)) {
  633. if (errno != ENOENT) {
  634. log(LOG_WARN, "Directory %s cannot be read: %s", dirname,
  635. strerror(errno));
  636. return -1;
  637. }
  638. if (!create) {
  639. log(LOG_WARN, "Directory %s does not exist.", dirname);
  640. return -1;
  641. }
  642. log(LOG_INFO, "Creating directory %s", dirname);
  643. #ifdef MS_WINDOWS
  644. r = mkdir(dirname);
  645. #else
  646. r = mkdir(dirname, 0700);
  647. #endif
  648. if (r) {
  649. log(LOG_WARN, "Error creating directory %s: %s", dirname,
  650. strerror(errno));
  651. return -1;
  652. } else {
  653. return 0;
  654. }
  655. }
  656. if (!(st.st_mode & S_IFDIR)) {
  657. log(LOG_WARN, "%s is not a directory", dirname);
  658. return -1;
  659. }
  660. #ifndef MS_WINDOWS
  661. if (st.st_uid != getuid()) {
  662. log(LOG_WARN, "%s is not owned by this UID (%d). You must fix this to proceed.", dirname, (int)getuid());
  663. return -1;
  664. }
  665. if (st.st_mode & 0077) {
  666. log(LOG_WARN, "Fixing permissions on directory %s", dirname);
  667. if (chmod(dirname, 0700)) {
  668. log(LOG_WARN, "Could not chmod directory %s: %s", dirname,
  669. strerror(errno));
  670. return -1;
  671. } else {
  672. return 0;
  673. }
  674. }
  675. #endif
  676. return 0;
  677. }
  678. /** Create a file named <b>fname</b> with the contents <b>str</b>. Overwrite the
  679. * previous <b>fname</b> if possible. Return 0 on success, -1 on failure.
  680. *
  681. * This function replaces the old file atomically, if possible.
  682. */
  683. int
  684. write_str_to_file(const char *fname, const char *str, int bin)
  685. {
  686. return write_bytes_to_file(fname, str, strlen(str), bin);
  687. }
  688. /* DOCDOC */
  689. int write_bytes_to_file(const char *fname, const char *str, size_t len,
  690. int bin)
  691. {
  692. char tempname[1024];
  693. int fd;
  694. size_t len;
  695. int result;
  696. if ((strlcpy(tempname,fname,1024) >= 1024) ||
  697. (strlcat(tempname,".tmp",1024) >= 1024)) {
  698. log(LOG_WARN, "Filename %s.tmp too long (>1024 chars)", fname);
  699. return -1;
  700. }
  701. if ((fd = open(tempname, O_WRONLY|O_CREAT|O_TRUNC|(bin?O_BINARY:0), 0600))
  702. < 0) {
  703. log(LOG_WARN, "Couldn't open %s for writing: %s", tempname,
  704. strerror(errno));
  705. return -1;
  706. }
  707. result = write_all(fd, str, len, 0);
  708. if(result < 0 || (size_t)result != len) {
  709. log(LOG_WARN, "Error writing to %s: %s", tempname, strerror(errno));
  710. close(fd);
  711. return -1;
  712. }
  713. if (close(fd)) {
  714. log(LOG_WARN,"Error flushing to %s: %s", tempname, strerror(errno));
  715. return -1;
  716. }
  717. /* XXXX use replace_file() instead. */
  718. #ifdef MS_WINDOWS
  719. /* On Windows, rename doesn't replace. We could call ReplaceFile, but
  720. * that's hard, and we can probably sneak by without atomicity. */
  721. switch (file_status(fname)) {
  722. case FN_ERROR:
  723. log(LOG_WARN, "Error replacing %s: %s", fname, strerror(errno));
  724. return -1;
  725. case FN_DIR:
  726. log(LOG_WARN, "Error replacing %s: is directory", fname);
  727. return -1;
  728. case FN_FILE:
  729. if (unlink(fname)) {
  730. log(LOG_WARN, "Error replacing %s while removing old copy: %s",
  731. fname, strerror(errno));
  732. return -1;
  733. }
  734. break;
  735. case FN_NOENT:
  736. ;
  737. }
  738. #endif
  739. if (rename(tempname, fname)) {
  740. log(LOG_WARN, "Error replacing %s: %s", fname, strerror(errno));
  741. return -1;
  742. }
  743. return 0;
  744. }
  745. /** Read the contents of <b>filename</b> into a newly allocated string; return the
  746. * string on success or NULL on failure.
  747. */
  748. char *read_file_to_str(const char *filename, int bin) {
  749. int fd; /* router file */
  750. struct stat statbuf;
  751. char *string;
  752. int r;
  753. tor_assert(filename);
  754. if(stat(filename, &statbuf) < 0) {
  755. log_fn(LOG_INFO,"Could not stat %s.",filename);
  756. return NULL;
  757. }
  758. fd = open(filename,O_RDONLY|(bin?O_BINARY:0),0);
  759. if (fd<0) {
  760. log_fn(LOG_WARN,"Could not open %s.",filename);
  761. return NULL;
  762. }
  763. string = tor_malloc(statbuf.st_size+1);
  764. r = read_all(fd,string,statbuf.st_size,0);
  765. if (r<0) {
  766. log_fn(LOG_WARN,"Error reading from file '%s': %s", filename,
  767. strerror(errno));
  768. tor_free(string);
  769. close(fd);
  770. return NULL;
  771. } else if (bin && r != statbuf.st_size) {
  772. /* If we're in binary mode, then we'd better have an exact match for
  773. * size. Otherwise, win32 encoding may throw us off, and that's okay. */
  774. log_fn(LOG_WARN,"Could read only %d of %ld bytes of file '%s'.",
  775. r, (long)statbuf.st_size,filename);
  776. tor_free(string);
  777. close(fd);
  778. return NULL;
  779. }
  780. close(fd);
  781. string[statbuf.st_size] = 0; /* null terminate it */
  782. return string;
  783. }
  784. /** read lines from f (no more than maxlen-1 bytes each) until we
  785. * get a non-whitespace line. If it isn't of the form "key value"
  786. * (value can have spaces), return -1.
  787. * Point *key to the first word in line, point *value * to the second.
  788. * Put a \0 at the end of key, remove everything at the end of value
  789. * that is whitespace or comment.
  790. * Return 1 if success, 0 if no more lines, -1 if error.
  791. */
  792. int
  793. parse_line_from_file(char *line, size_t maxlen, FILE *f,
  794. char **key_out, char **value_out) {
  795. char *s, *key, *end, *value;
  796. try_next_line:
  797. if(!fgets(line, maxlen, f)) {
  798. if(feof(f))
  799. return 0;
  800. return -1; /* real error */
  801. }
  802. if((s = strchr(line,'#'))) /* strip comments */
  803. *s = 0; /* stop the line there */
  804. /* remove end whitespace */
  805. s = strchr(line, 0); /* now we're at the null */
  806. do {
  807. *s = 0;
  808. s--;
  809. } while (s >= line && isspace((int)*s));
  810. key = line;
  811. while(isspace((int)*key))
  812. key++;
  813. if(*key == 0)
  814. goto try_next_line; /* this line has nothing on it */
  815. end = key;
  816. while(*end && !isspace((int)*end))
  817. end++;
  818. value = end;
  819. while(*value && isspace((int)*value))
  820. value++;
  821. #if 0
  822. if(!*end || !*value) { /* only a key on this line. no value. */
  823. *end = 0;
  824. log_fn(LOG_WARN,"Line has keyword '%s' but no value. Failing.",key);
  825. return -1;
  826. }
  827. #endif
  828. *end = 0; /* null it out */
  829. tor_assert(key);
  830. tor_assert(value);
  831. log_fn(LOG_DEBUG,"got keyword '%s', value '%s'", key, value);
  832. *key_out = key, *value_out = value;
  833. return 1;
  834. }
  835. /** Expand any homedir prefix on 'filename'; return a newly allocated
  836. * string. */
  837. char *expand_filename(const char *filename)
  838. {
  839. tor_assert(filename);
  840. /* XXXX Should eventually check for ~username/ */
  841. if (!strncmp(filename,"~/",2)) {
  842. size_t len;
  843. const char *home = getenv("HOME");
  844. char *result;
  845. if (!home) {
  846. log_fn(LOG_WARN, "Couldn't find $HOME environment variable while expanding %s", filename);
  847. return NULL;
  848. }
  849. /* minus two characters for ~/, plus one for /, plus one for NUL.
  850. * Round up to 16 in case we can't do math. */
  851. len = strlen(home)+strlen(filename)+16;
  852. result = tor_malloc(len);
  853. tor_snprintf(result,len,"%s/%s",home,filename+2);
  854. return result;
  855. } else {
  856. return tor_strdup(filename);
  857. }
  858. }
  859. /* =====
  860. * Net helpers
  861. * ===== */
  862. /** Return true iff <b>ip</b> (in host order) is an IP reserved to localhost,
  863. * or reserved for local networks by RFC 1918.
  864. */
  865. int is_internal_IP(uint32_t ip) {
  866. if (((ip & 0xff000000) == 0x0a000000) || /* 10/8 */
  867. ((ip & 0xff000000) == 0x00000000) || /* 0/8 */
  868. ((ip & 0xff000000) == 0x7f000000) || /* 127/8 */
  869. ((ip & 0xffff0000) == 0xa9fe0000) || /* 169.254/16 */
  870. ((ip & 0xfff00000) == 0xac100000) || /* 172.16/12 */
  871. ((ip & 0xffff0000) == 0xc0a80000)) /* 192.168/16 */
  872. return 1;
  873. return 0;
  874. }
  875. /** Return true iff <b>ip</b> (in host order) is judged to be on the
  876. * same network as us. For now, check if it's an internal IP. For XXX008,
  877. * also check if it's on the same class C network as our public IP.
  878. */
  879. int is_local_IP(uint32_t ip) {
  880. return is_internal_IP(ip);
  881. }
  882. /** Similar behavior to Unix gethostbyname: resolve <b>name</b>, and set
  883. * *addr to the proper IP address, in network byte order. Returns 0
  884. * on success, -1 on failure; 1 on transient failure.
  885. *
  886. * (This function exists because standard windows gethostbyname
  887. * doesn't treat raw IP addresses properly.)
  888. */
  889. int tor_lookup_hostname(const char *name, uint32_t *addr)
  890. {
  891. /* Perhaps eventually this should be replaced by a tor_getaddrinfo or
  892. * something.
  893. */
  894. struct in_addr iaddr;
  895. struct hostent *ent;
  896. tor_assert(addr);
  897. if (!*name) {
  898. /* Empty address is an error. */
  899. return -1;
  900. } else if (tor_inet_aton(name, &iaddr)) {
  901. /* It's an IP. */
  902. memcpy(addr, &iaddr.s_addr, 4);
  903. return 0;
  904. } else {
  905. ent = gethostbyname(name);
  906. if (ent) {
  907. /* break to remind us if we move away from IPv4 */
  908. tor_assert(ent->h_length == 4);
  909. memcpy(addr, ent->h_addr, 4);
  910. return 0;
  911. }
  912. memset(addr, 0, 4);
  913. #ifdef MS_WINDOWS
  914. return (WSAGetLastError() == WSATRY_AGAIN) ? 1 : -1;
  915. #else
  916. return (h_errno == TRY_AGAIN) ? 1 : -1;
  917. #endif
  918. }
  919. }
  920. /** Parse a string of the form "host[:port]" from <b>addrport</b>. If
  921. * <b>address</b> is provided, set *<b>address</b> to a copy of the
  922. * host portion of the string. If <b>addr</b> is provided, try to
  923. * resolve the host portion of the string and store it into
  924. * *<b>addr</b> (in host byte order). If <b>port</b> is provided,
  925. * store the port number into *<b>port</b>, or 0 if no port is given.
  926. * Return 0 on success, -1 on failure.
  927. */
  928. int
  929. parse_addr_port(const char *addrport, char **address, uint32_t *addr,
  930. uint16_t *port)
  931. {
  932. const char *colon;
  933. char *_address = NULL;
  934. int _port;
  935. int ok = 1;
  936. tor_assert(addrport);
  937. tor_assert(port);
  938. colon = strchr(addrport, ':');
  939. if (colon) {
  940. _address = tor_strndup(addrport, colon-addrport);
  941. _port = (int) tor_parse_long(colon+1,10,1,65535,NULL,NULL);
  942. if (!_port) {
  943. log_fn(LOG_WARN, "Port '%s' out of range", colon+1);
  944. ok = 0;
  945. }
  946. } else {
  947. _address = tor_strdup(addrport);
  948. _port = 0;
  949. }
  950. if (addr) {
  951. /* There's an addr pointer, so we need to resolve the hostname. */
  952. if (tor_lookup_hostname(_address,addr)) {
  953. log_fn(LOG_WARN, "Couldn't look up '%s'", _address);
  954. ok = 0;
  955. *addr = 0;
  956. }
  957. *addr = ntohl(*addr);
  958. }
  959. if (address && ok) {
  960. *address = _address;
  961. } else {
  962. if (address)
  963. *address = NULL;
  964. tor_free(_address);
  965. }
  966. if (port)
  967. *port = ok ? ((uint16_t) _port) : 0;
  968. return ok ? 0 : -1;
  969. }
  970. /** Parse a string <b>s</b> in the format of
  971. * (IP(/mask|/mask-bits)?|*):(*|port(-maxport)?), setting the various
  972. * *out pointers as appropriate. Return 0 on success, -1 on failure.
  973. */
  974. int
  975. parse_addr_and_port_range(const char *s, uint32_t *addr_out,
  976. uint32_t *mask_out, uint16_t *port_min_out,
  977. uint16_t *port_max_out)
  978. {
  979. char *address;
  980. char *mask, *port, *endptr;
  981. struct in_addr in;
  982. int bits;
  983. tor_assert(s);
  984. tor_assert(addr_out);
  985. tor_assert(mask_out);
  986. tor_assert(port_min_out);
  987. tor_assert(port_max_out);
  988. address = tor_strdup(s);
  989. /* Break 'address' into separate strings.
  990. */
  991. mask = strchr(address,'/');
  992. port = strchr(mask?mask:address,':');
  993. if (mask)
  994. *mask++ = '\0';
  995. if (port)
  996. *port++ = '\0';
  997. /* Now "address" is the IP|'*' part...
  998. * "mask" is the Mask|Maskbits part...
  999. * and "port" is the *|port|min-max part.
  1000. */
  1001. if (strcmp(address,"*")==0) {
  1002. *addr_out = 0;
  1003. } else if (tor_inet_aton(address, &in) != 0) {
  1004. *addr_out = ntohl(in.s_addr);
  1005. } else {
  1006. log_fn(LOG_WARN, "Malformed IP %s in address pattern; rejecting.",address);
  1007. goto err;
  1008. }
  1009. if (!mask) {
  1010. if (strcmp(address,"*")==0)
  1011. *mask_out = 0;
  1012. else
  1013. *mask_out = 0xFFFFFFFFu;
  1014. } else {
  1015. endptr = NULL;
  1016. bits = (int) strtol(mask, &endptr, 10);
  1017. if (!*endptr) {
  1018. /* strtol handled the whole mask. */
  1019. if (bits < 0 || bits > 32) {
  1020. log_fn(LOG_WARN, "Bad number of mask bits on address range; rejecting.");
  1021. goto err;
  1022. }
  1023. *mask_out = ~((1<<(32-bits))-1);
  1024. } else if (tor_inet_aton(mask, &in) != 0) {
  1025. *mask_out = ntohl(in.s_addr);
  1026. } else {
  1027. log_fn(LOG_WARN, "Malformed mask %s on address range; rejecting.",
  1028. mask);
  1029. goto err;
  1030. }
  1031. }
  1032. if (!port || strcmp(port, "*") == 0) {
  1033. *port_min_out = 1;
  1034. *port_max_out = 65535;
  1035. } else {
  1036. endptr = NULL;
  1037. *port_min_out = (uint16_t) tor_parse_long(port, 10, 1, 65535,
  1038. NULL, &endptr);
  1039. if (*endptr == '-') {
  1040. port = endptr+1;
  1041. endptr = NULL;
  1042. *port_max_out = (uint16_t) tor_parse_long(port, 10, 1, 65535, NULL,
  1043. &endptr);
  1044. if (*endptr || !*port_max_out) {
  1045. log_fn(LOG_WARN, "Malformed port %s on address range rejecting.",
  1046. port);
  1047. }
  1048. } else if (*endptr || !*port_min_out) {
  1049. log_fn(LOG_WARN, "Malformed port %s on address range; rejecting.",
  1050. port);
  1051. goto err;
  1052. } else {
  1053. *port_max_out = *port_min_out;
  1054. }
  1055. if (*port_min_out > *port_max_out) {
  1056. log_fn(LOG_WARN,"Insane port range on address policy; rejecting.");
  1057. goto err;
  1058. }
  1059. }
  1060. tor_free(address);
  1061. return 0;
  1062. err:
  1063. tor_free(address);
  1064. return -1;
  1065. }
  1066. /* =====
  1067. * Process helpers
  1068. * ===== */
  1069. #ifndef MS_WINDOWS
  1070. /* Based on code contributed by christian grothoff */
  1071. static int start_daemon_called = 0;
  1072. static int finish_daemon_called = 0;
  1073. static int daemon_filedes[2];
  1074. /** Start putting the process into daemon mode: fork and drop all resources
  1075. * except standard fds. The parent process never returns, but stays around
  1076. * until finish_daemon is called. (Note: it's safe to call this more
  1077. * than once: calls after the first are ignored.)
  1078. */
  1079. void start_daemon(const char *desired_cwd)
  1080. {
  1081. pid_t pid;
  1082. if (start_daemon_called)
  1083. return;
  1084. start_daemon_called = 1;
  1085. if(!desired_cwd)
  1086. desired_cwd = "/";
  1087. /* Don't hold the wrong FS mounted */
  1088. if (chdir(desired_cwd) < 0) {
  1089. log_fn(LOG_ERR,"chdir to %s failed. Exiting.",desired_cwd);
  1090. exit(1);
  1091. }
  1092. pipe(daemon_filedes);
  1093. pid = fork();
  1094. if (pid < 0) {
  1095. log_fn(LOG_ERR,"fork failed. Exiting.");
  1096. exit(1);
  1097. }
  1098. if (pid) { /* Parent */
  1099. int ok;
  1100. char c;
  1101. close(daemon_filedes[1]); /* we only read */
  1102. ok = -1;
  1103. while (0 < read(daemon_filedes[0], &c, sizeof(char))) {
  1104. if (c == '.')
  1105. ok = 1;
  1106. }
  1107. fflush(stdout);
  1108. if (ok == 1)
  1109. exit(0);
  1110. else
  1111. exit(1); /* child reported error */
  1112. } else { /* Child */
  1113. close(daemon_filedes[0]); /* we only write */
  1114. pid = setsid(); /* Detach from controlling terminal */
  1115. /*
  1116. * Fork one more time, so the parent (the session group leader) can exit.
  1117. * This means that we, as a non-session group leader, can never regain a
  1118. * controlling terminal. This part is recommended by Stevens's
  1119. * _Advanced Programming in the Unix Environment_.
  1120. */
  1121. if (fork() != 0) {
  1122. exit(0);
  1123. }
  1124. return;
  1125. }
  1126. }
  1127. /** Finish putting the process into daemon mode: drop standard fds, and tell
  1128. * the parent process to exit. (Note: it's safe to call this more than once:
  1129. * calls after the first are ignored. Calls start_daemon first if it hasn't
  1130. * been called already.)
  1131. */
  1132. void finish_daemon(void)
  1133. {
  1134. int nullfd;
  1135. char c = '.';
  1136. if (finish_daemon_called)
  1137. return;
  1138. if (!start_daemon_called)
  1139. start_daemon(NULL);
  1140. finish_daemon_called = 1;
  1141. nullfd = open("/dev/null",
  1142. O_CREAT | O_RDWR | O_APPEND);
  1143. if (nullfd < 0) {
  1144. log_fn(LOG_ERR,"/dev/null can't be opened. Exiting.");
  1145. exit(1);
  1146. }
  1147. /* close fds linking to invoking terminal, but
  1148. * close usual incoming fds, but redirect them somewhere
  1149. * useful so the fds don't get reallocated elsewhere.
  1150. */
  1151. if (dup2(nullfd,0) < 0 ||
  1152. dup2(nullfd,1) < 0 ||
  1153. dup2(nullfd,2) < 0) {
  1154. log_fn(LOG_ERR,"dup2 failed. Exiting.");
  1155. exit(1);
  1156. }
  1157. write(daemon_filedes[1], &c, sizeof(char)); /* signal success */
  1158. close(daemon_filedes[1]);
  1159. }
  1160. #else
  1161. /* defined(MS_WINDOWS) */
  1162. void start_daemon(const char *cp) {}
  1163. void finish_daemon(void) {}
  1164. #endif
  1165. /** Write the current process ID, followed by NL, into <b>filename</b>.
  1166. */
  1167. void write_pidfile(char *filename) {
  1168. #ifndef MS_WINDOWS
  1169. FILE *pidfile;
  1170. if ((pidfile = fopen(filename, "w")) == NULL) {
  1171. log_fn(LOG_WARN, "Unable to open %s for writing: %s", filename,
  1172. strerror(errno));
  1173. } else {
  1174. fprintf(pidfile, "%d\n", (int)getpid());
  1175. fclose(pidfile);
  1176. }
  1177. #endif
  1178. }
  1179. /*
  1180. Local Variables:
  1181. mode:c
  1182. indent-tabs-mode:nil
  1183. c-basic-offset:2
  1184. End:
  1185. */