buffers.c 76 KB

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