util.c 48 KB

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