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