-
-
Notifications
You must be signed in to change notification settings - Fork 168
/
Headers.hpp
439 lines (387 loc) · 10.6 KB
/
Headers.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
#ifndef __ET_HEADERS__
#define __ET_HEADERS__
#define CPPHTTPLIB_ZLIB_SUPPORT (1)
#define CPPHTTPLIB_OPENSSL_SUPPORT (1)
// httplib has to come before windows.h
#include "httplib.h"
#if __FreeBSD__
#define _WITH_GETLINE
#endif
#if __APPLE__
#include <sys/ucred.h>
#include <util.h>
#elif __FreeBSD__
#include <libutil.h>
#include <sys/socket.h>
#elif __NetBSD__ // do not need pty.h on NetBSD
#include <util.h>
#elif defined(_MSC_VER)
#include <WinSock2.h>
#include <Ws2tcpip.h>
#include <afunix.h>
#include <signal.h>
#include <codecvt>
inline int close(int fd) { return ::closesocket(fd); }
#else
#include <pty.h>
#include <signal.h>
#endif
#ifdef WIN32
#else
#include <arpa/inet.h>
#include <grp.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <paths.h>
#include <pthread.h>
#include <pwd.h>
#include <resolv.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/wait.h>
#include <termios.h>
#include <unistd.h>
#endif
#include <errno.h>
#include <fcntl.h>
#include <google/protobuf/message_lite.h>
#include <sodium.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <time.h>
#include <algorithm>
#include <array>
#include <atomic>
#include <ctime>
#include <deque>
#include <exception>
#include <fstream>
#include <iostream>
#include <locale>
#include <memory>
#include <mutex>
#include <optional>
#include <set>
#include <sstream>
#include <streambuf>
#include <string>
#include <thread>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// Need to check for Boost first because Mojave *has* std::filesystem,
// but won't let you use it.
#ifdef __APPLE__
#include <Availability.h>
#endif
#if defined(__APPLE__) && \
__MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_15
#if __has_include(<boost/filesystem.hpp>)
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;
#else
#include <filesystem>
namespace fs = std::filesystem;
#endif
#else
// For non-Apple systems, prefer std::filesystem
// Otherwise, older versions of boost cause failures.
#if __has_include(<filesystem>)
#include <filesystem>
namespace fs = std::filesystem;
#elif __has_include(<experimental/filesystem>)
#include <experimental/filesystem>
namespace fs = std::experimental;
#elif __has_include(<boost/filesystem>)
#include <boost/filesystem>
namespace fs = boost::filesystem
#else
#pragma message "No filesystem library found."
#endif
#endif
#include "ET.pb.h"
#include "ETerminal.pb.h"
#include "ThreadPool.h"
#include "base64.h"
#include "easylogging++.h"
#include "sago/platform_folders.h"
#include "sole.hpp"
#if !defined(__ANDROID__)
#include "ust.hpp"
#endif
#ifdef WITH_UTEMPTER
#include <utempter.h>
#endif
#if defined(_MSC_VER)
#define popen _popen
#define pclose _pclose
/* ssize_t is not defined on Windows */
#ifndef ssize_t
#if defined(_WIN64)
typedef signed __int64 ssize_t;
#else
typedef int ssize_t;
#endif
#endif /* !ssize_t */
/* On MSVC, ssize_t is SSIZE_T */
#ifdef _MSC_VER
#include <BaseTsd.h>
#define ssize_t SSIZE_T
#endif
#endif
using namespace std;
// The ET protocol version supported by this binary
static const int PROTOCOL_VERSION = 6;
// Nonces for CryptoHandler
static const unsigned char CLIENT_SERVER_NONCE_MSB = 0;
static const unsigned char SERVER_CLIENT_NONCE_MSB = 1;
// system ssh config files
const string SYSTEM_SSH_CONFIG_PATH = "/etc/ssh/ssh_config";
const string USER_SSH_CONFIG_PATH = "/.ssh/config";
// Keepalive configs
const int MAX_CLIENT_KEEP_ALIVE_DURATION = 5;
// This should be at least double the value of MAX_CLIENT_KEEP_ALIVE_DURATION to
// allow enough time.
const int SERVER_KEEP_ALIVE_DURATION = 11;
#if defined(__ANDROID__)
#define STFATAL LOG(FATAL) << "No Stack Trace on Android" << endl
#define STERROR LOG(ERROR) << "No Stack Trace on Android" << endl
#else
#define STFATAL LOG(FATAL) << "Stack Trace: " << endl << ust::generate()
#define STERROR LOG(ERROR) << "Stack Trace: " << endl << ust::generate()
#endif
inline int GetErrno() {
#ifdef WIN32
auto retval = WSAGetLastError();
if (retval >= 10000) {
// Do some translation
switch (retval) {
case WSAEWOULDBLOCK:
return EWOULDBLOCK;
case WSAEADDRINUSE:
return EADDRINUSE;
case WSAEINPROGRESS:
return EINPROGRESS;
case WSAENOTSOCK:
return ENOTSOCK;
case WSAECONNRESET:
return ECONNRESET;
case WSAECONNABORTED:
return ECONNABORTED;
default:
STFATAL << "Unmapped WSA error: " << retval;
}
}
return retval;
#else
return errno;
#endif
}
inline void SetErrno(int e) {
#ifdef WIN32
WSASetLastError(e);
#else
errno = e;
#endif
}
#ifdef WIN32
inline string WindowsErrnoToString() {
const int BUFSIZE = 4096;
char buf[BUFSIZE];
auto charsWritten = FormatMessageA(
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL,
WSAGetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buf,
BUFSIZE, NULL);
if (charsWritten) {
string s(buf, charsWritten + 1);
return s;
}
return "Unknown Error";
}
#define FATAL_FAIL(X) \
if (((X) == -1)) \
LOG(FATAL) << "Error: (" << WSAGetLastError() \
<< "): " << WindowsErrnoToString();
#define FATAL_FAIL_UNLESS_ZERO(X) \
if (((X) != 0)) \
LOG(FATAL) << "Error: (" << WSAGetLastError() \
<< "): " << WindowsErrnoToString();
#define FATAL_FAIL_UNLESS_EINVAL(X) FATAL_FAIL(X)
#else
#define FATAL_FAIL(X) \
if (((X) == -1)) \
STFATAL << "Error: (" << GetErrno() << "): " << strerror(GetErrno());
// On BSD/OSX we can get EINVAL if the remote side has closed the connection
// before we have initialized it.
#define FATAL_FAIL_UNLESS_EINVAL(X) \
if (((X) == -1) && GetErrno() != EINVAL) \
STFATAL << "Error: (" << GetErrno() << "): " << strerror(GetErrno());
// On FreeBSD we can get EAGAIN on close if the descriptor is being
// selected.
#define FATAL_FAIL_UNLESS_EAGAIN(X) \
if (((X) == -1) && GetErrno() != EAGAIN) \
STFATAL << "Error: (" << GetErrno() << "): " << strerror(GetErrno());
#endif
#ifndef ET_VERSION
#define ET_VERSION "unknown"
#endif
namespace et {
inline std::ostream& operator<<(std::ostream& os,
const et::SocketEndpoint& se) {
if (se.has_name()) {
os << se.name();
}
if (se.has_port()) {
os << ":" << se.port();
}
return os;
}
template <typename Out>
inline void split(const std::string& s, char delim, Out result) {
std::stringstream ss;
ss.str(s);
std::string item;
while (std::getline(ss, item, delim)) {
*(result++) = item;
}
}
inline std::vector<std::string> split(const std::string& s, char delim) {
std::vector<std::string> elems;
split(s, delim, std::back_inserter(elems));
return elems;
}
inline bool replace(std::string& str, const std::string& from,
const std::string& to) {
auto start_pos = str.find(from);
if (start_pos == std::string::npos) return false;
str.replace(start_pos, from.length(), to);
return true;
}
inline int replaceAll(std::string& str, const std::string& from,
const std::string& to) {
if (from.empty()) return 0;
int retval = 0;
auto start_pos = 0;
while ((start_pos = str.find(from, start_pos)) != std::string::npos) {
retval++;
str.replace(start_pos, from.length(), to);
start_pos += to.length(); // In case 'to' contains 'from', like replacing
// 'x' with 'yx'
}
return retval;
}
template <typename T>
inline T stringToProto(const string& s) {
T t;
if (!t.ParseFromString(s)) {
STFATAL << "Error parsing string to proto: " << s.length() << " " << s;
}
return t;
}
template <typename T>
inline string protoToString(const T& t) {
string s;
if (!t.SerializeToString(&s)) {
STFATAL << "Error serializing proto to string";
}
return s;
}
/**
* Wait on a fd to have data available.
*
* @return true if the fd has data, or false if the timeout (of 1 second) is
* reached or if the call is interrupted by a syscall.
*/
inline bool waitOnSocketData(int fd) {
fd_set fdset;
FD_ZERO(&fdset);
FD_SET(fd, &fdset);
timeval tv;
tv.tv_sec = 1;
tv.tv_usec = 0;
VLOG(4) << "Before selecting sockFd";
const int selectResult = select(fd + 1, &fdset, NULL, NULL, &tv);
if (selectResult < 0) {
if (errno == EINTR) {
// Interrupted by the signal, the caller will retry.
return false;
} else {
FATAL_FAIL(selectResult);
}
}
return FD_ISSET(fd, &fdset);
}
inline string genRandomAlphaNum(int len) {
static const char alphanum[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
string s(len, '\0');
for (int i = 0; i < len; ++i) {
s[i] = alphanum[randombytes_uniform(sizeof(alphanum) - 1)];
}
return s;
}
inline string GetTempDirectory() {
#ifdef WIN32
WCHAR buf[65536];
int retval = GetTempPath(65536, buf);
int a = 0;
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t> > converter;
std::string tmpDir = converter.to_bytes(wstring(buf, retval));
#else
string tmpDir = _PATH_TMP;
#endif
return tmpDir;
}
inline void HandleTerminate() {
static bool first = true;
if (first) {
first = false;
} else {
// If we are recursively terminating, just bail
return;
}
std::set_terminate([]() -> void {
std::exception_ptr eptr = std::current_exception();
if (eptr) {
try {
std::rethrow_exception(eptr);
} catch (const std::exception& e) {
STFATAL << "Uncaught c++ exception: " << e.what();
}
} else {
STFATAL << "Uncaught c++ exception (unknown)";
}
});
}
inline void InterruptSignalHandler(int signum) {
CLOG(INFO, "stdout") << endl
<< "Got interrupt (perhaps ctrl+c?): " << signum
<< ". Exiting." << endl;
::exit(signum);
}
inline void TerminateSignalHandler(int signum) {
CLOG(INFO, "stdout") << endl
<< "Got terminate signal: " << signum << ". Exiting."
<< endl;
::exit(signum);
}
} // namespace et
inline bool operator==(const google::protobuf::MessageLite& msg_a,
const google::protobuf::MessageLite& msg_b) {
return (msg_a.GetTypeName() == msg_b.GetTypeName()) &&
(msg_a.SerializeAsString() == msg_b.SerializeAsString());
}
inline bool operator!=(const google::protobuf::MessageLite& msg_a,
const google::protobuf::MessageLite& msg_b) {
return (msg_a.GetTypeName() != msg_b.GetTypeName()) ||
(msg_a.SerializeAsString() != msg_b.SerializeAsString());
}
#endif