SocksUdpClient.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. /*
  2. * Copyright (C) 2018 Jigsaw Operations LLC
  3. * Copyright (C) 2019 Ambroz Bizjak (modifications)
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * 1. Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * 2. Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * 3. Neither the name of the author nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  17. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. #include <stddef.h>
  28. #include <stdint.h>
  29. #include <stdlib.h>
  30. #include <string.h>
  31. #include <misc/balloc.h>
  32. #include <misc/offset.h>
  33. #include <misc/byteorder.h>
  34. #include <misc/compare.h>
  35. #include <misc/socks_proto.h>
  36. #include <misc/debug.h>
  37. #include <misc/bsize.h>
  38. #include <base/BLog.h>
  39. #include <system/BAddr.h>
  40. #include <socks_udp_client/SocksUdpClient.h>
  41. #include <generated/blog_channel_SocksUdpClient.h>
  42. static const int DnsPort = 53;
  43. static int addr_comparator (void *unused, BAddr *v1, BAddr *v2);
  44. static struct SocksUdpClient_connection * find_connection (SocksUdpClient *o, BAddr addr);
  45. static void socks_state_handler (struct SocksUdpClient_connection *con, int event);
  46. static void datagram_state_handler (struct SocksUdpClient_connection *con, int event);
  47. static void send_monitor_handler (struct SocksUdpClient_connection *con);
  48. static void recv_if_handler_send (
  49. struct SocksUdpClient_connection *con, uint8_t *data, int data_len);
  50. static struct SocksUdpClient_connection * connection_init (
  51. SocksUdpClient *o, BAddr local_addr, BAddr first_remote_addr,
  52. const uint8_t *first_data, int first_data_len);
  53. static void connection_free (struct SocksUdpClient_connection *con);
  54. static void connection_send (struct SocksUdpClient_connection *con,
  55. BAddr remote_addr, const uint8_t *data, int data_len);
  56. static void first_job_handler (struct SocksUdpClient_connection *con);
  57. static int compute_socks_mtu (int udp_mtu);
  58. static int get_dns_id (BAddr *remote_addr, const uint8_t *data, int data_len);
  59. int addr_comparator (void *unused, BAddr *v1, BAddr *v2)
  60. {
  61. return BAddr_CompareOrder(v1, v2);
  62. }
  63. struct SocksUdpClient_connection * find_connection (SocksUdpClient *o, BAddr addr)
  64. {
  65. BAVLNode *tree_node = BAVL_LookupExact(&o->connections_tree, &addr);
  66. if (!tree_node) {
  67. return NULL;
  68. }
  69. return UPPER_OBJECT(tree_node, struct SocksUdpClient_connection, connections_tree_node);
  70. }
  71. void socks_state_handler (struct SocksUdpClient_connection *con, int event)
  72. {
  73. DebugObject_Access(&con->client->d_obj);
  74. switch (event) {
  75. case BSOCKSCLIENT_EVENT_CONNECTED: {
  76. // Get the local address of the SOCKS TCP connection.
  77. BAddr tcp_local_addr;
  78. if (!BSocksClient_GetLocalAddr(&con->socks, &tcp_local_addr)) {
  79. BLog(BLOG_ERROR, "Failed to get TCP local address.");
  80. return connection_free(con);
  81. }
  82. // Sanity check the address type (required by SetPort below).
  83. if (tcp_local_addr.type != BADDR_TYPE_IPV4 &&
  84. tcp_local_addr.type != BADDR_TYPE_IPV6)
  85. {
  86. BLog(BLOG_ERROR, "Bad address type in TCP local address.");
  87. return connection_free(con);
  88. }
  89. // Bind the UDP socket to the same IP address and let the kernel pick the port.
  90. BAddr udp_bound_addr = tcp_local_addr;
  91. BAddr_SetPort(&udp_bound_addr, 0);
  92. if (!BDatagram_Bind(&con->socket, udp_bound_addr)) {
  93. BLog(BLOG_ERROR, "Failed to bind the UDP socket.");
  94. return connection_free(con);
  95. }
  96. // Update udp_bound_addr to the actual address that was bound.
  97. if (!BDatagram_GetLocalAddr(&con->socket, &udp_bound_addr)) {
  98. BLog(BLOG_ERROR, "Failed to get UDP bound address.");
  99. return connection_free(con);
  100. }
  101. // Set the DST.ADDR for SOCKS.
  102. BSocksClient_SetDestAddr(&con->socks, udp_bound_addr);
  103. } break;
  104. case BSOCKSCLIENT_EVENT_UP: {
  105. // The remote address to send datagrams to is the BND.ADDR provided by the
  106. // SOCKS server.
  107. BAddr remote_addr = BSocksClient_GetBindAddr(&con->socks);
  108. // Don't bother setting a source address for datagrams since we are bound.
  109. BIPAddr local_addr;
  110. BIPAddr_InitInvalid(&local_addr);
  111. // Set the addresses for BDatagram.
  112. // This will unblock the queue of outgoing packets.
  113. BDatagram_SetSendAddrs(&con->socket, remote_addr, local_addr);
  114. } break;
  115. case BSOCKSCLIENT_EVENT_ERROR: {
  116. char local_buffer[BADDR_MAX_PRINT_LEN];
  117. BAddr_Print(&con->local_addr, local_buffer);
  118. BLog(BLOG_ERROR,
  119. "SOCKS error event for %s, removing connection.", local_buffer);
  120. connection_free(con);
  121. } break;
  122. case BSOCKSCLIENT_EVENT_ERROR_CLOSED: {
  123. char local_buffer[BADDR_MAX_PRINT_LEN];
  124. BAddr_Print(&con->local_addr, local_buffer);
  125. BLog(BLOG_WARNING,
  126. "SOCKS closed event for %s, removing connection.", local_buffer);
  127. connection_free(con);
  128. } break;
  129. }
  130. }
  131. void datagram_state_handler (struct SocksUdpClient_connection *con, int event)
  132. {
  133. DebugObject_Access(&con->client->d_obj);
  134. if (event == BDATAGRAM_EVENT_ERROR) {
  135. char local_buffer[BADDR_MAX_PRINT_LEN];
  136. BAddr_Print(&con->local_addr, local_buffer);
  137. BLog(BLOG_ERROR,
  138. "Low-level datagram error %s, removing connection.", local_buffer);
  139. // Remove the connection. Note that BDatagram requires that we free
  140. // the BDatagram after an error is reported.
  141. connection_free(con);
  142. }
  143. }
  144. void send_monitor_handler (struct SocksUdpClient_connection *con)
  145. {
  146. DebugObject_Access(&con->client->d_obj);
  147. char local_buffer[BADDR_MAX_PRINT_LEN];
  148. BAddr_Print(&con->local_addr, local_buffer);
  149. BLog(BLOG_INFO,
  150. "Removing connection for %s due to inactivity.", local_buffer);
  151. // The connection has passed its idle timeout. Remove it.
  152. connection_free(con);
  153. }
  154. void recv_if_handler_send (
  155. struct SocksUdpClient_connection *con, uint8_t *data, int data_len)
  156. {
  157. DebugObject_Access(&con->client->d_obj);
  158. SocksUdpClient *o = con->client;
  159. ASSERT(data_len >= 0)
  160. ASSERT(data_len <= o->socks_mtu)
  161. // accept packet
  162. PacketPassInterface_Done(&con->recv_if);
  163. // check header
  164. struct socks_udp_header header;
  165. if (data_len < sizeof(header)) {
  166. BLog(BLOG_ERROR, "Missing SOCKS-UDP header.");
  167. return;
  168. }
  169. memcpy(&header, data, sizeof(header));
  170. data += sizeof(header);
  171. data_len -= sizeof(header);
  172. // parse address
  173. BAddr remote_addr;
  174. switch (header.atyp) {
  175. case SOCKS_ATYP_IPV4: {
  176. struct socks_addr_ipv4 addr_ipv4;
  177. if (data_len < sizeof(addr_ipv4)) {
  178. BLog(BLOG_ERROR, "Missing IPv4 address.");
  179. return;
  180. }
  181. memcpy(&addr_ipv4, data, sizeof(addr_ipv4));
  182. data += sizeof(addr_ipv4);
  183. data_len -= sizeof(addr_ipv4);
  184. remote_addr.type = BADDR_TYPE_IPV4;
  185. remote_addr.ipv4.ip = addr_ipv4.addr;
  186. remote_addr.ipv4.port = addr_ipv4.port;
  187. } break;
  188. case SOCKS_ATYP_IPV6: {
  189. struct socks_addr_ipv6 addr_ipv6;
  190. if (data_len < sizeof(addr_ipv6)) {
  191. BLog(BLOG_ERROR, "Missing IPv6 address.");
  192. return;
  193. }
  194. memcpy(&addr_ipv6, data, sizeof(addr_ipv6));
  195. data += sizeof(addr_ipv6);
  196. data_len -= sizeof(addr_ipv6);
  197. remote_addr.type = BADDR_TYPE_IPV6;
  198. memcpy(remote_addr.ipv6.ip, addr_ipv6.addr, sizeof(remote_addr.ipv6.ip));
  199. remote_addr.ipv6.port = addr_ipv6.port;
  200. } break;
  201. default: {
  202. BLog(BLOG_ERROR, "Bad address type");
  203. return;
  204. } break;
  205. }
  206. // check remaining data
  207. if (data_len > o->udp_mtu) {
  208. BLog(BLOG_ERROR, "too much data");
  209. return;
  210. }
  211. // pass packet to user
  212. SocksUdpClient *client = con->client;
  213. client->handler_received(client->user, con->local_addr, remote_addr, data, data_len);
  214. // Was this connection used for a DNS query?
  215. if (con->dns_id >= 0) {
  216. // Get the DNS transaction ID of the response.
  217. int recv_dns_id = get_dns_id(&remote_addr, data, data_len);
  218. // Does the transaction ID matche that of the request?
  219. if (recv_dns_id == con->dns_id) {
  220. // We have now forwarded the response, so this connection is no longer needed.
  221. char local_buffer[BADDR_MAX_PRINT_LEN];
  222. BAddr_Print(&con->local_addr, local_buffer);
  223. BLog(BLOG_DEBUG,
  224. "Removing connection for %s after the DNS response.", local_buffer);
  225. connection_free(con);
  226. } else {
  227. BLog(BLOG_INFO, "DNS client port received an unexpected non-DNS packet, "
  228. "disabling DNS optimization.");
  229. con->dns_id = -1;
  230. }
  231. }
  232. }
  233. struct SocksUdpClient_connection * connection_init (
  234. SocksUdpClient *o, BAddr local_addr, BAddr first_remote_addr,
  235. const uint8_t *first_data, int first_data_len)
  236. {
  237. ASSERT(o->num_connections <= o->max_connections)
  238. ASSERT(!find_connection(o, local_addr))
  239. char local_buffer[BADDR_MAX_PRINT_LEN];
  240. BAddr_Print(&local_addr, local_buffer);
  241. BLog(BLOG_DEBUG, "Creating connection for %s.", local_buffer);
  242. // allocate structure
  243. struct SocksUdpClient_connection *con =
  244. (struct SocksUdpClient_connection *)BAlloc(sizeof(*con));
  245. if (!con) {
  246. BLog(BLOG_ERROR, "BAlloc connection failed");
  247. goto fail0;
  248. }
  249. // set basic things
  250. con->client = o;
  251. con->local_addr = local_addr;
  252. // store first outgoing packet
  253. con->first_data = BAlloc(first_data_len);
  254. if (!con->first_data) {
  255. BLog(BLOG_ERROR, "BAlloc first data failed");
  256. goto fail1;
  257. }
  258. memcpy(con->first_data, first_data, first_data_len);
  259. con->first_data_len = first_data_len;
  260. con->first_remote_addr = first_remote_addr;
  261. // Get the DNS transaction ID from the packet, if any.
  262. con->dns_id = get_dns_id(&first_remote_addr, first_data, first_data_len);
  263. BPendingGroup *pg = BReactor_PendingGroup(o->reactor);
  264. // Init first job, to send the first packet asynchronously. This has to happen
  265. // asynchronously because con->send_writer (a BufferWriter) cannot accept writes until
  266. // after it is linked with its PacketBuffer (con->send_buffer), which happens
  267. // asynchronously.
  268. BPending_Init(&con->first_job, pg, (BPending_handler)first_job_handler, con);
  269. // Add the first job to the pending set. BPending acts as a LIFO stack, and
  270. // first_job_handler needs to run after async actions that occur in PacketBuffer_Init,
  271. // so we need to put first_job on the stack first.
  272. BPending_Set(&con->first_job);
  273. // Create a datagram socket
  274. if (!BDatagram_Init(&con->socket, con->local_addr.type, o->reactor, con,
  275. (BDatagram_handler)datagram_state_handler))
  276. {
  277. BLog(BLOG_ERROR, "Failed to create a UDP socket");
  278. goto fail2;
  279. }
  280. // We will set the DST.ADDR for SOCKS later (BSOCKSCLIENT_EVENT_CONNECTED).
  281. BAddr dummy_dst_addr;
  282. BAddr_InitNone(&dummy_dst_addr);
  283. // Initiate connection to socks server
  284. if (!BSocksClient_Init(&con->socks, o->server_addr, o->auth_info, o->num_auth_info,
  285. dummy_dst_addr, true, (BSocksClient_handler)socks_state_handler, con, o->reactor))
  286. {
  287. BLog(BLOG_ERROR, "Failed to initialize SOCKS client");
  288. goto fail3;
  289. }
  290. // Since we use o->socks_mtu for send and receive pipelines, we can handle maximally
  291. // sized packets (o->udp_mtu) including the SOCKS-UDP header.
  292. // Send pipeline: send_writer -> send_buffer -> send_monitor -> send_if -> socket.
  293. BDatagram_SendAsync_Init(&con->socket, o->socks_mtu);
  294. PacketPassInactivityMonitor_Init(&con->send_monitor,
  295. BDatagram_SendAsync_GetIf(&con->socket), o->reactor, o->keepalive_time,
  296. (PacketPassInactivityMonitor_handler)send_monitor_handler, con);
  297. BufferWriter_Init(&con->send_writer, o->socks_mtu, pg);
  298. if (!PacketBuffer_Init(&con->send_buffer, BufferWriter_GetOutput(&con->send_writer),
  299. PacketPassInactivityMonitor_GetInput(&con->send_monitor), o->send_buf_size, pg))
  300. {
  301. BLog(BLOG_ERROR, "Send buffer init failed");
  302. goto fail4;
  303. }
  304. // Receive pipeline: socket -> recv_buffer -> recv_if
  305. BDatagram_RecvAsync_Init(&con->socket, o->socks_mtu);
  306. PacketPassInterface_Init(&con->recv_if, o->socks_mtu,
  307. (PacketPassInterface_handler_send)recv_if_handler_send, con, pg);
  308. if (!SinglePacketBuffer_Init(&con->recv_buffer,
  309. BDatagram_RecvAsync_GetIf(&con->socket), &con->recv_if, pg))
  310. {
  311. BLog(BLOG_ERROR, "Receive buffer init failed");
  312. goto fail5;
  313. }
  314. // Insert to connections tree, it must succeed because of the assert.
  315. int inserted = BAVL_Insert(&o->connections_tree, &con->connections_tree_node, NULL);
  316. ASSERT(inserted)
  317. B_USE(inserted)
  318. // increment number of connections
  319. o->num_connections++;
  320. return con;
  321. fail5:
  322. PacketPassInterface_Free(&con->recv_if);
  323. BDatagram_RecvAsync_Free(&con->socket);
  324. PacketBuffer_Free(&con->send_buffer);
  325. fail4:
  326. BufferWriter_Free(&con->send_writer);
  327. PacketPassInactivityMonitor_Free(&con->send_monitor);
  328. BDatagram_SendAsync_Free(&con->socket);
  329. BSocksClient_Free(&con->socks);
  330. fail3:
  331. BDatagram_Free(&con->socket);
  332. fail2:
  333. BPending_Free(&con->first_job);
  334. BFree(con->first_data);
  335. fail1:
  336. BFree(con);
  337. fail0:
  338. return NULL;
  339. }
  340. void connection_free (struct SocksUdpClient_connection *con)
  341. {
  342. SocksUdpClient *o = con->client;
  343. // decrement number of connections
  344. ASSERT(o->num_connections > 0)
  345. o->num_connections--;
  346. // remove from connections tree
  347. BAVL_Remove(&o->connections_tree, &con->connections_tree_node);
  348. // Free UDP receive pipeline components
  349. SinglePacketBuffer_Free(&con->recv_buffer);
  350. PacketPassInterface_Free(&con->recv_if);
  351. BDatagram_RecvAsync_Free(&con->socket);
  352. // Free UDP send pipeline components
  353. PacketBuffer_Free(&con->send_buffer);
  354. BufferWriter_Free(&con->send_writer);
  355. PacketPassInactivityMonitor_Free(&con->send_monitor);
  356. BDatagram_SendAsync_Free(&con->socket);
  357. // Free SOCKS client
  358. BSocksClient_Free(&con->socks);
  359. // Free UDP socket
  360. BDatagram_Free(&con->socket);
  361. // Free first job
  362. BPending_Free(&con->first_job);
  363. // Free first outgoing packet
  364. BFree(con->first_data);
  365. // Free structure
  366. BFree(con);
  367. }
  368. void connection_send (struct SocksUdpClient_connection *con,
  369. BAddr remote_addr, const uint8_t *data, int data_len)
  370. {
  371. ASSERT(data_len >= 0)
  372. ASSERT(data_len <= con->client->udp_mtu)
  373. if (con->dns_id >= 0) {
  374. // So far, this connection has only sent a single DNS query.
  375. int new_dns_id = get_dns_id(&remote_addr, data, data_len);
  376. if (new_dns_id != con->dns_id) {
  377. BLog(BLOG_DEBUG, "Client reused DNS query port. Disabling DNS optimization.");
  378. con->dns_id = -1;
  379. }
  380. }
  381. // Check if we're sending to an IPv4 or IPv6 destination.
  382. int atyp;
  383. size_t address_size;
  384. // write address
  385. switch (remote_addr.type) {
  386. case BADDR_TYPE_IPV4: {
  387. atyp = SOCKS_ATYP_IPV4;
  388. address_size = sizeof(struct socks_addr_ipv4);
  389. } break;
  390. case BADDR_TYPE_IPV6: {
  391. atyp = SOCKS_ATYP_IPV6;
  392. address_size = sizeof(struct socks_addr_ipv6);
  393. } break;
  394. default: {
  395. BLog(BLOG_ERROR, "Bad address type in outgoing packet.");
  396. return;
  397. } break;
  398. }
  399. // Determine total packet size in the buffer.
  400. // This cannot exceed o->socks_mtu because data_len is required to not exceed
  401. // o->udp_mtu and o->socks_mtu is calculated to accomodate any UDP packet not
  402. // not exceeding o->udp_mtu.
  403. size_t total_len = sizeof(struct socks_udp_header) + address_size + data_len;
  404. ASSERT(total_len <= con->client->socks_mtu)
  405. // Get a pointer to write the packet to.
  406. uint8_t *out_data_begin;
  407. if (!BufferWriter_StartPacket(&con->send_writer, &out_data_begin)) {
  408. BLog(BLOG_ERROR, "Send buffer is full.");
  409. return;
  410. }
  411. uint8_t *out_data = out_data_begin;
  412. // Write header
  413. struct socks_udp_header header;
  414. header.rsv = 0;
  415. header.frag = 0;
  416. header.atyp = atyp;
  417. memcpy(out_data, &header, sizeof(header));
  418. out_data += sizeof(header);
  419. // Write address
  420. switch (atyp) {
  421. case SOCKS_ATYP_IPV4: {
  422. struct socks_addr_ipv4 addr_ipv4;
  423. addr_ipv4.addr = remote_addr.ipv4.ip;
  424. addr_ipv4.port = remote_addr.ipv4.port;
  425. memcpy(out_data, &addr_ipv4, sizeof(addr_ipv4));
  426. out_data += sizeof(addr_ipv4);
  427. } break;
  428. case SOCKS_ATYP_IPV6: {
  429. struct socks_addr_ipv6 addr_ipv6;
  430. memcpy(addr_ipv6.addr, remote_addr.ipv6.ip, sizeof(addr_ipv6.addr));
  431. addr_ipv6.port = remote_addr.ipv6.port;
  432. memcpy(out_data, &addr_ipv6, sizeof(addr_ipv6));
  433. out_data += sizeof(addr_ipv6);
  434. } break;
  435. }
  436. // Write payload
  437. memcpy(out_data, data, data_len);
  438. out_data += data_len;
  439. ASSERT(out_data - out_data_begin == total_len)
  440. // Submit packet to buffer
  441. BufferWriter_EndPacket(&con->send_writer, total_len);
  442. }
  443. void first_job_handler (struct SocksUdpClient_connection *con)
  444. {
  445. DebugObject_Access(&con->client->d_obj);
  446. ASSERT(con->first_data)
  447. // Send the first packet.
  448. connection_send(con, con->first_remote_addr, con->first_data, con->first_data_len);
  449. // Release the first packet buffer.
  450. BFree(con->first_data);
  451. con->first_data = NULL;
  452. con->first_data_len = 0;
  453. }
  454. int compute_socks_mtu (int udp_mtu)
  455. {
  456. bsize_t bs = bsize_add(
  457. bsize_fromint(udp_mtu),
  458. bsize_add(
  459. bsize_fromsize(sizeof(struct socks_udp_header)),
  460. bsize_fromsize(sizeof(struct socks_addr_ipv6))
  461. )
  462. );
  463. int s;
  464. return bsize_toint(bs, &s) ? s : -1;
  465. }
  466. // Get the DNS transaction ID, or -1 if this does not look like a DNS packet.
  467. int get_dns_id (BAddr *remote_addr, const uint8_t *data, int data_len)
  468. {
  469. if (ntoh16(BAddr_GetPort(remote_addr)) == DnsPort && data_len >= 2) {
  470. return (data[0] << 8) | data[1];
  471. } else {
  472. return -1;
  473. }
  474. }
  475. int SocksUdpClient_Init (SocksUdpClient *o, int udp_mtu, int max_connections,
  476. int send_buf_size, btime_t keepalive_time, BAddr server_addr,
  477. const struct BSocksClient_auth_info *auth_info, size_t num_auth_info,
  478. BReactor *reactor, void *user, SocksUdpClient_handler_received handler_received)
  479. {
  480. ASSERT(udp_mtu >= 0)
  481. ASSERT(max_connections > 0)
  482. ASSERT(send_buf_size > 0)
  483. // init simple things
  484. o->server_addr = server_addr;
  485. o->auth_info = auth_info;
  486. o->num_auth_info = num_auth_info;
  487. o->num_connections = 0;
  488. o->max_connections = max_connections;
  489. o->send_buf_size = send_buf_size;
  490. o->udp_mtu = udp_mtu;
  491. o->keepalive_time = keepalive_time;
  492. o->reactor = reactor;
  493. o->user = user;
  494. o->handler_received = handler_received;
  495. // calculate full MTU with SOCKS header
  496. o->socks_mtu = compute_socks_mtu(udp_mtu);
  497. if (o->socks_mtu < 0) {
  498. BLog(BLOG_ERROR, "SocksUdpClient_Init: MTU too large.");
  499. goto fail0;
  500. }
  501. // init connections tree
  502. BAVL_Init(&o->connections_tree,
  503. OFFSET_DIFF(struct SocksUdpClient_connection, local_addr, connections_tree_node),
  504. (BAVL_comparator)addr_comparator, NULL);
  505. DebugObject_Init(&o->d_obj);
  506. return 1;
  507. fail0:
  508. return 0;
  509. }
  510. void SocksUdpClient_Free (SocksUdpClient *o)
  511. {
  512. DebugObject_Free(&o->d_obj);
  513. // free connections
  514. while (!BAVL_IsEmpty(&o->connections_tree)) {
  515. BAVLNode *node = BAVL_GetFirst(&o->connections_tree);
  516. struct SocksUdpClient_connection *con =
  517. UPPER_OBJECT(node, struct SocksUdpClient_connection, connections_tree_node);
  518. connection_free(con);
  519. }
  520. }
  521. void SocksUdpClient_SubmitPacket (SocksUdpClient *o,
  522. BAddr local_addr, BAddr remote_addr, const uint8_t *data, int data_len)
  523. {
  524. DebugObject_Access(&o->d_obj);
  525. ASSERT(local_addr.type == BADDR_TYPE_IPV4 || local_addr.type == BADDR_TYPE_IPV6)
  526. ASSERT(remote_addr.type == BADDR_TYPE_IPV4 || remote_addr.type == BADDR_TYPE_IPV6)
  527. ASSERT(data_len >= 0)
  528. ASSERT(data_len <= o->udp_mtu)
  529. // lookup connection
  530. struct SocksUdpClient_connection *con = find_connection(o, local_addr);
  531. if (!con) {
  532. if (o->num_connections >= o->max_connections) {
  533. // Drop the packet.
  534. BLog(BLOG_WARNING, "Dropping UDP packet, reached max number of connections.");
  535. return;
  536. }
  537. // create new connection and enqueue the packet
  538. connection_init(o, local_addr, remote_addr, data, data_len);
  539. } else {
  540. // send packet
  541. connection_send(con, remote_addr, data, data_len);
  542. }
  543. }