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 local fields = self:get_form_layout():data(form);
672 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
676 local event = { room = self, fields = fields, changed = dirty };
677 module:fire_event("muc-config-submitted", event);
678 dirty = event.changed or dirty;
680 local name = fields['muc#roomconfig_roomname'];
681 if name ~= self:get_name() then
685 local description = fields['muc#roomconfig_roomdesc'];
686 if description ~= self:get_description() then
687 self:set_description(description);
690 local persistent = fields['muc#roomconfig_persistentroom'];
691 dirty = dirty or (self:is_persistent() ~= persistent)
692 module:log("debug", "persistent=%s", tostring(persistent));
694 local moderated = fields['muc#roomconfig_moderatedroom'];
695 dirty = dirty or (self:is_moderated() ~= moderated)
696 module:log("debug", "moderated=%s", tostring(moderated));
698 local membersonly = fields['muc#roomconfig_membersonly'];
699 dirty = dirty or (self:is_members_only() ~= membersonly)
700 module:log("debug", "membersonly=%s", tostring(membersonly));
702 local public = fields['muc#roomconfig_publicroom'];
703 dirty = dirty or (self:is_hidden() ~= (not public and true or nil))
705 local changesubject = fields['muc#roomconfig_changesubject'];
706 dirty = dirty or (self:get_changesubject() ~= (not changesubject and true or nil))
707 module:log('debug', 'changesubject=%s', changesubject and "true" or "false")
709 local historylength = tonumber(fields['muc#roomconfig_historylength']);
710 dirty = dirty or (historylength and (self:get_historylength() ~= historylength));
711 module:log('debug', 'historylength=%s', historylength)
714 local whois = fields['muc#roomconfig_whois'];
715 if not valid_whois[whois] then
716 origin.send(st.error_reply(stanza, 'cancel', 'bad-request', "Invalid value for 'whois'"));
719 local whois_changed = self._data.whois ~= whois
720 self._data.whois = whois
721 module:log('debug', 'whois=%s', whois)
723 local password = fields['muc#roomconfig_roomsecret'];
724 if self:get_password() ~= password then
725 self:set_password(password);
727 self:set_moderated(moderated);
728 self:set_members_only(membersonly);
729 self:set_persistent(persistent);
730 self:set_hidden(not public);
731 self:set_changesubject(changesubject);
732 self:set_historylength(historylength);
734 if self.save then self:save(true); end
735 origin.send(st.reply(stanza));
737 if dirty or whois_changed then
738 local msg = st.message({type='groupchat', from=self.jid})
739 :tag('x', {xmlns='http://jabber.org/protocol/muc#user'}):up()
742 msg.tags[1]:tag('status', {code = '104'}):up();
744 if whois_changed then
745 local code = (whois == 'moderators') and "173" or "172";
746 msg.tags[1]:tag('status', {code = code}):up();
749 self:broadcast_message(msg, false)
753 function room_mt:destroy(newjid, reason, password)
754 local pr = st.presence({type = "unavailable"})
755 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
756 :tag("item", { affiliation='none', role='none' }):up()
757 :tag("destroy", {jid=newjid})
758 if reason then pr:tag("reason"):text(reason):up(); end
759 if password then pr:tag("password"):text(password):up(); end
760 for nick, occupant in pairs(self._occupants) do
762 for jid in pairs(occupant.sessions) do
764 self:_route_stanza(pr);
765 self._jid_nick[jid] = nil;
767 self._occupants[nick] = nil;
769 self:set_persistent(false);
770 module:fire_event("muc-room-destroyed", { room = self });
773 function room_mt:handle_to_room(origin, stanza) -- presence changes and groupchat messages, along with disco/etc
774 local type = stanza.attr.type;
775 local xmlns = stanza.tags[1] and stanza.tags[1].attr.xmlns;
776 if stanza.name == "iq" then
777 if xmlns == "http://jabber.org/protocol/disco#info" and type == "get" and not stanza.tags[1].attr.node then
778 origin.send(self:get_disco_info(stanza));
779 elseif xmlns == "http://jabber.org/protocol/disco#items" and type == "get" and not stanza.tags[1].attr.node then
780 origin.send(self:get_disco_items(stanza));
781 elseif xmlns == "http://jabber.org/protocol/muc#admin" then
782 local actor = stanza.attr.from;
783 local affiliation = self:get_affiliation(actor);
784 local current_nick = self._jid_nick[actor];
785 local role = current_nick and self._occupants[current_nick].role or self:get_default_role(affiliation);
786 local item = stanza.tags[1].tags[1];
787 if item and item.name == "item" then
788 if type == "set" then
789 local callback = function() origin.send(st.reply(stanza)); end
790 if item.attr.jid then -- Validate provided JID
791 item.attr.jid = jid_prep(item.attr.jid);
792 if not item.attr.jid then
793 origin.send(st.error_reply(stanza, "modify", "jid-malformed"));
797 if not item.attr.jid and item.attr.nick then -- COMPAT Workaround for Miranda sending 'nick' instead of 'jid' when changing affiliation
798 local occupant = self._occupants[self.jid.."/"..item.attr.nick];
799 if occupant then item.attr.jid = occupant.jid; end
800 elseif not item.attr.nick and item.attr.jid then
801 local nick = self._jid_nick[item.attr.jid];
802 if nick then item.attr.nick = select(3, jid_split(nick)); end
804 local reason = item.tags[1] and item.tags[1].name == "reason" and #item.tags[1] == 1 and item.tags[1][1];
805 if item.attr.affiliation and item.attr.jid and not item.attr.role then
806 local success, errtype, err = self:set_affiliation(actor, item.attr.jid, item.attr.affiliation, callback, reason);
807 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
808 elseif item.attr.role and item.attr.nick and not item.attr.affiliation then
809 local success, errtype, err = self:set_role(actor, self.jid.."/"..item.attr.nick, item.attr.role, callback, reason);
810 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
812 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
814 elseif type == "get" then
815 local _aff = item.attr.affiliation;
816 local _rol = item.attr.role;
817 if _aff and not _rol then
818 if affiliation == "owner" or (affiliation == "admin" and _aff ~= "owner" and _aff ~= "admin") then
819 local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
820 for jid, affiliation in pairs(self._affiliations) do
821 if affiliation == _aff then
822 reply:tag("item", {affiliation = _aff, jid = jid}):up();
827 origin.send(st.error_reply(stanza, "auth", "forbidden"));
829 elseif _rol and not _aff then
830 if role == "moderator" then
831 -- TODO allow admins and owners not in room? Provide read-only access to everyone who can see the participants anyway?
832 if _rol == "none" then _rol = nil; end
833 local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
834 for occupant_jid, occupant in pairs(self._occupants) do
835 if occupant.role == _rol then
837 nick = select(3, jid_split(occupant_jid)),
838 role = _rol or "none",
839 affiliation = occupant.affiliation or "none",
846 origin.send(st.error_reply(stanza, "auth", "forbidden"));
849 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
852 elseif type == "set" or type == "get" then
853 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
855 elseif xmlns == "http://jabber.org/protocol/muc#owner" and (type == "get" or type == "set") and stanza.tags[1].name == "query" then
856 if self:get_affiliation(stanza.attr.from) ~= "owner" then
857 origin.send(st.error_reply(stanza, "auth", "forbidden", "Only owners can configure rooms"));
858 elseif stanza.attr.type == "get" then
859 self:send_form(origin, stanza);
860 elseif stanza.attr.type == "set" then
861 local child = stanza.tags[1].tags[1];
863 origin.send(st.error_reply(stanza, "modify", "bad-request"));
864 elseif child.name == "destroy" then
865 local newjid = child.attr.jid;
866 local reason, password;
867 for _,tag in ipairs(child.tags) do
868 if tag.name == "reason" then
869 reason = #tag.tags == 0 and tag[1];
870 elseif tag.name == "password" then
871 password = #tag.tags == 0 and tag[1];
874 self:destroy(newjid, reason, password);
875 origin.send(st.reply(stanza));
877 self:process_form(origin, stanza);
880 elseif type == "set" or type == "get" then
881 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
883 elseif stanza.name == "message" and type == "groupchat" then
884 local from, to = stanza.attr.from, stanza.attr.to;
885 local current_nick = self._jid_nick[from];
886 local occupant = self._occupants[current_nick];
887 if not occupant then -- not in room
888 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
889 elseif occupant.role == "visitor" then
890 origin.send(st.error_reply(stanza, "auth", "forbidden"));
892 local from = stanza.attr.from;
893 stanza.attr.from = current_nick;
894 local subject = getText(stanza, {"subject"});
896 if occupant.role == "moderator" or
897 ( self._data.changesubject and occupant.role == "participant" ) then -- and participant
898 self:set_subject(current_nick, subject); -- TODO use broadcast_message_stanza
900 stanza.attr.from = from;
901 origin.send(st.error_reply(stanza, "auth", "forbidden"));
904 self:broadcast_message(stanza, self:get_historylength() > 0 and stanza:get_child("body"));
906 stanza.attr.from = from;
908 elseif stanza.name == "message" and type == "error" and is_kickable_error(stanza) then
909 local current_nick = self._jid_nick[stanza.attr.from];
910 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
911 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza)); -- send unavailable
912 elseif stanza.name == "presence" then -- hack - some buggy clients send presence updates to the room rather than their nick
913 local to = stanza.attr.to;
914 local current_nick = self._jid_nick[stanza.attr.from];
916 stanza.attr.to = current_nick;
917 self:handle_to_occupant(origin, stanza);
919 elseif type ~= "error" and type ~= "result" then
920 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
922 elseif stanza.name == "message" and not(type == "chat" or type == "error" or type == "groupchat" or type == "headline") and #stanza.tags == 1
923 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
924 local x = stanza.tags[1];
925 local payload = (#x.tags == 1 and x.tags[1]);
926 if payload and payload.name == "invite" and payload.attr.to then
927 local _from, _to = stanza.attr.from, stanza.attr.to;
928 local _invitee = jid_prep(payload.attr.to);
930 local _reason = payload.tags[1] and payload.tags[1].name == 'reason' and #payload.tags[1].tags == 0 and payload.tags[1][1];
931 local invite = st.message({from = _to, to = _invitee, id = stanza.attr.id})
932 :tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
933 :tag('invite', {from=_from})
934 :tag('reason'):text(_reason or ""):up()
936 if self:get_password() then
937 invite:tag("password"):text(self:get_password()):up();
940 :tag('x', {xmlns="jabber:x:conference", jid=_to}) -- COMPAT: Some older clients expect this
943 :tag('body') -- Add a plain message for clients which don't support invites
944 :text(_from..' invited you to the room '.._to..(_reason and (' ('.._reason..')') or ""))
946 if self:is_members_only() and not self:get_affiliation(_invitee) then
947 log("debug", "%s invited %s into members only room %s, granting membership", _from, _invitee, _to);
948 self:set_affiliation(_from, _invitee, "member", nil, "Invited by " .. self._jid_nick[_from])
950 self:_route_stanza(invite);
952 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
955 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
958 if type == "error" or type == "result" then return; end
959 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
963 function room_mt:handle_stanza(origin, stanza)
964 local to_node, to_host, to_resource = jid_split(stanza.attr.to);
966 self:handle_to_occupant(origin, stanza);
968 self:handle_to_room(origin, stanza);
972 function room_mt:route_stanza(stanza) end -- Replace with a routing function, e.g., function(room, stanza) core_route_stanza(origin, stanza); end
974 function room_mt:get_affiliation(jid)
975 local node, host, resource = jid_split(jid);
976 local bare = node and node.."@"..host or host;
977 local result = self._affiliations[bare]; -- Affiliations are granted, revoked, and maintained based on the user's bare JID.
978 if not result and self._affiliations[host] == "outcast" then result = "outcast"; end -- host banned
981 function room_mt:set_affiliation(actor, jid, affiliation, callback, reason)
983 if affiliation == "none" then affiliation = nil; end
984 if affiliation and affiliation ~= "outcast" and affiliation ~= "owner" and affiliation ~= "admin" and affiliation ~= "member" then
985 return nil, "modify", "not-acceptable";
987 if actor ~= true then
988 local actor_affiliation = self:get_affiliation(actor);
989 local target_affiliation = self:get_affiliation(jid);
990 if target_affiliation == affiliation then -- no change, shortcut
991 if callback then callback(); end
994 if actor_affiliation ~= "owner" then
995 if affiliation == "owner" or affiliation == "admin" or actor_affiliation ~= "admin" or target_affiliation == "owner" or target_affiliation == "admin" then
996 return nil, "cancel", "not-allowed";
998 elseif target_affiliation == "owner" and jid_bare(actor) == jid then -- self change
999 local is_last = true;
1000 for j, aff in pairs(self._affiliations) do if j ~= jid and aff == "owner" then is_last = false; break; end end
1002 return nil, "cancel", "conflict";
1006 self._affiliations[jid] = affiliation;
1007 local role = self:get_default_role(affiliation);
1008 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"})
1009 :tag("item", {affiliation=affiliation or "none", role=role or "none"})
1010 :tag("reason"):text(reason or ""):up()
1012 local presence_type = nil;
1013 if not role then -- getting kicked
1014 presence_type = "unavailable";
1015 if affiliation == "outcast" then
1016 x:tag("status", {code="301"}):up(); -- banned
1018 x:tag("status", {code="321"}):up(); -- affiliation change
1021 local modified_nicks = {};
1022 for nick, occupant in pairs(self._occupants) do
1023 if jid_bare(occupant.jid) == jid then
1024 if not role then -- getting kicked
1025 self._occupants[nick] = nil;
1027 occupant.affiliation, occupant.role = affiliation, role;
1029 for jid,pres in pairs(occupant.sessions) do -- remove for all sessions of the nick
1030 if not role then self._jid_nick[jid] = nil; end
1031 local p = st.clone(pres);
1033 p.attr.type = presence_type;
1036 self:_route_stanza(p);
1037 if occupant.jid == jid then
1038 modified_nicks[nick] = p;
1043 if self.save then self:save(); end
1044 if callback then callback(); end
1045 for nick,p in pairs(modified_nicks) do
1047 self:broadcast_except_nick(p, nick);
1052 function room_mt:get_role(nick)
1053 local session = self._occupants[nick];
1054 return session and session.role or nil;
1056 function room_mt:can_set_role(actor_jid, occupant_jid, role)
1057 local occupant = self._occupants[occupant_jid];
1058 if not occupant or not actor_jid then return nil, "modify", "not-acceptable"; end
1060 if actor_jid == true then return true; end
1062 local actor = self._occupants[self._jid_nick[actor_jid]];
1063 if actor and actor.role == "moderator" then
1064 if occupant.affiliation ~= "owner" and occupant.affiliation ~= "admin" then
1065 if actor.affiliation == "owner" or actor.affiliation == "admin" then
1067 elseif occupant.role ~= "moderator" and role ~= "moderator" then
1072 return nil, "cancel", "not-allowed";
1074 function room_mt:set_role(actor, occupant_jid, role, callback, reason)
1075 if role == "none" then role = nil; end
1076 if role and role ~= "moderator" and role ~= "participant" and role ~= "visitor" then return nil, "modify", "not-acceptable"; end
1077 local allowed, err_type, err_condition = self:can_set_role(actor, occupant_jid, role);
1078 if not allowed then return allowed, err_type, err_condition; end
1079 local occupant = self._occupants[occupant_jid];
1080 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"})
1081 :tag("item", {affiliation=occupant.affiliation or "none", nick=select(3, jid_split(occupant_jid)), role=role or "none"})
1082 :tag("reason"):text(reason or ""):up()
1084 local presence_type = nil;
1085 if not role then -- kick
1086 presence_type = "unavailable";
1087 self._occupants[occupant_jid] = nil;
1088 for jid in pairs(occupant.sessions) do -- remove for all sessions of the nick
1089 self._jid_nick[jid] = nil;
1091 x:tag("status", {code = "307"}):up();
1093 occupant.role = role;
1096 for jid,pres in pairs(occupant.sessions) do -- send to all sessions of the nick
1097 local p = st.clone(pres);
1098 p.attr.from = occupant_jid;
1099 p.attr.type = presence_type;
1102 self:_route_stanza(p);
1103 if occupant.jid == jid then
1107 if callback then callback(); end
1109 self:broadcast_except_nick(bp, occupant_jid);
1114 function room_mt:_route_stanza(stanza)
1116 local to_occupant = self._occupants[self._jid_nick[stanza.attr.to]];
1117 local from_occupant = self._occupants[stanza.attr.from];
1118 if stanza.name == "presence" then
1119 if to_occupant and from_occupant then
1120 if self._data.whois == 'anyone' then
1121 muc_child = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
1123 if to_occupant.role == "moderator" or jid_bare(to_occupant.jid) == jid_bare(from_occupant.jid) then
1124 muc_child = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
1130 for _, item in pairs(muc_child.tags) do
1131 if item.name == "item" then
1132 if from_occupant == to_occupant then
1133 item.attr.jid = stanza.attr.to;
1135 item.attr.jid = from_occupant.jid;
1140 self:route_stanza(stanza);
1142 for _, item in pairs(muc_child.tags) do
1143 if item.name == "item" then
1144 item.attr.jid = nil;
1150 local _M = {}; -- module "muc"
1152 function _M.new_room(jid, config)
1153 return setmetatable({
1158 whois = 'moderators';
1159 history_length = math.min((config and config.history_length)
1160 or default_history_length, max_history_length);
1166 function _M.set_max_history_length(_max_history_length)
1167 max_history_length = _max_history_length or math.huge;
1170 _M.room_mt = room_mt;