Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

mod_smacks.lua 28KB

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