/
ban.cpp
733 lines (658 loc) · 18.4 KB
/
ban.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
/*
Copyright (C) 2008 - 2016 by Pauli Nieminen <paniemin@cc.hut.fi>
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 "config.hpp"
#include "log.hpp"
#include "filesystem.hpp"
#include "serialization/parser.hpp"
#include "serialization/binary_or_text.hpp"
#include "serialization/string_utils.hpp"
#include "serialization/unicode.hpp"
#include "util.hpp"
#include "ban.hpp"
#include "utils/functional.hpp"
namespace wesnothd {
static lg::log_domain log_server("server");
#define ERR_SERVER LOG_STREAM(err, log_server)
#define LOG_SERVER LOG_STREAM(info, log_server)
#define DBG_SERVER LOG_STREAM(debug, log_server)
std::ostream& operator<<(std::ostream& o, const banned& n)
{
return o << "IP: " << n.get_ip() <<
(n.get_nick().empty() ? "" : " nick: " + n.get_nick()) <<
" reason: '" << n.get_reason() << "'"
" start_time: " << n.get_human_start_time() <<
" end_time: " << n.get_human_end_time() <<
" issuer: " << n.get_who_banned();
}
bool banned_compare::operator()(const banned_ptr& a, const banned_ptr& b) const
{
return (*a) > (*b);
}
banned_compare_subnet::compare_fn banned_compare_subnet::active_ = &banned_compare_subnet::less;
bool banned_compare_subnet::operator()(const banned_ptr& a, const banned_ptr& b) const
{
return (this->*(active_))(a,b);
}
bool banned_compare_subnet::less(const banned_ptr& a, const banned_ptr& b) const
{
return a->get_int_ip() < b->get_int_ip();
}
const std::string banned::who_banned_default_ = "system";
banned_ptr banned::create_dummy(const std::string& ip)
{
banned_ptr dummy(new banned(ip));
return dummy;
}
banned::banned(const std::string& ip) :
ip_(0),
mask_(0),
ip_text_(),
end_time_(0),
start_time_(0),
reason_(),
who_banned_(who_banned_default_),
group_(),
nick_()
{
ip_mask pair = parse_ip(ip);
ip_ = pair.first;
mask_ = 0xFFFFFFFF;
}
banned::banned(const std::string& ip,
const time_t end_time,
const std::string& reason,
const std::string& who_banned,
const std::string& group,
const std::string& nick) :
ip_(0),
mask_(0),
ip_text_(ip),
end_time_(end_time),
start_time_(time(0)),
reason_(reason),
who_banned_(who_banned),
group_(group),
nick_(nick)
{
ip_mask pair = parse_ip(ip_text_);
ip_ = pair.first;
mask_ = pair.second;
}
banned::banned(const config& cfg) :
ip_(0),
mask_(0),
ip_text_(),
end_time_(0),
start_time_(0),
reason_(),
who_banned_(who_banned_default_),
group_(),
nick_()
{
read(cfg);
}
ip_mask parse_ip(const std::string& ip)
{
// We use bit operations to construct the integer
// ip_mask is a pair: first is ip and second is mask
ip_mask ret;
ret.first = 0;
ret.second = 0;
std::vector<std::string> split_ip = utils::split(ip, '.');
if (split_ip.size() > 4) throw banned::error("Malformed ip address: " + ip);
unsigned int shift = 4*8; // start shifting from the highest byte
unsigned int mask = 0xFF000000;
const unsigned int complete_part_mask = 0xFF;
std::vector<std::string>::const_iterator part = split_ip.begin();
bool wildcard = false;
do {
shift -= 8;
mask >>= 8;
if (part == split_ip.end())
{
if (!wildcard)
throw banned::error("Malformed ip address: '" + ip + "'");
// Adding 0 to ip and mask is nop
// we can then break out of loop
break;
} else {
if (*part == "*")
{
wildcard = true;
// Adding 0 to ip and mask is nop
} else {
//wildcard = false;
unsigned int part_ip = lexical_cast_default<unsigned int>(*part, complete_part_mask + 1);
if (part_ip > complete_part_mask)
throw banned::error("Malformed ip address: '" + ip + "'");
ret.first |= (part_ip << shift);
ret.second |= (complete_part_mask << shift);
}
}
++part;
} while (shift);
return ret;
}
void banned::read(const config& cfg)
{
{
// parse ip and mask
ip_text_ = cfg["ip"].str();
ip_mask pair = parse_ip(ip_text_);
ip_ = pair.first;
mask_ = pair.second;
}
nick_ = cfg["nick"].str();
if (cfg.has_attribute("end_time"))
end_time_ = lexical_cast_default<time_t>(cfg["end_time"], 0);
if (cfg.has_attribute("start_time"))
start_time_ = lexical_cast_default<time_t>(cfg["start_time"], 0);
reason_ = cfg["reason"].str();
// only overwrite defaults if exists
if (cfg.has_attribute("who_banned"))
who_banned_ = cfg["who_banned"].str();
if (cfg.has_attribute("group"))
group_ = cfg["group"].str();
}
void banned::write(config& cfg) const
{
cfg["ip"] = get_ip();
cfg["nick"] = get_nick();
if (end_time_ > 0)
{
std::stringstream ss;
ss << end_time_;
cfg["end_time"] = ss.str();
}
if (start_time_ > 0)
{
std::stringstream ss;
ss << start_time_;
cfg["start_time"] = ss.str();
}
cfg["reason"] = reason_;
if (who_banned_ != who_banned_default_)
{
cfg["who_banned"] = who_banned_;
}
if (!group_.empty())
{
cfg["group"] = group_;
}
}
std::string banned::get_human_start_time() const
{
if (start_time_ == 0)
return "unknown";
return lg::get_timestamp(start_time_);
}
std::string banned::get_human_end_time() const
{
if (end_time_ == 0)
{
return "permanent";
}
return lg::get_timestamp(end_time_);
}
std::string banned::get_human_time_span() const
{
if (end_time_ == 0)
{
return "permanent";
}
return lg::get_timespan(end_time_ - time(nullptr));
}
bool banned::operator>(const banned& b) const
{
return end_time_ > b.get_end_time();
}
unsigned int banned::get_mask_ip(unsigned int mask) const
{
return ip_ & mask & mask_;
}
bool banned::match_ip(const ip_mask& pair) const {
return (ip_ & mask_) == (pair.first & mask_);
}
// Unlike match_ip this function takes both masks into account.
bool banned::match_ipmask(const ip_mask& pair) const {
return (ip_ & mask_ & pair.second) == (pair.first & pair.second & mask_);
}
void ban_manager::read()
{
if (filename_.empty() || !filesystem::file_exists(filename_))
return;
LOG_SERVER << "Reading bans from " << filename_ << "\n";
config cfg;
filesystem::scoped_istream ban_file = filesystem::istream_file(filename_);
read_gz(cfg, *ban_file);
for (const config &b : cfg.child_range("ban"))
{
try {
banned_ptr new_ban(new banned(b));
assert(bans_.insert(new_ban).second);
if (new_ban->get_end_time() != 0)
time_queue_.push(new_ban);
} catch (banned::error& e) {
ERR_SERVER << e.message << " while reading bans" << std::endl;
}
}
// load deleted too
if (const config &cfg_del = cfg.child("deleted"))
{
for (const config &b : cfg_del.child_range("ban"))
{
try {
banned_ptr new_ban(new banned(b));
deleted_bans_.push_back(new_ban);
} catch (banned::error& e) {
ERR_SERVER << e.message << " while reading deleted bans" << std::endl;
}
}
}
}
void ban_manager::write()
{
if (filename_.empty() || !dirty_)
return;
LOG_SERVER << "Writing bans to " << filename_ << "\n";
dirty_ = false;
config cfg;
for (ban_set::const_iterator itor = bans_.begin();
itor != bans_.end(); ++itor)
{
config& child = cfg.add_child("ban");
(*itor)->write(child);
}
config& deleted = cfg.add_child("deleted");
for (deleted_ban_list::const_iterator itor = deleted_bans_.begin();
itor != deleted_bans_.end(); ++itor)
{
config& child = deleted.add_child("ban");
(*itor)->write(child);
}
filesystem::scoped_ostream ban_file = filesystem::ostream_file(filename_);
config_writer writer(*ban_file, true);
writer.write(cfg);
}
bool ban_manager::parse_time(const std::string& duration, time_t* time) const
{
if (!time) return false;
if (duration.substr(0,4) == "TIME") {
struct tm* loc;
loc = localtime(time);
size_t number = 0;
for (std::string::const_iterator i = duration.begin() + 4;
i != duration.end(); ++i) {
if (is_digit(*i))
{
number = number * 10 + to_digit(*i);
}
else
{
switch(*i)
{
case 'Y':
loc->tm_year = number;
break;
case 'M':
loc->tm_mon = number;
break;
case 'D':
loc->tm_mday = number;
break;
case 'h':
loc->tm_hour = number;
break;
case 'm':
loc->tm_min = number;
break;
case 's':
loc->tm_sec = number;
break;
default:
LOG_SERVER << "Invalid time modifier given: '" << *i << "'.\n";
break;
}
number = 0;
}
}
*time = mktime(loc);
return true;
}
default_ban_times::const_iterator time_itor = ban_times_.find(duration);
std::string dur_lower;
try {
dur_lower = utf8::lowercase(duration);
} catch ( utf8::invalid_utf8_exception & e ) {
ERR_SERVER << "While parsing ban command duration string, caught an invalid utf8 exception: " << e.what() << std::endl;
return false;
}
if (dur_lower == "permanent" || duration == "0") {
*time = 0;
} else if (ban_times_.find(duration) != ban_times_.end()) {
*time += time_itor->second;
} else {
std::string::const_iterator i = duration.begin();
int number = -1;
for (std::string::const_iterator d_end = duration.end(); i != d_end; ++i) {
if (is_digit(*i))
{
if (number == -1) number = 0;
number = number * 10 + to_digit(*i);
} else {
if (number == -1) number = 1;
switch(*i)
{
case 'Y':
case 'y':
if (++i != d_end && tolower(*i) == 'e'
&& ++i != d_end && tolower(*i) == 'a'
&& ++i != d_end && tolower(*i) == 'r'
&& ++i != d_end && tolower(*i) == 's') {
} else --i;
*time += number * 365*24*60*60; // a year;
break;
case 'M':
if (++i != d_end && tolower(*i) == 'i') {
if (++i != d_end && tolower(*i) == 'n'
&& ++i != d_end && tolower(*i) == 'u'
&& ++i != d_end && tolower(*i) == 't'
&& ++i != d_end && tolower(*i) == 'e'
&& ++i != d_end && tolower(*i) == 's') {
} else --i;
*time += number * 60;
break;
}
--i;
if (++i != d_end && tolower(*i) == 'o'
&& ++i != d_end && tolower(*i) == 'n'
&& ++i != d_end && tolower(*i) == 't'
&& ++i != d_end && tolower(*i) == 'h'
&& ++i != d_end && tolower(*i) == 's') {
} else --i;
*time += number * 30*24*60*60; // 30 days
break;
case 'D':
case 'd':
if (++i != d_end && tolower(*i) == 'a'
&& ++i != d_end && tolower(*i) == 'y'
&& ++i != d_end && tolower(*i) == 's') {
} else --i;
*time += number * 24*60*60;
break;
case 'H':
case 'h':
if (++i != d_end && tolower(*i) == 'o'
&& ++i != d_end && tolower(*i) == 'u'
&& ++i != d_end && tolower(*i) == 'r'
&& ++i != d_end && tolower(*i) == 's') {
} else --i;
*time += number * 60*60;
break;
case 'm':
if (++i != d_end && tolower(*i) == 'o') {
if (++i != d_end && tolower(*i) == 'n'
&& ++i != d_end && tolower(*i) == 't'
&& ++i != d_end && tolower(*i) == 'h'
&& ++i != d_end && tolower(*i) == 's') {
} else --i;
*time += number * 30*24*60*60; // 30 days
break;
}
--i;
if (++i != d_end && tolower(*i) == 'i'
&& ++i != d_end && tolower(*i) == 'n'
&& ++i != d_end && tolower(*i) == 'u'
&& ++i != d_end && tolower(*i) == 't'
&& ++i != d_end && tolower(*i) == 'e'
&& ++i != d_end && tolower(*i) == 's') {
} else --i;
*time += number * 60;
break;
case 'S':
case 's':
if (++i != d_end && tolower(*i) == 'e'
&& ++i != d_end && tolower(*i) == 'c'
&& ++i != d_end && tolower(*i) == 'o'
&& ++i != d_end && tolower(*i) == 'n'
&& ++i != d_end && tolower(*i) == 'd'
&& ++i != d_end && tolower(*i) == 's') {
} else --i;
*time += number;
break;
default:
return false;
break;
}
number = -1;
}
}
if (is_digit(*--i)) {
*time += number * 60; // default to minutes
}
}
return true;
}
std::string ban_manager::ban(const std::string& ip,
const time_t& end_time,
const std::string& reason,
const std::string& who_banned,
const std::string& group,
const std::string& nick)
{
std::ostringstream ret;
try {
ban_set::iterator ban;
if ((ban = bans_.find(banned::create_dummy(ip))) != bans_.end())
{
// Already exsiting ban for ip. We have to first remove it
ret << "Overwriting ban: " << (**ban) << "\n";
bans_.erase(ban);
}
} catch (banned::error& e) {
ERR_SERVER << e.message << " while creating dummy ban for finding existing ban" << std::endl;
return e.message;
}
try {
banned_ptr new_ban(new banned(ip, end_time, reason,who_banned, group, nick));
bans_.insert(new_ban);
if (end_time != 0)
time_queue_.push(new_ban);
ret << *new_ban;
} catch (banned::error& e) {
ERR_SERVER << e.message << " while banning" << std::endl;
return e.message;
}
dirty_ = true;
return ret.str();
}
void ban_manager::unban(std::ostringstream& os, const std::string& ip)
{
ban_set::iterator ban;
try {
ban = bans_.find(banned::create_dummy(ip));
} catch (banned::error& e) {
ERR_SERVER << e.message << std::endl;
os << e.message;
return;
}
if (ban == bans_.end())
{
os << "There is no ban on '" << ip << "'.";
return;
}
// keep ban entry still in memory
os << "Ban on '" << **ban << "' removed.";
// group bans don't get saved
if ((*ban)->get_group().empty()) deleted_bans_.push_back(*ban);
bans_.erase(ban);
dirty_ = true;
}
void ban_manager::unban_group(std::ostringstream& os, const std::string& group)
{
ban_set temp;
std::insert_iterator<ban_set> temp_inserter(temp, temp.begin());
std::remove_copy_if(bans_.begin(), bans_.end(), temp_inserter, std::bind(&banned::match_group,std::bind(&banned_ptr::get,_1),group));
os << "Removed " << (bans_.size() - temp.size()) << " bans";
bans_.swap(temp);
dirty_ = true;
}
void ban_manager::check_ban_times(time_t time_now)
{
while (!time_queue_.empty())
{
banned_ptr ban = time_queue_.top();
if (ban->get_end_time() > time_now)
{
// No bans going to expire
DBG_SERVER << "ban " << ban->get_ip() << " not removed. time: " << time_now << " end_time " << ban->get_end_time() << "\n";
break;
}
// This ban is going to expire so delete it.
LOG_SERVER << "Remove a ban " << ban->get_ip() << ". time: " << time_now << " end_time " << ban->get_end_time() << "\n";
std::ostringstream os;
unban(os, ban->get_ip());
time_queue_.pop();
}
// Save bans if there is any new ones
write();
}
void ban_manager::list_deleted_bans(std::ostringstream& out, const std::string& mask) const
{
if (deleted_bans_.empty())
{
out << "No removed bans found.";
return;
}
ip_mask pair;
try {
pair = parse_ip(mask);
} catch (banned::error& e) {
out << "parse error: " << e.message;
return;
}
out << "DELETED BANS LIST";
for (deleted_ban_list::const_iterator i = deleted_bans_.begin();
i != deleted_bans_.end();
++i)
{
if ((*i)->match_ipmask(pair)) out << "\n" << (**i);
}
}
void ban_manager::list_bans(std::ostringstream& out, const std::string& mask) const
{
if (bans_.empty())
{
out << "No bans set.";
return;
}
ip_mask pair;
try {
pair = parse_ip(mask);
} catch (banned::error& e) {
out << "parse error: " << e.message;
return;
}
out << "BAN LIST";
std::set<std::string> groups;
for (ban_set::const_iterator i = bans_.begin();
i != bans_.end(); ++i)
{
if ((*i)->get_group().empty())
{
if ((*i)->match_ipmask(pair)) out << "\n" << (**i);
} else {
groups.insert((*i)->get_group());
}
}
// Don't list ban groups when looking for specific bans.
if (!groups.empty() && mask == "*")
{
out << "\nban groups: ";
out << *groups.begin();
std::ostream& (*fn)(std::ostream&,const std::string&) = &std::operator<<;
std::for_each( ++groups.begin(), groups.end(), std::bind(fn,std::bind(fn,std::ref(out),std::string(", ")),_1));
}
}
std::string ban_manager::is_ip_banned(const std::string& ip) const
{
ip_mask pair;
try {
pair = parse_ip(ip);
} catch (banned::error&) {
return "";
}
ban_set::const_iterator ban = std::find_if(bans_.begin(), bans_.end(), std::bind(&banned::match_ip, std::bind(&banned_ptr::get, _1), pair));
if (ban == bans_.end()) return "";
const std::string& nick = (*ban)->get_nick();
return (*ban)->get_reason() + (nick.empty() ? "" : " (" + nick + ")") + " (" + (*ban)->get_human_time_span() + ")";
}
void ban_manager::init_ban_help()
{
ban_help_ = "ban <mask> <time> <reason>\n"
"The time format is: %d[%s[%d[%s[...]]]] where %s is a time"
" modifier: s or S (seconds), m (minutes), h or H (hours), d"
" or D (days), M (months) or y or Y (years) and %d is a number.\n"
"Permanent bans can be set with 'permanent' or '0' as the time"
" argument.\n";
default_ban_times::iterator itor = ban_times_.begin();
if (itor != ban_times_.end())
{
ban_help_ += "You can also use " + itor->first;
++itor;
}
for (; itor != ban_times_.end(); ++itor)
{
ban_help_ += std::string(", ") + itor->first;
}
if (!ban_times_.empty())
{
ban_help_ += " for standard ban times. (not combinable)\n";
}
ban_help_ += "ban 127.0.0.1 2h20m flooded lobby\n"
"kban suokko 5D flooded again\n"
"kban suokko Y One year ban for constant flooding";
}
void ban_manager::load_config(const config& cfg)
{
ban_times_.clear();
for (const config &bt : cfg.child_range("ban_time")) {
time_t duration = 0;
if (parse_time(bt["time"], &duration)) {
ban_times_.insert(default_ban_times::value_type(bt["name"], duration));
}
}
init_ban_help();
if (filename_ != cfg["ban_save_file"])
{
dirty_ = true;
filename_ = cfg["ban_save_file"].str();
}
}
ban_manager::~ban_manager()
{
try {
write();
} catch (...) {}
}
ban_manager::ban_manager()
: bans_()
, deleted_bans_()
, time_queue_()
, ban_times_()
, ban_help_()
, filename_()
, dirty_(false)
{
init_ban_help();
}
}