buffers.c 62 KB

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