e679f9fe6bb9b3b7ecbd5e527103e5402f944bd2
[prosody.git] / plugins / muc / muc.lib.lua
1 -- Prosody IM
2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 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 select = select;
10 local pairs, ipairs = pairs, ipairs;
11
12 local datamanager = require "util.datamanager";
13 local datetime = require "util.datetime";
14
15 local jid_split = require "util.jid".split;
16 local jid_bare = require "util.jid".bare;
17 local jid_prep = require "util.jid".prep;
18 local st = require "util.stanza";
19 local log = require "util.logger".init("mod_muc");
20 local multitable_new = require "util.multitable".new;
21 local t_insert, t_remove = table.insert, table.remove;
22 local setmetatable = setmetatable;
23 local base64 = require "util.encodings".base64;
24 local md5 = require "util.hashes".md5;
25
26 local muc_domain = nil; --module:get_host();
27 local default_history_length = 20;
28
29 ------------
30 local function filter_xmlns_from_array(array, filters)
31         local count = 0;
32         for i=#array,1,-1 do
33                 local attr = array[i].attr;
34                 if filters[attr and attr.xmlns] then
35                         t_remove(array, i);
36                         count = count + 1;
37                 end
38         end
39         return count;
40 end
41 local function filter_xmlns_from_stanza(stanza, filters)
42         if filters then
43                 if filter_xmlns_from_array(stanza.tags, filters) ~= 0 then
44                         return stanza, filter_xmlns_from_array(stanza, filters);
45                 end
46         end
47         return stanza, 0;
48 end
49 local presence_filters = {["http://jabber.org/protocol/muc"]=true;["http://jabber.org/protocol/muc#user"]=true};
50 local function get_filtered_presence(stanza)
51         return filter_xmlns_from_stanza(st.clone(stanza):reset(), presence_filters);
52 end
53 local kickable_error_conditions = {
54         ["gone"] = true;
55         ["internal-server-error"] = true;
56         ["item-not-found"] = true;
57         ["jid-malformed"] = true;
58         ["recipient-unavailable"] = true;
59         ["redirect"] = true;
60         ["remote-server-not-found"] = true;
61         ["remote-server-timeout"] = true;
62         ["service-unavailable"] = true;
63         ["malformed error"] = true;
64 };
65
66 local function get_error_condition(stanza)
67         local _, condition = stanza:get_error();
68         return condition or "malformed error";
69 end
70
71 local function is_kickable_error(stanza)
72         local cond = get_error_condition(stanza);
73         return kickable_error_conditions[cond] and cond;
74 end
75 local function getUsingPath(stanza, path, getText)
76         local tag = stanza;
77         for _, name in ipairs(path) do
78                 if type(tag) ~= 'table' then return; end
79                 tag = tag:child_with_name(name);
80         end
81         if tag and getText then tag = table.concat(tag); end
82         return tag;
83 end
84 local function getTag(stanza, path) return getUsingPath(stanza, path); end
85 local function getText(stanza, path) return getUsingPath(stanza, path, true); end
86 -----------
87
88 local room_mt = {};
89 room_mt.__index = room_mt;
90
91 function room_mt:get_default_role(affiliation)
92         if affiliation == "owner" or affiliation == "admin" then
93                 return "moderator";
94         elseif affiliation == "member" then
95                 return "participant";
96         elseif not affiliation then
97                 if not self:is_members_only() then
98                         return self:is_moderated() and "visitor" or "participant";
99                 end
100         end
101 end
102
103 function room_mt:broadcast_presence(stanza, sid, code, nick)
104         stanza = get_filtered_presence(stanza);
105         local occupant = self._occupants[stanza.attr.from];
106         stanza:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
107                 :tag("item", {affiliation=occupant.affiliation or "none", role=occupant.role or "none", nick=nick}):up();
108         if code then
109                 stanza:tag("status", {code=code}):up();
110         end
111         self:broadcast_except_nick(stanza, stanza.attr.from);
112         local me = self._occupants[stanza.attr.from];
113         if me then
114                 stanza:tag("status", {code='110'});
115                 stanza.attr.to = sid;
116                 self:_route_stanza(stanza);
117         end
118 end
119 function room_mt:broadcast_message(stanza, historic)
120         local to = stanza.attr.to;
121         for occupant, o_data in pairs(self._occupants) do
122                 for jid in pairs(o_data.sessions) do
123                         stanza.attr.to = jid;
124                         self:_route_stanza(stanza);
125                 end
126         end
127         stanza.attr.to = to;
128         if historic then -- add to history
129                 local history = self._data['history'];
130                 if not history then history = {}; self._data['history'] = history; end
131                 stanza = st.clone(stanza);
132                 stanza.attr.to = "";
133                 local stamp = datetime.datetime();
134                 local chars = #tostring(stanza);
135                 stanza:tag("delay", {xmlns = "urn:xmpp:delay", from = muc_domain, stamp = stamp}):up(); -- XEP-0203
136                 stanza:tag("x", {xmlns = "jabber:x:delay", from = muc_domain, stamp = datetime.legacy()}):up(); -- XEP-0091 (deprecated)
137                 local entry = { stanza = stanza, stamp = stamp };
138                 t_insert(history, entry);
139                 while #history > (self._data.history_length or default_history_length) do t_remove(history, 1) end
140         end
141 end
142 function room_mt:broadcast_except_nick(stanza, nick)
143         for rnick, occupant in pairs(self._occupants) do
144                 if rnick ~= nick then
145                         for jid in pairs(occupant.sessions) do
146                                 stanza.attr.to = jid;
147                                 self:_route_stanza(stanza);
148                         end
149                 end
150         end
151 end
152
153 function room_mt:send_occupant_list(to)
154         local current_nick = self._jid_nick[to];
155         for occupant, o_data in pairs(self._occupants) do
156                 if occupant ~= current_nick then
157                         local pres = get_filtered_presence(o_data.sessions[o_data.jid]);
158                         pres.attr.to, pres.attr.from = to, occupant;
159                         pres:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
160                                 :tag("item", {affiliation=o_data.affiliation or "none", role=o_data.role or "none"}):up();
161                         self:_route_stanza(pres);
162                 end
163         end
164 end
165 function room_mt:send_history(to, stanza)
166         local history = self._data['history']; -- send discussion history
167         if history then
168                 local x_tag = stanza and stanza:get_child("x", "http://jabber.org/protocol/muc");
169                 local history_tag = x_tag and x_tag:get_child("history", "http://jabber.org/protocol/muc");
170                 
171                 local maxchars = history_tag and tonumber(history_tag.attr.maxchars);
172                 if maxchars then maxchars = math.floor(maxchars); end
173                 
174                 local maxstanzas = math.floor(history_tag and tonumber(history_tag.attr.maxstanzas) or #history);
175                 if not history_tag then maxstanzas = 20; end
176
177                 local seconds = history_tag and tonumber(history_tag.attr.seconds);
178                 if seconds then seconds = datetime.datetime(os.time() - math.floor(seconds)); end
179
180                 local since = history_tag and history_tag.attr.since;
181                 if since and not since:match("^%d%d%d%d%-%d%d%-%d%dT%d%d:%d%d:%d%dZ$") then since = nil; end -- FIXME timezone support
182                 if seconds and (not since or since < seconds) then since = seconds; end
183
184                 local n = 0;
185                 local charcount = 0;
186                 local stanzacount = 0;
187                 
188                 for i=#history,1,-1 do
189                         local entry = history[i];
190                         if maxchars then
191                                 if not entry.chars then
192                                         entry.stanza.attr.to = "";
193                                         entry.chars = #tostring(entry.stanza);
194                                 end
195                                 charcount = charcount + entry.chars + #to;
196                                 if charcount > maxchars then break; end
197                         end
198                         if since and since > entry.stamp then break; end
199                         if n + 1 > maxstanzas then break; end
200                         n = n + 1;
201                 end
202                 for i=#history-n+1,#history do
203                         local msg = history[i].stanza;
204                         msg.attr.to = to;
205                         self:_route_stanza(msg);
206                 end
207         end
208         if self._data['subject'] then
209                 self:_route_stanza(st.message({type='groupchat', from=self.jid, to=to}):tag("subject"):text(self._data['subject']));
210         end
211 end
212
213 function room_mt:get_disco_info(stanza)
214         return st.reply(stanza):query("http://jabber.org/protocol/disco#info")
215                 :tag("identity", {category="conference", type="text"}):up()
216                 :tag("feature", {var="http://jabber.org/protocol/muc"}):up()
217                 :tag("feature", {var=self:get_password() and "muc_passwordprotected" or "muc_unsecured"}):up()
218                 :tag("feature", {var=self:is_moderated() and "muc_moderated" or "muc_unmoderated"}):up()
219                 :tag("feature", {var=self:is_members_only() and "muc_membersonly" or "muc_open"}):up()
220                 :tag("feature", {var=self:is_persistent() and "muc_persistent" or "muc_temporary"}):up()
221                 :tag("feature", {var=self:is_hidden() and "muc_hidden" or "muc_public"}):up()
222                 :tag("feature", {var=self._data.whois ~= "anyone" and "muc_semianonymous" or "muc_nonanonymous"}):up()
223         ;
224 end
225 function room_mt:get_disco_items(stanza)
226         local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#items");
227         for room_jid in pairs(self._occupants) do
228                 reply:tag("item", {jid = room_jid, name = room_jid:match("/(.*)")}):up();
229         end
230         return reply;
231 end
232 function room_mt:set_subject(current_nick, subject)
233         -- TODO check nick's authority
234         if subject == "" then subject = nil; end
235         self._data['subject'] = subject;
236         if self.save then self:save(); end
237         local msg = st.message({type='groupchat', from=current_nick})
238                 :tag('subject'):text(subject):up();
239         self:broadcast_message(msg, false);
240         return true;
241 end
242
243 local function build_unavailable_presence_from_error(stanza)
244         local type, condition, text = stanza:get_error();
245         local error_message = "Kicked: "..condition:gsub("%-", " ");
246         if text then
247                 error_message = error_message..": "..text;
248         end
249         return st.presence({type='unavailable', from=stanza.attr.from, to=stanza.attr.to})
250                 :tag('status'):text(error_message);
251 end
252
253 function room_mt:set_password(password)
254         if password == "" or type(password) ~= "string" then password = nil; end
255         if self._data.password ~= password then
256                 self._data.password = password;
257                 if self.save then self:save(true); end
258         end
259 end
260 function room_mt:get_password()
261         return self._data.password;
262 end
263 function room_mt:set_moderated(moderated)
264         moderated = moderated and true or nil;
265         if self._data.moderated ~= moderated then
266                 self._data.moderated = moderated;
267                 if self.save then self:save(true); end
268         end
269 end
270 function room_mt:is_moderated()
271         return self._data.moderated;
272 end
273 function room_mt:set_members_only(members_only)
274         members_only = members_only and true or nil;
275         if self._data.members_only ~= members_only then
276                 self._data.members_only = members_only;
277                 if self.save then self:save(true); end
278         end
279 end
280 function room_mt:is_members_only()
281         return self._data.members_only;
282 end
283 function room_mt:set_persistent(persistent)
284         persistent = persistent and true or nil;
285         if self._data.persistent ~= persistent then
286                 self._data.persistent = persistent;
287                 if self.save then self:save(true); end
288         end
289 end
290 function room_mt:is_persistent()
291         return self._data.persistent;
292 end
293 function room_mt:set_hidden(hidden)
294         hidden = hidden and true or nil;
295         if self._data.hidden ~= hidden then
296                 self._data.hidden = hidden;
297                 if self.save then self:save(true); end
298         end
299 end
300 function room_mt:is_hidden()
301         return self._data.hidden;
302 end
303
304 function room_mt:handle_to_occupant(origin, stanza) -- PM, vCards, etc
305         local from, to = stanza.attr.from, stanza.attr.to;
306         local room = jid_bare(to);
307         local current_nick = self._jid_nick[from];
308         local type = stanza.attr.type;
309         log("debug", "room: %s, current_nick: %s, stanza: %s", room or "nil", current_nick or "nil", stanza:top_tag());
310         if (select(2, jid_split(from)) == muc_domain) then error("Presence from the MUC itself!!!"); end
311         if stanza.name == "presence" then
312                 local pr = get_filtered_presence(stanza);
313                 pr.attr.from = current_nick;
314                 if type == "error" then -- error, kick em out!
315                         if current_nick then
316                                 log("debug", "kicking %s from %s", current_nick, room);
317                                 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza));
318                         end
319                 elseif type == "unavailable" then -- unavailable
320                         if current_nick then
321                                 log("debug", "%s leaving %s", current_nick, room);
322                                 local occupant = self._occupants[current_nick];
323                                 local new_jid = next(occupant.sessions);
324                                 if new_jid == from then new_jid = next(occupant.sessions, new_jid); end
325                                 if new_jid then
326                                         local jid = occupant.jid;
327                                         occupant.jid = new_jid;
328                                         occupant.sessions[from] = nil;
329                                         pr.attr.to = from;
330                                         pr:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
331                                                 :tag("item", {affiliation=occupant.affiliation or "none", role='none'}):up()
332                                                 :tag("status", {code='110'});
333                                         self:_route_stanza(pr);
334                                         if jid ~= new_jid then
335                                                 pr = st.clone(occupant.sessions[new_jid])
336                                                         :tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
337                                                         :tag("item", {affiliation=occupant.affiliation or "none", role=occupant.role or "none"});
338                                                 pr.attr.from = current_nick;
339                                                 self:broadcast_except_nick(pr, current_nick);
340                                         end
341                                 else
342                                         occupant.role = 'none';
343                                         self:broadcast_presence(pr, from);
344                                         self._occupants[current_nick] = nil;
345                                 end
346                                 self._jid_nick[from] = nil;
347                         end
348                 elseif not type then -- available
349                         if current_nick then
350                                 --if #pr == #stanza or current_nick ~= to then -- commented because google keeps resending directed presence
351                                         if current_nick == to then -- simple presence
352                                                 log("debug", "%s broadcasted presence", current_nick);
353                                                 self._occupants[current_nick].sessions[from] = pr;
354                                                 self:broadcast_presence(pr, from);
355                                         else -- change nick
356                                                 local occupant = self._occupants[current_nick];
357                                                 local is_multisession = next(occupant.sessions, next(occupant.sessions));
358                                                 if self._occupants[to] or is_multisession then
359                                                         log("debug", "%s couldn't change nick", current_nick);
360                                                         local reply = st.error_reply(stanza, "cancel", "conflict"):up();
361                                                         reply.tags[1].attr.code = "409";
362                                                         origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
363                                                 else
364                                                         local data = self._occupants[current_nick];
365                                                         local to_nick = select(3, jid_split(to));
366                                                         if to_nick then
367                                                                 log("debug", "%s (%s) changing nick to %s", current_nick, data.jid, to);
368                                                                 local p = st.presence({type='unavailable', from=current_nick});
369                                                                 self:broadcast_presence(p, from, '303', to_nick);
370                                                                 self._occupants[current_nick] = nil;
371                                                                 self._occupants[to] = data;
372                                                                 self._jid_nick[from] = to;
373                                                                 pr.attr.from = to;
374                                                                 self._occupants[to].sessions[from] = pr;
375                                                                 self:broadcast_presence(pr, from);
376                                                         else
377                                                                 --TODO malformed-jid
378                                                         end
379                                                 end
380                                         end
381                                 --else -- possible rejoin
382                                 --      log("debug", "%s had connection replaced", current_nick);
383                                 --      self:handle_to_occupant(origin, st.presence({type='unavailable', from=from, to=to})
384                                 --              :tag('status'):text('Replaced by new connection'):up()); -- send unavailable
385                                 --      self:handle_to_occupant(origin, stanza); -- resend available
386                                 --end
387                         else -- enter room
388                                 local new_nick = to;
389                                 local is_merge;
390                                 if self._occupants[to] then
391                                         if jid_bare(from) ~= jid_bare(self._occupants[to].jid) then
392                                                 new_nick = nil;
393                                         end
394                                         is_merge = true;
395                                 end
396                                 local password = stanza:get_child("x", "http://jabber.org/protocol/muc");
397                                 password = password and password:get_child("password", "http://jabber.org/protocol/muc");
398                                 password = password and password[1] ~= "" and password[1];
399                                 if self:get_password() and self:get_password() ~= password then
400                                         log("debug", "%s couldn't join due to invalid password: %s", from, to);
401                                         local reply = st.error_reply(stanza, "auth", "not-authorized"):up();
402                                         reply.tags[1].attr.code = "401";
403                                         origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
404                                 elseif not new_nick then
405                                         log("debug", "%s couldn't join due to nick conflict: %s", from, to);
406                                         local reply = st.error_reply(stanza, "cancel", "conflict"):up();
407                                         reply.tags[1].attr.code = "409";
408                                         origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
409                                 else
410                                         log("debug", "%s joining as %s", from, to);
411                                         if not next(self._affiliations) then -- new room, no owners
412                                                 self._affiliations[jid_bare(from)] = "owner";
413                                         end
414                                         local affiliation = self:get_affiliation(from);
415                                         local role = self:get_default_role(affiliation)
416                                         if role then -- new occupant
417                                                 if not is_merge then
418                                                         self._occupants[to] = {affiliation=affiliation, role=role, jid=from, sessions={[from]=get_filtered_presence(stanza)}};
419                                                 else
420                                                         self._occupants[to].sessions[from] = get_filtered_presence(stanza);
421                                                 end
422                                                 self._jid_nick[from] = to;
423                                                 self:send_occupant_list(from);
424                                                 pr.attr.from = to;
425                                                 if not is_merge then
426                                                         self:broadcast_presence(pr, from);
427                                                 else
428                                                         pr.attr.to = from;
429                                                         self:_route_stanza(pr:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
430                                                                 :tag("item", {affiliation=affiliation or "none", role=role or "none"}):up()
431                                                                 :tag("status", {code='110'}));
432                                                 end
433                                                 self:send_history(from, stanza);
434                                         else -- banned
435                                                 local reply = st.error_reply(stanza, "auth", "forbidden"):up();
436                                                 reply.tags[1].attr.code = "403";
437                                                 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
438                                         end
439                                 end
440                         end
441                 elseif type ~= 'result' then -- bad type
442                         if type ~= 'visible' and type ~= 'invisible' then -- COMPAT ejabberd can broadcast or forward XEP-0018 presences
443                                 origin.send(st.error_reply(stanza, "modify", "bad-request")); -- FIXME correct error?
444                         end
445                 end
446         elseif not current_nick then -- not in room
447                 if type == "error" or type == "result" then
448                         local id = stanza.name == "iq" and stanza.attr.id and base64.decode(stanza.attr.id);
449                         local _nick, _id, _hash = (id or ""):match("^(.+)%z(.*)%z(.+)$");
450                         local occupant = self._occupants[stanza.attr.to];
451                         if occupant and _nick and self._jid_nick[_nick] and _id and _hash then
452                                 local id, _to = stanza.attr.id;
453                                 for jid in pairs(occupant.sessions) do
454                                         if md5(jid) == _hash then
455                                                 _to = jid;
456                                                 break;
457                                         end
458                                 end
459                                 if _to then
460                                         stanza.attr.to, stanza.attr.from, stanza.attr.id = _to, self._jid_nick[_nick], _id;
461                                         self:_route_stanza(stanza);
462                                         stanza.attr.to, stanza.attr.from, stanza.attr.id = to, from, id;
463                                 end
464                         end
465                 else
466                         origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
467                 end
468         elseif stanza.name == "message" and type == "groupchat" then -- groupchat messages not allowed in PM
469                 origin.send(st.error_reply(stanza, "modify", "bad-request"));
470         elseif current_nick and stanza.name == "message" and type == "error" and is_kickable_error(stanza) then
471                 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
472                 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza)); -- send unavailable
473         else -- private stanza
474                 local o_data = self._occupants[to];
475                 if o_data then
476                         log("debug", "%s sent private stanza to %s (%s)", from, to, o_data.jid);
477                         local jid = o_data.jid;
478                         local bare = jid_bare(jid);
479                         stanza.attr.to, stanza.attr.from = jid, current_nick;
480                         local id = stanza.attr.id;
481                         if stanza.name=='iq' and type=='get' and stanza.tags[1].attr.xmlns == 'vcard-temp' and bare ~= jid then
482                                 stanza.attr.to = bare;
483                                 stanza.attr.id = base64.encode(jid.."\0"..id.."\0"..md5(from));
484                         end
485                         self:_route_stanza(stanza);
486                         stanza.attr.to, stanza.attr.from, stanza.attr.id = to, from, id;
487                 elseif type ~= "error" and type ~= "result" then -- recipient not in room
488                         origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
489                 end
490         end
491 end
492
493 function room_mt:send_form(origin, stanza)
494         local title = "Configuration for "..self.jid;
495         origin.send(st.reply(stanza):query("http://jabber.org/protocol/muc#owner")
496                 :tag("x", {xmlns='jabber:x:data', type='form'})
497                         :tag("title"):text(title):up()
498                         :tag("instructions"):text(title):up()
499                         :tag("field", {type='hidden', var='FORM_TYPE'}):tag("value"):text("http://jabber.org/protocol/muc#roomconfig"):up():up()
500                         :tag("field", {type='boolean', label='Make Room Persistent?', var='muc#roomconfig_persistentroom'})
501                                 :tag("value"):text(self:is_persistent() and "1" or "0"):up()
502                         :up()
503                         :tag("field", {type='boolean', label='Make Room Publicly Searchable?', var='muc#roomconfig_publicroom'})
504                                 :tag("value"):text(self:is_hidden() and "0" or "1"):up()
505                         :up()
506                         :tag("field", {type='list-single', label='Who May Discover Real JIDs?', var='muc#roomconfig_whois'})
507                             :tag("value"):text(self._data.whois or 'moderators'):up()
508                             :tag("option", {label = 'Moderators Only'})
509                                 :tag("value"):text('moderators'):up()
510                                 :up()
511                             :tag("option", {label = 'Anyone'})
512                                 :tag("value"):text('anyone'):up()
513                                 :up()
514                         :up()
515                         :tag("field", {type='text-private', label='Password', var='muc#roomconfig_roomsecret'})
516                                 :tag("value"):text(self:get_password() or ""):up()
517                         :up()
518                         :tag("field", {type='boolean', label='Make Room Moderated?', var='muc#roomconfig_moderatedroom'})
519                                 :tag("value"):text(self:is_moderated() and "1" or "0"):up()
520                         :up()
521                         :tag("field", {type='boolean', label='Make Room Members-Only?', var='muc#roomconfig_membersonly'})
522                                 :tag("value"):text(self:is_members_only() and "1" or "0"):up()
523                         :up()
524         );
525 end
526
527 local valid_whois = {
528     moderators = true,
529     anyone = true,
530 }
531
532 function room_mt:process_form(origin, stanza)
533         local query = stanza.tags[1];
534         local form;
535         for _, tag in ipairs(query.tags) do if tag.name == "x" and tag.attr.xmlns == "jabber:x:data" then form = tag; break; end end
536         if not form then origin.send(st.error_reply(stanza, "cancel", "service-unavailable")); return; end
537         if form.attr.type == "cancel" then origin.send(st.reply(stanza)); return; end
538         if form.attr.type ~= "submit" then origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
539         local fields = {};
540         for _, field in pairs(form.tags) do
541                 if field.name == "field" and field.attr.var and field.tags[1].name == "value" and #field.tags[1].tags == 0 then
542                         fields[field.attr.var] = field.tags[1][1] or "";
543                 end
544         end
545         if fields.FORM_TYPE ~= "http://jabber.org/protocol/muc#roomconfig" then origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
546
547         local dirty = false
548
549         local persistent = fields['muc#roomconfig_persistentroom'];
550         if persistent == "0" or persistent == "false" then persistent = nil; elseif persistent == "1" or persistent == "true" then persistent = true;
551         else origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
552         dirty = dirty or (self:is_persistent() ~= persistent)
553         module:log("debug", "persistent=%s", tostring(persistent));
554
555         local moderated = fields['muc#roomconfig_moderatedroom'];
556         if moderated == "0" or moderated == "false" then moderated = nil; elseif moderated == "1" or moderated == "true" then moderated = true;
557         else origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
558         dirty = dirty or (self:is_moderated() ~= moderated)
559         module:log("debug", "moderated=%s", tostring(moderated));
560
561         local membersonly = fields['muc#roomconfig_membersonly'];
562         if membersonly == "0" or membersonly == "false" then membersonly = nil; elseif membersonly == "1" or membersonly == "true" then membersonly = true;
563         else origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
564         dirty = dirty or (self:is_members_only() ~= membersonly)
565         module:log("debug", "membersonly=%s", tostring(membersonly));
566
567         local public = fields['muc#roomconfig_publicroom'];
568         if public == "0" or public == "false" then public = nil; elseif public == "1" or public == "true" then public = true;
569         else origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
570         dirty = dirty or (self:is_hidden() ~= (not public and true or nil))
571
572         local whois = fields['muc#roomconfig_whois'];
573         if not valid_whois[whois] then
574             origin.send(st.error_reply(stanza, 'cancel', 'bad-request'));
575             return;
576         end
577         local whois_changed = self._data.whois ~= whois
578         self._data.whois = whois
579         module:log('debug', 'whois=%s', whois)
580
581         local password = fields['muc#roomconfig_roomsecret'];
582         if password then
583                 self:set_password(password);
584         end
585         self:set_moderated(moderated);
586         self:set_members_only(membersonly);
587         self:set_persistent(persistent);
588         self:set_hidden(not public);
589
590         if self.save then self:save(true); end
591         origin.send(st.reply(stanza));
592
593         if dirty or whois_changed then
594             local msg = st.message({type='groupchat', from=self.jid})
595                     :tag('x', {xmlns='http://jabber.org/protocol/muc#user'}):up()
596
597             if dirty then
598                 msg.tags[1]:tag('status', {code = '104'})
599             end
600             if whois_changed then
601                 local code = (whois == 'moderators') and 173 or 172
602                 msg.tags[1]:tag('status', {code = code})
603             end
604
605             self:broadcast_message(msg, false)
606         end
607 end
608
609 function room_mt:destroy(newjid, reason, password)
610         local pr = st.presence({type = "unavailable"})
611                 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
612                         :tag("item", { affiliation='none', role='none' }):up()
613                         :tag("destroy", {jid=newjid})
614         if reason then pr:tag("reason"):text(reason):up(); end
615         if password then pr:tag("password"):text(password):up(); end
616         for nick, occupant in pairs(self._occupants) do
617                 pr.attr.from = nick;
618                 for jid in pairs(occupant.sessions) do
619                         pr.attr.to = jid;
620                         self:_route_stanza(pr);
621                         self._jid_nick[jid] = nil;
622                 end
623                 self._occupants[nick] = nil;
624         end
625         self:set_persistent(false);
626 end
627
628 function room_mt:handle_to_room(origin, stanza) -- presence changes and groupchat messages, along with disco/etc
629         local type = stanza.attr.type;
630         local xmlns = stanza.tags[1] and stanza.tags[1].attr.xmlns;
631         if stanza.name == "iq" then
632                 if xmlns == "http://jabber.org/protocol/disco#info" and type == "get" then
633                         origin.send(self:get_disco_info(stanza));
634                 elseif xmlns == "http://jabber.org/protocol/disco#items" and type == "get" then
635                         origin.send(self:get_disco_items(stanza));
636                 elseif xmlns == "http://jabber.org/protocol/muc#admin" then
637                         local actor = stanza.attr.from;
638                         local affiliation = self:get_affiliation(actor);
639                         local current_nick = self._jid_nick[actor];
640                         local role = current_nick and self._occupants[current_nick].role or self:get_default_role(affiliation);
641                         local item = stanza.tags[1].tags[1];
642                         if item and item.name == "item" then
643                                 if type == "set" then
644                                         local callback = function() origin.send(st.reply(stanza)); end
645                                         if item.attr.jid then -- Validate provided JID
646                                                 item.attr.jid = jid_prep(item.attr.jid);
647                                                 if not item.attr.jid then
648                                                         origin.send(st.error_reply(stanza, "modify", "jid-malformed"));
649                                                         return;
650                                                 end
651                                         end
652                                         if not item.attr.jid and item.attr.nick then -- COMPAT Workaround for Miranda sending 'nick' instead of 'jid' when changing affiliation
653                                                 local occupant = self._occupants[self.jid.."/"..item.attr.nick];
654                                                 if occupant then item.attr.jid = occupant.jid; end
655                                         elseif not item.attr.nick and item.attr.jid then
656                                                 local nick = self._jid_nick[item.attr.jid];
657                                                 if nick then item.attr.nick = select(3, jid_split(nick)); end
658                                         end
659                                         local reason = item.tags[1] and item.tags[1].name == "reason" and #item.tags[1] == 1 and item.tags[1][1];
660                                         if item.attr.affiliation and item.attr.jid and not item.attr.role then
661                                                 local success, errtype, err = self:set_affiliation(actor, item.attr.jid, item.attr.affiliation, callback, reason);
662                                                 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
663                                         elseif item.attr.role and item.attr.nick and not item.attr.affiliation then
664                                                 local success, errtype, err = self:set_role(actor, self.jid.."/"..item.attr.nick, item.attr.role, callback, reason);
665                                                 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
666                                         else
667                                                 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
668                                         end
669                                 elseif type == "get" then
670                                         local _aff = item.attr.affiliation;
671                                         local _rol = item.attr.role;
672                                         if _aff and not _rol then
673                                                 if affiliation == "owner" or (affiliation == "admin" and _aff ~= "owner" and _aff ~= "admin") then
674                                                         local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
675                                                         for jid, affiliation in pairs(self._affiliations) do
676                                                                 if affiliation == _aff then
677                                                                         reply:tag("item", {affiliation = _aff, jid = jid}):up();
678                                                                 end
679                                                         end
680                                                         origin.send(reply);
681                                                 else
682                                                         origin.send(st.error_reply(stanza, "auth", "forbidden"));
683                                                 end
684                                         elseif _rol and not _aff then
685                                                 if role == "moderator" then
686                                                         -- TODO allow admins and owners not in room? Provide read-only access to everyone who can see the participants anyway?
687                                                         if _rol == "none" then _rol = nil; end
688                                                         local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
689                                                         for occupant_jid, occupant in pairs(self._occupants) do
690                                                                 if occupant.role == _rol then
691                                                                         reply:tag("item", {
692                                                                                 nick = select(3, jid_split(occupant_jid)),
693                                                                                 role = _rol or "none",
694                                                                                 affiliation = occupant.affiliation or "none",
695                                                                                 jid = occupant.jid
696                                                                                 }):up();
697                                                                 end
698                                                         end
699                                                         origin.send(reply);
700                                                 else
701                                                         origin.send(st.error_reply(stanza, "auth", "forbidden"));
702                                                 end
703                                         else
704                                                 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
705                                         end
706                                 end
707                         elseif type == "set" or type == "get" then
708                                 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
709                         end
710                 elseif xmlns == "http://jabber.org/protocol/muc#owner" and (type == "get" or type == "set") and stanza.tags[1].name == "query" then
711                         if self:get_affiliation(stanza.attr.from) ~= "owner" then
712                                 origin.send(st.error_reply(stanza, "auth", "forbidden"));
713                         elseif stanza.attr.type == "get" then
714                                 self:send_form(origin, stanza);
715                         elseif stanza.attr.type == "set" then
716                                 local child = stanza.tags[1].tags[1];
717                                 if not child then
718                                         origin.send(st.error_reply(stanza, "auth", "bad-request"));
719                                 elseif child.name == "destroy" then
720                                         local newjid = child.attr.jid;
721                                         local reason, password;
722                                         for _,tag in ipairs(child.tags) do
723                                                 if tag.name == "reason" then
724                                                         reason = #tag.tags == 0 and tag[1];
725                                                 elseif tag.name == "password" then
726                                                         password = #tag.tags == 0 and tag[1];
727                                                 end
728                                         end
729                                         self:destroy(newjid, reason, password);
730                                         origin.send(st.reply(stanza));
731                                 else
732                                         self:process_form(origin, stanza);
733                                 end
734                         end
735                 elseif type == "set" or type == "get" then
736                         origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
737                 end
738         elseif stanza.name == "message" and type == "groupchat" then
739                 local from, to = stanza.attr.from, stanza.attr.to;
740                 local room = jid_bare(to);
741                 local current_nick = self._jid_nick[from];
742                 local occupant = self._occupants[current_nick];
743                 if not occupant then -- not in room
744                         origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
745                 elseif occupant.role == "visitor" then
746                         origin.send(st.error_reply(stanza, "cancel", "forbidden"));
747                 else
748                         local from = stanza.attr.from;
749                         stanza.attr.from = current_nick;
750                         local subject = getText(stanza, {"subject"});
751                         if subject then
752                                 if occupant.role == "moderator" then
753                                         self:set_subject(current_nick, subject); -- TODO use broadcast_message_stanza
754                                 else
755                                         stanza.attr.from = from;
756                                         origin.send(st.error_reply(stanza, "cancel", "forbidden"));
757                                 end
758                         else
759                                 self:broadcast_message(stanza, true);
760                         end
761                         stanza.attr.from = from;
762                 end
763         elseif stanza.name == "message" and type == "error" and is_kickable_error(stanza) then
764                 local current_nick = self._jid_nick[stanza.attr.from];
765                 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
766                 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza)); -- send unavailable
767         elseif stanza.name == "presence" then -- hack - some buggy clients send presence updates to the room rather than their nick
768                 local to = stanza.attr.to;
769                 local current_nick = self._jid_nick[stanza.attr.from];
770                 if current_nick then
771                         stanza.attr.to = current_nick;
772                         self:handle_to_occupant(origin, stanza);
773                         stanza.attr.to = to;
774                 elseif type ~= "error" and type ~= "result" then
775                         origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
776                 end
777         elseif stanza.name == "message" and not stanza.attr.type and #stanza.tags == 1 and self._jid_nick[stanza.attr.from]
778                 and stanza.tags[1].name == "x" and stanza.tags[1].attr.xmlns == "http://jabber.org/protocol/muc#user" then
779                 local x = stanza.tags[1];
780                 local payload = (#x.tags == 1 and x.tags[1]);
781                 if payload and payload.name == "invite" and payload.attr.to then
782                         local _from, _to = stanza.attr.from, stanza.attr.to;
783                         local _invitee = jid_prep(payload.attr.to);
784                         if _invitee then
785                                 local _reason = payload.tags[1] and payload.tags[1].name == 'reason' and #payload.tags[1].tags == 0 and payload.tags[1][1];
786                                 local invite = st.message({from = _to, to = _invitee, id = stanza.attr.id})
787                                         :tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
788                                                 :tag('invite', {from=_from})
789                                                         :tag('reason'):text(_reason or ""):up()
790                                                 :up();
791                                                 if self:get_password() then
792                                                         invite:tag("password"):text(self:get_password()):up();
793                                                 end
794                                         invite:up()
795                                         :tag('x', {xmlns="jabber:x:conference", jid=_to}) -- COMPAT: Some older clients expect this
796                                                 :text(_reason or "")
797                                         :up()
798                                         :tag('body') -- Add a plain message for clients which don't support invites
799                                                 :text(_from..' invited you to the room '.._to..(_reason and (' ('.._reason..')') or ""))
800                                         :up();
801                                 self:_route_stanza(invite);
802                         else
803                                 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
804                         end
805                 else
806                         origin.send(st.error_reply(stanza, "cancel", "bad-request"));
807                 end
808         else
809                 if type == "error" or type == "result" then return; end
810                 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
811         end
812 end
813
814 function room_mt:handle_stanza(origin, stanza)
815         local to_node, to_host, to_resource = jid_split(stanza.attr.to);
816         if to_resource then
817                 self:handle_to_occupant(origin, stanza);
818         else
819                 self:handle_to_room(origin, stanza);
820         end
821 end
822
823 function room_mt:route_stanza(stanza) end -- Replace with a routing function, e.g., function(room, stanza) core_route_stanza(origin, stanza); end
824
825 function room_mt:get_affiliation(jid)
826         local node, host, resource = jid_split(jid);
827         local bare = node and node.."@"..host or host;
828         local result = self._affiliations[bare]; -- Affiliations are granted, revoked, and maintained based on the user's bare JID.
829         if not result and self._affiliations[host] == "outcast" then result = "outcast"; end -- host banned
830         return result;
831 end
832 function room_mt:set_affiliation(actor, jid, affiliation, callback, reason)
833         jid = jid_bare(jid);
834         if affiliation == "none" then affiliation = nil; end
835         if affiliation and affiliation ~= "outcast" and affiliation ~= "owner" and affiliation ~= "admin" and affiliation ~= "member" then
836                 return nil, "modify", "not-acceptable";
837         end
838         if self:get_affiliation(actor) ~= "owner" then return nil, "cancel", "not-allowed"; end
839         if jid_bare(actor) == jid then return nil, "cancel", "not-allowed"; end
840         self._affiliations[jid] = affiliation;
841         local role = self:get_default_role(affiliation);
842         local p = st.presence()
843                 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
844                         :tag("item", {affiliation=affiliation or "none", role=role or "none"})
845                                 :tag("reason"):text(reason or ""):up()
846                         :up();
847         local x = p.tags[1];
848         local item = x.tags[1];
849         if not role then -- getting kicked
850                 p.attr.type = "unavailable";
851                 if affiliation == "outcast" then
852                         x:tag("status", {code="301"}):up(); -- banned
853                 else
854                         x:tag("status", {code="321"}):up(); -- affiliation change
855                 end
856         end
857         local modified_nicks = {};
858         for nick, occupant in pairs(self._occupants) do
859                 if jid_bare(occupant.jid) == jid then
860                         if not role then -- getting kicked
861                                 self._occupants[nick] = nil;
862                         else
863                                 t_insert(modified_nicks, nick);
864                                 occupant.affiliation, occupant.role = affiliation, role;
865                         end
866                         p.attr.from = nick;
867                         for jid in pairs(occupant.sessions) do -- remove for all sessions of the nick
868                                 if not role then self._jid_nick[jid] = nil; end
869                                 p.attr.to = jid;
870                                 self:_route_stanza(p);
871                         end
872                 end
873         end
874         if self.save then self:save(); end
875         if callback then callback(); end
876         for _, nick in ipairs(modified_nicks) do
877                 p.attr.from = nick;
878                 self:broadcast_except_nick(p, nick);
879         end
880         return true;
881 end
882
883 function room_mt:get_role(nick)
884         local session = self._occupants[nick];
885         return session and session.role or nil;
886 end
887 function room_mt:can_set_role(actor_jid, occupant_jid, role)
888         local actor = self._occupants[self._jid_nick[actor_jid]];
889         local occupant = self._occupants[occupant_jid];
890         
891         if not occupant or not actor then return nil, "modify", "not-acceptable"; end
892
893         if actor.role == "moderator" then
894                 if occupant.affiliation ~= "owner" and occupant.affiliation ~= "admin" then
895                         if actor.affiliation == "owner" or actor.affiliation == "admin" then
896                                 return true;
897                         elseif occupant.role ~= "moderator" and role ~= "moderator" then
898                                 return true;
899                         end
900                 end
901         end
902         return nil, "cancel", "not-allowed";
903 end
904 function room_mt:set_role(actor, occupant_jid, role, callback, reason)
905         if role == "none" then role = nil; end
906         if role and role ~= "moderator" and role ~= "participant" and role ~= "visitor" then return nil, "modify", "not-acceptable"; end
907         local allowed, err_type, err_condition = self:can_set_role(actor, occupant_jid, role);
908         if not allowed then return allowed, err_type, err_condition; end
909         local occupant = self._occupants[occupant_jid];
910         local p = st.presence({from = occupant_jid})
911                 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
912                         :tag("item", {affiliation=occupant.affiliation or "none", nick=select(3, jid_split(occupant_jid)), role=role or "none"})
913                                 :tag("reason"):text(reason or ""):up()
914                         :up();
915         if not role then -- kick
916                 p.attr.type = "unavailable";
917                 self._occupants[occupant_jid] = nil;
918                 for jid in pairs(occupant.sessions) do -- remove for all sessions of the nick
919                         self._jid_nick[jid] = nil;
920                 end
921                 p:tag("status", {code = "307"}):up();
922         else
923                 occupant.role = role;
924         end
925         for jid in pairs(occupant.sessions) do -- send to all sessions of the nick
926                 p.attr.to = jid;
927                 self:_route_stanza(p);
928         end
929         if callback then callback(); end
930         self:broadcast_except_nick(p, occupant_jid);
931         return true;
932 end
933
934 function room_mt:_route_stanza(stanza)
935         local muc_child;
936         local to_occupant = self._occupants[self._jid_nick[stanza.attr.to]];
937         local from_occupant = self._occupants[stanza.attr.from];
938         if stanza.name == "presence" then
939                 if to_occupant and from_occupant then
940                         if self._data.whois == 'anyone' then
941                             muc_child = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
942                         else
943                                 if to_occupant.role == "moderator" or jid_bare(to_occupant.jid) == jid_bare(from_occupant.jid) then
944                                         muc_child = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
945                                 end
946                         end
947                 end
948         end
949         if muc_child then
950                 for _, item in pairs(muc_child.tags) do
951                         if item.name == "item" then
952                                 if from_occupant == to_occupant then
953                                         item.attr.jid = stanza.attr.to;
954                                 else
955                                         item.attr.jid = from_occupant.jid;
956                                 end
957                         end
958                 end
959                 if self._data.whois == 'anyone' then
960                     muc_child:tag('status', { code = '100' });
961                 end
962         end
963         self:route_stanza(stanza);
964         if muc_child then
965                 for _, item in pairs(muc_child.tags) do
966                         if item.name == "item" then
967                                 item.attr.jid = nil;
968                         end
969                 end
970         end
971 end
972
973 local _M = {}; -- module "muc"
974
975 function _M.new_room(jid, config)
976         return setmetatable({
977                 jid = jid;
978                 _jid_nick = {};
979                 _occupants = {};
980                 _data = {
981                     whois = 'moderators';
982                     history_length = (config and config.history_length);
983                 };
984                 _affiliations = {};
985         }, room_mt);
986 end
987
988 return _M;