util.c 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502
  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
  628. 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
  648. read_all(int fd, char *buf, size_t count, int isSocket) {
  649. size_t numread = 0;
  650. int result;
  651. if (count > SIZE_T_CEILING)
  652. return -1;
  653. while (numread != count) {
  654. if (isSocket)
  655. result = recv(fd, buf+numread, count-numread, 0);
  656. else
  657. result = read(fd, buf+numread, count-numread);
  658. if (result<0)
  659. return -1;
  660. else if (result == 0)
  661. break;
  662. numread += result;
  663. }
  664. return numread;
  665. }
  666. /*
  667. * Filesystem operations.
  668. */
  669. /** Clean up <b>name</b> so that we can use it in a call to "stat". On Unix,
  670. * we do nothing. On Windows, we remove a trailing slash, unless the path is
  671. * the root of a disk. */
  672. static void
  673. clean_name_for_stat(char *name)
  674. {
  675. #ifdef MS_WINDOWS
  676. size_t len = strlen(name);
  677. if (!len)
  678. return;
  679. if (name[len-1]=='\\' || name[len-1]=='/') {
  680. if (len == 1 || (len==3 && name[1]==':'))
  681. return;
  682. name[len-1]='\0';
  683. }
  684. #endif
  685. }
  686. /** Return FN_ERROR if filename can't be read, FN_NOENT if it doesn't
  687. * exist, FN_FILE if it is a regular file, or FN_DIR if it's a
  688. * directory. */
  689. file_status_t file_status(const char *fname)
  690. {
  691. struct stat st;
  692. char *f;
  693. int r;
  694. f = tor_strdup(fname);
  695. clean_name_for_stat(f);
  696. r = stat(f, &st);
  697. tor_free(f);
  698. if (r) {
  699. if (errno == ENOENT) {
  700. return FN_NOENT;
  701. }
  702. return FN_ERROR;
  703. }
  704. if (st.st_mode & S_IFDIR)
  705. return FN_DIR;
  706. else if (st.st_mode & S_IFREG)
  707. return FN_FILE;
  708. else
  709. return FN_ERROR;
  710. }
  711. /** Check whether dirname exists and is private. If yes return 0. If
  712. * it does not exist, and check==CPD_CREATE is set, try to create it
  713. * and return 0 on success. If it does not exist, and
  714. * check==CPD_CHECK, and we think we can create it, return 0. Else
  715. * return -1. */
  716. int check_private_dir(const char *dirname, cpd_check_t check)
  717. {
  718. int r;
  719. struct stat st;
  720. char *f;
  721. tor_assert(dirname);
  722. f = tor_strdup(dirname);
  723. clean_name_for_stat(f);
  724. r = stat(f, &st);
  725. tor_free(f);
  726. if (r) {
  727. if (errno != ENOENT) {
  728. log(LOG_WARN, "Directory %s cannot be read: %s", dirname,
  729. strerror(errno));
  730. return -1;
  731. }
  732. if (check == CPD_NONE) {
  733. log(LOG_WARN, "Directory %s does not exist.", dirname);
  734. return -1;
  735. } else if (check == CPD_CREATE) {
  736. log(LOG_INFO, "Creating directory %s", dirname);
  737. #ifdef MS_WINDOWS
  738. r = mkdir(dirname);
  739. #else
  740. r = mkdir(dirname, 0700);
  741. #endif
  742. if (r) {
  743. log(LOG_WARN, "Error creating directory %s: %s", dirname,
  744. strerror(errno));
  745. return -1;
  746. }
  747. }
  748. /* XXXX In the case where check==CPD_CHECK, we should look at the
  749. * parent directory a little harder. */
  750. return 0;
  751. }
  752. if (!(st.st_mode & S_IFDIR)) {
  753. log(LOG_WARN, "%s is not a directory", dirname);
  754. return -1;
  755. }
  756. #ifndef MS_WINDOWS
  757. if (st.st_uid != getuid()) {
  758. log(LOG_WARN, "%s is not owned by this UID (%d). You must fix this to proceed.", dirname, (int)getuid());
  759. return -1;
  760. }
  761. if (st.st_mode & 0077) {
  762. log(LOG_WARN, "Fixing permissions on directory %s", dirname);
  763. if (chmod(dirname, 0700)) {
  764. log(LOG_WARN, "Could not chmod directory %s: %s", dirname,
  765. strerror(errno));
  766. return -1;
  767. } else {
  768. return 0;
  769. }
  770. }
  771. #endif
  772. return 0;
  773. }
  774. /** Create a file named <b>fname</b> with the contents <b>str</b>. Overwrite the
  775. * previous <b>fname</b> if possible. Return 0 on success, -1 on failure.
  776. *
  777. * This function replaces the old file atomically, if possible.
  778. */
  779. int
  780. write_str_to_file(const char *fname, const char *str, int bin)
  781. {
  782. #ifdef MS_WINDOWS
  783. if (!bin && strchr(str, '\r')) {
  784. log_fn(LOG_WARN,
  785. "How odd. Writing a string that does contain CR already.");
  786. }
  787. #endif
  788. return write_bytes_to_file(fname, str, strlen(str), bin);
  789. }
  790. /** As write_str_to_file, but does not assume a NUL-terminated *
  791. * string. Instead, we write <b>len</b> bytes, starting at <b>str</b>. */
  792. int write_bytes_to_file(const char *fname, const char *str, size_t len,
  793. int bin)
  794. {
  795. size_t tempname_len;
  796. char *tempname;
  797. int fd;
  798. int result;
  799. tempname_len = strlen(fname)+16;
  800. tor_assert(tempname_len > strlen(fname)); /*check for overflow*/
  801. tempname = tor_malloc(tempname_len);
  802. if (tor_snprintf(tempname, tempname_len, "%s.tmp", fname)<0) {
  803. log(LOG_WARN, "Failed to generate filename");
  804. goto err;
  805. }
  806. if ((fd = open(tempname, O_WRONLY|O_CREAT|O_TRUNC|(bin?O_BINARY:O_TEXT), 0600))
  807. < 0) {
  808. log(LOG_WARN, "Couldn't open %s for writing: %s", tempname,
  809. strerror(errno));
  810. goto err;
  811. }
  812. result = write_all(fd, str, len, 0);
  813. if (result < 0 || (size_t)result != len) {
  814. log(LOG_WARN, "Error writing to %s: %s", tempname, strerror(errno));
  815. close(fd);
  816. goto err;
  817. }
  818. if (close(fd)) {
  819. log(LOG_WARN,"Error flushing to %s: %s", tempname, strerror(errno));
  820. goto err;
  821. }
  822. if (replace_file(tempname, fname)) {
  823. log(LOG_WARN, "Error replacing %s: %s", fname, strerror(errno));
  824. goto err;
  825. }
  826. tor_free(tempname);
  827. return 0;
  828. err:
  829. tor_free(tempname);
  830. return -1;
  831. }
  832. /** Read the contents of <b>filename</b> into a newly allocated
  833. * string; return the string on success or NULL on failure.
  834. */
  835. /*
  836. * This function <em>may</em> return an erroneous result if the file
  837. * is modified while it is running, but must not crash or overflow.
  838. * Right now, the error case occurs when the file length grows between
  839. * the call to stat and the call to read_all: the resulting string will
  840. * be truncated.
  841. */
  842. char *read_file_to_str(const char *filename, int bin) {
  843. int fd; /* router file */
  844. struct stat statbuf;
  845. char *string, *f;
  846. int r;
  847. tor_assert(filename);
  848. f = tor_strdup(filename);
  849. clean_name_for_stat(f);
  850. r = stat(f, &statbuf);
  851. tor_free(f);
  852. if (r < 0) {
  853. log_fn(LOG_INFO,"Could not stat %s.",filename);
  854. return NULL;
  855. }
  856. fd = open(filename,O_RDONLY|(bin?O_BINARY:O_TEXT),0);
  857. if (fd<0) {
  858. log_fn(LOG_WARN,"Could not open %s.",filename);
  859. return NULL;
  860. }
  861. string = tor_malloc(statbuf.st_size+1);
  862. r = read_all(fd,string,statbuf.st_size,0);
  863. if (r<0) {
  864. log_fn(LOG_WARN,"Error reading from file '%s': %s", filename,
  865. strerror(errno));
  866. tor_free(string);
  867. close(fd);
  868. return NULL;
  869. }
  870. string[r] = '\0'; /* NUL-terminate the result. */
  871. if (bin && r != statbuf.st_size) {
  872. /* If we're in binary mode, then we'd better have an exact match for
  873. * size. Otherwise, win32 encoding may throw us off, and that's okay. */
  874. log_fn(LOG_WARN,"Could read only %d of %ld bytes of file '%s'.",
  875. r, (long)statbuf.st_size,filename);
  876. tor_free(string);
  877. close(fd);
  878. return NULL;
  879. }
  880. #ifdef MS_WINDOWS
  881. if (!bin && strchr(string, '\r')) {
  882. log_fn(LOG_DEBUG, "We didn't convert CRLF to LF as well as we hoped when reading %s. Coping.",
  883. filename);
  884. tor_strstrip(string, "\r");
  885. }
  886. #endif
  887. close(fd);
  888. return string;
  889. }
  890. /** Given a string containing part of a configuration file or similar format,
  891. * advance past comments and whitespace and try to parse a single line. If we
  892. * parse a line successfully, set *<b>key_out</b> to the key portion and
  893. * *<b>value_out</b> to the value portion of the line, and return a pointer to
  894. * the start of the next line. If we run out of data, return a pointer to the
  895. * end of the string. If we encounter an error, return NULL.
  896. *
  897. * NOTE: We modify <b>line</b> as we parse it, by inserting NULs to terminate
  898. * the key and value.
  899. */
  900. char *
  901. parse_line_from_str(char *line, char **key_out, char **value_out)
  902. {
  903. char *key, *val, *cp;
  904. tor_assert(key_out);
  905. tor_assert(value_out);
  906. *key_out = *value_out = key = val = NULL;
  907. /* Skip until the first keyword. */
  908. while (1) {
  909. while (TOR_ISSPACE(*line))
  910. ++line;
  911. if (*line == '#') {
  912. while (*line && *line != '\n')
  913. ++line;
  914. } else {
  915. break;
  916. }
  917. }
  918. if (!*line) { /* End of string? */
  919. *key_out = *value_out = NULL;
  920. return line;
  921. }
  922. /* Skip until the next space. */
  923. key = line;
  924. while (*line && !TOR_ISSPACE(*line) && *line != '#')
  925. ++line;
  926. /* Skip until the value */
  927. while (*line == ' ' || *line == '\t')
  928. *line++ = '\0';
  929. val = line;
  930. /* Find the end of the line. */
  931. while (*line && *line != '\n' && *line != '#')
  932. ++line;
  933. if (*line == '\n')
  934. cp = line++;
  935. else {
  936. cp = line-1;
  937. }
  938. while (cp>=val && TOR_ISSPACE(*cp))
  939. *cp-- = '\0';
  940. if (*line == '#') {
  941. do {
  942. *line++ = '\0';
  943. } while (*line && *line != '\n');
  944. if (*line == '\n')
  945. ++line;
  946. }
  947. *key_out = key;
  948. *value_out = val;
  949. return line;
  950. }
  951. /** Expand any homedir prefix on 'filename'; return a newly allocated
  952. * string. */
  953. char *expand_filename(const char *filename)
  954. {
  955. tor_assert(filename);
  956. if (*filename == '~') {
  957. size_t len;
  958. char *home, *result;
  959. const char *rest;
  960. if (filename[1] == '/' || filename[1] == '\0') {
  961. home = getenv("HOME");
  962. if (!home) {
  963. log_fn(LOG_WARN, "Couldn't find $HOME environment variable while expanding %s", filename);
  964. return NULL;
  965. }
  966. home = tor_strdup(home);
  967. rest = strlen(filename)>=2?(filename+2):NULL;
  968. } else {
  969. #ifdef HAVE_PWD_H
  970. char *username, *slash;
  971. slash = strchr(filename, '/');
  972. if (slash)
  973. username = tor_strndup(filename+1,slash-filename-1);
  974. else
  975. username = tor_strdup(filename+1);
  976. if (!(home = get_user_homedir(username))) {
  977. log_fn(LOG_WARN,"Couldn't get homedir for %s",username);
  978. tor_free(username);
  979. return NULL;
  980. }
  981. tor_free(username);
  982. rest = slash ? (slash+1) : NULL;
  983. #else
  984. log_fn(LOG_WARN, "Couldn't expend homedir on system without pwd.h");
  985. return tor_strdup(filename);
  986. #endif
  987. }
  988. tor_assert(home);
  989. /* Remove trailing slash. */
  990. if (strlen(home)>1 && !strcmpend(home,"/")) {
  991. home[strlen(home)-1] = '\0';
  992. }
  993. /* Plus one for /, plus one for NUL.
  994. * Round up to 16 in case we can't do math. */
  995. len = strlen(home)+strlen(rest)+16;
  996. result = tor_malloc(len);
  997. tor_snprintf(result,len,"%s/%s",home,rest?rest:"");
  998. tor_free(home);
  999. return result;
  1000. } else {
  1001. return tor_strdup(filename);
  1002. }
  1003. }
  1004. /* =====
  1005. * Net helpers
  1006. * ===== */
  1007. /** Return true iff <b>ip</b> (in host order) is an IP reserved to localhost,
  1008. * or reserved for local networks by RFC 1918.
  1009. */
  1010. int is_internal_IP(uint32_t ip) {
  1011. if (((ip & 0xff000000) == 0x0a000000) || /* 10/8 */
  1012. ((ip & 0xff000000) == 0x00000000) || /* 0/8 */
  1013. ((ip & 0xff000000) == 0x7f000000) || /* 127/8 */
  1014. ((ip & 0xffff0000) == 0xa9fe0000) || /* 169.254/16 */
  1015. ((ip & 0xfff00000) == 0xac100000) || /* 172.16/12 */
  1016. ((ip & 0xffff0000) == 0xc0a80000)) /* 192.168/16 */
  1017. return 1;
  1018. return 0;
  1019. }
  1020. /** Return true iff <b>ip</b> (in host order) is judged to be on the
  1021. * same network as us. For now, check if it's an internal IP.
  1022. *
  1023. * XXX Also check if it's on the same class C network as our public IP.
  1024. */
  1025. int is_local_IP(uint32_t ip) {
  1026. return is_internal_IP(ip);
  1027. }
  1028. /** Parse a string of the form "host[:port]" from <b>addrport</b>. If
  1029. * <b>address</b> is provided, set *<b>address</b> to a copy of the
  1030. * host portion of the string. If <b>addr</b> is provided, try to
  1031. * resolve the host portion of the string and store it into
  1032. * *<b>addr</b> (in host byte order). If <b>port</b> is provided,
  1033. * store the port number into *<b>port</b>, or 0 if no port is given.
  1034. * Return 0 on success, -1 on failure.
  1035. */
  1036. int
  1037. parse_addr_port(const char *addrport, char **address, uint32_t *addr,
  1038. uint16_t *port)
  1039. {
  1040. const char *colon;
  1041. char *_address = NULL;
  1042. int _port;
  1043. int ok = 1;
  1044. tor_assert(addrport);
  1045. tor_assert(port);
  1046. colon = strchr(addrport, ':');
  1047. if (colon) {
  1048. _address = tor_strndup(addrport, colon-addrport);
  1049. _port = (int) tor_parse_long(colon+1,10,1,65535,NULL,NULL);
  1050. if (!_port) {
  1051. log_fn(LOG_WARN, "Port '%s' out of range", colon+1);
  1052. ok = 0;
  1053. }
  1054. } else {
  1055. _address = tor_strdup(addrport);
  1056. _port = 0;
  1057. }
  1058. if (addr) {
  1059. /* There's an addr pointer, so we need to resolve the hostname. */
  1060. if (tor_lookup_hostname(_address,addr)) {
  1061. log_fn(LOG_WARN, "Couldn't look up '%s'", _address);
  1062. ok = 0;
  1063. *addr = 0;
  1064. }
  1065. *addr = ntohl(*addr);
  1066. }
  1067. if (address && ok) {
  1068. *address = _address;
  1069. } else {
  1070. if (address)
  1071. *address = NULL;
  1072. tor_free(_address);
  1073. }
  1074. if (port)
  1075. *port = ok ? ((uint16_t) _port) : 0;
  1076. return ok ? 0 : -1;
  1077. }
  1078. /** Parse a string <b>s</b> in the format of
  1079. * (IP(/mask|/mask-bits)?|*):(*|port(-maxport)?), setting the various
  1080. * *out pointers as appropriate. Return 0 on success, -1 on failure.
  1081. */
  1082. int
  1083. parse_addr_and_port_range(const char *s, uint32_t *addr_out,
  1084. uint32_t *mask_out, uint16_t *port_min_out,
  1085. uint16_t *port_max_out)
  1086. {
  1087. char *address;
  1088. char *mask, *port, *endptr;
  1089. struct in_addr in;
  1090. int bits;
  1091. tor_assert(s);
  1092. tor_assert(addr_out);
  1093. tor_assert(mask_out);
  1094. tor_assert(port_min_out);
  1095. tor_assert(port_max_out);
  1096. address = tor_strdup(s);
  1097. /* Break 'address' into separate strings.
  1098. */
  1099. mask = strchr(address,'/');
  1100. port = strchr(mask?mask:address,':');
  1101. if (mask)
  1102. *mask++ = '\0';
  1103. if (port)
  1104. *port++ = '\0';
  1105. /* Now "address" is the IP|'*' part...
  1106. * "mask" is the Mask|Maskbits part...
  1107. * and "port" is the *|port|min-max part.
  1108. */
  1109. if (strcmp(address,"*")==0) {
  1110. *addr_out = 0;
  1111. } else if (tor_inet_aton(address, &in) != 0) {
  1112. *addr_out = ntohl(in.s_addr);
  1113. } else {
  1114. log_fn(LOG_WARN, "Malformed IP %s in address pattern; rejecting.",address);
  1115. goto err;
  1116. }
  1117. if (!mask) {
  1118. if (strcmp(address,"*")==0)
  1119. *mask_out = 0;
  1120. else
  1121. *mask_out = 0xFFFFFFFFu;
  1122. } else {
  1123. endptr = NULL;
  1124. bits = (int) strtol(mask, &endptr, 10);
  1125. if (!*endptr) {
  1126. /* strtol handled the whole mask. */
  1127. if (bits < 0 || bits > 32) {
  1128. log_fn(LOG_WARN, "Bad number of mask bits on address range; rejecting.");
  1129. goto err;
  1130. }
  1131. *mask_out = ~((1<<(32-bits))-1);
  1132. } else if (tor_inet_aton(mask, &in) != 0) {
  1133. *mask_out = ntohl(in.s_addr);
  1134. } else {
  1135. log_fn(LOG_WARN, "Malformed mask %s on address range; rejecting.",
  1136. mask);
  1137. goto err;
  1138. }
  1139. }
  1140. if (!port || strcmp(port, "*") == 0) {
  1141. *port_min_out = 1;
  1142. *port_max_out = 65535;
  1143. } else {
  1144. endptr = NULL;
  1145. *port_min_out = (uint16_t) tor_parse_long(port, 10, 1, 65535,
  1146. NULL, &endptr);
  1147. if (*endptr == '-') {
  1148. port = endptr+1;
  1149. endptr = NULL;
  1150. *port_max_out = (uint16_t) tor_parse_long(port, 10, 1, 65535, NULL,
  1151. &endptr);
  1152. if (*endptr || !*port_max_out) {
  1153. log_fn(LOG_WARN, "Malformed port %s on address range rejecting.",
  1154. port);
  1155. }
  1156. } else if (*endptr || !*port_min_out) {
  1157. log_fn(LOG_WARN, "Malformed port %s on address range; rejecting.",
  1158. port);
  1159. goto err;
  1160. } else {
  1161. *port_max_out = *port_min_out;
  1162. }
  1163. if (*port_min_out > *port_max_out) {
  1164. log_fn(LOG_WARN,"Insane port range on address policy; rejecting.");
  1165. goto err;
  1166. }
  1167. }
  1168. tor_free(address);
  1169. return 0;
  1170. err:
  1171. tor_free(address);
  1172. return -1;
  1173. }
  1174. /** Given an IPv4 address <b>in</b> (in network order, as usual),
  1175. * write it as a string into the <b>buf_len</b>-byte buffer in
  1176. * <b>buf</b>.
  1177. */
  1178. int
  1179. tor_inet_ntoa(struct in_addr *in, char *buf, size_t buf_len)
  1180. {
  1181. uint32_t a = ntohl(in->s_addr);
  1182. return tor_snprintf(buf, buf_len, "%d.%d.%d.%d",
  1183. (int)(uint8_t)((a>>24)&0xff),
  1184. (int)(uint8_t)((a>>16)&0xff),
  1185. (int)(uint8_t)((a>>8 )&0xff),
  1186. (int)(uint8_t)((a )&0xff));
  1187. }
  1188. /* Return true iff <b>name</b> looks like it might be a hostname or IP
  1189. * address of some kind. */
  1190. int
  1191. is_plausible_address(const char *name)
  1192. {
  1193. const char *cp;
  1194. tor_assert(name);
  1195. /* We could check better here. */
  1196. for (cp=name; *cp; cp++) {
  1197. if (*cp != '.' && *cp != '-' && !TOR_ISALNUM(*cp))
  1198. return 0;
  1199. }
  1200. return 1;
  1201. }
  1202. /**
  1203. * Set *<b>addr</b> to the host-order IPv4 address (if any) of whatever
  1204. * interface connects to the internet. This address should only be used in
  1205. * checking whether our address has changed. Return 0 on success, -1 on
  1206. * failure.
  1207. */
  1208. int
  1209. get_interface_address(uint32_t *addr)
  1210. {
  1211. int sock=-1, r=-1;
  1212. struct sockaddr_in target_addr, my_addr;
  1213. socklen_t my_addr_len = sizeof(my_addr);
  1214. tor_assert(addr);
  1215. *addr = 0;
  1216. sock = socket(PF_INET,SOCK_DGRAM,IPPROTO_UDP);
  1217. if (sock < 0) {
  1218. int e = tor_socket_errno(-1);
  1219. log_fn(LOG_WARN, "unable to create socket: %s", tor_socket_strerror(e));
  1220. goto err;
  1221. }
  1222. memset(&target_addr, 0, sizeof(target_addr));
  1223. target_addr.sin_family = AF_INET;
  1224. /* discard port */
  1225. target_addr.sin_port = 9;
  1226. /* 18.0.0.1 (Don't worry: no packets are sent. We just need a real address
  1227. * on the internet.) */
  1228. target_addr.sin_addr.s_addr = htonl(0x12000001);
  1229. if (connect(sock,(struct sockaddr *)&target_addr,sizeof(target_addr))<0) {
  1230. int e = tor_socket_errno(sock);
  1231. log_fn(LOG_WARN, "connnect() failed: %s", tor_socket_strerror(e));
  1232. goto err;
  1233. }
  1234. /* XXXX Can this be right on IPv6 clients? */
  1235. if (getsockname(sock, &my_addr, &my_addr_len)) {
  1236. int e = tor_socket_errno(sock);
  1237. log_fn(LOG_WARN, "getsockname() failed: %s", tor_socket_strerror(e));
  1238. goto err;
  1239. }
  1240. *addr = ntohl(my_addr.sin_addr.s_addr);
  1241. r=0;
  1242. err:
  1243. if (sock >= 0)
  1244. tor_close_socket(sock);
  1245. return r;
  1246. }
  1247. /* =====
  1248. * Process helpers
  1249. * ===== */
  1250. #ifndef MS_WINDOWS
  1251. /* Based on code contributed by christian grothoff */
  1252. static int start_daemon_called = 0;
  1253. static int finish_daemon_called = 0;
  1254. static int daemon_filedes[2];
  1255. /** Start putting the process into daemon mode: fork and drop all resources
  1256. * except standard fds. The parent process never returns, but stays around
  1257. * until finish_daemon is called. (Note: it's safe to call this more
  1258. * than once: calls after the first are ignored.)
  1259. */
  1260. void start_daemon(void)
  1261. {
  1262. pid_t pid;
  1263. if (start_daemon_called)
  1264. return;
  1265. start_daemon_called = 1;
  1266. pipe(daemon_filedes);
  1267. pid = fork();
  1268. if (pid < 0) {
  1269. log_fn(LOG_ERR,"fork failed. Exiting.");
  1270. exit(1);
  1271. }
  1272. if (pid) { /* Parent */
  1273. int ok;
  1274. char c;
  1275. close(daemon_filedes[1]); /* we only read */
  1276. ok = -1;
  1277. while (0 < read(daemon_filedes[0], &c, sizeof(char))) {
  1278. if (c == '.')
  1279. ok = 1;
  1280. }
  1281. fflush(stdout);
  1282. if (ok == 1)
  1283. exit(0);
  1284. else
  1285. exit(1); /* child reported error */
  1286. } else { /* Child */
  1287. close(daemon_filedes[0]); /* we only write */
  1288. pid = setsid(); /* Detach from controlling terminal */
  1289. /*
  1290. * Fork one more time, so the parent (the session group leader) can exit.
  1291. * This means that we, as a non-session group leader, can never regain a
  1292. * controlling terminal. This part is recommended by Stevens's
  1293. * _Advanced Programming in the Unix Environment_.
  1294. */
  1295. if (fork() != 0) {
  1296. exit(0);
  1297. }
  1298. return;
  1299. }
  1300. }
  1301. /** Finish putting the process into daemon mode: drop standard fds, and tell
  1302. * the parent process to exit. (Note: it's safe to call this more than once:
  1303. * calls after the first are ignored. Calls start_daemon first if it hasn't
  1304. * been called already.)
  1305. */
  1306. void finish_daemon(const char *desired_cwd)
  1307. {
  1308. int nullfd;
  1309. char c = '.';
  1310. if (finish_daemon_called)
  1311. return;
  1312. if (!start_daemon_called)
  1313. start_daemon();
  1314. finish_daemon_called = 1;
  1315. if (!desired_cwd)
  1316. desired_cwd = "/";
  1317. /* Don't hold the wrong FS mounted */
  1318. if (chdir(desired_cwd) < 0) {
  1319. log_fn(LOG_ERR,"chdir to %s failed. Exiting.",desired_cwd);
  1320. exit(1);
  1321. }
  1322. nullfd = open("/dev/null",
  1323. O_CREAT | O_RDWR | O_APPEND);
  1324. if (nullfd < 0) {
  1325. log_fn(LOG_ERR,"/dev/null can't be opened. Exiting.");
  1326. exit(1);
  1327. }
  1328. /* close fds linking to invoking terminal, but
  1329. * close usual incoming fds, but redirect them somewhere
  1330. * useful so the fds don't get reallocated elsewhere.
  1331. */
  1332. if (dup2(nullfd,0) < 0 ||
  1333. dup2(nullfd,1) < 0 ||
  1334. dup2(nullfd,2) < 0) {
  1335. log_fn(LOG_ERR,"dup2 failed. Exiting.");
  1336. exit(1);
  1337. }
  1338. if (nullfd > 2)
  1339. close(nullfd);
  1340. write(daemon_filedes[1], &c, sizeof(char)); /* signal success */
  1341. close(daemon_filedes[1]);
  1342. }
  1343. #else
  1344. /* defined(MS_WINDOWS) */
  1345. void start_daemon(void) {}
  1346. void finish_daemon(const char *cp) {}
  1347. #endif
  1348. /** Write the current process ID, followed by NL, into <b>filename</b>.
  1349. */
  1350. void write_pidfile(char *filename) {
  1351. #ifndef MS_WINDOWS
  1352. FILE *pidfile;
  1353. if ((pidfile = fopen(filename, "w")) == NULL) {
  1354. log_fn(LOG_WARN, "Unable to open %s for writing: %s", filename,
  1355. strerror(errno));
  1356. } else {
  1357. fprintf(pidfile, "%d\n", (int)getpid());
  1358. fclose(pidfile);
  1359. }
  1360. #endif
  1361. }