buffers.c 70 KB

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