-
-
Notifications
You must be signed in to change notification settings - Fork 350
Expand file tree
/
Copy pathTLuaInterpreter.cpp
More file actions
8303 lines (7498 loc) · 350 KB
/
TLuaInterpreter.cpp
File metadata and controls
8303 lines (7498 loc) · 350 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
/***************************************************************************
* Copyright (C) 2008-2013 by Heiko Koehn - KoehnHeiko@googlemail.com *
* Copyright (C) 2013-2023, 2025-2026 by Stephen Lyons *
* - slysven@virginmedia.com *
* Copyright (C) 2014-2017 by Ahmed Charles - acharles@outlook.com *
* Copyright (C) 2016 by Eric Wallace - eewallace@gmail.com *
* Copyright (C) 2016 by Chris Leacy - cleacy1972@gmail.com *
* Copyright (C) 2016-2018 by Ian Adkins - ieadkins@gmail.com *
* Copyright (C) 2017 by Chris Reid - WackyWormer@hotmail.com *
* Copyright (C) 2022-2025 by Lecker Kebap - Leris@mudlet.org *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include "TLuaInterpreter.h"
#include "EAction.h"
#include "Host.h"
#include "TAlias.h"
#include "TCommandLine.h"
#include "TConsole.h"
#include "TDebug.h"
#include "TEvent.h"
#include "TFlipButton.h"
#include "TForkedProcess.h"
#include "TGameDetails.h"
#include "TLabel.h"
#include "TMap.h"
#include "TMapLabel.h"
#include "TRoomDB.h"
#include "TTextEdit.h"
#include "TEncodingHelper.h"
#include "TTimer.h"
#include "dlgComposer.h"
#include "dlgIRC.h"
#include "dlgMapper.h"
#include "dlgModuleManager.h"
#include "dlgTriggerEditor.h"
#include "mudlet.h"
#if defined(INCLUDE_3DMAPPER)
#include "glwidget_integration.h"
#endif
#include <math.h>
#include <QtConcurrent>
#include <QCollator>
#include <QCoreApplication>
#include <QDesktopServices>
#include <QFileDialog>
#include <QTableWidget>
#include <QToolTip>
#include <QFileInfo>
#include <QVector>
#include <limits>
using namespace std::chrono_literals;
extern "C" {
int luaopen_yajl(lua_State*);
}
// No documentation available in wiki - internal function
static bool isMain(const QString& name)
{
if (name.isEmpty()) {
return true;
}
if (!name.compare(qsl("main"))) {
return true;
}
return false;
}
static const char* bad_cmdline_type = "%s: bad argument #%d type (command line name as string expected, got %s)!";
static const char* bad_cmdline_value = "command line \"%s\" not found";
const QString TLuaInterpreter::csmInvalidRoomID{qsl("number %1 is not a valid roomID")};
const QString TLuaInterpreter::csmInvalidStopWatchID{qsl("stopwatch with ID %1 not found")};
const QString TLuaInterpreter::csmInvalidRedValue{qsl("red value %1 needs to be between 0-255")};
const QString TLuaInterpreter::csmInvalidGreenValue{qsl("green value %1 needs to be between 0-255")};
const QString TLuaInterpreter::csmInvalidBlueValue{qsl("blue value %1 needs to be between 0-255")};
const QString TLuaInterpreter::csmInvalidAlphaValue{qsl("alpha value %1 needs to be between 0-255")};
const QString TLuaInterpreter::csmInvalidExitRoomID{qsl("number %1 is not a valid exit roomID")};
const QString TLuaInterpreter::csmInvalidItemID{qsl("item ID as %1 does not seem to be parseable as a positive integer")};
const QString TLuaInterpreter::csmInvalidAreaID{qsl("number %1 is not a valid area id")};
const QString TLuaInterpreter::csmInvalidAreaName{qsl("string '%1' is not a valid area name")};
#define CMDLINE_NAME(ARG_L, ARG_pos) \
({ \
int pos_ = (ARG_pos); \
if (!lua_isstring(ARG_L, pos_)) { \
lua_pushfstring(ARG_L, bad_cmdline_type, __FUNCTION__, pos_, luaL_typename(ARG_L, pos_)); \
return lua_error(ARG_L); \
} \
lua_tostring(ARG_L, pos_); \
})
#define COMMANDLINE(ARG_L, ARG_name) \
({ \
const QString& name_ = (ARG_name); \
auto console_ = getHostFromLua(ARG_L).mpConsole; \
auto cmdLine_ = isMain(name_) ? &*console_->mpCommandLine : console_->mSubCommandLineMap.value(name_); \
if (!cmdLine_) { \
lua_pushnil(ARG_L); \
lua_pushfstring(ARG_L, bad_cmdline_value, name_.toUtf8().constData()); \
return 2; \
} \
cmdLine_; \
})
// variable names within these macros have trailing underscores because in
// at least one case, masking an existing variable with the new one confused
// GCC, leading to a crash.
TLuaInterpreter::TLuaInterpreter(Host* pH, const QString& hostName, int id)
: mpHost(pH)
, hostName(hostName)
, mHostID(id)
, purgeTimer(this)
, mpFileDownloader(new QNetworkAccessManager(this))
, mpFileSystemWatcher(new QFileSystemWatcher(this))
{
connect(&purgeTimer, &QTimer::timeout, this, &TLuaInterpreter::slot_purge);
connect(mpFileDownloader, &QNetworkAccessManager::finished, this, &TLuaInterpreter::slot_httpRequestFinished);
connect(mpFileSystemWatcher, &QFileSystemWatcher::fileChanged, this, &TLuaInterpreter::slot_pathChanged);
connect(mpFileSystemWatcher, &QFileSystemWatcher::directoryChanged, this, &TLuaInterpreter::slot_pathChanged);
initLuaGlobals();
purgeTimer.start(2s);
}
TLuaInterpreter::~TLuaInterpreter()
{
lua_close(pGlobalLua);
}
// No documentation available in wiki - internal function
// Replaces a check like this:
// if (!lua_isboolean(L, 14)) {
// lua_pushfstring(L,
// "createMapLabel: bad argument #14 type (showOnTop as boolean is optional, got %s!)",
// luaL_typename(L, 14));
// return lua_error(L);
// }
// bool showOnTop = lua_toboolean(L, 14);
//
// With reduced repetition like that:
// bool showOnTop = getVerifiedBool(L, "createMapLabel", 14, "showOnTop", true);
//
// The "isOptional" parameter is optional but modifies the error message to say
// that an argument is optional and it will default to not-optional parameters!
// HOWEVER it does not actually handle the absence of an argument that is
// supposed to BE optional - that has to be done by the caller before it
// makes the call... 8-P
//
// See also: getVerifiedString, getVerifiedInt, getVerifiedFloat, errorArgumentType
bool TLuaInterpreter::getVerifiedBool(lua_State* L, const char* functionName, const int pos, const char* publicName, const bool isOptional)
{
if (!lua_isboolean(L, pos)) {
errorArgumentType(L, functionName, pos, publicName, "boolean", isOptional);
lua_error(L);
Q_UNREACHABLE();
}
return lua_toboolean(L, pos);
}
// No documentation available in wiki - internal function
// See also: getVerifiedBool
/*static*/ std::pair<bool, QString> TLuaInterpreter::getVerifiedStringOrInteger(lua_State* L, const char* functionName, const int pos, const char* publicName, const bool isOptional)
{
if (lua_type(L, pos) == LUA_TNUMBER) {
// use lua_tonumber(...) and round because lua_tointeger(...) can return
// oversized values (long long int?) on Windows which do not always fit
// into an int:
return {true, QString::number(qRound(lua_tonumber(L, pos)))};
}
if (lua_type(L, pos) == LUA_TSTRING) {
return {false, lua_tostring(L, pos)};
}
errorArgumentType(L, functionName, pos, publicName, "string or integer", isOptional);
lua_error(L);
Q_UNREACHABLE();
}
// No documentation available in wiki - internal function
// See also: getVerifiedBool
QString TLuaInterpreter::getVerifiedString(lua_State* L, const char* functionName, const int pos, const char* publicName, const bool isOptional)
{
if (!lua_isstring(L, pos)) {
errorArgumentType(L, functionName, pos, publicName, "string", isOptional);
lua_error(L);
Q_UNREACHABLE();
}
return lua_tostring(L, pos);
}
// No documentation available in wiki - internal function
// See also: getVerifiedBool
int TLuaInterpreter::getVerifiedInt(lua_State* L, const char* functionName, const int pos, const char* publicName, const bool isOptional)
{
if (!lua_isnumber(L, pos)) {
errorArgumentType(L, functionName, pos, publicName, "number", isOptional);
lua_error(L);
Q_UNREACHABLE();
}
// lua_tointeger(...) returns a ptrdiff_t which on 64-bit platforms is a
// signed 64 bit value, which is usually larger than an "int" a.k.a. an
// int32_t:
// We have to error out here otherwise we have to restructure every usage
// to handle such an over/under-flow - at least with a change to a
// std::optional<int>...
auto const result = lua_tointeger(L, pos);
if (result < std::numeric_limits<int>::min() || result > std::numeric_limits<int>::max()) {
lua_pushfstring(L, "%s: integer over/under-flow in argument #%d (%s as an integer, provided value %s is outside of valid range %d to %d!)",
functionName, pos, publicName,
lua_tostring(L, pos),
std::numeric_limits<int>::min(),
std::numeric_limits<int>::max());
lua_error(L);
Q_UNREACHABLE();
}
return static_cast<int>(result);
}
// No documentation available in wiki - internal function
// See also: getVerifiedBool
float TLuaInterpreter::getVerifiedFloat(lua_State* L, const char* functionName, const int pos, const char* publicName, const bool isOptional)
{
if (!lua_isnumber(L, pos)) {
errorArgumentType(L, functionName, pos, publicName, "number", isOptional);
lua_error(L);
Q_UNREACHABLE();
}
return static_cast<float>(lua_tonumber(L, pos));
}
// No documentation available in wiki - internal function
// See also: getVerifiedBool
double TLuaInterpreter::getVerifiedDouble(lua_State* L, const char* functionName, const int pos, const char* publicName, const bool isOptional)
{
if (!lua_isnumber(L, pos)) {
errorArgumentType(L, functionName, pos, publicName, "number", isOptional);
lua_error(L);
Q_UNREACHABLE();
}
return lua_tonumber(L, pos);
}
// No documentation available in wiki - internal function
// Raises a Lua error in case of an API usage mistake
// See also: getVerifiedBool, warnArgumentValue
void TLuaInterpreter::errorArgumentType(lua_State* L, const char* functionName, const int pos, const char* publicName, const char* publicType, const bool isOptional)
{
if (isOptional) {
lua_pushfstring(L, "%s: bad argument #%d type (%s as %s is optional, got %s!)", functionName, pos, publicName, publicType, luaL_typename(L, pos));
} else {
lua_pushfstring(L, "%s: bad argument #%d type (%s as %s expected, got %s!)", functionName, pos, publicName, publicType, luaL_typename(L, pos));
}
}
// No documentation available in wiki - internal function
// returns nil+msg in case of a data mistake, for example a missing room. Should not raise a Lua error
// See also: announceWrongArgumentType
int TLuaInterpreter::warnArgumentValue(lua_State* L, const char* functionName, const QString& message, const bool useFalseInsteadofNil)
{
if (Q_LIKELY(!useFalseInsteadofNil)) {
lua_pushnil(L);
} else {
lua_pushboolean(L, false);
}
lua_pushstring(L, message.toUtf8().constData());
if (mudlet::smDebugMode) {
auto& host = getHostFromLua(L);
TDebug(Qt::white, QColorConstants::Svg::orange) << "Lua: " << functionName << ": " << message << "\n" >> &host;
}
return 2;
}
// No documentation available in wiki - internal function
int TLuaInterpreter::warnArgumentValue(lua_State* L, const char* functionName, const char* message, const bool useFalseInsteadofNil)
{
if (Q_LIKELY(!useFalseInsteadofNil)) {
lua_pushnil(L);
} else {
lua_pushboolean(L, false);
}
lua_pushstring(L, message);
if (mudlet::smDebugMode) {
auto& host = getHostFromLua(L);
TDebug(Qt::white, QColorConstants::Svg::orange) << "Lua: " << functionName << ": " << message << "\n" >> &host;
}
return 2;
}
// No documentation available in wiki - internal function
// Raises additional sysDownloadError Events on failure to process
// the local file, the second argument is "failureToWriteLocalFile" and besides
// the file to be written being the third argument (as multiple downloads are
// supported) a fourth argument gives the local file problem, one of:
// * "unableToOpenLocalFileForWriting"
// * "unableToWriteLocalFile"
// or a QFile::errorString() for the issue at hand
// Upon success we now give an additional (third value) which gives the number
// of bytes written into the downloaded file.
void TLuaInterpreter::slot_httpRequestFinished(QNetworkReply* reply)
{
Host* pHost = mpHost;
if (!pHost) {
qWarning() << qsl("TLuaInterpreter::slot_httpRequestFinished(...) ERROR: NULL Host pointer!");
return;
}
if (reply->error() != QNetworkReply::NoError) {
TEvent event{};
QString localFileName;
switch (reply->operation()) {
case QNetworkAccessManager::PostOperation:
event.mArgumentList << qsl("sysPostHttpError");
event.mArgumentTypeList << ARGUMENT_TYPE_STRING;
event.mArgumentList << reply->errorString();
event.mArgumentTypeList << ARGUMENT_TYPE_STRING;
event.mArgumentList << reply->url().toString();
event.mArgumentTypeList << ARGUMENT_TYPE_STRING;
break;
case QNetworkAccessManager::PutOperation:
event.mArgumentList << qsl("sysPutHttpError");
event.mArgumentTypeList << ARGUMENT_TYPE_STRING;
event.mArgumentList << reply->errorString();
event.mArgumentTypeList << ARGUMENT_TYPE_STRING;
event.mArgumentList << reply->url().toString();
event.mArgumentTypeList << ARGUMENT_TYPE_STRING;
break;
case QNetworkAccessManager::GetOperation:
localFileName = downloadMap.value(reply);
event.mArgumentList << (localFileName.isEmpty() ? qsl("sysGetHttpError") : qsl("sysDownloadError"));
event.mArgumentTypeList << ARGUMENT_TYPE_STRING;
event.mArgumentList << reply->errorString();
event.mArgumentTypeList << ARGUMENT_TYPE_STRING;
if (!localFileName.isEmpty()) {
event.mArgumentList << localFileName;
event.mArgumentTypeList << ARGUMENT_TYPE_STRING;
}
event.mArgumentList << reply->url().toString();
event.mArgumentTypeList << ARGUMENT_TYPE_STRING;
downloadMap.remove(reply);
break;
case QNetworkAccessManager::DeleteOperation:
event.mArgumentList << qsl("sysDeleteHttpError");
event.mArgumentTypeList << ARGUMENT_TYPE_STRING;
event.mArgumentList << reply->errorString();
event.mArgumentTypeList << ARGUMENT_TYPE_STRING;
event.mArgumentList << reply->url().toString();
event.mArgumentTypeList << ARGUMENT_TYPE_STRING;
break;
case QNetworkAccessManager::HeadOperation:
break;
case QNetworkAccessManager::CustomOperation:
event.mArgumentList << qsl("sysCustomHttpError");
event.mArgumentTypeList << ARGUMENT_TYPE_STRING;
event.mArgumentList << reply->errorString();
event.mArgumentTypeList << ARGUMENT_TYPE_STRING;
event.mArgumentList << reply->url().toString();
event.mArgumentTypeList << ARGUMENT_TYPE_STRING;
event.mArgumentList << reply->request().attribute(QNetworkRequest::CustomVerbAttribute).toString();
event.mArgumentTypeList << ARGUMENT_TYPE_STRING;
break;
case QNetworkAccessManager::UnknownOperation:
break;
}
event.mArgumentList << QString::number(createHttpResponseTable(reply));
event.mArgumentTypeList << ARGUMENT_TYPE_TABLE;
reply->deleteLater();
downloadMap.remove(reply);
pHost->raiseEvent(event);
return;
}
handleHttpOK(reply);
}
// No documentation available in wiki - internal function
void TLuaInterpreter::handleHttpOK(QNetworkReply* reply)
{
TEvent event{};
Host* pHost = mpHost;
if (!pHost) {
return;
}
switch (reply->operation()) {
case QNetworkAccessManager::HeadOperation:
break;
case QNetworkAccessManager::DeleteOperation:
event.mArgumentList << qsl("sysDeleteHttpDone");
event.mArgumentTypeList << ARGUMENT_TYPE_STRING;
event.mArgumentList << reply->url().toString();
event.mArgumentTypeList << ARGUMENT_TYPE_STRING;
event.mArgumentList << QString(reply->readAll());
event.mArgumentTypeList << ARGUMENT_TYPE_STRING;
break;
case QNetworkAccessManager::CustomOperation:
event.mArgumentList << QString("sysCustomHttpDone");
event.mArgumentTypeList << ARGUMENT_TYPE_STRING;
event.mArgumentList << reply->url().toString();
event.mArgumentTypeList << ARGUMENT_TYPE_STRING;
event.mArgumentList << QString(reply->readAll());
event.mArgumentTypeList << ARGUMENT_TYPE_STRING;
event.mArgumentList << reply->request().attribute(QNetworkRequest::CustomVerbAttribute).toString();
event.mArgumentTypeList << ARGUMENT_TYPE_STRING;
break;
case QNetworkAccessManager::UnknownOperation:
break;
case QNetworkAccessManager::PostOperation:
event.mArgumentList << qsl("sysPostHttpDone");
event.mArgumentTypeList << ARGUMENT_TYPE_STRING;
event.mArgumentList << reply->url().toString();
event.mArgumentTypeList << ARGUMENT_TYPE_STRING;
event.mArgumentList << QString(reply->readAll());
event.mArgumentTypeList << ARGUMENT_TYPE_STRING;
break;
case QNetworkAccessManager::PutOperation:
event.mArgumentList << qsl("sysPutHttpDone");
event.mArgumentTypeList << ARGUMENT_TYPE_STRING;
event.mArgumentList << reply->url().toString();
event.mArgumentTypeList << ARGUMENT_TYPE_STRING;
event.mArgumentList << QString(reply->readAll());
event.mArgumentTypeList << ARGUMENT_TYPE_STRING;
break;
case QNetworkAccessManager::GetOperation:
const QString localFileName = downloadMap.value(reply);
downloadMap.remove(reply);
// If the user did not give us a file path, we're not going to
// consider this an error, we're just going to attach the reply
// directly. Another way this could happen is the user made a POST
// request, and it redirected to a GET. In the case of POST requests,
// we don't ask the user for a file path.
if (localFileName.isEmpty()) {
event.mArgumentList << QLatin1String("sysGetHttpDone");
event.mArgumentTypeList << ARGUMENT_TYPE_STRING;
event.mArgumentList << reply->url().toString();
event.mArgumentTypeList << ARGUMENT_TYPE_STRING;
event.mArgumentList << QString(reply->readAll());
event.mArgumentTypeList << ARGUMENT_TYPE_STRING;
break;
}
QSaveFile localFile(localFileName);
if (!localFile.open(QFile::WriteOnly)) {
event.mArgumentList << QLatin1String("sysDownloadError");
event.mArgumentTypeList << ARGUMENT_TYPE_STRING;
event.mArgumentList << QLatin1String("Couldn't save to the destination file");
event.mArgumentTypeList << ARGUMENT_TYPE_STRING;
event.mArgumentList << localFileName;
event.mArgumentTypeList << ARGUMENT_TYPE_STRING;
event.mArgumentList << QLatin1String("Couldn't open the destination file for writing (permission errors?)");
event.mArgumentTypeList << ARGUMENT_TYPE_STRING;
break;
}
qint64 const bytesWritten = localFile.write(reply->readAll());
if (bytesWritten == -1) {
event.mArgumentList << QLatin1String("sysDownloadError");
event.mArgumentTypeList << ARGUMENT_TYPE_STRING;
event.mArgumentList << QLatin1String("Couldn't save to the destination file");
event.mArgumentTypeList << ARGUMENT_TYPE_STRING;
event.mArgumentList << localFileName;
event.mArgumentTypeList << ARGUMENT_TYPE_STRING;
event.mArgumentList << QLatin1String("Couldn't write downloaded content into the destination file");
event.mArgumentTypeList << ARGUMENT_TYPE_STRING;
break;
}
if (!localFile.commit()) {
qDebug() << "TTLuaInterpreter::handleHttpOK: error saving downloaded file: " << localFile.errorString();
}
if (localFile.error() == QFile::NoError) {
event.mArgumentList << QLatin1String("sysDownloadDone");
event.mArgumentTypeList << ARGUMENT_TYPE_STRING;
event.mArgumentList << localFileName;
event.mArgumentTypeList << ARGUMENT_TYPE_STRING;
event.mArgumentList << QString::number(bytesWritten);
event.mArgumentTypeList << ARGUMENT_TYPE_NUMBER;
} else {
event.mArgumentList << QLatin1String("sysDownloadError");
event.mArgumentTypeList << ARGUMENT_TYPE_STRING;
event.mArgumentList << QLatin1String("Couldn't save to the destination file");
event.mArgumentTypeList << ARGUMENT_TYPE_STRING;
event.mArgumentList << localFileName;
event.mArgumentTypeList << ARGUMENT_TYPE_STRING;
event.mArgumentList << localFile.errorString();
event.mArgumentTypeList << ARGUMENT_TYPE_STRING;
}
break;
}
event.mArgumentList << QString::number(createHttpResponseTable(reply));
event.mArgumentTypeList << ARGUMENT_TYPE_TABLE;
reply->deleteLater();
pHost->raiseEvent(event);
}
// No documentation available in wiki - internal function
// No documentation available in wiki - internal function
void TLuaInterpreter::slot_pathChanged(const QString& path)
{
// According to QtDocs it is possible that some editors will delete old file and create new one on edits
// Therefore it is required to add file to watches again
if (!mpFileSystemWatcher->files().contains(path) && QFile::exists(path)) {
mpFileSystemWatcher->addPath(path);
}
TEvent event{};
event.mArgumentList << QLatin1String("sysPathChanged");
event.mArgumentTypeList << ARGUMENT_TYPE_STRING;
event.mArgumentList << path;
event.mArgumentTypeList << ARGUMENT_TYPE_STRING;
mpHost->raiseEvent(event);
}
// No documentation available in wiki - internal function
void TLuaInterpreter::slot_deleteSender(int exitCode, QProcess::ExitStatus exitStatus)
{
Q_UNUSED(exitCode)
Q_UNUSED(exitStatus)
objectsToDelete.append(sender());
}
// No documentation available in wiki - internal function
void TLuaInterpreter::slot_purge()
{
while (!objectsToDelete.isEmpty()) {
delete objectsToDelete.takeFirst();
}
}
// No documentation available in wiki - internal function
int TLuaInterpreter::Wait(lua_State* L)
{
const int n = lua_gettop(L);
if (n != 1) {
lua_pushstring(L, "Wait: wrong number of arguments");
return lua_error(L);
}
const int luaSleepMsec = getVerifiedInt(L, __func__, 1, "sleep time in msec");
msleep(luaSleepMsec);
return 0;
}
// No documentation available in wiki - internal function
// dirToString will now catch and validate pretty much any string that could
// be a normal direction in a case insensitive manner and convert it to a
// standard value (one of: "n", "ne", ..., "nw", "up", "down", "in" or
// "out") but leave anything else as entered; OR convert a direction code as
// a number from 1 to 12 to those same standard direction strings.
// This is intended as a temporary step until a uniform means of specifying
// both "normal" and "special" exits for all lua commands that take exit
// directions as arguments in an unambiguous manner can be formulated - though
// to maintain backwards compatibility the current functions will remain even
// if they get marked out as being deprecated.
QString TLuaInterpreter::dirToString(lua_State* L, int position)
{
if (lua_isnumber(L, position)) {
qint64 const dirNum = static_cast<qint64>(lua_tonumber(L, position));
switch (dirNum) {
// breaks not needed - all handled cases end in a return!
case 1:
return qsl("n");
case 2:
return qsl("ne");
case 3:
return qsl("nw");
case 4:
return qsl("e");
case 5:
return qsl("w");
case 6:
return qsl("s");
case 7:
return qsl("se");
case 8:
return qsl("sw");
case 9:
return qsl("up");
case 10:
return qsl("down");
case 11:
return qsl("in");
case 12:
return qsl("out");
default:
return QString();
}
} else if (lua_isstring(L, position)) {
QString direction{lua_tostring(L, position)};
if (!direction.compare(QLatin1String("n"), Qt::CaseInsensitive) || !direction.compare(QLatin1String("north"), Qt::CaseInsensitive)) {
return QLatin1String("n");
} else if (!direction.compare(QLatin1String("e"), Qt::CaseInsensitive) || !direction.compare(QLatin1String("east"), Qt::CaseInsensitive)) {
return QLatin1String("e");
} else if (!direction.compare(QLatin1String("s"), Qt::CaseInsensitive) || !direction.compare(QLatin1String("south"), Qt::CaseInsensitive)) {
return QLatin1String("s");
} else if (!direction.compare(QLatin1String("w"), Qt::CaseInsensitive) || !direction.compare(QLatin1String("west"), Qt::CaseInsensitive)) {
return QLatin1String("w");
} else if (!direction.compare(QLatin1String("u"), Qt::CaseInsensitive) || !direction.compare(QLatin1String("up"), Qt::CaseInsensitive)) {
return QLatin1String("up");
} else if (!direction.compare(QLatin1String("d"), Qt::CaseInsensitive) || !direction.compare(QLatin1String("down"), Qt::CaseInsensitive)) {
return QLatin1String("down");
} else if (!direction.compare(QLatin1String("ne"), Qt::CaseInsensitive) || !direction.compare(QLatin1String("northeast"), Qt::CaseInsensitive)
|| !direction.compare(QLatin1String("north-east"), Qt::CaseInsensitive)) {
return QLatin1String("ne");
} else if (!direction.compare(QLatin1String("se"), Qt::CaseInsensitive) || !direction.compare(QLatin1String("southeast"), Qt::CaseInsensitive)
|| !direction.compare(QLatin1String("south-east"), Qt::CaseInsensitive)) {
return QLatin1String("se");
} else if (!direction.compare(QLatin1String("sw"), Qt::CaseInsensitive) || !direction.compare(QLatin1String("southwest"), Qt::CaseInsensitive)
|| !direction.compare(QLatin1String("south-west"), Qt::CaseInsensitive)) {
return QLatin1String("sw");
} else if (!direction.compare(QLatin1String("nw"), Qt::CaseInsensitive) || !direction.compare(QLatin1String("northwest"), Qt::CaseInsensitive)
|| !direction.compare(QLatin1String("north-west"), Qt::CaseInsensitive)) {
return QLatin1String("nw");
} else if (!direction.compare(QLatin1String("i"), Qt::CaseInsensitive) || !direction.compare(QLatin1String("in"), Qt::CaseInsensitive)) {
return QLatin1String("in");
} else if (!direction.compare(QLatin1String("o"), Qt::CaseInsensitive) || !direction.compare(QLatin1String("out"), Qt::CaseInsensitive)) {
return QLatin1String("out");
}
return direction;
}
return QString();
}
// No documentation available in wiki - internal function
int TLuaInterpreter::dirToNumber(lua_State* L, int position)
{
QString dir;
int dirNum;
if (lua_type(L, position) == LUA_TSTRING) {
dir = lua_tostring(L, position);
dir = dir.toLower();
if (!dir.compare(QLatin1String("n")) || !dir.compare(QLatin1String("north"))) {
return DIR_NORTH;
}
if (!dir.compare(QLatin1String("e")) || !dir.compare(QLatin1String("east"))) {
return DIR_EAST;
}
if (!dir.compare(QLatin1String("s")) || !dir.compare(QLatin1String("south"))) {
return DIR_SOUTH;
}
if (!dir.compare(QLatin1String("w")) || !dir.compare(QLatin1String("west"))) {
return DIR_WEST;
}
if (!dir.compare(QLatin1String("u")) || !dir.compare(QLatin1String("up"))) {
return DIR_UP;
}
if (!dir.compare(QLatin1String("d")) || !dir.compare(QLatin1String("down"))) {
return DIR_DOWN;
}
if (!dir.compare(QLatin1String("ne")) || !dir.compare(QLatin1String("northeast"))) {
return DIR_NORTHEAST;
}
if (!dir.compare(QLatin1String("nw")) || !dir.compare(QLatin1String("northwest"))) {
return DIR_NORTHWEST;
}
if (!dir.compare(QLatin1String("se")) || !dir.compare(QLatin1String("southeast"))) {
return DIR_SOUTHEAST;
}
if (!dir.compare(QLatin1String("sw")) || !dir.compare(QLatin1String("southwest"))) {
return DIR_SOUTHWEST;
}
if (!dir.compare(QLatin1String("i")) || !dir.compare(QLatin1String("in"))) {
return DIR_IN;
}
if (!dir.compare(QLatin1String("o")) || !dir.compare(QLatin1String("out"))) {
return DIR_OUT;
}
}
if (lua_type(L, position) == LUA_TNUMBER) {
dirNum = static_cast<int>(lua_tonumber(L, position));
return (dirNum >= DIR_NORTH && dirNum <= DIR_OUT ? dirNum : 0);
}
return 0;
}
// Documentation: https://wiki.mudlet.org/w/Manual:Lua_Functions#denyCurrentSend
int TLuaInterpreter::denyCurrentSend(lua_State* L)
{
Host& host = getHostFromLua(L);
host.mAllowToSendCommand = false;
return 0;
}
// Documentation: https://wiki.mudlet.org/w/Manual:Lua_Functions#getProfileName
int TLuaInterpreter::getProfileName(lua_State* L)
{
Host& host = getHostFromLua(L);
lua_pushstring(L, host.getName().toUtf8().constData());
return 1;
}
// Documentation: https://wiki.mudlet.org/w/Manual:Lua_Functions#getCommandSeparator
int TLuaInterpreter::getCommandSeparator(lua_State* L)
{
Host& host = getHostFromLua(L);
lua_pushstring(L, host.getCommandSeparator().toUtf8().constData());
return 1;
}
// Documentation: https://wiki.mudlet.org/w/Manual:Lua_Functions#resetProfile
int TLuaInterpreter::resetProfile(lua_State* L)
{
Host& host = getHostFromLua(L);
host.resetProfile_phase1();
lua_pushboolean(L, true);
return 1;
}
// Documentation: https://wiki.mudlet.org/w/Manual:Lua_Functions#getWindowsCodepage
int TLuaInterpreter::getWindowsCodepage(lua_State* L)
{
#if defined(Q_OS_WINDOWS)
QSettings registry(qsl(R"(HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Nls\CodePage)"), QSettings::NativeFormat);
auto value = registry.value(qsl("ACP"));
lua_pushstring(L, value.toString().toUtf8().constData());
return 1;
#else
return warnArgumentValue(L, __func__, "this function is only needed on Windows, and does not work here");
#endif
}
// Documentation: https://wiki.mudlet.org/w/Manual:Lua_Functions#spawn
int TLuaInterpreter::spawn(lua_State* L)
{
Host& host = getHostFromLua(L);
return TForkedProcess::startProcess(host.getLuaInterpreter(), L);
}
// Documentation: https://wiki.mudlet.org/w/Manual:Lua_Functions#loadReplay
int TLuaInterpreter::loadReplay(lua_State* L)
{
const QString replayFileName = getVerifiedString(L, __func__, 1, "replay file name");
if (replayFileName.isEmpty()) {
return warnArgumentValue(L, __func__, "a blank string is not a valid replay file name");
}
Host& host = getHostFromLua(L);
QString errMsg;
if (mudlet::self()->loadReplay(&host, replayFileName, &errMsg)) {
lua_pushboolean(L, true);
return 1;
} else {
// Although we only use English text for Lua messages the errMsg could
// contain a Windows pathFileName which may use non-ASCII characters:
return warnArgumentValue(L, __func__, qsl("unable to start replay, reason: '%1'").arg(errMsg));
}
}
// Documentation: https://wiki.mudlet.org/w/Manual:Lua_Functions#cut
int TLuaInterpreter::cut(lua_State* L)
{
const Host& host = getHostFromLua(L);
host.mpConsole->cut();
return 0;
}
// Internal helper for feedTelnet(...) and socketRaw(...) that enables the
// construction of data with bytes that cannot be prepared by normal means
// - including embedded nulls - for testing off-line and for writing protocol
// handlers for those that Mudlet does not provide itself respectively:
// Note: although "<<" and ">>" are extra codes that convert to '<' and '>'
// respectively this looks as though singular instances of either - or
// unrecognised "tags" with unknown other characters between them will still be
// passed through unchanged.
QByteArray TLuaInterpreter::parseTelnetCodes(const QByteArray& input)
{
// Increment the version - and document below - any changes to the table:
const int tableVersion = 1;
// Changes:
// 1 - Initial version.
/*
* Entry grouping
* * Hex digits
* * `O_` prefix - well known Telnet sub-option (less common/relevant ones ommitted)
* * ASCII character abbreviation
* * `T_` prefix - Telnet control code
*/
const QHash<QByteArray, unsigned char> lookupTable = {{QByteArray("<00>"), '\0'}, {QByteArray("<O_BINARY>"), '\0'}, {QByteArray("<NUL>"), '\0'},
{QByteArray("<01>"), '\x01'}, {QByteArray("<O_ECHO>"), '\x01'}, {QByteArray("<SOH>"), '\x01'},
{QByteArray("<02>"), '\x02'}, // Reconnect
{QByteArray("<STX>"), '\x02'},
{QByteArray("<03>"), '\x03'}, {QByteArray("<O_SGA>"), '\x03'}, {QByteArray("<ETX>"), '\x03'},
{QByteArray("<04>"), '\x04'}, // Approx Message Size Negotiation
{QByteArray("<EOT>"), '\x04'},
{QByteArray("<05>"), '\x05'}, {QByteArray("<O_STATUS>"), '\x05'}, {QByteArray("<ENQ>"), '\x05'},
{QByteArray("<06>"), '\x06'}, // Timing Mark
{QByteArray("<ACK>"), '\x06'},
{QByteArray("<07>"), '\x07'}, // Remote Controlled Trans and Echo
{QByteArray("<BELL>"), '\x07'},
{QByteArray("<08>"), '\x08'}, // Output Line Width
{QByteArray("<BS>"), '\x08'},
{QByteArray("<09>"), '\x09'}, // Output Page Size
{QByteArray("<HTAB>"), '\x09'},
{QByteArray("<0A>"), '\x0a'}, // Output Carriage-Return Disposition
{QByteArray("<LF>"), '\x0a'},
{QByteArray("<0B>"), '\x0b'}, // Output Horizontal Tab Stops
{QByteArray("<VTAB>"), '\x0b'},
{QByteArray("<0C>"), '\x0c'}, // Output Horizontal Tab Disposition
{QByteArray("<FF>"), '\x0c'},
{QByteArray("<0D>"), '\x0d'}, // Output Formfeed Disposition
{QByteArray("<CR>"), '\x0d'},
{QByteArray("<0E>"), '\x0e'}, // Output Vertical Tab Stops
{QByteArray("<SO>"), '\x0e'},
{QByteArray("<0F>"), '\x0f'}, // Output Vertical Tab Disposition
{QByteArray("<SI>"), '\x0f'},
{QByteArray("<10>"), '\x10'}, // Output Linefeed Disposition
{QByteArray("<DLE>"), '\x10'},
{QByteArray("<11>"), '\x11'}, // Extended ASCII
{QByteArray("<DC1>"), '\x11'},
{QByteArray("<12>"), '\x12'}, // Logout
{QByteArray("<DC2"), '\x12'},
{QByteArray("<13>"), '\x13'}, // Byte Macro
{QByteArray("<DC3>"), '\x13'},
{QByteArray("<14>"), '\x14'}, // Data Entry Terminal
{QByteArray("<DC4>"), '\x14'},
{QByteArray("<15>"), '\x15'}, // SUPDUP
{QByteArray("<NAK>"), '\x15'},
{QByteArray("<16>"), '\x16'}, // SUPDUP Output
{QByteArray("<SYN>"), '\x16'},
{QByteArray("<17>"), '\x17'}, // Send location
{QByteArray("<ETB>"), '\x17'},
{QByteArray("<18>"), '\x18'}, {QByteArray("<O_TERM>"), '\x18'}, {QByteArray("<CAN>"), '\x18'},
{QByteArray("<19>"), '\x19'}, {QByteArray("<O_EOR>"), '\x19'}, {QByteArray("<EM>"), '\x19'},
{QByteArray("<1A>"), '\x1a'}, // TACACS User Identification
{QByteArray("<SUB>"), '\x1a'},
{QByteArray("<1B>"), '\x1b'}, // Output Marking
{QByteArray("<ESC>"), '\x1b'},
{QByteArray("<1C>"), '\x1c'}, // Terminal Location Number
{QByteArray("<FS>"), '\x1c'},
{QByteArray("<1D>"), '\x1d'}, // Telnet 3270 Regime
{QByteArray("<GS>"), '\x1d'},
{QByteArray("<1E>"), '\x1e'}, // X.3 PAD
{QByteArray("<RS>"), '\x1e'},
{QByteArray("<1F>"), '\x1f'}, {QByteArray("<O_NAWS>"), '\x1f'}, {QByteArray("<US>"), '\x1f'},
{QByteArray("<SP>"), '\x20'}, // 32 dec, Space
{QByteArray("<O_NENV>"), '\x27'}, // 39 dec, New Environment (also MNES)
{QByteArray("<O_CHARS>"), '\x2a'}, // 42 dec, Character Set
{QByteArray("<O_KERMIT>"), '\x2f'}, // 47 dec
{QByteArray("<O_MSDP>"), '\x45'}, // 69 dec
{QByteArray("<O_MSSP>"), '\x46'}, // 70 dec
{QByteArray("<O_MCCP>"), '\x55'}, // 85 dec
{QByteArray("<O_MCCP2>"), '\x56'}, // 86 dec
{QByteArray("<O_MSP>"), '\x5a'}, // 90 dec
{QByteArray("<O_MXP>"), '\x5b'}, // 91 dec
{QByteArray("<O_ZENITH>"), '\x5d'}, // 93 dec
{QByteArray("<O_AARDWULF>"), '\x66'}, // 102 dec
{QByteArray("<DEL>"), '\x7f'}, // 127 dec
{QByteArray("<O_ATCP>"), '\xc8'}, // 200 dec
{QByteArray("<O_GMCP>"), '\xc9'}, // 201 dec
{QByteArray("<T_EOR>"), '\xef'}, // 239 dec
{QByteArray("<F0>"), '\xf0'}, {QByteArray("<T_SE>"), '\xf0'},
{QByteArray("<F1>"), '\xf1'}, {QByteArray("<T_NOP>"), '\xf1'},
{QByteArray("<F2>"), '\xf2'}, {QByteArray("<T_DM>"), '\xf2'},
{QByteArray("<F3>"), '\xf3'}, {QByteArray("<T_BRK>"), '\xf3'},
{QByteArray("<F4>"), '\xf4'}, {QByteArray("<T_IP>"), '\xf4'},
{QByteArray("<F5>"), '\xf5'}, {QByteArray("<T_ABOP>"), '\xf5'},
{QByteArray("<F6>"), '\xf6'}, {QByteArray("<T_AYT>"), '\xf6'},
{QByteArray("<F7>"), '\xf7'}, {QByteArray("<T_EC>"), '\xf7'},
{QByteArray("<F8>"), '\xf8'}, {QByteArray("<T_EL>"), '\xf8'},
{QByteArray("<F9>"), '\xf9'}, {QByteArray("<T_GA>"), '\xf9'},
{QByteArray("<FA>"), '\xfa'}, {QByteArray("<T_SB>"), '\xfa'},
{QByteArray("<FB>"), '\xfb'}, {QByteArray("<T_WILL>"), '\xfb'},
{QByteArray("<FC>"), '\xfc'}, {QByteArray("<T_WONT>"), '\xfc'},
{QByteArray("<FD>"), '\xfd'}, {QByteArray("<T_DO>"), '\xfd'},
{QByteArray("<FE>"), '\xfe'}, {QByteArray("<T_DONT>"), '\xfe'},
{QByteArray("<FF>"), '\xff'}, {QByteArray("<T_IAC>"), '\xff'}};
QByteArray bytes;
if (input.isEmpty()) {
bytes = QByteArray::number(tableVersion);
} else {
for (qsizetype index = 0, total = input.size(); index < total; ++index) {
if (input.at(index) == '<') {
// got an opening marker
if (((index + 1) < total) && (input.at(index + 1) == '<')) {
// got an escaped less than sign - so store it
bytes.append('<');
// nudge the index up one character
++index;
// and process the next one
continue;
}
// Else we haven't got an escaped one so find the closing greater then
qsizetype tagEnd = input.indexOf('>', index);
if (tagEnd > index) {
// Found it, so extract the whole tag including delimiters
QByteArray tag;
for (qsizetype i = index; i <= tagEnd; ++i) {
// store it
tag.append(input.at(i));