nc.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/ByteBuffer.h>
  7. #include <AK/HashTable.h>
  8. #include <LibCore/ArgsParser.h>
  9. #include <LibCore/EventLoop.h>
  10. #include <LibCore/Stream.h>
  11. #include <LibCore/System.h>
  12. #include <LibMain/Main.h>
  13. #include <arpa/inet.h>
  14. #include <errno.h>
  15. #include <netdb.h>
  16. #include <netinet/in.h>
  17. #include <stdio.h>
  18. #include <string.h>
  19. #include <sys/select.h>
  20. #include <sys/socket.h>
  21. #include <sys/time.h>
  22. #include <sys/types.h>
  23. #include <unistd.h>
  24. // NOTE: `warnln` is used instead of `outln` because we want to redirect all
  25. // output to stderr to allow for commands like:
  26. //
  27. // nc -l someport > out.file
  28. //
  29. // Below man page was considered to come up default bounds
  30. // for SO_RCVBUF
  31. // https://man7.org/linux/man-pages/man7/socket.7.html
  32. static constexpr size_t maximum_tcp_receive_buffer_size_upper_bound = 212992;
  33. static constexpr size_t maximum_tcp_receive_buffer_size_lower_bound = 256;
  34. static size_t get_maximum_tcp_buffer_size(size_t input_buf_size)
  35. {
  36. if (input_buf_size < maximum_tcp_receive_buffer_size_lower_bound)
  37. return maximum_tcp_receive_buffer_size_lower_bound;
  38. if (input_buf_size > maximum_tcp_receive_buffer_size_upper_bound)
  39. return maximum_tcp_receive_buffer_size_upper_bound;
  40. return input_buf_size;
  41. };
  42. ErrorOr<int> serenity_main(Main::Arguments arguments)
  43. {
  44. bool should_listen = false;
  45. bool verbose = false;
  46. bool should_close = false;
  47. bool udp_mode = false;
  48. char const* target = nullptr;
  49. int port = 0;
  50. int maximum_tcp_receive_buffer_size_input = -1;
  51. Core::ArgsParser args_parser;
  52. args_parser.set_general_help("Network cat: Connect to network sockets as if it were a file.");
  53. args_parser.add_option(should_listen, "Listen instead of connecting", "listen", 'l');
  54. args_parser.add_option(verbose, "Log everything that's happening", "verbose", 'v');
  55. args_parser.add_option(udp_mode, "UDP mode", "udp", 'u');
  56. args_parser.add_option(should_close, "Close connection after reading stdin to the end", nullptr, 'N');
  57. args_parser.add_option(maximum_tcp_receive_buffer_size_input, "Set maximum tcp receive buffer size", "length", 'I', nullptr);
  58. args_parser.add_positional_argument(target, "Address to listen on, or the address or hostname to connect to", "target");
  59. args_parser.add_positional_argument(port, "Port to connect to or listen on", "port");
  60. args_parser.parse(arguments);
  61. if (udp_mode) {
  62. if (should_listen) {
  63. warnln("listening on UDP not yet supported");
  64. return 1;
  65. }
  66. Core::EventLoop loop;
  67. auto socket = TRY(Core::Stream::UDPSocket::connect(target, port));
  68. if (verbose)
  69. warnln("connected to {}:{}", target, port);
  70. Array<u8, 1024> buffer;
  71. for (;;) {
  72. Bytes buffer_span = buffer.span();
  73. auto nread = TRY(Core::System::read(STDIN_FILENO, buffer_span));
  74. buffer_span = buffer_span.trim(nread);
  75. TRY(socket->write({ buffer_span.data(), static_cast<size_t>(nread) }));
  76. }
  77. }
  78. int fd = -1;
  79. int listen_fd = -1;
  80. if (should_listen) {
  81. listen_fd = TRY(Core::System::socket(AF_INET, SOCK_STREAM, 0));
  82. sockaddr_in sa {};
  83. sa.sin_family = AF_INET;
  84. sa.sin_port = htons(port);
  85. sa.sin_addr.s_addr = htonl(INADDR_ANY);
  86. if (target) {
  87. if (inet_pton(AF_INET, target, &sa.sin_addr) <= 0) {
  88. perror("inet_pton");
  89. return 1;
  90. }
  91. }
  92. TRY(Core::System::bind(listen_fd, (struct sockaddr*)&sa, sizeof(sa)));
  93. TRY(Core::System::listen(listen_fd, 1));
  94. char addr_str[INET_ADDRSTRLEN];
  95. sockaddr_in sin;
  96. socklen_t len;
  97. len = sizeof(sin);
  98. TRY(Core::System::getsockname(listen_fd, (struct sockaddr*)&sin, &len));
  99. if (verbose)
  100. warnln("waiting for a connection on {}:{}", inet_ntop(sin.sin_family, &sin.sin_addr, addr_str, sizeof(addr_str) - 1), ntohs(sin.sin_port));
  101. } else {
  102. fd = TRY(Core::System::socket(AF_INET, SOCK_STREAM, 0));
  103. struct timeval timeout {
  104. 3, 0
  105. };
  106. TRY(Core::System::setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)));
  107. TRY(Core::System::setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout)));
  108. auto* hostent = gethostbyname(target);
  109. if (!hostent) {
  110. warnln("Socket::connect: Unable to resolve '{}'", target);
  111. return 1;
  112. }
  113. sockaddr_in dst_addr {};
  114. dst_addr.sin_family = AF_INET;
  115. dst_addr.sin_port = htons(port);
  116. dst_addr.sin_addr.s_addr = *(in_addr_t const*)hostent->h_addr_list[0];
  117. if (verbose) {
  118. char addr_str[INET_ADDRSTRLEN];
  119. warnln("connecting to {}:{}", inet_ntop(dst_addr.sin_family, &dst_addr.sin_addr, addr_str, sizeof(addr_str) - 1), ntohs(dst_addr.sin_port));
  120. }
  121. TRY(Core::System::connect(fd, (struct sockaddr*)&dst_addr, sizeof(dst_addr)));
  122. if (verbose)
  123. warnln("connected!");
  124. }
  125. HashTable<int> connected_clients;
  126. bool stdin_closed = false;
  127. bool fd_closed = false;
  128. bool listen_fd_closed = false;
  129. fd_set readfds, writefds, exceptfds;
  130. size_t receive_buffer_size = get_maximum_tcp_buffer_size(maximum_tcp_receive_buffer_size_input);
  131. if (verbose && (maximum_tcp_receive_buffer_size_input != -1)) {
  132. warnln("receive_buffer_size set to {}", receive_buffer_size);
  133. }
  134. while (!stdin_closed || !fd_closed || !listen_fd_closed) {
  135. FD_ZERO(&readfds);
  136. FD_ZERO(&writefds);
  137. FD_ZERO(&exceptfds);
  138. int highest_fd = 0;
  139. if (!stdin_closed) {
  140. FD_SET(STDIN_FILENO, &readfds);
  141. FD_SET(STDIN_FILENO, &exceptfds);
  142. highest_fd = max(highest_fd, STDIN_FILENO);
  143. }
  144. if (!fd_closed && fd) {
  145. FD_SET(fd, &readfds);
  146. FD_SET(fd, &exceptfds);
  147. highest_fd = max(highest_fd, fd);
  148. }
  149. if (!listen_fd_closed && listen_fd) {
  150. FD_SET(listen_fd, &readfds);
  151. FD_SET(listen_fd, &exceptfds);
  152. highest_fd = max(highest_fd, listen_fd);
  153. }
  154. bool has_clients = (should_listen && !connected_clients.is_empty());
  155. if (has_clients) {
  156. for (auto const& client_fd : connected_clients) {
  157. FD_SET(client_fd, &readfds);
  158. FD_SET(client_fd, &exceptfds);
  159. highest_fd = max(highest_fd, client_fd);
  160. }
  161. }
  162. int ready = select(highest_fd + 1, &readfds, &writefds, &exceptfds, nullptr);
  163. if (ready == -1) {
  164. if (errno == EINTR)
  165. continue;
  166. perror("select");
  167. return 1;
  168. }
  169. if (!stdin_closed && FD_ISSET(STDIN_FILENO, &readfds)) {
  170. Array<u8, 1024> buffer;
  171. Bytes buffer_span = buffer.span();
  172. auto nread = TRY(Core::System::read(STDIN_FILENO, buffer_span));
  173. buffer_span = buffer_span.trim(nread);
  174. // stdin closed
  175. if (nread == 0) {
  176. stdin_closed = true;
  177. if (verbose)
  178. warnln("stdin closed");
  179. if (should_close) {
  180. if (should_listen) {
  181. TRY(Core::System::close(listen_fd));
  182. listen_fd_closed = true;
  183. } else {
  184. TRY(Core::System::close(fd));
  185. fd_closed = true;
  186. }
  187. }
  188. } else {
  189. if (should_listen && has_clients) {
  190. for (auto const& client_fd : connected_clients)
  191. TRY(Core::System::write(client_fd, buffer_span));
  192. } else {
  193. TRY(Core::System::write(fd, buffer_span));
  194. }
  195. }
  196. }
  197. if (!fd_closed && FD_ISSET(fd, &readfds)) {
  198. auto buffer = TRY(ByteBuffer::create_uninitialized(receive_buffer_size));
  199. Bytes buffer_span = buffer.bytes();
  200. auto nread = TRY(Core::System::read(fd, buffer_span));
  201. buffer_span = buffer_span.trim(nread);
  202. // remote end closed
  203. if (nread == 0) {
  204. close(STDIN_FILENO);
  205. stdin_closed = true;
  206. fd_closed = true;
  207. if (verbose)
  208. warnln("remote closed");
  209. } else {
  210. TRY(Core::System::write(STDOUT_FILENO, buffer_span));
  211. }
  212. }
  213. if (!listen_fd_closed && FD_ISSET(listen_fd, &readfds)) {
  214. char client_str[INET_ADDRSTRLEN];
  215. sockaddr_in client;
  216. socklen_t clientlen = sizeof(client);
  217. int new_client = TRY(Core::System::accept(listen_fd, (struct sockaddr*)&client, &clientlen));
  218. connected_clients.set(new_client);
  219. if (verbose)
  220. warnln("got connection from {}:{}", inet_ntop(client.sin_family, &client.sin_addr, client_str, sizeof(client_str) - 1), ntohs(client.sin_port));
  221. }
  222. if (has_clients) {
  223. for (auto const client_fd : connected_clients) {
  224. if (FD_ISSET(client_fd, &readfds)) {
  225. Array<u8, 1024> buffer;
  226. Bytes buffer_span = buffer.span();
  227. auto nread = TRY(Core::System::read(client_fd, buffer_span));
  228. buffer_span = buffer_span.trim(nread);
  229. if (nread == 0) {
  230. if (verbose) {
  231. struct sockaddr_in client;
  232. socklen_t clientlen = sizeof(client);
  233. TRY(Core::System::getpeername(client_fd, (struct sockaddr*)&client, &clientlen));
  234. warnln("remote connection closed {}:{}", inet_ntoa(client.sin_addr), ntohs(client.sin_port));
  235. }
  236. connected_clients.remove(client_fd);
  237. close(client_fd);
  238. FD_CLR(client_fd, &readfds);
  239. FD_CLR(client_fd, &exceptfds);
  240. } else {
  241. TRY(Core::System::write(STDOUT_FILENO, buffer_span));
  242. }
  243. }
  244. }
  245. }
  246. }
  247. return 0;
  248. }