buffers.c 62 KB

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