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 datamanager = require "util.datamanager";
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 multitable_new = require "util.multitable".new;
23 local t_insert, t_remove = table.insert, table.remove;
24 local setmetatable = setmetatable;
25 local base64 = require "util.encodings".base64;
26 local md5 = require "util.hashes".md5;
28 local muc_domain = nil; --module:get_host();
29 local default_history_length = 20;
32 local function filter_xmlns_from_array(array, filters)
35 local attr = array[i].attr;
36 if filters[attr and attr.xmlns] then
43 local function filter_xmlns_from_stanza(stanza, filters)
45 if filter_xmlns_from_array(stanza.tags, filters) ~= 0 then
46 return stanza, filter_xmlns_from_array(stanza, filters);
51 local presence_filters = {["http://jabber.org/protocol/muc"]=true;["http://jabber.org/protocol/muc#user"]=true};
52 local function get_filtered_presence(stanza)
53 return filter_xmlns_from_stanza(st.clone(stanza):reset(), presence_filters);
55 local kickable_error_conditions = {
57 ["internal-server-error"] = true;
58 ["item-not-found"] = true;
59 ["jid-malformed"] = true;
60 ["recipient-unavailable"] = true;
62 ["remote-server-not-found"] = true;
63 ["remote-server-timeout"] = true;
64 ["service-unavailable"] = true;
65 ["malformed error"] = true;
68 local function get_error_condition(stanza)
69 local _, condition = stanza:get_error();
70 return condition or "malformed error";
73 local function is_kickable_error(stanza)
74 local cond = get_error_condition(stanza);
75 return kickable_error_conditions[cond] and cond;
77 local function getUsingPath(stanza, path, getText)
79 for _, name in ipairs(path) do
80 if type(tag) ~= 'table' then return; end
81 tag = tag:child_with_name(name);
83 if tag and getText then tag = table.concat(tag); end
86 local function getTag(stanza, path) return getUsingPath(stanza, path); end
87 local function getText(stanza, path) return getUsingPath(stanza, path, true); end
91 room_mt.__index = room_mt;
93 function room_mt:get_default_role(affiliation)
94 if affiliation == "owner" or affiliation == "admin" then
96 elseif affiliation == "member" then
98 elseif not affiliation then
99 if not self:is_members_only() then
100 return self:is_moderated() and "visitor" or "participant";
105 function room_mt:broadcast_presence(stanza, sid, code, nick)
106 stanza = get_filtered_presence(stanza);
107 local occupant = self._occupants[stanza.attr.from];
108 stanza:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
109 :tag("item", {affiliation=occupant.affiliation or "none", role=occupant.role or "none", nick=nick}):up();
111 stanza:tag("status", {code=code}):up();
113 self:broadcast_except_nick(stanza, stanza.attr.from);
114 local me = self._occupants[stanza.attr.from];
116 stanza:tag("status", {code='110'}):up();
117 stanza.attr.to = sid;
118 self:_route_stanza(stanza);
121 function room_mt:broadcast_message(stanza, historic)
122 local to = stanza.attr.to;
123 for occupant, o_data in pairs(self._occupants) do
124 for jid in pairs(o_data.sessions) do
125 stanza.attr.to = jid;
126 self:_route_stanza(stanza);
130 if historic then -- add to history
131 local history = self._data['history'];
132 if not history then history = {}; self._data['history'] = history; end
133 stanza = st.clone(stanza);
135 local stamp = datetime.datetime();
136 local chars = #tostring(stanza);
137 stanza:tag("delay", {xmlns = "urn:xmpp:delay", from = muc_domain, stamp = stamp}):up(); -- XEP-0203
138 stanza:tag("x", {xmlns = "jabber:x:delay", from = muc_domain, stamp = datetime.legacy()}):up(); -- XEP-0091 (deprecated)
139 local entry = { stanza = stanza, stamp = stamp };
140 t_insert(history, entry);
141 while #history > (self._data.history_length or default_history_length) do t_remove(history, 1) end
144 function room_mt:broadcast_except_nick(stanza, nick)
145 for rnick, occupant in pairs(self._occupants) do
146 if rnick ~= nick then
147 for jid in pairs(occupant.sessions) do
148 stanza.attr.to = jid;
149 self:_route_stanza(stanza);
155 function room_mt:send_occupant_list(to)
156 local current_nick = self._jid_nick[to];
157 for occupant, o_data in pairs(self._occupants) do
158 if occupant ~= current_nick then
159 local pres = get_filtered_presence(o_data.sessions[o_data.jid]);
160 pres.attr.to, pres.attr.from = to, occupant;
161 pres:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
162 :tag("item", {affiliation=o_data.affiliation or "none", role=o_data.role or "none"}):up();
163 self:_route_stanza(pres);
167 function room_mt:send_history(to, stanza)
168 local history = self._data['history']; -- send discussion history
170 local x_tag = stanza and stanza:get_child("x", "http://jabber.org/protocol/muc");
171 local history_tag = x_tag and x_tag:get_child("history", "http://jabber.org/protocol/muc");
173 local maxchars = history_tag and tonumber(history_tag.attr.maxchars);
174 if maxchars then maxchars = math.floor(maxchars); end
176 local maxstanzas = math.floor(history_tag and tonumber(history_tag.attr.maxstanzas) or #history);
177 if not history_tag then maxstanzas = 20; end
179 local seconds = history_tag and tonumber(history_tag.attr.seconds);
180 if seconds then seconds = datetime.datetime(os.time() - math.floor(seconds)); end
182 local since = history_tag and history_tag.attr.since;
183 if since then since = datetime.parse(since); since = since and datetime.datetime(since); end
184 if seconds and (not since or since < seconds) then since = seconds; end
188 local stanzacount = 0;
190 for i=#history,1,-1 do
191 local entry = history[i];
193 if not entry.chars then
194 entry.stanza.attr.to = "";
195 entry.chars = #tostring(entry.stanza);
197 charcount = charcount + entry.chars + #to;
198 if charcount > maxchars then break; end
200 if since and since > entry.stamp then break; end
201 if n + 1 > maxstanzas then break; end
204 for i=#history-n+1,#history do
205 local msg = history[i].stanza;
207 self:_route_stanza(msg);
210 if self._data['subject'] then
211 self:_route_stanza(st.message({type='groupchat', from=self._data['subject_from'] or self.jid, to=to}):tag("subject"):text(self._data['subject']));
215 function room_mt:get_disco_info(stanza)
216 return st.reply(stanza):query("http://jabber.org/protocol/disco#info")
217 :tag("identity", {category="conference", type="text", name=self:get_name()}):up()
218 :tag("feature", {var="http://jabber.org/protocol/muc"}):up()
219 :tag("feature", {var=self:get_password() and "muc_passwordprotected" or "muc_unsecured"}):up()
220 :tag("feature", {var=self:is_moderated() and "muc_moderated" or "muc_unmoderated"}):up()
221 :tag("feature", {var=self:is_members_only() and "muc_membersonly" or "muc_open"}):up()
222 :tag("feature", {var=self:is_persistent() and "muc_persistent" or "muc_temporary"}):up()
223 :tag("feature", {var=self:is_hidden() and "muc_hidden" or "muc_public"}):up()
224 :tag("feature", {var=self._data.whois ~= "anyone" and "muc_semianonymous" or "muc_nonanonymous"}):up()
225 :add_child(dataform.new({
226 { name = "FORM_TYPE", type = "hidden", value = "http://jabber.org/protocol/muc#roominfo" },
227 { name = "muc#roominfo_description", label = "Description"}
228 }):form({["muc#roominfo_description"] = self:get_description()}, 'result'))
231 function room_mt:get_disco_items(stanza)
232 local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#items");
233 for room_jid in pairs(self._occupants) do
234 reply:tag("item", {jid = room_jid, name = room_jid:match("/(.*)")}):up();
238 function room_mt:set_subject(current_nick, subject)
239 -- TODO check nick's authority
240 if subject == "" then subject = nil; end
241 self._data['subject'] = subject;
242 self._data['subject_from'] = current_nick;
243 if self.save then self:save(); end
244 local msg = st.message({type='groupchat', from=current_nick})
245 :tag('subject'):text(subject):up();
246 self:broadcast_message(msg, false);
250 local function build_unavailable_presence_from_error(stanza)
251 local type, condition, text = stanza:get_error();
252 local error_message = "Kicked: "..(condition and condition:gsub("%-", " ") or "presence error");
254 error_message = error_message..": "..text;
256 return st.presence({type='unavailable', from=stanza.attr.from, to=stanza.attr.to})
257 :tag('status'):text(error_message);
260 function room_mt:set_name(name)
261 if name == "" or type(name) ~= "string" or name == (jid_split(self.jid)) then name = nil; end
262 if self._data.name ~= name then
263 self._data.name = name;
264 if self.save then self:save(true); end
267 function room_mt:get_name()
268 return self._data.name or jid_split(self.jid);
270 function room_mt:set_description(description)
271 if description == "" or type(description) ~= "string" then description = nil; end
272 if self._data.description ~= description then
273 self._data.description = description;
274 if self.save then self:save(true); end
277 function room_mt:get_description()
278 return self._data.description;
280 function room_mt:set_password(password)
281 if password == "" or type(password) ~= "string" then password = nil; end
282 if self._data.password ~= password then
283 self._data.password = password;
284 if self.save then self:save(true); end
287 function room_mt:get_password()
288 return self._data.password;
290 function room_mt:set_moderated(moderated)
291 moderated = moderated and true or nil;
292 if self._data.moderated ~= moderated then
293 self._data.moderated = moderated;
294 if self.save then self:save(true); end
297 function room_mt:is_moderated()
298 return self._data.moderated;
300 function room_mt:set_members_only(members_only)
301 members_only = members_only and true or nil;
302 if self._data.members_only ~= members_only then
303 self._data.members_only = members_only;
304 if self.save then self:save(true); end
307 function room_mt:is_members_only()
308 return self._data.members_only;
310 function room_mt:set_persistent(persistent)
311 persistent = persistent and true or nil;
312 if self._data.persistent ~= persistent then
313 self._data.persistent = persistent;
314 if self.save then self:save(true); end
317 function room_mt:is_persistent()
318 return self._data.persistent;
320 function room_mt:set_hidden(hidden)
321 hidden = hidden and true or nil;
322 if self._data.hidden ~= hidden then
323 self._data.hidden = hidden;
324 if self.save then self:save(true); end
327 function room_mt:is_hidden()
328 return self._data.hidden;
330 function room_mt:set_changesubject(changesubject)
331 changesubject = changesubject and true or nil;
332 if self._data.changesubject ~= changesubject then
333 self._data.changesubject = changesubject;
334 if self.save then self:save(true); end
337 function room_mt:get_changesubject()
338 return self._data.changesubject;
341 function room_mt:handle_to_occupant(origin, stanza) -- PM, vCards, etc
342 local from, to = stanza.attr.from, stanza.attr.to;
343 local room = jid_bare(to);
344 local current_nick = self._jid_nick[from];
345 local type = stanza.attr.type;
346 log("debug", "room: %s, current_nick: %s, stanza: %s", room or "nil", current_nick or "nil", stanza:top_tag());
347 if (select(2, jid_split(from)) == muc_domain) then error("Presence from the MUC itself!!!"); end
348 if stanza.name == "presence" then
349 local pr = get_filtered_presence(stanza);
350 pr.attr.from = current_nick;
351 if type == "error" then -- error, kick em out!
353 log("debug", "kicking %s from %s", current_nick, room);
354 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza));
356 elseif type == "unavailable" then -- unavailable
358 log("debug", "%s leaving %s", current_nick, room);
359 local occupant = self._occupants[current_nick];
360 local new_jid = next(occupant.sessions);
361 if new_jid == from then new_jid = next(occupant.sessions, new_jid); end
363 local jid = occupant.jid;
364 occupant.jid = new_jid;
365 occupant.sessions[from] = nil;
367 pr:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
368 :tag("item", {affiliation=occupant.affiliation or "none", role='none'}):up()
369 :tag("status", {code='110'}):up();
370 self:_route_stanza(pr);
371 if jid ~= new_jid then
372 pr = st.clone(occupant.sessions[new_jid])
373 :tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
374 :tag("item", {affiliation=occupant.affiliation or "none", role=occupant.role or "none"});
375 pr.attr.from = current_nick;
376 self:broadcast_except_nick(pr, current_nick);
379 occupant.role = 'none';
380 self:broadcast_presence(pr, from);
381 self._occupants[current_nick] = nil;
383 self._jid_nick[from] = nil;
385 elseif not type then -- available
387 --if #pr == #stanza or current_nick ~= to then -- commented because google keeps resending directed presence
388 if current_nick == to then -- simple presence
389 log("debug", "%s broadcasted presence", current_nick);
390 self._occupants[current_nick].sessions[from] = pr;
391 self:broadcast_presence(pr, from);
393 local occupant = self._occupants[current_nick];
394 local is_multisession = next(occupant.sessions, next(occupant.sessions));
395 if self._occupants[to] or is_multisession then
396 log("debug", "%s couldn't change nick", current_nick);
397 local reply = st.error_reply(stanza, "cancel", "conflict"):up();
398 reply.tags[1].attr.code = "409";
399 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
401 local data = self._occupants[current_nick];
402 local to_nick = select(3, jid_split(to));
404 log("debug", "%s (%s) changing nick to %s", current_nick, data.jid, to);
405 local p = st.presence({type='unavailable', from=current_nick});
406 self:broadcast_presence(p, from, '303', to_nick);
407 self._occupants[current_nick] = nil;
408 self._occupants[to] = data;
409 self._jid_nick[from] = to;
411 self._occupants[to].sessions[from] = pr;
412 self:broadcast_presence(pr, from);
418 --else -- possible rejoin
419 -- log("debug", "%s had connection replaced", current_nick);
420 -- self:handle_to_occupant(origin, st.presence({type='unavailable', from=from, to=to})
421 -- :tag('status'):text('Replaced by new connection'):up()); -- send unavailable
422 -- self:handle_to_occupant(origin, stanza); -- resend available
427 if self._occupants[to] then
428 if jid_bare(from) ~= jid_bare(self._occupants[to].jid) then
433 local password = stanza:get_child("x", "http://jabber.org/protocol/muc");
434 password = password and password:get_child("password", "http://jabber.org/protocol/muc");
435 password = password and password[1] ~= "" and password[1];
436 if self:get_password() and self:get_password() ~= password then
437 log("debug", "%s couldn't join due to invalid password: %s", from, to);
438 local reply = st.error_reply(stanza, "auth", "not-authorized"):up();
439 reply.tags[1].attr.code = "401";
440 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
441 elseif not new_nick then
442 log("debug", "%s couldn't join due to nick conflict: %s", from, to);
443 local reply = st.error_reply(stanza, "cancel", "conflict"):up();
444 reply.tags[1].attr.code = "409";
445 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
447 log("debug", "%s joining as %s", from, to);
448 if not next(self._affiliations) then -- new room, no owners
449 self._affiliations[jid_bare(from)] = "owner";
451 local affiliation = self:get_affiliation(from);
452 local role = self:get_default_role(affiliation)
453 if role then -- new occupant
455 self._occupants[to] = {affiliation=affiliation, role=role, jid=from, sessions={[from]=get_filtered_presence(stanza)}};
457 self._occupants[to].sessions[from] = get_filtered_presence(stanza);
459 self._jid_nick[from] = to;
460 self:send_occupant_list(from);
462 pr:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
463 :tag("item", {affiliation=affiliation or "none", role=role or "none"}):up();
465 self:broadcast_except_nick(pr, to);
467 pr:tag("status", {code='110'}):up();
468 if self._data.whois == 'anyone' then
469 pr:tag("status", {code='100'}):up();
472 self:_route_stanza(pr);
473 self:send_history(from, stanza);
474 elseif not affiliation then -- registration required for entering members-only room
475 local reply = st.error_reply(stanza, "auth", "registration-required"):up();
476 reply.tags[1].attr.code = "407";
477 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
479 local reply = st.error_reply(stanza, "auth", "forbidden"):up();
480 reply.tags[1].attr.code = "403";
481 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
485 elseif type ~= 'result' then -- bad type
486 if type ~= 'visible' and type ~= 'invisible' then -- COMPAT ejabberd can broadcast or forward XEP-0018 presences
487 origin.send(st.error_reply(stanza, "modify", "bad-request")); -- FIXME correct error?
490 elseif not current_nick then -- not in room
491 if type == "error" or type == "result" then
492 local id = stanza.name == "iq" and stanza.attr.id and base64.decode(stanza.attr.id);
493 local _nick, _id, _hash = (id or ""):match("^(.+)%z(.*)%z(.+)$");
494 local occupant = self._occupants[stanza.attr.to];
495 if occupant and _nick and self._jid_nick[_nick] and _id and _hash then
496 local id, _to = stanza.attr.id;
497 for jid in pairs(occupant.sessions) do
498 if md5(jid) == _hash then
504 stanza.attr.to, stanza.attr.from, stanza.attr.id = _to, self._jid_nick[_nick], _id;
505 self:_route_stanza(stanza);
506 stanza.attr.to, stanza.attr.from, stanza.attr.id = to, from, id;
510 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
512 elseif stanza.name == "message" and type == "groupchat" then -- groupchat messages not allowed in PM
513 origin.send(st.error_reply(stanza, "modify", "bad-request"));
514 elseif current_nick and stanza.name == "message" and type == "error" and is_kickable_error(stanza) then
515 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
516 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza)); -- send unavailable
517 else -- private stanza
518 local o_data = self._occupants[to];
520 log("debug", "%s sent private stanza to %s (%s)", from, to, o_data.jid);
521 local jid = o_data.jid;
522 local bare = jid_bare(jid);
523 stanza.attr.to, stanza.attr.from = jid, current_nick;
524 local id = stanza.attr.id;
525 if stanza.name=='iq' and type=='get' and stanza.tags[1].attr.xmlns == 'vcard-temp' and bare ~= jid then
526 stanza.attr.to = bare;
527 stanza.attr.id = base64.encode(jid.."\0"..id.."\0"..md5(from));
529 self:_route_stanza(stanza);
530 stanza.attr.to, stanza.attr.from, stanza.attr.id = to, from, id;
531 elseif type ~= "error" and type ~= "result" then -- recipient not in room
532 origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
537 function room_mt:send_form(origin, stanza)
538 origin.send(st.reply(stanza):query("http://jabber.org/protocol/muc#owner")
539 :add_child(self:get_form_layout():form())
543 function room_mt:get_form_layout()
544 local title = "Configuration for "..self.jid;
545 return dataform.new({
547 instructions = title,
551 value = 'http://jabber.org/protocol/muc#roomconfig'
554 name = 'muc#roomconfig_roomname',
555 type = 'text-single',
557 value = self:get_name() or "",
560 name = 'muc#roomconfig_roomdesc',
561 type = 'text-single',
562 label = 'Description',
563 value = self:get_description() or "",
566 name = 'muc#roomconfig_persistentroom',
568 label = 'Make Room Persistent?',
569 value = self:is_persistent()
572 name = 'muc#roomconfig_publicroom',
574 label = 'Make Room Publicly Searchable?',
575 value = not self:is_hidden()
578 name = 'muc#roomconfig_changesubject',
580 label = 'Allow Occupants to Change Subject?',
581 value = self:get_changesubject()
584 name = 'muc#roomconfig_whois',
585 type = 'list-single',
586 label = 'Who May Discover Real JIDs?',
588 { value = 'moderators', label = 'Moderators Only', default = self._data.whois == 'moderators' },
589 { value = 'anyone', label = 'Anyone', default = self._data.whois == 'anyone' }
593 name = 'muc#roomconfig_roomsecret',
594 type = 'text-private',
596 value = self:get_password() or "",
599 name = 'muc#roomconfig_moderatedroom',
601 label = 'Make Room Moderated?',
602 value = self:is_moderated()
605 name = 'muc#roomconfig_membersonly',
607 label = 'Make Room Members-Only?',
608 value = self:is_members_only()
613 local valid_whois = {
618 function room_mt:process_form(origin, stanza)
619 local query = stanza.tags[1];
621 for _, tag in ipairs(query.tags) do if tag.name == "x" and tag.attr.xmlns == "jabber:x:data" then form = tag; break; end end
622 if not form then origin.send(st.error_reply(stanza, "cancel", "service-unavailable")); return; end
623 if form.attr.type == "cancel" then origin.send(st.reply(stanza)); return; end
624 if form.attr.type ~= "submit" then origin.send(st.error_reply(stanza, "cancel", "bad-request", "Not a submitted form")); return; end
626 local fields = self:get_form_layout():data(form);
627 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
631 local name = fields['muc#roomconfig_roomname'];
632 if name ~= self:get_name() then
636 local description = fields['muc#roomconfig_roomdesc'];
637 if description ~= self:get_description() then
638 self:set_description(description);
641 local persistent = fields['muc#roomconfig_persistentroom'];
642 dirty = dirty or (self:is_persistent() ~= persistent)
643 module:log("debug", "persistent=%s", tostring(persistent));
645 local moderated = fields['muc#roomconfig_moderatedroom'];
646 dirty = dirty or (self:is_moderated() ~= moderated)
647 module:log("debug", "moderated=%s", tostring(moderated));
649 local membersonly = fields['muc#roomconfig_membersonly'];
650 dirty = dirty or (self:is_members_only() ~= membersonly)
651 module:log("debug", "membersonly=%s", tostring(membersonly));
653 local public = fields['muc#roomconfig_publicroom'];
654 dirty = dirty or (self:is_hidden() ~= (not public and true or nil))
656 local changesubject = fields['muc#roomconfig_changesubject'];
657 dirty = dirty or (self:get_changesubject() ~= (not changesubject and true or nil))
658 module:log('debug', 'changesubject=%s', changesubject and "true" or "false")
660 local whois = fields['muc#roomconfig_whois'];
661 if not valid_whois[whois] then
662 origin.send(st.error_reply(stanza, 'cancel', 'bad-request', "Invalid value for 'whois'"));
665 local whois_changed = self._data.whois ~= whois
666 self._data.whois = whois
667 module:log('debug', 'whois=%s', whois)
669 local password = fields['muc#roomconfig_roomsecret'];
670 if self:get_password() ~= password then
671 self:set_password(password);
673 self:set_moderated(moderated);
674 self:set_members_only(membersonly);
675 self:set_persistent(persistent);
676 self:set_hidden(not public);
677 self:set_changesubject(changesubject);
679 if self.save then self:save(true); end
680 origin.send(st.reply(stanza));
682 if dirty or whois_changed then
683 local msg = st.message({type='groupchat', from=self.jid})
684 :tag('x', {xmlns='http://jabber.org/protocol/muc#user'}):up()
687 msg.tags[1]:tag('status', {code = '104'}):up();
689 if whois_changed then
690 local code = (whois == 'moderators') and "173" or "172";
691 msg.tags[1]:tag('status', {code = code}):up();
694 self:broadcast_message(msg, false)
698 function room_mt:destroy(newjid, reason, password)
699 local pr = st.presence({type = "unavailable"})
700 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
701 :tag("item", { affiliation='none', role='none' }):up()
702 :tag("destroy", {jid=newjid})
703 if reason then pr:tag("reason"):text(reason):up(); end
704 if password then pr:tag("password"):text(password):up(); end
705 for nick, occupant in pairs(self._occupants) do
707 for jid in pairs(occupant.sessions) do
709 self:_route_stanza(pr);
710 self._jid_nick[jid] = nil;
712 self._occupants[nick] = nil;
714 self:set_persistent(false);
717 function room_mt:handle_to_room(origin, stanza) -- presence changes and groupchat messages, along with disco/etc
718 local type = stanza.attr.type;
719 local xmlns = stanza.tags[1] and stanza.tags[1].attr.xmlns;
720 if stanza.name == "iq" then
721 if xmlns == "http://jabber.org/protocol/disco#info" and type == "get" then
722 origin.send(self:get_disco_info(stanza));
723 elseif xmlns == "http://jabber.org/protocol/disco#items" and type == "get" then
724 origin.send(self:get_disco_items(stanza));
725 elseif xmlns == "http://jabber.org/protocol/muc#admin" then
726 local actor = stanza.attr.from;
727 local affiliation = self:get_affiliation(actor);
728 local current_nick = self._jid_nick[actor];
729 local role = current_nick and self._occupants[current_nick].role or self:get_default_role(affiliation);
730 local item = stanza.tags[1].tags[1];
731 if item and item.name == "item" then
732 if type == "set" then
733 local callback = function() origin.send(st.reply(stanza)); end
734 if item.attr.jid then -- Validate provided JID
735 item.attr.jid = jid_prep(item.attr.jid);
736 if not item.attr.jid then
737 origin.send(st.error_reply(stanza, "modify", "jid-malformed"));
741 if not item.attr.jid and item.attr.nick then -- COMPAT Workaround for Miranda sending 'nick' instead of 'jid' when changing affiliation
742 local occupant = self._occupants[self.jid.."/"..item.attr.nick];
743 if occupant then item.attr.jid = occupant.jid; end
744 elseif not item.attr.nick and item.attr.jid then
745 local nick = self._jid_nick[item.attr.jid];
746 if nick then item.attr.nick = select(3, jid_split(nick)); end
748 local reason = item.tags[1] and item.tags[1].name == "reason" and #item.tags[1] == 1 and item.tags[1][1];
749 if item.attr.affiliation and item.attr.jid and not item.attr.role then
750 local success, errtype, err = self:set_affiliation(actor, item.attr.jid, item.attr.affiliation, callback, reason);
751 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
752 elseif item.attr.role and item.attr.nick and not item.attr.affiliation then
753 local success, errtype, err = self:set_role(actor, self.jid.."/"..item.attr.nick, item.attr.role, callback, reason);
754 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
756 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
758 elseif type == "get" then
759 local _aff = item.attr.affiliation;
760 local _rol = item.attr.role;
761 if _aff and not _rol then
762 if affiliation == "owner" or (affiliation == "admin" and _aff ~= "owner" and _aff ~= "admin") then
763 local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
764 for jid, affiliation in pairs(self._affiliations) do
765 if affiliation == _aff then
766 reply:tag("item", {affiliation = _aff, jid = jid}):up();
771 origin.send(st.error_reply(stanza, "auth", "forbidden"));
773 elseif _rol and not _aff then
774 if role == "moderator" then
775 -- TODO allow admins and owners not in room? Provide read-only access to everyone who can see the participants anyway?
776 if _rol == "none" then _rol = nil; end
777 local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
778 for occupant_jid, occupant in pairs(self._occupants) do
779 if occupant.role == _rol then
781 nick = select(3, jid_split(occupant_jid)),
782 role = _rol or "none",
783 affiliation = occupant.affiliation or "none",
790 origin.send(st.error_reply(stanza, "auth", "forbidden"));
793 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
796 elseif type == "set" or type == "get" then
797 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
799 elseif xmlns == "http://jabber.org/protocol/muc#owner" and (type == "get" or type == "set") and stanza.tags[1].name == "query" then
800 if self:get_affiliation(stanza.attr.from) ~= "owner" then
801 origin.send(st.error_reply(stanza, "auth", "forbidden", "Only owners can configure rooms"));
802 elseif stanza.attr.type == "get" then
803 self:send_form(origin, stanza);
804 elseif stanza.attr.type == "set" then
805 local child = stanza.tags[1].tags[1];
807 origin.send(st.error_reply(stanza, "auth", "bad-request"));
808 elseif child.name == "destroy" then
809 local newjid = child.attr.jid;
810 local reason, password;
811 for _,tag in ipairs(child.tags) do
812 if tag.name == "reason" then
813 reason = #tag.tags == 0 and tag[1];
814 elseif tag.name == "password" then
815 password = #tag.tags == 0 and tag[1];
818 self:destroy(newjid, reason, password);
819 origin.send(st.reply(stanza));
821 self:process_form(origin, stanza);
824 elseif type == "set" or type == "get" then
825 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
827 elseif stanza.name == "message" and type == "groupchat" then
828 local from, to = stanza.attr.from, stanza.attr.to;
829 local room = jid_bare(to);
830 local current_nick = self._jid_nick[from];
831 local occupant = self._occupants[current_nick];
832 if not occupant then -- not in room
833 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
834 elseif occupant.role == "visitor" then
835 origin.send(st.error_reply(stanza, "cancel", "forbidden"));
837 local from = stanza.attr.from;
838 stanza.attr.from = current_nick;
839 local subject = getText(stanza, {"subject"});
841 if occupant.role == "moderator" or
842 ( self._data.changesubject and occupant.role == "participant" ) then -- and participant
843 self:set_subject(current_nick, subject); -- TODO use broadcast_message_stanza
845 stanza.attr.from = from;
846 origin.send(st.error_reply(stanza, "cancel", "forbidden"));
849 self:broadcast_message(stanza, true);
851 stanza.attr.from = from;
853 elseif stanza.name == "message" and type == "error" and is_kickable_error(stanza) then
854 local current_nick = self._jid_nick[stanza.attr.from];
855 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
856 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza)); -- send unavailable
857 elseif stanza.name == "presence" then -- hack - some buggy clients send presence updates to the room rather than their nick
858 local to = stanza.attr.to;
859 local current_nick = self._jid_nick[stanza.attr.from];
861 stanza.attr.to = current_nick;
862 self:handle_to_occupant(origin, stanza);
864 elseif type ~= "error" and type ~= "result" then
865 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
867 elseif stanza.name == "message" and not stanza.attr.type and #stanza.tags == 1 and self._jid_nick[stanza.attr.from]
868 and stanza.tags[1].name == "x" and stanza.tags[1].attr.xmlns == "http://jabber.org/protocol/muc#user" then
869 local x = stanza.tags[1];
870 local payload = (#x.tags == 1 and x.tags[1]);
871 if payload and payload.name == "invite" and payload.attr.to then
872 local _from, _to = stanza.attr.from, stanza.attr.to;
873 local _invitee = jid_prep(payload.attr.to);
875 local _reason = payload.tags[1] and payload.tags[1].name == 'reason' and #payload.tags[1].tags == 0 and payload.tags[1][1];
876 local invite = st.message({from = _to, to = _invitee, id = stanza.attr.id})
877 :tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
878 :tag('invite', {from=_from})
879 :tag('reason'):text(_reason or ""):up()
881 if self:get_password() then
882 invite:tag("password"):text(self:get_password()):up();
885 :tag('x', {xmlns="jabber:x:conference", jid=_to}) -- COMPAT: Some older clients expect this
888 :tag('body') -- Add a plain message for clients which don't support invites
889 :text(_from..' invited you to the room '.._to..(_reason and (' ('.._reason..')') or ""))
891 if self:is_members_only() and not self:get_affiliation(_invitee) then
892 log("debug", "%s invited %s into members only room %s, granting membership", _from, _invitee, _to);
893 self:set_affiliation(_from, _invitee, "member", nil, "Invited by " .. self._jid_nick[_from])
895 self:_route_stanza(invite);
897 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
900 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
903 if type == "error" or type == "result" then return; end
904 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
908 function room_mt:handle_stanza(origin, stanza)
909 local to_node, to_host, to_resource = jid_split(stanza.attr.to);
911 self:handle_to_occupant(origin, stanza);
913 self:handle_to_room(origin, stanza);
917 function room_mt:route_stanza(stanza) end -- Replace with a routing function, e.g., function(room, stanza) core_route_stanza(origin, stanza); end
919 function room_mt:get_affiliation(jid)
920 local node, host, resource = jid_split(jid);
921 local bare = node and node.."@"..host or host;
922 local result = self._affiliations[bare]; -- Affiliations are granted, revoked, and maintained based on the user's bare JID.
923 if not result and self._affiliations[host] == "outcast" then result = "outcast"; end -- host banned
926 function room_mt:set_affiliation(actor, jid, affiliation, callback, reason)
928 if affiliation == "none" then affiliation = nil; end
929 if affiliation and affiliation ~= "outcast" and affiliation ~= "owner" and affiliation ~= "admin" and affiliation ~= "member" then
930 return nil, "modify", "not-acceptable";
932 local actor_affiliation = self:get_affiliation(actor);
933 local target_affiliation = self:get_affiliation(jid);
934 if target_affiliation == affiliation then -- no change, shortcut
935 if callback then callback(); end
938 if actor_affiliation ~= "owner" then
939 if actor_affiliation ~= "admin" or target_affiliation == "owner" or target_affiliation == "admin" then
940 return nil, "cancel", "not-allowed";
942 elseif target_affiliation == "owner" and jid_bare(actor) == jid then -- self change
943 local is_last = true;
944 for j, aff in pairs(self._affiliations) do if j ~= jid and aff == "owner" then is_last = false; break; end end
946 return nil, "cancel", "conflict";
949 self._affiliations[jid] = affiliation;
950 local role = self:get_default_role(affiliation);
951 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"})
952 :tag("item", {affiliation=affiliation or "none", role=role or "none"})
953 :tag("reason"):text(reason or ""):up()
955 local presence_type = nil;
956 if not role then -- getting kicked
957 presence_type = "unavailable";
958 if affiliation == "outcast" then
959 x:tag("status", {code="301"}):up(); -- banned
961 x:tag("status", {code="321"}):up(); -- affiliation change
964 local modified_nicks = {};
965 for nick, occupant in pairs(self._occupants) do
966 if jid_bare(occupant.jid) == jid then
967 if not role then -- getting kicked
968 self._occupants[nick] = nil;
970 occupant.affiliation, occupant.role = affiliation, role;
972 for jid,pres in pairs(occupant.sessions) do -- remove for all sessions of the nick
973 if not role then self._jid_nick[jid] = nil; end
974 local p = st.clone(pres);
976 p.attr.type = presence_type;
979 self:_route_stanza(p);
980 if occupant.jid == jid then
981 modified_nicks[nick] = p;
986 if self.save then self:save(); end
987 if callback then callback(); end
988 for nick,p in pairs(modified_nicks) do
990 self:broadcast_except_nick(p, nick);
995 function room_mt:get_role(nick)
996 local session = self._occupants[nick];
997 return session and session.role or nil;
999 function room_mt:can_set_role(actor_jid, occupant_jid, role)
1000 local actor = self._occupants[self._jid_nick[actor_jid]];
1001 local occupant = self._occupants[occupant_jid];
1003 if not occupant or not actor then return nil, "modify", "not-acceptable"; end
1005 if actor.role == "moderator" then
1006 if occupant.affiliation ~= "owner" and occupant.affiliation ~= "admin" then
1007 if actor.affiliation == "owner" or actor.affiliation == "admin" then
1009 elseif occupant.role ~= "moderator" and role ~= "moderator" then
1014 return nil, "cancel", "not-allowed";
1016 function room_mt:set_role(actor, occupant_jid, role, callback, reason)
1017 if role == "none" then role = nil; end
1018 if role and role ~= "moderator" and role ~= "participant" and role ~= "visitor" then return nil, "modify", "not-acceptable"; end
1019 local allowed, err_type, err_condition = self:can_set_role(actor, occupant_jid, role);
1020 if not allowed then return allowed, err_type, err_condition; end
1021 local occupant = self._occupants[occupant_jid];
1022 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"})
1023 :tag("item", {affiliation=occupant.affiliation or "none", nick=select(3, jid_split(occupant_jid)), role=role or "none"})
1024 :tag("reason"):text(reason or ""):up()
1026 local presence_type = nil;
1027 if not role then -- kick
1028 presence_type = "unavailable";
1029 self._occupants[occupant_jid] = nil;
1030 for jid in pairs(occupant.sessions) do -- remove for all sessions of the nick
1031 self._jid_nick[jid] = nil;
1033 x:tag("status", {code = "307"}):up();
1035 occupant.role = role;
1038 for jid,pres in pairs(occupant.sessions) do -- send to all sessions of the nick
1039 local p = st.clone(pres);
1040 p.attr.from = occupant_jid;
1041 p.attr.type = presence_type;
1044 self:_route_stanza(p);
1045 if occupant.jid == jid then
1049 if callback then callback(); end
1051 self:broadcast_except_nick(bp, occupant_jid);
1056 function room_mt:_route_stanza(stanza)
1058 local to_occupant = self._occupants[self._jid_nick[stanza.attr.to]];
1059 local from_occupant = self._occupants[stanza.attr.from];
1060 if stanza.name == "presence" then
1061 if to_occupant and from_occupant then
1062 if self._data.whois == 'anyone' then
1063 muc_child = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
1065 if to_occupant.role == "moderator" or jid_bare(to_occupant.jid) == jid_bare(from_occupant.jid) then
1066 muc_child = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
1072 for _, item in pairs(muc_child.tags) do
1073 if item.name == "item" then
1074 if from_occupant == to_occupant then
1075 item.attr.jid = stanza.attr.to;
1077 item.attr.jid = from_occupant.jid;
1082 self:route_stanza(stanza);
1084 for _, item in pairs(muc_child.tags) do
1085 if item.name == "item" then
1086 item.attr.jid = nil;
1092 local _M = {}; -- module "muc"
1094 function _M.new_room(jid, config)
1095 return setmetatable({
1100 whois = 'moderators';
1101 history_length = (config and config.history_length);