buffers.c 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  4. * Copyright (c) 2007-2008, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /* $Id$ */
  7. const char buffers_c_id[] =
  8. "$Id$";
  9. /**
  10. * \file buffers.c
  11. * \brief Implements a generic buffer interface. Buffers are
  12. * fairly opaque string holders that can read to or flush from:
  13. * memory, file descriptors, or TLS connections.
  14. **/
  15. #define BUFFERS_PRIVATE
  16. #include "or.h"
  17. //#define PARANOIA
  18. //#define NOINLINE
  19. #ifdef PARANOIA
  20. /** Helper: If PARANOIA is defined, assert that the buffer in local variable
  21. * <b>buf</b> is well-formed. */
  22. #define check() STMT_BEGIN assert_buf_ok(buf); STMT_END
  23. #else
  24. #define check() STMT_NIL
  25. #endif
  26. #ifdef NOINLINE
  27. #undef INLINE
  28. #define INLINE
  29. #endif
  30. /* Implementation notes:
  31. *
  32. * After flirting with memmove, and dallying with ring-buffers, we're finally
  33. * getting up to speed with the 1970s and implementing buffers as a linked
  34. * list of small chunks. Each buffer has such a list; data is removed from
  35. * the head of the list, and added at the tail. The list is singly linked,
  36. * and the buffer keeps a pointer to the head and the tail.
  37. *
  38. * Every chunk, except the tail, contains at least one byte of data. Data in
  39. * each chunk is contiguous.
  40. *
  41. * When you need to treat the first N characters on a buffer as a contiguous
  42. * string, use the buf_pullup function to make them so. Don't do this more
  43. * than necessary.
  44. *
  45. * The major free Unix kernels have handled buffers like this since, like,
  46. * forever.
  47. */
  48. /* Chunk manipulation functions */
  49. /** A single chunk on a buffer or in a freelist. */
  50. typedef struct chunk_t {
  51. struct chunk_t *next; /**< The next chunk on the buffer or freelist. */
  52. size_t datalen; /**< The number of bytes stored in this chunk */
  53. size_t memlen; /**< The number of usable bytes of storage in <b>mem</b>. */
  54. char *data; /**< A pointer to the first byte of data stored in <b>mem</b>. */
  55. char mem[1]; /**< The actual memory used for storage in this chunk. May be
  56. * more than one byte long. */
  57. } chunk_t;
  58. /** Return the number of bytes needed to allocate a chunk to hold
  59. * <b>memlen</b> bytes. */
  60. #define CHUNK_ALLOC_SIZE(memlen) (sizeof(chunk_t) + (memlen) - 1)
  61. /** Return the number of usable bytes in a chunk allocated with
  62. * malloc(<b>memlen</b>). */
  63. #define CHUNK_SIZE_WITH_ALLOC(memlen) ((memlen) - sizeof(chunk_t) + 1)
  64. /** Return the next character in <b>chunk</b> onto which data can be appended.
  65. * If the chunk is full, this might be off the end of chunk->mem. */
  66. static INLINE char *
  67. CHUNK_WRITE_PTR(chunk_t *chunk)
  68. {
  69. return chunk->data + chunk->datalen;
  70. }
  71. /** Return the number of bytes that can be written onto <b>chunk</b> without
  72. * running out of space. */
  73. static INLINE size_t
  74. CHUNK_REMAINING_CAPACITY(const chunk_t *chunk)
  75. {
  76. return (chunk->mem + chunk->memlen) - (chunk->data + chunk->datalen);
  77. }
  78. /** Move all bytes stored in <b>chunk</b> to the front of <b>chunk</b>->mem,
  79. * to free up space at the end. */
  80. static INLINE void
  81. chunk_repack(chunk_t *chunk)
  82. {
  83. if (chunk->datalen && chunk->data != &chunk->mem[0]) {
  84. memmove(chunk->mem, chunk->data, chunk->datalen);
  85. }
  86. chunk->data = &chunk->mem[0];
  87. }
  88. #ifdef ENABLE_BUF_FREELISTS
  89. /** A freelist of chunks. */
  90. typedef struct chunk_freelist_t {
  91. size_t alloc_size; /**< What size chunks does this freelist hold? */
  92. int max_length; /**< Never allow more than this number of chunks in the
  93. * freelist. */
  94. int slack; /**< When trimming the freelist, leave this number of extra
  95. * chunks beyond lowest_length.*/
  96. int cur_length; /**< How many chunks on the freelist now? */
  97. int lowest_length; /**< What's the smallest value of cur_length since the
  98. * last time we cleaned this freelist? */
  99. uint64_t n_alloc;
  100. uint64_t n_free;
  101. uint64_t n_hit;
  102. chunk_t *head; /**< First chunk on the freelist. */
  103. } chunk_freelist_t;
  104. /** Macro to help define freelists. */
  105. #define FL(a,m,s) { a, m, s, 0, 0, 0, 0, 0, NULL }
  106. /** Static array of freelists, sorted by alloc_len, terminated by an entry
  107. * with alloc_size of 0. */
  108. static chunk_freelist_t freelists[] = {
  109. FL(4096, 256, 8), FL(8192, 128, 4), FL(16384, 64, 4), FL(32768, 32, 2),
  110. FL(0, 0, 0)
  111. };
  112. #undef FL
  113. /** How many times have we looked for a chunk of a size that no freelist
  114. * could help with? */
  115. static uint64_t n_freelist_miss = 0;
  116. static void assert_freelist_ok(chunk_freelist_t *fl);
  117. /** Return the freelist to hold chunks of size <b>alloc</b>, or NULL if
  118. * no freelist exists for that size. */
  119. static INLINE chunk_freelist_t *
  120. get_freelist(size_t alloc)
  121. {
  122. int i;
  123. for (i=0; freelists[i].alloc_size <= alloc; ++i) {
  124. if (freelists[i].alloc_size == alloc) {
  125. return &freelists[i];
  126. }
  127. }
  128. return NULL;
  129. }
  130. /** Deallocate a chunk or put it on a freelist */
  131. static void
  132. chunk_free(chunk_t *chunk)
  133. {
  134. size_t alloc = CHUNK_ALLOC_SIZE(chunk->memlen);
  135. chunk_freelist_t *freelist = get_freelist(alloc);
  136. if (freelist && freelist->cur_length < freelist->max_length) {
  137. chunk->next = freelist->head;
  138. freelist->head = chunk;
  139. ++freelist->cur_length;
  140. } else {
  141. if (freelist)
  142. ++freelist->n_free;
  143. tor_free(chunk);
  144. }
  145. }
  146. /** Allocate a new chunk with a given allocation size, or get one from the
  147. * freelist. Note that a chunk with allocation size A can actualy hold only
  148. * CHUNK_SIZE_WITH_ALLOC(A) bytes in its mem field. */
  149. static INLINE chunk_t *
  150. chunk_new_with_alloc_size(size_t alloc)
  151. {
  152. chunk_t *ch;
  153. chunk_freelist_t *freelist;
  154. tor_assert(alloc >= sizeof(chunk_t));
  155. freelist = get_freelist(alloc);
  156. if (freelist && freelist->head) {
  157. ch = freelist->head;
  158. freelist->head = ch->next;
  159. if (--freelist->cur_length < freelist->lowest_length)
  160. freelist->lowest_length = freelist->cur_length;
  161. ++freelist->n_hit;
  162. } else {
  163. /* XXXX021 take advantage of tor_malloc_roundup, once we know how that
  164. * affects freelists. */
  165. if (freelist)
  166. ++freelist->n_alloc;
  167. else
  168. ++n_freelist_miss;
  169. ch = tor_malloc(alloc);
  170. }
  171. ch->next = NULL;
  172. ch->datalen = 0;
  173. ch->memlen = CHUNK_SIZE_WITH_ALLOC(alloc);
  174. ch->data = &ch->mem[0];
  175. return ch;
  176. }
  177. #else
  178. static void
  179. chunk_free(chunk_t *chunk)
  180. {
  181. tor_free(chunk);
  182. }
  183. static INLINE chunk_t *
  184. chunk_new_with_alloc_size(size_t alloc)
  185. {
  186. chunk_t *ch;
  187. ch = tor_malloc_roundup(&alloc);
  188. ch->next = NULL;
  189. ch->datalen = 0;
  190. ch->memlen = CHUNK_SIZE_WITH_ALLOC(alloc);
  191. ch->data = &ch->mem[0];
  192. return ch;
  193. }
  194. #endif
  195. /** Allocate a new chunk with memory size of <b>sz</b>. */
  196. #define chunk_new_with_capacity(sz) \
  197. (chunk_new_with_alloc_size(CHUNK_ALLOC_SIZE(sz)))
  198. /** Expand <b>chunk</b> until it can hold <b>sz</b> bytes, and return a
  199. * new pointer to <b>chunk</b>. Old pointers are no longer valid. */
  200. static INLINE chunk_t *
  201. chunk_grow(chunk_t *chunk, size_t sz)
  202. {
  203. off_t offset;
  204. tor_assert(sz > chunk->memlen);
  205. offset = chunk->data - chunk->mem;
  206. chunk = tor_realloc(chunk, CHUNK_ALLOC_SIZE(sz));
  207. chunk->memlen = sz;
  208. chunk->data = chunk->mem + offset;
  209. return chunk;
  210. }
  211. /** If a read onto the end of a chunk would be smaller than this number, then
  212. * just start a new chunk. */
  213. #define MIN_READ_LEN 8
  214. /** Every chunk should take up at least this many bytes. */
  215. #define MIN_CHUNK_ALLOC 256
  216. /** No chunk should take up more than this many bytes. */
  217. #define MAX_CHUNK_ALLOC 65536
  218. /** Return the allocation size we'd like to use to hold <b>target</b>
  219. * bytes. */
  220. static INLINE size_t
  221. preferred_chunk_size(size_t target)
  222. {
  223. size_t sz = MIN_CHUNK_ALLOC;
  224. while (CHUNK_SIZE_WITH_ALLOC(sz) < target) {
  225. sz <<= 1;
  226. }
  227. return sz;
  228. }
  229. /** Remove from the freelists most chunks that have not been used since the
  230. * last call to buf_shrink_freelists(). */
  231. void
  232. buf_shrink_freelists(int free_all)
  233. {
  234. #ifdef ENABLE_BUF_FREELISTS
  235. int i;
  236. for (i = 0; freelists[i].alloc_size; ++i) {
  237. int slack = freelists[i].slack;
  238. assert_freelist_ok(&freelists[i]);
  239. if (free_all || freelists[i].lowest_length > slack) {
  240. int n_to_free = free_all ? freelists[i].cur_length :
  241. (freelists[i].lowest_length - slack);
  242. int n_to_skip = freelists[i].cur_length - n_to_free;
  243. int new_length = n_to_skip;
  244. chunk_t **chp = &freelists[i].head;
  245. chunk_t *chunk;
  246. log_info(LD_MM, "Cleaning freelist for %d-byte chunks: keeping %d, "
  247. "dropping %d.",
  248. (int)freelists[i].alloc_size, n_to_skip, n_to_free);
  249. while (n_to_skip) {
  250. tor_assert((*chp)->next);
  251. chp = &(*chp)->next;
  252. --n_to_skip;
  253. }
  254. chunk = *chp;
  255. *chp = NULL;
  256. while (chunk) {
  257. chunk_t *next = chunk->next;
  258. tor_free(chunk);
  259. chunk = next;
  260. --n_to_free;
  261. ++freelists[i].n_free;
  262. }
  263. tor_assert(!n_to_free);
  264. freelists[i].cur_length = new_length;
  265. }
  266. freelists[i].lowest_length = freelists[i].cur_length;
  267. assert_freelist_ok(&freelists[i]);
  268. }
  269. #else
  270. (void) free_all;
  271. #endif
  272. }
  273. /** Describe the current status of the freelists at log level <b>severity</b>.
  274. */
  275. void
  276. buf_dump_freelist_sizes(int severity)
  277. {
  278. #ifdef ENABLE_BUF_FREELISTS
  279. int i;
  280. log(severity, LD_MM, "====== Buffer freelists:");
  281. for (i = 0; freelists[i].alloc_size; ++i) {
  282. uint64_t total = ((uint64_t)freelists[i].cur_length) *
  283. freelists[i].alloc_size;
  284. log(severity, LD_MM,
  285. U64_FORMAT" bytes in %d %d-byte chunks ["U64_FORMAT
  286. " misses; "U64_FORMAT" frees; "U64_FORMAT" hits]",
  287. U64_PRINTF_ARG(total),
  288. freelists[i].cur_length, (int)freelists[i].alloc_size,
  289. U64_PRINTF_ARG(freelists[i].n_alloc),
  290. U64_PRINTF_ARG(freelists[i].n_free),
  291. U64_PRINTF_ARG(freelists[i].n_hit));
  292. }
  293. log(severity, LD_MM, U64_FORMAT" allocations in non-freelist sizes",
  294. U64_PRINTF_ARG(n_freelist_miss));
  295. #else
  296. (void)severity;
  297. #endif
  298. }
  299. /** Magic value for buf_t.magic, to catch pointer errors. */
  300. #define BUFFER_MAGIC 0xB0FFF312u
  301. /** A resizeable buffer, optimized for reading and writing. */
  302. struct buf_t {
  303. uint32_t magic; /**< Magic cookie for debugging: Must be set to
  304. * BUFFER_MAGIC. */
  305. size_t datalen; /**< How many bytes is this buffer holding right now? */
  306. size_t default_chunk_size; /**< Don't allocate any chunks smaller than
  307. * this for this buffer. */
  308. chunk_t *head; /**< First chunk in the list, or NULL for none. */
  309. chunk_t *tail; /**< Last chunk in the list, or NULL for none. */
  310. };
  311. /** Collapse data from the first N chunks from <b>buf</b> into buf->head,
  312. * growing it as necessary, until buf->head has the first <b>bytes</b> bytes
  313. * of data from the buffer, or until buf->head has all the data in <b>buf</b>.
  314. *
  315. * If <b>nulterminate</b> is true, ensure that there is a 0 byte in
  316. * buf->head->mem right after all the data. */
  317. static void
  318. buf_pullup(buf_t *buf, size_t bytes, int nulterminate)
  319. {
  320. chunk_t *dest, *src;
  321. size_t capacity;
  322. if (!buf->head)
  323. return;
  324. check();
  325. if (buf->datalen < bytes)
  326. bytes = buf->datalen;
  327. if (nulterminate) {
  328. capacity = bytes + 1;
  329. if (buf->head->datalen >= bytes && CHUNK_REMAINING_CAPACITY(buf->head)) {
  330. *CHUNK_WRITE_PTR(buf->head) = '\0';
  331. return;
  332. }
  333. } else {
  334. capacity = bytes;
  335. if (buf->head->datalen >= bytes)
  336. return;
  337. }
  338. if (buf->head->memlen >= capacity) {
  339. /* We don't need to grow the first chunk, but we might need to repack it.*/
  340. if (CHUNK_REMAINING_CAPACITY(buf->head) < capacity-buf->datalen)
  341. chunk_repack(buf->head);
  342. tor_assert(CHUNK_REMAINING_CAPACITY(buf->head) >= capacity-buf->datalen);
  343. } else {
  344. chunk_t *newhead;
  345. size_t newsize;
  346. /* We need to grow the chunk. */
  347. chunk_repack(buf->head);
  348. newsize = CHUNK_SIZE_WITH_ALLOC(preferred_chunk_size(capacity));
  349. newhead = chunk_grow(buf->head, newsize);
  350. tor_assert(newhead->memlen >= capacity);
  351. if (newhead != buf->head) {
  352. if (buf->tail == buf->head)
  353. buf->tail = newhead;
  354. buf->head = newhead;
  355. }
  356. }
  357. dest = buf->head;
  358. while (dest->datalen < bytes) {
  359. size_t n = bytes - dest->datalen;
  360. src = dest->next;
  361. tor_assert(src);
  362. if (n > src->datalen) {
  363. memcpy(CHUNK_WRITE_PTR(dest), src->data, src->datalen);
  364. dest->datalen += src->datalen;
  365. dest->next = src->next;
  366. if (buf->tail == src)
  367. buf->tail = dest;
  368. chunk_free(src);
  369. } else {
  370. memcpy(CHUNK_WRITE_PTR(dest), src->data, n);
  371. dest->datalen += n;
  372. src->data += n;
  373. src->datalen -= n;
  374. tor_assert(dest->datalen == bytes);
  375. }
  376. }
  377. if (nulterminate) {
  378. tor_assert(CHUNK_REMAINING_CAPACITY(buf->head));
  379. *CHUNK_WRITE_PTR(buf->head) = '\0';
  380. }
  381. check();
  382. }
  383. /** Resize buf so it won't hold extra memory that we haven't been
  384. * using lately.
  385. */
  386. void
  387. buf_shrink(buf_t *buf)
  388. {
  389. (void)buf;
  390. }
  391. /** Remove the first <b>n</b> bytes from buf. */
  392. static INLINE void
  393. buf_remove_from_front(buf_t *buf, size_t n)
  394. {
  395. tor_assert(buf->datalen >= n);
  396. while (n) {
  397. tor_assert(buf->head);
  398. if (buf->head->datalen > n) {
  399. buf->head->datalen -= n;
  400. buf->head->data += n;
  401. buf->datalen -= n;
  402. return;
  403. } else {
  404. chunk_t *victim = buf->head;
  405. n -= victim->datalen;
  406. buf->datalen -= victim->datalen;
  407. buf->head = victim->next;
  408. if (buf->tail == victim)
  409. buf->tail = NULL;
  410. chunk_free(victim);
  411. }
  412. }
  413. check();
  414. }
  415. /** Create and return a new buf with default chunk capacity <b>size</b>.
  416. */
  417. buf_t *
  418. buf_new_with_capacity(size_t size)
  419. {
  420. buf_t *b = buf_new();
  421. b->default_chunk_size = preferred_chunk_size(size);
  422. return b;
  423. }
  424. /** Allocate and return a new buffer with default capacity. */
  425. buf_t *
  426. buf_new(void)
  427. {
  428. buf_t *buf = tor_malloc_zero(sizeof(buf_t));
  429. buf->magic = BUFFER_MAGIC;
  430. buf->default_chunk_size = 4096;
  431. return buf;
  432. }
  433. /** Remove all data from <b>buf</b>. */
  434. void
  435. buf_clear(buf_t *buf)
  436. {
  437. chunk_t *chunk, *next;
  438. buf->datalen = 0;
  439. for (chunk = buf->head; chunk; chunk = next) {
  440. next = chunk->next;
  441. chunk_free(chunk);
  442. }
  443. buf->head = buf->tail = NULL;
  444. }
  445. /** Return the number of bytes stored in <b>buf</b> */
  446. size_t
  447. buf_datalen(const buf_t *buf)
  448. {
  449. return buf->datalen;
  450. }
  451. /** Return the total length of all chunks used in <b>buf</b>. */
  452. size_t
  453. buf_allocation(const buf_t *buf)
  454. {
  455. size_t total = 0;
  456. const chunk_t *chunk;
  457. for (chunk = buf->head; chunk; chunk = chunk->next) {
  458. total += chunk->memlen;
  459. }
  460. return total;
  461. }
  462. /** Return the number of bytes that can be added to <b>buf</b> without
  463. * performing any additional allocation. */
  464. size_t
  465. buf_slack(const buf_t *buf)
  466. {
  467. if (!buf->tail)
  468. return 0;
  469. else
  470. return CHUNK_REMAINING_CAPACITY(buf->tail);
  471. }
  472. /** Release storage held by <b>buf</b>. */
  473. void
  474. buf_free(buf_t *buf)
  475. {
  476. buf_clear(buf);
  477. buf->magic = 0xdeadbeef;
  478. tor_free(buf);
  479. }
  480. /** Append a new chunk with enough capacity to hold <b>capacity</b> bytes to
  481. * the tail of <b>buf</b>. If <b>capped</b>, don't allocate a chunk bigger
  482. * than MAX_CHUNK_ALLOC. */
  483. static chunk_t *
  484. buf_add_chunk_with_capacity(buf_t *buf, size_t capacity, int capped)
  485. {
  486. chunk_t *chunk;
  487. if (CHUNK_ALLOC_SIZE(capacity) < buf->default_chunk_size) {
  488. chunk = chunk_new_with_alloc_size(buf->default_chunk_size);
  489. } else if (capped && CHUNK_ALLOC_SIZE(capacity) > MAX_CHUNK_ALLOC) {
  490. chunk = chunk_new_with_alloc_size(MAX_CHUNK_ALLOC);
  491. } else {
  492. chunk = chunk_new_with_alloc_size(preferred_chunk_size(capacity));
  493. }
  494. if (buf->tail) {
  495. tor_assert(buf->head);
  496. buf->tail->next = chunk;
  497. buf->tail = chunk;
  498. } else {
  499. tor_assert(!buf->head);
  500. buf->head = buf->tail = chunk;
  501. }
  502. check();
  503. return chunk;
  504. }
  505. /** Read up to <b>at_most</b> bytes from the socket <b>fd</b> into
  506. * <b>chunk</b> (which must be on <b>buf</b>). If we get an EOF, set
  507. * *<b>reached_eof</b> to 1. Return -1 on error, 0 on eof or blocking,
  508. * and the number of bytes read otherwise. */
  509. static INLINE int
  510. read_to_chunk(buf_t *buf, chunk_t *chunk, int fd, size_t at_most,
  511. int *reached_eof)
  512. {
  513. int read_result;
  514. tor_assert(CHUNK_REMAINING_CAPACITY(chunk) >= at_most);
  515. read_result = tor_socket_recv(fd, CHUNK_WRITE_PTR(chunk), at_most, 0);
  516. if (read_result < 0) {
  517. int e = tor_socket_errno(fd);
  518. if (!ERRNO_IS_EAGAIN(e)) { /* it's a real error */
  519. #ifdef MS_WINDOWS
  520. if (e == WSAENOBUFS)
  521. log_warn(LD_NET,"recv() failed: WSAENOBUFS. Not enough ram?");
  522. #endif
  523. return -1;
  524. }
  525. return 0; /* would block. */
  526. } else if (read_result == 0) {
  527. log_debug(LD_NET,"Encountered eof on fd %d", (int)fd);
  528. *reached_eof = 1;
  529. return 0;
  530. } else { /* actually got bytes. */
  531. buf->datalen += read_result;
  532. chunk->datalen += read_result;
  533. log_debug(LD_NET,"Read %d bytes. %d on inbuf.", read_result,
  534. (int)buf->datalen);
  535. return read_result;
  536. }
  537. }
  538. /** As read_to_chunk(), but return (negative) error code on error, blocking,
  539. * or TLS, and the number of bytes read otherwise. */
  540. static INLINE int
  541. read_to_chunk_tls(buf_t *buf, chunk_t *chunk, tor_tls_t *tls,
  542. size_t at_most)
  543. {
  544. int read_result;
  545. tor_assert(CHUNK_REMAINING_CAPACITY(chunk) >= at_most);
  546. read_result = tor_tls_read(tls, CHUNK_WRITE_PTR(chunk), at_most);
  547. if (read_result < 0)
  548. return read_result;
  549. buf->datalen += read_result;
  550. chunk->datalen += read_result;
  551. return read_result;
  552. }
  553. /** Read from socket <b>s</b>, writing onto end of <b>buf</b>. Read at most
  554. * <b>at_most</b> bytes, growing the buffer as necessary. If recv() returns 0
  555. * (because of EOF), set *<b>reached_eof</b> to 1 and return 0. Return -1 on
  556. * error; else return the number of bytes read.
  557. */
  558. /* XXXX021 indicate "read blocked" somehow? */
  559. int
  560. read_to_buf(int s, size_t at_most, buf_t *buf, int *reached_eof)
  561. {
  562. /* XXXX021 It's stupid to overload the return values for these functions:
  563. * "error status" and "number of bytes read" are not mutually exclusive.
  564. */
  565. int r = 0;
  566. size_t total_read = 0;
  567. check();
  568. tor_assert(reached_eof);
  569. tor_assert(s >= 0);
  570. while (at_most > total_read) {
  571. size_t readlen = at_most - total_read;
  572. chunk_t *chunk;
  573. if (!buf->tail || CHUNK_REMAINING_CAPACITY(buf->tail) < MIN_READ_LEN) {
  574. chunk = buf_add_chunk_with_capacity(buf, at_most, 1);
  575. if (readlen > chunk->memlen)
  576. readlen = chunk->memlen;
  577. } else {
  578. size_t cap = CHUNK_REMAINING_CAPACITY(buf->tail);
  579. chunk = buf->tail;
  580. if (cap < readlen)
  581. readlen = cap;
  582. }
  583. r = read_to_chunk(buf, chunk, s, readlen, reached_eof);
  584. check();
  585. if (r < 0)
  586. return r; /* Error */
  587. else if ((size_t)r < readlen) /* eof, block, or no more to read. */
  588. return r + total_read;
  589. total_read += r;
  590. }
  591. return r;
  592. }
  593. /** As read_to_buf, but reads from a TLS connection, and returns a TLS
  594. * status value rather than the number of bytes read.
  595. *
  596. * Using TLS on OR connections complicates matters in two ways.
  597. *
  598. * First, a TLS stream has its own read buffer independent of the
  599. * connection's read buffer. (TLS needs to read an entire frame from
  600. * the network before it can decrypt any data. Thus, trying to read 1
  601. * byte from TLS can require that several KB be read from the network
  602. * and decrypted. The extra data is stored in TLS's decrypt buffer.)
  603. * Because the data hasn't been read by Tor (it's still inside the TLS),
  604. * this means that sometimes a connection "has stuff to read" even when
  605. * poll() didn't return POLLIN. The tor_tls_get_pending_bytes function is
  606. * used in connection.c to detect TLS objects with non-empty internal
  607. * buffers and read from them again.
  608. *
  609. * Second, the TLS stream's events do not correspond directly to network
  610. * events: sometimes, before a TLS stream can read, the network must be
  611. * ready to write -- or vice versa.
  612. */
  613. int
  614. read_to_buf_tls(tor_tls_t *tls, size_t at_most, buf_t *buf)
  615. {
  616. int r = 0;
  617. size_t total_read = 0;
  618. check();
  619. while (at_most > total_read) {
  620. size_t readlen = at_most - total_read;
  621. chunk_t *chunk;
  622. if (!buf->tail || CHUNK_REMAINING_CAPACITY(buf->tail) < MIN_READ_LEN) {
  623. chunk = buf_add_chunk_with_capacity(buf, at_most, 1);
  624. if (readlen > chunk->memlen)
  625. readlen = chunk->memlen;
  626. } else {
  627. size_t cap = CHUNK_REMAINING_CAPACITY(buf->tail);
  628. chunk = buf->tail;
  629. if (cap < readlen)
  630. readlen = cap;
  631. }
  632. r = read_to_chunk_tls(buf, chunk, tls, readlen);
  633. check();
  634. if (r < 0)
  635. return r; /* Error */
  636. else if ((size_t)r < readlen) /* eof, block, or no more to read. */
  637. return r;
  638. total_read += r;
  639. }
  640. return r;
  641. }
  642. /** Helper for flush_buf(): try to write <b>sz</b> bytes from chunk
  643. * <b>chunk</b> of buffer <b>buf</b> onto socket <b>s</b>. On success, deduct
  644. * the bytes written from *<b>buf_flushlen</b>. Return the number of bytes
  645. * written on success, 0 on blocking, -1 on failure.
  646. */
  647. static INLINE int
  648. flush_chunk(int s, buf_t *buf, chunk_t *chunk, size_t sz,
  649. size_t *buf_flushlen)
  650. {
  651. int write_result;
  652. tor_assert(sz <= chunk->datalen);
  653. write_result = tor_socket_send(s, chunk->data, sz, 0);
  654. if (write_result < 0) {
  655. int e = tor_socket_errno(s);
  656. if (!ERRNO_IS_EAGAIN(e)) { /* it's a real error */
  657. #ifdef MS_WINDOWS
  658. if (e == WSAENOBUFS)
  659. log_warn(LD_NET,"write() failed: WSAENOBUFS. Not enough ram?");
  660. #endif
  661. return -1;
  662. }
  663. log_debug(LD_NET,"write() would block, returning.");
  664. return 0;
  665. } else {
  666. *buf_flushlen -= write_result;
  667. buf_remove_from_front(buf, write_result);
  668. return write_result;
  669. }
  670. }
  671. /** Helper for flush_buf_tls(): try to write <b>sz</b> bytes from chunk
  672. * <b>chunk</b> of buffer <b>buf</b> onto socket <b>s</b>. (Tries to write
  673. * more if there is a forced pending write size.) On success, deduct the
  674. * bytes written from *<b>buf_flushlen</b>. Return the number of bytes
  675. * written on success, and a TOR_TLS error code on failue or blocking.
  676. */
  677. static INLINE int
  678. flush_chunk_tls(tor_tls_t *tls, buf_t *buf, chunk_t *chunk,
  679. size_t sz, size_t *buf_flushlen)
  680. {
  681. int r;
  682. size_t forced;
  683. char *data;
  684. forced = tor_tls_get_forced_write_size(tls);
  685. if (forced > sz)
  686. sz = forced;
  687. if (chunk) {
  688. data = chunk->data;
  689. tor_assert(sz <= chunk->datalen);
  690. } else {
  691. data = NULL;
  692. tor_assert(sz == 0);
  693. }
  694. r = tor_tls_write(tls, data, sz);
  695. if (r < 0)
  696. return r;
  697. if (*buf_flushlen > (size_t)r)
  698. *buf_flushlen -= r;
  699. else
  700. *buf_flushlen = 0;
  701. buf_remove_from_front(buf, r);
  702. log_debug(LD_NET,"flushed %d bytes, %d ready to flush, %d remain.",
  703. r,(int)*buf_flushlen,(int)buf->datalen);
  704. return r;
  705. }
  706. /** Write data from <b>buf</b> to the socket <b>s</b>. Write at most
  707. * <b>sz</b> bytes, decrement *<b>buf_flushlen</b> by
  708. * the number of bytes actually written, and remove the written bytes
  709. * from the buffer. Return the number of bytes written on success,
  710. * -1 on failure. Return 0 if write() would block.
  711. */
  712. int
  713. flush_buf(int s, buf_t *buf, size_t sz, size_t *buf_flushlen)
  714. {
  715. /* XXXX021 It's stupid to overload the return values for these functions:
  716. * "error status" and "number of bytes flushed" are not mutually exclusive.
  717. */
  718. int r;
  719. size_t flushed = 0;
  720. tor_assert(buf_flushlen);
  721. tor_assert(s >= 0);
  722. tor_assert(*buf_flushlen <= buf->datalen);
  723. tor_assert(sz <= *buf_flushlen);
  724. check();
  725. while (sz) {
  726. size_t flushlen0;
  727. tor_assert(buf->head);
  728. if (buf->head->datalen >= sz)
  729. flushlen0 = sz;
  730. else
  731. flushlen0 = buf->head->datalen;
  732. r = flush_chunk(s, buf, buf->head, flushlen0, buf_flushlen);
  733. check();
  734. if (r < 0)
  735. return r;
  736. flushed += r;
  737. sz -= r;
  738. if (r == 0 || (size_t)r < flushlen0) /* can't flush any more now. */
  739. break;
  740. }
  741. return flushed;
  742. }
  743. /** As flush_buf(), but writes data to a TLS connection. Can write more than
  744. * <b>flushlen</b> bytes.
  745. */
  746. int
  747. flush_buf_tls(tor_tls_t *tls, buf_t *buf, size_t flushlen,
  748. size_t *buf_flushlen)
  749. {
  750. int r;
  751. size_t flushed = 0;
  752. ssize_t sz;
  753. tor_assert(buf_flushlen);
  754. tor_assert(*buf_flushlen <= buf->datalen);
  755. tor_assert(flushlen <= *buf_flushlen);
  756. sz = (ssize_t) flushlen;
  757. /* we want to let tls write even if flushlen is zero, because it might
  758. * have a partial record pending */
  759. check_no_tls_errors();
  760. check();
  761. do {
  762. size_t flushlen0;
  763. if (buf->head) {
  764. if ((ssize_t)buf->head->datalen >= sz)
  765. flushlen0 = sz;
  766. else
  767. flushlen0 = buf->head->datalen;
  768. } else {
  769. flushlen0 = 0;
  770. }
  771. r = flush_chunk_tls(tls, buf, buf->head, flushlen0, buf_flushlen);
  772. check();
  773. if (r < 0)
  774. return r;
  775. flushed += r;
  776. sz -= r;
  777. if (r == 0) /* Can't flush any more now. */
  778. break;
  779. } while (sz > 0);
  780. return flushed;
  781. }
  782. /** Append <b>string_len</b> bytes from <b>string</b> to the end of
  783. * <b>buf</b>.
  784. *
  785. * Return the new length of the buffer on success, -1 on failure.
  786. */
  787. int
  788. write_to_buf(const char *string, size_t string_len, buf_t *buf)
  789. {
  790. if (!string_len)
  791. return buf->datalen;
  792. check();
  793. while (string_len) {
  794. size_t copy;
  795. if (!buf->tail || !CHUNK_REMAINING_CAPACITY(buf->tail))
  796. buf_add_chunk_with_capacity(buf, string_len, 1);
  797. copy = CHUNK_REMAINING_CAPACITY(buf->tail);
  798. if (copy > string_len)
  799. copy = string_len;
  800. memcpy(CHUNK_WRITE_PTR(buf->tail), string, copy);
  801. string_len -= copy;
  802. string += copy;
  803. buf->datalen += copy;
  804. buf->tail->datalen += copy;
  805. }
  806. check();
  807. return buf->datalen;
  808. }
  809. /** Helper: copy the first <b>string_len</b> bytes from <b>buf</b>
  810. * onto <b>string</b>.
  811. */
  812. static INLINE void
  813. peek_from_buf(char *string, size_t string_len, const buf_t *buf)
  814. {
  815. chunk_t *chunk;
  816. tor_assert(string);
  817. /* make sure we don't ask for too much */
  818. tor_assert(string_len <= buf->datalen);
  819. /* assert_buf_ok(buf); */
  820. chunk = buf->head;
  821. while (string_len) {
  822. size_t copy = string_len;
  823. tor_assert(chunk);
  824. if (chunk->datalen < copy)
  825. copy = chunk->datalen;
  826. memcpy(string, chunk->data, copy);
  827. string_len -= copy;
  828. string += copy;
  829. chunk = chunk->next;
  830. }
  831. }
  832. /** Remove <b>string_len</b> bytes from the front of <b>buf</b>, and store
  833. * them into <b>string</b>. Return the new buffer size. <b>string_len</b>
  834. * must be \<= the number of bytes on the buffer.
  835. */
  836. int
  837. fetch_from_buf(char *string, size_t string_len, buf_t *buf)
  838. {
  839. /* There must be string_len bytes in buf; write them onto string,
  840. * then memmove buf back (that is, remove them from buf).
  841. *
  842. * Return the number of bytes still on the buffer. */
  843. check();
  844. peek_from_buf(string, string_len, buf);
  845. buf_remove_from_front(buf, string_len);
  846. check();
  847. return buf->datalen;
  848. }
  849. /** Check <b>buf</b> for a variable-length cell according to the rules of link
  850. * protocol version <b>linkproto</b>. If one is found, pull it off the buffer
  851. * and assign a newly allocated var_cell_t to *<b>out</b>, and return 1.
  852. * Return 0 if whatever is on the start of buf_t is not a variable-length
  853. * cell. Return 1 and set *<b>out</b> to NULL if there seems to be the start
  854. * of a variable-length cell on <b>buf</b>, but the whole thing isn't there
  855. * yet. */
  856. int
  857. fetch_var_cell_from_buf(buf_t *buf, var_cell_t **out, int linkproto)
  858. {
  859. char hdr[VAR_CELL_HEADER_SIZE];
  860. var_cell_t *result;
  861. uint8_t command;
  862. uint16_t length;
  863. /* If linkproto is unknown (0) or v2 (2), variable-length cells work as
  864. * implemented here. If it's 1, there are no variable-length cells. Tor
  865. * does not support other versions right now, and so can't negotiate them.
  866. */
  867. if (linkproto == 1)
  868. return 0;
  869. check();
  870. *out = NULL;
  871. if (buf->datalen < VAR_CELL_HEADER_SIZE)
  872. return 0;
  873. peek_from_buf(hdr, sizeof(hdr), buf);
  874. command = *(uint8_t*)(hdr+2);
  875. if (!(CELL_COMMAND_IS_VAR_LENGTH(command)))
  876. return 0;
  877. length = ntohs(get_uint16(hdr+3));
  878. if (buf->datalen < (size_t)(VAR_CELL_HEADER_SIZE+length))
  879. return 1;
  880. result = var_cell_new(length);
  881. result->command = command;
  882. result->circ_id = ntohs(*(uint16_t*)hdr);
  883. buf_remove_from_front(buf, VAR_CELL_HEADER_SIZE);
  884. peek_from_buf(result->payload, length, buf);
  885. buf_remove_from_front(buf, length);
  886. check();
  887. *out = result;
  888. return 1;
  889. }
  890. /** Move up to *<b>buf_flushlen</b> bytes from <b>buf_in</b> to
  891. * <b>buf_out</b>, and modify *<b>buf_flushlen</b> appropriately.
  892. * Return the number of bytes actually copied.
  893. */
  894. int
  895. move_buf_to_buf(buf_t *buf_out, buf_t *buf_in, size_t *buf_flushlen)
  896. {
  897. /* XXXX we can do way better here, but this doesn't turn up in any
  898. * profiles. */
  899. char b[4096];
  900. size_t cp, len;
  901. len = *buf_flushlen;
  902. if (len > buf_in->datalen)
  903. len = buf_in->datalen;
  904. cp = len; /* Remember the number of bytes we intend to copy. */
  905. while (len) {
  906. /* This isn't the most efficient implementation one could imagine, since
  907. * it does two copies instead of 1, but I kinda doubt that this will be
  908. * critical path. */
  909. size_t n = len > sizeof(b) ? sizeof(b) : len;
  910. fetch_from_buf(b, n, buf_in);
  911. write_to_buf(b, n, buf_out);
  912. len -= n;
  913. }
  914. *buf_flushlen -= cp;
  915. return cp;
  916. }
  917. /** Internal structure: represents a position in a buffer. */
  918. typedef struct buf_pos_t {
  919. const chunk_t *chunk; /**< Which chunk are we pointing to? */
  920. int pos;/**< Which character inside the chunk's data are we pointing to? */
  921. size_t chunk_pos; /**< Total length of all previous chunks. */
  922. } buf_pos_t;
  923. /** Initialize <b>out</b> to point to the first character of <b>buf</b>.*/
  924. static void
  925. buf_pos_init(const buf_t *buf, buf_pos_t *out)
  926. {
  927. out->chunk = buf->head;
  928. out->pos = 0;
  929. out->chunk_pos = 0;
  930. }
  931. /** Advance <b>out</b> to the first appearance of <b>ch</b> at the current
  932. * position of <b>out</b>, or later. Return -1 if no instances are found;
  933. * otherwise returns the absolute position of the character. */
  934. static int
  935. buf_find_pos_of_char(char ch, buf_pos_t *out)
  936. {
  937. const chunk_t *chunk;
  938. int pos;
  939. tor_assert(out);
  940. if (out->chunk) {
  941. if (out->chunk->datalen) {
  942. /*XXXX020 remove this once the bug it detects is fixed. */
  943. if (!(out->pos < (off_t)out->chunk->datalen)) {
  944. log_warn(LD_BUG, "About to assert. %p, %d, %d, %p, %d.",
  945. out, (int)out->pos,
  946. (int)out->chunk_pos, out->chunk,
  947. out->chunk?(int)out->chunk->datalen : (int)-1
  948. );
  949. }
  950. tor_assert(out->pos < (off_t)out->chunk->datalen);
  951. } else {
  952. tor_assert(out->pos == 0);
  953. }
  954. }
  955. pos = out->pos;
  956. for (chunk = out->chunk; chunk; chunk = chunk->next) {
  957. char *cp = memchr(chunk->data+pos, ch, chunk->datalen - pos);
  958. if (cp) {
  959. out->chunk = chunk;
  960. out->pos = cp - chunk->data;
  961. return out->chunk_pos + out->pos;
  962. } else {
  963. out->chunk_pos += chunk->datalen;
  964. pos = 0;
  965. }
  966. }
  967. return -1;
  968. }
  969. /** Advance <b>pos</b> by a single character, if there are any more characters
  970. * in the buffer. Returns 0 on sucess, -1 on failure. */
  971. static INLINE int
  972. buf_pos_inc(buf_pos_t *pos)
  973. {
  974. ++pos->pos;
  975. if (pos->pos == (off_t)pos->chunk->datalen) {
  976. if (!pos->chunk->next)
  977. return -1;
  978. pos->chunk_pos += pos->chunk->datalen;
  979. pos->chunk = pos->chunk->next;
  980. pos->pos = 0;
  981. }
  982. return 0;
  983. }
  984. /** Return true iff the <b>n</b>-character string in <b>s</b> appears
  985. * (verbatim) at <b>pos</b>. */
  986. static int
  987. buf_matches_at_pos(const buf_pos_t *pos, const char *s, size_t n)
  988. {
  989. buf_pos_t p;
  990. if (!n)
  991. return 1;
  992. memcpy(&p, pos, sizeof(p));
  993. while (1) {
  994. char ch = p.chunk->data[p.pos];
  995. if (ch != *s)
  996. return 0;
  997. ++s;
  998. /* If we're out of characters that don't match, we match. Check this
  999. * _before_ we test incrementing pos, in case we're at the end of the
  1000. * string. */
  1001. if (--n == 0)
  1002. return 1;
  1003. if (buf_pos_inc(&p)<0)
  1004. return 0;
  1005. }
  1006. }
  1007. /** Return the first position in <b>buf</b> at which the <b>n</b>-character
  1008. * string <b>s</b> occurs, or -1 if it does not occur. */
  1009. /*private*/ int
  1010. buf_find_string_offset(const buf_t *buf, const char *s, size_t n)
  1011. {
  1012. buf_pos_t pos;
  1013. buf_pos_init(buf, &pos);
  1014. while (buf_find_pos_of_char(*s, &pos) >= 0) {
  1015. if (buf_matches_at_pos(&pos, s, n)) {
  1016. return pos.chunk_pos + pos.pos;
  1017. } else {
  1018. if (buf_pos_inc(&pos)<0)
  1019. return -1;
  1020. }
  1021. }
  1022. return -1;
  1023. }
  1024. /** There is a (possibly incomplete) http statement on <b>buf</b>, of the
  1025. * form "\%s\\r\\n\\r\\n\%s", headers, body. (body may contain nuls.)
  1026. * If a) the headers include a Content-Length field and all bytes in
  1027. * the body are present, or b) there's no Content-Length field and
  1028. * all headers are present, then:
  1029. *
  1030. * - strdup headers into <b>*headers_out</b>, and nul-terminate it.
  1031. * - memdup body into <b>*body_out</b>, and nul-terminate it.
  1032. * - Then remove them from <b>buf</b>, and return 1.
  1033. *
  1034. * - If headers or body is NULL, discard that part of the buf.
  1035. * - If a headers or body doesn't fit in the arg, return -1.
  1036. * (We ensure that the headers or body don't exceed max len,
  1037. * _even if_ we're planning to discard them.)
  1038. * - If force_complete is true, then succeed even if not all of the
  1039. * content has arrived.
  1040. *
  1041. * Else, change nothing and return 0.
  1042. */
  1043. int
  1044. fetch_from_buf_http(buf_t *buf,
  1045. char **headers_out, size_t max_headerlen,
  1046. char **body_out, size_t *body_used, size_t max_bodylen,
  1047. int force_complete)
  1048. {
  1049. char *headers, *p;
  1050. size_t headerlen, bodylen, contentlen;
  1051. int crlf_offset;
  1052. check();
  1053. if (!buf->head)
  1054. return 0;
  1055. crlf_offset = buf_find_string_offset(buf, "\r\n\r\n", 4);
  1056. if (crlf_offset > (int)max_headerlen ||
  1057. (crlf_offset < 0 && buf->datalen > max_headerlen)) {
  1058. log_debug(LD_HTTP,"headers too long.");
  1059. return -1;
  1060. } else if (crlf_offset < 0) {
  1061. log_debug(LD_HTTP,"headers not all here yet.");
  1062. return 0;
  1063. }
  1064. /* Okay, we have a full header. Make sure it all appears in the first
  1065. * chunk. */
  1066. if ((int)buf->head->datalen < crlf_offset + 4)
  1067. buf_pullup(buf, crlf_offset+4, 0);
  1068. headerlen = crlf_offset + 4;
  1069. headers = buf->head->data;
  1070. bodylen = buf->datalen - headerlen;
  1071. log_debug(LD_HTTP,"headerlen %d, bodylen %d.", (int)headerlen, (int)bodylen);
  1072. if (max_headerlen <= headerlen) {
  1073. log_warn(LD_HTTP,"headerlen %d larger than %d. Failing.",
  1074. (int)headerlen, (int)max_headerlen-1);
  1075. return -1;
  1076. }
  1077. if (max_bodylen <= bodylen) {
  1078. log_warn(LD_HTTP,"bodylen %d larger than %d. Failing.",
  1079. (int)bodylen, (int)max_bodylen-1);
  1080. return -1;
  1081. }
  1082. #define CONTENT_LENGTH "\r\nContent-Length: "
  1083. p = (char*) tor_memstr(headers, headerlen, CONTENT_LENGTH);
  1084. if (p) {
  1085. int i;
  1086. i = atoi(p+strlen(CONTENT_LENGTH));
  1087. if (i < 0) {
  1088. log_warn(LD_PROTOCOL, "Content-Length is less than zero; it looks like "
  1089. "someone is trying to crash us.");
  1090. return -1;
  1091. }
  1092. contentlen = i;
  1093. /* if content-length is malformed, then our body length is 0. fine. */
  1094. log_debug(LD_HTTP,"Got a contentlen of %d.",(int)contentlen);
  1095. if (bodylen < contentlen) {
  1096. if (!force_complete) {
  1097. log_debug(LD_HTTP,"body not all here yet.");
  1098. return 0; /* not all there yet */
  1099. }
  1100. }
  1101. if (bodylen > contentlen) {
  1102. bodylen = contentlen;
  1103. log_debug(LD_HTTP,"bodylen reduced to %d.",(int)bodylen);
  1104. }
  1105. }
  1106. /* all happy. copy into the appropriate places, and return 1 */
  1107. if (headers_out) {
  1108. *headers_out = tor_malloc(headerlen+1);
  1109. fetch_from_buf(*headers_out, headerlen, buf);
  1110. (*headers_out)[headerlen] = 0; /* nul terminate it */
  1111. }
  1112. if (body_out) {
  1113. tor_assert(body_used);
  1114. *body_used = bodylen;
  1115. *body_out = tor_malloc(bodylen+1);
  1116. fetch_from_buf(*body_out, bodylen, buf);
  1117. (*body_out)[bodylen] = 0; /* nul terminate it */
  1118. }
  1119. check();
  1120. return 1;
  1121. }
  1122. /** There is a (possibly incomplete) socks handshake on <b>buf</b>, of one
  1123. * of the forms
  1124. * - socks4: "socksheader username\\0"
  1125. * - socks4a: "socksheader username\\0 destaddr\\0"
  1126. * - socks5 phase one: "version #methods methods"
  1127. * - socks5 phase two: "version command 0 addresstype..."
  1128. * If it's a complete and valid handshake, and destaddr fits in
  1129. * MAX_SOCKS_ADDR_LEN bytes, then pull the handshake off the buf,
  1130. * assign to <b>req</b>, and return 1.
  1131. *
  1132. * If it's invalid or too big, return -1.
  1133. *
  1134. * Else it's not all there yet, leave buf alone and return 0.
  1135. *
  1136. * If you want to specify the socks reply, write it into <b>req->reply</b>
  1137. * and set <b>req->replylen</b>, else leave <b>req->replylen</b> alone.
  1138. *
  1139. * If <b>log_sockstype</b> is non-zero, then do a notice-level log of whether
  1140. * the connection is possibly leaking DNS requests locally or not.
  1141. *
  1142. * If <b>safe_socks</b> is true, then reject unsafe socks protocols.
  1143. *
  1144. * If returning 0 or -1, <b>req->address</b> and <b>req->port</b> are
  1145. * undefined.
  1146. */
  1147. int
  1148. fetch_from_buf_socks(buf_t *buf, socks_request_t *req,
  1149. int log_sockstype, int safe_socks)
  1150. {
  1151. unsigned int len;
  1152. char tmpbuf[INET_NTOA_BUF_LEN];
  1153. uint32_t destip;
  1154. uint8_t socksver;
  1155. enum {socks4, socks4a} socks4_prot = socks4a;
  1156. char *next, *startaddr;
  1157. struct in_addr in;
  1158. /* If the user connects with socks4 or the wrong variant of socks5,
  1159. * then log a warning to let him know that it might be unwise. */
  1160. static int have_warned_about_unsafe_socks = 0;
  1161. if (buf->datalen < 2) /* version and another byte */
  1162. return 0;
  1163. buf_pullup(buf, 128, 0);
  1164. tor_assert(buf->head && buf->head->datalen >= 2);
  1165. socksver = *buf->head->data;
  1166. switch (socksver) { /* which version of socks? */
  1167. case 5: /* socks5 */
  1168. if (req->socks_version != 5) { /* we need to negotiate a method */
  1169. unsigned char nummethods = (unsigned char)*(buf->head->data+1);
  1170. tor_assert(!req->socks_version);
  1171. if (buf->datalen < 2u+nummethods)
  1172. return 0;
  1173. buf_pullup(buf, 2u+nummethods, 0);
  1174. if (!nummethods || !memchr(buf->head->data+2, 0, nummethods)) {
  1175. log_warn(LD_APP,
  1176. "socks5: offered methods don't include 'no auth'. "
  1177. "Rejecting.");
  1178. req->replylen = 2; /* 2 bytes of response */
  1179. req->reply[0] = 5;
  1180. req->reply[1] = '\xFF'; /* reject all methods */
  1181. return -1;
  1182. }
  1183. /* remove packet from buf. also remove any other extraneous
  1184. * bytes, to support broken socks clients. */
  1185. buf_clear(buf);
  1186. req->replylen = 2; /* 2 bytes of response */
  1187. req->reply[0] = 5; /* socks5 reply */
  1188. req->reply[1] = SOCKS5_SUCCEEDED;
  1189. req->socks_version = 5; /* remember we've already negotiated auth */
  1190. log_debug(LD_APP,"socks5: accepted method 0");
  1191. return 0;
  1192. }
  1193. /* we know the method; read in the request */
  1194. log_debug(LD_APP,"socks5: checking request");
  1195. if (buf->datalen < 8) /* basic info plus >=2 for addr plus 2 for port */
  1196. return 0; /* not yet */
  1197. tor_assert(buf->head->datalen >= 8);
  1198. req->command = (unsigned char) *(buf->head->data+1);
  1199. if (req->command != SOCKS_COMMAND_CONNECT &&
  1200. req->command != SOCKS_COMMAND_RESOLVE &&
  1201. req->command != SOCKS_COMMAND_RESOLVE_PTR) {
  1202. /* not a connect or resolve or a resolve_ptr? we don't support it. */
  1203. log_warn(LD_APP,"socks5: command %d not recognized. Rejecting.",
  1204. req->command);
  1205. return -1;
  1206. }
  1207. switch (*(buf->head->data+3)) { /* address type */
  1208. case 1: /* IPv4 address */
  1209. log_debug(LD_APP,"socks5: ipv4 address type");
  1210. if (buf->datalen < 10) /* ip/port there? */
  1211. return 0; /* not yet */
  1212. destip = ntohl(*(uint32_t*)(buf->head->data+4));
  1213. in.s_addr = htonl(destip);
  1214. tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
  1215. if (strlen(tmpbuf)+1 > MAX_SOCKS_ADDR_LEN) {
  1216. log_warn(LD_APP,
  1217. "socks5 IP takes %d bytes, which doesn't fit in %d. "
  1218. "Rejecting.",
  1219. (int)strlen(tmpbuf)+1,(int)MAX_SOCKS_ADDR_LEN);
  1220. return -1;
  1221. }
  1222. strlcpy(req->address,tmpbuf,sizeof(req->address));
  1223. req->port = ntohs(*(uint16_t*)(buf->head->data+8));
  1224. buf_remove_from_front(buf, 10);
  1225. if (req->command != SOCKS_COMMAND_RESOLVE_PTR &&
  1226. !addressmap_have_mapping(req->address) &&
  1227. !have_warned_about_unsafe_socks) {
  1228. log_warn(LD_APP,
  1229. "Your application (using socks5 to port %d) is giving "
  1230. "Tor only an IP address. Applications that do DNS resolves "
  1231. "themselves may leak information. Consider using Socks4A "
  1232. "(e.g. via privoxy or socat) instead. For more information, "
  1233. "please see http://wiki.noreply.org/noreply/TheOnionRouter/"
  1234. "TorFAQ#SOCKSAndDNS.%s", req->port,
  1235. safe_socks ? " Rejecting." : "");
  1236. // have_warned_about_unsafe_socks = 1; // (for now, warn every time)
  1237. control_event_client_status(LOG_WARN,
  1238. "DANGEROUS_SOCKS PROTOCOL=SOCKS5 ADDRESS=%s:%d",
  1239. req->address, req->port);
  1240. if (safe_socks)
  1241. return -1;
  1242. }
  1243. return 1;
  1244. case 3: /* fqdn */
  1245. log_debug(LD_APP,"socks5: fqdn address type");
  1246. if (req->command == SOCKS_COMMAND_RESOLVE_PTR) {
  1247. log_warn(LD_APP, "socks5 received RESOLVE_PTR command with "
  1248. "hostname type. Rejecting.");
  1249. return -1;
  1250. }
  1251. len = (unsigned char)*(buf->head->data+4);
  1252. if (buf->datalen < 7+len) /* addr/port there? */
  1253. return 0; /* not yet */
  1254. buf_pullup(buf, 7+len, 0);
  1255. tor_assert(buf->head->datalen >= 7+len);
  1256. if (len+1 > MAX_SOCKS_ADDR_LEN) {
  1257. log_warn(LD_APP,
  1258. "socks5 hostname is %d bytes, which doesn't fit in "
  1259. "%d. Rejecting.", len+1,MAX_SOCKS_ADDR_LEN);
  1260. return -1;
  1261. }
  1262. memcpy(req->address,buf->head->data+5,len);
  1263. req->address[len] = 0;
  1264. req->port = ntohs(get_uint16(buf->head->data+5+len));
  1265. buf_remove_from_front(buf, 5+len+2);
  1266. if (!tor_strisprint(req->address) || strchr(req->address,'\"')) {
  1267. log_warn(LD_PROTOCOL,
  1268. "Your application (using socks5 to port %d) gave Tor "
  1269. "a malformed hostname: %s. Rejecting the connection.",
  1270. req->port, escaped(req->address));
  1271. return -1;
  1272. }
  1273. if (log_sockstype)
  1274. log_notice(LD_APP,
  1275. "Your application (using socks5 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. return 1;
  1279. default: /* unsupported */
  1280. log_warn(LD_APP,"socks5: unsupported address type %d. Rejecting.",
  1281. (int) *(buf->head->data+3));
  1282. return -1;
  1283. }
  1284. tor_assert(0);
  1285. case 4: /* socks4 */
  1286. /* http://archive.socks.permeo.com/protocol/socks4.protocol */
  1287. /* http://archive.socks.permeo.com/protocol/socks4a.protocol */
  1288. req->socks_version = 4;
  1289. if (buf->datalen < SOCKS4_NETWORK_LEN) /* basic info available? */
  1290. return 0; /* not yet */
  1291. buf_pullup(buf, 1280, 0);
  1292. req->command = (unsigned char) *(buf->head->data+1);
  1293. if (req->command != SOCKS_COMMAND_CONNECT &&
  1294. req->command != SOCKS_COMMAND_RESOLVE) {
  1295. /* not a connect or resolve? we don't support it. (No resolve_ptr with
  1296. * socks4.) */
  1297. log_warn(LD_APP,"socks4: command %d not recognized. Rejecting.",
  1298. req->command);
  1299. return -1;
  1300. }
  1301. req->port = ntohs(*(uint16_t*)(buf->head->data+2));
  1302. destip = ntohl(*(uint32_t*)(buf->head->data+4));
  1303. if ((!req->port && req->command!=SOCKS_COMMAND_RESOLVE) || !destip) {
  1304. log_warn(LD_APP,"socks4: Port or DestIP is zero. Rejecting.");
  1305. return -1;
  1306. }
  1307. if (destip >> 8) {
  1308. log_debug(LD_APP,"socks4: destip not in form 0.0.0.x.");
  1309. in.s_addr = htonl(destip);
  1310. tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
  1311. if (strlen(tmpbuf)+1 > MAX_SOCKS_ADDR_LEN) {
  1312. log_debug(LD_APP,"socks4 addr (%d bytes) too long. Rejecting.",
  1313. (int)strlen(tmpbuf));
  1314. return -1;
  1315. }
  1316. log_debug(LD_APP,
  1317. "socks4: successfully read destip (%s)", safe_str(tmpbuf));
  1318. socks4_prot = socks4;
  1319. }
  1320. next = memchr(buf->head->data+SOCKS4_NETWORK_LEN, 0,
  1321. buf->head->datalen-SOCKS4_NETWORK_LEN);
  1322. if (!next) {
  1323. if (buf->head->datalen >= 1024) {
  1324. log_debug(LD_APP, "Socks4 user name too long; rejecting.");
  1325. return -1;
  1326. }
  1327. log_debug(LD_APP,"socks4: Username not here yet.");
  1328. return 0;
  1329. }
  1330. tor_assert(next < CHUNK_WRITE_PTR(buf->head));
  1331. startaddr = NULL;
  1332. if (socks4_prot != socks4a &&
  1333. !addressmap_have_mapping(tmpbuf) &&
  1334. !have_warned_about_unsafe_socks) {
  1335. log_warn(LD_APP,
  1336. "Your application (using socks4 to port %d) is giving Tor "
  1337. "only an IP address. Applications that do DNS resolves "
  1338. "themselves may leak information. Consider using Socks4A "
  1339. "(e.g. via privoxy or socat) instead. For more information, "
  1340. "please see http://wiki.noreply.org/noreply/TheOnionRouter/"
  1341. "TorFAQ#SOCKSAndDNS.%s", req->port,
  1342. safe_socks ? " Rejecting." : "");
  1343. // have_warned_about_unsafe_socks = 1; // (for now, warn every time)
  1344. control_event_client_status(LOG_WARN,
  1345. "DANGEROUS_SOCKS PROTOCOL=SOCKS4 ADDRESS=%s:%d",
  1346. tmpbuf, req->port);
  1347. if (safe_socks)
  1348. return -1;
  1349. }
  1350. if (socks4_prot == socks4a) {
  1351. if (next+1 == CHUNK_WRITE_PTR(buf->head)) {
  1352. log_debug(LD_APP,"socks4: No part of destaddr here yet.");
  1353. return 0;
  1354. }
  1355. startaddr = next+1;
  1356. next = memchr(startaddr, 0, CHUNK_WRITE_PTR(buf->head)-startaddr);
  1357. if (!next) {
  1358. if (buf->head->datalen >= 1024) {
  1359. log_debug(LD_APP,"socks4: Destaddr too long.");
  1360. return -1;
  1361. }
  1362. log_debug(LD_APP,"socks4: Destaddr not all here yet.");
  1363. return 0;
  1364. }
  1365. if (MAX_SOCKS_ADDR_LEN <= next-startaddr) {
  1366. log_warn(LD_APP,"socks4: Destaddr too long. Rejecting.");
  1367. return -1;
  1368. }
  1369. // tor_assert(next < buf->cur+buf->datalen);
  1370. if (log_sockstype)
  1371. log_notice(LD_APP,
  1372. "Your application (using socks4a to port %d) gave "
  1373. "Tor a hostname, which means Tor will do the DNS resolve "
  1374. "for you. This is good.", req->port);
  1375. }
  1376. log_debug(LD_APP,"socks4: Everything is here. Success.");
  1377. strlcpy(req->address, startaddr ? startaddr : tmpbuf,
  1378. sizeof(req->address));
  1379. if (!tor_strisprint(req->address) || strchr(req->address,'\"')) {
  1380. log_warn(LD_PROTOCOL,
  1381. "Your application (using socks4 to port %d) gave Tor "
  1382. "a malformed hostname: %s. Rejecting the connection.",
  1383. req->port, escaped(req->address));
  1384. return -1;
  1385. }
  1386. /* next points to the final \0 on inbuf */
  1387. buf_remove_from_front(buf, next - buf->head->data + 1);
  1388. return 1;
  1389. case 'G': /* get */
  1390. case 'H': /* head */
  1391. case 'P': /* put/post */
  1392. case 'C': /* connect */
  1393. strlcpy(req->reply,
  1394. "HTTP/1.0 501 Tor is not an HTTP Proxy\r\n"
  1395. "Content-Type: text/html; charset=iso-8859-1\r\n\r\n"
  1396. "<html>\n"
  1397. "<head>\n"
  1398. "<title>Tor is not an HTTP Proxy</title>\n"
  1399. "</head>\n"
  1400. "<body>\n"
  1401. "<h1>Tor is not an HTTP Proxy</h1>\n"
  1402. "<p>\n"
  1403. "It appears you have configured your web browser to use Tor as an HTTP proxy."
  1404. "\n"
  1405. "This is not correct: Tor is a SOCKS proxy, not an HTTP proxy.\n"
  1406. "Please configure your client accordingly.\n"
  1407. "</p>\n"
  1408. "<p>\n"
  1409. "See <a href=\"https://www.torproject.org/documentation.html\">"
  1410. "https://www.torproject.org/documentation.html</a> for more "
  1411. "information.\n"
  1412. "<!-- Plus this comment, to make the body response more than 512 bytes, so "
  1413. " IE will be willing to display it. Comment comment comment comment "
  1414. " comment comment comment comment comment comment comment comment.-->\n"
  1415. "</p>\n"
  1416. "</body>\n"
  1417. "</html>\n"
  1418. , MAX_SOCKS_REPLY_LEN);
  1419. req->replylen = strlen(req->reply)+1;
  1420. /* fall through */
  1421. default: /* version is not socks4 or socks5 */
  1422. log_warn(LD_APP,
  1423. "Socks version %d not recognized. (Tor is not an http proxy.)",
  1424. *(buf->head->data));
  1425. {
  1426. char *tmp = tor_strndup(buf->head->data, 8); /*XXXX what if longer?*/
  1427. control_event_client_status(LOG_WARN,
  1428. "SOCKS_UNKNOWN_PROTOCOL DATA=\"%s\"",
  1429. escaped(tmp));
  1430. tor_free(tmp);
  1431. }
  1432. return -1;
  1433. }
  1434. }
  1435. /** Return 1 iff buf looks more like it has an (obsolete) v0 controller
  1436. * command on it than any valid v1 controller command. */
  1437. int
  1438. peek_buf_has_control0_command(buf_t *buf)
  1439. {
  1440. if (buf->datalen >= 4) {
  1441. char header[4];
  1442. uint16_t cmd;
  1443. peek_from_buf(header, sizeof(header), buf);
  1444. cmd = ntohs(get_uint16(header+2));
  1445. if (cmd <= 0x14)
  1446. return 1; /* This is definitely not a v1 control command. */
  1447. }
  1448. return 0;
  1449. }
  1450. /** Return the index within <b>buf</b> at which <b>ch</b> first appears,
  1451. * or -1 if <b>ch</b> does not appear on buf. */
  1452. static int
  1453. buf_find_offset_of_char(buf_t *buf, char ch)
  1454. {
  1455. chunk_t *chunk;
  1456. int offset = 0;
  1457. for (chunk = buf->head; chunk; chunk = chunk->next) {
  1458. char *cp = memchr(chunk->data, ch, chunk->datalen);
  1459. if (cp)
  1460. return offset + (cp - chunk->data);
  1461. else
  1462. offset += chunk->datalen;
  1463. }
  1464. return -1;
  1465. }
  1466. /** Try to read a single LF-terminated line from <b>buf</b>, and write it,
  1467. * NUL-terminated, into the *<b>data_len</b> byte buffer at <b>data_out</b>.
  1468. * Set *<b>data_len</b> to the number of bytes in the line, not counting the
  1469. * terminating NUL. Return 1 if we read a whole line, return 0 if we don't
  1470. * have a whole line yet, and return -1 if the line length exceeds
  1471. * *<b>data_len</b>.
  1472. */
  1473. int
  1474. fetch_from_buf_line(buf_t *buf, char *data_out, size_t *data_len)
  1475. {
  1476. size_t sz;
  1477. int offset;
  1478. if (!buf->head)
  1479. return 0;
  1480. offset = buf_find_offset_of_char(buf, '\n');
  1481. if (offset < 0)
  1482. return 0;
  1483. sz = (size_t) offset;
  1484. if (sz+2 > *data_len) {
  1485. *data_len = sz + 2;
  1486. return -1;
  1487. }
  1488. fetch_from_buf(data_out, sz+1, buf);
  1489. data_out[sz+1] = '\0';
  1490. *data_len = sz+1;
  1491. return 1;
  1492. }
  1493. /** Compress on uncompress the <b>data_len</b> bytes in <b>data</b> using the
  1494. * zlib state <b>state</b>, appending the result to <b>buf</b>. If
  1495. * <b>done</b> is true, flush the data in the state and finish the
  1496. * compression/uncompression. Return -1 on failure, 0 on success. */
  1497. int
  1498. write_to_buf_zlib(buf_t *buf, tor_zlib_state_t *state,
  1499. const char *data, size_t data_len,
  1500. int done)
  1501. {
  1502. char *next;
  1503. size_t old_avail, avail;
  1504. int over = 0;
  1505. do {
  1506. int need_new_chunk = 0;
  1507. if (!buf->tail || ! CHUNK_REMAINING_CAPACITY(buf->tail)) {
  1508. size_t cap = data_len / 4;
  1509. buf_add_chunk_with_capacity(buf, cap, 1);
  1510. }
  1511. next = CHUNK_WRITE_PTR(buf->tail);
  1512. avail = old_avail = CHUNK_REMAINING_CAPACITY(buf->tail);
  1513. switch (tor_zlib_process(state, &next, &avail, &data, &data_len, done)) {
  1514. case TOR_ZLIB_DONE:
  1515. over = 1;
  1516. break;
  1517. case TOR_ZLIB_ERR:
  1518. return -1;
  1519. case TOR_ZLIB_OK:
  1520. if (data_len == 0)
  1521. over = 1;
  1522. break;
  1523. case TOR_ZLIB_BUF_FULL:
  1524. if (avail) {
  1525. /* Zlib says we need more room (ZLIB_BUF_FULL). Start a new chunk
  1526. * automatically, whether were going to or not. */
  1527. need_new_chunk = 1;
  1528. }
  1529. break;
  1530. }
  1531. buf->datalen += old_avail - avail;
  1532. buf->tail->datalen += old_avail - avail;
  1533. if (need_new_chunk) {
  1534. buf_add_chunk_with_capacity(buf, data_len/4, 1);
  1535. }
  1536. } while (!over);
  1537. check();
  1538. return 0;
  1539. }
  1540. /** Log an error and exit if <b>buf</b> is corrupted.
  1541. */
  1542. void
  1543. assert_buf_ok(buf_t *buf)
  1544. {
  1545. tor_assert(buf);
  1546. tor_assert(buf->magic == BUFFER_MAGIC);
  1547. if (! buf->head) {
  1548. tor_assert(!buf->tail);
  1549. tor_assert(buf->datalen == 0);
  1550. } else {
  1551. chunk_t *ch;
  1552. size_t total = 0;
  1553. tor_assert(buf->tail);
  1554. for (ch = buf->head; ch; ch = ch->next) {
  1555. total += ch->datalen;
  1556. tor_assert(ch->datalen <= ch->memlen);
  1557. tor_assert(ch->data >= &ch->mem[0]);
  1558. tor_assert(ch->data < &ch->mem[0]+ch->memlen);
  1559. tor_assert(ch->data+ch->datalen <= &ch->mem[0] + ch->memlen);
  1560. if (!ch->next)
  1561. tor_assert(ch == buf->tail);
  1562. }
  1563. tor_assert(buf->datalen == total);
  1564. }
  1565. }
  1566. #ifdef ENABLE_BUF_FREELISTS
  1567. /** Log an error and exit if <b>fl</b> is corrupted.
  1568. */
  1569. static void
  1570. assert_freelist_ok(chunk_freelist_t *fl)
  1571. {
  1572. chunk_t *ch;
  1573. int n;
  1574. tor_assert(fl->alloc_size > 0);
  1575. n = 0;
  1576. for (ch = fl->head; ch; ch = ch->next) {
  1577. tor_assert(CHUNK_ALLOC_SIZE(ch->memlen) == fl->alloc_size);
  1578. ++n;
  1579. }
  1580. tor_assert(n == fl->cur_length);
  1581. tor_assert(n >= fl->lowest_length);
  1582. tor_assert(n <= fl->max_length);
  1583. }
  1584. #endif