buffers.c 49 KB

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