Blame view

publish/skynet/lualib/snax/msgserver.lua 7.23 KB
4d6f285d   zhouhaihai   增加发布功能
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
  local skynet = require "skynet"
  local gateserver = require "snax.gateserver"
  local netpack = require "skynet.netpack"
  local crypt = require "skynet.crypt"
  local socketdriver = require "skynet.socketdriver"
  local assert = assert
  local b64encode = crypt.base64encode
  local b64decode = crypt.base64decode
  
  --[[
  
  Protocol:
  
  	All the number type is big-endian
  
  	Shakehands (The first package)
  
  	Client -> Server :
  
  	base64(uid)@base64(server)#base64(subid):index:base64(hmac)
  
  	Server -> Client
  
  	XXX ErrorCode
  		404 User Not Found
  		403 Index Expired
  		401 Unauthorized
  		400 Bad Request
  		200 OK
  
  	Req-Resp
  
  	Client -> Server : Request
  		word size (Not include self)
  		string content (size-4)
  		dword session
  
  	Server -> Client : Response
  		word size (Not include self)
  		string content (size-5)
  		byte ok (1 is ok, 0 is error)
  		dword session
  
  API:
  	server.userid(username)
  		return uid, subid, server
  
  	server.username(uid, subid, server)
  		return username
  
  	server.login(username, secret)
  		update user secret
  
  	server.logout(username)
  		user logout
  
  	server.ip(username)
  		return ip when connection establish, or nil
  
  	server.start(conf)
  		start server
  
  Supported skynet command:
  	kick username (may used by loginserver)
  	login username secret  (used by loginserver)
  	logout username (used by agent)
  
  Config for server.start:
  	conf.expired_number : the number of the response message cached after sending out (default is 128)
  	conf.login_handler(uid, secret) -> subid : the function when a new user login, alloc a subid for it. (may call by login server)
  	conf.logout_handler(uid, subid) : the functon when a user logout. (may call by agent)
  	conf.kick_handler(uid, subid) : the functon when a user logout. (may call by login server)
  	conf.request_handler(username, session, msg) : the function when recv a new request.
  	conf.register_handler(servername) : call when gate open
  	conf.disconnect_handler(username) : call when a connection disconnect (afk)
  ]]
  
  local server = {}
  
  skynet.register_protocol {
  	name = "client",
  	id = skynet.PTYPE_CLIENT,
  }
  
  local user_online = {}
  local handshake = {}
  local connection = {}
  
  function server.userid(username)
  	-- base64(uid)@base64(server)#base64(subid)
  	local uid, servername, subid = username:match "([^@]*)@([^#]*)#(.*)"
  	return b64decode(uid), b64decode(subid), b64decode(servername)
  end
  
  function server.username(uid, subid, servername)
  	return string.format("%s@%s#%s", b64encode(uid), b64encode(servername), b64encode(tostring(subid)))
  end
  
  function server.logout(username)
  	local u = user_online[username]
  	user_online[username] = nil
  	if u.fd then
  		gateserver.closeclient(u.fd)
  		connection[u.fd] = nil
  	end
  end
  
  function server.login(username, secret)
  	assert(user_online[username] == nil)
  	user_online[username] = {
  		secret = secret,
  		version = 0,
  		index = 0,
  		username = username,
  		response = {},	-- response cache
  	}
  end
  
  function server.ip(username)
  	local u = user_online[username]
  	if u and u.fd then
  		return u.ip
  	end
  end
  
  function server.start(conf)
  	local expired_number = conf.expired_number or 128
  
  	local handler = {}
  
  	local CMD = {
  		login = assert(conf.login_handler),
  		logout = assert(conf.logout_handler),
  		kick = assert(conf.kick_handler),
  	}
  
  	function handler.command(cmd, source, ...)
  		local f = assert(CMD[cmd])
  		return f(...)
  	end
  
  	function handler.open(source, gateconf)
  		local servername = assert(gateconf.servername)
  		return conf.register_handler(servername)
  	end
  
  	function handler.connect(fd, addr)
  		handshake[fd] = addr
  		gateserver.openclient(fd)
  	end
  
  	function handler.disconnect(fd)
  		handshake[fd] = nil
  		local c = connection[fd]
  		if c then
  			c.fd = nil
  			connection[fd] = nil
  			if conf.disconnect_handler then
  				conf.disconnect_handler(c.username)
  			end
  		end
  	end
  
  	handler.error = handler.disconnect
  
  	-- atomic , no yield
  	local function do_auth(fd, message, addr)
  		local username, index, hmac = string.match(message, "([^:]*):([^:]*):([^:]*)")
  		local u = user_online[username]
  		if u == nil then
  			return "404 User Not Found"
  		end
  		local idx = assert(tonumber(index))
  		hmac = b64decode(hmac)
  
  		if idx <= u.version then
  			return "403 Index Expired"
  		end
  
  		local text = string.format("%s:%s", username, index)
  		local v = crypt.hmac_hash(u.secret, text)	-- equivalent to crypt.hmac64(crypt.hashkey(text), u.secret)
  		if v ~= hmac then
  			return "401 Unauthorized"
  		end
  
  		u.version = idx
  		u.fd = fd
  		u.ip = addr
  		connection[fd] = u
  	end
  
  	local function auth(fd, addr, msg, sz)
  		local message = netpack.tostring(msg, sz)
  		local ok, result = pcall(do_auth, fd, message, addr)
  		if not ok then
  			skynet.error(result)
  			result = "400 Bad Request"
  		end
  
  		local close = result ~= nil
  
  		if result == nil then
  			result = "200 OK"
  		end
  
  		socketdriver.send(fd, netpack.pack(result))
  
  		if close then
  			gateserver.closeclient(fd)
  		end
  	end
  
  	local request_handler = assert(conf.request_handler)
  
  	-- u.response is a struct { return_fd , response, version, index }
  	local function retire_response(u)
  		if u.index >= expired_number * 2 then
  			local max = 0
  			local response = u.response
  			for k,p in pairs(response) do
  				if p[1] == nil then
  					-- request complete, check expired
  					if p[4] < expired_number then
  						response[k] = nil
  					else
  						p[4] = p[4] - expired_number
  						if p[4] > max then
  							max = p[4]
  						end
  					end
  				end
  			end
  			u.index = max + 1
  		end
  	end
  
  	local function do_request(fd, message)
  		local u = assert(connection[fd], "invalid fd")
  		local session = string.unpack(">I4", message, -4)
  		message = message:sub(1,-5)
  		local p = u.response[session]
  		if p then
  			-- session can be reuse in the same connection
  			if p[3] == u.version then
  				local last = u.response[session]
  				u.response[session] = nil
  				p = nil
  				if last[2] == nil then
  					local error_msg = string.format("Conflict session %s", crypt.hexencode(session))
  					skynet.error(error_msg)
  					error(error_msg)
  				end
  			end
  		end
  
  		if p == nil then
  			p = { fd }
  			u.response[session] = p
  			local ok, result = pcall(conf.request_handler, u.username, message)
  			-- NOTICE: YIELD here, socket may close.
  			result = result or ""
  			if not ok then
  				skynet.error(result)
  				result = string.pack(">BI4", 0, session)
  			else
  				result = result .. string.pack(">BI4", 1, session)
  			end
  
  			p[2] = string.pack(">s2",result)
  			p[3] = u.version
  			p[4] = u.index
  		else
  			-- update version/index, change return fd.
  			-- resend response.
  			p[1] = fd
  			p[3] = u.version
  			p[4] = u.index
  			if p[2] == nil then
  				-- already request, but response is not ready
  				return
  			end
  		end
  		u.index = u.index + 1
  		-- the return fd is p[1] (fd may change by multi request) check connect
  		fd = p[1]
  		if connection[fd] then
  			socketdriver.send(fd, p[2])
  		end
  		p[1] = nil
  		retire_response(u)
  	end
  
  	local function request(fd, msg, sz)
  		local message = netpack.tostring(msg, sz)
  		local ok, err = pcall(do_request, fd, message)
  		-- not atomic, may yield
  		if not ok then
  			skynet.error(string.format("Invalid package %s : %s", err, message))
  			if connection[fd] then
  				gateserver.closeclient(fd)
  			end
  		end
  	end
  
  	function handler.message(fd, msg, sz)
  		local addr = handshake[fd]
  		if addr then
  			auth(fd,addr,msg,sz)
  			handshake[fd] = nil
  		else
  			request(fd, msg, sz)
  		end
  	end
  
  	return gateserver.start(handler)
  end
  
  return server