buffers.c 67 KB

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