/
infond.lua
720 lines (608 loc) · 20.3 KB
/
infond.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
--[[
Copyright (c) 2006 Florian Wesch <fw@dividuum.de>. All Rights Reserved.
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; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
]]--
-----------------------------------------------------------
-- Konfiguration laden
-----------------------------------------------------------
assert(loadfile(os.getenv("INFON_CONFIG") or (PREFIX .. "config.lua")))()
stats = {
num_clients = 0;
num_refused = 0;
num_players = 0;
num_maps = 0;
num_exec = 0;
}
-----------------------------------------------------------
-- Klasse fuer Clientverbindung
-----------------------------------------------------------
clients= {}
Client = {}
function Client.create(fd, addr)
stats.num_clients = stats.num_clients + 1
local obj = {}
setmetatable(obj, {
__index = function(self, what)
-- Nach Klassenmethode suchen
if Client[what] then
return Client[what]
end
-- Nix? Dann per default in Objekttabelle suchen
end
})
clients[fd] = obj
obj.fd = fd
obj:on_new_client(addr)
end
function Client.check_accept(addr)
for n, rule in ipairs(acl) do
if rule.time and rule.time < os.time() then
table.remove(acl, n)
elseif string.match(addr, rule.pattern) then
if rule.deny then
stats.num_refused = stats.num_refused + 1
return false, "refusing connection " .. addr .. ": " .. rule.deny .. "\r\n"
else
return true
end
end
end
return true
end
function Client:readln()
return coroutine.yield(self.thread)
end
paste = 0
function Client:nextpaste()
paste = paste + 1
return paste
end
function Client:paste_name(num)
return num
end
function Client:paste_full_name(num)
return "paste " .. self:paste_name(num) .. " from client " .. self.fd
end
function Client:kick_ban(reason, time)
local addr = self.addr:match("^([^:]+:[^:]+:?)")
local time = time and os.time() + time or nil
table.insert(acl, 1, {
pattern = "^" .. addr .. ".*$",
deny = reason,
time = time
})
self:disconnect(reason)
end
function Client:on_new_client(addr)
self.addr = addr
self.local_output = true
self.prompt = "> "
self.failed_shell = 0
self.forward_unknown = false
self.highlevel = highlevel[1]
self.last_action = {}
-- print(self.addr .. " accepted")
scroller_add(self.addr .. " joined")
self:start_thread()
end
function Client:start_thread()
self.thread = coroutine.create(self.handler)
local ok, msg = coroutine.resume(self.thread, self)
if not ok then
self:disconnect(msg)
end
end
function Client:on_destroy(reason)
-- print(self.addr .. " closed: " .. reason)
scroller_add(self.addr .. " disconnected: " .. reason)
end
function Client:on_input(line)
local ok, msg = coroutine.resume(self.thread, line)
if not ok then
self:writeln(msg)
self:writeln("restarting mainloop...")
self:start_thread()
end
end
function Client:disconnect(reason)
client_disconnect(self.fd, reason)
end
function Client:write(data)
client_write(self.fd, data)
end
function Client:turn_into_guiclient()
client_make_guiclient(self.fd)
end
function Client:is_guiclient()
return client_is_gui_client(self.fd)
end
function Client:attach_to_player(playerno, pass)
local ok, ret = pcall(client_attach_to_player, self.fd, playerno, pass)
if not ok then
return ret
elseif not ret then
return "attach failed. password wrong?"
else
return nil
end
end
function Client:detach()
local playerno = self:get_player()
if playerno then
client_detach_from_player(self.fd, playerno)
else
self:writeln("you cannot detach since you are not attached")
end
end
function Client:get_player()
return client_player_number(self.fd)
end
function Client:check_name(name)
if check_name_password and check_name_password(name, nil) then
self:write("Name '" .. name .. "' requires a password: ")
return check_name_password(name, self:readln())
else
return true
end
end
function Client:set_name(name)
local playerno = self:get_player()
if playerno and player_get_name(playerno) ~= name and name ~= '' then
local oldname = player_get_name(playerno)
if not self:check_name(name) then return false end
player_set_name(playerno, name)
local newname = player_get_name(playerno)
scroller_add(oldname .. " renamed to " .. newname)
return true
else
return false
end
end
function Client:set_color(color)
local playerno = self:get_player()
if playerno then
player_set_color(playerno, color)
else
self:writeln("you have no player!")
end
end
function Client:kill()
if self:get_player() then
player_kill(self:get_player())
else
self:writeln("no need to kill. you have no player")
end
end
function Client:execute(code, name)
local playerno = self:get_player()
if playerno then
stats.num_exec = stats.num_exec + 1
player_execute(playerno, self.local_output and self.fd or nil, code, name)
else
self:writeln("you do not have a player. cannot execute your code.")
end
end
function Client:writeln(line)
if line then
self:write(line .. "\r\n")
else
self:write("\r\n")
end
end
function Client:rate_limit(action, every)
local time, last = real_time(), self.last_action[action]
if not last or time > last + every then
self.last_action[action] = real_time()
return true
else
self:writeln(string.format("%s too fast. please wait %.1fs...",
action, (every - (time - last)) / 1000))
return false
end
end
function Client:centerln(line)
self:writeln(string.rep(" ", (60 - string.len(line)) / 2) .. line)
end
-- Speziell formatiert, so dass es von einem GUI Client
-- wie andere in packet.h definierte Packete gelesen
-- gelesen werden kann (len = 32 (space), type = 32 (space).
function Client:welcome(msg)
local msglen = string.len(msg)
if msglen > 28 then
print('welcome message too long')
msg = "Press <enter>"
msglen = string.len(msg)
end
self:write(" \r\n" .. msg .. string.rep(" ", 28 - msglen) .. "\r\n")
end
function Client.write_all(line)
table.foreach(clients, function (fd, obj)
obj:write(line)
end)
end
function Client.writeln_all(line)
table.foreach(clients, function (fd, obj)
obj:writeln(line)
end)
end
wall = Client.writeln_all
-----------------------------------------------------------
-- Server C Callbacks
-----------------------------------------------------------
function on_new_client(addr)
return Client.check_accept(addr)
end
function on_client_accepted(fd, addr)
Client.create(fd, addr)
end
function on_client_input(fd, line)
clients[fd]:on_input(line)
end
function on_client_close(fd, reason)
clients[fd]:on_destroy(reason)
clients[fd] = nil
end
-----------------------------------------------------------
-- Game C Callbacks
-----------------------------------------------------------
function on_game_started()
-- Demos starten?
if type(demo) == "string" then
server_start_writer(string.format("%s-%08X.demo", demo, os.time()), true, true);
elseif type(demo) == "function" then
server_start_writer(demo(), true, true)
end
-- Message
scroller_add("Started map " .. map)
-- wall("Started map " .. map)
-- server_tick anlegen
server_tick = coroutine.wrap(ServerMain)
-- Handler fuer Dinge, welche nur beim ersten Spiel aufgerufen werden sollen
if not first_game then
first_game = true
-- competition?
if competition then
set_realtime(false)
competition_done_setup = true
competition_rounds = #maps
disable_joining = "competition mode"
for _, bot in pairs(competition_bots) do
appendline(competition_log, string.format("joining '%s' as %d", bot.source, start_bot(bot.source, bot.log)))
end
end
-- Nach dem Starten des ersten Spiels einmalig Funktion autoexec aufrufen
if autoexec then pcall(autoexec) end
end
-- Mapchange
if competition then
appendline(competition_log, string.format("%d starting on map '%s'", os.time(), map))
end
end
function on_game_ended()
-- competition?
if competition then
for pno in each_player() do
appendline(competition_log, string.format("%d: score %d, creatures %d",
pno, player_score(pno), player_num_creatures(pno)))
end
appendline(competition_log, string.format("%d completed", os.time()))
competition_rounds = competition_rounds - 1
if competition_rounds == 0 then
shutdown()
end
end
-- kill all creatures
killall()
-- reset score
for pno in each_player() do
player_set_score(pno, 0)
end
end
-----------------------------------------------------------
-- World Funktionen
-----------------------------------------------------------
current_map = 1
map = maps[current_map]
function world_rotate_map()
current_map = current_map + 1
if current_map > #maps then
current_map = 1
end
map = maps[current_map]
end
function world_get_dummy()
return {
level_size = function () return 3,3 end;
level_koth_pos = function () return 1,1 end;
level_init = function () end;
level_tick = function () end;
level_spawn_point = function () end;
}
end
function world_load(map)
local world_code = assert(loadfile(PREFIX .. "level/" .. map .. ".lua"))
-- prepare safe world environment
world = {
-- lua functions
print = print;
pairs = pairs;
ipairs = ipairs;
unpack = unpack;
math = { random = math.random };
string = { upper = string.upper;
sub = string.sub;
len = string.len; };
table = { getn = table.getn };
-- game functions
world_dig = world_dig;
world_set_type = world_set_type;
world_set_gfx = world_set_gfx;
world_get_type = world_get_type;
world_get_gfx = world_get_gfx;
world_find_digged = world_find_digged;
world_add_food = world_add_food;
world_make_border = world_make_border;
world_fill_all = world_fill_all;
world_tile_center = world_tile_center;
game_time = game_time;
level_spawn_point = world_find_digged_worldcoord;
-- game constants
TILE_WIDTH = TILE_WIDTH;
TILE_HEIGHT = TILE_HEIGHT;
TILE_SOLID = TILE_SOLID;
TILE_PLAIN = TILE_PLAIN;
TILE_WATER = 2; -- compatibility
TILE_GFX_SOLID = TILE_GFX_SOLID;
TILE_GFX_PLAIN = TILE_GFX_PLAIN;
TILE_GFX_BORDER = TILE_GFX_BORDER;
TILE_GFX_SNOW_SOLID = TILE_GFX_SNOW_SOLID;
TILE_GFX_SNOW_PLAIN = TILE_GFX_SNOW_PLAIN;
TILE_GFX_SNOW_BORDER = TILE_GFX_SNOW_BORDER;
TILE_GFX_WATER = TILE_GFX_WATER;
TILE_GFX_LAVA = TILE_GFX_LAVA;
TILE_GFX_NONE = TILE_GFX_NONE;
TILE_GFX_KOTH = TILE_GFX_KOTH;
TILE_GFX_DESERT = TILE_GFX_DESERT;
}
-- activate environment for world code and load world
setfenv(world_code, world)()
local w, h = world.level_size()
local kx, ky = world.level_koth_pos()
return w, h, kx, ky
end
function world_init()
stats.num_maps = stats.num_maps + 1
local ok, w, h, kx, ky = pcall(world_load, map)
if not ok then
print("cannot load world '" .. map .. "': " .. w .. ". using dummy world")
world = world_get_dummy()
w, h = world.level_size()
kx, ky = world.level_koth_pos()
end
world_tick = coroutine.wrap(world_main)
return w, h, kx, ky
end
function world_main()
local ok, ret = pcall(world.level_init)
if not ok then
print("initializing world failed: " .. ret)
end
while true do
ok, ret = pcall(world.level_tick)
if not ok then
print("calling level_tick failed: " .. ret)
end
coroutine.yield()
end
end
function world_add_food_by_worldcoord(x, y, amount)
return world_add_food(x / TILE_WIDTH, y / TILE_HEIGHT, amount)
end
function world_tile_center(x, y)
return (x + 0.5) * TILE_WIDTH, (y + 0.5) * TILE_HEIGHT
end
function world_find_digged_worldcoord()
local x, y = world_find_digged()
if not x then return end
return world_tile_center(x, y)
end
function world_get_spawn_point(player)
return world.level_spawn_point(player)
end
-- compatibility function. do not use for new maps.
function world_dig(x, y, typ, gfx)
gfx = gfx or typ
if typ == world.TILE_WATER then -- water
world_set_gfx(x, y, TILE_GFX_WATER)
return
end
local w, h = world.level_size()
local kx, ky = world.level_koth_pos()
if x == kx and y == ky then
gfx = TILE_GFX_KOTH
end
return world_set_type(x, y, typ) and world_set_gfx(x, y, gfx)
end
function world_fill_all(gfx)
local w, h = world.level_size()
for x = 0, w - 1 do
for y = 0, h - 1 do
world_set_gfx(x, y, gfx)
end
end
end
function world_make_border(gfx)
local w, h = world.level_size()
for x = 0, w-1 do
world_set_gfx(x, 0, gfx)
world_set_gfx(x, h - 1, gfx)
end
for y = 0, h-1 do
world_set_gfx(0 , y, gfx)
world_set_gfx(w - 1, y, gfx)
end
end
-----------------------------------------------------------
-- Rules Funktionen
-----------------------------------------------------------
function rules_init()
local rules_code = assert(loadfile(PREFIX .. "rules/" .. rules .. ".lua"))
-- prepare safe rules environment
rule = {
-- lua functions
print = print;
-- game functions
game_time = game_time;
each_player = each_player;
player_score = player_score;
player_get_name = player_get_name;
player_change_score = player_change_score;
creature_spawn = creature_spawn;
creature_set_food = creature_set_food;
creature_get_food = creature_get_food;
creature_get_pos = creature_get_pos;
creature_get_player = creature_get_player;
creature_get_type = creature_get_type;
world_get_spawn_point = world_get_spawn_point;
world_add_food_by_worldcoord= world_add_food_by_worldcoord;
get_score_limit = function () return score_limit end;
get_time_limit = function () return time_limit end;
scroller_add = scroller_add;
set_intermission = set_intermission;
world_rotate_map = world_rotate_map;
reset = reset;
-- game constants
CREATURE_SMALL = CREATURE_SMALL;
CREATURE_BIG = CREATURE_BIG;
CREATURE_FLYER = CREATURE_FLYER;
}
-- activate environment for rules code and load rules
setfenv(rules_code, rule)()
end
function rules_call(name, ...)
if type(rule) ~= "table" then
error("'rule' is not a table. cannot call rule handler '" .. name .. "'")
end
if not rule[name] then
error("rule handler '" .. name .. "' not defined")
end
rule[name](...)
end
-----------------------------------------------------------
-- Praktisches?
-----------------------------------------------------------
function isnumber(var)
return tostring(tonumber(var)) == var
end
function appendline(filename, line)
if not filename then return end
local file = assert(io.open(filename, "a+"))
file:write(string.format("%s\n", line))
file:close()
end
function kick(fd, msg)
msg = msg or "kicked"
clients[fd]:disconnect(msg)
end
function kickban(fd, msg)
msg = msg or "kickbanned"
clients[fd]:kick_ban(msg)
end
function killall()
for pno in each_player() do
player_kill_all_creatures(pno)
end
end
function reset()
game_end()
end
function changemap(next_map)
map = next_map
reset()
end
function kickall()
table.foreach(clients, function (fd, client)
clients[fd]:disconnect("kicked")
end)
end
function p(x)
if type(x) == "table" then
cprint("+--- Table: " .. tostring(x))
for key, val in pairs(x) do
cprint("| " .. tostring(key) .. " " .. tostring(val))
end
cprint("+-----------------------")
else
cprint(type(x) .. " - " .. tostring(x))
end
end
function clientlist()
table.foreach(clients, function (fd, client)
cprint(string.format("%4d %s - %s", fd, client_is_gui_client(fd) and "*" or " ", client.addr))
end)
end
function batch()
cprint("enter lua code. '.' ends input.")
local code = ""
while true do
local input = coroutine.yield() -- read next line
if input == "." then
break
else
code = code .. input .. "\n"
end
end
assert(loadstring(code))()
end
function acllist()
for n, rule in ipairs(acl) do
cprint(string.format("%2d: %-30s - %9d - %s", n, rule.pattern, rule.time and rule.time - os.time() or -1, rule.deny or "accept"))
end
end
function start_listener()
assert(setup_listener(listenaddr, listenport),
string.format("cannot setup listener on %s:%d", listenaddr, listenport))
end
function stop_listener()
setup_listener("", 0)
end
function start_bot(botcode, logfile, highlevelcode)
local highlevelcode = highlevelcode or highlevel[1]
local password = tostring(math.random(100000, 999999))
local botfile = assert(io.open(botcode, "rb"))
local botsource = botfile:read("*a")
botfile:close()
local _, _, name = botcode:find("([^/\\]+)\.lua")
local playerno = player_create(name or botcode, password, highlevelcode)
if not playerno then
error("cannot create new player")
end
cprint(string.format("player %d - %s (%s) joined with password '%s'", playerno, name or botcode, botcode, password))
player_set_no_client_kick_time(playerno, 0)
if logfile then
local ok, logclient = pcall(server_start_writer, logfile, false, false)
if ok then
client_attach_to_player(logclient, playerno, password)
else
cprint("cannot start log writer: " .. logclient)
end
end
player_execute(playerno, nil, botsource, botcode)
return playerno
end
-----------------------------------------------------------
-- Clienthandler laden
-----------------------------------------------------------
assert(loadfile(PREFIX .. "server.lua"))()
-- setup listen socket
if listenaddr and listenport then start_listener() end