2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 Waqas Hussain
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
10 local pairs, ipairs = pairs, ipairs;
12 local datamanager = require "util.datamanager";
13 local datetime = require "util.datetime";
15 local dataform = require "util.dataforms";
17 local jid_split = require "util.jid".split;
18 local jid_bare = require "util.jid".bare;
19 local jid_prep = require "util.jid".prep;
20 local st = require "util.stanza";
21 local log = require "util.logger".init("mod_muc");
22 local multitable_new = require "util.multitable".new;
23 local t_insert, t_remove = table.insert, table.remove;
24 local setmetatable = setmetatable;
25 local base64 = require "util.encodings".base64;
26 local md5 = require "util.hashes".md5;
28 local muc_domain = nil; --module:get_host();
29 local default_history_length = 20;
32 local function filter_xmlns_from_array(array, filters)
35 local attr = array[i].attr;
36 if filters[attr and attr.xmlns] then
43 local function filter_xmlns_from_stanza(stanza, filters)
45 if filter_xmlns_from_array(stanza.tags, filters) ~= 0 then
46 return stanza, filter_xmlns_from_array(stanza, filters);
51 local presence_filters = {["http://jabber.org/protocol/muc"]=true;["http://jabber.org/protocol/muc#user"]=true};
52 local function get_filtered_presence(stanza)
53 return filter_xmlns_from_stanza(st.clone(stanza):reset(), presence_filters);
55 local kickable_error_conditions = {
57 ["internal-server-error"] = true;
58 ["item-not-found"] = true;
59 ["jid-malformed"] = true;
60 ["recipient-unavailable"] = true;
62 ["remote-server-not-found"] = true;
63 ["remote-server-timeout"] = true;
64 ["service-unavailable"] = true;
65 ["malformed error"] = true;
68 local function get_error_condition(stanza)
69 local _, condition = stanza:get_error();
70 return condition or "malformed error";
73 local function is_kickable_error(stanza)
74 local cond = get_error_condition(stanza);
75 return kickable_error_conditions[cond] and cond;
77 local function getUsingPath(stanza, path, getText)
79 for _, name in ipairs(path) do
80 if type(tag) ~= 'table' then return; end
81 tag = tag:child_with_name(name);
83 if tag and getText then tag = table.concat(tag); end
86 local function getTag(stanza, path) return getUsingPath(stanza, path); end
87 local function getText(stanza, path) return getUsingPath(stanza, path, true); end
91 room_mt.__index = room_mt;
93 function room_mt:get_default_role(affiliation)
94 if affiliation == "owner" or affiliation == "admin" then
96 elseif affiliation == "member" then
98 elseif not affiliation then
99 if not self:is_members_only() then
100 return self:is_moderated() and "visitor" or "participant";
105 function room_mt:broadcast_presence(stanza, sid, code, nick)
106 stanza = get_filtered_presence(stanza);
107 local occupant = self._occupants[stanza.attr.from];
108 stanza:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
109 :tag("item", {affiliation=occupant.affiliation or "none", role=occupant.role or "none", nick=nick}):up();
111 stanza:tag("status", {code=code}):up();
113 self:broadcast_except_nick(stanza, stanza.attr.from);
114 local me = self._occupants[stanza.attr.from];
116 stanza:tag("status", {code='110'}):up();
117 stanza.attr.to = sid;
118 self:_route_stanza(stanza);
121 function room_mt:broadcast_message(stanza, historic)
122 local to = stanza.attr.to;
123 for occupant, o_data in pairs(self._occupants) do
124 for jid in pairs(o_data.sessions) do
125 stanza.attr.to = jid;
126 self:_route_stanza(stanza);
130 if historic then -- add to history
131 local history = self._data['history'];
132 if not history then history = {}; self._data['history'] = history; end
133 stanza = st.clone(stanza);
135 local stamp = datetime.datetime();
136 local chars = #tostring(stanza);
137 stanza:tag("delay", {xmlns = "urn:xmpp:delay", from = muc_domain, stamp = stamp}):up(); -- XEP-0203
138 stanza:tag("x", {xmlns = "jabber:x:delay", from = muc_domain, stamp = datetime.legacy()}):up(); -- XEP-0091 (deprecated)
139 local entry = { stanza = stanza, stamp = stamp };
140 t_insert(history, entry);
141 while #history > (self._data.history_length or default_history_length) do t_remove(history, 1) end
144 function room_mt:broadcast_except_nick(stanza, nick)
145 for rnick, occupant in pairs(self._occupants) do
146 if rnick ~= nick then
147 for jid in pairs(occupant.sessions) do
148 stanza.attr.to = jid;
149 self:_route_stanza(stanza);
155 function room_mt:send_occupant_list(to)
156 local current_nick = self._jid_nick[to];
157 for occupant, o_data in pairs(self._occupants) do
158 if occupant ~= current_nick then
159 local pres = get_filtered_presence(o_data.sessions[o_data.jid]);
160 pres.attr.to, pres.attr.from = to, occupant;
161 pres:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
162 :tag("item", {affiliation=o_data.affiliation or "none", role=o_data.role or "none"}):up();
163 self:_route_stanza(pres);
167 function room_mt:send_history(to, stanza)
168 local history = self._data['history']; -- send discussion history
170 local x_tag = stanza and stanza:get_child("x", "http://jabber.org/protocol/muc");
171 local history_tag = x_tag and x_tag:get_child("history", "http://jabber.org/protocol/muc");
173 local maxchars = history_tag and tonumber(history_tag.attr.maxchars);
174 if maxchars then maxchars = math.floor(maxchars); end
176 local maxstanzas = math.floor(history_tag and tonumber(history_tag.attr.maxstanzas) or #history);
177 if not history_tag then maxstanzas = 20; end
179 local seconds = history_tag and tonumber(history_tag.attr.seconds);
180 if seconds then seconds = datetime.datetime(os.time() - math.floor(seconds)); end
182 local since = history_tag and history_tag.attr.since;
183 if since then since = datetime.parse(since); since = since and datetime.datetime(since); end
184 if seconds and (not since or since < seconds) then since = seconds; end
188 local stanzacount = 0;
190 for i=#history,1,-1 do
191 local entry = history[i];
193 if not entry.chars then
194 entry.stanza.attr.to = "";
195 entry.chars = #tostring(entry.stanza);
197 charcount = charcount + entry.chars + #to;
198 if charcount > maxchars then break; end
200 if since and since > entry.stamp then break; end
201 if n + 1 > maxstanzas then break; end
204 for i=#history-n+1,#history do
205 local msg = history[i].stanza;
207 self:_route_stanza(msg);
210 if self._data['subject'] then
211 self:_route_stanza(st.message({type='groupchat', from=self._data['subject_from'] or self.jid, to=to}):tag("subject"):text(self._data['subject']));
215 function room_mt:get_disco_info(stanza)
216 return st.reply(stanza):query("http://jabber.org/protocol/disco#info")
217 :tag("identity", {category="conference", type="text", name=self:get_name()}):up()
218 :tag("feature", {var="http://jabber.org/protocol/muc"}):up()
219 :tag("feature", {var=self:get_password() and "muc_passwordprotected" or "muc_unsecured"}):up()
220 :tag("feature", {var=self:is_moderated() and "muc_moderated" or "muc_unmoderated"}):up()
221 :tag("feature", {var=self:is_members_only() and "muc_membersonly" or "muc_open"}):up()
222 :tag("feature", {var=self:is_persistent() and "muc_persistent" or "muc_temporary"}):up()
223 :tag("feature", {var=self:is_hidden() and "muc_hidden" or "muc_public"}):up()
224 :tag("feature", {var=self._data.whois ~= "anyone" and "muc_semianonymous" or "muc_nonanonymous"}):up()
225 :add_child(dataform.new({
226 { name = "FORM_TYPE", type = "hidden", value = "http://jabber.org/protocol/muc#roominfo" },
227 { name = "muc#roominfo_description", label = "Description"}
228 }):form({["muc#roominfo_description"] = self:get_description()}, 'result'))
231 function room_mt:get_disco_items(stanza)
232 local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#items");
233 for room_jid in pairs(self._occupants) do
234 reply:tag("item", {jid = room_jid, name = room_jid:match("/(.*)")}):up();
238 function room_mt:set_subject(current_nick, subject)
239 -- TODO check nick's authority
240 if subject == "" then subject = nil; end
241 self._data['subject'] = subject;
242 self._data['subject_from'] = current_nick;
243 if self.save then self:save(); end
244 local msg = st.message({type='groupchat', from=current_nick})
245 :tag('subject'):text(subject):up();
246 self:broadcast_message(msg, false);
250 local function build_unavailable_presence_from_error(stanza)
251 local type, condition, text = stanza:get_error();
252 local error_message = "Kicked: "..(condition and condition:gsub("%-", " ") or "presence error");
254 error_message = error_message..": "..text;
256 return st.presence({type='unavailable', from=stanza.attr.from, to=stanza.attr.to})
257 :tag('status'):text(error_message);
260 function room_mt:set_name(name)
261 if name == "" or type(name) ~= "string" or name == (jid_split(self.jid)) then name = nil; end
262 if self._data.name ~= name then
263 self._data.name = name;
264 if self.save then self:save(true); end
267 function room_mt:get_name()
268 return self._data.name or jid_split(self.jid);
270 function room_mt:set_description(description)
271 if description == "" or type(description) ~= "string" then description = nil; end
272 if self._data.description ~= description then
273 self._data.description = description;
274 if self.save then self:save(true); end
277 function room_mt:get_description()
278 return self._data.description;
280 function room_mt:set_password(password)
281 if password == "" or type(password) ~= "string" then password = nil; end
282 if self._data.password ~= password then
283 self._data.password = password;
284 if self.save then self:save(true); end
287 function room_mt:get_password()
288 return self._data.password;
290 function room_mt:set_moderated(moderated)
291 moderated = moderated and true or nil;
292 if self._data.moderated ~= moderated then
293 self._data.moderated = moderated;
294 if self.save then self:save(true); end
297 function room_mt:is_moderated()
298 return self._data.moderated;
300 function room_mt:set_members_only(members_only)
301 members_only = members_only and true or nil;
302 if self._data.members_only ~= members_only then
303 self._data.members_only = members_only;
304 if self.save then self:save(true); end
307 function room_mt:is_members_only()
308 return self._data.members_only;
310 function room_mt:set_persistent(persistent)
311 persistent = persistent and true or nil;
312 if self._data.persistent ~= persistent then
313 self._data.persistent = persistent;
314 if self.save then self:save(true); end
317 function room_mt:is_persistent()
318 return self._data.persistent;
320 function room_mt:set_hidden(hidden)
321 hidden = hidden and true or nil;
322 if self._data.hidden ~= hidden then
323 self._data.hidden = hidden;
324 if self.save then self:save(true); end
327 function room_mt:is_hidden()
328 return self._data.hidden;
331 function room_mt:handle_to_occupant(origin, stanza) -- PM, vCards, etc
332 local from, to = stanza.attr.from, stanza.attr.to;
333 local room = jid_bare(to);
334 local current_nick = self._jid_nick[from];
335 local type = stanza.attr.type;
336 log("debug", "room: %s, current_nick: %s, stanza: %s", room or "nil", current_nick or "nil", stanza:top_tag());
337 if (select(2, jid_split(from)) == muc_domain) then error("Presence from the MUC itself!!!"); end
338 if stanza.name == "presence" then
339 local pr = get_filtered_presence(stanza);
340 pr.attr.from = current_nick;
341 if type == "error" then -- error, kick em out!
343 log("debug", "kicking %s from %s", current_nick, room);
344 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza));
346 elseif type == "unavailable" then -- unavailable
348 log("debug", "%s leaving %s", current_nick, room);
349 local occupant = self._occupants[current_nick];
350 local new_jid = next(occupant.sessions);
351 if new_jid == from then new_jid = next(occupant.sessions, new_jid); end
353 local jid = occupant.jid;
354 occupant.jid = new_jid;
355 occupant.sessions[from] = nil;
357 pr:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
358 :tag("item", {affiliation=occupant.affiliation or "none", role='none'}):up()
359 :tag("status", {code='110'});
360 self:_route_stanza(pr);
361 if jid ~= new_jid then
362 pr = st.clone(occupant.sessions[new_jid])
363 :tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
364 :tag("item", {affiliation=occupant.affiliation or "none", role=occupant.role or "none"});
365 pr.attr.from = current_nick;
366 self:broadcast_except_nick(pr, current_nick);
369 occupant.role = 'none';
370 self:broadcast_presence(pr, from);
371 self._occupants[current_nick] = nil;
373 self._jid_nick[from] = nil;
375 elseif not type then -- available
377 --if #pr == #stanza or current_nick ~= to then -- commented because google keeps resending directed presence
378 if current_nick == to then -- simple presence
379 log("debug", "%s broadcasted presence", current_nick);
380 self._occupants[current_nick].sessions[from] = pr;
381 self:broadcast_presence(pr, from);
383 local occupant = self._occupants[current_nick];
384 local is_multisession = next(occupant.sessions, next(occupant.sessions));
385 if self._occupants[to] or is_multisession then
386 log("debug", "%s couldn't change nick", current_nick);
387 local reply = st.error_reply(stanza, "cancel", "conflict"):up();
388 reply.tags[1].attr.code = "409";
389 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
391 local data = self._occupants[current_nick];
392 local to_nick = select(3, jid_split(to));
394 log("debug", "%s (%s) changing nick to %s", current_nick, data.jid, to);
395 local p = st.presence({type='unavailable', from=current_nick});
396 self:broadcast_presence(p, from, '303', to_nick);
397 self._occupants[current_nick] = nil;
398 self._occupants[to] = data;
399 self._jid_nick[from] = to;
401 self._occupants[to].sessions[from] = pr;
402 self:broadcast_presence(pr, from);
408 --else -- possible rejoin
409 -- log("debug", "%s had connection replaced", current_nick);
410 -- self:handle_to_occupant(origin, st.presence({type='unavailable', from=from, to=to})
411 -- :tag('status'):text('Replaced by new connection'):up()); -- send unavailable
412 -- self:handle_to_occupant(origin, stanza); -- resend available
417 if self._occupants[to] then
418 if jid_bare(from) ~= jid_bare(self._occupants[to].jid) then
423 local password = stanza:get_child("x", "http://jabber.org/protocol/muc");
424 password = password and password:get_child("password", "http://jabber.org/protocol/muc");
425 password = password and password[1] ~= "" and password[1];
426 if self:get_password() and self:get_password() ~= password then
427 log("debug", "%s couldn't join due to invalid password: %s", from, to);
428 local reply = st.error_reply(stanza, "auth", "not-authorized"):up();
429 reply.tags[1].attr.code = "401";
430 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
431 elseif not new_nick then
432 log("debug", "%s couldn't join due to nick conflict: %s", from, to);
433 local reply = st.error_reply(stanza, "cancel", "conflict"):up();
434 reply.tags[1].attr.code = "409";
435 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
437 log("debug", "%s joining as %s", from, to);
438 if not next(self._affiliations) then -- new room, no owners
439 self._affiliations[jid_bare(from)] = "owner";
441 local affiliation = self:get_affiliation(from);
442 local role = self:get_default_role(affiliation)
443 if role then -- new occupant
445 self._occupants[to] = {affiliation=affiliation, role=role, jid=from, sessions={[from]=get_filtered_presence(stanza)}};
447 self._occupants[to].sessions[from] = get_filtered_presence(stanza);
449 self._jid_nick[from] = to;
450 self:send_occupant_list(from);
453 self:broadcast_presence(pr, from);
456 self:_route_stanza(pr:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
457 :tag("item", {affiliation=affiliation or "none", role=role or "none"}):up()
458 :tag("status", {code='110'}));
460 self:send_history(from, stanza);
461 elseif not affiliation then -- registration required for entering members-only room
462 local reply = st.error_reply(stanza, "auth", "registration-required"):up();
463 reply.tags[1].attr.code = "407";
464 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
466 local reply = st.error_reply(stanza, "auth", "forbidden"):up();
467 reply.tags[1].attr.code = "403";
468 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
472 elseif type ~= 'result' then -- bad type
473 if type ~= 'visible' and type ~= 'invisible' then -- COMPAT ejabberd can broadcast or forward XEP-0018 presences
474 origin.send(st.error_reply(stanza, "modify", "bad-request")); -- FIXME correct error?
477 elseif not current_nick then -- not in room
478 if type == "error" or type == "result" then
479 local id = stanza.name == "iq" and stanza.attr.id and base64.decode(stanza.attr.id);
480 local _nick, _id, _hash = (id or ""):match("^(.+)%z(.*)%z(.+)$");
481 local occupant = self._occupants[stanza.attr.to];
482 if occupant and _nick and self._jid_nick[_nick] and _id and _hash then
483 local id, _to = stanza.attr.id;
484 for jid in pairs(occupant.sessions) do
485 if md5(jid) == _hash then
491 stanza.attr.to, stanza.attr.from, stanza.attr.id = _to, self._jid_nick[_nick], _id;
492 self:_route_stanza(stanza);
493 stanza.attr.to, stanza.attr.from, stanza.attr.id = to, from, id;
497 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
499 elseif stanza.name == "message" and type == "groupchat" then -- groupchat messages not allowed in PM
500 origin.send(st.error_reply(stanza, "modify", "bad-request"));
501 elseif current_nick and stanza.name == "message" and type == "error" and is_kickable_error(stanza) then
502 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
503 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza)); -- send unavailable
504 else -- private stanza
505 local o_data = self._occupants[to];
507 log("debug", "%s sent private stanza to %s (%s)", from, to, o_data.jid);
508 local jid = o_data.jid;
509 local bare = jid_bare(jid);
510 stanza.attr.to, stanza.attr.from = jid, current_nick;
511 local id = stanza.attr.id;
512 if stanza.name=='iq' and type=='get' and stanza.tags[1].attr.xmlns == 'vcard-temp' and bare ~= jid then
513 stanza.attr.to = bare;
514 stanza.attr.id = base64.encode(jid.."\0"..id.."\0"..md5(from));
516 self:_route_stanza(stanza);
517 stanza.attr.to, stanza.attr.from, stanza.attr.id = to, from, id;
518 elseif type ~= "error" and type ~= "result" then -- recipient not in room
519 origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
524 function room_mt:send_form(origin, stanza)
525 origin.send(st.reply(stanza):query("http://jabber.org/protocol/muc#owner")
526 :add_child(self:get_form_layout():form())
530 function room_mt:get_form_layout()
531 local title = "Configuration for "..self.jid;
532 return dataform.new({
534 instructions = title,
538 value = 'http://jabber.org/protocol/muc#roomconfig'
541 name = 'muc#roomconfig_roomname',
542 type = 'text-single',
544 value = self:get_name() or "",
547 name = 'muc#roomconfig_roomdesc',
548 type = 'text-single',
549 label = 'Description',
550 value = self:get_description() or "",
553 name = 'muc#roomconfig_persistentroom',
555 label = 'Make Room Persistent?',
556 value = self:is_persistent()
559 name = 'muc#roomconfig_publicroom',
561 label = 'Make Room Publicly Searchable?',
562 value = not self:is_hidden()
565 name = 'muc#roomconfig_whois',
566 type = 'list-single',
567 label = 'Who May Discover Real JIDs?',
569 { value = 'moderators', label = 'Moderators Only', default = self._data.whois == 'moderators' },
570 { value = 'anyone', label = 'Anyone', default = self._data.whois == 'anyone' }
574 name = 'muc#roomconfig_roomsecret',
575 type = 'text-private',
577 value = self:get_password() or "",
580 name = 'muc#roomconfig_moderatedroom',
582 label = 'Make Room Moderated?',
583 value = self:is_moderated()
586 name = 'muc#roomconfig_membersonly',
588 label = 'Make Room Members-Only?',
589 value = self:is_members_only()
594 local valid_whois = {
599 function room_mt:process_form(origin, stanza)
600 local query = stanza.tags[1];
602 for _, tag in ipairs(query.tags) do if tag.name == "x" and tag.attr.xmlns == "jabber:x:data" then form = tag; break; end end
603 if not form then origin.send(st.error_reply(stanza, "cancel", "service-unavailable")); return; end
604 if form.attr.type == "cancel" then origin.send(st.reply(stanza)); return; end
605 if form.attr.type ~= "submit" then origin.send(st.error_reply(stanza, "cancel", "bad-request", "Not a submitted form")); return; end
607 local fields = self:get_form_layout():data(form);
608 if fields.FORM_TYPE ~= "http://jabber.org/protocol/muc#roomconfig" then origin.send(st.error_reply(stanza, "cancel", "bad-request", "Form is not of type room configuration")); return; end
612 local name = fields['muc#roomconfig_roomname'];
617 local description = fields['muc#roomconfig_roomdesc'];
619 self:set_description(description);
622 local persistent = fields['muc#roomconfig_persistentroom'];
623 dirty = dirty or (self:is_persistent() ~= persistent)
624 module:log("debug", "persistent=%s", tostring(persistent));
626 local moderated = fields['muc#roomconfig_moderatedroom'];
627 dirty = dirty or (self:is_moderated() ~= moderated)
628 module:log("debug", "moderated=%s", tostring(moderated));
630 local membersonly = fields['muc#roomconfig_membersonly'];
631 dirty = dirty or (self:is_members_only() ~= membersonly)
632 module:log("debug", "membersonly=%s", tostring(membersonly));
634 local public = fields['muc#roomconfig_publicroom'];
635 dirty = dirty or (self:is_hidden() ~= (not public and true or nil))
637 local whois = fields['muc#roomconfig_whois'];
638 if not valid_whois[whois] then
639 origin.send(st.error_reply(stanza, 'cancel', 'bad-request', "Invalid value for 'whois'"));
642 local whois_changed = self._data.whois ~= whois
643 self._data.whois = whois
644 module:log('debug', 'whois=%s', whois)
646 local password = fields['muc#roomconfig_roomsecret'];
647 if self:get_password() ~= password then
648 self:set_password(password);
650 self:set_moderated(moderated);
651 self:set_members_only(membersonly);
652 self:set_persistent(persistent);
653 self:set_hidden(not public);
655 if self.save then self:save(true); end
656 origin.send(st.reply(stanza));
658 if dirty or whois_changed then
659 local msg = st.message({type='groupchat', from=self.jid})
660 :tag('x', {xmlns='http://jabber.org/protocol/muc#user'}):up()
663 msg.tags[1]:tag('status', {code = '104'}):up();
665 if whois_changed then
666 local code = (whois == 'moderators') and "173" or "172";
667 msg.tags[1]:tag('status', {code = code}):up();
670 self:broadcast_message(msg, false)
674 function room_mt:destroy(newjid, reason, password)
675 local pr = st.presence({type = "unavailable"})
676 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
677 :tag("item", { affiliation='none', role='none' }):up()
678 :tag("destroy", {jid=newjid})
679 if reason then pr:tag("reason"):text(reason):up(); end
680 if password then pr:tag("password"):text(password):up(); end
681 for nick, occupant in pairs(self._occupants) do
683 for jid in pairs(occupant.sessions) do
685 self:_route_stanza(pr);
686 self._jid_nick[jid] = nil;
688 self._occupants[nick] = nil;
690 self:set_persistent(false);
693 function room_mt:handle_to_room(origin, stanza) -- presence changes and groupchat messages, along with disco/etc
694 local type = stanza.attr.type;
695 local xmlns = stanza.tags[1] and stanza.tags[1].attr.xmlns;
696 if stanza.name == "iq" then
697 if xmlns == "http://jabber.org/protocol/disco#info" and type == "get" then
698 origin.send(self:get_disco_info(stanza));
699 elseif xmlns == "http://jabber.org/protocol/disco#items" and type == "get" then
700 origin.send(self:get_disco_items(stanza));
701 elseif xmlns == "http://jabber.org/protocol/muc#admin" then
702 local actor = stanza.attr.from;
703 local affiliation = self:get_affiliation(actor);
704 local current_nick = self._jid_nick[actor];
705 local role = current_nick and self._occupants[current_nick].role or self:get_default_role(affiliation);
706 local item = stanza.tags[1].tags[1];
707 if item and item.name == "item" then
708 if type == "set" then
709 local callback = function() origin.send(st.reply(stanza)); end
710 if item.attr.jid then -- Validate provided JID
711 item.attr.jid = jid_prep(item.attr.jid);
712 if not item.attr.jid then
713 origin.send(st.error_reply(stanza, "modify", "jid-malformed"));
717 if not item.attr.jid and item.attr.nick then -- COMPAT Workaround for Miranda sending 'nick' instead of 'jid' when changing affiliation
718 local occupant = self._occupants[self.jid.."/"..item.attr.nick];
719 if occupant then item.attr.jid = occupant.jid; end
720 elseif not item.attr.nick and item.attr.jid then
721 local nick = self._jid_nick[item.attr.jid];
722 if nick then item.attr.nick = select(3, jid_split(nick)); end
724 local reason = item.tags[1] and item.tags[1].name == "reason" and #item.tags[1] == 1 and item.tags[1][1];
725 if item.attr.affiliation and item.attr.jid and not item.attr.role then
726 local success, errtype, err = self:set_affiliation(actor, item.attr.jid, item.attr.affiliation, callback, reason);
727 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
728 elseif item.attr.role and item.attr.nick and not item.attr.affiliation then
729 local success, errtype, err = self:set_role(actor, self.jid.."/"..item.attr.nick, item.attr.role, callback, reason);
730 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
732 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
734 elseif type == "get" then
735 local _aff = item.attr.affiliation;
736 local _rol = item.attr.role;
737 if _aff and not _rol then
738 if affiliation == "owner" or (affiliation == "admin" and _aff ~= "owner" and _aff ~= "admin") then
739 local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
740 for jid, affiliation in pairs(self._affiliations) do
741 if affiliation == _aff then
742 reply:tag("item", {affiliation = _aff, jid = jid}):up();
747 origin.send(st.error_reply(stanza, "auth", "forbidden"));
749 elseif _rol and not _aff then
750 if role == "moderator" then
751 -- TODO allow admins and owners not in room? Provide read-only access to everyone who can see the participants anyway?
752 if _rol == "none" then _rol = nil; end
753 local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
754 for occupant_jid, occupant in pairs(self._occupants) do
755 if occupant.role == _rol then
757 nick = select(3, jid_split(occupant_jid)),
758 role = _rol or "none",
759 affiliation = occupant.affiliation or "none",
766 origin.send(st.error_reply(stanza, "auth", "forbidden"));
769 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
772 elseif type == "set" or type == "get" then
773 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
775 elseif xmlns == "http://jabber.org/protocol/muc#owner" and (type == "get" or type == "set") and stanza.tags[1].name == "query" then
776 if self:get_affiliation(stanza.attr.from) ~= "owner" then
777 origin.send(st.error_reply(stanza, "auth", "forbidden"));
778 elseif stanza.attr.type == "get" then
779 self:send_form(origin, stanza);
780 elseif stanza.attr.type == "set" then
781 local child = stanza.tags[1].tags[1];
783 origin.send(st.error_reply(stanza, "auth", "bad-request"));
784 elseif child.name == "destroy" then
785 local newjid = child.attr.jid;
786 local reason, password;
787 for _,tag in ipairs(child.tags) do
788 if tag.name == "reason" then
789 reason = #tag.tags == 0 and tag[1];
790 elseif tag.name == "password" then
791 password = #tag.tags == 0 and tag[1];
794 self:destroy(newjid, reason, password);
795 origin.send(st.reply(stanza));
797 self:process_form(origin, stanza);
800 elseif type == "set" or type == "get" then
801 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
803 elseif stanza.name == "message" and type == "groupchat" then
804 local from, to = stanza.attr.from, stanza.attr.to;
805 local room = jid_bare(to);
806 local current_nick = self._jid_nick[from];
807 local occupant = self._occupants[current_nick];
808 if not occupant then -- not in room
809 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
810 elseif occupant.role == "visitor" then
811 origin.send(st.error_reply(stanza, "cancel", "forbidden"));
813 local from = stanza.attr.from;
814 stanza.attr.from = current_nick;
815 local subject = getText(stanza, {"subject"});
817 if occupant.role == "moderator" then
818 self:set_subject(current_nick, subject); -- TODO use broadcast_message_stanza
820 stanza.attr.from = from;
821 origin.send(st.error_reply(stanza, "cancel", "forbidden"));
824 self:broadcast_message(stanza, true);
826 stanza.attr.from = from;
828 elseif stanza.name == "message" and type == "error" and is_kickable_error(stanza) then
829 local current_nick = self._jid_nick[stanza.attr.from];
830 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
831 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza)); -- send unavailable
832 elseif stanza.name == "presence" then -- hack - some buggy clients send presence updates to the room rather than their nick
833 local to = stanza.attr.to;
834 local current_nick = self._jid_nick[stanza.attr.from];
836 stanza.attr.to = current_nick;
837 self:handle_to_occupant(origin, stanza);
839 elseif type ~= "error" and type ~= "result" then
840 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
842 elseif stanza.name == "message" and not stanza.attr.type and #stanza.tags == 1 and self._jid_nick[stanza.attr.from]
843 and stanza.tags[1].name == "x" and stanza.tags[1].attr.xmlns == "http://jabber.org/protocol/muc#user" then
844 local x = stanza.tags[1];
845 local payload = (#x.tags == 1 and x.tags[1]);
846 if payload and payload.name == "invite" and payload.attr.to then
847 local _from, _to = stanza.attr.from, stanza.attr.to;
848 local _invitee = jid_prep(payload.attr.to);
850 local _reason = payload.tags[1] and payload.tags[1].name == 'reason' and #payload.tags[1].tags == 0 and payload.tags[1][1];
851 local invite = st.message({from = _to, to = _invitee, id = stanza.attr.id})
852 :tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
853 :tag('invite', {from=_from})
854 :tag('reason'):text(_reason or ""):up()
856 if self:get_password() then
857 invite:tag("password"):text(self:get_password()):up();
860 :tag('x', {xmlns="jabber:x:conference", jid=_to}) -- COMPAT: Some older clients expect this
863 :tag('body') -- Add a plain message for clients which don't support invites
864 :text(_from..' invited you to the room '.._to..(_reason and (' ('.._reason..')') or ""))
866 self:_route_stanza(invite);
868 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
871 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
874 if type == "error" or type == "result" then return; end
875 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
879 function room_mt:handle_stanza(origin, stanza)
880 local to_node, to_host, to_resource = jid_split(stanza.attr.to);
882 self:handle_to_occupant(origin, stanza);
884 self:handle_to_room(origin, stanza);
888 function room_mt:route_stanza(stanza) end -- Replace with a routing function, e.g., function(room, stanza) core_route_stanza(origin, stanza); end
890 function room_mt:get_affiliation(jid)
891 local node, host, resource = jid_split(jid);
892 local bare = node and node.."@"..host or host;
893 local result = self._affiliations[bare]; -- Affiliations are granted, revoked, and maintained based on the user's bare JID.
894 if not result and self._affiliations[host] == "outcast" then result = "outcast"; end -- host banned
897 function room_mt:set_affiliation(actor, jid, affiliation, callback, reason)
899 if affiliation == "none" then affiliation = nil; end
900 if affiliation and affiliation ~= "outcast" and affiliation ~= "owner" and affiliation ~= "admin" and affiliation ~= "member" then
901 return nil, "modify", "not-acceptable";
903 if self:get_affiliation(actor) ~= "owner" then return nil, "cancel", "not-allowed"; end
904 if jid_bare(actor) == jid then return nil, "cancel", "not-allowed"; end
905 self._affiliations[jid] = affiliation;
906 local role = self:get_default_role(affiliation);
907 local p = st.presence()
908 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
909 :tag("item", {affiliation=affiliation or "none", role=role or "none"})
910 :tag("reason"):text(reason or ""):up()
913 local item = x.tags[1];
914 if not role then -- getting kicked
915 p.attr.type = "unavailable";
916 if affiliation == "outcast" then
917 x:tag("status", {code="301"}):up(); -- banned
919 x:tag("status", {code="321"}):up(); -- affiliation change
922 local modified_nicks = {};
923 for nick, occupant in pairs(self._occupants) do
924 if jid_bare(occupant.jid) == jid then
925 t_insert(modified_nicks, nick);
926 if not role then -- getting kicked
927 self._occupants[nick] = nil;
929 occupant.affiliation, occupant.role = affiliation, role;
932 for jid in pairs(occupant.sessions) do -- remove for all sessions of the nick
933 if not role then self._jid_nick[jid] = nil; end
935 self:_route_stanza(p);
939 if self.save then self:save(); end
940 if callback then callback(); end
941 for _, nick in ipairs(modified_nicks) do
943 self:broadcast_except_nick(p, nick);
948 function room_mt:get_role(nick)
949 local session = self._occupants[nick];
950 return session and session.role or nil;
952 function room_mt:can_set_role(actor_jid, occupant_jid, role)
953 local actor = self._occupants[self._jid_nick[actor_jid]];
954 local occupant = self._occupants[occupant_jid];
956 if not occupant or not actor then return nil, "modify", "not-acceptable"; end
958 if actor.role == "moderator" then
959 if occupant.affiliation ~= "owner" and occupant.affiliation ~= "admin" then
960 if actor.affiliation == "owner" or actor.affiliation == "admin" then
962 elseif occupant.role ~= "moderator" and role ~= "moderator" then
967 return nil, "cancel", "not-allowed";
969 function room_mt:set_role(actor, occupant_jid, role, callback, reason)
970 if role == "none" then role = nil; end
971 if role and role ~= "moderator" and role ~= "participant" and role ~= "visitor" then return nil, "modify", "not-acceptable"; end
972 local allowed, err_type, err_condition = self:can_set_role(actor, occupant_jid, role);
973 if not allowed then return allowed, err_type, err_condition; end
974 local occupant = self._occupants[occupant_jid];
975 local p = st.presence({from = occupant_jid})
976 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
977 :tag("item", {affiliation=occupant.affiliation or "none", nick=select(3, jid_split(occupant_jid)), role=role or "none"})
978 :tag("reason"):text(reason or ""):up()
980 if not role then -- kick
981 p.attr.type = "unavailable";
982 self._occupants[occupant_jid] = nil;
983 for jid in pairs(occupant.sessions) do -- remove for all sessions of the nick
984 self._jid_nick[jid] = nil;
986 p:tag("status", {code = "307"}):up();
988 occupant.role = role;
990 for jid in pairs(occupant.sessions) do -- send to all sessions of the nick
992 self:_route_stanza(p);
994 if callback then callback(); end
995 self:broadcast_except_nick(p, occupant_jid);
999 function room_mt:_route_stanza(stanza)
1001 local to_occupant = self._occupants[self._jid_nick[stanza.attr.to]];
1002 local from_occupant = self._occupants[stanza.attr.from];
1003 if stanza.name == "presence" then
1004 if to_occupant and from_occupant then
1005 if self._data.whois == 'anyone' then
1006 muc_child = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
1008 if to_occupant.role == "moderator" or jid_bare(to_occupant.jid) == jid_bare(from_occupant.jid) then
1009 muc_child = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
1015 for _, item in pairs(muc_child.tags) do
1016 if item.name == "item" then
1017 if from_occupant == to_occupant then
1018 item.attr.jid = stanza.attr.to;
1020 item.attr.jid = from_occupant.jid;
1024 if self._data.whois == 'anyone' then
1025 muc_child:tag('status', { code = '100' }):up();
1028 self:route_stanza(stanza);
1030 for _, item in pairs(muc_child.tags) do
1031 if item.name == "item" then
1032 item.attr.jid = nil;
1038 local _M = {}; -- module "muc"
1040 function _M.new_room(jid, config)
1041 return setmetatable({
1046 whois = 'moderators';
1047 history_length = (config and config.history_length);