blob: c6730086b965fbc6ecec35dda04ebe34e069eb79 [file] [log] [blame]
Brian Silverman41cdd3e2019-01-19 19:48:58 -08001/*----------------------------------------------------------------------------*/
2/* Copyright (c) 2018 FIRST. All Rights Reserved. */
3/* 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;
51 out << wpi::ArrayRef<uint8_t>({static_cast<uint8_t>((len >> 8) & 0xff),
52 static_cast<uint8_t>(len & 0xff), 12,
53 static_cast<uint8_t>((ts >> 24) & 0xff),
54 static_cast<uint8_t>((ts >> 16) & 0xff),
55 static_cast<uint8_t>((ts >> 8) & 0xff),
56 static_cast<uint8_t>(ts & 0xff),
57 static_cast<uint8_t>((tcpSeq >> 8) & 0xff),
58 static_cast<uint8_t>(tcpSeq & 0xff)});
59 }
60 out << rem << toCopy;
61
62 // reset remainder
63 rem = str.slice(idx + 1, wpi::StringRef::npos);
64 return true;
65}
66
67static void CopyUdp(uv::Stream& in, std::shared_ptr<uv::Udp> out,
68 bool broadcast) {
69 sockaddr_in addr;
70 if (broadcast) {
71 out->SetBroadcast(true);
72 uv::NameToAddr("0.0.0.0", 6666, &addr);
73 } else {
74 uv::NameToAddr("127.0.0.1", 6666, &addr);
75 }
76
77 in.data.connect(
78 [ rem = std::make_shared<std::string>(), outPtr = out.get(), addr ](
79 uv::Buffer & buf, size_t len) {
80 // build buffers
81 wpi::SmallVector<uv::Buffer, 4> bufs;
82 if (!NewlineBuffer(*rem, buf, len, bufs, false, 0)) return;
83
84 // send output
85 outPtr->Send(addr, bufs, [](auto bufs2, uv::Error) {
86 for (auto buf : bufs2) buf.Deallocate();
87 });
88 },
89 out);
90}
91
92static void CopyTcp(uv::Stream& in, std::shared_ptr<uv::Stream> out) {
93 struct StreamData {
94 std::string rem;
95 uint16_t seq = 0;
96 };
97 in.data.connect([ data = std::make_shared<StreamData>(), outPtr = out.get() ](
98 uv::Buffer & buf, size_t len) {
99 // build buffers
100 wpi::SmallVector<uv::Buffer, 4> bufs;
101 if (!NewlineBuffer(data->rem, buf, len, bufs, true, data->seq++)) return;
102
103 // send output
104 outPtr->Write(bufs, [](auto bufs2, uv::Error) {
105 for (auto buf : bufs2) buf.Deallocate();
106 });
107 },
108 out);
109}
110
111static void CopyStream(uv::Stream& in, std::shared_ptr<uv::Stream> out) {
112 in.data.connect([out](uv::Buffer& buf, size_t len) {
113 uv::Buffer buf2 = buf.Dup();
114 buf2.len = len;
115 out->Write(buf2, [](auto bufs, uv::Error) {
116 for (auto buf : bufs) buf.Deallocate();
117 });
118 });
119}
120
121int main(int argc, char* argv[]) {
122 // parse arguments
123 int programArgc = 1;
124 bool useUdp = false;
125 bool broadcastUdp = false;
126 bool err = false;
127
128 while (programArgc < argc && argv[programArgc][0] == '-') {
129 if (wpi::StringRef(argv[programArgc]) == "-u") {
130 useUdp = true;
131 } else if (wpi::StringRef(argv[programArgc]) == "-b") {
132 useUdp = true;
133 broadcastUdp = true;
134 } else {
135 wpi::errs() << "unrecognized command line option " << argv[programArgc]
136 << '\n';
137 err = true;
138 }
139 ++programArgc;
140 }
141
142 if (err || (argc - programArgc) < 1) {
143 wpi::errs()
144 << argv[0] << " [-ub] program [arguments ...]\n"
145 << " -u send udp to localhost port 6666 instead of using tcp\n"
146 << " -b broadcast udp to port 6666 instead of using tcp\n";
147 return EXIT_FAILURE;
148 }
149
150 uv::Process::DisableStdioInheritance();
151
152 auto loop = uv::Loop::Create();
153 loop->error.connect(
154 [](uv::Error err) { wpi::errs() << "uv ERROR: " << err.str() << '\n'; });
155
156 // create pipes to communicate with child
157 auto stdinPipe = uv::Pipe::Create(loop);
158 auto stdoutPipe = uv::Pipe::Create(loop);
159 auto stderrPipe = uv::Pipe::Create(loop);
160
161 // create tty to pass from our console to child's
162 auto stdinTty = uv::Tty::Create(loop, 0, true);
163 auto stdoutTty = uv::Tty::Create(loop, 1, false);
164 auto stderrTty = uv::Tty::Create(loop, 2, false);
165
166 // pass through our console to child's (bidirectional)
167 if (stdinTty) CopyStream(*stdinTty, stdinPipe);
168 if (stdoutTty) CopyStream(*stdoutPipe, stdoutTty);
169 if (stderrTty) CopyStream(*stderrPipe, stderrTty);
170
171 // when our stdin closes, also close child stdin
172 if (stdinTty) stdinTty->end.connect([stdinPipe] { stdinPipe->Close(); });
173
174 if (useUdp) {
175 auto udp = uv::Udp::Create(loop);
176 // tee stdout and stderr
177 CopyUdp(*stdoutPipe, udp, broadcastUdp);
178 CopyUdp(*stderrPipe, udp, broadcastUdp);
179 } else {
180 auto tcp = uv::Tcp::Create(loop);
181
182 // bind to listen address and port
183 tcp->Bind("", 1740);
184
185 // when we get a connection, accept it
186 tcp->connection.connect([ srv = tcp.get(), stdoutPipe, stderrPipe ] {
187 auto tcp = srv->Accept();
188 if (!tcp) return;
189
190 // close on error
191 tcp->error.connect([s = tcp.get()](wpi::uv::Error err) { s->Close(); });
192
193 // tee stdout and stderr
194 CopyTcp(*stdoutPipe, tcp);
195 CopyTcp(*stderrPipe, tcp);
196 });
197
198 // start listening for incoming connections
199 tcp->Listen();
200 }
201
202 // build process options
203 wpi::SmallVector<uv::Process::Option, 8> options;
204
205 // hook up pipes to child
206 options.emplace_back(
207 uv::Process::StdioCreatePipe(0, *stdinPipe, UV_READABLE_PIPE));
208#ifndef _WIN32
209 // create a PTY so the child does unbuffered output
210 int parentfd, childfd;
211 if (openpty(&parentfd, &childfd, nullptr, nullptr, nullptr) == 0) {
212 stdoutPipe->Open(parentfd);
213 options.emplace_back(uv::Process::StdioInherit(1, childfd));
214 } else {
215 options.emplace_back(
216 uv::Process::StdioCreatePipe(1, *stdoutPipe, UV_WRITABLE_PIPE));
217 }
218#else
219 options.emplace_back(
220 uv::Process::StdioCreatePipe(1, *stdoutPipe, UV_WRITABLE_PIPE));
221#endif
222 options.emplace_back(
223 uv::Process::StdioCreatePipe(2, *stderrPipe, UV_WRITABLE_PIPE));
224
225 // pass our args as the child args (argv[1] becomes child argv[0], etc)
226 for (int i = programArgc; i < argc; ++i) options.emplace_back(argv[i]);
227
228 auto proc = uv::Process::SpawnArray(loop, argv[programArgc], options);
229 if (!proc) {
230 wpi::errs() << "could not start subprocess\n";
231 return EXIT_FAILURE;
232 }
233 proc->exited.connect([](int64_t status, int) { std::exit(status); });
234
235 // start reading
236 if (stdinTty) stdinTty->StartRead();
237 stdoutPipe->StartRead();
238 stderrPipe->StartRead();
239
240 // pass various signals to child
241 auto sigHandler = [proc](int signum) { proc->Kill(signum); };
242 for (int signum : {SIGINT, SIGHUP, SIGTERM}) {
243 auto sig = uv::Signal::Create(loop);
244 sig->Start(signum);
245 sig->signal.connect(sigHandler);
246 }
247
248 // run the loop!
249 loop->Run();
250}