buffers.c 80 KB

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