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