buffers.c 75 KB

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