You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

mod_smacks.lua 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646
  1. -- XEP-0198: Stream Management for Prosody IM
  2. --
  3. -- Copyright (C) 2010-2015 Matthew Wild
  4. -- Copyright (C) 2010 Waqas Hussain
  5. -- Copyright (C) 2012-2015 Kim Alvefur
  6. -- Copyright (C) 2012 Thijs Alkemade
  7. -- Copyright (C) 2014 Florian Zeitz
  8. -- Copyright (C) 2016-2020 Thilo Molitor
  9. --
  10. -- This project is MIT/X11 licensed. Please see the
  11. -- COPYING file in the source package for more information.
  12. --
  13. local st = require "util.stanza";
  14. local dep = require "util.dependencies";
  15. local cache = dep.softreq("util.cache"); -- only available in prosody 0.10+
  16. local uuid_generate = require "util.uuid".generate;
  17. local jid = require "util.jid";
  18. local t_insert, t_remove = table.insert, table.remove;
  19. local math_min = math.min;
  20. local math_max = math.max;
  21. local os_time = os.time;
  22. local tonumber, tostring = tonumber, tostring;
  23. local add_filter = require "util.filters".add_filter;
  24. local timer = require "util.timer";
  25. local datetime = require "util.datetime";
  26. local xmlns_sm2 = "urn:xmpp:sm:2";
  27. local xmlns_sm3 = "urn:xmpp:sm:3";
  28. local xmlns_errors = "urn:ietf:params:xml:ns:xmpp-stanzas";
  29. local xmlns_delay = "urn:xmpp:delay";
  30. local sm2_attr = { xmlns = xmlns_sm2 };
  31. local sm3_attr = { xmlns = xmlns_sm3 };
  32. local resume_timeout = module:get_option_number("smacks_hibernation_time", 300);
  33. local s2s_smacks = module:get_option_boolean("smacks_enabled_s2s", false);
  34. local s2s_resend = module:get_option_boolean("smacks_s2s_resend", false);
  35. local max_unacked_stanzas = module:get_option_number("smacks_max_unacked_stanzas", 0);
  36. local delayed_ack_timeout = module:get_option_number("smacks_max_ack_delay", 60);
  37. local max_hibernated_sessions = module:get_option_number("smacks_max_hibernated_sessions", 10);
  38. local max_old_sessions = module:get_option_number("smacks_max_old_sessions", 10);
  39. local core_process_stanza = prosody.core_process_stanza;
  40. local sessionmanager = require"core.sessionmanager";
  41. assert(max_hibernated_sessions > 0, "smacks_max_hibernated_sessions must be greater than 0");
  42. assert(max_old_sessions > 0, "smacks_max_old_sessions must be greater than 0");
  43. local c2s_sessions = module:shared("/*/c2s/sessions");
  44. local function init_session_cache(max_entries, evict_callback)
  45. -- old prosody version < 0.10 (no limiting at all!)
  46. if not cache then
  47. local store = {};
  48. return {
  49. get = function(user, key)
  50. if not user then return nil; end
  51. if not key then return nil; end
  52. return store[key];
  53. end;
  54. set = function(user, key, value)
  55. if not user then return nil; end
  56. if not key then return nil; end
  57. store[key] = value;
  58. end;
  59. };
  60. end
  61. -- use per user limited cache for prosody >= 0.10
  62. local stores = {};
  63. return {
  64. get = function(user, key)
  65. if not user then return nil; end
  66. if not key then return nil; end
  67. if not stores[user] then
  68. stores[user] = cache.new(max_entries, evict_callback);
  69. end
  70. return stores[user]:get(key);
  71. end;
  72. set = function(user, key, value)
  73. if not user then return nil; end
  74. if not key then return nil; end
  75. if not stores[user] then stores[user] = cache.new(max_entries, evict_callback); end
  76. stores[user]:set(key, value);
  77. -- remove empty caches completely
  78. if not stores[user]:count() then stores[user] = nil; end
  79. end;
  80. };
  81. end
  82. local old_session_registry = init_session_cache(max_old_sessions, nil);
  83. local session_registry = init_session_cache(max_hibernated_sessions, function(resumption_token, session)
  84. if session.destroyed then return true; end -- destroyed session can always be removed from cache
  85. session.log("warn", "User has too much hibernated sessions, removing oldest session (token: %s)", resumption_token);
  86. -- store old session's h values on force delete
  87. -- save only actual h value and username/host (for security)
  88. old_session_registry.set(session.username, resumption_token, {
  89. h = session.handled_stanza_count,
  90. username = session.username,
  91. host = session.host
  92. });
  93. return true; -- allow session to be removed from full cache to make room for new one
  94. end);
  95. local function stoppable_timer(delay, callback)
  96. local stopped = false;
  97. local timer = module:add_timer(delay, function (t)
  98. if stopped then return; end
  99. return callback(t);
  100. end);
  101. if timer and timer.stop then return timer; end -- new prosody api includes stop() function
  102. return {
  103. stop = function(self) stopped = true end;
  104. timer;
  105. };
  106. end
  107. local function delayed_ack_function(session)
  108. -- fire event only if configured to do so and our session is not already hibernated or destroyed
  109. if delayed_ack_timeout > 0 and session.awaiting_ack
  110. and not session.hibernating and not session.destroyed then
  111. session.log("debug", "Firing event 'smacks-ack-delayed', queue = %d",
  112. session.outgoing_stanza_queue and #session.outgoing_stanza_queue or 0);
  113. module:fire_event("smacks-ack-delayed", {origin = session, queue = session.outgoing_stanza_queue});
  114. end
  115. session.delayed_ack_timer = nil;
  116. end
  117. local function can_do_smacks(session, advertise_only)
  118. if session.smacks then return false, "unexpected-request", "Stream management is already enabled"; end
  119. local session_type = session.type;
  120. if session.username then
  121. if not(advertise_only) and not(session.resource) then -- Fail unless we're only advertising sm
  122. return false, "unexpected-request", "Client must bind a resource before enabling stream management";
  123. end
  124. return true;
  125. elseif s2s_smacks and (session_type == "s2sin" or session_type == "s2sout") then
  126. return true;
  127. end
  128. return false, "service-unavailable", "Stream management is not available for this stream";
  129. end
  130. module:hook("stream-features",
  131. function (event)
  132. if can_do_smacks(event.origin, true) then
  133. event.features:tag("sm", sm2_attr):tag("optional"):up():up();
  134. event.features:tag("sm", sm3_attr):tag("optional"):up():up();
  135. end
  136. end);
  137. module:hook("s2s-stream-features",
  138. function (event)
  139. if can_do_smacks(event.origin, true) then
  140. event.features:tag("sm", sm2_attr):tag("optional"):up():up();
  141. event.features:tag("sm", sm3_attr):tag("optional"):up():up();
  142. end
  143. end);
  144. local function request_ack_if_needed(session, force, reason)
  145. local queue = session.outgoing_stanza_queue;
  146. local expected_h = session.last_acknowledged_stanza + #queue;
  147. -- session.log("debug", "*** SMACKS(1) ***: awaiting_ack=%s, hibernating=%s", tostring(session.awaiting_ack), tostring(session.hibernating));
  148. if session.awaiting_ack == nil and not session.hibernating then
  149. -- this check of last_requested_h prevents ack-loops if missbehaving clients report wrong
  150. -- stanza counts. it is set when an <r> is really sent (e.g. inside timer), preventing any
  151. -- further requests until a higher h-value would be expected.
  152. -- session.log("debug", "*** SMACKS(2) ***: #queue=%s, max_unacked_stanzas=%s, expected_h=%s, last_requested_h=%s", tostring(#queue), tostring(max_unacked_stanzas), tostring(expected_h), tostring(session.last_requested_h));
  153. if (#queue > max_unacked_stanzas and expected_h ~= session.last_requested_h) or force then
  154. session.log("debug", "Queuing <r> (in a moment) from %s - #queue=%d", reason, #queue);
  155. session.awaiting_ack = false;
  156. session.awaiting_ack_timer = stoppable_timer(1e-06, function ()
  157. -- session.log("debug", "*** SMACKS(3) ***: awaiting_ack=%s, hibernating=%s", tostring(session.awaiting_ack), tostring(session.hibernating));
  158. -- only request ack if needed and our session is not already hibernated or destroyed
  159. if not session.awaiting_ack and not session.hibernating and not session.destroyed then
  160. session.log("debug", "Sending <r> (inside timer, before send) from %s - #queue=%d", reason, #queue);
  161. (session.sends2s or session.send)(st.stanza("r", { xmlns = session.smacks }))
  162. session.awaiting_ack = true;
  163. -- expected_h could be lower than this expression e.g. more stanzas added to the queue meanwhile)
  164. session.last_requested_h = session.last_acknowledged_stanza + #queue;
  165. session.log("debug", "Sending <r> (inside timer, after send) from %s - #queue=%d", reason, #queue);
  166. if not session.delayed_ack_timer then
  167. session.delayed_ack_timer = stoppable_timer(delayed_ack_timeout, function()
  168. delayed_ack_function(session);
  169. end);
  170. end
  171. end
  172. end);
  173. end
  174. end
  175. -- Trigger "smacks-ack-delayed"-event if we added new (ackable) stanzas to the outgoing queue
  176. -- and there isn't already a timer for this event running.
  177. -- If we wouldn't do this, stanzas added to the queue after the first "smacks-ack-delayed"-event
  178. -- would not trigger this event (again).
  179. if #queue > max_unacked_stanzas and session.awaiting_ack and session.delayed_ack_timer == nil then
  180. session.log("debug", "Calling delayed_ack_function directly (still waiting for ack)");
  181. delayed_ack_function(session);
  182. end
  183. end
  184. local function outgoing_stanza_filter(stanza, session)
  185. local is_stanza = stanza.attr and not stanza.attr.xmlns and not stanza.name:find":";
  186. if is_stanza and not stanza._cached then -- Stanza in default stream namespace
  187. local queue = session.outgoing_stanza_queue;
  188. local cached_stanza = st.clone(stanza);
  189. cached_stanza._cached = true;
  190. if cached_stanza and cached_stanza.name ~= "iq" and cached_stanza:get_child("delay", xmlns_delay) == nil then
  191. cached_stanza = cached_stanza:tag("delay", {
  192. xmlns = xmlns_delay,
  193. from = jid.bare(session.full_jid or session.host),
  194. stamp = datetime.datetime()
  195. });
  196. end
  197. queue[#queue+1] = cached_stanza;
  198. if session.hibernating then
  199. session.log("debug", "hibernating, stanza queued");
  200. module:fire_event("smacks-hibernation-stanza-queued", {origin = session, queue = queue, stanza = cached_stanza});
  201. return nil;
  202. end
  203. request_ack_if_needed(session, false, "outgoing_stanza_filter");
  204. end
  205. return stanza;
  206. end
  207. local function count_incoming_stanzas(stanza, session)
  208. if not stanza.attr.xmlns then
  209. session.handled_stanza_count = session.handled_stanza_count + 1;
  210. session.log("debug", "Handled %d incoming stanzas", session.handled_stanza_count);
  211. end
  212. return stanza;
  213. end
  214. local function wrap_session_out(session, resume)
  215. if not resume then
  216. session.outgoing_stanza_queue = {};
  217. session.last_acknowledged_stanza = 0;
  218. end
  219. add_filter(session, "stanzas/out", outgoing_stanza_filter, -999);
  220. local session_close = session.close;
  221. function session.close(...)
  222. if session.resumption_token then
  223. session_registry.set(session.username, session.resumption_token, nil);
  224. old_session_registry.set(session.username, session.resumption_token, nil);
  225. session.resumption_token = nil;
  226. end
  227. -- send out last ack as per revision 1.5.2 of XEP-0198
  228. if session.smacks and session.conn then
  229. (session.sends2s or session.send)(st.stanza("a", { xmlns = session.smacks, h = string.format("%d", session.handled_stanza_count) }));
  230. end
  231. return session_close(...);
  232. end
  233. return session;
  234. end
  235. local function wrap_session_in(session, resume)
  236. if not resume then
  237. session.handled_stanza_count = 0;
  238. end
  239. add_filter(session, "stanzas/in", count_incoming_stanzas, 999);
  240. return session;
  241. end
  242. local function wrap_session(session, resume)
  243. wrap_session_out(session, resume);
  244. wrap_session_in(session, resume);
  245. return session;
  246. end
  247. function handle_enable(session, stanza, xmlns_sm)
  248. local ok, err, err_text = can_do_smacks(session);
  249. if not ok then
  250. session.log("warn", "Failed to enable smacks: %s", err_text); -- TODO: XEP doesn't say we can send error text, should it?
  251. (session.sends2s or session.send)(st.stanza("failed", { xmlns = xmlns_sm }):tag(err, { xmlns = xmlns_errors}));
  252. return true;
  253. end
  254. module:log("debug", "Enabling stream management");
  255. session.smacks = xmlns_sm;
  256. wrap_session(session, false);
  257. local resume_token;
  258. local resume = stanza.attr.resume;
  259. if resume == "true" or resume == "1" then
  260. resume_token = uuid_generate();
  261. session_registry.set(session.username, resume_token, session);
  262. session.resumption_token = resume_token;
  263. end
  264. (session.sends2s or session.send)(st.stanza("enabled", { xmlns = xmlns_sm, id = resume_token, resume = resume, max = tostring(resume_timeout) }));
  265. return true;
  266. end
  267. module:hook_stanza(xmlns_sm2, "enable", function (session, stanza) return handle_enable(session, stanza, xmlns_sm2); end, 100);
  268. module:hook_stanza(xmlns_sm3, "enable", function (session, stanza) return handle_enable(session, stanza, xmlns_sm3); end, 100);
  269. module:hook_stanza("http://etherx.jabber.org/streams", "features",
  270. function (session, stanza)
  271. stoppable_timer(1e-6, function ()
  272. if can_do_smacks(session) then
  273. if stanza:get_child("sm", xmlns_sm3) then
  274. session.sends2s(st.stanza("enable", sm3_attr));
  275. session.smacks = xmlns_sm3;
  276. elseif stanza:get_child("sm", xmlns_sm2) then
  277. session.sends2s(st.stanza("enable", sm2_attr));
  278. session.smacks = xmlns_sm2;
  279. else
  280. return;
  281. end
  282. wrap_session_out(session, false);
  283. end
  284. end);
  285. end);
  286. function handle_enabled(session, stanza, xmlns_sm)
  287. module:log("debug", "Enabling stream management");
  288. session.smacks = xmlns_sm;
  289. wrap_session_in(session, false);
  290. -- FIXME Resume?
  291. return true;
  292. end
  293. module:hook_stanza(xmlns_sm2, "enabled", function (session, stanza) return handle_enabled(session, stanza, xmlns_sm2); end, 100);
  294. module:hook_stanza(xmlns_sm3, "enabled", function (session, stanza) return handle_enabled(session, stanza, xmlns_sm3); end, 100);
  295. function handle_r(origin, stanza, xmlns_sm)
  296. if not origin.smacks then
  297. module:log("debug", "Received ack request from non-smack-enabled session");
  298. return;
  299. end
  300. module:log("debug", "Received ack request, acking for %d", origin.handled_stanza_count);
  301. -- Reply with <a>
  302. (origin.sends2s or origin.send)(st.stanza("a", { xmlns = xmlns_sm, h = string.format("%d", origin.handled_stanza_count) }));
  303. -- piggyback our own ack request if needed (see request_ack_if_needed() for explanation of last_requested_h)
  304. local expected_h = origin.last_acknowledged_stanza + #origin.outgoing_stanza_queue;
  305. if #origin.outgoing_stanza_queue > 0 and expected_h ~= origin.last_requested_h then
  306. request_ack_if_needed(origin, true, "piggybacked by handle_r");
  307. end
  308. return true;
  309. end
  310. module:hook_stanza(xmlns_sm2, "r", function (origin, stanza) return handle_r(origin, stanza, xmlns_sm2); end);
  311. module:hook_stanza(xmlns_sm3, "r", function (origin, stanza) return handle_r(origin, stanza, xmlns_sm3); end);
  312. function handle_a(origin, stanza)
  313. if not origin.smacks then return; end
  314. origin.awaiting_ack = nil;
  315. if origin.awaiting_ack_timer then
  316. origin.awaiting_ack_timer:stop();
  317. end
  318. if origin.delayed_ack_timer then
  319. origin.delayed_ack_timer:stop();
  320. origin.delayed_ack_timer = nil;
  321. end
  322. -- Remove handled stanzas from outgoing_stanza_queue
  323. -- origin.log("debug", "ACK: h=%s, last=%s", stanza.attr.h or "", origin.last_acknowledged_stanza or "");
  324. local h = tonumber(stanza.attr.h);
  325. if not h then
  326. origin:close{ condition = "invalid-xml"; text = "Missing or invalid 'h' attribute"; };
  327. return;
  328. end
  329. local handled_stanza_count = h-origin.last_acknowledged_stanza;
  330. local queue = origin.outgoing_stanza_queue;
  331. if handled_stanza_count > #queue then
  332. origin.log("warn", "The client says it handled %d new stanzas, but we only sent %d :)",
  333. handled_stanza_count, #queue);
  334. origin.log("debug", "Client h: %d, our h: %d", tonumber(stanza.attr.h), origin.last_acknowledged_stanza);
  335. for i=1,#queue do
  336. origin.log("debug", "Q item %d: %s", i, tostring(queue[i]));
  337. end
  338. end
  339. for i=1,math_min(handled_stanza_count,#queue) do
  340. local handled_stanza = t_remove(origin.outgoing_stanza_queue, 1);
  341. module:fire_event("delivery/success", { session = origin, stanza = handled_stanza });
  342. end
  343. origin.log("debug", "#queue = %d", #queue);
  344. origin.last_acknowledged_stanza = origin.last_acknowledged_stanza + handled_stanza_count;
  345. request_ack_if_needed(origin, false, "handle_a")
  346. return true;
  347. end
  348. module:hook_stanza(xmlns_sm2, "a", handle_a);
  349. module:hook_stanza(xmlns_sm3, "a", handle_a);
  350. --TODO: Optimise... incoming stanzas should be handled by a per-session
  351. -- function that has a counter as an upvalue (no table indexing for increments,
  352. -- and won't slow non-198 sessions). We can also then remove the .handled flag
  353. -- on stanzas
  354. local function handle_unacked_stanzas(session)
  355. local queue = session.outgoing_stanza_queue;
  356. local error_attr = { type = "cancel" };
  357. if #queue > 0 then
  358. session.outgoing_stanza_queue = {};
  359. for i=1,#queue do
  360. if not module:fire_event("delivery/failure", { session = session, stanza = queue[i] }) then
  361. local reply = st.reply(queue[i]);
  362. if reply.attr.to ~= session.full_jid then
  363. reply.attr.type = "error";
  364. reply:tag("error", error_attr)
  365. :tag("recipient-unavailable", {xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas"});
  366. core_process_stanza(session, reply);
  367. end
  368. end
  369. end
  370. end
  371. end
  372. -- don't send delivery errors for messages which will be delivered by mam later on
  373. module:hook("delivery/failure", function(event)
  374. local session, stanza = event.session, event.stanza;
  375. -- Only deal with authenticated (c2s) sessions
  376. if session.username then
  377. if stanza.name == "message" and stanza.attr.xmlns == nil and
  378. ( stanza.attr.type == "chat" or ( stanza.attr.type or "normal" ) == "normal" ) then
  379. -- do nothing here for normal messages and don't send out "message delivery errors",
  380. -- because messages are already in MAM at this point (no need to frighten users)
  381. if session.mam_requested and stanza._was_archived then
  382. return true; -- stanza handled, don't send an error
  383. end
  384. -- store message in offline store, if this client does not use mam *and* was the last client online
  385. local sessions = prosody.hosts[module.host].sessions[session.username] and
  386. prosody.hosts[module.host].sessions[session.username].sessions or nil;
  387. if sessions and next(sessions) == session.resource and next(sessions, session.resource) == nil then
  388. module:fire_event("message/offline/handle", { origin = session, stanza = stanza } );
  389. return true; -- stanza handled, don't send an error
  390. end
  391. end
  392. end
  393. end);
  394. -- mark stanzas as archived --> this will allow us to send back errors for stanzas not archived
  395. -- because the user configured the server to do so ("no-archive"-setting for one special contact for example)
  396. module:hook("archive-message-added", function(event)
  397. local session, stanza, for_user, stanza_id = event.origin, event.stanza, event.for_user, event.id;
  398. if session then session.log("debug", "Marking stanza as archived, archive_id: %s, stanza: %s", tostring(stanza_id), tostring(stanza:top_tag())); end
  399. if not session then module:log("debug", "Marking stanza as archived in unknown session, archive_id: %s, stanza: %s", tostring(stanza_id), tostring(stanza:top_tag())); end
  400. stanza._was_archived = true;
  401. end);
  402. module:hook("pre-resource-unbind", function (event)
  403. local session, err = event.session, event.error;
  404. if session.smacks then
  405. if not session.resumption_token then
  406. local queue = session.outgoing_stanza_queue;
  407. if #queue > 0 then
  408. session.log("debug", "Destroying session with %d unacked stanzas", #queue);
  409. handle_unacked_stanzas(session);
  410. end
  411. else
  412. session.log("debug", "mod_smacks hibernating session for up to %d seconds", resume_timeout);
  413. local hibernate_time = os_time(); -- Track the time we went into hibernation
  414. session.hibernating = hibernate_time;
  415. local resumption_token = session.resumption_token;
  416. module:fire_event("smacks-hibernation-start", {origin = session, queue = session.outgoing_stanza_queue});
  417. timer.add_task(resume_timeout, function ()
  418. session.log("debug", "mod_smacks hibernation timeout reached...");
  419. -- We need to check the current resumption token for this resource
  420. -- matches the smacks session this timer is for in case it changed
  421. -- (for example, the client may have bound a new resource and
  422. -- started a new smacks session, or not be using smacks)
  423. local curr_session = full_sessions[session.full_jid];
  424. if session.destroyed then
  425. session.log("debug", "The session has already been destroyed");
  426. elseif curr_session and curr_session.resumption_token == resumption_token
  427. -- Check the hibernate time still matches what we think it is,
  428. -- otherwise the session resumed and re-hibernated.
  429. and session.hibernating == hibernate_time then
  430. -- wait longer if the timeout isn't reached because push was enabled for this session
  431. -- session.first_hibernated_push is the starting point for hibernation timeouts of those push enabled clients
  432. -- wait for an additional resume_timeout seconds if no push occured since hibernation at all
  433. local current_time = os_time();
  434. local timeout_start = math_max(session.hibernating, session.first_hibernated_push or session.hibernating);
  435. if session.push_identifier ~= nil and not session.first_hibernated_push then
  436. session.log("debug", "No push happened since hibernation started, hibernating session for up to %d extra seconds", resume_timeout);
  437. return resume_timeout;
  438. end
  439. if current_time-timeout_start < resume_timeout and session.push_identifier ~= nil then
  440. session.log("debug", "A push happened since hibernation started, hibernating session for up to %d extra seconds", current_time-timeout_start);
  441. return current_time-timeout_start; -- time left to wait
  442. end
  443. session.log("debug", "Destroying session for hibernating too long");
  444. session_registry.set(session.username, session.resumption_token, nil);
  445. -- save only actual h value and username/host (for security)
  446. old_session_registry.set(session.username, session.resumption_token, {
  447. h = session.handled_stanza_count,
  448. username = session.username,
  449. host = session.host
  450. });
  451. session.resumption_token = nil;
  452. sessionmanager.destroy_session(session);
  453. else
  454. session.log("debug", "Session resumed before hibernation timeout, all is well")
  455. end
  456. end);
  457. return true; -- Postpone destruction for now
  458. end
  459. end
  460. end);
  461. local function handle_s2s_destroyed(event)
  462. local session = event.session;
  463. local queue = session.outgoing_stanza_queue;
  464. if queue and #queue > 0 then
  465. session.log("warn", "Destroying session with %d unacked stanzas", #queue);
  466. if s2s_resend then
  467. for i = 1, #queue do
  468. module:send(queue[i]);
  469. end
  470. session.outgoing_stanza_queue = nil;
  471. else
  472. handle_unacked_stanzas(session);
  473. end
  474. end
  475. end
  476. module:hook("s2sout-destroyed", handle_s2s_destroyed);
  477. module:hook("s2sin-destroyed", handle_s2s_destroyed);
  478. local function get_session_id(session)
  479. return session.id or (tostring(session):match("[a-f0-9]+$"));
  480. end
  481. function handle_resume(session, stanza, xmlns_sm)
  482. if session.full_jid then
  483. session.log("warn", "Tried to resume after resource binding");
  484. session.send(st.stanza("failed", { xmlns = xmlns_sm })
  485. :tag("unexpected-request", { xmlns = xmlns_errors })
  486. );
  487. return true;
  488. end
  489. local id = stanza.attr.previd;
  490. local original_session = session_registry.get(session.username, id);
  491. if not original_session then
  492. session.log("debug", "Tried to resume non-existent session with id %s", id);
  493. local old_session = old_session_registry.get(session.username, id);
  494. if old_session and session.username == old_session.username
  495. and session.host == old_session.host
  496. and old_session.h then
  497. session.send(st.stanza("failed", { xmlns = xmlns_sm, h = string.format("%d", old_session.h) })
  498. :tag("item-not-found", { xmlns = xmlns_errors })
  499. );
  500. else
  501. session.send(st.stanza("failed", { xmlns = xmlns_sm })
  502. :tag("item-not-found", { xmlns = xmlns_errors })
  503. );
  504. end;
  505. elseif session.username == original_session.username
  506. and session.host == original_session.host then
  507. session.log("debug", "mod_smacks resuming existing session %s...", get_session_id(original_session));
  508. original_session.log("debug", "mod_smacks session resumed from %s...", get_session_id(session));
  509. -- TODO: All this should move to sessionmanager (e.g. session:replace(new_session))
  510. if original_session.conn then
  511. original_session.log("debug", "mod_smacks closing an old connection for this session");
  512. local conn = original_session.conn;
  513. c2s_sessions[conn] = nil;
  514. conn:close();
  515. end
  516. local migrated_session_log = session.log;
  517. original_session.ip = session.ip;
  518. original_session.conn = session.conn;
  519. original_session.send = session.send;
  520. original_session.close = session.close;
  521. original_session.filter = session.filter;
  522. original_session.filter.session = original_session;
  523. original_session.filters = session.filters;
  524. original_session.stream = session.stream;
  525. original_session.secure = session.secure;
  526. original_session.hibernating = nil;
  527. session.log = original_session.log;
  528. session.type = original_session.type;
  529. wrap_session(original_session, true);
  530. -- Inform xmppstream of the new session (passed to its callbacks)
  531. original_session.stream:set_session(original_session);
  532. -- Similar for connlisteners
  533. c2s_sessions[session.conn] = original_session;
  534. original_session.send(st.stanza("resumed", { xmlns = xmlns_sm,
  535. h = string.format("%d", original_session.handled_stanza_count), previd = id }));
  536. -- Fake an <a> with the h of the <resume/> from the client
  537. original_session:dispatch_stanza(st.stanza("a", { xmlns = xmlns_sm,
  538. h = stanza.attr.h }));
  539. -- Ok, we need to re-send any stanzas that the client didn't see
  540. -- ...they are what is now left in the outgoing stanza queue
  541. -- We have to use the send of "session" because we don't want to add our resent stanzas
  542. -- to the outgoing queue again
  543. local queue = original_session.outgoing_stanza_queue;
  544. session.log("debug", "resending all unacked stanzas that are still queued after resume, #queue = %d", #queue);
  545. for i=1,#queue do
  546. session.send(queue[i]);
  547. end
  548. session.log("debug", "all stanzas resent, now disabling send() in this migrated session, #queue = %d", #queue);
  549. function session.send(stanza)
  550. migrated_session_log("error", "Tried to send stanza on old session migrated by smacks resume (maybe there is a bug?): %s", tostring(stanza));
  551. return false;
  552. end
  553. module:fire_event("smacks-hibernation-end", {origin = session, resumed = original_session, queue = queue});
  554. request_ack_if_needed(original_session, true, "handle_resume");
  555. else
  556. module:log("warn", "Client %s@%s[%s] tried to resume stream for %s@%s[%s]",
  557. session.username or "?", session.host or "?", session.type,
  558. original_session.username or "?", original_session.host or "?", original_session.type);
  559. session.send(st.stanza("failed", { xmlns = xmlns_sm })
  560. :tag("not-authorized", { xmlns = xmlns_errors }));
  561. end
  562. return true;
  563. end
  564. module:hook_stanza(xmlns_sm2, "resume", function (session, stanza) return handle_resume(session, stanza, xmlns_sm2); end);
  565. module:hook_stanza(xmlns_sm3, "resume", function (session, stanza) return handle_resume(session, stanza, xmlns_sm3); end);
  566. local function handle_read_timeout(event)
  567. local session = event.session;
  568. if session.smacks then
  569. if session.awaiting_ack then
  570. if session.awaiting_ack_timer then
  571. session.awaiting_ack_timer:stop();
  572. end
  573. if session.delayed_ack_timer then
  574. session.delayed_ack_timer:stop();
  575. session.delayed_ack_timer = nil;
  576. end
  577. return false; -- Kick the session
  578. end
  579. session.log("debug", "Sending <r> (read timeout)");
  580. (session.sends2s or session.send)(st.stanza("r", { xmlns = session.smacks }));
  581. session.awaiting_ack = true;
  582. if not session.delayed_ack_timer then
  583. session.delayed_ack_timer = stoppable_timer(delayed_ack_timeout, function()
  584. delayed_ack_function(session);
  585. end);
  586. end
  587. return true;
  588. end
  589. end
  590. module:hook("s2s-read-timeout", handle_read_timeout);
  591. module:hook("c2s-read-timeout", handle_read_timeout);