buffers.c 59 KB

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