buffers.c 51 KB

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