blob: a6bdff44401260386af0ea7cf85c53181457de0a [file] [log] [blame]
James Kuszmaulcf324122023-01-14 14:07:17 -08001// Copyright (c) FIRST and other WPILib contributors.
2// Open Source Software; you can modify and/or share it under the terms of
3// the WPILib BSD license file in the root directory of this project.
4
5#include <cstdio>
6
7#include <fmt/format.h>
8#include <wpi/MathExtras.h>
9#include <wpi/SmallVector.h>
10#include <wpi/StringExtras.h>
11#include <wpi/timestamp.h>
12
13#include "wpinet/raw_uv_ostream.h"
14#include "wpinet/uv/Loop.h"
15#include "wpinet/uv/Tcp.h"
16#include "wpinet/uv/Tty.h"
17#include "wpinet/uv/Udp.h"
18#include "wpinet/uv/util.h"
19
20namespace uv = wpi::uv;
21
22static uint64_t startTime = wpi::Now();
23
24static bool NewlineBuffer(std::string& rem, uv::Buffer& buf, size_t len,
25 wpi::SmallVectorImpl<uv::Buffer>& bufs, bool tcp,
26 uint16_t tcpSeq) {
27 // scan for last newline
28 std::string_view str(buf.base, len);
29 size_t idx = str.rfind('\n');
30 if (idx == std::string_view::npos) {
31 // no newline yet, just keep appending to remainder
32 rem += str;
33 return false;
34 }
35
36 // build output
37 wpi::raw_uv_ostream out(bufs, 4096);
38 std::string_view toCopy = wpi::slice(str, 0, idx + 1);
39 if (tcp) {
40 // Header is 2 byte len, 1 byte type, 4 byte timestamp, 2 byte sequence num
41 uint32_t ts = wpi::FloatToBits((wpi::Now() - startTime) * 1.0e-6);
42 uint16_t len = rem.size() + toCopy.size() + 1 + 4 + 2;
43 const uint8_t header[] = {static_cast<uint8_t>((len >> 8) & 0xff),
44 static_cast<uint8_t>(len & 0xff),
45 12,
46 static_cast<uint8_t>((ts >> 24) & 0xff),
47 static_cast<uint8_t>((ts >> 16) & 0xff),
48 static_cast<uint8_t>((ts >> 8) & 0xff),
49 static_cast<uint8_t>(ts & 0xff),
50 static_cast<uint8_t>((tcpSeq >> 8) & 0xff),
51 static_cast<uint8_t>(tcpSeq & 0xff)};
52 out << std::span<const uint8_t>(header);
53 }
54 out << rem << toCopy;
55
56 // reset remainder
57 rem = wpi::slice(str, idx + 1, std::string_view::npos);
58 return true;
59}
60
61static void CopyUdp(uv::Stream& in, std::shared_ptr<uv::Udp> out, int port,
62 bool broadcast) {
63 sockaddr_in addr;
64 if (broadcast) {
65 out->SetBroadcast(true);
66 uv::NameToAddr("0.0.0.0", port, &addr);
67 } else {
68 uv::NameToAddr("127.0.0.1", port, &addr);
69 }
70
71 in.data.connect(
72 [rem = std::make_shared<std::string>(), outPtr = out.get(), addr](
73 uv::Buffer& buf, size_t len) {
74 // build buffers
75 wpi::SmallVector<uv::Buffer, 4> bufs;
76 if (!NewlineBuffer(*rem, buf, len, bufs, false, 0)) {
77 return;
78 }
79
80 // send output
81 outPtr->Send(addr, bufs, [](auto bufs2, uv::Error) {
82 for (auto buf : bufs2) {
83 buf.Deallocate();
84 }
85 });
86 },
87 out);
88}
89
90static void CopyTcp(uv::Stream& in, std::shared_ptr<uv::Stream> out) {
91 struct StreamData {
92 std::string rem;
93 uint16_t seq = 0;
94 };
95 in.data.connect(
96 [data = std::make_shared<StreamData>(), outPtr = out.get()](
97 uv::Buffer& buf, size_t len) {
98 // build buffers
99 wpi::SmallVector<uv::Buffer, 4> bufs;
100 if (!NewlineBuffer(data->rem, buf, len, bufs, true, data->seq++)) {
101 return;
102 }
103
104 // send output
105 outPtr->Write(bufs, [](auto bufs2, uv::Error) {
106 for (auto buf : bufs2) {
107 buf.Deallocate();
108 }
109 });
110 },
111 out);
112}
113
114static void CopyStream(uv::Stream& in, std::shared_ptr<uv::Stream> out) {
115 in.data.connect([out](uv::Buffer& buf, size_t len) {
116 uv::Buffer buf2 = buf.Dup();
117 buf2.len = len;
118 out->Write({buf2}, [](auto bufs, uv::Error) {
119 for (auto buf : bufs) {
120 buf.Deallocate();
121 }
122 });
123 });
124}
125
126int main(int argc, char* argv[]) {
127 // parse arguments
128 int arg = 1;
129 bool useUdp = false;
130 bool broadcastUdp = false;
131 bool err = false;
132 int port = -1;
133
134 while (arg < argc && argv[arg][0] == '-') {
135 if (std::string_view(argv[arg]) == "-u") {
136 useUdp = true;
137 } else if (std::string_view(argv[arg]) == "-b") {
138 useUdp = true;
139 broadcastUdp = true;
140 } else if (std::string_view(argv[arg]) == "-p") {
141 ++arg;
142 std::optional<int> portValue;
143 if (arg >= argc || argv[arg][0] == '-' ||
144 !(portValue = wpi::parse_integer<int>(argv[arg], 10))) {
145 std::fputs("-p must be followed by port number\n", stderr);
146 err = true;
147 } else if (portValue) {
148 port = portValue.value();
149 }
150 } else {
151 fmt::print(stderr, "unrecognized command line option {}\n", argv[arg]);
152 err = true;
153 }
154 ++arg;
155 }
156
157 if (err) {
158 std::fputs(argv[0], stderr);
159 std::fputs(
160 " [-ub] [-p PORT]\n"
161 " -u send udp to localhost port 6666 instead of using tcp\n"
162 " -b broadcast udp to port 6666 instead of using tcp\n"
163 " -p PORT use port PORT instead of 6666 (udp) or 1740 (tcp)\n",
164 stderr);
165 return EXIT_FAILURE;
166 }
167
168 auto loop = uv::Loop::Create();
169 loop->error.connect(
170 [](uv::Error err) { fmt::print(stderr, "uv ERROR: {}\n", err.str()); });
171
172 // create ttys
173 auto stdinTty = uv::Tty::Create(loop, 0, true);
174 auto stdoutTty = uv::Tty::Create(loop, 1, false);
175
176 // don't bother continuing if we don't have a stdin
177 if (!stdinTty) {
178 return EXIT_SUCCESS;
179 }
180
181 // pass through our input to output
182 if (stdoutTty) {
183 CopyStream(*stdinTty, stdoutTty);
184 }
185
186 // when our stdin closes, exit
187 stdinTty->end.connect([] { std::exit(EXIT_SUCCESS); });
188
189 if (useUdp) {
190 auto udp = uv::Udp::Create(loop);
191 // tee
192 CopyUdp(*stdinTty, udp, port < 0 ? 6666 : port, broadcastUdp);
193 } else {
194 auto tcp = uv::Tcp::Create(loop);
195
196 // bind to listen address and port
197 tcp->Bind("", port < 0 ? 1740 : port);
198
199 // when we get a connection, accept it
200 tcp->connection.connect([srv = tcp.get(), stdinTty] {
201 auto tcp = srv->Accept();
202 if (!tcp) {
203 return;
204 }
205
206 // close on error
207 tcp->error.connect([s = tcp.get()](wpi::uv::Error err) { s->Close(); });
208
209 // tee
210 CopyTcp(*stdinTty, tcp);
211 });
212
213 // start listening for incoming connections
214 tcp->Listen();
215 }
216
217 // start reading
218 if (stdinTty) {
219 stdinTty->StartRead();
220 }
221
222 // run the loop!
223 loop->Run();
224}