-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathinit.lua
2491 lines (2252 loc) · 60.2 KB
/
init.lua
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
--[[
sban mod for Minetest designed and coded by [email protected]
request an insecure enviroment to load the db handler
and access files in the world folder. This requires
access via secure.trusted in the minetest.conf file
before it will work! For example:
secure.trusted = sban
]]
local ie = minetest.request_insecure_environment()
-- success?
if not ie then
error("insecure environment inaccessible" ..
" - make sure this mod has been added to the" ..
" secure.trusted setting in minetest.conf!")
end
local _sql = ie.require("lsqlite3")
-- secure this instance of sqlite3 global
if sqlite3 then sqlite3 = nil end
-- register admin privilege
minetest.register_privilege("ban_admin", {
description = "ban administrator",
give_to_singleplayer = false,
give_to_admin = true,
})
local WP = minetest.get_worldpath()
local WL -- whitelist cache
local ESC = minetest.formspec_escape
local FORMNAME = "sban:main"
local bans = {}
local name_cache = {}
local ip_cache = {}
local hotlist = {}
local queue = {}
local retry = 2 -- retries for save_failed
local delay = 5
local DB = WP.."/sban.sqlite"
local db_version = '0.2.1'
local db = _sql.open(DB) -- connection
local mod_version = '0.2.0'
local expiry, owner, owner_id, def_duration, display_max, names_per_id, api
local importer, ID, HL_Max, max_cache_records, ttl, cap, ip_limit
local formstate = {}
local t_units = {
s = 1, S=1, m = 60, h = 3600, H = 3600,
d = 86400, D = 86400, w = 604800, W = 604800,
M = 2592000, y = 31104000, Y = 31104000, [""] = 1
}
local createDb, tmp_db, tmp_final
sban = {} -- global table holds API functions
--[[
################
### Settings ###
################
]]
-- db
db:busy_timeout(50)
-- minetest.conf
if minetest.settings then
expiry = minetest.settings:get("sban.ban_max")
owner = minetest.settings:get("name")
def_duration = minetest.settings:get("sban.fs_duration") or "1w"
display_max = tonumber(minetest.settings:get("sban.display_max")) or 10
names_per_id = tonumber(minetest.settings:get("sban.accounts_per_id"))
ip_limit = tonumber(minetest.settings:get("sban.ip_limit"))
importer = minetest.settings:get_bool("sban.import_enabled", true)
HL_Max = tonumber(minetest.settings:get("sban.hotlist_max")) or 15
max_cache_records = tonumber(minetest.settings:get("sban.cache.max")) or 1000
ttl = tonumber(minetest.settings:get("sban.cache.ttl")) or 86400
api = minetest.settings:get_bool("sban.api", true)
else
-- old api method
expiry = minetest.setting_get("sban.ban_max")
owner = minetest.setting_get("name")
def_duration = minetest.setting_get("sban.fs_duration") or "1w"
display_max = tonumber(minetest.setting_get("sban.display_max")) or 10
names_per_id = tonumber(minetest.setting_get("sban.accounts_per_id"))
ip_limit = tonumber(minetest.setting_get("sban.ip_limit"))
importer = minetest.setting_getbool("sban.import_enable") or true
HL_Max = tonumber(minetest.setting_get("sban.hotlist_max")) or 15
max_cache_records = tonumber(minetest.setting_get("sban.cache_max")) or 1000
ttl = tonumber(minetest.setting_get("sban.cache_ttl")) or 86400
api = minetest.setting_getbool("sban.api") or true
end
--[[
######################
### DB callback ###
######################
]]
-- used for debugging, traces & logs sqlite3 actions
local dev = false
if dev then
db:trace(
function(ud, sql)
minetest.log("action", "Sqlite Trace: " .. sql)
end
)
-- Log the lines modified in the db
optbl = {
[_sql.UPDATE] = "UPDATE";
[_sql.INSERT] = "INSERT";
[_sql.DELETE] = "DELETE"
}
setmetatable(optbl,
{__index=function(t,n) return string.format("Unknown op %d",n) end})
udtbl = {0, 0, 0}
db:update_hook(
function(ud, op, dname, tname, rowid)
minetest.log("action", "[sban] " .. optbl[op] ..
" applied to db table " .. tname .. " on rowid " .. rowid)
end, udtbl
)
end
--[[
##########################
### Helper Functions ###
##########################
]]
-- Db wrapper for error reporting
-- @param stmt String containing SQL statements
-- @return Boolean and error message
local function db_exec(stmt)
if db:exec(stmt) ~= _sql.OK then
minetest.log("error", "[sban] Sqlite ERROR: "..db:errmsg())
return false, db:errmsg()
else
return true
end
end
-- Convert value to seconds (src: xban2)
-- @param t String containing alphanumerical duration
-- @return Integer seconds of duration
local function parse_time(str)
local s = 0
for n, u in str:gmatch("(%d+)([smhdwySHDWMY]?)") do
s = s + (tonumber(n) * (t_units[u] or 1))
end
return s
end
-- Convert UTC to human readable date format
-- @param utc_int Integer, seconds since epoch
-- @return String containing datetime
local function hrdf(utc_int)
if type(utc_int) == "number" then
return (utc_int and os.date("%c", utc_int))
end
end
-- Check if param is an ip address
-- @paran str String
-- @return true if ip else nil
local function is_ip(str)
if str:find(":") or str:find("%.") then
return true
end
end
-- Escape special chars in reason string
-- @param str String input
-- @return escaped string
local function escape_string(str)
-- handle apostrophes
return str:gsub("'", "''")
end
-- Format ip string
-- @param str String input
-- @return formatted String
local function ip_key(str)
-- strip point and colon chars to create a key
local res = str:gsub("%.", "")
res:gsub('%:', '')
return res
end
-- Increment db player id
-- @return nil
local function inc_id()
ID = ID + 1
return ID
end
-- Manage cache size
-- @return nil
local function trim_cache()
-- return if cache isn't full, nothing to do
if cap < max_cache_records then return end
local oldest = os.time() -- init
local name, id
-- iterate the name cache looking for the
-- oldest last_login value
for key, data in pairs(name_cache) do
if data.last_login < oldest then
oldest = data.last_login
name = key
id = data.id
end
end
-- remove entries in the ip cache
for k,v in pairs(ip_cache) do
if v == id then
ip_cache[k] = nil
end
end
-- remove name cache entry
name_cache[name] = nil
-- adjust the cap
cap = cap - 1
end
if importer then
createDb = [[
CREATE TABLE IF NOT EXISTS active (
id INTEGER(10) PRIMARY KEY,
name VARCHAR(50),
source VARCHAR(50),
created INTEGER(30),
reason VARCHAR(300),
expires INTEGER(30),
pos VARCHAR(50)
);
CREATE TABLE IF NOT EXISTS expired (
id INTEGER(10),
name VARCHAR(50),
source VARCHAR(50),
created INTEGER(30),
reason VARCHAR(300),
expires INTEGER(30),
u_source VARCHAR(50),
u_reason VARCHAR(300),
u_date INTEGER(30),
last_pos VARCHAR(50)
);
CREATE INDEX IF NOT EXISTS idx_expired_id ON expired(id);
CREATE TABLE IF NOT EXISTS name (
id INTEGER(10),
name VARCHAR(50) PRIMARY KEY,
created INTEGER(30),
last_login INTEGER(30),
login_count INTEGER(8) DEFAULT(1)
);
CREATE INDEX IF NOT EXISTS idx_name_id ON name(id);
CREATE INDEX IF NOT EXISTS idx_name_lastlogin ON name(last_login);
CREATE TABLE IF NOT EXISTS address (
id INTEGER(10),
ip VARCHAR(50) PRIMARY KEY,
created INTEGER(30),
last_login INTEGER(30),
login_count INTEGER(8) DEFAULT(1),
violation BOOLEAN
);
CREATE INDEX IF NOT EXISTS idx_address_id ON address(id);
CREATE INDEX IF NOT EXISTS idx_address_lastlogin ON address(last_login);
CREATE TABLE IF NOT EXISTS whitelist (
name_or_ip VARCHAR(50) PRIMARY KEY,
source VARCHAR(50),
created INTEGER(30)
);
CREATE TABLE IF NOT EXISTS config (
setting VARCHAR(28) PRIMARY KEY,
data VARCHAR(255)
);
CREATE TABLE IF NOT EXISTS violation (
id INTEGER PRIMARY KEY,
data VARCHAR
);
]]
db_exec(createDb)
tmp_db = [[
CREATE TABLE IF NOT EXISTS tmp_a (
id INTEGER(10),
name VARCHAR(50),
created INTEGER(30),
last_login INTEGER(30),
login_count INTEGER(8) DEFAULT(1)
);
CREATE TABLE IF NOT EXISTS tmp_b (
id INTEGER(10),
ip VARCHAR(50),
created INTEGER(30),
last_login INTEGER(30),
login_count INTEGER(8) DEFAULT(1),
violation BOOLEAN
);
CREATE TABLE IF NOT EXISTS tmp_c (
id INTEGER(10),
name VARCHAR(50),
source VARCHAR(50),
created INTEGER(30),
reason VARCHAR(300),
expires INTEGER(30),
pos VARCHAR(50)
);
CREATE TABLE IF NOT EXISTS tmp_d (
id INTEGER(10),
name VARCHAR(50),
source VARCHAR(50),
created INTEGER(30),
reason VARCHAR(300),
expires INTEGER(30),
u_source VARCHAR(50),
u_reason VARCHAR(300),
u_date INTEGER(30),
last_pos VARCHAR(50)
);
]]
tmp_final = [[
DELETE FROM tmp_a where rowid NOT IN (SELECT min(rowid) FROM tmp_a GROUP BY name);
DELETE FROM tmp_b where rowid NOT IN (SELECT min(rowid) FROM tmp_b GROUP BY ip);
DELETE FROM tmp_c where rowid NOT IN (SELECT min(rowid) FROM tmp_c GROUP BY id);
INSERT INTO name (id, name, created, last_login, login_count)
SELECT * FROM tmp_a WHERE tmp_a.name NOT IN (SELECT name FROM name);
INSERT INTO address(id, ip, created, last_login, login_count, violation)
SELECT * FROM tmp_b WHERE tmp_b.ip NOT IN (SELECT ip FROM address);
INSERT INTO active (id, name, source, created, reason, expires, pos)
SELECT * FROM tmp_c WHERE tmp_c.id NOT IN (SELECT id FROM active);
INSERT INTO expired (id, name, source,created, reason, expires, u_source, u_reason, u_date, last_pos)
SELECT * FROM tmp_d;
DROP TABLE tmp_a;
DROP TABLE tmp_b;
DROP TABLE tmp_c;
DROP TABLE tmp_d;
COMMIT;
PRAGMA foreign_keys = ON;
VACUUM;
]]
end
--[[
###########################
### Database: Queries ###
###########################
]]
-- Fetch an id for an ip or name
-- @param name_or_ip string
-- @returns id integer or nil
local function get_id(name_or_ip)
local q
if is_ip(name_or_ip) then
-- check cache first
if ip_cache[ip_key(name_or_ip)] then
return ip_cache[ip_key(name_or_ip)]
end
-- check db
q = ([[
SELECT id
FROM address
WHERE ip = '%s' LIMIT 1;]]
):format(name_or_ip)
else
-- check cache first
if name_cache[name_or_ip] then
return name_cache[name_or_ip].id
end
-- check db
q = ([[
SELECT id
FROM name
WHERE name = '%s' LIMIT 1;]]
):format(name_or_ip)
end
local it, state = db:nrows(q)
local row = it(state)
if row then
return row.id
end
end
-- Fetch last id from the name table
-- @return last id integer or nil
local function last_id()
local q = "SELECT MAX(id) AS id FROM name;"
local it, state = db:nrows(q)
local row = it(state)
if row then
return row.id
end
end
-- Fetch expired ban records
-- @param id integer
-- @return ipair table of expired ban records
local function player_ban_expired(id)
local r = {}
local q = ([[
SELECT * FROM expired WHERE id = %i;
]]):format(id)
for row in db:nrows(q) do
r[#r + 1] = row
end
return r
end
-- Fetch name records
-- @param id integer
-- @return ipair table of name records ordered by last login
local function name_records(id)
local r = {}
local q = ([[
SELECT * FROM name
WHERE id = %i ORDER BY last_login DESC;
]]):format(id)
for row in db:nrows(q) do
r[#r + 1] = row
end
return r
end
-- Fetch address records
-- @param id integer
-- @return ipair table of ip address records ordered by last login
local function address_records(id)
local r = {}
local q = ([[
SELECT * FROM address
WHERE id = %i ORDER BY last_login DESC;
]]):format(id)
for row in db:nrows(q) do
r[#r + 1] = row
end
return r
end
-- Fetch violation records
-- @param id integer
-- @return ipair table of violation records
local function violation_record(id)
local q = ([[
SELECT data FROM violation WHERE id = %i LIMIT 1;
]]):format(id)
local it, state = db:nrows(q)
local row = it(state)
if row then
return minetest.deserialize(row.data)
end
end
-- Fetch active bans
-- @return keypair table
local function get_active_bans()
local r = {}
local q = "SELECT * FROM active;"
for row in db:nrows(q) do
r[row.id] = row
end
return r
end
-- Fetch whitelist
-- @return keypair table
local function get_whitelist()
local r = {}
local q = "SELECT * FROM whitelist;"
for row in db:nrows(q) do
r[row.name_or_ip] = true
end
return r
end
-- Fetch config setting
-- @param name setting string
-- @return data string
local function get_setting(name)
local q = ([[SELECT data FROM config WHERE setting = '%s';]]):format(name)
local it, state = db:nrows(q)
local row = it(state)
if row then
return row.data
end
end
-- Fetch names like 'name'
-- @param name string
-- @return keypair table of names
local function get_names(name)
local r,t = {},{}
local q = "SELECT name FROM name WHERE name LIKE '%"..name.."%';"
for row in db:nrows(q) do
-- Simple sort using a temp table to remove duplicates
if not t[row.name] then
r[#r+1] = row.name
t[row.name] = true
end
end
return r
end
cap = 0
-- Build name and address cache
-- @return nil
local function build_cache()
-- get last login timestamp
local q = "SELECT max(last_login) AS login FROM name;"
local it, state = db:nrows(q)
local last = it(state)
if last.login then
last = last.login - ttl -- adjust
q = ([[
SELECT * FROM name WHERE last_login > %i
ORDER BY last_login ASC LIMIT %s;
]]):format(last, max_cache_records)
for row in db:nrows(q) do
name_cache[row.name] = row
cap = cap + 1
end
minetest.log("action", "[sban] caching " .. cap .. " name records")
local ctr = 0
for k, row in pairs(name_cache) do
for _,v in ipairs(address_records(row.id)) do
ip_cache[ip_key(v.ip)] = row.id
ctr = ctr + 1
end
end
minetest.log("action", "[sban] caching " .. ctr .. " ip records")
end
end
build_cache()
--[[
###########################
### Database: Inserts ###
###########################
]]
-- Create name record
-- @param id integer
-- @param name string
-- @param ts integer utc
-- @return true
-- @return false, error message
local function add_name_record(id, name, ts)
local stmt = ([[
INSERT INTO name (id,name,created,last_login,login_count)
VALUES (%i,'%s',%i,%i,1);
]]):format(id, name, ts, ts)
return db_exec(stmt)
end
-- Create ip record
-- @param id integer
-- @param ip string
-- @param ts integer os.time()
-- @return true
-- @return false, error message
local function add_ip_record(id, ip, ts)
local stmt = ([[
INSERT INTO address (
id,
ip,
created,
last_login,
login_count,
violation
) VALUES (%i,'%s',%i,%i,1,0);
]]):format(id, ip, ts, ts)
return db_exec(stmt)
end
-- Create and cache id record
-- @param id integer
-- @param name string
-- @param ts integer
-- @param ip string
-- @return true
-- @return false, error message
local function create_player_record(id, name, ts, ip)
local stmt = ([[
BEGIN TRANSACTION;
INSERT INTO name (
id,
name,
created,
last_login,
login_count
) VALUES (%i,'%s',%i,%i,1);
INSERT INTO address (
id,
ip,
created,
last_login,
login_count,
violation
) VALUES (%i,'%s',%i,%i,1,0);
COMMIT;
]]):format(id,name,ts,ts,id,ip,ts,ts)
return db_exec(stmt)
end
-- Create db whitelist record
-- @param source name string
-- @param name_or_ip string
-- @return true
-- @return false, error message
local function add_whitelist_record(source, name_or_ip, ts)
local stmt = ([[
INSERT INTO whitelist
VALUES ('%s', '%s', %i)
]]):format(name_or_ip, source, ts)
return db_exec(stmt)
end
-- Create db ban record
-- @param id integer
-- @param name string
-- @param source string
-- @param created string
-- @param reason string
-- @param expires integer
-- @param pos string
-- @return true
-- @return false, error message
local function create_ban_record(id, name, source, created, reason, expires, pos)
local stmt = ([[
INSERT INTO active VALUES (%i,'%s','%s',%i,'%s',%i,'%s');
]]):format(id, name, source, created, reason, expires, pos)
return db_exec(stmt)
end
-- initialise db setting
-- @param setting string
-- @param data string
-- @return res bool, error string
local function init_setting(setting, data)
local stmt = ([[
INSERT INTO config VALUES ('%s', '%s');
]]):format(setting, data)
return db_exec(stmt)
end
--[[
###########################
### Database: Updates ###
###########################
]]
-- Update login record
-- @param id integer
-- @param name string
-- @return true
-- @return false, error message
local function update_login_record(id, name, ts)
-- update Db name record
local stmt = ([[
UPDATE name SET
last_login = %i,
login_count = login_count + 1
WHERE name = '%s';
]]):format(ts, name)
return db_exec(stmt)
end
-- Update address record
-- @param id integer
-- @param ip string
-- @return true
-- @return false, error message
local function update_address_record(id, ip, ts)
local stmt = ([[
UPDATE address
SET
last_login = %i,
login_count = login_count + 1
WHERE id = %i AND ip = '%s';
]]):format(ts, id, ip)
return db_exec(stmt)
end
-- Update ban record
-- @param id integer
-- @param source name string
-- @param reason string
-- @param name string
-- @return true
-- @return false, error message
local function update_ban_record(id, source, reason, name, ts)
local row = bans[id] -- use ban cache table
local stmt = ([[
INSERT INTO expired VALUES (%i,'%s','%s',%i,'%s',%i,'%s','%s',%i,'%s');
DELETE FROM active WHERE id = %i;
]]):format(row.id, row.name, row.source, row.created, escape_string(row.reason),
row.expires, source, reason, ts, row.pos, row.id)
return db_exec(stmt)
end
-- Update violation status
-- @param ip string
-- @return true
-- @return false, error message
local function update_idv_status(ip)
local stmt = ([[
UPDATE address
SET
violation = 'true'
WHERE ip = '%s';
]]):format(ip)
return db_exec(stmt)
end
--[[
##################################
### Database: Delete Records ###
##################################
]]
-- Remove ban record
-- @param id integer
-- @return true
-- @return false, error message
local function del_ban_record(id)
local stmt = ([[
DELETE FROM active WHERE id = %i
]]):format(id)
return db_exec(stmt)
end
-- Remove whitelist entry
-- @param name_or_ip string
-- @return true
-- @return false, error message
local function del_whitelist_record(name_or_ip)
local stmt = ([[
DELETE FROM whitelist WHERE name_or_ip = '%s'
]]):format(name_or_ip)
return db_exec(stmt)
end
--[[
###################
### Functions ###
###################
]]
-- Kicks players by name or id
-- @param name_or_id string or integer
-- @return nil
local function kicker(player_name, msg)
local r, res
res = false
local id = get_id(player_name)
if id then r = name_records(id) end
if r == {} then
minetest.log("warning", "Kicker: Failed to retrieve db record for " .. player_name)
table.insert(r, {name = player_name}) -- use the name passed in as a failsafe
end
for i, v in ipairs(r) do
local player = minetest.get_player_by_name(v.name)
if player then
player:set_detach() -- not reqd in later versions of mt
res = minetest.kick_player(v.name, msg)
end
end
return res
end
-- Create and cache name record
-- @param id integer
-- @param name string
-- @return nil
local function add_name(id, name)
local ts = os.time()
local res = add_name_record(id, name, ts)
if res then
-- cache name record
name_cache[name] = {
id = id,
name = name,
last_login = ts,
login_count = 1
}
else
minetest.log("warning", ([[[sban] Failed to add %s with id %i
to the name table]]):format(name, id))
end
return res
end
-- Create and cache ip record
-- @param id integer
-- @param ip string
-- @return nil
local function add_ip(id, ip)
local ts = os.time()
local res = add_ip_record(id, ip, ts)
if res then
ip_cache[ip_key(ip)] = id -- cache
else
minetest.log("warning", ([[[sban] Failed to add %s with id %i
to the address table]]):format(ip, id))
end
return res
end
-- Create and cache id record
-- @param name string
-- @param ip string
-- @return nil, -1 or id
local function create_player(name, ip)
local ts, id, res, err
if queue[name] then
-- assign saved id and timestamp
ts = queue[name].ts
id = queue[name].id
else
-- assign id and timestamp
ts = os.time()
id = inc_id()
end
res, err = create_player_record(id, name, ts, ip)
if err and queue[name] == nil then
-- create new job
queue[name] = {
id = id, -- assigned id
ip = ip, -- ip address
ts = ts, -- timestamp
jt = 1, -- job type
n = 0 -- retry counter
}
elseif err and queue[name] then
return -1
elseif res then
-- success, cache name record
name_cache[name] = {
id = id,
name = name,
last_login = ts
}
return id
end
end
-- Create ban record
-- @param name string
-- @param source string
-- @param reason string
-- @param expires integer
-- @return bool
local function create_ban(name, source, reason, expires)
local ts = os.time()
local id = get_id(name)
local player = minetest.get_player_by_name(name)
local msg
reason = escape_string(reason)
expires = expires or 0
-- initialise last position & fetch if playing
local pos = ""
if player then
pos = minetest.pos_to_string(vector.round(player:getpos()))
end
local res = create_ban_record(id, name, source, ts, reason, expires, pos)
if res then
-- cache the ban
bans[id] = {
id = id,
name = name,
source = source,
created = ts,
reason = reason,
expires = expires,
last_pos = pos
}
msg = "Owner kick bypass triggered in create_ban_record"
-- owner cannot be kicked ;)
if not dev and owner_id == id then
minetest.log("action", msg)
return res
end
-- create kick & log messages
local msg_k, msg_l
if expires ~= 0 then
-- temporary ban
local date = hrdf(expires)
msg_k = ("Banned: Expires: %s, Reason: %s"):format(date, reason)
msg_l = ("[sban] %s temp banned by %s reason: %s"
):format(name, source, reason) -- log msg
else
msg_k = ("Banned: Reason: %s"):format(reason)
msg_l = ("[sban] %s banned by %s reason: %s"
):format(name, source, reason)
end
minetest.log("action", msg_l)
kicker(name, msg_k)
end
return res
end
-- Update player ban
-- @param id integer
-- @param source name string
-- @param reason string
-- @param name string
-- @return bool
local function update_ban(id, source, reason, name)
local ts = os.time()
reason = escape_string(reason)
local res = update_ban_record(id, source, reason, name, ts)
if res then
bans[id] = nil -- update cache
-- log event
minetest.log("action",
("[sban] %s unbanned by %s reason: %s"):format(name, source, reason))
else
minetest.log("warning",
("[sban] record failed to save when banning %s"):format(name))
end
return res
end
-- Delete active ban by id
-- @param id integer
-- @return bool
local function del_ban(id)
local res = del_ban_record(id)
if res then
bans[id] = nil -- update cache
else
minetest.log("warning", ([[[sban] Failed to delete ban for id %i
in the active table]]):format(id))
end
return res
end
-- Update login record
-- @param id integer
-- @param name string
-- @return bool
local function update_login(id, name)
local ts = os.time()
local res = update_login_record(id, name, ts)
if res then
if not name_cache[name] then
name_cache[name] = {
id = id,
name = name,
last_login = ts
}
else
name_cache[name].last_login = ts
end
else
minetest.log("warning", ([[[sban] Failed to update login for %s with id %i
in the name table]]):format(name, id))