buffers.c 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445
  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. /** If there is a complete version 0 control message waiting on buf, then store
  1123. * its contents into *<b>type_out</b>, store its body's length into
  1124. * *<b>len_out</b>, allocate and store a string for its body into
  1125. * *<b>body_out</b>, and return 1. (body_out will always be NUL-terminated,
  1126. * even if the control message body doesn't end with NUL.)
  1127. *
  1128. * If there is not a complete control message waiting, return 0.
  1129. *
  1130. * Return -1 on error; return -2 on "seems to be control protocol v1."
  1131. */
  1132. int
  1133. fetch_from_buf_control0(buf_t *buf, uint32_t *len_out, uint16_t *type_out,
  1134. char **body_out, int check_for_v1)
  1135. {
  1136. uint32_t msglen;
  1137. uint16_t type;
  1138. char tmp[4];
  1139. tor_assert(buf);
  1140. tor_assert(len_out);
  1141. tor_assert(type_out);
  1142. tor_assert(body_out);
  1143. *len_out = 0;
  1144. *body_out = NULL;
  1145. if (buf->datalen < 4)
  1146. return 0;
  1147. peek_from_buf(tmp, 4, buf);
  1148. msglen = ntohs(get_uint16(tmp));
  1149. type = ntohs(get_uint16(tmp+2));
  1150. if (type > 255 && check_for_v1)
  1151. return -2;
  1152. if (buf->datalen < 4 + (unsigned)msglen)
  1153. return 0;
  1154. *len_out = msglen;
  1155. *type_out = type;
  1156. buf_remove_from_front(buf, 4);
  1157. if (msglen) {
  1158. *body_out = tor_malloc(msglen+1);
  1159. fetch_from_buf(*body_out, msglen, buf);
  1160. (*body_out)[msglen] = '\0';
  1161. }
  1162. return 1;
  1163. }
  1164. /** Helper: return a pointer to the first instance of <b>c</b> in the
  1165. * <b>len</b>characters after <b>start</b> on <b>buf</b>. Return NULL if the
  1166. * character isn't found. */
  1167. static char *
  1168. find_char_on_buf(buf_t *buf, char *start, size_t len, char c)
  1169. {
  1170. size_t len_rest;
  1171. char *cp;
  1172. _split_range(buf, start, &len, &len_rest);
  1173. cp = memchr(start, c, len);
  1174. if (cp || !len_rest)
  1175. return cp;
  1176. return memchr(buf->mem, c, len_rest);
  1177. }
  1178. /** Helper: return a pointer to the first CRLF after cp on <b>buf</b>. Return
  1179. * NULL if no CRLF is found. */
  1180. static char *
  1181. find_crlf_on_buf(buf_t *buf, char *cp)
  1182. {
  1183. char *next;
  1184. while (1) {
  1185. size_t remaining = buf->datalen - _buf_offset(buf,cp);
  1186. cp = find_char_on_buf(buf, cp, remaining, '\r');
  1187. if (!cp)
  1188. return NULL;
  1189. next = _wrap_ptr(buf, cp+1);
  1190. if (next == _buf_end(buf))
  1191. return NULL;
  1192. if (*next == '\n')
  1193. return cp;
  1194. cp = next;
  1195. }
  1196. }
  1197. /** Try to read a single CRLF-terminated line from <b>buf</b>, and write it,
  1198. * NUL-terminated, into the *<b>data_len</b> byte buffer at <b>data_out</b>.
  1199. * Set *<b>data_len</b> to the number of bytes in the line, not counting the
  1200. * terminating NUL. Return 1 if we read a whole line, return 0 if we don't
  1201. * have a whole line yet, and return -1 if we we need to grow the buffer.
  1202. */
  1203. int
  1204. fetch_from_buf_line(buf_t *buf, char *data_out, size_t *data_len)
  1205. {
  1206. char *eol;
  1207. size_t sz;
  1208. /* Look for a CRLF. */
  1209. if (!(eol = find_crlf_on_buf(buf, buf->cur))) {
  1210. return 0;
  1211. }
  1212. sz = _buf_offset(buf, eol);
  1213. if (sz+3 > *data_len) {
  1214. *data_len = sz+3;
  1215. return -1;
  1216. }
  1217. fetch_from_buf(data_out, sz+2, buf);
  1218. data_out[sz+2] = '\0';
  1219. *data_len = sz+2;
  1220. return 1;
  1221. }
  1222. /** Try to read a single LF-terminated line from <b>buf</b>, and write it,
  1223. * NUL-terminated, into the *<b>data_len</b> byte buffer at <b>data_out</b>.
  1224. * Set *<b>data_len</b> to the number of bytes in the line, not counting the
  1225. * terminating NUL. Return 1 if we read a whole line, return 0 if we don't
  1226. * have a whole line yet, and return -1 if the line length exceeds
  1227. *<b>data_len</b>.
  1228. */
  1229. int
  1230. fetch_from_buf_line_lf(buf_t *buf, char *data_out, size_t *data_len)
  1231. {
  1232. char *cp;
  1233. size_t sz;
  1234. size_t remaining = buf->datalen - _buf_offset(buf,buf->cur);
  1235. cp = find_char_on_buf(buf, buf->cur, remaining, '\n');
  1236. if (!cp)
  1237. return 0;
  1238. sz = _buf_offset(buf, cp);
  1239. if (sz+2 > *data_len) {
  1240. *data_len = sz+2;
  1241. return -1;
  1242. }
  1243. fetch_from_buf(data_out, sz+1, buf);
  1244. data_out[sz+1] = '\0';
  1245. *data_len = sz+1;
  1246. return 1;
  1247. }
  1248. /** Compress on uncompress the <b>data_len</b> bytes in <b>data</b> using the
  1249. * zlib state <b>state</b>, appending the result to <b>buf</b>. If
  1250. * <b>done</b> is true, flush the data in the state and finish the
  1251. * compression/uncompression. Return -1 on failure, 0 on success. */
  1252. int
  1253. write_to_buf_zlib(buf_t *buf, tor_zlib_state_t *state,
  1254. const char *data, size_t data_len,
  1255. int done)
  1256. {
  1257. char *next;
  1258. size_t old_avail, avail;
  1259. int over = 0;
  1260. do {
  1261. buf_ensure_capacity(buf, buf->datalen + 1024);
  1262. next = _buf_end(buf);
  1263. if (next < buf->cur)
  1264. old_avail = avail = buf->cur - next;
  1265. else
  1266. old_avail = avail = (buf->mem + buf->len) - next;
  1267. switch (tor_zlib_process(state, &next, &avail, &data, &data_len, done)) {
  1268. case TOR_ZLIB_DONE:
  1269. over = 1;
  1270. break;
  1271. case TOR_ZLIB_ERR:
  1272. return -1;
  1273. case TOR_ZLIB_OK:
  1274. if (data_len == 0)
  1275. over = 1;
  1276. break;
  1277. case TOR_ZLIB_BUF_FULL:
  1278. if (avail && buf->len >= 1024 + buf->datalen) {
  1279. /* Zlib says we need more room (ZLIB_BUF_FULL), and we're not about
  1280. * to wrap around (avail != 0), and resizing won't actually make us
  1281. * un-full: we're at the end of the buffer, and zlib refuses to
  1282. * append more here, but there's a pile of free space at the start
  1283. * of the buffer (about 1K). So chop a few characters off the
  1284. * end of the buffer. This feels silly; anybody got a better hack?
  1285. *
  1286. * (We don't just want to expand the buffer nevertheless. Consider a
  1287. * 1/3 full buffer with a single byte free at the end. zlib will
  1288. * often refuse to append to that, and so we want to use the
  1289. * beginning, not double the buffer to be just 1/6 full.)
  1290. */
  1291. tor_assert(next >= buf->cur);
  1292. buf->len -= avail;
  1293. }
  1294. break;
  1295. }
  1296. buf->datalen += old_avail - avail;
  1297. if (buf->datalen > buf->highwater)
  1298. buf->highwater = buf->datalen;
  1299. buf_total_used += old_avail - avail;
  1300. } while (!over);
  1301. return 0;
  1302. }
  1303. /** Log an error and exit if <b>buf</b> is corrupted.
  1304. */
  1305. void
  1306. assert_buf_ok(buf_t *buf)
  1307. {
  1308. tor_assert(buf);
  1309. tor_assert(buf->magic == BUFFER_MAGIC);
  1310. tor_assert(buf->mem);
  1311. tor_assert(buf->highwater <= buf->len);
  1312. tor_assert(buf->datalen <= buf->highwater);
  1313. #ifdef SENTINELS
  1314. {
  1315. uint32_t u32 = get_uint32(buf->mem - 4);
  1316. tor_assert(u32 == START_MAGIC);
  1317. u32 = get_uint32(buf->mem + buf->memsize);
  1318. tor_assert(u32 == END_MAGIC);
  1319. }
  1320. #endif
  1321. }