buffers.c 45 KB

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