buffers.c 59 KB

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