buffers.c 62 KB

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