util.c 38 KB

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