util.c 41 KB

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