e1deab996a48bf30807e58757475f45367ce71e2
[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 select = select;
10 local pairs, ipairs = pairs, ipairs;
11
12 local datetime = require "util.datetime";
13
14 local dataform = require "util.dataforms";
15
16 local jid_split = require "util.jid".split;
17 local jid_bare = require "util.jid".bare;
18 local jid_prep = require "util.jid".prep;
19 local st = require "util.stanza";
20 local log = require "util.logger".init("mod_muc");
21 local t_insert, t_remove = table.insert, table.remove;
22 local setmetatable = setmetatable;
23 local base64 = require "util.encodings".base64;
24 local md5 = require "util.hashes".md5;
25
26 local muc_domain = nil; --module:get_host();
27 local default_history_length, max_history_length = 20, math.huge;
28
29 ------------
30 local presence_filters = {["http://jabber.org/protocol/muc"]=true;["http://jabber.org/protocol/muc#user"]=true};
31 local function presence_filter(tag)
32         if presence_filters[tag.attr.xmlns] then
33                 return nil;
34         end
35         return tag;
36 end
37
38 local function get_filtered_presence(stanza)
39         return st.clone(stanza):maptags(presence_filter);
40 end
41 local kickable_error_conditions = {
42         ["gone"] = true;
43         ["internal-server-error"] = true;
44         ["item-not-found"] = true;
45         ["jid-malformed"] = true;
46         ["recipient-unavailable"] = true;
47         ["redirect"] = true;
48         ["remote-server-not-found"] = true;
49         ["remote-server-timeout"] = true;
50         ["service-unavailable"] = true;
51         ["malformed error"] = true;
52 };
53
54 local function get_error_condition(stanza)
55         local _, condition = stanza:get_error();
56         return condition or "malformed error";
57 end
58
59 local function is_kickable_error(stanza)
60         local cond = get_error_condition(stanza);
61         return kickable_error_conditions[cond] and cond;
62 end
63 -----------
64
65 local room_mt = {};
66 room_mt.__index = room_mt;
67
68 function room_mt:__tostring()
69         return "MUC room ("..self.jid..")";
70 end
71
72 function room_mt:get_default_role(affiliation)
73         if affiliation == "owner" or affiliation == "admin" then
74                 return "moderator";
75         elseif affiliation == "member" then
76                 return "participant";
77         elseif not affiliation then
78                 if not self:get_members_only() then
79                         return self:get_moderated() and "visitor" or "participant";
80                 end
81         end
82 end
83
84 function room_mt:broadcast_presence(stanza, sid, code, nick)
85         stanza = get_filtered_presence(stanza);
86         local occupant = self._occupants[stanza.attr.from];
87         stanza:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
88                 :tag("item", {affiliation=occupant.affiliation or "none", role=occupant.role or "none", nick=nick}):up();
89         if code then
90                 stanza:tag("status", {code=code}):up();
91         end
92         self:broadcast_except_nick(stanza, stanza.attr.from);
93         local me = self._occupants[stanza.attr.from];
94         if me then
95                 stanza:tag("status", {code='110'}):up();
96                 stanza.attr.to = sid;
97                 self:_route_stanza(stanza);
98         end
99 end
100 function room_mt:broadcast_message(stanza, historic)
101         local to = stanza.attr.to;
102         for occupant, o_data in pairs(self._occupants) do
103                 for jid in pairs(o_data.sessions) do
104                         stanza.attr.to = jid;
105                         self:_route_stanza(stanza);
106                 end
107         end
108         stanza.attr.to = to;
109         if historic then -- add to history
110                 local history = self._data['history'];
111                 if not history then history = {}; self._data['history'] = history; end
112                 stanza = st.clone(stanza);
113                 stanza.attr.to = "";
114                 local stamp = datetime.datetime();
115                 stanza:tag("delay", {xmlns = "urn:xmpp:delay", from = muc_domain, stamp = stamp}):up(); -- XEP-0203
116                 stanza:tag("x", {xmlns = "jabber:x:delay", from = muc_domain, stamp = datetime.legacy()}):up(); -- XEP-0091 (deprecated)
117                 local entry = { stanza = stanza, stamp = stamp };
118                 t_insert(history, entry);
119                 while #history > (self._data.history_length or default_history_length) do t_remove(history, 1) end
120         end
121 end
122 function room_mt:broadcast_except_nick(stanza, nick)
123         for rnick, occupant in pairs(self._occupants) do
124                 if rnick ~= nick then
125                         for jid in pairs(occupant.sessions) do
126                                 stanza.attr.to = jid;
127                                 self:_route_stanza(stanza);
128                         end
129                 end
130         end
131 end
132
133 function room_mt:send_occupant_list(to)
134         local current_nick = self._jid_nick[to];
135         for occupant, o_data in pairs(self._occupants) do
136                 if occupant ~= current_nick then
137                         local pres = get_filtered_presence(o_data.sessions[o_data.jid]);
138                         pres.attr.to, pres.attr.from = to, occupant;
139                         pres:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
140                                 :tag("item", {affiliation=o_data.affiliation or "none", role=o_data.role or "none"}):up();
141                         self:_route_stanza(pres);
142                 end
143         end
144 end
145 function room_mt:send_history(to, stanza)
146         local history = self._data['history']; -- send discussion history
147         if history then
148                 local x_tag = stanza and stanza:get_child("x", "http://jabber.org/protocol/muc");
149                 local history_tag = x_tag and x_tag:get_child("history", "http://jabber.org/protocol/muc");
150                 
151                 local maxchars = history_tag and tonumber(history_tag.attr.maxchars);
152                 if maxchars then maxchars = math.floor(maxchars); end
153                 
154                 local maxstanzas = math.floor(history_tag and tonumber(history_tag.attr.maxstanzas) or #history);
155                 if not history_tag then maxstanzas = 20; end
156
157                 local seconds = history_tag and tonumber(history_tag.attr.seconds);
158                 if seconds then seconds = datetime.datetime(os.time() - math.floor(seconds)); end
159
160                 local since = history_tag and history_tag.attr.since;
161                 if since then since = datetime.parse(since); since = since and datetime.datetime(since); end
162                 if seconds and (not since or since < seconds) then since = seconds; end
163
164                 local n = 0;
165                 local charcount = 0;
166                 
167                 for i=#history,1,-1 do
168                         local entry = history[i];
169                         if maxchars then
170                                 if not entry.chars then
171                                         entry.stanza.attr.to = "";
172                                         entry.chars = #tostring(entry.stanza);
173                                 end
174                                 charcount = charcount + entry.chars + #to;
175                                 if charcount > maxchars then break; end
176                         end
177                         if since and since > entry.stamp then break; end
178                         if n + 1 > maxstanzas then break; end
179                         n = n + 1;
180                 end
181                 for i=#history-n+1,#history do
182                         local msg = history[i].stanza;
183                         msg.attr.to = to;
184                         self:_route_stanza(msg);
185                 end
186         end
187         if self._data['subject'] then
188                 self:_route_stanza(st.message({type='groupchat', from=self._data['subject_from'] or self.jid, to=to}):tag("subject"):text(self._data['subject']));
189         end
190 end
191
192 function room_mt:get_disco_info(stanza)
193         local count = 0; for _ in pairs(self._occupants) do count = count + 1; end
194         return st.reply(stanza):query("http://jabber.org/protocol/disco#info")
195                 :tag("identity", {category="conference", type="text", name=self:get_name()}):up()
196                 :tag("feature", {var="http://jabber.org/protocol/muc"}):up()
197                 :tag("feature", {var=self:get_password() and "muc_passwordprotected" or "muc_unsecured"}):up()
198                 :tag("feature", {var=self:get_moderated() and "muc_moderated" or "muc_unmoderated"}):up()
199                 :tag("feature", {var=self:get_members_only() and "muc_membersonly" or "muc_open"}):up()
200                 :tag("feature", {var=self:get_persistent() and "muc_persistent" or "muc_temporary"}):up()
201                 :tag("feature", {var=self:get_hidden() and "muc_hidden" or "muc_public"}):up()
202                 :tag("feature", {var=self._data.whois ~= "anyone" and "muc_semianonymous" or "muc_nonanonymous"}):up()
203                 :add_child(dataform.new({
204                         { name = "FORM_TYPE", type = "hidden", value = "http://jabber.org/protocol/muc#roominfo" },
205                         { name = "muc#roominfo_description", label = "Description"},
206                         { name = "muc#roominfo_occupants", label = "Number of occupants", value = tostring(count) }
207                 }):form({["muc#roominfo_description"] = self:get_description()}, 'result'))
208         ;
209 end
210 function room_mt:get_disco_items(stanza)
211         local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#items");
212         for room_jid in pairs(self._occupants) do
213                 reply:tag("item", {jid = room_jid, name = room_jid:match("/(.*)")}):up();
214         end
215         return reply;
216 end
217 function room_mt:set_subject(current_nick, subject)
218         -- TODO check nick's authority
219         if subject == "" then subject = nil; end
220         self._data['subject'] = subject;
221         self._data['subject_from'] = current_nick;
222         if self.save then self:save(); end
223         local msg = st.message({type='groupchat', from=current_nick})
224                 :tag('subject'):text(subject):up();
225         self:broadcast_message(msg, false);
226         return true;
227 end
228
229 local function build_unavailable_presence_from_error(stanza)
230         local type, condition, text = stanza:get_error();
231         local error_message = "Kicked: "..(condition and condition:gsub("%-", " ") or "presence error");
232         if text then
233                 error_message = error_message..": "..text;
234         end
235         return st.presence({type='unavailable', from=stanza.attr.from, to=stanza.attr.to})
236                 :tag('status'):text(error_message);
237 end
238
239 function room_mt:set_name(name)
240         if name == "" or type(name) ~= "string" or name == (jid_split(self.jid)) then name = nil; end
241         if self._data.name ~= name then
242                 self._data.name = name;
243                 if self.save then self:save(true); end
244         end
245 end
246 function room_mt:get_name()
247         return self._data.name or jid_split(self.jid);
248 end
249 function room_mt:set_description(description)
250         if description == "" or type(description) ~= "string" then description = nil; end
251         if self._data.description ~= description then
252                 self._data.description = description;
253                 if self.save then self:save(true); end
254         end
255 end
256 function room_mt:get_description()
257         return self._data.description;
258 end
259 function room_mt:set_password(password)
260         if password == "" or type(password) ~= "string" then password = nil; end
261         if self._data.password ~= password then
262                 self._data.password = password;
263                 if self.save then self:save(true); end
264         end
265 end
266 function room_mt:get_password()
267         return self._data.password;
268 end
269 function room_mt:set_moderated(moderated)
270         moderated = moderated and true or nil;
271         if self._data.moderated ~= moderated then
272                 self._data.moderated = moderated;
273                 if self.save then self:save(true); end
274         end
275 end
276 function room_mt:get_moderated()
277         return self._data.moderated;
278 end
279 function room_mt:set_members_only(members_only)
280         members_only = members_only and true or nil;
281         if self._data.members_only ~= members_only then
282                 self._data.members_only = members_only;
283                 if self.save then self:save(true); end
284         end
285 end
286 function room_mt:get_members_only()
287         return self._data.members_only;
288 end
289 function room_mt:set_persistent(persistent)
290         persistent = persistent and true or nil;
291         if self._data.persistent ~= persistent then
292                 self._data.persistent = persistent;
293                 if self.save then self:save(true); end
294         end
295 end
296 function room_mt:get_persistent()
297         return self._data.persistent;
298 end
299 function room_mt:set_hidden(hidden)
300         hidden = hidden and true or nil;
301         if self._data.hidden ~= hidden then
302                 self._data.hidden = hidden;
303                 if self.save then self:save(true); end
304         end
305 end
306 function room_mt:get_hidden()
307         return self._data.hidden;
308 end
309 function room_mt:get_public()
310         return not self:get_hidden();
311 end
312 function room_mt:set_public(public)
313         return self:set_hidden(not public);
314 end
315 function room_mt:set_changesubject(changesubject)
316         changesubject = changesubject and true or nil;
317         if self._data.changesubject ~= changesubject then
318                 self._data.changesubject = changesubject;
319                 if self.save then self:save(true); end
320         end
321 end
322 function room_mt:get_changesubject()
323         return self._data.changesubject;
324 end
325 function room_mt:get_historylength()
326         return self._data.history_length or default_history_length;
327 end
328 function room_mt:set_historylength(length)
329         length = math.min(tonumber(length) or default_history_length, max_history_length or math.huge);
330         if length == default_history_length then
331                 length = nil;
332         end
333         self._data.history_length = length;
334 end
335
336
337 local valid_whois = { moderators = true, anyone = true };
338
339 function room_mt:set_whois(whois)
340         if valid_whois[whois] and self._data.whois ~= whois then
341                 self._data.whois = whois;
342                 if self.save then self:save(true); end
343         end
344 end
345
346 function room_mt:get_whois()
347         return self._data.whois;
348 end
349
350 local function construct_stanza_id(room, stanza)
351         local from_jid, to_nick = stanza.attr.from, stanza.attr.to;
352         local from_nick = room._jid_nick[from_jid];
353         local occupant = room._occupants[to_nick];
354         local to_jid = occupant.jid;
355         
356         return from_nick, to_jid, base64.encode(to_jid.."\0"..stanza.attr.id.."\0"..md5(from_jid));
357 end
358 local function deconstruct_stanza_id(room, stanza)
359         local from_jid_possiblybare, to_nick = stanza.attr.from, stanza.attr.to;
360         local from_jid, id, to_jid_hash = (base64.decode(stanza.attr.id) or ""):match("^(.+)%z(.*)%z(.+)$");
361         local from_nick = room._jid_nick[from_jid];
362
363         if not(from_nick) then return; end
364         if not(from_jid_possiblybare == from_jid or from_jid_possiblybare == jid_bare(from_jid)) then return; end
365
366         local occupant = room._occupants[to_nick];
367         for to_jid in pairs(occupant and occupant.sessions or {}) do
368                 if md5(to_jid) == to_jid_hash then
369                         return from_nick, to_jid, id;
370                 end
371         end
372 end
373
374
375 function room_mt:handle_to_occupant(origin, stanza) -- PM, vCards, etc
376         local from, to = stanza.attr.from, stanza.attr.to;
377         local room = jid_bare(to);
378         local current_nick = self._jid_nick[from];
379         local type = stanza.attr.type;
380         log("debug", "room: %s, current_nick: %s, stanza: %s", room or "nil", current_nick or "nil", stanza:top_tag());
381         if (select(2, jid_split(from)) == muc_domain) then error("Presence from the MUC itself!!!"); end
382         if stanza.name == "presence" then
383                 local pr = get_filtered_presence(stanza);
384                 pr.attr.from = current_nick;
385                 if type == "error" then -- error, kick em out!
386                         if current_nick then
387                                 log("debug", "kicking %s from %s", current_nick, room);
388                                 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza));
389                         end
390                 elseif type == "unavailable" then -- unavailable
391                         if current_nick then
392                                 log("debug", "%s leaving %s", current_nick, room);
393                                 self._jid_nick[from] = nil;
394                                 local occupant = self._occupants[current_nick];
395                                 local new_jid = next(occupant.sessions);
396                                 if new_jid == from then new_jid = next(occupant.sessions, new_jid); end
397                                 if new_jid then
398                                         local jid = occupant.jid;
399                                         occupant.jid = new_jid;
400                                         occupant.sessions[from] = nil;
401                                         pr.attr.to = from;
402                                         pr:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
403                                                 :tag("item", {affiliation=occupant.affiliation or "none", role='none'}):up()
404                                                 :tag("status", {code='110'}):up();
405                                         self:_route_stanza(pr);
406                                         if jid ~= new_jid then
407                                                 pr = st.clone(occupant.sessions[new_jid])
408                                                         :tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
409                                                         :tag("item", {affiliation=occupant.affiliation or "none", role=occupant.role or "none"});
410                                                 pr.attr.from = current_nick;
411                                                 self:broadcast_except_nick(pr, current_nick);
412                                         end
413                                 else
414                                         occupant.role = 'none';
415                                         self:broadcast_presence(pr, from);
416                                         self._occupants[current_nick] = nil;
417                                 end
418                         end
419                 elseif not type then -- available
420                         if current_nick then
421                                 --if #pr == #stanza or current_nick ~= to then -- commented because google keeps resending directed presence
422                                         if current_nick == to then -- simple presence
423                                                 log("debug", "%s broadcasted presence", current_nick);
424                                                 self._occupants[current_nick].sessions[from] = pr;
425                                                 self:broadcast_presence(pr, from);
426                                         else -- change nick
427                                                 local occupant = self._occupants[current_nick];
428                                                 local is_multisession = next(occupant.sessions, next(occupant.sessions));
429                                                 if self._occupants[to] or is_multisession then
430                                                         log("debug", "%s couldn't change nick", current_nick);
431                                                         local reply = st.error_reply(stanza, "cancel", "conflict"):up();
432                                                         reply.tags[1].attr.code = "409";
433                                                         origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
434                                                 else
435                                                         local data = self._occupants[current_nick];
436                                                         local to_nick = select(3, jid_split(to));
437                                                         if to_nick then
438                                                                 log("debug", "%s (%s) changing nick to %s", current_nick, data.jid, to);
439                                                                 local p = st.presence({type='unavailable', from=current_nick});
440                                                                 self:broadcast_presence(p, from, '303', to_nick);
441                                                                 self._occupants[current_nick] = nil;
442                                                                 self._occupants[to] = data;
443                                                                 self._jid_nick[from] = to;
444                                                                 pr.attr.from = to;
445                                                                 self._occupants[to].sessions[from] = pr;
446                                                                 self:broadcast_presence(pr, from);
447                                                         else
448                                                                 --TODO malformed-jid
449                                                         end
450                                                 end
451                                         end
452                                 --else -- possible rejoin
453                                 --      log("debug", "%s had connection replaced", current_nick);
454                                 --      self:handle_to_occupant(origin, st.presence({type='unavailable', from=from, to=to})
455                                 --              :tag('status'):text('Replaced by new connection'):up()); -- send unavailable
456                                 --      self:handle_to_occupant(origin, stanza); -- resend available
457                                 --end
458                         else -- enter room
459                                 local new_nick = to;
460                                 local is_merge;
461                                 if self._occupants[to] then
462                                         if jid_bare(from) ~= jid_bare(self._occupants[to].jid) then
463                                                 new_nick = nil;
464                                         end
465                                         is_merge = true;
466                                 end
467                                 local password = stanza:get_child("x", "http://jabber.org/protocol/muc");
468                                 password = password and password:get_child("password", "http://jabber.org/protocol/muc");
469                                 password = password and password[1] ~= "" and password[1];
470                                 if self:get_password() and self:get_password() ~= password then
471                                         log("debug", "%s couldn't join due to invalid password: %s", from, to);
472                                         local reply = st.error_reply(stanza, "auth", "not-authorized"):up();
473                                         reply.tags[1].attr.code = "401";
474                                         origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
475                                 elseif not new_nick then
476                                         log("debug", "%s couldn't join due to nick conflict: %s", from, to);
477                                         local reply = st.error_reply(stanza, "cancel", "conflict"):up();
478                                         reply.tags[1].attr.code = "409";
479                                         origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
480                                 else
481                                         log("debug", "%s joining as %s", from, to);
482                                         if not next(self._affiliations) then -- new room, no owners
483                                                 self._affiliations[jid_bare(from)] = "owner";
484                                         end
485                                         local affiliation = self:get_affiliation(from);
486                                         local role = self:get_default_role(affiliation)
487                                         if role then -- new occupant
488                                                 if not is_merge then
489                                                         self._occupants[to] = {affiliation=affiliation, role=role, jid=from, sessions={[from]=get_filtered_presence(stanza)}};
490                                                 else
491                                                         self._occupants[to].sessions[from] = get_filtered_presence(stanza);
492                                                 end
493                                                 self._jid_nick[from] = to;
494                                                 self:send_occupant_list(from);
495                                                 pr.attr.from = to;
496                                                 pr:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
497                                                         :tag("item", {affiliation=affiliation or "none", role=role or "none"}):up();
498                                                 if not is_merge then
499                                                         self:broadcast_except_nick(pr, to);
500                                                 end
501                                                 pr:tag("status", {code='110'}):up();
502                                                 if self._data.whois == 'anyone' then
503                                                         pr:tag("status", {code='100'}):up();
504                                                 end
505                                                 pr.attr.to = from;
506                                                 self:_route_stanza(pr);
507                                                 self:send_history(from, stanza);
508                                         elseif not affiliation then -- registration required for entering members-only room
509                                                 local reply = st.error_reply(stanza, "auth", "registration-required"):up();
510                                                 reply.tags[1].attr.code = "407";
511                                                 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
512                                         else -- banned
513                                                 local reply = st.error_reply(stanza, "auth", "forbidden"):up();
514                                                 reply.tags[1].attr.code = "403";
515                                                 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
516                                         end
517                                 end
518                         end
519                 elseif type ~= 'result' then -- bad type
520                         if type ~= 'visible' and type ~= 'invisible' then -- COMPAT ejabberd can broadcast or forward XEP-0018 presences
521                                 origin.send(st.error_reply(stanza, "modify", "bad-request")); -- FIXME correct error?
522                         end
523                 end
524         elseif not current_nick then -- not in room
525                 if (type == "error" or type == "result") and stanza.name == "iq" then
526                         local id = stanza.attr.id;
527                         stanza.attr.from, stanza.attr.to, stanza.attr.id = deconstruct_stanza_id(self, stanza);
528                         if stanza.attr.id then
529                                 self:_route_stanza(stanza);
530                         end
531                         stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
532                 elseif type ~= "error" then
533                         origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
534                 end
535         elseif stanza.name == "message" and type == "groupchat" then -- groupchat messages not allowed in PM
536                 origin.send(st.error_reply(stanza, "modify", "bad-request"));
537         elseif current_nick and stanza.name == "message" and type == "error" and is_kickable_error(stanza) then
538                 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
539                 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza)); -- send unavailable
540         else -- private stanza
541                 local o_data = self._occupants[to];
542                 if o_data then
543                         log("debug", "%s sent private stanza to %s (%s)", from, to, o_data.jid);
544                         if stanza.name == "iq" then
545                                 local id = stanza.attr.id;
546                                 if stanza.attr.type == "get" or stanza.attr.type == "set" then
547                                         stanza.attr.from, stanza.attr.to, stanza.attr.id = construct_stanza_id(self, stanza);
548                                 else
549                                         stanza.attr.from, stanza.attr.to, stanza.attr.id = deconstruct_stanza_id(self, stanza);
550                                 end
551                                 if type == 'get' and stanza.tags[1].attr.xmlns == 'vcard-temp' then
552                                         stanza.attr.to = jid_bare(stanza.attr.to);
553                                 end
554                                 if stanza.attr.id then
555                                         self:_route_stanza(stanza);
556                                 end
557                                 stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
558                         else -- message
559                                 stanza.attr.from = current_nick;
560                                 for jid in pairs(o_data.sessions) do
561                                         stanza.attr.to = jid;
562                                         self:_route_stanza(stanza);
563                                 end
564                                 stanza.attr.from, stanza.attr.to = from, to;
565                         end
566                 elseif type ~= "error" and type ~= "result" then -- recipient not in room
567                         origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
568                 end
569         end
570 end
571
572 function room_mt:send_form(origin, stanza)
573         origin.send(st.reply(stanza):query("http://jabber.org/protocol/muc#owner")
574                 :add_child(self:get_form_layout(stanza.attr.from):form())
575         );
576 end
577
578 function room_mt:get_form_layout(actor)
579         local form = dataform.new({
580                 title = "Configuration for "..self.jid,
581                 instructions = "Complete and submit this form to configure the room.",
582                 {
583                         name = 'FORM_TYPE',
584                         type = 'hidden',
585                         value = 'http://jabber.org/protocol/muc#roomconfig'
586                 },
587                 {
588                         name = 'muc#roomconfig_roomname',
589                         type = 'text-single',
590                         label = 'Name',
591                         value = self:get_name() or "",
592                 },
593                 {
594                         name = 'muc#roomconfig_roomdesc',
595                         type = 'text-single',
596                         label = 'Description',
597                         value = self:get_description() or "",
598                 },
599                 {
600                         name = 'muc#roomconfig_persistentroom',
601                         type = 'boolean',
602                         label = 'Make Room Persistent?',
603                         value = self:get_persistent()
604                 },
605                 {
606                         name = 'muc#roomconfig_publicroom',
607                         type = 'boolean',
608                         label = 'Make Room Publicly Searchable?',
609                         value = not self:get_hidden()
610                 },
611                 {
612                         name = 'muc#roomconfig_changesubject',
613                         type = 'boolean',
614                         label = 'Allow Occupants to Change Subject?',
615                         value = self:get_changesubject()
616                 },
617                 {
618                         name = 'muc#roomconfig_whois',
619                         type = 'list-single',
620                         label = 'Who May Discover Real JIDs?',
621                         value = {
622                                 { value = 'moderators', label = 'Moderators Only', default = self._data.whois == 'moderators' },
623                                 { value = 'anyone',     label = 'Anyone',          default = self._data.whois == 'anyone' }
624                         }
625                 },
626                 {
627                         name = 'muc#roomconfig_roomsecret',
628                         type = 'text-private',
629                         label = 'Password',
630                         value = self:get_password() or "",
631                 },
632                 {
633                         name = 'muc#roomconfig_moderatedroom',
634                         type = 'boolean',
635                         label = 'Make Room Moderated?',
636                         value = self:get_moderated()
637                 },
638                 {
639                         name = 'muc#roomconfig_membersonly',
640                         type = 'boolean',
641                         label = 'Make Room Members-Only?',
642                         value = self:get_members_only()
643                 },
644                 {
645                         name = 'muc#roomconfig_historylength',
646                         type = 'text-single',
647                         label = 'Maximum Number of History Messages Returned by Room',
648                         value = tostring(self:get_historylength())
649                 }
650         });
651         return module:fire_event("muc-config-form", { room = self, actor = actor, form = form }) or form;
652 end
653
654 function room_mt:process_form(origin, stanza)
655         local query = stanza.tags[1];
656         local form;
657         for _, tag in ipairs(query.tags) do if tag.name == "x" and tag.attr.xmlns == "jabber:x:data" then form = tag; break; end end
658         if not form then origin.send(st.error_reply(stanza, "cancel", "service-unavailable")); return; end
659         if form.attr.type == "cancel" then origin.send(st.reply(stanza)); return; end
660         if form.attr.type ~= "submit" then origin.send(st.error_reply(stanza, "cancel", "bad-request", "Not a submitted form")); return; end
661
662         local fields = self:get_form_layout(stanza.attr.from):data(form);
663         if fields.FORM_TYPE ~= "http://jabber.org/protocol/muc#roomconfig" then origin.send(st.error_reply(stanza, "cancel", "bad-request", "Form is not of type room configuration")); return; end
664
665
666         local changed = {};
667
668         local function handle_option(name, field, allowed)
669                 local new = fields[field];
670                 if new == nil then return; end
671                 if allowed and not allowed[new] then return; end
672                 if new == self["get_"..name](self) then return; end
673                 changed[name] = true;
674                 self["set_"..name](self, new);
675         end
676
677         local event = { room = self, fields = fields, changed = changed, stanza = stanza, origin = origin, update_option = handle_option };
678         module:fire_event("muc-config-submitted", event);
679
680         handle_option("name", "muc#roomconfig_roomname");
681         handle_option("description", "muc#roomconfig_roomdesc");
682         handle_option("persistent", "muc#roomconfig_persistentroom");
683         handle_option("moderated", "muc#roomconfig_moderatedroom");
684         handle_option("members_only", "muc#roomconfig_membersonly");
685         handle_option("public", "muc#roomconfig_publicroom");
686         handle_option("changesubject", "muc#roomconfig_changesubject");
687         handle_option("historylength", "muc#roomconfig_historylength");
688         handle_option("whois", "muc#roomconfig_whois", valid_whois);
689         handle_option("password", "muc#roomconfig_roomsecret");
690
691         if self.save then self:save(true); end
692         origin.send(st.reply(stanza));
693
694         if next(changed) then
695                 local msg = st.message({type='groupchat', from=self.jid})
696                         :tag('x', {xmlns='http://jabber.org/protocol/muc#user'}):up()
697                                 :tag('status', {code = '104'}):up();
698                 if changed.whois then
699                         local code = (self:get_whois() == 'moderators') and "173" or "172";
700                         msg.tags[1]:tag('status', {code = code}):up();
701                 end
702                 self:broadcast_message(msg, false)
703         end
704 end
705
706 function room_mt:destroy(newjid, reason, password)
707         local pr = st.presence({type = "unavailable"})
708                 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
709                         :tag("item", { affiliation='none', role='none' }):up()
710                         :tag("destroy", {jid=newjid})
711         if reason then pr:tag("reason"):text(reason):up(); end
712         if password then pr:tag("password"):text(password):up(); end
713         for nick, occupant in pairs(self._occupants) do
714                 pr.attr.from = nick;
715                 for jid in pairs(occupant.sessions) do
716                         pr.attr.to = jid;
717                         self:_route_stanza(pr);
718                         self._jid_nick[jid] = nil;
719                 end
720                 self._occupants[nick] = nil;
721         end
722         self:set_persistent(false);
723         module:fire_event("muc-room-destroyed", { room = self });
724 end
725
726 function room_mt:handle_to_room(origin, stanza) -- presence changes and groupchat messages, along with disco/etc
727         local type = stanza.attr.type;
728         local xmlns = stanza.tags[1] and stanza.tags[1].attr.xmlns;
729         if stanza.name == "iq" then
730                 if xmlns == "http://jabber.org/protocol/disco#info" and type == "get" and not stanza.tags[1].attr.node then
731                         origin.send(self:get_disco_info(stanza));
732                 elseif xmlns == "http://jabber.org/protocol/disco#items" and type == "get" and not stanza.tags[1].attr.node then
733                         origin.send(self:get_disco_items(stanza));
734                 elseif xmlns == "http://jabber.org/protocol/muc#admin" then
735                         local actor = stanza.attr.from;
736                         local affiliation = self:get_affiliation(actor);
737                         local current_nick = self._jid_nick[actor];
738                         local role = current_nick and self._occupants[current_nick].role or self:get_default_role(affiliation);
739                         local item = stanza.tags[1].tags[1];
740                         if item and item.name == "item" then
741                                 if type == "set" then
742                                         local callback = function() origin.send(st.reply(stanza)); end
743                                         if item.attr.jid then -- Validate provided JID
744                                                 item.attr.jid = jid_prep(item.attr.jid);
745                                                 if not item.attr.jid then
746                                                         origin.send(st.error_reply(stanza, "modify", "jid-malformed"));
747                                                         return;
748                                                 end
749                                         end
750                                         if not item.attr.jid and item.attr.nick then -- COMPAT Workaround for Miranda sending 'nick' instead of 'jid' when changing affiliation
751                                                 local occupant = self._occupants[self.jid.."/"..item.attr.nick];
752                                                 if occupant then item.attr.jid = occupant.jid; end
753                                         elseif not item.attr.nick and item.attr.jid then
754                                                 local nick = self._jid_nick[item.attr.jid];
755                                                 if nick then item.attr.nick = select(3, jid_split(nick)); end
756                                         end
757                                         local reason = item.tags[1] and item.tags[1].name == "reason" and #item.tags[1] == 1 and item.tags[1][1];
758                                         if item.attr.affiliation and item.attr.jid and not item.attr.role then
759                                                 local success, errtype, err = self:set_affiliation(actor, item.attr.jid, item.attr.affiliation, callback, reason);
760                                                 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
761                                         elseif item.attr.role and item.attr.nick and not item.attr.affiliation then
762                                                 local success, errtype, err = self:set_role(actor, self.jid.."/"..item.attr.nick, item.attr.role, callback, reason);
763                                                 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
764                                         else
765                                                 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
766                                         end
767                                 elseif type == "get" then
768                                         local _aff = item.attr.affiliation;
769                                         local _rol = item.attr.role;
770                                         if _aff and not _rol then
771                                                 if affiliation == "owner" or (affiliation == "admin" and _aff ~= "owner" and _aff ~= "admin") then
772                                                         local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
773                                                         for jid, affiliation in pairs(self._affiliations) do
774                                                                 if affiliation == _aff then
775                                                                         reply:tag("item", {affiliation = _aff, jid = jid}):up();
776                                                                 end
777                                                         end
778                                                         origin.send(reply);
779                                                 else
780                                                         origin.send(st.error_reply(stanza, "auth", "forbidden"));
781                                                 end
782                                         elseif _rol and not _aff then
783                                                 if role == "moderator" then
784                                                         -- TODO allow admins and owners not in room? Provide read-only access to everyone who can see the participants anyway?
785                                                         if _rol == "none" then _rol = nil; end
786                                                         local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
787                                                         for occupant_jid, occupant in pairs(self._occupants) do
788                                                                 if occupant.role == _rol then
789                                                                         reply:tag("item", {
790                                                                                 nick = select(3, jid_split(occupant_jid)),
791                                                                                 role = _rol or "none",
792                                                                                 affiliation = occupant.affiliation or "none",
793                                                                                 jid = occupant.jid
794                                                                                 }):up();
795                                                                 end
796                                                         end
797                                                         origin.send(reply);
798                                                 else
799                                                         origin.send(st.error_reply(stanza, "auth", "forbidden"));
800                                                 end
801                                         else
802                                                 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
803                                         end
804                                 end
805                         elseif type == "set" or type == "get" then
806                                 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
807                         end
808                 elseif xmlns == "http://jabber.org/protocol/muc#owner" and (type == "get" or type == "set") and stanza.tags[1].name == "query" then
809                         if self:get_affiliation(stanza.attr.from) ~= "owner" then
810                                 origin.send(st.error_reply(stanza, "auth", "forbidden", "Only owners can configure rooms"));
811                         elseif stanza.attr.type == "get" then
812                                 self:send_form(origin, stanza);
813                         elseif stanza.attr.type == "set" then
814                                 local child = stanza.tags[1].tags[1];
815                                 if not child then
816                                         origin.send(st.error_reply(stanza, "modify", "bad-request"));
817                                 elseif child.name == "destroy" then
818                                         local newjid = child.attr.jid;
819                                         local reason, password;
820                                         for _,tag in ipairs(child.tags) do
821                                                 if tag.name == "reason" then
822                                                         reason = #tag.tags == 0 and tag[1];
823                                                 elseif tag.name == "password" then
824                                                         password = #tag.tags == 0 and tag[1];
825                                                 end
826                                         end
827                                         self:destroy(newjid, reason, password);
828                                         origin.send(st.reply(stanza));
829                                 else
830                                         self:process_form(origin, stanza);
831                                 end
832                         end
833                 elseif type == "set" or type == "get" then
834                         origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
835                 end
836         elseif stanza.name == "message" and type == "groupchat" then
837                 local from = stanza.attr.from;
838                 local current_nick = self._jid_nick[from];
839                 local occupant = self._occupants[current_nick];
840                 if not occupant then -- not in room
841                         origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
842                 elseif occupant.role == "visitor" then
843                         origin.send(st.error_reply(stanza, "auth", "forbidden"));
844                 else
845                         local from = stanza.attr.from;
846                         stanza.attr.from = current_nick;
847                         local subject = stanza:get_child_text("subject");
848                         if subject then
849                                 if occupant.role == "moderator" or
850                                         ( self._data.changesubject and occupant.role == "participant" ) then -- and participant
851                                         self:set_subject(current_nick, subject); -- TODO use broadcast_message_stanza
852                                 else
853                                         stanza.attr.from = from;
854                                         origin.send(st.error_reply(stanza, "auth", "forbidden"));
855                                 end
856                         else
857                                 self:broadcast_message(stanza, self:get_historylength() > 0 and stanza:get_child("body"));
858                         end
859                         stanza.attr.from = from;
860                 end
861         elseif stanza.name == "message" and type == "error" and is_kickable_error(stanza) then
862                 local current_nick = self._jid_nick[stanza.attr.from];
863                 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
864                 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza)); -- send unavailable
865         elseif stanza.name == "presence" then -- hack - some buggy clients send presence updates to the room rather than their nick
866                 local to = stanza.attr.to;
867                 local current_nick = self._jid_nick[stanza.attr.from];
868                 if current_nick then
869                         stanza.attr.to = current_nick;
870                         self:handle_to_occupant(origin, stanza);
871                         stanza.attr.to = to;
872                 elseif type ~= "error" and type ~= "result" then
873                         origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
874                 end
875         elseif stanza.name == "message" and not(type == "chat" or type == "error" or type == "groupchat" or type == "headline") and #stanza.tags == 1
876                 and self._jid_nick[stanza.attr.from] and stanza.tags[1].name == "x" and stanza.tags[1].attr.xmlns == "http://jabber.org/protocol/muc#user" then
877                 local x = stanza.tags[1];
878                 local payload = (#x.tags == 1 and x.tags[1]);
879                 if payload and payload.name == "invite" and payload.attr.to then
880                         local _from, _to = stanza.attr.from, stanza.attr.to;
881                         local _invitee = jid_prep(payload.attr.to);
882                         if _invitee then
883                                 local _reason = payload.tags[1] and payload.tags[1].name == 'reason' and #payload.tags[1].tags == 0 and payload.tags[1][1];
884                                 local invite = st.message({from = _to, to = _invitee, id = stanza.attr.id})
885                                         :tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
886                                                 :tag('invite', {from=_from})
887                                                         :tag('reason'):text(_reason or ""):up()
888                                                 :up();
889                                                 if self:get_password() then
890                                                         invite:tag("password"):text(self:get_password()):up();
891                                                 end
892                                         invite:up()
893                                         :tag('x', {xmlns="jabber:x:conference", jid=_to}) -- COMPAT: Some older clients expect this
894                                                 :text(_reason or "")
895                                         :up()
896                                         :tag('body') -- Add a plain message for clients which don't support invites
897                                                 :text(_from..' invited you to the room '.._to..(_reason and (' ('.._reason..')') or ""))
898                                         :up();
899                                 if self:get_members_only() and not self:get_affiliation(_invitee) then
900                                         log("debug", "%s invited %s into members only room %s, granting membership", _from, _invitee, _to);
901                                         self:set_affiliation(_from, _invitee, "member", nil, "Invited by " .. self._jid_nick[_from])
902                                 end
903                                 self:_route_stanza(invite);
904                         else
905                                 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
906                         end
907                 else
908                         origin.send(st.error_reply(stanza, "cancel", "bad-request"));
909                 end
910         else
911                 if type == "error" or type == "result" then return; end
912                 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
913         end
914 end
915
916 function room_mt:handle_stanza(origin, stanza)
917         local to_node, to_host, to_resource = jid_split(stanza.attr.to);
918         if to_resource then
919                 self:handle_to_occupant(origin, stanza);
920         else
921                 self:handle_to_room(origin, stanza);
922         end
923 end
924
925 function room_mt:route_stanza(stanza) end -- Replace with a routing function, e.g., function(room, stanza) core_route_stanza(origin, stanza); end
926
927 function room_mt:get_affiliation(jid)
928         local node, host, resource = jid_split(jid);
929         local bare = node and node.."@"..host or host;
930         local result = self._affiliations[bare]; -- Affiliations are granted, revoked, and maintained based on the user's bare JID.
931         if not result and self._affiliations[host] == "outcast" then result = "outcast"; end -- host banned
932         return result;
933 end
934 function room_mt:set_affiliation(actor, jid, affiliation, callback, reason)
935         jid = jid_bare(jid);
936         if affiliation == "none" then affiliation = nil; end
937         if affiliation and affiliation ~= "outcast" and affiliation ~= "owner" and affiliation ~= "admin" and affiliation ~= "member" then
938                 return nil, "modify", "not-acceptable";
939         end
940         if actor ~= true then
941                 local actor_affiliation = self:get_affiliation(actor);
942                 local target_affiliation = self:get_affiliation(jid);
943                 if target_affiliation == affiliation then -- no change, shortcut
944                         if callback then callback(); end
945                         return true;
946                 end
947                 if actor_affiliation ~= "owner" then
948                         if affiliation == "owner" or affiliation == "admin" or actor_affiliation ~= "admin" or target_affiliation == "owner" or target_affiliation == "admin" then
949                                 return nil, "cancel", "not-allowed";
950                         end
951                 elseif target_affiliation == "owner" and jid_bare(actor) == jid then -- self change
952                         local is_last = true;
953                         for j, aff in pairs(self._affiliations) do if j ~= jid and aff == "owner" then is_last = false; break; end end
954                         if is_last then
955                                 return nil, "cancel", "conflict";
956                         end
957                 end
958         end
959         self._affiliations[jid] = affiliation;
960         local role = self:get_default_role(affiliation);
961         local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"})
962                         :tag("item", {affiliation=affiliation or "none", role=role or "none"})
963                                 :tag("reason"):text(reason or ""):up()
964                         :up();
965         local presence_type = nil;
966         if not role then -- getting kicked
967                 presence_type = "unavailable";
968                 if affiliation == "outcast" then
969                         x:tag("status", {code="301"}):up(); -- banned
970                 else
971                         x:tag("status", {code="321"}):up(); -- affiliation change
972                 end
973         end
974         local modified_nicks = {};
975         for nick, occupant in pairs(self._occupants) do
976                 if jid_bare(occupant.jid) == jid then
977                         if not role then -- getting kicked
978                                 self._occupants[nick] = nil;
979                         else
980                                 occupant.affiliation, occupant.role = affiliation, role;
981                         end
982                         for jid,pres in pairs(occupant.sessions) do -- remove for all sessions of the nick
983                                 if not role then self._jid_nick[jid] = nil; end
984                                 local p = st.clone(pres);
985                                 p.attr.from = nick;
986                                 p.attr.type = presence_type;
987                                 p.attr.to = jid;
988                                 p:add_child(x);
989                                 self:_route_stanza(p);
990                                 if occupant.jid == jid then
991                                         modified_nicks[nick] = p;
992                                 end
993                         end
994                 end
995         end
996         if self.save then self:save(); end
997         if callback then callback(); end
998         for nick,p in pairs(modified_nicks) do
999                 p.attr.from = nick;
1000                 self:broadcast_except_nick(p, nick);
1001         end
1002         return true;
1003 end
1004
1005 function room_mt:get_role(nick)
1006         local session = self._occupants[nick];
1007         return session and session.role or nil;
1008 end
1009 function room_mt:can_set_role(actor_jid, occupant_jid, role)
1010         local occupant = self._occupants[occupant_jid];
1011         if not occupant or not actor_jid then return nil, "modify", "not-acceptable"; end
1012
1013         if actor_jid == true then return true; end
1014
1015         local actor = self._occupants[self._jid_nick[actor_jid]];
1016         if actor.role == "moderator" then
1017                 if occupant.affiliation ~= "owner" and occupant.affiliation ~= "admin" then
1018                         if actor.affiliation == "owner" or actor.affiliation == "admin" then
1019                                 return true;
1020                         elseif occupant.role ~= "moderator" and role ~= "moderator" then
1021                                 return true;
1022                         end
1023                 end
1024         end
1025         return nil, "cancel", "not-allowed";
1026 end
1027 function room_mt:set_role(actor, occupant_jid, role, callback, reason)
1028         if role == "none" then role = nil; end
1029         if role and role ~= "moderator" and role ~= "participant" and role ~= "visitor" then return nil, "modify", "not-acceptable"; end
1030         local allowed, err_type, err_condition = self:can_set_role(actor, occupant_jid, role);
1031         if not allowed then return allowed, err_type, err_condition; end
1032         local occupant = self._occupants[occupant_jid];
1033         local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"})
1034                         :tag("item", {affiliation=occupant.affiliation or "none", nick=select(3, jid_split(occupant_jid)), role=role or "none"})
1035                                 :tag("reason"):text(reason or ""):up()
1036                         :up();
1037         local presence_type = nil;
1038         if not role then -- kick
1039                 presence_type = "unavailable";
1040                 self._occupants[occupant_jid] = nil;
1041                 for jid in pairs(occupant.sessions) do -- remove for all sessions of the nick
1042                         self._jid_nick[jid] = nil;
1043                 end
1044                 x:tag("status", {code = "307"}):up();
1045         else
1046                 occupant.role = role;
1047         end
1048         local bp;
1049         for jid,pres in pairs(occupant.sessions) do -- send to all sessions of the nick
1050                 local p = st.clone(pres);
1051                 p.attr.from = occupant_jid;
1052                 p.attr.type = presence_type;
1053                 p.attr.to = jid;
1054                 p:add_child(x);
1055                 self:_route_stanza(p);
1056                 if occupant.jid == jid then
1057                         bp = p;
1058                 end
1059         end
1060         if callback then callback(); end
1061         if bp then
1062                 self:broadcast_except_nick(bp, occupant_jid);
1063         end
1064         return true;
1065 end
1066
1067 function room_mt:_route_stanza(stanza)
1068         local muc_child;
1069         local to_occupant = self._occupants[self._jid_nick[stanza.attr.to]];
1070         local from_occupant = self._occupants[stanza.attr.from];
1071         if stanza.name == "presence" then
1072                 if to_occupant and from_occupant then
1073                         if self._data.whois == 'anyone' then
1074                             muc_child = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
1075                         else
1076                                 if to_occupant.role == "moderator" or jid_bare(to_occupant.jid) == jid_bare(from_occupant.jid) then
1077                                         muc_child = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
1078                                 end
1079                         end
1080                 end
1081         end
1082         if muc_child then
1083                 for _, item in pairs(muc_child.tags) do
1084                         if item.name == "item" then
1085                                 if from_occupant == to_occupant then
1086                                         item.attr.jid = stanza.attr.to;
1087                                 else
1088                                         item.attr.jid = from_occupant.jid;
1089                                 end
1090                         end
1091                 end
1092         end
1093         self:route_stanza(stanza);
1094         if muc_child then
1095                 for _, item in pairs(muc_child.tags) do
1096                         if item.name == "item" then
1097                                 item.attr.jid = nil;
1098                         end
1099                 end
1100         end
1101 end
1102
1103 local _M = {}; -- module "muc"
1104
1105 function _M.new_room(jid, config)
1106         return setmetatable({
1107                 jid = jid;
1108                 _jid_nick = {};
1109                 _occupants = {};
1110                 _data = {
1111                     whois = 'moderators';
1112                     history_length = math.min((config and config.history_length)
1113                         or default_history_length, max_history_length);
1114                 };
1115                 _affiliations = {};
1116         }, room_mt);
1117 end
1118
1119 function _M.set_max_history_length(_max_history_length)
1120         max_history_length = _max_history_length or math.huge;
1121 end
1122
1123 _M.room_mt = room_mt;
1124
1125 return _M;