buffers.c 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319
  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[1]; /**< The actual memory used for storage in this chunk. May be
  65. * more than one byte long. */
  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, int 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. int
  598. read_to_buf(int s, size_t at_most, buf_t *buf, int *reached_eof,
  599. int *socket_error)
  600. {
  601. int r = 0;
  602. size_t total_read = 0;
  603. check();
  604. tor_assert(reached_eof);
  605. tor_assert(s >= 0);
  606. while (at_most > total_read) {
  607. size_t readlen = at_most - total_read;
  608. chunk_t *chunk;
  609. if (!buf->tail || CHUNK_REMAINING_CAPACITY(buf->tail) < MIN_READ_LEN) {
  610. chunk = buf_add_chunk_with_capacity(buf, at_most, 1);
  611. if (readlen > chunk->memlen)
  612. readlen = chunk->memlen;
  613. } else {
  614. size_t cap = CHUNK_REMAINING_CAPACITY(buf->tail);
  615. chunk = buf->tail;
  616. if (cap < readlen)
  617. readlen = cap;
  618. }
  619. r = read_to_chunk(buf, chunk, s, readlen, reached_eof, socket_error);
  620. check();
  621. if (r < 0)
  622. return r; /* Error */
  623. tor_assert(total_read+r < INT_MAX);
  624. total_read += r;
  625. if ((size_t)r < readlen) { /* eof, block, or no more to read. */
  626. break;
  627. }
  628. }
  629. return (int)total_read;
  630. }
  631. /** As read_to_buf, but reads from a TLS connection, and returns a TLS
  632. * status value rather than the number of bytes read.
  633. *
  634. * Using TLS on OR connections complicates matters in two ways.
  635. *
  636. * First, a TLS stream has its own read buffer independent of the
  637. * connection's read buffer. (TLS needs to read an entire frame from
  638. * the network before it can decrypt any data. Thus, trying to read 1
  639. * byte from TLS can require that several KB be read from the network
  640. * and decrypted. The extra data is stored in TLS's decrypt buffer.)
  641. * Because the data hasn't been read by Tor (it's still inside the TLS),
  642. * this means that sometimes a connection "has stuff to read" even when
  643. * poll() didn't return POLLIN. The tor_tls_get_pending_bytes function is
  644. * used in connection.c to detect TLS objects with non-empty internal
  645. * buffers and read from them again.
  646. *
  647. * Second, the TLS stream's events do not correspond directly to network
  648. * events: sometimes, before a TLS stream can read, the network must be
  649. * ready to write -- or vice versa.
  650. */
  651. int
  652. read_to_buf_tls(tor_tls_t *tls, size_t at_most, buf_t *buf)
  653. {
  654. int r = 0;
  655. size_t total_read = 0;
  656. check();
  657. while (at_most > total_read) {
  658. size_t readlen = at_most - total_read;
  659. chunk_t *chunk;
  660. if (!buf->tail || CHUNK_REMAINING_CAPACITY(buf->tail) < MIN_READ_LEN) {
  661. chunk = buf_add_chunk_with_capacity(buf, at_most, 1);
  662. if (readlen > chunk->memlen)
  663. readlen = chunk->memlen;
  664. } else {
  665. size_t cap = CHUNK_REMAINING_CAPACITY(buf->tail);
  666. chunk = buf->tail;
  667. if (cap < readlen)
  668. readlen = cap;
  669. }
  670. r = read_to_chunk_tls(buf, chunk, tls, readlen);
  671. check();
  672. if (r < 0)
  673. return r; /* Error */
  674. tor_assert(total_read+r < INT_MAX);
  675. total_read += r;
  676. if ((size_t)r < readlen) /* eof, block, or no more to read. */
  677. break;
  678. }
  679. return (int)total_read;
  680. }
  681. /** Helper for flush_buf(): try to write <b>sz</b> bytes from chunk
  682. * <b>chunk</b> of buffer <b>buf</b> onto socket <b>s</b>. On success, deduct
  683. * the bytes written from *<b>buf_flushlen</b>. Return the number of bytes
  684. * written on success, 0 on blocking, -1 on failure.
  685. */
  686. static INLINE int
  687. flush_chunk(int s, buf_t *buf, chunk_t *chunk, size_t sz,
  688. size_t *buf_flushlen)
  689. {
  690. ssize_t write_result;
  691. if (sz > chunk->datalen)
  692. sz = chunk->datalen;
  693. write_result = tor_socket_send(s, chunk->data, sz, 0);
  694. if (write_result < 0) {
  695. int e = tor_socket_errno(s);
  696. if (!ERRNO_IS_EAGAIN(e)) { /* it's a real error */
  697. #ifdef MS_WINDOWS
  698. if (e == WSAENOBUFS)
  699. log_warn(LD_NET,"write() failed: WSAENOBUFS. Not enough ram?");
  700. #endif
  701. return -1;
  702. }
  703. log_debug(LD_NET,"write() would block, returning.");
  704. return 0;
  705. } else {
  706. *buf_flushlen -= write_result;
  707. buf_remove_from_front(buf, write_result);
  708. tor_assert(write_result < INT_MAX);
  709. return (int)write_result;
  710. }
  711. }
  712. /** Helper for flush_buf_tls(): try to write <b>sz</b> bytes from chunk
  713. * <b>chunk</b> of buffer <b>buf</b> onto socket <b>s</b>. (Tries to write
  714. * more if there is a forced pending write size.) On success, deduct the
  715. * bytes written from *<b>buf_flushlen</b>. Return the number of bytes
  716. * written on success, and a TOR_TLS error code on failure or blocking.
  717. */
  718. static INLINE int
  719. flush_chunk_tls(tor_tls_t *tls, buf_t *buf, chunk_t *chunk,
  720. size_t sz, size_t *buf_flushlen)
  721. {
  722. int r;
  723. size_t forced;
  724. char *data;
  725. forced = tor_tls_get_forced_write_size(tls);
  726. if (forced > sz)
  727. sz = forced;
  728. if (chunk) {
  729. data = chunk->data;
  730. tor_assert(sz <= chunk->datalen);
  731. } else {
  732. data = NULL;
  733. tor_assert(sz == 0);
  734. }
  735. r = tor_tls_write(tls, data, sz);
  736. if (r < 0)
  737. return r;
  738. if (*buf_flushlen > (size_t)r)
  739. *buf_flushlen -= r;
  740. else
  741. *buf_flushlen = 0;
  742. buf_remove_from_front(buf, r);
  743. log_debug(LD_NET,"flushed %d bytes, %d ready to flush, %d remain.",
  744. r,(int)*buf_flushlen,(int)buf->datalen);
  745. return r;
  746. }
  747. /** Write data from <b>buf</b> to the socket <b>s</b>. Write at most
  748. * <b>sz</b> bytes, decrement *<b>buf_flushlen</b> by
  749. * the number of bytes actually written, and remove the written bytes
  750. * from the buffer. Return the number of bytes written on success,
  751. * -1 on failure. Return 0 if write() would block.
  752. */
  753. int
  754. flush_buf(int s, buf_t *buf, size_t sz, size_t *buf_flushlen)
  755. {
  756. int r;
  757. size_t flushed = 0;
  758. tor_assert(buf_flushlen);
  759. tor_assert(s >= 0);
  760. tor_assert(*buf_flushlen <= buf->datalen);
  761. tor_assert(sz <= *buf_flushlen);
  762. check();
  763. while (sz) {
  764. size_t flushlen0;
  765. tor_assert(buf->head);
  766. if (buf->head->datalen >= sz)
  767. flushlen0 = sz;
  768. else
  769. flushlen0 = buf->head->datalen;
  770. r = flush_chunk(s, buf, buf->head, flushlen0, buf_flushlen);
  771. check();
  772. if (r < 0)
  773. return r;
  774. flushed += r;
  775. sz -= r;
  776. if (r == 0 || (size_t)r < flushlen0) /* can't flush any more now. */
  777. break;
  778. }
  779. tor_assert(flushed < INT_MAX);
  780. return (int)flushed;
  781. }
  782. /** As flush_buf(), but writes data to a TLS connection. Can write more than
  783. * <b>flushlen</b> bytes.
  784. */
  785. int
  786. flush_buf_tls(tor_tls_t *tls, buf_t *buf, size_t flushlen,
  787. size_t *buf_flushlen)
  788. {
  789. int r;
  790. size_t flushed = 0;
  791. ssize_t sz;
  792. tor_assert(buf_flushlen);
  793. tor_assert(*buf_flushlen <= buf->datalen);
  794. tor_assert(flushlen <= *buf_flushlen);
  795. sz = (ssize_t) flushlen;
  796. /* we want to let tls write even if flushlen is zero, because it might
  797. * have a partial record pending */
  798. check_no_tls_errors();
  799. check();
  800. do {
  801. size_t flushlen0;
  802. if (buf->head) {
  803. if ((ssize_t)buf->head->datalen >= sz)
  804. flushlen0 = sz;
  805. else
  806. flushlen0 = buf->head->datalen;
  807. } else {
  808. flushlen0 = 0;
  809. }
  810. r = flush_chunk_tls(tls, buf, buf->head, flushlen0, buf_flushlen);
  811. check();
  812. if (r < 0)
  813. return r;
  814. flushed += r;
  815. sz -= r;
  816. if (r == 0) /* Can't flush any more now. */
  817. break;
  818. } while (sz > 0);
  819. tor_assert(flushed < INT_MAX);
  820. return (int)flushed;
  821. }
  822. /** Append <b>string_len</b> bytes from <b>string</b> to the end of
  823. * <b>buf</b>.
  824. *
  825. * Return the new length of the buffer on success, -1 on failure.
  826. */
  827. int
  828. write_to_buf(const char *string, size_t string_len, buf_t *buf)
  829. {
  830. if (!string_len)
  831. return (int)buf->datalen;
  832. check();
  833. while (string_len) {
  834. size_t copy;
  835. if (!buf->tail || !CHUNK_REMAINING_CAPACITY(buf->tail))
  836. buf_add_chunk_with_capacity(buf, string_len, 1);
  837. copy = CHUNK_REMAINING_CAPACITY(buf->tail);
  838. if (copy > string_len)
  839. copy = string_len;
  840. memcpy(CHUNK_WRITE_PTR(buf->tail), string, copy);
  841. string_len -= copy;
  842. string += copy;
  843. buf->datalen += copy;
  844. buf->tail->datalen += copy;
  845. }
  846. check();
  847. tor_assert(buf->datalen < INT_MAX);
  848. return (int)buf->datalen;
  849. }
  850. /** Helper: copy the first <b>string_len</b> bytes from <b>buf</b>
  851. * onto <b>string</b>.
  852. */
  853. static INLINE void
  854. peek_from_buf(char *string, size_t string_len, const buf_t *buf)
  855. {
  856. chunk_t *chunk;
  857. tor_assert(string);
  858. /* make sure we don't ask for too much */
  859. tor_assert(string_len <= buf->datalen);
  860. /* assert_buf_ok(buf); */
  861. chunk = buf->head;
  862. while (string_len) {
  863. size_t copy = string_len;
  864. tor_assert(chunk);
  865. if (chunk->datalen < copy)
  866. copy = chunk->datalen;
  867. memcpy(string, chunk->data, copy);
  868. string_len -= copy;
  869. string += copy;
  870. chunk = chunk->next;
  871. }
  872. }
  873. /** Remove <b>string_len</b> bytes from the front of <b>buf</b>, and store
  874. * them into <b>string</b>. Return the new buffer size. <b>string_len</b>
  875. * must be \<= the number of bytes on the buffer.
  876. */
  877. int
  878. fetch_from_buf(char *string, size_t string_len, buf_t *buf)
  879. {
  880. /* There must be string_len bytes in buf; write them onto string,
  881. * then memmove buf back (that is, remove them from buf).
  882. *
  883. * Return the number of bytes still on the buffer. */
  884. check();
  885. peek_from_buf(string, string_len, buf);
  886. buf_remove_from_front(buf, string_len);
  887. check();
  888. tor_assert(buf->datalen < INT_MAX);
  889. return (int)buf->datalen;
  890. }
  891. /** Check <b>buf</b> for a variable-length cell according to the rules of link
  892. * protocol version <b>linkproto</b>. If one is found, pull it off the buffer
  893. * and assign a newly allocated var_cell_t to *<b>out</b>, and return 1.
  894. * Return 0 if whatever is on the start of buf_t is not a variable-length
  895. * cell. Return 1 and set *<b>out</b> to NULL if there seems to be the start
  896. * of a variable-length cell on <b>buf</b>, but the whole thing isn't there
  897. * yet. */
  898. int
  899. fetch_var_cell_from_buf(buf_t *buf, var_cell_t **out, int linkproto)
  900. {
  901. char hdr[VAR_CELL_HEADER_SIZE];
  902. var_cell_t *result;
  903. uint8_t command;
  904. uint16_t length;
  905. /* If linkproto is unknown (0) or v2 (2), variable-length cells work as
  906. * implemented here. If it's 1, there are no variable-length cells. Tor
  907. * does not support other versions right now, and so can't negotiate them.
  908. */
  909. if (linkproto == 1)
  910. return 0;
  911. check();
  912. *out = NULL;
  913. if (buf->datalen < VAR_CELL_HEADER_SIZE)
  914. return 0;
  915. peek_from_buf(hdr, sizeof(hdr), buf);
  916. command = get_uint8(hdr+2);
  917. if (!(CELL_COMMAND_IS_VAR_LENGTH(command)))
  918. return 0;
  919. length = ntohs(get_uint16(hdr+3));
  920. if (buf->datalen < (size_t)(VAR_CELL_HEADER_SIZE+length))
  921. return 1;
  922. result = var_cell_new(length);
  923. result->command = command;
  924. result->circ_id = ntohs(get_uint16(hdr));
  925. buf_remove_from_front(buf, VAR_CELL_HEADER_SIZE);
  926. peek_from_buf((char*) result->payload, length, buf);
  927. buf_remove_from_front(buf, length);
  928. check();
  929. *out = result;
  930. return 1;
  931. }
  932. #ifdef USE_BUFFEREVENTS
  933. /** Try to read <b>n</b> bytes from <b>buf</b> at <b>pos</b> (which may be
  934. * NULL for the start of the buffer), copying the data only if necessary. Set
  935. * *<b>data</b> to a pointer to the desired bytes. Set <b>free_out</b> to 1
  936. * if we needed to malloc *<b>data</b> because the original bytes were
  937. * noncontiguous; 0 otherwise. Return the number of bytes actually available
  938. * at <b>data</b>.
  939. */
  940. static ssize_t
  941. inspect_evbuffer(struct evbuffer *buf, char **data, size_t n, int *free_out,
  942. struct evbuffer_ptr *pos)
  943. {
  944. int n_vecs, i;
  945. if (evbuffer_get_length(buf) < n)
  946. n = evbuffer_get_length(buf);
  947. if (n == 0)
  948. return 0;
  949. n_vecs = evbuffer_peek(buf, n, pos, NULL, 0);
  950. tor_assert(n_vecs > 0);
  951. if (n_vecs == 1) {
  952. struct evbuffer_iovec v;
  953. i = evbuffer_peek(buf, n, pos, &v, 1);
  954. tor_assert(i == 1);
  955. *data = v.iov_base;
  956. *free_out = 0;
  957. return v.iov_len;
  958. } else {
  959. struct evbuffer_iovec *vecs =
  960. tor_malloc(sizeof(struct evbuffer_iovec)*n_vecs);
  961. size_t copied = 0;
  962. i = evbuffer_peek(buf, n, NULL, vecs, n_vecs);
  963. tor_assert(i == n_vecs);
  964. *data = tor_malloc(n);
  965. for (i=0; i < n_vecs; ++i) {
  966. size_t copy = n - copied;
  967. if (copy > vecs[i].iov_len)
  968. copy = vecs[i].iov_len;
  969. tor_assert(copied+copy <= n);
  970. memcpy(data+copied, vecs[i].iov_base, copy);
  971. copied += copy;
  972. }
  973. *free_out = 1;
  974. return copied;
  975. }
  976. }
  977. /** As fetch_var_cell_from_buf, buf works on an evbuffer. */
  978. int
  979. fetch_var_cell_from_evbuffer(struct evbuffer *buf, var_cell_t **out,
  980. int linkproto)
  981. {
  982. char *hdr = NULL;
  983. int free_hdr = 0;
  984. size_t n;
  985. size_t buf_len;
  986. uint8_t command;
  987. uint16_t cell_length;
  988. var_cell_t *cell;
  989. int result = 0;
  990. if (linkproto == 1)
  991. return 0;
  992. *out = NULL;
  993. buf_len = evbuffer_get_length(buf);
  994. if (buf_len < VAR_CELL_HEADER_SIZE)
  995. return 0;
  996. n = inspect_evbuffer(buf, &hdr, VAR_CELL_HEADER_SIZE, &free_hdr, NULL);
  997. tor_assert(n >= VAR_CELL_HEADER_SIZE);
  998. command = get_uint8(hdr+2);
  999. if (!(CELL_COMMAND_IS_VAR_LENGTH(command))) {
  1000. goto done;
  1001. }
  1002. cell_length = ntohs(get_uint16(hdr+3));
  1003. if (buf_len < (size_t)(VAR_CELL_HEADER_SIZE+cell_length)) {
  1004. result = 1; /* Not all here yet. */
  1005. goto done;
  1006. }
  1007. cell = var_cell_new(cell_length);
  1008. cell->command = command;
  1009. cell->circ_id = ntohs(get_uint16(hdr));
  1010. evbuffer_drain(buf, VAR_CELL_HEADER_SIZE);
  1011. evbuffer_remove(buf, cell->payload, cell_length);
  1012. *out = cell;
  1013. result = 1;
  1014. done:
  1015. if (free_hdr && hdr)
  1016. tor_free(hdr);
  1017. return result;
  1018. }
  1019. #endif
  1020. /** Move up to *<b>buf_flushlen</b> bytes from <b>buf_in</b> to
  1021. * <b>buf_out</b>, and modify *<b>buf_flushlen</b> appropriately.
  1022. * Return the number of bytes actually copied.
  1023. */
  1024. int
  1025. move_buf_to_buf(buf_t *buf_out, buf_t *buf_in, size_t *buf_flushlen)
  1026. {
  1027. /* We can do way better here, but this doesn't turn up in any profiles. */
  1028. char b[4096];
  1029. size_t cp, len;
  1030. len = *buf_flushlen;
  1031. if (len > buf_in->datalen)
  1032. len = buf_in->datalen;
  1033. cp = len; /* Remember the number of bytes we intend to copy. */
  1034. tor_assert(cp < INT_MAX);
  1035. while (len) {
  1036. /* This isn't the most efficient implementation one could imagine, since
  1037. * it does two copies instead of 1, but I kinda doubt that this will be
  1038. * critical path. */
  1039. size_t n = len > sizeof(b) ? sizeof(b) : len;
  1040. fetch_from_buf(b, n, buf_in);
  1041. write_to_buf(b, n, buf_out);
  1042. len -= n;
  1043. }
  1044. *buf_flushlen -= cp;
  1045. return (int)cp;
  1046. }
  1047. /** Internal structure: represents a position in a buffer. */
  1048. typedef struct buf_pos_t {
  1049. const chunk_t *chunk; /**< Which chunk are we pointing to? */
  1050. int pos;/**< Which character inside the chunk's data are we pointing to? */
  1051. size_t chunk_pos; /**< Total length of all previous chunks. */
  1052. } buf_pos_t;
  1053. /** Initialize <b>out</b> to point to the first character of <b>buf</b>.*/
  1054. static void
  1055. buf_pos_init(const buf_t *buf, buf_pos_t *out)
  1056. {
  1057. out->chunk = buf->head;
  1058. out->pos = 0;
  1059. out->chunk_pos = 0;
  1060. }
  1061. /** Advance <b>out</b> to the first appearance of <b>ch</b> at the current
  1062. * position of <b>out</b>, or later. Return -1 if no instances are found;
  1063. * otherwise returns the absolute position of the character. */
  1064. static off_t
  1065. buf_find_pos_of_char(char ch, buf_pos_t *out)
  1066. {
  1067. const chunk_t *chunk;
  1068. int pos;
  1069. tor_assert(out);
  1070. if (out->chunk) {
  1071. if (out->chunk->datalen) {
  1072. tor_assert(out->pos < (off_t)out->chunk->datalen);
  1073. } else {
  1074. tor_assert(out->pos == 0);
  1075. }
  1076. }
  1077. pos = out->pos;
  1078. for (chunk = out->chunk; chunk; chunk = chunk->next) {
  1079. char *cp = memchr(chunk->data+pos, ch, chunk->datalen - pos);
  1080. if (cp) {
  1081. out->chunk = chunk;
  1082. tor_assert(cp - chunk->data < INT_MAX);
  1083. out->pos = (int)(cp - chunk->data);
  1084. return out->chunk_pos + out->pos;
  1085. } else {
  1086. out->chunk_pos += chunk->datalen;
  1087. pos = 0;
  1088. }
  1089. }
  1090. return -1;
  1091. }
  1092. /** Advance <b>pos</b> by a single character, if there are any more characters
  1093. * in the buffer. Returns 0 on success, -1 on failure. */
  1094. static INLINE int
  1095. buf_pos_inc(buf_pos_t *pos)
  1096. {
  1097. ++pos->pos;
  1098. if (pos->pos == (off_t)pos->chunk->datalen) {
  1099. if (!pos->chunk->next)
  1100. return -1;
  1101. pos->chunk_pos += pos->chunk->datalen;
  1102. pos->chunk = pos->chunk->next;
  1103. pos->pos = 0;
  1104. }
  1105. return 0;
  1106. }
  1107. /** Return true iff the <b>n</b>-character string in <b>s</b> appears
  1108. * (verbatim) at <b>pos</b>. */
  1109. static int
  1110. buf_matches_at_pos(const buf_pos_t *pos, const char *s, size_t n)
  1111. {
  1112. buf_pos_t p;
  1113. if (!n)
  1114. return 1;
  1115. memcpy(&p, pos, sizeof(p));
  1116. while (1) {
  1117. char ch = p.chunk->data[p.pos];
  1118. if (ch != *s)
  1119. return 0;
  1120. ++s;
  1121. /* If we're out of characters that don't match, we match. Check this
  1122. * _before_ we test incrementing pos, in case we're at the end of the
  1123. * string. */
  1124. if (--n == 0)
  1125. return 1;
  1126. if (buf_pos_inc(&p)<0)
  1127. return 0;
  1128. }
  1129. }
  1130. /** Return the first position in <b>buf</b> at which the <b>n</b>-character
  1131. * string <b>s</b> occurs, or -1 if it does not occur. */
  1132. /*private*/ int
  1133. buf_find_string_offset(const buf_t *buf, const char *s, size_t n)
  1134. {
  1135. buf_pos_t pos;
  1136. buf_pos_init(buf, &pos);
  1137. while (buf_find_pos_of_char(*s, &pos) >= 0) {
  1138. if (buf_matches_at_pos(&pos, s, n)) {
  1139. tor_assert(pos.chunk_pos + pos.pos < INT_MAX);
  1140. return (int)(pos.chunk_pos + pos.pos);
  1141. } else {
  1142. if (buf_pos_inc(&pos)<0)
  1143. return -1;
  1144. }
  1145. }
  1146. return -1;
  1147. }
  1148. /** There is a (possibly incomplete) http statement on <b>buf</b>, of the
  1149. * form "\%s\\r\\n\\r\\n\%s", headers, body. (body may contain NULs.)
  1150. * If a) the headers include a Content-Length field and all bytes in
  1151. * the body are present, or b) there's no Content-Length field and
  1152. * all headers are present, then:
  1153. *
  1154. * - strdup headers into <b>*headers_out</b>, and NUL-terminate it.
  1155. * - memdup body into <b>*body_out</b>, and NUL-terminate it.
  1156. * - Then remove them from <b>buf</b>, and return 1.
  1157. *
  1158. * - If headers or body is NULL, discard that part of the buf.
  1159. * - If a headers or body doesn't fit in the arg, return -1.
  1160. * (We ensure that the headers or body don't exceed max len,
  1161. * _even if_ we're planning to discard them.)
  1162. * - If force_complete is true, then succeed even if not all of the
  1163. * content has arrived.
  1164. *
  1165. * Else, change nothing and return 0.
  1166. */
  1167. int
  1168. fetch_from_buf_http(buf_t *buf,
  1169. char **headers_out, size_t max_headerlen,
  1170. char **body_out, size_t *body_used, size_t max_bodylen,
  1171. int force_complete)
  1172. {
  1173. char *headers, *p;
  1174. size_t headerlen, bodylen, contentlen;
  1175. int crlf_offset;
  1176. check();
  1177. if (!buf->head)
  1178. return 0;
  1179. crlf_offset = buf_find_string_offset(buf, "\r\n\r\n", 4);
  1180. if (crlf_offset > (int)max_headerlen ||
  1181. (crlf_offset < 0 && buf->datalen > max_headerlen)) {
  1182. log_debug(LD_HTTP,"headers too long.");
  1183. return -1;
  1184. } else if (crlf_offset < 0) {
  1185. log_debug(LD_HTTP,"headers not all here yet.");
  1186. return 0;
  1187. }
  1188. /* Okay, we have a full header. Make sure it all appears in the first
  1189. * chunk. */
  1190. if ((int)buf->head->datalen < crlf_offset + 4)
  1191. buf_pullup(buf, crlf_offset+4, 0);
  1192. headerlen = crlf_offset + 4;
  1193. headers = buf->head->data;
  1194. bodylen = buf->datalen - headerlen;
  1195. log_debug(LD_HTTP,"headerlen %d, bodylen %d.", (int)headerlen, (int)bodylen);
  1196. if (max_headerlen <= headerlen) {
  1197. log_warn(LD_HTTP,"headerlen %d larger than %d. Failing.",
  1198. (int)headerlen, (int)max_headerlen-1);
  1199. return -1;
  1200. }
  1201. if (max_bodylen <= bodylen) {
  1202. log_warn(LD_HTTP,"bodylen %d larger than %d. Failing.",
  1203. (int)bodylen, (int)max_bodylen-1);
  1204. return -1;
  1205. }
  1206. #define CONTENT_LENGTH "\r\nContent-Length: "
  1207. p = (char*) tor_memstr(headers, headerlen, CONTENT_LENGTH);
  1208. if (p) {
  1209. int i;
  1210. i = atoi(p+strlen(CONTENT_LENGTH));
  1211. if (i < 0) {
  1212. log_warn(LD_PROTOCOL, "Content-Length is less than zero; it looks like "
  1213. "someone is trying to crash us.");
  1214. return -1;
  1215. }
  1216. contentlen = i;
  1217. /* if content-length is malformed, then our body length is 0. fine. */
  1218. log_debug(LD_HTTP,"Got a contentlen of %d.",(int)contentlen);
  1219. if (bodylen < contentlen) {
  1220. if (!force_complete) {
  1221. log_debug(LD_HTTP,"body not all here yet.");
  1222. return 0; /* not all there yet */
  1223. }
  1224. }
  1225. if (bodylen > contentlen) {
  1226. bodylen = contentlen;
  1227. log_debug(LD_HTTP,"bodylen reduced to %d.",(int)bodylen);
  1228. }
  1229. }
  1230. /* all happy. copy into the appropriate places, and return 1 */
  1231. if (headers_out) {
  1232. *headers_out = tor_malloc(headerlen+1);
  1233. fetch_from_buf(*headers_out, headerlen, buf);
  1234. (*headers_out)[headerlen] = 0; /* NUL terminate it */
  1235. }
  1236. if (body_out) {
  1237. tor_assert(body_used);
  1238. *body_used = bodylen;
  1239. *body_out = tor_malloc(bodylen+1);
  1240. fetch_from_buf(*body_out, bodylen, buf);
  1241. (*body_out)[bodylen] = 0; /* NUL terminate it */
  1242. }
  1243. check();
  1244. return 1;
  1245. }
  1246. #ifdef USE_BUFFEREVENTS
  1247. /** As fetch_from_buf_http, buf works on an evbuffer. */
  1248. int
  1249. fetch_from_evbuffer_http(struct evbuffer *buf,
  1250. char **headers_out, size_t max_headerlen,
  1251. char **body_out, size_t *body_used, size_t max_bodylen,
  1252. int force_complete)
  1253. {
  1254. struct evbuffer_ptr crlf, content_length;
  1255. size_t headerlen, bodylen, contentlen;
  1256. /* Find the first \r\n\r\n in the buffer */
  1257. crlf = evbuffer_search(buf, "\r\n\r\n", 4, NULL);
  1258. if (crlf.pos < 0) {
  1259. /* We didn't find one. */
  1260. if (evbuffer_get_length(buf) > max_headerlen)
  1261. return -1; /* Headers too long. */
  1262. return 0; /* Headers not here yet. */
  1263. } else if (crlf.pos > (int)max_headerlen) {
  1264. return -1; /* Headers too long. */
  1265. }
  1266. headerlen = crlf.pos + 4; /* Skip over the \r\n\r\n */
  1267. bodylen = evbuffer_get_length(buf) - headerlen;
  1268. if (bodylen > max_bodylen)
  1269. return -1; /* body too long */
  1270. /* Look for the first occurrence of CONTENT_LENGTH insize buf before the
  1271. * crlfcrlf */
  1272. content_length = evbuffer_search_range(buf, CONTENT_LENGTH,
  1273. strlen(CONTENT_LENGTH), NULL, &crlf);
  1274. if (content_length.pos >= 0) {
  1275. /* We found a content_length: parse it and figure out if the body is here
  1276. * yet. */
  1277. struct evbuffer_ptr eol;
  1278. char *data = NULL;
  1279. int free_data = 0;
  1280. int n, i;
  1281. n = evbuffer_ptr_set(buf, &content_length, strlen(CONTENT_LENGTH),
  1282. EVBUFFER_PTR_ADD);
  1283. tor_assert(n == 0);
  1284. eol = evbuffer_search_eol(buf, &content_length, NULL, EVBUFFER_EOL_CRLF);
  1285. tor_assert(eol.pos > content_length.pos);
  1286. tor_assert(eol.pos <= crlf.pos);
  1287. inspect_evbuffer(buf, &data, eol.pos - content_length.pos, &free_data,
  1288. &content_length);
  1289. i = atoi(data);
  1290. if (free_data)
  1291. tor_free(data);
  1292. if (i < 0) {
  1293. log_warn(LD_PROTOCOL, "Content-Length is less than zero; it looks like "
  1294. "someone is trying to crash us.");
  1295. return -1;
  1296. }
  1297. contentlen = i;
  1298. /* if content-length is malformed, then our body length is 0. fine. */
  1299. log_debug(LD_HTTP,"Got a contentlen of %d.",(int)contentlen);
  1300. if (bodylen < contentlen) {
  1301. if (!force_complete) {
  1302. log_debug(LD_HTTP,"body not all here yet.");
  1303. return 0; /* not all there yet */
  1304. }
  1305. }
  1306. if (bodylen > contentlen) {
  1307. bodylen = contentlen;
  1308. log_debug(LD_HTTP,"bodylen reduced to %d.",(int)bodylen);
  1309. }
  1310. }
  1311. if (headers_out) {
  1312. *headers_out = tor_malloc(headerlen+1);
  1313. evbuffer_remove(buf, *headers_out, headerlen);
  1314. (*headers_out)[headerlen] = '\0';
  1315. }
  1316. if (body_out) {
  1317. tor_assert(headers_out);
  1318. tor_assert(body_used);
  1319. *body_used = bodylen;
  1320. *body_out = tor_malloc(bodylen+1);
  1321. evbuffer_remove(buf, *body_out, bodylen);
  1322. (*body_out)[bodylen] = '\0';
  1323. }
  1324. return 1;
  1325. }
  1326. #endif
  1327. /**
  1328. * Wait this many seconds before warning the user about using SOCKS unsafely
  1329. * again (requires that WarnUnsafeSocks is turned on). */
  1330. #define SOCKS_WARN_INTERVAL 5
  1331. /** Warn that the user application has made an unsafe socks request using
  1332. * protocol <b>socks_protocol</b> on port <b>port</b>. Don't warn more than
  1333. * once per SOCKS_WARN_INTERVAL, unless <b>safe_socks</b> is set. */
  1334. static void
  1335. log_unsafe_socks_warning(int socks_protocol, const char *address,
  1336. uint16_t port, int safe_socks)
  1337. {
  1338. static ratelim_t socks_ratelim = RATELIM_INIT(SOCKS_WARN_INTERVAL);
  1339. or_options_t *options = get_options();
  1340. char *m = NULL;
  1341. if (! options->WarnUnsafeSocks)
  1342. return;
  1343. if (safe_socks || (m = rate_limit_log(&socks_ratelim, approx_time()))) {
  1344. log_warn(LD_APP,
  1345. "Your application (using socks%d to port %d) is giving "
  1346. "Tor only an IP address. Applications that do DNS resolves "
  1347. "themselves may leak information. Consider using Socks4A "
  1348. "(e.g. via privoxy or socat) instead. For more information, "
  1349. "please see https://wiki.torproject.org/TheOnionRouter/"
  1350. "TorFAQ#SOCKSAndDNS.%s%s",
  1351. socks_protocol,
  1352. (int)port,
  1353. safe_socks ? " Rejecting." : "",
  1354. m ? m : "");
  1355. tor_free(m);
  1356. }
  1357. control_event_client_status(LOG_WARN,
  1358. "DANGEROUS_SOCKS PROTOCOL=SOCKS%d ADDRESS=%s:%d",
  1359. socks_protocol, address, (int)port);
  1360. }
  1361. /** There is a (possibly incomplete) socks handshake on <b>buf</b>, of one
  1362. * of the forms
  1363. * - socks4: "socksheader username\\0"
  1364. * - socks4a: "socksheader username\\0 destaddr\\0"
  1365. * - socks5 phase one: "version #methods methods"
  1366. * - socks5 phase two: "version command 0 addresstype..."
  1367. * If it's a complete and valid handshake, and destaddr fits in
  1368. * MAX_SOCKS_ADDR_LEN bytes, then pull the handshake off the buf,
  1369. * assign to <b>req</b>, and return 1.
  1370. *
  1371. * If it's invalid or too big, return -1.
  1372. *
  1373. * Else it's not all there yet, leave buf alone and return 0.
  1374. *
  1375. * If you want to specify the socks reply, write it into <b>req->reply</b>
  1376. * and set <b>req->replylen</b>, else leave <b>req->replylen</b> alone.
  1377. *
  1378. * If <b>log_sockstype</b> is non-zero, then do a notice-level log of whether
  1379. * the connection is possibly leaking DNS requests locally or not.
  1380. *
  1381. * If <b>safe_socks</b> is true, then reject unsafe socks protocols.
  1382. *
  1383. * If returning 0 or -1, <b>req->address</b> and <b>req->port</b> are
  1384. * undefined.
  1385. */
  1386. int
  1387. fetch_from_buf_socks(buf_t *buf, socks_request_t *req,
  1388. int log_sockstype, int safe_socks)
  1389. {
  1390. int res;
  1391. ssize_t n_drain;
  1392. size_t want_length = 128;
  1393. if (buf->datalen < 2) /* version and another byte */
  1394. return 0;
  1395. do {
  1396. n_drain = 0;
  1397. buf_pullup(buf, want_length, 0);
  1398. tor_assert(buf->head && buf->head->datalen >= 2);
  1399. want_length = 0;
  1400. res = parse_socks(buf->head->data, buf->head->datalen, req, log_sockstype,
  1401. safe_socks, &n_drain, &want_length);
  1402. if (n_drain < 0)
  1403. buf_clear(buf);
  1404. else if (n_drain > 0)
  1405. buf_remove_from_front(buf, n_drain);
  1406. } while (res == 0 && buf->head &&
  1407. buf->datalen > buf->head->datalen &&
  1408. want_length < buf->head->datalen);
  1409. return res;
  1410. }
  1411. #ifdef USE_BUFFEREVENTS
  1412. /* As fetch_from_buf_socks(), but targets an evbuffer instead. */
  1413. int
  1414. fetch_from_evbuffer_socks(struct evbuffer *buf, socks_request_t *req,
  1415. int log_sockstype, int safe_socks)
  1416. {
  1417. char *data;
  1418. ssize_t n_drain;
  1419. size_t datalen, buflen, want_length;
  1420. int res;
  1421. buflen = evbuffer_get_length(buf);
  1422. if (buflen < 2)
  1423. return 0;
  1424. {
  1425. /* See if we can find the socks request in the first chunk of the buffer.
  1426. */
  1427. struct evbuffer_iovec v;
  1428. int i;
  1429. want_length = evbuffer_get_contiguous_space(buf);
  1430. n_drain = 0;
  1431. i = evbuffer_peek(buf, want_length, NULL, &v, 1);
  1432. tor_assert(i == 1);
  1433. data = v.iov_base;
  1434. datalen = v.iov_len;
  1435. res = parse_socks(data, datalen, req, log_sockstype,
  1436. safe_socks, &n_drain, &want_length);
  1437. if (n_drain < 0)
  1438. evbuffer_drain(buf, evbuffer_get_length(buf));
  1439. else if (n_drain > 0)
  1440. evbuffer_drain(buf, n_drain);
  1441. if (res)
  1442. return res;
  1443. }
  1444. /* Okay, the first chunk of the buffer didn't have a complete socks request.
  1445. * That means that either we don't have a whole socks request at all, or
  1446. * it's gotten split up. We're going to try passing parse_socks() bigger
  1447. * and bigger chunks until either it says "Okay, I got it", or it says it
  1448. * will need more data than we currently have. */
  1449. /* Loop while we have more data that we haven't given parse_socks() yet. */
  1450. while (evbuffer_get_length(buf) > datalen) {
  1451. int free_data = 0;
  1452. n_drain = 0;
  1453. data = NULL;
  1454. datalen = inspect_evbuffer(buf, &data, want_length, &free_data, NULL);
  1455. res = parse_socks(data, datalen, req, log_sockstype,
  1456. safe_socks, &n_drain, &want_length);
  1457. if (free_data)
  1458. tor_free(data);
  1459. if (n_drain < 0)
  1460. evbuffer_drain(buf, evbuffer_get_length(buf));
  1461. else if (n_drain > 0)
  1462. evbuffer_drain(buf, n_drain);
  1463. if (res) /* If res is nonzero, parse_socks() made up its mind. */
  1464. return res;
  1465. /* If parse_socks says that we want less data than we actually tried to
  1466. give it, we've got some kind of weird situation; just exit the loop for
  1467. now.
  1468. */
  1469. if (want_length <= datalen)
  1470. break;
  1471. /* Otherwise, it wants more data than we gave it. If we can provide more
  1472. * data than we gave it, we'll try to do so in the next iteration of the
  1473. * loop. If we can't, the while loop will exit. It's okay if it asked for
  1474. * more than we have total; maybe it doesn't really need so much. */
  1475. }
  1476. return res;
  1477. }
  1478. #endif
  1479. /** Implementation helper to implement fetch_from_*_socks. Instead of looking
  1480. * at a buffer's contents, we look at the <b>datalen</b> bytes of data in
  1481. * <b>data</b>. Instead of removing data from the buffer, we set
  1482. * <b>drain_out</b> to the amount of data that should be removed (or -1 if the
  1483. * buffer should be cleared). Instead of pulling more data into the first
  1484. * chunk of the buffer, we set *<b>want_length_out</b> to the number of bytes
  1485. * we'd like to see in the input buffer, if they're available. */
  1486. static int
  1487. parse_socks(const char *data, size_t datalen, socks_request_t *req,
  1488. int log_sockstype, int safe_socks, ssize_t *drain_out,
  1489. size_t *want_length_out)
  1490. {
  1491. unsigned int len;
  1492. char tmpbuf[TOR_ADDR_BUF_LEN+1];
  1493. tor_addr_t destaddr;
  1494. uint32_t destip;
  1495. uint8_t socksver;
  1496. enum {socks4, socks4a} socks4_prot = socks4a;
  1497. char *next, *startaddr;
  1498. struct in_addr in;
  1499. socksver = *data;
  1500. switch (socksver) { /* which version of socks? */
  1501. case 5: /* socks5 */
  1502. if (req->socks_version != 5) { /* we need to negotiate a method */
  1503. unsigned char nummethods = (unsigned char)*(data+1);
  1504. tor_assert(!req->socks_version);
  1505. if (datalen < 2u+nummethods) {
  1506. *want_length_out = 2u+nummethods;
  1507. return 0;
  1508. }
  1509. if (!nummethods || !memchr(data+2, 0, nummethods)) {
  1510. log_warn(LD_APP,
  1511. "socks5: offered methods don't include 'no auth'. "
  1512. "Rejecting.");
  1513. req->replylen = 2; /* 2 bytes of response */
  1514. req->reply[0] = 5;
  1515. req->reply[1] = '\xFF'; /* reject all methods */
  1516. return -1;
  1517. }
  1518. /* remove packet from buf. also remove any other extraneous
  1519. * bytes, to support broken socks clients. */
  1520. *drain_out = -1;
  1521. req->replylen = 2; /* 2 bytes of response */
  1522. req->reply[0] = 5; /* socks5 reply */
  1523. req->reply[1] = 0; /* tell client to use "none" auth method */
  1524. req->socks_version = 5; /* remember we've already negotiated auth */
  1525. log_debug(LD_APP,"socks5: accepted method 0");
  1526. return 0;
  1527. }
  1528. /* we know the method; read in the request */
  1529. log_debug(LD_APP,"socks5: checking request");
  1530. if (datalen < 8) {/* basic info plus >=2 for addr plus 2 for port */
  1531. *want_length_out = 8;
  1532. return 0; /* not yet */
  1533. }
  1534. req->command = (unsigned char) *(data+1);
  1535. if (req->command != SOCKS_COMMAND_CONNECT &&
  1536. req->command != SOCKS_COMMAND_RESOLVE &&
  1537. req->command != SOCKS_COMMAND_RESOLVE_PTR) {
  1538. /* not a connect or resolve or a resolve_ptr? we don't support it. */
  1539. log_warn(LD_APP,"socks5: command %d not recognized. Rejecting.",
  1540. req->command);
  1541. return -1;
  1542. }
  1543. switch (*(data+3)) { /* address type */
  1544. case 1: /* IPv4 address */
  1545. case 4: /* IPv6 address */ {
  1546. const int is_v6 = *(data+3) == 4;
  1547. const unsigned addrlen = is_v6 ? 16 : 4;
  1548. log_debug(LD_APP,"socks5: ipv4 address type");
  1549. if (datalen < 6+addrlen) {/* ip/port there? */
  1550. *want_length_out = 6+addrlen;
  1551. return 0; /* not yet */
  1552. }
  1553. if (is_v6)
  1554. tor_addr_from_ipv6_bytes(&destaddr, data+4);
  1555. else
  1556. tor_addr_from_ipv4n(&destaddr, get_uint32(data+4));
  1557. tor_addr_to_str(tmpbuf, &destaddr, sizeof(tmpbuf), 1);
  1558. if (strlen(tmpbuf)+1 > MAX_SOCKS_ADDR_LEN) {
  1559. log_warn(LD_APP,
  1560. "socks5 IP takes %d bytes, which doesn't fit in %d. "
  1561. "Rejecting.",
  1562. (int)strlen(tmpbuf)+1,(int)MAX_SOCKS_ADDR_LEN);
  1563. return -1;
  1564. }
  1565. strlcpy(req->address,tmpbuf,sizeof(req->address));
  1566. req->port = ntohs(get_uint16(data+4+addrlen));
  1567. *drain_out = 6+addrlen;
  1568. if (req->command != SOCKS_COMMAND_RESOLVE_PTR &&
  1569. !addressmap_have_mapping(req->address,0)) {
  1570. log_unsafe_socks_warning(5, req->address, req->port, safe_socks);
  1571. if (safe_socks)
  1572. return -1;
  1573. }
  1574. return 1;
  1575. }
  1576. case 3: /* fqdn */
  1577. log_debug(LD_APP,"socks5: fqdn address type");
  1578. if (req->command == SOCKS_COMMAND_RESOLVE_PTR) {
  1579. log_warn(LD_APP, "socks5 received RESOLVE_PTR command with "
  1580. "hostname type. Rejecting.");
  1581. return -1;
  1582. }
  1583. len = (unsigned char)*(data+4);
  1584. if (datalen < 7+len) { /* addr/port there? */
  1585. *want_length_out = 7+len;
  1586. return 0; /* not yet */
  1587. }
  1588. if (len+1 > MAX_SOCKS_ADDR_LEN) {
  1589. log_warn(LD_APP,
  1590. "socks5 hostname is %d bytes, which doesn't fit in "
  1591. "%d. Rejecting.", len+1,MAX_SOCKS_ADDR_LEN);
  1592. return -1;
  1593. }
  1594. memcpy(req->address,data+5,len);
  1595. req->address[len] = 0;
  1596. req->port = ntohs(get_uint16(data+5+len));
  1597. *drain_out = 5+len+2;
  1598. if (!tor_strisprint(req->address) || strchr(req->address,'\"')) {
  1599. log_warn(LD_PROTOCOL,
  1600. "Your application (using socks5 to port %d) gave Tor "
  1601. "a malformed hostname: %s. Rejecting the connection.",
  1602. req->port, escaped(req->address));
  1603. return -1;
  1604. }
  1605. if (log_sockstype)
  1606. log_notice(LD_APP,
  1607. "Your application (using socks5 to port %d) gave "
  1608. "Tor a hostname, which means Tor will do the DNS resolve "
  1609. "for you. This is good.", req->port);
  1610. return 1;
  1611. default: /* unsupported */
  1612. log_warn(LD_APP,"socks5: unsupported address type %d. Rejecting.",
  1613. (int) *(data+3));
  1614. return -1;
  1615. }
  1616. tor_assert(0);
  1617. case 4: /* socks4 */
  1618. /* http://archive.socks.permeo.com/protocol/socks4.protocol */
  1619. /* http://archive.socks.permeo.com/protocol/socks4a.protocol */
  1620. req->socks_version = 4;
  1621. if (datalen < SOCKS4_NETWORK_LEN) {/* basic info available? */
  1622. *want_length_out = SOCKS4_NETWORK_LEN;
  1623. return 0; /* not yet */
  1624. }
  1625. // buf_pullup(buf, 1280, 0);
  1626. req->command = (unsigned char) *(data+1);
  1627. if (req->command != SOCKS_COMMAND_CONNECT &&
  1628. req->command != SOCKS_COMMAND_RESOLVE) {
  1629. /* not a connect or resolve? we don't support it. (No resolve_ptr with
  1630. * socks4.) */
  1631. log_warn(LD_APP,"socks4: command %d not recognized. Rejecting.",
  1632. req->command);
  1633. return -1;
  1634. }
  1635. req->port = ntohs(get_uint16(data+2));
  1636. destip = ntohl(get_uint32(data+4));
  1637. if ((!req->port && req->command!=SOCKS_COMMAND_RESOLVE) || !destip) {
  1638. log_warn(LD_APP,"socks4: Port or DestIP is zero. Rejecting.");
  1639. return -1;
  1640. }
  1641. if (destip >> 8) {
  1642. log_debug(LD_APP,"socks4: destip not in form 0.0.0.x.");
  1643. in.s_addr = htonl(destip);
  1644. tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
  1645. if (strlen(tmpbuf)+1 > MAX_SOCKS_ADDR_LEN) {
  1646. log_debug(LD_APP,"socks4 addr (%d bytes) too long. Rejecting.",
  1647. (int)strlen(tmpbuf));
  1648. return -1;
  1649. }
  1650. log_debug(LD_APP,
  1651. "socks4: successfully read destip (%s)",
  1652. safe_str_client(tmpbuf));
  1653. socks4_prot = socks4;
  1654. }
  1655. next = memchr(data+SOCKS4_NETWORK_LEN, 0,
  1656. datalen-SOCKS4_NETWORK_LEN);
  1657. if (!next) {
  1658. if (datalen >= 1024) {
  1659. log_debug(LD_APP, "Socks4 user name too long; rejecting.");
  1660. return -1;
  1661. }
  1662. log_debug(LD_APP,"socks4: Username not here yet.");
  1663. *want_length_out = datalen+1024; /* ???? */
  1664. return 0;
  1665. }
  1666. tor_assert(next < data+datalen);
  1667. startaddr = NULL;
  1668. if (socks4_prot != socks4a &&
  1669. !addressmap_have_mapping(tmpbuf,0)) {
  1670. log_unsafe_socks_warning(4, tmpbuf, req->port, safe_socks);
  1671. if (safe_socks)
  1672. return -1;
  1673. }
  1674. if (socks4_prot == socks4a) {
  1675. if (next+1 == data+datalen) {
  1676. log_debug(LD_APP,"socks4: No part of destaddr here yet.");
  1677. *want_length_out = datalen + 1024; /* More than we need, but safe */
  1678. return 0;
  1679. }
  1680. startaddr = next+1;
  1681. next = memchr(startaddr, 0, data + datalen - startaddr);
  1682. if (!next) {
  1683. if (datalen >= 1024) {
  1684. log_debug(LD_APP,"socks4: Destaddr too long.");
  1685. return -1;
  1686. }
  1687. log_debug(LD_APP,"socks4: Destaddr not all here yet.");
  1688. *want_length_out = datalen + 1024;
  1689. return 0;
  1690. }
  1691. if (MAX_SOCKS_ADDR_LEN <= next-startaddr) {
  1692. log_warn(LD_APP,"socks4: Destaddr too long. Rejecting.");
  1693. return -1;
  1694. }
  1695. // tor_assert(next < buf->cur+buf->datalen);
  1696. if (log_sockstype)
  1697. log_notice(LD_APP,
  1698. "Your application (using socks4a to port %d) gave "
  1699. "Tor a hostname, which means Tor will do the DNS resolve "
  1700. "for you. This is good.", req->port);
  1701. }
  1702. log_debug(LD_APP,"socks4: Everything is here. Success.");
  1703. strlcpy(req->address, startaddr ? startaddr : tmpbuf,
  1704. sizeof(req->address));
  1705. if (!tor_strisprint(req->address) || strchr(req->address,'\"')) {
  1706. log_warn(LD_PROTOCOL,
  1707. "Your application (using socks4 to port %d) gave Tor "
  1708. "a malformed hostname: %s. Rejecting the connection.",
  1709. req->port, escaped(req->address));
  1710. return -1;
  1711. }
  1712. /* next points to the final \0 on inbuf */
  1713. *drain_out = next - data + 1;
  1714. return 1;
  1715. case 'G': /* get */
  1716. case 'H': /* head */
  1717. case 'P': /* put/post */
  1718. case 'C': /* connect */
  1719. strlcpy(req->reply,
  1720. "HTTP/1.0 501 Tor is not an HTTP Proxy\r\n"
  1721. "Content-Type: text/html; charset=iso-8859-1\r\n\r\n"
  1722. "<html>\n"
  1723. "<head>\n"
  1724. "<title>Tor is not an HTTP Proxy</title>\n"
  1725. "</head>\n"
  1726. "<body>\n"
  1727. "<h1>Tor is not an HTTP Proxy</h1>\n"
  1728. "<p>\n"
  1729. "It appears you have configured your web browser to use Tor as an HTTP proxy."
  1730. "\n"
  1731. "This is not correct: Tor is a SOCKS proxy, not an HTTP proxy.\n"
  1732. "Please configure your client accordingly.\n"
  1733. "</p>\n"
  1734. "<p>\n"
  1735. "See <a href=\"https://www.torproject.org/documentation.html\">"
  1736. "https://www.torproject.org/documentation.html</a> for more "
  1737. "information.\n"
  1738. "<!-- Plus this comment, to make the body response more than 512 bytes, so "
  1739. " IE will be willing to display it. Comment comment comment comment "
  1740. " comment comment comment comment comment comment comment comment.-->\n"
  1741. "</p>\n"
  1742. "</body>\n"
  1743. "</html>\n"
  1744. , MAX_SOCKS_REPLY_LEN);
  1745. req->replylen = strlen(req->reply)+1;
  1746. /* fall through */
  1747. default: /* version is not socks4 or socks5 */
  1748. log_warn(LD_APP,
  1749. "Socks version %d not recognized. (Tor is not an http proxy.)",
  1750. *(data));
  1751. {
  1752. /* Tell the controller the first 8 bytes. */
  1753. char *tmp = tor_strndup(data, datalen < 8 ? datalen : 8);
  1754. control_event_client_status(LOG_WARN,
  1755. "SOCKS_UNKNOWN_PROTOCOL DATA=\"%s\"",
  1756. escaped(tmp));
  1757. tor_free(tmp);
  1758. }
  1759. return -1;
  1760. }
  1761. }
  1762. /** Inspect a reply from SOCKS server stored in <b>buf</b> according
  1763. * to <b>state</b>, removing the protocol data upon success. Return 0 on
  1764. * incomplete response, 1 on success and -1 on error, in which case
  1765. * <b>reason</b> is set to a descriptive message (free() when finished
  1766. * with it).
  1767. *
  1768. * As a special case, 2 is returned when user/pass is required
  1769. * during SOCKS5 handshake and user/pass is configured.
  1770. */
  1771. int
  1772. fetch_from_buf_socks_client(buf_t *buf, int state, char **reason)
  1773. {
  1774. ssize_t drain = 0;
  1775. int r;
  1776. if (buf->datalen < 2)
  1777. return 0;
  1778. buf_pullup(buf, 128, 0);
  1779. tor_assert(buf->head && buf->head->datalen >= 2);
  1780. r = parse_socks_client((uint8_t*)buf->head->data, buf->head->datalen,
  1781. state, reason, &drain);
  1782. if (drain > 0)
  1783. buf_remove_from_front(buf, drain);
  1784. else if (drain < 0)
  1785. buf_clear(buf);
  1786. return r;
  1787. }
  1788. #ifdef USE_BUFFEREVENTS
  1789. /** As fetch_from_buf_socks_client, buf works on an evbuffer */
  1790. int
  1791. fetch_from_evbuffer_socks_client(struct evbuffer *buf, int state,
  1792. char **reason)
  1793. {
  1794. ssize_t drain = 0;
  1795. uint8_t *data;
  1796. size_t datalen;
  1797. int r;
  1798. data = evbuffer_pullup(buf, 128); /* Make sure we have at least 128
  1799. * contiguous bytes if possible. */
  1800. datalen = evbuffer_get_contiguous_space(buf);
  1801. r = parse_socks_client(data, datalen, state, reason, &drain);
  1802. if (drain > 0)
  1803. evbuffer_drain(buf, drain);
  1804. else
  1805. evbuffer_drain(buf, evbuffer_get_length(buf));
  1806. return r;
  1807. }
  1808. #endif
  1809. /** Implementation logic for fetch_from_*_socks_client. */
  1810. static int
  1811. parse_socks_client(const uint8_t *data, size_t datalen,
  1812. int state, char **reason,
  1813. ssize_t *drain_out)
  1814. {
  1815. unsigned int addrlen;
  1816. *drain_out = 0;
  1817. if (datalen < 2)
  1818. return 0;
  1819. switch (state) {
  1820. case PROXY_SOCKS4_WANT_CONNECT_OK:
  1821. /* Wait for the complete response */
  1822. if (datalen < 8)
  1823. return 0;
  1824. if (data[1] != 0x5a) {
  1825. *reason = tor_strdup(socks4_response_code_to_string(data[1]));
  1826. return -1;
  1827. }
  1828. /* Success */
  1829. *drain_out = 8;
  1830. return 1;
  1831. case PROXY_SOCKS5_WANT_AUTH_METHOD_NONE:
  1832. /* we don't have any credentials */
  1833. if (data[1] != 0x00) {
  1834. *reason = tor_strdup("server doesn't support any of our "
  1835. "available authentication methods");
  1836. return -1;
  1837. }
  1838. log_info(LD_NET, "SOCKS 5 client: continuing without authentication");
  1839. *drain_out = -1;
  1840. return 1;
  1841. case PROXY_SOCKS5_WANT_AUTH_METHOD_RFC1929:
  1842. /* we have a username and password. return 1 if we can proceed without
  1843. * providing authentication, or 2 otherwise. */
  1844. switch (data[1]) {
  1845. case 0x00:
  1846. log_info(LD_NET, "SOCKS 5 client: we have auth details but server "
  1847. "doesn't require authentication.");
  1848. *drain_out = -1;
  1849. return 1;
  1850. case 0x02:
  1851. log_info(LD_NET, "SOCKS 5 client: need authentication.");
  1852. *drain_out = -1;
  1853. return 2;
  1854. /* fall through */
  1855. }
  1856. *reason = tor_strdup("server doesn't support any of our available "
  1857. "authentication methods");
  1858. return -1;
  1859. case PROXY_SOCKS5_WANT_AUTH_RFC1929_OK:
  1860. /* handle server reply to rfc1929 authentication */
  1861. if (data[1] != 0x00) {
  1862. *reason = tor_strdup("authentication failed");
  1863. return -1;
  1864. }
  1865. log_info(LD_NET, "SOCKS 5 client: authentication successful.");
  1866. *drain_out = -1;
  1867. return 1;
  1868. case PROXY_SOCKS5_WANT_CONNECT_OK:
  1869. /* response is variable length. BND.ADDR, etc, isn't needed
  1870. * (don't bother with buf_pullup()), but make sure to eat all
  1871. * the data used */
  1872. /* wait for address type field to arrive */
  1873. if (datalen < 4)
  1874. return 0;
  1875. switch (data[3]) {
  1876. case 0x01: /* ip4 */
  1877. addrlen = 4;
  1878. break;
  1879. case 0x04: /* ip6 */
  1880. addrlen = 16;
  1881. break;
  1882. case 0x03: /* fqdn (can this happen here?) */
  1883. if (datalen < 5)
  1884. return 0;
  1885. addrlen = 1 + data[4];
  1886. break;
  1887. default:
  1888. *reason = tor_strdup("invalid response to connect request");
  1889. return -1;
  1890. }
  1891. /* wait for address and port */
  1892. if (datalen < 6 + addrlen)
  1893. return 0;
  1894. if (data[1] != 0x00) {
  1895. *reason = tor_strdup(socks5_response_code_to_string(data[1]));
  1896. return -1;
  1897. }
  1898. *drain_out = 6 + addrlen;
  1899. return 1;
  1900. }
  1901. /* shouldn't get here... */
  1902. tor_assert(0);
  1903. return -1;
  1904. }
  1905. /** Return 1 iff buf looks more like it has an (obsolete) v0 controller
  1906. * command on it than any valid v1 controller command. */
  1907. int
  1908. peek_buf_has_control0_command(buf_t *buf)
  1909. {
  1910. if (buf->datalen >= 4) {
  1911. char header[4];
  1912. uint16_t cmd;
  1913. peek_from_buf(header, sizeof(header), buf);
  1914. cmd = ntohs(get_uint16(header+2));
  1915. if (cmd <= 0x14)
  1916. return 1; /* This is definitely not a v1 control command. */
  1917. }
  1918. return 0;
  1919. }
  1920. #ifdef USE_BUFFEREVENTS
  1921. int
  1922. peek_evbuffer_has_control0_command(struct evbuffer *buf)
  1923. {
  1924. int result = 0;
  1925. if (evbuffer_get_length(buf) >= 4) {
  1926. int free_out = 0;
  1927. char *data = NULL;
  1928. size_t n = inspect_evbuffer(buf, &data, 4, &free_out, NULL);
  1929. uint16_t cmd;
  1930. tor_assert(n >= 4);
  1931. cmd = ntohs(get_uint16(data+2));
  1932. if (cmd <= 0x14)
  1933. result = 1;
  1934. if (free_out)
  1935. tor_free(data);
  1936. }
  1937. return result;
  1938. }
  1939. #endif
  1940. /** Return the index within <b>buf</b> at which <b>ch</b> first appears,
  1941. * or -1 if <b>ch</b> does not appear on buf. */
  1942. static off_t
  1943. buf_find_offset_of_char(buf_t *buf, char ch)
  1944. {
  1945. chunk_t *chunk;
  1946. off_t offset = 0;
  1947. for (chunk = buf->head; chunk; chunk = chunk->next) {
  1948. char *cp = memchr(chunk->data, ch, chunk->datalen);
  1949. if (cp)
  1950. return offset + (cp - chunk->data);
  1951. else
  1952. offset += chunk->datalen;
  1953. }
  1954. return -1;
  1955. }
  1956. /** Try to read a single LF-terminated line from <b>buf</b>, and write it
  1957. * (including the LF), NUL-terminated, into the *<b>data_len</b> byte buffer
  1958. * at <b>data_out</b>. Set *<b>data_len</b> to the number of bytes in the
  1959. * line, not counting the terminating NUL. Return 1 if we read a whole line,
  1960. * return 0 if we don't have a whole line yet, and return -1 if the line
  1961. * length exceeds *<b>data_len</b>.
  1962. */
  1963. int
  1964. fetch_from_buf_line(buf_t *buf, char *data_out, size_t *data_len)
  1965. {
  1966. size_t sz;
  1967. off_t offset;
  1968. if (!buf->head)
  1969. return 0;
  1970. offset = buf_find_offset_of_char(buf, '\n');
  1971. if (offset < 0)
  1972. return 0;
  1973. sz = (size_t) offset;
  1974. if (sz+2 > *data_len) {
  1975. *data_len = sz + 2;
  1976. return -1;
  1977. }
  1978. fetch_from_buf(data_out, sz+1, buf);
  1979. data_out[sz+1] = '\0';
  1980. *data_len = sz+1;
  1981. return 1;
  1982. }
  1983. /** Compress on uncompress the <b>data_len</b> bytes in <b>data</b> using the
  1984. * zlib state <b>state</b>, appending the result to <b>buf</b>. If
  1985. * <b>done</b> is true, flush the data in the state and finish the
  1986. * compression/uncompression. Return -1 on failure, 0 on success. */
  1987. int
  1988. write_to_buf_zlib(buf_t *buf, tor_zlib_state_t *state,
  1989. const char *data, size_t data_len,
  1990. int done)
  1991. {
  1992. char *next;
  1993. size_t old_avail, avail;
  1994. int over = 0;
  1995. do {
  1996. int need_new_chunk = 0;
  1997. if (!buf->tail || ! CHUNK_REMAINING_CAPACITY(buf->tail)) {
  1998. size_t cap = data_len / 4;
  1999. buf_add_chunk_with_capacity(buf, cap, 1);
  2000. }
  2001. next = CHUNK_WRITE_PTR(buf->tail);
  2002. avail = old_avail = CHUNK_REMAINING_CAPACITY(buf->tail);
  2003. switch (tor_zlib_process(state, &next, &avail, &data, &data_len, done)) {
  2004. case TOR_ZLIB_DONE:
  2005. over = 1;
  2006. break;
  2007. case TOR_ZLIB_ERR:
  2008. return -1;
  2009. case TOR_ZLIB_OK:
  2010. if (data_len == 0)
  2011. over = 1;
  2012. break;
  2013. case TOR_ZLIB_BUF_FULL:
  2014. if (avail) {
  2015. /* Zlib says we need more room (ZLIB_BUF_FULL). Start a new chunk
  2016. * automatically, whether were going to or not. */
  2017. need_new_chunk = 1;
  2018. }
  2019. break;
  2020. }
  2021. buf->datalen += old_avail - avail;
  2022. buf->tail->datalen += old_avail - avail;
  2023. if (need_new_chunk) {
  2024. buf_add_chunk_with_capacity(buf, data_len/4, 1);
  2025. }
  2026. } while (!over);
  2027. check();
  2028. return 0;
  2029. }
  2030. #ifdef USE_BUFFEREVENTS
  2031. int
  2032. write_to_evbuffer_zlib(struct evbuffer *buf, tor_zlib_state_t *state,
  2033. const char *data, size_t data_len,
  2034. int done)
  2035. {
  2036. char *next;
  2037. size_t old_avail, avail;
  2038. int over = 0, n;
  2039. struct evbuffer_iovec vec[1];
  2040. do {
  2041. int need_new_chunk = 0;
  2042. {
  2043. size_t cap = data_len / 4;
  2044. if (cap < 128)
  2045. cap = 128;
  2046. /* XXXX NM this strategy is fragmentation-prone. We should really have
  2047. * two iovecs, and write first into the one, and then into the
  2048. * second if the first gets full. */
  2049. n = evbuffer_reserve_space(buf, cap, vec, 1);
  2050. tor_assert(n == 1);
  2051. }
  2052. next = vec[0].iov_base;
  2053. avail = old_avail = vec[0].iov_len;
  2054. switch (tor_zlib_process(state, &next, &avail, &data, &data_len, done)) {
  2055. case TOR_ZLIB_DONE:
  2056. over = 1;
  2057. break;
  2058. case TOR_ZLIB_ERR:
  2059. return -1;
  2060. case TOR_ZLIB_OK:
  2061. if (data_len == 0)
  2062. over = 1;
  2063. break;
  2064. case TOR_ZLIB_BUF_FULL:
  2065. if (avail) {
  2066. /* Zlib says we need more room (ZLIB_BUF_FULL). Start a new chunk
  2067. * automatically, whether were going to or not. */
  2068. need_new_chunk = 1;
  2069. }
  2070. break;
  2071. }
  2072. /* XXXX possible infinite loop on BUF_FULL. */
  2073. vec[0].iov_len = old_avail - avail;
  2074. evbuffer_commit_space(buf, vec, 1);
  2075. } while (!over);
  2076. check();
  2077. return 0;
  2078. }
  2079. #endif
  2080. /** Log an error and exit if <b>buf</b> is corrupted.
  2081. */
  2082. void
  2083. assert_buf_ok(buf_t *buf)
  2084. {
  2085. tor_assert(buf);
  2086. tor_assert(buf->magic == BUFFER_MAGIC);
  2087. if (! buf->head) {
  2088. tor_assert(!buf->tail);
  2089. tor_assert(buf->datalen == 0);
  2090. } else {
  2091. chunk_t *ch;
  2092. size_t total = 0;
  2093. tor_assert(buf->tail);
  2094. for (ch = buf->head; ch; ch = ch->next) {
  2095. total += ch->datalen;
  2096. tor_assert(ch->datalen <= ch->memlen);
  2097. tor_assert(ch->data >= &ch->mem[0]);
  2098. tor_assert(ch->data < &ch->mem[0]+ch->memlen);
  2099. tor_assert(ch->data+ch->datalen <= &ch->mem[0] + ch->memlen);
  2100. if (!ch->next)
  2101. tor_assert(ch == buf->tail);
  2102. }
  2103. tor_assert(buf->datalen == total);
  2104. }
  2105. }
  2106. #ifdef ENABLE_BUF_FREELISTS
  2107. /** Log an error and exit if <b>fl</b> is corrupted.
  2108. */
  2109. static void
  2110. assert_freelist_ok(chunk_freelist_t *fl)
  2111. {
  2112. chunk_t *ch;
  2113. int n;
  2114. tor_assert(fl->alloc_size > 0);
  2115. n = 0;
  2116. for (ch = fl->head; ch; ch = ch->next) {
  2117. tor_assert(CHUNK_ALLOC_SIZE(ch->memlen) == fl->alloc_size);
  2118. ++n;
  2119. }
  2120. tor_assert(n == fl->cur_length);
  2121. tor_assert(n >= fl->lowest_length);
  2122. tor_assert(n <= fl->max_length);
  2123. }
  2124. #endif