buffers.c 44 KB

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