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._data['subject_from'] or 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 self._data['subject_from'] = current_nick;
237 if self.save then self:save(); end
238 local msg = st.message({type='groupchat', from=current_nick})
239 :tag('subject'):text(subject):up();
240 self:broadcast_message(msg, false);
244 local function build_unavailable_presence_from_error(stanza)
245 local type, condition, text = stanza:get_error();
246 local error_message = "Kicked: "..condition:gsub("%-", " ");
248 error_message = error_message..": "..text;
250 return st.presence({type='unavailable', from=stanza.attr.from, to=stanza.attr.to})
251 :tag('status'):text(error_message);
254 function room_mt:set_password(password)
255 if password == "" or type(password) ~= "string" then password = nil; end
256 if self._data.password ~= password then
257 self._data.password = password;
258 if self.save then self:save(true); end
261 function room_mt:get_password()
262 return self._data.password;
264 function room_mt:set_moderated(moderated)
265 moderated = moderated and true or nil;
266 if self._data.moderated ~= moderated then
267 self._data.moderated = moderated;
268 if self.save then self:save(true); end
271 function room_mt:is_moderated()
272 return self._data.moderated;
274 function room_mt:set_members_only(members_only)
275 members_only = members_only and true or nil;
276 if self._data.members_only ~= members_only then
277 self._data.members_only = members_only;
278 if self.save then self:save(true); end
281 function room_mt:is_members_only()
282 return self._data.members_only;
284 function room_mt:set_persistent(persistent)
285 persistent = persistent and true or nil;
286 if self._data.persistent ~= persistent then
287 self._data.persistent = persistent;
288 if self.save then self:save(true); end
291 function room_mt:is_persistent()
292 return self._data.persistent;
294 function room_mt:set_hidden(hidden)
295 hidden = hidden and true or nil;
296 if self._data.hidden ~= hidden then
297 self._data.hidden = hidden;
298 if self.save then self:save(true); end
301 function room_mt:is_hidden()
302 return self._data.hidden;
305 function room_mt:handle_to_occupant(origin, stanza) -- PM, vCards, etc
306 local from, to = stanza.attr.from, stanza.attr.to;
307 local room = jid_bare(to);
308 local current_nick = self._jid_nick[from];
309 local type = stanza.attr.type;
310 log("debug", "room: %s, current_nick: %s, stanza: %s", room or "nil", current_nick or "nil", stanza:top_tag());
311 if (select(2, jid_split(from)) == muc_domain) then error("Presence from the MUC itself!!!"); end
312 if stanza.name == "presence" then
313 local pr = get_filtered_presence(stanza);
314 pr.attr.from = current_nick;
315 if type == "error" then -- error, kick em out!
317 log("debug", "kicking %s from %s", current_nick, room);
318 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza));
320 elseif type == "unavailable" then -- unavailable
322 log("debug", "%s leaving %s", current_nick, room);
323 local occupant = self._occupants[current_nick];
324 local new_jid = next(occupant.sessions);
325 if new_jid == from then new_jid = next(occupant.sessions, new_jid); end
327 local jid = occupant.jid;
328 occupant.jid = new_jid;
329 occupant.sessions[from] = nil;
331 pr:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
332 :tag("item", {affiliation=occupant.affiliation or "none", role='none'}):up()
333 :tag("status", {code='110'});
334 self:_route_stanza(pr);
335 if jid ~= new_jid then
336 pr = st.clone(occupant.sessions[new_jid])
337 :tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
338 :tag("item", {affiliation=occupant.affiliation or "none", role=occupant.role or "none"});
339 pr.attr.from = current_nick;
340 self:broadcast_except_nick(pr, current_nick);
343 occupant.role = 'none';
344 self:broadcast_presence(pr, from);
345 self._occupants[current_nick] = nil;
347 self._jid_nick[from] = nil;
349 elseif not type then -- available
351 --if #pr == #stanza or current_nick ~= to then -- commented because google keeps resending directed presence
352 if current_nick == to then -- simple presence
353 log("debug", "%s broadcasted presence", current_nick);
354 self._occupants[current_nick].sessions[from] = pr;
355 self:broadcast_presence(pr, from);
357 local occupant = self._occupants[current_nick];
358 local is_multisession = next(occupant.sessions, next(occupant.sessions));
359 if self._occupants[to] or is_multisession then
360 log("debug", "%s couldn't change nick", current_nick);
361 local reply = st.error_reply(stanza, "cancel", "conflict"):up();
362 reply.tags[1].attr.code = "409";
363 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
365 local data = self._occupants[current_nick];
366 local to_nick = select(3, jid_split(to));
368 log("debug", "%s (%s) changing nick to %s", current_nick, data.jid, to);
369 local p = st.presence({type='unavailable', from=current_nick});
370 self:broadcast_presence(p, from, '303', to_nick);
371 self._occupants[current_nick] = nil;
372 self._occupants[to] = data;
373 self._jid_nick[from] = to;
375 self._occupants[to].sessions[from] = pr;
376 self:broadcast_presence(pr, from);
382 --else -- possible rejoin
383 -- log("debug", "%s had connection replaced", current_nick);
384 -- self:handle_to_occupant(origin, st.presence({type='unavailable', from=from, to=to})
385 -- :tag('status'):text('Replaced by new connection'):up()); -- send unavailable
386 -- self:handle_to_occupant(origin, stanza); -- resend available
391 if self._occupants[to] then
392 if jid_bare(from) ~= jid_bare(self._occupants[to].jid) then
397 local password = stanza:get_child("x", "http://jabber.org/protocol/muc");
398 password = password and password:get_child("password", "http://jabber.org/protocol/muc");
399 password = password and password[1] ~= "" and password[1];
400 if self:get_password() and self:get_password() ~= password then
401 log("debug", "%s couldn't join due to invalid password: %s", from, to);
402 local reply = st.error_reply(stanza, "auth", "not-authorized"):up();
403 reply.tags[1].attr.code = "401";
404 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
405 elseif not new_nick then
406 log("debug", "%s couldn't join due to nick conflict: %s", from, to);
407 local reply = st.error_reply(stanza, "cancel", "conflict"):up();
408 reply.tags[1].attr.code = "409";
409 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
411 log("debug", "%s joining as %s", from, to);
412 if not next(self._affiliations) then -- new room, no owners
413 self._affiliations[jid_bare(from)] = "owner";
415 local affiliation = self:get_affiliation(from);
416 local role = self:get_default_role(affiliation)
417 if role then -- new occupant
419 self._occupants[to] = {affiliation=affiliation, role=role, jid=from, sessions={[from]=get_filtered_presence(stanza)}};
421 self._occupants[to].sessions[from] = get_filtered_presence(stanza);
423 self._jid_nick[from] = to;
424 self:send_occupant_list(from);
427 self:broadcast_presence(pr, from);
430 self:_route_stanza(pr:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
431 :tag("item", {affiliation=affiliation or "none", role=role or "none"}):up()
432 :tag("status", {code='110'}));
434 self:send_history(from, stanza);
436 local reply = st.error_reply(stanza, "auth", "forbidden"):up();
437 reply.tags[1].attr.code = "403";
438 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
442 elseif type ~= 'result' then -- bad type
443 if type ~= 'visible' and type ~= 'invisible' then -- COMPAT ejabberd can broadcast or forward XEP-0018 presences
444 origin.send(st.error_reply(stanza, "modify", "bad-request")); -- FIXME correct error?
447 elseif not current_nick then -- not in room
448 if type == "error" or type == "result" then
449 local id = stanza.name == "iq" and stanza.attr.id and base64.decode(stanza.attr.id);
450 local _nick, _id, _hash = (id or ""):match("^(.+)%z(.*)%z(.+)$");
451 local occupant = self._occupants[stanza.attr.to];
452 if occupant and _nick and self._jid_nick[_nick] and _id and _hash then
453 local id, _to = stanza.attr.id;
454 for jid in pairs(occupant.sessions) do
455 if md5(jid) == _hash then
461 stanza.attr.to, stanza.attr.from, stanza.attr.id = _to, self._jid_nick[_nick], _id;
462 self:_route_stanza(stanza);
463 stanza.attr.to, stanza.attr.from, stanza.attr.id = to, from, id;
467 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
469 elseif stanza.name == "message" and type == "groupchat" then -- groupchat messages not allowed in PM
470 origin.send(st.error_reply(stanza, "modify", "bad-request"));
471 elseif current_nick and stanza.name == "message" and type == "error" and is_kickable_error(stanza) then
472 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
473 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza)); -- send unavailable
474 else -- private stanza
475 local o_data = self._occupants[to];
477 log("debug", "%s sent private stanza to %s (%s)", from, to, o_data.jid);
478 local jid = o_data.jid;
479 local bare = jid_bare(jid);
480 stanza.attr.to, stanza.attr.from = jid, current_nick;
481 local id = stanza.attr.id;
482 if stanza.name=='iq' and type=='get' and stanza.tags[1].attr.xmlns == 'vcard-temp' and bare ~= jid then
483 stanza.attr.to = bare;
484 stanza.attr.id = base64.encode(jid.."\0"..id.."\0"..md5(from));
486 self:_route_stanza(stanza);
487 stanza.attr.to, stanza.attr.from, stanza.attr.id = to, from, id;
488 elseif type ~= "error" and type ~= "result" then -- recipient not in room
489 origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
494 function room_mt:send_form(origin, stanza)
495 local title = "Configuration for "..self.jid;
496 origin.send(st.reply(stanza):query("http://jabber.org/protocol/muc#owner")
497 :tag("x", {xmlns='jabber:x:data', type='form'})
498 :tag("title"):text(title):up()
499 :tag("instructions"):text(title):up()
500 :tag("field", {type='hidden', var='FORM_TYPE'}):tag("value"):text("http://jabber.org/protocol/muc#roomconfig"):up():up()
501 :tag("field", {type='boolean', label='Make Room Persistent?', var='muc#roomconfig_persistentroom'})
502 :tag("value"):text(self:is_persistent() and "1" or "0"):up()
504 :tag("field", {type='boolean', label='Make Room Publicly Searchable?', var='muc#roomconfig_publicroom'})
505 :tag("value"):text(self:is_hidden() and "0" or "1"):up()
507 :tag("field", {type='list-single', label='Who May Discover Real JIDs?', var='muc#roomconfig_whois'})
508 :tag("value"):text(self._data.whois or 'moderators'):up()
509 :tag("option", {label = 'Moderators Only'})
510 :tag("value"):text('moderators'):up()
512 :tag("option", {label = 'Anyone'})
513 :tag("value"):text('anyone'):up()
516 :tag("field", {type='text-private', label='Password', var='muc#roomconfig_roomsecret'})
517 :tag("value"):text(self:get_password() or ""):up()
519 :tag("field", {type='boolean', label='Make Room Moderated?', var='muc#roomconfig_moderatedroom'})
520 :tag("value"):text(self:is_moderated() and "1" or "0"):up()
522 :tag("field", {type='boolean', label='Make Room Members-Only?', var='muc#roomconfig_membersonly'})
523 :tag("value"):text(self:is_members_only() and "1" or "0"):up()
528 local valid_whois = {
533 function room_mt:process_form(origin, stanza)
534 local query = stanza.tags[1];
536 for _, tag in ipairs(query.tags) do if tag.name == "x" and tag.attr.xmlns == "jabber:x:data" then form = tag; break; end end
537 if not form then origin.send(st.error_reply(stanza, "cancel", "service-unavailable")); return; end
538 if form.attr.type == "cancel" then origin.send(st.reply(stanza)); return; end
539 if form.attr.type ~= "submit" then origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
541 for _, field in pairs(form.tags) do
542 if field.name == "field" and field.attr.var and field.tags[1].name == "value" and #field.tags[1].tags == 0 then
543 fields[field.attr.var] = field.tags[1][1] or "";
546 if fields.FORM_TYPE ~= "http://jabber.org/protocol/muc#roomconfig" then origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
550 local persistent = fields['muc#roomconfig_persistentroom'];
551 if persistent == "0" or persistent == "false" then persistent = nil; elseif persistent == "1" or persistent == "true" then persistent = true;
552 else origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
553 dirty = dirty or (self:is_persistent() ~= persistent)
554 module:log("debug", "persistent=%s", tostring(persistent));
556 local moderated = fields['muc#roomconfig_moderatedroom'];
557 if moderated == "0" or moderated == "false" then moderated = nil; elseif moderated == "1" or moderated == "true" then moderated = true;
558 else origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
559 dirty = dirty or (self:is_moderated() ~= moderated)
560 module:log("debug", "moderated=%s", tostring(moderated));
562 local membersonly = fields['muc#roomconfig_membersonly'];
563 if membersonly == "0" or membersonly == "false" then membersonly = nil; elseif membersonly == "1" or membersonly == "true" then membersonly = true;
564 else origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
565 dirty = dirty or (self:is_members_only() ~= membersonly)
566 module:log("debug", "membersonly=%s", tostring(membersonly));
568 local public = fields['muc#roomconfig_publicroom'];
569 if public == "0" or public == "false" then public = nil; elseif public == "1" or public == "true" then public = true;
570 else origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
571 dirty = dirty or (self:is_hidden() ~= (not public and true or nil))
573 local whois = fields['muc#roomconfig_whois'];
574 if not valid_whois[whois] then
575 origin.send(st.error_reply(stanza, 'cancel', 'bad-request'));
578 local whois_changed = self._data.whois ~= whois
579 self._data.whois = whois
580 module:log('debug', 'whois=%s', whois)
582 local password = fields['muc#roomconfig_roomsecret'];
584 self:set_password(password);
586 self:set_moderated(moderated);
587 self:set_members_only(membersonly);
588 self:set_persistent(persistent);
589 self:set_hidden(not public);
591 if self.save then self:save(true); end
592 origin.send(st.reply(stanza));
594 if dirty or whois_changed then
595 local msg = st.message({type='groupchat', from=self.jid})
596 :tag('x', {xmlns='http://jabber.org/protocol/muc#user'}):up()
599 msg.tags[1]:tag('status', {code = '104'})
601 if whois_changed then
602 local code = (whois == 'moderators') and 173 or 172
603 msg.tags[1]:tag('status', {code = code})
606 self:broadcast_message(msg, false)
610 function room_mt:destroy(newjid, reason, password)
611 local pr = st.presence({type = "unavailable"})
612 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
613 :tag("item", { affiliation='none', role='none' }):up()
614 :tag("destroy", {jid=newjid})
615 if reason then pr:tag("reason"):text(reason):up(); end
616 if password then pr:tag("password"):text(password):up(); end
617 for nick, occupant in pairs(self._occupants) do
619 for jid in pairs(occupant.sessions) do
621 self:_route_stanza(pr);
622 self._jid_nick[jid] = nil;
624 self._occupants[nick] = nil;
626 self:set_persistent(false);
629 function room_mt:handle_to_room(origin, stanza) -- presence changes and groupchat messages, along with disco/etc
630 local type = stanza.attr.type;
631 local xmlns = stanza.tags[1] and stanza.tags[1].attr.xmlns;
632 if stanza.name == "iq" then
633 if xmlns == "http://jabber.org/protocol/disco#info" and type == "get" then
634 origin.send(self:get_disco_info(stanza));
635 elseif xmlns == "http://jabber.org/protocol/disco#items" and type == "get" then
636 origin.send(self:get_disco_items(stanza));
637 elseif xmlns == "http://jabber.org/protocol/muc#admin" then
638 local actor = stanza.attr.from;
639 local affiliation = self:get_affiliation(actor);
640 local current_nick = self._jid_nick[actor];
641 local role = current_nick and self._occupants[current_nick].role or self:get_default_role(affiliation);
642 local item = stanza.tags[1].tags[1];
643 if item and item.name == "item" then
644 if type == "set" then
645 local callback = function() origin.send(st.reply(stanza)); end
646 if item.attr.jid then -- Validate provided JID
647 item.attr.jid = jid_prep(item.attr.jid);
648 if not item.attr.jid then
649 origin.send(st.error_reply(stanza, "modify", "jid-malformed"));
653 if not item.attr.jid and item.attr.nick then -- COMPAT Workaround for Miranda sending 'nick' instead of 'jid' when changing affiliation
654 local occupant = self._occupants[self.jid.."/"..item.attr.nick];
655 if occupant then item.attr.jid = occupant.jid; end
656 elseif not item.attr.nick and item.attr.jid then
657 local nick = self._jid_nick[item.attr.jid];
658 if nick then item.attr.nick = select(3, jid_split(nick)); end
660 local reason = item.tags[1] and item.tags[1].name == "reason" and #item.tags[1] == 1 and item.tags[1][1];
661 if item.attr.affiliation and item.attr.jid and not item.attr.role then
662 local success, errtype, err = self:set_affiliation(actor, item.attr.jid, item.attr.affiliation, callback, reason);
663 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
664 elseif item.attr.role and item.attr.nick and not item.attr.affiliation then
665 local success, errtype, err = self:set_role(actor, self.jid.."/"..item.attr.nick, item.attr.role, callback, reason);
666 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
668 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
670 elseif type == "get" then
671 local _aff = item.attr.affiliation;
672 local _rol = item.attr.role;
673 if _aff and not _rol then
674 if affiliation == "owner" or (affiliation == "admin" and _aff ~= "owner" and _aff ~= "admin") then
675 local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
676 for jid, affiliation in pairs(self._affiliations) do
677 if affiliation == _aff then
678 reply:tag("item", {affiliation = _aff, jid = jid}):up();
683 origin.send(st.error_reply(stanza, "auth", "forbidden"));
685 elseif _rol and not _aff then
686 if role == "moderator" then
687 -- TODO allow admins and owners not in room? Provide read-only access to everyone who can see the participants anyway?
688 if _rol == "none" then _rol = nil; end
689 local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
690 for occupant_jid, occupant in pairs(self._occupants) do
691 if occupant.role == _rol then
693 nick = select(3, jid_split(occupant_jid)),
694 role = _rol or "none",
695 affiliation = occupant.affiliation or "none",
702 origin.send(st.error_reply(stanza, "auth", "forbidden"));
705 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
708 elseif type == "set" or type == "get" then
709 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
711 elseif xmlns == "http://jabber.org/protocol/muc#owner" and (type == "get" or type == "set") and stanza.tags[1].name == "query" then
712 if self:get_affiliation(stanza.attr.from) ~= "owner" then
713 origin.send(st.error_reply(stanza, "auth", "forbidden"));
714 elseif stanza.attr.type == "get" then
715 self:send_form(origin, stanza);
716 elseif stanza.attr.type == "set" then
717 local child = stanza.tags[1].tags[1];
719 origin.send(st.error_reply(stanza, "auth", "bad-request"));
720 elseif child.name == "destroy" then
721 local newjid = child.attr.jid;
722 local reason, password;
723 for _,tag in ipairs(child.tags) do
724 if tag.name == "reason" then
725 reason = #tag.tags == 0 and tag[1];
726 elseif tag.name == "password" then
727 password = #tag.tags == 0 and tag[1];
730 self:destroy(newjid, reason, password);
731 origin.send(st.reply(stanza));
733 self:process_form(origin, stanza);
736 elseif type == "set" or type == "get" then
737 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
739 elseif stanza.name == "message" and type == "groupchat" then
740 local from, to = stanza.attr.from, stanza.attr.to;
741 local room = jid_bare(to);
742 local current_nick = self._jid_nick[from];
743 local occupant = self._occupants[current_nick];
744 if not occupant then -- not in room
745 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
746 elseif occupant.role == "visitor" then
747 origin.send(st.error_reply(stanza, "cancel", "forbidden"));
749 local from = stanza.attr.from;
750 stanza.attr.from = current_nick;
751 local subject = getText(stanza, {"subject"});
753 if occupant.role == "moderator" then
754 self:set_subject(current_nick, subject); -- TODO use broadcast_message_stanza
756 stanza.attr.from = from;
757 origin.send(st.error_reply(stanza, "cancel", "forbidden"));
760 self:broadcast_message(stanza, true);
762 stanza.attr.from = from;
764 elseif stanza.name == "message" and type == "error" and is_kickable_error(stanza) then
765 local current_nick = self._jid_nick[stanza.attr.from];
766 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
767 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza)); -- send unavailable
768 elseif stanza.name == "presence" then -- hack - some buggy clients send presence updates to the room rather than their nick
769 local to = stanza.attr.to;
770 local current_nick = self._jid_nick[stanza.attr.from];
772 stanza.attr.to = current_nick;
773 self:handle_to_occupant(origin, stanza);
775 elseif type ~= "error" and type ~= "result" then
776 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
778 elseif stanza.name == "message" and not stanza.attr.type and #stanza.tags == 1 and self._jid_nick[stanza.attr.from]
779 and stanza.tags[1].name == "x" and stanza.tags[1].attr.xmlns == "http://jabber.org/protocol/muc#user" then
780 local x = stanza.tags[1];
781 local payload = (#x.tags == 1 and x.tags[1]);
782 if payload and payload.name == "invite" and payload.attr.to then
783 local _from, _to = stanza.attr.from, stanza.attr.to;
784 local _invitee = jid_prep(payload.attr.to);
786 local _reason = payload.tags[1] and payload.tags[1].name == 'reason' and #payload.tags[1].tags == 0 and payload.tags[1][1];
787 local invite = st.message({from = _to, to = _invitee, id = stanza.attr.id})
788 :tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
789 :tag('invite', {from=_from})
790 :tag('reason'):text(_reason or ""):up()
792 if self:get_password() then
793 invite:tag("password"):text(self:get_password()):up();
796 :tag('x', {xmlns="jabber:x:conference", jid=_to}) -- COMPAT: Some older clients expect this
799 :tag('body') -- Add a plain message for clients which don't support invites
800 :text(_from..' invited you to the room '.._to..(_reason and (' ('.._reason..')') or ""))
802 self:_route_stanza(invite);
804 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
807 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
810 if type == "error" or type == "result" then return; end
811 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
815 function room_mt:handle_stanza(origin, stanza)
816 local to_node, to_host, to_resource = jid_split(stanza.attr.to);
818 self:handle_to_occupant(origin, stanza);
820 self:handle_to_room(origin, stanza);
824 function room_mt:route_stanza(stanza) end -- Replace with a routing function, e.g., function(room, stanza) core_route_stanza(origin, stanza); end
826 function room_mt:get_affiliation(jid)
827 local node, host, resource = jid_split(jid);
828 local bare = node and node.."@"..host or host;
829 local result = self._affiliations[bare]; -- Affiliations are granted, revoked, and maintained based on the user's bare JID.
830 if not result and self._affiliations[host] == "outcast" then result = "outcast"; end -- host banned
833 function room_mt:set_affiliation(actor, jid, affiliation, callback, reason)
835 if affiliation == "none" then affiliation = nil; end
836 if affiliation and affiliation ~= "outcast" and affiliation ~= "owner" and affiliation ~= "admin" and affiliation ~= "member" then
837 return nil, "modify", "not-acceptable";
839 if self:get_affiliation(actor) ~= "owner" then return nil, "cancel", "not-allowed"; end
840 if jid_bare(actor) == jid then return nil, "cancel", "not-allowed"; end
841 self._affiliations[jid] = affiliation;
842 local role = self:get_default_role(affiliation);
843 local p = st.presence()
844 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
845 :tag("item", {affiliation=affiliation or "none", role=role or "none"})
846 :tag("reason"):text(reason or ""):up()
849 local item = x.tags[1];
850 if not role then -- getting kicked
851 p.attr.type = "unavailable";
852 if affiliation == "outcast" then
853 x:tag("status", {code="301"}):up(); -- banned
855 x:tag("status", {code="321"}):up(); -- affiliation change
858 local modified_nicks = {};
859 for nick, occupant in pairs(self._occupants) do
860 if jid_bare(occupant.jid) == jid then
861 if not role then -- getting kicked
862 self._occupants[nick] = nil;
864 t_insert(modified_nicks, nick);
865 occupant.affiliation, occupant.role = affiliation, role;
868 for jid in pairs(occupant.sessions) do -- remove for all sessions of the nick
869 if not role then self._jid_nick[jid] = nil; end
871 self:_route_stanza(p);
875 if self.save then self:save(); end
876 if callback then callback(); end
877 for _, nick in ipairs(modified_nicks) do
879 self:broadcast_except_nick(p, nick);
884 function room_mt:get_role(nick)
885 local session = self._occupants[nick];
886 return session and session.role or nil;
888 function room_mt:can_set_role(actor_jid, occupant_jid, role)
889 local actor = self._occupants[self._jid_nick[actor_jid]];
890 local occupant = self._occupants[occupant_jid];
892 if not occupant or not actor then return nil, "modify", "not-acceptable"; end
894 if actor.role == "moderator" then
895 if occupant.affiliation ~= "owner" and occupant.affiliation ~= "admin" then
896 if actor.affiliation == "owner" or actor.affiliation == "admin" then
898 elseif occupant.role ~= "moderator" and role ~= "moderator" then
903 return nil, "cancel", "not-allowed";
905 function room_mt:set_role(actor, occupant_jid, role, callback, reason)
906 if role == "none" then role = nil; end
907 if role and role ~= "moderator" and role ~= "participant" and role ~= "visitor" then return nil, "modify", "not-acceptable"; end
908 local allowed, err_type, err_condition = self:can_set_role(actor, occupant_jid, role);
909 if not allowed then return allowed, err_type, err_condition; end
910 local occupant = self._occupants[occupant_jid];
911 local p = st.presence({from = occupant_jid})
912 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
913 :tag("item", {affiliation=occupant.affiliation or "none", nick=select(3, jid_split(occupant_jid)), role=role or "none"})
914 :tag("reason"):text(reason or ""):up()
916 if not role then -- kick
917 p.attr.type = "unavailable";
918 self._occupants[occupant_jid] = nil;
919 for jid in pairs(occupant.sessions) do -- remove for all sessions of the nick
920 self._jid_nick[jid] = nil;
922 p:tag("status", {code = "307"}):up();
924 occupant.role = role;
926 for jid in pairs(occupant.sessions) do -- send to all sessions of the nick
928 self:_route_stanza(p);
930 if callback then callback(); end
931 self:broadcast_except_nick(p, occupant_jid);
935 function room_mt:_route_stanza(stanza)
937 local to_occupant = self._occupants[self._jid_nick[stanza.attr.to]];
938 local from_occupant = self._occupants[stanza.attr.from];
939 if stanza.name == "presence" then
940 if to_occupant and from_occupant then
941 if self._data.whois == 'anyone' then
942 muc_child = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
944 if to_occupant.role == "moderator" or jid_bare(to_occupant.jid) == jid_bare(from_occupant.jid) then
945 muc_child = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
951 for _, item in pairs(muc_child.tags) do
952 if item.name == "item" then
953 if from_occupant == to_occupant then
954 item.attr.jid = stanza.attr.to;
956 item.attr.jid = from_occupant.jid;
960 if self._data.whois == 'anyone' then
961 muc_child:tag('status', { code = '100' });
964 self:route_stanza(stanza);
966 for _, item in pairs(muc_child.tags) do
967 if item.name == "item" then
974 local _M = {}; -- module "muc"
976 function _M.new_room(jid, config)
977 return setmetatable({
982 whois = 'moderators';
983 history_length = (config and config.history_length);