util.c 47 KB

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