util.c 43 KB

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