buffers.c 58 KB

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