util.c 38 KB

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