-
-
Notifications
You must be signed in to change notification settings - Fork 988
/
server.cpp
1858 lines (1506 loc) · 56.4 KB
/
server.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
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright (C) 2003 - 2018 by David White <dave@whitevine.net>
Copyright (C) 2015 - 2020 by Iris Morelle <shadowm2006@gmail.com>
Part of the Battle for Wesnoth Project https://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY.
See the COPYING file for more details.
*/
/**
* @file
* Wesnoth addon server.
* Expects a "server.cfg" config file in the current directory
* and saves addons under data/.
*/
#include "server/campaignd/server.hpp"
#include "filesystem.hpp"
#include "lexical_cast.hpp"
#include "log.hpp"
#include "serialization/base64.hpp"
#include "serialization/binary_or_text.hpp"
#include "serialization/parser.hpp"
#include "serialization/string_utils.hpp"
#include "serialization/unicode.hpp"
#include "game_config.hpp"
#include "addon/validation.hpp"
#include "server/campaignd/addon_utils.hpp"
#include "server/campaignd/auth.hpp"
#include "server/campaignd/blacklist.hpp"
#include "server/campaignd/control.hpp"
#include "server/campaignd/fs_commit.hpp"
#include "server/campaignd/options.hpp"
#include "game_version.hpp"
#include "hash.hpp"
#include "utils/optimer.hpp"
#include <csignal>
#include <ctime>
#include <iomanip>
// the fork execute is unix specific only tested on Linux quite sure it won't
// work on Windows not sure which other platforms have a problem with it.
#if !(defined(_WIN32))
#include <errno.h>
#endif
static lg::log_domain log_campaignd("campaignd");
#define DBG_CS LOG_STREAM(debug, log_campaignd)
#define LOG_CS LOG_STREAM(info, log_campaignd)
#define WRN_CS LOG_STREAM(warn, log_campaignd)
#define ERR_CS LOG_STREAM(err, log_campaignd)
static lg::log_domain log_config("config");
#define ERR_CONFIG LOG_STREAM(err, log_config)
#define WRN_CONFIG LOG_STREAM(warn, log_config)
static lg::log_domain log_server("server");
#define ERR_SERVER LOG_STREAM(err, log_server)
namespace campaignd {
namespace {
/**
* campaignd capabilities supported by this version of the server.
*
* These are advertised to clients using the @a [server_id] command. They may
* be disabled or re-enabled at runtime.
*/
const std::set<std::string> cap_defaults = {
// Legacy item and passphrase-based authentication
"auth:legacy",
// Delta WML packs
"delta",
};
/**
* Default URL to the add-ons server web index.
*/
const std::string default_web_url = "https://add-ons.wesnoth.org/";
/**
* Default license terms for content uploaded to the server.
*
* This used by both the @a [server_id] command and @a [request_terms] in
* their responses.
*
* The text is intended for display on the client with Pango markup enabled and
* sent by the server as-is, so it ought to be formatted accordingly.
*/
const std::string default_license_notice = R"""(<span size='x-large'>General Rules</span>
The current version of the server rules can be found at: https://r.wesnoth.org/t51347
<span color='#f88'>Any content that does not conform to the rules listed at the link above, as well as the licensing terms below, may be removed at any time without prior notice.</span>
<span size='x-large'>Licensing</span>
All content within add-ons uploaded to this server must be licensed under the terms of the GNU General Public License (GPL), version 2 or later, with the sole exception of graphics and audio explicitly denoted as released under a Creative Commons license either in:
a) a combined toplevel file, e.g. “<span font_family='monospace'>My_Addon/ART_LICENSE</span>”; <b>or</b>
b) a file with the same path as the asset with “<span font_family='monospace'>.license</span>” appended, e.g. “<span font_family='monospace'>My_Addon/images/units/axeman.png.license</span>”.
<b>By uploading content to this server, you certify that you have the right to:</b>
a) release all included art and audio explicitly denoted with a Creative Commons license in the prescribed manner under that license; <b>and</b>
b) release all other included content under the terms of the chosen versions of the GNU GPL.)""";
bool timing_reports_enabled = false;
void timing_report_function(const util::ms_optimer& tim, const campaignd::server::request& req, const std::string& label = {})
{
if(timing_reports_enabled) {
if(label.empty()) {
LOG_CS << req << "Time elapsed: " << tim << " ms\n";
} else {
LOG_CS << req << "Time elapsed [" << label << "]: " << tim << " ms\n";
}
}
}
inline util::ms_optimer service_timer(const campaignd::server::request& req, const std::string& label = {})
{
return util::ms_optimer{std::bind(timing_report_function, std::placeholders::_1, req, label)};
}
//
// Auxiliary shortcut functions
//
/**
* WML version of campaignd::auth::verify_passphrase().
*
* The salt and hash are retrieved from the @a passsalt and @a passhash
* attributes, respectively.
*/
inline bool authenticate(config& addon, const config::attribute_value& passphrase)
{
return auth::verify_passphrase(passphrase, addon["passsalt"], addon["passhash"]);
}
/**
* WML version of campaignd::auth::generate_hash().
*
* The salt and hash are written into the @a passsalt and @a passhash
* attributes, respectively.
*/
inline void set_passphrase(config& addon, const std::string& passphrase)
{
std::tie(addon["passsalt"], addon["passhash"]) = auth::generate_hash(passphrase);
}
/**
* Returns the update pack filename for the specified old/new version pair.
*
* The filename is in the form @p "update_pack_<VERSION_MD5>.gz".
*/
inline std::string make_update_pack_filename(const std::string& old_version, const std::string& new_version)
{
return "update_pack_" + utils::md5(old_version + new_version).hex_digest() + ".gz";
}
/**
* Returns the full pack filename for the specified version.
*
* The filename is in the form @p "full_pack_<VERSION_MD5>.gz".
*/
inline std::string make_full_pack_filename(const std::string& version)
{
return "full_pack_" + utils::md5(version).hex_digest() + ".gz";
}
/**
* Returns the index filename for the specified version.
*
* The filename is in the form @p "full_pack_<VERSION_MD5>.hash.gz".
*/
inline std::string make_index_filename(const std::string& version)
{
return "full_pack_" + utils::md5(version).hex_digest() + ".hash.gz";
}
/**
* Returns the index counterpart for the specified full pack file.
*
* The result is in the same form as make_index_filename().
*/
inline std::string index_from_full_pack_filename(std::string pack_fn)
{
auto dot_pos = pack_fn.find_last_of('.');
if(dot_pos != std::string::npos) {
pack_fn.replace(dot_pos, std::string::npos, ".hash.gz");
}
return pack_fn;
}
/**
* Returns @a false if @a cfg is null or empty.
*/
bool have_wml(const utils::optional_reference<const config>& cfg)
{
return cfg && !cfg->empty();
}
/**
* Scans multiple WML pack-like trees for illegal names.
*
* Null WML objects are skipped.
*/
bool multi_find_illegal_names(std::vector<std::string>& names, const std::vector<const config*>& indices)
{
names.clear();
for(auto* index : indices) {
if(index) {
check_names_legal(*index, &names);
}
}
return !names.empty();
}
/**
* Scans multiple WML pack-like trees for case conflicts.
*
* Null WML objects are skipped.
*/
bool multi_find_case_conflicts(std::vector<std::string>& names, const std::vector<const config*>& indices)
{
names.clear();
for(auto* index : indices) {
if(index) {
check_case_insensitive_duplicates(*index, &names);
}
}
return !names.empty();
}
/**
* Escapes double quotes intended to be passed into simple_wml.
*
* Just why does simple_wml have to be so broken to force us to use this, though?
*/
std::string simple_wml_escape(const std::string& text)
{
std::string res;
auto it = text.begin();
while(it != text.end()) {
res.append(*it == '"' ? 2 : 1, *it);
++it;
}
return res;
}
} // end anonymous namespace
server::server(const std::string& cfg_file, unsigned short port)
: server_base(default_campaignd_port, true)
, capabilities_(cap_defaults)
, addons_()
, dirty_addons_()
, cfg_()
, cfg_file_(cfg_file)
, read_only_(false)
, compress_level_(0)
, update_pack_lifespan_(0)
, strict_versions_(true)
, hooks_()
, handlers_()
, feedback_url_format_()
, web_url_()
, license_notice_()
, blacklist_()
, blacklist_file_()
, stats_exempt_ips_()
, flush_timer_(io_service_)
{
#ifndef _WIN32
struct sigaction sa;
std::memset( &sa, 0, sizeof(sa) );
#pragma GCC diagnostic ignored "-Wold-style-cast"
sa.sa_handler = SIG_IGN;
int res = sigaction( SIGPIPE, &sa, nullptr);
assert( res == 0 );
#endif
load_config();
// Command line config override. This won't get saved back to disk since we
// leave the WML intentionally untouched.
if(port != 0) {
port_ = port;
}
LOG_CS << "Port: " << port_ << '\n';
LOG_CS << "Server directory: " << game_config::path << " (" << addons_.size() << " add-ons)\n";
register_handlers();
start_server();
flush_cfg();
}
server::~server()
{
write_config();
}
void server::load_config()
{
LOG_CS << "Reading configuration from " << cfg_file_ << "...\n";
filesystem::scoped_istream in = filesystem::istream_file(cfg_file_);
read(cfg_, *in);
read_only_ = cfg_["read_only"].to_bool(false);
if(read_only_) {
LOG_CS << "READ-ONLY MODE ACTIVE\n";
}
strict_versions_ = cfg_["strict_versions"].to_bool(true);
// Seems like compression level above 6 is a waste of CPU cycles.
compress_level_ = cfg_["compress_level"].to_int(6);
// One month probably will be fine (#TODO: testing needed)
update_pack_lifespan_ = cfg_["update_pack_lifespan"].to_time_t(30 * 24 * 60 * 60);
if(const auto& svinfo_cfg = server_info()) {
feedback_url_format_ = svinfo_cfg["feedback_url_format"].str();
web_url_ = svinfo_cfg["web_url"].str(default_web_url);
license_notice_ = svinfo_cfg["license_notice"].str(default_license_notice);
}
blacklist_file_ = cfg_["blacklist_file"].str();
load_blacklist();
stats_exempt_ips_ = utils::split(cfg_["stats_exempt_ips"].str());
// Load any configured hooks.
hooks_.emplace(std::string("hook_post_upload"), cfg_["hook_post_upload"]);
hooks_.emplace(std::string("hook_post_erase"), cfg_["hook_post_erase"]);
#ifndef _WIN32
// Open the control socket if enabled.
if(!cfg_["control_socket"].empty()) {
const std::string& path = cfg_["control_socket"].str();
if(path != fifo_path_) {
const int res = mkfifo(path.c_str(),0660);
if(res != 0 && errno != EEXIST) {
ERR_CS << "could not make fifo at '" << path << "' (" << strerror(errno) << ")\n";
} else {
input_.close();
int fifo = open(path.c_str(), O_RDWR|O_NONBLOCK);
input_.assign(fifo);
LOG_CS << "opened fifo at '" << path << "'. Server commands may be written to this file.\n";
read_from_fifo();
fifo_path_ = path;
}
}
}
#endif
// Certain config values are saved to WML again so that a given server
// instance's parameters remain constant even if the code defaults change
// at some later point.
cfg_["compress_level"] = compress_level_;
// But not the listening port number.
port_ = cfg_["port"].to_int(default_campaignd_port);
// Limit the max size of WML documents received from the net to prevent the
// possible excessive use of resources due to malformed packets received.
// Since an addon is sent in a single WML document this essentially limits
// the maximum size of an addon that can be uploaded.
simple_wml::document::document_size_limit = cfg_["document_size_limit"].to_int(default_document_size_limit);
//Loading addons
addons_.clear();
std::vector<std::string> legacy_addons, dirs;
filesystem::get_files_in_dir("data", &legacy_addons, &dirs);
config meta;
for(const std::string& addon_dir : dirs) {
in = filesystem::istream_file(filesystem::normalize_path("data/" + addon_dir + "/addon.cfg"));
read(meta, *in);
if(!meta.empty()) {
addons_.emplace(meta["name"].str(), meta);
} else {
throw filesystem::io_exception("Failed to load addon from dir '" + addon_dir + "'\n");
}
}
// Convert all legacy addons to the new format on load
if(cfg_.has_child("campaigns")) {
config& campaigns = cfg_.child("campaigns");
WRN_CS << "Old format addons have been detected in the config! They will be converted to the new file format! "
<< campaigns.child_count("campaign") << " entries to be processed.\n";
for(config& campaign : campaigns.child_range("campaign")) {
const std::string& addon_id = campaign["name"].str();
const std::string& addon_file = campaign["filename"].str();
if(get_addon(addon_id)) {
throw filesystem::io_exception("The addon '" + addon_id
+ "' already exists in the new form! Possible code or filesystem interference!\n");
}
if(std::find(legacy_addons.begin(), legacy_addons.end(), addon_id) == legacy_addons.end()) {
throw filesystem::io_exception("No file has been found for the legacy addon '" + addon_id
+ "'. Check the file structure!\n");
}
config data;
in = filesystem::istream_file(filesystem::normalize_path(addon_file));
read_gz(data, *in);
if(!data) {
throw filesystem::io_exception("Couldn't read the content file for the legacy addon '" + addon_id + "'!\n");
}
config version_cfg = config("version", campaign["version"].str());
version_cfg["filename"] = make_full_pack_filename(campaign["version"]);
campaign.add_child("version", version_cfg);
data.remove_attributes("title", "campaign_name", "author", "description", "version", "timestamp", "original_timestamp", "icon", "type", "tags");
filesystem::delete_file(filesystem::normalize_path(addon_file));
{
filesystem::atomic_commit campaign_file(addon_file + "/" + version_cfg["filename"].str());
config_writer writer(*campaign_file.ostream(), true, compress_level_);
writer.write(data);
campaign_file.commit();
}
{
filesystem::atomic_commit campaign_hash_file(addon_file + "/" + make_index_filename(campaign["version"]));
config_writer writer(*campaign_hash_file.ostream(), true, compress_level_);
config data_hash = config("name", "");
write_hashlist(data_hash, data);
writer.write(data_hash);
campaign_hash_file.commit();
}
addons_.emplace(addon_id, campaign);
mark_dirty(addon_id);
}
cfg_.clear_children("campaigns");
LOG_CS << "Legacy addons processing finished.\n";
write_config();
}
LOG_CS << "Loaded addons metadata. " << addons_.size() << " addons found.\n";
}
std::ostream& operator<<(std::ostream& o, const server::request& r)
{
o << '[' << r.addr << ' ' << r.cmd << "] ";
return o;
}
void server::handle_new_client(socket_ptr socket)
{
boost::asio::spawn(io_service_, [this, socket](boost::asio::yield_context yield) {
while(true) {
boost::system::error_code ec;
auto doc { coro_receive_doc(socket, yield[ec]) };
if(check_error(ec, socket) || !doc) return;
config data;
read(data, doc->output());
config::all_children_iterator i = data.ordered_begin();
if(i != data.ordered_end()) {
// We only handle the first child.
const config::any_child& c = *i;
request_handlers_table::const_iterator j
= handlers_.find(c.key);
if(j != handlers_.end()) {
// Call the handler.
request req{c.key, c.cfg, socket, yield};
auto st = service_timer(req);
j->second(this, req);
} else {
send_error("Unrecognized [" + c.key + "] request.",socket);
}
}
}
});
}
#ifndef _WIN32
void server::handle_read_from_fifo(const boost::system::error_code& error, std::size_t)
{
if(error) {
if(error == boost::asio::error::operation_aborted)
// This means fifo was closed by load_config() to open another fifo
return;
ERR_CS << "Error reading from fifo: " << error.message() << '\n';
return;
}
std::istream is(&admin_cmd_);
std::string cmd;
std::getline(is, cmd);
const control_line ctl = cmd;
if(ctl == "shut_down") {
LOG_CS << "Shut down requested by admin, shutting down...\n";
throw server_shutdown("Shut down via fifo command");
} else if(ctl == "readonly") {
if(ctl.args_count()) {
cfg_["read_only"] = read_only_ = utils::string_bool(ctl[1], true);
}
LOG_CS << "Read only mode: " << (read_only_ ? "enabled" : "disabled") << '\n';
} else if(ctl == "flush") {
LOG_CS << "Flushing config to disk...\n";
write_config();
} else if(ctl == "reload") {
if(ctl.args_count()) {
if(ctl[1] == "blacklist") {
LOG_CS << "Reloading blacklist...\n";
load_blacklist();
} else {
ERR_CS << "Unrecognized admin reload argument: " << ctl[1] << '\n';
}
} else {
LOG_CS << "Reloading all configuration...\n";
load_config();
LOG_CS << "Reloaded configuration\n";
}
} else if(ctl == "delete") {
if(ctl.args_count() != 1) {
ERR_CS << "Incorrect number of arguments for 'delete'\n";
} else {
const std::string& addon_id = ctl[1];
LOG_CS << "deleting add-on '" << addon_id << "' requested from control FIFO\n";
delete_addon(addon_id);
}
} else if(ctl == "hide" || ctl == "unhide") {
if(ctl.args_count() != 1) {
ERR_CS << "Incorrect number of arguments for '" << ctl.cmd() << "'\n";
} else {
const std::string& addon_id = ctl[1];
config& addon = get_addon(addon_id);
if(!addon) {
ERR_CS << "Add-on '" << addon_id << "' not found, cannot " << ctl.cmd() << "\n";
} else {
addon["hidden"] = ctl.cmd() == "hide";
mark_dirty(addon_id);
write_config();
LOG_CS << "Add-on '" << addon_id << "' is now " << (ctl.cmd() == "hide" ? "hidden" : "unhidden") << '\n';
}
}
} else if(ctl == "setpass") {
if(ctl.args_count() != 2) {
ERR_CS << "Incorrect number of arguments for 'setpass'\n";
} else {
const std::string& addon_id = ctl[1];
const std::string& newpass = ctl[2];
config& addon = get_addon(addon_id);
if(!addon) {
ERR_CS << "Add-on '" << addon_id << "' not found, cannot set passphrase\n";
} else if(newpass.empty()) {
// Shouldn't happen!
ERR_CS << "Add-on passphrases may not be empty!\n";
} else {
set_passphrase(addon, newpass);
mark_dirty(addon_id);
write_config();
LOG_CS << "New passphrase set for '" << addon_id << "'\n";
}
}
} else if(ctl == "setattr") {
if(ctl.args_count() != 3) {
ERR_CS << "Incorrect number of arguments for 'setattr'\n";
} else {
const std::string& addon_id = ctl[1];
const std::string& key = ctl[2];
const std::string& value = ctl[3];
config& addon = get_addon(addon_id);
if(!addon) {
ERR_CS << "Add-on '" << addon_id << "' not found, cannot set attribute\n";
} else if(key == "name" || key == "version") {
ERR_CS << "setattr cannot be used to rename add-ons or change their version\n";
} else if(key == "passhash"|| key == "passsalt") {
ERR_CS << "setattr cannot be used to set auth data -- use setpass instead\n";
} else if(!addon.has_attribute(key)) {
// NOTE: This is a very naive approach for validating setattr's
// input, but it should generally work since add-on
// uploads explicitly set all recognized attributes to
// the values provided by the .pbl data or the empty
// string if absent, and this is normally preserved by
// the config serialization.
ERR_CS << "Attribute '" << value << "' is not a recognized add-on attribute\n";
} else {
addon[key] = value;
mark_dirty(addon_id);
write_config();
LOG_CS << "Set attribute on add-on '" << addon_id << "':\n"
<< key << "=\"" << value << "\"\n";
}
}
} else {
ERR_CS << "Unrecognized admin command: " << ctl.full() << '\n';
}
read_from_fifo();
}
void server::handle_sighup(const boost::system::error_code&, int)
{
LOG_CS << "SIGHUP caught, reloading config.\n";
load_config(); // TODO: handle port number config changes
LOG_CS << "Reloaded configuration\n";
sighup_.async_wait(std::bind(&server::handle_sighup, this, std::placeholders::_1, std::placeholders::_2));
}
#endif
void server::flush_cfg()
{
flush_timer_.expires_from_now(std::chrono::minutes(10));
flush_timer_.async_wait(std::bind(&server::handle_flush, this, std::placeholders::_1));
}
void server::handle_flush(const boost::system::error_code& error)
{
if(error) {
ERR_CS << "Error from reload timer: " << error.message() << "\n";
throw boost::system::system_error(error);
}
write_config();
flush_cfg();
}
void server::load_blacklist()
{
// We *always* want to clear the blacklist first, especially if we are
// reloading the configuration and the blacklist is no longer enabled.
blacklist_.clear();
if(blacklist_file_.empty()) {
return;
}
try {
filesystem::scoped_istream in = filesystem::istream_file(blacklist_file_);
config blcfg;
read(blcfg, *in);
blacklist_.read(blcfg);
LOG_CS << "using blacklist from " << blacklist_file_ << '\n';
} catch(const config::error&) {
ERR_CS << "failed to read blacklist from " << blacklist_file_ << ", blacklist disabled\n";
}
}
void server::write_config()
{
DBG_CS << "writing configuration and add-ons list to disk...\n";
filesystem::atomic_commit out(cfg_file_);
write(*out.ostream(), cfg_);
out.commit();
for(const std::string& name : dirty_addons_) {
const config& addon = get_addon(name);
if(addon && !addon["filename"].empty()) {
filesystem::atomic_commit addon_out(filesystem::normalize_path(addon["filename"].str() + "/addon.cfg"));
write(*addon_out.ostream(), addon);
addon_out.commit();
}
}
dirty_addons_.clear();
DBG_CS << "... done\n";
}
void server::fire(const std::string& hook, [[maybe_unused]] const std::string& addon)
{
const std::map<std::string, std::string>::const_iterator itor = hooks_.find(hook);
if(itor == hooks_.end()) {
return;
}
const std::string& script = itor->second;
if(script.empty()) {
return;
}
#if defined(_WIN32)
ERR_CS << "Tried to execute a script on an unsupported platform\n";
return;
#else
pid_t childpid;
if((childpid = fork()) == -1) {
ERR_CS << "fork failed while updating add-on " << addon << '\n';
return;
}
if(childpid == 0) {
// We are the child process. Execute the script. We run as a
// separate thread sharing stdout/stderr, which will make the
// log look ugly.
execlp(script.c_str(), script.c_str(), addon.c_str(), static_cast<char *>(nullptr));
// exec() and family never return; if they do, we have a problem
std::cerr << "ERROR: exec failed with errno " << errno << " for addon " << addon
<< '\n';
exit(errno);
} else {
return;
}
#endif
}
bool server::ignore_address_stats(const std::string& addr) const
{
for(const auto& mask : stats_exempt_ips_) {
// TODO: we want CIDR subnet mask matching here, not glob matching!
if(utils::wildcard_string_match(addr, mask)) {
return true;
}
}
return false;
}
void server::send_message(const std::string& msg, socket_ptr sock)
{
const auto& escaped_msg = simple_wml_escape(msg);
simple_wml::document doc;
doc.root().add_child("message").set_attr_dup("message", escaped_msg.c_str());
async_send_doc_queued(sock, doc);
}
void server::send_error(const std::string& msg, socket_ptr sock)
{
ERR_CS << "[" << client_address(sock) << "] " << msg << '\n';
const auto& escaped_msg = simple_wml_escape(msg);
simple_wml::document doc;
doc.root().add_child("error").set_attr_dup("message", escaped_msg.c_str());
async_send_doc_queued(sock, doc);
}
void server::send_error(const std::string& msg, const std::string& extra_data, unsigned int status_code, socket_ptr sock)
{
const std::string& status_hex = formatter()
<< "0x" << std::setfill('0') << std::setw(2*sizeof(unsigned int)) << std::hex
<< std::uppercase << status_code;
ERR_CS << "[" << client_address(sock) << "]: (" << status_hex << ") " << msg << '\n';
const auto& escaped_status_str = simple_wml_escape(std::to_string(status_code));
const auto& escaped_msg = simple_wml_escape(msg);
const auto& escaped_extra_data = simple_wml_escape(extra_data);
simple_wml::document doc;
simple_wml::node& err_cfg = doc.root().add_child("error");
err_cfg.set_attr_dup("message", escaped_msg.c_str());
err_cfg.set_attr_dup("extra_data", escaped_extra_data.c_str());
err_cfg.set_attr_dup("status_code", escaped_status_str.c_str());
async_send_doc_queued(sock, doc);
}
config& server::get_addon(const std::string& id)
{
auto addon = addons_.find(id);
if(addon != addons_.end()) {
return addon->second;
} else {
return config::get_invalid();
}
}
void server::delete_addon(const std::string& id)
{
config& cfg = get_addon(id);
if(!cfg) {
ERR_CS << "Cannot delete unrecognized add-on '" << id << "'\n";
return;
}
std::string fn = cfg["filename"].str();
if(fn.empty()) {
ERR_CS << "Add-on '" << id << "' does not have an associated filename, cannot delete\n";
}
if(!filesystem::delete_directory(fn)) {
ERR_CS << "Could not delete the directory for addon '" << id
<< "' (" << fn << "): " << strerror(errno) << '\n';
}
addons_.erase(id);
write_config();
fire("hook_post_erase", id);
LOG_CS << "Deleted add-on '" << id << "'\n";
}
#define REGISTER_CAMPAIGND_HANDLER(req_id) \
handlers_[#req_id] = std::bind(&server::handle_##req_id, \
std::placeholders::_1, std::placeholders::_2)
void server::register_handlers()
{
REGISTER_CAMPAIGND_HANDLER(server_id);
REGISTER_CAMPAIGND_HANDLER(request_campaign_list);
REGISTER_CAMPAIGND_HANDLER(request_campaign);
REGISTER_CAMPAIGND_HANDLER(request_campaign_hash);
REGISTER_CAMPAIGND_HANDLER(request_terms);
REGISTER_CAMPAIGND_HANDLER(upload);
REGISTER_CAMPAIGND_HANDLER(delete);
REGISTER_CAMPAIGND_HANDLER(change_passphrase);
}
void server::handle_server_id(const server::request& req)
{
DBG_CS << req << "Sending server identification\n";
std::ostringstream ostr;
write(ostr, config{"server_id", config{
"cap", utils::join(capabilities_),
"version", game_config::revision,
"url", web_url_,
"license_notice", license_notice_,
}});
const auto& wml = ostr.str();
simple_wml::document doc(wml.c_str(), simple_wml::INIT_STATIC);
doc.compress();
async_send_doc_queued(req.sock, doc);
}
void server::handle_request_campaign_list(const server::request& req)
{
LOG_CS << req << "Sending add-ons list\n";
std::time_t epoch = std::time(nullptr);
config addons_list;
addons_list["timestamp"] = epoch;
if(req.cfg["times_relative_to"] != "now") {
epoch = 0;
}
bool before_flag = false;
std::time_t before = epoch;
if(!req.cfg["before"].empty()) {
before += req.cfg["before"].to_time_t();
before_flag = true;
}
bool after_flag = false;
std::time_t after = epoch;
if(!req.cfg["after"].empty()) {
after += req.cfg["after"].to_time_t();
after_flag = true;
}
const std::string& name = req.cfg["name"];
const std::string& lang = req.cfg["language"];
for(const auto& addon : addons_)
{
if(!name.empty() && name != addon.first) {
continue;
}
config i = addon.second;
if(i["hidden"].to_bool()) {
continue;
}
const auto& tm = i["timestamp"];
if(before_flag && (tm.empty() || tm.to_time_t(0) >= before)) {
continue;
}
if(after_flag && (tm.empty() || tm.to_time_t(0) <= after)) {
continue;
}
if(!lang.empty()) {
bool found = false;
for(const config& j : i.child_range("translation"))
{
if(j["language"] == lang && j["supported"].to_bool(true)) {//for old addons
found = true;
break;
}
}
if(!found) {
continue;
}
}
addons_list.add_child("campaign", i);
}
for(config& j : addons_list.child_range("campaign"))
{
// Remove attributes containing information that's considered sensitive
// or irrelevant to clients
j.remove_attributes("passphrase", "passhash", "passsalt", "upload_ip", "email");
// Build a feedback_url string attribute from the internal [feedback]
// data or deliver an empty value, in case clients decide to assume its
// presence.
const config& url_params = j.child_or_empty("feedback");
j["feedback_url"] = !url_params.empty() && !feedback_url_format_.empty()
? format_addon_feedback_url(feedback_url_format_, url_params) : "";
// Clients don't need to see the original data, so discard it.
j.clear_children("feedback");
// Update packs info is internal stuff
j.clear_children("update_pack");
}
config response;
response.add_child("campaigns", std::move(addons_list));
std::ostringstream ostr;
write(ostr, response);
std::string wml = ostr.str();
simple_wml::document doc(wml.c_str(), simple_wml::INIT_STATIC);
doc.compress();
async_send_doc_queued(req.sock, doc);
}
void server::handle_request_campaign(const server::request& req)
{
config& addon = get_addon(req.cfg["name"]);
if(!addon || addon["hidden"].to_bool()) {
send_error("Add-on '" + req.cfg["name"].str() + "' not found.", req.sock);
return;
}
const auto& name = req.cfg["name"].str();
auto version_map = get_version_map(addon);
if(version_map.empty()) {
send_error("No versions of the add-on '" + name + "' are available on the server.", req.sock);
return;
}
// Base the payload against the latest version if no particular version is being requested
const auto& from = req.cfg["from_version"].str();
const auto& to = req.cfg["version"].str(version_map.rbegin()->first);
auto to_version_iter = version_map.find(version_info{to});
if(to_version_iter == version_map.end()) {
send_error("Could not find requested version " + to + " of the addon '" + name +
"'.", req.sock);
return;
}
auto full_pack_path = addon["filename"].str() + '/' + to_version_iter->second["filename"].str();
const int full_pack_size = filesystem::file_size(full_pack_path);
if(!from.empty() && version_map.count(version_info{from}) != 0) {
// Build a sequence of updates beginning from the client's old version to the
// requested version. Every pair of incrementing versions on the server should
// have an update pack written to disk during the original upload(s).
//
// TODO: consider merging update packs instead of building a linear