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 gettime = os.time;
13 local datetime = require "util.datetime";
15 local dataform = require "util.dataforms";
17 local jid_split = require "util.jid".split;
18 local jid_bare = require "util.jid".bare;
19 local jid_prep = require "util.jid".prep;
20 local st = require "util.stanza";
21 local log = require "util.logger".init("mod_muc");
22 local t_insert, t_remove = table.insert, table.remove;
23 local setmetatable = setmetatable;
24 local base64 = require "util.encodings".base64;
25 local md5 = require "util.hashes".md5;
27 local muc_domain = nil; --module:get_host();
28 local default_history_length, max_history_length = 20, math.huge;
31 local presence_filters = {["http://jabber.org/protocol/muc"]=true;["http://jabber.org/protocol/muc#user"]=true};
32 local function presence_filter(tag)
33 if presence_filters[tag.attr.xmlns] then
39 local function get_filtered_presence(stanza)
40 return st.clone(stanza):maptags(presence_filter);
42 local kickable_error_conditions = {
44 ["internal-server-error"] = true;
45 ["item-not-found"] = true;
46 ["jid-malformed"] = true;
47 ["recipient-unavailable"] = true;
49 ["remote-server-not-found"] = true;
50 ["remote-server-timeout"] = true;
51 ["service-unavailable"] = true;
52 ["malformed error"] = true;
55 local function get_error_condition(stanza)
56 local _, condition = stanza:get_error();
57 return condition or "malformed error";
60 local function is_kickable_error(stanza)
61 local cond = get_error_condition(stanza);
62 return kickable_error_conditions[cond] and cond;
67 room_mt.__index = room_mt;
69 function room_mt:__tostring()
70 return "MUC room ("..self.jid..")";
73 function room_mt:get_default_role(affiliation)
74 if affiliation == "owner" or affiliation == "admin" then
76 elseif affiliation == "member" then
78 elseif not affiliation then
79 if not self:get_members_only() then
80 return self:get_moderated() and "visitor" or "participant";
85 function room_mt:broadcast_presence(stanza, sid, code, nick)
86 stanza = get_filtered_presence(stanza);
87 local occupant = self._occupants[stanza.attr.from];
88 stanza:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
89 :tag("item", {affiliation=occupant.affiliation or "none", role=occupant.role or "none", nick=nick}):up();
91 stanza:tag("status", {code=code}):up();
93 self:broadcast_except_nick(stanza, stanza.attr.from);
94 local me = self._occupants[stanza.attr.from];
96 stanza:tag("status", {code='110'}):up();
98 self:_route_stanza(stanza);
101 function room_mt:broadcast_message(stanza, historic)
102 local to = stanza.attr.to;
103 for occupant, o_data in pairs(self._occupants) do
104 for jid in pairs(o_data.sessions) do
105 stanza.attr.to = jid;
106 self:_route_stanza(stanza);
110 if historic then -- add to history
111 return self:save_to_history(stanza)
114 function room_mt:save_to_history(stanza)
115 local history = self._data['history'];
116 if not history then history = {}; self._data['history'] = history; end
117 stanza = st.clone(stanza);
119 local stamp = datetime.datetime();
120 stanza:tag("delay", {xmlns = "urn:xmpp:delay", from = muc_domain, stamp = stamp}):up(); -- XEP-0203
121 stanza:tag("x", {xmlns = "jabber:x:delay", from = muc_domain, stamp = datetime.legacy()}):up(); -- XEP-0091 (deprecated)
122 local entry = { stanza = stanza, stamp = stamp };
123 t_insert(history, entry);
124 while #history > (self._data.history_length or default_history_length) do t_remove(history, 1) end
126 function room_mt:broadcast_except_nick(stanza, nick)
127 for rnick, occupant in pairs(self._occupants) do
128 if rnick ~= nick then
129 for jid in pairs(occupant.sessions) do
130 stanza.attr.to = jid;
131 self:_route_stanza(stanza);
137 function room_mt:send_occupant_list(to)
138 local current_nick = self._jid_nick[to];
139 for occupant, o_data in pairs(self._occupants) do
140 if occupant ~= current_nick then
141 local pres = get_filtered_presence(o_data.sessions[o_data.jid]);
142 pres.attr.to, pres.attr.from = to, occupant;
143 pres:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
144 :tag("item", {affiliation=o_data.affiliation or "none", role=o_data.role or "none"}):up();
145 self:_route_stanza(pres);
150 local function parse_history(stanza)
151 local x_tag = 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");
153 if not history_tag then
157 local maxchars = tonumber(history_tag.attr.maxchars);
159 local maxstanzas = tonumber(history_tag.attr.maxstanzas);
161 -- messages received since the UTC datetime specified
162 local since = history_tag.attr.since;
164 since = datetime.parse(since);
167 -- messages received in the last "X" seconds.
168 local seconds = tonumber(history_tag.attr.seconds);
170 seconds = gettime() - seconds
172 since = math.max(since, seconds);
178 return maxchars, maxstanzas, since
180 -- Get history for 'to'
181 function room_mt:get_history(to, maxchars, maxstanzas, since)
182 local history = self._data['history']; -- send discussion history
183 if not history then return end
184 local history_len = #history
186 maxstanzas = maxstanzas or history_len
189 for i=history_len,1,-1 do
190 local entry = history[i];
192 if not entry.chars then
193 entry.stanza.attr.to = "";
194 entry.chars = #tostring(entry.stanza);
196 charcount = charcount + entry.chars + #to;
197 if charcount > maxchars then break; end
199 if since and since > entry.stamp then break; end
200 if n + 1 > maxstanzas then break; end
204 local i = history_len-n+1
206 if i > history_len then return nil end
207 local entry = history[i]
208 local msg = entry.stanza
214 function room_mt:send_history(to, stanza)
215 local maxchars, maxstanzas, since = parse_history(stanza)
216 for msg in self:get_history(to, maxchars, maxstanzas, since) do
217 self:_route_stanza(msg);
220 function room_mt:send_subject(to)
221 if self._data['subject'] then
222 self:_route_stanza(st.message({type='groupchat', from=self._data['subject_from'] or self.jid, to=to}):tag("subject"):text(self._data['subject']));
226 function room_mt:get_disco_info(stanza)
227 local count = 0; for _ in pairs(self._occupants) do count = count + 1; end
228 return st.reply(stanza):query("http://jabber.org/protocol/disco#info")
229 :tag("identity", {category="conference", type="text", name=self:get_name()}):up()
230 :tag("feature", {var="http://jabber.org/protocol/muc"}):up()
231 :tag("feature", {var=self:get_password() and "muc_passwordprotected" or "muc_unsecured"}):up()
232 :tag("feature", {var=self:get_moderated() and "muc_moderated" or "muc_unmoderated"}):up()
233 :tag("feature", {var=self:get_members_only() and "muc_membersonly" or "muc_open"}):up()
234 :tag("feature", {var=self:get_persistent() and "muc_persistent" or "muc_temporary"}):up()
235 :tag("feature", {var=self:get_hidden() and "muc_hidden" or "muc_public"}):up()
236 :tag("feature", {var=self._data.whois ~= "anyone" and "muc_semianonymous" or "muc_nonanonymous"}):up()
237 :add_child(dataform.new({
238 { name = "FORM_TYPE", type = "hidden", value = "http://jabber.org/protocol/muc#roominfo" },
239 { name = "muc#roominfo_description", label = "Description", value = "" },
240 { name = "muc#roominfo_occupants", label = "Number of occupants", value = tostring(count) }
241 }):form({["muc#roominfo_description"] = self:get_description()}, 'result'))
244 function room_mt:get_disco_items(stanza)
245 local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#items");
246 for room_jid in pairs(self._occupants) do
247 reply:tag("item", {jid = room_jid, name = room_jid:match("/(.*)")}):up();
251 function room_mt:set_subject(current_nick, subject)
252 if subject == "" then subject = nil; end
253 self._data['subject'] = subject;
254 self._data['subject_from'] = current_nick;
255 if self.save then self:save(); end
256 local msg = st.message({type='groupchat', from=current_nick})
257 :tag('subject'):text(subject):up();
258 self:broadcast_message(msg, false);
262 function room_mt:handle_kickable(origin, stanza)
263 local type, condition, text = stanza:get_error();
264 local error_message = "Kicked: "..(condition and condition:gsub("%-", " ") or "presence error");
266 error_message = error_message..": "..text;
268 local kick_stanza = st.presence({type='unavailable', from=stanza.attr.from, to=stanza.attr.to})
269 :tag('status'):text(error_message);
270 self:handle_unavailable_to_occupant(origin, kick_stanza); -- send unavailable
274 function room_mt:set_name(name)
275 if name == "" or type(name) ~= "string" or name == (jid_split(self.jid)) then name = nil; end
276 if self._data.name ~= name then
277 self._data.name = name;
278 if self.save then self:save(true); end
281 function room_mt:get_name()
282 return self._data.name or jid_split(self.jid);
284 function room_mt:set_description(description)
285 if description == "" or type(description) ~= "string" then description = nil; end
286 if self._data.description ~= description then
287 self._data.description = description;
288 if self.save then self:save(true); end
291 function room_mt:get_description()
292 return self._data.description;
294 function room_mt:set_password(password)
295 if password == "" or type(password) ~= "string" then password = nil; end
296 if self._data.password ~= password then
297 self._data.password = password;
298 if self.save then self:save(true); end
301 function room_mt:get_password()
302 return self._data.password;
304 function room_mt:set_moderated(moderated)
305 moderated = moderated and true or nil;
306 if self._data.moderated ~= moderated then
307 self._data.moderated = moderated;
308 if self.save then self:save(true); end
311 function room_mt:get_moderated()
312 return self._data.moderated;
314 function room_mt:set_members_only(members_only)
315 members_only = members_only and true or nil;
316 if self._data.members_only ~= members_only then
317 self._data.members_only = members_only;
318 if self.save then self:save(true); end
321 function room_mt:get_members_only()
322 return self._data.members_only;
324 function room_mt:set_persistent(persistent)
325 persistent = persistent and true or nil;
326 if self._data.persistent ~= persistent then
327 self._data.persistent = persistent;
328 if self.save then self:save(true); end
331 function room_mt:get_persistent()
332 return self._data.persistent;
334 function room_mt:set_hidden(hidden)
335 hidden = hidden and true or nil;
336 if self._data.hidden ~= hidden then
337 self._data.hidden = hidden;
338 if self.save then self:save(true); end
341 function room_mt:get_hidden()
342 return self._data.hidden;
344 function room_mt:get_public()
345 return not self:get_hidden();
347 function room_mt:set_public(public)
348 return self:set_hidden(not public);
350 function room_mt:set_changesubject(changesubject)
351 changesubject = changesubject and true or nil;
352 if self._data.changesubject ~= changesubject then
353 self._data.changesubject = changesubject;
354 if self.save then self:save(true); end
357 function room_mt:get_changesubject()
358 return self._data.changesubject;
360 function room_mt:get_historylength()
361 return self._data.history_length or default_history_length;
363 function room_mt:set_historylength(length)
364 length = math.min(tonumber(length) or default_history_length, max_history_length or math.huge);
365 if length == default_history_length then
368 self._data.history_length = length;
372 local valid_whois = { moderators = true, anyone = true };
374 function room_mt:set_whois(whois)
375 if valid_whois[whois] and self._data.whois ~= whois then
376 self._data.whois = whois;
377 if self.save then self:save(true); end
381 function room_mt:get_whois()
382 return self._data.whois;
385 function room_mt:handle_unavailable_to_occupant(origin, stanza)
386 local from = stanza.attr.from;
387 local current_nick = self._jid_nick[from];
388 if not current_nick then
389 return true; -- discard
391 local pr = get_filtered_presence(stanza);
392 pr.attr.from = current_nick;
393 log("debug", "%s leaving %s", current_nick, self.jid);
394 self._jid_nick[from] = nil;
395 local occupant = self._occupants[current_nick];
396 local new_jid = next(occupant.sessions);
397 if new_jid == from then new_jid = next(occupant.sessions, new_jid); end
399 local jid = occupant.jid;
400 occupant.jid = new_jid;
401 occupant.sessions[from] = nil;
403 pr:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
404 :tag("item", {affiliation=occupant.affiliation or "none", role='none'}):up()
405 :tag("status", {code='110'}):up();
406 self:_route_stanza(pr);
407 if jid ~= new_jid then
408 pr = st.clone(occupant.sessions[new_jid])
409 :tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
410 :tag("item", {affiliation=occupant.affiliation or "none", role=occupant.role or "none"});
411 pr.attr.from = current_nick;
412 self:broadcast_except_nick(pr, current_nick);
415 occupant.role = 'none';
416 self:broadcast_presence(pr, from);
417 self._occupants[current_nick] = nil;
422 function room_mt:handle_occupant_presence(origin, stanza)
423 local from = stanza.attr.from;
424 local pr = get_filtered_presence(stanza);
425 local current_nick = stanza.attr.to
426 pr.attr.from = current_nick;
427 log("debug", "%s broadcasted presence", current_nick);
428 self._occupants[current_nick].sessions[from] = pr;
429 self:broadcast_presence(pr, from);
433 function room_mt:handle_change_nick(origin, stanza, current_nick, to)
434 local from = stanza.attr.from;
435 local occupant = self._occupants[current_nick];
436 local is_multisession = next(occupant.sessions, next(occupant.sessions));
437 if self._occupants[to] or is_multisession then
438 log("debug", "%s couldn't change nick", current_nick);
439 local reply = st.error_reply(stanza, "cancel", "conflict"):up();
440 reply.tags[1].attr.code = "409";
441 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
444 local data = self._occupants[current_nick];
445 local to_nick = select(3, jid_split(to));
446 log("debug", "%s (%s) changing nick to %s", current_nick, data.jid, to);
447 local p = st.presence({type='unavailable', from=current_nick});
448 self:broadcast_presence(p, from, '303', to_nick);
449 self._occupants[current_nick] = nil;
450 self._occupants[to] = data;
451 self._jid_nick[from] = to;
452 local pr = get_filtered_presence(stanza);
454 self._occupants[to].sessions[from] = pr;
455 self:broadcast_presence(pr, from);
460 function room_mt:handle_join(origin, stanza)
461 local from, to = stanza.attr.from, stanza.attr.to;
462 log("debug", "%s joining as %s", from, to);
463 if not next(self._affiliations) then -- new room, no owners
464 self._affiliations[jid_bare(from)] = "owner";
465 if self.locked and not stanza:get_child("x", "http://jabber.org/protocol/muc") then
466 self.locked = nil; -- Older groupchat protocol doesn't lock
468 elseif self.locked then -- Deny entry
469 origin.send(st.error_reply(stanza, "cancel", "item-not-found"));
472 local affiliation = self:get_affiliation(from);
473 local role = self:get_default_role(affiliation)
474 if role then -- new occupant
475 local is_merge = not not self._occupants[to]
477 self._occupants[to] = {affiliation=affiliation, role=role, jid=from, sessions={[from]=get_filtered_presence(stanza)}};
479 self._occupants[to].sessions[from] = get_filtered_presence(stanza);
481 self._jid_nick[from] = to;
482 self:send_occupant_list(from);
483 local pr = get_filtered_presence(stanza);
485 pr:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
486 :tag("item", {affiliation=affiliation or "none", role=role or "none"}):up();
488 self:broadcast_except_nick(pr, to);
490 pr:tag("status", {code='110'}):up();
491 if self._data.whois == 'anyone' then
492 pr:tag("status", {code='100'}):up();
495 pr:tag("status", {code='201'}):up();
498 self:_route_stanza(pr);
499 self:send_history(from, stanza);
500 self:send_subject(from);
502 elseif not affiliation then -- registration required for entering members-only room
503 local reply = st.error_reply(stanza, "auth", "registration-required"):up();
504 reply.tags[1].attr.code = "407";
505 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
508 local reply = st.error_reply(stanza, "auth", "forbidden"):up();
509 reply.tags[1].attr.code = "403";
510 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
515 function room_mt:handle_available_to_occupant(origin, stanza)
516 local from, to = stanza.attr.from, stanza.attr.to;
517 local current_nick = self._jid_nick[from];
519 --if #pr == #stanza or current_nick ~= to then -- commented because google keeps resending directed presence
520 if current_nick == to then -- simple presence
521 return self:handle_occupant_presence(origin, stanza)
523 return self:handle_change_nick(origin, stanza, current_nick, to)
525 --else -- possible rejoin
526 -- log("debug", "%s had connection replaced", current_nick);
527 -- self:handle_to_occupant(origin, st.presence({type='unavailable', from=from, to=to})
528 -- :tag('status'):text('Replaced by new connection'):up()); -- send unavailable
529 -- self:handle_to_occupant(origin, stanza); -- resend available
533 if self._occupants[to] then
534 if jid_bare(from) ~= jid_bare(self._occupants[to].jid) then
538 local password = stanza:get_child("x", "http://jabber.org/protocol/muc");
539 password = password and password:get_child("password", "http://jabber.org/protocol/muc");
540 password = password and password[1] ~= "" and password[1];
541 if self:get_password() and self:get_password() ~= password then
542 log("debug", "%s couldn't join due to invalid password: %s", from, to);
543 local reply = st.error_reply(stanza, "auth", "not-authorized"):up();
544 reply.tags[1].attr.code = "401";
545 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
547 elseif not new_nick then
548 log("debug", "%s couldn't join due to nick conflict: %s", from, to);
549 local reply = st.error_reply(stanza, "cancel", "conflict"):up();
550 reply.tags[1].attr.code = "409";
551 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
554 return self:handle_join(origin, stanza)
559 function room_mt:handle_presence_to_occupant(origin, stanza)
560 local type = stanza.attr.type;
561 if type == "error" then -- error, kick em out!
562 return self:handle_kickable(origin, stanza)
563 elseif type == "unavailable" then -- unavailable
564 return self:handle_unavailable_to_occupant(origin, stanza)
565 elseif not type then -- available
566 return self:handle_available_to_occupant(origin, stanza)
567 elseif type ~= 'result' then -- bad type
568 if type ~= 'visible' and type ~= 'invisible' then -- COMPAT ejabberd can broadcast or forward XEP-0018 presences
569 origin.send(st.error_reply(stanza, "modify", "bad-request")); -- FIXME correct error?
575 function room_mt:handle_iq_to_occupant(origin, stanza)
576 local from, to = stanza.attr.from, stanza.attr.to;
577 local type = stanza.attr.type;
578 local id = stanza.attr.id;
579 local current_nick = self._jid_nick[from];
580 local o_data = self._occupants[to];
581 if (type == "error" or type == "result") then
582 do -- deconstruct_stanza_id
583 if not current_nick or not o_data then return nil; end
584 local from_jid, id, to_jid_hash = (base64.decode(stanza.attr.id) or ""):match("^(.+)%z(.*)%z(.+)$");
585 if not(from == from_jid or from == jid_bare(from_jid)) then return nil; end
587 for to_jid in pairs(o_data.sessions) do
588 if md5(to_jid) == to_jid_hash then
589 session_jid = to_jid;
593 if session_jid == nil then return nil; end
594 stanza.attr.from, stanza.attr.to, stanza.attr.id = current_nick, session_jid, id
596 log("debug", "%s sent private iq stanza to %s (%s)", from, to, stanza.attr.to);
597 self:_route_stanza(stanza);
598 stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
600 else -- Type is "get" or "set"
601 if not current_nick then
602 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
605 if not o_data then -- recipient not in room
606 origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
609 do -- construct_stanza_id
610 stanza.attr.id = base64.encode(to_jid.."\0"..stanza.attr.id.."\0"..md5(from));
612 stanza.attr.from, stanza.attr.to = current_nick, o_data.jid;
613 log("debug", "%s sent private iq stanza to %s (%s)", from, to, o_data.jid);
614 if stanza.tags[1].attr.xmlns == 'vcard-temp' then
615 stanza.attr.to = jid_bare(stanza.attr.to);
617 self:_route_stanza(stanza);
618 stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
623 function room_mt:handle_message_to_occupant(origin, stanza)
624 local from, to = stanza.attr.from, stanza.attr.to;
625 local current_nick = self._jid_nick[from];
626 local type = stanza.attr.type;
627 if not current_nick then -- not in room
628 if type ~= "error" then
629 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
633 if type == "groupchat" then -- groupchat messages not allowed in PM
634 origin.send(st.error_reply(stanza, "modify", "bad-request"));
636 elseif type == "error" and is_kickable_error(stanza) then
637 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
638 return self:handle_kickable(origin, stanza); -- send unavailable
641 local o_data = self._occupants[to];
643 origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
646 log("debug", "%s sent private message stanza to %s (%s)", from, to, o_data.jid);
647 stanza:tag("x", { xmlns = "http://jabber.org/protocol/muc#user" }):up();
648 stanza.attr.from = current_nick;
649 for jid in pairs(o_data.sessions) do
650 stanza.attr.to = jid;
651 self:_route_stanza(stanza);
653 stanza.attr.from, stanza.attr.to = from, to;
657 function room_mt:handle_to_occupant(origin, stanza) -- PM, vCards, etc
658 local from, to = stanza.attr.from, stanza.attr.to;
659 local room = jid_bare(to);
660 local current_nick = self._jid_nick[from];
661 log("debug", "room: %s, current_nick: %s, stanza: %s", room or "nil", current_nick or "nil", stanza:top_tag());
662 if (select(2, jid_split(from)) == muc_domain) then error("Presence from the MUC itself!!!"); end
663 if stanza.name == "presence" then
664 return self:handle_presence_to_occupant(origin, stanza)
665 elseif stanza.name == "iq" then
666 return self:handle_iq_to_occupant(origin, stanza)
667 elseif stanza.name == "message" then
668 return self:handle_message_to_occupant(origin, stanza)
672 function room_mt:send_form(origin, stanza)
673 origin.send(st.reply(stanza):query("http://jabber.org/protocol/muc#owner")
674 :add_child(self:get_form_layout(stanza.attr.from):form())
678 function room_mt:get_form_layout(actor)
679 local form = dataform.new({
680 title = "Configuration for "..self.jid,
681 instructions = "Complete and submit this form to configure the room.",
685 value = 'http://jabber.org/protocol/muc#roomconfig'
688 name = 'muc#roomconfig_roomname',
689 type = 'text-single',
691 value = self:get_name() or "",
694 name = 'muc#roomconfig_roomdesc',
695 type = 'text-single',
696 label = 'Description',
697 value = self:get_description() or "",
700 name = 'muc#roomconfig_persistentroom',
702 label = 'Make Room Persistent?',
703 value = self:get_persistent()
706 name = 'muc#roomconfig_publicroom',
708 label = 'Make Room Publicly Searchable?',
709 value = not self:get_hidden()
712 name = 'muc#roomconfig_changesubject',
714 label = 'Allow Occupants to Change Subject?',
715 value = self:get_changesubject()
718 name = 'muc#roomconfig_whois',
719 type = 'list-single',
720 label = 'Who May Discover Real JIDs?',
722 { value = 'moderators', label = 'Moderators Only', default = self._data.whois == 'moderators' },
723 { value = 'anyone', label = 'Anyone', default = self._data.whois == 'anyone' }
727 name = 'muc#roomconfig_roomsecret',
728 type = 'text-private',
730 value = self:get_password() or "",
733 name = 'muc#roomconfig_moderatedroom',
735 label = 'Make Room Moderated?',
736 value = self:get_moderated()
739 name = 'muc#roomconfig_membersonly',
741 label = 'Make Room Members-Only?',
742 value = self:get_members_only()
745 name = 'muc#roomconfig_historylength',
746 type = 'text-single',
747 label = 'Maximum Number of History Messages Returned by Room',
748 value = tostring(self:get_historylength())
751 return module:fire_event("muc-config-form", { room = self, actor = actor, form = form }) or form;
754 function room_mt:process_form(origin, stanza)
755 local query = stanza.tags[1];
757 for _, tag in ipairs(query.tags) do if tag.name == "x" and tag.attr.xmlns == "jabber:x:data" then form = tag; break; end end
758 if not form then origin.send(st.error_reply(stanza, "cancel", "service-unavailable")); return; end
759 if form.attr.type == "cancel" then origin.send(st.reply(stanza)); return; end
760 if form.attr.type ~= "submit" then origin.send(st.error_reply(stanza, "cancel", "bad-request", "Not a submitted form")); return; end
762 local fields = self:get_form_layout(stanza.attr.from):data(form);
763 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
768 local function handle_option(name, field, allowed)
769 local new = fields[field];
770 if new == nil then return; end
771 if allowed and not allowed[new] then return; end
772 if new == self["get_"..name](self) then return; end
773 changed[name] = true;
774 self["set_"..name](self, new);
777 local event = { room = self, fields = fields, changed = changed, stanza = stanza, origin = origin, update_option = handle_option };
778 module:fire_event("muc-config-submitted", event);
780 handle_option("name", "muc#roomconfig_roomname");
781 handle_option("description", "muc#roomconfig_roomdesc");
782 handle_option("persistent", "muc#roomconfig_persistentroom");
783 handle_option("moderated", "muc#roomconfig_moderatedroom");
784 handle_option("members_only", "muc#roomconfig_membersonly");
785 handle_option("public", "muc#roomconfig_publicroom");
786 handle_option("changesubject", "muc#roomconfig_changesubject");
787 handle_option("historylength", "muc#roomconfig_historylength");
788 handle_option("whois", "muc#roomconfig_whois", valid_whois);
789 handle_option("password", "muc#roomconfig_roomsecret");
791 if self.save then self:save(true); end
793 module:fire_event("muc-room-unlocked", { room = self });
796 origin.send(st.reply(stanza));
798 if next(changed) then
799 local msg = st.message({type='groupchat', from=self.jid})
800 :tag('x', {xmlns='http://jabber.org/protocol/muc#user'}):up()
801 :tag('status', {code = '104'}):up();
802 if changed.whois then
803 local code = (self:get_whois() == 'moderators') and "173" or "172";
804 msg.tags[1]:tag('status', {code = code}):up();
806 self:broadcast_message(msg, false)
810 function room_mt:destroy(newjid, reason, password)
811 local pr = st.presence({type = "unavailable"})
812 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
813 :tag("item", { affiliation='none', role='none' }):up()
814 :tag("destroy", {jid=newjid})
815 if reason then pr:tag("reason"):text(reason):up(); end
816 if password then pr:tag("password"):text(password):up(); end
817 for nick, occupant in pairs(self._occupants) do
819 for jid in pairs(occupant.sessions) do
821 self:_route_stanza(pr);
822 self._jid_nick[jid] = nil;
824 self._occupants[nick] = nil;
826 self:set_persistent(false);
827 module:fire_event("muc-room-destroyed", { room = self });
830 function room_mt:handle_admin_item_set_command(origin, stanza)
831 local item = stanza.tags[1].tags[1];
832 if item.attr.jid then -- Validate provided JID
833 item.attr.jid = jid_prep(item.attr.jid);
834 if not item.attr.jid then
835 origin.send(st.error_reply(stanza, "modify", "jid-malformed"));
839 if not item.attr.jid and item.attr.nick then -- COMPAT Workaround for Miranda sending 'nick' instead of 'jid' when changing affiliation
840 local occupant = self._occupants[self.jid.."/"..item.attr.nick];
841 if occupant then item.attr.jid = occupant.jid; end
842 elseif not item.attr.nick and item.attr.jid then
843 local nick = self._jid_nick[item.attr.jid];
844 if nick then item.attr.nick = select(3, jid_split(nick)); end
846 local actor = stanza.attr.from;
847 local callback = function() origin.send(st.reply(stanza)); end
848 local reason = item.tags[1] and item.tags[1].name == "reason" and #item.tags[1] == 1 and item.tags[1][1];
849 if item.attr.affiliation and item.attr.jid and not item.attr.role then
850 local success, errtype, err = self:set_affiliation(actor, item.attr.jid, item.attr.affiliation, callback, reason);
851 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
853 elseif item.attr.role and item.attr.nick and not item.attr.affiliation then
854 local success, errtype, err = self:set_role(actor, self.jid.."/"..item.attr.nick, item.attr.role, callback, reason);
855 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
858 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
863 function room_mt:handle_admin_item_get_command(origin, stanza)
864 local actor = stanza.attr.from;
865 local affiliation = self:get_affiliation(actor);
866 local current_nick = self._jid_nick[actor];
867 local role = current_nick and self._occupants[current_nick].role or self:get_default_role(affiliation);
868 local item = stanza.tags[1].tags[1];
869 local _aff = item.attr.affiliation;
870 local _rol = item.attr.role;
871 if _aff and not _rol then
872 if affiliation == "owner" or (affiliation == "admin" and _aff ~= "owner" and _aff ~= "admin") then
873 local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
874 for jid, affiliation in pairs(self._affiliations) do
875 if affiliation == _aff then
876 reply:tag("item", {affiliation = _aff, jid = jid}):up();
882 origin.send(st.error_reply(stanza, "auth", "forbidden"));
885 elseif _rol and not _aff then
886 if role == "moderator" then
887 -- TODO allow admins and owners not in room? Provide read-only access to everyone who can see the participants anyway?
888 if _rol == "none" then _rol = nil; end
889 local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
890 for occupant_jid, occupant in pairs(self._occupants) do
891 if occupant.role == _rol then
893 nick = select(3, jid_split(occupant_jid)),
894 role = _rol or "none",
895 affiliation = occupant.affiliation or "none",
903 origin.send(st.error_reply(stanza, "auth", "forbidden"));
907 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
912 function room_mt:handle_owner_query_get_to_room(origin, stanza)
913 if self:get_affiliation(stanza.attr.from) ~= "owner" then
914 origin.send(st.error_reply(stanza, "auth", "forbidden", "Only owners can configure rooms"));
918 self:send_form(origin, stanza);
921 function room_mt:handle_owner_query_set_to_room(origin, stanza)
922 if self:get_affiliation(stanza.attr.from) ~= "owner" then
923 origin.send(st.error_reply(stanza, "auth", "forbidden", "Only owners can configure rooms"));
927 local child = stanza.tags[1].tags[1];
929 origin.send(st.error_reply(stanza, "modify", "bad-request"));
931 elseif child.name == "destroy" then
932 local newjid = child.attr.jid;
933 local reason, password;
934 for _,tag in ipairs(child.tags) do
935 if tag.name == "reason" then
936 reason = #tag.tags == 0 and tag[1];
937 elseif tag.name == "password" then
938 password = #tag.tags == 0 and tag[1];
941 self:destroy(newjid, reason, password);
942 origin.send(st.reply(stanza));
945 self:process_form(origin, stanza);
950 function room_mt:handle_iq_to_room(origin, stanza)
951 local type = stanza.attr.type;
952 local xmlns = stanza.tags[1] and stanza.tags[1].attr.xmlns;
953 if xmlns == "http://jabber.org/protocol/disco#info" and type == "get" and not stanza.tags[1].attr.node then
954 origin.send(self:get_disco_info(stanza));
956 elseif xmlns == "http://jabber.org/protocol/disco#items" and type == "get" and not stanza.tags[1].attr.node then
957 origin.send(self:get_disco_items(stanza));
959 elseif xmlns == "http://jabber.org/protocol/muc#admin" then
960 local item = stanza.tags[1].tags[1];
961 if item and item.name == "item" then
962 if type == "set" then
963 return self:handle_admin_item_set_command(origin, stanza)
964 elseif type == "get" then
965 return self:handle_admin_item_get_command(origin, stanza)
967 elseif type == "set" or type == "get" then
968 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
971 elseif xmlns == "http://jabber.org/protocol/muc#owner" and (type == "get" or type == "set") and stanza.tags[1].name == "query" then
972 if stanza.attr.type == "get" then
973 return self:handle_owner_query_get_to_room(origin, stanza)
974 elseif stanza.attr.type == "set" then
975 return self:handle_owner_query_set_to_room(origin, stanza)
982 function room_mt:handle_groupchat_to_room(origin, stanza)
983 local from = stanza.attr.from;
984 local current_nick = self._jid_nick[from];
985 local occupant = self._occupants[current_nick];
986 if not occupant then -- not in room
987 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
989 elseif occupant.role == "visitor" then
990 origin.send(st.error_reply(stanza, "auth", "forbidden"));
993 local from = stanza.attr.from;
994 stanza.attr.from = current_nick;
995 local subject = stanza:get_child_text("subject");
997 if occupant.role == "moderator" or
998 ( self._data.changesubject and occupant.role == "participant" ) then -- and participant
999 self:set_subject(current_nick, subject);
1001 stanza.attr.from = from;
1002 origin.send(st.error_reply(stanza, "auth", "forbidden"));
1005 self:broadcast_message(stanza, self:get_historylength() > 0 and stanza:get_child("body"));
1007 stanza.attr.from = from;
1012 -- hack - some buggy clients send presence updates to the room rather than their nick
1013 function room_mt:handle_presence_to_room(origin, stanza)
1014 local current_nick = self._jid_nick[stanza.attr.from];
1016 if current_nick then
1017 local to = stanza.attr.to;
1018 stanza.attr.to = current_nick;
1019 handled = self:handle_presence_to_occupant(origin, stanza);
1020 stanza.attr.to = to;
1025 function room_mt:handle_invite_to_room(origin, stanza, payload)
1026 local _from, _to = stanza.attr.from, stanza.attr.to;
1027 local _invitee = jid_prep(payload.attr.to);
1029 local _reason = payload.tags[1] and payload.tags[1].name == 'reason' and #payload.tags[1].tags == 0 and payload.tags[1][1];
1030 local invite = st.message({from = _to, to = _invitee, id = stanza.attr.id})
1031 :tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
1032 :tag('invite', {from=_from})
1033 :tag('reason'):text(_reason or ""):up()
1035 if self:get_password() then
1036 invite:tag("password"):text(self:get_password()):up();
1039 :tag('x', {xmlns="jabber:x:conference", jid=_to}) -- COMPAT: Some older clients expect this
1040 :text(_reason or "")
1042 :tag('body') -- Add a plain message for clients which don't support invites
1043 :text(_from..' invited you to the room '.._to..(_reason and (' ('.._reason..')') or ""))
1045 if self:get_members_only() and not self:get_affiliation(_invitee) then
1046 log("debug", "%s invited %s into members only room %s, granting membership", _from, _invitee, _to);
1047 self:set_affiliation(_from, _invitee, "member", nil, "Invited by " .. self._jid_nick[_from])
1049 self:_route_stanza(invite);
1052 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
1057 function room_mt:handle_message_to_room(origin, stanza)
1058 local type = stanza.attr.type;
1059 if type == "groupchat" then
1060 return self:handle_groupchat_to_room(origin, stanza)
1061 elseif type == "error" and is_kickable_error(stanza) then
1062 return self:handle_kickable(origin, stanza)
1063 elseif not(type == "chat" or type == "error" or type == "groupchat" or type == "headline") and #stanza.tags == 1
1064 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
1065 local x = stanza.tags[1];
1066 local payload = (#x.tags == 1 and x.tags[1]);
1067 if payload and payload.name == "invite" and payload.attr.to then
1068 return self:handle_invite_to_room(origin, stanza, payload)
1070 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
1078 function room_mt:handle_to_room(origin, stanza) -- presence changes and groupchat messages, along with disco/etc
1079 if stanza.name == "iq" then
1080 return self:handle_iq_to_room(origin, stanza)
1081 elseif stanza.name == "message" then
1082 return self:handle_message_to_room(origin, stanza)
1083 elseif stanza.name == "presence" then
1084 return self:handle_presence_to_room(origin, stanza)
1088 function room_mt:handle_stanza(origin, stanza)
1089 local to_node, to_host, to_resource = jid_split(stanza.attr.to);
1092 handled = self:handle_to_occupant(origin, stanza);
1094 handled = self:handle_to_room(origin, stanza);
1098 local type = stanza.attr.type
1099 if stanza.name ~= "iq" or type == "get" or type == "set" then
1100 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
1105 function room_mt:route_stanza(stanza) end -- Replace with a routing function, e.g., function(room, stanza) core_route_stanza(origin, stanza); end
1107 function room_mt:get_affiliation(jid)
1108 local node, host, resource = jid_split(jid);
1109 local bare = node and node.."@"..host or host;
1110 local result = self._affiliations[bare]; -- Affiliations are granted, revoked, and maintained based on the user's bare JID.
1111 if not result and self._affiliations[host] == "outcast" then result = "outcast"; end -- host banned
1114 function room_mt:set_affiliation(actor, jid, affiliation, callback, reason)
1115 jid = jid_bare(jid);
1116 if affiliation == "none" then affiliation = nil; end
1117 if affiliation and affiliation ~= "outcast" and affiliation ~= "owner" and affiliation ~= "admin" and affiliation ~= "member" then
1118 return nil, "modify", "not-acceptable";
1120 if actor ~= true then
1121 local actor_affiliation = self:get_affiliation(actor);
1122 local target_affiliation = self:get_affiliation(jid);
1123 if target_affiliation == affiliation then -- no change, shortcut
1124 if callback then callback(); end
1127 if actor_affiliation ~= "owner" then
1128 if affiliation == "owner" or affiliation == "admin" or actor_affiliation ~= "admin" or target_affiliation == "owner" or target_affiliation == "admin" then
1129 return nil, "cancel", "not-allowed";
1131 elseif target_affiliation == "owner" and jid_bare(actor) == jid then -- self change
1132 local is_last = true;
1133 for j, aff in pairs(self._affiliations) do if j ~= jid and aff == "owner" then is_last = false; break; end end
1135 return nil, "cancel", "conflict";
1139 self._affiliations[jid] = affiliation;
1140 local role = self:get_default_role(affiliation);
1141 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"})
1142 :tag("item", {affiliation=affiliation or "none", role=role or "none"})
1143 :tag("reason"):text(reason or ""):up()
1145 local presence_type = nil;
1146 if not role then -- getting kicked
1147 presence_type = "unavailable";
1148 if affiliation == "outcast" then
1149 x:tag("status", {code="301"}):up(); -- banned
1151 x:tag("status", {code="321"}):up(); -- affiliation change
1154 local modified_nicks = {};
1155 for nick, occupant in pairs(self._occupants) do
1156 if jid_bare(occupant.jid) == jid then
1157 if not role then -- getting kicked
1158 self._occupants[nick] = nil;
1160 occupant.affiliation, occupant.role = affiliation, role;
1162 for jid,pres in pairs(occupant.sessions) do -- remove for all sessions of the nick
1163 if not role then self._jid_nick[jid] = nil; end
1164 local p = st.clone(pres);
1166 p.attr.type = presence_type;
1169 self:_route_stanza(p);
1170 if occupant.jid == jid then
1171 modified_nicks[nick] = p;
1176 if self.save then self:save(); end
1177 if callback then callback(); end
1178 for nick,p in pairs(modified_nicks) do
1180 self:broadcast_except_nick(p, nick);
1185 function room_mt:get_role(nick)
1186 local session = self._occupants[nick];
1187 return session and session.role or nil;
1189 function room_mt:can_set_role(actor_jid, occupant_jid, role)
1190 local occupant = self._occupants[occupant_jid];
1191 if not occupant or not actor_jid then return nil, "modify", "not-acceptable"; end
1193 if actor_jid == true then return true; end
1195 local actor = self._occupants[self._jid_nick[actor_jid]];
1196 if actor.role == "moderator" then
1197 if occupant.affiliation ~= "owner" and occupant.affiliation ~= "admin" then
1198 if actor.affiliation == "owner" or actor.affiliation == "admin" then
1200 elseif occupant.role ~= "moderator" and role ~= "moderator" then
1205 return nil, "cancel", "not-allowed";
1207 function room_mt:set_role(actor, occupant_jid, role, callback, reason)
1208 if role == "none" then role = nil; end
1209 if role and role ~= "moderator" and role ~= "participant" and role ~= "visitor" then return nil, "modify", "not-acceptable"; end
1210 local allowed, err_type, err_condition = self:can_set_role(actor, occupant_jid, role);
1211 if not allowed then return allowed, err_type, err_condition; end
1212 local occupant = self._occupants[occupant_jid];
1213 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"})
1214 :tag("item", {affiliation=occupant.affiliation or "none", nick=select(3, jid_split(occupant_jid)), role=role or "none"})
1215 :tag("reason"):text(reason or ""):up()
1217 local presence_type = nil;
1218 if not role then -- kick
1219 presence_type = "unavailable";
1220 self._occupants[occupant_jid] = nil;
1221 for jid in pairs(occupant.sessions) do -- remove for all sessions of the nick
1222 self._jid_nick[jid] = nil;
1224 x:tag("status", {code = "307"}):up();
1226 occupant.role = role;
1229 for jid,pres in pairs(occupant.sessions) do -- send to all sessions of the nick
1230 local p = st.clone(pres);
1231 p.attr.from = occupant_jid;
1232 p.attr.type = presence_type;
1235 self:_route_stanza(p);
1236 if occupant.jid == jid then
1240 if callback then callback(); end
1242 self:broadcast_except_nick(bp, occupant_jid);
1247 function room_mt:_route_stanza(stanza)
1249 local to_occupant = self._occupants[self._jid_nick[stanza.attr.to]];
1250 local from_occupant = self._occupants[stanza.attr.from];
1251 if stanza.name == "presence" then
1252 if to_occupant and from_occupant then
1253 if self._data.whois == 'anyone' then
1254 muc_child = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
1256 if to_occupant.role == "moderator" or jid_bare(to_occupant.jid) == jid_bare(from_occupant.jid) then
1257 muc_child = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
1263 for _, item in pairs(muc_child.tags) do
1264 if item.name == "item" then
1265 if from_occupant == to_occupant then
1266 item.attr.jid = stanza.attr.to;
1268 item.attr.jid = from_occupant.jid;
1273 self:route_stanza(stanza);
1275 for _, item in pairs(muc_child.tags) do
1276 if item.name == "item" then
1277 item.attr.jid = nil;
1283 local _M = {}; -- module "muc"
1285 function _M.new_room(jid, config)
1286 return setmetatable({
1291 whois = 'moderators';
1292 history_length = math.min((config and config.history_length)
1293 or default_history_length, max_history_length);
1299 function _M.set_max_history_length(_max_history_length)
1300 max_history_length = _max_history_length or math.huge;
1303 _M.room_mt = room_mt;