buffers.c 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156
  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. while (at_most > total_read) {
  554. size_t readlen = at_most - total_read;
  555. chunk_t *chunk;
  556. if (!buf->tail || CHUNK_REMAINING_CAPACITY(buf->tail) < MIN_READ_LEN) {
  557. chunk = buf_add_chunk_with_capacity(buf, at_most, 1);
  558. if (readlen > chunk->memlen)
  559. readlen = chunk->memlen;
  560. } else {
  561. size_t cap = CHUNK_REMAINING_CAPACITY(buf->tail);
  562. chunk = buf->tail;
  563. if (cap < readlen)
  564. readlen = cap;
  565. }
  566. r = read_to_chunk(buf, chunk, s, readlen, reached_eof, socket_error);
  567. check();
  568. if (r < 0)
  569. return r; /* Error */
  570. tor_assert(total_read+r < INT_MAX);
  571. total_read += r;
  572. if ((size_t)r < readlen) { /* eof, block, or no more to read. */
  573. break;
  574. }
  575. }
  576. return (int)total_read;
  577. }
  578. /** As read_to_buf, but reads from a TLS connection, and returns a TLS
  579. * status value rather than the number of bytes read.
  580. *
  581. * Using TLS on OR connections complicates matters in two ways.
  582. *
  583. * First, a TLS stream has its own read buffer independent of the
  584. * connection's read buffer. (TLS needs to read an entire frame from
  585. * the network before it can decrypt any data. Thus, trying to read 1
  586. * byte from TLS can require that several KB be read from the network
  587. * and decrypted. The extra data is stored in TLS's decrypt buffer.)
  588. * Because the data hasn't been read by Tor (it's still inside the TLS),
  589. * this means that sometimes a connection "has stuff to read" even when
  590. * poll() didn't return POLLIN. The tor_tls_get_pending_bytes function is
  591. * used in connection.c to detect TLS objects with non-empty internal
  592. * buffers and read from them again.
  593. *
  594. * Second, the TLS stream's events do not correspond directly to network
  595. * events: sometimes, before a TLS stream can read, the network must be
  596. * ready to write -- or vice versa.
  597. */
  598. int
  599. read_to_buf_tls(tor_tls_t *tls, size_t at_most, buf_t *buf)
  600. {
  601. int r = 0;
  602. size_t total_read = 0;
  603. check_no_tls_errors();
  604. check();
  605. while (at_most > total_read) {
  606. size_t readlen = at_most - total_read;
  607. chunk_t *chunk;
  608. if (!buf->tail || CHUNK_REMAINING_CAPACITY(buf->tail) < MIN_READ_LEN) {
  609. chunk = buf_add_chunk_with_capacity(buf, at_most, 1);
  610. if (readlen > chunk->memlen)
  611. readlen = chunk->memlen;
  612. } else {
  613. size_t cap = CHUNK_REMAINING_CAPACITY(buf->tail);
  614. chunk = buf->tail;
  615. if (cap < readlen)
  616. readlen = cap;
  617. }
  618. r = read_to_chunk_tls(buf, chunk, tls, readlen);
  619. check();
  620. if (r < 0)
  621. return r; /* Error */
  622. tor_assert(total_read+r < INT_MAX);
  623. total_read += r;
  624. if ((size_t)r < readlen) /* eof, block, or no more to read. */
  625. break;
  626. }
  627. return (int)total_read;
  628. }
  629. /** Helper for flush_buf(): try to write <b>sz</b> bytes from chunk
  630. * <b>chunk</b> of buffer <b>buf</b> onto socket <b>s</b>. On success, deduct
  631. * the bytes written from *<b>buf_flushlen</b>. Return the number of bytes
  632. * written on success, 0 on blocking, -1 on failure.
  633. */
  634. static inline int
  635. flush_chunk(tor_socket_t s, buf_t *buf, chunk_t *chunk, size_t sz,
  636. size_t *buf_flushlen)
  637. {
  638. ssize_t write_result;
  639. if (sz > chunk->datalen)
  640. sz = chunk->datalen;
  641. write_result = tor_socket_send(s, chunk->data, sz, 0);
  642. if (write_result < 0) {
  643. int e = tor_socket_errno(s);
  644. if (!ERRNO_IS_EAGAIN(e)) { /* it's a real error */
  645. #ifdef _WIN32
  646. if (e == WSAENOBUFS)
  647. log_warn(LD_NET,"write() failed: WSAENOBUFS. Not enough ram?");
  648. #endif
  649. return -1;
  650. }
  651. log_debug(LD_NET,"write() would block, returning.");
  652. return 0;
  653. } else {
  654. *buf_flushlen -= write_result;
  655. buf_remove_from_front(buf, write_result);
  656. tor_assert(write_result < INT_MAX);
  657. return (int)write_result;
  658. }
  659. }
  660. /** Helper for flush_buf_tls(): try to write <b>sz</b> bytes from chunk
  661. * <b>chunk</b> of buffer <b>buf</b> onto socket <b>s</b>. (Tries to write
  662. * more if there is a forced pending write size.) On success, deduct the
  663. * bytes written from *<b>buf_flushlen</b>. Return the number of bytes
  664. * written on success, and a TOR_TLS error code on failure or blocking.
  665. */
  666. static inline int
  667. flush_chunk_tls(tor_tls_t *tls, buf_t *buf, chunk_t *chunk,
  668. size_t sz, size_t *buf_flushlen)
  669. {
  670. int r;
  671. size_t forced;
  672. char *data;
  673. forced = tor_tls_get_forced_write_size(tls);
  674. if (forced > sz)
  675. sz = forced;
  676. if (chunk) {
  677. data = chunk->data;
  678. tor_assert(sz <= chunk->datalen);
  679. } else {
  680. data = NULL;
  681. tor_assert(sz == 0);
  682. }
  683. r = tor_tls_write(tls, data, sz);
  684. if (r < 0)
  685. return r;
  686. if (*buf_flushlen > (size_t)r)
  687. *buf_flushlen -= r;
  688. else
  689. *buf_flushlen = 0;
  690. buf_remove_from_front(buf, r);
  691. log_debug(LD_NET,"flushed %d bytes, %d ready to flush, %d remain.",
  692. r,(int)*buf_flushlen,(int)buf->datalen);
  693. return r;
  694. }
  695. /** Write data from <b>buf</b> to the socket <b>s</b>. Write at most
  696. * <b>sz</b> bytes, decrement *<b>buf_flushlen</b> by
  697. * the number of bytes actually written, and remove the written bytes
  698. * from the buffer. Return the number of bytes written on success,
  699. * -1 on failure. Return 0 if write() would block.
  700. */
  701. int
  702. flush_buf(tor_socket_t s, buf_t *buf, size_t sz, size_t *buf_flushlen)
  703. {
  704. /* XXXX It's stupid to overload the return values for these functions:
  705. * "error status" and "number of bytes flushed" are not mutually exclusive.
  706. */
  707. int r;
  708. size_t flushed = 0;
  709. tor_assert(buf_flushlen);
  710. tor_assert(SOCKET_OK(s));
  711. tor_assert(*buf_flushlen <= buf->datalen);
  712. tor_assert(sz <= *buf_flushlen);
  713. check();
  714. while (sz) {
  715. size_t flushlen0;
  716. tor_assert(buf->head);
  717. if (buf->head->datalen >= sz)
  718. flushlen0 = sz;
  719. else
  720. flushlen0 = buf->head->datalen;
  721. r = flush_chunk(s, buf, buf->head, flushlen0, buf_flushlen);
  722. check();
  723. if (r < 0)
  724. return r;
  725. flushed += r;
  726. sz -= r;
  727. if (r == 0 || (size_t)r < flushlen0) /* can't flush any more now. */
  728. break;
  729. }
  730. tor_assert(flushed < INT_MAX);
  731. return (int)flushed;
  732. }
  733. /** As flush_buf(), but writes data to a TLS connection. Can write more than
  734. * <b>flushlen</b> bytes.
  735. */
  736. int
  737. flush_buf_tls(tor_tls_t *tls, buf_t *buf, size_t flushlen,
  738. size_t *buf_flushlen)
  739. {
  740. int r;
  741. size_t flushed = 0;
  742. ssize_t sz;
  743. tor_assert(buf_flushlen);
  744. tor_assert(*buf_flushlen <= buf->datalen);
  745. tor_assert(flushlen <= *buf_flushlen);
  746. sz = (ssize_t) flushlen;
  747. /* we want to let tls write even if flushlen is zero, because it might
  748. * have a partial record pending */
  749. check_no_tls_errors();
  750. check();
  751. do {
  752. size_t flushlen0;
  753. if (buf->head) {
  754. if ((ssize_t)buf->head->datalen >= sz)
  755. flushlen0 = sz;
  756. else
  757. flushlen0 = buf->head->datalen;
  758. } else {
  759. flushlen0 = 0;
  760. }
  761. r = flush_chunk_tls(tls, buf, buf->head, flushlen0, buf_flushlen);
  762. check();
  763. if (r < 0)
  764. return r;
  765. flushed += r;
  766. sz -= r;
  767. if (r == 0) /* Can't flush any more now. */
  768. break;
  769. } while (sz > 0);
  770. tor_assert(flushed < INT_MAX);
  771. return (int)flushed;
  772. }
  773. /** Append <b>string_len</b> bytes from <b>string</b> to the end of
  774. * <b>buf</b>.
  775. *
  776. * Return the new length of the buffer on success, -1 on failure.
  777. */
  778. int
  779. write_to_buf(const char *string, size_t string_len, buf_t *buf)
  780. {
  781. if (!string_len)
  782. return (int)buf->datalen;
  783. check();
  784. while (string_len) {
  785. size_t copy;
  786. if (!buf->tail || !CHUNK_REMAINING_CAPACITY(buf->tail))
  787. buf_add_chunk_with_capacity(buf, string_len, 1);
  788. copy = CHUNK_REMAINING_CAPACITY(buf->tail);
  789. if (copy > string_len)
  790. copy = string_len;
  791. memcpy(CHUNK_WRITE_PTR(buf->tail), string, copy);
  792. string_len -= copy;
  793. string += copy;
  794. buf->datalen += copy;
  795. buf->tail->datalen += copy;
  796. }
  797. check();
  798. tor_assert(buf->datalen < INT_MAX);
  799. return (int)buf->datalen;
  800. }
  801. /** Helper: copy the first <b>string_len</b> bytes from <b>buf</b>
  802. * onto <b>string</b>.
  803. */
  804. static inline void
  805. peek_from_buf(char *string, size_t string_len, const buf_t *buf)
  806. {
  807. chunk_t *chunk;
  808. tor_assert(string);
  809. /* make sure we don't ask for too much */
  810. tor_assert(string_len <= buf->datalen);
  811. /* assert_buf_ok(buf); */
  812. chunk = buf->head;
  813. while (string_len) {
  814. size_t copy = string_len;
  815. tor_assert(chunk);
  816. if (chunk->datalen < copy)
  817. copy = chunk->datalen;
  818. memcpy(string, chunk->data, copy);
  819. string_len -= copy;
  820. string += copy;
  821. chunk = chunk->next;
  822. }
  823. }
  824. /** Remove <b>string_len</b> bytes from the front of <b>buf</b>, and store
  825. * them into <b>string</b>. Return the new buffer size. <b>string_len</b>
  826. * must be \<= the number of bytes on the buffer.
  827. */
  828. int
  829. fetch_from_buf(char *string, size_t string_len, buf_t *buf)
  830. {
  831. /* There must be string_len bytes in buf; write them onto string,
  832. * then memmove buf back (that is, remove them from buf).
  833. *
  834. * Return the number of bytes still on the buffer. */
  835. check();
  836. peek_from_buf(string, string_len, buf);
  837. buf_remove_from_front(buf, string_len);
  838. check();
  839. tor_assert(buf->datalen < INT_MAX);
  840. return (int)buf->datalen;
  841. }
  842. /** True iff the cell command <b>command</b> is one that implies a
  843. * variable-length cell in Tor link protocol <b>linkproto</b>. */
  844. static inline int
  845. cell_command_is_var_length(uint8_t command, int linkproto)
  846. {
  847. /* If linkproto is v2 (2), CELL_VERSIONS is the only variable-length cells
  848. * work as implemented here. If it's 1, there are no variable-length cells.
  849. * Tor does not support other versions right now, and so can't negotiate
  850. * them.
  851. */
  852. switch (linkproto) {
  853. case 1:
  854. /* Link protocol version 1 has no variable-length cells. */
  855. return 0;
  856. case 2:
  857. /* In link protocol version 2, VERSIONS is the only variable-length cell */
  858. return command == CELL_VERSIONS;
  859. case 0:
  860. case 3:
  861. default:
  862. /* In link protocol version 3 and later, and in version "unknown",
  863. * commands 128 and higher indicate variable-length. VERSIONS is
  864. * grandfathered in. */
  865. return command == CELL_VERSIONS || command >= 128;
  866. }
  867. }
  868. /** Check <b>buf</b> for a variable-length cell according to the rules of link
  869. * protocol version <b>linkproto</b>. If one is found, pull it off the buffer
  870. * and assign a newly allocated var_cell_t to *<b>out</b>, and return 1.
  871. * Return 0 if whatever is on the start of buf_t is not a variable-length
  872. * cell. Return 1 and set *<b>out</b> to NULL if there seems to be the start
  873. * of a variable-length cell on <b>buf</b>, but the whole thing isn't there
  874. * yet. */
  875. int
  876. fetch_var_cell_from_buf(buf_t *buf, var_cell_t **out, int linkproto)
  877. {
  878. char hdr[VAR_CELL_MAX_HEADER_SIZE];
  879. var_cell_t *result;
  880. uint8_t command;
  881. uint16_t length;
  882. const int wide_circ_ids = linkproto >= MIN_LINK_PROTO_FOR_WIDE_CIRC_IDS;
  883. const int circ_id_len = get_circ_id_size(wide_circ_ids);
  884. const unsigned header_len = get_var_cell_header_size(wide_circ_ids);
  885. check();
  886. *out = NULL;
  887. if (buf->datalen < header_len)
  888. return 0;
  889. peek_from_buf(hdr, header_len, buf);
  890. command = get_uint8(hdr + circ_id_len);
  891. if (!(cell_command_is_var_length(command, linkproto)))
  892. return 0;
  893. length = ntohs(get_uint16(hdr + circ_id_len + 1));
  894. if (buf->datalen < (size_t)(header_len+length))
  895. return 1;
  896. result = var_cell_new(length);
  897. result->command = command;
  898. if (wide_circ_ids)
  899. result->circ_id = ntohl(get_uint32(hdr));
  900. else
  901. result->circ_id = ntohs(get_uint16(hdr));
  902. buf_remove_from_front(buf, header_len);
  903. peek_from_buf((char*) result->payload, length, buf);
  904. buf_remove_from_front(buf, length);
  905. check();
  906. *out = result;
  907. return 1;
  908. }
  909. /** Move up to *<b>buf_flushlen</b> bytes from <b>buf_in</b> to
  910. * <b>buf_out</b>, and modify *<b>buf_flushlen</b> appropriately.
  911. * Return the number of bytes actually copied.
  912. */
  913. int
  914. move_buf_to_buf(buf_t *buf_out, buf_t *buf_in, size_t *buf_flushlen)
  915. {
  916. /* We can do way better here, but this doesn't turn up in any profiles. */
  917. char b[4096];
  918. size_t cp, len;
  919. len = *buf_flushlen;
  920. if (len > buf_in->datalen)
  921. len = buf_in->datalen;
  922. cp = len; /* Remember the number of bytes we intend to copy. */
  923. tor_assert(cp < INT_MAX);
  924. while (len) {
  925. /* This isn't the most efficient implementation one could imagine, since
  926. * it does two copies instead of 1, but I kinda doubt that this will be
  927. * critical path. */
  928. size_t n = len > sizeof(b) ? sizeof(b) : len;
  929. fetch_from_buf(b, n, buf_in);
  930. write_to_buf(b, n, buf_out);
  931. len -= n;
  932. }
  933. *buf_flushlen -= cp;
  934. return (int)cp;
  935. }
  936. /** Internal structure: represents a position in a buffer. */
  937. typedef struct buf_pos_t {
  938. const chunk_t *chunk; /**< Which chunk are we pointing to? */
  939. int pos;/**< Which character inside the chunk's data are we pointing to? */
  940. size_t chunk_pos; /**< Total length of all previous chunks. */
  941. } buf_pos_t;
  942. /** Initialize <b>out</b> to point to the first character of <b>buf</b>.*/
  943. static void
  944. buf_pos_init(const buf_t *buf, buf_pos_t *out)
  945. {
  946. out->chunk = buf->head;
  947. out->pos = 0;
  948. out->chunk_pos = 0;
  949. }
  950. /** Advance <b>out</b> to the first appearance of <b>ch</b> at the current
  951. * position of <b>out</b>, or later. Return -1 if no instances are found;
  952. * otherwise returns the absolute position of the character. */
  953. static off_t
  954. buf_find_pos_of_char(char ch, buf_pos_t *out)
  955. {
  956. const chunk_t *chunk;
  957. int pos;
  958. tor_assert(out);
  959. if (out->chunk) {
  960. if (out->chunk->datalen) {
  961. tor_assert(out->pos < (off_t)out->chunk->datalen);
  962. } else {
  963. tor_assert(out->pos == 0);
  964. }
  965. }
  966. pos = out->pos;
  967. for (chunk = out->chunk; chunk; chunk = chunk->next) {
  968. char *cp = memchr(chunk->data+pos, ch, chunk->datalen - pos);
  969. if (cp) {
  970. out->chunk = chunk;
  971. tor_assert(cp - chunk->data < INT_MAX);
  972. out->pos = (int)(cp - chunk->data);
  973. return out->chunk_pos + out->pos;
  974. } else {
  975. out->chunk_pos += chunk->datalen;
  976. pos = 0;
  977. }
  978. }
  979. return -1;
  980. }
  981. /** Advance <b>pos</b> by a single character, if there are any more characters
  982. * in the buffer. Returns 0 on success, -1 on failure. */
  983. static inline int
  984. buf_pos_inc(buf_pos_t *pos)
  985. {
  986. ++pos->pos;
  987. if (pos->pos == (off_t)pos->chunk->datalen) {
  988. if (!pos->chunk->next)
  989. return -1;
  990. pos->chunk_pos += pos->chunk->datalen;
  991. pos->chunk = pos->chunk->next;
  992. pos->pos = 0;
  993. }
  994. return 0;
  995. }
  996. /** Return true iff the <b>n</b>-character string in <b>s</b> appears
  997. * (verbatim) at <b>pos</b>. */
  998. static int
  999. buf_matches_at_pos(const buf_pos_t *pos, const char *s, size_t n)
  1000. {
  1001. buf_pos_t p;
  1002. if (!n)
  1003. return 1;
  1004. memcpy(&p, pos, sizeof(p));
  1005. while (1) {
  1006. char ch = p.chunk->data[p.pos];
  1007. if (ch != *s)
  1008. return 0;
  1009. ++s;
  1010. /* If we're out of characters that don't match, we match. Check this
  1011. * _before_ we test incrementing pos, in case we're at the end of the
  1012. * string. */
  1013. if (--n == 0)
  1014. return 1;
  1015. if (buf_pos_inc(&p)<0)
  1016. return 0;
  1017. }
  1018. }
  1019. /** Return the first position in <b>buf</b> at which the <b>n</b>-character
  1020. * string <b>s</b> occurs, or -1 if it does not occur. */
  1021. STATIC int
  1022. buf_find_string_offset(const buf_t *buf, const char *s, size_t n)
  1023. {
  1024. buf_pos_t pos;
  1025. buf_pos_init(buf, &pos);
  1026. while (buf_find_pos_of_char(*s, &pos) >= 0) {
  1027. if (buf_matches_at_pos(&pos, s, n)) {
  1028. tor_assert(pos.chunk_pos + pos.pos < INT_MAX);
  1029. return (int)(pos.chunk_pos + pos.pos);
  1030. } else {
  1031. if (buf_pos_inc(&pos)<0)
  1032. return -1;
  1033. }
  1034. }
  1035. return -1;
  1036. }
  1037. /**
  1038. * Scan the HTTP headers in the <b>headerlen</b>-byte memory range at
  1039. * <b>headers</b>, looking for a "Content-Length" header. Try to set
  1040. * *<b>result_out</b> to the numeric value of that header if possible.
  1041. * Return -1 if the header was malformed, 0 if it was missing, and 1 if
  1042. * it was present and well-formed.
  1043. */
  1044. STATIC int
  1045. buf_http_find_content_length(const char *headers, size_t headerlen,
  1046. size_t *result_out)
  1047. {
  1048. const char *p, *newline;
  1049. char *len_str, *eos=NULL;
  1050. size_t remaining, result;
  1051. int ok;
  1052. *result_out = 0; /* The caller shouldn't look at this unless the
  1053. * return value is 1, but let's prevent confusion */
  1054. #define CONTENT_LENGTH "\r\nContent-Length: "
  1055. p = (char*) tor_memstr(headers, headerlen, CONTENT_LENGTH);
  1056. if (p == NULL)
  1057. return 0;
  1058. tor_assert(p >= headers && p < headers+headerlen);
  1059. remaining = (headers+headerlen)-p;
  1060. p += strlen(CONTENT_LENGTH);
  1061. remaining -= strlen(CONTENT_LENGTH);
  1062. newline = memchr(p, '\n', remaining);
  1063. if (newline == NULL)
  1064. return -1;
  1065. len_str = tor_memdup_nulterm(p, newline-p);
  1066. /* We limit the size to INT_MAX because other parts of the buffer.c
  1067. * code don't like buffers to be any bigger than that. */
  1068. result = (size_t) tor_parse_uint64(len_str, 10, 0, INT_MAX, &ok, &eos);
  1069. if (eos && !tor_strisspace(eos)) {
  1070. ok = 0;
  1071. } else {
  1072. *result_out = result;
  1073. }
  1074. tor_free(len_str);
  1075. return ok ? 1 : -1;
  1076. }
  1077. /** There is a (possibly incomplete) http statement on <b>buf</b>, of the
  1078. * form "\%s\\r\\n\\r\\n\%s", headers, body. (body may contain NULs.)
  1079. * If a) the headers include a Content-Length field and all bytes in
  1080. * the body are present, or b) there's no Content-Length field and
  1081. * all headers are present, then:
  1082. *
  1083. * - strdup headers into <b>*headers_out</b>, and NUL-terminate it.
  1084. * - memdup body into <b>*body_out</b>, and NUL-terminate it.
  1085. * - Then remove them from <b>buf</b>, and return 1.
  1086. *
  1087. * - If headers or body is NULL, discard that part of the buf.
  1088. * - If a headers or body doesn't fit in the arg, return -1.
  1089. * (We ensure that the headers or body don't exceed max len,
  1090. * _even if_ we're planning to discard them.)
  1091. * - If force_complete is true, then succeed even if not all of the
  1092. * content has arrived.
  1093. *
  1094. * Else, change nothing and return 0.
  1095. */
  1096. int
  1097. fetch_from_buf_http(buf_t *buf,
  1098. char **headers_out, size_t max_headerlen,
  1099. char **body_out, size_t *body_used, size_t max_bodylen,
  1100. int force_complete)
  1101. {
  1102. char *headers;
  1103. size_t headerlen, bodylen, contentlen=0;
  1104. int crlf_offset;
  1105. int r;
  1106. check();
  1107. if (!buf->head)
  1108. return 0;
  1109. crlf_offset = buf_find_string_offset(buf, "\r\n\r\n", 4);
  1110. if (crlf_offset > (int)max_headerlen ||
  1111. (crlf_offset < 0 && buf->datalen > max_headerlen)) {
  1112. log_debug(LD_HTTP,"headers too long.");
  1113. return -1;
  1114. } else if (crlf_offset < 0) {
  1115. log_debug(LD_HTTP,"headers not all here yet.");
  1116. return 0;
  1117. }
  1118. /* Okay, we have a full header. Make sure it all appears in the first
  1119. * chunk. */
  1120. if ((int)buf->head->datalen < crlf_offset + 4)
  1121. buf_pullup(buf, crlf_offset+4);
  1122. headerlen = crlf_offset + 4;
  1123. headers = buf->head->data;
  1124. bodylen = buf->datalen - headerlen;
  1125. log_debug(LD_HTTP,"headerlen %d, bodylen %d.", (int)headerlen, (int)bodylen);
  1126. if (max_headerlen <= headerlen) {
  1127. log_warn(LD_HTTP,"headerlen %d larger than %d. Failing.",
  1128. (int)headerlen, (int)max_headerlen-1);
  1129. return -1;
  1130. }
  1131. if (max_bodylen <= bodylen) {
  1132. log_warn(LD_HTTP,"bodylen %d larger than %d. Failing.",
  1133. (int)bodylen, (int)max_bodylen-1);
  1134. return -1;
  1135. }
  1136. r = buf_http_find_content_length(headers, headerlen, &contentlen);
  1137. if (r == -1) {
  1138. log_warn(LD_PROTOCOL, "Content-Length is bogus; maybe "
  1139. "someone is trying to crash us.");
  1140. return -1;
  1141. } else if (r == 1) {
  1142. /* if content-length is malformed, then our body length is 0. fine. */
  1143. log_debug(LD_HTTP,"Got a contentlen of %d.",(int)contentlen);
  1144. if (bodylen < contentlen) {
  1145. if (!force_complete) {
  1146. log_debug(LD_HTTP,"body not all here yet.");
  1147. return 0; /* not all there yet */
  1148. }
  1149. }
  1150. if (bodylen > contentlen) {
  1151. bodylen = contentlen;
  1152. log_debug(LD_HTTP,"bodylen reduced to %d.",(int)bodylen);
  1153. }
  1154. } else {
  1155. tor_assert(r == 0);
  1156. /* Leave bodylen alone */
  1157. }
  1158. /* all happy. copy into the appropriate places, and return 1 */
  1159. if (headers_out) {
  1160. *headers_out = tor_malloc(headerlen+1);
  1161. fetch_from_buf(*headers_out, headerlen, buf);
  1162. (*headers_out)[headerlen] = 0; /* NUL terminate it */
  1163. }
  1164. if (body_out) {
  1165. tor_assert(body_used);
  1166. *body_used = bodylen;
  1167. *body_out = tor_malloc(bodylen+1);
  1168. fetch_from_buf(*body_out, bodylen, buf);
  1169. (*body_out)[bodylen] = 0; /* NUL terminate it */
  1170. }
  1171. check();
  1172. return 1;
  1173. }
  1174. /**
  1175. * Wait this many seconds before warning the user about using SOCKS unsafely
  1176. * again (requires that WarnUnsafeSocks is turned on). */
  1177. #define SOCKS_WARN_INTERVAL 5
  1178. /** Warn that the user application has made an unsafe socks request using
  1179. * protocol <b>socks_protocol</b> on port <b>port</b>. Don't warn more than
  1180. * once per SOCKS_WARN_INTERVAL, unless <b>safe_socks</b> is set. */
  1181. static void
  1182. log_unsafe_socks_warning(int socks_protocol, const char *address,
  1183. uint16_t port, int safe_socks)
  1184. {
  1185. static ratelim_t socks_ratelim = RATELIM_INIT(SOCKS_WARN_INTERVAL);
  1186. const or_options_t *options = get_options();
  1187. if (! options->WarnUnsafeSocks)
  1188. return;
  1189. if (safe_socks) {
  1190. log_fn_ratelim(&socks_ratelim, LOG_WARN, LD_APP,
  1191. "Your application (using socks%d to port %d) is giving "
  1192. "Tor only an IP address. Applications that do DNS resolves "
  1193. "themselves may leak information. Consider using Socks4A "
  1194. "(e.g. via privoxy or socat) instead. For more information, "
  1195. "please see https://wiki.torproject.org/TheOnionRouter/"
  1196. "TorFAQ#SOCKSAndDNS.%s",
  1197. socks_protocol,
  1198. (int)port,
  1199. safe_socks ? " Rejecting." : "");
  1200. }
  1201. control_event_client_status(LOG_WARN,
  1202. "DANGEROUS_SOCKS PROTOCOL=SOCKS%d ADDRESS=%s:%d",
  1203. socks_protocol, address, (int)port);
  1204. }
  1205. /** Do not attempt to parse socks messages longer than this. This value is
  1206. * actually significantly higher than the longest possible socks message. */
  1207. #define MAX_SOCKS_MESSAGE_LEN 512
  1208. /** Return a new socks_request_t. */
  1209. socks_request_t *
  1210. socks_request_new(void)
  1211. {
  1212. return tor_malloc_zero(sizeof(socks_request_t));
  1213. }
  1214. /** Free all storage held in the socks_request_t <b>req</b>. */
  1215. void
  1216. socks_request_free(socks_request_t *req)
  1217. {
  1218. if (!req)
  1219. return;
  1220. if (req->username) {
  1221. memwipe(req->username, 0x10, req->usernamelen);
  1222. tor_free(req->username);
  1223. }
  1224. if (req->password) {
  1225. memwipe(req->password, 0x04, req->passwordlen);
  1226. tor_free(req->password);
  1227. }
  1228. memwipe(req, 0xCC, sizeof(socks_request_t));
  1229. tor_free(req);
  1230. }
  1231. /** There is a (possibly incomplete) socks handshake on <b>buf</b>, of one
  1232. * of the forms
  1233. * - socks4: "socksheader username\\0"
  1234. * - socks4a: "socksheader username\\0 destaddr\\0"
  1235. * - socks5 phase one: "version #methods methods"
  1236. * - socks5 phase two: "version command 0 addresstype..."
  1237. * If it's a complete and valid handshake, and destaddr fits in
  1238. * MAX_SOCKS_ADDR_LEN bytes, then pull the handshake off the buf,
  1239. * assign to <b>req</b>, and return 1.
  1240. *
  1241. * If it's invalid or too big, return -1.
  1242. *
  1243. * Else it's not all there yet, leave buf alone and return 0.
  1244. *
  1245. * If you want to specify the socks reply, write it into <b>req->reply</b>
  1246. * and set <b>req->replylen</b>, else leave <b>req->replylen</b> alone.
  1247. *
  1248. * If <b>log_sockstype</b> is non-zero, then do a notice-level log of whether
  1249. * the connection is possibly leaking DNS requests locally or not.
  1250. *
  1251. * If <b>safe_socks</b> is true, then reject unsafe socks protocols.
  1252. *
  1253. * If returning 0 or -1, <b>req->address</b> and <b>req->port</b> are
  1254. * undefined.
  1255. */
  1256. int
  1257. fetch_from_buf_socks(buf_t *buf, socks_request_t *req,
  1258. int log_sockstype, int safe_socks)
  1259. {
  1260. int res;
  1261. ssize_t n_drain;
  1262. size_t want_length = 128;
  1263. if (buf->datalen < 2) /* version and another byte */
  1264. return 0;
  1265. do {
  1266. n_drain = 0;
  1267. buf_pullup(buf, want_length);
  1268. tor_assert(buf->head && buf->head->datalen >= 2);
  1269. want_length = 0;
  1270. res = parse_socks(buf->head->data, buf->head->datalen, req, log_sockstype,
  1271. safe_socks, &n_drain, &want_length);
  1272. if (n_drain < 0)
  1273. buf_clear(buf);
  1274. else if (n_drain > 0)
  1275. buf_remove_from_front(buf, n_drain);
  1276. } while (res == 0 && buf->head && want_length < buf->datalen &&
  1277. buf->datalen >= 2);
  1278. return res;
  1279. }
  1280. /** The size of the header of an Extended ORPort message: 2 bytes for
  1281. * COMMAND, 2 bytes for BODYLEN */
  1282. #define EXT_OR_CMD_HEADER_SIZE 4
  1283. /** Read <b>buf</b>, which should contain an Extended ORPort message
  1284. * from a transport proxy. If well-formed, create and populate
  1285. * <b>out</b> with the Extended ORport message. Return 0 if the
  1286. * buffer was incomplete, 1 if it was well-formed and -1 if we
  1287. * encountered an error while parsing it. */
  1288. int
  1289. fetch_ext_or_command_from_buf(buf_t *buf, ext_or_cmd_t **out)
  1290. {
  1291. char hdr[EXT_OR_CMD_HEADER_SIZE];
  1292. uint16_t len;
  1293. check();
  1294. if (buf->datalen < EXT_OR_CMD_HEADER_SIZE)
  1295. return 0;
  1296. peek_from_buf(hdr, sizeof(hdr), buf);
  1297. len = ntohs(get_uint16(hdr+2));
  1298. if (buf->datalen < (unsigned)len + EXT_OR_CMD_HEADER_SIZE)
  1299. return 0;
  1300. *out = ext_or_cmd_new(len);
  1301. (*out)->cmd = ntohs(get_uint16(hdr));
  1302. (*out)->len = len;
  1303. buf_remove_from_front(buf, EXT_OR_CMD_HEADER_SIZE);
  1304. fetch_from_buf((*out)->body, len, buf);
  1305. return 1;
  1306. }
  1307. /** Create a SOCKS5 reply message with <b>reason</b> in its REP field and
  1308. * have Tor send it as error response to <b>req</b>.
  1309. */
  1310. static void
  1311. socks_request_set_socks5_error(socks_request_t *req,
  1312. socks5_reply_status_t reason)
  1313. {
  1314. req->replylen = 10;
  1315. memset(req->reply,0,10);
  1316. req->reply[0] = 0x05; // VER field.
  1317. req->reply[1] = reason; // REP field.
  1318. req->reply[3] = 0x01; // ATYP field.
  1319. }
  1320. /** Implementation helper to implement fetch_from_*_socks. Instead of looking
  1321. * at a buffer's contents, we look at the <b>datalen</b> bytes of data in
  1322. * <b>data</b>. Instead of removing data from the buffer, we set
  1323. * <b>drain_out</b> to the amount of data that should be removed (or -1 if the
  1324. * buffer should be cleared). Instead of pulling more data into the first
  1325. * chunk of the buffer, we set *<b>want_length_out</b> to the number of bytes
  1326. * we'd like to see in the input buffer, if they're available. */
  1327. static int
  1328. parse_socks(const char *data, size_t datalen, socks_request_t *req,
  1329. int log_sockstype, int safe_socks, ssize_t *drain_out,
  1330. size_t *want_length_out)
  1331. {
  1332. unsigned int len;
  1333. char tmpbuf[TOR_ADDR_BUF_LEN+1];
  1334. tor_addr_t destaddr;
  1335. uint32_t destip;
  1336. uint8_t socksver;
  1337. char *next, *startaddr;
  1338. unsigned char usernamelen, passlen;
  1339. struct in_addr in;
  1340. if (datalen < 2) {
  1341. /* We always need at least 2 bytes. */
  1342. *want_length_out = 2;
  1343. return 0;
  1344. }
  1345. if (req->socks_version == 5 && !req->got_auth) {
  1346. /* See if we have received authentication. Strictly speaking, we should
  1347. also check whether we actually negotiated username/password
  1348. authentication. But some broken clients will send us authentication
  1349. even if we negotiated SOCKS_NO_AUTH. */
  1350. if (*data == 1) { /* username/pass version 1 */
  1351. /* Format is: authversion [1 byte] == 1
  1352. usernamelen [1 byte]
  1353. username [usernamelen bytes]
  1354. passlen [1 byte]
  1355. password [passlen bytes] */
  1356. usernamelen = (unsigned char)*(data + 1);
  1357. if (datalen < 2u + usernamelen + 1u) {
  1358. *want_length_out = 2u + usernamelen + 1u;
  1359. return 0;
  1360. }
  1361. passlen = (unsigned char)*(data + 2u + usernamelen);
  1362. if (datalen < 2u + usernamelen + 1u + passlen) {
  1363. *want_length_out = 2u + usernamelen + 1u + passlen;
  1364. return 0;
  1365. }
  1366. req->replylen = 2; /* 2 bytes of response */
  1367. req->reply[0] = 1; /* authversion == 1 */
  1368. req->reply[1] = 0; /* authentication successful */
  1369. log_debug(LD_APP,
  1370. "socks5: Accepted username/password without checking.");
  1371. if (usernamelen) {
  1372. req->username = tor_memdup(data+2u, usernamelen);
  1373. req->usernamelen = usernamelen;
  1374. }
  1375. if (passlen) {
  1376. req->password = tor_memdup(data+3u+usernamelen, passlen);
  1377. req->passwordlen = passlen;
  1378. }
  1379. *drain_out = 2u + usernamelen + 1u + passlen;
  1380. req->got_auth = 1;
  1381. *want_length_out = 7; /* Minimal socks5 command. */
  1382. return 0;
  1383. } else if (req->auth_type == SOCKS_USER_PASS) {
  1384. /* unknown version byte */
  1385. log_warn(LD_APP, "Socks5 username/password version %d not recognized; "
  1386. "rejecting.", (int)*data);
  1387. return -1;
  1388. }
  1389. }
  1390. socksver = *data;
  1391. switch (socksver) { /* which version of socks? */
  1392. case 5: /* socks5 */
  1393. if (req->socks_version != 5) { /* we need to negotiate a method */
  1394. unsigned char nummethods = (unsigned char)*(data+1);
  1395. int have_user_pass, have_no_auth;
  1396. int r=0;
  1397. tor_assert(!req->socks_version);
  1398. if (datalen < 2u+nummethods) {
  1399. *want_length_out = 2u+nummethods;
  1400. return 0;
  1401. }
  1402. if (!nummethods)
  1403. return -1;
  1404. req->replylen = 2; /* 2 bytes of response */
  1405. req->reply[0] = 5; /* socks5 reply */
  1406. have_user_pass = (memchr(data+2, SOCKS_USER_PASS, nummethods) !=NULL);
  1407. have_no_auth = (memchr(data+2, SOCKS_NO_AUTH, nummethods) !=NULL);
  1408. if (have_user_pass && !(have_no_auth && req->socks_prefer_no_auth)) {
  1409. req->auth_type = SOCKS_USER_PASS;
  1410. req->reply[1] = SOCKS_USER_PASS; /* tell client to use "user/pass"
  1411. auth method */
  1412. req->socks_version = 5; /* remember we've already negotiated auth */
  1413. log_debug(LD_APP,"socks5: accepted method 2 (username/password)");
  1414. r=0;
  1415. } else if (have_no_auth) {
  1416. req->reply[1] = SOCKS_NO_AUTH; /* tell client to use "none" auth
  1417. method */
  1418. req->socks_version = 5; /* remember we've already negotiated auth */
  1419. log_debug(LD_APP,"socks5: accepted method 0 (no authentication)");
  1420. r=0;
  1421. } else {
  1422. log_warn(LD_APP,
  1423. "socks5: offered methods don't include 'no auth' or "
  1424. "username/password. Rejecting.");
  1425. req->reply[1] = '\xFF'; /* reject all methods */
  1426. r=-1;
  1427. }
  1428. /* Remove packet from buf. Some SOCKS clients will have sent extra
  1429. * junk at this point; let's hope it's an authentication message. */
  1430. *drain_out = 2u + nummethods;
  1431. return r;
  1432. }
  1433. if (req->auth_type != SOCKS_NO_AUTH && !req->got_auth) {
  1434. log_warn(LD_APP,
  1435. "socks5: negotiated authentication, but none provided");
  1436. return -1;
  1437. }
  1438. /* we know the method; read in the request */
  1439. log_debug(LD_APP,"socks5: checking request");
  1440. if (datalen < 7) {/* basic info plus >=1 for addr plus 2 for port */
  1441. *want_length_out = 7;
  1442. return 0; /* not yet */
  1443. }
  1444. req->command = (unsigned char) *(data+1);
  1445. if (req->command != SOCKS_COMMAND_CONNECT &&
  1446. req->command != SOCKS_COMMAND_RESOLVE &&
  1447. req->command != SOCKS_COMMAND_RESOLVE_PTR) {
  1448. /* not a connect or resolve or a resolve_ptr? we don't support it. */
  1449. socks_request_set_socks5_error(req,SOCKS5_COMMAND_NOT_SUPPORTED);
  1450. log_warn(LD_APP,"socks5: command %d not recognized. Rejecting.",
  1451. req->command);
  1452. return -1;
  1453. }
  1454. switch (*(data+3)) { /* address type */
  1455. case 1: /* IPv4 address */
  1456. case 4: /* IPv6 address */ {
  1457. const int is_v6 = *(data+3) == 4;
  1458. const unsigned addrlen = is_v6 ? 16 : 4;
  1459. log_debug(LD_APP,"socks5: ipv4 address type");
  1460. if (datalen < 6+addrlen) {/* ip/port there? */
  1461. *want_length_out = 6+addrlen;
  1462. return 0; /* not yet */
  1463. }
  1464. if (is_v6)
  1465. tor_addr_from_ipv6_bytes(&destaddr, data+4);
  1466. else
  1467. tor_addr_from_ipv4n(&destaddr, get_uint32(data+4));
  1468. tor_addr_to_str(tmpbuf, &destaddr, sizeof(tmpbuf), 1);
  1469. if (strlen(tmpbuf)+1 > MAX_SOCKS_ADDR_LEN) {
  1470. socks_request_set_socks5_error(req, SOCKS5_GENERAL_ERROR);
  1471. log_warn(LD_APP,
  1472. "socks5 IP takes %d bytes, which doesn't fit in %d. "
  1473. "Rejecting.",
  1474. (int)strlen(tmpbuf)+1,(int)MAX_SOCKS_ADDR_LEN);
  1475. return -1;
  1476. }
  1477. strlcpy(req->address,tmpbuf,sizeof(req->address));
  1478. req->port = ntohs(get_uint16(data+4+addrlen));
  1479. *drain_out = 6+addrlen;
  1480. if (req->command != SOCKS_COMMAND_RESOLVE_PTR &&
  1481. !addressmap_have_mapping(req->address,0)) {
  1482. log_unsafe_socks_warning(5, req->address, req->port, safe_socks);
  1483. if (safe_socks) {
  1484. socks_request_set_socks5_error(req, SOCKS5_NOT_ALLOWED);
  1485. return -1;
  1486. }
  1487. }
  1488. return 1;
  1489. }
  1490. case 3: /* fqdn */
  1491. log_debug(LD_APP,"socks5: fqdn address type");
  1492. if (req->command == SOCKS_COMMAND_RESOLVE_PTR) {
  1493. socks_request_set_socks5_error(req,
  1494. SOCKS5_ADDRESS_TYPE_NOT_SUPPORTED);
  1495. log_warn(LD_APP, "socks5 received RESOLVE_PTR command with "
  1496. "hostname type. Rejecting.");
  1497. return -1;
  1498. }
  1499. len = (unsigned char)*(data+4);
  1500. if (datalen < 7+len) { /* addr/port there? */
  1501. *want_length_out = 7+len;
  1502. return 0; /* not yet */
  1503. }
  1504. if (len+1 > MAX_SOCKS_ADDR_LEN) {
  1505. socks_request_set_socks5_error(req, SOCKS5_GENERAL_ERROR);
  1506. log_warn(LD_APP,
  1507. "socks5 hostname is %d bytes, which doesn't fit in "
  1508. "%d. Rejecting.", len+1,MAX_SOCKS_ADDR_LEN);
  1509. return -1;
  1510. }
  1511. memcpy(req->address,data+5,len);
  1512. req->address[len] = 0;
  1513. req->port = ntohs(get_uint16(data+5+len));
  1514. *drain_out = 5+len+2;
  1515. if (string_is_valid_ipv4_address(req->address) ||
  1516. string_is_valid_ipv6_address(req->address)) {
  1517. log_unsafe_socks_warning(5,req->address,req->port,safe_socks);
  1518. if (safe_socks) {
  1519. socks_request_set_socks5_error(req, SOCKS5_NOT_ALLOWED);
  1520. return -1;
  1521. }
  1522. } else if (!string_is_valid_hostname(req->address)) {
  1523. socks_request_set_socks5_error(req, SOCKS5_GENERAL_ERROR);
  1524. log_warn(LD_PROTOCOL,
  1525. "Your application (using socks5 to port %d) gave Tor "
  1526. "a malformed hostname: %s. Rejecting the connection.",
  1527. req->port, escaped_safe_str_client(req->address));
  1528. return -1;
  1529. }
  1530. if (log_sockstype)
  1531. log_notice(LD_APP,
  1532. "Your application (using socks5 to port %d) instructed "
  1533. "Tor to take care of the DNS resolution itself if "
  1534. "necessary. This is good.", req->port);
  1535. return 1;
  1536. default: /* unsupported */
  1537. socks_request_set_socks5_error(req,
  1538. SOCKS5_ADDRESS_TYPE_NOT_SUPPORTED);
  1539. log_warn(LD_APP,"socks5: unsupported address type %d. Rejecting.",
  1540. (int) *(data+3));
  1541. return -1;
  1542. }
  1543. tor_assert(0);
  1544. case 4: { /* socks4 */
  1545. enum {socks4, socks4a} socks4_prot = socks4a;
  1546. const char *authstart, *authend;
  1547. /* http://ss5.sourceforge.net/socks4.protocol.txt */
  1548. /* http://ss5.sourceforge.net/socks4A.protocol.txt */
  1549. req->socks_version = 4;
  1550. if (datalen < SOCKS4_NETWORK_LEN) {/* basic info available? */
  1551. *want_length_out = SOCKS4_NETWORK_LEN;
  1552. return 0; /* not yet */
  1553. }
  1554. // buf_pullup(buf, 1280);
  1555. req->command = (unsigned char) *(data+1);
  1556. if (req->command != SOCKS_COMMAND_CONNECT &&
  1557. req->command != SOCKS_COMMAND_RESOLVE) {
  1558. /* not a connect or resolve? we don't support it. (No resolve_ptr with
  1559. * socks4.) */
  1560. log_warn(LD_APP,"socks4: command %d not recognized. Rejecting.",
  1561. req->command);
  1562. return -1;
  1563. }
  1564. req->port = ntohs(get_uint16(data+2));
  1565. destip = ntohl(get_uint32(data+4));
  1566. if ((!req->port && req->command!=SOCKS_COMMAND_RESOLVE) || !destip) {
  1567. log_warn(LD_APP,"socks4: Port or DestIP is zero. Rejecting.");
  1568. return -1;
  1569. }
  1570. if (destip >> 8) {
  1571. log_debug(LD_APP,"socks4: destip not in form 0.0.0.x.");
  1572. in.s_addr = htonl(destip);
  1573. tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
  1574. if (strlen(tmpbuf)+1 > MAX_SOCKS_ADDR_LEN) {
  1575. log_debug(LD_APP,"socks4 addr (%d bytes) too long. Rejecting.",
  1576. (int)strlen(tmpbuf));
  1577. return -1;
  1578. }
  1579. log_debug(LD_APP,
  1580. "socks4: successfully read destip (%s)",
  1581. safe_str_client(tmpbuf));
  1582. socks4_prot = socks4;
  1583. }
  1584. authstart = data + SOCKS4_NETWORK_LEN;
  1585. next = memchr(authstart, 0,
  1586. datalen-SOCKS4_NETWORK_LEN);
  1587. if (!next) {
  1588. if (datalen >= 1024) {
  1589. log_debug(LD_APP, "Socks4 user name too long; rejecting.");
  1590. return -1;
  1591. }
  1592. log_debug(LD_APP,"socks4: Username not here yet.");
  1593. *want_length_out = datalen+1024; /* More than we need, but safe */
  1594. return 0;
  1595. }
  1596. authend = next;
  1597. tor_assert(next < data+datalen);
  1598. startaddr = NULL;
  1599. if (socks4_prot != socks4a &&
  1600. !addressmap_have_mapping(tmpbuf,0)) {
  1601. log_unsafe_socks_warning(4, tmpbuf, req->port, safe_socks);
  1602. if (safe_socks)
  1603. return -1;
  1604. }
  1605. if (socks4_prot == socks4a) {
  1606. if (next+1 == data+datalen) {
  1607. log_debug(LD_APP,"socks4: No part of destaddr here yet.");
  1608. *want_length_out = datalen + 1024; /* More than we need, but safe */
  1609. return 0;
  1610. }
  1611. startaddr = next+1;
  1612. next = memchr(startaddr, 0, data + datalen - startaddr);
  1613. if (!next) {
  1614. if (datalen >= 1024) {
  1615. log_debug(LD_APP,"socks4: Destaddr too long.");
  1616. return -1;
  1617. }
  1618. log_debug(LD_APP,"socks4: Destaddr not all here yet.");
  1619. *want_length_out = datalen + 1024; /* More than we need, but safe */
  1620. return 0;
  1621. }
  1622. if (MAX_SOCKS_ADDR_LEN <= next-startaddr) {
  1623. log_warn(LD_APP,"socks4: Destaddr too long. Rejecting.");
  1624. return -1;
  1625. }
  1626. // tor_assert(next < buf->cur+buf->datalen);
  1627. if (log_sockstype)
  1628. log_notice(LD_APP,
  1629. "Your application (using socks4a to port %d) instructed "
  1630. "Tor to take care of the DNS resolution itself if "
  1631. "necessary. This is good.", req->port);
  1632. }
  1633. log_debug(LD_APP,"socks4: Everything is here. Success.");
  1634. strlcpy(req->address, startaddr ? startaddr : tmpbuf,
  1635. sizeof(req->address));
  1636. if (!tor_strisprint(req->address) || strchr(req->address,'\"')) {
  1637. log_warn(LD_PROTOCOL,
  1638. "Your application (using socks4 to port %d) gave Tor "
  1639. "a malformed hostname: %s. Rejecting the connection.",
  1640. req->port, escaped_safe_str_client(req->address));
  1641. return -1;
  1642. }
  1643. if (authend != authstart) {
  1644. req->got_auth = 1;
  1645. req->usernamelen = authend - authstart;
  1646. req->username = tor_memdup(authstart, authend - authstart);
  1647. }
  1648. /* next points to the final \0 on inbuf */
  1649. *drain_out = next - data + 1;
  1650. return 1;
  1651. }
  1652. case 'G': /* get */
  1653. case 'H': /* head */
  1654. case 'P': /* put/post */
  1655. case 'C': /* connect */
  1656. strlcpy((char*)req->reply,
  1657. "HTTP/1.0 501 Tor is not an HTTP Proxy\r\n"
  1658. "Content-Type: text/html; charset=iso-8859-1\r\n\r\n"
  1659. "<html>\n"
  1660. "<head>\n"
  1661. "<title>Tor is not an HTTP Proxy</title>\n"
  1662. "</head>\n"
  1663. "<body>\n"
  1664. "<h1>Tor is not an HTTP Proxy</h1>\n"
  1665. "<p>\n"
  1666. "It appears you have configured your web browser to use Tor as an HTTP proxy."
  1667. "\n"
  1668. "This is not correct: Tor is a SOCKS proxy, not an HTTP proxy.\n"
  1669. "Please configure your client accordingly.\n"
  1670. "</p>\n"
  1671. "<p>\n"
  1672. "See <a href=\"https://www.torproject.org/documentation.html\">"
  1673. "https://www.torproject.org/documentation.html</a> for more "
  1674. "information.\n"
  1675. "<!-- Plus this comment, to make the body response more than 512 bytes, so "
  1676. " IE will be willing to display it. Comment comment comment comment "
  1677. " comment comment comment comment comment comment comment comment.-->\n"
  1678. "</p>\n"
  1679. "</body>\n"
  1680. "</html>\n"
  1681. , MAX_SOCKS_REPLY_LEN);
  1682. req->replylen = strlen((char*)req->reply)+1;
  1683. /* fall through */
  1684. default: /* version is not socks4 or socks5 */
  1685. log_warn(LD_APP,
  1686. "Socks version %d not recognized. (Tor is not an http proxy.)",
  1687. *(data));
  1688. {
  1689. /* Tell the controller the first 8 bytes. */
  1690. char *tmp = tor_strndup(data, datalen < 8 ? datalen : 8);
  1691. control_event_client_status(LOG_WARN,
  1692. "SOCKS_UNKNOWN_PROTOCOL DATA=\"%s\"",
  1693. escaped(tmp));
  1694. tor_free(tmp);
  1695. }
  1696. return -1;
  1697. }
  1698. }
  1699. /** Inspect a reply from SOCKS server stored in <b>buf</b> according
  1700. * to <b>state</b>, removing the protocol data upon success. Return 0 on
  1701. * incomplete response, 1 on success and -1 on error, in which case
  1702. * <b>reason</b> is set to a descriptive message (free() when finished
  1703. * with it).
  1704. *
  1705. * As a special case, 2 is returned when user/pass is required
  1706. * during SOCKS5 handshake and user/pass is configured.
  1707. */
  1708. int
  1709. fetch_from_buf_socks_client(buf_t *buf, int state, char **reason)
  1710. {
  1711. ssize_t drain = 0;
  1712. int r;
  1713. if (buf->datalen < 2)
  1714. return 0;
  1715. buf_pullup(buf, MAX_SOCKS_MESSAGE_LEN);
  1716. tor_assert(buf->head && buf->head->datalen >= 2);
  1717. r = parse_socks_client((uint8_t*)buf->head->data, buf->head->datalen,
  1718. state, reason, &drain);
  1719. if (drain > 0)
  1720. buf_remove_from_front(buf, drain);
  1721. else if (drain < 0)
  1722. buf_clear(buf);
  1723. return r;
  1724. }
  1725. /** Implementation logic for fetch_from_*_socks_client. */
  1726. static int
  1727. parse_socks_client(const uint8_t *data, size_t datalen,
  1728. int state, char **reason,
  1729. ssize_t *drain_out)
  1730. {
  1731. unsigned int addrlen;
  1732. *drain_out = 0;
  1733. if (datalen < 2)
  1734. return 0;
  1735. switch (state) {
  1736. case PROXY_SOCKS4_WANT_CONNECT_OK:
  1737. /* Wait for the complete response */
  1738. if (datalen < 8)
  1739. return 0;
  1740. if (data[1] != 0x5a) {
  1741. *reason = tor_strdup(socks4_response_code_to_string(data[1]));
  1742. return -1;
  1743. }
  1744. /* Success */
  1745. *drain_out = 8;
  1746. return 1;
  1747. case PROXY_SOCKS5_WANT_AUTH_METHOD_NONE:
  1748. /* we don't have any credentials */
  1749. if (data[1] != 0x00) {
  1750. *reason = tor_strdup("server doesn't support any of our "
  1751. "available authentication methods");
  1752. return -1;
  1753. }
  1754. log_info(LD_NET, "SOCKS 5 client: continuing without authentication");
  1755. *drain_out = -1;
  1756. return 1;
  1757. case PROXY_SOCKS5_WANT_AUTH_METHOD_RFC1929:
  1758. /* we have a username and password. return 1 if we can proceed without
  1759. * providing authentication, or 2 otherwise. */
  1760. switch (data[1]) {
  1761. case 0x00:
  1762. log_info(LD_NET, "SOCKS 5 client: we have auth details but server "
  1763. "doesn't require authentication.");
  1764. *drain_out = -1;
  1765. return 1;
  1766. case 0x02:
  1767. log_info(LD_NET, "SOCKS 5 client: need authentication.");
  1768. *drain_out = -1;
  1769. return 2;
  1770. /* fall through */
  1771. }
  1772. *reason = tor_strdup("server doesn't support any of our available "
  1773. "authentication methods");
  1774. return -1;
  1775. case PROXY_SOCKS5_WANT_AUTH_RFC1929_OK:
  1776. /* handle server reply to rfc1929 authentication */
  1777. if (data[1] != 0x00) {
  1778. *reason = tor_strdup("authentication failed");
  1779. return -1;
  1780. }
  1781. log_info(LD_NET, "SOCKS 5 client: authentication successful.");
  1782. *drain_out = -1;
  1783. return 1;
  1784. case PROXY_SOCKS5_WANT_CONNECT_OK:
  1785. /* response is variable length. BND.ADDR, etc, isn't needed
  1786. * (don't bother with buf_pullup()), but make sure to eat all
  1787. * the data used */
  1788. /* wait for address type field to arrive */
  1789. if (datalen < 4)
  1790. return 0;
  1791. switch (data[3]) {
  1792. case 0x01: /* ip4 */
  1793. addrlen = 4;
  1794. break;
  1795. case 0x04: /* ip6 */
  1796. addrlen = 16;
  1797. break;
  1798. case 0x03: /* fqdn (can this happen here?) */
  1799. if (datalen < 5)
  1800. return 0;
  1801. addrlen = 1 + data[4];
  1802. break;
  1803. default:
  1804. *reason = tor_strdup("invalid response to connect request");
  1805. return -1;
  1806. }
  1807. /* wait for address and port */
  1808. if (datalen < 6 + addrlen)
  1809. return 0;
  1810. if (data[1] != 0x00) {
  1811. *reason = tor_strdup(socks5_response_code_to_string(data[1]));
  1812. return -1;
  1813. }
  1814. *drain_out = 6 + addrlen;
  1815. return 1;
  1816. }
  1817. /* shouldn't get here... */
  1818. tor_assert(0);
  1819. return -1;
  1820. }
  1821. /** Return 1 iff buf looks more like it has an (obsolete) v0 controller
  1822. * command on it than any valid v1 controller command. */
  1823. int
  1824. peek_buf_has_control0_command(buf_t *buf)
  1825. {
  1826. if (buf->datalen >= 4) {
  1827. char header[4];
  1828. uint16_t cmd;
  1829. peek_from_buf(header, sizeof(header), buf);
  1830. cmd = ntohs(get_uint16(header+2));
  1831. if (cmd <= 0x14)
  1832. return 1; /* This is definitely not a v1 control command. */
  1833. }
  1834. return 0;
  1835. }
  1836. /** Return the index within <b>buf</b> at which <b>ch</b> first appears,
  1837. * or -1 if <b>ch</b> does not appear on buf. */
  1838. static off_t
  1839. buf_find_offset_of_char(buf_t *buf, char ch)
  1840. {
  1841. chunk_t *chunk;
  1842. off_t offset = 0;
  1843. for (chunk = buf->head; chunk; chunk = chunk->next) {
  1844. char *cp = memchr(chunk->data, ch, chunk->datalen);
  1845. if (cp)
  1846. return offset + (cp - chunk->data);
  1847. else
  1848. offset += chunk->datalen;
  1849. }
  1850. return -1;
  1851. }
  1852. /** Try to read a single LF-terminated line from <b>buf</b>, and write it
  1853. * (including the LF), NUL-terminated, into the *<b>data_len</b> byte buffer
  1854. * at <b>data_out</b>. Set *<b>data_len</b> to the number of bytes in the
  1855. * line, not counting the terminating NUL. Return 1 if we read a whole line,
  1856. * return 0 if we don't have a whole line yet, and return -1 if the line
  1857. * length exceeds *<b>data_len</b>.
  1858. */
  1859. int
  1860. fetch_from_buf_line(buf_t *buf, char *data_out, size_t *data_len)
  1861. {
  1862. size_t sz;
  1863. off_t offset;
  1864. if (!buf->head)
  1865. return 0;
  1866. offset = buf_find_offset_of_char(buf, '\n');
  1867. if (offset < 0)
  1868. return 0;
  1869. sz = (size_t) offset;
  1870. if (sz+2 > *data_len) {
  1871. *data_len = sz + 2;
  1872. return -1;
  1873. }
  1874. fetch_from_buf(data_out, sz+1, buf);
  1875. data_out[sz+1] = '\0';
  1876. *data_len = sz+1;
  1877. return 1;
  1878. }
  1879. /** Compress on uncompress the <b>data_len</b> bytes in <b>data</b> using the
  1880. * zlib state <b>state</b>, appending the result to <b>buf</b>. If
  1881. * <b>done</b> is true, flush the data in the state and finish the
  1882. * compression/uncompression. Return -1 on failure, 0 on success. */
  1883. int
  1884. write_to_buf_zlib(buf_t *buf, tor_zlib_state_t *state,
  1885. const char *data, size_t data_len,
  1886. int done)
  1887. {
  1888. char *next;
  1889. size_t old_avail, avail;
  1890. int over = 0;
  1891. do {
  1892. int need_new_chunk = 0;
  1893. if (!buf->tail || ! CHUNK_REMAINING_CAPACITY(buf->tail)) {
  1894. size_t cap = data_len / 4;
  1895. buf_add_chunk_with_capacity(buf, cap, 1);
  1896. }
  1897. next = CHUNK_WRITE_PTR(buf->tail);
  1898. avail = old_avail = CHUNK_REMAINING_CAPACITY(buf->tail);
  1899. switch (tor_zlib_process(state, &next, &avail, &data, &data_len, done)) {
  1900. case TOR_ZLIB_DONE:
  1901. over = 1;
  1902. break;
  1903. case TOR_ZLIB_ERR:
  1904. return -1;
  1905. case TOR_ZLIB_OK:
  1906. if (data_len == 0)
  1907. over = 1;
  1908. break;
  1909. case TOR_ZLIB_BUF_FULL:
  1910. if (avail) {
  1911. /* Zlib says we need more room (ZLIB_BUF_FULL). Start a new chunk
  1912. * automatically, whether were going to or not. */
  1913. need_new_chunk = 1;
  1914. }
  1915. break;
  1916. }
  1917. buf->datalen += old_avail - avail;
  1918. buf->tail->datalen += old_avail - avail;
  1919. if (need_new_chunk) {
  1920. buf_add_chunk_with_capacity(buf, data_len/4, 1);
  1921. }
  1922. } while (!over);
  1923. check();
  1924. return 0;
  1925. }
  1926. /** Set *<b>output</b> to contain a copy of the data in *<b>input</b> */
  1927. int
  1928. buf_set_to_copy(buf_t **output,
  1929. const buf_t *input)
  1930. {
  1931. if (*output)
  1932. buf_free(*output);
  1933. *output = buf_copy(input);
  1934. return 0;
  1935. }
  1936. /** Log an error and exit if <b>buf</b> is corrupted.
  1937. */
  1938. void
  1939. assert_buf_ok(buf_t *buf)
  1940. {
  1941. tor_assert(buf);
  1942. tor_assert(buf->magic == BUFFER_MAGIC);
  1943. if (! buf->head) {
  1944. tor_assert(!buf->tail);
  1945. tor_assert(buf->datalen == 0);
  1946. } else {
  1947. chunk_t *ch;
  1948. size_t total = 0;
  1949. tor_assert(buf->tail);
  1950. for (ch = buf->head; ch; ch = ch->next) {
  1951. total += ch->datalen;
  1952. tor_assert(ch->datalen <= ch->memlen);
  1953. tor_assert(ch->data >= &ch->mem[0]);
  1954. tor_assert(ch->data <= &ch->mem[0]+ch->memlen);
  1955. if (ch->data == &ch->mem[0]+ch->memlen) {
  1956. static int warned = 0;
  1957. if (! warned) {
  1958. log_warn(LD_BUG, "Invariant violation in buf.c related to #15083");
  1959. warned = 1;
  1960. }
  1961. }
  1962. tor_assert(ch->data+ch->datalen <= &ch->mem[0] + ch->memlen);
  1963. if (!ch->next)
  1964. tor_assert(ch == buf->tail);
  1965. }
  1966. tor_assert(buf->datalen == total);
  1967. }
  1968. }