buffers.c 62 KB

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