buffers.c 76 KB

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