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 local history = self._data['history'];
111 if not history then history = {}; self._data['history'] = history; end
112 stanza = st.clone(stanza);
114 local stamp = datetime.datetime();
115 stanza:tag("delay", {xmlns = "urn:xmpp:delay", from = muc_domain, stamp = stamp}):up(); -- XEP-0203
116 stanza:tag("x", {xmlns = "jabber:x:delay", from = muc_domain, stamp = datetime.legacy()}):up(); -- XEP-0091 (deprecated)
117 local entry = { stanza = stanza, stamp = stamp };
118 t_insert(history, entry);
119 while #history > (self._data.history_length or default_history_length) do t_remove(history, 1) end
122 function room_mt:broadcast_except_nick(stanza, nick)
123 for rnick, occupant in pairs(self._occupants) do
124 if rnick ~= nick then
125 for jid in pairs(occupant.sessions) do
126 stanza.attr.to = jid;
127 self:_route_stanza(stanza);
133 function room_mt:send_occupant_list(to)
134 local current_nick = self._jid_nick[to];
135 for occupant, o_data in pairs(self._occupants) do
136 if occupant ~= current_nick then
137 local pres = get_filtered_presence(o_data.sessions[o_data.jid]);
138 pres.attr.to, pres.attr.from = to, occupant;
139 pres:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
140 :tag("item", {affiliation=o_data.affiliation or "none", role=o_data.role or "none"}):up();
141 self:_route_stanza(pres);
145 function room_mt:send_history(to, stanza)
146 local history = self._data['history']; -- send discussion history
148 local x_tag = stanza and stanza:get_child("x", "http://jabber.org/protocol/muc");
149 local history_tag = x_tag and x_tag:get_child("history", "http://jabber.org/protocol/muc");
151 local maxchars = history_tag and tonumber(history_tag.attr.maxchars);
152 if maxchars then maxchars = math.floor(maxchars); end
154 local maxstanzas = math.floor(history_tag and tonumber(history_tag.attr.maxstanzas) or #history);
155 if not history_tag then maxstanzas = 20; end
157 local seconds = history_tag and tonumber(history_tag.attr.seconds);
158 if seconds then seconds = datetime.datetime(os.time() - math.floor(seconds)); end
160 local since = history_tag and history_tag.attr.since;
161 if since then since = datetime.parse(since); since = since and datetime.datetime(since); end
162 if seconds and (not since or since < seconds) then since = seconds; end
167 for i=#history,1,-1 do
168 local entry = history[i];
170 if not entry.chars then
171 entry.stanza.attr.to = "";
172 entry.chars = #tostring(entry.stanza);
174 charcount = charcount + entry.chars + #to;
175 if charcount > maxchars then break; end
177 if since and since > entry.stamp then break; end
178 if n + 1 > maxstanzas then break; end
181 for i=#history-n+1,#history do
182 local msg = history[i].stanza;
184 self:_route_stanza(msg);
187 if self._data['subject'] then
188 self:_route_stanza(st.message({type='groupchat', from=self._data['subject_from'] or self.jid, to=to}):tag("subject"):text(self._data['subject']));
192 function room_mt:get_disco_info(stanza)
193 local count = 0; for _ in pairs(self._occupants) do count = count + 1; end
194 return st.reply(stanza):query("http://jabber.org/protocol/disco#info")
195 :tag("identity", {category="conference", type="text", name=self:get_name()}):up()
196 :tag("feature", {var="http://jabber.org/protocol/muc"}):up()
197 :tag("feature", {var=self:get_password() and "muc_passwordprotected" or "muc_unsecured"}):up()
198 :tag("feature", {var=self:get_moderated() and "muc_moderated" or "muc_unmoderated"}):up()
199 :tag("feature", {var=self:get_members_only() and "muc_membersonly" or "muc_open"}):up()
200 :tag("feature", {var=self:get_persistent() and "muc_persistent" or "muc_temporary"}):up()
201 :tag("feature", {var=self:get_hidden() and "muc_hidden" or "muc_public"}):up()
202 :tag("feature", {var=self._data.whois ~= "anyone" and "muc_semianonymous" or "muc_nonanonymous"}):up()
203 :add_child(dataform.new({
204 { name = "FORM_TYPE", type = "hidden", value = "http://jabber.org/protocol/muc#roominfo" },
205 { name = "muc#roominfo_description", label = "Description"},
206 { name = "muc#roominfo_occupants", label = "Number of occupants", value = tostring(count) }
207 }):form({["muc#roominfo_description"] = self:get_description()}, 'result'))
210 function room_mt:get_disco_items(stanza)
211 local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#items");
212 for room_jid in pairs(self._occupants) do
213 reply:tag("item", {jid = room_jid, name = room_jid:match("/(.*)")}):up();
217 function room_mt:set_subject(current_nick, subject)
218 if subject == "" then subject = nil; end
219 self._data['subject'] = subject;
220 self._data['subject_from'] = current_nick;
221 if self.save then self:save(); end
222 local msg = st.message({type='groupchat', from=current_nick})
223 :tag('subject'):text(subject):up();
224 self:broadcast_message(msg, false);
228 local function build_unavailable_presence_from_error(stanza)
229 local type, condition, text = stanza:get_error();
230 local error_message = "Kicked: "..(condition and condition:gsub("%-", " ") or "presence error");
232 error_message = error_message..": "..text;
234 return st.presence({type='unavailable', from=stanza.attr.from, to=stanza.attr.to})
235 :tag('status'):text(error_message);
238 function room_mt:set_name(name)
239 if name == "" or type(name) ~= "string" or name == (jid_split(self.jid)) then name = nil; end
240 if self._data.name ~= name then
241 self._data.name = name;
242 if self.save then self:save(true); end
245 function room_mt:get_name()
246 return self._data.name or jid_split(self.jid);
248 function room_mt:set_description(description)
249 if description == "" or type(description) ~= "string" then description = nil; end
250 if self._data.description ~= description then
251 self._data.description = description;
252 if self.save then self:save(true); end
255 function room_mt:get_description()
256 return self._data.description;
258 function room_mt:set_password(password)
259 if password == "" or type(password) ~= "string" then password = nil; end
260 if self._data.password ~= password then
261 self._data.password = password;
262 if self.save then self:save(true); end
265 function room_mt:get_password()
266 return self._data.password;
268 function room_mt:set_moderated(moderated)
269 moderated = moderated and true or nil;
270 if self._data.moderated ~= moderated then
271 self._data.moderated = moderated;
272 if self.save then self:save(true); end
275 function room_mt:get_moderated()
276 return self._data.moderated;
278 function room_mt:set_members_only(members_only)
279 members_only = members_only and true or nil;
280 if self._data.members_only ~= members_only then
281 self._data.members_only = members_only;
282 if self.save then self:save(true); end
285 function room_mt:get_members_only()
286 return self._data.members_only;
288 function room_mt:set_persistent(persistent)
289 persistent = persistent and true or nil;
290 if self._data.persistent ~= persistent then
291 self._data.persistent = persistent;
292 if self.save then self:save(true); end
295 function room_mt:get_persistent()
296 return self._data.persistent;
298 function room_mt:set_hidden(hidden)
299 hidden = hidden and true or nil;
300 if self._data.hidden ~= hidden then
301 self._data.hidden = hidden;
302 if self.save then self:save(true); end
305 function room_mt:get_hidden()
306 return self._data.hidden;
308 function room_mt:get_public()
309 return not self:get_hidden();
311 function room_mt:set_public(public)
312 return self:set_hidden(not public);
314 function room_mt:set_changesubject(changesubject)
315 changesubject = changesubject and true or nil;
316 if self._data.changesubject ~= changesubject then
317 self._data.changesubject = changesubject;
318 if self.save then self:save(true); end
321 function room_mt:get_changesubject()
322 return self._data.changesubject;
324 function room_mt:get_historylength()
325 return self._data.history_length or default_history_length;
327 function room_mt:set_historylength(length)
328 length = math.min(tonumber(length) or default_history_length, max_history_length or math.huge);
329 if length == default_history_length then
332 self._data.history_length = length;
336 local valid_whois = { moderators = true, anyone = true };
338 function room_mt:set_whois(whois)
339 if valid_whois[whois] and self._data.whois ~= whois then
340 self._data.whois = whois;
341 if self.save then self:save(true); end
345 function room_mt:get_whois()
346 return self._data.whois;
349 local function construct_stanza_id(room, stanza)
350 local from_jid, to_nick = stanza.attr.from, stanza.attr.to;
351 local from_nick = room._jid_nick[from_jid];
352 local occupant = room._occupants[to_nick];
353 local to_jid = occupant.jid;
355 return from_nick, to_jid, base64.encode(to_jid.."\0"..stanza.attr.id.."\0"..md5(from_jid));
357 local function deconstruct_stanza_id(room, stanza)
358 local from_jid_possiblybare, to_nick = stanza.attr.from, stanza.attr.to;
359 local from_jid, id, to_jid_hash = (base64.decode(stanza.attr.id) or ""):match("^(.+)%z(.*)%z(.+)$");
360 local from_nick = room._jid_nick[from_jid];
362 if not(from_nick) then return; end
363 if not(from_jid_possiblybare == from_jid or from_jid_possiblybare == jid_bare(from_jid)) then return; end
365 local occupant = room._occupants[to_nick];
366 for to_jid in pairs(occupant and occupant.sessions or {}) do
367 if md5(to_jid) == to_jid_hash then
368 return from_nick, to_jid, id;
374 function room_mt:handle_to_occupant(origin, stanza) -- PM, vCards, etc
375 local from, to = stanza.attr.from, stanza.attr.to;
376 local room = jid_bare(to);
377 local current_nick = self._jid_nick[from];
378 local type = stanza.attr.type;
379 log("debug", "room: %s, current_nick: %s, stanza: %s", room or "nil", current_nick or "nil", stanza:top_tag());
380 if (select(2, jid_split(from)) == muc_domain) then error("Presence from the MUC itself!!!"); end
381 if stanza.name == "presence" then
382 local pr = get_filtered_presence(stanza);
383 pr.attr.from = current_nick;
384 if type == "error" then -- error, kick em out!
386 log("debug", "kicking %s from %s", current_nick, room);
387 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza));
389 elseif type == "unavailable" then -- unavailable
391 log("debug", "%s leaving %s", current_nick, room);
392 self._jid_nick[from] = nil;
393 local occupant = self._occupants[current_nick];
394 local new_jid = next(occupant.sessions);
395 if new_jid == from then new_jid = next(occupant.sessions, new_jid); end
397 local jid = occupant.jid;
398 occupant.jid = new_jid;
399 occupant.sessions[from] = nil;
401 pr:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
402 :tag("item", {affiliation=occupant.affiliation or "none", role='none'}):up()
403 :tag("status", {code='110'}):up();
404 self:_route_stanza(pr);
405 if jid ~= new_jid then
406 pr = st.clone(occupant.sessions[new_jid])
407 :tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
408 :tag("item", {affiliation=occupant.affiliation or "none", role=occupant.role or "none"});
409 pr.attr.from = current_nick;
410 self:broadcast_except_nick(pr, current_nick);
413 occupant.role = 'none';
414 self:broadcast_presence(pr, from);
415 self._occupants[current_nick] = nil;
418 elseif not type then -- available
420 --if #pr == #stanza or current_nick ~= to then -- commented because google keeps resending directed presence
421 if current_nick == to then -- simple presence
422 log("debug", "%s broadcasted presence", current_nick);
423 self._occupants[current_nick].sessions[from] = pr;
424 self:broadcast_presence(pr, from);
426 local occupant = self._occupants[current_nick];
427 local is_multisession = next(occupant.sessions, next(occupant.sessions));
428 if self._occupants[to] or is_multisession then
429 log("debug", "%s couldn't change nick", current_nick);
430 local reply = st.error_reply(stanza, "cancel", "conflict"):up();
431 reply.tags[1].attr.code = "409";
432 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
434 local data = self._occupants[current_nick];
435 local to_nick = select(3, jid_split(to));
437 log("debug", "%s (%s) changing nick to %s", current_nick, data.jid, to);
438 local p = st.presence({type='unavailable', from=current_nick});
439 self:broadcast_presence(p, from, '303', to_nick);
440 self._occupants[current_nick] = nil;
441 self._occupants[to] = data;
442 self._jid_nick[from] = to;
444 self._occupants[to].sessions[from] = pr;
445 self:broadcast_presence(pr, from);
451 --else -- possible rejoin
452 -- log("debug", "%s had connection replaced", current_nick);
453 -- self:handle_to_occupant(origin, st.presence({type='unavailable', from=from, to=to})
454 -- :tag('status'):text('Replaced by new connection'):up()); -- send unavailable
455 -- self:handle_to_occupant(origin, stanza); -- resend available
460 if self._occupants[to] then
461 if jid_bare(from) ~= jid_bare(self._occupants[to].jid) then
466 local password = stanza:get_child("x", "http://jabber.org/protocol/muc");
467 password = password and password:get_child("password", "http://jabber.org/protocol/muc");
468 password = password and password[1] ~= "" and password[1];
469 if self:get_password() and self:get_password() ~= password then
470 log("debug", "%s couldn't join due to invalid password: %s", from, to);
471 local reply = st.error_reply(stanza, "auth", "not-authorized"):up();
472 reply.tags[1].attr.code = "401";
473 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
474 elseif not new_nick then
475 log("debug", "%s couldn't join due to nick conflict: %s", from, to);
476 local reply = st.error_reply(stanza, "cancel", "conflict"):up();
477 reply.tags[1].attr.code = "409";
478 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
480 log("debug", "%s joining as %s", from, to);
481 if not next(self._affiliations) then -- new room, no owners
482 self._affiliations[jid_bare(from)] = "owner";
483 if self.locked and not stanza:get_child("x", "http://jabber.org/protocol/muc") then
484 self.locked = nil; -- Older groupchat protocol doesn't lock
486 elseif self.locked then -- Deny entry
487 origin.send(st.error_reply(stanza, "cancel", "item-not-found"));
490 local affiliation = self:get_affiliation(from);
491 local role = self:get_default_role(affiliation)
492 if role then -- new occupant
494 self._occupants[to] = {affiliation=affiliation, role=role, jid=from, sessions={[from]=get_filtered_presence(stanza)}};
496 self._occupants[to].sessions[from] = get_filtered_presence(stanza);
498 self._jid_nick[from] = to;
499 self:send_occupant_list(from);
501 pr:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
502 :tag("item", {affiliation=affiliation or "none", role=role or "none"}):up();
504 self:broadcast_except_nick(pr, to);
506 pr:tag("status", {code='110'}):up();
507 if self._data.whois == 'anyone' then
508 pr:tag("status", {code='100'}):up();
511 pr:tag("status", {code='201'}):up();
514 self:_route_stanza(pr);
515 self:send_history(from, stanza);
516 elseif not affiliation then -- registration required for entering members-only room
517 local reply = st.error_reply(stanza, "auth", "registration-required"):up();
518 reply.tags[1].attr.code = "407";
519 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
521 local reply = st.error_reply(stanza, "auth", "forbidden"):up();
522 reply.tags[1].attr.code = "403";
523 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
527 elseif type ~= 'result' then -- bad type
528 if type ~= 'visible' and type ~= 'invisible' then -- COMPAT ejabberd can broadcast or forward XEP-0018 presences
529 origin.send(st.error_reply(stanza, "modify", "bad-request")); -- FIXME correct error?
532 elseif not current_nick then -- not in room
533 if (type == "error" or type == "result") and stanza.name == "iq" then
534 local id = stanza.attr.id;
535 stanza.attr.from, stanza.attr.to, stanza.attr.id = deconstruct_stanza_id(self, stanza);
536 if stanza.attr.id then
537 self:_route_stanza(stanza);
539 stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
540 elseif type ~= "error" then
541 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
543 elseif stanza.name == "message" and type == "groupchat" then -- groupchat messages not allowed in PM
544 origin.send(st.error_reply(stanza, "modify", "bad-request"));
545 elseif current_nick and stanza.name == "message" and type == "error" and is_kickable_error(stanza) then
546 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
547 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza)); -- send unavailable
548 else -- private stanza
549 local o_data = self._occupants[to];
551 log("debug", "%s sent private stanza to %s (%s)", from, to, o_data.jid);
552 if stanza.name == "iq" then
553 local id = stanza.attr.id;
554 if stanza.attr.type == "get" or stanza.attr.type == "set" then
555 stanza.attr.from, stanza.attr.to, stanza.attr.id = construct_stanza_id(self, stanza);
557 stanza.attr.from, stanza.attr.to, stanza.attr.id = deconstruct_stanza_id(self, stanza);
559 if type == 'get' and stanza.tags[1].attr.xmlns == 'vcard-temp' then
560 stanza.attr.to = jid_bare(stanza.attr.to);
562 if stanza.attr.id then
563 self:_route_stanza(stanza);
565 stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
567 stanza.attr.from = current_nick;
568 for jid in pairs(o_data.sessions) do
569 stanza.attr.to = jid;
570 self:_route_stanza(stanza);
572 stanza.attr.from, stanza.attr.to = from, to;
574 elseif type ~= "error" and type ~= "result" then -- recipient not in room
575 origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
580 function room_mt:send_form(origin, stanza)
581 origin.send(st.reply(stanza):query("http://jabber.org/protocol/muc#owner")
582 :add_child(self:get_form_layout(stanza.attr.from):form())
586 function room_mt:get_form_layout(actor)
587 local form = dataform.new({
588 title = "Configuration for "..self.jid,
589 instructions = "Complete and submit this form to configure the room.",
593 value = 'http://jabber.org/protocol/muc#roomconfig'
596 name = 'muc#roomconfig_roomname',
597 type = 'text-single',
599 value = self:get_name() or "",
602 name = 'muc#roomconfig_roomdesc',
603 type = 'text-single',
604 label = 'Description',
605 value = self:get_description() or "",
608 name = 'muc#roomconfig_persistentroom',
610 label = 'Make Room Persistent?',
611 value = self:get_persistent()
614 name = 'muc#roomconfig_publicroom',
616 label = 'Make Room Publicly Searchable?',
617 value = not self:get_hidden()
620 name = 'muc#roomconfig_changesubject',
622 label = 'Allow Occupants to Change Subject?',
623 value = self:get_changesubject()
626 name = 'muc#roomconfig_whois',
627 type = 'list-single',
628 label = 'Who May Discover Real JIDs?',
630 { value = 'moderators', label = 'Moderators Only', default = self._data.whois == 'moderators' },
631 { value = 'anyone', label = 'Anyone', default = self._data.whois == 'anyone' }
635 name = 'muc#roomconfig_roomsecret',
636 type = 'text-private',
638 value = self:get_password() or "",
641 name = 'muc#roomconfig_moderatedroom',
643 label = 'Make Room Moderated?',
644 value = self:get_moderated()
647 name = 'muc#roomconfig_membersonly',
649 label = 'Make Room Members-Only?',
650 value = self:get_members_only()
653 name = 'muc#roomconfig_historylength',
654 type = 'text-single',
655 label = 'Maximum Number of History Messages Returned by Room',
656 value = tostring(self:get_historylength())
659 return module:fire_event("muc-config-form", { room = self, actor = actor, form = form }) or form;
662 function room_mt:process_form(origin, stanza)
663 local query = stanza.tags[1];
665 for _, tag in ipairs(query.tags) do if tag.name == "x" and tag.attr.xmlns == "jabber:x:data" then form = tag; break; end end
666 if not form then origin.send(st.error_reply(stanza, "cancel", "service-unavailable")); return; end
667 if form.attr.type == "cancel" then origin.send(st.reply(stanza)); return; end
668 if form.attr.type ~= "submit" then origin.send(st.error_reply(stanza, "cancel", "bad-request", "Not a submitted form")); return; end
670 local fields = self:get_form_layout(stanza.attr.from):data(form);
671 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 function handle_option(name, field, allowed)
677 local new = fields[field];
678 if new == nil then return; end
679 if allowed and not allowed[new] then return; end
680 if new == self["get_"..name](self) then return; end
681 changed[name] = true;
682 self["set_"..name](self, new);
685 local event = { room = self, fields = fields, changed = changed, stanza = stanza, origin = origin, update_option = handle_option };
686 module:fire_event("muc-config-submitted", event);
688 handle_option("name", "muc#roomconfig_roomname");
689 handle_option("description", "muc#roomconfig_roomdesc");
690 handle_option("persistent", "muc#roomconfig_persistentroom");
691 handle_option("moderated", "muc#roomconfig_moderatedroom");
692 handle_option("members_only", "muc#roomconfig_membersonly");
693 handle_option("public", "muc#roomconfig_publicroom");
694 handle_option("changesubject", "muc#roomconfig_changesubject");
695 handle_option("historylength", "muc#roomconfig_historylength");
696 handle_option("whois", "muc#roomconfig_whois", valid_whois);
697 handle_option("password", "muc#roomconfig_roomsecret");
699 if self.save then self:save(true); end
701 module:fire_event("muc-room-unlocked", { room = self });
704 origin.send(st.reply(stanza));
706 if next(changed) then
707 local msg = st.message({type='groupchat', from=self.jid})
708 :tag('x', {xmlns='http://jabber.org/protocol/muc#user'}):up()
709 :tag('status', {code = '104'}):up();
710 if changed.whois then
711 local code = (self:get_whois() == 'moderators') and "173" or "172";
712 msg.tags[1]:tag('status', {code = code}):up();
714 self:broadcast_message(msg, false)
718 function room_mt:destroy(newjid, reason, password)
719 local pr = st.presence({type = "unavailable"})
720 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
721 :tag("item", { affiliation='none', role='none' }):up()
722 :tag("destroy", {jid=newjid})
723 if reason then pr:tag("reason"):text(reason):up(); end
724 if password then pr:tag("password"):text(password):up(); end
725 for nick, occupant in pairs(self._occupants) do
727 for jid in pairs(occupant.sessions) do
729 self:_route_stanza(pr);
730 self._jid_nick[jid] = nil;
732 self._occupants[nick] = nil;
734 self:set_persistent(false);
735 module:fire_event("muc-room-destroyed", { room = self });
738 function room_mt:handle_to_room(origin, stanza) -- presence changes and groupchat messages, along with disco/etc
739 local type = stanza.attr.type;
740 local xmlns = stanza.tags[1] and stanza.tags[1].attr.xmlns;
741 if stanza.name == "iq" then
742 if xmlns == "http://jabber.org/protocol/disco#info" and type == "get" and not stanza.tags[1].attr.node then
743 origin.send(self:get_disco_info(stanza));
744 elseif xmlns == "http://jabber.org/protocol/disco#items" and type == "get" and not stanza.tags[1].attr.node then
745 origin.send(self:get_disco_items(stanza));
746 elseif xmlns == "http://jabber.org/protocol/muc#admin" then
747 local actor = stanza.attr.from;
748 local affiliation = self:get_affiliation(actor);
749 local current_nick = self._jid_nick[actor];
750 local role = current_nick and self._occupants[current_nick].role or self:get_default_role(affiliation);
751 local item = stanza.tags[1].tags[1];
752 if item and item.name == "item" then
753 if type == "set" then
754 local callback = function() origin.send(st.reply(stanza)); end
755 if item.attr.jid then -- Validate provided JID
756 item.attr.jid = jid_prep(item.attr.jid);
757 if not item.attr.jid then
758 origin.send(st.error_reply(stanza, "modify", "jid-malformed"));
762 if not item.attr.jid and item.attr.nick then -- COMPAT Workaround for Miranda sending 'nick' instead of 'jid' when changing affiliation
763 local occupant = self._occupants[self.jid.."/"..item.attr.nick];
764 if occupant then item.attr.jid = occupant.jid; end
765 elseif not item.attr.nick and item.attr.jid then
766 local nick = self._jid_nick[item.attr.jid];
767 if nick then item.attr.nick = select(3, jid_split(nick)); end
769 local reason = item.tags[1] and item.tags[1].name == "reason" and #item.tags[1] == 1 and item.tags[1][1];
770 if item.attr.affiliation and item.attr.jid and not item.attr.role then
771 local success, errtype, err = self:set_affiliation(actor, item.attr.jid, item.attr.affiliation, callback, reason);
772 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
773 elseif item.attr.role and item.attr.nick and not item.attr.affiliation then
774 local success, errtype, err = self:set_role(actor, self.jid.."/"..item.attr.nick, item.attr.role, callback, reason);
775 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
777 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
779 elseif type == "get" then
780 local _aff = item.attr.affiliation;
781 local _rol = item.attr.role;
782 if _aff and not _rol then
783 if affiliation == "owner" or (affiliation == "admin" and _aff ~= "owner" and _aff ~= "admin") then
784 local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
785 for jid, affiliation in pairs(self._affiliations) do
786 if affiliation == _aff then
787 reply:tag("item", {affiliation = _aff, jid = jid}):up();
792 origin.send(st.error_reply(stanza, "auth", "forbidden"));
794 elseif _rol and not _aff then
795 if role == "moderator" then
796 -- TODO allow admins and owners not in room? Provide read-only access to everyone who can see the participants anyway?
797 if _rol == "none" then _rol = nil; end
798 local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
799 for occupant_jid, occupant in pairs(self._occupants) do
800 if occupant.role == _rol then
802 nick = select(3, jid_split(occupant_jid)),
803 role = _rol or "none",
804 affiliation = occupant.affiliation or "none",
811 origin.send(st.error_reply(stanza, "auth", "forbidden"));
814 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
817 elseif type == "set" or type == "get" then
818 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
820 elseif xmlns == "http://jabber.org/protocol/muc#owner" and (type == "get" or type == "set") and stanza.tags[1].name == "query" then
821 if self:get_affiliation(stanza.attr.from) ~= "owner" then
822 origin.send(st.error_reply(stanza, "auth", "forbidden", "Only owners can configure rooms"));
823 elseif stanza.attr.type == "get" then
824 self:send_form(origin, stanza);
825 elseif stanza.attr.type == "set" then
826 local child = stanza.tags[1].tags[1];
828 origin.send(st.error_reply(stanza, "modify", "bad-request"));
829 elseif child.name == "destroy" then
830 local newjid = child.attr.jid;
831 local reason, password;
832 for _,tag in ipairs(child.tags) do
833 if tag.name == "reason" then
834 reason = #tag.tags == 0 and tag[1];
835 elseif tag.name == "password" then
836 password = #tag.tags == 0 and tag[1];
839 self:destroy(newjid, reason, password);
840 origin.send(st.reply(stanza));
842 self:process_form(origin, stanza);
845 elseif type == "set" or type == "get" then
846 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
848 elseif stanza.name == "message" and type == "groupchat" then
849 local from = stanza.attr.from;
850 local current_nick = self._jid_nick[from];
851 local occupant = self._occupants[current_nick];
852 if not occupant then -- not in room
853 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
854 elseif occupant.role == "visitor" then
855 origin.send(st.error_reply(stanza, "auth", "forbidden"));
857 local from = stanza.attr.from;
858 stanza.attr.from = current_nick;
859 local subject = stanza:get_child_text("subject");
861 if occupant.role == "moderator" or
862 ( self._data.changesubject and occupant.role == "participant" ) then -- and participant
863 self:set_subject(current_nick, subject);
865 stanza.attr.from = from;
866 origin.send(st.error_reply(stanza, "auth", "forbidden"));
869 self:broadcast_message(stanza, self:get_historylength() > 0 and stanza:get_child("body"));
871 stanza.attr.from = from;
873 elseif stanza.name == "message" and type == "error" and is_kickable_error(stanza) then
874 local current_nick = self._jid_nick[stanza.attr.from];
875 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
876 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza)); -- send unavailable
877 elseif stanza.name == "presence" then -- hack - some buggy clients send presence updates to the room rather than their nick
878 local to = stanza.attr.to;
879 local current_nick = self._jid_nick[stanza.attr.from];
881 stanza.attr.to = current_nick;
882 self:handle_to_occupant(origin, stanza);
884 elseif type ~= "error" and type ~= "result" then
885 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
887 elseif stanza.name == "message" and not(type == "chat" or type == "error" or type == "groupchat" or type == "headline") and #stanza.tags == 1
888 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
889 local x = stanza.tags[1];
890 local payload = (#x.tags == 1 and x.tags[1]);
891 if payload and payload.name == "invite" and payload.attr.to then
892 local _from, _to = stanza.attr.from, stanza.attr.to;
893 local _invitee = jid_prep(payload.attr.to);
895 local _reason = payload.tags[1] and payload.tags[1].name == 'reason' and #payload.tags[1].tags == 0 and payload.tags[1][1];
896 local invite = st.message({from = _to, to = _invitee, id = stanza.attr.id})
897 :tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
898 :tag('invite', {from=_from})
899 :tag('reason'):text(_reason or ""):up()
901 if self:get_password() then
902 invite:tag("password"):text(self:get_password()):up();
905 :tag('x', {xmlns="jabber:x:conference", jid=_to}) -- COMPAT: Some older clients expect this
908 :tag('body') -- Add a plain message for clients which don't support invites
909 :text(_from..' invited you to the room '.._to..(_reason and (' ('.._reason..')') or ""))
911 if self:get_members_only() and not self:get_affiliation(_invitee) then
912 log("debug", "%s invited %s into members only room %s, granting membership", _from, _invitee, _to);
913 self:set_affiliation(_from, _invitee, "member", nil, "Invited by " .. self._jid_nick[_from])
915 self:_route_stanza(invite);
917 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
920 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
923 if type == "error" or type == "result" then return; end
924 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
928 function room_mt:handle_stanza(origin, stanza)
929 local to_node, to_host, to_resource = jid_split(stanza.attr.to);
931 self:handle_to_occupant(origin, stanza);
933 self:handle_to_room(origin, stanza);
937 function room_mt:route_stanza(stanza) end -- Replace with a routing function, e.g., function(room, stanza) core_route_stanza(origin, stanza); end
939 function room_mt:get_affiliation(jid)
940 local node, host, resource = jid_split(jid);
941 local bare = node and node.."@"..host or host;
942 local result = self._affiliations[bare]; -- Affiliations are granted, revoked, and maintained based on the user's bare JID.
943 if not result and self._affiliations[host] == "outcast" then result = "outcast"; end -- host banned
946 function room_mt:set_affiliation(actor, jid, affiliation, callback, reason)
948 if affiliation == "none" then affiliation = nil; end
949 if affiliation and affiliation ~= "outcast" and affiliation ~= "owner" and affiliation ~= "admin" and affiliation ~= "member" then
950 return nil, "modify", "not-acceptable";
952 if actor ~= true then
953 local actor_affiliation = self:get_affiliation(actor);
954 local target_affiliation = self:get_affiliation(jid);
955 if target_affiliation == affiliation then -- no change, shortcut
956 if callback then callback(); end
959 if actor_affiliation ~= "owner" then
960 if affiliation == "owner" or affiliation == "admin" or actor_affiliation ~= "admin" or target_affiliation == "owner" or target_affiliation == "admin" then
961 return nil, "cancel", "not-allowed";
963 elseif target_affiliation == "owner" and jid_bare(actor) == jid then -- self change
964 local is_last = true;
965 for j, aff in pairs(self._affiliations) do if j ~= jid and aff == "owner" then is_last = false; break; end end
967 return nil, "cancel", "conflict";
971 self._affiliations[jid] = affiliation;
972 local role = self:get_default_role(affiliation);
973 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"})
974 :tag("item", {affiliation=affiliation or "none", role=role or "none"})
975 :tag("reason"):text(reason or ""):up()
977 local presence_type = nil;
978 if not role then -- getting kicked
979 presence_type = "unavailable";
980 if affiliation == "outcast" then
981 x:tag("status", {code="301"}):up(); -- banned
983 x:tag("status", {code="321"}):up(); -- affiliation change
986 local modified_nicks = {};
987 for nick, occupant in pairs(self._occupants) do
988 if jid_bare(occupant.jid) == jid then
989 if not role then -- getting kicked
990 self._occupants[nick] = nil;
992 occupant.affiliation, occupant.role = affiliation, role;
994 for jid,pres in pairs(occupant.sessions) do -- remove for all sessions of the nick
995 if not role then self._jid_nick[jid] = nil; end
996 local p = st.clone(pres);
998 p.attr.type = presence_type;
1001 self:_route_stanza(p);
1002 if occupant.jid == jid then
1003 modified_nicks[nick] = p;
1008 if self.save then self:save(); end
1009 if callback then callback(); end
1010 for nick,p in pairs(modified_nicks) do
1012 self:broadcast_except_nick(p, nick);
1017 function room_mt:get_role(nick)
1018 local session = self._occupants[nick];
1019 return session and session.role or nil;
1021 function room_mt:can_set_role(actor_jid, occupant_jid, role)
1022 local occupant = self._occupants[occupant_jid];
1023 if not occupant or not actor_jid then return nil, "modify", "not-acceptable"; end
1025 if actor_jid == true then return true; end
1027 local actor = self._occupants[self._jid_nick[actor_jid]];
1028 if actor.role == "moderator" then
1029 if occupant.affiliation ~= "owner" and occupant.affiliation ~= "admin" then
1030 if actor.affiliation == "owner" or actor.affiliation == "admin" then
1032 elseif occupant.role ~= "moderator" and role ~= "moderator" then
1037 return nil, "cancel", "not-allowed";
1039 function room_mt:set_role(actor, occupant_jid, role, callback, reason)
1040 if role == "none" then role = nil; end
1041 if role and role ~= "moderator" and role ~= "participant" and role ~= "visitor" then return nil, "modify", "not-acceptable"; end
1042 local allowed, err_type, err_condition = self:can_set_role(actor, occupant_jid, role);
1043 if not allowed then return allowed, err_type, err_condition; end
1044 local occupant = self._occupants[occupant_jid];
1045 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"})
1046 :tag("item", {affiliation=occupant.affiliation or "none", nick=select(3, jid_split(occupant_jid)), role=role or "none"})
1047 :tag("reason"):text(reason or ""):up()
1049 local presence_type = nil;
1050 if not role then -- kick
1051 presence_type = "unavailable";
1052 self._occupants[occupant_jid] = nil;
1053 for jid in pairs(occupant.sessions) do -- remove for all sessions of the nick
1054 self._jid_nick[jid] = nil;
1056 x:tag("status", {code = "307"}):up();
1058 occupant.role = role;
1061 for jid,pres in pairs(occupant.sessions) do -- send to all sessions of the nick
1062 local p = st.clone(pres);
1063 p.attr.from = occupant_jid;
1064 p.attr.type = presence_type;
1067 self:_route_stanza(p);
1068 if occupant.jid == jid then
1072 if callback then callback(); end
1074 self:broadcast_except_nick(bp, occupant_jid);
1079 function room_mt:_route_stanza(stanza)
1081 local to_occupant = self._occupants[self._jid_nick[stanza.attr.to]];
1082 local from_occupant = self._occupants[stanza.attr.from];
1083 if stanza.name == "presence" then
1084 if to_occupant and from_occupant then
1085 if self._data.whois == 'anyone' then
1086 muc_child = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
1088 if to_occupant.role == "moderator" or jid_bare(to_occupant.jid) == jid_bare(from_occupant.jid) then
1089 muc_child = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
1095 for _, item in pairs(muc_child.tags) do
1096 if item.name == "item" then
1097 if from_occupant == to_occupant then
1098 item.attr.jid = stanza.attr.to;
1100 item.attr.jid = from_occupant.jid;
1105 self:route_stanza(stanza);
1107 for _, item in pairs(muc_child.tags) do
1108 if item.name == "item" then
1109 item.attr.jid = nil;
1115 local _M = {}; -- module "muc"
1117 function _M.new_room(jid, config)
1118 return setmetatable({
1123 whois = 'moderators';
1124 history_length = math.min((config and config.history_length)
1125 or default_history_length, max_history_length);
1131 function _M.set_max_history_length(_max_history_length)
1132 max_history_length = _max_history_length or math.huge;
1135 _M.room_mt = room_mt;