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 jid_split = require "util.jid".split;
16 local jid_bare = require "util.jid".bare;
17 local jid_prep = require "util.jid".prep;
18 local st = require "util.stanza";
19 local log = require "util.logger".init("mod_muc");
20 local multitable_new = require "util.multitable".new;
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 = 20;
30 local function filter_xmlns_from_array(array, filters)
33 local attr = array[i].attr;
34 if filters[attr and attr.xmlns] then
41 local function filter_xmlns_from_stanza(stanza, filters)
43 if filter_xmlns_from_array(stanza.tags, filters) ~= 0 then
44 return stanza, filter_xmlns_from_array(stanza, filters);
49 local presence_filters = {["http://jabber.org/protocol/muc"]=true;["http://jabber.org/protocol/muc#user"]=true};
50 local function get_filtered_presence(stanza)
51 return filter_xmlns_from_stanza(st.clone(stanza):reset(), presence_filters);
53 local kickable_error_conditions = {
55 ["internal-server-error"] = true;
56 ["item-not-found"] = true;
57 ["jid-malformed"] = true;
58 ["recipient-unavailable"] = true;
60 ["remote-server-not-found"] = true;
61 ["remote-server-timeout"] = true;
62 ["service-unavailable"] = true;
63 ["malformed error"] = true;
66 local function get_error_condition(stanza)
67 local _, condition = stanza:get_error();
68 return condition or "malformed error";
71 local function is_kickable_error(stanza)
72 local cond = get_error_condition(stanza);
73 return kickable_error_conditions[cond] and cond;
75 local function getUsingPath(stanza, path, getText)
77 for _, name in ipairs(path) do
78 if type(tag) ~= 'table' then return; end
79 tag = tag:child_with_name(name);
81 if tag and getText then tag = table.concat(tag); end
84 local function getTag(stanza, path) return getUsingPath(stanza, path); end
85 local function getText(stanza, path) return getUsingPath(stanza, path, true); end
89 room_mt.__index = room_mt;
91 function room_mt:get_default_role(affiliation)
92 if affiliation == "owner" or affiliation == "admin" then
94 elseif affiliation == "member" then
96 elseif not affiliation then
97 if not self:is_members_only() then
98 return self:is_moderated() and "visitor" or "participant";
103 function room_mt:broadcast_presence(stanza, sid, code, nick)
104 stanza = get_filtered_presence(stanza);
105 local occupant = self._occupants[stanza.attr.from];
106 stanza:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
107 :tag("item", {affiliation=occupant.affiliation or "none", role=occupant.role or "none", nick=nick}):up();
109 stanza:tag("status", {code=code}):up();
111 self:broadcast_except_nick(stanza, stanza.attr.from);
112 local me = self._occupants[stanza.attr.from];
114 stanza:tag("status", {code='110'});
115 stanza.attr.to = sid;
116 self:_route_stanza(stanza);
119 function room_mt:broadcast_message(stanza, historic)
120 local to = stanza.attr.to;
121 for occupant, o_data in pairs(self._occupants) do
122 for jid in pairs(o_data.sessions) do
123 stanza.attr.to = jid;
124 self:_route_stanza(stanza);
128 if historic then -- add to history
129 local history = self._data['history'];
130 if not history then history = {}; self._data['history'] = history; end
131 stanza = st.clone(stanza);
133 local stamp = datetime.datetime();
134 local chars = #tostring(stanza);
135 stanza:tag("delay", {xmlns = "urn:xmpp:delay", from = muc_domain, stamp = stamp}):up(); -- XEP-0203
136 stanza:tag("x", {xmlns = "jabber:x:delay", from = muc_domain, stamp = datetime.legacy()}):up(); -- XEP-0091 (deprecated)
137 local entry = { stanza = stanza, stamp = stamp };
138 t_insert(history, entry);
139 while #history > (self._data.history_length or default_history_length) do t_remove(history, 1) end
142 function room_mt:broadcast_except_nick(stanza, nick)
143 for rnick, occupant in pairs(self._occupants) do
144 if rnick ~= nick then
145 for jid in pairs(occupant.sessions) do
146 stanza.attr.to = jid;
147 self:_route_stanza(stanza);
153 function room_mt:send_occupant_list(to)
154 local current_nick = self._jid_nick[to];
155 for occupant, o_data in pairs(self._occupants) do
156 if occupant ~= current_nick then
157 local pres = get_filtered_presence(o_data.sessions[o_data.jid]);
158 pres.attr.to, pres.attr.from = to, occupant;
159 pres:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
160 :tag("item", {affiliation=o_data.affiliation or "none", role=o_data.role or "none"}):up();
161 self:_route_stanza(pres);
165 function room_mt:send_history(to, stanza)
166 local history = self._data['history']; -- send discussion history
168 local x_tag = stanza and stanza:get_child("x", "http://jabber.org/protocol/muc");
169 local history_tag = x_tag and x_tag:get_child("history", "http://jabber.org/protocol/muc");
171 local maxchars = history_tag and tonumber(history_tag.attr.maxchars);
172 if maxchars then maxchars = math.floor(maxchars); end
174 local maxstanzas = math.floor(history_tag and tonumber(history_tag.attr.maxstanzas) or #history);
175 if not history_tag then maxstanzas = 20; end
177 local seconds = history_tag and tonumber(history_tag.attr.seconds);
178 if seconds then seconds = datetime.datetime(os.time() - math.floor(seconds)); end
180 local since = history_tag and history_tag.attr.since;
181 if since and not since:match("^%d%d%d%d%-%d%d%-%d%dT%d%d:%d%d:%d%dZ$") then since = nil; end -- FIXME timezone support
182 if seconds and (not since or since < seconds) then since = seconds; end
186 local stanzacount = 0;
188 for i=#history,1,-1 do
189 local entry = history[i];
191 if not entry.chars then
192 entry.stanza.attr.to = "";
193 entry.chars = #tostring(entry.stanza);
195 charcount = charcount + entry.chars + #to;
196 if charcount > maxchars then break; end
198 if since and since > entry.stamp then break; end
199 if n + 1 > maxstanzas then break; end
202 for i=#history-n+1,#history do
203 local msg = history[i].stanza;
205 self:_route_stanza(msg);
208 if self._data['subject'] then
209 self:_route_stanza(st.message({type='groupchat', from=self.jid, to=to}):tag("subject"):text(self._data['subject']));
213 function room_mt:get_disco_info(stanza)
214 return st.reply(stanza):query("http://jabber.org/protocol/disco#info")
215 :tag("identity", {category="conference", type="text"}):up()
216 :tag("feature", {var="http://jabber.org/protocol/muc"}):up()
217 :tag("feature", {var=self:get_password() and "muc_passwordprotected" or "muc_unsecured"}):up()
218 :tag("feature", {var=self:is_moderated() and "muc_moderated" or "muc_unmoderated"}):up()
219 :tag("feature", {var=self:is_members_only() and "muc_membersonly" or "muc_open"}):up()
220 :tag("feature", {var=self:is_persistent() and "muc_persistent" or "muc_temporary"}):up()
221 :tag("feature", {var=self:is_hidden() and "muc_hidden" or "muc_public"}):up()
222 :tag("feature", {var=self._data.whois ~= "anyone" and "muc_semianonymous" or "muc_nonanonymous"}):up()
225 function room_mt:get_disco_items(stanza)
226 local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#items");
227 for room_jid in pairs(self._occupants) do
228 reply:tag("item", {jid = room_jid, name = room_jid:match("/(.*)")}):up();
232 function room_mt:set_subject(current_nick, subject)
233 -- TODO check nick's authority
234 if subject == "" then subject = nil; end
235 self._data['subject'] = subject;
236 if self.save then self:save(); end
237 local msg = st.message({type='groupchat', from=current_nick})
238 :tag('subject'):text(subject):up();
239 self:broadcast_message(msg, false);
243 local function build_unavailable_presence_from_error(stanza)
244 local type, condition, text = stanza:get_error();
245 local error_message = "Kicked: "..condition:gsub("%-", " ");
247 error_message = error_message..": "..text;
249 return st.presence({type='unavailable', from=stanza.attr.from, to=stanza.attr.to})
250 :tag('status'):text(error_message);
253 function room_mt:set_password(password)
254 if password == "" or type(password) ~= "string" then password = nil; end
255 if self._data.password ~= password then
256 self._data.password = password;
257 if self.save then self:save(true); end
260 function room_mt:get_password()
261 return self._data.password;
263 function room_mt:set_moderated(moderated)
264 moderated = moderated and true or nil;
265 if self._data.moderated ~= moderated then
266 self._data.moderated = moderated;
267 if self.save then self:save(true); end
270 function room_mt:is_moderated()
271 return self._data.moderated;
273 function room_mt:set_members_only(members_only)
274 members_only = members_only and true or nil;
275 if self._data.members_only ~= members_only then
276 self._data.members_only = members_only;
277 if self.save then self:save(true); end
280 function room_mt:is_members_only()
281 return self._data.members_only;
283 function room_mt:set_persistent(persistent)
284 persistent = persistent and true or nil;
285 if self._data.persistent ~= persistent then
286 self._data.persistent = persistent;
287 if self.save then self:save(true); end
290 function room_mt:is_persistent()
291 return self._data.persistent;
293 function room_mt:set_hidden(hidden)
294 hidden = hidden and true or nil;
295 if self._data.hidden ~= hidden then
296 self._data.hidden = hidden;
297 if self.save then self:save(true); end
300 function room_mt:is_hidden()
301 return self._data.hidden;
304 function room_mt:handle_to_occupant(origin, stanza) -- PM, vCards, etc
305 local from, to = stanza.attr.from, stanza.attr.to;
306 local room = jid_bare(to);
307 local current_nick = self._jid_nick[from];
308 local type = stanza.attr.type;
309 log("debug", "room: %s, current_nick: %s, stanza: %s", room or "nil", current_nick or "nil", stanza:top_tag());
310 if (select(2, jid_split(from)) == muc_domain) then error("Presence from the MUC itself!!!"); end
311 if stanza.name == "presence" then
312 local pr = get_filtered_presence(stanza);
313 pr.attr.from = current_nick;
314 if type == "error" then -- error, kick em out!
316 log("debug", "kicking %s from %s", current_nick, room);
317 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza));
319 elseif type == "unavailable" then -- unavailable
321 log("debug", "%s leaving %s", current_nick, room);
322 local occupant = self._occupants[current_nick];
323 local new_jid = next(occupant.sessions);
324 if new_jid == from then new_jid = next(occupant.sessions, new_jid); end
326 local jid = occupant.jid;
327 occupant.jid = new_jid;
328 occupant.sessions[from] = nil;
330 pr:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
331 :tag("item", {affiliation=occupant.affiliation or "none", role='none'}):up()
332 :tag("status", {code='110'});
333 self:_route_stanza(pr);
334 if jid ~= new_jid then
335 pr = st.clone(occupant.sessions[new_jid])
336 :tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
337 :tag("item", {affiliation=occupant.affiliation or "none", role=occupant.role or "none"});
338 pr.attr.from = current_nick;
339 self:broadcast_except_nick(pr, current_nick);
342 occupant.role = 'none';
343 self:broadcast_presence(pr, from);
344 self._occupants[current_nick] = nil;
346 self._jid_nick[from] = nil;
348 elseif not type then -- available
350 --if #pr == #stanza or current_nick ~= to then -- commented because google keeps resending directed presence
351 if current_nick == to then -- simple presence
352 log("debug", "%s broadcasted presence", current_nick);
353 self._occupants[current_nick].sessions[from] = pr;
354 self:broadcast_presence(pr, from);
356 local occupant = self._occupants[current_nick];
357 local is_multisession = next(occupant.sessions, next(occupant.sessions));
358 if self._occupants[to] or is_multisession then
359 log("debug", "%s couldn't change nick", current_nick);
360 local reply = st.error_reply(stanza, "cancel", "conflict"):up();
361 reply.tags[1].attr.code = "409";
362 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
364 local data = self._occupants[current_nick];
365 local to_nick = select(3, jid_split(to));
367 log("debug", "%s (%s) changing nick to %s", current_nick, data.jid, to);
368 local p = st.presence({type='unavailable', from=current_nick});
369 self:broadcast_presence(p, from, '303', to_nick);
370 self._occupants[current_nick] = nil;
371 self._occupants[to] = data;
372 self._jid_nick[from] = to;
374 self._occupants[to].sessions[from] = pr;
375 self:broadcast_presence(pr, from);
381 --else -- possible rejoin
382 -- log("debug", "%s had connection replaced", current_nick);
383 -- self:handle_to_occupant(origin, st.presence({type='unavailable', from=from, to=to})
384 -- :tag('status'):text('Replaced by new connection'):up()); -- send unavailable
385 -- self:handle_to_occupant(origin, stanza); -- resend available
390 if self._occupants[to] then
391 if jid_bare(from) ~= jid_bare(self._occupants[to].jid) then
396 local password = stanza:get_child("x", "http://jabber.org/protocol/muc");
397 password = password and password:get_child("password", "http://jabber.org/protocol/muc");
398 password = password and password[1] ~= "" and password[1];
399 if self:get_password() and self:get_password() ~= password then
400 log("debug", "%s couldn't join due to invalid password: %s", from, to);
401 local reply = st.error_reply(stanza, "auth", "not-authorized"):up();
402 reply.tags[1].attr.code = "401";
403 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
404 elseif not new_nick then
405 log("debug", "%s couldn't join due to nick conflict: %s", from, to);
406 local reply = st.error_reply(stanza, "cancel", "conflict"):up();
407 reply.tags[1].attr.code = "409";
408 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
410 log("debug", "%s joining as %s", from, to);
411 if not next(self._affiliations) then -- new room, no owners
412 self._affiliations[jid_bare(from)] = "owner";
414 local affiliation = self:get_affiliation(from);
415 local role = self:get_default_role(affiliation)
416 if role then -- new occupant
418 self._occupants[to] = {affiliation=affiliation, role=role, jid=from, sessions={[from]=get_filtered_presence(stanza)}};
420 self._occupants[to].sessions[from] = get_filtered_presence(stanza);
422 self._jid_nick[from] = to;
423 self:send_occupant_list(from);
426 self:broadcast_presence(pr, from);
429 self:_route_stanza(pr:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
430 :tag("item", {affiliation=affiliation or "none", role=role or "none"}):up()
431 :tag("status", {code='110'}));
433 self:send_history(from, stanza);
435 local reply = st.error_reply(stanza, "auth", "forbidden"):up();
436 reply.tags[1].attr.code = "403";
437 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
441 elseif type ~= 'result' then -- bad type
442 if type ~= 'visible' and type ~= 'invisible' then -- COMPAT ejabberd can broadcast or forward XEP-0018 presences
443 origin.send(st.error_reply(stanza, "modify", "bad-request")); -- FIXME correct error?
446 elseif not current_nick then -- not in room
447 if type == "error" or type == "result" then
448 local id = stanza.name == "iq" and stanza.attr.id and base64.decode(stanza.attr.id);
449 local _nick, _id, _hash = (id or ""):match("^(.+)%z(.*)%z(.+)$");
450 local occupant = self._occupants[stanza.attr.to];
451 if occupant and _nick and self._jid_nick[_nick] and _id and _hash then
452 local id, _to = stanza.attr.id;
453 for jid in pairs(occupant.sessions) do
454 if md5(jid) == _hash then
460 stanza.attr.to, stanza.attr.from, stanza.attr.id = _to, self._jid_nick[_nick], _id;
461 self:_route_stanza(stanza);
462 stanza.attr.to, stanza.attr.from, stanza.attr.id = to, from, id;
466 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
468 elseif stanza.name == "message" and type == "groupchat" then -- groupchat messages not allowed in PM
469 origin.send(st.error_reply(stanza, "modify", "bad-request"));
470 elseif current_nick and stanza.name == "message" and type == "error" and is_kickable_error(stanza) then
471 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
472 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza)); -- send unavailable
473 else -- private stanza
474 local o_data = self._occupants[to];
476 log("debug", "%s sent private stanza to %s (%s)", from, to, o_data.jid);
477 local jid = o_data.jid;
478 local bare = jid_bare(jid);
479 stanza.attr.to, stanza.attr.from = jid, current_nick;
480 local id = stanza.attr.id;
481 if stanza.name=='iq' and type=='get' and stanza.tags[1].attr.xmlns == 'vcard-temp' and bare ~= jid then
482 stanza.attr.to = bare;
483 stanza.attr.id = base64.encode(jid.."\0"..id.."\0"..md5(from));
485 self:_route_stanza(stanza);
486 stanza.attr.to, stanza.attr.from, stanza.attr.id = to, from, id;
487 elseif type ~= "error" and type ~= "result" then -- recipient not in room
488 origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
493 function room_mt:send_form(origin, stanza)
494 local title = "Configuration for "..self.jid;
495 origin.send(st.reply(stanza):query("http://jabber.org/protocol/muc#owner")
496 :tag("x", {xmlns='jabber:x:data', type='form'})
497 :tag("title"):text(title):up()
498 :tag("instructions"):text(title):up()
499 :tag("field", {type='hidden', var='FORM_TYPE'}):tag("value"):text("http://jabber.org/protocol/muc#roomconfig"):up():up()
500 :tag("field", {type='boolean', label='Make Room Persistent?', var='muc#roomconfig_persistentroom'})
501 :tag("value"):text(self:is_persistent() and "1" or "0"):up()
503 :tag("field", {type='boolean', label='Make Room Publicly Searchable?', var='muc#roomconfig_publicroom'})
504 :tag("value"):text(self:is_hidden() and "0" or "1"):up()
506 :tag("field", {type='list-single', label='Who May Discover Real JIDs?', var='muc#roomconfig_whois'})
507 :tag("value"):text(self._data.whois or 'moderators'):up()
508 :tag("option", {label = 'Moderators Only'})
509 :tag("value"):text('moderators'):up()
511 :tag("option", {label = 'Anyone'})
512 :tag("value"):text('anyone'):up()
515 :tag("field", {type='text-private', label='Password', var='muc#roomconfig_roomsecret'})
516 :tag("value"):text(self:get_password() or ""):up()
518 :tag("field", {type='boolean', label='Make Room Moderated?', var='muc#roomconfig_moderatedroom'})
519 :tag("value"):text(self:is_moderated() and "1" or "0"):up()
521 :tag("field", {type='boolean', label='Make Room Members-Only?', var='muc#roomconfig_membersonly'})
522 :tag("value"):text(self:is_members_only() and "1" or "0"):up()
527 local valid_whois = {
532 function room_mt:process_form(origin, stanza)
533 local query = stanza.tags[1];
535 for _, tag in ipairs(query.tags) do if tag.name == "x" and tag.attr.xmlns == "jabber:x:data" then form = tag; break; end end
536 if not form then origin.send(st.error_reply(stanza, "cancel", "service-unavailable")); return; end
537 if form.attr.type == "cancel" then origin.send(st.reply(stanza)); return; end
538 if form.attr.type ~= "submit" then origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
540 for _, field in pairs(form.tags) do
541 if field.name == "field" and field.attr.var and field.tags[1].name == "value" and #field.tags[1].tags == 0 then
542 fields[field.attr.var] = field.tags[1][1] or "";
545 if fields.FORM_TYPE ~= "http://jabber.org/protocol/muc#roomconfig" then origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
549 local persistent = fields['muc#roomconfig_persistentroom'];
550 if persistent == "0" or persistent == "false" then persistent = nil; elseif persistent == "1" or persistent == "true" then persistent = true;
551 else origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
552 dirty = dirty or (self:is_persistent() ~= persistent)
553 module:log("debug", "persistent=%s", tostring(persistent));
555 local moderated = fields['muc#roomconfig_moderatedroom'];
556 if moderated == "0" or moderated == "false" then moderated = nil; elseif moderated == "1" or moderated == "true" then moderated = true;
557 else origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
558 dirty = dirty or (self:is_moderated() ~= moderated)
559 module:log("debug", "moderated=%s", tostring(moderated));
561 local membersonly = fields['muc#roomconfig_membersonly'];
562 if membersonly == "0" or membersonly == "false" then membersonly = nil; elseif membersonly == "1" or membersonly == "true" then membersonly = true;
563 else origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
564 dirty = dirty or (self:is_members_only() ~= membersonly)
565 module:log("debug", "membersonly=%s", tostring(membersonly));
567 local public = fields['muc#roomconfig_publicroom'];
568 if public == "0" or public == "false" then public = nil; elseif public == "1" or public == "true" then public = true;
569 else origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
570 dirty = dirty or (self:is_hidden() ~= (not public and true or nil))
572 local whois = fields['muc#roomconfig_whois'];
573 if not valid_whois[whois] then
574 origin.send(st.error_reply(stanza, 'cancel', 'bad-request'));
577 local whois_changed = self._data.whois ~= whois
578 self._data.whois = whois
579 module:log('debug', 'whois=%s', whois)
581 local password = fields['muc#roomconfig_roomsecret'];
583 self:set_password(password);
585 self:set_moderated(moderated);
586 self:set_members_only(membersonly);
587 self:set_persistent(persistent);
588 self:set_hidden(not public);
590 if self.save then self:save(true); end
591 origin.send(st.reply(stanza));
593 if dirty or whois_changed then
594 local msg = st.message({type='groupchat', from=self.jid})
595 :tag('x', {xmlns='http://jabber.org/protocol/muc#user'}):up()
598 msg.tags[1]:tag('status', {code = '104'})
600 if whois_changed then
601 local code = (whois == 'moderators') and 173 or 172
602 msg.tags[1]:tag('status', {code = code})
605 self:broadcast_message(msg, false)
609 function room_mt:destroy(newjid, reason, password)
610 local pr = st.presence({type = "unavailable"})
611 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
612 :tag("item", { affiliation='none', role='none' }):up()
613 :tag("destroy", {jid=newjid})
614 if reason then pr:tag("reason"):text(reason):up(); end
615 if password then pr:tag("password"):text(password):up(); end
616 for nick, occupant in pairs(self._occupants) do
618 for jid in pairs(occupant.sessions) do
620 self:_route_stanza(pr);
621 self._jid_nick[jid] = nil;
623 self._occupants[nick] = nil;
625 self:set_persistent(false);
628 function room_mt:handle_to_room(origin, stanza) -- presence changes and groupchat messages, along with disco/etc
629 local type = stanza.attr.type;
630 local xmlns = stanza.tags[1] and stanza.tags[1].attr.xmlns;
631 if stanza.name == "iq" then
632 if xmlns == "http://jabber.org/protocol/disco#info" and type == "get" then
633 origin.send(self:get_disco_info(stanza));
634 elseif xmlns == "http://jabber.org/protocol/disco#items" and type == "get" then
635 origin.send(self:get_disco_items(stanza));
636 elseif xmlns == "http://jabber.org/protocol/muc#admin" then
637 local actor = stanza.attr.from;
638 local affiliation = self:get_affiliation(actor);
639 local current_nick = self._jid_nick[actor];
640 local role = current_nick and self._occupants[current_nick].role or self:get_default_role(affiliation);
641 local item = stanza.tags[1].tags[1];
642 if item and item.name == "item" then
643 if type == "set" then
644 local callback = function() origin.send(st.reply(stanza)); end
645 if item.attr.jid then -- Validate provided JID
646 item.attr.jid = jid_prep(item.attr.jid);
647 if not item.attr.jid then
648 origin.send(st.error_reply(stanza, "modify", "jid-malformed"));
652 if not item.attr.jid and item.attr.nick then -- COMPAT Workaround for Miranda sending 'nick' instead of 'jid' when changing affiliation
653 local occupant = self._occupants[self.jid.."/"..item.attr.nick];
654 if occupant then item.attr.jid = occupant.jid; end
655 elseif not item.attr.nick and item.attr.jid then
656 local nick = self._jid_nick[item.attr.jid];
657 if nick then item.attr.nick = select(3, jid_split(nick)); end
659 local reason = item.tags[1] and item.tags[1].name == "reason" and #item.tags[1] == 1 and item.tags[1][1];
660 if item.attr.affiliation and item.attr.jid and not item.attr.role then
661 local success, errtype, err = self:set_affiliation(actor, item.attr.jid, item.attr.affiliation, callback, reason);
662 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
663 elseif item.attr.role and item.attr.nick and not item.attr.affiliation then
664 local success, errtype, err = self:set_role(actor, self.jid.."/"..item.attr.nick, item.attr.role, callback, reason);
665 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
667 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
669 elseif type == "get" then
670 local _aff = item.attr.affiliation;
671 local _rol = item.attr.role;
672 if _aff and not _rol then
673 if affiliation == "owner" or (affiliation == "admin" and _aff ~= "owner" and _aff ~= "admin") then
674 local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
675 for jid, affiliation in pairs(self._affiliations) do
676 if affiliation == _aff then
677 reply:tag("item", {affiliation = _aff, jid = jid}):up();
682 origin.send(st.error_reply(stanza, "auth", "forbidden"));
684 elseif _rol and not _aff then
685 if role == "moderator" then
686 -- TODO allow admins and owners not in room? Provide read-only access to everyone who can see the participants anyway?
687 if _rol == "none" then _rol = nil; end
688 local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
689 for occupant_jid, occupant in pairs(self._occupants) do
690 if occupant.role == _rol then
692 nick = select(3, jid_split(occupant_jid)),
693 role = _rol or "none",
694 affiliation = occupant.affiliation or "none",
701 origin.send(st.error_reply(stanza, "auth", "forbidden"));
704 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
707 elseif type == "set" or type == "get" then
708 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
710 elseif xmlns == "http://jabber.org/protocol/muc#owner" and (type == "get" or type == "set") and stanza.tags[1].name == "query" then
711 if self:get_affiliation(stanza.attr.from) ~= "owner" then
712 origin.send(st.error_reply(stanza, "auth", "forbidden"));
713 elseif stanza.attr.type == "get" then
714 self:send_form(origin, stanza);
715 elseif stanza.attr.type == "set" then
716 local child = stanza.tags[1].tags[1];
718 origin.send(st.error_reply(stanza, "auth", "bad-request"));
719 elseif child.name == "destroy" then
720 local newjid = child.attr.jid;
721 local reason, password;
722 for _,tag in ipairs(child.tags) do
723 if tag.name == "reason" then
724 reason = #tag.tags == 0 and tag[1];
725 elseif tag.name == "password" then
726 password = #tag.tags == 0 and tag[1];
729 self:destroy(newjid, reason, password);
730 origin.send(st.reply(stanza));
732 self:process_form(origin, stanza);
735 elseif type == "set" or type == "get" then
736 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
738 elseif stanza.name == "message" and type == "groupchat" then
739 local from, to = stanza.attr.from, stanza.attr.to;
740 local room = jid_bare(to);
741 local current_nick = self._jid_nick[from];
742 local occupant = self._occupants[current_nick];
743 if not occupant then -- not in room
744 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
745 elseif occupant.role == "visitor" then
746 origin.send(st.error_reply(stanza, "cancel", "forbidden"));
748 local from = stanza.attr.from;
749 stanza.attr.from = current_nick;
750 local subject = getText(stanza, {"subject"});
752 if occupant.role == "moderator" then
753 self:set_subject(current_nick, subject); -- TODO use broadcast_message_stanza
755 stanza.attr.from = from;
756 origin.send(st.error_reply(stanza, "cancel", "forbidden"));
759 self:broadcast_message(stanza, true);
761 stanza.attr.from = from;
763 elseif stanza.name == "message" and type == "error" and is_kickable_error(stanza) then
764 local current_nick = self._jid_nick[stanza.attr.from];
765 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
766 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza)); -- send unavailable
767 elseif stanza.name == "presence" then -- hack - some buggy clients send presence updates to the room rather than their nick
768 local to = stanza.attr.to;
769 local current_nick = self._jid_nick[stanza.attr.from];
771 stanza.attr.to = current_nick;
772 self:handle_to_occupant(origin, stanza);
774 elseif type ~= "error" and type ~= "result" then
775 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
777 elseif stanza.name == "message" and not stanza.attr.type and #stanza.tags == 1 and self._jid_nick[stanza.attr.from]
778 and stanza.tags[1].name == "x" and stanza.tags[1].attr.xmlns == "http://jabber.org/protocol/muc#user" then
779 local x = stanza.tags[1];
780 local payload = (#x.tags == 1 and x.tags[1]);
781 if payload and payload.name == "invite" and payload.attr.to then
782 local _from, _to = stanza.attr.from, stanza.attr.to;
783 local _invitee = jid_prep(payload.attr.to);
785 local _reason = payload.tags[1] and payload.tags[1].name == 'reason' and #payload.tags[1].tags == 0 and payload.tags[1][1];
786 local invite = st.message({from = _to, to = _invitee, id = stanza.attr.id})
787 :tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
788 :tag('invite', {from=_from})
789 :tag('reason'):text(_reason or ""):up()
791 if self:get_password() then
792 invite:tag("password"):text(self:get_password()):up();
795 :tag('x', {xmlns="jabber:x:conference", jid=_to}) -- COMPAT: Some older clients expect this
798 :tag('body') -- Add a plain message for clients which don't support invites
799 :text(_from..' invited you to the room '.._to..(_reason and (' ('.._reason..')') or ""))
801 self:_route_stanza(invite);
803 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
806 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
809 if type == "error" or type == "result" then return; end
810 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
814 function room_mt:handle_stanza(origin, stanza)
815 local to_node, to_host, to_resource = jid_split(stanza.attr.to);
817 self:handle_to_occupant(origin, stanza);
819 self:handle_to_room(origin, stanza);
823 function room_mt:route_stanza(stanza) end -- Replace with a routing function, e.g., function(room, stanza) core_route_stanza(origin, stanza); end
825 function room_mt:get_affiliation(jid)
826 local node, host, resource = jid_split(jid);
827 local bare = node and node.."@"..host or host;
828 local result = self._affiliations[bare]; -- Affiliations are granted, revoked, and maintained based on the user's bare JID.
829 if not result and self._affiliations[host] == "outcast" then result = "outcast"; end -- host banned
832 function room_mt:set_affiliation(actor, jid, affiliation, callback, reason)
834 if affiliation == "none" then affiliation = nil; end
835 if affiliation and affiliation ~= "outcast" and affiliation ~= "owner" and affiliation ~= "admin" and affiliation ~= "member" then
836 return nil, "modify", "not-acceptable";
838 if self:get_affiliation(actor) ~= "owner" then return nil, "cancel", "not-allowed"; end
839 if jid_bare(actor) == jid then return nil, "cancel", "not-allowed"; end
840 self._affiliations[jid] = affiliation;
841 local role = self:get_default_role(affiliation);
842 local p = st.presence()
843 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
844 :tag("item", {affiliation=affiliation or "none", role=role or "none"})
845 :tag("reason"):text(reason or ""):up()
848 local item = x.tags[1];
849 if not role then -- getting kicked
850 p.attr.type = "unavailable";
851 if affiliation == "outcast" then
852 x:tag("status", {code="301"}):up(); -- banned
854 x:tag("status", {code="321"}):up(); -- affiliation change
857 local modified_nicks = {};
858 for nick, occupant in pairs(self._occupants) do
859 if jid_bare(occupant.jid) == jid then
860 if not role then -- getting kicked
861 self._occupants[nick] = nil;
863 t_insert(modified_nicks, nick);
864 occupant.affiliation, occupant.role = affiliation, role;
867 for jid in pairs(occupant.sessions) do -- remove for all sessions of the nick
868 if not role then self._jid_nick[jid] = nil; end
870 self:_route_stanza(p);
874 if self.save then self:save(); end
875 if callback then callback(); end
876 for _, nick in ipairs(modified_nicks) do
878 self:broadcast_except_nick(p, nick);
883 function room_mt:get_role(nick)
884 local session = self._occupants[nick];
885 return session and session.role or nil;
887 function room_mt:can_set_role(actor_jid, occupant_jid, role)
888 local actor = self._occupants[self._jid_nick[actor_jid]];
889 local occupant = self._occupants[occupant_jid];
891 if not occupant or not actor then return nil, "modify", "not-acceptable"; end
893 if actor.role == "moderator" then
894 if occupant.affiliation ~= "owner" and occupant.affiliation ~= "admin" then
895 if actor.affiliation == "owner" or actor.affiliation == "admin" then
897 elseif occupant.role ~= "moderator" and role ~= "moderator" then
902 return nil, "cancel", "not-allowed";
904 function room_mt:set_role(actor, occupant_jid, role, callback, reason)
905 if role == "none" then role = nil; end
906 if role and role ~= "moderator" and role ~= "participant" and role ~= "visitor" then return nil, "modify", "not-acceptable"; end
907 local allowed, err_type, err_condition = self:can_set_role(actor, occupant_jid, role);
908 if not allowed then return allowed, err_type, err_condition; end
909 local occupant = self._occupants[occupant_jid];
910 local p = st.presence({from = occupant_jid})
911 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
912 :tag("item", {affiliation=occupant.affiliation or "none", nick=select(3, jid_split(occupant_jid)), role=role or "none"})
913 :tag("reason"):text(reason or ""):up()
915 if not role then -- kick
916 p.attr.type = "unavailable";
917 self._occupants[occupant_jid] = nil;
918 for jid in pairs(occupant.sessions) do -- remove for all sessions of the nick
919 self._jid_nick[jid] = nil;
921 p:tag("status", {code = "307"}):up();
923 occupant.role = role;
925 for jid in pairs(occupant.sessions) do -- send to all sessions of the nick
927 self:_route_stanza(p);
929 if callback then callback(); end
930 self:broadcast_except_nick(p, occupant_jid);
934 function room_mt:_route_stanza(stanza)
936 local to_occupant = self._occupants[self._jid_nick[stanza.attr.to]];
937 local from_occupant = self._occupants[stanza.attr.from];
938 if stanza.name == "presence" then
939 if to_occupant and from_occupant then
940 if self._data.whois == 'anyone' then
941 muc_child = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
943 if to_occupant.role == "moderator" or jid_bare(to_occupant.jid) == jid_bare(from_occupant.jid) then
944 muc_child = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
950 for _, item in pairs(muc_child.tags) do
951 if item.name == "item" then
952 if from_occupant == to_occupant then
953 item.attr.jid = stanza.attr.to;
955 item.attr.jid = from_occupant.jid;
959 if self._data.whois == 'anyone' then
960 muc_child:tag('status', { code = '100' });
963 self:route_stanza(stanza);
965 for _, item in pairs(muc_child.tags) do
966 if item.name == "item" then
973 local _M = {}; -- module "muc"
975 function _M.new_room(jid, config)
976 return setmetatable({
981 whois = 'moderators';
982 history_length = (config and config.history_length);