buffers.c 59 KB

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