buffers.c 82 KB

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