buffers.c 74 KB

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