Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

mod_smacks.lua 28KB

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