buffers.c 74 KB

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