buffers.c 59 KB

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