1: %% Stream Management tests 2: -module(sm_SUITE). 3: 4: -compile([export_all, nowarn_export_all]). 5: -include_lib("exml/include/exml.hrl"). 6: -include_lib("eunit/include/eunit.hrl"). 7: -include_lib("escalus/include/escalus.hrl"). 8: -include_lib("common_test/include/ct.hrl"). 9: 10: %% Injected code callbacks 11: -export([rpc_start_hook_handler/3, 12: rpc_stop_hook_handler/2, 13: hook_handler_fn/3, 14: regression_handler/5]). 15: 16: -export([rpc_start_filter_hook_handler/3, 17: rpc_stop_filter_hook_handler/2, 18: filter_hook_handler_fn/3]). 19: 20: -import(distributed_helper, [mim/0, 21: require_rpc_nodes/1, 22: rpc/4]). 23: 24: -import(domain_helper, [host_type/0]). 25: 26: -import(sm_helper, [connect_fresh/3, 27: connect_fresh/4, 28: connect_spec/2, 29: connect_spec/3, 30: connect_same/2, 31: connect_same/3, 32: connect_resume/2, 33: process_initial_stanza/1, 34: send_initial_presence/1, 35: get_ack/1, 36: ack_initial_presence/1]). 37: 38: -define(MOD_SM, mod_stream_management). 39: -define(CONSTRAINT_CHECK_TIMEOUT, 5000). 40: -define(LONG_TIMEOUT, 3600). 41: -define(SHORT_TIMEOUT, 1). 42: -define(SMALL_SM_BUFFER, 3). 43: -define(PING_REQUEST_TIMEOUT, 1). 44: -define(PING_INTERVAL, 5). 45: 46: %%-------------------------------------------------------------------- 47: %% Suite configuration 48: %%-------------------------------------------------------------------- 49: 50: suite() -> 51: require_rpc_nodes([mim]) ++ escalus:suite(). 52: 53: all() -> 54: ct_helper:groups_to_all(groups()). 55: 56: groups() -> 57: G = [ 58: % {parallel, [parallel], parallel_cases()}, 59: % {parallel_manual_ack_freq_1, [parallel], parallel_manual_ack_freq_1_cases()}, 60: % {manual_ack_freq_2, [], manual_ack_freq_2_cases()}, 61: % {stale_h, [], stale_h_cases()}, 62: % {parallel_unacknowledged_message_hook, [parallel], parallel_unacknowledged_message_hook_cases()} 63: {ping, [], [ping_timeout]} 64: ], 65: ct_helper:repeat_all_until_any_fail(G, 1000). 66: 67: parallel_cases() -> 68: [server_announces_sm, 69: server_enables_sm_before_session, 70: server_enables_sm_after_session, 71: server_returns_failed_after_start, 72: server_returns_failed_after_auth, 73: server_enables_resumption, 74: client_enables_sm_twice_fails_with_correct_error_stanza, 75: session_resumed_then_old_session_is_closed_gracefully_with_correct_error_stanza, 76: session_resumed_and_old_session_dead_doesnt_route_error_to_new_session, 77: basic_ack, 78: h_ok_before_session, 79: h_ok_after_session_enabled_before_session, 80: h_ok_after_session_enabled_after_session, 81: h_ok_after_a_chat, 82: h_non_given_closes_stream_gracefully, 83: resend_unacked_on_reconnection, 84: session_established, 85: wait_for_resumption, 86: resume_session, 87: resume_session_with_wrong_h_does_not_leak_sessions, 88: resume_session_with_wrong_sid_returns_item_not_found, 89: resume_session_with_wrong_namespace_is_a_noop, 90: resume_dead_session_results_in_item_not_found, 91: resume_session_kills_old_C2S_gracefully, 92: carboncopy_works, 93: carboncopy_works_after_resume, 94: aggressively_pipelined_resume, 95: replies_are_processed_by_resumed_session, 96: subscription_requests_are_buffered_properly, 97: messages_are_properly_flushed_during_resumption]. 98: 99: parallel_manual_ack_freq_1_cases() -> 100: [client_acks_more_than_sent, 101: too_many_unacked_stanzas, 102: resend_unacked_after_resume_timeout, 103: resume_session_state_send_message_with_ack, 104: resume_session_state_send_message_without_ack, 105: resume_session_state_stop_c2s, 106: server_requests_ack_after_session, 107: resend_more_offline_messages_than_buffer_size, 108: server_requests_ack]. 109: 110: manual_ack_freq_2_cases() -> 111: [server_requests_ack_freq_2]. 112: 113: stale_h_cases() -> 114: [resume_expired_session_returns_correct_h, 115: gc_repeat_after_never_means_no_cleaning, 116: gc_repeat_after_timeout_does_clean]. 117: 118: stream_mgmt_disabled_cases() -> 119: [no_crash_if_stream_mgmt_disabled_but_client_requests_stream_mgmt, 120: no_crash_if_stream_mgmt_disabled_but_client_requests_stream_mgmt_with_resumption]. 121: 122: manual_ack_freq_long_session_timeout_cases() -> 123: [preserve_order]. 124: 125: parallel_unacknowledged_message_hook_cases() -> 126: [unacknowledged_message_hook_bounce, 127: unacknowledged_message_hook_offline, 128: unacknowledged_message_hook_resume, 129: unacknowledged_message_hook_filter]. 130: 131: %%-------------------------------------------------------------------- 132: %% Init & teardown 133: %%-------------------------------------------------------------------- 134: 135: init_per_suite(Config) -> 136: NewConfig = dynamic_modules:save_modules(host_type(), Config), 137: NewConfigWithSM = escalus_users:update_userspec(NewConfig, alice, stream_management, true), 138: mongoose_helper:inject_module(?MODULE), 139: escalus:init_per_suite(NewConfigWithSM). 140: 141: end_per_suite(Config) -> 142: escalus_fresh:clean(), 143: dynamic_modules:restore_modules(Config), 144: escalus:end_per_suite(Config). 145: 146: init_per_group(Group, Config) when Group =:= parallel_unacknowledged_message_hook; 147: Group =:= manual_ack_freq_long_session_timeout; 148: Group =:= parallel_manual_ack_freq_1; 149: Group =:= manual_ack_freq_2 -> 150: dynamic_modules:ensure_modules(host_type(), required_modules(group, Group)), 151: Config; 152: init_per_group(stale_h, Config) -> 153: Config; 154: init_per_group(stream_mgmt_disabled, Config) -> 155: dynamic_modules:stop(host_type(), ?MOD_SM), 156: rpc(mim(), mnesia, delete_table, [sm_session]), 157: Config; 158: init_per_group(ping, Config) -> 159: Config; 160: init_per_group(Group, Config) -> 161: dynamic_modules:ensure_modules(host_type(), required_modules(group, Group)), 162: Config. 163: 164: end_per_group(_Group, _Config) -> 165: ok. 166: 167: init_per_testcase(resume_expired_session_returns_correct_h = CN, Config) -> 168: dynamic_modules:ensure_modules(host_type(), required_modules(testcase, CN)), 169: escalus:init_per_testcase(CN, Config); 170: init_per_testcase(CN, Config) when CN =:= gc_repeat_after_never_means_no_cleaning; 171: CN =:= gc_repeat_after_timeout_does_clean -> 172: dynamic_modules:ensure_modules(host_type(), required_modules(testcase, CN)), 173: Config2 = register_some_smid_h(Config), 174: escalus:init_per_testcase(CN, Config2); 175: init_per_testcase(ping_timeout = CN, Config) -> 176: ok = rpc(mim(), meck, new, [mod_ping, [passthrough, no_link]]), 177: dynamic_modules:ensure_modules(host_type(), required_modules(testcase, CN)), 178: escalus:init_per_testcase(CN, Config); 179: init_per_testcase(server_requests_ack_freq_2 = CN, Config) -> 180: escalus:init_per_testcase(CN, Config); 181: init_per_testcase(replies_are_processed_by_resumed_session = CN, Config) -> 182: register_handler(), 183: escalus:init_per_testcase(CN, Config); 184: init_per_testcase(CaseName, Config) -> 185: escalus:init_per_testcase(CaseName, Config). 186: 187: end_per_testcase(CN, Config) when CN =:= resume_expired_session_returns_correct_h; 188: CN =:= gc_repeat_after_never_means_no_cleaning; 189: CN =:= gc_repeat_after_timeout_does_clean -> 190: Name = rpc(mim(), gen_mod, get_module_proc, [host_type(), stream_management_stale_h]), 191: rpc(mim(), ejabberd_sup, stop_child, [Name]), 192: escalus:end_per_testcase(CN, Config); 193: end_per_testcase(replies_are_processed_by_resumed_session = CN, Config) -> 194: unregister_handler(), 195: escalus:end_per_testcase(CN, Config); 196: end_per_testcase(ping_timeout = CN, Config) -> 197: rpc(mim(), meck, unload, [mod_ping]), 198: escalus:end_per_testcase(CN, Config); 199: end_per_testcase(CaseName, Config) -> 200: escalus:end_per_testcase(CaseName, Config). 201: 202: %% Module configuration per group (in case of stale_h group it is per testcase) 203: 204: required_modules(Scope, Name) -> 205: SMConfig = case required_sm_opts(Scope, Name) of 206: stopped -> stopped; 207: ExtraOpts -> maps:merge(common_sm_opts(), ExtraOpts) 208: end, 209: Backend = mongoose_helper:mnesia_or_rdbms_backend(), 210: BaseModules = [ 211: {mod_stream_management, config_parser_helper:mod_config(mod_stream_management, SMConfig)}, 212: {mod_offline, config_parser_helper:mod_config(mod_offline, #{backend => Backend})} 213: ], 214: case Name of 215: ping_timeout -> 216: BaseModules ++ [{mod_ping, config_parser_helper:mod_config(mod_ping, mod_ping_opts())}]; 217: _ -> 218: BaseModules 219: end. 220: 221: required_sm_opts(group, parallel) -> 222: #{ack_freq => never}; 223: required_sm_opts(group, parallel_manual_ack_freq_1) -> 224: #{ack_freq => 1, 225: resume_timeout => ?LONG_TIMEOUT}; 226: required_sm_opts(group, manual_ack_freq_2) -> 227: #{ack_freq => 2}; 228: required_sm_opts(group, stream_mgmt_disabled) -> 229: stopped; 230: required_sm_opts(group, parallel_unacknowledged_message_hook) -> 231: #{ack_freq => 1}; 232: required_sm_opts(group, manual_ack_freq_long_session_timeout) -> 233: #{ack_freq => 1, buffer_max => 1000}; 234: required_sm_opts(testcase, resume_expired_session_returns_correct_h) -> 235: #{ack_freq => 1, 236: resume_timeout => ?SHORT_TIMEOUT, 237: stale_h => stale_h(?LONG_TIMEOUT, ?LONG_TIMEOUT)}; 238: required_sm_opts(testcase, gc_repeat_after_never_means_no_cleaning) -> 239: #{stale_h => stale_h(?LONG_TIMEOUT, ?SHORT_TIMEOUT)}; 240: required_sm_opts(testcase, gc_repeat_after_timeout_does_clean) -> 241: #{stale_h => stale_h(?SHORT_TIMEOUT, ?SHORT_TIMEOUT)}; 242: required_sm_opts(testcase, ping_timeout) -> 243: #{ack_freq => 1, 244: resume_timeout => ?SHORT_TIMEOUT}. 245: 246: common_sm_opts() -> 247: Backend = ct_helper:get_internal_database(), 248: #{buffer_max => ?SMALL_SM_BUFFER, backend => Backend}. 249: 250: stale_h(RepeatAfter, Geriatric) -> 251: #{enabled => true, 252: repeat_after => RepeatAfter, 253: geriatric => Geriatric}. 254: 255: make_smid() -> 256: base64:encode(crypto:strong_rand_bytes(21)). 257: 258: register_smid(IntSmidId) -> 259: S = {SMID = make_smid(), IntSmidId}, 260: ok = rpc(mim(), ?MOD_SM, register_stale_smid_h, [host_type(), SMID, IntSmidId]), 261: S. 262: 263: register_some_smid_h(Config) -> 264: TestSmids = lists:map(fun register_smid/1, lists:seq(1, 3)), 265: [{smid_test, TestSmids} | Config]. 266: 267: mod_ping_opts() -> 268: #{send_pings => true, 269: ping_interval => ?PING_INTERVAL, 270: ping_req_timeout => ?PING_REQUEST_TIMEOUT, 271: timeout_action => kill}. 272: 273: %%-------------------------------------------------------------------- 274: %% Tests 275: %%-------------------------------------------------------------------- 276: 277: server_announces_sm(Config) -> 278: AliceSpec = escalus_fresh:freshen_spec(Config, alice), 279: {ok, #client{props = Props}, Features} = escalus_connection:start(AliceSpec, 280: [start_stream]), 281: true = escalus_session:can_use_stream_management(Props, Features). 282: 283: 284: server_enables_sm_before_session(Config) -> 285: connect_fresh(Config, alice, sm_after_bind). 286: 287: server_enables_sm_after_session(Config) -> 288: connect_fresh(Config, alice, sm_after_session). 289: 290: server_returns_failed_after_start(Config) -> 291: Alice = connect_fresh(Config, alice, before_auth), 292: server_returns_failed(Alice). 293: 294: server_returns_failed_after_auth(Config) -> 295: Alice = connect_fresh(Config, alice, auth), 296: server_returns_failed(Alice). 297: 298: server_enables_resumption(Config) -> 299: Alice = connect_fresh(Config, alice, sr_presence), 300: escalus_connection:stop(Alice). 301: 302: server_returns_failed(Alice) -> 303: escalus_connection:send(Alice, escalus_stanza:enable_sm()), 304: escalus:assert(is_sm_failed, [<<"unexpected-request">>], 305: escalus_connection:get_stanza(Alice, enable_sm_failed)). 306: 307: client_enables_sm_twice_fails_with_correct_error_stanza(Config) -> 308: Alice = connect_fresh(Config, alice, sm_before_session), 309: escalus_connection:send(Alice, escalus_stanza:enable_sm()), 310: escalus:assert(is_sm_failed, [<<"unexpected-request">>], 311: escalus_connection:get_stanza(Alice, enable_sm_failed)), 312: escalus:assert(is_stream_end, 313: escalus_connection:get_stanza(Alice, enable_sm_failed)), 314: true = escalus_connection:wait_for_close(Alice, timer:seconds(5)). 315: 316: session_resumed_then_old_session_is_closed_gracefully_with_correct_error_stanza(Config) -> 317: %% GIVEN USER WITH STREAM RESUMPTION ENABLED 318: Alice = connect_fresh(Config, alice, sr_presence), 319: SMH = escalus_connection:get_sm_h(Alice), 320: %% WHEN USER RESUMES SESSION FROM NEW CLIENT 321: Alice2 = connect_resume(Alice, SMH), 322: process_initial_stanza(Alice2), 323: %% THEN: Old session is gracefully closed with the correct error stanza 324: escalus:assert(is_stream_error, [<<"conflict">>, <<>>], 325: escalus_connection:get_stanza(Alice, close_old_stream)), 326: escalus:assert(is_stream_end, 327: escalus_connection:get_stanza(Alice, close_old_stream)), 328: true = escalus_connection:wait_for_close(Alice, timer:seconds(5)), 329: true = escalus_connection:is_connected(Alice2), 330: escalus_connection:stop(Alice2). 331: 332: session_resumed_and_old_session_dead_doesnt_route_error_to_new_session(Config) -> 333: %% GIVEN USER WITH STREAM RESUMPTION ENABLED 334: Alice = connect_fresh(Config, alice, sr_presence), 335: %% WHEN FIRST SESSION DIES AND USER RESUMES FROM NEW CLIENT 336: Alice2 = sm_helper:kill_and_connect_resume(Alice), 337: process_initial_stanza(Alice2), 338: %% THEN new session does not have any message rerouted 339: false = escalus_client:has_stanzas(Alice2), 340: true = escalus_connection:is_connected(Alice2), 341: escalus_connection:stop(Alice2). 342: 343: basic_ack(Config) -> 344: Alice = connect_fresh(Config, alice, sm_after_session), 345: escalus_connection:send(Alice, escalus_stanza:roster_get()), 346: escalus:assert(is_roster_result, 347: escalus_connection:get_stanza(Alice, roster_result)), 348: escalus_connection:send(Alice, escalus_stanza:sm_request()), 349: escalus:assert(is_sm_ack, 350: escalus_connection:get_stanza(Alice, stream_mgmt_ack)). 351: 352: %% Test that "h" value is valid when: 353: %% - SM is enabled *before* the session is established 354: %% - <r/> is sent *before* the session is established 355: h_ok_before_session(Config) -> 356: Alice = connect_fresh(Config, alice, sm_after_bind), 357: escalus_connection:send(Alice, escalus_stanza:sm_request()), 358: escalus:assert(is_sm_ack, [0], 359: escalus_connection:get_stanza(Alice, stream_mgmt_ack)). 360: 361: %% Test that "h" value is valid when: 362: %% - SM is enabled *before* the session is established 363: %% - <r/> is sent *after* the session is established 364: h_ok_after_session_enabled_before_session(Config) -> 365: Alice = connect_fresh(Config, alice, sm_before_session), 366: escalus_connection:send(Alice, escalus_stanza:sm_request()), 367: escalus:assert(is_sm_ack, [1], 368: escalus_connection:get_stanza(Alice, stream_mgmt_ack)). 369: 370: %% Test that "h" value is valid when: 371: %% - SM is enabled *after* the session is established 372: %% - <r/> is sent *after* the session is established 373: h_ok_after_session_enabled_after_session(Config) -> 374: Alice = connect_fresh(Config, alice, sm_after_session), 375: escalus_connection:send(Alice, escalus_stanza:roster_get()), 376: escalus:assert(is_roster_result, 377: escalus_connection:get_stanza(Alice, roster_result)), 378: escalus_connection:send(Alice, escalus_stanza:sm_request()), 379: escalus:assert(is_sm_ack, [1], 380: escalus_connection:get_stanza(Alice, stream_mgmt_ack)). 381: 382: %% Test that "h" value is valid after exchanging a few messages. 383: h_ok_after_a_chat(ConfigIn) -> 384: Config = escalus_users:update_userspec(ConfigIn, alice, 385: stream_management, true), 386: escalus:fresh_story(Config, [{alice,1}, {bob,1}], fun(Alice, Bob) -> 387: escalus:send(Alice, escalus_stanza:chat_to(Bob, <<"Hi, Bob!">>)), 388: escalus:assert(is_chat_message, [<<"Hi, Bob!">>], 389: escalus:wait_for_stanza(Bob)), 390: escalus:send(Bob, escalus_stanza:chat_to(Alice, <<"Hi, Alice!">>)), 391: escalus:assert(is_chat_message, [<<"Hi, Alice!">>], 392: escalus:wait_for_stanza(Alice)), 393: escalus:send(Bob, escalus_stanza:chat_to(Alice, <<"How's life?">>)), 394: escalus:assert(is_chat_message, [<<"How's life?">>], 395: escalus:wait_for_stanza(Alice)), 396: escalus:send(Alice, escalus_stanza:chat_to(Bob, <<"Pretty !@#$%^$">>)), 397: escalus:assert(is_chat_message, [<<"Pretty !@#$%^$">>], 398: escalus:wait_for_stanza(Bob)), 399: escalus:send(Alice, escalus_stanza:sm_request()), 400: escalus:assert(is_sm_ack, [3], escalus:wait_for_stanza(Alice)), 401: %% Ack, so that unacked messages don't go into offline store. 402: escalus:send(Alice, escalus_stanza:sm_ack(3)) 403: end). 404: 405: h_non_given_closes_stream_gracefully(ConfigIn) -> 406: AStanza = #xmlel{name = <<"a">>, 407: attrs = [{<<"xmlns">>, <<"urn:xmpp:sm:3">>}]}, 408: Config = escalus_users:update_userspec(ConfigIn, alice, 409: stream_management, true), 410: escalus:fresh_story(Config, [{alice,1}], fun(Alice) -> 411: C2SPid = mongoose_helper:get_session_pid(Alice), 412: escalus:send(Alice, AStanza), 413: escalus:assert(is_stream_error, 414: [<<"policy-violation">>, <<>>], 415: escalus:wait_for_stanza(Alice)), 416: mongoose_helper:wait_for_pid_to_die(C2SPid), 417: escalus:assert(is_stream_end, escalus_connection:get_stanza(Alice, stream_end)), 418: true = escalus_connection:wait_for_close(Alice, timer:seconds(5)) 419: end). 420: 421: client_acks_more_than_sent(Config) -> 422: Alice = connect_fresh(Config, alice, sm_after_session), 423: escalus:send(Alice, escalus_stanza:sm_ack(5)), 424: StreamErrorStanza = escalus:wait_for_stanza(Alice), 425: %% Assert "undefined-condition" children 426: escalus:assert(is_stream_error, [<<"undefined-condition">>, <<>>], StreamErrorStanza), 427: %% Assert "handled-count-too-high" children with correct attributes 428: HandledCountSubElement = exml_query:path(StreamErrorStanza, 429: [{element_with_ns, 430: <<"handled-count-too-high">>, 431: <<"urn:xmpp:sm:3">>}]), 432: <<"5">> = exml_query:attr(HandledCountSubElement, <<"h">>), 433: <<"0">> = exml_query:attr(HandledCountSubElement, <<"send-count">>), 434: %% Assert graceful stream end 435: escalus:assert(is_stream_end, escalus_connection:get_stanza(Alice, stream_end)), 436: true = escalus_connection:wait_for_close(Alice, timer:seconds(5)). 437: 438: too_many_unacked_stanzas(Config) -> 439: Bob = connect_fresh(Config, bob, presence), 440: Alice = connect_fresh(Config, alice, sm_presence, manual), 441: get_ack(Alice), 442: [escalus:send(Bob, escalus_stanza:chat_to(Alice, 443: <<(integer_to_binary(N))/binary, ": Hi, Alice!">>)) 444: || N <- lists:seq(1,?SMALL_SM_BUFFER)], 445: escalus:wait_for_stanzas(Alice, ?SMALL_SM_BUFFER * 2), % messages and ack requests 446: escalus:assert(is_stream_error, [<<"resource-constraint">>, 447: <<"too many unacked stanzas">>], 448: %% wait for deferred buffer check 449: escalus:wait_for_stanza(Alice, ?CONSTRAINT_CHECK_TIMEOUT + 1000)). 450: 451: server_requests_ack(Config) -> 452: server_requests_ack(Config, 1). 453: 454: server_requests_ack_freq_2(Config) -> 455: server_requests_ack(Config, 2). 456: 457: server_requests_ack(Config, N) -> 458: Bob = connect_fresh(Config, bob, presence), 459: Alice = connect_fresh(Config, alice, sm_presence, manual), 460: %% ack request after initial presence 461: maybe_assert_ack_request(1, N, Alice), 462: escalus:send(Bob, escalus_stanza:chat_to(Alice, <<"Hi, Alice!">>)), 463: escalus:assert(is_chat_message, [<<"Hi, Alice!">>], 464: escalus:wait_for_stanza(Alice)), 465: maybe_assert_ack_request(2, N, Alice). 466: 467: maybe_assert_ack_request(StanzasRec, AckRequests, Alice) -> 468: ct:log("StanzasRec: ~p, AckRequests: ~p", [StanzasRec, AckRequests]), 469: case StanzasRec rem AckRequests of 470: 0 -> 471: escalus:assert(is_sm_ack_request, escalus:wait_for_stanza(Alice)); 472: _ -> 473: ok 474: end, 475: StanzasRec. 476: 477: server_requests_ack_after_session(Config) -> 478: Alice = connect_fresh(Config, alice, sm_before_session, manual), 479: escalus:assert(is_sm_ack_request, escalus_connection:get_stanza(Alice, stream_mgmt_req)). 480: 481: resend_more_offline_messages_than_buffer_size(Config) -> 482: %% connect bob and alice 483: Bob = connect_fresh(Config, bob, presence), 484: AliceSpec = escalus_fresh:create_fresh_user(Config, alice), 485: 486: % sent some messages - more than unacked buffer size 487: MessagesToSend = ?SMALL_SM_BUFFER + 1, 488: AliceJid = common_helper:get_bjid(AliceSpec), 489: [escalus_connection:send(Bob, escalus_stanza:chat_to(AliceJid, integer_to_binary(I))) 490: || I <- lists:seq(1, MessagesToSend)], 491: mongoose_helper:wait_for_n_offline_messages(AliceJid, MessagesToSend), 492: 493: % connect alice who wants to receive all messages from offline storage 494: Alice = connect_spec(AliceSpec, sm_after_session, manual), 495: send_initial_presence(Alice), 496: escalus:wait_for_stanzas(Alice, MessagesToSend * 2), %messages and ack requests 497: 498: escalus_connection:get_stanza(Alice, presence), 499: get_ack(Alice), % ack request 500: 501: % confirm messages + presence 502: escalus_connection:send(Alice, escalus_stanza:sm_ack(4)), 503: % wait for check constraint message on server side 504: 505: ct:sleep(?CONSTRAINT_CHECK_TIMEOUT + 1000), 506: false = escalus_client:has_stanzas(Alice), 507: % should not receive anything especially any stream errors 508: 509: escalus_connection:stop(Alice), 510: escalus_connection:stop(Bob). 511: 512: resend_unacked_on_reconnection(Config) -> 513: Texts = three_texts(), 514: Bob = connect_fresh(Config, bob, presence), 515: Alice = connect_fresh(Config, alice, sm_presence), 516: AliceSpec = sm_helper:client_to_spec0(Alice), 517: %% Bob sends some messages to Alice. 518: sm_helper:send_messages(Bob, Alice, Texts), 519: %% Alice receives the messages. 520: sm_helper:wait_for_messages(Alice, Texts), 521: %% Alice disconnects without acking the messages. 522: sm_helper:stop_client_and_wait_for_termination(Alice), 523: %% Messages go to the offline store. 524: %% Alice receives the messages from the offline store. 525: NewAlice = connect_spec(AliceSpec, session, manual), 526: send_initial_presence(NewAlice), 527: sm_helper:wait_for_messages(NewAlice, Texts), 528: %% Alice acks the delayed messages so they won't go again 529: %% to the offline store. 530: escalus_connection:send(NewAlice, escalus_stanza:sm_ack(3)). 531: 532: %% Remove wait_for_n_offline_messages and you will get anything, but preserve_order 533: %% TODO Test without wait_for_n_offline_messages. It would require changes in SM 534: %% and more strict tests, reproducing delays in SM and in mod_offline. 535: preserve_order(Config) -> 536: %% connect bob and alice 537: Bob = connect_fresh(Config, bob, presence), 538: Alice = connect_fresh(Config, alice, sr_presence, manual), 539: AliceSpec = sm_helper:client_to_spec(Alice), 540: escalus_connection:send(Bob, escalus_stanza:chat_to_short_jid(Alice, <<"1">>)), 541: 542: %% kill alice connection 543: escalus_connection:kill(Alice), 544: C2SPid = mongoose_helper:get_session_pid(Alice), 545: sm_helper:wait_until_resume_session(C2SPid), 546: 547: escalus_connection:send(Bob, escalus_stanza:chat_to_short_jid(Alice, <<"2">>)), 548: escalus_connection:send(Bob, escalus_stanza:chat_to_short_jid(Alice, <<"3">>)), 549: 550: NewAlice = connect_spec(AliceSpec, session, manual), 551: escalus_connection:send(NewAlice, escalus_stanza:enable_sm([resume])), 552: 553: escalus_connection:send(Bob, escalus_stanza:chat_to_short_jid(Alice, <<"4">>)), 554: escalus_connection:send(Bob, escalus_stanza:chat_to_short_jid(Alice, <<"5">>)), 555: 556: %% Without this check we will get stuff out of order 557: mongoose_helper:wait_for_n_offline_messages(NewAlice, 5), 558: 559: send_initial_presence(NewAlice), 560: %% Without this check we can get "6, 1, 2, 3, 4, 5" messages in the next receive_all_ordered 561: mongoose_helper:wait_for_n_offline_messages(NewAlice, 0), 562: escalus_connection:send(Bob, escalus_stanza:chat_to_short_jid(Alice, <<"6">>)), 563: 564: %% "2, 3, 4, 5, 6, 1" is possible (where only 1 is from offline storage, the rest is from sm) 565: receive_all_ordered(NewAlice, 6), 566: 567: % replace connection 568: NewAlice2 = connect_spec(AliceSpec, session, manual), 569: % allow messages to go to the offline storage 570: mongoose_helper:wait_for_n_offline_messages(NewAlice, 6), 571: 572: send_initial_presence(NewAlice2), 573: 574: % receves messages in correct order 575: receive_all_ordered(NewAlice2, 6), 576: 577: escalus_connection:stop(Bob), 578: escalus_connection:stop(NewAlice2). 579: 580: receive_all_ordered(Conn, Last) -> 581: receive_all_ordered(Conn, 1, Last, []). 582: 583: %% Receive messages from N to Last. 584: %% Ignores acks and presences. 585: %% Handles case when out of order and when not enough stanzas. 586: receive_all_ordered(_Conn, N, Last, Acc) when N > Last -> 587: Texts = lists:map(fun integer_to_binary/1, lists:seq(1, Last)), 588: sm_helper:assert_messages(Acc, Texts); 589: receive_all_ordered(Conn, N, Last, Acc) -> 590: Stanzas = escalus:wait_for_stanzas(Conn, 1), 591: case Stanzas of 592: [#xmlel{name = <<"message">>}] -> 593: receive_all_ordered(Conn, N + 1, Last, Acc ++ Stanzas); 594: [_] -> %% Ack or presence 595: receive_all_ordered(Conn, N, Last, Acc); 596: [] -> 597: ct:fail({timeout_waiting, N, Acc}) 598: end. 599: 600: resend_unacked_after_resume_timeout(Config) -> 601: %% connect bob and alice 602: Bob = connect_fresh(Config, bob, presence), 603: Alice = connect_fresh(Config, alice, sr_presence), 604: AliceSpec = sm_helper:client_to_spec(Alice), 605: 606: escalus_connection:send(Bob, escalus_stanza:chat_to_short_jid(Alice, <<"msg-1">>)), 607: %% kill alice connection 608: escalus_connection:kill(Alice), 609: 610: %% ensure there is no session 611: C2SPid = mongoose_helper:get_session_pid(Alice), 612: sm_helper:wait_until_resume_session(C2SPid), 613: 614: %% alice come back and receives unacked message 615: NewAlice = connect_spec(AliceSpec, session), 616: send_initial_presence(NewAlice), 617: 618: escalus_new_assert:mix_match([is_presence, is_chat(<<"msg-1">>)], 619: escalus:wait_for_stanzas(NewAlice, 2)), 620: 621: escalus_connection:stop(Bob), 622: escalus_connection:stop(NewAlice). 623: 624: ping_timeout(Config) -> 625: %% make sure there are no leftover stanzas in the history 626: ?assertEqual([], get_stanzas_filtered_by_mod_ping()), 627: 628: %% connect Alice and wait for the session to close 629: Alice = connect_fresh(Config, alice, sr_presence), 630: 631: escalus_client:wait_for_stanza(Alice), 632: ct:sleep(?PING_REQUEST_TIMEOUT + ?PING_INTERVAL + timer:seconds(1)), 633: 634: %% attempt to resume the session after the connection drop 635: NewAlice = sm_helper:kill_and_connect_with_resume_session_without_waiting_for_result(Alice), 636: 637: %% after resume_timeout, we expect the session to be closed 638: escalus_connection:get_stanza(NewAlice, failed_resumption), 639: 640: %% bind a new session and expect unacknowledged messages to be resent 641: escalus_session:session(escalus_session:bind(NewAlice)), 642: send_initial_presence(NewAlice), 643: 644: %% check if the error stanza was handled by mod_ping 645: [Stanza] = get_stanzas_filtered_by_mod_ping(), 646: escalus:assert(is_iq_error, Stanza), 647: ?assertNotEqual(undefined, 648: exml_query:subelement_with_name_and_ns(Stanza, <<"ping">>, <<"urn:xmpp:ping">>)), 649: 650: %% stop the connection 651: escalus_connection:stop(NewAlice). 652: 653: resume_expired_session_returns_correct_h(Config) -> 654: %% connect bob and alice 655: Bob = connect_fresh(Config, bob, sr_presence), 656: Alice = connect_fresh(Config, alice, sr_presence, manual), 657: get_ack(Alice), 658: 659: %% Bob sends a message to Alice, and Alice receives it but doesn't acknowledge 660: escalus_connection:send(Bob, escalus_stanza:chat_to_short_jid(Alice, <<"msg-1">>)), 661: escalus:assert(is_chat_message, [<<"msg-1">>], escalus:wait_for_stanza(Alice)), 662: %% alice comes back, but too late, so resumption doesn't work, 663: %% but she receives the previous h = 1 anyway 664: %% NewAlice is also manual ack 665: NewAlice = sm_helper:kill_and_connect_with_resume_session_without_waiting_for_result(Alice), 666: FailedResumption = escalus_connection:get_stanza(NewAlice, failed_resumption), 667: <<"1">> = exml_query:attr(FailedResumption, <<"h">>), 668: %% And we can continue with bind and session 669: escalus_session:session(escalus_session:bind(NewAlice)), 670: send_initial_presence(NewAlice), 671: Stanzas = [escalus_connection:get_stanza(NewAlice, {msg, 1}), 672: escalus_connection:get_stanza(NewAlice, {msg, 2})], 673: escalus_new_assert:mix_match([is_presence, is_chat(<<"msg-1">>)], Stanzas), 674: escalus_connection:stop(Bob), 675: escalus_connection:stop(NewAlice). 676: 677: gc_repeat_after_never_means_no_cleaning(Config) -> 678: [{SMID1, _}, {SMID2, _}, {SMID3, _}] = ?config(smid_test, Config), 679: {stale_h, 1} = rpc(mim(), ?MOD_SM, get_session_from_smid, [host_type(), SMID1]), 680: {stale_h, 2} = rpc(mim(), ?MOD_SM, get_session_from_smid, [host_type(), SMID2]), 681: {stale_h, 3} = rpc(mim(), ?MOD_SM, get_session_from_smid, [host_type(), SMID3]). 682: 683: gc_repeat_after_timeout_does_clean(Config) -> 684: [{SMID1, _} | _ ] = ?config(smid_test, Config), 685: mongoose_helper:wait_until(fun() -> 686: rpc(mim(), ?MOD_SM, get_stale_h, [host_type(), SMID1]) 687: end, 688: {error, smid_not_found}, 689: #{name => smid_garbage_collected}). 690: 691: resume_session_state_send_message_without_ack(Config) -> 692: resume_session_state_send_message_generic(Config, no_ack). 693: 694: resume_session_state_send_message_with_ack(Config) -> 695: resume_session_state_send_message_generic(Config, ack). 696: 697: resume_session_state_send_message_generic(Config, AckInitialPresence) -> 698: %% connect bob and alice 699: Bob = connect_fresh(Config, bob, presence), 700: Alice = connect_fresh(Config, alice, sr_presence, manual), 701: maybe_ack_initial_presence(Alice, AckInitialPresence), 702: escalus_connection:send(Bob, escalus_stanza:chat_to_short_jid(Alice, <<"msg-1">>)), 703: %% kill alice connection 704: C2SPid = mongoose_helper:get_session_pid(Alice), 705: escalus_connection:kill(Alice), 706: sm_helper:wait_until_resume_session(C2SPid), 707: sm_helper:assert_alive_resources(Alice, 1), 708: 709: %% send some messages and check if c2s can handle it 710: escalus_connection:send(Bob, escalus_stanza:chat_to_short_jid(Alice, <<"msg-2">>)), 711: escalus_connection:send(Bob, escalus_stanza:chat_to_short_jid(Alice, <<"msg-3">>)), 712: %% suspend the process to ensure that Alice has enough time to reconnect, 713: %% before resumption timeout occurs. 714: ok = rpc(mim(), sys, suspend, [C2SPid]), 715: 716: %% alice comes back and receives unacked message 717: NewAlice = connect_same(Alice, presence), 718: %% now we can resume c2s process of the old connection 719: %% and let it process session resumption timeout 720: ok = rpc(mim(), sys, resume, [C2SPid]), 721: Stanzas = escalus:wait_for_stanzas(NewAlice, 3), 722: 723: % what about order ? 724: % alice receive presence from herself and 3 unacked messages from bob 725: escalus_new_assert:mix_match([is_chat(<<"msg-1">>), 726: is_chat(<<"msg-2">>), 727: is_chat(<<"msg-3">>)], 728: Stanzas), 729: escalus_connection:stop(Bob), 730: escalus_connection:stop(NewAlice). 731: 732: %%for instance it can be done by mod ping 733: resume_session_state_stop_c2s(Config) -> 734: Bob = connect_fresh(Config, bob, presence), 735: Alice = connect_fresh(Config, alice, sr_presence, manual), 736: 737: get_ack(Alice), 738: ack_initial_presence(Alice), 739: 740: escalus_connection:send(Bob, escalus_stanza:chat_to_short_jid(Alice, <<"msg-1">>)), 741: escalus:assert(is_chat_message, [<<"msg-1">>], escalus_connection:get_stanza(Alice, msg)), 742: 743: %% get pid of c2s 744: C2SPid = mongoose_helper:get_session_pid(Alice), 745: %% Wait c2s process to process our presence ack. 746: %% Otherwise, we can receive two initial presences sometimes. 747: sm_helper:wait_for_c2s_unacked_count(C2SPid, 1), 748: 749: % kill alice connection 750: escalus_connection:kill(Alice), 751: % session should be alive 752: sm_helper:assert_alive_resources(Alice, 1), 753: rpc(mim(), mongoose_c2s, stop, [C2SPid, normal]), 754: sm_helper:wait_until_resume_session(C2SPid), 755: %% suspend the process to ensure that Alice has enough time to reconnect, 756: %% before resumption timeout occurs. 757: ok = rpc(mim(), sys, suspend, [C2SPid]), 758: 759: %% alice comes back and receives unacked message 760: NewAlice = connect_same(Alice, presence, manual), 761: %% now we can resume c2s process of the old connection 762: %% and let it process session resumption timeout 763: ok = rpc(mim(), sys, resume, [C2SPid]), 764: 765: escalus:assert(is_chat_message, [<<"msg-1">>], escalus_connection:get_stanza(NewAlice, msg)), 766: escalus_connection:stop(Bob), 767: escalus_connection:stop(NewAlice). 768: 769: %% This test only verifies the validity of helpers (get_session_pid, 770: %% get_c2s_state_name) written for wait_for_resumption 771: %% testcase. 772: session_established(Config) -> 773: Alice = connect_fresh(Config, alice, presence), 774: C2SPid = mongoose_helper:get_session_pid(Alice), 775: session_established = mongoose_helper:get_c2s_state_name(C2SPid), 776: escalus_connection:stop(Alice). 777: 778: %% Ensure that after a violent disconnection, 779: %% the c2s waits for resumption (but don't resume yet). 780: wait_for_resumption(Config) -> 781: AliceSpec = escalus_fresh:create_fresh_user(Config, alice), 782: Bob = connect_fresh(Config, bob, session), 783: Texts = three_texts(), 784: {C2SPid, _} = buffer_unacked_messages_and_die(Config, AliceSpec, Bob, Texts), 785: sm_helper:wait_until_resume_session(C2SPid). 786: 787: unacknowledged_message_hook_filter(Config) -> 788: FilterText = <<"filter">>, 789: Bob = connect_fresh(Config, bob, presence), 790: AliceSpec = escalus_fresh:create_fresh_user(Config, alice), 791: Resource = proplists:get_value(username, AliceSpec), 792: HookHandlerExtra = start_filter_hook_listener(FilterText, Resource), 793: Alice = connect_spec([{resource, Resource} | AliceSpec], sr_presence, manual), 794: %% Ack the presence stanza 795: get_ack(Alice), 796: ack_initial_presence(Alice), 797: Messages = [<<"msg-1">>, <<"msg-2">>, <<"msg-3">>, <<"msg-4">>], 798: All = [<<"msg-1">>, FilterText, <<"msg-2">>, FilterText, <<"msg-3">>, <<"msg-4">>], 799: [ escalus_connection:send(Bob, escalus_stanza:chat_to_short_jid(Alice, Body)) || Body <- All ], 800: %% kill alice connection 801: C2SPid = mongoose_helper:get_session_pid(Alice), 802: escalus_connection:kill(Alice), 803: sm_helper:wait_until_resume_session(C2SPid), 804: sm_helper:assert_alive_resources(Alice, 1), 805: %% ensure second C2S is registered so all the messages are bounced properly 806: NewAlice = connect_spec([{resource, <<"2">>}| AliceSpec], sr_presence, manual), 807: send_initial_presence(NewAlice), 808: sm_helper:wait_for_resource_count(NewAlice, 2), 809: ok = rpc(mim(), sys, terminate, [C2SPid, normal]), 810: %% verify that the filtered message is never received 811: verify_no_receive_filtertext(NewAlice, FilterText, Messages), 812: stop_hook_listener(HookHandlerExtra), 813: escalus_connection:stop(Bob). 814: 815: verify_no_receive_filtertext(_, _, []) -> 816: ok; 817: verify_no_receive_filtertext(Client, FilterText, Messages) -> 818: case escalus:wait_for_stanzas(Client, 1, 500) of 819: [] -> ct:fail("Messages pending: ~p~n", [Messages]); 820: [St] -> 821: case exml_query:path(St, [{element, <<"body">>}, cdata]) of 822: undefined -> 823: verify_no_receive_filtertext(Client, FilterText, Messages); 824: FilterText -> 825: ct:fail("Composing forwarded from a different c2s process"); 826: Message -> 827: Pred = fun(Msg) -> Msg =/= Message end, 828: {Pending, _} = lists:partition(Pred, Messages), 829: verify_no_receive_filtertext(Client, FilterText, Pending) 830: end 831: end. 832: 833: unacknowledged_message_hook_resume(Config) -> 834: unacknowledged_message_hook_common(fun unacknowledged_message_hook_resume/4, Config). 835: 836: unacknowledged_message_hook_resume(AliceSpec, Resource, SMID, _C2SPid) -> 837: NewAlice = connect_spec(AliceSpec, {resume, SMID, 1}, manual), 838: send_initial_presence(NewAlice), 839: {Resource, NewAlice}. 840: 841: unacknowledged_message_hook_bounce(Config) -> 842: unacknowledged_message_hook_common(fun unacknowledged_message_hook_bounce/4, Config). 843: 844: unacknowledged_message_hook_bounce(AliceSpec, Resource, _SMID, C2SPid) -> 845: NewResource = <<"new_", Resource/binary>>, 846: NewSpec = lists:keystore(resource, 1, AliceSpec, {resource, NewResource}), 847: NewAlice = connect_spec(NewSpec, sr_session, manual), 848: send_initial_presence(NewAlice), 849: %% ensure second C2S is registered so all the messages are bounced properly 850: sm_helper:wait_for_resource_count(NewAlice, 2), 851: ok = rpc(mim(), sys, terminate, [C2SPid, normal]), 852: {NewResource, NewAlice}. 853: 854: unacknowledged_message_hook_offline(Config) -> 855: unacknowledged_message_hook_common(fun unacknowledged_message_hook_offline/4, Config). 856: 857: unacknowledged_message_hook_offline(AliceSpec, Resource, _SMID, C2SPid) -> 858: C2SRef = erlang:monitor(process, C2SPid), 859: sm_helper:wait_for_process_termination(C2SRef), 860: %% reset the session, so old C2S process is stopped 861: NewAlice = connect_spec(AliceSpec, sr_session, manual), 862: %% wait for old C2S termination before send presence. other way 863: %% some of the latest unacknowledged messages can be bounced to 864: %% the new C2S process instead of going to the mod_offline storage. 865: %% looks like all the unacknowledged messages arrive to the new 866: %% C2S, but the message sequence is broken (the bounced messages 867: %% delivered before the messages from the mod_offline storage) 868: send_initial_presence(NewAlice), 869: {Resource, NewAlice}. 870: 871: unacknowledged_message_hook_common(RestartConnectionFN, Config) -> 872: %% connect bob and alice 873: Bob = connect_fresh(Config, bob, presence), 874: 875: AliceSpec0 = escalus_fresh:create_fresh_user(Config, alice), 876: Resource = proplists:get_value(username, AliceSpec0), 877: AliceSpec = [{resource, Resource} | AliceSpec0], 878: HookHandlerExtra = start_hook_listener(Resource), 879: Alice = connect_spec(AliceSpec, sr_presence, manual), 880: %% Ack the presence stanza 881: get_ack(Alice), 882: ack_initial_presence(Alice), 883: 884: SMID = sm_helper:client_to_smid(Alice), 885: 886: escalus_connection:send(Bob, escalus_stanza:chat_to_short_jid(Alice, <<"msg-1">>)), 887: escalus_connection:send(Bob, escalus_stanza:chat_to_short_jid(Alice, <<"msg-2">>)), 888: %% kill alice connection 889: C2SPid = mongoose_helper:get_session_pid(Alice), 890: escalus_connection:kill(Alice), 891: sm_helper:wait_until_resume_session(C2SPid), 892: sm_helper:assert_alive_resources(Alice, 1), 893: 894: escalus:assert(is_chat_message, [<<"msg-1">>], wait_for_unacked_msg_hook(0, Resource, 100)), 895: escalus:assert(is_chat_message, [<<"msg-2">>], wait_for_unacked_msg_hook(0, Resource, 100)), 896: ?assertEqual(timeout, wait_for_unacked_msg_hook(0, Resource, 100)), 897: 898: %% send some messages and check if c2s can handle it 899: escalus_connection:send(Bob, escalus_stanza:chat_to_short_jid(Alice, <<"msg-3">>)), 900: escalus_connection:send(Bob, escalus_stanza:chat_to_short_jid(Alice, <<"msg-4">>)), 901: escalus:assert(is_chat_message, [<<"msg-3">>], wait_for_unacked_msg_hook(0, Resource, 100)), 902: escalus:assert(is_chat_message, [<<"msg-4">>], wait_for_unacked_msg_hook(0, Resource, 100)), 903: ?assertEqual(timeout, wait_for_unacked_msg_hook(0, Resource, 100)), 904: 905: %% alice comes back and receives unacked message 906: {NewResource, NewAlice} = RestartConnectionFN(AliceSpec, Resource, SMID, C2SPid), 907: 908: mongoose_helper:wait_until( 909: fun() -> 910: Stanza = escalus_connection:get_stanza(NewAlice, msg), 911: escalus:assert(is_chat_message, [<<"msg-4">>], Stanza), 912: ok 913: end, ok), 914: 915: NewC2SPid = mongoose_helper:get_session_pid(NewAlice), 916: escalus_connection:kill(NewAlice), 917: sm_helper:wait_until_resume_session(NewC2SPid), 918: 919: escalus:assert(is_chat_message, [<<"msg-1">>], wait_for_unacked_msg_hook(1, NewResource, 100)), 920: escalus:assert(is_chat_message, [<<"msg-2">>], wait_for_unacked_msg_hook(1, NewResource, 100)), 921: escalus:assert(is_chat_message, [<<"msg-3">>], wait_for_unacked_msg_hook(1, NewResource, 100)), 922: escalus:assert(is_chat_message, [<<"msg-4">>], wait_for_unacked_msg_hook(1, NewResource, 100)), 923: ?assertEqual(timeout, wait_for_unacked_msg_hook(0, Resource, 100)), 924: stop_hook_listener(HookHandlerExtra), 925: escalus_connection:stop(Bob). 926: 927: resume_session(Config) -> 928: AliceSpec = escalus_fresh:create_fresh_user(Config, alice), 929: Texts = three_texts(), 930: escalus:fresh_story(Config, [{bob, 1}], fun(Bob) -> 931: {_, SMID} = buffer_unacked_messages_and_die(Config, AliceSpec, Bob, Texts), 932: %% Resume the session. 933: Alice = connect_spec(AliceSpec, {resume, SMID, 1}, manual), 934: %% Alice receives the unacked messages from the previous 935: %% interrupted session. 936: sm_helper:wait_for_messages(Alice, Texts), 937: %% Alice acks the received messages. 938: escalus_connection:send(Alice, escalus_stanza:sm_ack(5)), 939: escalus_connection:stop(Alice) 940: end). 941: 942: resume_session_with_wrong_h_does_not_leak_sessions(Config) -> 943: AliceSpec = escalus_fresh:create_fresh_user(Config, alice), 944: Messages = three_texts(), 945: HostType = host_type(), 946: escalus:fresh_story(Config, [{bob, 1}], fun(Bob) -> 947: {_, SMID} = buffer_unacked_messages_and_die(Config, AliceSpec, Bob, Messages), 948: %% Resume the session. 949: Alice = connect_spec(AliceSpec, auth, manual), 950: Resumed = sm_helper:try_to_resume_stream(Alice, SMID, 30), 951: escalus:assert(is_stream_error, [<<"undefined-condition">>, <<>>], Resumed), 952: escalus_connection:wait_for_close(Alice, timer:seconds(5)), 953: Fun = fun() -> 954: [] = sm_helper:get_user_present_resources(Alice), 955: sm_helper:get_sid_by_stream_id(HostType, SMID) 956: end, 957: mongoose_helper:wait_until(Fun, {error, smid_not_found}, #{name => smid_is_cleaned}) 958: end). 959: 960: resume_session_with_wrong_sid_returns_item_not_found(Config) -> 961: session_resumption_expects_item_not_found(Config, <<"wrong-sid">>). 962: 963: resume_session_with_wrong_namespace_is_a_noop(Config) -> 964: Alice = connect_fresh(Config, alice, auth), 965: #xmlel{attrs = Attrs} = Resume = escalus_stanza:resume(<<"doesnt_matter">>, 4), 966: Attrs2 = lists:keyreplace(<<"xmlns">>, 1, Attrs, {<<"xmlns">>, <<"not-stream-mgnt">>}), 967: escalus_connection:send(Alice, Resume#xmlel{attrs = Attrs2}), 968: escalus_assert:has_no_stanzas(Alice), 969: [] = sm_helper:get_user_present_resources(Alice), 970: true = escalus_connection:is_connected(Alice), 971: escalus_connection:stop(Alice). 972: 973: resume_dead_session_results_in_item_not_found(Config) -> 974: SMID = base64:encode(crypto:strong_rand_bytes(21)), 975: SID = {os:timestamp(), undefined}, 976: HostType = host_type(), 977: rpc(mim(), ?MOD_SM, register_smid, [HostType, SMID, SID]), 978: session_resumption_expects_item_not_found(Config, SMID). 979: 980: session_resumption_expects_item_not_found(Config, SMID) -> 981: Alice = connect_fresh(Config, alice, auth), 982: Resumed = sm_helper:try_to_resume_stream(Alice, SMID, 2), 983: escalus:assert(is_sm_failed, [<<"item-not-found">>], Resumed), 984: [] = sm_helper:get_user_present_resources(Alice), 985: true = escalus_connection:is_connected(Alice), 986: escalus_connection:stop(Alice). 987: 988: resume_session_kills_old_C2S_gracefully(Config) -> 989: Alice = connect_fresh(Config, alice, sr_presence, manual), 990: C2SPid = mongoose_helper:get_session_pid(Alice), 991: 992: %% Monitor the C2S process and disconnect Alice. 993: MonitorRef = sm_helper:monitor_session(Alice), 994: escalus_client:kill_connection(Config, Alice), 995: 996: %% Ensure the c2s process is waiting for resumption. 997: sm_helper:wait_until_resume_session(C2SPid), 998: 999: %% Resume the session. 1000: NewAlice = connect_resume(Alice, 1), 1001: 1002: %% C2S process should die gracefully with Reason=normal. 1003: sm_helper:wait_for_process_termination(MonitorRef), 1004: escalus_connection:stop(NewAlice). 1005: 1006: carboncopy_works(Config) -> 1007: escalus:fresh_story(Config, [{alice, 2}, {bob, 1}], fun(Alice1, Alice, Bob) -> 1008: mongoose_helper:enable_carbons([Alice1, Alice]), 1009: escalus_connection:send(Bob, escalus_stanza:chat_to(Alice1, <<"msg-4">>)), 1010: sm_helper:wait_for_messages(Alice1, [<<"msg-4">>]), 1011: carboncopy_helper:wait_for_carbon_chat_with_body(Alice, <<"msg-4">>, #{from => Bob, to => Alice1}) 1012: end). 1013: 1014: carboncopy_works_after_resume(Config) -> 1015: Texts = three_texts(), 1016: escalus:fresh_story(Config, [{alice, 1}, {bob, 1}], fun(Alice1, Bob) -> 1017: AliceSpec = [{resource, <<"res2">>} | sm_helper:client_to_spec(Alice1)], 1018: F = fun(Alice2) -> 1019: [escalus:assert(is_presence_with_type, [<<"available">>], escalus:wait_for_stanza(A)) || A <- [Alice1, Alice2]], 1020: mongoose_helper:enable_carbons([Alice1, Alice2]) 1021: end, 1022: {_, SMID} = buffer_unacked_messages_and_die(Config, AliceSpec, Bob, Texts, F), 1023: %% Resume the session. 1024: Alice = connect_spec(AliceSpec, {resume, SMID, 1}, manual), 1025: wait_for_carbon_with_bodies(Alice1, Texts, #{from => Bob, to => Alice}), 1026: %% Get a presence from Alice1 again 1027: escalus:assert(is_presence_with_type, [<<"available">>], escalus:wait_for_stanza(Alice)), 1028: %% Alice receives an IQ result from the carbon copy enable request 1029: escalus:assert(is_iq_result, [], escalus:wait_for_stanza(Alice)), 1030: %% Alice receives the unacked messages from the previous 1031: %% interrupted session. 1032: sm_helper:wait_for_messages(Alice, Texts), 1033: %% Alice acks the received messages. 1034: escalus_connection:send(Alice, escalus_stanza:sm_ack(5)), 1035: %% Direct send 1036: escalus_connection:send(Bob, escalus_stanza:chat_to(Alice1, <<"msg-4">>)), 1037: sm_helper:wait_for_messages(Alice1, [<<"msg-4">>]), 1038: carboncopy_helper:wait_for_carbon_chat_with_body(Alice, <<"msg-4">>, #{from => Bob, to => Alice1}), 1039: escalus_connection:stop(Alice) 1040: end). 1041: 1042: wait_for_carbon_with_bodies(Client, Texts, Params) -> 1043: [carboncopy_helper:wait_for_carbon_chat_with_body(Client, Text, Params) || Text <- Texts]. 1044: 1045: buffer_unacked_messages_and_die(Config, AliceSpec, Bob, Texts) -> 1046: F = fun(_Client) -> ok end, 1047: buffer_unacked_messages_and_die(Config, AliceSpec, Bob, Texts, F). 1048: 1049: buffer_unacked_messages_and_die(Config, AliceSpec, Bob, Texts, F) -> 1050: Alice = connect_spec(AliceSpec, sr_presence, manual), 1051: F(Alice), 1052: C2SPid = mongoose_helper:get_session_pid(Alice), 1053: %% Bobs sends some messages to Alice. 1054: sm_helper:send_messages(Bob, Alice, Texts), 1055: %% Alice receives them, but doesn't ack. 1056: sm_helper:wait_for_messages(Alice, Texts), 1057: %% Alice's connection is violently terminated. 1058: escalus_client:kill_connection(Config, Alice), 1059: sm_helper:wait_until_resume_session(C2SPid), 1060: SMID = sm_helper:client_to_smid(Alice), 1061: {C2SPid, SMID}. 1062: 1063: aggressively_pipelined_resume(Config) -> 1064: AliceSpec = [{manual_ack, true}, {parser_opts, [{start_tag, <<"stream:stream">>}]} 1065: | escalus_fresh:create_fresh_user(Config, alice)], 1066: UnackedMessages = three_texts(), 1067: escalus:fresh_story(Config, [{bob, 1}], fun(Bob) -> 1068: {_, SMID} = buffer_unacked_messages_and_die(Config, AliceSpec, Bob, UnackedMessages), 1069: %% Resume the session. 1070: Alice = escalus_connection:connect(AliceSpec), 1071: 1072: Username = proplists:get_value(username, AliceSpec), 1073: Password = proplists:get_value(password, AliceSpec), 1074: Payload = <<0:8,Username/binary,0:8,Password/binary>>, 1075: Server = proplists:get_value(server, AliceSpec), 1076: 1077: Stream = escalus_stanza:stream_start(Server, <<"jabber:client">>), 1078: Auth = escalus_stanza:auth(<<"PLAIN">>, [#xmlcdata{content = base64:encode(Payload)}]), 1079: AuthStream = escalus_stanza:stream_start(Server, <<"jabber:client">>), 1080: Resume = escalus_stanza:resume(SMID, 2), 1081: 1082: escalus_client:send(Alice, [Stream, Auth, AuthStream, Resume]), 1083: Messages = [escalus_connection:get_stanza(Alice, {get_resumed, I}) || I <- lists:seq(1, 6)], 1084: escalus:assert(is_sm_resumed, [SMID], lists:last(Messages)), 1085: 1086: escalus_connection:stop(Alice) 1087: end). 1088: 1089: %% This is a regression test for a case when a session processes a request, which will 1090: %% receive a response from the server, i.e. will have the same origin SID in mongoose_acc. 1091: %% Without proper handling, the reply would be rejected because the resumed session 1092: %% has new SID. 1093: replies_are_processed_by_resumed_session(Config) -> 1094: %% GIVEN a session and registered special IQ handler (added in init_per_testcase), 1095: %% that waits for old session process to terminate (at this point new process 1096: %% has fully taken over) and then actually sends the reply. 1097: Alice = connect_fresh(Config, alice, sr_presence), 1098: 1099: %% WHEN a client sends IQ request to the special handler... 1100: IQReq = escalus_stanza:iq_get(regression_ns(), []), 1101: escalus:send(Alice, IQReq), 1102: 1103: %% ... goes down and session is resumed. 1104: Alice2 = sm_helper:kill_and_connect_resume(Alice), 1105: 1106: %% THEN the client receives the reply properly. 1107: IQReply = escalus:wait_for_stanza(Alice2), 1108: escalus:assert(is_iq_result, [IQReq], IQReply), 1109: escalus_connection:stop(Alice2). 1110: 1111: %% This is a regression test for a bug, which manifested in following scenario 1112: %% (due to improper presence sub requests buffering): 1113: %% 1. Bob is online, Alice is offline 1114: %% 2. Bob subscribes to Alice's presence; 1115: %% 3. Alice becomes online 1116: %% 4. Bob sends a message to Alice 1117: %% 5. Alice doesn't SM-ack the request or message, terminates the connection 1118: %% 6. Alice reconnects but with session *replace*, not resume 1119: %% 7. Packet rerouting crashes on the buffered sub request, preventing resending whole buffer 1120: %% 8. Alice doesn't receive the buffered message 1121: subscription_requests_are_buffered_properly(Config) -> 1122: AliceSpec = escalus_fresh:create_fresh_user(Config, alice), 1123: MsgBody = <<"buffered">>, 1124: escalus:fresh_story(Config, [{bob, 1}], fun(Bob) -> 1125: % GIVEN Bob's pending subscription to Alice's presence 1126: AliceJid = common_helper:get_bjid(AliceSpec), 1127: escalus:send(Bob, escalus_stanza:presence_direct(AliceJid, <<"subscribe">>)), 1128: _RosterPushReq = escalus:wait_for_stanza(Bob), 1129: 1130: % WHEN Alice becomes online... 1131: Alice = connect_spec(AliceSpec, sr_session, manual), 1132: send_initial_presence(Alice), 1133: %% subscribe could come before the initial presence 1134: escalus:assert_many([is_presence(<<"available">>), is_presence(<<"subscribe">>)], 1135: escalus:wait_for_stanzas(Alice, 2)), 1136: 1137: % ...and Bob sends a message to Alice... 1138: escalus:send(Bob, escalus_stanza:chat_to(Alice, MsgBody)), 1139: MsgStanza = escalus:wait_for_stanza(Alice), 1140: escalus:assert(is_chat_message, [MsgBody], MsgStanza), 1141: 1142: % ...and Alice terminates connection without acking anything... 1143: escalus_client:kill_connection(Config, Alice), 1144: 1145: % ...and reconnects with session replacement. 1146: Alice2 = connect_spec(AliceSpec, session, manual), 1147: 1148: % THEN Alice receives (without sending initial presence): 1149: % * buffered Bob's message (like above) 1150: % Alice DOESN'T receive: 1151: % * buffered subscription request because it is dropped by ejabberd_sm 1152: % because it's treated like repeated sub request to bare JID, so it's not 1153: % processed by any sub req handler (like mod_roster) 1154: % * buffered available presence from Alice - because it is addressed to another SID 1155: % and Alice2 is a brand new session 1156: escalus:assert(is_chat_message, [MsgBody], escalus:wait_for_stanza(Alice2)), 1157: sm_helper:send_and_receive(Bob, Alice2, <<"flush1">>), 1158: escalus_assert:has_no_stanzas(Alice2), 1159: 1160: %% Only once an initial presence is sent, a subscription request is sent 1161: send_initial_presence(Alice2), 1162: escalus:assert_many([is_presence(<<"available">>), is_presence(<<"subscribe">>)], 1163: escalus:wait_for_stanzas(Alice2, 2)), 1164: 1165: sm_helper:send_and_receive(Bob, Alice2, <<"flush2">>), 1166: escalus_assert:has_no_stanzas(Alice2), 1167: 1168: escalus_connection:stop(Alice2) 1169: end). 1170: 1171: %% This is a regression test for a bug, due to which messages sent to old session 1172: %% in a middle of state handover were not appended properly to SM buffer. 1173: %% Scenario to reproduce: 1174: %% 1. Online Bob and Alice 1175: %% 2. Alice kills the connection 1176: %% 3. Alice's session is suspended 1177: %% 4. Alice resumes session with new connection. At this moment new session is still not 1178: %% present in session table. `resume` request is stuck in old proc mailbox. 1179: %% 5. Bob sends a message to Alice. Only old proc is present in session table so now 1180: %% old session has two messages in mailbox: `resume` and XML from Bob 1181: %% 6. We resume old process and it begins session handover 1182: %% 7. Bob's message is appended to SM buffer in "flush" step 1183: %% 8. With bug fixed, the message is retransmitted properly 1184: messages_are_properly_flushed_during_resumption(Config) -> 1185: escalus:fresh_story(Config, [{bob, 1}], fun(Bob) -> 1186: % GIVEN (online Bob) and (Alice in resume state); Alice's session is suspended 1187: Alice = connect_fresh(Config, alice, sr_presence), 1188: SMH = escalus_connection:get_sm_h(Alice), 1189: escalus_client:kill_connection(Config, Alice), 1190: %% The receiver process would stop now 1191: C2SPid = mongoose_helper:get_session_pid(Alice), 1192: sm_helper:wait_until_resume_session(C2SPid), 1193: 1194: sm_helper:wait_for_queue_length(C2SPid, 0), 1195: ok = rpc(mim(), sys, suspend, [C2SPid]), 1196: 1197: % WHEN new session requests resumption 1198: % we wait until that old session has resumption request enqueued; 1199: % we need it to ensure the order of messages: resume first, Bob's chat second. 1200: % Actual wait and message sent by Bob is done in separate process 1201: % because new client start will block until old process is resumed 1202: 1203: MsgBody = <<"flush-regression">>, 1204: spawn_link(fun() -> 1205: sm_helper:wait_for_queue_length(C2SPid, 1), 1206: 1207: % Bob sends a message... 1208: escalus:send(Bob, escalus_stanza:chat_to(Alice, MsgBody)), 1209: 1210: % ...we ensure that a message is enqueued in Alice's session... 1211: % (2 messages = resume request + Bob's message) 1212: sm_helper:wait_for_queue_length(C2SPid, 2), 1213: 1214: % ...and old process is resumed. 1215: ok = rpc(mim(), sys, resume, [C2SPid]) 1216: end), 1217: Alice2 = connect_resume(Alice, SMH), 1218: % THEN Alice's new session receives Bob's message 1219: RecvMsg = escalus:wait_for_stanza(Alice2), 1220: escalus:assert(is_chat_message, [MsgBody], RecvMsg) 1221: end). 1222: 1223: no_crash_if_stream_mgmt_disabled_but_client_requests_stream_mgmt(Config) -> 1224: Alice = connect_fresh(Config, alice, session, manual), 1225: %% Should not crash anything! 1226: escalus_connection:send(Alice, escalus_stanza:enable_sm()), 1227: Response = escalus_connection:get_stanza(Alice, service_unavailable), 1228: escalus:assert(is_sm_failed, [<<"feature-not-implemented">>], Response), 1229: escalus_connection:stop(Alice). 1230: 1231: no_crash_if_stream_mgmt_disabled_but_client_requests_stream_mgmt_with_resumption(Config) -> 1232: Alice = connect_fresh(Config, alice, session, manual), 1233: %% Should not crash anything! 1234: escalus_connection:send(Alice, escalus_stanza:enable_sm([resume])), 1235: Response = escalus_connection:get_stanza(Alice, service_unavailable), 1236: escalus:assert(is_sm_failed, [<<"feature-not-implemented">>], Response), 1237: escalus_connection:stop(Alice). 1238: 1239: %%-------------------------------------------------------------------- 1240: %% Helpers 1241: %%-------------------------------------------------------------------- 1242: start_hook_listener(Resource) -> 1243: TestCasePid = self(), 1244: rpc(mim(), ?MODULE, rpc_start_hook_handler, [TestCasePid, Resource, host_type()]). 1245: 1246: stop_hook_listener(HookExtra) -> 1247: rpc(mim(), ?MODULE, rpc_stop_hook_handler, [HookExtra, host_type()]). 1248: 1249: rpc_start_hook_handler(TestCasePid, User, HostType) -> 1250: LUser = jid:nodeprep(User), 1251: Extra = #{luser => LUser, pid => TestCasePid}, 1252: gen_hook:add_handler(unacknowledged_message, HostType, 1253: fun ?MODULE:hook_handler_fn/3, 1254: Extra, 50), 1255: Extra. 1256: 1257: rpc_stop_hook_handler(HookExtra, HostType) -> 1258: gen_hook:delete_handler(unacknowledged_message, HostType, 1259: fun ?MODULE:hook_handler_fn/3, 1260: HookExtra, 50). 1261: 1262: hook_handler_fn(Acc, 1263: #{jid := Jid} = _Params, 1264: #{luser := LUser, pid := TestCasePid} = _Extra) -> 1265: {U, _S, R} = jid:to_lower(Jid), 1266: case U of 1267: LUser -> 1268: Counter = mongoose_acc:get(sm_test, counter, 0, Acc), 1269: El = mongoose_acc:element(Acc), 1270: TestCasePid ! {sm_test, Counter, R, El}, 1271: {ok, mongoose_acc:set_permanent(sm_test, counter, Counter + 1, Acc)}; 1272: _ -> {ok, Acc} 1273: end. 1274: 1275: wait_for_unacked_msg_hook(Counter, Res, Timeout) -> 1276: receive 1277: {sm_test, AccCounter, Resource, Stanza} = Msg -> 1278: ?assertEqual(Counter, AccCounter, Msg), 1279: ?assertEqual(Res, Resource, Msg), 1280: Stanza 1281: after Timeout -> 1282: timeout 1283: end. 1284: 1285: start_filter_hook_listener(FilterText, Resource) -> 1286: rpc(mim(), ?MODULE, rpc_start_filter_hook_handler, [FilterText, Resource, host_type()]). 1287: 1288: stop_filter_hook_listener(HookExtra) -> 1289: rpc(mim(), ?MODULE, rpc_stop_filter_hook_handler, [HookExtra, host_type()]). 1290: 1291: rpc_start_filter_hook_handler(FilterText, User, HostType) -> 1292: LUser = jid:nodeprep(User), 1293: Extra = #{luser => LUser, filter_text => FilterText}, 1294: gen_hook:add_handler(filter_unacknowledged_messages, HostType, 1295: fun ?MODULE:filter_hook_handler_fn/3, 1296: Extra, 50), 1297: Extra. 1298: 1299: rpc_stop_filter_hook_handler(HookExtra, HostType) -> 1300: gen_hook:delete_handler(filter_unacknowledged_messages, HostType, 1301: fun ?MODULE:filter_hook_handler_fn/3, 1302: HookExtra, 50). 1303: 1304: filter_hook_handler_fn(Buffer, 1305: #{jid := Jid} = _Params, 1306: #{luser := LUser, filter_text := FilterText} = _Extra) -> 1307: {U, _} = jid:to_lus(Jid), 1308: case U of 1309: LUser -> 1310: F = fun(Acc) -> filter_text(Acc, FilterText) end, 1311: NewBuffer = lists:filter(F, Buffer), 1312: {ok, NewBuffer}; 1313: _ -> {ok, Buffer} 1314: end. 1315: 1316: filter_text(Acc, FilterText) -> 1317: case mongoose_acc:stanza_name(Acc) of 1318: <<"message">> -> 1319: El = mongoose_acc:element(Acc), 1320: FilterText =/= exml_query:path(El, [{element, <<"body">>}, cdata]); 1321: _ -> 1322: true 1323: end. 1324: 1325: is_chat(Content) -> 1326: fun(Stanza) -> escalus_pred:is_chat_message(Content, Stanza) end. 1327: 1328: is_presence(Type) -> 1329: fun(Stanza) -> escalus_pred:is_presence_with_type(Type, Stanza) end. 1330: 1331: three_texts() -> 1332: [<<"msg-1">>, <<"msg-2">>, <<"msg-3">>]. 1333: 1334: get_stanzas_filtered_by_mod_ping() -> 1335: History = rpc(mim(), meck, history, [mod_ping]), 1336: [Stanza || 1337: {_Pid, 1338: {_Mod, 1339: filter_local_packet = _Func, 1340: [{_, _, _, Stanza} = _Acc, _Params, _Extra] = _Args 1341: }, 1342: {stop, drop} = _Result 1343: } <- History 1344: ]. 1345: %%-------------------------------------------------------------------- 1346: %% IQ handler necessary for reproducing "replies_are_processed_by_resumed_session" 1347: %%-------------------------------------------------------------------- 1348: 1349: regression_ns() -> 1350: <<"regression">>. 1351: 1352: register_handler() -> 1353: HostType = host_type(), 1354: rpc(mim(), gen_iq_handler, add_iq_handler_for_domain, 1355: [HostType, regression_ns(), ejabberd_sm, 1356: fun ?MODULE:regression_handler/5, #{}, one_queue]). 1357: 1358: unregister_handler() -> 1359: HostType = host_type(), 1360: rpc(mim(), gen_iq_handler, remove_iq_handler_for_domain, 1361: [HostType, regression_ns(), ejabberd_sm]). 1362: 1363: regression_handler(Acc, _From, _To, IQ, _Extra) -> 1364: %% A bit of a hack - will no longer work when the SID format changes 1365: {_, Pid} = mongoose_acc:get(c2s, origin_sid, undefined, Acc), 1366: erlang:monitor(process, Pid), 1367: receive 1368: {'DOWN', _, _, _, _} -> 1369: ok 1370: after 1371: 10000 -> 1372: error({c2s_not_stopped_after_timeout, Pid}) 1373: end, 1374: %% We avoid another race condition - there is a short window where user session 1375: %% is not registered in ejabberd_sm: between old process termination and the moment 1376: %% when the new process stores new session in memory. It should be fixed separately. 1377: wait_for_session(mongoose_acc:get(c2s, origin_jid, undefined, Acc), 50, 100), 1378: {Acc, jlib:make_result_iq_reply(IQ)}. 1379: 1380: wait_for_session(JID, Retries, SleepTime) -> 1381: case ejabberd_sm:get_session(JID) of 1382: offline -> 1383: timer:sleep(SleepTime), 1384: wait_for_session(JID, Retries - 1, SleepTime); 1385: _ -> 1386: ok 1387: end. 1388: 1389: maybe_ack_initial_presence(Alice, ack) -> 1390: ack_initial_presence(Alice); 1391: maybe_ack_initial_presence(_Alice, no_ack) -> 1392: ok.