buffers.c 78 KB

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