aboutsummaryrefslogtreecommitdiffstats
path: root/util/session.lua
blob: fda7fccdccfbcca1e37e035d7de6d6873ec192ba (plain)
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
local initialize_filters = require "util.filters".initialize;
local logger = require "util.logger";

local function new_session(typ)
	local session = {
		type = typ .. "_unauthed";
	};
	return session;
end

local function set_id(session)
	local id = typ .. tostring(session):match("%x+$"):lower();
	session.id = id;
	return session;
end

local function set_logger(session)
	local log = logger.init(id);
	session.log = log;
	return session;
end

local function set_conn(session, conn)
	session.conn = conn;
	session.ip = conn:ip();
	return session;
end

local function set_send(session)
	local conn = session.conn;
	if not conn then
		function session.send(data)
			log("debug", "Discarding data sent to unconnected session: %s", tostring(data));
			return false;
		end
		return session;
	end
	local filter = initialize_filters(session);
	local w = conn.write;
	session.send = function (t)
		if t.name then
			t = filter("stanzas/out", t);
		end
		if t then
			t = filter("bytes/out", tostring(t));
			if t then
				local ret, err = w(conn, t);
				if not ret then
					session.log("debug", "Error writing to connection: %s", tostring(err));
					return false, err;
				end
			end
		end
		return true;
	end
	return session;
end

return {
	new = new_session;
	set_id = set_id;
	set_logger = set_logger;
	set_conn = set_conn;
	set_send = set_send;
}