buffers.c 50 KB

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