/
main.cpp
648 lines (515 loc) · 16.9 KB
/
main.cpp
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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
/*
Copyright 2011 John Selbie
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "commonincludes.h"
#include "stuncore.h"
#include "server.h"
#include "tcpserver.h"
#include "adapters.h"
#include "cmdlineparser.h"
#include <getopt.h>
#include "prettyprint.h"
#include "oshelper.h"
#include "stringhelper.h"
// unusual to include usage.cpp and usagelite.cpp here, but these are auto-generated resource file
#include "usage.txtcode"
#include "usagelite.txtcode"
void PrintUsage(bool fSummaryUsage)
{
size_t width = GetConsoleWidth();
const char* psz = fSummaryUsage ? usagelite_text : usage_text;
// save some margin space
if (width > 2)
{
width -= 2;
}
PrettyPrint(psz, width);
}
void LogHR(uint16_t level, HRESULT hr)
{
uint32_t facility = HRESULT_FACILITY(hr);
char msg[400];
const char* pMsg = NULL;
bool fGotMsg = false;
if (facility == FACILITY_ERRNO)
{
msg[0] = '\0';
int err = (int)(HRESULT_CODE(hr));
pMsg = strerror_r(err, msg, ARRAYSIZE(msg));
if (pMsg)
{
Logging::LogMsg(level, "Error: %s", pMsg);
fGotMsg = true;
}
if (err == EADDRINUSE)
{
Logging::LogMsg(level,
"This error likely means another application is listening on one\n"
"or more of the same ports you are attempting to configure this\n"
"server to listen on. Run \"netstat -a -p -t -u\" to see a list\n"
"of all ports in use and associated process id for each");
}
}
if (fGotMsg == false)
{
Logging::LogMsg(level, "Error: %x", hr);
}
}
struct StartupArgs
{
std::string strMode;
std::string strPrimaryInterface;
std::string strAltInterface;
std::string strPrimaryPort;
std::string strAltPort;
std::string strFamily;
std::string strProtocol;
std::string strHelp;
std::string strVerbosity;
std::string strMaxConnections;
};
#define PRINTARG(member) Logging::LogMsg(LL_DEBUG, "%s = %s", #member, args.member.length() ? args.member.c_str() : "<empty>");
void DumpStartupArgs(StartupArgs& args)
{
Logging::LogMsg(LL_DEBUG, "\n\n--------------------------");
PRINTARG(strMode);
PRINTARG(strPrimaryInterface);
PRINTARG(strAltInterface);
PRINTARG(strPrimaryPort);
PRINTARG(strAltPort);
PRINTARG(strFamily);
PRINTARG(strProtocol);
PRINTARG(strHelp);
PRINTARG(strVerbosity);
PRINTARG(strMaxConnections);
Logging::LogMsg(LL_DEBUG, "--------------------------\n");
}
void DumpConfig(CStunServerConfig &config)
{
std::string strSocket;
if (config.fHasPP)
{
config.addrPP.ToString(&strSocket);
Logging::LogMsg(LL_DEBUG, "PP = %s", strSocket.c_str());
}
if (config.fHasPA)
{
config.addrPA.ToString(&strSocket);
Logging::LogMsg(LL_DEBUG, "PA = %s", strSocket.c_str());
}
if (config.fHasAP)
{
config.addrAP.ToString(&strSocket);
Logging::LogMsg(LL_DEBUG, "AP = %s", strSocket.c_str());
}
if (config.fHasAA)
{
config.addrAA.ToString(&strSocket);
Logging::LogMsg(LL_DEBUG, "AA = %s", strSocket.c_str());
}
Logging::LogMsg(LL_DEBUG, "Protocol = %s", config.fTCP ? "TCP" : "UDP");
if (config.fTCP && (config.nMaxConnections>0))
{
Logging::LogMsg(LL_DEBUG, "Max TCP Connections per thread: %d", config.nMaxConnections);
}
}
HRESULT ResolveAdapterName(bool fPrimary, int family, std::string& strAdapterName, uint16_t port, CSocketAddress* pAddr)
{
HRESULT hr = S_OK;
if (strAdapterName.length() == 0)
{
hr = GetBestAddressForSocketBind(fPrimary, family, port, pAddr);
if (SUCCEEDED(hr))
{
pAddr->ToString(&strAdapterName);
// strip off the port suffix
size_t x = strAdapterName.find_last_of(':');
if (x != std::string::npos)
{
strAdapterName = strAdapterName.substr(0, x);
}
}
}
else
{
hr = GetSocketAddressForAdapter(family, strAdapterName.c_str(), port, pAddr);
}
return hr;
}
HRESULT BuildServerConfigurationFromArgs(StartupArgs& argsIn, CStunServerConfig* pConfigOut)
{
HRESULT hr = S_OK;
// default values;
int family = AF_INET;
// bool fIsUdp = true;
int nPrimaryPort = DEFAULT_STUN_PORT;
int nAltPort = DEFAULT_STUN_PORT + 1;
bool fHasAtLeastTwoAdapters = false;
CStunServerConfig config;
int nMaxConnections = 0;
enum ServerMode
{
Basic,
Full
};
ServerMode mode=Basic;
StartupArgs args = argsIn;
ChkIfA(pConfigOut == NULL, E_INVALIDARG);
// normalize the args. The "trim" is not needed for command line args, but will be useful when we have an "init file" for intializing the server
StringHelper::ToLower(args.strMode);
StringHelper::Trim(args.strMode);
StringHelper::Trim(args.strPrimaryInterface);
StringHelper::Trim(args.strAltInterface);
StringHelper::Trim(args.strPrimaryPort);
StringHelper::Trim(args.strAltPort);
StringHelper::Trim(args.strFamily);
StringHelper::ToLower(args.strProtocol);
StringHelper::Trim(args.strProtocol);
// ---- MODE ----------------------------------------------------------
if (args.strMode.length() > 0)
{
if (args.strMode == "basic")
{
mode = Basic;
}
else if (args.strMode == "full")
{
mode = Full;
}
else
{
Logging::LogMsg(LL_ALWAYS, "Mode must be \"full\" or \"basic\".");
Chk(E_INVALIDARG);
}
}
// ---- FAMILY --------------------------------------------------------
family = AF_INET;
if (args.strFamily.length() > 0)
{
if (args.strFamily == "4")
{
family = AF_INET;
}
else if (args.strFamily == "6")
{
family = AF_INET6;
}
else
{
Logging::LogMsg(LL_ALWAYS, "Family argument must be '4' or '6'");
Chk(E_INVALIDARG);
}
}
// ---- PROTOCOL --------------------------------------------------------
if (args.strProtocol.length() > 0)
{
if ((args.strProtocol != "udp") && (args.strProtocol != "tcp"))
{
Logging::LogMsg(LL_ALWAYS, "Protocol argument must be 'udp' or 'tcp'. 'tls' is not supported yet");
Chk(E_INVALIDARG);
}
config.fTCP = (args.strProtocol == "tcp");
}
// ---- MAX Connections -----------------------------------------------------
nMaxConnections = 0;
if (args.strMaxConnections.length() > 0)
{
if (config.fTCP == false)
{
Logging::LogMsg(LL_ALWAYS, "Max connections parameter has no meaning in UDP mode. Did you mean to specify \"--protocol=tcp ?\"");
}
else
{
hr = StringHelper::ValidateNumberString(args.strMaxConnections.c_str(), 1, 100000, &nMaxConnections);
if (FAILED(hr))
{
Logging::LogMsg(LL_ALWAYS, "Max connections must be between 1-100000");
Chk(hr);
}
}
config.nMaxConnections = nMaxConnections;
}
// ---- PRIMARY PORT --------------------------------------------------------
nPrimaryPort = DEFAULT_STUN_PORT;
if (args.strPrimaryPort.length() > 0)
{
hr = StringHelper::ValidateNumberString(args.strPrimaryPort.c_str(), 0x0001, 0xffff, &nPrimaryPort);
if (FAILED(hr))
{
Logging::LogMsg(LL_ALWAYS, "Primary port value is invalid. Value must be between 1-65535");
Chk(hr);
}
}
// ---- ALT PORT --------------------------------------------------------
nAltPort = DEFAULT_STUN_PORT + 1;
if (args.strAltPort.length() > 0)
{
hr = StringHelper::ValidateNumberString(args.strAltPort.c_str(), 0x0001, 0xffff, &nAltPort);
if (FAILED(hr))
{
Logging::LogMsg(LL_ALWAYS, "Alt port value is invalid. Value must be between 1-65535");
Chk(hr);
}
}
if (nPrimaryPort == nAltPort)
{
Logging::LogMsg(LL_ALWAYS, "Primary port and altnernate port must be different values");
Chk(E_INVALIDARG);
}
// ---- Adapters and mode adjustment
fHasAtLeastTwoAdapters = ::HasAtLeastTwoAdapters(family);
if (mode == Basic)
{
uint16_t port = (uint16_t)((int16_t)nPrimaryPort);
// in basic mode, if no adapter is specified, bind to all of them
if (args.strPrimaryInterface.length() == 0)
{
if (family == AF_INET)
{
config.addrPP = CSocketAddress(0, port);
config.fHasPP = true;
}
else if (family == AF_INET6)
{
sockaddr_in6 addr6 = {}; // zero-init
addr6.sin6_family = AF_INET6;
config.addrPP = CSocketAddress(addr6);
config.addrPP.SetPort(port);
config.fHasPP = true;
}
}
else
{
CSocketAddress addr;
hr = GetSocketAddressForAdapter(family, args.strPrimaryInterface.c_str(), port, &addr);
if (FAILED(hr))
{
Logging::LogMsg(LL_ALWAYS, "No matching primary adapter found for %s", args.strPrimaryInterface.c_str());
Chk(hr);
}
config.addrPP = addr;
config.fHasPP = true;
}
}
else // Full mode
{
CSocketAddress addrPrimary;
CSocketAddress addrAlternate;
uint16_t portPrimary = (uint16_t)((int16_t)nPrimaryPort);
uint16_t portAlternate = (uint16_t)((int16_t)nAltPort);
// in full mode, we can't bind to all adapters
// so if one isn't specified, it's best guess - just avoid duplicates
if (fHasAtLeastTwoAdapters == false)
{
Logging::LogMsg(LL_ALWAYS, "There does not appear to be two or more unique IP addresses to run in full mode");
Chk(E_UNEXPECTED);
}
hr = ResolveAdapterName(true, family, args.strPrimaryInterface, 0, &addrPrimary);
if (FAILED(hr))
{
Logging::LogMsg(LL_ALWAYS, "Can't find address for primary interface");
Chk(hr);
}
hr = ResolveAdapterName(false, family, args.strAltInterface, 0, &addrAlternate);
if (FAILED(hr))
{
Logging::LogMsg(LL_ALWAYS, "Can't find address for alternate interface");
Chk(hr);
}
if (addrPrimary.IsSameIP(addrAlternate))
{
Logging::LogMsg(LL_ALWAYS, "Error - Primary interface and Alternate Interface appear to have the same IP address. Full mode requires two IP addresses that are unique");
Chk(E_INVALIDARG);
}
config.addrPP = addrPrimary;
config.addrPP.SetPort(portPrimary);
config.fHasPP = true;
config.addrPA = addrPrimary;
config.addrPA.SetPort(portAlternate);
config.fHasPA = true;
config.addrAP = addrAlternate;
config.addrAP.SetPort(portPrimary);
config.fHasAP = true;
config.addrAA = addrAlternate;
config.addrAA.SetPort(portAlternate);
config.fHasAA = true;
}
*pConfigOut = config;
hr = S_OK;
Cleanup:
return hr;
}
HRESULT ParseCommandLineArgs(int argc, char** argv, int startindex, StartupArgs* pStartupArgs)
{
CCmdLineParser cmdline;
std::string strHelp;
bool fError = false;
cmdline.AddOption("mode", required_argument, &pStartupArgs->strMode);
cmdline.AddOption("primaryinterface", required_argument, &pStartupArgs->strPrimaryInterface);
cmdline.AddOption("altinterface", required_argument, &pStartupArgs->strAltInterface);
cmdline.AddOption("primaryport", required_argument, &pStartupArgs->strPrimaryPort);
cmdline.AddOption("altport", required_argument, &pStartupArgs->strAltPort);
cmdline.AddOption("family", required_argument, &pStartupArgs->strFamily);
cmdline.AddOption("protocol", required_argument, &pStartupArgs->strProtocol);
cmdline.AddOption("maxconn", required_argument, &pStartupArgs->strMaxConnections);
cmdline.AddOption("help", no_argument, &pStartupArgs->strHelp);
cmdline.AddOption("verbosity", required_argument, &pStartupArgs->strVerbosity);
cmdline.ParseCommandLine(argc, argv, startindex, &fError);
return fError ? E_INVALIDARG : S_OK;
}
// This routine will set SIGINT And SIGTERM to "blocked" status only so that the
// child worker threads will never have these events raised on them.
HRESULT InitAppExitListener()
{
HRESULT hr = S_OK;
sigset_t sigs;
int ret;
sigemptyset(&sigs);
sigaddset(&sigs, SIGINT);
sigaddset(&sigs, SIGTERM);
ret = pthread_sigmask(SIG_BLOCK, &sigs, NULL);
hr = (ret == 0) ? S_OK : ERRNO_TO_HRESULT(ret);
Logging::LogMsg(LL_DEBUG, "InitAppExitListener: x%x", hr);
return hr;
}
// after all the child threads have initialized with a signal mask that blocks SIGINT and SIGTERM
// then the main thread UI can just sit on WaitForAppExitSignal and wait for CTRL-C to get pressed
void WaitForAppExitSignal()
{
while (true)
{
sigset_t sigs;
sigemptyset(&sigs);
sigaddset(&sigs, SIGINT);
sigaddset(&sigs, SIGTERM);
int sig = 0;
int ret = sigwait(&sigs, &sig);
Logging::LogMsg(LL_DEBUG, "sigwait returns %d (errno==%d)", ret, (ret==-1)?0:errno);
if ((sig == SIGINT) || (sig == SIGTERM))
{
break;
}
}
}
HRESULT StartUDP(CRefCountedPtr<CStunServer>& spServer, CStunServerConfig& config)
{
HRESULT hr;
hr = CStunServer::CreateInstance(config, spServer.GetPointerPointer());
if (FAILED(hr))
{
Logging::LogMsg(LL_ALWAYS, "Unable to initialize server (error code = x%x)", hr);
LogHR(LL_ALWAYS, hr);
return hr;
}
hr = spServer->Start();
if (FAILED(hr))
{
Logging::LogMsg(LL_ALWAYS, "Unable to start server (error code = x%x)", hr);
LogHR(LL_ALWAYS, hr);
return hr;
}
return S_OK;
}
HRESULT StartTCP(CRefCountedPtr<CTCPServer>& spTCPServer, CStunServerConfig& config)
{
HRESULT hr;
hr = CTCPServer::CreateInstance(config, spTCPServer.GetPointerPointer());
if (FAILED(hr))
{
Logging::LogMsg(LL_ALWAYS, "Unable to initialize TCP server (error code = x%x)", hr);
LogHR(LL_ALWAYS, hr);
return hr;
}
hr = spTCPServer->Start();
if (FAILED(hr))
{
Logging::LogMsg(LL_ALWAYS, "Unable to start TCP server (error code = x%x)", hr);
LogHR(LL_ALWAYS, hr);
return hr;
}
return S_OK;
}
int main(int argc, char** argv)
{
HRESULT hr = S_OK;
StartupArgs args;
CStunServerConfig config;
CRefCountedPtr<CStunServer> spServer;
CRefCountedPtr<CTCPServer> spTCPServer;
#ifdef DEBUG
Logging::SetLogLevel(LL_DEBUG);
#else
Logging::SetLogLevel(LL_ALWAYS);
#endif
hr = ParseCommandLineArgs(argc, argv, 1, &args);
if (FAILED(hr))
{
PrintUsage(true);
return -1;
}
if (args.strHelp.length() > 0)
{
PrintUsage(false);
return -2;
}
if (args.strVerbosity.length() > 0)
{
int loglevel = (uint32_t)atoi(args.strVerbosity.c_str());
if (loglevel >= 0)
{
Logging::SetLogLevel((uint32_t)loglevel);
}
}
if (SUCCEEDED(hr))
{
::DumpStartupArgs(args);
hr = BuildServerConfigurationFromArgs(args, &config);
}
if (FAILED(hr))
{
Logging::LogMsg(LL_ALWAYS, "Error building configuration from command line options");
PrintUsage(true);
return -3;
}
DumpConfig(config);
InitAppExitListener();
if (config.fTCP == false)
{
hr = StartUDP(spServer, config);
if (FAILED(hr))
{
return -4;
}
}
else
{
hr = StartTCP(spTCPServer, config);
if (FAILED(hr))
{
return -5;
}
}
Logging::LogMsg(LL_DEBUG, "Successfully started server.");
WaitForAppExitSignal();
Logging::LogMsg(LL_DEBUG, "Server is exiting");
if (spServer != NULL)
{
spServer->Stop();
spServer.ReleaseAndClear();
}
if (spTCPServer != NULL)
{
spTCPServer->Stop();
spTCPServer.ReleaseAndClear();
}
return 0;
}