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.
9 local datamanager = require "util.datamanager";
10 local datetime = require "util.datetime";
12 local jid_split = require "util.jid".split;
13 local jid_bare = require "util.jid".bare;
14 local jid_prep = require "util.jid".prep;
15 local st = require "util.stanza";
16 local log = require "util.logger".init("mod_muc");
17 local multitable_new = require "util.multitable".new;
18 local t_insert, t_remove = table.insert, table.remove;
19 local setmetatable = setmetatable;
20 local base64 = require "util.encodings".base64;
21 local md5 = require "util.hashes".md5;
23 local muc_domain = nil; --module:get_host();
24 local history_length = 20;
27 local function filter_xmlns_from_array(array, filters)
30 local attr = array[i].attr;
31 if filters[attr and attr.xmlns] then
38 local function filter_xmlns_from_stanza(stanza, filters)
40 if filter_xmlns_from_array(stanza.tags, filters) ~= 0 then
41 return stanza, filter_xmlns_from_array(stanza, filters);
46 local presence_filters = {["http://jabber.org/protocol/muc"]=true;["http://jabber.org/protocol/muc#user"]=true};
47 local function get_filtered_presence(stanza)
48 return filter_xmlns_from_stanza(st.clone(stanza):reset(), presence_filters);
50 local kickable_error_conditions = {
52 ["internal-server-error"] = true;
53 ["item-not-found"] = true;
54 ["jid-malformed"] = true;
55 ["recipient-unavailable"] = true;
57 ["remote-server-not-found"] = true;
58 ["remote-server-timeout"] = true;
59 ["service-unavailable"] = true;
60 ["malformed error"] = true;
63 local function get_error_condition(stanza)
64 local _, condition = stanza:get_error();
65 return condition or "malformed error";
68 local function is_kickable_error(stanza)
69 local cond = get_error_condition(stanza);
70 return kickable_error_conditions[cond] and cond;
72 local function getUsingPath(stanza, path, getText)
74 for _, name in ipairs(path) do
75 if type(tag) ~= 'table' then return; end
76 tag = tag:child_with_name(name);
78 if tag and getText then tag = table.concat(tag); end
81 local function getTag(stanza, path) return getUsingPath(stanza, path); end
82 local function getText(stanza, path) return getUsingPath(stanza, path, true); end
86 room_mt.__index = room_mt;
88 function room_mt:get_default_role(affiliation)
89 if affiliation == "owner" or affiliation == "admin" then
91 elseif affiliation == "member" then
93 elseif not affiliation then
94 if not self:is_members_only() then
95 return self:is_moderated() and "visitor" or "participant";
100 function room_mt:broadcast_presence(stanza, sid, code, nick)
101 stanza = get_filtered_presence(stanza);
102 local occupant = self._occupants[stanza.attr.from];
103 stanza:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
104 :tag("item", {affiliation=occupant.affiliation or "none", role=occupant.role or "none", nick=nick}):up();
106 stanza:tag("status", {code=code}):up();
108 self:broadcast_except_nick(stanza, stanza.attr.from);
109 local me = self._occupants[stanza.attr.from];
111 stanza:tag("status", {code='110'});
112 stanza.attr.to = sid;
113 self:_route_stanza(stanza);
116 function room_mt:broadcast_message(stanza, historic)
117 local to = stanza.attr.to;
118 for occupant, o_data in pairs(self._occupants) do
119 for jid in pairs(o_data.sessions) do
120 stanza.attr.to = jid;
121 self:_route_stanza(stanza);
125 if historic then -- add to history
126 local history = self._data['history'];
127 if not history then history = {}; self._data['history'] = history; end
128 stanza = st.clone(stanza);
130 local stamp = datetime.datetime();
131 local chars = #tostring(stanza);
132 stanza:tag("delay", {xmlns = "urn:xmpp:delay", from = muc_domain, stamp = stamp}):up(); -- XEP-0203
133 stanza:tag("x", {xmlns = "jabber:x:delay", from = muc_domain, stamp = datetime.legacy()}):up(); -- XEP-0091 (deprecated)
134 local entry = { stanza = stanza, stamp = stamp };
135 t_insert(history, entry);
136 while #history > history_length do t_remove(history, 1) end
139 function room_mt:broadcast_except_nick(stanza, nick)
140 for rnick, occupant in pairs(self._occupants) do
141 if rnick ~= nick then
142 for jid in pairs(occupant.sessions) do
143 stanza.attr.to = jid;
144 self:_route_stanza(stanza);
150 function room_mt:send_occupant_list(to)
151 local current_nick = self._jid_nick[to];
152 for occupant, o_data in pairs(self._occupants) do
153 if occupant ~= current_nick then
154 local pres = get_filtered_presence(o_data.sessions[o_data.jid]);
155 pres.attr.to, pres.attr.from = to, occupant;
156 pres:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
157 :tag("item", {affiliation=o_data.affiliation or "none", role=o_data.role or "none"}):up();
158 self:_route_stanza(pres);
162 function room_mt:send_history(to, stanza)
163 local history = self._data['history']; -- send discussion history
165 local x_tag = stanza and stanza:get_child("x", "http://jabber.org/protocol/muc");
166 local history_tag = x_tag and x_tag:get_child("history", "http://jabber.org/protocol/muc");
168 local maxchars = history_tag and tonumber(history_tag.attr.maxchars);
169 if maxchars then maxchars = math.floor(maxchars); end
171 local maxstanzas = math.floor(history_tag and tonumber(history_tag.attr.maxstanzas) or #history);
172 if not history_tag then maxstanzas = 20; end
174 local seconds = history_tag and tonumber(history_tag.attr.seconds);
175 if seconds then seconds = datetime.datetime(os.time() - math.floor(seconds)); end
177 local since = history_tag and history_tag.attr.since;
178 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
179 if seconds and (not since or since < seconds) then since = seconds; end
183 local stanzacount = 0;
185 for i=#history,1,-1 do
186 local entry = history[i];
188 if not entry.chars then
189 entry.stanza.attr.to = "";
190 entry.chars = #tostring(entry.stanza);
192 charcount = charcount + entry.chars + #to;
193 if charcount > maxchars then break; end
195 if since and since > entry.stamp then break; end
196 if n + 1 > maxstanzas then break; end
199 for i=#history-n+1,#history do
200 local msg = history[i].stanza;
202 self:_route_stanza(msg);
205 if self._data['subject'] then
206 self:_route_stanza(st.message({type='groupchat', from=self.jid, to=to}):tag("subject"):text(self._data['subject']));
210 function room_mt:get_disco_info(stanza)
211 return st.reply(stanza):query("http://jabber.org/protocol/disco#info")
212 :tag("identity", {category="conference", type="text"}):up()
213 :tag("feature", {var="http://jabber.org/protocol/muc"}):up()
214 :tag("feature", {var=self:get_password() and "muc_passwordprotected" or "muc_unsecured"}):up()
215 :tag("feature", {var=self:is_moderated() and "muc_moderated" or "muc_unmoderated"}):up()
216 :tag("feature", {var=self:is_members_only() and "muc_membersonly" or "muc_open"}):up()
219 function room_mt:get_disco_items(stanza)
220 local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#items");
221 for room_jid in pairs(self._occupants) do
222 reply:tag("item", {jid = room_jid, name = room_jid:match("/(.*)")}):up();
226 function room_mt:set_subject(current_nick, subject)
227 -- TODO check nick's authority
228 if subject == "" then subject = nil; end
229 self._data['subject'] = subject;
230 if self.save then self:save(); end
231 local msg = st.message({type='groupchat', from=current_nick})
232 :tag('subject'):text(subject):up();
233 self:broadcast_message(msg, false);
237 local function build_unavailable_presence_from_error(stanza)
238 local type, condition, text = stanza:get_error();
239 local error_message = "Kicked: "..condition:gsub("%-", " ");
241 error_message = error_message..": "..text;
243 return st.presence({type='unavailable', from=stanza.attr.from, to=stanza.attr.to})
244 :tag('status'):text(error_message);
247 function room_mt:set_password(password)
248 if password == "" or type(password) ~= "string" then password = nil; end
249 if self._data.password ~= password then
250 self._data.password = password;
251 if self.save then self:save(true); end
254 function room_mt:get_password()
255 return self._data.password;
257 function room_mt:set_moderated(moderated)
258 moderated = moderated and true or nil;
259 if self._data.moderated ~= moderated then
260 self._data.moderated = moderated;
261 if self.save then self:save(true); end
264 function room_mt:is_moderated()
265 return self._data.moderated;
267 function room_mt:set_members_only(members_only)
268 members_only = members_only and true or nil;
269 if self._data.members_only ~= members_only then
270 self._data.members_only = members_only;
271 if self.save then self:save(true); end
274 function room_mt:is_members_only()
275 return self._data.members_only;
278 function room_mt:handle_to_occupant(origin, stanza) -- PM, vCards, etc
279 local from, to = stanza.attr.from, stanza.attr.to;
280 local room = jid_bare(to);
281 local current_nick = self._jid_nick[from];
282 local type = stanza.attr.type;
283 log("debug", "room: %s, current_nick: %s, stanza: %s", room or "nil", current_nick or "nil", stanza:top_tag());
284 if (select(2, jid_split(from)) == muc_domain) then error("Presence from the MUC itself!!!"); end
285 if stanza.name == "presence" then
286 local pr = get_filtered_presence(stanza);
287 pr.attr.from = current_nick;
288 if type == "error" then -- error, kick em out!
290 log("debug", "kicking %s from %s", current_nick, room);
291 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza));
293 elseif type == "unavailable" then -- unavailable
295 log("debug", "%s leaving %s", current_nick, room);
296 local occupant = self._occupants[current_nick];
297 local new_jid = next(occupant.sessions);
298 if new_jid == from then new_jid = next(occupant.sessions, new_jid); end
300 local jid = occupant.jid;
301 occupant.jid = new_jid;
302 occupant.sessions[from] = nil;
304 pr:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
305 :tag("item", {affiliation=occupant.affiliation or "none", role='none'}):up()
306 :tag("status", {code='110'});
307 self:_route_stanza(pr);
308 if jid ~= new_jid then
309 pr = st.clone(occupant.sessions[new_jid])
310 :tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
311 :tag("item", {affiliation=occupant.affiliation or "none", role=occupant.role or "none"});
312 pr.attr.from = current_nick;
313 self:broadcast_except_nick(pr, current_nick);
316 occupant.role = 'none';
317 self:broadcast_presence(pr, from);
318 self._occupants[current_nick] = nil;
320 self._jid_nick[from] = nil;
322 elseif not type then -- available
324 --if #pr == #stanza or current_nick ~= to then -- commented because google keeps resending directed presence
325 if current_nick == to then -- simple presence
326 log("debug", "%s broadcasted presence", current_nick);
327 self._occupants[current_nick].sessions[from] = pr;
328 self:broadcast_presence(pr, from);
330 local occupant = self._occupants[current_nick];
331 local is_multisession = next(occupant.sessions, next(occupant.sessions));
332 if self._occupants[to] or is_multisession then
333 log("debug", "%s couldn't change nick", current_nick);
334 local reply = st.error_reply(stanza, "cancel", "conflict"):up();
335 reply.tags[1].attr.code = "409";
336 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
338 local data = self._occupants[current_nick];
339 local to_nick = select(3, jid_split(to));
341 log("debug", "%s (%s) changing nick to %s", current_nick, data.jid, to);
342 local p = st.presence({type='unavailable', from=current_nick});
343 self:broadcast_presence(p, from, '303', to_nick);
344 self._occupants[current_nick] = nil;
345 self._occupants[to] = data;
346 self._jid_nick[from] = to;
348 self._occupants[to].sessions[from] = pr;
349 self:broadcast_presence(pr, from);
355 --else -- possible rejoin
356 -- log("debug", "%s had connection replaced", current_nick);
357 -- self:handle_to_occupant(origin, st.presence({type='unavailable', from=from, to=to})
358 -- :tag('status'):text('Replaced by new connection'):up()); -- send unavailable
359 -- self:handle_to_occupant(origin, stanza); -- resend available
364 if self._occupants[to] then
365 if jid_bare(from) ~= jid_bare(self._occupants[to].jid) then
370 local password = stanza:get_child("x", "http://jabber.org/protocol/muc");
371 password = password and password:get_child("password", "http://jabber.org/protocol/muc");
372 password = password and password[1] ~= "" and password[1];
373 if self:get_password() and self:get_password() ~= password then
374 log("debug", "%s couldn't join due to invalid password: %s", from, to);
375 local reply = st.error_reply(stanza, "auth", "not-authorized"):up();
376 reply.tags[1].attr.code = "401";
377 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
378 elseif not new_nick then
379 log("debug", "%s couldn't join due to nick conflict: %s", from, to);
380 local reply = st.error_reply(stanza, "cancel", "conflict"):up();
381 reply.tags[1].attr.code = "409";
382 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
384 log("debug", "%s joining as %s", from, to);
385 if not next(self._affiliations) then -- new room, no owners
386 self._affiliations[jid_bare(from)] = "owner";
388 local affiliation = self:get_affiliation(from);
389 local role = self:get_default_role(affiliation)
390 if role then -- new occupant
392 self._occupants[to] = {affiliation=affiliation, role=role, jid=from, sessions={[from]=get_filtered_presence(stanza)}};
394 self._occupants[to].sessions[from] = get_filtered_presence(stanza);
396 self._jid_nick[from] = to;
397 self:send_occupant_list(from);
400 self:broadcast_presence(pr, from);
403 self:_route_stanza(pr:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
404 :tag("item", {affiliation=affiliation or "none", role=role or "none"}):up()
405 :tag("status", {code='110'}));
407 self:send_history(from, stanza);
409 local reply = st.error_reply(stanza, "auth", "forbidden"):up();
410 reply.tags[1].attr.code = "403";
411 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
415 elseif type ~= 'result' then -- bad type
416 if type ~= 'visible' and type ~= 'invisible' then -- COMPAT ejabberd can broadcast or forward XEP-0018 presences
417 origin.send(st.error_reply(stanza, "modify", "bad-request")); -- FIXME correct error?
420 elseif not current_nick then -- not in room
421 if type == "error" or type == "result" then
422 local id = stanza.name == "iq" and stanza.attr.id and base64.decode(stanza.attr.id);
423 local _nick, _id, _hash = (id or ""):match("^(.+)%z(.*)%z(.+)$");
424 local occupant = self._occupants[stanza.attr.to];
425 if occupant and _nick and self._jid_nick[_nick] and _id and _hash then
426 local id, _to = stanza.attr.id;
427 for jid in pairs(occupant.sessions) do
428 if md5(jid) == _hash then
434 stanza.attr.to, stanza.attr.from, stanza.attr.id = _to, self._jid_nick[_nick], _id;
435 self:_route_stanza(stanza);
436 stanza.attr.to, stanza.attr.from, stanza.attr.id = to, from, id;
440 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
442 elseif stanza.name == "message" and type == "groupchat" then -- groupchat messages not allowed in PM
443 origin.send(st.error_reply(stanza, "modify", "bad-request"));
444 elseif current_nick and stanza.name == "message" and type == "error" and is_kickable_error(stanza) then
445 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
446 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza)); -- send unavailable
447 else -- private stanza
448 local o_data = self._occupants[to];
450 log("debug", "%s sent private stanza to %s (%s)", from, to, o_data.jid);
451 local jid = o_data.jid;
452 local bare = jid_bare(jid);
453 stanza.attr.to, stanza.attr.from = jid, current_nick;
454 local id = stanza.attr.id;
455 if stanza.name=='iq' and type=='get' and stanza.tags[1].attr.xmlns == 'vcard-temp' and bare ~= jid then
456 stanza.attr.to = bare;
457 stanza.attr.id = base64.encode(jid.."\0"..id.."\0"..md5(from));
459 self:_route_stanza(stanza);
460 stanza.attr.to, stanza.attr.from, stanza.attr.id = to, from, id;
461 elseif type ~= "error" and type ~= "result" then -- recipient not in room
462 origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
467 function room_mt:send_form(origin, stanza)
468 local title = "Configuration for "..self.jid;
469 origin.send(st.reply(stanza):query("http://jabber.org/protocol/muc#owner")
470 :tag("x", {xmlns='jabber:x:data', type='form'})
471 :tag("title"):text(title):up()
472 :tag("instructions"):text(title):up()
473 :tag("field", {type='hidden', var='FORM_TYPE'}):tag("value"):text("http://jabber.org/protocol/muc#roomconfig"):up():up()
474 :tag("field", {type='boolean', label='Make Room Persistent?', var='muc#roomconfig_persistentroom'})
475 :tag("value"):text(self._data.persistent and "1" or "0"):up()
477 :tag("field", {type='boolean', label='Make Room Publicly Searchable?', var='muc#roomconfig_publicroom'})
478 :tag("value"):text(self._data.hidden and "0" or "1"):up()
480 :tag("field", {type='list-single', label='Who May Discover Real JIDs?', var='muc#roomconfig_whois'})
481 :tag("value"):text(self._data.whois or 'moderators'):up()
482 :tag("option", {label = 'Moderators Only'})
483 :tag("value"):text('moderators'):up()
485 :tag("option", {label = 'Anyone'})
486 :tag("value"):text('anyone'):up()
489 :tag("field", {type='text-private', label='Password', var='muc#roomconfig_roomsecret'})
490 :tag("value"):text(self:get_password() or ""):up()
492 :tag("field", {type='boolean', label='Make Room Moderated?', var='muc#roomconfig_moderatedroom'})
493 :tag("value"):text(self:is_moderated() and "1" or "0"):up()
495 :tag("field", {type='boolean', label='Make Room Members-Only?', var='muc#roomconfig_membersonly'})
496 :tag("value"):text(self:is_members_only() and "1" or "0"):up()
501 local valid_whois = {
506 function room_mt:process_form(origin, stanza)
507 local query = stanza.tags[1];
509 for _, tag in ipairs(query.tags) do if tag.name == "x" and tag.attr.xmlns == "jabber:x:data" then form = tag; break; end end
510 if not form then origin.send(st.error_reply(stanza, "cancel", "service-unavailable")); return; end
511 if form.attr.type == "cancel" then origin.send(st.reply(stanza)); return; end
512 if form.attr.type ~= "submit" then origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
514 for _, field in pairs(form.tags) do
515 if field.name == "field" and field.attr.var and field.tags[1].name == "value" and #field.tags[1].tags == 0 then
516 fields[field.attr.var] = field.tags[1][1] or "";
519 if fields.FORM_TYPE ~= "http://jabber.org/protocol/muc#roomconfig" then origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
523 local persistent = fields['muc#roomconfig_persistentroom'];
524 if persistent == "0" or persistent == "false" then persistent = nil; elseif persistent == "1" or persistent == "true" then persistent = true;
525 else origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
526 dirty = dirty or (self._data.persistent ~= persistent)
527 self._data.persistent = persistent;
528 module:log("debug", "persistent=%s", tostring(persistent));
530 local moderated = fields['muc#roomconfig_moderatedroom'];
531 if moderated == "0" or moderated == "false" then moderated = nil; elseif moderated == "1" or moderated == "true" then moderated = true;
532 else origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
533 dirty = dirty or (self:is_moderated() ~= moderated)
534 module:log("debug", "moderated=%s", tostring(moderated));
536 local membersonly = fields['muc#roomconfig_membersonly'];
537 if membersonly == "0" or membersonly == "false" then membersonly = nil; elseif membersonly == "1" or membersonly == "true" then membersonly = true;
538 else origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
539 dirty = dirty or (self:is_members_only() ~= membersonly)
540 module:log("debug", "membersonly=%s", tostring(membersonly));
542 local public = fields['muc#roomconfig_publicroom'];
543 if public == "0" or public == "false" then public = nil; elseif public == "1" or public == "true" then public = true;
544 else origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
545 dirty = dirty or (self._data.hidden ~= (not public and true or nil))
546 self._data.hidden = not public and true or nil;
548 local whois = fields['muc#roomconfig_whois'];
549 if not valid_whois[whois] then
550 origin.send(st.error_reply(stanza, 'cancel', 'bad-request'));
553 local whois_changed = self._data.whois ~= whois
554 self._data.whois = whois
555 module:log('debug', 'whois=%s', tostring(whois))
557 local password = fields['muc#roomconfig_roomsecret'];
559 self:set_password(password);
561 self:set_moderated(moderated);
562 self:set_members_only(membersonly);
564 if self.save then self:save(true); end
565 origin.send(st.reply(stanza));
567 if dirty or whois_changed then
568 local msg = st.message({type='groupchat', from=self.jid})
569 :tag('x', {xmlns='http://jabber.org/protocol/muc#user'}):up()
572 msg.tags[1]:tag('status', {code = '104'})
574 if whois_changed then
575 local code = (whois == 'moderators') and 173 or 172
576 msg.tags[1]:tag('status', {code = code})
579 self:broadcast_message(msg, false)
583 function room_mt:destroy(newjid, reason, password)
584 local pr = st.presence({type = "unavailable"})
585 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
586 :tag("item", { affiliation='none', role='none' }):up()
587 :tag("destroy", {jid=newjid})
588 if reason then pr:tag("reason"):text(reason):up(); end
589 if password then pr:tag("password"):text(password):up(); end
590 for nick, occupant in pairs(self._occupants) do
592 for jid in pairs(occupant.sessions) do
594 self:_route_stanza(pr);
595 self._jid_nick[jid] = nil;
597 self._occupants[nick] = nil;
599 self._data.persistent = nil;
600 if self.save then self:save(true); end
603 function room_mt:handle_to_room(origin, stanza) -- presence changes and groupchat messages, along with disco/etc
604 local type = stanza.attr.type;
605 local xmlns = stanza.tags[1] and stanza.tags[1].attr.xmlns;
606 if stanza.name == "iq" then
607 if xmlns == "http://jabber.org/protocol/disco#info" and type == "get" then
608 origin.send(self:get_disco_info(stanza));
609 elseif xmlns == "http://jabber.org/protocol/disco#items" and type == "get" then
610 origin.send(self:get_disco_items(stanza));
611 elseif xmlns == "http://jabber.org/protocol/muc#admin" then
612 local actor = stanza.attr.from;
613 local affiliation = self:get_affiliation(actor);
614 local current_nick = self._jid_nick[actor];
615 local role = current_nick and self._occupants[current_nick].role or self:get_default_role(affiliation);
616 local item = stanza.tags[1].tags[1];
617 if item and item.name == "item" then
618 if type == "set" then
619 local callback = function() origin.send(st.reply(stanza)); end
620 if item.attr.jid then -- Validate provided JID
621 item.attr.jid = jid_prep(item.attr.jid);
622 if not item.attr.jid then
623 origin.send(st.error_reply(stanza, "modify", "jid-malformed"));
627 if not item.attr.jid and item.attr.nick then -- COMPAT Workaround for Miranda sending 'nick' instead of 'jid' when changing affiliation
628 local occupant = self._occupants[self.jid.."/"..item.attr.nick];
629 if occupant then item.attr.jid = occupant.jid; end
630 elseif not item.attr.nick and item.attr.jid then
631 local nick = self._jid_nick[item.attr.jid];
632 if nick then item.attr.nick = select(3, jid_split(nick)); end
634 local reason = item.tags[1] and item.tags[1].name == "reason" and #item.tags[1] == 1 and item.tags[1][1];
635 if item.attr.affiliation and item.attr.jid and not item.attr.role then
636 local success, errtype, err = self:set_affiliation(actor, item.attr.jid, item.attr.affiliation, callback, reason);
637 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
638 elseif item.attr.role and item.attr.nick and not item.attr.affiliation then
639 local success, errtype, err = self:set_role(actor, self.jid.."/"..item.attr.nick, item.attr.role, callback, reason);
640 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
642 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
644 elseif type == "get" then
645 local _aff = item.attr.affiliation;
646 local _rol = item.attr.role;
647 if _aff and not _rol then
648 if affiliation == "owner" or (affiliation == "admin" and _aff ~= "owner" and _aff ~= "admin") then
649 local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
650 for jid, affiliation in pairs(self._affiliations) do
651 if affiliation == _aff then
652 reply:tag("item", {affiliation = _aff, jid = jid}):up();
657 origin.send(st.error_reply(stanza, "auth", "forbidden"));
659 elseif _rol and not _aff then
660 if role == "moderator" then
661 -- TODO allow admins and owners not in room? Provide read-only access to everyone who can see the participants anyway?
662 if _rol == "none" then _rol = nil; end
663 local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
664 for occupant_jid, occupant in pairs(self._occupants) do
665 if occupant.role == _rol then
667 nick = select(3, jid_split(occupant_jid)),
668 role = _rol or "none",
669 affiliation = occupant.affiliation or "none",
676 origin.send(st.error_reply(stanza, "auth", "forbidden"));
679 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
682 elseif type == "set" or type == "get" then
683 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
685 elseif xmlns == "http://jabber.org/protocol/muc#owner" and (type == "get" or type == "set") and stanza.tags[1].name == "query" then
686 if self:get_affiliation(stanza.attr.from) ~= "owner" then
687 origin.send(st.error_reply(stanza, "auth", "forbidden"));
688 elseif stanza.attr.type == "get" then
689 self:send_form(origin, stanza);
690 elseif stanza.attr.type == "set" then
691 local child = stanza.tags[1].tags[1];
693 origin.send(st.error_reply(stanza, "auth", "bad-request"));
694 elseif child.name == "destroy" then
695 local newjid = child.attr.jid;
696 local reason, password;
697 for _,tag in ipairs(child.tags) do
698 if tag.name == "reason" then
699 reason = #tag.tags == 0 and tag[1];
700 elseif tag.name == "password" then
701 password = #tag.tags == 0 and tag[1];
704 self:destroy(newjid, reason, password);
705 origin.send(st.reply(stanza));
707 self:process_form(origin, stanza);
710 elseif type == "set" or type == "get" then
711 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
713 elseif stanza.name == "message" and type == "groupchat" then
714 local from, to = stanza.attr.from, stanza.attr.to;
715 local room = jid_bare(to);
716 local current_nick = self._jid_nick[from];
717 local occupant = self._occupants[current_nick];
718 if not occupant then -- not in room
719 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
720 elseif occupant.role == "visitor" then
721 origin.send(st.error_reply(stanza, "cancel", "forbidden"));
723 local from = stanza.attr.from;
724 stanza.attr.from = current_nick;
725 local subject = getText(stanza, {"subject"});
727 if occupant.role == "moderator" then
728 self:set_subject(current_nick, subject); -- TODO use broadcast_message_stanza
730 stanza.attr.from = from;
731 origin.send(st.error_reply(stanza, "cancel", "forbidden"));
734 self:broadcast_message(stanza, true);
736 stanza.attr.from = from;
738 elseif stanza.name == "message" and type == "error" and is_kickable_error(stanza) then
739 local current_nick = self._jid_nick[stanza.attr.from];
740 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
741 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza)); -- send unavailable
742 elseif stanza.name == "presence" then -- hack - some buggy clients send presence updates to the room rather than their nick
743 local to = stanza.attr.to;
744 local current_nick = self._jid_nick[stanza.attr.from];
746 stanza.attr.to = current_nick;
747 self:handle_to_occupant(origin, stanza);
749 elseif type ~= "error" and type ~= "result" then
750 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
752 elseif stanza.name == "message" and not stanza.attr.type and #stanza.tags == 1 and self._jid_nick[stanza.attr.from]
753 and stanza.tags[1].name == "x" and stanza.tags[1].attr.xmlns == "http://jabber.org/protocol/muc#user" then
754 local x = stanza.tags[1];
755 local payload = (#x.tags == 1 and x.tags[1]);
756 if payload and payload.name == "invite" and payload.attr.to then
757 local _from, _to = stanza.attr.from, stanza.attr.to;
758 local _invitee = jid_prep(payload.attr.to);
760 local _reason = payload.tags[1] and payload.tags[1].name == 'reason' and #payload.tags[1].tags == 0 and payload.tags[1][1];
761 local invite = st.message({from = _to, to = _invitee, id = stanza.attr.id})
762 :tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
763 :tag('invite', {from=_from})
764 :tag('reason'):text(_reason or ""):up()
766 if self:get_password() then
767 invite:tag("password"):text(self:get_password()):up();
770 :tag('x', {xmlns="jabber:x:conference", jid=_to}) -- COMPAT: Some older clients expect this
773 :tag('body') -- Add a plain message for clients which don't support invites
774 :text(_from..' invited you to the room '.._to..(_reason and (' ('.._reason..')') or ""))
776 self:_route_stanza(invite);
778 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
781 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
784 if type == "error" or type == "result" then return; end
785 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
789 function room_mt:handle_stanza(origin, stanza)
790 local to_node, to_host, to_resource = jid_split(stanza.attr.to);
792 self:handle_to_occupant(origin, stanza);
794 self:handle_to_room(origin, stanza);
798 function room_mt:route_stanza(stanza) end -- Replace with a routing function, e.g., function(room, stanza) core_route_stanza(origin, stanza); end
800 function room_mt:get_affiliation(jid)
801 local node, host, resource = jid_split(jid);
802 local bare = node and node.."@"..host or host;
803 local result = self._affiliations[bare]; -- Affiliations are granted, revoked, and maintained based on the user's bare JID.
804 if not result and self._affiliations[host] == "outcast" then result = "outcast"; end -- host banned
807 function room_mt:set_affiliation(actor, jid, affiliation, callback, reason)
809 if affiliation == "none" then affiliation = nil; end
810 if affiliation and affiliation ~= "outcast" and affiliation ~= "owner" and affiliation ~= "admin" and affiliation ~= "member" then
811 return nil, "modify", "not-acceptable";
813 if self:get_affiliation(actor) ~= "owner" then return nil, "cancel", "not-allowed"; end
814 if jid_bare(actor) == jid then return nil, "cancel", "not-allowed"; end
815 self._affiliations[jid] = affiliation;
816 local role = self:get_default_role(affiliation);
817 local p = st.presence()
818 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
819 :tag("item", {affiliation=affiliation or "none", role=role or "none"})
820 :tag("reason"):text(reason or ""):up()
823 local item = x.tags[1];
824 if not role then -- getting kicked
825 p.attr.type = "unavailable";
826 if affiliation == "outcast" then
827 x:tag("status", {code="301"}):up(); -- banned
829 x:tag("status", {code="321"}):up(); -- affiliation change
832 local modified_nicks = {};
833 for nick, occupant in pairs(self._occupants) do
834 if jid_bare(occupant.jid) == jid then
835 if not role then -- getting kicked
836 self._occupants[nick] = nil;
838 t_insert(modified_nicks, nick);
839 occupant.affiliation, occupant.role = affiliation, role;
842 for jid in pairs(occupant.sessions) do -- remove for all sessions of the nick
843 if not role then self._jid_nick[jid] = nil; end
845 self:_route_stanza(p);
849 if self.save then self:save(); end
850 if callback then callback(); end
851 for _, nick in ipairs(modified_nicks) do
853 self:broadcast_except_nick(p, nick);
858 function room_mt:get_role(nick)
859 local session = self._occupants[nick];
860 return session and session.role or nil;
862 function room_mt:set_role(actor, occupant_jid, role, callback, reason)
863 if role == "none" then role = nil; end
864 if role and role ~= "moderator" and role ~= "participant" and role ~= "visitor" then return nil, "modify", "not-acceptable"; end
865 if self:get_affiliation(actor) ~= "owner" then return nil, "cancel", "not-allowed"; end
866 local occupant = self._occupants[occupant_jid];
867 if not occupant then return nil, "modify", "not-acceptable"; end
868 if occupant.affiliation == "owner" or occupant.affiliation == "admin" then return nil, "cancel", "not-allowed"; end
869 local p = st.presence({from = occupant_jid})
870 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
871 :tag("item", {affiliation=occupant.affiliation or "none", nick=select(3, jid_split(occupant_jid)), role=role or "none"})
872 :tag("reason"):text(reason or ""):up()
874 if not role then -- kick
875 p.attr.type = "unavailable";
876 self._occupants[occupant_jid] = nil;
877 for jid in pairs(occupant.sessions) do -- remove for all sessions of the nick
878 self._jid_nick[jid] = nil;
880 p:tag("status", {code = "307"}):up();
882 occupant.role = role;
884 for jid in pairs(occupant.sessions) do -- send to all sessions of the nick
886 self:_route_stanza(p);
888 if callback then callback(); end
889 self:broadcast_except_nick(p, occupant_jid);
893 function room_mt:_route_stanza(stanza)
895 local to_occupant = self._occupants[self._jid_nick[stanza.attr.to]];
896 local from_occupant = self._occupants[stanza.attr.from];
897 if stanza.name == "presence" then
898 if to_occupant and from_occupant then
899 if self._data.whois == 'anyone' then
900 muc_child = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
902 if to_occupant.role == "moderator" or jid_bare(to_occupant.jid) == jid_bare(from_occupant.jid) then
903 muc_child = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
909 for _, item in pairs(muc_child.tags) do
910 if item.name == "item" then
911 if from_occupant == to_occupant then
912 item.attr.jid = stanza.attr.to;
914 item.attr.jid = from_occupant.jid;
918 if self._data.whois == 'anyone' then
919 muc_child:tag('status', { code = '100' });
922 self:route_stanza(stanza);
924 for _, item in pairs(muc_child.tags) do
925 if item.name == "item" then
932 local _M = {}; -- module "muc"
934 function _M.new_room(jid)
935 return setmetatable({
940 whois = 'moderators',