buffers.c 67 KB

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