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