forked from dannagle/PacketSender
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
executable file
·1657 lines (1263 loc) · 51 KB
/
Copy pathmain.cpp
File metadata and controls
executable file
·1657 lines (1263 loc) · 51 KB
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
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
*
* This file is part of Packet Sender
*
* Licensed GPL v2
* https://PacketSender.com/
*
* Copyright NagleCode, LLC
*
*/
#include "globals.h"
#ifndef CONSOLE_BUILD
#include <QtWidgets/QApplication>
#include <QColor>
#include <QDesktopServices>
#include <QPalette>
#include <QTranslator>
#include <QLibraryInfo>
#if QT_VERSION > QT_VERSION_CHECK(6, 0, 0)
#include <QGuiApplication>
#include <QStyleHints>
#endif
#include "settings.h"
#include "languagechooser.h"
#endif
#include <QDir>
#include <QCommandLineParser>
#include <QHostInfo>
#include <QSslError>
#include <QList>
#include <QSslCipher>
#include <QDeadlineTimer>
#include <QProcess>
#include <QStandardPaths>
#include <QSettings>
#include <QTimer>
#include<tuple>
#include "mainpacketreceiver.h"
#ifndef CONSOLE_BUILD
#include "translations.h"
#include "panelgenerator.h"
#include "packetnetwork.h"
#include "mainwindow.h"
#endif
#define DEBUGMODE 0
#include <cstdlib>
#define STOPSENDCHECK() if(hasstop) { \
stopcounter++; \
if(stopcounter >= stopnum) { \
break; \
} \
}
int intenseTrafficGenerator(QTextStream &out, QUdpSocket &sock, QHostAddress addy, unsigned int port, QString hexString, double bps, double rate, qint64 stopnum, qint64 usdelay);
bool isGuiApp()
{
QProcess *process = new QProcess();
QString program = "xrandr";
process->start(program, QStringList());
process->waitForFinished(500);
int exitcode = process->exitCode();
QDEBUGVAR(exitcode);
delete process;
if (exitcode > 0) {
// This means xrandr exists, but it couldn't connect.
return false;
}
if (exitcode < 0) {
//command not found. Maybe xrandr isn't present.
// TODO some other test?
return true;
}
// returned zero. All is good.
return true;
}
void myMessageOutputDisable(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
Q_UNUSED(type);
Q_UNUSED(context);
Q_UNUSED(msg);
}
#define OUTVAR(var) o<< "\n" << # var << ":" << var ;
#define OUTIF() if(!quiet) o<< "\n"
#define OUTPUT() outBuilder = outBuilder.trimmed(); outBuilder.append("\n"); out << outBuilder; out.flush(); outBuilder.clear();
#ifndef CONSOLE_BUILD
bool loadAndInstallTranslators(
QTranslator &qtTrans,
QTranslator &qtbaseTrans,
QTranslator &appTrans,
const QString &qtName,
const QString &qtbaseName,
const QString &appQmPath)
{
bool qtOk = qtTrans.load(qtName, QLibraryInfo::location(QLibraryInfo::TranslationsPath));
bool qtbaseOk = qtbaseTrans.load(qtbaseName, QLibraryInfo::location(QLibraryInfo::TranslationsPath));
bool appOk = appTrans.load(appQmPath);
QDEBUG() << "qt lang loaded" << qtOk;
QDEBUG() << "base lang loaded" << qtbaseOk;
QDEBUG() << "app lang loaded" << appOk;
bool allInstalled =
QApplication::installTranslator(&qtTrans) &&
QApplication::installTranslator(&qtbaseTrans) &&
QApplication::installTranslator(&appTrans);
QDEBUG() << "All translators installed:" << allInstalled;
return allInstalled;
}
void debugThemeFiles(bool debugMode) {
if(debugMode) {
QFile testDark(Settings::DARK_STYLE_SHEET_NAME);
QDEBUG() << "Dark stylesheet exists?" << testDark.exists();
QFile testLight(Settings::LIGHT_STYLE_SHEET_NAME);
QDEBUG() << "Light stylesheet exists?" << testLight.exists();
}
}
void applyTheme(bool isDark, bool debugMode, QApplication *app, MainWindow *mainWin = nullptr) {
if(isDark) {
app->setPalette(app->style()->standardPalette());
} else {
QPalette lightPalette;
lightPalette.setColor(QPalette::Window, QColor(250, 250, 250));
lightPalette.setColor(QPalette::WindowText, Qt::black);
lightPalette.setColor(QPalette::Base, Qt::white);
lightPalette.setColor(QPalette::AlternateBase, QColor(245, 245, 245));
lightPalette.setColor(QPalette::ToolTipBase, Qt::white);
lightPalette.setColor(QPalette::ToolTipText, Qt::black);
lightPalette.setColor(QPalette::Text, Qt::black);
lightPalette.setColor(QPalette::Button, QColor(245, 245, 245));
lightPalette.setColor(QPalette::ButtonText, Qt::black);
lightPalette.setColor(QPalette::BrightText, Qt::red);
lightPalette.setColor(QPalette::Link, QColor(0, 80, 160));
lightPalette.setColor(QPalette::Highlight, QColor(255, 249, 196));
lightPalette.setColor(QPalette::HighlightedText, Qt::black);
app->setPalette(lightPalette);
}
debugThemeFiles(debugMode);
QFile file(isDark ? Settings::DARK_STYLE_SHEET_NAME : Settings::LIGHT_STYLE_SHEET_NAME);
QString styleSheet = "";
if (file.open(QFile::ReadOnly)) {
styleSheet = QLatin1String(file.readAll());
file.close();
} else {
qWarning() << "Failed to open embedded stylesheet:" << file.fileName()
<< "(error:" << file.errorString() << ")";
return; // <<<<< Don't set empty! Skip apply to avoid crash
}
app->setStyleSheet(styleSheet);
// Force repolish on EVERY widget in the app (including children)
QList<QWidget*> allWidgets = qApp->allWidgets(); // This gets everything, top-level + children
for (QWidget *widget : allWidgets) {
if (widget) {
if (!widget->styleSheet().isEmpty() && widget->styleSheet() != styleSheet) {
QDEBUG() << "Clearing local stylesheet on" << widget->objectName() << "or class" << widget->metaObject()->className();
widget->setStyleSheet("");
}
widget->style()->unpolish(widget);
widget->style()->polish(widget);
widget->update();
widget->updateGeometry(); // Helps layouts recalc if needed
}
}
// Update global darkMode for other uses (e.g., in MainWindow)
PanelGenerator::darkMode = isDark;
}
void setupThemePolling(QApplication *app, MainWindow *mainWindow, bool debugMode = false)
{
QTimer *themePollTimer = new QTimer(app); // parent = app so it auto-deletes
themePollTimer->setInterval(3000);
bool lastDark = Settings::useDark();
QObject::connect(themePollTimer, &QTimer::timeout, [app, mainWindow, debugMode, &lastDark]() {
bool current = Settings::useDark();
if (current != lastDark) {
QDEBUG() << "[THEME POLL] Change detected:" << (current ? "Dark" : "Light");
applyTheme(current, debugMode, app, mainWindow);
lastDark = current;
}
});
themePollTimer->start();
if(debugMode) {
QDEBUG() << "[THEME POLL] Timer started - polling every 3 seconds";
}
}
#endif
int main(int argc, char *argv[])
{
int debugMode = DEBUGMODE;
if (QFile::exists("DEBUGMODE")) {
debugMode = 1;
}
if (QFile::exists(QDir::homePath() + "/DEBUGMODE")) {
debugMode = 1;
}
if (debugMode) {
QDEBUG() << "run-time debug mode";
} else {
qInstallMessageHandler(myMessageOutputDisable);
}
QDEBUG() << "number of arguments:" << argc;
QStringList args;
QDEBUGVAR(RAND_MAX);
QDEBUGVAR(QThread::idealThreadCount());
bool gatekeeper = false;
bool force_gui = false;
bool panels_only = false;
//Upon first launch, Apple will assign a psn number and
//pass it as a command line argument.
//This is most often during the gatekeeper stage.
//It only does this on first launch. I still need to catch it though.
if (argc == 2) {
gatekeeper = true;
QString arg2 = QString(argv[1]);
//only the help and version should trigger
if (arg2.contains("-h")) {
gatekeeper = false;
}
if (arg2.contains("help")) {
gatekeeper = false;
}
if (arg2.contains("-v")) {
gatekeeper = false;
}
if (arg2.contains("-l")) {
gatekeeper = false;
}
if (arg2.contains("version")) {
gatekeeper = false;
}
force_gui = arg2.contains("--gui");
panels_only = arg2.contains("--starterpanel");
}
//Create the settings folders if they do not exist
if(!QFile::exists("portablemode.txt")) {
QDir mdir;
mdir.mkpath(SETTINGSPATH);
}
//this is stored as base64 so smart git repos
//do not complain about shipping a private key.
QFile snakeoilKey("://ps.key.base64");
QFile snakeoilCert("://ps.pem.base64");
QFile snakeoilCA("://snakeoilca.crt.base64");
QString defaultCertFile = CERTFILE;
QString defaultKeyFile = KEYFILE;
QString defaultCAFile = CAFILE;
QFile certfile(defaultCertFile);
QFile keyfile(defaultKeyFile);
QFile cafile(defaultCAFile);
QByteArray decoded;
decoded.clear();
if (!certfile.exists()) {
if (snakeoilCert.open(QFile::ReadOnly)) {
decoded = QByteArray::fromBase64(snakeoilCert.readAll());
snakeoilCert.close();
}
if (certfile.open(QFile::WriteOnly)) {
certfile.write(decoded);
certfile.close();
}
}
if (!keyfile.exists()) {
if (snakeoilKey.open(QFile::ReadOnly)) {
decoded = QByteArray::fromBase64(snakeoilKey.readAll());
snakeoilKey.close();
}
if (keyfile.open(QFile::WriteOnly)) {
keyfile.write(decoded);
keyfile.close();
}
}
if (!cafile.exists()) {
if (snakeoilCA.open(QFile::ReadOnly)) {
decoded = QByteArray::fromBase64(snakeoilCA.readAll());
snakeoilCA.close();
}
if (cafile.open(QFile::WriteOnly)) {
cafile.write(decoded);
cafile.close();
}
}
QSettings settings(SETTINGSFILE, QSettings::IniFormat);
if(settings.value("leaveSessionOpen", "").toString().isEmpty()) {
settings.setValue("leaveSessionOpen", "false");
}
#if QT_VERSION < QT_VERSION_CHECK(5, 10, 0)
srand(time(NULL));
#endif
if (((argc > 1) && (!gatekeeper))
#ifdef CONSOLE_BUILD
|| true
#endif
) {
QCoreApplication a(argc, argv);
args = a.arguments();
QDEBUGVAR(args);
qRegisterMetaType<Packet>();
QDEBUG() << "Running command line mode.";
Packet sendPacket;
sendPacket.init();
QString outBuilder;
QTextStream o(&outBuilder);
QTextStream out(stdout);
QCoreApplication::setApplicationName("Packet Sender");
QString versionBuilder = QString("Version ") + SW_VERSION;
if (QSslSocket::supportsSsl()) {
versionBuilder.append(" / SSL:");
versionBuilder.append(QSslSocket::sslLibraryBuildVersionString());
} else {
versionBuilder.append(" / SSL library not found");
}
#ifdef GIT_CURRENT_SHA1
versionBuilder.append(" / Commit: " + QString(GIT_CURRENT_SHA1));
#endif
QCoreApplication::setApplicationVersion(versionBuilder);
QCommandLineParser parser;
parser.setApplicationDescription("Packet Sender is a Network UDP/TCP/SSL/HTTP Test Utility by NagleCode\nSee https://PacketSender.com/ for more information.");
parser.addHelpOption();
parser.addVersionOption();
// A boolean option with a single name (-p)
QCommandLineOption quietOption(QStringList() << "q" << "quiet", "Quiet mode. Only output received data.");
parser.addOption(quietOption);
QCommandLineOption hexOption(QStringList() << "x" << "hex", "Parse data-to-send as hex (default for TCP/UDP/SSL).");
parser.addOption(hexOption);
QCommandLineOption asciiOption(QStringList() << "a" << "ascii", "Parse data-to-send as mixed-ascii (default for http and GUI).");
parser.addOption(asciiOption);
QCommandLineOption pureAsciiOption(QStringList() << "A" << "ASCII", "Parse data-to-send as pure ascii (no \\xx translation).");
parser.addOption(pureAsciiOption);
// Command line server mode
QCommandLineOption serverOption(QStringList() << "l" << "listen", "Listen instead of send. Use bind options to specify port/IP. Otherwise, dynamic/All.");
parser.addOption(serverOption);
// Command line server response
QCommandLineOption responseOption(QStringList() << "r" << "response", "Server mode response data in mixed-ascii. Macro supported.", "ascii");
parser.addOption(responseOption);
// An option with a value
QCommandLineOption waitOption(QStringList() << "w" << "wait",
"Wait up to <milliseconds> for a response after sending. Zero means do not wait (Default).",
"ms");
parser.addOption(waitOption);
// An option with a value
QCommandLineOption fileOption(QStringList() << "f" << "file",
"Send contents of specified path. Max 10 MiB for UDP, 100 MiB for TCP/SSL.",
"path");
parser.addOption(fileOption);
// An option with a value
QCommandLineOption bindPortOption(QStringList() << "b" << "bind",
"Bind port. Default is 0 (dynamic).",
"port");
parser.addOption(bindPortOption);
QCommandLineOption bindIPv6Option(QStringList() << "6" << "ipv6", "Force IPv6. Same as -B \"::\". Default is IP:Any.");
parser.addOption(bindIPv6Option);
QCommandLineOption bindIPv4Option(QStringList() << "4" << "ipv4", "Force IPv4. Same as -B \"0.0.0.0\". Default is IP:Any.");
parser.addOption(bindIPv4Option);
QCommandLineOption bindIPOption(QStringList() << "B" << "bindip",
"Bind custom IP. Default is IP:Any.",
"IP");
parser.addOption(bindIPOption);
QCommandLineOption tcpOption(QStringList() << "t" << "tcp", "Send TCP (default).");
parser.addOption(tcpOption);
QCommandLineOption sslOption(QStringList() << "s" << "ssl", "Send SSL and ignore errors.");
parser.addOption(sslOption);
QCommandLineOption sslNoErrorOption(QStringList() << "S" << "SSL", "Send SSL and stop for errors.");
parser.addOption(sslNoErrorOption);
// A boolean option with multiple names (-f, --force)
QCommandLineOption udpOption(QStringList() << "u" << "udp", "Send UDP.");
parser.addOption(udpOption);
QCommandLineOption dtlsOption(QStringList() << "dtls", "Send DTLS.");
if(PacketNetwork::DTLSisSupported()) {
//parser.addOption(dtlsOption);
QDEBUG() << "DTLS is not yet supported on DTLS.";
}
// A single option with a value
QCommandLineOption httpOption(QStringList() << "http", "Send HTTP. Allowed values are GET (default) and POST", "http");
parser.addOption(httpOption);
// An option with a value
QCommandLineOption nameOption(QStringList() << "n" << "name",
"Send previously saved packet named <name>. Other options overrides saved packet parameters.",
"name");
parser.addOption(nameOption);
QCommandLineOption wolOption(QStringList() << "wol", "Send Wake-On-LAN / Magic Packet to <mac> and (optional) <port>.", "mac");
parser.addOption(wolOption);
// Intense Traffic Generator
QCommandLineOption bpsOption(QStringList() << "bps", "Intense traffic. Calculate rate based on value of bits per second.", "bps");
parser.addOption(bpsOption);
QCommandLineOption numOption(QStringList() << "num", "Intense traffic. Number of packets to send. Default unlimited.", "number");
parser.addOption(numOption);
QCommandLineOption rateOption(QStringList() << "rate", "Intense traffic. Rate. Ignored in bps option.", "Hertz");
parser.addOption(rateOption);
QCommandLineOption usdelayOption(QStringList() << "usdelay", "Intense traffic. Resend delay. Used if rate is 0. Ignored in bps option.", "microseconds");
parser.addOption(usdelayOption);
QCommandLineOption maxOption(QStringList() << "max", "Intense traffic. Run as fast as possible.");
parser.addOption(maxOption);
parser.addPositionalArgument("address", "Destination address/URL. Optional for saved packet.");
parser.addPositionalArgument("port", "Destination port/POST data. Optional for saved packet.");
parser.addPositionalArgument("data", "Data to send. Optional for saved packet.");
if (argc < 2) {
parser.showHelp();
return 0;
}
// Process the actual command line arguments given by the user
parser.process(a);
const QStringList args = parser.positionalArguments();
bool quiet = parser.isSet(quietOption);
bool hex = parser.isSet(hexOption);
bool mixedascii = parser.isSet(asciiOption);
bool ascii = parser.isSet(pureAsciiOption);
unsigned int wait = parser.value(waitOption).toUInt();
unsigned int bind = parser.value(bindPortOption).toUInt();
QHostAddress bindIP = QHostAddress(QHostAddress::Any);
QDEBUGVAR(parser.isSet(bindIPOption));
QString bindIPstr = "";
if(parser.isSet(bindIPOption)) {
bindIPstr = parser.value(bindIPOption).trimmed();
}
bool tcp = parser.isSet(tcpOption);
bool udp = parser.isSet(udpOption);
bool dtls = parser.isSet(dtlsOption);
if(dtls) {
if(!PacketNetwork::DTLSisSupported()) {
OUTIF() << "DTLS is not supported in this installation. ";
OUTPUT();
return -1;
}
}
bool ssl = parser.isSet(sslOption);
bool sslNoError = parser.isSet(sslNoErrorOption);
if(ssl) {
if(!QSslSocket::supportsSsl()) {
OUTIF() << "SSL is not supported in this installation. ";
OUTPUT();
return -1;
}
}
bool ipv6 = parser.isSet(bindIPv6Option);
bool ipv4 = parser.isSet(bindIPv4Option);
bool http = parser.isSet(httpOption);
bool wol = parser.isSet(wolOption);
bool server = parser.isSet(serverOption);
QString response = parser.value(responseOption);
QDEBUGVAR(response);
bool okbps = false;
bool okrate = false;
bool maxrate = parser.isSet(maxOption);
bool intense = parser.isSet(bpsOption) || parser.isSet(numOption)|| parser.isSet(rateOption) || parser.isSet(usdelayOption) || maxrate;
double bps = parser.value(bpsOption).toDouble(&okbps);
qint64 stopnum = parser.value(numOption).toULongLong();
double rate = parser.value(rateOption).toDouble(&okrate);
qint64 usdelay = parser.value(usdelayOption).toULongLong();
if(intense) {
if (maxrate) {
OUTIF() << "Maximum sending. Calculated " << QThread::idealThreadCount() << " send threads are supported.";
bps = 0;
rate = 0;
} else {
if (!okrate && !okbps) {
OUTIF() << "Warning: Invalid rate and/or bps. Intense traffic will free-run.";
bps = 0;
rate = 0;
}
}
}
if (sslNoError) ssl = true;
QString name = parser.value(nameOption);
QString httpMethod = parser.value(httpOption).trimmed().toUpper();
QString filePath = parser.value(fileOption);
QString address = "";
QString addressOriginal = "";
unsigned int port = 0;
int argssize = args.size();
QDEBUGVAR(argssize);
QString data, dataString;
data.clear();
dataString.clear();
if (argssize >= 1) {
address = args[0];
}
if(wol) {
QString targetMAC = parser.value(wolOption).trimmed().toUpper();
if (argssize >= 1) {
port = QString(args[0]).toUInt();
}
if(port < 1) {
port = 7;
}
Packet wolPkt = Packet::generateWakeOnLAN(targetMAC, port);
if(wolPkt.errorString.isEmpty()) {
OUTIF() << "Sending broadcast Wake-On-LAN to target: " + targetMAC + " on port " + QString::number(port);
udp = true;
tcp = false;
ssl = false;
http = false;
address = wolPkt.toIP;
data = wolPkt.hexString;
} else {
OUTIF() << "Error generating Wake-On-LAN: " + wolPkt.errorString;
OUTPUT();
return -1;
}
}
if(http) {
if(parser.isSet(httpOption)) {
if(httpMethod != "GET" && httpMethod != "POST") {
OUTIF() << "Error: supported HTTP methods are GET and POST. Specified: " << httpMethod;
filePath.clear();
OUTPUT();
return -1;
}
if(name.isEmpty()) {
if(address.isEmpty()) {
OUTIF() << "Error: URL is required after HTTP method is no name is supplied.";
filePath.clear();
OUTPUT();
return -1;
}
}
if(httpMethod == "POST") {
if(argssize < 2) {
OUTIF() << "Error: data is required after specifying POST.";
filePath.clear();
OUTPUT();
return -1;
} else {
data = args[1];
}
}
}
} else {
if (argssize >= 2) {
port = args[1].toUInt();
}
if (argssize >= 3) {
data = (args[2]);
}
}
bool multicast = PacketNetwork::isMulticast(address);
//check for invalid options..
if (argssize > 3) {
OUTIF() << "Warning: Extra parameters detected. Try surrounding your data with quotes.";
}
if (hex && mixedascii) {
OUTIF() << "Warning: both hex and pure ascii set. Defaulting to hex.";
mixedascii = false;
}
if (hex && ascii) {
OUTIF() << "Warning: both hex and pure ascii set. Defaulting to hex.";
ascii = false;
}
if (mixedascii && ascii) {
OUTIF() << "Warning: both mixed ascii and pure ascii set. Defaulting to pure ascii.";
mixedascii = false;
}
if(multicast) {
OUTIF() << "Info: Joining multicast address forces UDP and IPv4.";
udp = true;
tcp = false;
ssl = false;
ipv6 = false;
ipv4 = true;
http = false;
dtls = false;
}
if (tcp && udp) {
OUTIF() << "Warning: both TCP and UDP set. Defaulting to TCP.";
udp = false;
dtls = false;
}
if (tcp && dtls) {
OUTIF() << "Warning: both TCP and DTLS set. Defaulting to TCP.";
udp = false;
dtls = false;
}
if (tcp && ssl) {
OUTIF() << "Warning: both TCP and SSL set. Defaulting to SSL.";
tcp = false;
}
if (udp && dtls) {
OUTIF() << "Warning: both UDP and DTLS set. Defaulting to DTLS.";
udp = false;
}
if (http && tcp) {
OUTIF() << "Warning: both HTTP and TCP set. Defaulting to HTTP.";
tcp = false;
}
if (!filePath.isEmpty() && !QFile::exists(filePath)) {
OUTIF() << "Error: specified path " << filePath << " does not exist.";
filePath.clear();
OUTPUT();
return -1;
}
if (!bindIPstr.isEmpty()) {
QHostAddress address(bindIPstr);
if ((QAbstractSocket::IPv4Protocol == address.protocol() ) || (QAbstractSocket::IPv6Protocol == address.protocol())
) {
OUTIF() << "Binding to custom IP " << bindIPstr;
bindIP = address;
} else {
OUTIF() << "Error: " << bindIPstr << " is an invalid address.";
OUTPUT();
return -1;
}
}
if(ipv4 && ipv6) {
OUTIF() << "Warning: both ipv4 and ipv6 are set. Defaulting to ipv4.";
ipv6 = false;
}
if(!bindIPstr.isEmpty() && ipv4) {
OUTIF() << "Warning: both ipv4 and custom IP bind are set. Defaulting to custom IP.";
ipv4 = false;
}
if(!bindIPstr.isEmpty() && ipv6) {
OUTIF() << "Warning: both ipv6 and custom IP bind are set. Defaulting to custom IP.";
ipv6 = false;
}
if(ipv4) {
QDEBUG() << "bindIP set to IPv4";
bindIP = QHostAddress(QHostAddress::AnyIPv4);
}
if(ipv6) {
QDEBUG() << "bindIP set to IPv6";
bindIP = QHostAddress(QHostAddress::AnyIPv6);
}
//bind is now default 0
if (!bind && parser.isSet(bindPortOption)) {
OUTIF() << "Warning: Binding to port zero is dynamic.";
}
if (!port && name.isEmpty() && !http && !server) {
OUTIF() << "Warning: Sending to port zero.";
}
//set default choices
if (!hex && !ascii && !mixedascii) {
if(http) {
mixedascii = true;
} else {
hex = true;
}
}
if (!tcp && !udp && !ssl && !http && !dtls) {
tcp = true;
}
if ((tcp || ssl || dtls || http) && intense) {
OUTIF() << "Warning: Intense Traffic is UDP only.";
}
if(intense) {
udp = true;
tcp = false;
ssl = false;
http = false;
dtls = false;
}
QSettings settings(SETTINGSFILE, QSettings::IniFormat);
bool translateMacroSend = settings.value("translateMacroSendCheck", true).toBool();
if(server) {
bool bindResult = false;
MainPacketReceiver * receiver = new MainPacketReceiver(nullptr);
if(!response.isEmpty()) {
Packet replyPacket;
QDEBUGVAR(response);
replyPacket.hexString = Packet::ASCIITohex(response);
receiver->responsePacket(replyPacket);
if(!replyPacket.hexString.isEmpty()) {
OUTIF() << "Loading response packet.";
}
}
QString bindIP = "any";
if(!bindIPstr.isEmpty()) {
bindIP = bindIPstr;
}
QString bindmode = "";
if(dtls) {
// TODO: how to set up DTLS server?
} else {
if(udp) {
bindmode = "UDP";
QUdpSocket sock;
bindResult = receiver->initUDP(bindIP, bind);
bind = receiver->udpSocket->localPort();
bindIP = receiver->udpSocket->localAddress().toString();
} else {
if(tcp) {
bindmode = "TCP";
}
if(ssl) {
bindmode = "SSL";
}
bindResult = receiver->initSSL(bindIP, bind, ssl);
bind = receiver->tcpServer->serverPort();
bindIP = receiver->tcpServer->serverAddress().toString();
}
}
bindIP = bindIP.toUpper();
if(bindResult) {
OUTIF() << bindmode << " Server started on " << bindIP << ":" << bind;
OUTIF() << "Use ctrl+c to exit.";
OUTPUT();
a.exec();
} else {
OUTIF() << "Failed to bind " << bindmode << " " << bindIP << ":" << bind;
if(bind < 1024) {
OUTIF() << "Note that lower port numbers may require admin/sudo";
}
OUTPUT();
}
OUTIF() << "Done with server mode. ";
OUTPUT();
return 0;
}
//Create the packet to send.
if (!name.isEmpty()) {
sendPacket = Packet::fetchFromDB(name);
if(translateMacroSend && (!intense)) {
QString data = Packet::macroSwap(sendPacket.asciiString());
sendPacket.hexString = Packet::ASCIITohex(data);
}
if (sendPacket.name.isEmpty()) {
OUTIF() << "Error: Saved packet \"" << name << "\" not found.";
OUTPUT();
return -1;
} else {
QDEBUGVAR(sendPacket.name);
ssl = sendPacket.isSSL();
tcp = sendPacket.isTCP();
udp = sendPacket.isUDP();
dtls = sendPacket.isDTLS();
http = sendPacket.isHTTP() || sendPacket.isHTTPS();
if (data.isEmpty() && (!http)) {
data = sendPacket.hexString;
hex = true;
ascii = false;
mixedascii = false;
}
if (!port) {
port = sendPacket.port;
}
if (address.isEmpty()) {
address = sendPacket.toIP;
}
if (parser.isSet(udpOption)) {
udp = true;
ssl = false;
tcp = false;
dtls = false;
}
if (parser.isSet(tcpOption)) {
tcp = true;
http = false;
udp = false;
dtls = false;
}
if (parser.isSet(sslOption)) {
ssl = true;
tcp = true;
dtls = false;
http = false;
}
if (intense) {
udp = true;
ssl = false;
tcp = false;
http = false;
dtls = false;
}
}
}
if (!parser.isSet(bindPortOption)) {
bind = 0;
}
if (!filePath.isEmpty() && QFile::exists(filePath)) {
QFile dataFile(filePath);
if (dataFile.open(QFile::ReadOnly)) {
if (tcp || ssl || http) {
QByteArray dataArray = dataFile.read(1024 * 1024 * 100);;
dataString = Packet::byteArrayToHex(dataArray);
} else {
QByteArray dataArray = dataFile.read(1024 * 1024 * 10);
dataString = Packet::byteArrayToHex(dataArray);
}
dataFile.close();
//data format is raw.
ascii = 0;
hex = 0;
mixedascii = 0;
}
}
QDEBUGVAR(argssize);
QDEBUGVAR(quiet);
QDEBUGVAR(hex);
QDEBUGVAR(mixedascii);
QDEBUGVAR(ascii);
QDEBUGVAR(address);
QDEBUGVAR(port);
QDEBUGVAR(wait);
QDEBUGVAR(bind);
QDEBUGVAR(bindIP);
QDEBUGVAR(ipv4);
QDEBUGVAR(ipv6);
QDEBUGVAR(tcp);
QDEBUGVAR(udp);
QDEBUGVAR(dtls);