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 local reply = 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()
209 local dataform = dataform.new({
210 { name = "FORM_TYPE", type = "hidden", value = "http://jabber.org/protocol/muc#roominfo" },
211 { name = "muc#roominfo_description", label = "Description", value = "" },
212 { name = "muc#roominfo_occupants", label = "Number of occupants", value = "" }
215 ["muc#roominfo_description"] = self:get_description(),
216 ["muc#roominfo_occupants"] = tostring(count),
218 module:fire_event("muc-disco#info", { room = self, reply = reply, form = dataform, formdata = formdata });
219 reply:add_child(dataform:form(formdata, 'result'))
222 function room_mt:get_disco_items(stanza)
223 local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#items");
224 for room_jid in pairs(self._occupants) do
225 reply:tag("item", {jid = room_jid, name = room_jid:match("/(.*)")}):up();
229 function room_mt:set_subject(current_nick, subject)
230 if subject == "" then subject = nil; end
231 self._data['subject'] = subject;
232 self._data['subject_from'] = current_nick;
233 if self.save then self:save(); end
234 local msg = st.message({type='groupchat', from=current_nick})
235 :tag('subject'):text(subject):up();
236 self:broadcast_message(msg, false);
240 local function build_unavailable_presence_from_error(stanza)
241 local type, condition, text = stanza:get_error();
242 local error_message = "Kicked: "..(condition and condition:gsub("%-", " ") or "presence error");
244 error_message = error_message..": "..text;
246 return st.presence({type='unavailable', from=stanza.attr.from, to=stanza.attr.to})
247 :tag('status'):text(error_message);
250 function room_mt:set_name(name)
251 if name == "" or type(name) ~= "string" or name == (jid_split(self.jid)) then name = nil; end
252 if self._data.name ~= name then
253 self._data.name = name;
254 if self.save then self:save(true); end
257 function room_mt:get_name()
258 return self._data.name or jid_split(self.jid);
260 function room_mt:set_description(description)
261 if description == "" or type(description) ~= "string" then description = nil; end
262 if self._data.description ~= description then
263 self._data.description = description;
264 if self.save then self:save(true); end
267 function room_mt:get_description()
268 return self._data.description;
270 function room_mt:set_password(password)
271 if password == "" or type(password) ~= "string" then password = nil; end
272 if self._data.password ~= password then
273 self._data.password = password;
274 if self.save then self:save(true); end
277 function room_mt:get_password()
278 return self._data.password;
280 function room_mt:set_moderated(moderated)
281 moderated = moderated and true or nil;
282 if self._data.moderated ~= moderated then
283 self._data.moderated = moderated;
284 if self.save then self:save(true); end
287 function room_mt:get_moderated()
288 return self._data.moderated;
290 function room_mt:set_members_only(members_only)
291 members_only = members_only and true or nil;
292 if self._data.members_only ~= members_only then
293 self._data.members_only = members_only;
294 if self.save then self:save(true); end
297 function room_mt:get_members_only()
298 return self._data.members_only;
300 function room_mt:set_persistent(persistent)
301 persistent = persistent and true or nil;
302 if self._data.persistent ~= persistent then
303 self._data.persistent = persistent;
304 if self.save then self:save(true); end
307 function room_mt:get_persistent()
308 return self._data.persistent;
310 function room_mt:set_hidden(hidden)
311 hidden = hidden and true or nil;
312 if self._data.hidden ~= hidden then
313 self._data.hidden = hidden;
314 if self.save then self:save(true); end
317 function room_mt:get_hidden()
318 return self._data.hidden;
320 function room_mt:get_public()
321 return not self:get_hidden();
323 function room_mt:set_public(public)
324 return self:set_hidden(not public);
326 function room_mt:set_changesubject(changesubject)
327 changesubject = changesubject and true or nil;
328 if self._data.changesubject ~= changesubject then
329 self._data.changesubject = changesubject;
330 if self.save then self:save(true); end
333 function room_mt:get_changesubject()
334 return self._data.changesubject;
336 function room_mt:get_historylength()
337 return self._data.history_length or default_history_length;
339 function room_mt:set_historylength(length)
340 length = math.min(tonumber(length) or default_history_length, max_history_length or math.huge);
341 if length == default_history_length then
344 self._data.history_length = length;
348 local valid_whois = { moderators = true, anyone = true };
350 function room_mt:set_whois(whois)
351 if valid_whois[whois] and self._data.whois ~= whois then
352 self._data.whois = whois;
353 if self.save then self:save(true); end
357 function room_mt:get_whois()
358 return self._data.whois;
361 local function construct_stanza_id(room, stanza)
362 local from_jid, to_nick = stanza.attr.from, stanza.attr.to;
363 local from_nick = room._jid_nick[from_jid];
364 local occupant = room._occupants[to_nick];
365 local to_jid = occupant.jid;
367 return from_nick, to_jid, base64.encode(to_jid.."\0"..stanza.attr.id.."\0"..md5(from_jid));
369 local function deconstruct_stanza_id(room, stanza)
370 local from_jid_possiblybare, to_nick = stanza.attr.from, stanza.attr.to;
371 local from_jid, id, to_jid_hash = (base64.decode(stanza.attr.id) or ""):match("^(%Z+)%z(%Z*)%z(.+)$");
372 local from_nick = room._jid_nick[from_jid];
374 if not(from_nick) then return; end
375 if not(from_jid_possiblybare == from_jid or from_jid_possiblybare == jid_bare(from_jid)) then return; end
377 local occupant = room._occupants[to_nick];
378 for to_jid in pairs(occupant and occupant.sessions or {}) do
379 if md5(to_jid) == to_jid_hash then
380 return from_nick, to_jid, id;
386 function room_mt:handle_to_occupant(origin, stanza) -- PM, vCards, etc
387 local from, to = stanza.attr.from, stanza.attr.to;
388 local room = jid_bare(to);
389 local current_nick = self._jid_nick[from];
390 local type = stanza.attr.type;
391 log("debug", "room: %s, current_nick: %s, stanza: %s", room or "nil", current_nick or "nil", stanza:top_tag());
392 if (select(2, jid_split(from)) == muc_domain) then error("Presence from the MUC itself!!!"); end
393 if stanza.name == "presence" then
394 local pr = get_filtered_presence(stanza);
395 pr.attr.from = current_nick;
396 if type == "error" then -- error, kick em out!
398 log("debug", "kicking %s from %s", current_nick, room);
399 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza));
401 elseif type == "unavailable" then -- unavailable
403 log("debug", "%s leaving %s", current_nick, room);
404 self._jid_nick[from] = nil;
405 local occupant = self._occupants[current_nick];
406 local new_jid = next(occupant.sessions);
407 if new_jid == from then new_jid = next(occupant.sessions, new_jid); end
409 local jid = occupant.jid;
410 occupant.jid = new_jid;
411 occupant.sessions[from] = nil;
413 pr:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
414 :tag("item", {affiliation=occupant.affiliation or "none", role='none'}):up()
415 :tag("status", {code='110'}):up();
416 self:_route_stanza(pr);
417 if jid ~= new_jid then
418 pr = st.clone(occupant.sessions[new_jid])
419 :tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
420 :tag("item", {affiliation=occupant.affiliation or "none", role=occupant.role or "none"});
421 pr.attr.from = current_nick;
422 self:broadcast_except_nick(pr, current_nick);
425 occupant.role = 'none';
426 self:broadcast_presence(pr, from);
427 self._occupants[current_nick] = nil;
430 elseif not type then -- available
432 --if #pr == #stanza or current_nick ~= to then -- commented because google keeps resending directed presence
433 if current_nick == to then -- simple presence
434 log("debug", "%s broadcasted presence", current_nick);
435 self._occupants[current_nick].sessions[from] = pr;
436 self:broadcast_presence(pr, from);
438 local occupant = self._occupants[current_nick];
439 local is_multisession = next(occupant.sessions, next(occupant.sessions));
440 if self._occupants[to] or is_multisession then
441 log("debug", "%s couldn't change nick", current_nick);
442 local reply = st.error_reply(stanza, "cancel", "conflict"):up();
443 reply.tags[1].attr.code = "409";
444 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
446 local data = self._occupants[current_nick];
447 local to_nick = select(3, jid_split(to));
449 log("debug", "%s (%s) changing nick to %s", current_nick, data.jid, to);
450 local p = st.presence({type='unavailable', from=current_nick});
451 self:broadcast_presence(p, from, '303', to_nick);
452 self._occupants[current_nick] = nil;
453 self._occupants[to] = data;
454 self._jid_nick[from] = to;
456 self._occupants[to].sessions[from] = pr;
457 self:broadcast_presence(pr, from);
463 --else -- possible rejoin
464 -- log("debug", "%s had connection replaced", current_nick);
465 -- self:handle_to_occupant(origin, st.presence({type='unavailable', from=from, to=to})
466 -- :tag('status'):text('Replaced by new connection'):up()); -- send unavailable
467 -- self:handle_to_occupant(origin, stanza); -- resend available
472 if self._occupants[to] then
473 if jid_bare(from) ~= jid_bare(self._occupants[to].jid) then
478 local password = stanza:get_child("x", "http://jabber.org/protocol/muc");
479 password = password and password:get_child("password", "http://jabber.org/protocol/muc");
480 password = password and password[1] ~= "" and password[1];
481 if self:get_password() and self:get_password() ~= password then
482 log("debug", "%s couldn't join due to invalid password: %s", from, to);
483 local reply = st.error_reply(stanza, "auth", "not-authorized"):up();
484 reply.tags[1].attr.code = "401";
485 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
486 elseif not new_nick then
487 log("debug", "%s couldn't join due to nick conflict: %s", from, to);
488 local reply = st.error_reply(stanza, "cancel", "conflict"):up();
489 reply.tags[1].attr.code = "409";
490 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
492 log("debug", "%s joining as %s", from, to);
493 if not next(self._affiliations) then -- new room, no owners
494 self._affiliations[jid_bare(from)] = "owner";
495 if self.locked and not stanza:get_child("x", "http://jabber.org/protocol/muc") then
496 self.locked = nil; -- Older groupchat protocol doesn't lock
498 elseif self.locked then -- Deny entry
499 origin.send(st.error_reply(stanza, "cancel", "item-not-found"));
502 local affiliation = self:get_affiliation(from);
503 local role = self:get_default_role(affiliation)
504 if role then -- new occupant
506 self._occupants[to] = {affiliation=affiliation, role=role, jid=from, sessions={[from]=get_filtered_presence(stanza)}};
508 self._occupants[to].sessions[from] = get_filtered_presence(stanza);
510 self._jid_nick[from] = to;
511 self:send_occupant_list(from);
513 pr:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
514 :tag("item", {affiliation=affiliation or "none", role=role or "none"}):up();
516 self:broadcast_except_nick(pr, to);
518 pr:tag("status", {code='110'}):up();
519 if self._data.whois == 'anyone' then
520 pr:tag("status", {code='100'}):up();
523 pr:tag("status", {code='201'}):up();
526 self:_route_stanza(pr);
527 self:send_history(from, stanza);
528 self:send_subject(from);
529 elseif not affiliation then -- registration required for entering members-only room
530 local reply = st.error_reply(stanza, "auth", "registration-required"):up();
531 reply.tags[1].attr.code = "407";
532 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
534 local reply = st.error_reply(stanza, "auth", "forbidden"):up();
535 reply.tags[1].attr.code = "403";
536 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
540 elseif type ~= 'result' then -- bad type
541 if type ~= 'visible' and type ~= 'invisible' then -- COMPAT ejabberd can broadcast or forward XEP-0018 presences
542 origin.send(st.error_reply(stanza, "modify", "bad-request")); -- FIXME correct error?
545 elseif not current_nick then -- not in room
546 if (type == "error" or type == "result") and stanza.name == "iq" then
547 local id = stanza.attr.id;
548 stanza.attr.from, stanza.attr.to, stanza.attr.id = deconstruct_stanza_id(self, stanza);
549 if stanza.attr.id then
550 self:_route_stanza(stanza);
552 stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
553 elseif type ~= "error" then
554 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
556 elseif stanza.name == "message" and type == "groupchat" then -- groupchat messages not allowed in PM
557 origin.send(st.error_reply(stanza, "modify", "bad-request"));
558 elseif current_nick and stanza.name == "message" and type == "error" and is_kickable_error(stanza) then
559 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
560 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza)); -- send unavailable
561 else -- private stanza
562 local o_data = self._occupants[to];
564 log("debug", "%s sent private stanza to %s (%s)", from, to, o_data.jid);
565 if stanza.name == "iq" then
566 local id = stanza.attr.id;
567 if stanza.attr.type == "get" or stanza.attr.type == "set" then
568 stanza.attr.from, stanza.attr.to, stanza.attr.id = construct_stanza_id(self, stanza);
570 stanza.attr.from, stanza.attr.to, stanza.attr.id = deconstruct_stanza_id(self, stanza);
572 if type == 'get' and stanza.tags[1].attr.xmlns == 'vcard-temp' then
573 stanza.attr.to = jid_bare(stanza.attr.to);
575 if stanza.attr.id then
576 self:_route_stanza(stanza);
578 stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
580 stanza:tag("x", { xmlns = "http://jabber.org/protocol/muc#user" }):up();
581 stanza.attr.from = current_nick;
582 for jid in pairs(o_data.sessions) do
583 stanza.attr.to = jid;
584 self:_route_stanza(stanza);
586 stanza.attr.from, stanza.attr.to = from, to;
588 elseif type ~= "error" and type ~= "result" then -- recipient not in room
589 origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
594 function room_mt:send_form(origin, stanza)
595 origin.send(st.reply(stanza):query("http://jabber.org/protocol/muc#owner")
596 :add_child(self:get_form_layout(stanza.attr.from):form())
600 function room_mt:get_form_layout(actor)
601 local form = dataform.new({
602 title = "Configuration for "..self.jid,
603 instructions = "Complete and submit this form to configure the room.",
607 value = 'http://jabber.org/protocol/muc#roomconfig'
610 name = 'muc#roomconfig_roomname',
611 type = 'text-single',
613 value = self:get_name() or "",
616 name = 'muc#roomconfig_roomdesc',
617 type = 'text-single',
618 label = 'Description',
619 value = self:get_description() or "",
622 name = 'muc#roomconfig_persistentroom',
624 label = 'Make Room Persistent?',
625 value = self:get_persistent()
628 name = 'muc#roomconfig_publicroom',
630 label = 'Make Room Publicly Searchable?',
631 value = not self:get_hidden()
634 name = 'muc#roomconfig_changesubject',
636 label = 'Allow Occupants to Change Subject?',
637 value = self:get_changesubject()
640 name = 'muc#roomconfig_whois',
641 type = 'list-single',
642 label = 'Who May Discover Real JIDs?',
644 { value = 'moderators', label = 'Moderators Only', default = self._data.whois == 'moderators' },
645 { value = 'anyone', label = 'Anyone', default = self._data.whois == 'anyone' }
649 name = 'muc#roomconfig_roomsecret',
650 type = 'text-private',
652 value = self:get_password() or "",
655 name = 'muc#roomconfig_moderatedroom',
657 label = 'Make Room Moderated?',
658 value = self:get_moderated()
661 name = 'muc#roomconfig_membersonly',
663 label = 'Make Room Members-Only?',
664 value = self:get_members_only()
667 name = 'muc#roomconfig_historylength',
668 type = 'text-single',
669 label = 'Maximum Number of History Messages Returned by Room',
670 value = tostring(self:get_historylength())
673 return module:fire_event("muc-config-form", { room = self, actor = actor, form = form }) or form;
676 function room_mt:process_form(origin, stanza)
677 local query = stanza.tags[1];
679 for _, tag in ipairs(query.tags) do if tag.name == "x" and tag.attr.xmlns == "jabber:x:data" then form = tag; break; end end
680 if not form then origin.send(st.error_reply(stanza, "cancel", "service-unavailable")); return; end
681 if form.attr.type == "cancel" then origin.send(st.reply(stanza)); return; end
682 if form.attr.type ~= "submit" then origin.send(st.error_reply(stanza, "cancel", "bad-request", "Not a submitted form")); return; end
684 if form.tags[1] == nil then
686 if self.save then self:save(true); end
687 origin.send(st.reply(stanza));
691 local fields, errors, present = self:get_form_layout(stanza.attr.from):data(form);
692 if fields.FORM_TYPE ~= "http://jabber.org/protocol/muc#roomconfig" then
693 origin.send(st.error_reply(stanza, "cancel", "bad-request", "Form is not of type room configuration"));
699 local function handle_option(name, field, allowed)
700 if not present[field] then return; end
701 local new = fields[field];
702 if allowed and not allowed[new] then return; end
703 if new == self["get_"..name](self) then return; end
704 changed[name] = true;
705 self["set_"..name](self, new);
708 local event = { room = self, fields = fields, changed = changed, stanza = stanza, origin = origin, update_option = handle_option };
709 module:fire_event("muc-config-submitted", event);
711 handle_option("name", "muc#roomconfig_roomname");
712 handle_option("description", "muc#roomconfig_roomdesc");
713 handle_option("persistent", "muc#roomconfig_persistentroom");
714 handle_option("moderated", "muc#roomconfig_moderatedroom");
715 handle_option("members_only", "muc#roomconfig_membersonly");
716 handle_option("public", "muc#roomconfig_publicroom");
717 handle_option("changesubject", "muc#roomconfig_changesubject");
718 handle_option("historylength", "muc#roomconfig_historylength");
719 handle_option("whois", "muc#roomconfig_whois", valid_whois);
720 handle_option("password", "muc#roomconfig_roomsecret");
722 if self.save then self:save(true); end
724 module:fire_event("muc-room-unlocked", { room = self });
727 origin.send(st.reply(stanza));
729 if next(changed) then
730 local msg = st.message({type='groupchat', from=self.jid})
731 :tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
732 :tag('status', {code = '104'}):up();
733 if changed.whois then
734 local code = (self:get_whois() == 'moderators') and "173" or "172";
735 msg.tags[1]:tag('status', {code = code}):up();
737 self:broadcast_message(msg, false)
741 function room_mt:destroy(newjid, reason, password)
742 local pr = st.presence({type = "unavailable"})
743 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
744 :tag("item", { affiliation='none', role='none' }):up()
745 :tag("destroy", {jid=newjid})
746 if reason then pr:tag("reason"):text(reason):up(); end
747 if password then pr:tag("password"):text(password):up(); end
748 for nick, occupant in pairs(self._occupants) do
750 for jid in pairs(occupant.sessions) do
752 self:_route_stanza(pr);
753 self._jid_nick[jid] = nil;
755 self._occupants[nick] = nil;
757 self:set_persistent(false);
758 module:fire_event("muc-room-destroyed", { room = self });
761 function room_mt:handle_to_room(origin, stanza) -- presence changes and groupchat messages, along with disco/etc
762 local type = stanza.attr.type;
763 local xmlns = stanza.tags[1] and stanza.tags[1].attr.xmlns;
764 if stanza.name == "iq" then
765 if xmlns == "http://jabber.org/protocol/disco#info" and type == "get" and not stanza.tags[1].attr.node then
766 origin.send(self:get_disco_info(stanza));
767 elseif xmlns == "http://jabber.org/protocol/disco#items" and type == "get" and not stanza.tags[1].attr.node then
768 origin.send(self:get_disco_items(stanza));
769 elseif xmlns == "http://jabber.org/protocol/muc#admin" then
770 local actor = stanza.attr.from;
771 local affiliation = self:get_affiliation(actor);
772 local current_nick = self._jid_nick[actor];
773 local role = current_nick and self._occupants[current_nick].role or self:get_default_role(affiliation);
774 local item = stanza.tags[1].tags[1];
775 if item and item.name == "item" then
776 if type == "set" then
777 local callback = function() origin.send(st.reply(stanza)); end
778 if item.attr.jid then -- Validate provided JID
779 item.attr.jid = jid_prep(item.attr.jid);
780 if not item.attr.jid then
781 origin.send(st.error_reply(stanza, "modify", "jid-malformed"));
785 if not item.attr.jid and item.attr.nick then -- COMPAT Workaround for Miranda sending 'nick' instead of 'jid' when changing affiliation
786 local occupant = self._occupants[self.jid.."/"..item.attr.nick];
787 if occupant then item.attr.jid = occupant.jid; end
788 elseif not item.attr.nick and item.attr.jid then
789 local nick = self._jid_nick[item.attr.jid];
790 if nick then item.attr.nick = select(3, jid_split(nick)); end
792 local reason = item.tags[1] and item.tags[1].name == "reason" and #item.tags[1] == 1 and item.tags[1][1];
793 if item.attr.affiliation and item.attr.jid and not item.attr.role then
794 local success, errtype, err = self:set_affiliation(actor, item.attr.jid, item.attr.affiliation, callback, reason);
795 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
796 elseif item.attr.role and item.attr.nick and not item.attr.affiliation then
797 local success, errtype, err = self:set_role(actor, self.jid.."/"..item.attr.nick, item.attr.role, callback, reason);
798 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
800 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
802 elseif type == "get" then
803 local _aff = item.attr.affiliation;
804 local _rol = item.attr.role;
805 if _aff and not _rol then
806 if affiliation == "owner" or (affiliation == "admin" and _aff ~= "owner" and _aff ~= "admin")
807 or (affiliation and affiliation ~= "outcast" and self:get_members_only() and self:get_whois() == "anyone") then
808 local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
809 for jid, affiliation in pairs(self._affiliations) do
810 if affiliation == _aff then
811 reply:tag("item", {affiliation = _aff, jid = jid}):up();
816 origin.send(st.error_reply(stanza, "auth", "forbidden"));
818 elseif _rol and not _aff then
819 if role == "moderator" then
820 -- TODO allow admins and owners not in room? Provide read-only access to everyone who can see the participants anyway?
821 if _rol == "none" then _rol = nil; end
822 local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
823 for occupant_jid, occupant in pairs(self._occupants) do
824 if occupant.role == _rol then
826 nick = select(3, jid_split(occupant_jid)),
827 role = _rol or "none",
828 affiliation = occupant.affiliation or "none",
835 origin.send(st.error_reply(stanza, "auth", "forbidden"));
838 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
841 elseif type == "set" or type == "get" then
842 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
844 elseif xmlns == "http://jabber.org/protocol/muc#owner" and (type == "get" or type == "set") and stanza.tags[1].name == "query" then
845 if self:get_affiliation(stanza.attr.from) ~= "owner" then
846 origin.send(st.error_reply(stanza, "auth", "forbidden", "Only owners can configure rooms"));
847 elseif stanza.attr.type == "get" then
848 self:send_form(origin, stanza);
849 elseif stanza.attr.type == "set" then
850 local child = stanza.tags[1].tags[1];
852 origin.send(st.error_reply(stanza, "modify", "bad-request"));
853 elseif child.name == "destroy" then
854 local newjid = child.attr.jid;
855 local reason, password;
856 for _,tag in ipairs(child.tags) do
857 if tag.name == "reason" then
858 reason = #tag.tags == 0 and tag[1];
859 elseif tag.name == "password" then
860 password = #tag.tags == 0 and tag[1];
863 self:destroy(newjid, reason, password);
864 origin.send(st.reply(stanza));
866 self:process_form(origin, stanza);
869 elseif type == "set" or type == "get" then
870 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
872 elseif stanza.name == "message" and type == "groupchat" then
873 local from = stanza.attr.from;
874 local current_nick = self._jid_nick[from];
875 local occupant = self._occupants[current_nick];
876 if not occupant then -- not in room
877 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
878 elseif occupant.role == "visitor" then
879 origin.send(st.error_reply(stanza, "auth", "forbidden"));
881 local from = stanza.attr.from;
882 stanza.attr.from = current_nick;
883 local subject = stanza:get_child_text("subject");
885 if occupant.role == "moderator" or
886 ( self._data.changesubject and occupant.role == "participant" ) then -- and participant
887 self:set_subject(current_nick, subject);
889 stanza.attr.from = from;
890 origin.send(st.error_reply(stanza, "auth", "forbidden"));
893 self:broadcast_message(stanza, self:get_historylength() > 0 and stanza:get_child("body"));
895 stanza.attr.from = from;
897 elseif stanza.name == "message" and type == "error" and is_kickable_error(stanza) then
898 local current_nick = self._jid_nick[stanza.attr.from];
899 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
900 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza)); -- send unavailable
901 elseif stanza.name == "presence" then -- hack - some buggy clients send presence updates to the room rather than their nick
902 local to = stanza.attr.to;
903 local current_nick = self._jid_nick[stanza.attr.from];
905 stanza.attr.to = current_nick;
906 self:handle_to_occupant(origin, stanza);
908 elseif type ~= "error" and type ~= "result" then
909 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
911 elseif stanza.name == "message" and not(type == "chat" or type == "error" or type == "groupchat" or type == "headline") and #stanza.tags == 1
912 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
913 local x = stanza.tags[1];
914 local payload = (#x.tags == 1 and x.tags[1]);
915 if payload and payload.name == "invite" and payload.attr.to then
916 local _from, _to = stanza.attr.from, stanza.attr.to;
917 local _invitee = jid_prep(payload.attr.to);
919 local _reason = payload.tags[1] and payload.tags[1].name == 'reason' and #payload.tags[1].tags == 0 and payload.tags[1][1];
920 local invite = st.message({from = _to, to = _invitee, id = stanza.attr.id})
921 :tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
922 :tag('invite', {from=_from})
923 :tag('reason'):text(_reason or ""):up()
925 if self:get_password() then
926 invite:tag("password"):text(self:get_password()):up();
929 :tag('x', {xmlns="jabber:x:conference", jid=_to}) -- COMPAT: Some older clients expect this
932 :tag('body') -- Add a plain message for clients which don't support invites
933 :text(_from..' invited you to the room '.._to..(_reason and (' ('.._reason..')') or ""))
935 if self:get_members_only() and not self:get_affiliation(_invitee) then
936 log("debug", "%s invited %s into members only room %s, granting membership", _from, _invitee, _to);
937 self:set_affiliation(_from, _invitee, "member", nil, "Invited by " .. self._jid_nick[_from])
939 self:_route_stanza(invite);
941 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
944 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
947 if type == "error" or type == "result" then return; end
948 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
952 function room_mt:handle_stanza(origin, stanza)
953 local to_node, to_host, to_resource = jid_split(stanza.attr.to);
955 self:handle_to_occupant(origin, stanza);
957 self:handle_to_room(origin, stanza);
961 function room_mt:route_stanza(stanza) end -- Replace with a routing function, e.g., function(room, stanza) core_route_stanza(origin, stanza); end
963 function room_mt:get_affiliation(jid)
964 local node, host, resource = jid_split(jid);
965 local bare = node and node.."@"..host or host;
966 local result = self._affiliations[bare]; -- Affiliations are granted, revoked, and maintained based on the user's bare JID.
967 if not result and self._affiliations[host] == "outcast" then result = "outcast"; end -- host banned
970 function room_mt:set_affiliation(actor, jid, affiliation, callback, reason)
972 if affiliation == "none" then affiliation = nil; end
973 if affiliation and affiliation ~= "outcast" and affiliation ~= "owner" and affiliation ~= "admin" and affiliation ~= "member" then
974 return nil, "modify", "not-acceptable";
976 if actor ~= true then
977 local actor_affiliation = self:get_affiliation(actor);
978 local target_affiliation = self:get_affiliation(jid);
979 if target_affiliation == affiliation then -- no change, shortcut
980 if callback then callback(); end
983 if actor_affiliation ~= "owner" then
984 if affiliation == "owner" or affiliation == "admin" or actor_affiliation ~= "admin" or target_affiliation == "owner" or target_affiliation == "admin" then
985 return nil, "cancel", "not-allowed";
987 elseif target_affiliation == "owner" and jid_bare(actor) == jid then -- self change
988 local is_last = true;
989 for j, aff in pairs(self._affiliations) do if j ~= jid and aff == "owner" then is_last = false; break; end end
991 return nil, "cancel", "conflict";
995 self._affiliations[jid] = affiliation;
996 local role = self:get_default_role(affiliation);
997 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"})
998 :tag("item", {affiliation=affiliation or "none", role=role or "none"})
999 :tag("reason"):text(reason or ""):up()
1001 local presence_type = nil;
1002 if not role then -- getting kicked
1003 presence_type = "unavailable";
1004 if affiliation == "outcast" then
1005 x:tag("status", {code="301"}):up(); -- banned
1007 x:tag("status", {code="321"}):up(); -- affiliation change
1010 local modified_nicks = {};
1011 for nick, occupant in pairs(self._occupants) do
1012 if jid_bare(occupant.jid) == jid then
1013 if not role then -- getting kicked
1014 self._occupants[nick] = nil;
1016 occupant.affiliation, occupant.role = affiliation, role;
1018 for jid,pres in pairs(occupant.sessions) do -- remove for all sessions of the nick
1019 if not role then self._jid_nick[jid] = nil; end
1020 local p = st.clone(pres);
1022 p.attr.type = presence_type;
1025 self:_route_stanza(p);
1026 if occupant.jid == jid then
1027 modified_nicks[nick] = p;
1032 if self.save then self:save(); end
1033 if callback then callback(); end
1034 for nick,p in pairs(modified_nicks) do
1036 self:broadcast_except_nick(p, nick);
1041 function room_mt:get_role(nick)
1042 local session = self._occupants[nick];
1043 return session and session.role or nil;
1045 function room_mt:can_set_role(actor_jid, occupant_jid, role)
1046 local occupant = self._occupants[occupant_jid];
1047 if not occupant or not actor_jid then return nil, "modify", "not-acceptable"; end
1049 if actor_jid == true then return true; end
1051 local actor = self._occupants[self._jid_nick[actor_jid]];
1052 if actor and actor.role == "moderator" then
1053 if occupant.affiliation ~= "owner" and occupant.affiliation ~= "admin" then
1054 if actor.affiliation == "owner" or actor.affiliation == "admin" then
1056 elseif occupant.role ~= "moderator" and role ~= "moderator" then
1061 return nil, "cancel", "not-allowed";
1063 function room_mt:set_role(actor, occupant_jid, role, callback, reason)
1064 if role == "none" then role = nil; end
1065 if role and role ~= "moderator" and role ~= "participant" and role ~= "visitor" then return nil, "modify", "not-acceptable"; end
1066 local allowed, err_type, err_condition = self:can_set_role(actor, occupant_jid, role);
1067 if not allowed then return allowed, err_type, err_condition; end
1068 local occupant = self._occupants[occupant_jid];
1069 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"})
1070 :tag("item", {affiliation=occupant.affiliation or "none", nick=select(3, jid_split(occupant_jid)), role=role or "none"})
1071 :tag("reason"):text(reason or ""):up()
1073 local presence_type = nil;
1074 if not role then -- kick
1075 presence_type = "unavailable";
1076 self._occupants[occupant_jid] = nil;
1077 for jid in pairs(occupant.sessions) do -- remove for all sessions of the nick
1078 self._jid_nick[jid] = nil;
1080 x:tag("status", {code = "307"}):up();
1082 occupant.role = role;
1085 for jid,pres in pairs(occupant.sessions) do -- send to all sessions of the nick
1086 local p = st.clone(pres);
1087 p.attr.from = occupant_jid;
1088 p.attr.type = presence_type;
1091 self:_route_stanza(p);
1092 if occupant.jid == jid then
1096 if callback then callback(); end
1098 self:broadcast_except_nick(bp, occupant_jid);
1103 function room_mt:_route_stanza(stanza)
1105 local to_occupant = self._occupants[self._jid_nick[stanza.attr.to]];
1106 local from_occupant = self._occupants[stanza.attr.from];
1107 if stanza.name == "presence" then
1108 if to_occupant and from_occupant then
1109 if self._data.whois == 'anyone' then
1110 muc_child = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
1112 if to_occupant.role == "moderator" or jid_bare(to_occupant.jid) == jid_bare(from_occupant.jid) then
1113 muc_child = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
1119 for _, item in pairs(muc_child.tags) do
1120 if item.name == "item" then
1121 if from_occupant == to_occupant then
1122 item.attr.jid = stanza.attr.to;
1124 item.attr.jid = from_occupant.jid;
1129 self:route_stanza(stanza);
1131 for _, item in pairs(muc_child.tags) do
1132 if item.name == "item" then
1133 item.attr.jid = nil;
1139 local _M = {}; -- module "muc"
1141 function _M.new_room(jid, config)
1142 return setmetatable({
1147 whois = 'moderators';
1148 history_length = math.min((config and config.history_length)
1149 or default_history_length, max_history_length);
1155 function _M.set_max_history_length(_max_history_length)
1156 max_history_length = _max_history_length or math.huge;
1159 _M.room_mt = room_mt;