buffers.c 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson. */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. const char buffers_c_id[] =
  7. "$Id$";
  8. /**
  9. * \file buffers.c
  10. * \brief Implements a generic buffer interface. Buffers are
  11. * fairly opaque string holders that can read to or flush from:
  12. * memory, file descriptors, or TLS connections.
  13. **/
  14. #include "or.h"
  15. #define SENTINELS
  16. #undef CHECK_AFTER_RESIZE
  17. #undef PARANOIA
  18. #undef NOINLINE
  19. #ifdef SENTINELS
  20. /* If SENTINELS is defined, check for attempts to write beyond the
  21. * end/before the start of the buffer.
  22. */
  23. #define START_MAGIC 0x70370370u
  24. #define END_MAGIC 0xA0B0C0D0u
  25. #define RAW_MEM(m) ((void*)(((char*)m)-4))
  26. #define GUARDED_MEM(m) ((void*)(((char*)m)+4))
  27. #define ALLOC_LEN(ln) ((ln)+8)
  28. #define SET_GUARDS(m, ln) \
  29. do { set_uint32((m)-4,START_MAGIC); set_uint32((m)+ln,END_MAGIC); } while (0)
  30. #else
  31. #define RAW_MEM(m) (m)
  32. #define GUARDED_MEM(m) (m)
  33. #define ALLOC_LEN(ln) (ln)
  34. #define SET_GUARDS(m,ln) do {} while (0)
  35. #endif
  36. #ifdef PARANOIA
  37. #define check() do { assert_buf_ok(buf); } while (0)
  38. #else
  39. #define check() do { } while (0)
  40. #endif
  41. #ifdef NOINLINE
  42. #undef INLINE
  43. #define INLINE
  44. #endif
  45. #define BUFFER_MAGIC 0xB0FFF312u
  46. /** A resizeable buffer, optimized for reading and writing. */
  47. struct buf_t {
  48. uint32_t magic; /**< Magic cookie for debugging: Must be set to
  49. * BUFFER_MAGIC */
  50. char *mem; /**< Storage for data in the buffer */
  51. char *cur; /**< The first byte used for storing data in the buffer. */
  52. size_t highwater; /**< Largest observed datalen since last buf_shrink */
  53. size_t len; /**< Maximum amount of data that <b>mem</b> can hold. */
  54. size_t datalen; /**< Number of bytes currently in <b>mem</b>. */
  55. };
  56. uint64_t buf_total_used = 0;
  57. uint64_t buf_total_alloc = 0;
  58. /** Size, in bytes, for newly allocated buffers. Should be a power of 2. */
  59. #define INITIAL_BUF_SIZE (4*1024)
  60. /** Size, in bytes, for minimum 'shrink' size for buffers. Buffers may start
  61. * out smaller than this, but they will never autoshrink to less
  62. * than this size. */
  63. #define MIN_LAZY_SHRINK_SIZE (4*1024)
  64. static INLINE void peek_from_buf(char *string, size_t string_len, buf_t *buf);
  65. /** If the contents of buf wrap around the end of the allocated space,
  66. * malloc a new buf and copy the contents in starting at the
  67. * beginning. This operation is relatively expensive, so it shouldn't
  68. * be used e.g. for every single read or write.
  69. */
  70. static void
  71. buf_normalize(buf_t *buf)
  72. {
  73. check();
  74. if (buf->cur + buf->datalen <= buf->mem+buf->len) {
  75. return;
  76. } else {
  77. char *newmem, *oldmem;
  78. size_t sz = (buf->mem+buf->len)-buf->cur;
  79. log_warn(LD_BUG, "Unexpected non-normalized buffer.");
  80. newmem = GUARDED_MEM(tor_malloc(ALLOC_LEN(buf->len)));
  81. SET_GUARDS(newmem, buf->len);
  82. memcpy(newmem, buf->cur, sz);
  83. memcpy(newmem+sz, buf->mem, buf->datalen-sz);
  84. oldmem = RAW_MEM(buf->mem);
  85. tor_free(oldmem); /* Can't use tor_free directly. */
  86. buf->mem = buf->cur = newmem;
  87. check();
  88. }
  89. }
  90. /** Return the point in the buffer where the next byte will get stored. */
  91. static INLINE char *
  92. _buf_end(buf_t *buf)
  93. {
  94. char *next = buf->cur + buf->datalen;
  95. char *end = buf->mem + buf->len;
  96. return (next < end) ? next : (next - buf->len);
  97. }
  98. /** If the pointer <b>cp</b> has passed beyond the end of the buffer, wrap it
  99. * around. */
  100. static INLINE char *
  101. _wrap_ptr(buf_t *buf, char *cp)
  102. {
  103. return (cp >= buf->mem + buf->len) ? (cp - buf->len) : cp;
  104. }
  105. /** Return the offset of <b>cp</b> within the buffer. */
  106. static INLINE int
  107. _buf_offset(buf_t *buf, char *cp)
  108. {
  109. if (cp >= buf->cur)
  110. return cp - buf->cur;
  111. else
  112. /* return (cp - buf->mem) + buf->mem+buf->len - buf->cur */
  113. return cp + buf->len - buf->cur;
  114. }
  115. /** If the range of *<b>len</b> bytes starting at <b>at</b> wraps around the
  116. * end of the buffer, then set *<b>len</b> to the number of bytes starting
  117. * at <b>at</b>, and set *<b>more_len</b> to the number of bytes starting
  118. * at <b>buf-&gt;mem</b>. Otherwise, set *<b>more_len</b> to 0.
  119. */
  120. static INLINE void
  121. _split_range(buf_t *buf, char *at, size_t *len,
  122. size_t *more_len)
  123. {
  124. char *eos = at + *len;
  125. check();
  126. if (eos >= (buf->mem + buf->len)) {
  127. *more_len = eos - (buf->mem + buf->len);
  128. *len -= *more_len;
  129. } else {
  130. *more_len = 0;
  131. }
  132. }
  133. /** Change a buffer's capacity. <b>new_capacity</b> must be \>=
  134. * buf->datalen. */
  135. static void
  136. buf_resize(buf_t *buf, size_t new_capacity)
  137. {
  138. off_t offset;
  139. #ifdef CHECK_AFTER_RESIZE
  140. char *tmp, *tmp2;
  141. #endif
  142. tor_assert(buf->datalen <= new_capacity);
  143. tor_assert(new_capacity);
  144. #ifdef CHECK_AFTER_RESIZE
  145. assert_buf_ok(buf);
  146. tmp = tor_malloc(buf->datalen);
  147. tmp2 = tor_malloc(buf->datalen);
  148. peek_from_buf(tmp, buf->datalen, buf);
  149. #endif
  150. if (buf->len == new_capacity)
  151. return;
  152. offset = buf->cur - buf->mem;
  153. if (offset + buf->datalen > new_capacity) {
  154. /* We need to move stuff before we shrink. */
  155. if (offset + buf->datalen > buf->len) {
  156. /* We have:
  157. *
  158. * mem[0] ... mem[datalen-(len-offset)] (end of data)
  159. * mem[offset] ... mem[len-1] (the start of the data)
  160. *
  161. * We're shrinking the buffer by (len-new_capacity) bytes, so we need
  162. * to move the start portion back by that many bytes.
  163. */
  164. memmove(buf->cur-(buf->len-new_capacity), buf->cur,
  165. buf->len-offset);
  166. offset -= (buf->len-new_capacity);
  167. } else {
  168. /* The data doesn't wrap around, but it does extend beyond the new
  169. * buffer length:
  170. * mem[offset] ... mem[offset+datalen-1] (the data)
  171. */
  172. memmove(buf->mem, buf->cur, buf->datalen);
  173. offset = 0;
  174. }
  175. }
  176. /* XXX Some play code to throw away old buffers sometimes rather
  177. * than constantly reallocing them; just in case this is our memory
  178. * problem. It looks for now like it isn't, so disabled. -RD */
  179. if (0 && new_capacity == MIN_LAZY_SHRINK_SIZE &&
  180. !buf->datalen &&
  181. buf->len >= 1<<16) {
  182. /* don't realloc; free and malloc */
  183. char *oldmem, *newmem = GUARDED_MEM(tor_malloc(ALLOC_LEN(new_capacity)));
  184. SET_GUARDS(newmem, new_capacity);
  185. oldmem = RAW_MEM(buf->mem);
  186. tor_free(oldmem);
  187. buf->mem = buf->cur = newmem;
  188. } else {
  189. buf->mem = GUARDED_MEM(tor_realloc(RAW_MEM(buf->mem),
  190. ALLOC_LEN(new_capacity)));
  191. SET_GUARDS(buf->mem, new_capacity);
  192. buf->cur = buf->mem+offset;
  193. }
  194. buf_total_alloc += new_capacity;
  195. buf_total_alloc -= buf->len;
  196. if (offset + buf->datalen > buf->len) {
  197. /* We need to move data now that we are done growing. The buffer
  198. * now contains:
  199. *
  200. * mem[0] ... mem[datalen-(len-offset)] (end of data)
  201. * mem[offset] ... mem[len-1] (the start of the data)
  202. * mem[len]...mem[new_capacity] (empty space)
  203. *
  204. * We're growing by (new_capacity-len) bytes, so we need to move the
  205. * end portion forward by that many bytes.
  206. */
  207. memmove(buf->cur+(new_capacity-buf->len), buf->cur,
  208. buf->len-offset);
  209. buf->cur += new_capacity-buf->len;
  210. }
  211. buf->len = new_capacity;
  212. #ifdef CHECK_AFTER_RESIZE
  213. assert_buf_ok(buf);
  214. peek_from_buf(tmp2, buf->datalen, buf);
  215. if (memcmp(tmp, tmp2, buf->datalen)) {
  216. tor_assert(0);
  217. }
  218. tor_free(tmp);
  219. tor_free(tmp2);
  220. #endif
  221. }
  222. /** If the buffer is not large enough to hold <b>capacity</b> bytes, resize
  223. * it so that it can. (The new size will be a power of 2 times the old
  224. * size.)
  225. */
  226. static INLINE int
  227. buf_ensure_capacity(buf_t *buf, size_t capacity)
  228. {
  229. size_t new_len, min_len;
  230. if (buf->len >= capacity) /* Don't grow if we're already big enough. */
  231. return 0;
  232. if (capacity > MAX_BUF_SIZE) /* Don't grow past the maximum. */
  233. return -1;
  234. /* Find the smallest new_len equal to (2**X) for some X; such that
  235. * new_len is at least capacity, and at least 2*buf->len.
  236. */
  237. min_len = buf->len*2;
  238. new_len = 16;
  239. while (new_len < min_len)
  240. new_len *= 2;
  241. while (new_len < capacity)
  242. new_len *= 2;
  243. /* Resize the buffer. */
  244. log_debug(LD_MM,"Growing buffer from %d to %d bytes.",
  245. (int)buf->len, (int)new_len);
  246. buf_resize(buf,new_len);
  247. return 0;
  248. }
  249. /** Resize buf so it won't hold extra memory that we haven't been
  250. * using lately (that is, since the last time we called buf_shrink).
  251. * Try to shrink the buf until it is the largest factor of two that
  252. * can contain <b>buf</b>-&gt;highwater, but never smaller than
  253. * MIN_LAZY_SHRINK_SIZE.
  254. */
  255. void
  256. buf_shrink(buf_t *buf)
  257. {
  258. size_t new_len;
  259. new_len = buf->len;
  260. while (buf->highwater < (new_len>>2) && new_len > MIN_LAZY_SHRINK_SIZE*2)
  261. new_len >>= 1;
  262. buf->highwater = buf->datalen;
  263. if (new_len == buf->len)
  264. return;
  265. log_debug(LD_MM,"Shrinking buffer from %d to %d bytes.",
  266. (int)buf->len, (int)new_len);
  267. buf_resize(buf, new_len);
  268. }
  269. /** Remove the first <b>n</b> bytes from buf. */
  270. static INLINE void
  271. buf_remove_from_front(buf_t *buf, size_t n)
  272. {
  273. tor_assert(buf->datalen >= n);
  274. buf->datalen -= n;
  275. buf_total_used -= n;
  276. if (buf->datalen) {
  277. buf->cur = _wrap_ptr(buf, buf->cur+n);
  278. } else {
  279. buf->cur = buf->mem;
  280. }
  281. check();
  282. }
  283. /** Make sure that the memory in buf ends with a zero byte. */
  284. static INLINE int
  285. buf_nul_terminate(buf_t *buf)
  286. {
  287. if (buf_ensure_capacity(buf,buf->datalen+1)<0)
  288. return -1;
  289. *_buf_end(buf) = '\0';
  290. return 0;
  291. }
  292. /** Create and return a new buf with capacity <b>size</b>. */
  293. buf_t *
  294. buf_new_with_capacity(size_t size)
  295. {
  296. buf_t *buf;
  297. buf = tor_malloc_zero(sizeof(buf_t));
  298. buf->magic = BUFFER_MAGIC;
  299. buf->cur = buf->mem = GUARDED_MEM(tor_malloc(ALLOC_LEN(size)));
  300. SET_GUARDS(buf->mem, size);
  301. buf->len = size;
  302. buf_total_alloc += size;
  303. assert_buf_ok(buf);
  304. return buf;
  305. }
  306. /** Allocate and return a new buffer with default capacity. */
  307. buf_t *
  308. buf_new(void)
  309. {
  310. return buf_new_with_capacity(INITIAL_BUF_SIZE);
  311. }
  312. /** Remove all data from <b>buf</b>. */
  313. void
  314. buf_clear(buf_t *buf)
  315. {
  316. buf_total_used -= buf->datalen;
  317. buf->datalen = 0;
  318. buf->cur = buf->mem;
  319. }
  320. /** Return the number of bytes stored in <b>buf</b> */
  321. size_t
  322. buf_datalen(const buf_t *buf)
  323. {
  324. return buf->datalen;
  325. }
  326. /** Return the maximum bytes that can be stored in <b>buf</b> before buf
  327. * needs to resize. */
  328. size_t
  329. buf_capacity(const buf_t *buf)
  330. {
  331. return buf->len;
  332. }
  333. /** For testing only: Return a pointer to the raw memory stored in
  334. * <b>buf</b>. */
  335. const char *
  336. _buf_peek_raw_buffer(const buf_t *buf)
  337. {
  338. return buf->cur;
  339. }
  340. /** Release storage held by <b>buf</b>. */
  341. void
  342. buf_free(buf_t *buf)
  343. {
  344. char *oldmem;
  345. assert_buf_ok(buf);
  346. buf->magic = 0xDEADBEEF;
  347. oldmem = RAW_MEM(buf->mem);
  348. tor_free(oldmem);
  349. buf_total_alloc -= buf->len;
  350. buf_total_used -= buf->datalen;
  351. tor_free(buf);
  352. }
  353. /** Helper for read_to_buf(): read no more than at_most bytes from
  354. * socket s into buffer buf, starting at the position pos. (Does not
  355. * check for overflow.) Set *reached_eof to true on EOF. Return
  356. * number of bytes read on success, 0 if the read would block, -1 on
  357. * failure.
  358. */
  359. static INLINE int
  360. read_to_buf_impl(int s, size_t at_most, buf_t *buf,
  361. char *pos, int *reached_eof)
  362. {
  363. int read_result;
  364. // log_fn(LOG_DEBUG,"reading at most %d bytes.",at_most);
  365. read_result = recv(s, pos, at_most, 0);
  366. if (read_result < 0) {
  367. int e = tor_socket_errno(s);
  368. if (!ERRNO_IS_EAGAIN(e)) { /* it's a real error */
  369. #ifdef MS_WINDOWS
  370. if (e == WSAENOBUFS)
  371. log_warn(LD_NET,"recv() failed: WSAENOBUFS. Not enough ram?");
  372. #endif
  373. return -1;
  374. }
  375. return 0; /* would block. */
  376. } else if (read_result == 0) {
  377. log_debug(LD_NET,"Encountered eof");
  378. *reached_eof = 1;
  379. return 0;
  380. } else { /* we read some bytes */
  381. buf->datalen += read_result;
  382. buf_total_used += read_result;
  383. if (buf->datalen > buf->highwater)
  384. buf->highwater = buf->datalen;
  385. log_debug(LD_NET,"Read %d bytes. %d on inbuf.",read_result,
  386. (int)buf->datalen);
  387. return read_result;
  388. }
  389. }
  390. /** Read from socket <b>s</b>, writing onto end of <b>buf</b>. Read at most
  391. * <b>at_most</b> bytes, resizing the buffer as necessary. If recv()
  392. * returns 0, set *<b>reached_eof</b> to 1 and return 0. Return -1 on error;
  393. * else return the number of bytes read. Return 0 if recv() would
  394. * block.
  395. */
  396. int
  397. read_to_buf(int s, size_t at_most, buf_t *buf, int *reached_eof)
  398. {
  399. int r;
  400. char *next;
  401. size_t at_start;
  402. /* assert_buf_ok(buf); */
  403. tor_assert(reached_eof);
  404. tor_assert(s>=0);
  405. if (buf_ensure_capacity(buf,buf->datalen+at_most))
  406. return -1;
  407. if (at_most + buf->datalen > buf->len)
  408. at_most = buf->len - buf->datalen; /* take the min of the two */
  409. if (at_most == 0)
  410. return 0; /* we shouldn't read anything */
  411. next = _buf_end(buf);
  412. _split_range(buf, next, &at_most, &at_start);
  413. r = read_to_buf_impl(s, at_most, buf, next, reached_eof);
  414. check();
  415. if (r < 0 || (size_t)r < at_most) {
  416. return r; /* Either error, eof, block, or no more to read. */
  417. }
  418. if (at_start) {
  419. int r2;
  420. tor_assert(_buf_end(buf) == buf->mem);
  421. r2 = read_to_buf_impl(s, at_start, buf, buf->mem, reached_eof);
  422. check();
  423. if (r2 < 0) {
  424. return r2;
  425. } else {
  426. r += r2;
  427. }
  428. }
  429. return r;
  430. }
  431. /** Helper for read_to_buf_tls(): read no more than <b>at_most</b>
  432. * bytes from the TLS connection <b>tls</b> into buffer <b>buf</b>,
  433. * starting at the position <b>next</b>. (Does not check for overflow.)
  434. * Return number of bytes read on success, 0 if the read would block,
  435. * -1 on failure.
  436. */
  437. static INLINE int
  438. read_to_buf_tls_impl(tor_tls_t *tls, size_t at_most, buf_t *buf, char *next)
  439. {
  440. int r;
  441. log_debug(LD_NET,"before: %d on buf, %d pending, at_most %d.",
  442. (int)buf_datalen(buf), (int)tor_tls_get_pending_bytes(tls),
  443. (int)at_most);
  444. r = tor_tls_read(tls, next, at_most);
  445. if (r<0)
  446. return r;
  447. buf->datalen += r;
  448. buf_total_used += r;
  449. if (buf->datalen > buf->highwater)
  450. buf->highwater = buf->datalen;
  451. log_debug(LD_NET,"Read %d bytes. %d on inbuf; %d pending",r,
  452. (int)buf->datalen,(int)tor_tls_get_pending_bytes(tls));
  453. return r;
  454. }
  455. /** As read_to_buf, but reads from a TLS connection.
  456. *
  457. * Using TLS on OR connections complicates matters in two ways.
  458. *
  459. * First, a TLS stream has its own read buffer independent of the
  460. * connection's read buffer. (TLS needs to read an entire frame from
  461. * the network before it can decrypt any data. Thus, trying to read 1
  462. * byte from TLS can require that several KB be read from the network
  463. * and decrypted. The extra data is stored in TLS's decrypt buffer.)
  464. * Because the data hasn't been read by Tor (it's still inside the TLS),
  465. * this means that sometimes a connection "has stuff to read" even when
  466. * poll() didn't return POLLIN. The tor_tls_get_pending_bytes function is
  467. * used in connection.c to detect TLS objects with non-empty internal
  468. * buffers and read from them again.
  469. *
  470. * Second, the TLS stream's events do not correspond directly to network
  471. * events: sometimes, before a TLS stream can read, the network must be
  472. * ready to write -- or vice versa.
  473. */
  474. int
  475. read_to_buf_tls(tor_tls_t *tls, size_t at_most, buf_t *buf)
  476. {
  477. int r;
  478. char *next;
  479. size_t at_start;
  480. tor_assert(tls);
  481. assert_buf_ok(buf);
  482. log_debug(LD_NET,"start: %d on buf, %d pending, at_most %d.",
  483. (int)buf_datalen(buf), (int)tor_tls_get_pending_bytes(tls),
  484. (int)at_most);
  485. if (buf_ensure_capacity(buf, at_most+buf->datalen))
  486. return TOR_TLS_ERROR;
  487. if (at_most + buf->datalen > buf->len)
  488. at_most = buf->len - buf->datalen;
  489. if (at_most == 0)
  490. return 0;
  491. next = _buf_end(buf);
  492. _split_range(buf, next, &at_most, &at_start);
  493. r = read_to_buf_tls_impl(tls, at_most, buf, next);
  494. check();
  495. if (r < 0 || (size_t)r < at_most)
  496. return r; /* Either error, eof, block, or no more to read. */
  497. if (at_start) {
  498. int r2;
  499. tor_assert(_buf_end(buf) == buf->mem);
  500. r2 = read_to_buf_tls_impl(tls, at_start, buf, buf->mem);
  501. check();
  502. if (r2 < 0)
  503. return r2;
  504. else
  505. r += r2;
  506. }
  507. return r;
  508. }
  509. /** Helper for flush_buf(): try to write <b>sz</b> bytes from buffer
  510. * <b>buf</b> onto socket <b>s</b>. On success, deduct the bytes written
  511. * from *<b>buf_flushlen</b>.
  512. * Return the number of bytes written on success, -1 on failure.
  513. */
  514. static INLINE int
  515. flush_buf_impl(int s, buf_t *buf, size_t sz, size_t *buf_flushlen)
  516. {
  517. int write_result;
  518. write_result = send(s, buf->cur, sz, 0);
  519. if (write_result < 0) {
  520. int e = tor_socket_errno(s);
  521. if (!ERRNO_IS_EAGAIN(e)) { /* it's a real error */
  522. #ifdef MS_WINDOWS
  523. if (e == WSAENOBUFS)
  524. log_warn(LD_NET,"write() failed: WSAENOBUFS. Not enough ram?");
  525. #endif
  526. return -1;
  527. }
  528. log_debug(LD_NET,"write() would block, returning.");
  529. return 0;
  530. } else {
  531. *buf_flushlen -= write_result;
  532. buf_remove_from_front(buf, write_result);
  533. return write_result;
  534. }
  535. }
  536. /** Write data from <b>buf</b> to the socket <b>s</b>. Write at most
  537. * <b>sz</b> bytes, decrement *<b>buf_flushlen</b> by
  538. * the number of bytes actually written, and remove the written bytes
  539. * from the buffer. Return the number of bytes written on success,
  540. * -1 on failure. Return 0 if write() would block.
  541. */
  542. int
  543. flush_buf(int s, buf_t *buf, size_t sz, size_t *buf_flushlen)
  544. {
  545. int r;
  546. size_t flushed = 0;
  547. size_t flushlen0, flushlen1;
  548. /* assert_buf_ok(buf); */
  549. tor_assert(buf_flushlen);
  550. tor_assert(s>=0);
  551. tor_assert(*buf_flushlen <= buf->datalen);
  552. tor_assert(sz <= *buf_flushlen);
  553. if (sz == 0) /* nothing to flush */
  554. return 0;
  555. flushlen0 = sz;
  556. _split_range(buf, buf->cur, &flushlen0, &flushlen1);
  557. r = flush_buf_impl(s, buf, flushlen0, buf_flushlen);
  558. check();
  559. log_debug(LD_NET,"%d: flushed %d bytes, %d ready to flush, %d remain.",
  560. s,r,(int)*buf_flushlen,(int)buf->datalen);
  561. if (r < 0 || (size_t)r < flushlen0)
  562. return r; /* Error, or can't flush any more now. */
  563. flushed = r;
  564. if (flushlen1) {
  565. tor_assert(buf->cur == buf->mem);
  566. r = flush_buf_impl(s, buf, flushlen1, buf_flushlen);
  567. check();
  568. log_debug(LD_NET,"%d: flushed %d bytes, %d ready to flush, %d remain.",
  569. s,r,(int)*buf_flushlen,(int)buf->datalen);
  570. if (r<0)
  571. return r;
  572. flushed += r;
  573. }
  574. return flushed;
  575. }
  576. /** Helper for flush_buf_tls(): try to write <b>sz</b> bytes from buffer
  577. * <b>buf</b> onto TLS object <b>tls</b>. On success, deduct the bytes
  578. * written from *<b>buf_flushlen</b>.
  579. * Return the number of bytes written on success, -1 on failure.
  580. */
  581. static INLINE int
  582. flush_buf_tls_impl(tor_tls_t *tls, buf_t *buf, size_t sz, size_t *buf_flushlen)
  583. {
  584. int r;
  585. r = tor_tls_write(tls, buf->cur, sz);
  586. if (r < 0) {
  587. return r;
  588. }
  589. *buf_flushlen -= r;
  590. buf_remove_from_front(buf, r);
  591. log_debug(LD_NET,"flushed %d bytes, %d ready to flush, %d remain.",
  592. r,(int)*buf_flushlen,(int)buf->datalen);
  593. return r;
  594. }
  595. /** As flush_buf(), but writes data to a TLS connection.
  596. */
  597. int
  598. flush_buf_tls(tor_tls_t *tls, buf_t *buf, size_t sz, size_t *buf_flushlen)
  599. {
  600. int r;
  601. size_t flushed=0;
  602. size_t flushlen0, flushlen1;
  603. /* assert_buf_ok(buf); */
  604. tor_assert(tls);
  605. tor_assert(buf_flushlen);
  606. tor_assert(*buf_flushlen <= buf->datalen);
  607. tor_assert(sz <= *buf_flushlen);
  608. /* we want to let tls write even if flushlen is zero, because it might
  609. * have a partial record pending */
  610. check_no_tls_errors();
  611. flushlen0 = sz;
  612. _split_range(buf, buf->cur, &flushlen0, &flushlen1);
  613. r = flush_buf_tls_impl(tls, buf, flushlen0, buf_flushlen);
  614. check();
  615. if (r < 0 || (size_t)r < flushlen0)
  616. return r; /* Error, or can't flush any more now. */
  617. flushed = r;
  618. if (flushlen1) {
  619. tor_assert(buf->cur == buf->mem);
  620. r = flush_buf_tls_impl(tls, buf, flushlen1, buf_flushlen);
  621. check();
  622. if (r<0)
  623. return r;
  624. flushed += r;
  625. }
  626. return flushed;
  627. }
  628. /** Append <b>string_len</b> bytes from <b>string</b> to the end of
  629. * <b>buf</b>.
  630. *
  631. * Return the new length of the buffer on success, -1 on failure.
  632. */
  633. int
  634. write_to_buf(const char *string, size_t string_len, buf_t *buf)
  635. {
  636. char *next;
  637. size_t len2;
  638. /* append string to buf (growing as needed, return -1 if "too big")
  639. * return total number of bytes on the buf
  640. */
  641. tor_assert(string);
  642. /* assert_buf_ok(buf); */
  643. if (buf_ensure_capacity(buf, buf->datalen+string_len)) {
  644. log_warn(LD_MM, "buflen too small, can't hold %d bytes.",
  645. (int)(buf->datalen+string_len));
  646. return -1;
  647. }
  648. next = _buf_end(buf);
  649. _split_range(buf, next, &string_len, &len2);
  650. memcpy(next, string, string_len);
  651. buf->datalen += string_len;
  652. buf_total_used += string_len;
  653. if (len2) {
  654. tor_assert(_buf_end(buf) == buf->mem);
  655. memcpy(buf->mem, string+string_len, len2);
  656. buf->datalen += len2;
  657. buf_total_used += len2;
  658. }
  659. if (buf->datalen > buf->highwater)
  660. buf->highwater = buf->datalen;
  661. log_debug(LD_NET,"added %d bytes to buf (now %d total).",
  662. (int)string_len, (int)buf->datalen);
  663. check();
  664. return buf->datalen;
  665. }
  666. /** Helper: copy the first <b>string_len</b> bytes from <b>buf</b>
  667. * onto <b>string</b>.
  668. */
  669. static INLINE void
  670. peek_from_buf(char *string, size_t string_len, buf_t *buf)
  671. {
  672. size_t len2;
  673. /* There must be string_len bytes in buf; write them onto string,
  674. * then memmove buf back (that is, remove them from buf).
  675. *
  676. * Return the number of bytes still on the buffer. */
  677. tor_assert(string);
  678. /* make sure we don't ask for too much */
  679. tor_assert(string_len <= buf->datalen);
  680. /* assert_buf_ok(buf); */
  681. _split_range(buf, buf->cur, &string_len, &len2);
  682. memcpy(string, buf->cur, string_len);
  683. if (len2) {
  684. memcpy(string+string_len,buf->mem,len2);
  685. }
  686. }
  687. /** Remove <b>string_len</b> bytes from the front of <b>buf</b>, and store
  688. * them into <b>string</b>. Return the new buffer size. <b>string_len</b>
  689. * must be \<= the number of bytes on the buffer.
  690. */
  691. int
  692. fetch_from_buf(char *string, size_t string_len, buf_t *buf)
  693. {
  694. /* There must be string_len bytes in buf; write them onto string,
  695. * then memmove buf back (that is, remove them from buf).
  696. *
  697. * Return the number of bytes still on the buffer. */
  698. check();
  699. peek_from_buf(string, string_len, buf);
  700. buf_remove_from_front(buf, string_len);
  701. check();
  702. return buf->datalen;
  703. }
  704. /** There is a (possibly incomplete) http statement on <b>buf</b>, of the
  705. * form "\%s\\r\\n\\r\\n\%s", headers, body. (body may contain nuls.)
  706. * If a) the headers include a Content-Length field and all bytes in
  707. * the body are present, or b) there's no Content-Length field and
  708. * all headers are present, then:
  709. *
  710. * - strdup headers into <b>*headers_out</b>, and nul-terminate it.
  711. * - memdup body into <b>*body_out</b>, and nul-terminate it.
  712. * - Then remove them from <b>buf</b>, and return 1.
  713. *
  714. * - If headers or body is NULL, discard that part of the buf.
  715. * - If a headers or body doesn't fit in the arg, return -1.
  716. * (We ensure that the headers or body don't exceed max len,
  717. * _even if_ we're planning to discard them.)
  718. * - If force_complete is true, then succeed even if not all of the
  719. * content has arrived.
  720. *
  721. * Else, change nothing and return 0.
  722. */
  723. int
  724. fetch_from_buf_http(buf_t *buf,
  725. char **headers_out, size_t max_headerlen,
  726. char **body_out, size_t *body_used, size_t max_bodylen,
  727. int force_complete)
  728. {
  729. char *headers, *body, *p;
  730. size_t headerlen, bodylen, contentlen;
  731. /* assert_buf_ok(buf); */
  732. buf_normalize(buf);
  733. if (buf_nul_terminate(buf)<0) {
  734. log_warn(LD_BUG,"Couldn't nul-terminate buffer");
  735. return -1;
  736. }
  737. headers = buf->cur;
  738. body = strstr(headers,"\r\n\r\n");
  739. if (!body) {
  740. log_debug(LD_HTTP,"headers not all here yet.");
  741. return 0;
  742. }
  743. body += 4; /* Skip the the CRLFCRLF */
  744. headerlen = body-headers; /* includes the CRLFCRLF */
  745. bodylen = buf->datalen - headerlen;
  746. log_debug(LD_HTTP,"headerlen %d, bodylen %d.", (int)headerlen, (int)bodylen);
  747. if (max_headerlen <= headerlen) {
  748. log_warn(LD_HTTP,"headerlen %d larger than %d. Failing.",
  749. (int)headerlen, (int)max_headerlen-1);
  750. return -1;
  751. }
  752. if (max_bodylen <= bodylen) {
  753. log_warn(LD_HTTP,"bodylen %d larger than %d. Failing.",
  754. (int)bodylen, (int)max_bodylen-1);
  755. return -1;
  756. }
  757. #define CONTENT_LENGTH "\r\nContent-Length: "
  758. p = strstr(headers, CONTENT_LENGTH);
  759. if (p) {
  760. int i;
  761. i = atoi(p+strlen(CONTENT_LENGTH));
  762. if (i < 0) {
  763. log_warn(LD_PROTOCOL, "Content-Length is less than zero; it looks like "
  764. "someone is trying to crash us.");
  765. return -1;
  766. }
  767. contentlen = i;
  768. /* if content-length is malformed, then our body length is 0. fine. */
  769. log_debug(LD_HTTP,"Got a contentlen of %d.",(int)contentlen);
  770. if (bodylen < contentlen) {
  771. if (!force_complete) {
  772. log_debug(LD_HTTP,"body not all here yet.");
  773. return 0; /* not all there yet */
  774. }
  775. }
  776. if (bodylen > contentlen) {
  777. bodylen = contentlen;
  778. log_debug(LD_HTTP,"bodylen reduced to %d.",(int)bodylen);
  779. }
  780. }
  781. /* all happy. copy into the appropriate places, and return 1 */
  782. if (headers_out) {
  783. *headers_out = tor_malloc(headerlen+1);
  784. memcpy(*headers_out,buf->cur,headerlen);
  785. (*headers_out)[headerlen] = 0; /* null terminate it */
  786. }
  787. if (body_out) {
  788. tor_assert(body_used);
  789. *body_used = bodylen;
  790. *body_out = tor_malloc(bodylen+1);
  791. memcpy(*body_out,buf->cur+headerlen,bodylen);
  792. (*body_out)[bodylen] = 0; /* null terminate it */
  793. }
  794. buf_remove_from_front(buf, headerlen+bodylen);
  795. return 1;
  796. }
  797. /** There is a (possibly incomplete) socks handshake on <b>buf</b>, of one
  798. * of the forms
  799. * - socks4: "socksheader username\\0"
  800. * - socks4a: "socksheader username\\0 destaddr\\0"
  801. * - socks5 phase one: "version #methods methods"
  802. * - socks5 phase two: "version command 0 addresstype..."
  803. * If it's a complete and valid handshake, and destaddr fits in
  804. * MAX_SOCKS_ADDR_LEN bytes, then pull the handshake off the buf,
  805. * assign to <b>req</b>, and return 1.
  806. *
  807. * If it's invalid or too big, return -1.
  808. *
  809. * Else it's not all there yet, leave buf alone and return 0.
  810. *
  811. * If you want to specify the socks reply, write it into <b>req->reply</b>
  812. * and set <b>req->replylen</b>, else leave <b>req->replylen</b> alone.
  813. *
  814. * If <b>log_sockstype</b> is non-zero, then do a notice-level log of whether
  815. * the connection is possibly leaking DNS requests locally or not.
  816. *
  817. * If <b>safe_socks</b> is true, then reject unsafe socks protocols.
  818. *
  819. * If returning 0 or -1, <b>req->address</b> and <b>req->port</b> are
  820. * undefined.
  821. */
  822. int
  823. fetch_from_buf_socks(buf_t *buf, socks_request_t *req,
  824. int log_sockstype, int safe_socks)
  825. {
  826. unsigned char len;
  827. char tmpbuf[INET_NTOA_BUF_LEN];
  828. uint32_t destip;
  829. enum {socks4, socks4a} socks4_prot = socks4a;
  830. char *next, *startaddr;
  831. struct in_addr in;
  832. /* If the user connects with socks4 or the wrong variant of socks5,
  833. * then log a warning to let him know that it might be unwise. */
  834. static int have_warned_about_unsafe_socks = 0;
  835. if (buf->datalen < 2) /* version and another byte */
  836. return 0;
  837. buf_normalize(buf);
  838. switch (*(buf->cur)) { /* which version of socks? */
  839. case 5: /* socks5 */
  840. if (req->socks_version != 5) { /* we need to negotiate a method */
  841. unsigned char nummethods = (unsigned char)*(buf->cur+1);
  842. tor_assert(!req->socks_version);
  843. if (buf->datalen < 2u+nummethods)
  844. return 0;
  845. if (!nummethods || !memchr(buf->cur+2, 0, nummethods)) {
  846. log_warn(LD_APP,
  847. "socks5: offered methods don't include 'no auth'. "
  848. "Rejecting.");
  849. req->replylen = 2; /* 2 bytes of response */
  850. req->reply[0] = 5;
  851. req->reply[1] = '\xFF'; /* reject all methods */
  852. return -1;
  853. }
  854. buf_remove_from_front(buf,2+nummethods); /* remove packet from buf */
  855. req->replylen = 2; /* 2 bytes of response */
  856. req->reply[0] = 5; /* socks5 reply */
  857. req->reply[1] = SOCKS5_SUCCEEDED;
  858. req->socks_version = 5; /* remember we've already negotiated auth */
  859. log_debug(LD_APP,"socks5: accepted method 0");
  860. return 0;
  861. }
  862. /* we know the method; read in the request */
  863. log_debug(LD_APP,"socks5: checking request");
  864. if (buf->datalen < 8) /* basic info plus >=2 for addr plus 2 for port */
  865. return 0; /* not yet */
  866. req->command = (unsigned char) *(buf->cur+1);
  867. if (req->command != SOCKS_COMMAND_CONNECT &&
  868. req->command != SOCKS_COMMAND_RESOLVE) {
  869. /* not a connect or resolve? we don't support it. */
  870. log_warn(LD_APP,"socks5: command %d not recognized. Rejecting.",
  871. req->command);
  872. return -1;
  873. }
  874. switch (*(buf->cur+3)) { /* address type */
  875. case 1: /* IPv4 address */
  876. log_debug(LD_APP,"socks5: ipv4 address type");
  877. if (buf->datalen < 10) /* ip/port there? */
  878. return 0; /* not yet */
  879. destip = ntohl(*(uint32_t*)(buf->cur+4));
  880. in.s_addr = htonl(destip);
  881. tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
  882. if (strlen(tmpbuf)+1 > MAX_SOCKS_ADDR_LEN) {
  883. log_warn(LD_APP,
  884. "socks5 IP takes %d bytes, which doesn't fit in %d. "
  885. "Rejecting.",
  886. (int)strlen(tmpbuf)+1,(int)MAX_SOCKS_ADDR_LEN);
  887. return -1;
  888. }
  889. strlcpy(req->address,tmpbuf,sizeof(req->address));
  890. req->port = ntohs(*(uint16_t*)(buf->cur+8));
  891. buf_remove_from_front(buf, 10);
  892. if (!address_is_in_virtual_range(req->address) &&
  893. !have_warned_about_unsafe_socks) {
  894. log_warn(LD_APP,
  895. "Your application (using socks5 on port %d) is giving "
  896. "Tor only an IP address. Applications that do DNS resolves "
  897. "themselves may leak information. Consider using Socks4A "
  898. "(e.g. via privoxy or socat) instead. For more information, "
  899. "please see http://wiki.noreply.org/noreply/TheOnionRouter/"
  900. "TorFAQ#SOCKSAndDNS.%s", req->port,
  901. safe_socks ? " Rejecting." : "");
  902. // have_warned_about_unsafe_socks = 1; // (for now, warn every time)
  903. if (safe_socks)
  904. return -1;
  905. }
  906. return 1;
  907. case 3: /* fqdn */
  908. log_debug(LD_APP,"socks5: fqdn address type");
  909. len = (unsigned char)*(buf->cur+4);
  910. if (buf->datalen < 7u+len) /* addr/port there? */
  911. return 0; /* not yet */
  912. if (len+1 > MAX_SOCKS_ADDR_LEN) {
  913. log_warn(LD_APP,
  914. "socks5 hostname is %d bytes, which doesn't fit in "
  915. "%d. Rejecting.", len+1,MAX_SOCKS_ADDR_LEN);
  916. return -1;
  917. }
  918. memcpy(req->address,buf->cur+5,len);
  919. req->address[len] = 0;
  920. req->port = ntohs(get_uint16(buf->cur+5+len));
  921. buf_remove_from_front(buf, 5+len+2);
  922. if (!tor_strisprint(req->address) || strchr(req->address,'\"')) {
  923. log_warn(LD_PROTOCOL,
  924. "Your application (using socks5 on port %d) gave Tor "
  925. "a malformed hostname: %s. Rejecting the connection.",
  926. req->port, escaped(req->address));
  927. return -1;
  928. }
  929. if (log_sockstype)
  930. log_notice(LD_APP,
  931. "Your application (using socks5 on port %d) gave "
  932. "Tor a hostname, which means Tor will do the DNS resolve "
  933. "for you. This is good.", req->port);
  934. return 1;
  935. default: /* unsupported */
  936. log_warn(LD_APP,"socks5: unsupported address type %d. Rejecting.",
  937. *(buf->cur+3));
  938. return -1;
  939. }
  940. tor_assert(0);
  941. case 4: /* socks4 */
  942. /* http://archive.socks.permeo.com/protocol/socks4.protocol */
  943. /* http://archive.socks.permeo.com/protocol/socks4a.protocol */
  944. req->socks_version = 4;
  945. if (buf->datalen < SOCKS4_NETWORK_LEN) /* basic info available? */
  946. return 0; /* not yet */
  947. req->command = (unsigned char) *(buf->cur+1);
  948. if (req->command != SOCKS_COMMAND_CONNECT &&
  949. req->command != SOCKS_COMMAND_RESOLVE) {
  950. /* not a connect or resolve? we don't support it. */
  951. log_warn(LD_APP,"socks4: command %d not recognized. Rejecting.",
  952. req->command);
  953. return -1;
  954. }
  955. req->port = ntohs(*(uint16_t*)(buf->cur+2));
  956. destip = ntohl(*(uint32_t*)(buf->mem+4));
  957. if ((!req->port && req->command!=SOCKS_COMMAND_RESOLVE) || !destip) {
  958. log_warn(LD_APP,"socks4: Port or DestIP is zero. Rejecting.");
  959. return -1;
  960. }
  961. if (destip >> 8) {
  962. log_debug(LD_APP,"socks4: destip not in form 0.0.0.x.");
  963. in.s_addr = htonl(destip);
  964. tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
  965. if (strlen(tmpbuf)+1 > MAX_SOCKS_ADDR_LEN) {
  966. log_debug(LD_APP,"socks4 addr (%d bytes) too long. Rejecting.",
  967. (int)strlen(tmpbuf));
  968. return -1;
  969. }
  970. log_debug(LD_APP,
  971. "socks4: successfully read destip (%s)", safe_str(tmpbuf));
  972. socks4_prot = socks4;
  973. }
  974. next = memchr(buf->cur+SOCKS4_NETWORK_LEN, 0,
  975. buf->datalen-SOCKS4_NETWORK_LEN);
  976. if (!next) {
  977. log_debug(LD_APP,"socks4: Username not here yet.");
  978. return 0;
  979. }
  980. tor_assert(next < buf->cur+buf->datalen);
  981. startaddr = NULL;
  982. if (socks4_prot != socks4a &&
  983. !address_is_in_virtual_range(tmpbuf) &&
  984. !have_warned_about_unsafe_socks) {
  985. log_warn(LD_APP,
  986. "Your application (using socks4 on port %d) is giving Tor "
  987. "only an IP address. Applications that do DNS resolves "
  988. "themselves may leak information. Consider using Socks4A "
  989. "(e.g. via privoxy or socat) instead. For more information, "
  990. "please see http://wiki.noreply.org/noreply/TheOnionRouter/"
  991. "TorFAQ#SOCKSAndDNS.%s", req->port,
  992. safe_socks ? " Rejecting." : "");
  993. // have_warned_about_unsafe_socks = 1; // (for now, warn every time)
  994. if (safe_socks)
  995. return -1;
  996. }
  997. if (socks4_prot == socks4a) {
  998. if (next+1 == buf->cur+buf->datalen) {
  999. log_debug(LD_APP,"socks4: No part of destaddr here yet.");
  1000. return 0;
  1001. }
  1002. startaddr = next+1;
  1003. next = memchr(startaddr, 0, buf->cur+buf->datalen-startaddr);
  1004. if (!next) {
  1005. log_debug(LD_APP,"socks4: Destaddr not all here yet.");
  1006. return 0;
  1007. }
  1008. if (MAX_SOCKS_ADDR_LEN <= next-startaddr) {
  1009. log_warn(LD_APP,"socks4: Destaddr too long. Rejecting.");
  1010. return -1;
  1011. }
  1012. tor_assert(next < buf->cur+buf->datalen);
  1013. if (log_sockstype)
  1014. log_notice(LD_APP,
  1015. "Your application (using socks4a on port %d) gave "
  1016. "Tor a hostname, which means Tor will do the DNS resolve "
  1017. "for you. This is good.", req->port);
  1018. }
  1019. log_debug(LD_APP,"socks4: Everything is here. Success.");
  1020. strlcpy(req->address, startaddr ? startaddr : tmpbuf,
  1021. sizeof(req->address));
  1022. if (!tor_strisprint(req->address) || strchr(req->address,'\"')) {
  1023. log_warn(LD_PROTOCOL,
  1024. "Your application (using socks4 on port %d) gave Tor "
  1025. "a malformed hostname: %s. Rejecting the connection.",
  1026. req->port, escaped(req->address));
  1027. return -1;
  1028. }
  1029. /* next points to the final \0 on inbuf */
  1030. buf_remove_from_front(buf, next-buf->cur+1);
  1031. return 1;
  1032. case 'G': /* get */
  1033. case 'H': /* head */
  1034. case 'P': /* put/post */
  1035. case 'C': /* connect */
  1036. strlcpy(req->reply,
  1037. "HTTP/1.0 501 Tor is not an HTTP Proxy\r\n"
  1038. "Content-Type: text/html; charset=iso-8859-1\r\n\r\n"
  1039. "<html>\n"
  1040. "<head>\n"
  1041. "<title>Tor is not an HTTP Proxy</title>\n"
  1042. "</head>\n"
  1043. "<body>\n"
  1044. "<h1>Tor is not an HTTP Proxy</h1>\n"
  1045. "<p>\n"
  1046. "It appears you have configured your web browser to use Tor as an HTTP proxy."
  1047. "\n"
  1048. "This is not correct: Tor is a SOCKS proxy, not an HTTP proxy.\n"
  1049. "Please configure your client accordingly.\n"
  1050. "</p>\n"
  1051. "<p>\n"
  1052. "See <a href=\"http://tor.eff.org/documentation.html\">"
  1053. "http://tor.eff.org/documentation.html</a> for more information.\n"
  1054. "<!-- Plus this comment, to make the body response more than 512 bytes, so "
  1055. " IE will be willing to display it. Comment comment comment comment "
  1056. " comment comment comment comment comment comment comment comment.-->\n"
  1057. "</p>\n"
  1058. "</body>\n"
  1059. "</html>\n"
  1060. , MAX_SOCKS_REPLY_LEN);
  1061. req->replylen = strlen(req->reply)+1;
  1062. /* fall through */
  1063. default: /* version is not socks4 or socks5 */
  1064. log_warn(LD_APP,
  1065. "Socks version %d not recognized. (Tor is not an http proxy.)",
  1066. *(buf->cur));
  1067. return -1;
  1068. }
  1069. }
  1070. /** If there is a complete version 0 control message waiting on buf, then store
  1071. * its contents into *<b>type_out</b>, store its body's length into
  1072. * *<b>len_out</b>, allocate and store a string for its body into
  1073. * *<b>body_out</b>, and return 1. (body_out will always be NUL-terminated,
  1074. * even if the control message body doesn't end with NUL.)
  1075. *
  1076. * If there is not a complete control message waiting, return 0.
  1077. *
  1078. * Return -1 on error; return -2 on "seems to be control protocol v1."
  1079. */
  1080. int
  1081. fetch_from_buf_control0(buf_t *buf, uint32_t *len_out, uint16_t *type_out,
  1082. char **body_out, int check_for_v1)
  1083. {
  1084. uint32_t msglen;
  1085. uint16_t type;
  1086. char tmp[4];
  1087. tor_assert(buf);
  1088. tor_assert(len_out);
  1089. tor_assert(type_out);
  1090. tor_assert(body_out);
  1091. *len_out = 0;
  1092. *body_out = NULL;
  1093. if (buf->datalen < 4)
  1094. return 0;
  1095. peek_from_buf(tmp, 4, buf);
  1096. msglen = ntohs(get_uint16(tmp));
  1097. type = ntohs(get_uint16(tmp+2));
  1098. if (type > 255 && check_for_v1)
  1099. return -2;
  1100. if (buf->datalen < 4 + (unsigned)msglen)
  1101. return 0;
  1102. *len_out = msglen;
  1103. *type_out = type;
  1104. buf_remove_from_front(buf, 4);
  1105. if (msglen) {
  1106. *body_out = tor_malloc(msglen+1);
  1107. fetch_from_buf(*body_out, msglen, buf);
  1108. (*body_out)[msglen] = '\0';
  1109. }
  1110. return 1;
  1111. }
  1112. /** Helper: return a pointer to the first instance of <b>c</b> in the
  1113. * <b>len</b>characters after <b>start</b> on <b>buf</b>. Return NULL if the
  1114. * character isn't found. */
  1115. static char *
  1116. find_char_on_buf(buf_t *buf, char *start, size_t len, char c)
  1117. {
  1118. size_t len_rest;
  1119. char *cp;
  1120. _split_range(buf, start, &len, &len_rest);
  1121. cp = memchr(buf->cur, c, len);
  1122. if (cp || !len_rest)
  1123. return cp;
  1124. return memchr(buf->mem, c, len_rest);
  1125. }
  1126. /** Helper: return a pointer to the first CRLF after cp on <b>buf</b>. Return
  1127. * NULL if no CRLF is found. */
  1128. static char *
  1129. find_crlf_on_buf(buf_t *buf, char *cp)
  1130. {
  1131. char *next;
  1132. while (1) {
  1133. size_t remaining = buf->datalen - _buf_offset(buf,cp);
  1134. cp = find_char_on_buf(buf, cp, remaining, '\r');
  1135. if (!cp)
  1136. return NULL;
  1137. next = _wrap_ptr(buf, cp+1);
  1138. if (next == _buf_end(buf))
  1139. return NULL;
  1140. if (*next == '\n')
  1141. return cp;
  1142. cp = next;
  1143. }
  1144. }
  1145. /** Try to read a single CRLF-terminated line from <b>buf</b>, and write it,
  1146. * NUL-terminated, into the *<b>data_len</b> byte buffer at <b>data_out</b>.
  1147. * Set *<b>data_len</b> to the number of bytes in the line, not counting the
  1148. * terminating NUL. Return 1 if we read a whole line, return 0 if we don't
  1149. * have a whole line yet, and return -1 if we we need to grow the buffer.
  1150. */
  1151. int
  1152. fetch_from_buf_line(buf_t *buf, char *data_out, size_t *data_len)
  1153. {
  1154. char *eol;
  1155. size_t sz;
  1156. /* Look for a CRLF. */
  1157. if (!(eol = find_crlf_on_buf(buf, buf->cur))) {
  1158. return 0;
  1159. }
  1160. sz = _buf_offset(buf, eol);
  1161. if (sz+3 > *data_len) {
  1162. *data_len = sz+3;
  1163. return -1;
  1164. }
  1165. fetch_from_buf(data_out, sz+2, buf);
  1166. data_out[sz+2] = '\0';
  1167. *data_len = sz+2;
  1168. return 1;
  1169. }
  1170. /** DOCDOC */
  1171. int
  1172. write_to_buf_zlib(buf_t *buf, tor_zlib_state_t *state,
  1173. const char *data, size_t data_len,
  1174. int done)
  1175. {
  1176. char *next;
  1177. size_t old_avail, avail;
  1178. while (1) {
  1179. buf_ensure_capacity(buf, buf->datalen + 1024);
  1180. next = _buf_end(buf);
  1181. if (next < buf->cur)
  1182. old_avail = avail = buf->cur - next;
  1183. else
  1184. old_avail = avail = (buf->mem + buf->datalen) - buf->cur;
  1185. switch (tor_zlib_process(state, &next, &avail, &data, &data_len, done)) {
  1186. case TOR_ZLIB_DONE:
  1187. return 0;
  1188. case TOR_ZLIB_ERR:
  1189. return -1;
  1190. case TOR_ZLIB_OK:
  1191. if (data_len == 0)
  1192. return 0;
  1193. break;
  1194. case TOR_ZLIB_BUF_FULL:
  1195. if (avail && buf->len >= 1024 + buf->datalen) {
  1196. /* Zlib says we need more room (ZLIB_BUF_FULL), and we're not about
  1197. * to wrap around (avail != 0), and resizing won't actually make us
  1198. * un-full: we're at the end of the buffer, and zlib refuses to
  1199. * append more here, but there's a pile of free space at the start
  1200. * of the buffer (about 1K). So chop a few characters off the
  1201. * end of the buffer. This feels silly; anybody got a better hack?
  1202. *
  1203. * (We don't just want to expand the buffer nevertheless. Consider a
  1204. * 1/3 full buffer with a single byte free at the end. zlib will
  1205. * often refuse to append to that, and so we want to use the
  1206. * beginning, not double the buffer to be just 1/6 full.)
  1207. */
  1208. tor_assert(next >= buf->cur);
  1209. buf->len -= avail;
  1210. }
  1211. break;
  1212. }
  1213. buf->datalen += old_avail - avail;
  1214. if (buf->datalen > buf->highwater)
  1215. buf->highwater = buf->datalen;
  1216. buf_total_used += old_avail - avail;
  1217. }
  1218. }
  1219. /** Log an error and exit if <b>buf</b> is corrupted.
  1220. */
  1221. void
  1222. assert_buf_ok(buf_t *buf)
  1223. {
  1224. tor_assert(buf);
  1225. tor_assert(buf->magic == BUFFER_MAGIC);
  1226. tor_assert(buf->mem);
  1227. tor_assert(buf->highwater <= buf->len);
  1228. tor_assert(buf->datalen <= buf->highwater);
  1229. #ifdef SENTINELS
  1230. {
  1231. uint32_t u32 = get_uint32(buf->mem - 4);
  1232. tor_assert(u32 == START_MAGIC);
  1233. u32 = get_uint32(buf->mem + buf->len);
  1234. tor_assert(u32 == END_MAGIC);
  1235. }
  1236. #endif
  1237. }