/
game.cpp
1815 lines (1622 loc) · 63.2 KB
/
game.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 - 2015 by David White <dave@whitevine.net>
Part of the Battle for Wesnoth Project http://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.
*/
#include "../global.hpp"
#include "../filesystem.hpp"
#include "../game_config.hpp" // game_config::observer_team_name
#include "../log.hpp"
#include "game.hpp"
#include "player_network.hpp"
#include "serialization/string_utils.hpp"
#include "util.hpp"
#include <sstream>
#include <iomanip>
#include <boost/foreach.hpp>
#include <cstdio>
static lg::log_domain log_server("server");
#define ERR_GAME LOG_STREAM(err, log_server)
#define WRN_GAME LOG_STREAM(warn, log_server)
#define LOG_GAME LOG_STREAM(info, log_server)
#define DBG_GAME LOG_STREAM(debug, log_server)
static lg::log_domain log_config("config");
#define WRN_CONFIG LOG_STREAM(warn, log_config)
namespace
{
struct split_conv_impl
{
void operator()(std::vector<int>& res, const simple_wml::string_span& span)
{
if(!span.empty()) {
res.push_back(span.to_int());
}
}
};
template<typename TResult, typename TConvert>
std::vector<TResult> split(const simple_wml::string_span& val, TConvert conv, const char c = ',')
{
std::vector<TResult> res;
simple_wml::string_span::const_iterator i1 = val.begin();
simple_wml::string_span::const_iterator i2 = i1;
while (i2 != val.end()) {
if (*i2 == c) {
conv(res, simple_wml::string_span(i1, i2));
++i2;
i1 = i2;
} else {
++i2;
}
}
conv(res, simple_wml::string_span(i1, i2));
return res;
}
}
namespace wesnothd {
int game::id_num = 1;
void game::missing_user(network::connection socket, const std::string& func) const
{
WRN_GAME << func << "(): Could not find user (socket:\t" << socket
<< ") in player_info_ in game:\t\"" << name_ << "\" (" << id_ << ")\n";
}
game::game(player_map& players, const network::connection host,
const std::string& name, bool save_replays,
const std::string& replay_save_path) :
player_info_(&players),
id_(id_num++),
name_(name),
password_(),
owner_(host),
players_(),
observers_(),
muted_observers_(),
sides_(),
side_controllers_(),
nsides_(0),
started_(false),
level_(),
history_(),
description_(NULL),
end_turn_(0),
num_turns_(0),
all_observers_muted_(false),
bans_(),
termination_(),
save_replays_(save_replays),
replay_save_path_(replay_save_path),
rng_(),
last_choice_request_id_(-1) /* or maybe 0 ? it shouldn't matter*/
{
assert(owner_);
players_.push_back(owner_);
const player_map::iterator pl = player_info_->find(owner_);
if (pl == player_info_->end()) {
missing_user(owner_, __func__);
return;
}
// Mark the host as unavailable in the lobby.
pl->second.mark_available(id_, name_);
pl->second.set_status(player::PLAYING);
}
game::~game()
{
try {
save_replay();
user_vector users = all_game_users();
for (user_vector::const_iterator u = users.begin(); u != users.end(); ++u) {
remove_player(*u, false, true);
}
clear_history();
} catch (...) {}
}
/// returns const so that operator [] won't create empty keys if not existent
static const simple_wml::node& get_multiplayer(const simple_wml::node& root)
{
if(const simple_wml::node* multiplayer = root.child("multiplayer"))
return *multiplayer;
else
{
ERR_GAME << "no [multiplayer] found. Returning root\n";
return root;
}
}
bool game::allow_observers() const {
return get_multiplayer(level_.root())["observer"].to_bool(true);
}
bool game::is_observer(const network::connection player) const {
return std::find(observers_.begin(),observers_.end(),player) != observers_.end();
}
bool game::is_muted_observer(const network::connection player) const {
if (!is_observer(player)) {
return false;
}
if (all_observers_muted_) {
return true;
}
return std::find(muted_observers_.begin(), muted_observers_.end(), player)
!= muted_observers_.end();
}
bool game::is_player(const network::connection player) const {
return std::find(players_.begin(),players_.end(),player) != players_.end();
}
namespace {
std::string describe_turns(int turn, int num_turns)
{
char buf[100];
if(num_turns == -1) {
snprintf(buf, sizeof(buf), "%d/-", turn);
} else {
snprintf(buf, sizeof(buf), "%d/%d", turn, num_turns);
}
return buf;
}
}//anon namespace
std::string game::username(const player_map::const_iterator pl) const
{
if (pl != player_info_->end()) {
return pl->second.name();
}
return "(unknown)";
}
std::string game::list_users(user_vector users, const std::string& func) const
{
std::string list;
for (user_vector::const_iterator user = users.begin(); user != users.end(); ++user) {
const player_map::const_iterator pl = player_info_->find(*user);
if (pl != player_info_->end()) {
if (!list.empty()) list += ", ";
list += pl->second.name();
} else missing_user(*user, func);
}
return list;
}
void game::perform_controller_tweaks() {
const simple_wml::node::child_list & sides = get_sides_list();
DBG_GAME << "****\n Performing controller tweaks. sides = " << std::endl;
DBG_GAME << debug_sides_info() << std::endl;
DBG_GAME << "****" << std::endl;
update_side_data(); // Necessary to read the level_ and get sides_, etc. updated to match
for(simple_wml::node::child_list::const_iterator s = sides.begin(); s != sides.end(); ++s) {
if ((**s)["controller"] != "null") {
const size_t side_index = (**s)["side"].to_int() - 1;
if(side_index >= sides_.size()) {
continue;
}
if (sides_[side_index] == 0) {
sides_[side_index] = owner_;
std::stringstream msg;
msg << "Side " << side_index + 1 << " had no controller during controller tweaks! The host was assigned control.";
LOG_GAME << msg.str() << " (game id: " << id_ << ")\n";
send_and_record_server_message(msg.str());
}
const player_map::const_iterator user = player_info_->find(sides_[side_index]);
std::string user_name = "null (server missing user)";
if (user == player_info_->end()) {
missing_user(user->first, __func__);
} else {
user_name = username(user);
}
// Issue change_controller command, transfering this side to its owner with proper name and controller.
// Ensures that what the server now thinks is true is effected on all of the clients.
//
// We use the "player_left" field as follows. Normally change_controller sends one message to the owner,
// and one message to everyone else. In case that a player drops, the owner is gone and should not get
// a message, instead the host gets a [side_drop] message.
//
// In the server controller tweaks, we want to avoid sending controller change messages to the host.
// Doing this has the negative consequence that all of the AI side names are given the owners name.
// Therefore, if the side belongs to the host, we pass player_left = true, otherwise player_left = false.
change_controller(side_index, sides_[side_index], user_name , sides_[side_index] == owner_, (**s)["controller"].to_string());
//next lines change controller types found in level_ to be what is appropriate for an observer at game start.
if ((**s)["controller"] == "ai") {
(*s)->set_attr("controller", "network_ai");
} else { //this catches "reserved" also
(*s)->set_attr("controller", "network");
}
if (sides_[side_index] == 0) {
std::stringstream msg;
msg << "Side " << side_index + 1 << " had no controller AFTER controller tweaks! Ruh Roh!";
LOG_GAME << msg.str() << " (game id: " << id_ << ")\n";
}
}
}
update_side_data(); // this is the last time that update_side_data will actually run, as now the game will start and started_ will be true.
//TODO: Does it matter that the server is telling the host to change a bunch of sides?
//According to playturn.cpp, the host should ignore all such messages. Still might be better
//not to send them at all, although not if it complicates the server code.
}
void game::start_game(const player_map::const_iterator starter) {
const simple_wml::node::child_list & sides = get_sides_list();
DBG_GAME << "****\n Starting game. sides = " << std::endl;
DBG_GAME << debug_sides_info() << std::endl;
DBG_GAME << "****" << std::endl;
started_ = true;
// Prevent inserting empty keys when reading.
const simple_wml::node& multiplayer = get_multiplayer(level_.root());
const bool save = multiplayer["savegame"].to_bool();
LOG_GAME << network::ip_address(starter->first) << "\t"
<< starter->second.name() << "\t" << "started"
<< (save ? " reloaded" : "") << " game:\t\"" << name_ << "\" (" << id_
// << ") with: " << list_users(players_, __func__) << ". Settings: map: " << s["id"]
<< ") with: " << list_users(players_, __func__) << ". Settings: map: " << multiplayer["mp_scenario"]
// << "\tera: " << (s.child("era") ? (*s.child("era"))["id"] : "")
<< "\tera: " << multiplayer["mp_era"]
<< "\tXP: " << multiplayer["experience_modifier"]
<< "\tGPV: " << multiplayer["mp_village_gold"]
<< "\tfog: " << multiplayer["mp_fog"]
<< "\tshroud: " << multiplayer["mp_shroud"]
<< "\tobservers: " << multiplayer["observer"]
<< "\tshuffle: " << multiplayer["shuffle_sides"]
<< "\ttimer: " << multiplayer["mp_countdown"]
<< (multiplayer["mp_countdown"].to_bool() ?
"\treservoir time: " + multiplayer["mp_countdown_reservoir_time"].to_string() +
"\tinit time: " + multiplayer["mp_countdown_init_time"].to_string() +
"\taction bonus: " + multiplayer["mp_countdown_action_bonus"].to_string() +
"\tturn bonus: " + multiplayer["mp_countdown_turn_bonus"].to_string() : "")
<< "\n";
for(simple_wml::node::child_list::const_iterator s = sides.begin(); s != sides.end(); ++s) {
if ((**s)["controller"] != "null") {
const size_t side_index = (**s)["side"].to_int() - 1;
if(side_index >= sides_.size()) {
continue;
}
if (sides_[side_index] == 0) {
std::stringstream msg;
msg << "Side " << side_index + 1 << " has no controller but should! The host needs to assign control for the game to proceed past that side's turn.";
LOG_GAME << msg.str() << " (game id: " << id_ << ")\n";
send_and_record_server_message(msg.str());
}
}
}
DBG_GAME << "Number of sides: " << nsides_ << "\n";
int turn = 1;
int side = 0;
// Savegames have a snapshot that tells us which side starts.
if (const simple_wml::node* snapshot = level_.root().child("snapshot")) {
turn = lexical_cast_default<int>((*snapshot)["turn_at"], 1);
side = lexical_cast_default<int>((*snapshot)["playing_team"], 0);
LOG_GAME << "Reload from turn: " << turn
<< ". Current side is: " << side + 1 << ".\n";
}
end_turn_ = (turn - 1) * nsides_ + side - 1;
num_turns_ = lexical_cast_default<int>((*starting_pos( level_.root()))["turns"], -1);
end_turn();
clear_history();
// Send [observer] tags for all observers that are already in the game.
send_observerjoins();
}
void game::update_game()
{
started_ = false;
description_->set_attr("turn", "");
update_side_data();
describe_slots();
}
bool game::send_taken_side(simple_wml::document& cfg, const simple_wml::node::child_list::const_iterator side) const
{
const size_t side_index = (**side)["side"].to_int() - 1;
//negative values are casted (int -> size_t) to very high values to this check will fail for them too.
if (side_index >= sides_.size()) return false;
if (sides_[side_index] != 0) return false;
// We expect that the host will really use our proposed side number. (He could do different...)
cfg.root().set_attr_dup("side", (**side)["side"]);
// Tell the host which side the new player should take.
return wesnothd::send_to_one(cfg, owner_);
}
bool game::take_side(const player_map::const_iterator user)
{
DBG_GAME << "take_side...\n";
if (started_) return false;
simple_wml::document cfg;
cfg.root().set_attr_dup("name", user->second.name().c_str());
// Check if we can figure out a fitting side.
const simple_wml::node::child_list& sides = get_sides_list();
for(simple_wml::node::child_list::const_iterator side = sides.begin(); side != sides.end(); ++side) {
if(((**side)["controller"] == "network" || (**side)["controller"] == "reserved")
&& (**side)["current_player"] == user->second.name().c_str())
{
if (send_taken_side(cfg, side)) return true;
}
}
// If there was no fitting side just take the first available.
for(simple_wml::node::child_list::const_iterator side = sides.begin(); side != sides.end(); ++side) {
if((**side)["controller"] == "network") {
if (send_taken_side(cfg, side)) return true;
}
}
DBG_GAME << "take_side: there are no more sides available\n";
//if we get here we couldn't find a side to take
return false;
}
void game::reset_sides()
{
side_controllers_.clear();
sides_.clear();
nsides_ = get_sides_list().size();
side_controllers_.resize(nsides_);
sides_.resize(nsides_);
}
void game::update_side_data()
{
//added by iceiceice: since level_ will now reflect how an observer
if (started_) return; //views the replay start position and not the current position, the sides_, side_controllers_,
//players_ info should not be updated from the level_ after the game has started.
//controller changes are now stored in the history, so an observer that joins will get up to
//date that way.
DBG_GAME << "update_side_data...\n";
DBG_GAME << debug_player_info();
// Remember everyone that is in the game.
const user_vector users = all_game_users();
players_.clear();
observers_.clear();
reset_sides();
const simple_wml::node::child_list& level_sides = get_sides_list();
/* This causes data corruption for some reason
if (!lg::debug.dont_log(log_server)) {
for (simple_wml::node::child_list::const_iterator side = level_sides.begin();
side != level_sides.end(); ++side)
DBG_GAME << "[side]\n" << simple_wml::node_to_string(**side) << "[/side]\n";
}*/
// For each user:
// * Find the username.
// * Find the side this username corresponds to.
for (user_vector::const_iterator user = users.begin(); user != users.end(); ++user) {
player_map::iterator info = player_info_->find(*user);
if (info == player_info_->end()) {
missing_user(*user, __func__);
continue;
}
bool side_found = false;
for (simple_wml::node::child_list::const_iterator side = level_sides.begin();
side != level_sides.end(); ++side)
{
const size_t side_index = (**side)["side"].to_int() - 1;
if (side_index >= sides_.size()
|| sides_[side_index] != 0) continue;
const simple_wml::string_span& player_id = (**side)["player_id"];
const simple_wml::string_span& controller = (**side)["controller"];
if ( player_id == info->second.name().c_str()) {
//if this is called before perform_controller_tweaks() we have "ai" and "human" controllers
//if its called after that we have "network" and "network_ai" controllers.
if(controller != "network" && controller != "human" && controller != "ai" && controller != "network_ai") {
//we found invalid [side] data. Some message would be cool.
continue;
}
//convert "network_ai" -> "ai", "network" -> "human"
side_controllers_[side_index] = controller == "network" ? "human" : controller == "network_ai" ? "ai" : controller.to_string();
sides_[side_index] = *user;
side_found = true;
}
else if (*user == owner_ && (controller == "null")) {
//the *user == owner_ check has no effect,
//it's just an optimisation so that we only do this once.
side_controllers_[side_index] = controller.to_string();
}
}
if (side_found) {
players_.push_back(*user);
info->second.set_status(player::PLAYING);
} else {
observers_.push_back(*user);
info->second.set_status(player::OBSERVING);
}
}
DBG_GAME << debug_player_info();
}
void game::transfer_side_control(const network::connection sock, const simple_wml::node& cfg) {
DBG_GAME << "transfer_side_control...\n";
if (!is_player(sock) && sock != owner_) {
send_server_message("You cannot change controllers: not a player.", sock);
return;
}
// Check the side number.
const unsigned int side_num = cfg["side"].to_int();
if(side_num < 1 || side_num > sides_.size()) {
std::ostringstream msg;
msg << "The side number has to be between 1 and "
<< sides_.size() << ".";
send_server_message(msg.str(), sock);
return;
}
if (side_num > get_sides_list().size()) {
send_server_message("Invalid side number.", sock);
return;
}
const simple_wml::string_span& newplayer_name = cfg["player"];
const network::connection old_player = sides_[side_num - 1];
const player_map::iterator oldplayer = player_info_->find(old_player);
if (oldplayer == player_info_->end()) missing_user(old_player, __func__);
const std::string old_player_name = username(oldplayer);
// A player (un)droids his side.
if (newplayer_name.empty()) {
if (sock != old_player) {
if (cfg["controller"].empty()) {
send_server_message("No player name or controller type given.", sock);
} else {
send_server_message("You can only (un)droid your own sides!", sock);
}
return;
} else if (cfg["controller"] != "ai" && cfg["controller"] != "human") {
std::stringstream msg;
msg << "Wrong controller type received: '" << cfg["controller"] << "'";
DBG_GAME << msg.str() << "\n";
send_server_message(msg.str(), sock);
return;
}
change_controller(side_num - 1, old_player, old_player_name, false, cfg["controller"].to_string());
return;
}
// Check if the sender actually owns the side he gives away or is the host.
if (!(sock == old_player || sock == owner_)) {
std::stringstream msg;
msg << "You can't give away side " << side_num << ". It's controlled by '"
<< old_player_name << "' not you.";
DBG_GAME << msg.str() << "\n";
send_server_message(msg.str(), sock);
return;
}
//find the player that is passed control
player_map::iterator newplayer = find_user(newplayer_name);
// Is he in this game?
if (newplayer == player_info_->end() || !is_member(newplayer->first)) {
send_server_message(newplayer_name.to_string() + " is not in this game", sock);
return;
}
if (newplayer->first == old_player) {
std::stringstream msg;
msg << "That's already " << newplayer_name << "'s side, silly.";
send_server_message(msg.str(), sock);
return;
}
sides_[side_num - 1] = 0;
// If the old player lost his last side, make him an observer.
if (std::find(sides_.begin(), sides_.end(), old_player) == sides_.end()
&& is_player(old_player)) {
observers_.push_back(old_player);
oldplayer->second.set_status(player::OBSERVING);
players_.erase(std::remove(players_.begin(), players_.end(), old_player), players_.end());
// Tell others that the player becomes an observer.
send_and_record_server_message(old_player_name + " becomes an observer.");
// Update the client side observer list for everyone except old player.
simple_wml::document observer_join;
observer_join.root().add_child("observer").set_attr_dup("name", old_player_name.c_str());
send_data(observer_join, old_player);
}
change_controller(side_num - 1, newplayer->first, newplayer->second.name(), false);
// If we gave the new side to an observer add him to players_.
if (is_observer(newplayer->first)) {
players_.push_back(newplayer->first);
newplayer->second.set_status(player::PLAYING);
observers_.erase(std::remove(observers_.begin(), observers_.end(), newplayer->first), observers_.end());
// Send everyone but the new player the observer_quit message.
send_observerquit(newplayer);
}
}
void game::change_controller(const size_t side_index,
const network::connection sock,
const std::string& player_name,
const bool player_left,
const std::string& controller)
{
DBG_GAME << __func__ << "...\n";
const std::string& side = lexical_cast_default<std::string, size_t>(side_index + 1);
sides_[side_index] = sock;
if (player_left && side_controllers_[side_index] == "ai") {
// Automatic AI side transfer.
} else if (controller.empty()) {
if (started_) {
send_and_record_server_message(player_name + " takes control of side " + side + ".");
}
side_controllers_[side_index] = "human";
} else {
if (started_) {
send_and_record_server_message(player_name + (controller == "ai" ? " " : " un")
+ "droids side " + side + ".");
}
side_controllers_[side_index] = (controller == "ai" ? "ai" : "human");
}
simple_wml::document response;
simple_wml::node& change = response.root().add_child("change_controller");
change.set_attr("side", side.c_str());
change.set_attr("player", player_name.c_str());
// Tell everyone but the new player that this side's controller changed.
change.set_attr("controller", (side_controllers_[side_index] == "ai" ? "network_ai" : "network"));
send_data(response, sock);
if (started_) { //this is added instead of the if (started_) {...} below
//the purpose of these records is so that observers, replay viewers, get controller updates correctly
record_data(response.clone());
}
// Tell the new player that he controls this side now.
// Just don't send it when the player left the game. (The host gets the
// side_drop already.)
if (!player_left) {
change.set_attr("controller", (side_controllers_[side_index] == "ai" ? "ai" : "human"));
wesnothd::send_to_one(response, sock);
}
}
void game::notify_new_host(){
const std::string owner_name = username(player_info_->find(owner_));
simple_wml::document cfg;
simple_wml::node& cfg_host_transfer = cfg.root().add_child("host_transfer");
// Why do we send the new host his own name?
cfg_host_transfer.set_attr("name", owner_name.c_str());
cfg_host_transfer.set_attr("value", "1");
std::string message = owner_name + " has been chosen as the new host.";
if (!wesnothd::send_to_one(cfg, owner_)) {
message += " But an internal error occurred. You probably have to abandon this game.";
}
send_and_record_server_message(message);
}
bool game::describe_slots() {
if(started_ || description_ == NULL)
return false;
int available_slots = 0;
int num_sides = get_sides_list().size();
int i = 0;
const simple_wml::node::child_list& side_list = get_sides_list();
for(simple_wml::node::child_list::const_iterator it = side_list.begin(); it != side_list.end(); ++it, ++i) {
if (((**it)["allow_player"].to_bool(true) == false) || (**it)["controller"] == "null") {
num_sides--;
} else if (sides_[i] == 0) {
++available_slots;
}
}
char buf[50];
snprintf(buf,sizeof(buf), "%d/%d", available_slots, num_sides);
if ((*description_)["slots"] != buf) {
description_->set_attr_dup("slots", buf);
return true;
} else {
return false;
}
}
bool game::player_is_banned(const network::connection sock) const {
std::vector<std::string>::const_iterator ban =
std::find(bans_.begin(), bans_.end(), network::ip_address(sock));
return ban != bans_.end();
}
void game::mute_all_observers() {
all_observers_muted_ = !all_observers_muted_;
if (all_observers_muted_) {
send_and_record_server_message("All observers have been muted.");
} else {
send_and_record_server_message("Muting of all observers has been removed.");
}
}
void game::send_muted_observers(const player_map::const_iterator user) const
{
if (all_observers_muted_) {
send_server_message("All observers are muted.", user->first);
return;
}
std::string muted_nicks = list_users(muted_observers_, __func__);
send_server_message("Muted observers: " + muted_nicks, user->first);
}
void game::mute_observer(const simple_wml::node& mute,
const player_map::const_iterator muter)
{
if (muter->first != owner_) {
send_server_message("You cannot mute: not the game host.", muter->first);
return;
}
const simple_wml::string_span& username = mute["username"];
if (username.empty()) {
send_muted_observers(muter);
return;
}
const player_map::const_iterator user = find_user(username);
/**
* @todo FIXME: Maybe rather save muted nicks as a set of strings and
* also allow muting of usernames not in the game.
*/
if (user == player_info_->end() || !is_observer(user->first)) {
send_server_message("Observer '" + username.to_string() + "' not found.", muter->first);
return;
}
// Prevent muting ourselves.
if (user->first == muter->first) {
send_server_message("Don't mute yourself, silly.", muter->first);
return;
}
if (is_muted_observer(user->first)) {
send_server_message(username.to_string() + " is already muted.", muter->first);
return;
}
LOG_GAME << network::ip_address(muter->first) << "\t"
<< muter->second.name() << " muted: " << username << " ("
<< network::ip_address(user->first) << ")\tin game:\t\""
<< name_ << "\" (" << id_ << ")\n";
muted_observers_.push_back(user->first);
send_and_record_server_message(username.to_string() + " has been muted.");
}
void game::unmute_observer(const simple_wml::node& unmute,
const player_map::const_iterator unmuter)
{
if (unmuter->first != owner_) {
send_server_message("You cannot unmute: not the game host.", unmuter->first);
return;
}
const simple_wml::string_span& username = unmute["username"];
if (username.empty()) {
muted_observers_.clear();
send_and_record_server_message("Everyone has been unmuted.");
return;
}
const player_map::const_iterator user = find_user(username);
if (user == player_info_->end() || !is_observer(user->first)) {
send_server_message("Observer '" + username.to_string() + "' not found.", unmuter->first);
return;
}
if (!is_muted_observer(user->first)) {
send_server_message(username.to_string() + " is not muted.", unmuter->first);
return;
}
LOG_GAME << network::ip_address(unmuter->first) << "\t"
<< unmuter->second.name() << " unmuted: " << username << " ("
<< network::ip_address(user->first) << ")\tin game:\t\""
<< name_ << "\" (" << id_ << ")\n";
muted_observers_.erase(std::remove(muted_observers_.begin(),
muted_observers_.end(), user->first), muted_observers_.end());
send_and_record_server_message(username.to_string() + " has been unmuted.");
}
void game::send_leave_game(network::connection user) const
{
static simple_wml::document leave_game("[leave_game]\n[/leave_game]\n", simple_wml::INIT_COMPRESSED);
wesnothd::send_to_one(leave_game, user);
}
network::connection game::kick_member(const simple_wml::node& kick,
const player_map::const_iterator kicker)
{
if (kicker->first != owner_) {
send_server_message("You cannot kick: not the game host", kicker->first);
return 0;
}
const simple_wml::string_span& username = kick["username"];
const player_map::const_iterator user = find_user(username);
if (user == player_info_->end() || !is_member(user->first)) {
send_server_message("'" + username.to_string() + "' is not a member of this game.", kicker->first);
return 0;
} else if (user->first == kicker->first) {
send_server_message("Don't kick yourself, silly.", kicker->first);
return 0;
} else if (user->second.is_moderator()) {
send_server_message("You're not allowed to kick a moderator.", kicker->first);
return 0;
}
LOG_GAME << network::ip_address(kicker->first) << "\t"
<< kicker->second.name() << "\tkicked: " << username << " ("
<< network::ip_address(user->first) << ")\tfrom game:\t\""
<< name_ << "\" (" << id_ << ")\n";
send_and_record_server_message(username.to_string() + " has been kicked.");
// Tell the user to leave the game.
send_leave_game(user->first);
remove_player(user->first);
return user->first;
}
network::connection game::ban_user(const simple_wml::node& ban,
const player_map::const_iterator banner)
{
if (banner->first != owner_) {
send_server_message("You cannot ban: not the game host", banner->first);
return 0;
}
const simple_wml::string_span& username = ban["username"];
const player_map::const_iterator user = find_user(username);
if (user == player_info_->end()) {
send_server_message("User '" + username.to_string() + "' not found.", banner->first);
return 0;
} else if (user->first == banner->first) {
send_server_message("Don't ban yourself, silly.", banner->first);
return 0;
} else if (player_is_banned(user->first)) {
send_server_message("'" + username.to_string() + "' is already banned.", banner->first);
return 0;
} else if (user->second.is_moderator()) {
send_server_message("You're not allowed to ban a moderator.", banner->first);
return 0;
}
LOG_GAME << network::ip_address(banner->first) << "\t"
<< banner->second.name() << "\tbanned: " << username << " ("
<< network::ip_address(user->first) << ")\tfrom game:\t\""
<< name_ << "\" (" << id_ << ")\n";
bans_.push_back(network::ip_address(user->first));
send_and_record_server_message(username.to_string() + " has been banned.");
if (is_member(user->first)) {
//tell the user to leave the game.
send_leave_game(user->first);
remove_player(user->first);
return user->first;
}
// Don't return the user if he wasn't in this game.
return 0;
}
void game::unban_user(const simple_wml::node& unban,
const player_map::const_iterator unbanner)
{
if (unbanner->first != owner_) {
send_server_message("You cannot unban: not the game host.", unbanner->first);
return;
}
const simple_wml::string_span& username = unban["username"];
const player_map::const_iterator user = find_user(username);
if (user == player_info_->end()) {
send_server_message("User '" + username.to_string() + "' not found.", unbanner->first);
return;
}
if (!player_is_banned(user->first)) {
send_server_message("'" + username.to_string() + "' is not banned.", unbanner->first);
return;
}
LOG_GAME << network::ip_address(unbanner->first) << "\t"
<< unbanner->second.name() << "\tunbanned: " << username << " ("
<< network::ip_address(user->first) << ")\tfrom game:\t\""
<< name_ << "\" (" << id_ << ")\n";
bans_.erase(std::remove(bans_.begin(), bans_.end(), network::ip_address(user->first)), bans_.end());
send_and_record_server_message(username.to_string() + " has been unbanned.");
}
void game::process_message(simple_wml::document& data, const player_map::iterator user) {
if (owner_ == 0) {
ERR_GAME << "No owner in game::process_message" << std::endl;
}
simple_wml::node* const message = data.root().child("message");
assert(message);
message->set_attr_dup("sender", user->second.name().c_str());
const simple_wml::string_span& msg = (*message)["message"];
chat_message::truncate_message(msg, *message);
send_data(data, user->first, "game message");
}
bool game::is_legal_command(const simple_wml::node& command, const player_map::const_iterator user)
{
const bool is_player = this->is_player(user->first);
const bool is_host = user->first == owner_;
const bool is_current = is_current_player(user->first);
if(command.has_attr("from_side")) {
const size_t from_side_index = command["from_side"].to_int() - 1;
if(command["from_side"] == "server") {
//Someone pretends to be the server...
return false;
}
if(from_side_index >= sides_.size() || sides_[from_side_index] != user->first) {
return false;
}
}
if(is_current) return true;
// Only single commands allowed.
// NOTE: some non-dependent commands like move,attack.. might contain a [checkup] tag after their first data.
// But those packages are only sended by the currently active player which we check above.
if (!command.one_child()) return false;
// Chatting is never an illegal command.
if (command.child("speak")) return true;
if (is_player && command.has_attr("dependent") && command.has_attr("from_side"))
//AKA it's generated by get_user_input for example [global_variable]
{
return true;
}
if ((is_player || is_host)
&& (command.child("label")
|| command.child("clear_labels")
|| command.child("rename")
|| command.child("countdown_update")
))
{
return true;
}
return false;
}
bool game::process_turn(simple_wml::document& data, const player_map::const_iterator user) {
//DBG_GAME << "processing commands: '" << cfg << "'\n";
if (!started_) return false;
simple_wml::node* const turn = data.root().child("turn");
bool turn_ended = false;
// Any private 'speak' commands must be repackaged separate
// to other commands, and re-sent, since they should only go
// to some clients.
bool repackage = false;
int index = 0;
std::vector<int> marked;
const simple_wml::node::child_list& commands = turn->children("command");
simple_wml::node::child_list::const_iterator command;
for (command = commands.begin(); command != commands.end(); ++command) {
if (!is_legal_command(**command, user)) {
LOG_GAME << "ILLEGAL COMMAND in game: " << id_ << " ((("
<< simple_wml::node_to_string(**command) << ")))\n";
std::stringstream msg;
msg << "Removing illegal command '" << (**command).first_child().to_string()
<< "' from: " << user->second.name()
<< ". Current player is: "
<< username(player_info_->find(current_player()))
<< " (" << end_turn_ + 1 << "/" << nsides_ << ").";
LOG_GAME << msg.str() << " (socket: " << current_player()
<< ") (game id: " << id_ << ")\n";
send_and_record_server_message(msg.str());
marked.push_back(index - marked.size());
} else if ((**command).child("speak")) {
simple_wml::node& speak = *(**command).child("speak");
if (speak["to_sides"] != "" || is_muted_observer(user->first)) {
DBG_GAME << "repackaging..." << std::endl;
repackage = true;
}
const simple_wml::string_span& msg = speak["message"];
chat_message::truncate_message(msg, speak);
// Force the description to be correct,
// to prevent spoofing of messages.
speak.set_attr_dup("id", user->second.name().c_str());
// Also check the side for players.
if (is_player(user->first)) {
const size_t side_index = speak["side"].to_int() - 1;
if (side_index >= sides_.size()
|| sides_[side_index] != user->first) {
if (user->first == current_player()) {
speak.set_attr_dup("side", lexical_cast_default<std::string>(current_side() + 1).c_str());
} else {
const side_vector::const_iterator s =
std::find(sides_.begin(), sides_.end(), user->first);
speak.set_attr_dup("side", lexical_cast_default<std::string>(s - sides_.begin() + 1).c_str());
}
}
}
}
else if (is_current_player(user->first) && (**command).child("end_turn")) {
turn_ended = end_turn();
}
++index;
}
for(std::vector<int>::const_iterator j = marked.begin(); j != marked.end(); ++j) {
turn->remove_child("command",*j);
}
if (turn->no_children()) {
return false;
}
if (!repackage) {
record_data(data.clone());
send_data(data, user->first, "game replay");
return turn_ended;
}
for (command = commands.begin(); command != commands.end(); ++command) {
simple_wml::node* const speak = (**command).child("speak");
if (speak == NULL) {
simple_wml::document* mdata = new simple_wml::document;
simple_wml::node& turn = mdata->root().add_child("turn");
(**command).copy_into(turn.add_child("command"));
send_data(*mdata, user->first, "game replay");
record_data(mdata);
continue;
}
const simple_wml::string_span& to_sides = (*speak)["to_sides"];
// Anyone can send to the observer team.
if (is_muted_observer(user->first) && to_sides != game_config::observer_team_name.c_str()) {