-
-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathconfighttp.cpp
More file actions
1356 lines (1177 loc) · 44.6 KB
/
Copy pathconfighttp.cpp
File metadata and controls
1356 lines (1177 loc) · 44.6 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
/**
* @file src/confighttp.cpp
* @brief Definitions for the Web UI Config HTTP server.
*
* @todo Authentication, better handling of routes common to nvhttp, cleanup
*/
#define BOOST_BIND_GLOBAL_PLACEHOLDERS
// standard includes
#include <filesystem>
#include <format>
#include <fstream>
#include <set>
// lib includes
#include <boost/algorithm/string.hpp>
#include <boost/asio/ssl/context.hpp>
#include <boost/filesystem.hpp>
#include <nlohmann/json.hpp>
#include <Simple-Web-Server/crypto.hpp>
#include <Simple-Web-Server/server_https.hpp>
// local includes
#include "config.h"
#include "confighttp.h"
#include "crypto.h"
#include "display_device.h"
#include "file_handler.h"
#include "globals.h"
#include "httpcommon.h"
#include "logging.h"
#include "network.h"
#include "nvhttp.h"
#include "platform/common.h"
#include "process.h"
#include "stream.h"
#include "utility.h"
#include "uuid.h"
using namespace std::literals;
namespace confighttp {
namespace fs = std::filesystem;
using https_server_t = SimpleWeb::Server<SimpleWeb::HTTPS>;
using args_t = SimpleWeb::CaseInsensitiveMultimap;
using resp_https_t = std::shared_ptr<typename SimpleWeb::ServerBase<SimpleWeb::HTTPS>::Response>;
using req_https_t = std::shared_ptr<typename SimpleWeb::ServerBase<SimpleWeb::HTTPS>::Request>;
enum class op_e {
ADD, ///< Add client
REMOVE ///< Remove client
};
/**
* @brief Log the request details.
* @param request The HTTP request object.
*/
void print_req(const req_https_t &request) {
BOOST_LOG(debug) << "METHOD :: "sv << request->method;
BOOST_LOG(debug) << "DESTINATION :: "sv << request->path;
for (auto &[name, val] : request->header) {
BOOST_LOG(debug) << name << " -- " << (name == "Authorization" ? "CREDENTIALS REDACTED" : val);
}
BOOST_LOG(debug) << " [--] "sv;
for (auto &[name, val] : request->parse_query_string()) {
BOOST_LOG(debug) << name << " -- " << val;
}
BOOST_LOG(debug) << " [--] "sv;
}
/**
* @brief Send a response.
* @param response The HTTP response object.
* @param output_tree The JSON tree to send.
*/
void send_response(resp_https_t response, const nlohmann::json &output_tree) {
SimpleWeb::CaseInsensitiveMultimap headers;
headers.emplace("Content-Type", "application/json");
headers.emplace("X-Frame-Options", "DENY");
headers.emplace("Content-Security-Policy", "frame-ancestors 'none';");
response->write(output_tree.dump(), headers);
}
/**
* @brief Send a 401 Unauthorized response.
* @param response The HTTP response object.
* @param request The HTTP request object.
*/
void send_unauthorized(resp_https_t response, req_https_t request) {
auto address = net::addr_to_normalized_string(request->remote_endpoint().address());
BOOST_LOG(info) << "Web UI: ["sv << address << "] -- not authorized"sv;
constexpr SimpleWeb::StatusCode code = SimpleWeb::StatusCode::client_error_unauthorized;
nlohmann::json tree;
tree["status_code"] = code;
tree["status"] = false;
tree["error"] = "Unauthorized";
const SimpleWeb::CaseInsensitiveMultimap headers {
{"Content-Type", "application/json"},
{"WWW-Authenticate", R"(Basic realm="Sunshine Gamestream Host", charset="UTF-8")"},
{"X-Frame-Options", "DENY"},
{"Content-Security-Policy", "frame-ancestors 'none';"}
};
response->write(code, tree.dump(), headers);
}
/**
* @brief Send a redirect response.
* @param response The HTTP response object.
* @param request The HTTP request object.
* @param path The path to redirect to.
*/
void send_redirect(resp_https_t response, req_https_t request, const char *path) {
auto address = net::addr_to_normalized_string(request->remote_endpoint().address());
BOOST_LOG(info) << "Web UI: ["sv << address << "] -- not authorized"sv;
const SimpleWeb::CaseInsensitiveMultimap headers {
{"Location", path},
{"X-Frame-Options", "DENY"},
{"Content-Security-Policy", "frame-ancestors 'none';"}
};
response->write(SimpleWeb::StatusCode::redirection_temporary_redirect, headers);
}
/**
* @brief Authenticate the user.
* @param response The HTTP response object.
* @param request The HTTP request object.
* @return True if the user is authenticated, false otherwise.
*/
bool authenticate(resp_https_t response, req_https_t request) {
auto address = net::addr_to_normalized_string(request->remote_endpoint().address());
auto ip_type = net::from_address(address);
if (ip_type > http::origin_web_ui_allowed) {
BOOST_LOG(info) << "Web UI: ["sv << address << "] -- denied"sv;
response->write(SimpleWeb::StatusCode::client_error_forbidden);
return false;
}
// If credentials are shown, redirect the user to a /welcome page
if (config::sunshine.username.empty()) {
send_redirect(response, request, "/welcome");
return false;
}
auto fg = util::fail_guard([&]() {
send_unauthorized(response, request);
});
auto auth = request->header.find("authorization");
if (auth == request->header.end()) {
return false;
}
auto &rawAuth = auth->second;
auto authData = SimpleWeb::Crypto::Base64::decode(rawAuth.substr("Basic "sv.length()));
int index = authData.find(':');
if (index >= authData.size() - 1) {
return false;
}
auto username = authData.substr(0, index);
auto password = authData.substr(index + 1);
auto hash = util::hex(crypto::hash(password + config::sunshine.salt)).to_string();
if (!boost::iequals(username, config::sunshine.username) || hash != config::sunshine.password) {
return false;
}
fg.disable();
return true;
}
/**
* @brief Send a 404 Not Found response.
* @param response The HTTP response object.
* @param request The HTTP request object.
*/
void not_found(resp_https_t response, [[maybe_unused]] req_https_t request) {
constexpr SimpleWeb::StatusCode code = SimpleWeb::StatusCode::client_error_not_found;
nlohmann::json tree;
tree["status_code"] = code;
tree["error"] = "Not Found";
SimpleWeb::CaseInsensitiveMultimap headers;
headers.emplace("Content-Type", "application/json");
headers.emplace("X-Frame-Options", "DENY");
headers.emplace("Content-Security-Policy", "frame-ancestors 'none';");
response->write(code, tree.dump(), headers);
}
/**
* @brief Send a 400 Bad Request response.
* @param response The HTTP response object.
* @param request The HTTP request object.
* @param error_message The error message to include in the response.
*/
void bad_request(resp_https_t response, [[maybe_unused]] req_https_t request, const std::string &error_message = "Bad Request") {
constexpr SimpleWeb::StatusCode code = SimpleWeb::StatusCode::client_error_bad_request;
nlohmann::json tree;
tree["status_code"] = code;
tree["status"] = false;
tree["error"] = error_message;
SimpleWeb::CaseInsensitiveMultimap headers;
headers.emplace("Content-Type", "application/json");
headers.emplace("X-Frame-Options", "DENY");
headers.emplace("Content-Security-Policy", "frame-ancestors 'none';");
response->write(code, tree.dump(), headers);
}
/**
* @brief Validate the request content type and send bad request when mismatch.
* @param response The HTTP response object.
* @param request The HTTP request object.
* @param contentType The expected content type
*/
bool check_content_type(resp_https_t response, req_https_t request, const std::string_view &contentType) {
auto requestContentType = request->header.find("content-type");
if (requestContentType == request->header.end()) {
bad_request(response, request, "Content type not provided");
return false;
}
// Extract the media type part before any parameters (e.g., charset)
std::string actualContentType = requestContentType->second;
size_t semicolonPos = actualContentType.find(';');
if (semicolonPos != std::string::npos) {
actualContentType = actualContentType.substr(0, semicolonPos);
}
// Trim whitespace and convert to lowercase for case-insensitive comparison
boost::algorithm::trim(actualContentType);
boost::algorithm::to_lower(actualContentType);
std::string expectedContentType(contentType);
boost::algorithm::to_lower(expectedContentType);
if (actualContentType != expectedContentType) {
bad_request(response, request, "Content type mismatch");
return false;
}
return true;
}
/**
* @brief Get the index page.
* @param response The HTTP response object.
* @param request The HTTP request object.
* @todo combine these functions into a single function that accepts the page, i.e "index", "pin", "apps"
*/
void getIndexPage(resp_https_t response, req_https_t request) {
if (!authenticate(response, request)) {
return;
}
print_req(request);
std::string content = file_handler::read_file(WEB_DIR "index.html");
SimpleWeb::CaseInsensitiveMultimap headers;
headers.emplace("Content-Type", "text/html; charset=utf-8");
headers.emplace("X-Frame-Options", "DENY");
headers.emplace("Content-Security-Policy", "frame-ancestors 'none';");
response->write(content, headers);
}
/**
* @brief Get the PIN page.
* @param response The HTTP response object.
* @param request The HTTP request object.
*/
void getPinPage(resp_https_t response, req_https_t request) {
if (!authenticate(response, request)) {
return;
}
print_req(request);
std::string content = file_handler::read_file(WEB_DIR "pin.html");
SimpleWeb::CaseInsensitiveMultimap headers;
headers.emplace("Content-Type", "text/html; charset=utf-8");
headers.emplace("X-Frame-Options", "DENY");
headers.emplace("Content-Security-Policy", "frame-ancestors 'none';");
response->write(content, headers);
}
/**
* @brief Get the apps page.
* @param response The HTTP response object.
* @param request The HTTP request object.
*/
void getAppsPage(resp_https_t response, req_https_t request) {
if (!authenticate(response, request)) {
return;
}
print_req(request);
std::string content = file_handler::read_file(WEB_DIR "apps.html");
SimpleWeb::CaseInsensitiveMultimap headers;
headers.emplace("Content-Type", "text/html; charset=utf-8");
headers.emplace("X-Frame-Options", "DENY");
headers.emplace("Content-Security-Policy", "frame-ancestors 'none';");
headers.emplace("Access-Control-Allow-Origin", "https://images.igdb.com/");
response->write(content, headers);
}
/**
* @brief Get the clients page.
* @param response The HTTP response object.
* @param request The HTTP request object.
*/
void getClientsPage(resp_https_t response, req_https_t request) {
if (!authenticate(response, request)) {
return;
}
print_req(request);
std::string content = file_handler::read_file(WEB_DIR "clients.html");
SimpleWeb::CaseInsensitiveMultimap headers;
headers.emplace("Content-Type", "text/html; charset=utf-8");
headers.emplace("X-Frame-Options", "DENY");
headers.emplace("Content-Security-Policy", "frame-ancestors 'none';");
response->write(content, headers);
}
/**
* @brief Get the sessions page.
* @param response The HTTP response object.
* @param request The HTTP request object.
*/
void getSessionsPage(resp_https_t response, req_https_t request) {
if (!authenticate(response, request)) {
return;
}
print_req(request);
std::string content = file_handler::read_file(WEB_DIR "sessions.html");
SimpleWeb::CaseInsensitiveMultimap headers;
headers.emplace("Content-Type", "text/html; charset=utf-8");
headers.emplace("X-Frame-Options", "DENY");
headers.emplace("Content-Security-Policy", "frame-ancestors 'none';");
response->write(content, headers);
}
/**
* @brief Get the configuration page.
* @param response The HTTP response object.
* @param request The HTTP request object.
*/
void getConfigPage(resp_https_t response, req_https_t request) {
if (!authenticate(response, request)) {
return;
}
print_req(request);
std::string content = file_handler::read_file(WEB_DIR "config.html");
SimpleWeb::CaseInsensitiveMultimap headers;
headers.emplace("Content-Type", "text/html; charset=utf-8");
headers.emplace("X-Frame-Options", "DENY");
headers.emplace("Content-Security-Policy", "frame-ancestors 'none';");
response->write(content, headers);
}
/**
* @brief Get the password page.
* @param response The HTTP response object.
* @param request The HTTP request object.
*/
void getPasswordPage(resp_https_t response, req_https_t request) {
if (!authenticate(response, request)) {
return;
}
print_req(request);
std::string content = file_handler::read_file(WEB_DIR "password.html");
SimpleWeb::CaseInsensitiveMultimap headers;
headers.emplace("Content-Type", "text/html; charset=utf-8");
headers.emplace("X-Frame-Options", "DENY");
headers.emplace("Content-Security-Policy", "frame-ancestors 'none';");
response->write(content, headers);
}
/**
* @brief Get the welcome page.
* @param response The HTTP response object.
* @param request The HTTP request object.
*/
void getWelcomePage(resp_https_t response, req_https_t request) {
print_req(request);
if (!config::sunshine.username.empty()) {
send_redirect(response, request, "/");
return;
}
std::string content = file_handler::read_file(WEB_DIR "welcome.html");
SimpleWeb::CaseInsensitiveMultimap headers;
headers.emplace("Content-Type", "text/html; charset=utf-8");
headers.emplace("X-Frame-Options", "DENY");
headers.emplace("Content-Security-Policy", "frame-ancestors 'none';");
response->write(content, headers);
}
/**
* @brief Get the troubleshooting page.
* @param response The HTTP response object.
* @param request The HTTP request object.
*/
void getTroubleshootingPage(resp_https_t response, req_https_t request) {
if (!authenticate(response, request)) {
return;
}
print_req(request);
std::string content = file_handler::read_file(WEB_DIR "troubleshooting.html");
SimpleWeb::CaseInsensitiveMultimap headers;
headers.emplace("Content-Type", "text/html; charset=utf-8");
headers.emplace("X-Frame-Options", "DENY");
headers.emplace("Content-Security-Policy", "frame-ancestors 'none';");
response->write(content, headers);
}
/**
* @brief Get the favicon image.
* @param response The HTTP response object.
* @param request The HTTP request object.
* @todo combine function with getSunshineLogoImage and possibly getNodeModules
* @todo use mime_types map
*/
void getFaviconImage(resp_https_t response, req_https_t request) {
print_req(request);
std::ifstream in(WEB_DIR "images/sunshine.ico", std::ios::binary);
SimpleWeb::CaseInsensitiveMultimap headers;
headers.emplace("Content-Type", "image/x-icon");
headers.emplace("X-Frame-Options", "DENY");
headers.emplace("Content-Security-Policy", "frame-ancestors 'none';");
response->write(SimpleWeb::StatusCode::success_ok, in, headers);
}
/**
* @brief Get the Sunshine logo image.
* @param response The HTTP response object.
* @param request The HTTP request object.
* @todo combine function with getFaviconImage and possibly getNodeModules
* @todo use mime_types map
*/
void getSunshineLogoImage(resp_https_t response, req_https_t request) {
print_req(request);
std::ifstream in(WEB_DIR "images/logo-sunshine-45.png", std::ios::binary);
SimpleWeb::CaseInsensitiveMultimap headers;
headers.emplace("Content-Type", "image/png");
headers.emplace("X-Frame-Options", "DENY");
headers.emplace("Content-Security-Policy", "frame-ancestors 'none';");
response->write(SimpleWeb::StatusCode::success_ok, in, headers);
}
/**
* @brief Check if a path is a child of another path.
* @param base The base path.
* @param query The path to check.
* @return True if the path is a child of the base path, false otherwise.
*/
bool isChildPath(fs::path const &base, fs::path const &query) {
auto relPath = fs::relative(base, query);
return *(relPath.begin()) != fs::path("..");
}
/**
* @brief Get an asset from the node_modules directory.
* @param response The HTTP response object.
* @param request The HTTP request object.
*/
void getNodeModules(resp_https_t response, req_https_t request) {
print_req(request);
fs::path webDirPath(WEB_DIR);
fs::path nodeModulesPath(webDirPath / "assets");
// .relative_path is needed to shed any leading slash that might exist in the request path
auto filePath = fs::weakly_canonical(webDirPath / fs::path(request->path).relative_path());
// Don't do anything if file does not exist or is outside the assets directory
if (!isChildPath(filePath, nodeModulesPath)) {
BOOST_LOG(warning) << "Someone requested a path " << filePath << " that is outside the assets folder";
bad_request(response, request);
return;
}
if (!fs::exists(filePath)) {
not_found(response, request);
return;
}
auto relPath = fs::relative(filePath, webDirPath);
// get the mime type from the file extension mime_types map
// remove the leading period from the extension
auto mimeType = mime_types.find(relPath.extension().string().substr(1));
// check if the extension is in the map at the x position
if (mimeType == mime_types.end()) {
bad_request(response, request);
return;
}
// if it is, set the content type to the mime type
SimpleWeb::CaseInsensitiveMultimap headers;
headers.emplace("Content-Type", mimeType->second);
headers.emplace("X-Frame-Options", "DENY");
headers.emplace("Content-Security-Policy", "frame-ancestors 'none';");
std::ifstream in(filePath.string(), std::ios::binary);
response->write(SimpleWeb::StatusCode::success_ok, in, headers);
}
/**
* @brief Get the list of available applications.
* @param response The HTTP response object.
* @param request The HTTP request object.
*
* @api_examples{/api/apps| GET| null}
*/
void getApps(resp_https_t response, req_https_t request) {
if (!authenticate(response, request)) {
return;
}
print_req(request);
try {
std::string content = file_handler::read_file(config::stream.file_apps.c_str());
nlohmann::json file_tree = nlohmann::json::parse(content);
// Legacy versions of Sunshine used strings for boolean and integers, let's convert them
// List of keys to convert to boolean
std::vector<std::string> boolean_keys = {
"exclude-global-prep-cmd",
"elevated",
"auto-detach",
"wait-all"
};
// List of keys to convert to integers
std::vector<std::string> integer_keys = {
"exit-timeout"
};
// Walk fileTree and convert true/false strings to boolean or integer values
for (auto &app : file_tree["apps"]) {
for (const auto &key : boolean_keys) {
if (app.contains(key) && app[key].is_string()) {
app[key] = app[key] == "true";
}
}
for (const auto &key : integer_keys) {
if (app.contains(key) && app[key].is_string()) {
app[key] = std::stoi(app[key].get<std::string>());
}
}
if (app.contains("prep-cmd")) {
for (auto &prep : app["prep-cmd"]) {
if (prep.contains("elevated") && prep["elevated"].is_string()) {
prep["elevated"] = prep["elevated"] == "true";
}
}
}
}
send_response(response, file_tree);
} catch (std::exception &e) {
BOOST_LOG(warning) << "GetApps: "sv << e.what();
bad_request(response, request, e.what());
}
}
/**
* @brief Save an application. To save a new application the index must be `-1`. To update an existing application, you must provide the current index of the application.
* @param response The HTTP response object.
* @param request The HTTP request object.
* The body for the post request should be JSON serialized in the following format:
* @code{.json}
* {
* "name": "Application Name",
* "output": "Log Output Path",
* "cmd": "Command to run the application",
* "index": -1,
* "exclude-global-prep-cmd": false,
* "elevated": false,
* "auto-detach": true,
* "wait-all": true,
* "exit-timeout": 5,
* "prep-cmd": [
* {
* "do": "Command to prepare",
* "undo": "Command to undo preparation",
* "elevated": false
* }
* ],
* "detached": [
* "Detached command"
* ],
* "image-path": "Full path to the application image. Must be a png file."
* }
* @endcode
*
* @api_examples{/api/apps| POST| {"name":"Hello, World!","index":-1}}
*/
void saveApp(resp_https_t response, req_https_t request) {
if (!check_content_type(response, request, "application/json")) {
return;
}
if (!authenticate(response, request)) {
return;
}
print_req(request);
std::stringstream ss;
ss << request->content.rdbuf();
try {
// TODO: Input Validation
nlohmann::json output_tree;
nlohmann::json input_tree = nlohmann::json::parse(ss);
std::string file = file_handler::read_file(config::stream.file_apps.c_str());
BOOST_LOG(info) << file;
nlohmann::json file_tree = nlohmann::json::parse(file);
if (input_tree["prep-cmd"].empty()) {
input_tree.erase("prep-cmd");
}
if (input_tree["detached"].empty()) {
input_tree.erase("detached");
}
auto &apps_node = file_tree["apps"];
int index = input_tree["index"].get<int>(); // this will intentionally cause exception if the provided value is the wrong type
input_tree.erase("index");
if (index == -1) {
apps_node.push_back(input_tree);
} else {
nlohmann::json newApps = nlohmann::json::array();
for (size_t i = 0; i < apps_node.size(); ++i) {
if (i == index) {
newApps.push_back(input_tree);
} else {
newApps.push_back(apps_node[i]);
}
}
file_tree["apps"] = newApps;
}
// Sort the apps array by name
std::sort(apps_node.begin(), apps_node.end(), [](const nlohmann::json &a, const nlohmann::json &b) {
return a["name"].get<std::string>() < b["name"].get<std::string>();
});
file_handler::write_file(config::stream.file_apps.c_str(), file_tree.dump(4));
proc::refresh(config::stream.file_apps);
output_tree["status"] = true;
send_response(response, output_tree);
} catch (std::exception &e) {
BOOST_LOG(warning) << "SaveApp: "sv << e.what();
bad_request(response, request, e.what());
}
}
/**
* @brief Close the currently running application.
* @param response The HTTP response object.
* @param request The HTTP request object.
*
* @api_examples{/api/apps/close| POST| null}
*/
void closeApp(resp_https_t response, req_https_t request) {
if (!check_content_type(response, request, "application/json")) {
return;
}
if (!authenticate(response, request)) {
return;
}
print_req(request);
proc::proc.terminate();
nlohmann::json output_tree;
output_tree["status"] = true;
send_response(response, output_tree);
}
/**
* @brief Delete an application.
* @param response The HTTP response object.
* @param request The HTTP request object.
*
* @api_examples{/api/apps/9999| DELETE| null}
*/
void deleteApp(resp_https_t response, req_https_t request) {
// Skip check_content_type() for this endpoint since the request body is not used.
if (!authenticate(response, request)) {
return;
}
print_req(request);
try {
nlohmann::json output_tree;
nlohmann::json new_apps = nlohmann::json::array();
std::string file = file_handler::read_file(config::stream.file_apps.c_str());
nlohmann::json file_tree = nlohmann::json::parse(file);
auto &apps_node = file_tree["apps"];
const int index = std::stoi(request->path_match[1]);
if (index < 0 || index >= static_cast<int>(apps_node.size())) {
std::string error;
if (const int max_index = static_cast<int>(apps_node.size()) - 1; max_index < 0) {
error = "No applications to delete";
} else {
error = std::format("'index' {} out of range, max index is {}", index, max_index);
}
bad_request(response, request, error);
return;
}
for (size_t i = 0; i < apps_node.size(); ++i) {
if (i != index) {
new_apps.push_back(apps_node[i]);
}
}
file_tree["apps"] = new_apps;
file_handler::write_file(config::stream.file_apps.c_str(), file_tree.dump(4));
proc::refresh(config::stream.file_apps);
output_tree["status"] = true;
output_tree["result"] = std::format("application {} deleted", index);
send_response(response, output_tree);
} catch (std::exception &e) {
BOOST_LOG(warning) << "DeleteApp: "sv << e.what();
bad_request(response, request, e.what());
}
}
/**
* @brief Get the list of paired clients.
* @param response The HTTP response object.
* @param request The HTTP request object.
*
* @api_examples{/api/clients/list| GET| null}
*/
void getClients(resp_https_t response, req_https_t request) {
if (!authenticate(response, request)) {
return;
}
print_req(request);
const nlohmann::json named_certs = nvhttp::get_all_clients();
nlohmann::json output_tree;
output_tree["named_certs"] = named_certs;
output_tree["status"] = true;
send_response(response, output_tree);
}
/**
* @brief Unpair a client.
* @param response The HTTP response object.
* @param request The HTTP request object.
* The body for the post request should be JSON serialized in the following format:
* @code{.json}
* {
* "uuid": "<uuid>"
* }
* @endcode
*
* @api_examples{/api/unpair| POST| {"uuid":"1234"}}
*/
void unpair(resp_https_t response, req_https_t request) {
if (!check_content_type(response, request, "application/json")) {
return;
}
if (!authenticate(response, request)) {
return;
}
print_req(request);
std::stringstream ss;
ss << request->content.rdbuf();
try {
// TODO: Input Validation
nlohmann::json output_tree;
const nlohmann::json input_tree = nlohmann::json::parse(ss);
const std::string uuid = input_tree.value("uuid", "");
output_tree["status"] = nvhttp::unpair_client(uuid);
send_response(response, output_tree);
} catch (std::exception &e) {
BOOST_LOG(warning) << "Unpair: "sv << e.what();
bad_request(response, request, e.what());
}
}
/**
* @brief Unpair all clients.
* @param response The HTTP response object.
* @param request The HTTP request object.
*
* @api_examples{/api/clients/unpair-all| POST| null}
*/
void unpairAll(resp_https_t response, req_https_t request) {
if (!check_content_type(response, request, "application/json")) {
return;
}
if (!authenticate(response, request)) {
return;
}
print_req(request);
nvhttp::erase_all_clients();
proc::proc.terminate();
nlohmann::json output_tree;
output_tree["status"] = true;
send_response(response, output_tree);
}
/**
* @brief Get the list of active streaming sessions.
* @param response The HTTP response object.
* @param request The HTTP request object.
*
* @api_examples{/api/sessions| GET| null}
*/
void getSessions(resp_https_t response, req_https_t request) {
if (!authenticate(response, request)) {
return;
}
print_req(request);
auto sessions = stream::session::get_all_sessions();
nlohmann::json sessions_json = nlohmann::json::array();
auto now = std::chrono::steady_clock::now();
for (const auto &session : sessions) {
nlohmann::json session_json;
session_json["id"] = session.id;
session_json["client_name"] = session.client_name;
session_json["ip_address"] = session.ip_address;
// Calculate duration in seconds
auto duration = std::chrono::duration_cast<std::chrono::seconds>(now - session.start_time);
session_json["duration_seconds"] = duration.count();
sessions_json.push_back(session_json);
}
nlohmann::json output_tree;
output_tree["sessions"] = sessions_json;
output_tree["status"] = true;
send_response(response, output_tree);
}
/**
* @brief Disconnect an active streaming session.
* @param response The HTTP response object.
* @param request The HTTP request object.
* The body for the post request should be JSON serialized in the following format:
* @code{.json}
* {
* "session_id": "<id>"
* }
* @endcode
*
* @api_examples{/api/sessions/disconnect| POST| {"session_id":"1234"}}
*/
void disconnectSession(resp_https_t response, req_https_t request) {
if (!check_content_type(response, request, "application/json")) {
return;
}
if (!authenticate(response, request)) {
return;
}
print_req(request);
std::stringstream ss;
ss << request->content.rdbuf();
try {
nlohmann::json output_tree;
const nlohmann::json input_tree = nlohmann::json::parse(ss);
const std::string session_id = input_tree.value("session_id", "");
if (session_id.empty()) {
bad_request(response, request, "Missing session_id");
return;
}
output_tree["status"] = stream::session::disconnect(session_id);
send_response(response, output_tree);
} catch (std::exception &e) {
BOOST_LOG(warning) << "DisconnectSession: "sv << e.what();
bad_request(response, request, e.what());
}
}
/**
* @brief Get the configuration settings.
* @param response The HTTP response object.
* @param request The HTTP request object.
*
* @api_examples{/api/config| GET| null}
*/
void getConfig(resp_https_t response, req_https_t request) {
if (!authenticate(response, request)) {
return;
}
print_req(request);
nlohmann::json output_tree;
output_tree["status"] = true;
output_tree["platform"] = SUNSHINE_PLATFORM;
output_tree["version"] = PROJECT_VERSION;
auto vars = config::parse_config(file_handler::read_file(config::sunshine.config_file.c_str()));
for (auto &[name, value] : vars) {
output_tree[name] = std::move(value);
}
send_response(response, output_tree);
}
/**
* @brief Get the locale setting. This endpoint does not require authentication.
* @param response The HTTP response object.
* @param request The HTTP request object.
*
* @api_examples{/api/configLocale| GET| null}
*/
void getLocale(resp_https_t response, req_https_t request) {
// we need to return the locale whether authenticated or not
print_req(request);
nlohmann::json output_tree;
output_tree["status"] = true;
output_tree["locale"] = config::sunshine.locale;
send_response(response, output_tree);
}
/**
* @brief Save the configuration settings.
* @param response The HTTP response object.
* @param request The HTTP request object.
* The body for the post request should be JSON serialized in the following format:
* @code{.json}
* {
* "key": "value"
* }
* @endcode
*
* @attention{It is recommended to ONLY save the config settings that differ from the default behavior.}
*
* @api_examples{/api/config| POST| {"key":"value"}}
*/
void saveConfig(resp_https_t response, req_https_t request) {
if (!check_content_type(response, request, "application/json")) {
return;
}
if (!authenticate(response, request)) {
return;
}
print_req(request);