forked from xLightsSequencer/xLights
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWebServer.cpp
856 lines (721 loc) · 31.9 KB
/
WebServer.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
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
/***************************************************************
* This source files comes from the xLights project
* https://www.xlights.org
* https://github.com/smeighan/xLights
* See the github commit history for a record of contributing
* developers.
* Copyright claimed based on commit dates recorded in Github
* License: https://github.com/smeighan/xLights/blob/master/License.txt
**************************************************************/
#include <wx/wx.h>
#include <wx/dir.h> // Linux needs this
#include <wx/stdpaths.h>
#include <wx/filename.h>
#include <wx/uri.h>
#include "WebServer.h"
#include "xScheduleMain.h"
#include "ScheduleManager.h"
#include "xScheduleApp.h"
#include "ScheduleOptions.h"
#include "../xLights/UtilFunctions.h"
#include "md5.h"
#include <log4cpp/Category.hh>
#undef WXUSINGDLL
#include "wxJSON/jsonreader.h"
//#define DETAILED_LOGGING
bool __apiOnly = false;
std::string __password = "";
std::list<std::string> __Loggedin;
int __loginTimeout = 30;
std::string __validPass = "";
std::string __defaultPage = "index.html";
void WebServer::GeneratePass()
{
wxString newPass = "";
for (int i = 0; i < 16; i++) {
int r = rand01() * 36;
if (r < 10) {
newPass += char('0' + r);
}
else {
newPass += char('A' + (r - 10));
}
}
__validPass = newPass;
}
void RemoveFromValid(HttpConnection& connection)
{
static log4cpp::Category& logger_base = log4cpp::Category::getInstance(std::string("log_base"));
// remove any existing entry for this machine ... one logged in entry per machine
for (auto it = __Loggedin.begin(); it != __Loggedin.end(); ++it) {
wxArrayString li = wxSplit(*it, '|');
if (li[0] == connection.Address().IPAddress()) {
logger_base.debug("Security: Removing ip %s.", (const char*)li[0].c_str());
__Loggedin.remove(*it);
break;
}
}
}
void UpdateValid(HttpConnection& connection)
{
if (__password == "") return; // no password ... always logged in
for (auto it = __Loggedin.begin(); it != __Loggedin.end(); ++it) {
wxArrayString li = wxSplit(*it, '|');
if (li[0] == connection.Address().IPAddress()) {
li[1] = wxDateTime::Now().FormatISOCombined();
*it = li[0] + "|" + li[1];
return;
}
}
}
void AddToValid(HttpConnection& connection)
{
static log4cpp::Category& logger_base = log4cpp::Category::getInstance(std::string("log_base"));
// remove any existing entry for this machine ... one logged in entry per machine
for (auto it = __Loggedin.begin(); it != __Loggedin.end(); ++it) {
wxArrayString li = wxSplit(*it, '|');
if (li[0] == connection.Address().IPAddress()) {
logger_base.debug("Security: Removing ip %s.", (const char*)li[0].c_str());
__Loggedin.remove(*it);
break;
}
}
wxString security = connection.Address().IPAddress() + "|" + wxDateTime::Now().FormatISOCombined();
logger_base.debug("Security: Adding record %s.", (const char*)security.c_str());
__Loggedin.push_back(security);
}
bool IsValidPass(const std::string& pass)
{
return __validPass != "" && pass == __validPass;
}
bool CheckLoggedIn(HttpConnection& connection, const std::string& pass)
{
static log4cpp::Category& logger_base = log4cpp::Category::getInstance(std::string("log_base"));
if (__password == "") return true; // no password ... always logged in
if (IsValidPass(pass)) return true; // pages which have a valid pass can call APIs
// remove old logins
std::list<wxString> toremove;
for (const auto& it : __Loggedin) {
wxArrayString li = wxSplit(it, '|');
wxDateTime lastused;
lastused.ParseISOCombined(li[1]);
if (wxDateTime::Now() - lastused > __loginTimeout * 60000) {
logger_base.debug("Security: Removing ip %s due to timout.", (const char*)li[0].c_str());
toremove.push_back(it);
}
}
for (const auto& it : toremove) {
__Loggedin.remove(it);
}
for (auto it = __Loggedin.begin(); it != __Loggedin.end(); ++it) {
wxArrayString li = wxSplit(*it, '|');
if (li[0] == connection.Address().IPAddress()) {
li[1] = wxDateTime::Now().FormatISOCombined();
*it = li[0] + "|" + li[1];
return true;
}
}
return false;
}
std::map<wxString, wxString> ParseURI(wxString uri)
{
std::map<wxString, wxString> res;
wxString s(uri);
wxString q = s.AfterFirst('?');
if (q != "") {
wxArrayString p = wxSplit(q, '&');
for (auto it = p.begin(); it != p.end(); ++it) {
wxArrayString x = wxSplit(*it, '=');
if (x.Count() >= 2) {
wxString key = x[0];
res[key] = "";
for (auto it2 = x.begin(); it2 != x.end(); ++it2) {
if (it2 == x.begin()) {
// ignore the key
}
else {
if (res[key] != "") {
res[key] += "=";
}
res[key] += *it2;
}
}
}
}
}
return res;
}
wxString ProcessCommand(HttpConnection& connection, const wxString& command, const wxString& parameters, const wxString& data, const wxString& reference, const std::string& pass)
{
wxStopWatch sw;
static log4cpp::Category& logger_base = log4cpp::Category::getInstance(std::string("log_base"));
if (!CheckLoggedIn(connection, pass)) {
return "{\"result\":\"not logged in\",\"command\":\"" +
command + "\",\"reference\":\"" +
reference + "\",\"ip\":\"" +
connection.Address().IPAddress() + "\"}";
}
#ifdef DETAILED_LOGGING
logger_base.info("xScheduleCommand received command = '%s' parameters = '%s'.", (const char*)command.c_str(), (const char*)parameters.c_str());
#endif
wxString result;
size_t rate = 0;
wxString msg = "";
if (xScheduleFrame::GetScheduleManager()->Action(command, parameters, data, nullptr, nullptr, nullptr, rate, msg)) {
wxCommandEvent event(EVT_FRAMEMS);
event.SetInt(rate);
wxPostEvent(wxGetApp().GetTopWindow(), event);
result = "{\"result\":\"ok\",\"reference\":\"" +
reference + "\",\"command\":\"" +
command + "\"}";
#ifdef DETAILED_LOGGING
logger_base.info(" Time %ld.", sw.Time());
#endif
}
else {
result = "{\"result\":\"failed\",\"command\":\"" +
command + "\",\"reference\":\"" +
reference + "\",\"message\":\"" +
msg + "\"}";
logger_base.info("Command command=%s parameters=%s result='%s'. Time %ld.", (const char*)command.c_str(), (const char*)parameters.c_str(), (const char*)msg.c_str(), sw.Time());
}
return result;
}
wxString ProcessPluginRequest(HttpConnection& connection, const wxString& plugin, const wxString& command, const wxString& parameters, const wxString& data, const wxString& reference, const std::string& pass)
{
wxStopWatch sw;
static log4cpp::Category& logger_base = log4cpp::Category::getInstance(std::string("log_base"));
if (!CheckLoggedIn(connection, pass)) {
return "{\"result\":\"not logged in\",\"command\":\"" +
command + "\",\"ip\":\"" +
connection.Address().IPAddress() + "\"}";
}
#ifdef DETAILED_LOGGING
logger_base.info("xSchedule received plugin request command = '%s' parameters = '%s'.", (const char*)command.c_str(), (const char*)parameters.c_str());
#endif
return ((xScheduleFrame*)wxTheApp->GetTopWindow())->ProcessPluginRequest(plugin, command, parameters, data, reference);
}
wxString ProcessQuery(HttpConnection& connection, const wxString& query, const wxString& parameters, const wxString& reference, const std::string& pass)
{
wxStopWatch sw;
static log4cpp::Category& logger_base = log4cpp::Category::getInstance(std::string("log_base"));
if (!CheckLoggedIn(connection, pass)) {
return "{\"result\":\"not logged in\",\"query\":\"" +
query + "\",\"reference\":\"" +
reference + "\",\"ip\":\"" +
connection.Address().IPAddress() + "\"}";
}
// log everything but playing status
#ifndef DETAILED_LOGGING
if (query != "GetPlayingStatus")
#endif
logger_base.info("xScheduleQuery received query = '%s' parameters = '%s'.", (const char*)query.c_str(), (const char*)parameters.c_str());
wxString result = "";
wxString msg;
if (xScheduleFrame::GetScheduleManager()->Query(query, parameters, result, msg, connection.Address().IPAddress(), reference)) {
#ifndef DETAILED_LOGGING
if (query != "GetPlayingStatus")
#endif
logger_base.info(" data = '%s'. Time = %ld.", (const char*)result.c_str(), sw.Time());
}
else {
result = "{\"result\":\"failed\",\"query\":\"" +
query + "\",\"reference\":\"" +
reference + "\",\"message\":\"" +
msg + "\"}";
logger_base.info(" data = '' : '%s'. Time = %ld.", (const char*)result.c_str(), sw.Time());
}
return result;
}
wxString ProcessXyzzy(HttpConnection& connection, const wxString& command, const wxString& parameters, const wxString& reference, const std::string& pass)
{
wxStopWatch sw;
static log4cpp::Category& logger_base = log4cpp::Category::getInstance(std::string("log_base"));
wxString result;
wxString msg;
if (xScheduleFrame::GetScheduleManager()->DoXyzzy(command, parameters, msg, reference)) {
result = msg;
#ifdef DETAILED_LOGGING
logger_base.info("xyzzy command=%s parameters=%s result='%s'. Time %ld.", (const char*)command.c_str(), (const char*)parameters.c_str(), (const char*)msg.c_str(), sw.Time());
#endif
}
else {
result = "{\"result\":\"failed\",\"xyzzy\":\"" +
command + "\",\"reference\":\"" +
reference + "\",\"message\":\"" +
msg + "\"}";
logger_base.info("xyzzy command=%s parameters=%s result='%s'. Time %ld.", (const char*)command.c_str(), (const char*)parameters.c_str(), (const char*)msg.c_str(), sw.Time());
}
return result;
}
wxString ProcessLogin(HttpConnection& connection, const wxString& credential, const wxString& reference)
{
wxStopWatch sw;
static log4cpp::Category& logger_base = log4cpp::Category::getInstance(std::string("log_base"));
wxString result;
if (__password != "") {
wxString cred = connection.Address().IPAddress() + __password;
// calculate md5 hash
wxString hash = md5(cred);
if (hash == credential) {
// this is a valid login
AddToValid(connection);
result = "{\"result\":\"ok\",\"reference\":\"" + reference + "\",\"command\":\"login\"}";
// THIS SHOULD BE REMOVED
//logger_base.debug("Security: Login %s success.", (const char *)credential.c_str());
logger_base.debug("Security: Login success %s. Time %ld.", (const char*)connection.Address().IPAddress().c_str(), sw.Time());
}
else {
// not a valid login
// THIS SHOULD BE REMOVED
//logger_base.debug("Security: Login failed - credential was %s for %s when it should have been %s.", (const char *)credential.c_str(), (const char *)cred.c_str(), (const char *)hash.c_str());
RemoveFromValid(connection);
result = "{\"result\":\"failed\",\"command\":\"login\",\"message\":\"Login failed.\",\"reference\":\"" + reference + "\",\"ip\":\"" + connection.Address().IPAddress() + "\"}";
logger_base.debug("Security: Login failed. data = '%s'. Time = %ld.", (const char*)result.c_str(), sw.Time());
}
}
else {
result = "{\"result\":\"ok\",\"command\":\"login\",\"reference\":\"" + reference + "\"}";
}
return result;
}
wxString ProcessStash(HttpConnection& connection, const wxString& command, const wxString& key, wxString& data, const wxString& reference, const std::string& pass)
{
wxStopWatch sw;
static log4cpp::Category& logger_base = log4cpp::Category::getInstance(std::string("log_base"));
if (!CheckLoggedIn(connection, pass)) {
return "{\"result\":\"not logged in\",\"stash\":\"" +
command + "\",\"reference\":\"" +
reference + "\",\"ip\":\"" +
connection.Address().IPAddress() + "\"}";
}
logger_base.info("xScheduleStash received command = '%s' key = '%s'.", (const char*)command.c_str(), (const char*)key.c_str());
wxString result;
if (wxString(command).Lower() == "store") {
logger_base.info(" data = '%s'.", (const char*)data.c_str());
if (key == "GetModels") {
result = "{\"result\":\"failed\",\"stash\":\"" +
command + "\",\"reference\":\"" +
reference + "\",\"message\":\"Unable to store under key 'GetModels'. This is a reserved key.\"}";
logger_base.info(" data = '%s'. Time = %ld.", (const char*)data.c_str(), sw.Time());
}
else {
// now store it in a file
wxString msg = "";
if (xScheduleFrame::GetScheduleManager()->StoreData(key, data, msg)) {
#ifdef DETAILED_LOGGING
logger_base.info(" Time %ld.", sw.Time());
#endif
result = "{\"result\":\"ok\",\"reference\":\"" + reference + "\",\"stash\":\"" + command + "\"}";
}
else {
result = "{\"result\":\"failed\",\"stash\":\"" +
command + "\",\"reference\":\"" +
reference + "\",\"message\":\"" +
msg + "\"}";
logger_base.info(" data = '%s'. Time = %ld.", (const char*)data.c_str(), sw.Time());
}
}
}
else if (wxString(command).Lower() == "retrieve") {
wxString msg = "";
if (xScheduleFrame::GetScheduleManager()->RetrieveData(key, data, msg)) {
logger_base.info(" data = '%s'. Time = %ld.", (const char*)data.c_str(), sw.Time());
result = "";
}
else {
result = "{\"result\":\"failed\",\"stash\":\"" +
command + "\",\"reference\":\"" +
reference + "\",\"message\":\"" +
msg + "\"}";
logger_base.info(" data = '' : '%s'. Time = %ld.", (const char*)data.c_str(), sw.Time());
}
}
else if (wxString(command).Lower() == "retrievejson") {
wxString msg = "";
if (xScheduleFrame::GetScheduleManager()->RetrieveData(key, data, msg)) {
logger_base.info(" data = '%s'. Time = %ld.", (const char*)data.c_str(), sw.Time());
result = "{\"reference\":\"" + reference +
"\",\"key\":\"" + key + "\",\"value\":[" + data + "]}";
}
else {
result = "{\"result\":\"failed\",\"stash\":\"" +
command + "\",\"reference\":\"" +
reference + "\",\"message\":\"" +
msg + "\"}";
logger_base.info(" data = '' : '%s'. Time = %ld.", (const char*)data.c_str(), sw.Time());
}
}
else {
result = "{\"result\":\"failed\",\"stash\":\"" +
command + "\",\"reference\":\"" +
reference + "\",\"message\":\"Unknown stash command.\"}";
logger_base.info(" '%s'. Time = %ld.", (const char*)data.c_str(), sw.Time());
}
return result;
}
wxString GetPluginRequest(const wxString& request)
{
if (request == "") return "";
auto plugin = request.AfterFirst('/').BeforeFirst('?');
if (plugin == "") return "";
return ((xScheduleFrame*)wxTheApp->GetTopWindow())->GetWebPluginRequest(plugin.ToStdString());
}
bool MyRequestHandler(HttpConnection& connection, HttpRequest& request)
{
wxLogNull logNo; //kludge: avoid "error 0" message from wxWidgets after new file is written
static log4cpp::Category& logger_base = log4cpp::Category::getInstance(std::string("log_base"));
bool res = false;
std::string plugin;
logger_base.debug("Web request %s.", (const char*)request.URI().c_str());
xScheduleFrame::GetScheduleManager()->WebRequestReceived();
wxString wwwroot = xScheduleFrame::GetScheduleManager()->GetOptions()->GetWWWRoot();
if (request.URI().Lower().StartsWith("/xschedulecommand")) {
wxURI url(request.URI());
std::map<wxString, wxString> parms = ParseURI(url.BuildUnescapedURI());
wxString command = parms["Command"];
wxString parameters = parms["Parameters"];
wxString reference = parms["Reference"];
wxString result = ProcessCommand(connection, command, parameters, request.Data(), reference, "");
HttpResponse response(connection, request, HttpStatus::OK);
response.MakeFromText(result, "application/json");
connection.SendResponse(response);
res = true;
}
else if (request.URI().Lower().StartsWith("/xyzzy2")) {
wxURI url(request.URI().Lower());
std::map<wxString, wxString> parms = ParseURI(url.BuildUnescapedURI());
wxString command = parms["c"];
wxString parameters = parms["p"];
wxString reference = parms["r"];
wxString result = ProcessXyzzy(connection, command + "2", parameters, reference, "");
HttpResponse response(connection, request, HttpStatus::OK);
response.MakeFromText(result, "application/json");
connection.SendResponse(response);
res = true;
}
else if (request.URI().Lower().StartsWith("/xyzzy")) {
wxURI url(request.URI().Lower());
std::map<wxString, wxString> parms = ParseURI(url.BuildUnescapedURI());
wxString command = parms["c"];
wxString parameters = parms["p"];
wxString reference = parms["r"];
wxString result = ProcessXyzzy(connection, command, parameters, reference, "");
HttpResponse response(connection, request, HttpStatus::OK);
response.MakeFromText(result, "application/json");
connection.SendResponse(response);
res = true;
}
else if (request.URI().Lower().StartsWith("/xschedulelogin")) {
wxURI url(request.URI());
std::map<wxString, wxString> parms = ParseURI(url.BuildUnescapedURI());
wxString credential = parms["Credential"];
wxString reference = parms["Reference"];
wxString result = ProcessLogin(connection, credential, reference);
HttpResponse response(connection, request, HttpStatus::OK);
response.MakeFromText(result, "application/json");
connection.SendResponse(response);
res = true;
}
else if (request.URI().Lower().StartsWith("/xschedulestash")) {
wxURI url(request.URI());
std::map<wxString, wxString> parms = ParseURI(url.BuildUnescapedURI());
wxString command = parms["Command"];
wxString key = parms["Key"];
wxString reference = parms["Reference"];
wxString data = request.Data();
wxString result = ProcessStash(connection, command, key, data, reference, "");
HttpResponse response(connection, request, HttpStatus::OK);
if (result == "") {
response.MakeFromText(data, "text/plain");
}
else {
response.MakeFromText(result, "application/json");
}
connection.SendResponse(response);
res = true;
}
else if (request.URI().Lower().StartsWith("/xschedulequery")) {
wxURI url(request.URI());
std::map<wxString, wxString> parms = ParseURI(url.BuildUnescapedURI());
wxString query = parms["Query"];
wxString parameters = parms["Parameters"];
wxString reference = parms["Reference"];
wxString result = ProcessQuery(connection, query, parameters, reference, "");
HttpResponse response(connection, request, HttpStatus::OK);
response.MakeFromText(result, "application/json");
connection.SendResponse(response);
res = true;
}
else {
plugin = GetPluginRequest(request.URI().Lower());
if (plugin != "") {
wxURI url(request.URI());
std::map<wxString, wxString> parms = ParseURI(url.BuildUnescapedURI());
wxString command = parms["Command"];
wxString parameters = parms["Parameters"];
wxString reference = parms["Reference"];
wxString data = request.Data();
wxString result = ProcessPluginRequest(connection, plugin, command, parameters, data, reference, "");
HttpResponse response(connection, request, HttpStatus::OK);
response.MakeFromText(result, "application/json");
connection.SendResponse(response);
}
else if (wwwroot != "" && !__apiOnly && (request.URI() == "" || request.URI() == "/" || request.URI() == "/" + wwwroot || request.URI() == "/" + wwwroot + "/")) {
// Chris if you need this line to be this way on linux then use a #ifdef as the other works on windows
//int port = connection.Server()->Context().Port;
//wxString url = "http://" + request.Host() + ":" + wxString::Format(wxT("%i"), port) + "/" + wwwroot + "/index.html";
wxString url = "http://" + request.Host() + "/" + wwwroot + "/" + __defaultPage;
logger_base.info("Redirecting to '%s'.", (const char*)url.c_str());
HttpResponse response(connection, request, HttpStatus::PermanentRedirect);
response.AddHeader("Location", url);
//response.AddHeader("Connection", "Close");
response.MakeFromText("Redirected to " + url + "\n", "text/plain");
connection.SendResponse(response);
res = true; // disable default processing
}
else if (wwwroot != "") {
wxString uri = wxURI(request.URI()).BuildUnescapedURI();
if (!__apiOnly && request.URI().StartsWith("/" + wwwroot)) {
#ifdef __WXMSW__
wxString d = wxFileName(wxStandardPaths::Get().GetExecutablePath()).GetPath();
#elif __LINUX__
wxString d = wxStandardPaths::Get().GetDataDir();
if (!wxDir::Exists(d)) {
d = wxFileName(wxStandardPaths::Get().GetExecutablePath()).GetPath();
}
#else
wxString d = wxStandardPaths::Get().GetResourcesDir();
#endif
wxString file = d;
if (uri.Contains("?")) {
file += uri.BeforeFirst('?');
}
else {
file += uri;
}
logger_base.info("File request received = '%s' : '%s'.", (const char*)file.c_str(), (const char*)uri.c_str());
if (!wxFile::Exists(file)) {
logger_base.error(" 404: file not found.");
}
HttpResponse response(connection, request, HttpStatus::OK);
//response.AddHeader("Cache-Control", "max-age=14400");
wxFileName fn(file);
if (__validPass != "" && fn.GetExt().Lower().StartsWith("htm") || fn.GetExt().Lower() == "js") {
// we should replace any tokens with our token values
wxFile f;
if (f.Open(file, wxFile::OpenMode::read)) {
wxString data;
if (f.ReadAll(&data)) {
data.Replace("!PASS!", __validPass);
wxString mime = "text/html";
if (fn.GetExt().Lower() == "js") {
mime = "text/javascript";
}
response.MakeFromText(data, mime);
}
else {
response.MakeFromFile(file);
}
}
else {
response.MakeFromFile(file);
}
}
else {
response.MakeFromFile(file);
}
connection.SendResponse(response);
res = true; // disable default processing
}
}
}
if (res) {
logger_base.debug("Web request handled");
}
else {
logger_base.debug("Web request NOT handled");
}
return res; // lets the library's default processing
}
void MyMessageHandler(HttpConnection& connection, WebSocketMessage& message)
{
wxLogNull logNo; //kludge: avoid "error 0" message from wxWidgets after new file is written
static log4cpp::Category& logger_base = log4cpp::Category::getInstance(std::string("log_base"));
xScheduleFrame::GetScheduleManager()->WebRequestReceived();
if (message.Type() == WebSocketMessage::Text) {
wxString result;
wxString text((char*)message.Content().GetData(), message.Content().GetDataLen());
if (text != "") {
logger_base.info("Received " + text);
// construct the JSON root object
wxJSONValue root;
// construct a JSON parser
wxJSONReader reader;
// now read the JSON text and store it in the 'root' structure
// check for errors before retreiving values...
int numErrors = reader.Parse(text, &root);
if (numErrors > 0) {
logger_base.error("The JSON document is not well-formed: " + text);
const wxArrayString& errors = reader.GetErrors();
for (auto it = errors.begin(); it != errors.end(); ++it) {
logger_base.error(" " + std::string(it->c_str()));
}
WebSocketMessage wsm("{\"result\":\"failed\",\"message\":\"JSON message not well formed.\"}");
connection.SendMessage(wsm);
return;
}
wxJSONValue defaultValue = wxString("");
std::string plugin;
// extract the type of request
wxString type = root.Get("Type", defaultValue).AsString().Lower();
if (type == "command") {
wxString c = root.Get("Command", defaultValue).AsString();
wxString p = root.Get("Parameters", defaultValue).AsString();
wxString d = root.Get("Data", defaultValue).AsString();
wxString r = root.Get("Reference", defaultValue).AsString();
wxString pass = root.Get("Pass", defaultValue).AsString();
result = ProcessCommand(connection, c, p, d, r, pass);
}
else if (type == "query") {
wxString q = root.Get("Query", defaultValue).AsString();
wxString p = root.Get("Parameters", defaultValue).AsString();
wxString r = root.Get("Reference", defaultValue).AsString();
wxString pass = root.Get("Pass", defaultValue).AsString();
result = ProcessQuery(connection, q, p, r, pass);
}
else if (type == "xyzzy2") {
wxString c = root.Get("c", defaultValue).AsString();
wxString p = root.Get("p", defaultValue).AsString();
wxString r = root.Get("r", defaultValue).AsString();
result = ProcessXyzzy(connection, c + "2", p, r, "");
}
else if (type == "xyzzy") {
wxString c = root.Get("c", defaultValue).AsString();
wxString p = root.Get("p", defaultValue).AsString();
wxString r = root.Get("r", defaultValue).AsString();
result = ProcessXyzzy(connection, c, p, r, "");
}
else if (type == "login") {
wxString c = root.Get("Credential", defaultValue).AsString();
wxString r = root.Get("Reference", defaultValue).AsString();
result = ProcessLogin(connection, c, r);
}
else if (type == "stash") {
wxString c = root.Get("Command", defaultValue).AsString();
wxString k = root.Get("Key", defaultValue).AsString();
wxString d = root.Get("Data", defaultValue).AsString();
wxString r = root.Get("Reference", defaultValue).AsString();
wxString pass = root.Get("Pass", defaultValue).AsString();
result = ProcessStash(connection, c, k, d, r, pass);
if (result == "") {
result = d;
}
}
else {
plugin = ((xScheduleFrame*)wxTheApp->GetTopWindow())->GetWebPluginRequest(type);
if (plugin != "") {
wxString c = root.Get("Command", defaultValue).AsString();
wxString p = root.Get("Parameters", defaultValue).AsString();
wxString d = root.Get("Data", defaultValue).AsString();
wxString r = root.Get("Reference", defaultValue).AsString();
wxString pass = root.Get("Pass", defaultValue).AsString();
result = ProcessPluginRequest(connection, plugin, c, p, d, r, pass);
}
else {
wxString r = root.Get("Reference", defaultValue).AsString();
WebSocketMessage wsm("{\"result\":\"failed\",\"reference\":\"" + r + "\",\"message\":\"Unknown request type or plugin not running.\"}");
connection.SendMessage(wsm);
return;
}
}
}
else {
result = "{\"result\":\"failed\",\"reference\":\"\",\"message\":\"Empty request.\"}";
}
WebSocketMessage wsm(result);
connection.SendMessage(wsm);
}
else if (message.Type() == WebSocketMessage::Binary) {
logger_base.info("Received <binary>");
WebSocketMessage wsm("{\"result\":\"failed\",\"message\":\"Binary web sockets not supported.\"}");
connection.SendMessage(wsm);
}
}
void WebServer::SendMessageToAllWebSockets(const wxString& message)
{
static bool reentry = false;
if (reentry) {
return;
}
reentry = true;
for (const auto& it : _connections) {
if (it.second->IsWebSocket()) {
WebSocketMessage wsm(message);
if (it.second->SendMessage(wsm)) {
UpdateValid(*it.second);
}
else {
RemoveFromValid(*it.second);
}
}
}
reentry = false;
}
bool WebServer::IsSomeoneListening() const
{
for (auto it : _connections) {
if (it.second->IsWebSocket()) {
return true;
}
}
return false;
}
void WebServer::SetAllowUnauthenticatedPagesToBypassLogin(bool allowUnauthPages)
{
if (!allowUnauthPages) {
__validPass = "";
}
else if (__validPass == "") {
GeneratePass();
}
}
WebServer::WebServer(int port, bool apionly, const wxString& password, int mins, bool allowUnauthPages, const std::string& defaultPage)
{
__apiOnly = apionly; // put this in a global.
__password = password;
__loginTimeout = mins;
if (defaultPage != "") __defaultPage = defaultPage;
SetAllowUnauthenticatedPagesToBypassLogin(allowUnauthPages);
wxLogNull logNo; //kludge: avoid "error 0" message from wxWidgets after new file is written
static log4cpp::Category& logger_base = log4cpp::Category::getInstance(std::string("log_base"));
HttpContext context;
context.Port = port;
context.RequestHandler = MyRequestHandler;
context.MessageHandler = MyMessageHandler;
if (!Start(context)) {
logger_base.error("Error starting web server.");
wxMessageBox("Error starting web server. You may already have a program listening on port " + wxString::Format(wxT("%i"), port));
}
}
WebServer::~WebServer()
{
wxLogNull logNo; //kludge: avoid "error 0" message from wxWidgets after new file is written
Stop();
}
void WebServer::SetAPIOnly(bool apiOnly)
{
__apiOnly = apiOnly;
}
void WebServer::SetPasswordTimeout(int mins)
{
__loginTimeout = mins;
}
void WebServer::SetPassword(const wxString& password)
{
__password = password;
}
void WebServer::SetDefaultPage(const std::string& defaultPage)
{
if (defaultPage != "") __defaultPage = defaultPage;
}