blob: ed45eebe255964c333160d2119381114ce5a0d8f [file] [log] [blame]
Brian Silverman41cdd3e2019-01-19 19:48:58 -08001/*----------------------------------------------------------------------------*/
James Kuszmaul4f3ad3c2019-12-01 16:35:21 -08002/* Copyright (c) 2018-2019 FIRST. All Rights Reserved. */
Brian Silverman41cdd3e2019-01-19 19:48:58 -08003/* Open Source Software - may be modified and shared by FRC teams. The code */
4/* must be accompanied by the FIRST BSD license file in the root directory of */
5/* the project. */
6/*----------------------------------------------------------------------------*/
7
8#ifdef __APPLE__
9#include <util.h>
10#elif !defined(_WIN32)
11#include <pty.h>
12#endif
13
14#include "wpi/MathExtras.h"
15#include "wpi/SmallVector.h"
16#include "wpi/raw_ostream.h"
17#include "wpi/raw_uv_ostream.h"
18#include "wpi/timestamp.h"
19#include "wpi/uv/Loop.h"
20#include "wpi/uv/Pipe.h"
21#include "wpi/uv/Process.h"
22#include "wpi/uv/Signal.h"
23#include "wpi/uv/Tcp.h"
24#include "wpi/uv/Tty.h"
25#include "wpi/uv/Udp.h"
26#include "wpi/uv/util.h"
27
28namespace uv = wpi::uv;
29
30static uint64_t startTime = wpi::Now();
31
32static bool NewlineBuffer(std::string& rem, uv::Buffer& buf, size_t len,
33 wpi::SmallVectorImpl<uv::Buffer>& bufs, bool tcp,
34 uint16_t tcpSeq) {
35 // scan for last newline
36 wpi::StringRef str(buf.base, len);
37 size_t idx = str.rfind('\n');
38 if (idx == wpi::StringRef::npos) {
39 // no newline yet, just keep appending to remainder
40 rem += str;
41 return false;
42 }
43
44 // build output
45 wpi::raw_uv_ostream out(bufs, 4096);
46 wpi::StringRef toCopy = str.slice(0, idx + 1);
47 if (tcp) {
48 // Header is 2 byte len, 1 byte type, 4 byte timestamp, 2 byte sequence num
49 uint32_t ts = wpi::FloatToBits((wpi::Now() - startTime) * 1.0e-6);
50 uint16_t len = rem.size() + toCopy.size() + 1 + 4 + 2;
James Kuszmaul4f3ad3c2019-12-01 16:35:21 -080051 const uint8_t header[] = {static_cast<uint8_t>((len >> 8) & 0xff),
52 static_cast<uint8_t>(len & 0xff),
53 12,
54 static_cast<uint8_t>((ts >> 24) & 0xff),
55 static_cast<uint8_t>((ts >> 16) & 0xff),
56 static_cast<uint8_t>((ts >> 8) & 0xff),
57 static_cast<uint8_t>(ts & 0xff),
58 static_cast<uint8_t>((tcpSeq >> 8) & 0xff),
59 static_cast<uint8_t>(tcpSeq & 0xff)};
60 out << wpi::ArrayRef<uint8_t>(header);
Brian Silverman41cdd3e2019-01-19 19:48:58 -080061 }
62 out << rem << toCopy;
63
64 // reset remainder
65 rem = str.slice(idx + 1, wpi::StringRef::npos);
66 return true;
67}
68
69static void CopyUdp(uv::Stream& in, std::shared_ptr<uv::Udp> out,
70 bool broadcast) {
71 sockaddr_in addr;
72 if (broadcast) {
73 out->SetBroadcast(true);
74 uv::NameToAddr("0.0.0.0", 6666, &addr);
75 } else {
76 uv::NameToAddr("127.0.0.1", 6666, &addr);
77 }
78
79 in.data.connect(
James Kuszmaul4f3ad3c2019-12-01 16:35:21 -080080 [rem = std::make_shared<std::string>(), outPtr = out.get(), addr](
81 uv::Buffer& buf, size_t len) {
Brian Silverman41cdd3e2019-01-19 19:48:58 -080082 // build buffers
83 wpi::SmallVector<uv::Buffer, 4> bufs;
84 if (!NewlineBuffer(*rem, buf, len, bufs, false, 0)) return;
85
86 // send output
87 outPtr->Send(addr, bufs, [](auto bufs2, uv::Error) {
88 for (auto buf : bufs2) buf.Deallocate();
89 });
90 },
91 out);
92}
93
94static void CopyTcp(uv::Stream& in, std::shared_ptr<uv::Stream> out) {
95 struct StreamData {
96 std::string rem;
97 uint16_t seq = 0;
98 };
James Kuszmaul4f3ad3c2019-12-01 16:35:21 -080099 in.data.connect(
100 [data = std::make_shared<StreamData>(), outPtr = out.get()](
101 uv::Buffer& buf, size_t len) {
102 // build buffers
103 wpi::SmallVector<uv::Buffer, 4> bufs;
104 if (!NewlineBuffer(data->rem, buf, len, bufs, true, data->seq++))
105 return;
Brian Silverman41cdd3e2019-01-19 19:48:58 -0800106
James Kuszmaul4f3ad3c2019-12-01 16:35:21 -0800107 // send output
108 outPtr->Write(bufs, [](auto bufs2, uv::Error) {
109 for (auto buf : bufs2) buf.Deallocate();
110 });
111 },
112 out);
Brian Silverman41cdd3e2019-01-19 19:48:58 -0800113}
114
115static void CopyStream(uv::Stream& in, std::shared_ptr<uv::Stream> out) {
116 in.data.connect([out](uv::Buffer& buf, size_t len) {
117 uv::Buffer buf2 = buf.Dup();
118 buf2.len = len;
119 out->Write(buf2, [](auto bufs, uv::Error) {
120 for (auto buf : bufs) buf.Deallocate();
121 });
122 });
123}
124
125int main(int argc, char* argv[]) {
126 // parse arguments
127 int programArgc = 1;
128 bool useUdp = false;
129 bool broadcastUdp = false;
130 bool err = false;
131
132 while (programArgc < argc && argv[programArgc][0] == '-') {
133 if (wpi::StringRef(argv[programArgc]) == "-u") {
134 useUdp = true;
135 } else if (wpi::StringRef(argv[programArgc]) == "-b") {
136 useUdp = true;
137 broadcastUdp = true;
138 } else {
139 wpi::errs() << "unrecognized command line option " << argv[programArgc]
140 << '\n';
141 err = true;
142 }
143 ++programArgc;
144 }
145
146 if (err || (argc - programArgc) < 1) {
147 wpi::errs()
148 << argv[0] << " [-ub] program [arguments ...]\n"
149 << " -u send udp to localhost port 6666 instead of using tcp\n"
150 << " -b broadcast udp to port 6666 instead of using tcp\n";
151 return EXIT_FAILURE;
152 }
153
154 uv::Process::DisableStdioInheritance();
155
156 auto loop = uv::Loop::Create();
157 loop->error.connect(
158 [](uv::Error err) { wpi::errs() << "uv ERROR: " << err.str() << '\n'; });
159
160 // create pipes to communicate with child
161 auto stdinPipe = uv::Pipe::Create(loop);
162 auto stdoutPipe = uv::Pipe::Create(loop);
163 auto stderrPipe = uv::Pipe::Create(loop);
164
165 // create tty to pass from our console to child's
166 auto stdinTty = uv::Tty::Create(loop, 0, true);
167 auto stdoutTty = uv::Tty::Create(loop, 1, false);
168 auto stderrTty = uv::Tty::Create(loop, 2, false);
169
170 // pass through our console to child's (bidirectional)
171 if (stdinTty) CopyStream(*stdinTty, stdinPipe);
172 if (stdoutTty) CopyStream(*stdoutPipe, stdoutTty);
173 if (stderrTty) CopyStream(*stderrPipe, stderrTty);
174
175 // when our stdin closes, also close child stdin
176 if (stdinTty) stdinTty->end.connect([stdinPipe] { stdinPipe->Close(); });
177
178 if (useUdp) {
179 auto udp = uv::Udp::Create(loop);
180 // tee stdout and stderr
181 CopyUdp(*stdoutPipe, udp, broadcastUdp);
182 CopyUdp(*stderrPipe, udp, broadcastUdp);
183 } else {
184 auto tcp = uv::Tcp::Create(loop);
185
186 // bind to listen address and port
187 tcp->Bind("", 1740);
188
189 // when we get a connection, accept it
James Kuszmaul4f3ad3c2019-12-01 16:35:21 -0800190 tcp->connection.connect([srv = tcp.get(), stdoutPipe, stderrPipe] {
Brian Silverman41cdd3e2019-01-19 19:48:58 -0800191 auto tcp = srv->Accept();
192 if (!tcp) return;
193
194 // close on error
195 tcp->error.connect([s = tcp.get()](wpi::uv::Error err) { s->Close(); });
196
197 // tee stdout and stderr
198 CopyTcp(*stdoutPipe, tcp);
199 CopyTcp(*stderrPipe, tcp);
200 });
201
202 // start listening for incoming connections
203 tcp->Listen();
204 }
205
206 // build process options
207 wpi::SmallVector<uv::Process::Option, 8> options;
208
209 // hook up pipes to child
210 options.emplace_back(
211 uv::Process::StdioCreatePipe(0, *stdinPipe, UV_READABLE_PIPE));
212#ifndef _WIN32
213 // create a PTY so the child does unbuffered output
214 int parentfd, childfd;
215 if (openpty(&parentfd, &childfd, nullptr, nullptr, nullptr) == 0) {
216 stdoutPipe->Open(parentfd);
217 options.emplace_back(uv::Process::StdioInherit(1, childfd));
218 } else {
219 options.emplace_back(
220 uv::Process::StdioCreatePipe(1, *stdoutPipe, UV_WRITABLE_PIPE));
221 }
222#else
223 options.emplace_back(
224 uv::Process::StdioCreatePipe(1, *stdoutPipe, UV_WRITABLE_PIPE));
225#endif
226 options.emplace_back(
227 uv::Process::StdioCreatePipe(2, *stderrPipe, UV_WRITABLE_PIPE));
228
229 // pass our args as the child args (argv[1] becomes child argv[0], etc)
230 for (int i = programArgc; i < argc; ++i) options.emplace_back(argv[i]);
231
232 auto proc = uv::Process::SpawnArray(loop, argv[programArgc], options);
233 if (!proc) {
234 wpi::errs() << "could not start subprocess\n";
235 return EXIT_FAILURE;
236 }
237 proc->exited.connect([](int64_t status, int) { std::exit(status); });
238
239 // start reading
240 if (stdinTty) stdinTty->StartRead();
241 stdoutPipe->StartRead();
242 stderrPipe->StartRead();
243
244 // pass various signals to child
245 auto sigHandler = [proc](int signum) { proc->Kill(signum); };
246 for (int signum : {SIGINT, SIGHUP, SIGTERM}) {
247 auto sig = uv::Signal::Create(loop);
248 sig->Start(signum);
249 sig->signal.connect(sigHandler);
250 }
251
252 // run the loop!
253 loop->Run();
254}