This repository was archived by the owner on Jul 19, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.lua
More file actions
200 lines (162 loc) · 5.24 KB
/
server.lua
File metadata and controls
200 lines (162 loc) · 5.24 KB
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
--[[
- @module server
- @brief This is the server file that the client connects to
--]]
local server = {}
assert = require("batteries.assert")
local stringx = require("batteries.stringx")
local socket = require("socket")
server.inited = false
server.clients = {}
server.host = "*"
server.port = 8000
server.allowedAddresses = { "127.0.0.1" }
local __NULL__FUNC__ = function() end
--[[
- @brief Log a message with the current date and time to the console.
- @param `string` Formatable text
- @param `...` Arguments to format the log with
--]]
function server:log(format, ...)
local dateTime = os.date("%m/%d/%Y %H:%M:%S")
print("[" .. dateTime .. "] " .. string.format(format, ...))
end
--[[
- @brief Initialize the server protocol.
--]]
function server:init()
assert:equal(self.inited, false)
self.socket = socket.bind(self.host, self.port)
assert:some(self.socket, "socket failed to be created")
self.socket:settimeout(0)
local _, port = self.socket:getsockname()
self:log("Server initialized on port %d", port)
self.inited = true
end
--[[
- @brief Configure the server settings.
- @param `table` Structured as { port = `number`, addresses = { `string`, `string`, `...` } }
--]]
function server:config(config)
if config then
if config.port then
self.port = assert:type(config.port, "number")
end
if config.addresses then
if type(config.addresses) ~= "nil" and config.addresses ~= "*" then
self.allowedAddresses = assert:type(config.addresses, "table")
return
end
self.allowedAddresses = nil
end
end
end
--[[
- @brief Handle receiving of data per line.
- @param `tcp{connected}` Client object that was accepted in `client:update()`.
- @note If there's no data and the Client timed out, we want to wait for more data.
- @note If there's no data and we get any other message, close the Client connection.
- @note If there's data, we want to return it to the main server to log that we got it.
--]]
function server:receive(client)
while true do
local data, message = client:receive("*l")
if not data then
if message == "timeout" then
coroutine.yield(true)
else
coroutine.yield(nil)
end
else
return data
end
end
end
--[[
- @brief Handle when we get a Client to connect.
- @param `tcp{connected}` Client object from `server:update()`
- @note This function also handls receiving data from the Client.
- @note The server expects already-parsed Lua data from the Client's end.
--]]
function server:onConnect(client)
local ip, _ = client:getsockname()
assert:some(ip, "failed to retrieve sockname for client")
while true do
local line, _ = self:receive(client)
if not line or #line == 0 then
break
end
local data_lines = stringx.split(line, "/", 1)
local values = {love.data.unpack(data_lines[1], data_lines[2])}
table.remove(values, #values)
self:log(table.concat(values, ", "))
end
client:close()
end
--[[
- @brief Check if an IP address is allowed to connect.
- @param `string` IP address to check.
- @note `server.allowedAddresses` handles this, so add IP addresses that you trust.
- @note However, setting the table to either `nil` or "*" can allow any connection.
--]]
function server:checkAddressAllowed(hostname)
if self.allowedAddresses == nil then
return true
end
for _, address in ipairs(self.allowedAddresses) do
local pattern = "^" .. address:gsub("%.", "%%."):gsub("%*", "%%d*") .. "$"
if hostname:match(pattern) then
return true
end
end
return false
end
--[[
- @brief Update the server protocol.
- @note Waits and accepts clients to be useable for data reception.
- @note Once a Client is accepted, it is checked against `server.allowedAddresses`.
- @note It is then kept alive until the server has been told that the Client disconnects.
--]]
function server:update()
if not self.inited then
self:init()
end
while true do
local client = self.socket:accept()
if not client then
break
end
client:settimeout(0)
local ip, port = client:getpeername()
if self:checkAddressAllowed(ip) then
local connection = coroutine.wrap(function()
xpcall(self:onConnect(client), __NULL__FUNC__)
end)
self.clients[connection] = { ip = ip, port = port }
self:log("Client Connection: %s:%d", ip, port)
else
self:log("Got non-allowed connection from %s:%d", ip, port)
client:close()
end
end
for connection, _ in pairs(self.clients) do
local status = connection()
if status == nil then
local v = self.clients[connection]
self:log("Client Disconnected: %s:%d", v.ip, v.port)
self.clients[connection] = nil
end
end
end
--[[
- @brief Close the server down.
- @note Calls `socket:shutdown()` and then `socket:close()`.
--]]
function server:close()
if not self.socket then
return
end
self.socket:shutdown()
self.socket:close()
end
return server