Code tidying for xmpp{client,server}_listeners
[prosody.git] / net / xmppserver_listener.lua
1 -- Prosody IM v0.1
2 -- Copyright (C) 2008 Matthew Wild
3 -- Copyright (C) 2008 Waqas Hussain
4 -- 
5 -- This program is free software; you can redistribute it and/or
6 -- modify it under the terms of the GNU General Public License
7 -- as published by the Free Software Foundation; either version 2
8 -- of the License, or (at your option) any later version.
9 -- 
10 -- This program is distributed in the hope that it will be useful,
11 -- but WITHOUT ANY WARRANTY; without even the implied warranty of
12 -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 -- GNU General Public License for more details.
14 -- 
15 -- You should have received a copy of the GNU General Public License
16 -- along with this program; if not, write to the Free Software
17 -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18 --
19
20
21
22 local logger = require "logger";
23 local lxp = require "lxp"
24 local init_xmlhandlers = require "core.xmlhandlers"
25 local sm_new_session = require "core.sessionmanager".new_session;
26 local s2s_new_incoming = require "core.s2smanager".new_incoming;
27 local s2s_streamopened = require "core.s2smanager".streamopened;
28 local s2s_streamclosed = require "core.s2smanager".streamclosed;
29 local s2s_destroy_session = require "core.s2smanager".destroy_session;
30 local s2s_attempt_connect = require "core.s2smanager".attempt_connection;
31 local stream_callbacks = { ns = "http://etherx.jabber.org/streams", streamopened = s2s_streamopened, streamclosed = s2s_streamclosed, handlestanza =  core_process_stanza };
32
33 function stream_callbacks.error(session, error, data)
34         if error == "no-stream" then
35                 session:close("invalid-namespace");
36         else
37                 session.log("debug", "Server-to-server XML parse error: %s", tostring(error));
38                 session:close("xml-not-well-formed");
39         end
40 end
41
42 local function handleerr(err) log("error", "Traceback[s2s]:", err, debug.traceback()); end
43 function stream_callbacks.handlestanza(a, b)
44         xpcall(function () core_process_stanza(a, b) end, handleerr);
45 end
46
47 local connlisteners_register = require "net.connlisteners".register;
48
49 local t_insert = table.insert;
50 local t_concat = table.concat;
51 local t_concatall = function (t, sep) local tt = {}; for _, s in ipairs(t) do t_insert(tt, tostring(s)); end return t_concat(tt, sep); end
52 local m_random = math.random;
53 local format = string.format;
54 local sm_new_session, sm_destroy_session = sessionmanager.new_session, sessionmanager.destroy_session; --import("core.sessionmanager", "new_session", "destroy_session");
55 local st = stanza;
56
57 local sessions = {};
58 local xmppserver = { default_port = 5269, default_mode = "*a" };
59
60 -- These are session methods --
61
62 local function session_reset_stream(session)
63         -- Reset stream
64                 local parser = lxp.new(init_xmlhandlers(session, stream_callbacks), "|");
65                 session.parser = parser;
66                 
67                 session.notopen = true;
68                 
69                 function session.data(conn, data)
70                         local ok, err = parser:parse(data);
71                         if ok then return; end
72                         session:close("xml-not-well-formed");
73                 end
74                 
75                 return true;
76 end
77
78
79 local stream_xmlns_attr = {xmlns='urn:ietf:params:xml:ns:xmpp-streams'};
80 local function session_close(session, reason)
81         local log = session.log or log;
82         if session.conn then
83                 if reason then
84                         if type(reason) == "string" then -- assume stream error
85                                 log("info", "Disconnecting %s[%s], <stream:error> is: %s", session.host or "(unknown host)", session.type, reason);
86                                 session.sends2s(st.stanza("stream:error"):tag(reason, {xmlns = 'urn:ietf:params:xml:ns:xmpp-streams' }));
87                         elseif type(reason) == "table" then
88                                 if reason.condition then
89                                         local stanza = st.stanza("stream:error"):tag(reason.condition, stream_xmlns_attr):up();
90                                         if reason.text then
91                                                 stanza:tag("text", stream_xmlns_attr):text(reason.text):up();
92                                         end
93                                         if reason.extra then
94                                                 stanza:add_child(reason.extra);
95                                         end
96                                         log("info", "Disconnecting %s[%s], <stream:error> is: %s", session.host or "(unknown host)", session.type, tostring(stanza));
97                                         session.sends2s(stanza);
98                                 elseif reason.name then -- a stanza
99                                         log("info", "Disconnecting %s->%s[%s], <stream:error> is: %s", session.from_host or "(unknown host)", session.to_host or "(unknown host)", session.type, tostring(reason));
100                                         session.sends2s(reason);
101                                 end
102                         end
103                 end
104                 session.sends2s("</stream:stream>");
105                 session.conn.close();
106                 xmppserver.disconnect(session.conn, "stream error");
107         end
108 end
109
110
111 -- End of session methods --
112
113 function xmppserver.listener(conn, data)
114         local session = sessions[conn];
115         if not session then
116                 session = s2s_new_incoming(conn);
117                 sessions[conn] = session;
118
119                 -- Logging functions --
120
121                 
122                 local conn_name = "s2sin"..tostring(conn):match("[a-f0-9]+$");
123                 session.log = logger.init(conn_name);
124                 
125                 session.log("info", "Incoming s2s connection");
126                 
127                 session.reset_stream = session_reset_stream;
128                 session.close = session_close;
129                 
130                 session_reset_stream(session); -- Initialise, ready for use
131                 
132                 -- Debug version --
133 --              local function handleerr(err) print("Traceback:", err, debug.traceback()); end
134 --              session.stanza_dispatch = function (stanza) return select(2, xpcall(function () return core_process_stanza(session, stanza); end, handleerr));  end
135         end
136         if data then
137                 session.data(conn, data);
138         end
139 end
140         
141 function xmppserver.disconnect(conn, err)
142         local session = sessions[conn];
143         if session then
144                 if err and err ~= "closed" and session.srv_hosts then
145                         if s2s_attempt_connect(session, err) then
146                                 return; -- Session lives for now
147                         end
148                 end
149                 (session.log or log)("info", "s2s disconnected: %s->%s (%s)", tostring(session.from_host), tostring(session.to_host), tostring(err));
150                 s2s_destroy_session(session);
151                 sessions[conn]  = nil;
152                 session = nil;
153                 collectgarbage("collect");
154         end
155 end
156
157 function xmppserver.register_outgoing(conn, session)
158         session.direction = "outgoing";
159         sessions[conn] = session;
160         
161         session.reset_stream = session_reset_stream;    
162         session_reset_stream(session); -- Initialise, ready for use
163         
164         --local function handleerr(err) print("Traceback:", err, debug.traceback()); end
165         --session.stanza_dispatch = function (stanza) return select(2, xpcall(function () return core_process_stanza(session, stanza); end, handleerr));  end
166 end
167
168 connlisteners_register("xmppserver", xmppserver);
169
170
171 -- We need to perform some initialisation when a connection is created
172 -- We also need to perform that same initialisation at other points (SASL, TLS, ...)
173
174 -- ...and we need to handle data
175 -- ...and record all sessions associated with connections