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 datetime = require "util.datetime";
14 local dataform = require "util.dataforms";
16 local jid_split = require "util.jid".split;
17 local jid_bare = require "util.jid".bare;
18 local jid_prep = require "util.jid".prep;
19 local st = require "util.stanza";
20 local log = require "util.logger".init("mod_muc");
21 local t_insert, t_remove = table.insert, table.remove;
22 local setmetatable = setmetatable;
23 local base64 = require "util.encodings".base64;
24 local md5 = require "util.hashes".md5;
26 local muc_domain = nil; --module:get_host();
27 local default_history_length, max_history_length = 20, math.huge;
30 local presence_filters = {["http://jabber.org/protocol/muc"]=true;["http://jabber.org/protocol/muc#user"]=true};
31 local function presence_filter(tag)
32 if presence_filters[tag.attr.xmlns] then
38 local function get_filtered_presence(stanza)
39 return st.clone(stanza):maptags(presence_filter);
41 local kickable_error_conditions = {
43 ["internal-server-error"] = true;
44 ["item-not-found"] = true;
45 ["jid-malformed"] = true;
46 ["recipient-unavailable"] = true;
48 ["remote-server-not-found"] = true;
49 ["remote-server-timeout"] = true;
50 ["service-unavailable"] = true;
51 ["malformed error"] = true;
54 local function get_error_condition(stanza)
55 local _, condition = stanza:get_error();
56 return condition or "malformed error";
59 local function is_kickable_error(stanza)
60 local cond = get_error_condition(stanza);
61 return kickable_error_conditions[cond] and cond;
66 room_mt.__index = room_mt;
68 function room_mt:__tostring()
69 return "MUC room ("..self.jid..")";
72 function room_mt:get_default_role(affiliation)
73 if affiliation == "owner" or affiliation == "admin" then
75 elseif affiliation == "member" then
77 elseif not affiliation then
78 if not self:get_members_only() then
79 return self:get_moderated() and "visitor" or "participant";
84 function room_mt:broadcast_presence(stanza, sid, code, nick)
85 stanza = get_filtered_presence(stanza);
86 local occupant = self._occupants[stanza.attr.from];
87 stanza:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
88 :tag("item", {affiliation=occupant.affiliation or "none", role=occupant.role or "none", nick=nick}):up();
90 stanza:tag("status", {code=code}):up();
92 self:broadcast_except_nick(stanza, stanza.attr.from);
93 local me = self._occupants[stanza.attr.from];
95 stanza:tag("status", {code='110'}):up();
97 self:_route_stanza(stanza);
100 function room_mt:broadcast_message(stanza, historic)
101 local to = stanza.attr.to;
102 for occupant, o_data in pairs(self._occupants) do
103 for jid in pairs(o_data.sessions) do
104 stanza.attr.to = jid;
105 self:_route_stanza(stanza);
109 if historic then -- add to history
110 return self:save_to_history(stanza)
113 function room_mt:save_to_history(stanza)
114 local history = self._data['history'];
115 if not history then history = {}; self._data['history'] = history; end
116 stanza = st.clone(stanza);
118 local stamp = datetime.datetime();
119 stanza:tag("delay", {xmlns = "urn:xmpp:delay", from = muc_domain, stamp = stamp}):up(); -- XEP-0203
120 stanza:tag("x", {xmlns = "jabber:x:delay", from = muc_domain, stamp = datetime.legacy()}):up(); -- XEP-0091 (deprecated)
121 local entry = { stanza = stanza, stamp = stamp };
122 t_insert(history, entry);
123 while #history > (self._data.history_length or default_history_length) do t_remove(history, 1) end
125 function room_mt:broadcast_except_nick(stanza, nick)
126 for rnick, occupant in pairs(self._occupants) do
127 if rnick ~= nick then
128 for jid in pairs(occupant.sessions) do
129 stanza.attr.to = jid;
130 self:_route_stanza(stanza);
136 function room_mt:send_occupant_list(to)
137 local current_nick = self._jid_nick[to];
138 for occupant, o_data in pairs(self._occupants) do
139 if occupant ~= current_nick then
140 local pres = get_filtered_presence(o_data.sessions[o_data.jid]);
141 pres.attr.to, pres.attr.from = to, occupant;
142 pres:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
143 :tag("item", {affiliation=o_data.affiliation or "none", role=o_data.role or "none"}):up();
144 self:_route_stanza(pres);
148 function room_mt:send_history(to, stanza)
149 local history = self._data['history']; -- send discussion history
151 local x_tag = stanza and stanza:get_child("x", "http://jabber.org/protocol/muc");
152 local history_tag = x_tag and x_tag:get_child("history", "http://jabber.org/protocol/muc");
154 local maxchars = history_tag and tonumber(history_tag.attr.maxchars);
155 if maxchars then maxchars = math.floor(maxchars); end
157 local maxstanzas = math.floor(history_tag and tonumber(history_tag.attr.maxstanzas) or #history);
158 if not history_tag then maxstanzas = 20; end
160 local seconds = history_tag and tonumber(history_tag.attr.seconds);
161 if seconds then seconds = datetime.datetime(os.time() - math.floor(seconds)); end
163 local since = history_tag and history_tag.attr.since;
164 if since then since = datetime.parse(since); since = since and datetime.datetime(since); end
165 if seconds and (not since or since < seconds) then since = seconds; end
170 for i=#history,1,-1 do
171 local entry = history[i];
173 if not entry.chars then
174 entry.stanza.attr.to = "";
175 entry.chars = #tostring(entry.stanza);
177 charcount = charcount + entry.chars + #to;
178 if charcount > maxchars then break; end
180 if since and since > entry.stamp then break; end
181 if n + 1 > maxstanzas then break; end
184 for i=#history-n+1,#history do
185 local msg = history[i].stanza;
187 self:_route_stanza(msg);
191 function room_mt:send_subject(to)
192 if self._data['subject'] then
193 self:_route_stanza(st.message({type='groupchat', from=self._data['subject_from'] or self.jid, to=to}):tag("subject"):text(self._data['subject']));
197 function room_mt:get_disco_info(stanza)
198 local count = 0; for _ in pairs(self._occupants) do count = count + 1; end
199 return st.reply(stanza):query("http://jabber.org/protocol/disco#info")
200 :tag("identity", {category="conference", type="text", name=self:get_name()}):up()
201 :tag("feature", {var="http://jabber.org/protocol/muc"}):up()
202 :tag("feature", {var=self:get_password() and "muc_passwordprotected" or "muc_unsecured"}):up()
203 :tag("feature", {var=self:get_moderated() and "muc_moderated" or "muc_unmoderated"}):up()
204 :tag("feature", {var=self:get_members_only() and "muc_membersonly" or "muc_open"}):up()
205 :tag("feature", {var=self:get_persistent() and "muc_persistent" or "muc_temporary"}):up()
206 :tag("feature", {var=self:get_hidden() and "muc_hidden" or "muc_public"}):up()
207 :tag("feature", {var=self._data.whois ~= "anyone" and "muc_semianonymous" or "muc_nonanonymous"}):up()
208 :add_child(dataform.new({
209 { name = "FORM_TYPE", type = "hidden", value = "http://jabber.org/protocol/muc#roominfo" },
210 { name = "muc#roominfo_description", label = "Description", value = "" },
211 { name = "muc#roominfo_occupants", label = "Number of occupants", value = tostring(count) }
212 }):form({["muc#roominfo_description"] = self:get_description()}, 'result'))
215 function room_mt:get_disco_items(stanza)
216 local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#items");
217 for room_jid in pairs(self._occupants) do
218 reply:tag("item", {jid = room_jid, name = room_jid:match("/(.*)")}):up();
222 function room_mt:set_subject(current_nick, subject)
223 if subject == "" then subject = nil; end
224 self._data['subject'] = subject;
225 self._data['subject_from'] = current_nick;
226 if self.save then self:save(); end
227 local msg = st.message({type='groupchat', from=current_nick})
228 :tag('subject'):text(subject):up();
229 self:broadcast_message(msg, false);
233 local function build_unavailable_presence_from_error(stanza)
234 local type, condition, text = stanza:get_error();
235 local error_message = "Kicked: "..(condition and condition:gsub("%-", " ") or "presence error");
237 error_message = error_message..": "..text;
239 return st.presence({type='unavailable', from=stanza.attr.from, to=stanza.attr.to})
240 :tag('status'):text(error_message);
243 function room_mt:set_name(name)
244 if name == "" or type(name) ~= "string" or name == (jid_split(self.jid)) then name = nil; end
245 if self._data.name ~= name then
246 self._data.name = name;
247 if self.save then self:save(true); end
250 function room_mt:get_name()
251 return self._data.name or jid_split(self.jid);
253 function room_mt:set_description(description)
254 if description == "" or type(description) ~= "string" then description = nil; end
255 if self._data.description ~= description then
256 self._data.description = description;
257 if self.save then self:save(true); end
260 function room_mt:get_description()
261 return self._data.description;
263 function room_mt:set_password(password)
264 if password == "" or type(password) ~= "string" then password = nil; end
265 if self._data.password ~= password then
266 self._data.password = password;
267 if self.save then self:save(true); end
270 function room_mt:get_password()
271 return self._data.password;
273 function room_mt:set_moderated(moderated)
274 moderated = moderated and true or nil;
275 if self._data.moderated ~= moderated then
276 self._data.moderated = moderated;
277 if self.save then self:save(true); end
280 function room_mt:get_moderated()
281 return self._data.moderated;
283 function room_mt:set_members_only(members_only)
284 members_only = members_only and true or nil;
285 if self._data.members_only ~= members_only then
286 self._data.members_only = members_only;
287 if self.save then self:save(true); end
290 function room_mt:get_members_only()
291 return self._data.members_only;
293 function room_mt:set_persistent(persistent)
294 persistent = persistent and true or nil;
295 if self._data.persistent ~= persistent then
296 self._data.persistent = persistent;
297 if self.save then self:save(true); end
300 function room_mt:get_persistent()
301 return self._data.persistent;
303 function room_mt:set_hidden(hidden)
304 hidden = hidden and true or nil;
305 if self._data.hidden ~= hidden then
306 self._data.hidden = hidden;
307 if self.save then self:save(true); end
310 function room_mt:get_hidden()
311 return self._data.hidden;
313 function room_mt:get_public()
314 return not self:get_hidden();
316 function room_mt:set_public(public)
317 return self:set_hidden(not public);
319 function room_mt:set_changesubject(changesubject)
320 changesubject = changesubject and true or nil;
321 if self._data.changesubject ~= changesubject then
322 self._data.changesubject = changesubject;
323 if self.save then self:save(true); end
326 function room_mt:get_changesubject()
327 return self._data.changesubject;
329 function room_mt:get_historylength()
330 return self._data.history_length or default_history_length;
332 function room_mt:set_historylength(length)
333 length = math.min(tonumber(length) or default_history_length, max_history_length or math.huge);
334 if length == default_history_length then
337 self._data.history_length = length;
341 local valid_whois = { moderators = true, anyone = true };
343 function room_mt:set_whois(whois)
344 if valid_whois[whois] and self._data.whois ~= whois then
345 self._data.whois = whois;
346 if self.save then self:save(true); end
350 function room_mt:get_whois()
351 return self._data.whois;
354 local function construct_stanza_id(room, stanza)
355 local from_jid, to_nick = stanza.attr.from, stanza.attr.to;
356 local from_nick = room._jid_nick[from_jid];
357 local occupant = room._occupants[to_nick];
358 local to_jid = occupant.jid;
360 return from_nick, to_jid, base64.encode(to_jid.."\0"..stanza.attr.id.."\0"..md5(from_jid));
362 local function deconstruct_stanza_id(room, stanza)
363 local from_jid_possiblybare, to_nick = stanza.attr.from, stanza.attr.to;
364 local from_jid, id, to_jid_hash = (base64.decode(stanza.attr.id) or ""):match("^(.+)%z(.*)%z(.+)$");
365 local from_nick = room._jid_nick[from_jid];
367 if not(from_nick) then return; end
368 if not(from_jid_possiblybare == from_jid or from_jid_possiblybare == jid_bare(from_jid)) then return; end
370 local occupant = room._occupants[to_nick];
371 for to_jid in pairs(occupant and occupant.sessions or {}) do
372 if md5(to_jid) == to_jid_hash then
373 return from_nick, to_jid, id;
379 function room_mt:handle_to_occupant(origin, stanza) -- PM, vCards, etc
380 local from, to = stanza.attr.from, stanza.attr.to;
381 local room = jid_bare(to);
382 local current_nick = self._jid_nick[from];
383 local type = stanza.attr.type;
384 log("debug", "room: %s, current_nick: %s, stanza: %s", room or "nil", current_nick or "nil", stanza:top_tag());
385 if (select(2, jid_split(from)) == muc_domain) then error("Presence from the MUC itself!!!"); end
386 if stanza.name == "presence" then
387 local pr = get_filtered_presence(stanza);
388 pr.attr.from = current_nick;
389 if type == "error" then -- error, kick em out!
391 log("debug", "kicking %s from %s", current_nick, room);
392 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza));
394 elseif type == "unavailable" then -- unavailable
396 log("debug", "%s leaving %s", current_nick, room);
397 self._jid_nick[from] = nil;
398 local occupant = self._occupants[current_nick];
399 local new_jid = next(occupant.sessions);
400 if new_jid == from then new_jid = next(occupant.sessions, new_jid); end
402 local jid = occupant.jid;
403 occupant.jid = new_jid;
404 occupant.sessions[from] = nil;
406 pr:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
407 :tag("item", {affiliation=occupant.affiliation or "none", role='none'}):up()
408 :tag("status", {code='110'}):up();
409 self:_route_stanza(pr);
410 if jid ~= new_jid then
411 pr = st.clone(occupant.sessions[new_jid])
412 :tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
413 :tag("item", {affiliation=occupant.affiliation or "none", role=occupant.role or "none"});
414 pr.attr.from = current_nick;
415 self:broadcast_except_nick(pr, current_nick);
418 occupant.role = 'none';
419 self:broadcast_presence(pr, from);
420 self._occupants[current_nick] = nil;
423 elseif not type then -- available
425 --if #pr == #stanza or current_nick ~= to then -- commented because google keeps resending directed presence
426 if current_nick == to then -- simple presence
427 log("debug", "%s broadcasted presence", current_nick);
428 self._occupants[current_nick].sessions[from] = pr;
429 self:broadcast_presence(pr, from);
431 local occupant = self._occupants[current_nick];
432 local is_multisession = next(occupant.sessions, next(occupant.sessions));
433 if self._occupants[to] or is_multisession then
434 log("debug", "%s couldn't change nick", current_nick);
435 local reply = st.error_reply(stanza, "cancel", "conflict"):up();
436 reply.tags[1].attr.code = "409";
437 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
439 local data = self._occupants[current_nick];
440 local to_nick = select(3, jid_split(to));
442 log("debug", "%s (%s) changing nick to %s", current_nick, data.jid, to);
443 local p = st.presence({type='unavailable', from=current_nick});
444 self:broadcast_presence(p, from, '303', to_nick);
445 self._occupants[current_nick] = nil;
446 self._occupants[to] = data;
447 self._jid_nick[from] = to;
449 self._occupants[to].sessions[from] = pr;
450 self:broadcast_presence(pr, from);
456 --else -- possible rejoin
457 -- log("debug", "%s had connection replaced", current_nick);
458 -- self:handle_to_occupant(origin, st.presence({type='unavailable', from=from, to=to})
459 -- :tag('status'):text('Replaced by new connection'):up()); -- send unavailable
460 -- self:handle_to_occupant(origin, stanza); -- resend available
465 if self._occupants[to] then
466 if jid_bare(from) ~= jid_bare(self._occupants[to].jid) then
471 local password = stanza:get_child("x", "http://jabber.org/protocol/muc");
472 password = password and password:get_child("password", "http://jabber.org/protocol/muc");
473 password = password and password[1] ~= "" and password[1];
474 if self:get_password() and self:get_password() ~= password then
475 log("debug", "%s couldn't join due to invalid password: %s", from, to);
476 local reply = st.error_reply(stanza, "auth", "not-authorized"):up();
477 reply.tags[1].attr.code = "401";
478 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
479 elseif not new_nick then
480 log("debug", "%s couldn't join due to nick conflict: %s", from, to);
481 local reply = st.error_reply(stanza, "cancel", "conflict"):up();
482 reply.tags[1].attr.code = "409";
483 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
485 log("debug", "%s joining as %s", from, to);
486 if not next(self._affiliations) then -- new room, no owners
487 self._affiliations[jid_bare(from)] = "owner";
488 if self.locked and not stanza:get_child("x", "http://jabber.org/protocol/muc") then
489 self.locked = nil; -- Older groupchat protocol doesn't lock
491 elseif self.locked then -- Deny entry
492 origin.send(st.error_reply(stanza, "cancel", "item-not-found"));
495 local affiliation = self:get_affiliation(from);
496 local role = self:get_default_role(affiliation)
497 if role then -- new occupant
499 self._occupants[to] = {affiliation=affiliation, role=role, jid=from, sessions={[from]=get_filtered_presence(stanza)}};
501 self._occupants[to].sessions[from] = get_filtered_presence(stanza);
503 self._jid_nick[from] = to;
504 self:send_occupant_list(from);
506 pr:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
507 :tag("item", {affiliation=affiliation or "none", role=role or "none"}):up();
509 self:broadcast_except_nick(pr, to);
511 pr:tag("status", {code='110'}):up();
512 if self._data.whois == 'anyone' then
513 pr:tag("status", {code='100'}):up();
516 pr:tag("status", {code='201'}):up();
519 self:_route_stanza(pr);
520 self:send_history(from, stanza);
521 self:send_subject(from);
522 elseif not affiliation then -- registration required for entering members-only room
523 local reply = st.error_reply(stanza, "auth", "registration-required"):up();
524 reply.tags[1].attr.code = "407";
525 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
527 local reply = st.error_reply(stanza, "auth", "forbidden"):up();
528 reply.tags[1].attr.code = "403";
529 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
533 elseif type ~= 'result' then -- bad type
534 if type ~= 'visible' and type ~= 'invisible' then -- COMPAT ejabberd can broadcast or forward XEP-0018 presences
535 origin.send(st.error_reply(stanza, "modify", "bad-request")); -- FIXME correct error?
538 elseif not current_nick then -- not in room
539 if (type == "error" or type == "result") and stanza.name == "iq" then
540 local id = stanza.attr.id;
541 stanza.attr.from, stanza.attr.to, stanza.attr.id = deconstruct_stanza_id(self, stanza);
542 if stanza.attr.id then
543 self:_route_stanza(stanza);
545 stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
546 elseif type ~= "error" then
547 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
549 elseif stanza.name == "message" and type == "groupchat" then -- groupchat messages not allowed in PM
550 origin.send(st.error_reply(stanza, "modify", "bad-request"));
551 elseif current_nick and stanza.name == "message" and type == "error" and is_kickable_error(stanza) then
552 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
553 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza)); -- send unavailable
554 else -- private stanza
555 local o_data = self._occupants[to];
557 log("debug", "%s sent private stanza to %s (%s)", from, to, o_data.jid);
558 if stanza.name == "iq" then
559 local id = stanza.attr.id;
560 if stanza.attr.type == "get" or stanza.attr.type == "set" then
561 stanza.attr.from, stanza.attr.to, stanza.attr.id = construct_stanza_id(self, stanza);
563 stanza.attr.from, stanza.attr.to, stanza.attr.id = deconstruct_stanza_id(self, stanza);
565 if type == 'get' and stanza.tags[1].attr.xmlns == 'vcard-temp' then
566 stanza.attr.to = jid_bare(stanza.attr.to);
568 if stanza.attr.id then
569 self:_route_stanza(stanza);
571 stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
573 stanza:tag("x", { xmlns = "http://jabber.org/protocol/muc#user" }):up();
574 stanza.attr.from = current_nick;
575 for jid in pairs(o_data.sessions) do
576 stanza.attr.to = jid;
577 self:_route_stanza(stanza);
579 stanza.attr.from, stanza.attr.to = from, to;
581 elseif type ~= "error" and type ~= "result" then -- recipient not in room
582 origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
587 function room_mt:send_form(origin, stanza)
588 origin.send(st.reply(stanza):query("http://jabber.org/protocol/muc#owner")
589 :add_child(self:get_form_layout(stanza.attr.from):form())
593 function room_mt:get_form_layout(actor)
594 local form = dataform.new({
595 title = "Configuration for "..self.jid,
596 instructions = "Complete and submit this form to configure the room.",
600 value = 'http://jabber.org/protocol/muc#roomconfig'
603 name = 'muc#roomconfig_roomname',
604 type = 'text-single',
606 value = self:get_name() or "",
609 name = 'muc#roomconfig_roomdesc',
610 type = 'text-single',
611 label = 'Description',
612 value = self:get_description() or "",
615 name = 'muc#roomconfig_persistentroom',
617 label = 'Make Room Persistent?',
618 value = self:get_persistent()
621 name = 'muc#roomconfig_publicroom',
623 label = 'Make Room Publicly Searchable?',
624 value = not self:get_hidden()
627 name = 'muc#roomconfig_changesubject',
629 label = 'Allow Occupants to Change Subject?',
630 value = self:get_changesubject()
633 name = 'muc#roomconfig_whois',
634 type = 'list-single',
635 label = 'Who May Discover Real JIDs?',
637 { value = 'moderators', label = 'Moderators Only', default = self._data.whois == 'moderators' },
638 { value = 'anyone', label = 'Anyone', default = self._data.whois == 'anyone' }
642 name = 'muc#roomconfig_roomsecret',
643 type = 'text-private',
645 value = self:get_password() or "",
648 name = 'muc#roomconfig_moderatedroom',
650 label = 'Make Room Moderated?',
651 value = self:get_moderated()
654 name = 'muc#roomconfig_membersonly',
656 label = 'Make Room Members-Only?',
657 value = self:get_members_only()
660 name = 'muc#roomconfig_historylength',
661 type = 'text-single',
662 label = 'Maximum Number of History Messages Returned by Room',
663 value = tostring(self:get_historylength())
666 return module:fire_event("muc-config-form", { room = self, actor = actor, form = form }) or form;
669 function room_mt:process_form(origin, stanza)
670 local query = stanza.tags[1];
672 for _, tag in ipairs(query.tags) do if tag.name == "x" and tag.attr.xmlns == "jabber:x:data" then form = tag; break; end end
673 if not form then origin.send(st.error_reply(stanza, "cancel", "service-unavailable")); return; end
674 if form.attr.type == "cancel" then origin.send(st.reply(stanza)); return; end
675 if form.attr.type ~= "submit" then origin.send(st.error_reply(stanza, "cancel", "bad-request", "Not a submitted form")); return; end
677 local fields = self:get_form_layout(stanza.attr.from):data(form);
678 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
683 local function handle_option(name, field, allowed)
684 local new = fields[field];
685 if new == nil then return; end
686 if allowed and not allowed[new] then return; end
687 if new == self["get_"..name](self) then return; end
688 changed[name] = true;
689 self["set_"..name](self, new);
692 local event = { room = self, fields = fields, changed = changed, stanza = stanza, origin = origin, update_option = handle_option };
693 module:fire_event("muc-config-submitted", event);
695 handle_option("name", "muc#roomconfig_roomname");
696 handle_option("description", "muc#roomconfig_roomdesc");
697 handle_option("persistent", "muc#roomconfig_persistentroom");
698 handle_option("moderated", "muc#roomconfig_moderatedroom");
699 handle_option("members_only", "muc#roomconfig_membersonly");
700 handle_option("public", "muc#roomconfig_publicroom");
701 handle_option("changesubject", "muc#roomconfig_changesubject");
702 handle_option("historylength", "muc#roomconfig_historylength");
703 handle_option("whois", "muc#roomconfig_whois", valid_whois);
704 handle_option("password", "muc#roomconfig_roomsecret");
706 if self.save then self:save(true); end
708 module:fire_event("muc-room-unlocked", { room = self });
711 origin.send(st.reply(stanza));
713 if next(changed) then
714 local msg = st.message({type='groupchat', from=self.jid})
715 :tag('x', {xmlns='http://jabber.org/protocol/muc#user'}):up()
716 :tag('status', {code = '104'}):up();
717 if changed.whois then
718 local code = (self:get_whois() == 'moderators') and "173" or "172";
719 msg.tags[1]:tag('status', {code = code}):up();
721 self:broadcast_message(msg, false)
725 function room_mt:destroy(newjid, reason, password)
726 local pr = st.presence({type = "unavailable"})
727 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
728 :tag("item", { affiliation='none', role='none' }):up()
729 :tag("destroy", {jid=newjid})
730 if reason then pr:tag("reason"):text(reason):up(); end
731 if password then pr:tag("password"):text(password):up(); end
732 for nick, occupant in pairs(self._occupants) do
734 for jid in pairs(occupant.sessions) do
736 self:_route_stanza(pr);
737 self._jid_nick[jid] = nil;
739 self._occupants[nick] = nil;
741 self:set_persistent(false);
742 module:fire_event("muc-room-destroyed", { room = self });
745 function room_mt:handle_to_room(origin, stanza) -- presence changes and groupchat messages, along with disco/etc
746 local type = stanza.attr.type;
747 local xmlns = stanza.tags[1] and stanza.tags[1].attr.xmlns;
748 if stanza.name == "iq" then
749 if xmlns == "http://jabber.org/protocol/disco#info" and type == "get" and not stanza.tags[1].attr.node then
750 origin.send(self:get_disco_info(stanza));
751 elseif xmlns == "http://jabber.org/protocol/disco#items" and type == "get" and not stanza.tags[1].attr.node then
752 origin.send(self:get_disco_items(stanza));
753 elseif xmlns == "http://jabber.org/protocol/muc#admin" then
754 local actor = stanza.attr.from;
755 local affiliation = self:get_affiliation(actor);
756 local current_nick = self._jid_nick[actor];
757 local role = current_nick and self._occupants[current_nick].role or self:get_default_role(affiliation);
758 local item = stanza.tags[1].tags[1];
759 if item and item.name == "item" then
760 if type == "set" then
761 local callback = function() origin.send(st.reply(stanza)); end
762 if item.attr.jid then -- Validate provided JID
763 item.attr.jid = jid_prep(item.attr.jid);
764 if not item.attr.jid then
765 origin.send(st.error_reply(stanza, "modify", "jid-malformed"));
769 if not item.attr.jid and item.attr.nick then -- COMPAT Workaround for Miranda sending 'nick' instead of 'jid' when changing affiliation
770 local occupant = self._occupants[self.jid.."/"..item.attr.nick];
771 if occupant then item.attr.jid = occupant.jid; end
772 elseif not item.attr.nick and item.attr.jid then
773 local nick = self._jid_nick[item.attr.jid];
774 if nick then item.attr.nick = select(3, jid_split(nick)); end
776 local reason = item.tags[1] and item.tags[1].name == "reason" and #item.tags[1] == 1 and item.tags[1][1];
777 if item.attr.affiliation and item.attr.jid and not item.attr.role then
778 local success, errtype, err = self:set_affiliation(actor, item.attr.jid, item.attr.affiliation, callback, reason);
779 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
780 elseif item.attr.role and item.attr.nick and not item.attr.affiliation then
781 local success, errtype, err = self:set_role(actor, self.jid.."/"..item.attr.nick, item.attr.role, callback, reason);
782 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
784 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
786 elseif type == "get" then
787 local _aff = item.attr.affiliation;
788 local _rol = item.attr.role;
789 if _aff and not _rol then
790 if affiliation == "owner" or (affiliation == "admin" and _aff ~= "owner" and _aff ~= "admin") then
791 local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
792 for jid, affiliation in pairs(self._affiliations) do
793 if affiliation == _aff then
794 reply:tag("item", {affiliation = _aff, jid = jid}):up();
799 origin.send(st.error_reply(stanza, "auth", "forbidden"));
801 elseif _rol and not _aff then
802 if role == "moderator" then
803 -- TODO allow admins and owners not in room? Provide read-only access to everyone who can see the participants anyway?
804 if _rol == "none" then _rol = nil; end
805 local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
806 for occupant_jid, occupant in pairs(self._occupants) do
807 if occupant.role == _rol then
809 nick = select(3, jid_split(occupant_jid)),
810 role = _rol or "none",
811 affiliation = occupant.affiliation or "none",
818 origin.send(st.error_reply(stanza, "auth", "forbidden"));
821 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
824 elseif type == "set" or type == "get" then
825 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
827 elseif xmlns == "http://jabber.org/protocol/muc#owner" and (type == "get" or type == "set") and stanza.tags[1].name == "query" then
828 if self:get_affiliation(stanza.attr.from) ~= "owner" then
829 origin.send(st.error_reply(stanza, "auth", "forbidden", "Only owners can configure rooms"));
830 elseif stanza.attr.type == "get" then
831 self:send_form(origin, stanza);
832 elseif stanza.attr.type == "set" then
833 local child = stanza.tags[1].tags[1];
835 origin.send(st.error_reply(stanza, "modify", "bad-request"));
836 elseif child.name == "destroy" then
837 local newjid = child.attr.jid;
838 local reason, password;
839 for _,tag in ipairs(child.tags) do
840 if tag.name == "reason" then
841 reason = #tag.tags == 0 and tag[1];
842 elseif tag.name == "password" then
843 password = #tag.tags == 0 and tag[1];
846 self:destroy(newjid, reason, password);
847 origin.send(st.reply(stanza));
849 self:process_form(origin, stanza);
852 elseif type == "set" or type == "get" then
853 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
855 elseif stanza.name == "message" and type == "groupchat" then
856 local from = stanza.attr.from;
857 local current_nick = self._jid_nick[from];
858 local occupant = self._occupants[current_nick];
859 if not occupant then -- not in room
860 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
861 elseif occupant.role == "visitor" then
862 origin.send(st.error_reply(stanza, "auth", "forbidden"));
864 local from = stanza.attr.from;
865 stanza.attr.from = current_nick;
866 local subject = stanza:get_child_text("subject");
868 if occupant.role == "moderator" or
869 ( self._data.changesubject and occupant.role == "participant" ) then -- and participant
870 self:set_subject(current_nick, subject);
872 stanza.attr.from = from;
873 origin.send(st.error_reply(stanza, "auth", "forbidden"));
876 self:broadcast_message(stanza, self:get_historylength() > 0 and stanza:get_child("body"));
878 stanza.attr.from = from;
880 elseif stanza.name == "message" and type == "error" and is_kickable_error(stanza) then
881 local current_nick = self._jid_nick[stanza.attr.from];
882 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
883 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza)); -- send unavailable
884 elseif stanza.name == "presence" then -- hack - some buggy clients send presence updates to the room rather than their nick
885 local to = stanza.attr.to;
886 local current_nick = self._jid_nick[stanza.attr.from];
888 stanza.attr.to = current_nick;
889 self:handle_to_occupant(origin, stanza);
891 elseif type ~= "error" and type ~= "result" then
892 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
894 elseif stanza.name == "message" and not(type == "chat" or type == "error" or type == "groupchat" or type == "headline") and #stanza.tags == 1
895 and self._jid_nick[stanza.attr.from] and stanza.tags[1].name == "x" and stanza.tags[1].attr.xmlns == "http://jabber.org/protocol/muc#user" then
896 local x = stanza.tags[1];
897 local payload = (#x.tags == 1 and x.tags[1]);
898 if payload and payload.name == "invite" and payload.attr.to then
899 local _from, _to = stanza.attr.from, stanza.attr.to;
900 local _invitee = jid_prep(payload.attr.to);
902 local _reason = payload.tags[1] and payload.tags[1].name == 'reason' and #payload.tags[1].tags == 0 and payload.tags[1][1];
903 local invite = st.message({from = _to, to = _invitee, id = stanza.attr.id})
904 :tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
905 :tag('invite', {from=_from})
906 :tag('reason'):text(_reason or ""):up()
908 if self:get_password() then
909 invite:tag("password"):text(self:get_password()):up();
912 :tag('x', {xmlns="jabber:x:conference", jid=_to}) -- COMPAT: Some older clients expect this
915 :tag('body') -- Add a plain message for clients which don't support invites
916 :text(_from..' invited you to the room '.._to..(_reason and (' ('.._reason..')') or ""))
918 if self:get_members_only() and not self:get_affiliation(_invitee) then
919 log("debug", "%s invited %s into members only room %s, granting membership", _from, _invitee, _to);
920 self:set_affiliation(_from, _invitee, "member", nil, "Invited by " .. self._jid_nick[_from])
922 self:_route_stanza(invite);
924 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
927 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
930 if type == "error" or type == "result" then return; end
931 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
935 function room_mt:handle_stanza(origin, stanza)
936 local to_node, to_host, to_resource = jid_split(stanza.attr.to);
938 self:handle_to_occupant(origin, stanza);
940 self:handle_to_room(origin, stanza);
944 function room_mt:route_stanza(stanza) end -- Replace with a routing function, e.g., function(room, stanza) core_route_stanza(origin, stanza); end
946 function room_mt:get_affiliation(jid)
947 local node, host, resource = jid_split(jid);
948 local bare = node and node.."@"..host or host;
949 local result = self._affiliations[bare]; -- Affiliations are granted, revoked, and maintained based on the user's bare JID.
950 if not result and self._affiliations[host] == "outcast" then result = "outcast"; end -- host banned
953 function room_mt:set_affiliation(actor, jid, affiliation, callback, reason)
955 if affiliation == "none" then affiliation = nil; end
956 if affiliation and affiliation ~= "outcast" and affiliation ~= "owner" and affiliation ~= "admin" and affiliation ~= "member" then
957 return nil, "modify", "not-acceptable";
959 if actor ~= true then
960 local actor_affiliation = self:get_affiliation(actor);
961 local target_affiliation = self:get_affiliation(jid);
962 if target_affiliation == affiliation then -- no change, shortcut
963 if callback then callback(); end
966 if actor_affiliation ~= "owner" then
967 if affiliation == "owner" or affiliation == "admin" or actor_affiliation ~= "admin" or target_affiliation == "owner" or target_affiliation == "admin" then
968 return nil, "cancel", "not-allowed";
970 elseif target_affiliation == "owner" and jid_bare(actor) == jid then -- self change
971 local is_last = true;
972 for j, aff in pairs(self._affiliations) do if j ~= jid and aff == "owner" then is_last = false; break; end end
974 return nil, "cancel", "conflict";
978 self._affiliations[jid] = affiliation;
979 local role = self:get_default_role(affiliation);
980 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"})
981 :tag("item", {affiliation=affiliation or "none", role=role or "none"})
982 :tag("reason"):text(reason or ""):up()
984 local presence_type = nil;
985 if not role then -- getting kicked
986 presence_type = "unavailable";
987 if affiliation == "outcast" then
988 x:tag("status", {code="301"}):up(); -- banned
990 x:tag("status", {code="321"}):up(); -- affiliation change
993 local modified_nicks = {};
994 for nick, occupant in pairs(self._occupants) do
995 if jid_bare(occupant.jid) == jid then
996 if not role then -- getting kicked
997 self._occupants[nick] = nil;
999 occupant.affiliation, occupant.role = affiliation, role;
1001 for jid,pres in pairs(occupant.sessions) do -- remove for all sessions of the nick
1002 if not role then self._jid_nick[jid] = nil; end
1003 local p = st.clone(pres);
1005 p.attr.type = presence_type;
1008 self:_route_stanza(p);
1009 if occupant.jid == jid then
1010 modified_nicks[nick] = p;
1015 if self.save then self:save(); end
1016 if callback then callback(); end
1017 for nick,p in pairs(modified_nicks) do
1019 self:broadcast_except_nick(p, nick);
1024 function room_mt:get_role(nick)
1025 local session = self._occupants[nick];
1026 return session and session.role or nil;
1028 function room_mt:can_set_role(actor_jid, occupant_jid, role)
1029 local occupant = self._occupants[occupant_jid];
1030 if not occupant or not actor_jid then return nil, "modify", "not-acceptable"; end
1032 if actor_jid == true then return true; end
1034 local actor = self._occupants[self._jid_nick[actor_jid]];
1035 if actor and actor.role == "moderator" then
1036 if occupant.affiliation ~= "owner" and occupant.affiliation ~= "admin" then
1037 if actor.affiliation == "owner" or actor.affiliation == "admin" then
1039 elseif occupant.role ~= "moderator" and role ~= "moderator" then
1044 return nil, "cancel", "not-allowed";
1046 function room_mt:set_role(actor, occupant_jid, role, callback, reason)
1047 if role == "none" then role = nil; end
1048 if role and role ~= "moderator" and role ~= "participant" and role ~= "visitor" then return nil, "modify", "not-acceptable"; end
1049 local allowed, err_type, err_condition = self:can_set_role(actor, occupant_jid, role);
1050 if not allowed then return allowed, err_type, err_condition; end
1051 local occupant = self._occupants[occupant_jid];
1052 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"})
1053 :tag("item", {affiliation=occupant.affiliation or "none", nick=select(3, jid_split(occupant_jid)), role=role or "none"})
1054 :tag("reason"):text(reason or ""):up()
1056 local presence_type = nil;
1057 if not role then -- kick
1058 presence_type = "unavailable";
1059 self._occupants[occupant_jid] = nil;
1060 for jid in pairs(occupant.sessions) do -- remove for all sessions of the nick
1061 self._jid_nick[jid] = nil;
1063 x:tag("status", {code = "307"}):up();
1065 occupant.role = role;
1068 for jid,pres in pairs(occupant.sessions) do -- send to all sessions of the nick
1069 local p = st.clone(pres);
1070 p.attr.from = occupant_jid;
1071 p.attr.type = presence_type;
1074 self:_route_stanza(p);
1075 if occupant.jid == jid then
1079 if callback then callback(); end
1081 self:broadcast_except_nick(bp, occupant_jid);
1086 function room_mt:_route_stanza(stanza)
1088 local to_occupant = self._occupants[self._jid_nick[stanza.attr.to]];
1089 local from_occupant = self._occupants[stanza.attr.from];
1090 if stanza.name == "presence" then
1091 if to_occupant and from_occupant then
1092 if self._data.whois == 'anyone' then
1093 muc_child = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
1095 if to_occupant.role == "moderator" or jid_bare(to_occupant.jid) == jid_bare(from_occupant.jid) then
1096 muc_child = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
1102 for _, item in pairs(muc_child.tags) do
1103 if item.name == "item" then
1104 if from_occupant == to_occupant then
1105 item.attr.jid = stanza.attr.to;
1107 item.attr.jid = from_occupant.jid;
1112 self:route_stanza(stanza);
1114 for _, item in pairs(muc_child.tags) do
1115 if item.name == "item" then
1116 item.attr.jid = nil;
1122 local _M = {}; -- module "muc"
1124 function _M.new_room(jid, config)
1125 return setmetatable({
1130 whois = 'moderators';
1131 history_length = math.min((config and config.history_length)
1132 or default_history_length, max_history_length);
1138 function _M.set_max_history_length(_max_history_length)
1139 max_history_length = _max_history_length or math.huge;
1142 _M.room_mt = room_mt;