-
-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathconfighttp.cpp
More file actions
1930 lines (1655 loc) · 66.4 KB
/
Copy pathconfighttp.cpp
File metadata and controls
1930 lines (1655 loc) · 66.4 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 <algorithm>
#include <filesystem>
#include <format>
#include <fstream>
#include <string_view>
// 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>
#ifdef _WIN32
#include "platform/windows/misc.h"
#include <vector>
#include <Windows.h>
#endif
// 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 "rtsp.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<SimpleWeb::ServerBase<SimpleWeb::HTTPS>::Response>;
using req_https_t = std::shared_ptr<SimpleWeb::ServerBase<SimpleWeb::HTTPS>::Request>;
using https_handler_t = std::function<void(resp_https_t, req_https_t)>;
enum class op_e {
ADD, ///< Add client
REMOVE ///< Remove client
};
// CSRF token management
struct csrf_token_t {
std::string token;
std::chrono::steady_clock::time_point expiration;
};
// Store CSRF tokens with thread safety
std::map<std::string, csrf_token_t, std::less<>> csrf_tokens; // NOSONAR(cpp:S5421) - intentionally mutable global
std::mutex csrf_tokens_mutex; // NOSONAR(cpp:S5421) - intentionally mutable global
// CSRF token configuration
constexpr auto CSRF_TOKEN_SIZE = 32; // 32 bytes = 256 bits
constexpr auto CSRF_TOKEN_LIFETIME = std::chrono::hours(1); // Tokens valid for 1 hour
/**
* @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(const 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(const resp_https_t &response, const 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 auto 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(const resp_https_t &response, const 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(const resp_https_t &response, const req_https_t &request) {
auto address = net::addr_to_normalized_string(request->remote_endpoint().address());
if (const auto ip_type = net::from_address(address); 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);
});
const auto auth = request->header.find("authorization");
if (auth == request->header.end()) {
return false;
}
const auto &rawAuth = auth->second;
auto authData = SimpleWeb::Crypto::Base64::decode(rawAuth.substr("Basic "sv.length()));
const auto index = static_cast<int>(authData.find(':'));
if (index >= authData.size() - 1) {
return false;
}
const auto username = authData.substr(0, index);
const auto password = authData.substr(index + 1);
if (const auto hash = util::hex(crypto::hash(password + config::sunshine.salt)).to_string(); !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.
* @param error_message The error message to include in the response.
*/
void not_found(const resp_https_t &response, [[maybe_unused]] const req_https_t &request, const std::string &error_message) {
constexpr auto code = SimpleWeb::StatusCode::client_error_not_found;
nlohmann::json tree;
tree["status_code"] = code;
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 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(const resp_https_t &response, [[maybe_unused]] const req_https_t &request, const std::string &error_message) {
constexpr auto 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 a bad request when mismatched.
* @param response The HTTP response object.
* @param request The HTTP request object.
* @param contentType The expected content type
*/
bool check_content_type(const resp_https_t &response, const req_https_t &request, const std::string_view &contentType) {
const 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;
if (const size_t semicolonPos = actualContentType.find(';'); 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 a unique client identifier for CSRF token management.
* @param request The HTTP request object.
* @return A unique identifier based on username or IP address.
*/
std::string get_client_id(const req_https_t &request) {
// Try to use the authenticated username as client ID
if (const auto auth = request->header.find("authorization"); !config::sunshine.username.empty() && auth != request->header.end()) {
if (const auto &rawAuth = auth->second; rawAuth.rfind("Basic "sv, 0) == 0) {
auto authData = SimpleWeb::Crypto::Base64::decode(rawAuth.substr("Basic "sv.length()));
if (const auto index = static_cast<int>(authData.find(':')); index < authData.size() - 1) {
return authData.substr(0, index); // Return username
}
}
}
// Fall back to IP address if no username
return net::addr_to_normalized_string(request->remote_endpoint().address());
}
/**
* @brief Generate a new CSRF token for a client.
* @param client_id A unique identifier for the client (e.g., session ID or username).
* @return The generated CSRF token.
*/
std::string generate_csrf_token(const std::string &client_id) {
// Generate a cryptographically secure random token
std::string token = crypto::rand_alphabet(CSRF_TOKEN_SIZE);
std::scoped_lock lock(csrf_tokens_mutex);
// Clean up expired tokens first
const auto now = std::chrono::steady_clock::now();
std::erase_if(csrf_tokens, [&now](const auto &entry) {
return entry.second.expiration < now;
});
// Store the token with expiration
csrf_tokens[client_id] = csrf_token_t {
token,
now + CSRF_TOKEN_LIFETIME
};
return token;
}
/**
* @brief Validate a stored CSRF token for a client against a provided token string.
* @param response The HTTP response object.
* @param request The HTTP request object.
* @param client_id A unique identifier for the client.
* @param provided_token The token string to validate.
* @return True if the token is valid, false otherwise.
*/
bool validate_stored_csrf_token(const resp_https_t &response, const req_https_t &request, const std::string_view client_id, const std::string_view provided_token) {
std::scoped_lock lock(csrf_tokens_mutex);
const auto token_it = csrf_tokens.find(client_id);
if (token_it == csrf_tokens.end()) {
auto address = net::addr_to_normalized_string(request->remote_endpoint().address());
BOOST_LOG(error) << "Web UI: ["sv << address << "] -- CSRF token validation failed: no token found for client"sv;
bad_request(response, request, "Invalid CSRF token");
return false;
}
if (const auto now = std::chrono::steady_clock::now(); token_it->second.expiration < now) {
csrf_tokens.erase(token_it);
auto address = net::addr_to_normalized_string(request->remote_endpoint().address());
BOOST_LOG(error) << "Web UI: ["sv << address << "] -- CSRF token validation failed: token expired"sv;
bad_request(response, request, "CSRF token expired");
return false;
}
if (token_it->second.token != provided_token) {
auto address = net::addr_to_normalized_string(request->remote_endpoint().address());
BOOST_LOG(error) << "Web UI: ["sv << address << "] -- CSRF token validation failed: token mismatch"sv;
bad_request(response, request, "Invalid CSRF token");
return false;
}
return true;
}
bool validate_csrf_token(const resp_https_t &response, const req_https_t &request, const std::string &client_id) {
// Helper function to check if a URL starts with any allowed origin
auto is_allowed_origin = [](const std::string_view url) {
return std::ranges::any_of(config::sunshine.csrf_allowed_origins, [&url](const std::string &allowed_origin) {
// Ensure exact prefix match (with ":" or "/" after to prevent malicious.com matching allowed.com)
if (url.rfind(allowed_origin, 0) != 0) { // rfind with pos=0 checks if the url starts with allowed_origin
return false;
}
// Check that it's followed by ":" (port) or "/" (path) or is an exact match
const size_t len = allowed_origin.length();
return url.length() == len || url[len] == ':' || url[len] == '/';
});
};
// Check if the request is from the same origin (Origin or Referer header matches configured allowed origins)
const auto origin_it = request->header.find("Origin");
if (origin_it != request->header.end() && is_allowed_origin(origin_it->second)) {
// Same origin request - allow without CSRF token
return true;
}
// If we have a Referer header, check if it's same-origin
const auto referer_it = request->header.find("Referer");
if (referer_it != request->header.end() && is_allowed_origin(referer_it->second)) {
// Same origin request - allow without CSRF token
return true;
}
// If neither Origin nor Referer is present, this cannot be a browser-initiated CSRF attack.
// Non-browser clients (e.g. curl, scripts) never send these headers, and a malicious web page
// cannot cause a non-browser client to make requests on a user's behalf.
if (origin_it == request->header.end() && referer_it == request->header.end()) {
return true;
}
// A browser-like request arrived with an Origin/Referer that doesn't match an allowed origin.
// Require a CSRF token.
const std::string_view blocked_origin = (origin_it != request->header.end()) ? origin_it->second : referer_it->second;
// Extract token from X-CSRF-Token header
const auto header_it = request->header.find("X-CSRF-Token");
if (header_it == request->header.end()) {
// Also check query parameters as fallback
auto query_params = request->parse_query_string();
const auto query_it = query_params.find("csrf_token");
if (query_it == query_params.end()) {
auto address = net::addr_to_normalized_string(request->remote_endpoint().address());
BOOST_LOG(error) << "Web UI: ["sv << address << "] -- CSRF protection blocked request from origin: "sv << blocked_origin;
BOOST_LOG(error) << "Web UI: To allow this origin, add it to the 'csrf_allowed_origins' option in your Sunshine configuration"sv;
bad_request(response, request, "Missing CSRF token");
return false;
}
return validate_stored_csrf_token(response, request, client_id, query_it->second);
}
// Validate token from header
return validate_stored_csrf_token(response, request, client_id, header_it->second);
}
/**
* @brief Validates the application index and sends an error response if invalid.
* @param response The HTTP response object.
* @param request The HTTP request object.
* @param index The application index/id.
*/
bool check_app_index(const resp_https_t &response, const req_https_t &request, int index) {
std::string file = file_handler::read_file(config::stream.file_apps.c_str());
nlohmann::json file_tree = nlohmann::json::parse(file);
if (const auto &apps = file_tree["apps"]; index < 0 || index >= static_cast<int>(apps.size())) {
std::string error;
if (const int max_index = static_cast<int>(apps.size()) - 1; max_index < 0) {
error = "No applications found";
} else {
error = std::format("'index' {} out of range, max index is {}", index, max_index);
}
bad_request(response, request, error);
return false;
}
return true;
}
/**
* @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 an HTML page.
* @param response The HTTP response object.
* @param request The HTTP request object.
* @param html_file The HTML file to serve (relative to WEB_DIR).
* @param require_auth Whether to require authentication (default: true).
* @param redirect_if_username If true, redirect to "/" when the username is set (for welcome page).
*/
void getPage(const resp_https_t &response, const req_https_t &request, const char *html_file, const bool require_auth, const bool redirect_if_username) {
// Special handling for welcome page: redirect if the username is already set
if (redirect_if_username && !config::sunshine.username.empty()) {
send_redirect(response, request, "/");
return;
}
if (require_auth && !authenticate(response, request)) {
return;
}
print_req(request);
const std::string content = file_handler::read_file((std::string(WEB_DIR) + html_file).c_str());
SimpleWeb::CaseInsensitiveMultimap headers;
headers.emplace("Content-Type", "text/html; charset=utf-8");
// prevent click jacking
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(const resp_https_t &response, const 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(const resp_https_t &response, const 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.
* @param response The HTTP response object.
* @param request The HTTP request object.
*/
void getAsset(const resp_https_t &response, const 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 the 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 a CSRF token for the authenticated user.
* @param response The HTTP response object.
* @param request The HTTP request object.
*
* @api_examples{/api/csrf-token| GET| null}
*/
void getCSRFToken(const resp_https_t &response, const req_https_t &request) {
if (!authenticate(response, request)) {
return;
}
print_req(request);
std::string client_id = get_client_id(request);
std::string token = generate_csrf_token(client_id);
nlohmann::json output_tree;
output_tree["csrf_token"] = token;
send_response(response, output_tree);
}
/**
* @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(const resp_https_t &response, const 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
const 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(const resp_https_t &response, const req_https_t &request) {
if (!check_content_type(response, request, "application/json")) {
return;
}
if (!authenticate(response, request)) {
return;
}
std::string client_id = get_client_id(request);
if (!validate_csrf_token(response, request, client_id)) {
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 an 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(const resp_https_t &response, const req_https_t &request) {
if (!authenticate(response, request)) {
return;
}
std::string client_id = get_client_id(request);
if (!validate_csrf_token(response, request, client_id)) {
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(const resp_https_t &response, const req_https_t &request) {
if (!authenticate(response, request)) {
return;
}
std::string client_id = get_client_id(request);
if (!validate_csrf_token(response, request, client_id)) {
return;
}
print_req(request);
try {
nlohmann::json output_tree;
nlohmann::json new_apps = nlohmann::json::array();
const int index = std::stoi(request->path_match[1]);
if (!check_app_index(response, request, index)) {
return;
}
std::string file = file_handler::read_file(config::stream.file_apps.c_str());
nlohmann::json file_tree = nlohmann::json::parse(file);
auto &apps = file_tree["apps"];
for (size_t i = 0; i < apps.size(); ++i) {
if (i != index) {
new_apps.push_back(apps[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(const resp_https_t &response, const 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 Enable or disable 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>",
* "enabled": true
* }
* @endcode
*
* @api_examples{/api/clients/update| POST| {"uuid":"<uuid>","enabled":true}}
*/
void updateClient(resp_https_t response, req_https_t request) {
if (!check_content_type(response, request, "application/json")) {
return;
}
if (!authenticate(response, request)) {
return;
}
std::string client_id = get_client_id(request);
if (!validate_csrf_token(response, request, client_id)) {
return;
}
print_req(request);
std::stringstream ss;
ss << request->content.rdbuf();
try {
nlohmann::json input_tree = nlohmann::json::parse(ss.str());
nlohmann::json output_tree;
std::string uuid = input_tree.value("uuid", "");
bool enabled = input_tree.value("enabled", true);
output_tree["status"] = nvhttp::set_client_enabled(uuid, enabled);
if (!enabled && output_tree["status"]) {
auto cert = nvhttp::get_cert_by_uuid(uuid);
if (!cert.empty()) {
rtsp_stream::terminate_sessions_by_cert(cert);
}
if (rtsp_stream::session_count() == 0 && proc::proc.running() > 0) {
proc::proc.terminate();
}
}
send_response(response, output_tree);
} catch (nlohmann::json::exception &e) {
BOOST_LOG(warning) << "Update Client: "sv << e.what();
bad_request(response, request, e.what());
}
}
/**
* @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(const resp_https_t &response, const req_https_t &request) {
if (!check_content_type(response, request, "application/json")) {
return;
}
if (!authenticate(response, request)) {
return;
}
std::string client_id = get_client_id(request);
if (!validate_csrf_token(response, request, client_id)) {
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", "");
const bool removed = nvhttp::unpair_client(uuid);
output_tree["status"] = removed;
if (removed && nvhttp::get_all_clients().empty()) {
proc::proc.terminate();
}
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(const resp_https_t &response, const req_https_t &request) {
if (!authenticate(response, request)) {
return;
}
std::string client_id = get_client_id(request);
if (!validate_csrf_token(response, request, client_id)) {
return;
}
print_req(request);
nvhttp::erase_all_clients();
proc::proc.terminate();
nlohmann::json output_tree;
output_tree["status"] = true;
send_response(response, output_tree);
}
/**