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 function filter_xmlns_from_array(array, filters)
33 local attr = array[i].attr;
34 if filters[attr and attr.xmlns] then
41 local function filter_xmlns_from_stanza(stanza, filters)
43 if filter_xmlns_from_array(stanza.tags, filters) ~= 0 then
44 return stanza, filter_xmlns_from_array(stanza, filters);
49 local presence_filters = {["http://jabber.org/protocol/muc"]=true;["http://jabber.org/protocol/muc#user"]=true};
50 local function get_filtered_presence(stanza)
51 return filter_xmlns_from_stanza(st.clone(stanza):reset(), presence_filters);
53 local kickable_error_conditions = {
55 ["internal-server-error"] = true;
56 ["item-not-found"] = true;
57 ["jid-malformed"] = true;
58 ["recipient-unavailable"] = true;
60 ["remote-server-not-found"] = true;
61 ["remote-server-timeout"] = true;
62 ["service-unavailable"] = true;
63 ["malformed error"] = true;
66 local function get_error_condition(stanza)
67 local _, condition = stanza:get_error();
68 return condition or "malformed error";
71 local function is_kickable_error(stanza)
72 local cond = get_error_condition(stanza);
73 return kickable_error_conditions[cond] and cond;
75 local function getUsingPath(stanza, path, getText)
77 for _, name in ipairs(path) do
78 if type(tag) ~= 'table' then return; end
79 tag = tag:child_with_name(name);
81 if tag and getText then tag = table.concat(tag); end
84 local function getTag(stanza, path) return getUsingPath(stanza, path); end
85 local function getText(stanza, path) return getUsingPath(stanza, path, true); end
89 room_mt.__index = room_mt;
91 function room_mt:__tostring()
92 return "MUC room ("..self.jid..")";
95 function room_mt:get_default_role(affiliation)
96 if affiliation == "owner" or affiliation == "admin" then
98 elseif affiliation == "member" then
100 elseif not affiliation then
101 if not self:is_members_only() then
102 return self:is_moderated() and "visitor" or "participant";
107 function room_mt:broadcast_presence(stanza, sid, code, nick)
108 stanza = get_filtered_presence(stanza);
109 local occupant = self._occupants[stanza.attr.from];
110 stanza:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
111 :tag("item", {affiliation=occupant.affiliation or "none", role=occupant.role or "none", nick=nick}):up();
113 stanza:tag("status", {code=code}):up();
115 self:broadcast_except_nick(stanza, stanza.attr.from);
116 local me = self._occupants[stanza.attr.from];
118 stanza:tag("status", {code='110'}):up();
119 stanza.attr.to = sid;
120 self:_route_stanza(stanza);
123 function room_mt:broadcast_message(stanza, historic)
124 local to = stanza.attr.to;
125 for occupant, o_data in pairs(self._occupants) do
126 for jid in pairs(o_data.sessions) do
127 stanza.attr.to = jid;
128 self:_route_stanza(stanza);
132 if historic then -- add to history
133 local history = self._data['history'];
134 if not history then history = {}; self._data['history'] = history; end
135 stanza = st.clone(stanza);
137 local stamp = datetime.datetime();
138 stanza:tag("delay", {xmlns = "urn:xmpp:delay", from = muc_domain, stamp = stamp}):up(); -- XEP-0203
139 stanza:tag("x", {xmlns = "jabber:x:delay", from = muc_domain, stamp = datetime.legacy()}):up(); -- XEP-0091 (deprecated)
140 local entry = { stanza = stanza, stamp = stamp };
141 t_insert(history, entry);
142 while #history > (self._data.history_length or default_history_length) do t_remove(history, 1) end
145 function room_mt:broadcast_except_nick(stanza, nick)
146 for rnick, occupant in pairs(self._occupants) do
147 if rnick ~= nick then
148 for jid in pairs(occupant.sessions) do
149 stanza.attr.to = jid;
150 self:_route_stanza(stanza);
156 function room_mt:send_occupant_list(to)
157 local current_nick = self._jid_nick[to];
158 for occupant, o_data in pairs(self._occupants) do
159 if occupant ~= current_nick then
160 local pres = get_filtered_presence(o_data.sessions[o_data.jid]);
161 pres.attr.to, pres.attr.from = to, occupant;
162 pres:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
163 :tag("item", {affiliation=o_data.affiliation or "none", role=o_data.role or "none"}):up();
164 self:_route_stanza(pres);
168 function room_mt:send_history(to, stanza)
169 local history = self._data['history']; -- send discussion history
171 local x_tag = stanza and stanza:get_child("x", "http://jabber.org/protocol/muc");
172 local history_tag = x_tag and x_tag:get_child("history", "http://jabber.org/protocol/muc");
174 local maxchars = history_tag and tonumber(history_tag.attr.maxchars);
175 if maxchars then maxchars = math.floor(maxchars); end
177 local maxstanzas = math.floor(history_tag and tonumber(history_tag.attr.maxstanzas) or #history);
178 if not history_tag then maxstanzas = 20; end
180 local seconds = history_tag and tonumber(history_tag.attr.seconds);
181 if seconds then seconds = datetime.datetime(os.time() - math.floor(seconds)); end
183 local since = history_tag and history_tag.attr.since;
184 if since then since = datetime.parse(since); since = since and datetime.datetime(since); end
185 if seconds and (not since or since < seconds) then since = seconds; end
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 local count = 0; for _ in pairs(self._occupants) do count = count + 1; end
217 return st.reply(stanza):query("http://jabber.org/protocol/disco#info")
218 :tag("identity", {category="conference", type="text", name=self:get_name()}):up()
219 :tag("feature", {var="http://jabber.org/protocol/muc"}):up()
220 :tag("feature", {var=self:get_password() and "muc_passwordprotected" or "muc_unsecured"}):up()
221 :tag("feature", {var=self:is_moderated() and "muc_moderated" or "muc_unmoderated"}):up()
222 :tag("feature", {var=self:is_members_only() and "muc_membersonly" or "muc_open"}):up()
223 :tag("feature", {var=self:is_persistent() and "muc_persistent" or "muc_temporary"}):up()
224 :tag("feature", {var=self:is_hidden() and "muc_hidden" or "muc_public"}):up()
225 :tag("feature", {var=self._data.whois ~= "anyone" and "muc_semianonymous" or "muc_nonanonymous"}):up()
226 :add_child(dataform.new({
227 { name = "FORM_TYPE", type = "hidden", value = "http://jabber.org/protocol/muc#roominfo" },
228 { name = "muc#roominfo_description", label = "Description", value = "" },
229 { name = "muc#roominfo_occupants", label = "Number of occupants", value = tostring(count) }
230 }):form({["muc#roominfo_description"] = self:get_description()}, 'result'))
233 function room_mt:get_disco_items(stanza)
234 local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#items");
235 for room_jid in pairs(self._occupants) do
236 reply:tag("item", {jid = room_jid, name = room_jid:match("/(.*)")}):up();
240 function room_mt:set_subject(current_nick, subject)
241 -- TODO check nick's authority
242 if subject == "" then subject = nil; end
243 self._data['subject'] = subject;
244 self._data['subject_from'] = current_nick;
245 if self.save then self:save(); end
246 local msg = st.message({type='groupchat', from=current_nick})
247 :tag('subject'):text(subject):up();
248 self:broadcast_message(msg, false);
252 local function build_unavailable_presence_from_error(stanza)
253 local type, condition, text = stanza:get_error();
254 local error_message = "Kicked: "..(condition and condition:gsub("%-", " ") or "presence error");
256 error_message = error_message..": "..text;
258 return st.presence({type='unavailable', from=stanza.attr.from, to=stanza.attr.to})
259 :tag('status'):text(error_message);
262 function room_mt:set_name(name)
263 if name == "" or type(name) ~= "string" or name == (jid_split(self.jid)) then name = nil; end
264 if self._data.name ~= name then
265 self._data.name = name;
266 if self.save then self:save(true); end
269 function room_mt:get_name()
270 return self._data.name or jid_split(self.jid);
272 function room_mt:set_description(description)
273 if description == "" or type(description) ~= "string" then description = nil; end
274 if self._data.description ~= description then
275 self._data.description = description;
276 if self.save then self:save(true); end
279 function room_mt:get_description()
280 return self._data.description;
282 function room_mt:set_password(password)
283 if password == "" or type(password) ~= "string" then password = nil; end
284 if self._data.password ~= password then
285 self._data.password = password;
286 if self.save then self:save(true); end
289 function room_mt:get_password()
290 return self._data.password;
292 function room_mt:set_moderated(moderated)
293 moderated = moderated and true or nil;
294 if self._data.moderated ~= moderated then
295 self._data.moderated = moderated;
296 if self.save then self:save(true); end
299 function room_mt:is_moderated()
300 return self._data.moderated;
302 function room_mt:set_members_only(members_only)
303 members_only = members_only and true or nil;
304 if self._data.members_only ~= members_only then
305 self._data.members_only = members_only;
306 if self.save then self:save(true); end
309 function room_mt:is_members_only()
310 return self._data.members_only;
312 function room_mt:set_persistent(persistent)
313 persistent = persistent and true or nil;
314 if self._data.persistent ~= persistent then
315 self._data.persistent = persistent;
316 if self.save then self:save(true); end
319 function room_mt:is_persistent()
320 return self._data.persistent;
322 function room_mt:set_hidden(hidden)
323 hidden = hidden and true or nil;
324 if self._data.hidden ~= hidden then
325 self._data.hidden = hidden;
326 if self.save then self:save(true); end
329 function room_mt:is_hidden()
330 return self._data.hidden;
332 function room_mt:set_changesubject(changesubject)
333 changesubject = changesubject and true or nil;
334 if self._data.changesubject ~= changesubject then
335 self._data.changesubject = changesubject;
336 if self.save then self:save(true); end
339 function room_mt:get_changesubject()
340 return self._data.changesubject;
342 function room_mt:get_historylength()
343 return self._data.history_length or default_history_length;
345 function room_mt:set_historylength(length)
346 length = math.min(tonumber(length) or default_history_length, max_history_length or math.huge);
347 if length == default_history_length then
350 self._data.history_length = length;
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(%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";
489 local affiliation = self:get_affiliation(from);
490 local role = self:get_default_role(affiliation)
491 if role then -- new occupant
493 self._occupants[to] = {affiliation=affiliation, role=role, jid=from, sessions={[from]=get_filtered_presence(stanza)}};
495 self._occupants[to].sessions[from] = get_filtered_presence(stanza);
497 self._jid_nick[from] = to;
498 self:send_occupant_list(from);
500 pr:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
501 :tag("item", {affiliation=affiliation or "none", role=role or "none"}):up();
503 self:broadcast_except_nick(pr, to);
505 pr:tag("status", {code='110'}):up();
506 if self._data.whois == 'anyone' then
507 pr:tag("status", {code='100'}):up();
510 self:_route_stanza(pr);
511 self:send_history(from, stanza);
512 elseif not affiliation then -- registration required for entering members-only room
513 local reply = st.error_reply(stanza, "auth", "registration-required"):up();
514 reply.tags[1].attr.code = "407";
515 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
517 local reply = st.error_reply(stanza, "auth", "forbidden"):up();
518 reply.tags[1].attr.code = "403";
519 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
523 elseif type ~= 'result' then -- bad type
524 if type ~= 'visible' and type ~= 'invisible' then -- COMPAT ejabberd can broadcast or forward XEP-0018 presences
525 origin.send(st.error_reply(stanza, "modify", "bad-request")); -- FIXME correct error?
528 elseif not current_nick then -- not in room
529 if (type == "error" or type == "result") and stanza.name == "iq" then
530 local id = stanza.attr.id;
531 stanza.attr.from, stanza.attr.to, stanza.attr.id = deconstruct_stanza_id(self, stanza);
532 if stanza.attr.id then
533 self:_route_stanza(stanza);
535 stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
536 elseif type ~= "error" then
537 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
539 elseif stanza.name == "message" and type == "groupchat" then -- groupchat messages not allowed in PM
540 origin.send(st.error_reply(stanza, "modify", "bad-request"));
541 elseif current_nick and stanza.name == "message" and type == "error" and is_kickable_error(stanza) then
542 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
543 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza)); -- send unavailable
544 else -- private stanza
545 local o_data = self._occupants[to];
547 log("debug", "%s sent private stanza to %s (%s)", from, to, o_data.jid);
548 if stanza.name == "iq" then
549 local id = stanza.attr.id;
550 if stanza.attr.type == "get" or stanza.attr.type == "set" then
551 stanza.attr.from, stanza.attr.to, stanza.attr.id = construct_stanza_id(self, stanza);
553 stanza.attr.from, stanza.attr.to, stanza.attr.id = deconstruct_stanza_id(self, stanza);
555 if type == 'get' and stanza.tags[1].attr.xmlns == 'vcard-temp' then
556 stanza.attr.to = jid_bare(stanza.attr.to);
558 if stanza.attr.id then
559 self:_route_stanza(stanza);
561 stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
563 stanza.attr.from = current_nick;
564 for jid in pairs(o_data.sessions) do
565 stanza.attr.to = jid;
566 self:_route_stanza(stanza);
568 stanza.attr.from, stanza.attr.to = from, to;
570 elseif type ~= "error" and type ~= "result" then -- recipient not in room
571 origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
576 function room_mt:send_form(origin, stanza)
577 origin.send(st.reply(stanza):query("http://jabber.org/protocol/muc#owner")
578 :add_child(self:get_form_layout():form())
582 function room_mt:get_form_layout()
583 local form = dataform.new({
584 title = "Configuration for "..self.jid,
585 instructions = "Complete and submit this form to configure the room.",
589 value = 'http://jabber.org/protocol/muc#roomconfig'
592 name = 'muc#roomconfig_roomname',
593 type = 'text-single',
595 value = self:get_name() or "",
598 name = 'muc#roomconfig_roomdesc',
599 type = 'text-single',
600 label = 'Description',
601 value = self:get_description() or "",
604 name = 'muc#roomconfig_persistentroom',
606 label = 'Make Room Persistent?',
607 value = self:is_persistent()
610 name = 'muc#roomconfig_publicroom',
612 label = 'Make Room Publicly Searchable?',
613 value = not self:is_hidden()
616 name = 'muc#roomconfig_changesubject',
618 label = 'Allow Occupants to Change Subject?',
619 value = self:get_changesubject()
622 name = 'muc#roomconfig_whois',
623 type = 'list-single',
624 label = 'Who May Discover Real JIDs?',
626 { value = 'moderators', label = 'Moderators Only', default = self._data.whois == 'moderators' },
627 { value = 'anyone', label = 'Anyone', default = self._data.whois == 'anyone' }
631 name = 'muc#roomconfig_roomsecret',
632 type = 'text-private',
634 value = self:get_password() or "",
637 name = 'muc#roomconfig_moderatedroom',
639 label = 'Make Room Moderated?',
640 value = self:is_moderated()
643 name = 'muc#roomconfig_membersonly',
645 label = 'Make Room Members-Only?',
646 value = self:is_members_only()
649 name = 'muc#roomconfig_historylength',
650 type = 'text-single',
651 label = 'Maximum Number of History Messages Returned by Room',
652 value = tostring(self:get_historylength())
655 return module:fire_event("muc-config-form", { room = self, form = form }) or form;
658 local valid_whois = {
663 function room_mt:process_form(origin, stanza)
664 local query = stanza.tags[1];
666 for _, tag in ipairs(query.tags) do if tag.name == "x" and tag.attr.xmlns == "jabber:x:data" then form = tag; break; end end
667 if not form then origin.send(st.error_reply(stanza, "cancel", "service-unavailable")); return; end
668 if form.attr.type == "cancel" then origin.send(st.reply(stanza)); return; end
669 if form.attr.type ~= "submit" then origin.send(st.error_reply(stanza, "cancel", "bad-request", "Not a submitted form")); return; end
671 if form.tags[1] == nil then
673 if self.save then self:save(true); end
674 origin.send(st.reply(stanza));
679 local fields = self:get_form_layout():data(form);
680 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
684 local event = { room = self, fields = fields, changed = dirty };
685 module:fire_event("muc-config-submitted", event);
686 dirty = event.changed or dirty;
688 local name = fields['muc#roomconfig_roomname'];
689 if name ~= self:get_name() then
693 local description = fields['muc#roomconfig_roomdesc'];
694 if description ~= self:get_description() then
695 self:set_description(description);
698 local persistent = fields['muc#roomconfig_persistentroom'];
699 dirty = dirty or (self:is_persistent() ~= persistent)
700 module:log("debug", "persistent=%s", tostring(persistent));
702 local moderated = fields['muc#roomconfig_moderatedroom'];
703 dirty = dirty or (self:is_moderated() ~= moderated)
704 module:log("debug", "moderated=%s", tostring(moderated));
706 local membersonly = fields['muc#roomconfig_membersonly'];
707 dirty = dirty or (self:is_members_only() ~= membersonly)
708 module:log("debug", "membersonly=%s", tostring(membersonly));
710 local public = fields['muc#roomconfig_publicroom'];
711 dirty = dirty or (self:is_hidden() ~= (not public and true or nil))
713 local changesubject = fields['muc#roomconfig_changesubject'];
714 dirty = dirty or (self:get_changesubject() ~= (not changesubject and true or nil))
715 module:log('debug', 'changesubject=%s', changesubject and "true" or "false")
717 local historylength = tonumber(fields['muc#roomconfig_historylength']);
718 dirty = dirty or (historylength and (self:get_historylength() ~= historylength));
719 module:log('debug', 'historylength=%s', historylength)
722 local whois = fields['muc#roomconfig_whois'];
723 if not valid_whois[whois] then
724 origin.send(st.error_reply(stanza, 'cancel', 'bad-request', "Invalid value for 'whois'"));
727 local whois_changed = self._data.whois ~= whois
728 self._data.whois = whois
729 module:log('debug', 'whois=%s', whois)
731 local password = fields['muc#roomconfig_roomsecret'];
732 if self:get_password() ~= password then
733 self:set_password(password);
735 self:set_moderated(moderated);
736 self:set_members_only(membersonly);
737 self:set_persistent(persistent);
738 self:set_hidden(not public);
739 self:set_changesubject(changesubject);
740 self:set_historylength(historylength);
742 if self.save then self:save(true); end
743 origin.send(st.reply(stanza));
745 if dirty or whois_changed then
746 local msg = st.message({type='groupchat', from=self.jid})
747 :tag('x', {xmlns='http://jabber.org/protocol/muc#user'});
750 msg.tags[1]:tag('status', {code = '104'}):up();
752 if whois_changed then
753 local code = (whois == 'moderators') and "173" or "172";
754 msg.tags[1]:tag('status', {code = code}):up();
758 self:broadcast_message(msg, false)
762 function room_mt:destroy(newjid, reason, password)
763 local pr = st.presence({type = "unavailable"})
764 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
765 :tag("item", { affiliation='none', role='none' }):up()
766 :tag("destroy", {jid=newjid})
767 if reason then pr:tag("reason"):text(reason):up(); end
768 if password then pr:tag("password"):text(password):up(); end
769 for nick, occupant in pairs(self._occupants) do
771 for jid in pairs(occupant.sessions) do
773 self:_route_stanza(pr);
774 self._jid_nick[jid] = nil;
776 self._occupants[nick] = nil;
778 self:set_persistent(false);
779 module:fire_event("muc-room-destroyed", { room = self });
782 function room_mt:handle_to_room(origin, stanza) -- presence changes and groupchat messages, along with disco/etc
783 local type = stanza.attr.type;
784 local xmlns = stanza.tags[1] and stanza.tags[1].attr.xmlns;
785 if stanza.name == "iq" then
786 if xmlns == "http://jabber.org/protocol/disco#info" and type == "get" and not stanza.tags[1].attr.node then
787 origin.send(self:get_disco_info(stanza));
788 elseif xmlns == "http://jabber.org/protocol/disco#items" and type == "get" and not stanza.tags[1].attr.node then
789 origin.send(self:get_disco_items(stanza));
790 elseif xmlns == "http://jabber.org/protocol/muc#admin" then
791 local actor = stanza.attr.from;
792 local affiliation = self:get_affiliation(actor);
793 local current_nick = self._jid_nick[actor];
794 local role = current_nick and self._occupants[current_nick].role or self:get_default_role(affiliation);
795 local item = stanza.tags[1].tags[1];
796 if item and item.name == "item" then
797 if type == "set" then
798 local callback = function() origin.send(st.reply(stanza)); end
799 if item.attr.jid then -- Validate provided JID
800 item.attr.jid = jid_prep(item.attr.jid);
801 if not item.attr.jid then
802 origin.send(st.error_reply(stanza, "modify", "jid-malformed"));
806 if not item.attr.jid and item.attr.nick then -- COMPAT Workaround for Miranda sending 'nick' instead of 'jid' when changing affiliation
807 local occupant = self._occupants[self.jid.."/"..item.attr.nick];
808 if occupant then item.attr.jid = occupant.jid; end
809 elseif not item.attr.nick and item.attr.jid then
810 local nick = self._jid_nick[item.attr.jid];
811 if nick then item.attr.nick = select(3, jid_split(nick)); end
813 local reason = item.tags[1] and item.tags[1].name == "reason" and #item.tags[1] == 1 and item.tags[1][1];
814 if item.attr.affiliation and item.attr.jid and not item.attr.role then
815 local success, errtype, err = self:set_affiliation(actor, item.attr.jid, item.attr.affiliation, callback, reason);
816 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
817 elseif item.attr.role and item.attr.nick and not item.attr.affiliation then
818 local success, errtype, err = self:set_role(actor, self.jid.."/"..item.attr.nick, item.attr.role, callback, reason);
819 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
821 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
823 elseif type == "get" then
824 local _aff = item.attr.affiliation;
825 local _rol = item.attr.role;
826 if _aff and not _rol then
827 if affiliation == "owner" or (affiliation == "admin" and _aff ~= "owner" and _aff ~= "admin") then
828 local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
829 for jid, affiliation in pairs(self._affiliations) do
830 if affiliation == _aff then
831 reply:tag("item", {affiliation = _aff, jid = jid}):up();
836 origin.send(st.error_reply(stanza, "auth", "forbidden"));
838 elseif _rol and not _aff then
839 if role == "moderator" then
840 -- TODO allow admins and owners not in room? Provide read-only access to everyone who can see the participants anyway?
841 if _rol == "none" then _rol = nil; end
842 local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
843 for occupant_jid, occupant in pairs(self._occupants) do
844 if occupant.role == _rol then
846 nick = select(3, jid_split(occupant_jid)),
847 role = _rol or "none",
848 affiliation = occupant.affiliation or "none",
855 origin.send(st.error_reply(stanza, "auth", "forbidden"));
858 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
861 elseif type == "set" or type == "get" then
862 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
864 elseif xmlns == "http://jabber.org/protocol/muc#owner" and (type == "get" or type == "set") and stanza.tags[1].name == "query" then
865 if self:get_affiliation(stanza.attr.from) ~= "owner" then
866 origin.send(st.error_reply(stanza, "auth", "forbidden", "Only owners can configure rooms"));
867 elseif stanza.attr.type == "get" then
868 self:send_form(origin, stanza);
869 elseif stanza.attr.type == "set" then
870 local child = stanza.tags[1].tags[1];
872 origin.send(st.error_reply(stanza, "modify", "bad-request"));
873 elseif child.name == "destroy" then
874 local newjid = child.attr.jid;
875 local reason, password;
876 for _,tag in ipairs(child.tags) do
877 if tag.name == "reason" then
878 reason = #tag.tags == 0 and tag[1];
879 elseif tag.name == "password" then
880 password = #tag.tags == 0 and tag[1];
883 self:destroy(newjid, reason, password);
884 origin.send(st.reply(stanza));
886 self:process_form(origin, stanza);
889 elseif type == "set" or type == "get" then
890 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
892 elseif stanza.name == "message" and type == "groupchat" then
893 local from, to = stanza.attr.from, stanza.attr.to;
894 local current_nick = self._jid_nick[from];
895 local occupant = self._occupants[current_nick];
896 if not occupant then -- not in room
897 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
898 elseif occupant.role == "visitor" then
899 origin.send(st.error_reply(stanza, "auth", "forbidden"));
901 local from = stanza.attr.from;
902 stanza.attr.from = current_nick;
903 local subject = getText(stanza, {"subject"});
905 if occupant.role == "moderator" or
906 ( self._data.changesubject and occupant.role == "participant" ) then -- and participant
907 self:set_subject(current_nick, subject); -- TODO use broadcast_message_stanza
909 stanza.attr.from = from;
910 origin.send(st.error_reply(stanza, "auth", "forbidden"));
913 self:broadcast_message(stanza, self:get_historylength() > 0 and stanza:get_child("body"));
915 stanza.attr.from = from;
917 elseif stanza.name == "message" and type == "error" and is_kickable_error(stanza) then
918 local current_nick = self._jid_nick[stanza.attr.from];
919 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
920 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza)); -- send unavailable
921 elseif stanza.name == "presence" then -- hack - some buggy clients send presence updates to the room rather than their nick
922 local to = stanza.attr.to;
923 local current_nick = self._jid_nick[stanza.attr.from];
925 stanza.attr.to = current_nick;
926 self:handle_to_occupant(origin, stanza);
928 elseif type ~= "error" and type ~= "result" then
929 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
931 elseif stanza.name == "message" and not(type == "chat" or type == "error" or type == "groupchat" or type == "headline") and #stanza.tags == 1
932 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
933 local x = stanza.tags[1];
934 local payload = (#x.tags == 1 and x.tags[1]);
935 if payload and payload.name == "invite" and payload.attr.to then
936 local _from, _to = stanza.attr.from, stanza.attr.to;
937 local _invitee = jid_prep(payload.attr.to);
939 local _reason = payload.tags[1] and payload.tags[1].name == 'reason' and #payload.tags[1].tags == 0 and payload.tags[1][1];
940 local invite = st.message({from = _to, to = _invitee, id = stanza.attr.id})
941 :tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
942 :tag('invite', {from=_from})
943 :tag('reason'):text(_reason or ""):up()
945 if self:get_password() then
946 invite:tag("password"):text(self:get_password()):up();
949 :tag('x', {xmlns="jabber:x:conference", jid=_to}) -- COMPAT: Some older clients expect this
952 :tag('body') -- Add a plain message for clients which don't support invites
953 :text(_from..' invited you to the room '.._to..(_reason and (' ('.._reason..')') or ""))
955 if self:is_members_only() and not self:get_affiliation(_invitee) then
956 log("debug", "%s invited %s into members only room %s, granting membership", _from, _invitee, _to);
957 self:set_affiliation(_from, _invitee, "member", nil, "Invited by " .. self._jid_nick[_from])
959 self:_route_stanza(invite);
961 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
964 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
967 if type == "error" or type == "result" then return; end
968 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
972 function room_mt:handle_stanza(origin, stanza)
973 local to_node, to_host, to_resource = jid_split(stanza.attr.to);
975 self:handle_to_occupant(origin, stanza);
977 self:handle_to_room(origin, stanza);
981 function room_mt:route_stanza(stanza) end -- Replace with a routing function, e.g., function(room, stanza) core_route_stanza(origin, stanza); end
983 function room_mt:get_affiliation(jid)
984 local node, host, resource = jid_split(jid);
985 local bare = node and node.."@"..host or host;
986 local result = self._affiliations[bare]; -- Affiliations are granted, revoked, and maintained based on the user's bare JID.
987 if not result and self._affiliations[host] == "outcast" then result = "outcast"; end -- host banned
990 function room_mt:set_affiliation(actor, jid, affiliation, callback, reason)
992 if affiliation == "none" then affiliation = nil; end
993 if affiliation and affiliation ~= "outcast" and affiliation ~= "owner" and affiliation ~= "admin" and affiliation ~= "member" then
994 return nil, "modify", "not-acceptable";
996 if actor ~= true then
997 local actor_affiliation = self:get_affiliation(actor);
998 local target_affiliation = self:get_affiliation(jid);
999 if target_affiliation == affiliation then -- no change, shortcut
1000 if callback then callback(); end
1003 if actor_affiliation ~= "owner" then
1004 if affiliation == "owner" or affiliation == "admin" or actor_affiliation ~= "admin" or target_affiliation == "owner" or target_affiliation == "admin" then
1005 return nil, "cancel", "not-allowed";
1007 elseif target_affiliation == "owner" and jid_bare(actor) == jid then -- self change
1008 local is_last = true;
1009 for j, aff in pairs(self._affiliations) do if j ~= jid and aff == "owner" then is_last = false; break; end end
1011 return nil, "cancel", "conflict";
1015 self._affiliations[jid] = affiliation;
1016 local role = self:get_default_role(affiliation);
1017 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"})
1018 :tag("item", {affiliation=affiliation or "none", role=role or "none"})
1019 :tag("reason"):text(reason or ""):up()
1021 local presence_type = nil;
1022 if not role then -- getting kicked
1023 presence_type = "unavailable";
1024 if affiliation == "outcast" then
1025 x:tag("status", {code="301"}):up(); -- banned
1027 x:tag("status", {code="321"}):up(); -- affiliation change
1030 local modified_nicks = {};
1031 for nick, occupant in pairs(self._occupants) do
1032 if jid_bare(occupant.jid) == jid then
1033 if not role then -- getting kicked
1034 self._occupants[nick] = nil;
1036 occupant.affiliation, occupant.role = affiliation, role;
1038 for jid,pres in pairs(occupant.sessions) do -- remove for all sessions of the nick
1039 if not role then self._jid_nick[jid] = nil; end
1040 local p = st.clone(pres);
1042 p.attr.type = presence_type;
1045 self:_route_stanza(p);
1046 if occupant.jid == jid then
1047 modified_nicks[nick] = p;
1052 if self.save then self:save(); end
1053 if callback then callback(); end
1054 for nick,p in pairs(modified_nicks) do
1056 self:broadcast_except_nick(p, nick);
1061 function room_mt:get_role(nick)
1062 local session = self._occupants[nick];
1063 return session and session.role or nil;
1065 function room_mt:can_set_role(actor_jid, occupant_jid, role)
1066 local occupant = self._occupants[occupant_jid];
1067 if not occupant or not actor_jid then return nil, "modify", "not-acceptable"; end
1069 if actor_jid == true then return true; end
1071 local actor = self._occupants[self._jid_nick[actor_jid]];
1072 if actor and actor.role == "moderator" then
1073 if occupant.affiliation ~= "owner" and occupant.affiliation ~= "admin" then
1074 if actor.affiliation == "owner" or actor.affiliation == "admin" then
1076 elseif occupant.role ~= "moderator" and role ~= "moderator" then
1081 return nil, "cancel", "not-allowed";
1083 function room_mt:set_role(actor, occupant_jid, role, callback, reason)
1084 if role == "none" then role = nil; end
1085 if role and role ~= "moderator" and role ~= "participant" and role ~= "visitor" then return nil, "modify", "not-acceptable"; end
1086 local allowed, err_type, err_condition = self:can_set_role(actor, occupant_jid, role);
1087 if not allowed then return allowed, err_type, err_condition; end
1088 local occupant = self._occupants[occupant_jid];
1089 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"})
1090 :tag("item", {affiliation=occupant.affiliation or "none", nick=select(3, jid_split(occupant_jid)), role=role or "none"})
1091 :tag("reason"):text(reason or ""):up()
1093 local presence_type = nil;
1094 if not role then -- kick
1095 presence_type = "unavailable";
1096 self._occupants[occupant_jid] = nil;
1097 for jid in pairs(occupant.sessions) do -- remove for all sessions of the nick
1098 self._jid_nick[jid] = nil;
1100 x:tag("status", {code = "307"}):up();
1102 occupant.role = role;
1105 for jid,pres in pairs(occupant.sessions) do -- send to all sessions of the nick
1106 local p = st.clone(pres);
1107 p.attr.from = occupant_jid;
1108 p.attr.type = presence_type;
1111 self:_route_stanza(p);
1112 if occupant.jid == jid then
1116 if callback then callback(); end
1118 self:broadcast_except_nick(bp, occupant_jid);
1123 function room_mt:_route_stanza(stanza)
1125 local to_occupant = self._occupants[self._jid_nick[stanza.attr.to]];
1126 local from_occupant = self._occupants[stanza.attr.from];
1127 if stanza.name == "presence" then
1128 if to_occupant and from_occupant then
1129 if self._data.whois == 'anyone' then
1130 muc_child = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
1132 if to_occupant.role == "moderator" or jid_bare(to_occupant.jid) == jid_bare(from_occupant.jid) then
1133 muc_child = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
1139 for _, item in pairs(muc_child.tags) do
1140 if item.name == "item" then
1141 if from_occupant == to_occupant then
1142 item.attr.jid = stanza.attr.to;
1144 item.attr.jid = from_occupant.jid;
1149 self:route_stanza(stanza);
1151 for _, item in pairs(muc_child.tags) do
1152 if item.name == "item" then
1153 item.attr.jid = nil;
1159 local _M = {}; -- module "muc"
1161 function _M.new_room(jid, config)
1162 return setmetatable({
1167 whois = 'moderators';
1168 history_length = math.min((config and config.history_length)
1169 or default_history_length, max_history_length);
1175 function _M.set_max_history_length(_max_history_length)
1176 max_history_length = _max_history_length or math.huge;
1179 _M.room_mt = room_mt;