0fb5223dbb47636ca90291bfa67c22d760b0ffd2
[prosody.git] / plugins / muc / muc.lib.lua
1 -- Prosody IM
2 -- Copyright (C) 2008-2009 Matthew Wild
3 -- Copyright (C) 2008-2009 Waqas Hussain
4 -- 
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
7 --
8
9 local datamanager = require "util.datamanager";
10 local datetime = require "util.datetime";
11
12 local jid_split = require "util.jid".split;
13 local jid_bare = require "util.jid".bare;
14 local jid_prep = require "util.jid".prep;
15 local st = require "util.stanza";
16 local log = require "util.logger".init("mod_muc");
17 local multitable_new = require "util.multitable".new;
18 local t_insert, t_remove = table.insert, table.remove;
19 local setmetatable = setmetatable;
20 local base64 = require "util.encodings".base64;
21 local md5 = require "util.hashes".md5;
22
23 local muc_domain = nil; --module:get_host();
24 local history_length = 20;
25
26 ------------
27 local function filter_xmlns_from_array(array, filters)
28         local count = 0;
29         for i=#array,1,-1 do
30                 local attr = array[i].attr;
31                 if filters[attr and attr.xmlns] then
32                         t_remove(array, i);
33                         count = count + 1;
34                 end
35         end
36         return count;
37 end
38 local function filter_xmlns_from_stanza(stanza, filters)
39         if filters then
40                 if filter_xmlns_from_array(stanza.tags, filters) ~= 0 then
41                         return stanza, filter_xmlns_from_array(stanza, filters);
42                 end
43         end
44         return stanza, 0;
45 end
46 local presence_filters = {["http://jabber.org/protocol/muc"]=true;["http://jabber.org/protocol/muc#user"]=true};
47 local function get_filtered_presence(stanza)
48         return filter_xmlns_from_stanza(st.clone(stanza):reset(), presence_filters);
49 end
50 local kickable_error_conditions = {
51         ["gone"] = true;
52         ["internal-server-error"] = true;
53         ["item-not-found"] = true;
54         ["jid-malformed"] = true;
55         ["recipient-unavailable"] = true;
56         ["redirect"] = true;
57         ["remote-server-not-found"] = true;
58         ["remote-server-timeout"] = true;
59         ["service-unavailable"] = true;
60         ["malformed error"] = true;
61 };
62 local function get_error_condition(stanza)
63         for _, tag in ipairs(stanza.tags) do
64                 if tag.name == "error" and (not(tag.attr.xmlns) or tag.attr.xmlns == "jabber:client") then
65                         for _, cond in ipairs(tag.tags) do
66                                 if cond.attr.xmlns == "urn:ietf:params:xml:ns:xmpp-stanzas" then
67                                         return cond.name;
68                                 end
69                         end
70                         return "malformed error";
71                 end
72         end
73         return "malformed error";
74 end
75 local function is_kickable_error(stanza)
76         local cond = get_error_condition(stanza);
77         return kickable_error_conditions[cond] and cond;
78 end
79 local function getUsingPath(stanza, path, getText)
80         local tag = stanza;
81         for _, name in ipairs(path) do
82                 if type(tag) ~= 'table' then return; end
83                 tag = tag:child_with_name(name);
84         end
85         if tag and getText then tag = table.concat(tag); end
86         return tag;
87 end
88 local function getTag(stanza, path) return getUsingPath(stanza, path); end
89 local function getText(stanza, path) return getUsingPath(stanza, path, true); end
90 -----------
91
92 --[[function get_room_disco_info(room, stanza)
93         return st.iq({type='result', id=stanza.attr.id, from=stanza.attr.to, to=stanza.attr.from}):query("http://jabber.org/protocol/disco#info")
94                 :tag("identity", {category='conference', type='text', name=room._data["name"]):up()
95                 :tag("feature", {var="http://jabber.org/protocol/muc"}); -- TODO cache disco reply
96 end
97 function get_room_disco_items(room, stanza)
98         return st.iq({type='result', id=stanza.attr.id, from=stanza.attr.to, to=stanza.attr.from}):query("http://jabber.org/protocol/disco#items");
99 end -- TODO allow non-private rooms]]
100
101 --
102
103 local room_mt = {};
104 room_mt.__index = room_mt;
105
106 function room_mt:get_default_role(affiliation)
107         if affiliation == "owner" or affiliation == "admin" then
108                 return "moderator";
109         elseif affiliation == "member" or not affiliation then
110                 return "participant";
111         end
112 end
113
114 function room_mt:broadcast_presence(stanza, sid, code, nick)
115         stanza = get_filtered_presence(stanza);
116         local occupant = self._occupants[stanza.attr.from];
117         stanza:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
118                 :tag("item", {affiliation=occupant.affiliation or "none", role=occupant.role or "none", nick=nick}):up();
119         if code then
120                 stanza:tag("status", {code=code}):up();
121         end
122         self:broadcast_except_nick(stanza, stanza.attr.from);
123         local me = self._occupants[stanza.attr.from];
124         if me then
125                 stanza:tag("status", {code='110'});
126                 stanza.attr.to = sid;
127                 self:_route_stanza(stanza);
128         end
129 end
130 function room_mt:broadcast_message(stanza, historic)
131         local to = stanza.attr.to;
132         for occupant, o_data in pairs(self._occupants) do
133                 for jid in pairs(o_data.sessions) do
134                         stanza.attr.to = jid;
135                         self:_route_stanza(stanza);
136                 end
137         end
138         stanza.attr.to = to;
139         if historic then -- add to history
140                 local history = self._data['history'];
141                 if not history then history = {}; self._data['history'] = history; end
142                 stanza = st.clone(stanza);
143                 stanza:tag("delay", {xmlns = "urn:xmpp:delay", from = muc_domain, stamp = datetime.datetime()}):up(); -- XEP-0203
144                 stanza:tag("x", {xmlns = "jabber:x:delay", from = muc_domain, stamp = datetime.legacy()}):up(); -- XEP-0091 (deprecated)
145                 t_insert(history, st.preserialize(stanza));
146                 while #history > history_length do t_remove(history, 1) end
147         end
148 end
149 function room_mt:broadcast_except_nick(stanza, nick)
150         for rnick, occupant in pairs(self._occupants) do
151                 if rnick ~= nick then
152                         for jid in pairs(occupant.sessions) do
153                                 stanza.attr.to = jid;
154                                 self:_route_stanza(stanza);
155                         end
156                 end
157         end
158 end
159
160 function room_mt:send_occupant_list(to)
161         local current_nick = self._jid_nick[to];
162         for occupant, o_data in pairs(self._occupants) do
163                 if occupant ~= current_nick then
164                         local pres = get_filtered_presence(o_data.sessions[o_data.jid]);
165                         pres.attr.to, pres.attr.from = to, occupant;
166                         pres:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
167                                 :tag("item", {affiliation=o_data.affiliation or "none", role=o_data.role or "none"}):up();
168                         self:_route_stanza(pres);
169                 end
170         end
171 end
172 function room_mt:send_history(to)
173         local history = self._data['history']; -- send discussion history
174         if history then
175                 for _, msg in ipairs(history) do
176                         msg = st.deserialize(msg);
177                         msg.attr.to=to;
178                         self:_route_stanza(msg);
179                 end
180         end
181         if self._data['subject'] then
182                 self:_route_stanza(st.message({type='groupchat', from=self.jid, to=to}):tag("subject"):text(self._data['subject']));
183         end
184 end
185
186 local function room_get_disco_info(self, stanza)
187         return st.reply(stanza):query("http://jabber.org/protocol/disco#info")
188                 :tag("identity", {category="conference", type="text"}):up()
189                 :tag("feature", {var="http://jabber.org/protocol/muc"});
190 end
191 local function room_get_disco_items(self, stanza)
192         local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#items");
193         for room_jid in pairs(self._occupants) do
194                 reply:tag("item", {jid = room_jid, name = room_jid:match("/(.*)")}):up();
195         end
196         return reply;
197 end
198 function room_mt:set_subject(current_nick, subject)
199         -- TODO check nick's authority
200         if subject == "" then subject = nil; end
201         self._data['subject'] = subject;
202         if self.save then self:save(); end
203         local msg = st.message({type='groupchat', from=current_nick})
204                 :tag('subject'):text(subject):up();
205         self:broadcast_message(msg, false);
206         return true;
207 end
208
209 function room_mt:handle_to_occupant(origin, stanza) -- PM, vCards, etc
210         local from, to = stanza.attr.from, stanza.attr.to;
211         local room = jid_bare(to);
212         local current_nick = self._jid_nick[from];
213         local type = stanza.attr.type;
214         log("debug", "room: %s, current_nick: %s, stanza: %s", room or "nil", current_nick or "nil", stanza:top_tag());
215         if (select(2, jid_split(from)) == muc_domain) then error("Presence from the MUC itself!!!"); end
216         if stanza.name == "presence" then
217                 local pr = get_filtered_presence(stanza);
218                 pr.attr.from = current_nick;
219                 if type == "error" then -- error, kick em out!
220                         if current_nick then
221                                 log("debug", "kicking %s from %s", current_nick, room);
222                                 self:handle_to_occupant(origin, st.presence({type='unavailable', from=from, to=to})
223                                         :tag('status'):text('Kicked: '..get_error_condition(stanza))); -- send unavailable
224                         end
225                 elseif type == "unavailable" then -- unavailable
226                         if current_nick then
227                                 log("debug", "%s leaving %s", current_nick, room);
228                                 local occupant = self._occupants[current_nick];
229                                 local new_jid = next(occupant.sessions);
230                                 if new_jid == from then new_jid = next(occupant.sessions, new_jid); end
231                                 if new_jid then
232                                         local jid = occupant.jid;
233                                         occupant.jid = new_jid;
234                                         occupant.sessions[from] = nil;
235                                         pr.attr.to = from;
236                                         pr:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
237                                                 :tag("item", {affiliation=occupant.affiliation or "none", role='none'}):up()
238                                                 :tag("status", {code='110'});
239                                         self:_route_stanza(pr);
240                                         if jid ~= new_jid then
241                                                 pr = st.clone(occupant.sessions[new_jid])
242                                                         :tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
243                                                         :tag("item", {affiliation=occupant.affiliation or "none", role=occupant.role or "none"});
244                                                 pr.attr.from = current_nick;
245                                                 self:broadcast_except_nick(pr, current_nick);
246                                         end
247                                 else
248                                         occupant.role = 'none';
249                                         self:broadcast_presence(pr, from);
250                                         self._occupants[current_nick] = nil;
251                                 end
252                                 self._jid_nick[from] = nil;
253                         end
254                 elseif not type then -- available
255                         if current_nick then
256                                 --if #pr == #stanza or current_nick ~= to then -- commented because google keeps resending directed presence
257                                         if current_nick == to then -- simple presence
258                                                 log("debug", "%s broadcasted presence", current_nick);
259                                                 self._occupants[current_nick].sessions[from] = pr;
260                                                 self:broadcast_presence(pr, from);
261                                         else -- change nick
262                                                 local occupant = self._occupants[current_nick];
263                                                 local is_multisession = next(occupant.sessions, next(occupant.sessions));
264                                                 if self._occupants[to] or is_multisession then
265                                                         log("debug", "%s couldn't change nick", current_nick);
266                                                         local reply = st.error_reply(stanza, "cancel", "conflict"):up();
267                                                         reply.tags[1].attr.code = "409";
268                                                         origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
269                                                 else
270                                                         local data = self._occupants[current_nick];
271                                                         local to_nick = select(3, jid_split(to));
272                                                         if to_nick then
273                                                                 log("debug", "%s (%s) changing nick to %s", current_nick, data.jid, to);
274                                                                 local p = st.presence({type='unavailable', from=current_nick});
275                                                                 self:broadcast_presence(p, from, '303', to_nick);
276                                                                 self._occupants[current_nick] = nil;
277                                                                 self._occupants[to] = data;
278                                                                 self._jid_nick[from] = to;
279                                                                 pr.attr.from = to;
280                                                                 self._occupants[to].sessions[from] = pr;
281                                                                 self:broadcast_presence(pr, from);
282                                                         else
283                                                                 --TODO malformed-jid
284                                                         end
285                                                 end
286                                         end
287                                 --else -- possible rejoin
288                                 --      log("debug", "%s had connection replaced", current_nick);
289                                 --      self:handle_to_occupant(origin, st.presence({type='unavailable', from=from, to=to})
290                                 --              :tag('status'):text('Replaced by new connection'):up()); -- send unavailable
291                                 --      self:handle_to_occupant(origin, stanza); -- resend available
292                                 --end
293                         else -- enter room
294                                 local new_nick = to;
295                                 local is_merge;
296                                 if self._occupants[to] then
297                                         if jid_bare(from) ~= jid_bare(self._occupants[to].jid) then
298                                                 new_nick = nil;
299                                         end
300                                         is_merge = true;
301                                 end
302                                 if not new_nick then
303                                         log("debug", "%s couldn't join due to nick conflict: %s", from, to);
304                                         local reply = st.error_reply(stanza, "cancel", "conflict"):up();
305                                         reply.tags[1].attr.code = "409";
306                                         origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
307                                 else
308                                         log("debug", "%s joining as %s", from, to);
309                                         if not next(self._affiliations) then -- new room, no owners
310                                                 self._affiliations[jid_bare(from)] = "owner";
311                                         end
312                                         local affiliation = self:get_affiliation(from);
313                                         local role = self:get_default_role(affiliation)
314                                         if role then -- new occupant
315                                                 if not is_merge then
316                                                         self._occupants[to] = {affiliation=affiliation, role=role, jid=from, sessions={[from]=get_filtered_presence(stanza)}};
317                                                 else
318                                                         self._occupants[to].sessions[from] = get_filtered_presence(stanza);
319                                                 end
320                                                 self._jid_nick[from] = to;
321                                                 self:send_occupant_list(from);
322                                                 pr.attr.from = to;
323                                                 if not is_merge then
324                                                         self:broadcast_presence(pr, from);
325                                                 else
326                                                         pr.attr.to = from;
327                                                         self:_route_stanza(pr:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
328                                                                 :tag("item", {affiliation=affiliation or "none", role=role or "none"}):up()
329                                                                 :tag("status", {code='110'}));
330                                                 end
331                                                 self:send_history(from);
332                                         else -- banned
333                                                 local reply = st.error_reply(stanza, "auth", "forbidden"):up();
334                                                 reply.tags[1].attr.code = "403";
335                                                 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
336                                         end
337                                 end
338                         end
339                 elseif type ~= 'result' then -- bad type
340                         if type ~= 'visible' and type ~= 'invisible' then -- COMPAT ejabberd can broadcast or forward XEP-0018 presences
341                                 origin.send(st.error_reply(stanza, "modify", "bad-request")); -- FIXME correct error?
342                         end
343                 end
344         elseif not current_nick then -- not in room
345                 if type == "error" or type == "result" then
346                         local id = stanza.name == "iq" and stanza.attr.id and base64.decode(stanza.attr.id);
347                         local _nick, _id, _hash = (id or ""):match("^(.+)%z(.*)%z(.+)$");
348                         local occupant = self._occupants[stanza.attr.to];
349                         if occupant and _nick and self._jid_nick[_nick] and _id and _hash then
350                                 local id, _to = stanza.attr.id;
351                                 for jid in pairs(occupant.sessions) do
352                                         if md5(jid) == _hash then
353                                                 _to = jid;
354                                                 break;
355                                         end
356                                 end
357                                 if _to then
358                                         stanza.attr.to, stanza.attr.from, stanza.attr.id = _to, self._jid_nick[_nick], _id;
359                                         self:_route_stanza(stanza);
360                                         stanza.attr.to, stanza.attr.from, stanza.attr.id = to, from, id;
361                                 end
362                         end
363                 else
364                         origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
365                 end
366         elseif stanza.name == "message" and type == "groupchat" then -- groupchat messages not allowed in PM
367                 origin.send(st.error_reply(stanza, "modify", "bad-request"));
368         elseif current_nick and stanza.name == "message" and type == "error" and is_kickable_error(stanza) then
369                 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
370                 self:handle_to_occupant(origin, st.presence({type='unavailable', from=stanza.attr.from, to=stanza.attr.to})
371                         :tag('status'):text('Kicked: '..get_error_condition(stanza))); -- send unavailable
372         else -- private stanza
373                 local o_data = self._occupants[to];
374                 if o_data then
375                         log("debug", "%s sent private stanza to %s (%s)", from, to, o_data.jid);
376                         local jid = o_data.jid;
377                         local bare = jid_bare(jid);
378                         stanza.attr.to, stanza.attr.from = jid, current_nick;
379                         local id = stanza.attr.id;
380                         if stanza.name=='iq' and type=='get' and stanza.tags[1].attr.xmlns == 'vcard-temp' and bare ~= jid then
381                                 stanza.attr.to = bare;
382                                 stanza.attr.id = base64.encode(jid.."\0"..id.."\0"..md5(from));
383                         end
384                         self:_route_stanza(stanza);
385                         stanza.attr.to, stanza.attr.from, stanza.attr.id = to, from, id;
386                 elseif type ~= "error" and type ~= "result" then -- recipient not in room
387                         origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
388                 end
389         end
390 end
391
392 function room_mt:handle_form(origin, stanza)
393         if self:get_affiliation(stanza.attr.from) ~= "owner" then origin.send(st.error_reply(stanza, "auth", "forbidden")); return; end
394         if stanza.attr.type == "get" then
395                 local title = "Configuration for "..self.jid;
396                 origin.send(st.reply(stanza):query("http://jabber.org/protocol/muc#owner")
397                         :tag("x", {xmlns='jabber:x:data', type='form'})
398                                 :tag("title"):text(title):up()
399                                 :tag("instructions"):text(title):up()
400                                 :tag("field", {type='hidden', var='FORM_TYPE'}):tag("value"):text("http://jabber.org/protocol/muc#roomconfig"):up():up()
401                                 :tag("field", {type='boolean', label='Make Room Persistent?', var='muc#roomconfig_persistentroom'})
402                                         :tag("value"):text(self._data.persistent and "1" or "0"):up()
403                                 :up()
404                                 :tag("field", {type='boolean', label='Make Room Publicly Searchable?', var='muc#roomconfig_publicroom'})
405                                         :tag("value"):text(self._data.hidden and "0" or "1"):up()
406                                 :up()
407                 );
408         elseif stanza.attr.type == "set" then
409                 local query = stanza.tags[1];
410                 local form;
411                 for _, tag in ipairs(query.tags) do if tag.name == "x" and tag.attr.xmlns == "jabber:x:data" then form = tag; break; end end
412                 if not form then origin.send(st.error_reply(stanza, "cancel", "service-unavailable")); return; end
413                 if form.attr.type == "cancel" then origin.send(st.reply(stanza)); return; end
414                 if form.attr.type ~= "submit" then origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
415                 local fields = {};
416                 for _, field in pairs(form.tags) do
417                         if field.name == "field" and field.attr.var and field.tags[1].name == "value" and #field.tags[1].tags == 0 then
418                                 fields[field.attr.var] = field.tags[1][1] or "";
419                         end
420                 end
421                 if fields.FORM_TYPE ~= "http://jabber.org/protocol/muc#roomconfig" then origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
422
423                 local persistent = fields['muc#roomconfig_persistentroom'];
424                 if persistent == "0" or persistent == "false" then persistent = nil; elseif persistent == "1" or persistent == "true" then persistent = true;
425                 else origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
426                 self._data.persistent = persistent;
427                 module:log("debug", "persistent=%s", tostring(persistent));
428
429                 local public = fields['muc#roomconfig_publicroom'];
430                 if public == "0" or public == "false" then public = nil; elseif public == "1" or public == "true" then public = true;
431                 else origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
432                 self._data.hidden = not public and true or nil;
433
434                 if self.save then self:save(true); end
435                 origin.send(st.reply(stanza));
436         end
437 end
438
439 function room_mt:handle_to_room(origin, stanza) -- presence changes and groupchat messages, along with disco/etc
440         local type = stanza.attr.type;
441         local xmlns = stanza.tags[1] and stanza.tags[1].attr.xmlns;
442         if stanza.name == "iq" then
443                 if xmlns == "http://jabber.org/protocol/disco#info" and type == "get" then
444                         origin.send(room_get_disco_info(self, stanza));
445                 elseif xmlns == "http://jabber.org/protocol/disco#items" and type == "get" then
446                         origin.send(room_get_disco_items(self, stanza));
447                 elseif xmlns == "http://jabber.org/protocol/muc#admin" then
448                         local actor = stanza.attr.from;
449                         local affiliation = self:get_affiliation(actor);
450                         local current_nick = self._jid_nick[actor];
451                         local role = current_nick and self._occupants[current_nick].role or self:get_default_role(affiliation);
452                         local item = stanza.tags[1].tags[1];
453                         if item and item.name == "item" then
454                                 if type == "set" then
455                                         local callback = function() origin.send(st.reply(stanza)); end
456                                         if item.attr.jid then -- Validate provided JID
457                                                 item.attr.jid = jid_prep(item.attr.jid);
458                                                 if not item.attr.jid then
459                                                         origin.send(st.error_reply(stanza, "modify", "jid-malformed"));
460                                                         return;
461                                                 end
462                                         end
463                                         if not item.attr.jid and item.attr.nick then -- COMPAT Workaround for Miranda sending 'nick' instead of 'jid' when changing affiliation
464                                                 local occupant = self._occupants[self.jid.."/"..item.attr.nick];
465                                                 if occupant then item.attr.jid = occupant.jid; end
466                                         end
467                                         local reason = item.tags[1] and item.tags[1].name == "reason" and #item.tags[1] == 1 and item.tags[1][1];
468                                         if item.attr.affiliation and item.attr.jid and not item.attr.role then
469                                                 local success, errtype, err = self:set_affiliation(actor, item.attr.jid, item.attr.affiliation, callback, reason);
470                                                 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
471                                         elseif item.attr.role and item.attr.nick and not item.attr.affiliation then
472                                                 local success, errtype, err = self:set_role(actor, self.jid.."/"..item.attr.nick, item.attr.role, callback, reason);
473                                                 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
474                                         else
475                                                 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
476                                         end
477                                 elseif type == "get" then
478                                         local _aff = item.attr.affiliation;
479                                         local _rol = item.attr.role;
480                                         if _aff and not _rol then
481                                                 if affiliation == "owner" or (affiliation == "admin" and _aff ~= "owner" and _aff ~= "admin") then
482                                                         local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
483                                                         for jid, affiliation in pairs(self._affiliations) do
484                                                                 if affiliation == _aff then
485                                                                         reply:tag("item", {affiliation = _aff, jid = jid}):up();
486                                                                 end
487                                                         end
488                                                         origin.send(reply);
489                                                 else
490                                                         origin.send(st.error_reply(stanza, "auth", "forbidden"));
491                                                 end
492                                         elseif _rol and not _aff then
493                                                 if role == "moderator" then
494                                                         -- TODO allow admins and owners not in room? Provide read-only access to everyone who can see the participants anyway?
495                                                         if _rol == "none" then _rol = nil; end
496                                                         local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
497                                                         for nick, occupant in pairs(self._occupants) do
498                                                                 if occupant.role == _rol then
499                                                                         reply:tag("item", {nick = nick, role = _rol or "none", affiliation = occupant.affiliation or "none", jid = occupant.jid}):up();
500                                                                 end
501                                                         end
502                                                         origin.send(reply);
503                                                 else
504                                                         origin.send(st.error_reply(stanza, "auth", "forbidden"));
505                                                 end
506                                         else
507                                                 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
508                                         end
509                                 end
510                         elseif type == "set" or type == "get" then
511                                 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
512                         end
513                 elseif xmlns == "http://jabber.org/protocol/muc#owner" and (type == "get" or type == "set") and stanza.tags[1].name == "query" then
514                         self:handle_form(origin, stanza);
515                 elseif type == "set" or type == "get" then
516                         origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
517                 end
518         elseif stanza.name == "message" and type == "groupchat" then
519                 local from, to = stanza.attr.from, stanza.attr.to;
520                 local room = jid_bare(to);
521                 local current_nick = self._jid_nick[from];
522                 if not current_nick then -- not in room
523                         origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
524                 else
525                         local from = stanza.attr.from;
526                         stanza.attr.from = current_nick;
527                         local subject = getText(stanza, {"subject"});
528                         if subject then
529                                 self:set_subject(current_nick, subject); -- TODO use broadcast_message_stanza
530                         else
531                                 self:broadcast_message(stanza, true);
532                         end
533                         stanza.attr.from = from;
534                 end
535         elseif stanza.name == "message" and type == "error" and is_kickable_error(stanza) then
536                 local current_nick = self._jid_nick[stanza.attr.from];
537                 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
538                 self:handle_to_occupant(origin, st.presence({type='unavailable', from=stanza.attr.from, to=stanza.attr.to})
539                         :tag('status'):text('Kicked: '..get_error_condition(stanza))); -- send unavailable
540         elseif stanza.name == "presence" then -- hack - some buggy clients send presence updates to the room rather than their nick
541                 local to = stanza.attr.to;
542                 local current_nick = self._jid_nick[stanza.attr.from];
543                 if current_nick then
544                         stanza.attr.to = current_nick;
545                         self:handle_to_occupant(origin, stanza);
546                         stanza.attr.to = to;
547                 elseif type ~= "error" and type ~= "result" then
548                         origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
549                 end
550         elseif stanza.name == "message" and not stanza.attr.type and #stanza.tags == 1 and self._jid_nick[stanza.attr.from]
551                 and stanza.tags[1].name == "x" and stanza.tags[1].attr.xmlns == "http://jabber.org/protocol/muc#user" then
552                 local x = stanza.tags[1];
553                 local payload = (#x.tags == 1 and x.tags[1]);
554                 if payload and payload.name == "invite" and payload.attr.to then
555                         local _from, _to = stanza.attr.from, stanza.attr.to;
556                         local _invitee = jid_prep(payload.attr.to);
557                         if _invitee then
558                                 local _reason = payload.tags[1] and payload.tags[1].name == 'reason' and #payload.tags[1].tags == 0 and payload.tags[1][1];
559                                 local invite = st.message({from = _to, to = _invitee, id = stanza.attr.id})
560                                         :tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
561                                                 :tag('invite', {from=_from})
562                                                         :tag('reason'):text(_reason or ""):up()
563                                                 :up()
564                                         :up()
565                                         :tag('x', {xmlns="jabber:x:conference", jid=_to}) -- COMPAT: Some older clients expect this
566                                                 :text(_reason or "")
567                                         :up()
568                                         :tag('body') -- Add a plain message for clients which don't support invites
569                                                 :text(_from..' invited you to the room '.._to..(_reason and (' ('.._reason..')') or ""))
570                                         :up();
571                                 self:_route_stanza(invite);
572                         else
573                                 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
574                         end
575                 else
576                         origin.send(st.error_reply(stanza, "cancel", "bad-request"));
577                 end
578         else
579                 if type == "error" or type == "result" then return; end
580                 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
581         end
582 end
583
584 function room_mt:handle_stanza(origin, stanza)
585         local to_node, to_host, to_resource = jid_split(stanza.attr.to);
586         if to_resource then
587                 self:handle_to_occupant(origin, stanza);
588         else
589                 self:handle_to_room(origin, stanza);
590         end
591 end
592
593 function room_mt:route_stanza(stanza) end -- Replace with a routing function, e.g., function(room, stanza) core_route_stanza(origin, stanza); end
594
595 function room_mt:get_affiliation(jid)
596         local node, host, resource = jid_split(jid);
597         local bare = node and node.."@"..host or host;
598         local result = self._affiliations[bare]; -- Affiliations are granted, revoked, and maintained based on the user's bare JID.
599         if not result and self._affiliations[host] == "outcast" then result = "outcast"; end -- host banned
600         return result;
601 end
602 function room_mt:set_affiliation(actor, jid, affiliation, callback, reason)
603         jid = jid_bare(jid);
604         if affiliation == "none" then affiliation = nil; end
605         if affiliation and affiliation ~= "outcast" and affiliation ~= "owner" and affiliation ~= "admin" and affiliation ~= "member" then
606                 return nil, "modify", "not-acceptable";
607         end
608         if self:get_affiliation(actor) ~= "owner" then return nil, "cancel", "not-allowed"; end
609         if jid_bare(actor) == jid then return nil, "cancel", "not-allowed"; end
610         self._affiliations[jid] = affiliation;
611         local role = self:get_default_role(affiliation);
612         local p = st.presence()
613                 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
614                         :tag("item", {affiliation=affiliation or "none", role=role or "none"})
615                                 :tag("reason"):text(reason or ""):up()
616                         :up();
617         local x = p.tags[1];
618         local item = x.tags[1];
619         if not role then -- getting kicked
620                 p.attr.type = "unavailable";
621                 if affiliation == "outcast" then
622                         x:tag("status", {code="301"}):up(); -- banned
623                 else
624                         x:tag("status", {code="321"}):up(); -- affiliation change
625                 end
626         end
627         local modified_nicks = {};
628         for nick, occupant in pairs(self._occupants) do
629                 if jid_bare(occupant.jid) == jid then
630                         if not role then -- getting kicked
631                                 self._occupants[nick] = nil;
632                         else
633                                 t_insert(modified_nicks, nick);
634                                 occupant.affiliation, occupant.role = affiliation, role;
635                         end
636                         p.attr.from = nick;
637                         for jid in pairs(occupant.sessions) do -- remove for all sessions of the nick
638                                 if not role then self._jid_nick[jid] = nil; end
639                                 p.attr.to = jid;
640                                 self:_route_stanza(p);
641                         end
642                 end
643         end
644         if self.save then self:save(); end
645         if callback then callback(); end
646         for _, nick in ipairs(modified_nicks) do
647                 p.attr.from = nick;
648                 self:broadcast_except_nick(p, nick);
649         end
650         return true;
651 end
652
653 function room_mt:get_role(nick)
654         local session = self._occupants[nick];
655         return session and session.role or nil;
656 end
657 function room_mt:set_role(actor, nick, role, callback, reason)
658         if role == "none" then role = nil; end
659         if role and role ~= "moderator" and role ~= "participant" and role ~= "visitor" then return nil, "modify", "not-acceptable"; end
660         if self:get_affiliation(actor) ~= "owner" then return nil, "cancel", "not-allowed"; end
661         local occupant = self._occupants[nick];
662         if not occupant then return nil, "modify", "not-acceptable"; end
663         if occupant.affiliation == "owner" or occupant.affiliation == "admin" then return nil, "cancel", "not-allowed"; end
664         local p = st.presence({from = nick})
665                 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
666                         :tag("item", {affiliation=occupant.affiliation or "none", nick=nick, role=role or "none"})
667                                 :tag("reason"):text(reason or ""):up()
668                         :up();
669         if not role then -- kick
670                 p.attr.type = "unavailable";
671                 self._occupants[nick] = nil;
672                 for jid in pairs(occupant.sessions) do -- remove for all sessions of the nick
673                         self._jid_nick[jid] = nil;
674                 end
675                 p:tag("status", {code = "307"}):up();
676         else
677                 occupant.role = role;
678         end
679         for jid in pairs(occupant.sessions) do -- send to all sessions of the nick
680                 p.attr.to = jid;
681                 self:_route_stanza(p);
682         end
683         if callback then callback(); end
684         self:broadcast_except_nick(p, nick);
685         return true;
686 end
687
688 function room_mt:_route_stanza(stanza)
689         local muc_child;
690         local to_occupant = self._occupants[self._jid_nick[stanza.attr.to]];
691         local from_occupant = self._occupants[stanza.attr.from];
692         if stanza.name == "presence" then
693                 if to_occupant and from_occupant then
694                         if to_occupant.role == "moderator" or jid_bare(to_occupant.jid) == jid_bare(from_occupant.jid) then
695                                 for i=#stanza.tags,1,-1 do
696                                         local tag = stanza.tags[i];
697                                         if tag.name == "x" and tag.attr.xmlns == "http://jabber.org/protocol/muc#user" then
698                                                 muc_child = tag;
699                                                 break;
700                                         end
701                                 end
702                         end
703                 end
704         end
705         if muc_child then
706                 for _, item in pairs(muc_child.tags) do
707                         if item.name == "item" then
708                                 if from_occupant == to_occupant then
709                                         item.attr.jid = stanza.attr.to;
710                                 else
711                                         item.attr.jid = from_occupant.jid;
712                                 end
713                         end
714                 end
715         end
716         self:route_stanza(stanza);
717         if muc_child then
718                 for _, item in pairs(muc_child.tags) do
719                         if item.name == "item" then
720                                 item.attr.jid = nil;
721                         end
722                 end
723         end
724 end
725
726 local _M = {}; -- module "muc"
727
728 function _M.new_room(jid)
729         return setmetatable({
730                 jid = jid;
731                 _jid_nick = {};
732                 _occupants = {};
733                 _data = {};
734                 _affiliations = {};
735         }, room_mt);
736 end
737
738 return _M;