cf8946eb8237fe8f705c8aef905f9e4bb7725f44
[prosody.git] / plugins / muc / muc.lib.lua
1 -- Prosody IM
2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 Waqas Hussain
4 -- 
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
7 --
8
9 local datamanager = require "util.datamanager";
10 local datetime = require "util.datetime";
11
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;
22
23 local muc_domain = nil; --module:get_host();
24 local history_length = 20;
25
26 ------------
27 local function filter_xmlns_from_array(array, filters)
28         local count = 0;
29         for i=#array,1,-1 do
30                 local attr = array[i].attr;
31                 if filters[attr and attr.xmlns] then
32                         t_remove(array, i);
33                         count = count + 1;
34                 end
35         end
36         return count;
37 end
38 local function filter_xmlns_from_stanza(stanza, filters)
39         if filters then
40                 if filter_xmlns_from_array(stanza.tags, filters) ~= 0 then
41                         return stanza, filter_xmlns_from_array(stanza, filters);
42                 end
43         end
44         return stanza, 0;
45 end
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);
49 end
50 local kickable_error_conditions = {
51         ["gone"] = true;
52         ["internal-server-error"] = true;
53         ["item-not-found"] = true;
54         ["jid-malformed"] = true;
55         ["recipient-unavailable"] = true;
56         ["redirect"] = true;
57         ["remote-server-not-found"] = true;
58         ["remote-server-timeout"] = true;
59         ["service-unavailable"] = true;
60         ["malformed error"] = true;
61 };
62
63 local function get_error_condition(stanza)
64         local _, condition = stanza:get_error();
65         return condition or "malformed error";
66 end
67
68 local function is_kickable_error(stanza)
69         local cond = get_error_condition(stanza);
70         return kickable_error_conditions[cond] and cond;
71 end
72 local function getUsingPath(stanza, path, getText)
73         local tag = stanza;
74         for _, name in ipairs(path) do
75                 if type(tag) ~= 'table' then return; end
76                 tag = tag:child_with_name(name);
77         end
78         if tag and getText then tag = table.concat(tag); end
79         return tag;
80 end
81 local function getTag(stanza, path) return getUsingPath(stanza, path); end
82 local function getText(stanza, path) return getUsingPath(stanza, path, true); end
83 -----------
84
85 local room_mt = {};
86 room_mt.__index = room_mt;
87
88 function room_mt:get_default_role(affiliation)
89         if affiliation == "owner" or affiliation == "admin" then
90                 return "moderator";
91         elseif affiliation == "member" then
92                 return "participant";
93         elseif not affiliation then
94                 if not self:is_members_only() then
95                         return self:is_moderated() and "visitor" or "participant";
96                 end
97         end
98 end
99
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();
105         if code then
106                 stanza:tag("status", {code=code}):up();
107         end
108         self:broadcast_except_nick(stanza, stanza.attr.from);
109         local me = self._occupants[stanza.attr.from];
110         if me then
111                 stanza:tag("status", {code='110'});
112                 stanza.attr.to = sid;
113                 self:_route_stanza(stanza);
114         end
115 end
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);
122                 end
123         end
124         stanza.attr.to = to;
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);
129                 stanza.attr.to = "";
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
137         end
138 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);
145                         end
146                 end
147         end
148 end
149
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);
159                 end
160         end
161 end
162 function room_mt:send_history(to, stanza)
163         local history = self._data['history']; -- send discussion history
164         if history then
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");
167                 
168                 local maxchars = history_tag and tonumber(history_tag.attr.maxchars);
169                 if maxchars then maxchars = math.floor(maxchars); end
170                 
171                 local maxstanzas = math.floor(history_tag and tonumber(history_tag.attr.maxstanzas) or #history);
172                 if not history_tag then maxstanzas = 20; end
173
174                 local seconds = history_tag and tonumber(history_tag.attr.seconds);
175                 if seconds then seconds = datetime.datetime(os.time() - math.floor(seconds)); end
176
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
180
181                 local n = 0;
182                 local charcount = 0;
183                 local stanzacount = 0;
184                 
185                 for i=#history,1,-1 do
186                         local entry = history[i];
187                         if maxchars then
188                                 if not entry.chars then
189                                         entry.stanza.attr.to = "";
190                                         entry.chars = #tostring(entry.stanza);
191                                 end
192                                 charcount = charcount + entry.chars + #to;
193                                 if charcount > maxchars then break; end
194                         end
195                         if since and since > entry.stamp then break; end
196                         if n + 1 > maxstanzas then break; end
197                         n = n + 1;
198                 end
199                 for i=#history-n+1,#history do
200                         local msg = history[i].stanza;
201                         msg.attr.to = to;
202                         self:_route_stanza(msg);
203                 end
204         end
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']));
207         end
208 end
209
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         ;
217 end
218 function room_mt:get_disco_items(stanza)
219         local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#items");
220         for room_jid in pairs(self._occupants) do
221                 reply:tag("item", {jid = room_jid, name = room_jid:match("/(.*)")}):up();
222         end
223         return reply;
224 end
225 function room_mt:set_subject(current_nick, subject)
226         -- TODO check nick's authority
227         if subject == "" then subject = nil; end
228         self._data['subject'] = subject;
229         if self.save then self:save(); end
230         local msg = st.message({type='groupchat', from=current_nick})
231                 :tag('subject'):text(subject):up();
232         self:broadcast_message(msg, false);
233         return true;
234 end
235
236 local function build_unavailable_presence_from_error(stanza)
237         local type, condition, text = stanza:get_error();
238         local error_message = "Kicked: "..condition:gsub("%-", " ");
239         if text then
240                 error_message = error_message..": "..text;
241         end
242         return st.presence({type='unavailable', from=stanza.attr.from, to=stanza.attr.to})
243                 :tag('status'):text(error_message);
244 end
245
246 function room_mt:set_password(password)
247         if password == "" or type(password) ~= "string" then password = nil; end
248         if self._data.password ~= password then
249                 self._data.password = password;
250                 if self.save then self:save(true); end
251         end
252 end
253 function room_mt:get_password()
254         return self._data.password;
255 end
256 function room_mt:set_moderated(moderated)
257         moderated = moderated and true or nil;
258         if self._data.moderated ~= moderated then
259                 self._data.moderated = moderated;
260                 if self.save then self:save(true); end
261         end
262 end
263 function room_mt:is_moderated()
264         return self._data.moderated;
265 end
266 function room_mt:set_members_only(members_only)
267         members_only = members_only and true or nil;
268         if self._data.members_only ~= members_only then
269                 self._data.members_only = members_only;
270                 if self.save then self:save(true); end
271         end
272 end
273 function room_mt:is_members_only()
274         return self._data.members_only;
275 end
276
277 function room_mt:handle_to_occupant(origin, stanza) -- PM, vCards, etc
278         local from, to = stanza.attr.from, stanza.attr.to;
279         local room = jid_bare(to);
280         local current_nick = self._jid_nick[from];
281         local type = stanza.attr.type;
282         log("debug", "room: %s, current_nick: %s, stanza: %s", room or "nil", current_nick or "nil", stanza:top_tag());
283         if (select(2, jid_split(from)) == muc_domain) then error("Presence from the MUC itself!!!"); end
284         if stanza.name == "presence" then
285                 local pr = get_filtered_presence(stanza);
286                 pr.attr.from = current_nick;
287                 if type == "error" then -- error, kick em out!
288                         if current_nick then
289                                 log("debug", "kicking %s from %s", current_nick, room);
290                                 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza));
291                         end
292                 elseif type == "unavailable" then -- unavailable
293                         if current_nick then
294                                 log("debug", "%s leaving %s", current_nick, room);
295                                 local occupant = self._occupants[current_nick];
296                                 local new_jid = next(occupant.sessions);
297                                 if new_jid == from then new_jid = next(occupant.sessions, new_jid); end
298                                 if new_jid then
299                                         local jid = occupant.jid;
300                                         occupant.jid = new_jid;
301                                         occupant.sessions[from] = nil;
302                                         pr.attr.to = from;
303                                         pr:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
304                                                 :tag("item", {affiliation=occupant.affiliation or "none", role='none'}):up()
305                                                 :tag("status", {code='110'});
306                                         self:_route_stanza(pr);
307                                         if jid ~= new_jid then
308                                                 pr = st.clone(occupant.sessions[new_jid])
309                                                         :tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
310                                                         :tag("item", {affiliation=occupant.affiliation or "none", role=occupant.role or "none"});
311                                                 pr.attr.from = current_nick;
312                                                 self:broadcast_except_nick(pr, current_nick);
313                                         end
314                                 else
315                                         occupant.role = 'none';
316                                         self:broadcast_presence(pr, from);
317                                         self._occupants[current_nick] = nil;
318                                 end
319                                 self._jid_nick[from] = nil;
320                         end
321                 elseif not type then -- available
322                         if current_nick then
323                                 --if #pr == #stanza or current_nick ~= to then -- commented because google keeps resending directed presence
324                                         if current_nick == to then -- simple presence
325                                                 log("debug", "%s broadcasted presence", current_nick);
326                                                 self._occupants[current_nick].sessions[from] = pr;
327                                                 self:broadcast_presence(pr, from);
328                                         else -- change nick
329                                                 local occupant = self._occupants[current_nick];
330                                                 local is_multisession = next(occupant.sessions, next(occupant.sessions));
331                                                 if self._occupants[to] or is_multisession then
332                                                         log("debug", "%s couldn't change nick", current_nick);
333                                                         local reply = st.error_reply(stanza, "cancel", "conflict"):up();
334                                                         reply.tags[1].attr.code = "409";
335                                                         origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
336                                                 else
337                                                         local data = self._occupants[current_nick];
338                                                         local to_nick = select(3, jid_split(to));
339                                                         if to_nick then
340                                                                 log("debug", "%s (%s) changing nick to %s", current_nick, data.jid, to);
341                                                                 local p = st.presence({type='unavailable', from=current_nick});
342                                                                 self:broadcast_presence(p, from, '303', to_nick);
343                                                                 self._occupants[current_nick] = nil;
344                                                                 self._occupants[to] = data;
345                                                                 self._jid_nick[from] = to;
346                                                                 pr.attr.from = to;
347                                                                 self._occupants[to].sessions[from] = pr;
348                                                                 self:broadcast_presence(pr, from);
349                                                         else
350                                                                 --TODO malformed-jid
351                                                         end
352                                                 end
353                                         end
354                                 --else -- possible rejoin
355                                 --      log("debug", "%s had connection replaced", current_nick);
356                                 --      self:handle_to_occupant(origin, st.presence({type='unavailable', from=from, to=to})
357                                 --              :tag('status'):text('Replaced by new connection'):up()); -- send unavailable
358                                 --      self:handle_to_occupant(origin, stanza); -- resend available
359                                 --end
360                         else -- enter room
361                                 local new_nick = to;
362                                 local is_merge;
363                                 if self._occupants[to] then
364                                         if jid_bare(from) ~= jid_bare(self._occupants[to].jid) then
365                                                 new_nick = nil;
366                                         end
367                                         is_merge = true;
368                                 end
369                                 local password = stanza:get_child("x", "http://jabber.org/protocol/muc");
370                                 password = password and password:get_child("password", "http://jabber.org/protocol/muc");
371                                 password = password and password[1] ~= "" and password[1];
372                                 if self:get_password() and self:get_password() ~= password then
373                                         log("debug", "%s couldn't join due to invalid password: %s", from, to);
374                                         local reply = st.error_reply(stanza, "auth", "not-authorized"):up();
375                                         reply.tags[1].attr.code = "401";
376                                         origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
377                                 elseif not new_nick then
378                                         log("debug", "%s couldn't join due to nick conflict: %s", from, to);
379                                         local reply = st.error_reply(stanza, "cancel", "conflict"):up();
380                                         reply.tags[1].attr.code = "409";
381                                         origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
382                                 else
383                                         log("debug", "%s joining as %s", from, to);
384                                         if not next(self._affiliations) then -- new room, no owners
385                                                 self._affiliations[jid_bare(from)] = "owner";
386                                         end
387                                         local affiliation = self:get_affiliation(from);
388                                         local role = self:get_default_role(affiliation)
389                                         if role then -- new occupant
390                                                 if not is_merge then
391                                                         self._occupants[to] = {affiliation=affiliation, role=role, jid=from, sessions={[from]=get_filtered_presence(stanza)}};
392                                                 else
393                                                         self._occupants[to].sessions[from] = get_filtered_presence(stanza);
394                                                 end
395                                                 self._jid_nick[from] = to;
396                                                 self:send_occupant_list(from);
397                                                 pr.attr.from = to;
398                                                 if not is_merge then
399                                                         self:broadcast_presence(pr, from);
400                                                 else
401                                                         pr.attr.to = from;
402                                                         self:_route_stanza(pr:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
403                                                                 :tag("item", {affiliation=affiliation or "none", role=role or "none"}):up()
404                                                                 :tag("status", {code='110'}));
405                                                 end
406                                                 self:send_history(from, stanza);
407                                         else -- banned
408                                                 local reply = st.error_reply(stanza, "auth", "forbidden"):up();
409                                                 reply.tags[1].attr.code = "403";
410                                                 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
411                                         end
412                                 end
413                         end
414                 elseif type ~= 'result' then -- bad type
415                         if type ~= 'visible' and type ~= 'invisible' then -- COMPAT ejabberd can broadcast or forward XEP-0018 presences
416                                 origin.send(st.error_reply(stanza, "modify", "bad-request")); -- FIXME correct error?
417                         end
418                 end
419         elseif not current_nick then -- not in room
420                 if type == "error" or type == "result" then
421                         local id = stanza.name == "iq" and stanza.attr.id and base64.decode(stanza.attr.id);
422                         local _nick, _id, _hash = (id or ""):match("^(.+)%z(.*)%z(.+)$");
423                         local occupant = self._occupants[stanza.attr.to];
424                         if occupant and _nick and self._jid_nick[_nick] and _id and _hash then
425                                 local id, _to = stanza.attr.id;
426                                 for jid in pairs(occupant.sessions) do
427                                         if md5(jid) == _hash then
428                                                 _to = jid;
429                                                 break;
430                                         end
431                                 end
432                                 if _to then
433                                         stanza.attr.to, stanza.attr.from, stanza.attr.id = _to, self._jid_nick[_nick], _id;
434                                         self:_route_stanza(stanza);
435                                         stanza.attr.to, stanza.attr.from, stanza.attr.id = to, from, id;
436                                 end
437                         end
438                 else
439                         origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
440                 end
441         elseif stanza.name == "message" and type == "groupchat" then -- groupchat messages not allowed in PM
442                 origin.send(st.error_reply(stanza, "modify", "bad-request"));
443         elseif current_nick and stanza.name == "message" and type == "error" and is_kickable_error(stanza) then
444                 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
445                 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza)); -- send unavailable
446         else -- private stanza
447                 local o_data = self._occupants[to];
448                 if o_data then
449                         log("debug", "%s sent private stanza to %s (%s)", from, to, o_data.jid);
450                         local jid = o_data.jid;
451                         local bare = jid_bare(jid);
452                         stanza.attr.to, stanza.attr.from = jid, current_nick;
453                         local id = stanza.attr.id;
454                         if stanza.name=='iq' and type=='get' and stanza.tags[1].attr.xmlns == 'vcard-temp' and bare ~= jid then
455                                 stanza.attr.to = bare;
456                                 stanza.attr.id = base64.encode(jid.."\0"..id.."\0"..md5(from));
457                         end
458                         self:_route_stanza(stanza);
459                         stanza.attr.to, stanza.attr.from, stanza.attr.id = to, from, id;
460                 elseif type ~= "error" and type ~= "result" then -- recipient not in room
461                         origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
462                 end
463         end
464 end
465
466 function room_mt:send_form(origin, stanza)
467         local title = "Configuration for "..self.jid;
468         origin.send(st.reply(stanza):query("http://jabber.org/protocol/muc#owner")
469                 :tag("x", {xmlns='jabber:x:data', type='form'})
470                         :tag("title"):text(title):up()
471                         :tag("instructions"):text(title):up()
472                         :tag("field", {type='hidden', var='FORM_TYPE'}):tag("value"):text("http://jabber.org/protocol/muc#roomconfig"):up():up()
473                         :tag("field", {type='boolean', label='Make Room Persistent?', var='muc#roomconfig_persistentroom'})
474                                 :tag("value"):text(self._data.persistent and "1" or "0"):up()
475                         :up()
476                         :tag("field", {type='boolean', label='Make Room Publicly Searchable?', var='muc#roomconfig_publicroom'})
477                                 :tag("value"):text(self._data.hidden and "0" or "1"):up()
478                         :up()
479                         :tag("field", {type='list-single', label='Who May Discover Real JIDs?', var='muc#roomconfig_whois'})
480                             :tag("value"):text(self._data.whois or 'moderators'):up()
481                             :tag("option", {label = 'Moderators Only'})
482                                 :tag("value"):text('moderators'):up()
483                                 :up()
484                             :tag("option", {label = 'Anyone'})
485                                 :tag("value"):text('anyone'):up()
486                                 :up()
487                         :up()
488                         :tag("field", {type='text-private', label='Password', var='muc#roomconfig_roomsecret'})
489                                 :tag("value"):text(self:get_password() or ""):up()
490                         :up()
491                         :tag("field", {type='boolean', label='Make Room Moderated?', var='muc#roomconfig_moderatedroom'})
492                                 :tag("value"):text(self:is_moderated() and "1" or "0"):up()
493                         :up()
494         );
495 end
496
497 local valid_whois = {
498     moderators = true,
499     anyone = true,
500 }
501
502 function room_mt:process_form(origin, stanza)
503         local query = stanza.tags[1];
504         local form;
505         for _, tag in ipairs(query.tags) do if tag.name == "x" and tag.attr.xmlns == "jabber:x:data" then form = tag; break; end end
506         if not form then origin.send(st.error_reply(stanza, "cancel", "service-unavailable")); return; end
507         if form.attr.type == "cancel" then origin.send(st.reply(stanza)); return; end
508         if form.attr.type ~= "submit" then origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
509         local fields = {};
510         for _, field in pairs(form.tags) do
511                 if field.name == "field" and field.attr.var and field.tags[1].name == "value" and #field.tags[1].tags == 0 then
512                         fields[field.attr.var] = field.tags[1][1] or "";
513                 end
514         end
515         if fields.FORM_TYPE ~= "http://jabber.org/protocol/muc#roomconfig" then origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
516
517         local dirty = false
518
519         local persistent = fields['muc#roomconfig_persistentroom'];
520         if persistent == "0" or persistent == "false" then persistent = nil; elseif persistent == "1" or persistent == "true" then persistent = true;
521         else origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
522         dirty = dirty or (self._data.persistent ~= persistent)
523         self._data.persistent = persistent;
524         module:log("debug", "persistent=%s", tostring(persistent));
525
526         local moderated = fields['muc#roomconfig_moderatedroom'];
527         if moderated == "0" or moderated == "false" then moderated = nil; elseif moderated == "1" or moderated == "true" then moderated = true;
528         else origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
529         dirty = dirty or (self:is_moderated() ~= moderated)
530         module:log("debug", "moderated=%s", tostring(moderated));
531
532         local public = fields['muc#roomconfig_publicroom'];
533         if public == "0" or public == "false" then public = nil; elseif public == "1" or public == "true" then public = true;
534         else origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
535         dirty = dirty or (self._data.hidden ~= (not public and true or nil))
536         self._data.hidden = not public and true or nil;
537
538         local whois = fields['muc#roomconfig_whois'];
539         if not valid_whois[whois] then
540             origin.send(st.error_reply(stanza, 'cancel', 'bad-request'));
541             return;
542         end
543         local whois_changed = self._data.whois ~= whois
544         self._data.whois = whois
545         module:log('debug', 'whois=%s', tostring(whois))
546
547         local password = fields['muc#roomconfig_roomsecret'];
548         if password then
549                 self:set_password(password);
550         end
551         self:set_moderated(moderated);
552
553         if self.save then self:save(true); end
554         origin.send(st.reply(stanza));
555
556         if dirty or whois_changed then
557             local msg = st.message({type='groupchat', from=self.jid})
558                     :tag('x', {xmlns='http://jabber.org/protocol/muc#user'}):up()
559
560             if dirty then
561                 msg.tags[1]:tag('status', {code = '104'})
562             end
563             if whois_changed then
564                 local code = (whois == 'moderators') and 173 or 172
565                 msg.tags[1]:tag('status', {code = code})
566             end
567
568             self:broadcast_message(msg, false)
569         end
570 end
571
572 function room_mt:destroy(newjid, reason, password)
573         local pr = st.presence({type = "unavailable"})
574                 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
575                         :tag("item", { affiliation='none', role='none' }):up()
576                         :tag("destroy", {jid=newjid})
577         if reason then pr:tag("reason"):text(reason):up(); end
578         if password then pr:tag("password"):text(password):up(); end
579         for nick, occupant in pairs(self._occupants) do
580                 pr.attr.from = nick;
581                 for jid in pairs(occupant.sessions) do
582                         pr.attr.to = jid;
583                         self:_route_stanza(pr);
584                         self._jid_nick[jid] = nil;
585                 end
586                 self._occupants[nick] = nil;
587         end
588         self._data.persistent = nil;
589         if self.save then self:save(true); end
590 end
591
592 function room_mt:handle_to_room(origin, stanza) -- presence changes and groupchat messages, along with disco/etc
593         local type = stanza.attr.type;
594         local xmlns = stanza.tags[1] and stanza.tags[1].attr.xmlns;
595         if stanza.name == "iq" then
596                 if xmlns == "http://jabber.org/protocol/disco#info" and type == "get" then
597                         origin.send(self:get_disco_info(stanza));
598                 elseif xmlns == "http://jabber.org/protocol/disco#items" and type == "get" then
599                         origin.send(self:get_disco_items(stanza));
600                 elseif xmlns == "http://jabber.org/protocol/muc#admin" then
601                         local actor = stanza.attr.from;
602                         local affiliation = self:get_affiliation(actor);
603                         local current_nick = self._jid_nick[actor];
604                         local role = current_nick and self._occupants[current_nick].role or self:get_default_role(affiliation);
605                         local item = stanza.tags[1].tags[1];
606                         if item and item.name == "item" then
607                                 if type == "set" then
608                                         local callback = function() origin.send(st.reply(stanza)); end
609                                         if item.attr.jid then -- Validate provided JID
610                                                 item.attr.jid = jid_prep(item.attr.jid);
611                                                 if not item.attr.jid then
612                                                         origin.send(st.error_reply(stanza, "modify", "jid-malformed"));
613                                                         return;
614                                                 end
615                                         end
616                                         if not item.attr.jid and item.attr.nick then -- COMPAT Workaround for Miranda sending 'nick' instead of 'jid' when changing affiliation
617                                                 local occupant = self._occupants[self.jid.."/"..item.attr.nick];
618                                                 if occupant then item.attr.jid = occupant.jid; end
619                                         elseif not item.attr.nick and item.attr.jid then
620                                                 local nick = self._jid_nick[item.attr.jid];
621                                                 if nick then item.attr.nick = select(3, jid_split(nick)); end
622                                         end
623                                         local reason = item.tags[1] and item.tags[1].name == "reason" and #item.tags[1] == 1 and item.tags[1][1];
624                                         if item.attr.affiliation and item.attr.jid and not item.attr.role then
625                                                 local success, errtype, err = self:set_affiliation(actor, item.attr.jid, item.attr.affiliation, callback, reason);
626                                                 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
627                                         elseif item.attr.role and item.attr.nick and not item.attr.affiliation then
628                                                 local success, errtype, err = self:set_role(actor, self.jid.."/"..item.attr.nick, item.attr.role, callback, reason);
629                                                 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
630                                         else
631                                                 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
632                                         end
633                                 elseif type == "get" then
634                                         local _aff = item.attr.affiliation;
635                                         local _rol = item.attr.role;
636                                         if _aff and not _rol then
637                                                 if affiliation == "owner" or (affiliation == "admin" and _aff ~= "owner" and _aff ~= "admin") then
638                                                         local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
639                                                         for jid, affiliation in pairs(self._affiliations) do
640                                                                 if affiliation == _aff then
641                                                                         reply:tag("item", {affiliation = _aff, jid = jid}):up();
642                                                                 end
643                                                         end
644                                                         origin.send(reply);
645                                                 else
646                                                         origin.send(st.error_reply(stanza, "auth", "forbidden"));
647                                                 end
648                                         elseif _rol and not _aff then
649                                                 if role == "moderator" then
650                                                         -- TODO allow admins and owners not in room? Provide read-only access to everyone who can see the participants anyway?
651                                                         if _rol == "none" then _rol = nil; end
652                                                         local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
653                                                         for occupant_jid, occupant in pairs(self._occupants) do
654                                                                 if occupant.role == _rol then
655                                                                         reply:tag("item", {
656                                                                                 nick = select(3, jid_split(occupant_jid)),
657                                                                                 role = _rol or "none",
658                                                                                 affiliation = occupant.affiliation or "none",
659                                                                                 jid = occupant.jid
660                                                                                 }):up();
661                                                                 end
662                                                         end
663                                                         origin.send(reply);
664                                                 else
665                                                         origin.send(st.error_reply(stanza, "auth", "forbidden"));
666                                                 end
667                                         else
668                                                 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
669                                         end
670                                 end
671                         elseif type == "set" or type == "get" then
672                                 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
673                         end
674                 elseif xmlns == "http://jabber.org/protocol/muc#owner" and (type == "get" or type == "set") and stanza.tags[1].name == "query" then
675                         if self:get_affiliation(stanza.attr.from) ~= "owner" then
676                                 origin.send(st.error_reply(stanza, "auth", "forbidden"));
677                         elseif stanza.attr.type == "get" then
678                                 self:send_form(origin, stanza);
679                         elseif stanza.attr.type == "set" then
680                                 local child = stanza.tags[1].tags[1];
681                                 if not child then
682                                         origin.send(st.error_reply(stanza, "auth", "bad-request"));
683                                 elseif child.name == "destroy" then
684                                         local newjid = child.attr.jid;
685                                         local reason, password;
686                                         for _,tag in ipairs(child.tags) do
687                                                 if tag.name == "reason" then
688                                                         reason = #tag.tags == 0 and tag[1];
689                                                 elseif tag.name == "password" then
690                                                         password = #tag.tags == 0 and tag[1];
691                                                 end
692                                         end
693                                         self:destroy(newjid, reason, password);
694                                         origin.send(st.reply(stanza));
695                                 else
696                                         self:process_form(origin, stanza);
697                                 end
698                         end
699                 elseif type == "set" or type == "get" then
700                         origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
701                 end
702         elseif stanza.name == "message" and type == "groupchat" then
703                 local from, to = stanza.attr.from, stanza.attr.to;
704                 local room = jid_bare(to);
705                 local current_nick = self._jid_nick[from];
706                 local occupant = self._occupants[current_nick];
707                 if not occupant then -- not in room
708                         origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
709                 elseif occupant.role == "visitor" then
710                         origin.send(st.error_reply(stanza, "cancel", "forbidden"));
711                 else
712                         local from = stanza.attr.from;
713                         stanza.attr.from = current_nick;
714                         local subject = getText(stanza, {"subject"});
715                         if subject then
716                                 if occupant.role == "moderator" then
717                                         self:set_subject(current_nick, subject); -- TODO use broadcast_message_stanza
718                                 else
719                                         stanza.attr.from = from;
720                                         origin.send(st.error_reply(stanza, "cancel", "forbidden"));
721                                 end
722                         else
723                                 self:broadcast_message(stanza, true);
724                         end
725                         stanza.attr.from = from;
726                 end
727         elseif stanza.name == "message" and type == "error" and is_kickable_error(stanza) then
728                 local current_nick = self._jid_nick[stanza.attr.from];
729                 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
730                 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza)); -- send unavailable
731         elseif stanza.name == "presence" then -- hack - some buggy clients send presence updates to the room rather than their nick
732                 local to = stanza.attr.to;
733                 local current_nick = self._jid_nick[stanza.attr.from];
734                 if current_nick then
735                         stanza.attr.to = current_nick;
736                         self:handle_to_occupant(origin, stanza);
737                         stanza.attr.to = to;
738                 elseif type ~= "error" and type ~= "result" then
739                         origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
740                 end
741         elseif stanza.name == "message" and not stanza.attr.type and #stanza.tags == 1 and self._jid_nick[stanza.attr.from]
742                 and stanza.tags[1].name == "x" and stanza.tags[1].attr.xmlns == "http://jabber.org/protocol/muc#user" then
743                 local x = stanza.tags[1];
744                 local payload = (#x.tags == 1 and x.tags[1]);
745                 if payload and payload.name == "invite" and payload.attr.to then
746                         local _from, _to = stanza.attr.from, stanza.attr.to;
747                         local _invitee = jid_prep(payload.attr.to);
748                         if _invitee then
749                                 local _reason = payload.tags[1] and payload.tags[1].name == 'reason' and #payload.tags[1].tags == 0 and payload.tags[1][1];
750                                 local invite = st.message({from = _to, to = _invitee, id = stanza.attr.id})
751                                         :tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
752                                                 :tag('invite', {from=_from})
753                                                         :tag('reason'):text(_reason or ""):up()
754                                                 :up();
755                                                 if self:get_password() then
756                                                         invite:tag("password"):text(self:get_password()):up();
757                                                 end
758                                         invite:up()
759                                         :tag('x', {xmlns="jabber:x:conference", jid=_to}) -- COMPAT: Some older clients expect this
760                                                 :text(_reason or "")
761                                         :up()
762                                         :tag('body') -- Add a plain message for clients which don't support invites
763                                                 :text(_from..' invited you to the room '.._to..(_reason and (' ('.._reason..')') or ""))
764                                         :up();
765                                 self:_route_stanza(invite);
766                         else
767                                 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
768                         end
769                 else
770                         origin.send(st.error_reply(stanza, "cancel", "bad-request"));
771                 end
772         else
773                 if type == "error" or type == "result" then return; end
774                 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
775         end
776 end
777
778 function room_mt:handle_stanza(origin, stanza)
779         local to_node, to_host, to_resource = jid_split(stanza.attr.to);
780         if to_resource then
781                 self:handle_to_occupant(origin, stanza);
782         else
783                 self:handle_to_room(origin, stanza);
784         end
785 end
786
787 function room_mt:route_stanza(stanza) end -- Replace with a routing function, e.g., function(room, stanza) core_route_stanza(origin, stanza); end
788
789 function room_mt:get_affiliation(jid)
790         local node, host, resource = jid_split(jid);
791         local bare = node and node.."@"..host or host;
792         local result = self._affiliations[bare]; -- Affiliations are granted, revoked, and maintained based on the user's bare JID.
793         if not result and self._affiliations[host] == "outcast" then result = "outcast"; end -- host banned
794         return result;
795 end
796 function room_mt:set_affiliation(actor, jid, affiliation, callback, reason)
797         jid = jid_bare(jid);
798         if affiliation == "none" then affiliation = nil; end
799         if affiliation and affiliation ~= "outcast" and affiliation ~= "owner" and affiliation ~= "admin" and affiliation ~= "member" then
800                 return nil, "modify", "not-acceptable";
801         end
802         if self:get_affiliation(actor) ~= "owner" then return nil, "cancel", "not-allowed"; end
803         if jid_bare(actor) == jid then return nil, "cancel", "not-allowed"; end
804         self._affiliations[jid] = affiliation;
805         local role = self:get_default_role(affiliation);
806         local p = st.presence()
807                 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
808                         :tag("item", {affiliation=affiliation or "none", role=role or "none"})
809                                 :tag("reason"):text(reason or ""):up()
810                         :up();
811         local x = p.tags[1];
812         local item = x.tags[1];
813         if not role then -- getting kicked
814                 p.attr.type = "unavailable";
815                 if affiliation == "outcast" then
816                         x:tag("status", {code="301"}):up(); -- banned
817                 else
818                         x:tag("status", {code="321"}):up(); -- affiliation change
819                 end
820         end
821         local modified_nicks = {};
822         for nick, occupant in pairs(self._occupants) do
823                 if jid_bare(occupant.jid) == jid then
824                         if not role then -- getting kicked
825                                 self._occupants[nick] = nil;
826                         else
827                                 t_insert(modified_nicks, nick);
828                                 occupant.affiliation, occupant.role = affiliation, role;
829                         end
830                         p.attr.from = nick;
831                         for jid in pairs(occupant.sessions) do -- remove for all sessions of the nick
832                                 if not role then self._jid_nick[jid] = nil; end
833                                 p.attr.to = jid;
834                                 self:_route_stanza(p);
835                         end
836                 end
837         end
838         if self.save then self:save(); end
839         if callback then callback(); end
840         for _, nick in ipairs(modified_nicks) do
841                 p.attr.from = nick;
842                 self:broadcast_except_nick(p, nick);
843         end
844         return true;
845 end
846
847 function room_mt:get_role(nick)
848         local session = self._occupants[nick];
849         return session and session.role or nil;
850 end
851 function room_mt:set_role(actor, occupant_jid, role, callback, reason)
852         if role == "none" then role = nil; end
853         if role and role ~= "moderator" and role ~= "participant" and role ~= "visitor" then return nil, "modify", "not-acceptable"; end
854         if self:get_affiliation(actor) ~= "owner" then return nil, "cancel", "not-allowed"; end
855         local occupant = self._occupants[occupant_jid];
856         if not occupant then return nil, "modify", "not-acceptable"; end
857         if occupant.affiliation == "owner" or occupant.affiliation == "admin" then return nil, "cancel", "not-allowed"; end
858         local p = st.presence({from = occupant_jid})
859                 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
860                         :tag("item", {affiliation=occupant.affiliation or "none", nick=select(3, jid_split(occupant_jid)), role=role or "none"})
861                                 :tag("reason"):text(reason or ""):up()
862                         :up();
863         if not role then -- kick
864                 p.attr.type = "unavailable";
865                 self._occupants[occupant_jid] = nil;
866                 for jid in pairs(occupant.sessions) do -- remove for all sessions of the nick
867                         self._jid_nick[jid] = nil;
868                 end
869                 p:tag("status", {code = "307"}):up();
870         else
871                 occupant.role = role;
872         end
873         for jid in pairs(occupant.sessions) do -- send to all sessions of the nick
874                 p.attr.to = jid;
875                 self:_route_stanza(p);
876         end
877         if callback then callback(); end
878         self:broadcast_except_nick(p, occupant_jid);
879         return true;
880 end
881
882 function room_mt:_route_stanza(stanza)
883         local muc_child;
884         local to_occupant = self._occupants[self._jid_nick[stanza.attr.to]];
885         local from_occupant = self._occupants[stanza.attr.from];
886         if stanza.name == "presence" then
887                 if to_occupant and from_occupant then
888                         if self._data.whois == 'anyone' then
889                             muc_child = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
890                         else
891                                 if to_occupant.role == "moderator" or jid_bare(to_occupant.jid) == jid_bare(from_occupant.jid) then
892                                         muc_child = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
893                                 end
894                         end
895                 end
896         end
897         if muc_child then
898                 for _, item in pairs(muc_child.tags) do
899                         if item.name == "item" then
900                                 if from_occupant == to_occupant then
901                                         item.attr.jid = stanza.attr.to;
902                                 else
903                                         item.attr.jid = from_occupant.jid;
904                                 end
905                         end
906                 end
907                 if self._data.whois == 'anyone' then
908                     muc_child:tag('status', { code = '100' });
909                 end
910         end
911         self:route_stanza(stanza);
912         if muc_child then
913                 for _, item in pairs(muc_child.tags) do
914                         if item.name == "item" then
915                                 item.attr.jid = nil;
916                         end
917                 end
918         end
919 end
920
921 local _M = {}; -- module "muc"
922
923 function _M.new_room(jid)
924         return setmetatable({
925                 jid = jid;
926                 _jid_nick = {};
927                 _occupants = {};
928                 _data = {
929                     whois = 'moderators',
930                 };
931                 _affiliations = {};
932         }, room_mt);
933 end
934
935 return _M;