From c07bce5d7ed0c03000db4ca922a8351c75455c69 Mon Sep 17 00:00:00 2001 From: James Criscuolo Date: Mon, 20 May 2019 11:26:08 -0400 Subject: [PATCH] dist/ lib/ files for 0.14.0 --- dist/sip-0.14.0.js | 38134 ++++++++++++++++ dist/sip-0.14.0.min.js | 1 + dist/sip.js | 38134 ++++++++++++++++ dist/sip.min.js | 1 + lib/ClientContext.d.ts | 26 + lib/ClientContext.js | 111 + lib/Constants.d.ts | 62 + lib/Constants.js | 192 + lib/Contexts/client-context.d.ts | 11 + lib/Contexts/client-context.js | 52 + lib/Contexts/invite-client-context.d.ts | 116 + lib/Contexts/invite-client-context.js | 781 + lib/Contexts/invite-server-context.d.ts | 130 + lib/Contexts/invite-server-context.js | 693 + lib/Contexts/publish-client-context.d.ts | 14 + lib/Contexts/publish-client-context.js | 61 + lib/Contexts/refer-client-context.d.ts | 21 + lib/Contexts/refer-client-context.js | 79 + lib/Contexts/refer-server-context.d.ts | 26 + lib/Contexts/refer-server-context.js | 109 + lib/Contexts/subscribe-client-context.d.ts | 18 + lib/Contexts/subscribe-client-context.js | 78 + lib/Core/dialogs/dialog-state.d.ts | 31 + lib/Core/dialogs/dialog-state.js | 2 + lib/Core/dialogs/dialog.d.ts | 153 + lib/Core/dialogs/dialog.js | 564 + lib/Core/dialogs/index.d.ts | 4 + lib/Core/dialogs/index.js | 8 + lib/Core/dialogs/invite-dialog.d.ts | 170 + lib/Core/dialogs/invite-dialog.js | 812 + lib/Core/dialogs/session-dialog.d.ts | 170 + lib/Core/dialogs/session-dialog.js | 812 + lib/Core/dialogs/subscribe-dialog.d.ts | 39 + lib/Core/dialogs/subscribe-dialog.js | 105 + lib/Core/dialogs/subscription-dialog.d.ts | 116 + lib/Core/dialogs/subscription-dialog.js | 504 + lib/Core/messages/body.d.ts | 70 + lib/Core/messages/body.js | 139 + lib/Core/messages/incoming-request.d.ts | 62 + lib/Core/messages/incoming-request.js | 2 + lib/Core/messages/incoming-response.d.ts | 11 + lib/Core/messages/incoming-response.js | 2 + lib/Core/messages/index.d.ts | 6 + lib/Core/messages/index.js | 7 + lib/Core/messages/methods/ack.d.ts | 11 + lib/Core/messages/methods/ack.js | 2 + lib/Core/messages/methods/bye.d.ts | 9 + lib/Core/messages/methods/bye.js | 2 + lib/Core/messages/methods/cancel.d.ts | 9 + lib/Core/messages/methods/cancel.js | 2 + lib/Core/messages/methods/index.d.ts | 12 + lib/Core/messages/methods/index.js | 2 + lib/Core/messages/methods/info.d.ts | 9 + lib/Core/messages/methods/info.js | 2 + lib/Core/messages/methods/invite.d.ts | 70 + lib/Core/messages/methods/invite.js | 2 + lib/Core/messages/methods/message.d.ts | 9 + lib/Core/messages/methods/message.js | 2 + lib/Core/messages/methods/notify.d.ts | 9 + lib/Core/messages/methods/notify.js | 2 + lib/Core/messages/methods/prack.d.ts | 9 + lib/Core/messages/methods/prack.js | 2 + lib/Core/messages/methods/publish.d.ts | 9 + lib/Core/messages/methods/publish.js | 2 + lib/Core/messages/methods/refer.d.ts | 9 + lib/Core/messages/methods/refer.js | 2 + lib/Core/messages/methods/register.d.ts | 9 + lib/Core/messages/methods/register.js | 2 + lib/Core/messages/methods/subscribe.d.ts | 36 + lib/Core/messages/methods/subscribe.js | 2 + lib/Core/messages/outgoing-request.d.ts | 59 + lib/Core/messages/outgoing-request.js | 2 + lib/Core/messages/outgoing-response.d.ts | 35 + lib/Core/messages/outgoing-response.js | 122 + lib/Core/session/index.d.ts | 2 + lib/Core/session/index.js | 6 + lib/Core/session/session-delegate.d.ts | 49 + lib/Core/session/session-delegate.js | 2 + lib/Core/session/session.d.ts | 132 + lib/Core/session/session.js | 37 + lib/Core/subscription/index.d.ts | 2 + lib/Core/subscription/index.js | 6 + .../subscription/subscription-delegate.d.ts | 23 + .../subscription/subscription-delegate.js | 2 + lib/Core/subscription/subscription.d.ts | 50 + lib/Core/subscription/subscription.js | 14 + lib/Core/transactions/client-transaction.d.ts | 44 + lib/Core/transactions/client-transaction.js | 82 + lib/Core/transactions/index.d.ts | 10 + lib/Core/transactions/index.js | 14 + .../invite-client-transaction.d.ts | 115 + .../transactions/invite-client-transaction.js | 495 + .../invite-server-transaction.d.ts | 125 + .../transactions/invite-server-transaction.js | 401 + .../non-invite-client-transaction.d.ts | 68 + .../non-invite-client-transaction.js | 257 + .../non-invite-server-transaction.d.ts | 55 + .../non-invite-server-transaction.js | 241 + lib/Core/transactions/server-transaction.d.ts | 33 + lib/Core/transactions/server-transaction.js | 44 + lib/Core/transactions/transaction-state.d.ts | 10 + lib/Core/transactions/transaction-state.js | 13 + lib/Core/transactions/transaction-user.d.ts | 68 + lib/Core/transactions/transaction-user.js | 2 + lib/Core/transactions/transaction.d.ts | 60 + lib/Core/transactions/transaction.js | 134 + lib/Core/user-agent-core/allowed-methods.d.ts | 4 + lib/Core/user-agent-core/allowed-methods.js | 19 + lib/Core/user-agent-core/index.d.ts | 3 + lib/Core/user-agent-core/index.js | 7 + .../user-agent-core-configuration.d.ts | 102 + .../user-agent-core-configuration.js | 42 + .../user-agent-core-delegate.d.ts | 31 + .../user-agent-core-delegate.js | 2 + lib/Core/user-agent-core/user-agent-core.d.ts | 164 + lib/Core/user-agent-core/user-agent-core.js | 757 + .../user-agents/bye-user-agent-client.d.ts | 6 + lib/Core/user-agents/bye-user-agent-client.js | 30 + .../user-agents/bye-user-agent-server.d.ts | 7 + lib/Core/user-agents/bye-user-agent-server.js | 25 + .../user-agents/cancel-user-agent-client.d.ts | 7 + .../user-agents/cancel-user-agent-client.js | 25 + lib/Core/user-agents/index.d.ts | 24 + lib/Core/user-agents/index.js | 29 + .../user-agents/info-user-agent-client.d.ts | 6 + .../user-agents/info-user-agent-client.js | 29 + .../user-agents/info-user-agent-server.d.ts | 7 + .../user-agents/info-user-agent-server.js | 25 + .../user-agents/invite-user-agent-client.d.ts | 27 + .../user-agents/invite-user-agent-client.js | 295 + .../user-agents/invite-user-agent-server.d.ts | 75 + .../user-agents/invite-user-agent-server.js | 248 + .../message-user-agent-client.d.ts | 7 + .../user-agents/message-user-agent-client.js | 25 + .../message-user-agent-server.d.ts | 8 + .../user-agents/message-user-agent-server.js | 27 + .../user-agents/notify-user-agent-client.d.ts | 6 + .../user-agents/notify-user-agent-client.js | 29 + .../user-agents/notify-user-agent-server.d.ts | 13 + .../user-agents/notify-user-agent-server.js | 38 + .../user-agents/prack-user-agent-client.d.ts | 6 + .../user-agents/prack-user-agent-client.js | 30 + .../user-agents/prack-user-agent-server.d.ts | 13 + .../user-agents/prack-user-agent-server.js | 41 + .../publish-user-agent-client.d.ts | 7 + .../user-agents/publish-user-agent-client.js | 25 + .../re-invite-user-agent-client.d.ts | 16 + .../re-invite-user-agent-client.js | 118 + .../re-invite-user-agent-server.d.ts | 24 + .../re-invite-user-agent-server.js | 91 + .../re-subscribe-user-agent-client.d.ts | 14 + .../re-subscribe-user-agent-client.js | 81 + .../re-subscribe-user-agent-server.d.ts | 7 + .../re-subscribe-user-agent-server.js | 25 + .../user-agents/refer-user-agent-client.d.ts | 6 + .../user-agents/refer-user-agent-client.js | 29 + .../user-agents/refer-user-agent-server.d.ts | 13 + .../user-agents/refer-user-agent-server.js | 38 + .../register-user-agent-client.d.ts | 7 + .../user-agents/register-user-agent-client.js | 25 + .../subscribe-user-agent-client.d.ts | 63 + .../subscribe-user-agent-client.js | 306 + .../subscribe-user-agent-server.d.ts | 8 + .../subscribe-user-agent-server.js | 27 + lib/Core/user-agents/user-agent-client.d.ts | 86 + lib/Core/user-agents/user-agent-client.js | 311 + lib/Core/user-agents/user-agent-server.d.ts | 78 + lib/Core/user-agents/user-agent-server.js | 257 + lib/DigestAuthentication.d.ts | 50 + lib/DigestAuthentication.js | 145 + lib/Enums.d.ts | 61 + lib/Enums.js | 71 + lib/Exceptions.d.ts | 85 + lib/Exceptions.js | 185 + lib/Grammar.d.ts | 19 + lib/Grammar.js | 39 + lib/Grammar/dist/Grammar.d.ts | 50 + lib/Grammar/dist/Grammar.js | 14299 ++++++ lib/LoggerFactory.d.ts | 33 + lib/LoggerFactory.js | 129 + lib/NameAddrHeader.d.ts | 23 + lib/NameAddrHeader.js | 72 + lib/Parser.d.ts | 19 + lib/Parser.js | 245 + lib/PublishContext.d.ts | 39 + lib/PublishContext.js | 277 + lib/React/SessionDescriptionHandler.d.ts | 93 + lib/React/SessionDescriptionHandler.js | 648 + .../SessionDescriptionHandlerObserver.d.ts | 11 + .../SessionDescriptionHandlerObserver.js | 23 + lib/ReferContext.d.ts | 59 + lib/ReferContext.js | 359 + lib/RegisterContext.d.ts | 39 + lib/RegisterContext.js | 436 + lib/SIPMessage.d.ts | 182 + lib/SIPMessage.js | 430 + lib/ServerContext.d.ts | 32 + lib/ServerContext.js | 132 + lib/Session.d.ts | 358 + lib/Session.js | 2185 + lib/Session/DTMF.d.ts | 26 + lib/Session/DTMF.js | 165 + lib/Subscription.d.ts | 130 + lib/Subscription.js | 441 + lib/SubscriptionOriginal.d.ts | 41 + lib/SubscriptionOriginal.js | 348 + lib/Timers.d.ts | 16 + lib/Timers.js | 21 + lib/Transport.d.ts | 81 + lib/Transport.js | 103 + lib/UA.d.ts | 225 + lib/UA.js | 1012 + lib/URI.d.ts | 57 + lib/URI.js | 258 + lib/Utils.d.ts | 25 + lib/Utils.js | 202 + lib/Web/Modifiers.d.ts | 8 + lib/Web/Modifiers.js | 121 + lib/Web/SessionDescriptionHandler.d.ts | 122 + lib/Web/SessionDescriptionHandler.js | 638 + .../SessionDescriptionHandlerObserver.d.ts | 11 + lib/Web/SessionDescriptionHandlerObserver.js | 23 + lib/Web/Simple.d.ts | 45 + lib/Web/Simple.js | 423 + lib/Web/Transport.d.ts | 160 + lib/Web/Transport.js | 706 + lib/Web/index.d.ts | 5 + lib/Web/index.js | 10 + lib/index.d.ts | 36 + lib/index.js | 68 + lib/session-description-handler-factory.d.ts | 14 + lib/session-description-handler-factory.js | 2 + lib/session-description-handler-observer.d.ts | 8 + lib/session-description-handler-observer.js | 2 + lib/session-description-handler.d.ts | 73 + lib/session-description-handler.js | 3 + 236 files changed, 116047 insertions(+) create mode 100644 dist/sip-0.14.0.js create mode 100644 dist/sip-0.14.0.min.js create mode 100644 dist/sip.js create mode 100644 dist/sip.min.js create mode 100644 lib/ClientContext.d.ts create mode 100644 lib/ClientContext.js create mode 100644 lib/Constants.d.ts create mode 100644 lib/Constants.js create mode 100644 lib/Contexts/client-context.d.ts create mode 100644 lib/Contexts/client-context.js create mode 100644 lib/Contexts/invite-client-context.d.ts create mode 100644 lib/Contexts/invite-client-context.js create mode 100644 lib/Contexts/invite-server-context.d.ts create mode 100644 lib/Contexts/invite-server-context.js create mode 100644 lib/Contexts/publish-client-context.d.ts create mode 100644 lib/Contexts/publish-client-context.js create mode 100644 lib/Contexts/refer-client-context.d.ts create mode 100644 lib/Contexts/refer-client-context.js create mode 100644 lib/Contexts/refer-server-context.d.ts create mode 100644 lib/Contexts/refer-server-context.js create mode 100644 lib/Contexts/subscribe-client-context.d.ts create mode 100644 lib/Contexts/subscribe-client-context.js create mode 100644 lib/Core/dialogs/dialog-state.d.ts create mode 100644 lib/Core/dialogs/dialog-state.js create mode 100644 lib/Core/dialogs/dialog.d.ts create mode 100644 lib/Core/dialogs/dialog.js create mode 100644 lib/Core/dialogs/index.d.ts create mode 100644 lib/Core/dialogs/index.js create mode 100644 lib/Core/dialogs/invite-dialog.d.ts create mode 100644 lib/Core/dialogs/invite-dialog.js create mode 100644 lib/Core/dialogs/session-dialog.d.ts create mode 100644 lib/Core/dialogs/session-dialog.js create mode 100644 lib/Core/dialogs/subscribe-dialog.d.ts create mode 100644 lib/Core/dialogs/subscribe-dialog.js create mode 100644 lib/Core/dialogs/subscription-dialog.d.ts create mode 100644 lib/Core/dialogs/subscription-dialog.js create mode 100644 lib/Core/messages/body.d.ts create mode 100644 lib/Core/messages/body.js create mode 100644 lib/Core/messages/incoming-request.d.ts create mode 100644 lib/Core/messages/incoming-request.js create mode 100644 lib/Core/messages/incoming-response.d.ts create mode 100644 lib/Core/messages/incoming-response.js create mode 100644 lib/Core/messages/index.d.ts create mode 100644 lib/Core/messages/index.js create mode 100644 lib/Core/messages/methods/ack.d.ts create mode 100644 lib/Core/messages/methods/ack.js create mode 100644 lib/Core/messages/methods/bye.d.ts create mode 100644 lib/Core/messages/methods/bye.js create mode 100644 lib/Core/messages/methods/cancel.d.ts create mode 100644 lib/Core/messages/methods/cancel.js create mode 100644 lib/Core/messages/methods/index.d.ts create mode 100644 lib/Core/messages/methods/index.js create mode 100644 lib/Core/messages/methods/info.d.ts create mode 100644 lib/Core/messages/methods/info.js create mode 100644 lib/Core/messages/methods/invite.d.ts create mode 100644 lib/Core/messages/methods/invite.js create mode 100644 lib/Core/messages/methods/message.d.ts create mode 100644 lib/Core/messages/methods/message.js create mode 100644 lib/Core/messages/methods/notify.d.ts create mode 100644 lib/Core/messages/methods/notify.js create mode 100644 lib/Core/messages/methods/prack.d.ts create mode 100644 lib/Core/messages/methods/prack.js create mode 100644 lib/Core/messages/methods/publish.d.ts create mode 100644 lib/Core/messages/methods/publish.js create mode 100644 lib/Core/messages/methods/refer.d.ts create mode 100644 lib/Core/messages/methods/refer.js create mode 100644 lib/Core/messages/methods/register.d.ts create mode 100644 lib/Core/messages/methods/register.js create mode 100644 lib/Core/messages/methods/subscribe.d.ts create mode 100644 lib/Core/messages/methods/subscribe.js create mode 100644 lib/Core/messages/outgoing-request.d.ts create mode 100644 lib/Core/messages/outgoing-request.js create mode 100644 lib/Core/messages/outgoing-response.d.ts create mode 100644 lib/Core/messages/outgoing-response.js create mode 100644 lib/Core/session/index.d.ts create mode 100644 lib/Core/session/index.js create mode 100644 lib/Core/session/session-delegate.d.ts create mode 100644 lib/Core/session/session-delegate.js create mode 100644 lib/Core/session/session.d.ts create mode 100644 lib/Core/session/session.js create mode 100644 lib/Core/subscription/index.d.ts create mode 100644 lib/Core/subscription/index.js create mode 100644 lib/Core/subscription/subscription-delegate.d.ts create mode 100644 lib/Core/subscription/subscription-delegate.js create mode 100644 lib/Core/subscription/subscription.d.ts create mode 100644 lib/Core/subscription/subscription.js create mode 100644 lib/Core/transactions/client-transaction.d.ts create mode 100644 lib/Core/transactions/client-transaction.js create mode 100644 lib/Core/transactions/index.d.ts create mode 100644 lib/Core/transactions/index.js create mode 100644 lib/Core/transactions/invite-client-transaction.d.ts create mode 100644 lib/Core/transactions/invite-client-transaction.js create mode 100644 lib/Core/transactions/invite-server-transaction.d.ts create mode 100644 lib/Core/transactions/invite-server-transaction.js create mode 100644 lib/Core/transactions/non-invite-client-transaction.d.ts create mode 100644 lib/Core/transactions/non-invite-client-transaction.js create mode 100644 lib/Core/transactions/non-invite-server-transaction.d.ts create mode 100644 lib/Core/transactions/non-invite-server-transaction.js create mode 100644 lib/Core/transactions/server-transaction.d.ts create mode 100644 lib/Core/transactions/server-transaction.js create mode 100644 lib/Core/transactions/transaction-state.d.ts create mode 100644 lib/Core/transactions/transaction-state.js create mode 100644 lib/Core/transactions/transaction-user.d.ts create mode 100644 lib/Core/transactions/transaction-user.js create mode 100644 lib/Core/transactions/transaction.d.ts create mode 100644 lib/Core/transactions/transaction.js create mode 100644 lib/Core/user-agent-core/allowed-methods.d.ts create mode 100644 lib/Core/user-agent-core/allowed-methods.js create mode 100644 lib/Core/user-agent-core/index.d.ts create mode 100644 lib/Core/user-agent-core/index.js create mode 100644 lib/Core/user-agent-core/user-agent-core-configuration.d.ts create mode 100644 lib/Core/user-agent-core/user-agent-core-configuration.js create mode 100644 lib/Core/user-agent-core/user-agent-core-delegate.d.ts create mode 100644 lib/Core/user-agent-core/user-agent-core-delegate.js create mode 100644 lib/Core/user-agent-core/user-agent-core.d.ts create mode 100644 lib/Core/user-agent-core/user-agent-core.js create mode 100644 lib/Core/user-agents/bye-user-agent-client.d.ts create mode 100644 lib/Core/user-agents/bye-user-agent-client.js create mode 100644 lib/Core/user-agents/bye-user-agent-server.d.ts create mode 100644 lib/Core/user-agents/bye-user-agent-server.js create mode 100644 lib/Core/user-agents/cancel-user-agent-client.d.ts create mode 100644 lib/Core/user-agents/cancel-user-agent-client.js create mode 100644 lib/Core/user-agents/index.d.ts create mode 100644 lib/Core/user-agents/index.js create mode 100644 lib/Core/user-agents/info-user-agent-client.d.ts create mode 100644 lib/Core/user-agents/info-user-agent-client.js create mode 100644 lib/Core/user-agents/info-user-agent-server.d.ts create mode 100644 lib/Core/user-agents/info-user-agent-server.js create mode 100644 lib/Core/user-agents/invite-user-agent-client.d.ts create mode 100644 lib/Core/user-agents/invite-user-agent-client.js create mode 100644 lib/Core/user-agents/invite-user-agent-server.d.ts create mode 100644 lib/Core/user-agents/invite-user-agent-server.js create mode 100644 lib/Core/user-agents/message-user-agent-client.d.ts create mode 100644 lib/Core/user-agents/message-user-agent-client.js create mode 100644 lib/Core/user-agents/message-user-agent-server.d.ts create mode 100644 lib/Core/user-agents/message-user-agent-server.js create mode 100644 lib/Core/user-agents/notify-user-agent-client.d.ts create mode 100644 lib/Core/user-agents/notify-user-agent-client.js create mode 100644 lib/Core/user-agents/notify-user-agent-server.d.ts create mode 100644 lib/Core/user-agents/notify-user-agent-server.js create mode 100644 lib/Core/user-agents/prack-user-agent-client.d.ts create mode 100644 lib/Core/user-agents/prack-user-agent-client.js create mode 100644 lib/Core/user-agents/prack-user-agent-server.d.ts create mode 100644 lib/Core/user-agents/prack-user-agent-server.js create mode 100644 lib/Core/user-agents/publish-user-agent-client.d.ts create mode 100644 lib/Core/user-agents/publish-user-agent-client.js create mode 100644 lib/Core/user-agents/re-invite-user-agent-client.d.ts create mode 100644 lib/Core/user-agents/re-invite-user-agent-client.js create mode 100644 lib/Core/user-agents/re-invite-user-agent-server.d.ts create mode 100644 lib/Core/user-agents/re-invite-user-agent-server.js create mode 100644 lib/Core/user-agents/re-subscribe-user-agent-client.d.ts create mode 100644 lib/Core/user-agents/re-subscribe-user-agent-client.js create mode 100644 lib/Core/user-agents/re-subscribe-user-agent-server.d.ts create mode 100644 lib/Core/user-agents/re-subscribe-user-agent-server.js create mode 100644 lib/Core/user-agents/refer-user-agent-client.d.ts create mode 100644 lib/Core/user-agents/refer-user-agent-client.js create mode 100644 lib/Core/user-agents/refer-user-agent-server.d.ts create mode 100644 lib/Core/user-agents/refer-user-agent-server.js create mode 100644 lib/Core/user-agents/register-user-agent-client.d.ts create mode 100644 lib/Core/user-agents/register-user-agent-client.js create mode 100644 lib/Core/user-agents/subscribe-user-agent-client.d.ts create mode 100644 lib/Core/user-agents/subscribe-user-agent-client.js create mode 100644 lib/Core/user-agents/subscribe-user-agent-server.d.ts create mode 100644 lib/Core/user-agents/subscribe-user-agent-server.js create mode 100644 lib/Core/user-agents/user-agent-client.d.ts create mode 100644 lib/Core/user-agents/user-agent-client.js create mode 100644 lib/Core/user-agents/user-agent-server.d.ts create mode 100644 lib/Core/user-agents/user-agent-server.js create mode 100644 lib/DigestAuthentication.d.ts create mode 100644 lib/DigestAuthentication.js create mode 100644 lib/Enums.d.ts create mode 100644 lib/Enums.js create mode 100644 lib/Exceptions.d.ts create mode 100644 lib/Exceptions.js create mode 100644 lib/Grammar.d.ts create mode 100644 lib/Grammar.js create mode 100644 lib/Grammar/dist/Grammar.d.ts create mode 100644 lib/Grammar/dist/Grammar.js create mode 100644 lib/LoggerFactory.d.ts create mode 100644 lib/LoggerFactory.js create mode 100644 lib/NameAddrHeader.d.ts create mode 100644 lib/NameAddrHeader.js create mode 100644 lib/Parser.d.ts create mode 100644 lib/Parser.js create mode 100644 lib/PublishContext.d.ts create mode 100644 lib/PublishContext.js create mode 100644 lib/React/SessionDescriptionHandler.d.ts create mode 100644 lib/React/SessionDescriptionHandler.js create mode 100644 lib/React/SessionDescriptionHandlerObserver.d.ts create mode 100644 lib/React/SessionDescriptionHandlerObserver.js create mode 100644 lib/ReferContext.d.ts create mode 100644 lib/ReferContext.js create mode 100644 lib/RegisterContext.d.ts create mode 100644 lib/RegisterContext.js create mode 100644 lib/SIPMessage.d.ts create mode 100644 lib/SIPMessage.js create mode 100644 lib/ServerContext.d.ts create mode 100644 lib/ServerContext.js create mode 100644 lib/Session.d.ts create mode 100644 lib/Session.js create mode 100644 lib/Session/DTMF.d.ts create mode 100644 lib/Session/DTMF.js create mode 100644 lib/Subscription.d.ts create mode 100644 lib/Subscription.js create mode 100644 lib/SubscriptionOriginal.d.ts create mode 100644 lib/SubscriptionOriginal.js create mode 100644 lib/Timers.d.ts create mode 100644 lib/Timers.js create mode 100644 lib/Transport.d.ts create mode 100644 lib/Transport.js create mode 100644 lib/UA.d.ts create mode 100644 lib/UA.js create mode 100644 lib/URI.d.ts create mode 100644 lib/URI.js create mode 100644 lib/Utils.d.ts create mode 100644 lib/Utils.js create mode 100644 lib/Web/Modifiers.d.ts create mode 100644 lib/Web/Modifiers.js create mode 100644 lib/Web/SessionDescriptionHandler.d.ts create mode 100644 lib/Web/SessionDescriptionHandler.js create mode 100644 lib/Web/SessionDescriptionHandlerObserver.d.ts create mode 100644 lib/Web/SessionDescriptionHandlerObserver.js create mode 100644 lib/Web/Simple.d.ts create mode 100644 lib/Web/Simple.js create mode 100644 lib/Web/Transport.d.ts create mode 100644 lib/Web/Transport.js create mode 100644 lib/Web/index.d.ts create mode 100644 lib/Web/index.js create mode 100644 lib/index.d.ts create mode 100644 lib/index.js create mode 100644 lib/session-description-handler-factory.d.ts create mode 100644 lib/session-description-handler-factory.js create mode 100644 lib/session-description-handler-observer.d.ts create mode 100644 lib/session-description-handler-observer.js create mode 100644 lib/session-description-handler.d.ts create mode 100644 lib/session-description-handler.js diff --git a/dist/sip-0.14.0.js b/dist/sip-0.14.0.js new file mode 100644 index 000000000..9139d3d8f --- /dev/null +++ b/dist/sip-0.14.0.js @@ -0,0 +1,38134 @@ +/*! + * + * SIP version 0.14.0 + * Copyright (c) 2014-2019 Junction Networks, Inc + * Homepage: https://sipjs.com + * License: https://sipjs.com/license/ + * + * + * ~~~SIP.js contains substantial portions of JsSIP under the following license~~~ + * Homepage: http://jssip.net + * Copyright (c) 2012-2013 José Luis Millán - Versatica + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * ~~~ end JsSIP license ~~~ + * + * + * + * + */ +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(); + else if(typeof define === 'function' && define.amd) + define([], factory); + else if(typeof exports === 'object') + exports["SIP"] = factory(); + else + root["SIP"] = factory(); +})(this, function() { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) { +/******/ return installedModules[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ i: moduleId, +/******/ l: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.l = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; +/******/ +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; +/******/ +/******/ // define getter function for harmony exports +/******/ __webpack_require__.d = function(exports, name, getter) { +/******/ if(!__webpack_require__.o(exports, name)) { +/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); +/******/ } +/******/ }; +/******/ +/******/ // define __esModule on exports +/******/ __webpack_require__.r = function(exports) { +/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { +/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); +/******/ } +/******/ Object.defineProperty(exports, '__esModule', { value: true }); +/******/ }; +/******/ +/******/ // create a fake namespace object +/******/ // mode & 1: value is a module id, require it +/******/ // mode & 2: merge all properties of value into the ns +/******/ // mode & 4: return value when already ns object +/******/ // mode & 8|1: behave like require +/******/ __webpack_require__.t = function(value, mode) { +/******/ if(mode & 1) value = __webpack_require__(value); +/******/ if(mode & 8) return value; +/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; +/******/ var ns = Object.create(null); +/******/ __webpack_require__.r(ns); +/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); +/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); +/******/ return ns; +/******/ }; +/******/ +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = function(module) { +/******/ var getter = module && module.__esModule ? +/******/ function getDefault() { return module['default']; } : +/******/ function getModuleExports() { return module; }; +/******/ __webpack_require__.d(getter, 'a', getter); +/******/ return getter; +/******/ }; +/******/ +/******/ // Object.prototype.hasOwnProperty.call +/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; +/******/ +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; +/******/ +/******/ +/******/ // Load entry module and return exports +/******/ return __webpack_require__(__webpack_require__.s = 0); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +var ClientContext_1 = __webpack_require__(1); +exports.ClientContext = ClientContext_1.ClientContext; +var Constants_1 = __webpack_require__(3); +exports.C = Constants_1.C; +var DigestAuthentication_1 = __webpack_require__(12); +exports.DigestAuthentication = DigestAuthentication_1.DigestAuthentication; +var Enums_1 = __webpack_require__(5); +exports.DialogStatus = Enums_1.DialogStatus; +exports.SessionStatus = Enums_1.SessionStatus; +exports.TypeStrings = Enums_1.TypeStrings; +exports.UAStatus = Enums_1.UAStatus; +var Exceptions_1 = __webpack_require__(47); +exports.Exceptions = Exceptions_1.Exceptions; +var Grammar_1 = __webpack_require__(7); +exports.Grammar = Grammar_1.Grammar; +var LoggerFactory_1 = __webpack_require__(48); +exports.LoggerFactory = LoggerFactory_1.LoggerFactory; +var NameAddrHeader_1 = __webpack_require__(9); +exports.NameAddrHeader = NameAddrHeader_1.NameAddrHeader; +var Parser_1 = __webpack_require__(49); +exports.Parser = Parser_1.Parser; +var PublishContext_1 = __webpack_require__(50); +exports.PublishContext = PublishContext_1.PublishContext; +var ReferContext_1 = __webpack_require__(51); +exports.ReferClientContext = ReferContext_1.ReferClientContext; +exports.ReferServerContext = ReferContext_1.ReferServerContext; +var RegisterContext_1 = __webpack_require__(66); +exports.RegisterContext = RegisterContext_1.RegisterContext; +var ServerContext_1 = __webpack_require__(62); +exports.ServerContext = ServerContext_1.ServerContext; +var Session_1 = __webpack_require__(67); +exports.InviteClientContext = Session_1.InviteClientContext; +exports.InviteServerContext = Session_1.InviteServerContext; +exports.Session = Session_1.Session; +var SIPMessage_1 = __webpack_require__(6); +exports.IncomingRequest = SIPMessage_1.IncomingRequest; +exports.IncomingResponse = SIPMessage_1.IncomingResponse; +exports.OutgoingRequest = SIPMessage_1.OutgoingRequest; +var Subscription_1 = __webpack_require__(71); +exports.Subscription = Subscription_1.Subscription; +var Timers_1 = __webpack_require__(56); +exports.Timers = Timers_1.Timers; +var transactions_1 = __webpack_require__(52); +var Transactions = { + InviteClientTransaction: transactions_1.InviteClientTransaction, + InviteServerTransaction: transactions_1.InviteServerTransaction, + NonInviteClientTransaction: transactions_1.NonInviteClientTransaction, + NonInviteServerTransaction: transactions_1.NonInviteServerTransaction +}; +exports.Transactions = Transactions; +var Transport_1 = __webpack_require__(75); +exports.Transport = Transport_1.Transport; +var UA_1 = __webpack_require__(76); +exports.UA = UA_1.UA; +var URI_1 = __webpack_require__(10); +exports.URI = URI_1.URI; +var Utils_1 = __webpack_require__(11); +exports.Utils = Utils_1.Utils; +var Web = __webpack_require__(115); +exports.Web = Web; +// tslint:disable-next-line:no-var-requires +var pkg = __webpack_require__(4); +var name = pkg.title; +exports.name = name; +var version = pkg.version; +exports.version = version; + + +/***/ }), +/* 1 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var events_1 = __webpack_require__(2); +var Constants_1 = __webpack_require__(3); +var Enums_1 = __webpack_require__(5); +var SIPMessage_1 = __webpack_require__(6); +var Utils_1 = __webpack_require__(11); +var ClientContext = /** @class */ (function (_super) { + __extends(ClientContext, _super); + function ClientContext(ua, method, target, options) { + var _this = _super.call(this) || this; + _this.data = {}; + ClientContext.initializer(_this, ua, method, target, options); + return _this; + } + ClientContext.initializer = function (objToConstruct, ua, method, originalTarget, options) { + objToConstruct.type = Enums_1.TypeStrings.ClientContext; + // Validate arguments + if (originalTarget === undefined) { + throw new TypeError("Not enough arguments"); + } + objToConstruct.ua = ua; + objToConstruct.logger = ua.getLogger("sip.clientcontext"); + objToConstruct.method = method; + var target = ua.normalizeTarget(originalTarget); + if (!target) { + throw new TypeError("Invalid target: " + originalTarget); + } + /* Options + * - extraHeaders + * - params + * - contentType + * - body + */ + options = Object.create(options || Object.prototype); + options.extraHeaders = (options.extraHeaders || []).slice(); + // Build the request + objToConstruct.request = new SIPMessage_1.OutgoingRequest(objToConstruct.method, target, objToConstruct.ua, options.params, options.extraHeaders); + if (options.body) { + var body = options.body; + var contentType = options.contentType ? options.contentType : "application/sdp"; + var bodyObj = { + body: body, + contentType: contentType + }; + objToConstruct.body = bodyObj; + objToConstruct.request.body = bodyObj; + } + /* Set other properties from the request */ + if (objToConstruct.request.from) { + objToConstruct.localIdentity = objToConstruct.request.from; + } + if (objToConstruct.request.to) { + objToConstruct.remoteIdentity = objToConstruct.request.to; + } + }; + ClientContext.prototype.send = function () { + var _this = this; + this.ua.userAgentCore.request(this.request, { + onAccept: function (response) { return _this.receiveResponse(response.message); }, + onProgress: function (response) { return _this.receiveResponse(response.message); }, + onRedirect: function (response) { return _this.receiveResponse(response.message); }, + onReject: function (response) { return _this.receiveResponse(response.message); }, + onTrying: function (response) { return _this.receiveResponse(response.message); } + }); + return this; + }; + ClientContext.prototype.receiveResponse = function (response) { + var statusCode = response.statusCode || 0; + var cause = Utils_1.Utils.getReasonPhrase(statusCode); + switch (true) { + case /^1[0-9]{2}$/.test(statusCode.toString()): + this.emit("progress", response, cause); + break; + case /^2[0-9]{2}$/.test(statusCode.toString()): + if (this.ua.applicants[this.toString()]) { + delete this.ua.applicants[this.toString()]; + } + this.emit("accepted", response, cause); + break; + default: + if (this.ua.applicants[this.toString()]) { + delete this.ua.applicants[this.toString()]; + } + this.emit("rejected", response, cause); + this.emit("failed", response, cause); + break; + } + }; + ClientContext.prototype.onRequestTimeout = function () { + this.emit("failed", undefined, Constants_1.C.causes.REQUEST_TIMEOUT); + }; + ClientContext.prototype.onTransportError = function () { + this.emit("failed", undefined, Constants_1.C.causes.CONNECTION_ERROR); + }; + return ClientContext; +}(events_1.EventEmitter)); +exports.ClientContext = ClientContext; + + +/***/ }), +/* 2 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + +var R = typeof Reflect === 'object' ? Reflect : null +var ReflectApply = R && typeof R.apply === 'function' + ? R.apply + : function ReflectApply(target, receiver, args) { + return Function.prototype.apply.call(target, receiver, args); + } + +var ReflectOwnKeys +if (R && typeof R.ownKeys === 'function') { + ReflectOwnKeys = R.ownKeys +} else if (Object.getOwnPropertySymbols) { + ReflectOwnKeys = function ReflectOwnKeys(target) { + return Object.getOwnPropertyNames(target) + .concat(Object.getOwnPropertySymbols(target)); + }; +} else { + ReflectOwnKeys = function ReflectOwnKeys(target) { + return Object.getOwnPropertyNames(target); + }; +} + +function ProcessEmitWarning(warning) { + if (console && console.warn) console.warn(warning); +} + +var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) { + return value !== value; +} + +function EventEmitter() { + EventEmitter.init.call(this); +} +module.exports = EventEmitter; + +// Backwards-compat with node 0.10.x +EventEmitter.EventEmitter = EventEmitter; + +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._eventsCount = 0; +EventEmitter.prototype._maxListeners = undefined; + +// By default EventEmitters will print a warning if more than 10 listeners are +// added to it. This is a useful default which helps finding memory leaks. +var defaultMaxListeners = 10; + +Object.defineProperty(EventEmitter, 'defaultMaxListeners', { + enumerable: true, + get: function() { + return defaultMaxListeners; + }, + set: function(arg) { + if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) { + throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.'); + } + defaultMaxListeners = arg; + } +}); + +EventEmitter.init = function() { + + if (this._events === undefined || + this._events === Object.getPrototypeOf(this)._events) { + this._events = Object.create(null); + this._eventsCount = 0; + } + + this._maxListeners = this._maxListeners || undefined; +}; + +// Obviously not all Emitters should be limited to 10. This function allows +// that to be increased. Set to zero for unlimited. +EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { + if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) { + throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.'); + } + this._maxListeners = n; + return this; +}; + +function $getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter.defaultMaxListeners; + return that._maxListeners; +} + +EventEmitter.prototype.getMaxListeners = function getMaxListeners() { + return $getMaxListeners(this); +}; + +EventEmitter.prototype.emit = function emit(type) { + var args = []; + for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); + var doError = (type === 'error'); + + var events = this._events; + if (events !== undefined) + doError = (doError && events.error === undefined); + else if (!doError) + return false; + + // If there is no 'error' event listener then throw. + if (doError) { + var er; + if (args.length > 0) + er = args[0]; + if (er instanceof Error) { + // Note: The comments on the `throw` lines are intentional, they show + // up in Node's output if this results in an unhandled exception. + throw er; // Unhandled 'error' event + } + // At least give some kind of context to the user + var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : '')); + err.context = er; + throw err; // Unhandled 'error' event + } + + var handler = events[type]; + + if (handler === undefined) + return false; + + if (typeof handler === 'function') { + ReflectApply(handler, this, args); + } else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + ReflectApply(listeners[i], this, args); + } + + return true; +}; + +function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; + + if (typeof listener !== 'function') { + throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); + } + + events = target._events; + if (events === undefined) { + events = target._events = Object.create(null); + target._eventsCount = 0; + } else { + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (events.newListener !== undefined) { + target.emit('newListener', type, + listener.listener ? listener.listener : listener); + + // Re-assign `events` because a newListener handler could have caused the + // this._events to be assigned to a new object + events = target._events; + } + existing = events[type]; + } + + if (existing === undefined) { + // Optimize the case of one listener. Don't need the extra array object. + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === 'function') { + // Adding the second element, need to change to array. + existing = events[type] = + prepend ? [listener, existing] : [existing, listener]; + // If we've already got an array, just append. + } else if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + + // Check for listener leak + m = $getMaxListeners(target); + if (m > 0 && existing.length > m && !existing.warned) { + existing.warned = true; + // No error code for this since it is a Warning + // eslint-disable-next-line no-restricted-syntax + var w = new Error('Possible EventEmitter memory leak detected. ' + + existing.length + ' ' + String(type) + ' listeners ' + + 'added. Use emitter.setMaxListeners() to ' + + 'increase limit'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + ProcessEmitWarning(w); + } + } + + return target; +} + +EventEmitter.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); +}; + +EventEmitter.prototype.on = EventEmitter.prototype.addListener; + +EventEmitter.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; + +function onceWrapper() { + var args = []; + for (var i = 0; i < arguments.length; i++) args.push(arguments[i]); + if (!this.fired) { + this.target.removeListener(this.type, this.wrapFn); + this.fired = true; + ReflectApply(this.listener, this.target, args); + } +} + +function _onceWrap(target, type, listener) { + var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; + var wrapped = onceWrapper.bind(state); + wrapped.listener = listener; + state.wrapFn = wrapped; + return wrapped; +} + +EventEmitter.prototype.once = function once(type, listener) { + if (typeof listener !== 'function') { + throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); + } + this.on(type, _onceWrap(this, type, listener)); + return this; +}; + +EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + if (typeof listener !== 'function') { + throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); + } + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; + +// Emits a 'removeListener' event if and only if the listener was removed. +EventEmitter.prototype.removeListener = + function removeListener(type, listener) { + var list, events, position, i, originalListener; + + if (typeof listener !== 'function') { + throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); + } + + events = this._events; + if (events === undefined) + return this; + + list = events[type]; + if (list === undefined) + return this; + + if (list === listener || list.listener === listener) { + if (--this._eventsCount === 0) + this._events = Object.create(null); + else { + delete events[type]; + if (events.removeListener) + this.emit('removeListener', type, list.listener || listener); + } + } else if (typeof list !== 'function') { + position = -1; + + for (i = list.length - 1; i >= 0; i--) { + if (list[i] === listener || list[i].listener === listener) { + originalListener = list[i].listener; + position = i; + break; + } + } + + if (position < 0) + return this; + + if (position === 0) + list.shift(); + else { + spliceOne(list, position); + } + + if (list.length === 1) + events[type] = list[0]; + + if (events.removeListener !== undefined) + this.emit('removeListener', type, originalListener || listener); + } + + return this; + }; + +EventEmitter.prototype.off = EventEmitter.prototype.removeListener; + +EventEmitter.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events, i; + + events = this._events; + if (events === undefined) + return this; + + // not listening for removeListener, no need to emit + if (events.removeListener === undefined) { + if (arguments.length === 0) { + this._events = Object.create(null); + this._eventsCount = 0; + } else if (events[type] !== undefined) { + if (--this._eventsCount === 0) + this._events = Object.create(null); + else + delete events[type]; + } + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + var keys = Object.keys(events); + var key; + for (i = 0; i < keys.length; ++i) { + key = keys[i]; + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = Object.create(null); + this._eventsCount = 0; + return this; + } + + listeners = events[type]; + + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners !== undefined) { + // LIFO order + for (i = listeners.length - 1; i >= 0; i--) { + this.removeListener(type, listeners[i]); + } + } + + return this; + }; + +function _listeners(target, type, unwrap) { + var events = target._events; + + if (events === undefined) + return []; + + var evlistener = events[type]; + if (evlistener === undefined) + return []; + + if (typeof evlistener === 'function') + return unwrap ? [evlistener.listener || evlistener] : [evlistener]; + + return unwrap ? + unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); +} + +EventEmitter.prototype.listeners = function listeners(type) { + return _listeners(this, type, true); +}; + +EventEmitter.prototype.rawListeners = function rawListeners(type) { + return _listeners(this, type, false); +}; + +EventEmitter.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount.call(emitter, type); + } +}; + +EventEmitter.prototype.listenerCount = listenerCount; +function listenerCount(type) { + var events = this._events; + + if (events !== undefined) { + var evlistener = events[type]; + + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener !== undefined) { + return evlistener.length; + } + } + + return 0; +} + +EventEmitter.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; +}; + +function arrayClone(arr, n) { + var copy = new Array(n); + for (var i = 0; i < n; ++i) + copy[i] = arr[i]; + return copy; +} + +function spliceOne(list, index) { + for (; index + 1 < list.length; index++) + list[index] = list[index + 1]; + list.pop(); +} + +function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; +} + + +/***/ }), +/* 3 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +// tslint:disable-next-line:no-var-requires +var pkg = __webpack_require__(4); +var C; +(function (C) { + C.USER_AGENT = pkg.title + "/" + pkg.version; + // SIP scheme + C.SIP = "sip"; + C.SIPS = "sips"; + // End and Failure causes + var causes; + (function (causes) { + // Generic error causes + causes["CONNECTION_ERROR"] = "Connection Error"; + causes["INTERNAL_ERROR"] = "Internal Error"; + causes["REQUEST_TIMEOUT"] = "Request Timeout"; + causes["SIP_FAILURE_CODE"] = "SIP Failure Code"; + // SIP error causes + causes["ADDRESS_INCOMPLETE"] = "Address Incomplete"; + causes["AUTHENTICATION_ERROR"] = "Authentication Error"; + causes["BUSY"] = "Busy"; + causes["DIALOG_ERROR"] = "Dialog Error"; + causes["INCOMPATIBLE_SDP"] = "Incompatible SDP"; + causes["NOT_FOUND"] = "Not Found"; + causes["REDIRECTED"] = "Redirected"; + causes["REJECTED"] = "Rejected"; + causes["UNAVAILABLE"] = "Unavailable"; + // Session error causes + causes["BAD_MEDIA_DESCRIPTION"] = "Bad Media Description"; + causes["CANCELED"] = "Canceled"; + causes["EXPIRES"] = "Expires"; + causes["NO_ACK"] = "No ACK"; + causes["NO_ANSWER"] = "No Answer"; + causes["NO_PRACK"] = "No PRACK"; + causes["RTP_TIMEOUT"] = "RTP Timeout"; + causes["USER_DENIED_MEDIA_ACCESS"] = "User Denied Media Access"; + causes["WEBRTC_ERROR"] = "WebRTC Error"; + causes["WEBRTC_NOT_SUPPORTED"] = "WebRTC Not Supported"; + })(causes = C.causes || (C.causes = {})); + var supported; + (function (supported) { + supported["REQUIRED"] = "required"; + supported["SUPPORTED"] = "supported"; + supported["UNSUPPORTED"] = "none"; + })(supported = C.supported || (C.supported = {})); + C.SIP_ERROR_CAUSES = { + ADDRESS_INCOMPLETE: [484], + AUTHENTICATION_ERROR: [401, 407], + BUSY: [486, 600], + INCOMPATIBLE_SDP: [488, 606], + NOT_FOUND: [404, 604], + REDIRECTED: [300, 301, 302, 305, 380], + REJECTED: [403, 603], + UNAVAILABLE: [480, 410, 408, 430] + }; + // SIP Methods + C.ACK = "ACK"; + C.BYE = "BYE"; + C.CANCEL = "CANCEL"; + C.INFO = "INFO"; + C.INVITE = "INVITE"; + C.MESSAGE = "MESSAGE"; + C.NOTIFY = "NOTIFY"; + C.OPTIONS = "OPTIONS"; + C.REGISTER = "REGISTER"; + C.UPDATE = "UPDATE"; + C.SUBSCRIBE = "SUBSCRIBE"; + C.PUBLISH = "PUBLISH"; + C.REFER = "REFER"; + C.PRACK = "PRACK"; + /* SIP Response Reasons + * DOC: http://www.iana.org/assignments/sip-parameters + * Copied from https://github.com/versatica/OverSIP/blob/master/lib/oversip/sip/constants.rb#L7 + */ + C.REASON_PHRASE = { + 100: "Trying", + 180: "Ringing", + 181: "Call Is Being Forwarded", + 182: "Queued", + 183: "Session Progress", + 199: "Early Dialog Terminated", + 200: "OK", + 202: "Accepted", + 204: "No Notification", + 300: "Multiple Choices", + 301: "Moved Permanently", + 302: "Moved Temporarily", + 305: "Use Proxy", + 380: "Alternative Service", + 400: "Bad Request", + 401: "Unauthorized", + 402: "Payment Required", + 403: "Forbidden", + 404: "Not Found", + 405: "Method Not Allowed", + 406: "Not Acceptable", + 407: "Proxy Authentication Required", + 408: "Request Timeout", + 410: "Gone", + 412: "Conditional Request Failed", + 413: "Request Entity Too Large", + 414: "Request-URI Too Long", + 415: "Unsupported Media Type", + 416: "Unsupported URI Scheme", + 417: "Unknown Resource-Priority", + 420: "Bad Extension", + 421: "Extension Required", + 422: "Session Interval Too Small", + 423: "Interval Too Brief", + 428: "Use Identity Header", + 429: "Provide Referrer Identity", + 430: "Flow Failed", + 433: "Anonymity Disallowed", + 436: "Bad Identity-Info", + 437: "Unsupported Certificate", + 438: "Invalid Identity Header", + 439: "First Hop Lacks Outbound Support", + 440: "Max-Breadth Exceeded", + 469: "Bad Info Package", + 470: "Consent Needed", + 478: "Unresolvable Destination", + 480: "Temporarily Unavailable", + 481: "Call/Transaction Does Not Exist", + 482: "Loop Detected", + 483: "Too Many Hops", + 484: "Address Incomplete", + 485: "Ambiguous", + 486: "Busy Here", + 487: "Request Terminated", + 488: "Not Acceptable Here", + 489: "Bad Event", + 491: "Request Pending", + 493: "Undecipherable", + 494: "Security Agreement Required", + 500: "Internal Server Error", + 501: "Not Implemented", + 502: "Bad Gateway", + 503: "Service Unavailable", + 504: "Server Time-out", + 505: "Version Not Supported", + 513: "Message Too Large", + 580: "Precondition Failure", + 600: "Busy Everywhere", + 603: "Decline", + 604: "Does Not Exist Anywhere", + 606: "Not Acceptable" + }; + /* SIP Option Tags + * DOC: http://www.iana.org/assignments/sip-parameters/sip-parameters.xhtml#sip-parameters-4 + */ + C.OPTION_TAGS = { + "100rel": true, + "199": true, + "answermode": true, + "early-session": true, + "eventlist": true, + "explicitsub": true, + "from-change": true, + "geolocation-http": true, + "geolocation-sip": true, + "gin": true, + "gruu": true, + "histinfo": true, + "ice": true, + "join": true, + "multiple-refer": true, + "norefersub": true, + "nosub": true, + "outbound": true, + "path": true, + "policy": true, + "precondition": true, + "pref": true, + "privacy": true, + "recipient-list-invite": true, + "recipient-list-message": true, + "recipient-list-subscribe": true, + "replaces": true, + "resource-priority": true, + "sdp-anat": true, + "sec-agree": true, + "tdialog": true, + "timer": true, + "uui": true // RFC 7433 + }; + var dtmfType; + (function (dtmfType) { + dtmfType["INFO"] = "info"; + dtmfType["RTP"] = "rtp"; + })(dtmfType = C.dtmfType || (C.dtmfType = {})); +})(C = exports.C || (exports.C = {})); + + +/***/ }), +/* 4 */ +/***/ (function(module) { + +module.exports = {"name":"sip.js","title":"SIP.js","description":"A simple, intuitive, and powerful JavaScript signaling library","version":"0.14.0","license":"MIT","main":"./lib/index.js","types":"./lib/index.d.ts","homepage":"https://sipjs.com","author":"OnSIP (https://sipjs.com/aboutus/)","contributors":[{"url":"https://github.com/onsip/SIP.js/blob/master/THANKS.md"}],"repository":{"type":"git","url":"https://github.com/onsip/SIP.js.git"},"keywords":["sip","webrtc","library","websocket","javascript","typescript"],"dependencies":{"crypto-js":"^3.1.9-1"},"devDependencies":{"@types/crypto-js":"^3.1.43","@types/jasmine":"^3.3.11","@types/node":"^12.0.2","circular-dependency-plugin":"^5.0.2","jasmine-core":"^3.4.0","karma":"^4.1.0","karma-chrome-launcher":"^2.2.0","karma-cli":"^2.0.0","karma-jasmine":"^2.0.1","karma-jasmine-html-reporter":"^1.4.2","karma-mocha-reporter":"^2.2.5","karma-sourcemap-loader":"^0.3.7","karma-webpack":"^3.0.5","pegjs":"^0.10.0","ts-loader":"^6.0.1","ts-pegjs":"0.2.3","tslint":"^5.16.0","typescript":"^3.4.5","webpack":"^4.32.0","webpack-cli":"^3.3.2"},"engines":{"node":">=8.0"},"scripts":{"prebuild":"tslint -p tsconfig-base.json -c tslint.json","generate-grammar":"node build/grammarGenerator.js","build-reg-bundle":"webpack --progress --config build/webpack.config.js --env.buildType reg","build-min-bundle":"webpack --progress --config build/webpack.config.js --env.buildType min","build-bundles":"npm run build-reg-bundle && npm run build-min-bundle","build-lib":"tsc -p src","build-test":"tsc -p test","copy-dist-files":"cp dist/sip.js dist/sip-$npm_package_version.js && cp dist/sip.min.js dist/sip-$npm_package_version.min.js","build":"npm run generate-grammar && npm run build-lib && npm run build-reg-bundle && npm run build-min-bundle && npm run copy-dist-files","browserTest":"npm run build-test && sleep 2 && open http://0.0.0.0:9876/debug.html & karma start --reporters kjhtml --no-single-run","commandLineTest":"npm run build-test && karma start --reporters mocha --browsers ChromeHeadless --single-run","buildAndTest":"npm run build && npm run commandLineTest","buildAndBrowserTest":"npm run build && npm run browserTest"}}; + +/***/ }), +/* 5 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +// enums can't really be declared, so they are set here. +// pulled out of individual files to avoid circular dependencies +Object.defineProperty(exports, "__esModule", { value: true }); +var DialogStatus; +(function (DialogStatus) { + DialogStatus[DialogStatus["STATUS_EARLY"] = 1] = "STATUS_EARLY"; + DialogStatus[DialogStatus["STATUS_CONFIRMED"] = 2] = "STATUS_CONFIRMED"; +})(DialogStatus = exports.DialogStatus || (exports.DialogStatus = {})); +var SessionStatus; +(function (SessionStatus) { + // Session states + SessionStatus[SessionStatus["STATUS_NULL"] = 0] = "STATUS_NULL"; + SessionStatus[SessionStatus["STATUS_INVITE_SENT"] = 1] = "STATUS_INVITE_SENT"; + SessionStatus[SessionStatus["STATUS_1XX_RECEIVED"] = 2] = "STATUS_1XX_RECEIVED"; + SessionStatus[SessionStatus["STATUS_INVITE_RECEIVED"] = 3] = "STATUS_INVITE_RECEIVED"; + SessionStatus[SessionStatus["STATUS_WAITING_FOR_ANSWER"] = 4] = "STATUS_WAITING_FOR_ANSWER"; + SessionStatus[SessionStatus["STATUS_ANSWERED"] = 5] = "STATUS_ANSWERED"; + SessionStatus[SessionStatus["STATUS_WAITING_FOR_PRACK"] = 6] = "STATUS_WAITING_FOR_PRACK"; + SessionStatus[SessionStatus["STATUS_WAITING_FOR_ACK"] = 7] = "STATUS_WAITING_FOR_ACK"; + SessionStatus[SessionStatus["STATUS_CANCELED"] = 8] = "STATUS_CANCELED"; + SessionStatus[SessionStatus["STATUS_TERMINATED"] = 9] = "STATUS_TERMINATED"; + SessionStatus[SessionStatus["STATUS_ANSWERED_WAITING_FOR_PRACK"] = 10] = "STATUS_ANSWERED_WAITING_FOR_PRACK"; + SessionStatus[SessionStatus["STATUS_EARLY_MEDIA"] = 11] = "STATUS_EARLY_MEDIA"; + SessionStatus[SessionStatus["STATUS_CONFIRMED"] = 12] = "STATUS_CONFIRMED"; +})(SessionStatus = exports.SessionStatus || (exports.SessionStatus = {})); +var TypeStrings; +(function (TypeStrings) { + TypeStrings[TypeStrings["ClientContext"] = 0] = "ClientContext"; + TypeStrings[TypeStrings["ConfigurationError"] = 1] = "ConfigurationError"; + TypeStrings[TypeStrings["Dialog"] = 2] = "Dialog"; + TypeStrings[TypeStrings["DigestAuthentication"] = 3] = "DigestAuthentication"; + TypeStrings[TypeStrings["DTMF"] = 4] = "DTMF"; + TypeStrings[TypeStrings["IncomingMessage"] = 5] = "IncomingMessage"; + TypeStrings[TypeStrings["IncomingRequest"] = 6] = "IncomingRequest"; + TypeStrings[TypeStrings["IncomingResponse"] = 7] = "IncomingResponse"; + TypeStrings[TypeStrings["InvalidStateError"] = 8] = "InvalidStateError"; + TypeStrings[TypeStrings["InviteClientContext"] = 9] = "InviteClientContext"; + TypeStrings[TypeStrings["InviteServerContext"] = 10] = "InviteServerContext"; + TypeStrings[TypeStrings["Logger"] = 11] = "Logger"; + TypeStrings[TypeStrings["LoggerFactory"] = 12] = "LoggerFactory"; + TypeStrings[TypeStrings["MethodParameterError"] = 13] = "MethodParameterError"; + TypeStrings[TypeStrings["NameAddrHeader"] = 14] = "NameAddrHeader"; + TypeStrings[TypeStrings["NotSupportedError"] = 15] = "NotSupportedError"; + TypeStrings[TypeStrings["OutgoingRequest"] = 16] = "OutgoingRequest"; + TypeStrings[TypeStrings["Parameters"] = 17] = "Parameters"; + TypeStrings[TypeStrings["PublishContext"] = 18] = "PublishContext"; + TypeStrings[TypeStrings["ReferClientContext"] = 19] = "ReferClientContext"; + TypeStrings[TypeStrings["ReferServerContext"] = 20] = "ReferServerContext"; + TypeStrings[TypeStrings["RegisterContext"] = 21] = "RegisterContext"; + TypeStrings[TypeStrings["RenegotiationError"] = 22] = "RenegotiationError"; + TypeStrings[TypeStrings["RequestSender"] = 23] = "RequestSender"; + TypeStrings[TypeStrings["ServerContext"] = 24] = "ServerContext"; + TypeStrings[TypeStrings["Session"] = 25] = "Session"; + TypeStrings[TypeStrings["SessionDescriptionHandler"] = 26] = "SessionDescriptionHandler"; + TypeStrings[TypeStrings["SessionDescriptionHandlerError"] = 27] = "SessionDescriptionHandlerError"; + TypeStrings[TypeStrings["SessionDescriptionHandlerObserver"] = 28] = "SessionDescriptionHandlerObserver"; + TypeStrings[TypeStrings["Subscription"] = 29] = "Subscription"; + TypeStrings[TypeStrings["Transport"] = 30] = "Transport"; + TypeStrings[TypeStrings["UA"] = 31] = "UA"; + TypeStrings[TypeStrings["URI"] = 32] = "URI"; +})(TypeStrings = exports.TypeStrings || (exports.TypeStrings = {})); +// UA status codes +var UAStatus; +(function (UAStatus) { + UAStatus[UAStatus["STATUS_INIT"] = 0] = "STATUS_INIT"; + UAStatus[UAStatus["STATUS_STARTING"] = 1] = "STATUS_STARTING"; + UAStatus[UAStatus["STATUS_READY"] = 2] = "STATUS_READY"; + UAStatus[UAStatus["STATUS_USER_CLOSED"] = 3] = "STATUS_USER_CLOSED"; + UAStatus[UAStatus["STATUS_NOT_READY"] = 4] = "STATUS_NOT_READY"; +})(UAStatus = exports.UAStatus || (exports.UAStatus = {})); + + +/***/ }), +/* 6 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Constants_1 = __webpack_require__(3); +var Enums_1 = __webpack_require__(5); +var Grammar_1 = __webpack_require__(7); +var Utils_1 = __webpack_require__(11); +exports.getSupportedHeader = function (request) { + var optionTags = []; + if (request.method === Constants_1.C.REGISTER) { + optionTags.push("path", "gruu"); + } + else if (request.method === Constants_1.C.INVITE && + (request.ua.contact.pubGruu || request.ua.contact.tempGruu)) { + optionTags.push("gruu"); + } + if (request.ua.configuration.rel100 === Constants_1.C.supported.SUPPORTED) { + optionTags.push("100rel"); + } + if (request.ua.configuration.replaces === Constants_1.C.supported.SUPPORTED) { + optionTags.push("replaces"); + } + optionTags.push("outbound"); + optionTags = optionTags.concat(request.ua.configuration.extraSupported || []); + var allowUnregistered = request.ua.configuration.hackAllowUnregisteredOptionTags || false; + var optionTagSet = {}; + optionTags = optionTags.filter(function (optionTag) { + var registered = Constants_1.C.OPTION_TAGS[optionTag]; + var unique = !optionTagSet[optionTag]; + optionTagSet[optionTag] = true; + return (registered || allowUnregistered) && unique; + }); + return "Supported: " + optionTags.join(", ") + "\r\n"; +}; +/** + * @class Class for outgoing SIP request. + * @param {String} method request method + * @param {String} ruri request uri + * @param {SIP.UA} ua + * @param {Object} params parameters that will have priority over ua.configuration parameters: + *
+ * - cseq, callId, fromTag, fromUri, fromDisplayName, toUri, toTag, routeSet + * @param {Object} [headers] extra headers + * @param {String} [body] + */ +var OutgoingRequest = /** @class */ (function () { + function OutgoingRequest(method, ruri, ua, params, extraHeaders, body) { + if (params === void 0) { params = {}; } + this.type = Enums_1.TypeStrings.OutgoingRequest; + this.ua = ua; + this.headers = {}; + this.method = method; + this.ruri = ruri; + this.body = body; + this.extraHeaders = (extraHeaders || []).slice(); + // Fill the Common SIP Request Headers + // Route + if (params.routeSet) { + this.setHeader("route", params.routeSet); + } + else if (ua.configuration.usePreloadedRoute && ua.transport) { + this.setHeader("route", ua.transport.server.sipUri); + } + // Via + // Empty Via header. Will be filled by the client transaction. + this.setHeader("via", ""); + // Max-Forwards + // is a constant on ua.c, removed for circular dependency + this.setHeader("max-forwards", "70"); + // To + var toUri = params.toUri || ruri; + this.toTag = params.toTag; + var to = (params.toDisplayName || params.toDisplayName === 0) ? '"' + params.toDisplayName + '" ' : ""; + to += "<" + (toUri.type === Enums_1.TypeStrings.URI ? toUri.toRaw() : toUri) + ">"; + to += this.toTag ? ";tag=" + this.toTag : ""; + this.to = Grammar_1.Grammar.nameAddrHeaderParse(to); + this.setHeader("to", to); + // From + var fromUri = params.fromUri || ua.configuration.uri || ""; + this.fromTag = params.fromTag || Utils_1.Utils.newTag(); + var from; + if (params.fromDisplayName || params.fromDisplayName === 0) { + from = '"' + params.fromDisplayName + '" '; + } + else if (ua.configuration.displayName) { + from = '"' + ua.configuration.displayName + '" '; + } + else { + from = ""; + } + from += "<" + (fromUri.type === Enums_1.TypeStrings.URI ? fromUri.toRaw() : fromUri) + ">;tag="; + from += this.fromTag; + this.from = Grammar_1.Grammar.nameAddrHeaderParse(from); + this.setHeader("from", from); + // Call-ID + this.callId = params.callId || (ua.configuration.sipjsId + Utils_1.Utils.createRandomToken(15)); + this.setHeader("call-id", this.callId); + // CSeq + // Why not make this a "1" if not provided? See: https://tools.ietf.org/html/rfc3261#section-8.1.1.5 + this.cseq = params.cseq || Math.floor(Math.random() * 10000); + this.setHeader("cseq", this.cseq + " " + method); + } + /** + * Get the value of the given header name at the given position. + * @param {String} name header name + * @returns {String|undefined} Returns the specified header, undefined if header doesn't exist. + */ + OutgoingRequest.prototype.getHeader = function (name) { + var header = this.headers[Utils_1.Utils.headerize(name)]; + if (header) { + if (header[0]) { + return header[0]; + } + } + else { + var regexp = new RegExp("^\\s*" + name + "\\s*:", "i"); + for (var _i = 0, _a = this.extraHeaders; _i < _a.length; _i++) { + var exHeader = _a[_i]; + if (regexp.test(exHeader)) { + return exHeader.substring(exHeader.indexOf(":") + 1).trim(); + } + } + } + return; + }; + /** + * Get the header/s of the given name. + * @param {String} name header name + * @returns {Array} Array with all the headers of the specified name. + */ + OutgoingRequest.prototype.getHeaders = function (name) { + var result = []; + var headerArray = this.headers[Utils_1.Utils.headerize(name)]; + if (headerArray) { + for (var _i = 0, headerArray_1 = headerArray; _i < headerArray_1.length; _i++) { + var headerPart = headerArray_1[_i]; + result.push(headerPart); + } + } + else { + var regexp = new RegExp("^\\s*" + name + "\\s*:", "i"); + for (var _a = 0, _b = this.extraHeaders; _a < _b.length; _a++) { + var exHeader = _b[_a]; + if (regexp.test(exHeader)) { + result.push(exHeader.substring(exHeader.indexOf(":") + 1).trim()); + } + } + } + return result; + }; + /** + * Verify the existence of the given header. + * @param {String} name header name + * @returns {boolean} true if header with given name exists, false otherwise + */ + OutgoingRequest.prototype.hasHeader = function (name) { + if (this.headers[Utils_1.Utils.headerize(name)]) { + return true; + } + else { + var regexp = new RegExp("^\\s*" + name + "\\s*:", "i"); + for (var _i = 0, _a = this.extraHeaders; _i < _a.length; _i++) { + var extraHeader = _a[_i]; + if (regexp.test(extraHeader)) { + return true; + } + } + } + return false; + }; + /** + * Replace the the given header by the given value. + * @param {String} name header name + * @param {String | Array} value header value + */ + OutgoingRequest.prototype.setHeader = function (name, value) { + this.headers[Utils_1.Utils.headerize(name)] = (value instanceof Array) ? value : [value]; + }; + /** + * The Via header field indicates the transport used for the transaction + * and identifies the location where the response is to be sent. A Via + * header field value is added only after the transport that will be + * used to reach the next hop has been selected (which may involve the + * usage of the procedures in [4]). + * + * When the UAC creates a request, it MUST insert a Via into that + * request. The protocol name and protocol version in the header field + * MUST be SIP and 2.0, respectively. The Via header field value MUST + * contain a branch parameter. This parameter is used to identify the + * transaction created by that request. This parameter is used by both + * the client and the server. + * https://tools.ietf.org/html/rfc3261#section-8.1.1.7 + * @param branchParameter The branch parameter. + * @param transport The transport. + */ + OutgoingRequest.prototype.setViaHeader = function (branch, transport) { + // FIXME: Default scheme to "WSS" + // This should go away once transport is typed and we can be sure + // we are getting the something valid from there transport. + var scheme = "WSS"; + // FIXME: Transport's server property is not typed (as of writing this). + if (transport.server && transport.server.scheme) { + scheme = transport.server.scheme; + } + // FIXME: Hack + if (this.ua.configuration.hackViaTcp) { + scheme = "TCP"; + } + var via = "SIP/2.0/" + scheme; + via += " " + this.ua.configuration.viaHost + ";branch=" + branch; + if (this.ua.configuration.forceRport) { + via += ";rport"; + } + this.setHeader("via", via); + this.branch = branch; + }; + OutgoingRequest.prototype.toString = function () { + var msg = ""; + msg += this.method + " " + (this.ruri.type === Enums_1.TypeStrings.URI ? + this.ruri.toRaw() : this.ruri) + " SIP/2.0\r\n"; + for (var header in this.headers) { + if (this.headers[header]) { + for (var _i = 0, _a = this.headers[header]; _i < _a.length; _i++) { + var headerPart = _a[_i]; + msg += header + ": " + headerPart + "\r\n"; + } + } + } + for (var _b = 0, _c = this.extraHeaders; _b < _c.length; _b++) { + var header = _c[_b]; + msg += header.trim() + "\r\n"; + } + msg += exports.getSupportedHeader(this); + msg += "User-Agent: " + this.ua.configuration.userAgentString + "\r\n"; + if (this.body) { + if (typeof this.body === "string") { + msg += "Content-Length: " + Utils_1.Utils.str_utf8_length(this.body) + "\r\n\r\n"; + msg += this.body; + } + else { + if (this.body.body && this.body.contentType) { + msg += "Content-Type: " + this.body.contentType + "\r\n"; + msg += "Content-Length: " + Utils_1.Utils.str_utf8_length(this.body.body) + "\r\n\r\n"; + msg += this.body.body; + } + else { + msg += "Content-Length: " + 0 + "\r\n\r\n"; + } + } + } + else { + msg += "Content-Length: " + 0 + "\r\n\r\n"; + } + return msg; + }; + return OutgoingRequest; +}()); +exports.OutgoingRequest = OutgoingRequest; +/** + * @class Class for incoming SIP message. + */ +// tslint:disable-next-line:max-classes-per-file +var IncomingMessage = /** @class */ (function () { + function IncomingMessage() { + this.type = Enums_1.TypeStrings.IncomingMessage; + this.headers = {}; + } + /** + * Insert a header of the given name and value into the last position of the + * header array. + * @param {String} name header name + * @param {String} value header value + */ + IncomingMessage.prototype.addHeader = function (name, value) { + var header = { raw: value }; + name = Utils_1.Utils.headerize(name); + if (this.headers[name]) { + this.headers[name].push(header); + } + else { + this.headers[name] = [header]; + } + }; + /** + * Get the value of the given header name at the given position. + * @param {String} name header name + * @returns {String|undefined} Returns the specified header, undefined if header doesn't exist. + */ + IncomingMessage.prototype.getHeader = function (name) { + var header = this.headers[Utils_1.Utils.headerize(name)]; + if (header) { + if (header[0]) { + return header[0].raw; + } + } + else { + return; + } + }; + /** + * Get the header/s of the given name. + * @param {String} name header name + * @returns {Array} Array with all the headers of the specified name. + */ + IncomingMessage.prototype.getHeaders = function (name) { + var header = this.headers[Utils_1.Utils.headerize(name)]; + var result = []; + if (!header) { + return []; + } + for (var _i = 0, header_1 = header; _i < header_1.length; _i++) { + var headerPart = header_1[_i]; + result.push(headerPart.raw); + } + return result; + }; + /** + * Verify the existence of the given header. + * @param {String} name header name + * @returns {boolean} true if header with given name exists, false otherwise + */ + IncomingMessage.prototype.hasHeader = function (name) { + return !!this.headers[Utils_1.Utils.headerize(name)]; + }; + /** + * Parse the given header on the given index. + * @param {String} name header name + * @param {Number} [idx=0] header index + * @returns {Object|undefined} Parsed header object, undefined if the + * header is not present or in case of a parsing error. + */ + IncomingMessage.prototype.parseHeader = function (name, idx) { + if (idx === void 0) { idx = 0; } + name = Utils_1.Utils.headerize(name); + if (!this.headers[name]) { + // this.logger.log("header '" + name + "' not present"); + return; + } + else if (idx >= this.headers[name].length) { + // this.logger.log("not so many '" + name + "' headers present"); + return; + } + var header = this.headers[name][idx]; + var value = header.raw; + if (header.parsed) { + return header.parsed; + } + // substitute '-' by '_' for grammar rule matching. + var parsed = Grammar_1.Grammar.parse(value, name.replace(/-/g, "_")); + if (parsed === -1) { + this.headers[name].splice(idx, 1); // delete from headers + // this.logger.warn('error parsing "' + name + '" header field with value "' + value + '"'); + return; + } + else { + header.parsed = parsed; + return parsed; + } + }; + /** + * Message Header attribute selector. Alias of parseHeader. + * @param {String} name header name + * @param {Number} [idx=0] header index + * @returns {Object|undefined} Parsed header object, undefined if the + * header is not present or in case of a parsing error. + * + * @example + * message.s('via',3).port + */ + IncomingMessage.prototype.s = function (name, idx) { + if (idx === void 0) { idx = 0; } + return this.parseHeader(name, idx); + }; + /** + * Replace the value of the given header by the value. + * @param {String} name header name + * @param {String} value header value + */ + IncomingMessage.prototype.setHeader = function (name, value) { + this.headers[Utils_1.Utils.headerize(name)] = [{ raw: value }]; + }; + IncomingMessage.prototype.toString = function () { + return this.data; + }; + return IncomingMessage; +}()); +exports.IncomingMessage = IncomingMessage; +/** + * @class Class for incoming SIP request. + */ +// tslint:disable-next-line:max-classes-per-file +var IncomingRequest = /** @class */ (function (_super) { + __extends(IncomingRequest, _super); + function IncomingRequest(ua) { + var _this = _super.call(this) || this; + _this.ua = ua; + _this.type = Enums_1.TypeStrings.IncomingRequest; + return _this; + } + return IncomingRequest; +}(IncomingMessage)); +exports.IncomingRequest = IncomingRequest; +/** + * @class Class for incoming SIP response. + */ +// tslint:disable-next-line:max-classes-per-file +var IncomingResponse = /** @class */ (function (_super) { + __extends(IncomingResponse, _super); + function IncomingResponse(ua) { + var _this = _super.call(this) || this; + _this.ua = ua; + _this.type = Enums_1.TypeStrings.IncomingResponse; + _this.headers = {}; + return _this; + } + return IncomingResponse; +}(IncomingMessage)); +exports.IncomingResponse = IncomingResponse; + + +/***/ }), +/* 7 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +var pegGrammar = __webpack_require__(8); +var Grammar; +(function (Grammar) { + function parse(input, startRule) { + var options = { startRule: startRule }; + try { + pegGrammar.parse(input, options); + } + catch (e) { + options.data = -1; + } + return options.data; + } + Grammar.parse = parse; + /** + * Parse the given string and returns a SIP.NameAddrHeader instance or undefined if + * it is an invalid NameAddrHeader. + * @public + * @param {String} name_addr_header + */ + function nameAddrHeaderParse(nameAddrHeader) { + var parsedNameAddrHeader = Grammar.parse(nameAddrHeader, "Name_Addr_Header"); + return parsedNameAddrHeader !== -1 ? parsedNameAddrHeader : undefined; + } + Grammar.nameAddrHeaderParse = nameAddrHeaderParse; + /** + * Parse the given string and returns a SIP.URI instance or undefined if + * it is an invalid URI. + * @public + * @param {String} uri + */ + function URIParse(uri) { + var parsedUri = Grammar.parse(uri, "SIP_URI"); + return parsedUri !== -1 ? parsedUri : undefined; + } + Grammar.URIParse = URIParse; +})(Grammar = exports.Grammar || (exports.Grammar = {})); + + +/***/ }), +/* 8 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +// tslint:disable:interface-name +// tslint:disable: trailing-comma +// tslint:disable: object-literal-sort-keys +// tslint:disable: max-line-length +// tslint:disable: only-arrow-functions +// tslint:disable: one-variable-per-declaration +// tslint:disable: no-consecutive-blank-lines +// tslint:disable: align +// tslint:disable: radix +// tslint:disable: quotemark +// tslint:disable: semicolon +// tslint:disable: object-literal-shorthand +// tslint:disable: variable-name +// tslint:disable: no-var-keyword +// tslint:disable: whitespace +// tslint:disable: curly +// tslint:disable: prefer-const +// tslint:disable: object-literal-key-quotes +// tslint:disable: no-string-literal +// tslint:disable: one-line +// tslint:disable: no-unused-expression +// tslint:disable: space-before-function-paren +// tslint:disable: arrow-return-shorthand +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +// Generated by PEG.js v. 0.10.0 (ts-pegjs plugin v. 0.2.3 ) +// +// https://pegjs.org/ https://github.com/metadevpro/ts-pegjs +var NameAddrHeader_1 = __webpack_require__(9); +var URI_1 = __webpack_require__(10); +var SyntaxError = /** @class */ (function (_super) { + __extends(SyntaxError, _super); + function SyntaxError(message, expected, found, location) { + var _this = _super.call(this) || this; + _this.message = message; + _this.expected = expected; + _this.found = found; + _this.location = location; + _this.name = "SyntaxError"; + if (typeof Error.captureStackTrace === "function") { + Error.captureStackTrace(_this, SyntaxError); + } + return _this; + } + SyntaxError.buildMessage = function (expected, found) { + function hex(ch) { + return ch.charCodeAt(0).toString(16).toUpperCase(); + } + function literalEscape(s) { + return s + .replace(/\\/g, "\\\\") + .replace(/"/g, "\\\"") + .replace(/\0/g, "\\0") + .replace(/\t/g, "\\t") + .replace(/\n/g, "\\n") + .replace(/\r/g, "\\r") + .replace(/[\x00-\x0F]/g, function (ch) { return "\\x0" + hex(ch); }) + .replace(/[\x10-\x1F\x7F-\x9F]/g, function (ch) { return "\\x" + hex(ch); }); + } + function classEscape(s) { + return s + .replace(/\\/g, "\\\\") + .replace(/\]/g, "\\]") + .replace(/\^/g, "\\^") + .replace(/-/g, "\\-") + .replace(/\0/g, "\\0") + .replace(/\t/g, "\\t") + .replace(/\n/g, "\\n") + .replace(/\r/g, "\\r") + .replace(/[\x00-\x0F]/g, function (ch) { return "\\x0" + hex(ch); }) + .replace(/[\x10-\x1F\x7F-\x9F]/g, function (ch) { return "\\x" + hex(ch); }); + } + function describeExpectation(expectation) { + switch (expectation.type) { + case "literal": + return "\"" + literalEscape(expectation.text) + "\""; + case "class": + var escapedParts = expectation.parts.map(function (part) { + return Array.isArray(part) + ? classEscape(part[0]) + "-" + classEscape(part[1]) + : classEscape(part); + }); + return "[" + (expectation.inverted ? "^" : "") + escapedParts + "]"; + case "any": + return "any character"; + case "end": + return "end of input"; + case "other": + return expectation.description; + } + } + function describeExpected(expected1) { + var descriptions = expected1.map(describeExpectation); + var i; + var j; + descriptions.sort(); + if (descriptions.length > 0) { + for (i = 1, j = 1; i < descriptions.length; i++) { + if (descriptions[i - 1] !== descriptions[i]) { + descriptions[j] = descriptions[i]; + j++; + } + } + descriptions.length = j; + } + switch (descriptions.length) { + case 1: + return descriptions[0]; + case 2: + return descriptions[0] + " or " + descriptions[1]; + default: + return descriptions.slice(0, -1).join(", ") + + ", or " + + descriptions[descriptions.length - 1]; + } + } + function describeFound(found1) { + return found1 ? "\"" + literalEscape(found1) + "\"" : "end of input"; + } + return "Expected " + describeExpected(expected) + " but " + describeFound(found) + " found."; + }; + return SyntaxError; +}(Error)); +exports.SyntaxError = SyntaxError; +function peg$parse(input, options) { + options = options !== undefined ? options : {}; + var peg$FAILED = {}; + var peg$startRuleFunctions = { Contact: peg$parseContact, Name_Addr_Header: peg$parseName_Addr_Header, Record_Route: peg$parseRecord_Route, Request_Response: peg$parseRequest_Response, SIP_URI: peg$parseSIP_URI, Subscription_State: peg$parseSubscription_State, Supported: peg$parseSupported, Require: peg$parseRequire, Via: peg$parseVia, absoluteURI: peg$parseabsoluteURI, Call_ID: peg$parseCall_ID, Content_Disposition: peg$parseContent_Disposition, Content_Length: peg$parseContent_Length, Content_Type: peg$parseContent_Type, CSeq: peg$parseCSeq, displayName: peg$parsedisplayName, Event: peg$parseEvent, From: peg$parseFrom, host: peg$parsehost, Max_Forwards: peg$parseMax_Forwards, Min_SE: peg$parseMin_SE, Proxy_Authenticate: peg$parseProxy_Authenticate, quoted_string: peg$parsequoted_string, Refer_To: peg$parseRefer_To, Replaces: peg$parseReplaces, Session_Expires: peg$parseSession_Expires, stun_URI: peg$parsestun_URI, To: peg$parseTo, turn_URI: peg$parseturn_URI, uuid: peg$parseuuid, WWW_Authenticate: peg$parseWWW_Authenticate, challenge: peg$parsechallenge, sipfrag: peg$parsesipfrag, Referred_By: peg$parseReferred_By }; + var peg$startRuleFunction = peg$parseContact; + var peg$c0 = "\r\n"; + var peg$c1 = peg$literalExpectation("\r\n", false); + var peg$c2 = /^[0-9]/; + var peg$c3 = peg$classExpectation([["0", "9"]], false, false); + var peg$c4 = /^[a-zA-Z]/; + var peg$c5 = peg$classExpectation([["a", "z"], ["A", "Z"]], false, false); + var peg$c6 = /^[0-9a-fA-F]/; + var peg$c7 = peg$classExpectation([["0", "9"], ["a", "f"], ["A", "F"]], false, false); + var peg$c8 = /^[\0-\xFF]/; + var peg$c9 = peg$classExpectation([["\0", "\xFF"]], false, false); + var peg$c10 = /^["]/; + var peg$c11 = peg$classExpectation(["\""], false, false); + var peg$c12 = " "; + var peg$c13 = peg$literalExpectation(" ", false); + var peg$c14 = "\t"; + var peg$c15 = peg$literalExpectation("\t", false); + var peg$c16 = /^[a-zA-Z0-9]/; + var peg$c17 = peg$classExpectation([["a", "z"], ["A", "Z"], ["0", "9"]], false, false); + var peg$c18 = ";"; + var peg$c19 = peg$literalExpectation(";", false); + var peg$c20 = "/"; + var peg$c21 = peg$literalExpectation("/", false); + var peg$c22 = "?"; + var peg$c23 = peg$literalExpectation("?", false); + var peg$c24 = ":"; + var peg$c25 = peg$literalExpectation(":", false); + var peg$c26 = "@"; + var peg$c27 = peg$literalExpectation("@", false); + var peg$c28 = "&"; + var peg$c29 = peg$literalExpectation("&", false); + var peg$c30 = "="; + var peg$c31 = peg$literalExpectation("=", false); + var peg$c32 = "+"; + var peg$c33 = peg$literalExpectation("+", false); + var peg$c34 = "$"; + var peg$c35 = peg$literalExpectation("$", false); + var peg$c36 = ","; + var peg$c37 = peg$literalExpectation(",", false); + var peg$c38 = "-"; + var peg$c39 = peg$literalExpectation("-", false); + var peg$c40 = "_"; + var peg$c41 = peg$literalExpectation("_", false); + var peg$c42 = "."; + var peg$c43 = peg$literalExpectation(".", false); + var peg$c44 = "!"; + var peg$c45 = peg$literalExpectation("!", false); + var peg$c46 = "~"; + var peg$c47 = peg$literalExpectation("~", false); + var peg$c48 = "*"; + var peg$c49 = peg$literalExpectation("*", false); + var peg$c50 = "'"; + var peg$c51 = peg$literalExpectation("'", false); + var peg$c52 = "("; + var peg$c53 = peg$literalExpectation("(", false); + var peg$c54 = ")"; + var peg$c55 = peg$literalExpectation(")", false); + var peg$c56 = "%"; + var peg$c57 = peg$literalExpectation("%", false); + var peg$c58 = function () { return " "; }; + var peg$c59 = function () { return ':'; }; + var peg$c60 = /^[!-~]/; + var peg$c61 = peg$classExpectation([["!", "~"]], false, false); + var peg$c62 = /^[\x80-\uFFFF]/; + var peg$c63 = peg$classExpectation([["\x80", "\uFFFF"]], false, false); + var peg$c64 = /^[\x80-\xBF]/; + var peg$c65 = peg$classExpectation([["\x80", "\xBF"]], false, false); + var peg$c66 = /^[a-f]/; + var peg$c67 = peg$classExpectation([["a", "f"]], false, false); + var peg$c68 = "`"; + var peg$c69 = peg$literalExpectation("`", false); + var peg$c70 = "<"; + var peg$c71 = peg$literalExpectation("<", false); + var peg$c72 = ">"; + var peg$c73 = peg$literalExpectation(">", false); + var peg$c74 = "\\"; + var peg$c75 = peg$literalExpectation("\\", false); + var peg$c76 = "["; + var peg$c77 = peg$literalExpectation("[", false); + var peg$c78 = "]"; + var peg$c79 = peg$literalExpectation("]", false); + var peg$c80 = "{"; + var peg$c81 = peg$literalExpectation("{", false); + var peg$c82 = "}"; + var peg$c83 = peg$literalExpectation("}", false); + var peg$c84 = function () { return "*"; }; + var peg$c85 = function () { return "/"; }; + var peg$c86 = function () { return "="; }; + var peg$c87 = function () { return "("; }; + var peg$c88 = function () { return ")"; }; + var peg$c89 = function () { return ">"; }; + var peg$c90 = function () { return "<"; }; + var peg$c91 = function () { return ","; }; + var peg$c92 = function () { return ";"; }; + var peg$c93 = function () { return ":"; }; + var peg$c94 = function () { return "\""; }; + var peg$c95 = /^[!-']/; + var peg$c96 = peg$classExpectation([["!", "'"]], false, false); + var peg$c97 = /^[*-[]/; + var peg$c98 = peg$classExpectation([["*", "["]], false, false); + var peg$c99 = /^[\]-~]/; + var peg$c100 = peg$classExpectation([["]", "~"]], false, false); + var peg$c101 = function (contents) { + return contents; + }; + var peg$c102 = /^[#-[]/; + var peg$c103 = peg$classExpectation([["#", "["]], false, false); + var peg$c104 = /^[\0-\t]/; + var peg$c105 = peg$classExpectation([["\0", "\t"]], false, false); + var peg$c106 = /^[\x0B-\f]/; + var peg$c107 = peg$classExpectation([["\x0B", "\f"]], false, false); + var peg$c108 = /^[\x0E-\x7F]/; + var peg$c109 = peg$classExpectation([["\x0E", "\x7F"]], false, false); + var peg$c110 = function () { + options = options || { data: {} }; + options.data.uri = new URI_1.URI(options.data.scheme, options.data.user, options.data.host, options.data.port); + delete options.data.scheme; + delete options.data.user; + delete options.data.host; + delete options.data.host_type; + delete options.data.port; + }; + var peg$c111 = function () { + options = options || { data: {} }; + options.data.uri = new URI_1.URI(options.data.scheme, options.data.user, options.data.host, options.data.port, options.data.uri_params, options.data.uri_headers); + delete options.data.scheme; + delete options.data.user; + delete options.data.host; + delete options.data.host_type; + delete options.data.port; + delete options.data.uri_params; + if (options.startRule === 'SIP_URI') { + options.data = options.data.uri; + } + }; + var peg$c112 = "sips"; + var peg$c113 = peg$literalExpectation("sips", true); + var peg$c114 = "sip"; + var peg$c115 = peg$literalExpectation("sip", true); + var peg$c116 = function (uri_scheme) { + options = options || { data: {} }; + options.data.scheme = uri_scheme; + }; + var peg$c117 = function () { + options = options || { data: {} }; + options.data.user = decodeURIComponent(text().slice(0, -1)); + }; + var peg$c118 = function () { + options = options || { data: {} }; + options.data.password = text(); + }; + var peg$c119 = function () { + options = options || { data: {} }; + options.data.host = text(); + return options.data.host; + }; + var peg$c120 = function () { + options = options || { data: {} }; + options.data.host_type = 'domain'; + return text(); + }; + var peg$c121 = /^[a-zA-Z0-9_\-]/; + var peg$c122 = peg$classExpectation([["a", "z"], ["A", "Z"], ["0", "9"], "_", "-"], false, false); + var peg$c123 = /^[a-zA-Z0-9\-]/; + var peg$c124 = peg$classExpectation([["a", "z"], ["A", "Z"], ["0", "9"], "-"], false, false); + var peg$c125 = function () { + options = options || { data: {} }; + options.data.host_type = 'IPv6'; + return text(); + }; + var peg$c126 = "::"; + var peg$c127 = peg$literalExpectation("::", false); + var peg$c128 = function () { + options = options || { data: {} }; + options.data.host_type = 'IPv6'; + return text(); + }; + var peg$c129 = function () { + options = options || { data: {} }; + options.data.host_type = 'IPv4'; + return text(); + }; + var peg$c130 = "25"; + var peg$c131 = peg$literalExpectation("25", false); + var peg$c132 = /^[0-5]/; + var peg$c133 = peg$classExpectation([["0", "5"]], false, false); + var peg$c134 = "2"; + var peg$c135 = peg$literalExpectation("2", false); + var peg$c136 = /^[0-4]/; + var peg$c137 = peg$classExpectation([["0", "4"]], false, false); + var peg$c138 = "1"; + var peg$c139 = peg$literalExpectation("1", false); + var peg$c140 = /^[1-9]/; + var peg$c141 = peg$classExpectation([["1", "9"]], false, false); + var peg$c142 = function (port) { + options = options || { data: {} }; + port = parseInt(port.join('')); + options.data.port = port; + return port; + }; + var peg$c143 = "transport="; + var peg$c144 = peg$literalExpectation("transport=", true); + var peg$c145 = "udp"; + var peg$c146 = peg$literalExpectation("udp", true); + var peg$c147 = "tcp"; + var peg$c148 = peg$literalExpectation("tcp", true); + var peg$c149 = "sctp"; + var peg$c150 = peg$literalExpectation("sctp", true); + var peg$c151 = "tls"; + var peg$c152 = peg$literalExpectation("tls", true); + var peg$c153 = function (transport) { + options = options || { data: {} }; + if (!options.data.uri_params) + options.data.uri_params = {}; + options.data.uri_params['transport'] = transport.toLowerCase(); + }; + var peg$c154 = "user="; + var peg$c155 = peg$literalExpectation("user=", true); + var peg$c156 = "phone"; + var peg$c157 = peg$literalExpectation("phone", true); + var peg$c158 = "ip"; + var peg$c159 = peg$literalExpectation("ip", true); + var peg$c160 = function (user) { + options = options || { data: {} }; + if (!options.data.uri_params) + options.data.uri_params = {}; + options.data.uri_params['user'] = user.toLowerCase(); + }; + var peg$c161 = "method="; + var peg$c162 = peg$literalExpectation("method=", true); + var peg$c163 = function (method) { + options = options || { data: {} }; + if (!options.data.uri_params) + options.data.uri_params = {}; + options.data.uri_params['method'] = method; + }; + var peg$c164 = "ttl="; + var peg$c165 = peg$literalExpectation("ttl=", true); + var peg$c166 = function (ttl) { + options = options || { data: {} }; + if (!options.data.params) + options.data.params = {}; + options.data.params['ttl'] = ttl; + }; + var peg$c167 = "maddr="; + var peg$c168 = peg$literalExpectation("maddr=", true); + var peg$c169 = function (maddr) { + options = options || { data: {} }; + if (!options.data.uri_params) + options.data.uri_params = {}; + options.data.uri_params['maddr'] = maddr; + }; + var peg$c170 = "lr"; + var peg$c171 = peg$literalExpectation("lr", true); + var peg$c172 = function () { + options = options || { data: {} }; + if (!options.data.uri_params) + options.data.uri_params = {}; + options.data.uri_params['lr'] = undefined; + }; + var peg$c173 = function (param, value) { + options = options || { data: {} }; + if (!options.data.uri_params) + options.data.uri_params = {}; + if (value === null) { + value = undefined; + } + else { + value = value[1]; + } + options.data.uri_params[param.toLowerCase()] = value; + }; + var peg$c174 = function (hname, hvalue) { + hname = hname.join('').toLowerCase(); + hvalue = hvalue.join(''); + options = options || { data: {} }; + if (!options.data.uri_headers) + options.data.uri_headers = {}; + if (!options.data.uri_headers[hname]) { + options.data.uri_headers[hname] = [hvalue]; + } + else { + options.data.uri_headers[hname].push(hvalue); + } + }; + var peg$c175 = function () { + options = options || { data: {} }; + // lots of tests fail if this isn't guarded... + if (options.startRule === 'Refer_To') { + options.data.uri = new URI_1.URI(options.data.scheme, options.data.user, options.data.host, options.data.port, options.data.uri_params, options.data.uri_headers); + delete options.data.scheme; + delete options.data.user; + delete options.data.host; + delete options.data.host_type; + delete options.data.port; + delete options.data.uri_params; + } + }; + var peg$c176 = "//"; + var peg$c177 = peg$literalExpectation("//", false); + var peg$c178 = function () { + options = options || { data: {} }; + options.data.scheme = text(); + }; + var peg$c179 = peg$literalExpectation("SIP", true); + var peg$c180 = function () { + options = options || { data: {} }; + options.data.sip_version = text(); + }; + var peg$c181 = "INVITE"; + var peg$c182 = peg$literalExpectation("INVITE", false); + var peg$c183 = "ACK"; + var peg$c184 = peg$literalExpectation("ACK", false); + var peg$c185 = "VXACH"; + var peg$c186 = peg$literalExpectation("VXACH", false); + var peg$c187 = "OPTIONS"; + var peg$c188 = peg$literalExpectation("OPTIONS", false); + var peg$c189 = "BYE"; + var peg$c190 = peg$literalExpectation("BYE", false); + var peg$c191 = "CANCEL"; + var peg$c192 = peg$literalExpectation("CANCEL", false); + var peg$c193 = "REGISTER"; + var peg$c194 = peg$literalExpectation("REGISTER", false); + var peg$c195 = "SUBSCRIBE"; + var peg$c196 = peg$literalExpectation("SUBSCRIBE", false); + var peg$c197 = "NOTIFY"; + var peg$c198 = peg$literalExpectation("NOTIFY", false); + var peg$c199 = "REFER"; + var peg$c200 = peg$literalExpectation("REFER", false); + var peg$c201 = "PUBLISH"; + var peg$c202 = peg$literalExpectation("PUBLISH", false); + var peg$c203 = function () { + options = options || { data: {} }; + options.data.method = text(); + return options.data.method; + }; + var peg$c204 = function (status_code) { + options = options || { data: {} }; + options.data.status_code = parseInt(status_code.join('')); + }; + var peg$c205 = function () { + options = options || { data: {} }; + options.data.reason_phrase = text(); + }; + var peg$c206 = function () { + options = options || { data: {} }; + options.data = text(); + }; + var peg$c207 = function () { + var idx, length; + options = options || { data: {} }; + length = options.data.multi_header.length; + for (idx = 0; idx < length; idx++) { + if (options.data.multi_header[idx].parsed === null) { + options.data = null; + break; + } + } + if (options.data !== null) { + options.data = options.data.multi_header; + } + else { + options.data = -1; + } + }; + var peg$c208 = function () { + var header; + options = options || { data: {} }; + if (!options.data.multi_header) + options.data.multi_header = []; + try { + header = new NameAddrHeader_1.NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); + delete options.data.uri; + delete options.data.displayName; + delete options.data.params; + } + catch (e) { + header = null; + } + options.data.multi_header.push({ 'position': peg$currPos, + 'offset': location().start.offset, + 'parsed': header + }); + }; + var peg$c209 = function (displayName) { + displayName = text().trim(); + if (displayName[0] === '\"') { + displayName = displayName.substring(1, displayName.length - 1); + } + options = options || { data: {} }; + options.data.displayName = displayName; + }; + var peg$c210 = "q"; + var peg$c211 = peg$literalExpectation("q", true); + var peg$c212 = function (q) { + options = options || { data: {} }; + if (!options.data.params) + options.data.params = {}; + options.data.params['q'] = q; + }; + var peg$c213 = "expires"; + var peg$c214 = peg$literalExpectation("expires", true); + var peg$c215 = function (expires) { + options = options || { data: {} }; + if (!options.data.params) + options.data.params = {}; + options.data.params['expires'] = expires; + }; + var peg$c216 = function (delta_seconds) { + return parseInt(delta_seconds.join('')); + }; + var peg$c217 = "0"; + var peg$c218 = peg$literalExpectation("0", false); + var peg$c219 = function () { + return parseFloat(text()); + }; + var peg$c220 = function (param, value) { + options = options || { data: {} }; + if (!options.data.params) + options.data.params = {}; + if (value === null) { + value = undefined; + } + else { + value = value[1]; + } + options.data.params[param.toLowerCase()] = value; + }; + var peg$c221 = "render"; + var peg$c222 = peg$literalExpectation("render", true); + var peg$c223 = "session"; + var peg$c224 = peg$literalExpectation("session", true); + var peg$c225 = "icon"; + var peg$c226 = peg$literalExpectation("icon", true); + var peg$c227 = "alert"; + var peg$c228 = peg$literalExpectation("alert", true); + var peg$c229 = function () { + options = options || { data: {} }; + if (options.startRule === 'Content_Disposition') { + options.data.type = text().toLowerCase(); + } + }; + var peg$c230 = "handling"; + var peg$c231 = peg$literalExpectation("handling", true); + var peg$c232 = "optional"; + var peg$c233 = peg$literalExpectation("optional", true); + var peg$c234 = "required"; + var peg$c235 = peg$literalExpectation("required", true); + var peg$c236 = function (length) { + options = options || { data: {} }; + options.data = parseInt(length.join('')); + }; + var peg$c237 = function () { + options = options || { data: {} }; + options.data = text(); + }; + var peg$c238 = "text"; + var peg$c239 = peg$literalExpectation("text", true); + var peg$c240 = "image"; + var peg$c241 = peg$literalExpectation("image", true); + var peg$c242 = "audio"; + var peg$c243 = peg$literalExpectation("audio", true); + var peg$c244 = "video"; + var peg$c245 = peg$literalExpectation("video", true); + var peg$c246 = "application"; + var peg$c247 = peg$literalExpectation("application", true); + var peg$c248 = "message"; + var peg$c249 = peg$literalExpectation("message", true); + var peg$c250 = "multipart"; + var peg$c251 = peg$literalExpectation("multipart", true); + var peg$c252 = "x-"; + var peg$c253 = peg$literalExpectation("x-", true); + var peg$c254 = function (cseq_value) { + options = options || { data: {} }; + options.data.value = parseInt(cseq_value.join('')); + }; + var peg$c255 = function (expires) { options = options || { data: {} }; options.data = expires; }; + var peg$c256 = function (event_type) { + options = options || { data: {} }; + options.data.event = event_type.toLowerCase(); + }; + var peg$c257 = function () { + options = options || { data: {} }; + var tag = options.data.tag; + options.data = new NameAddrHeader_1.NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); + if (tag) { + options.data.setParam('tag', tag); + } + }; + var peg$c258 = "tag"; + var peg$c259 = peg$literalExpectation("tag", true); + var peg$c260 = function (tag) { options = options || { data: {} }; options.data.tag = tag; }; + var peg$c261 = function (forwards) { + options = options || { data: {} }; + options.data = parseInt(forwards.join('')); + }; + var peg$c262 = function (min_expires) { options = options || { data: {} }; options.data = min_expires; }; + var peg$c263 = function () { + options = options || { data: {} }; + options.data = new NameAddrHeader_1.NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); + }; + var peg$c264 = "digest"; + var peg$c265 = peg$literalExpectation("Digest", true); + var peg$c266 = "realm"; + var peg$c267 = peg$literalExpectation("realm", true); + var peg$c268 = function (realm) { options = options || { data: {} }; options.data.realm = realm; }; + var peg$c269 = "domain"; + var peg$c270 = peg$literalExpectation("domain", true); + var peg$c271 = "nonce"; + var peg$c272 = peg$literalExpectation("nonce", true); + var peg$c273 = function (nonce) { options = options || { data: {} }; options.data.nonce = nonce; }; + var peg$c274 = "opaque"; + var peg$c275 = peg$literalExpectation("opaque", true); + var peg$c276 = function (opaque) { options = options || { data: {} }; options.data.opaque = opaque; }; + var peg$c277 = "stale"; + var peg$c278 = peg$literalExpectation("stale", true); + var peg$c279 = "true"; + var peg$c280 = peg$literalExpectation("true", true); + var peg$c281 = function () { options = options || { data: {} }; options.data.stale = true; }; + var peg$c282 = "false"; + var peg$c283 = peg$literalExpectation("false", true); + var peg$c284 = function () { options = options || { data: {} }; options.data.stale = false; }; + var peg$c285 = "algorithm"; + var peg$c286 = peg$literalExpectation("algorithm", true); + var peg$c287 = "md5"; + var peg$c288 = peg$literalExpectation("MD5", true); + var peg$c289 = "md5-sess"; + var peg$c290 = peg$literalExpectation("MD5-sess", true); + var peg$c291 = function (algorithm) { + options = options || { data: {} }; + options.data.algorithm = algorithm.toUpperCase(); + }; + var peg$c292 = "qop"; + var peg$c293 = peg$literalExpectation("qop", true); + var peg$c294 = "auth-int"; + var peg$c295 = peg$literalExpectation("auth-int", true); + var peg$c296 = "auth"; + var peg$c297 = peg$literalExpectation("auth", true); + var peg$c298 = function (qop_value) { + options = options || { data: {} }; + options.data.qop || (options.data.qop = []); + options.data.qop.push(qop_value.toLowerCase()); + }; + var peg$c299 = function (rack_value) { + options = options || { data: {} }; + options.data.value = parseInt(rack_value.join('')); + }; + var peg$c300 = function () { + var idx, length; + options = options || { data: {} }; + length = options.data.multi_header.length; + for (idx = 0; idx < length; idx++) { + if (options.data.multi_header[idx].parsed === null) { + options.data = null; + break; + } + } + if (options.data !== null) { + options.data = options.data.multi_header; + } + else { + options.data = -1; + } + }; + var peg$c301 = function () { + var header; + options = options || { data: {} }; + if (!options.data.multi_header) + options.data.multi_header = []; + try { + header = new NameAddrHeader_1.NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); + delete options.data.uri; + delete options.data.displayName; + delete options.data.params; + } + catch (e) { + header = null; + } + options.data.multi_header.push({ 'position': peg$currPos, + 'offset': location().start.offset, + 'parsed': header + }); + }; + var peg$c302 = function () { + options = options || { data: {} }; + options.data = new NameAddrHeader_1.NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); + }; + var peg$c303 = function () { + options = options || { data: {} }; + if (!(options.data.replaces_from_tag && options.data.replaces_to_tag)) { + options.data = -1; + } + }; + var peg$c304 = function () { + options = options || { data: {} }; + options.data = { + call_id: options.data + }; + }; + var peg$c305 = "from-tag"; + var peg$c306 = peg$literalExpectation("from-tag", true); + var peg$c307 = function (from_tag) { + options = options || { data: {} }; + options.data.replaces_from_tag = from_tag; + }; + var peg$c308 = "to-tag"; + var peg$c309 = peg$literalExpectation("to-tag", true); + var peg$c310 = function (to_tag) { + options = options || { data: {} }; + options.data.replaces_to_tag = to_tag; + }; + var peg$c311 = "early-only"; + var peg$c312 = peg$literalExpectation("early-only", true); + var peg$c313 = function () { + options = options || { data: {} }; + options.data.early_only = true; + }; + var peg$c314 = function (head, r) { return r; }; + var peg$c315 = function (head, tail) { return list(head, tail); }; + var peg$c316 = function (value) { + options = options || { data: {} }; + if (options.startRule === 'Require') { + options.data = value || []; + } + }; + var peg$c317 = function (rseq_value) { + options = options || { data: {} }; + options.data.value = parseInt(rseq_value.join('')); + }; + var peg$c318 = "active"; + var peg$c319 = peg$literalExpectation("active", true); + var peg$c320 = "pending"; + var peg$c321 = peg$literalExpectation("pending", true); + var peg$c322 = "terminated"; + var peg$c323 = peg$literalExpectation("terminated", true); + var peg$c324 = function () { + options = options || { data: {} }; + options.data.state = text(); + }; + var peg$c325 = "reason"; + var peg$c326 = peg$literalExpectation("reason", true); + var peg$c327 = function (reason) { + options = options || { data: {} }; + if (typeof reason !== 'undefined') + options.data.reason = reason; + }; + var peg$c328 = function (expires) { + options = options || { data: {} }; + if (typeof expires !== 'undefined') + options.data.expires = expires; + }; + var peg$c329 = "retry_after"; + var peg$c330 = peg$literalExpectation("retry_after", true); + var peg$c331 = function (retry_after) { + options = options || { data: {} }; + if (typeof retry_after !== 'undefined') + options.data.retry_after = retry_after; + }; + var peg$c332 = "deactivated"; + var peg$c333 = peg$literalExpectation("deactivated", true); + var peg$c334 = "probation"; + var peg$c335 = peg$literalExpectation("probation", true); + var peg$c336 = "rejected"; + var peg$c337 = peg$literalExpectation("rejected", true); + var peg$c338 = "timeout"; + var peg$c339 = peg$literalExpectation("timeout", true); + var peg$c340 = "giveup"; + var peg$c341 = peg$literalExpectation("giveup", true); + var peg$c342 = "noresource"; + var peg$c343 = peg$literalExpectation("noresource", true); + var peg$c344 = "invariant"; + var peg$c345 = peg$literalExpectation("invariant", true); + var peg$c346 = function (value) { + options = options || { data: {} }; + if (options.startRule === 'Supported') { + options.data = value || []; + } + }; + var peg$c347 = function () { + options = options || { data: {} }; + var tag = options.data.tag; + options.data = new NameAddrHeader_1.NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); + if (tag) { + options.data.setParam('tag', tag); + } + }; + var peg$c348 = "ttl"; + var peg$c349 = peg$literalExpectation("ttl", true); + var peg$c350 = function (via_ttl_value) { + options = options || { data: {} }; + options.data.ttl = via_ttl_value; + }; + var peg$c351 = "maddr"; + var peg$c352 = peg$literalExpectation("maddr", true); + var peg$c353 = function (via_maddr) { + options = options || { data: {} }; + options.data.maddr = via_maddr; + }; + var peg$c354 = "received"; + var peg$c355 = peg$literalExpectation("received", true); + var peg$c356 = function (via_received) { + options = options || { data: {} }; + options.data.received = via_received; + }; + var peg$c357 = "branch"; + var peg$c358 = peg$literalExpectation("branch", true); + var peg$c359 = function (via_branch) { + options = options || { data: {} }; + options.data.branch = via_branch; + }; + var peg$c360 = "rport"; + var peg$c361 = peg$literalExpectation("rport", true); + var peg$c362 = function (response_port) { + options = options || { data: {} }; + if (typeof response_port !== 'undefined') + options.data.rport = response_port.join(''); + }; + var peg$c363 = function (via_protocol) { + options = options || { data: {} }; + options.data.protocol = via_protocol; + }; + var peg$c364 = peg$literalExpectation("UDP", true); + var peg$c365 = peg$literalExpectation("TCP", true); + var peg$c366 = peg$literalExpectation("TLS", true); + var peg$c367 = peg$literalExpectation("SCTP", true); + var peg$c368 = function (via_transport) { + options = options || { data: {} }; + options.data.transport = via_transport; + }; + var peg$c369 = function () { + options = options || { data: {} }; + options.data.host = text(); + }; + var peg$c370 = function (via_sent_by_port) { + options = options || { data: {} }; + options.data.port = parseInt(via_sent_by_port.join('')); + }; + var peg$c371 = function (ttl) { + return parseInt(ttl.join('')); + }; + var peg$c372 = function (deltaSeconds) { + options = options || { data: {} }; + if (options.startRule === 'Session_Expires') { + options.data.deltaSeconds = deltaSeconds; + } + }; + var peg$c373 = "refresher"; + var peg$c374 = peg$literalExpectation("refresher", false); + var peg$c375 = "uas"; + var peg$c376 = peg$literalExpectation("uas", false); + var peg$c377 = "uac"; + var peg$c378 = peg$literalExpectation("uac", false); + var peg$c379 = function (endpoint) { + options = options || { data: {} }; + if (options.startRule === 'Session_Expires') { + options.data.refresher = endpoint; + } + }; + var peg$c380 = function (deltaSeconds) { + options = options || { data: {} }; + if (options.startRule === 'Min_SE') { + options.data = deltaSeconds; + } + }; + var peg$c381 = "stuns"; + var peg$c382 = peg$literalExpectation("stuns", true); + var peg$c383 = "stun"; + var peg$c384 = peg$literalExpectation("stun", true); + var peg$c385 = function (scheme) { + options = options || { data: {} }; + options.data.scheme = scheme; + }; + var peg$c386 = function (host) { + options = options || { data: {} }; + options.data.host = host; + }; + var peg$c387 = "?transport="; + var peg$c388 = peg$literalExpectation("?transport=", false); + var peg$c389 = "turns"; + var peg$c390 = peg$literalExpectation("turns", true); + var peg$c391 = "turn"; + var peg$c392 = peg$literalExpectation("turn", true); + var peg$c393 = function (transport) { + options = options || { data: {} }; + options.data.transport = transport; + }; + var peg$c394 = function () { + options = options || { data: {} }; + options.data = text(); + }; + var peg$c395 = "Referred-By"; + var peg$c396 = peg$literalExpectation("Referred-By", false); + var peg$c397 = "b"; + var peg$c398 = peg$literalExpectation("b", false); + var peg$c399 = "cid"; + var peg$c400 = peg$literalExpectation("cid", false); + var peg$currPos = 0; + var peg$savedPos = 0; + var peg$posDetailsCache = [{ line: 1, column: 1 }]; + var peg$maxFailPos = 0; + var peg$maxFailExpected = []; + var peg$silentFails = 0; + var peg$result; + if (options.startRule !== undefined) { + if (!(options.startRule in peg$startRuleFunctions)) { + throw new Error("Can't start parsing from rule \"" + options.startRule + "\"."); + } + peg$startRuleFunction = peg$startRuleFunctions[options.startRule]; + } + function text() { + return input.substring(peg$savedPos, peg$currPos); + } + function location() { + return peg$computeLocation(peg$savedPos, peg$currPos); + } + function expected(description, location1) { + location1 = location1 !== undefined + ? location1 + : peg$computeLocation(peg$savedPos, peg$currPos); + throw peg$buildStructuredError([peg$otherExpectation(description)], input.substring(peg$savedPos, peg$currPos), location1); + } + function error(message, location1) { + location1 = location1 !== undefined + ? location1 + : peg$computeLocation(peg$savedPos, peg$currPos); + throw peg$buildSimpleError(message, location1); + } + function peg$literalExpectation(text1, ignoreCase) { + return { type: "literal", text: text1, ignoreCase: ignoreCase }; + } + function peg$classExpectation(parts, inverted, ignoreCase) { + return { type: "class", parts: parts, inverted: inverted, ignoreCase: ignoreCase }; + } + function peg$anyExpectation() { + return { type: "any" }; + } + function peg$endExpectation() { + return { type: "end" }; + } + function peg$otherExpectation(description) { + return { type: "other", description: description }; + } + function peg$computePosDetails(pos) { + var details = peg$posDetailsCache[pos]; + var p; + if (details) { + return details; + } + else { + p = pos - 1; + while (!peg$posDetailsCache[p]) { + p--; + } + details = peg$posDetailsCache[p]; + details = { + line: details.line, + column: details.column + }; + while (p < pos) { + if (input.charCodeAt(p) === 10) { + details.line++; + details.column = 1; + } + else { + details.column++; + } + p++; + } + peg$posDetailsCache[pos] = details; + return details; + } + } + function peg$computeLocation(startPos, endPos) { + var startPosDetails = peg$computePosDetails(startPos); + var endPosDetails = peg$computePosDetails(endPos); + return { + start: { + offset: startPos, + line: startPosDetails.line, + column: startPosDetails.column + }, + end: { + offset: endPos, + line: endPosDetails.line, + column: endPosDetails.column + } + }; + } + function peg$fail(expected1) { + if (peg$currPos < peg$maxFailPos) { + return; + } + if (peg$currPos > peg$maxFailPos) { + peg$maxFailPos = peg$currPos; + peg$maxFailExpected = []; + } + peg$maxFailExpected.push(expected1); + } + function peg$buildSimpleError(message, location1) { + return new SyntaxError(message, [], "", location1); + } + function peg$buildStructuredError(expected1, found, location1) { + return new SyntaxError(SyntaxError.buildMessage(expected1, found), expected1, found, location1); + } + function peg$parseCRLF() { + var s0; + if (input.substr(peg$currPos, 2) === peg$c0) { + s0 = peg$c0; + peg$currPos += 2; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c1); + } + } + return s0; + } + function peg$parseDIGIT() { + var s0; + if (peg$c2.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c3); + } + } + return s0; + } + function peg$parseALPHA() { + var s0; + if (peg$c4.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c5); + } + } + return s0; + } + function peg$parseHEXDIG() { + var s0; + if (peg$c6.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c7); + } + } + return s0; + } + function peg$parseWSP() { + var s0; + s0 = peg$parseSP(); + if (s0 === peg$FAILED) { + s0 = peg$parseHTAB(); + } + return s0; + } + function peg$parseOCTET() { + var s0; + if (peg$c8.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c9); + } + } + return s0; + } + function peg$parseDQUOTE() { + var s0; + if (peg$c10.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c11); + } + } + return s0; + } + function peg$parseSP() { + var s0; + if (input.charCodeAt(peg$currPos) === 32) { + s0 = peg$c12; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c13); + } + } + return s0; + } + function peg$parseHTAB() { + var s0; + if (input.charCodeAt(peg$currPos) === 9) { + s0 = peg$c14; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c15); + } + } + return s0; + } + function peg$parsealphanum() { + var s0; + if (peg$c16.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c17); + } + } + return s0; + } + function peg$parsereserved() { + var s0; + if (input.charCodeAt(peg$currPos) === 59) { + s0 = peg$c18; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c19); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 47) { + s0 = peg$c20; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c21); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 63) { + s0 = peg$c22; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c23); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s0 = peg$c24; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 64) { + s0 = peg$c26; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c27); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 38) { + s0 = peg$c28; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c29); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s0 = peg$c30; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c31); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s0 = peg$c32; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 36) { + s0 = peg$c34; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c35); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s0 = peg$c36; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c37); + } + } + } + } + } + } + } + } + } + } + } + return s0; + } + function peg$parseunreserved() { + var s0; + s0 = peg$parsealphanum(); + if (s0 === peg$FAILED) { + s0 = peg$parsemark(); + } + return s0; + } + function peg$parsemark() { + var s0; + if (input.charCodeAt(peg$currPos) === 45) { + s0 = peg$c38; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c39); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 95) { + s0 = peg$c40; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c41); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s0 = peg$c42; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c43); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 33) { + s0 = peg$c44; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c45); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 126) { + s0 = peg$c46; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c47); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 42) { + s0 = peg$c48; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c49); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 39) { + s0 = peg$c50; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c51); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 40) { + s0 = peg$c52; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c53); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s0 = peg$c54; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c55); + } + } + } + } + } + } + } + } + } + } + return s0; + } + function peg$parseescaped() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + s1 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 37) { + s2 = peg$c56; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c57); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseHEXDIG(); + if (s3 !== peg$FAILED) { + s4 = peg$parseHEXDIG(); + if (s4 !== peg$FAILED) { + s2 = [s2, s3, s4]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s0 = input.substring(s0, peg$currPos); + } + else { + s0 = s1; + } + return s0; + } + function peg$parseLWS() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$currPos; + s2 = []; + s3 = peg$parseWSP(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseWSP(); + } + if (s2 !== peg$FAILED) { + s3 = peg$parseCRLF(); + if (s3 !== peg$FAILED) { + s2 = [s2, s3]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseWSP(); + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseWSP(); + } + } + else { + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c58(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseSWS() { + var s0; + s0 = peg$parseLWS(); + if (s0 === peg$FAILED) { + s0 = null; + } + return s0; + } + function peg$parseHCOLON() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = []; + s2 = peg$parseSP(); + if (s2 === peg$FAILED) { + s2 = peg$parseHTAB(); + } + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseSP(); + if (s2 === peg$FAILED) { + s2 = peg$parseHTAB(); + } + } + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s2 = peg$c24; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseSWS(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c59(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseTEXT_UTF8_TRIM() { + var s0, s1, s2, s3, s4, s5, s6; + s0 = peg$currPos; + s1 = peg$currPos; + s2 = []; + s3 = peg$parseTEXT_UTF8char(); + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseTEXT_UTF8char(); + } + } + else { + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$currPos; + s5 = []; + s6 = peg$parseLWS(); + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parseLWS(); + } + if (s5 !== peg$FAILED) { + s6 = peg$parseTEXT_UTF8char(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$currPos; + s5 = []; + s6 = peg$parseLWS(); + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parseLWS(); + } + if (s5 !== peg$FAILED) { + s6 = peg$parseTEXT_UTF8char(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + if (s3 !== peg$FAILED) { + s2 = [s2, s3]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s0 = input.substring(s0, peg$currPos); + } + else { + s0 = s1; + } + return s0; + } + function peg$parseTEXT_UTF8char() { + var s0; + if (peg$c60.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c61); + } + } + if (s0 === peg$FAILED) { + s0 = peg$parseUTF8_NONASCII(); + } + return s0; + } + function peg$parseUTF8_NONASCII() { + var s0; + if (peg$c62.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c63); + } + } + return s0; + } + function peg$parseUTF8_CONT() { + var s0; + if (peg$c64.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c65); + } + } + return s0; + } + function peg$parseLHEX() { + var s0; + s0 = peg$parseDIGIT(); + if (s0 === peg$FAILED) { + if (peg$c66.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c67); + } + } + } + return s0; + } + function peg$parsetoken() { + var s0, s1, s2; + s0 = peg$currPos; + s1 = []; + s2 = peg$parsealphanum(); + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s2 = peg$c38; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c39); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s2 = peg$c42; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c43); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 33) { + s2 = peg$c44; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c45); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 37) { + s2 = peg$c56; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c57); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 42) { + s2 = peg$c48; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c49); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 95) { + s2 = peg$c40; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c41); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s2 = peg$c32; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 96) { + s2 = peg$c68; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c69); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 39) { + s2 = peg$c50; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c51); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 126) { + s2 = peg$c46; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c47); + } + } + } + } + } + } + } + } + } + } + } + } + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parsealphanum(); + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s2 = peg$c38; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c39); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s2 = peg$c42; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c43); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 33) { + s2 = peg$c44; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c45); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 37) { + s2 = peg$c56; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c57); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 42) { + s2 = peg$c48; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c49); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 95) { + s2 = peg$c40; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c41); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s2 = peg$c32; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 96) { + s2 = peg$c68; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c69); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 39) { + s2 = peg$c50; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c51); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 126) { + s2 = peg$c46; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c47); + } + } + } + } + } + } + } + } + } + } + } + } + } + } + else { + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s0 = input.substring(s0, peg$currPos); + } + else { + s0 = s1; + } + return s0; + } + function peg$parsetoken_nodot() { + var s0, s1, s2; + s0 = peg$currPos; + s1 = []; + s2 = peg$parsealphanum(); + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s2 = peg$c38; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c39); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 33) { + s2 = peg$c44; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c45); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 37) { + s2 = peg$c56; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c57); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 42) { + s2 = peg$c48; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c49); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 95) { + s2 = peg$c40; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c41); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s2 = peg$c32; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 96) { + s2 = peg$c68; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c69); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 39) { + s2 = peg$c50; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c51); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 126) { + s2 = peg$c46; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c47); + } + } + } + } + } + } + } + } + } + } + } + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parsealphanum(); + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s2 = peg$c38; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c39); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 33) { + s2 = peg$c44; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c45); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 37) { + s2 = peg$c56; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c57); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 42) { + s2 = peg$c48; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c49); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 95) { + s2 = peg$c40; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c41); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s2 = peg$c32; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 96) { + s2 = peg$c68; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c69); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 39) { + s2 = peg$c50; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c51); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 126) { + s2 = peg$c46; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c47); + } + } + } + } + } + } + } + } + } + } + } + } + } + else { + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s0 = input.substring(s0, peg$currPos); + } + else { + s0 = s1; + } + return s0; + } + function peg$parseseparators() { + var s0; + if (input.charCodeAt(peg$currPos) === 40) { + s0 = peg$c52; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c53); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s0 = peg$c54; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c55); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 60) { + s0 = peg$c70; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c71); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 62) { + s0 = peg$c72; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c73); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 64) { + s0 = peg$c26; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c27); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s0 = peg$c36; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c37); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 59) { + s0 = peg$c18; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c19); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s0 = peg$c24; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 92) { + s0 = peg$c74; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c75); + } + } + if (s0 === peg$FAILED) { + s0 = peg$parseDQUOTE(); + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 47) { + s0 = peg$c20; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c21); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 91) { + s0 = peg$c76; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c77); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s0 = peg$c78; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c79); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 63) { + s0 = peg$c22; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c23); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s0 = peg$c30; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c31); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 123) { + s0 = peg$c80; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c81); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 125) { + s0 = peg$c82; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c83); + } + } + if (s0 === peg$FAILED) { + s0 = peg$parseSP(); + if (s0 === peg$FAILED) { + s0 = peg$parseHTAB(); + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + return s0; + } + function peg$parseword() { + var s0, s1, s2; + s0 = peg$currPos; + s1 = []; + s2 = peg$parsealphanum(); + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s2 = peg$c38; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c39); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s2 = peg$c42; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c43); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 33) { + s2 = peg$c44; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c45); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 37) { + s2 = peg$c56; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c57); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 42) { + s2 = peg$c48; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c49); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 95) { + s2 = peg$c40; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c41); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s2 = peg$c32; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 96) { + s2 = peg$c68; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c69); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 39) { + s2 = peg$c50; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c51); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 126) { + s2 = peg$c46; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c47); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 40) { + s2 = peg$c52; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c53); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s2 = peg$c54; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c55); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 60) { + s2 = peg$c70; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c71); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 62) { + s2 = peg$c72; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c73); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s2 = peg$c24; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 92) { + s2 = peg$c74; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c75); + } + } + if (s2 === peg$FAILED) { + s2 = peg$parseDQUOTE(); + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 47) { + s2 = peg$c20; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c21); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 91) { + s2 = peg$c76; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c77); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s2 = peg$c78; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c79); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 63) { + s2 = peg$c22; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c23); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 123) { + s2 = peg$c80; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c81); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 125) { + s2 = peg$c82; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c83); + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parsealphanum(); + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s2 = peg$c38; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c39); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s2 = peg$c42; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c43); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 33) { + s2 = peg$c44; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c45); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 37) { + s2 = peg$c56; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c57); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 42) { + s2 = peg$c48; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c49); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 95) { + s2 = peg$c40; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c41); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s2 = peg$c32; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 96) { + s2 = peg$c68; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c69); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 39) { + s2 = peg$c50; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c51); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 126) { + s2 = peg$c46; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c47); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 40) { + s2 = peg$c52; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c53); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s2 = peg$c54; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c55); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 60) { + s2 = peg$c70; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c71); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 62) { + s2 = peg$c72; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c73); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s2 = peg$c24; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 92) { + s2 = peg$c74; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c75); + } + } + if (s2 === peg$FAILED) { + s2 = peg$parseDQUOTE(); + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 47) { + s2 = peg$c20; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c21); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 91) { + s2 = peg$c76; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c77); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s2 = peg$c78; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c79); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 63) { + s2 = peg$c22; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c23); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 123) { + s2 = peg$c80; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c81); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 125) { + s2 = peg$c82; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c83); + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + else { + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s0 = input.substring(s0, peg$currPos); + } + else { + s0 = s1; + } + return s0; + } + function peg$parseSTAR() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parseSWS(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 42) { + s2 = peg$c48; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c49); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseSWS(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c84(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseSLASH() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parseSWS(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 47) { + s2 = peg$c20; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c21); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseSWS(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c85(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseEQUAL() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parseSWS(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s2 = peg$c30; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c31); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseSWS(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c86(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseLPAREN() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parseSWS(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 40) { + s2 = peg$c52; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c53); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseSWS(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c87(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseRPAREN() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parseSWS(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s2 = peg$c54; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c55); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseSWS(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c88(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseRAQUOT() { + var s0, s1, s2; + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 62) { + s1 = peg$c72; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c73); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseSWS(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c89(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseLAQUOT() { + var s0, s1, s2; + s0 = peg$currPos; + s1 = peg$parseSWS(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 60) { + s2 = peg$c70; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c71); + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c90(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseCOMMA() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parseSWS(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s2 = peg$c36; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c37); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseSWS(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c91(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseSEMI() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parseSWS(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 59) { + s2 = peg$c18; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c19); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseSWS(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c92(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseCOLON() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parseSWS(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s2 = peg$c24; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseSWS(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c93(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseLDQUOT() { + var s0, s1, s2; + s0 = peg$currPos; + s1 = peg$parseSWS(); + if (s1 !== peg$FAILED) { + s2 = peg$parseDQUOTE(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c94(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseRDQUOT() { + var s0, s1, s2; + s0 = peg$currPos; + s1 = peg$parseDQUOTE(); + if (s1 !== peg$FAILED) { + s2 = peg$parseSWS(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c94(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsecomment() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parseLPAREN(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parsectext(); + if (s3 === peg$FAILED) { + s3 = peg$parsequoted_pair(); + if (s3 === peg$FAILED) { + s3 = peg$parsecomment(); + } + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parsectext(); + if (s3 === peg$FAILED) { + s3 = peg$parsequoted_pair(); + if (s3 === peg$FAILED) { + s3 = peg$parsecomment(); + } + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseRPAREN(); + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsectext() { + var s0; + if (peg$c95.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c96); + } + } + if (s0 === peg$FAILED) { + if (peg$c97.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c98); + } + } + if (s0 === peg$FAILED) { + if (peg$c99.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c100); + } + } + if (s0 === peg$FAILED) { + s0 = peg$parseUTF8_NONASCII(); + if (s0 === peg$FAILED) { + s0 = peg$parseLWS(); + } + } + } + } + return s0; + } + function peg$parsequoted_string() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$currPos; + s2 = peg$parseSWS(); + if (s2 !== peg$FAILED) { + s3 = peg$parseDQUOTE(); + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$parseqdtext(); + if (s5 === peg$FAILED) { + s5 = peg$parsequoted_pair(); + } + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$parseqdtext(); + if (s5 === peg$FAILED) { + s5 = peg$parsequoted_pair(); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseDQUOTE(); + if (s5 !== peg$FAILED) { + s2 = [s2, s3, s4, s5]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s0 = input.substring(s0, peg$currPos); + } + else { + s0 = s1; + } + return s0; + } + function peg$parsequoted_string_clean() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parseSWS(); + if (s1 !== peg$FAILED) { + s2 = peg$parseDQUOTE(); + if (s2 !== peg$FAILED) { + s3 = peg$currPos; + s4 = []; + s5 = peg$parseqdtext(); + if (s5 === peg$FAILED) { + s5 = peg$parsequoted_pair(); + } + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$parseqdtext(); + if (s5 === peg$FAILED) { + s5 = peg$parsequoted_pair(); + } + } + if (s4 !== peg$FAILED) { + s3 = input.substring(s3, peg$currPos); + } + else { + s3 = s4; + } + if (s3 !== peg$FAILED) { + s4 = peg$parseDQUOTE(); + if (s4 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c101(s3); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseqdtext() { + var s0; + s0 = peg$parseLWS(); + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 33) { + s0 = peg$c44; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c45); + } + } + if (s0 === peg$FAILED) { + if (peg$c102.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c103); + } + } + if (s0 === peg$FAILED) { + if (peg$c99.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c100); + } + } + if (s0 === peg$FAILED) { + s0 = peg$parseUTF8_NONASCII(); + } + } + } + } + return s0; + } + function peg$parsequoted_pair() { + var s0, s1, s2; + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 92) { + s1 = peg$c74; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c75); + } + } + if (s1 !== peg$FAILED) { + if (peg$c104.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c105); + } + } + if (s2 === peg$FAILED) { + if (peg$c106.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c107); + } + } + if (s2 === peg$FAILED) { + if (peg$c108.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c109); + } + } + } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseSIP_URI_noparams() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + s1 = peg$parseuri_scheme(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s2 = peg$c24; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseuserinfo(); + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + s4 = peg$parsehostport(); + if (s4 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c110(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseSIP_URI() { + var s0, s1, s2, s3, s4, s5, s6; + s0 = peg$currPos; + s1 = peg$parseuri_scheme(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s2 = peg$c24; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseuserinfo(); + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + s4 = peg$parsehostport(); + if (s4 !== peg$FAILED) { + s5 = peg$parseuri_parameters(); + if (s5 !== peg$FAILED) { + s6 = peg$parseheaders(); + if (s6 === peg$FAILED) { + s6 = null; + } + if (s6 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c111(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseuri_scheme() { + var s0, s1; + s0 = peg$currPos; + if (input.substr(peg$currPos, 4).toLowerCase() === peg$c112) { + s1 = input.substr(peg$currPos, 4); + peg$currPos += 4; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c113); + } + } + if (s1 === peg$FAILED) { + if (input.substr(peg$currPos, 3).toLowerCase() === peg$c114) { + s1 = input.substr(peg$currPos, 3); + peg$currPos += 3; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c115); + } + } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c116(s1); + } + s0 = s1; + return s0; + } + function peg$parseuserinfo() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + s1 = peg$parseuser(); + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s3 = peg$c24; + peg$currPos++; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s3 !== peg$FAILED) { + s4 = peg$parsepassword(); + if (s4 !== peg$FAILED) { + s3 = [s3, s4]; + s2 = s3; + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 64) { + s3 = peg$c26; + peg$currPos++; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c27); + } + } + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c117(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseuser() { + var s0, s1; + s0 = []; + s1 = peg$parseunreserved(); + if (s1 === peg$FAILED) { + s1 = peg$parseescaped(); + if (s1 === peg$FAILED) { + s1 = peg$parseuser_unreserved(); + } + } + if (s1 !== peg$FAILED) { + while (s1 !== peg$FAILED) { + s0.push(s1); + s1 = peg$parseunreserved(); + if (s1 === peg$FAILED) { + s1 = peg$parseescaped(); + if (s1 === peg$FAILED) { + s1 = peg$parseuser_unreserved(); + } + } + } + } + else { + s0 = peg$FAILED; + } + return s0; + } + function peg$parseuser_unreserved() { + var s0; + if (input.charCodeAt(peg$currPos) === 38) { + s0 = peg$c28; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c29); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s0 = peg$c30; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c31); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s0 = peg$c32; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 36) { + s0 = peg$c34; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c35); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s0 = peg$c36; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c37); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 59) { + s0 = peg$c18; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c19); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 63) { + s0 = peg$c22; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c23); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 47) { + s0 = peg$c20; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c21); + } + } + } + } + } + } + } + } + } + return s0; + } + function peg$parsepassword() { + var s0, s1, s2; + s0 = peg$currPos; + s1 = []; + s2 = peg$parseunreserved(); + if (s2 === peg$FAILED) { + s2 = peg$parseescaped(); + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 38) { + s2 = peg$c28; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c29); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s2 = peg$c30; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c31); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s2 = peg$c32; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 36) { + s2 = peg$c34; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c35); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s2 = peg$c36; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c37); + } + } + } + } + } + } + } + } + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseunreserved(); + if (s2 === peg$FAILED) { + s2 = peg$parseescaped(); + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 38) { + s2 = peg$c28; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c29); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s2 = peg$c30; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c31); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s2 = peg$c32; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 36) { + s2 = peg$c34; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c35); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s2 = peg$c36; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c37); + } + } + } + } + } + } + } + } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c118(); + } + s0 = s1; + return s0; + } + function peg$parsehostport() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + s1 = peg$parsehost(); + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s3 = peg$c24; + peg$currPos++; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s3 !== peg$FAILED) { + s4 = peg$parseport(); + if (s4 !== peg$FAILED) { + s3 = [s3, s4]; + s2 = s3; + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsehost() { + var s0, s1; + s0 = peg$currPos; + s1 = peg$parsehostname(); + if (s1 === peg$FAILED) { + s1 = peg$parseIPv4address(); + if (s1 === peg$FAILED) { + s1 = peg$parseIPv6reference(); + } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c119(); + } + s0 = s1; + return s0; + } + function peg$parsehostname() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + s1 = []; + s2 = peg$currPos; + s3 = peg$parsedomainlabel(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c42; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c43); + } + } + if (s4 !== peg$FAILED) { + s3 = [s3, s4]; + s2 = s3; + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$currPos; + s3 = peg$parsedomainlabel(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c42; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c43); + } + } + if (s4 !== peg$FAILED) { + s3 = [s3, s4]; + s2 = s3; + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parsetoplabel(); + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s3 = peg$c42; + peg$currPos++; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c43); + } + } + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c120(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsedomainlabel() { + var s0, s1; + s0 = []; + if (peg$c121.test(input.charAt(peg$currPos))) { + s1 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c122); + } + } + if (s1 !== peg$FAILED) { + while (s1 !== peg$FAILED) { + s0.push(s1); + if (peg$c121.test(input.charAt(peg$currPos))) { + s1 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c122); + } + } + } + } + else { + s0 = peg$FAILED; + } + return s0; + } + function peg$parsetoplabel() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (peg$c4.test(input.charAt(peg$currPos))) { + s1 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c5); + } + } + if (s1 !== peg$FAILED) { + s2 = []; + if (peg$c123.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c124); + } + } + while (s3 !== peg$FAILED) { + s2.push(s3); + if (peg$c123.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c124); + } + } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseIPv6reference() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c76; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c77); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseIPv6address(); + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s3 = peg$c78; + peg$currPos++; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c79); + } + } + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c125(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseIPv6address() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14; + s0 = peg$currPos; + s1 = peg$currPos; + s2 = peg$parseh16(); + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s3 = peg$c24; + peg$currPos++; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s3 !== peg$FAILED) { + s4 = peg$parseh16(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s5 = peg$c24; + peg$currPos++; + } + else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parseh16(); + if (s6 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s7 = peg$c24; + peg$currPos++; + } + else { + s7 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s7 !== peg$FAILED) { + s8 = peg$parseh16(); + if (s8 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s9 = peg$c24; + peg$currPos++; + } + else { + s9 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s9 !== peg$FAILED) { + s10 = peg$parseh16(); + if (s10 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s11 = peg$c24; + peg$currPos++; + } + else { + s11 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s11 !== peg$FAILED) { + s12 = peg$parseh16(); + if (s12 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s13 = peg$c24; + peg$currPos++; + } + else { + s13 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s13 !== peg$FAILED) { + s14 = peg$parsels32(); + if (s14 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c126) { + s2 = peg$c126; + peg$currPos += 2; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c127); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseh16(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s4 = peg$c24; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseh16(); + if (s5 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s6 = peg$c24; + peg$currPos++; + } + else { + s6 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s6 !== peg$FAILED) { + s7 = peg$parseh16(); + if (s7 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s8 = peg$c24; + peg$currPos++; + } + else { + s8 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s8 !== peg$FAILED) { + s9 = peg$parseh16(); + if (s9 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s10 = peg$c24; + peg$currPos++; + } + else { + s10 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s10 !== peg$FAILED) { + s11 = peg$parseh16(); + if (s11 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s12 = peg$c24; + peg$currPos++; + } + else { + s12 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s12 !== peg$FAILED) { + s13 = peg$parsels32(); + if (s13 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c126) { + s2 = peg$c126; + peg$currPos += 2; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c127); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseh16(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s4 = peg$c24; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseh16(); + if (s5 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s6 = peg$c24; + peg$currPos++; + } + else { + s6 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s6 !== peg$FAILED) { + s7 = peg$parseh16(); + if (s7 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s8 = peg$c24; + peg$currPos++; + } + else { + s8 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s8 !== peg$FAILED) { + s9 = peg$parseh16(); + if (s9 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s10 = peg$c24; + peg$currPos++; + } + else { + s10 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s10 !== peg$FAILED) { + s11 = peg$parsels32(); + if (s11 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6, s7, s8, s9, s10, s11]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c126) { + s2 = peg$c126; + peg$currPos += 2; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c127); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseh16(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s4 = peg$c24; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseh16(); + if (s5 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s6 = peg$c24; + peg$currPos++; + } + else { + s6 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s6 !== peg$FAILED) { + s7 = peg$parseh16(); + if (s7 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s8 = peg$c24; + peg$currPos++; + } + else { + s8 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s8 !== peg$FAILED) { + s9 = peg$parsels32(); + if (s9 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6, s7, s8, s9]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c126) { + s2 = peg$c126; + peg$currPos += 2; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c127); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseh16(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s4 = peg$c24; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseh16(); + if (s5 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s6 = peg$c24; + peg$currPos++; + } + else { + s6 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s6 !== peg$FAILED) { + s7 = peg$parsels32(); + if (s7 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6, s7]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c126) { + s2 = peg$c126; + peg$currPos += 2; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c127); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseh16(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s4 = peg$c24; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parsels32(); + if (s5 !== peg$FAILED) { + s2 = [s2, s3, s4, s5]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c126) { + s2 = peg$c126; + peg$currPos += 2; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c127); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parsels32(); + if (s3 !== peg$FAILED) { + s2 = [s2, s3]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c126) { + s2 = peg$c126; + peg$currPos += 2; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c127); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseh16(); + if (s3 !== peg$FAILED) { + s2 = [s2, s3]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = peg$currPos; + s2 = peg$parseh16(); + if (s2 !== peg$FAILED) { + if (input.substr(peg$currPos, 2) === peg$c126) { + s3 = peg$c126; + peg$currPos += 2; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c127); + } + } + if (s3 !== peg$FAILED) { + s4 = peg$parseh16(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s5 = peg$c24; + peg$currPos++; + } + else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parseh16(); + if (s6 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s7 = peg$c24; + peg$currPos++; + } + else { + s7 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s7 !== peg$FAILED) { + s8 = peg$parseh16(); + if (s8 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s9 = peg$c24; + peg$currPos++; + } + else { + s9 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s9 !== peg$FAILED) { + s10 = peg$parseh16(); + if (s10 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s11 = peg$c24; + peg$currPos++; + } + else { + s11 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s11 !== peg$FAILED) { + s12 = peg$parsels32(); + if (s12 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = peg$currPos; + s2 = peg$parseh16(); + if (s2 !== peg$FAILED) { + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s4 = peg$c24; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseh16(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + if (input.substr(peg$currPos, 2) === peg$c126) { + s4 = peg$c126; + peg$currPos += 2; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c127); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseh16(); + if (s5 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s6 = peg$c24; + peg$currPos++; + } + else { + s6 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s6 !== peg$FAILED) { + s7 = peg$parseh16(); + if (s7 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s8 = peg$c24; + peg$currPos++; + } + else { + s8 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s8 !== peg$FAILED) { + s9 = peg$parseh16(); + if (s9 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s10 = peg$c24; + peg$currPos++; + } + else { + s10 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s10 !== peg$FAILED) { + s11 = peg$parsels32(); + if (s11 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6, s7, s8, s9, s10, s11]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = peg$currPos; + s2 = peg$parseh16(); + if (s2 !== peg$FAILED) { + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s4 = peg$c24; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseh16(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + s4 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s5 = peg$c24; + peg$currPos++; + } + else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parseh16(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + if (input.substr(peg$currPos, 2) === peg$c126) { + s5 = peg$c126; + peg$currPos += 2; + } + else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c127); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parseh16(); + if (s6 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s7 = peg$c24; + peg$currPos++; + } + else { + s7 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s7 !== peg$FAILED) { + s8 = peg$parseh16(); + if (s8 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s9 = peg$c24; + peg$currPos++; + } + else { + s9 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s9 !== peg$FAILED) { + s10 = peg$parsels32(); + if (s10 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6, s7, s8, s9, s10]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = peg$currPos; + s2 = peg$parseh16(); + if (s2 !== peg$FAILED) { + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s4 = peg$c24; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseh16(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + s4 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s5 = peg$c24; + peg$currPos++; + } + else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parseh16(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s5 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s6 = peg$c24; + peg$currPos++; + } + else { + s6 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s6 !== peg$FAILED) { + s7 = peg$parseh16(); + if (s7 !== peg$FAILED) { + s6 = [s6, s7]; + s5 = s6; + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + if (s5 === peg$FAILED) { + s5 = null; + } + if (s5 !== peg$FAILED) { + if (input.substr(peg$currPos, 2) === peg$c126) { + s6 = peg$c126; + peg$currPos += 2; + } + else { + s6 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c127); + } + } + if (s6 !== peg$FAILED) { + s7 = peg$parseh16(); + if (s7 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s8 = peg$c24; + peg$currPos++; + } + else { + s8 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s8 !== peg$FAILED) { + s9 = peg$parsels32(); + if (s9 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6, s7, s8, s9]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = peg$currPos; + s2 = peg$parseh16(); + if (s2 !== peg$FAILED) { + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s4 = peg$c24; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseh16(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + s4 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s5 = peg$c24; + peg$currPos++; + } + else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parseh16(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s5 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s6 = peg$c24; + peg$currPos++; + } + else { + s6 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s6 !== peg$FAILED) { + s7 = peg$parseh16(); + if (s7 !== peg$FAILED) { + s6 = [s6, s7]; + s5 = s6; + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + if (s5 === peg$FAILED) { + s5 = null; + } + if (s5 !== peg$FAILED) { + s6 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s7 = peg$c24; + peg$currPos++; + } + else { + s7 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s7 !== peg$FAILED) { + s8 = peg$parseh16(); + if (s8 !== peg$FAILED) { + s7 = [s7, s8]; + s6 = s7; + } + else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } + else { + peg$currPos = s6; + s6 = peg$FAILED; + } + if (s6 === peg$FAILED) { + s6 = null; + } + if (s6 !== peg$FAILED) { + if (input.substr(peg$currPos, 2) === peg$c126) { + s7 = peg$c126; + peg$currPos += 2; + } + else { + s7 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c127); + } + } + if (s7 !== peg$FAILED) { + s8 = peg$parsels32(); + if (s8 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6, s7, s8]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = peg$currPos; + s2 = peg$parseh16(); + if (s2 !== peg$FAILED) { + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s4 = peg$c24; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseh16(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + s4 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s5 = peg$c24; + peg$currPos++; + } + else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parseh16(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s5 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s6 = peg$c24; + peg$currPos++; + } + else { + s6 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s6 !== peg$FAILED) { + s7 = peg$parseh16(); + if (s7 !== peg$FAILED) { + s6 = [s6, s7]; + s5 = s6; + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + if (s5 === peg$FAILED) { + s5 = null; + } + if (s5 !== peg$FAILED) { + s6 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s7 = peg$c24; + peg$currPos++; + } + else { + s7 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s7 !== peg$FAILED) { + s8 = peg$parseh16(); + if (s8 !== peg$FAILED) { + s7 = [s7, s8]; + s6 = s7; + } + else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } + else { + peg$currPos = s6; + s6 = peg$FAILED; + } + if (s6 === peg$FAILED) { + s6 = null; + } + if (s6 !== peg$FAILED) { + s7 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s8 = peg$c24; + peg$currPos++; + } + else { + s8 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s8 !== peg$FAILED) { + s9 = peg$parseh16(); + if (s9 !== peg$FAILED) { + s8 = [s8, s9]; + s7 = s8; + } + else { + peg$currPos = s7; + s7 = peg$FAILED; + } + } + else { + peg$currPos = s7; + s7 = peg$FAILED; + } + if (s7 === peg$FAILED) { + s7 = null; + } + if (s7 !== peg$FAILED) { + if (input.substr(peg$currPos, 2) === peg$c126) { + s8 = peg$c126; + peg$currPos += 2; + } + else { + s8 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c127); + } + } + if (s8 !== peg$FAILED) { + s9 = peg$parseh16(); + if (s9 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6, s7, s8, s9]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = peg$currPos; + s2 = peg$parseh16(); + if (s2 !== peg$FAILED) { + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s4 = peg$c24; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseh16(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + s4 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s5 = peg$c24; + peg$currPos++; + } + else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parseh16(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s5 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s6 = peg$c24; + peg$currPos++; + } + else { + s6 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s6 !== peg$FAILED) { + s7 = peg$parseh16(); + if (s7 !== peg$FAILED) { + s6 = [s6, s7]; + s5 = s6; + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + if (s5 === peg$FAILED) { + s5 = null; + } + if (s5 !== peg$FAILED) { + s6 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s7 = peg$c24; + peg$currPos++; + } + else { + s7 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s7 !== peg$FAILED) { + s8 = peg$parseh16(); + if (s8 !== peg$FAILED) { + s7 = [s7, s8]; + s6 = s7; + } + else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } + else { + peg$currPos = s6; + s6 = peg$FAILED; + } + if (s6 === peg$FAILED) { + s6 = null; + } + if (s6 !== peg$FAILED) { + s7 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s8 = peg$c24; + peg$currPos++; + } + else { + s8 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s8 !== peg$FAILED) { + s9 = peg$parseh16(); + if (s9 !== peg$FAILED) { + s8 = [s8, s9]; + s7 = s8; + } + else { + peg$currPos = s7; + s7 = peg$FAILED; + } + } + else { + peg$currPos = s7; + s7 = peg$FAILED; + } + if (s7 === peg$FAILED) { + s7 = null; + } + if (s7 !== peg$FAILED) { + s8 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s9 = peg$c24; + peg$currPos++; + } + else { + s9 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s9 !== peg$FAILED) { + s10 = peg$parseh16(); + if (s10 !== peg$FAILED) { + s9 = [s9, s10]; + s8 = s9; + } + else { + peg$currPos = s8; + s8 = peg$FAILED; + } + } + else { + peg$currPos = s8; + s8 = peg$FAILED; + } + if (s8 === peg$FAILED) { + s8 = null; + } + if (s8 !== peg$FAILED) { + if (input.substr(peg$currPos, 2) === peg$c126) { + s9 = peg$c126; + peg$currPos += 2; + } + else { + s9 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c127); + } + } + if (s9 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6, s7, s8, s9]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c128(); + } + s0 = s1; + return s0; + } + function peg$parseh16() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + s1 = peg$parseHEXDIG(); + if (s1 !== peg$FAILED) { + s2 = peg$parseHEXDIG(); + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + s3 = peg$parseHEXDIG(); + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + s4 = peg$parseHEXDIG(); + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s1 = [s1, s2, s3, s4]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsels32() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parseh16(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s2 = peg$c24; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseh16(); + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$parseIPv4address(); + } + return s0; + } + function peg$parseIPv4address() { + var s0, s1, s2, s3, s4, s5, s6, s7; + s0 = peg$currPos; + s1 = peg$parsedec_octet(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s2 = peg$c42; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c43); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parsedec_octet(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c42; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c43); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parsedec_octet(); + if (s5 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s6 = peg$c42; + peg$currPos++; + } + else { + s6 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c43); + } + } + if (s6 !== peg$FAILED) { + s7 = peg$parsedec_octet(); + if (s7 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c129(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsedec_octet() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c130) { + s1 = peg$c130; + peg$currPos += 2; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c131); + } + } + if (s1 !== peg$FAILED) { + if (peg$c132.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c133); + } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 50) { + s1 = peg$c134; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c135); + } + } + if (s1 !== peg$FAILED) { + if (peg$c136.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c137); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseDIGIT(); + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 49) { + s1 = peg$c138; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c139); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseDIGIT(); + if (s2 !== peg$FAILED) { + s3 = peg$parseDIGIT(); + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (peg$c140.test(input.charAt(peg$currPos))) { + s1 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c141); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseDIGIT(); + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$parseDIGIT(); + } + } + } + } + return s0; + } + function peg$parseport() { + var s0, s1, s2, s3, s4, s5, s6; + s0 = peg$currPos; + s1 = peg$currPos; + s2 = peg$parseDIGIT(); + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + s3 = peg$parseDIGIT(); + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + s4 = peg$parseDIGIT(); + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s5 = peg$parseDIGIT(); + if (s5 === peg$FAILED) { + s5 = null; + } + if (s5 !== peg$FAILED) { + s6 = peg$parseDIGIT(); + if (s6 === peg$FAILED) { + s6 = null; + } + if (s6 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c142(s1); + } + s0 = s1; + return s0; + } + function peg$parseuri_parameters() { + var s0, s1, s2, s3; + s0 = []; + s1 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 59) { + s2 = peg$c18; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c19); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseuri_parameter(); + if (s3 !== peg$FAILED) { + s2 = [s2, s3]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + while (s1 !== peg$FAILED) { + s0.push(s1); + s1 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 59) { + s2 = peg$c18; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c19); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseuri_parameter(); + if (s3 !== peg$FAILED) { + s2 = [s2, s3]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + return s0; + } + function peg$parseuri_parameter() { + var s0; + s0 = peg$parsetransport_param(); + if (s0 === peg$FAILED) { + s0 = peg$parseuser_param(); + if (s0 === peg$FAILED) { + s0 = peg$parsemethod_param(); + if (s0 === peg$FAILED) { + s0 = peg$parsettl_param(); + if (s0 === peg$FAILED) { + s0 = peg$parsemaddr_param(); + if (s0 === peg$FAILED) { + s0 = peg$parselr_param(); + if (s0 === peg$FAILED) { + s0 = peg$parseother_param(); + } + } + } + } + } + } + return s0; + } + function peg$parsetransport_param() { + var s0, s1, s2; + s0 = peg$currPos; + if (input.substr(peg$currPos, 10).toLowerCase() === peg$c143) { + s1 = input.substr(peg$currPos, 10); + peg$currPos += 10; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c144); + } + } + if (s1 !== peg$FAILED) { + if (input.substr(peg$currPos, 3).toLowerCase() === peg$c145) { + s2 = input.substr(peg$currPos, 3); + peg$currPos += 3; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c146); + } + } + if (s2 === peg$FAILED) { + if (input.substr(peg$currPos, 3).toLowerCase() === peg$c147) { + s2 = input.substr(peg$currPos, 3); + peg$currPos += 3; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c148); + } + } + if (s2 === peg$FAILED) { + if (input.substr(peg$currPos, 4).toLowerCase() === peg$c149) { + s2 = input.substr(peg$currPos, 4); + peg$currPos += 4; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c150); + } + } + if (s2 === peg$FAILED) { + if (input.substr(peg$currPos, 3).toLowerCase() === peg$c151) { + s2 = input.substr(peg$currPos, 3); + peg$currPos += 3; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c152); + } + } + if (s2 === peg$FAILED) { + s2 = peg$parsetoken(); + } + } + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c153(s2); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseuser_param() { + var s0, s1, s2; + s0 = peg$currPos; + if (input.substr(peg$currPos, 5).toLowerCase() === peg$c154) { + s1 = input.substr(peg$currPos, 5); + peg$currPos += 5; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c155); + } + } + if (s1 !== peg$FAILED) { + if (input.substr(peg$currPos, 5).toLowerCase() === peg$c156) { + s2 = input.substr(peg$currPos, 5); + peg$currPos += 5; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c157); + } + } + if (s2 === peg$FAILED) { + if (input.substr(peg$currPos, 2).toLowerCase() === peg$c158) { + s2 = input.substr(peg$currPos, 2); + peg$currPos += 2; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c159); + } + } + if (s2 === peg$FAILED) { + s2 = peg$parsetoken(); + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c160(s2); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsemethod_param() { + var s0, s1, s2; + s0 = peg$currPos; + if (input.substr(peg$currPos, 7).toLowerCase() === peg$c161) { + s1 = input.substr(peg$currPos, 7); + peg$currPos += 7; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c162); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseMethod(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c163(s2); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsettl_param() { + var s0, s1, s2; + s0 = peg$currPos; + if (input.substr(peg$currPos, 4).toLowerCase() === peg$c164) { + s1 = input.substr(peg$currPos, 4); + peg$currPos += 4; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c165); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parsettl(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c166(s2); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsemaddr_param() { + var s0, s1, s2; + s0 = peg$currPos; + if (input.substr(peg$currPos, 6).toLowerCase() === peg$c167) { + s1 = input.substr(peg$currPos, 6); + peg$currPos += 6; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c168); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parsehost(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c169(s2); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parselr_param() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + if (input.substr(peg$currPos, 2).toLowerCase() === peg$c170) { + s1 = input.substr(peg$currPos, 2); + peg$currPos += 2; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c171); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 61) { + s3 = peg$c30; + peg$currPos++; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c31); + } + } + if (s3 !== peg$FAILED) { + s4 = peg$parsetoken(); + if (s4 !== peg$FAILED) { + s3 = [s3, s4]; + s2 = s3; + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c172(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseother_param() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + s1 = peg$parsepname(); + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 61) { + s3 = peg$c30; + peg$currPos++; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c31); + } + } + if (s3 !== peg$FAILED) { + s4 = peg$parsepvalue(); + if (s4 !== peg$FAILED) { + s3 = [s3, s4]; + s2 = s3; + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c173(s1, s2); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsepname() { + var s0, s1, s2; + s0 = peg$currPos; + s1 = []; + s2 = peg$parseparamchar(); + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseparamchar(); + } + } + else { + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s0 = input.substring(s0, peg$currPos); + } + else { + s0 = s1; + } + return s0; + } + function peg$parsepvalue() { + var s0, s1, s2; + s0 = peg$currPos; + s1 = []; + s2 = peg$parseparamchar(); + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseparamchar(); + } + } + else { + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s0 = input.substring(s0, peg$currPos); + } + else { + s0 = s1; + } + return s0; + } + function peg$parseparamchar() { + var s0; + s0 = peg$parseparam_unreserved(); + if (s0 === peg$FAILED) { + s0 = peg$parseunreserved(); + if (s0 === peg$FAILED) { + s0 = peg$parseescaped(); + } + } + return s0; + } + function peg$parseparam_unreserved() { + var s0; + if (input.charCodeAt(peg$currPos) === 91) { + s0 = peg$c76; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c77); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s0 = peg$c78; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c79); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 47) { + s0 = peg$c20; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c21); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s0 = peg$c24; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 38) { + s0 = peg$c28; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c29); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s0 = peg$c32; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 36) { + s0 = peg$c34; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c35); + } + } + } + } + } + } + } + } + return s0; + } + function peg$parseheaders() { + var s0, s1, s2, s3, s4, s5, s6; + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 63) { + s1 = peg$c22; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c23); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseheader(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 38) { + s5 = peg$c28; + peg$currPos++; + } + else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c29); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parseheader(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 38) { + s5 = peg$c28; + peg$currPos++; + } + else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c29); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parseheader(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseheader() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parsehname(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s2 = peg$c30; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c31); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parsehvalue(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c174(s1, s3); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsehname() { + var s0, s1; + s0 = []; + s1 = peg$parsehnv_unreserved(); + if (s1 === peg$FAILED) { + s1 = peg$parseunreserved(); + if (s1 === peg$FAILED) { + s1 = peg$parseescaped(); + } + } + if (s1 !== peg$FAILED) { + while (s1 !== peg$FAILED) { + s0.push(s1); + s1 = peg$parsehnv_unreserved(); + if (s1 === peg$FAILED) { + s1 = peg$parseunreserved(); + if (s1 === peg$FAILED) { + s1 = peg$parseescaped(); + } + } + } + } + else { + s0 = peg$FAILED; + } + return s0; + } + function peg$parsehvalue() { + var s0, s1; + s0 = []; + s1 = peg$parsehnv_unreserved(); + if (s1 === peg$FAILED) { + s1 = peg$parseunreserved(); + if (s1 === peg$FAILED) { + s1 = peg$parseescaped(); + } + } + while (s1 !== peg$FAILED) { + s0.push(s1); + s1 = peg$parsehnv_unreserved(); + if (s1 === peg$FAILED) { + s1 = peg$parseunreserved(); + if (s1 === peg$FAILED) { + s1 = peg$parseescaped(); + } + } + } + return s0; + } + function peg$parsehnv_unreserved() { + var s0; + if (input.charCodeAt(peg$currPos) === 91) { + s0 = peg$c76; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c77); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s0 = peg$c78; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c79); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 47) { + s0 = peg$c20; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c21); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 63) { + s0 = peg$c22; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c23); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s0 = peg$c24; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s0 = peg$c32; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 36) { + s0 = peg$c34; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c35); + } + } + } + } + } + } + } + } + return s0; + } + function peg$parseRequest_Response() { + var s0; + s0 = peg$parseStatus_Line(); + if (s0 === peg$FAILED) { + s0 = peg$parseRequest_Line(); + } + return s0; + } + function peg$parseRequest_Line() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parseMethod(); + if (s1 !== peg$FAILED) { + s2 = peg$parseSP(); + if (s2 !== peg$FAILED) { + s3 = peg$parseRequest_URI(); + if (s3 !== peg$FAILED) { + s4 = peg$parseSP(); + if (s4 !== peg$FAILED) { + s5 = peg$parseSIP_Version(); + if (s5 !== peg$FAILED) { + s1 = [s1, s2, s3, s4, s5]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseRequest_URI() { + var s0; + s0 = peg$parseSIP_URI(); + if (s0 === peg$FAILED) { + s0 = peg$parseabsoluteURI(); + } + return s0; + } + function peg$parseabsoluteURI() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parsescheme(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s2 = peg$c24; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parsehier_part(); + if (s3 === peg$FAILED) { + s3 = peg$parseopaque_part(); + } + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c175(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsehier_part() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + s1 = peg$parsenet_path(); + if (s1 === peg$FAILED) { + s1 = peg$parseabs_path(); + } + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 63) { + s3 = peg$c22; + peg$currPos++; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c23); + } + } + if (s3 !== peg$FAILED) { + s4 = peg$parsequery(); + if (s4 !== peg$FAILED) { + s3 = [s3, s4]; + s2 = s3; + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsenet_path() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c176) { + s1 = peg$c176; + peg$currPos += 2; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c177); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseauthority(); + if (s2 !== peg$FAILED) { + s3 = peg$parseabs_path(); + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseabs_path() { + var s0, s1, s2; + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 47) { + s1 = peg$c20; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c21); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parsepath_segments(); + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseopaque_part() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parseuric_no_slash(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseuric(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseuric(); + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseuric() { + var s0; + s0 = peg$parsereserved(); + if (s0 === peg$FAILED) { + s0 = peg$parseunreserved(); + if (s0 === peg$FAILED) { + s0 = peg$parseescaped(); + } + } + return s0; + } + function peg$parseuric_no_slash() { + var s0; + s0 = peg$parseunreserved(); + if (s0 === peg$FAILED) { + s0 = peg$parseescaped(); + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 59) { + s0 = peg$c18; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c19); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 63) { + s0 = peg$c22; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c23); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s0 = peg$c24; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 64) { + s0 = peg$c26; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c27); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 38) { + s0 = peg$c28; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c29); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s0 = peg$c30; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c31); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s0 = peg$c32; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 36) { + s0 = peg$c34; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c35); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s0 = peg$c36; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c37); + } + } + } + } + } + } + } + } + } + } + } + } + return s0; + } + function peg$parsepath_segments() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parsesegment(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 47) { + s4 = peg$c20; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c21); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parsesegment(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 47) { + s4 = peg$c20; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c21); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parsesegment(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsesegment() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = []; + s2 = peg$parsepchar(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parsepchar(); + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 59) { + s4 = peg$c18; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c19); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseparam(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 59) { + s4 = peg$c18; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c19); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseparam(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseparam() { + var s0, s1; + s0 = []; + s1 = peg$parsepchar(); + while (s1 !== peg$FAILED) { + s0.push(s1); + s1 = peg$parsepchar(); + } + return s0; + } + function peg$parsepchar() { + var s0; + s0 = peg$parseunreserved(); + if (s0 === peg$FAILED) { + s0 = peg$parseescaped(); + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s0 = peg$c24; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 64) { + s0 = peg$c26; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c27); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 38) { + s0 = peg$c28; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c29); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s0 = peg$c30; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c31); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s0 = peg$c32; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 36) { + s0 = peg$c34; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c35); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s0 = peg$c36; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c37); + } + } + } + } + } + } + } + } + } + } + return s0; + } + function peg$parsescheme() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + s1 = peg$currPos; + s2 = peg$parseALPHA(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseALPHA(); + if (s4 === peg$FAILED) { + s4 = peg$parseDIGIT(); + if (s4 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s4 = peg$c32; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + if (s4 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s4 = peg$c38; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c39); + } + } + if (s4 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c42; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c43); + } + } + } + } + } + } + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseALPHA(); + if (s4 === peg$FAILED) { + s4 = peg$parseDIGIT(); + if (s4 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s4 = peg$c32; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + if (s4 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s4 = peg$c38; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c39); + } + } + if (s4 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c42; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c43); + } + } + } + } + } + } + } + if (s3 !== peg$FAILED) { + s2 = [s2, s3]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c178(); + } + s0 = s1; + return s0; + } + function peg$parseauthority() { + var s0; + s0 = peg$parsesrvr(); + if (s0 === peg$FAILED) { + s0 = peg$parsereg_name(); + } + return s0; + } + function peg$parsesrvr() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$currPos; + s2 = peg$parseuserinfo(); + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 64) { + s3 = peg$c26; + peg$currPos++; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c27); + } + } + if (s3 !== peg$FAILED) { + s2 = [s2, s3]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + s2 = peg$parsehostport(); + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = null; + } + return s0; + } + function peg$parsereg_name() { + var s0, s1; + s0 = []; + s1 = peg$parseunreserved(); + if (s1 === peg$FAILED) { + s1 = peg$parseescaped(); + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 36) { + s1 = peg$c34; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c35); + } + } + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s1 = peg$c36; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c37); + } + } + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 59) { + s1 = peg$c18; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c19); + } + } + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s1 = peg$c24; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 64) { + s1 = peg$c26; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c27); + } + } + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 38) { + s1 = peg$c28; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c29); + } + } + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s1 = peg$c30; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c31); + } + } + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s1 = peg$c32; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + } + } + } + } + } + } + } + } + } + if (s1 !== peg$FAILED) { + while (s1 !== peg$FAILED) { + s0.push(s1); + s1 = peg$parseunreserved(); + if (s1 === peg$FAILED) { + s1 = peg$parseescaped(); + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 36) { + s1 = peg$c34; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c35); + } + } + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s1 = peg$c36; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c37); + } + } + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 59) { + s1 = peg$c18; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c19); + } + } + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s1 = peg$c24; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 64) { + s1 = peg$c26; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c27); + } + } + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 38) { + s1 = peg$c28; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c29); + } + } + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s1 = peg$c30; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c31); + } + } + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s1 = peg$c32; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + } + } + } + } + } + } + } + } + } + } + } + else { + s0 = peg$FAILED; + } + return s0; + } + function peg$parsequery() { + var s0, s1; + s0 = []; + s1 = peg$parseuric(); + while (s1 !== peg$FAILED) { + s0.push(s1); + s1 = peg$parseuric(); + } + return s0; + } + function peg$parseSIP_Version() { + var s0, s1, s2, s3, s4, s5, s6; + s0 = peg$currPos; + if (input.substr(peg$currPos, 3).toLowerCase() === peg$c114) { + s1 = input.substr(peg$currPos, 3); + peg$currPos += 3; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c179); + } + } + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 47) { + s2 = peg$c20; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c21); + } + } + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseDIGIT(); + if (s4 !== peg$FAILED) { + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseDIGIT(); + } + } + else { + s3 = peg$FAILED; + } + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c42; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c43); + } + } + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$parseDIGIT(); + if (s6 !== peg$FAILED) { + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parseDIGIT(); + } + } + else { + s5 = peg$FAILED; + } + if (s5 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c180(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseINVITEm() { + var s0; + if (input.substr(peg$currPos, 6) === peg$c181) { + s0 = peg$c181; + peg$currPos += 6; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c182); + } + } + return s0; + } + function peg$parseACKm() { + var s0; + if (input.substr(peg$currPos, 3) === peg$c183) { + s0 = peg$c183; + peg$currPos += 3; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c184); + } + } + return s0; + } + function peg$parsePRACKm() { + var s0; + if (input.substr(peg$currPos, 5) === peg$c185) { + s0 = peg$c185; + peg$currPos += 5; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c186); + } + } + return s0; + } + function peg$parseOPTIONSm() { + var s0; + if (input.substr(peg$currPos, 7) === peg$c187) { + s0 = peg$c187; + peg$currPos += 7; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c188); + } + } + return s0; + } + function peg$parseBYEm() { + var s0; + if (input.substr(peg$currPos, 3) === peg$c189) { + s0 = peg$c189; + peg$currPos += 3; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c190); + } + } + return s0; + } + function peg$parseCANCELm() { + var s0; + if (input.substr(peg$currPos, 6) === peg$c191) { + s0 = peg$c191; + peg$currPos += 6; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c192); + } + } + return s0; + } + function peg$parseREGISTERm() { + var s0; + if (input.substr(peg$currPos, 8) === peg$c193) { + s0 = peg$c193; + peg$currPos += 8; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c194); + } + } + return s0; + } + function peg$parseSUBSCRIBEm() { + var s0; + if (input.substr(peg$currPos, 9) === peg$c195) { + s0 = peg$c195; + peg$currPos += 9; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c196); + } + } + return s0; + } + function peg$parseNOTIFYm() { + var s0; + if (input.substr(peg$currPos, 6) === peg$c197) { + s0 = peg$c197; + peg$currPos += 6; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c198); + } + } + return s0; + } + function peg$parseREFERm() { + var s0; + if (input.substr(peg$currPos, 5) === peg$c199) { + s0 = peg$c199; + peg$currPos += 5; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c200); + } + } + return s0; + } + function peg$parsePUBLISHm() { + var s0; + if (input.substr(peg$currPos, 7) === peg$c201) { + s0 = peg$c201; + peg$currPos += 7; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c202); + } + } + return s0; + } + function peg$parseMethod() { + var s0, s1; + s0 = peg$currPos; + s1 = peg$parseINVITEm(); + if (s1 === peg$FAILED) { + s1 = peg$parseACKm(); + if (s1 === peg$FAILED) { + s1 = peg$parseOPTIONSm(); + if (s1 === peg$FAILED) { + s1 = peg$parseBYEm(); + if (s1 === peg$FAILED) { + s1 = peg$parseCANCELm(); + if (s1 === peg$FAILED) { + s1 = peg$parseREGISTERm(); + if (s1 === peg$FAILED) { + s1 = peg$parseSUBSCRIBEm(); + if (s1 === peg$FAILED) { + s1 = peg$parsePUBLISHm(); + if (s1 === peg$FAILED) { + s1 = peg$parseNOTIFYm(); + if (s1 === peg$FAILED) { + s1 = peg$parseREFERm(); + if (s1 === peg$FAILED) { + s1 = peg$parsetoken(); + } + } + } + } + } + } + } + } + } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c203(); + } + s0 = s1; + return s0; + } + function peg$parseStatus_Line() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parseSIP_Version(); + if (s1 !== peg$FAILED) { + s2 = peg$parseSP(); + if (s2 !== peg$FAILED) { + s3 = peg$parseStatus_Code(); + if (s3 !== peg$FAILED) { + s4 = peg$parseSP(); + if (s4 !== peg$FAILED) { + s5 = peg$parseReason_Phrase(); + if (s5 !== peg$FAILED) { + s1 = [s1, s2, s3, s4, s5]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseStatus_Code() { + var s0, s1; + s0 = peg$currPos; + s1 = peg$parseextension_code(); + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c204(s1); + } + s0 = s1; + return s0; + } + function peg$parseextension_code() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parseDIGIT(); + if (s1 !== peg$FAILED) { + s2 = peg$parseDIGIT(); + if (s2 !== peg$FAILED) { + s3 = peg$parseDIGIT(); + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseReason_Phrase() { + var s0, s1, s2; + s0 = peg$currPos; + s1 = []; + s2 = peg$parsereserved(); + if (s2 === peg$FAILED) { + s2 = peg$parseunreserved(); + if (s2 === peg$FAILED) { + s2 = peg$parseescaped(); + if (s2 === peg$FAILED) { + s2 = peg$parseUTF8_NONASCII(); + if (s2 === peg$FAILED) { + s2 = peg$parseUTF8_CONT(); + if (s2 === peg$FAILED) { + s2 = peg$parseSP(); + if (s2 === peg$FAILED) { + s2 = peg$parseHTAB(); + } + } + } + } + } + } + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parsereserved(); + if (s2 === peg$FAILED) { + s2 = peg$parseunreserved(); + if (s2 === peg$FAILED) { + s2 = peg$parseescaped(); + if (s2 === peg$FAILED) { + s2 = peg$parseUTF8_NONASCII(); + if (s2 === peg$FAILED) { + s2 = peg$parseUTF8_CONT(); + if (s2 === peg$FAILED) { + s2 = peg$parseSP(); + if (s2 === peg$FAILED) { + s2 = peg$parseHTAB(); + } + } + } + } + } + } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c205(); + } + s0 = s1; + return s0; + } + function peg$parseAllow_Events() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parseevent_type(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseCOMMA(); + if (s4 !== peg$FAILED) { + s5 = peg$parseevent_type(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseCOMMA(); + if (s4 !== peg$FAILED) { + s5 = peg$parseevent_type(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseCall_ID() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + s1 = peg$parseword(); + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 64) { + s3 = peg$c26; + peg$currPos++; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c27); + } + } + if (s3 !== peg$FAILED) { + s4 = peg$parseword(); + if (s4 !== peg$FAILED) { + s3 = [s3, s4]; + s2 = s3; + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c206(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseContact() { + var s0, s1, s2, s3, s4, s5, s6; + s0 = peg$currPos; + s1 = peg$parseSTAR(); + if (s1 === peg$FAILED) { + s1 = peg$currPos; + s2 = peg$parsecontact_param(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$currPos; + s5 = peg$parseCOMMA(); + if (s5 !== peg$FAILED) { + s6 = peg$parsecontact_param(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$currPos; + s5 = peg$parseCOMMA(); + if (s5 !== peg$FAILED) { + s6 = peg$parsecontact_param(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + if (s3 !== peg$FAILED) { + s2 = [s2, s3]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c207(); + } + s0 = s1; + return s0; + } + function peg$parsecontact_param() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parseSIP_URI_noparams(); + if (s1 === peg$FAILED) { + s1 = peg$parsename_addr(); + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsecontact_params(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsecontact_params(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c208(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsename_addr() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + s1 = peg$parsedisplayName(); + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + s2 = peg$parseLAQUOT(); + if (s2 !== peg$FAILED) { + s3 = peg$parseSIP_URI(); + if (s3 !== peg$FAILED) { + s4 = peg$parseRAQUOT(); + if (s4 !== peg$FAILED) { + s1 = [s1, s2, s3, s4]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsedisplayName() { + var s0, s1, s2, s3, s4, s5, s6; + s0 = peg$currPos; + s1 = peg$currPos; + s2 = peg$parsetoken(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$currPos; + s5 = peg$parseLWS(); + if (s5 !== peg$FAILED) { + s6 = peg$parsetoken(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$currPos; + s5 = peg$parseLWS(); + if (s5 !== peg$FAILED) { + s6 = peg$parsetoken(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + if (s3 !== peg$FAILED) { + s2 = [s2, s3]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = peg$parsequoted_string(); + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c209(s1); + } + s0 = s1; + return s0; + } + function peg$parsecontact_params() { + var s0; + s0 = peg$parsec_p_q(); + if (s0 === peg$FAILED) { + s0 = peg$parsec_p_expires(); + if (s0 === peg$FAILED) { + s0 = peg$parsegeneric_param(); + } + } + return s0; + } + function peg$parsec_p_q() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.substr(peg$currPos, 1).toLowerCase() === peg$c210) { + s1 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c211); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parseqvalue(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c212(s3); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsec_p_expires() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.substr(peg$currPos, 7).toLowerCase() === peg$c213) { + s1 = input.substr(peg$currPos, 7); + peg$currPos += 7; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c214); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parsedelta_seconds(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c215(s3); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsedelta_seconds() { + var s0, s1, s2; + s0 = peg$currPos; + s1 = []; + s2 = peg$parseDIGIT(); + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseDIGIT(); + } + } + else { + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c216(s1); + } + s0 = s1; + return s0; + } + function peg$parseqvalue() { + var s0, s1, s2, s3, s4, s5, s6; + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 48) { + s1 = peg$c217; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c218); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s3 = peg$c42; + peg$currPos++; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c43); + } + } + if (s3 !== peg$FAILED) { + s4 = peg$parseDIGIT(); + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s5 = peg$parseDIGIT(); + if (s5 === peg$FAILED) { + s5 = null; + } + if (s5 !== peg$FAILED) { + s6 = peg$parseDIGIT(); + if (s6 === peg$FAILED) { + s6 = null; + } + if (s6 !== peg$FAILED) { + s3 = [s3, s4, s5, s6]; + s2 = s3; + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c219(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsegeneric_param() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + s1 = peg$parsetoken(); + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + s3 = peg$parseEQUAL(); + if (s3 !== peg$FAILED) { + s4 = peg$parsegen_value(); + if (s4 !== peg$FAILED) { + s3 = [s3, s4]; + s2 = s3; + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c220(s1, s2); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsegen_value() { + var s0; + s0 = peg$parsetoken(); + if (s0 === peg$FAILED) { + s0 = peg$parsehost(); + if (s0 === peg$FAILED) { + s0 = peg$parsequoted_string(); + } + } + return s0; + } + function peg$parseContent_Disposition() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parsedisp_type(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsedisp_param(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsedisp_param(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsedisp_type() { + var s0, s1; + s0 = peg$currPos; + if (input.substr(peg$currPos, 6).toLowerCase() === peg$c221) { + s1 = input.substr(peg$currPos, 6); + peg$currPos += 6; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c222); + } + } + if (s1 === peg$FAILED) { + if (input.substr(peg$currPos, 7).toLowerCase() === peg$c223) { + s1 = input.substr(peg$currPos, 7); + peg$currPos += 7; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c224); + } + } + if (s1 === peg$FAILED) { + if (input.substr(peg$currPos, 4).toLowerCase() === peg$c225) { + s1 = input.substr(peg$currPos, 4); + peg$currPos += 4; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c226); + } + } + if (s1 === peg$FAILED) { + if (input.substr(peg$currPos, 5).toLowerCase() === peg$c227) { + s1 = input.substr(peg$currPos, 5); + peg$currPos += 5; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c228); + } + } + if (s1 === peg$FAILED) { + s1 = peg$parsetoken(); + } + } + } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c229(); + } + s0 = s1; + return s0; + } + function peg$parsedisp_param() { + var s0; + s0 = peg$parsehandling_param(); + if (s0 === peg$FAILED) { + s0 = peg$parsegeneric_param(); + } + return s0; + } + function peg$parsehandling_param() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.substr(peg$currPos, 8).toLowerCase() === peg$c230) { + s1 = input.substr(peg$currPos, 8); + peg$currPos += 8; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c231); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + if (input.substr(peg$currPos, 8).toLowerCase() === peg$c232) { + s3 = input.substr(peg$currPos, 8); + peg$currPos += 8; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c233); + } + } + if (s3 === peg$FAILED) { + if (input.substr(peg$currPos, 8).toLowerCase() === peg$c234) { + s3 = input.substr(peg$currPos, 8); + peg$currPos += 8; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c235); + } + } + if (s3 === peg$FAILED) { + s3 = peg$parsetoken(); + } + } + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseContent_Encoding() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parsetoken(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseCOMMA(); + if (s4 !== peg$FAILED) { + s5 = peg$parsetoken(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseCOMMA(); + if (s4 !== peg$FAILED) { + s5 = peg$parsetoken(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseContent_Length() { + var s0, s1, s2; + s0 = peg$currPos; + s1 = []; + s2 = peg$parseDIGIT(); + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseDIGIT(); + } + } + else { + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c236(s1); + } + s0 = s1; + return s0; + } + function peg$parseContent_Type() { + var s0, s1; + s0 = peg$currPos; + s1 = peg$parsemedia_type(); + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c237(); + } + s0 = s1; + return s0; + } + function peg$parsemedia_type() { + var s0, s1, s2, s3, s4, s5, s6, s7; + s0 = peg$currPos; + s1 = peg$parsem_type(); + if (s1 !== peg$FAILED) { + s2 = peg$parseSLASH(); + if (s2 !== peg$FAILED) { + s3 = peg$parsem_subtype(); + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$currPos; + s6 = peg$parseSEMI(); + if (s6 !== peg$FAILED) { + s7 = peg$parsem_parameter(); + if (s7 !== peg$FAILED) { + s6 = [s6, s7]; + s5 = s6; + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$currPos; + s6 = peg$parseSEMI(); + if (s6 !== peg$FAILED) { + s7 = peg$parsem_parameter(); + if (s7 !== peg$FAILED) { + s6 = [s6, s7]; + s5 = s6; + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + if (s4 !== peg$FAILED) { + s1 = [s1, s2, s3, s4]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsem_type() { + var s0; + s0 = peg$parsediscrete_type(); + if (s0 === peg$FAILED) { + s0 = peg$parsecomposite_type(); + } + return s0; + } + function peg$parsediscrete_type() { + var s0; + if (input.substr(peg$currPos, 4).toLowerCase() === peg$c238) { + s0 = input.substr(peg$currPos, 4); + peg$currPos += 4; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c239); + } + } + if (s0 === peg$FAILED) { + if (input.substr(peg$currPos, 5).toLowerCase() === peg$c240) { + s0 = input.substr(peg$currPos, 5); + peg$currPos += 5; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c241); + } + } + if (s0 === peg$FAILED) { + if (input.substr(peg$currPos, 5).toLowerCase() === peg$c242) { + s0 = input.substr(peg$currPos, 5); + peg$currPos += 5; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c243); + } + } + if (s0 === peg$FAILED) { + if (input.substr(peg$currPos, 5).toLowerCase() === peg$c244) { + s0 = input.substr(peg$currPos, 5); + peg$currPos += 5; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c245); + } + } + if (s0 === peg$FAILED) { + if (input.substr(peg$currPos, 11).toLowerCase() === peg$c246) { + s0 = input.substr(peg$currPos, 11); + peg$currPos += 11; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c247); + } + } + if (s0 === peg$FAILED) { + s0 = peg$parseextension_token(); + } + } + } + } + } + return s0; + } + function peg$parsecomposite_type() { + var s0; + if (input.substr(peg$currPos, 7).toLowerCase() === peg$c248) { + s0 = input.substr(peg$currPos, 7); + peg$currPos += 7; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c249); + } + } + if (s0 === peg$FAILED) { + if (input.substr(peg$currPos, 9).toLowerCase() === peg$c250) { + s0 = input.substr(peg$currPos, 9); + peg$currPos += 9; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c251); + } + } + if (s0 === peg$FAILED) { + s0 = peg$parseextension_token(); + } + } + return s0; + } + function peg$parseextension_token() { + var s0; + s0 = peg$parsetoken(); + if (s0 === peg$FAILED) { + s0 = peg$parsex_token(); + } + return s0; + } + function peg$parsex_token() { + var s0, s1, s2; + s0 = peg$currPos; + if (input.substr(peg$currPos, 2).toLowerCase() === peg$c252) { + s1 = input.substr(peg$currPos, 2); + peg$currPos += 2; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c253); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parsetoken(); + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsem_subtype() { + var s0; + s0 = peg$parseextension_token(); + if (s0 === peg$FAILED) { + s0 = peg$parsetoken(); + } + return s0; + } + function peg$parsem_parameter() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parsetoken(); + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parsem_value(); + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsem_value() { + var s0; + s0 = peg$parsetoken(); + if (s0 === peg$FAILED) { + s0 = peg$parsequoted_string(); + } + return s0; + } + function peg$parseCSeq() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parseCSeq_value(); + if (s1 !== peg$FAILED) { + s2 = peg$parseLWS(); + if (s2 !== peg$FAILED) { + s3 = peg$parseMethod(); + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseCSeq_value() { + var s0, s1, s2; + s0 = peg$currPos; + s1 = []; + s2 = peg$parseDIGIT(); + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseDIGIT(); + } + } + else { + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c254(s1); + } + s0 = s1; + return s0; + } + function peg$parseExpires() { + var s0, s1; + s0 = peg$currPos; + s1 = peg$parsedelta_seconds(); + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c255(s1); + } + s0 = s1; + return s0; + } + function peg$parseEvent() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parseevent_type(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsegeneric_param(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsegeneric_param(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c256(s1); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseevent_type() { + var s0, s1, s2, s3, s4, s5, s6; + s0 = peg$currPos; + s1 = peg$currPos; + s2 = peg$parsetoken_nodot(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s5 = peg$c42; + peg$currPos++; + } + else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c43); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parsetoken_nodot(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s5 = peg$c42; + peg$currPos++; + } + else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c43); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parsetoken_nodot(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + if (s3 !== peg$FAILED) { + s2 = [s2, s3]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s0 = input.substring(s0, peg$currPos); + } + else { + s0 = s1; + } + return s0; + } + function peg$parseFrom() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parseSIP_URI_noparams(); + if (s1 === peg$FAILED) { + s1 = peg$parsename_addr(); + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsefrom_param(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsefrom_param(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c257(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsefrom_param() { + var s0; + s0 = peg$parsetag_param(); + if (s0 === peg$FAILED) { + s0 = peg$parsegeneric_param(); + } + return s0; + } + function peg$parsetag_param() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.substr(peg$currPos, 3).toLowerCase() === peg$c258) { + s1 = input.substr(peg$currPos, 3); + peg$currPos += 3; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c259); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parsetoken(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c260(s3); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseMax_Forwards() { + var s0, s1, s2; + s0 = peg$currPos; + s1 = []; + s2 = peg$parseDIGIT(); + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseDIGIT(); + } + } + else { + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c261(s1); + } + s0 = s1; + return s0; + } + function peg$parseMin_Expires() { + var s0, s1; + s0 = peg$currPos; + s1 = peg$parsedelta_seconds(); + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c262(s1); + } + s0 = s1; + return s0; + } + function peg$parseName_Addr_Header() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8; + s0 = peg$currPos; + s1 = []; + s2 = peg$parsedisplayName(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parsedisplayName(); + } + if (s1 !== peg$FAILED) { + s2 = peg$parseLAQUOT(); + if (s2 !== peg$FAILED) { + s3 = peg$parseSIP_URI(); + if (s3 !== peg$FAILED) { + s4 = peg$parseRAQUOT(); + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$currPos; + s7 = peg$parseSEMI(); + if (s7 !== peg$FAILED) { + s8 = peg$parsegeneric_param(); + if (s8 !== peg$FAILED) { + s7 = [s7, s8]; + s6 = s7; + } + else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } + else { + peg$currPos = s6; + s6 = peg$FAILED; + } + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$currPos; + s7 = peg$parseSEMI(); + if (s7 !== peg$FAILED) { + s8 = peg$parsegeneric_param(); + if (s8 !== peg$FAILED) { + s7 = [s7, s8]; + s6 = s7; + } + else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } + else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } + if (s5 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c263(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseProxy_Authenticate() { + var s0; + s0 = peg$parsechallenge(); + return s0; + } + function peg$parsechallenge() { + var s0, s1, s2, s3, s4, s5, s6, s7; + s0 = peg$currPos; + if (input.substr(peg$currPos, 6).toLowerCase() === peg$c264) { + s1 = input.substr(peg$currPos, 6); + peg$currPos += 6; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c265); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseLWS(); + if (s2 !== peg$FAILED) { + s3 = peg$parsedigest_cln(); + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$currPos; + s6 = peg$parseCOMMA(); + if (s6 !== peg$FAILED) { + s7 = peg$parsedigest_cln(); + if (s7 !== peg$FAILED) { + s6 = [s6, s7]; + s5 = s6; + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$currPos; + s6 = peg$parseCOMMA(); + if (s6 !== peg$FAILED) { + s7 = peg$parsedigest_cln(); + if (s7 !== peg$FAILED) { + s6 = [s6, s7]; + s5 = s6; + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + if (s4 !== peg$FAILED) { + s1 = [s1, s2, s3, s4]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$parseother_challenge(); + } + return s0; + } + function peg$parseother_challenge() { + var s0, s1, s2, s3, s4, s5, s6, s7; + s0 = peg$currPos; + s1 = peg$parsetoken(); + if (s1 !== peg$FAILED) { + s2 = peg$parseLWS(); + if (s2 !== peg$FAILED) { + s3 = peg$parseauth_param(); + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$currPos; + s6 = peg$parseCOMMA(); + if (s6 !== peg$FAILED) { + s7 = peg$parseauth_param(); + if (s7 !== peg$FAILED) { + s6 = [s6, s7]; + s5 = s6; + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$currPos; + s6 = peg$parseCOMMA(); + if (s6 !== peg$FAILED) { + s7 = peg$parseauth_param(); + if (s7 !== peg$FAILED) { + s6 = [s6, s7]; + s5 = s6; + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + if (s4 !== peg$FAILED) { + s1 = [s1, s2, s3, s4]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseauth_param() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parsetoken(); + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parsetoken(); + if (s3 === peg$FAILED) { + s3 = peg$parsequoted_string(); + } + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsedigest_cln() { + var s0; + s0 = peg$parserealm(); + if (s0 === peg$FAILED) { + s0 = peg$parsedomain(); + if (s0 === peg$FAILED) { + s0 = peg$parsenonce(); + if (s0 === peg$FAILED) { + s0 = peg$parseopaque(); + if (s0 === peg$FAILED) { + s0 = peg$parsestale(); + if (s0 === peg$FAILED) { + s0 = peg$parsealgorithm(); + if (s0 === peg$FAILED) { + s0 = peg$parseqop_options(); + if (s0 === peg$FAILED) { + s0 = peg$parseauth_param(); + } + } + } + } + } + } + } + return s0; + } + function peg$parserealm() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.substr(peg$currPos, 5).toLowerCase() === peg$c266) { + s1 = input.substr(peg$currPos, 5); + peg$currPos += 5; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c267); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parserealm_value(); + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parserealm_value() { + var s0, s1; + s0 = peg$currPos; + s1 = peg$parsequoted_string_clean(); + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c268(s1); + } + s0 = s1; + return s0; + } + function peg$parsedomain() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8; + s0 = peg$currPos; + if (input.substr(peg$currPos, 6).toLowerCase() === peg$c269) { + s1 = input.substr(peg$currPos, 6); + peg$currPos += 6; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c270); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parseLDQUOT(); + if (s3 !== peg$FAILED) { + s4 = peg$parseURI(); + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$currPos; + s7 = []; + s8 = peg$parseSP(); + if (s8 !== peg$FAILED) { + while (s8 !== peg$FAILED) { + s7.push(s8); + s8 = peg$parseSP(); + } + } + else { + s7 = peg$FAILED; + } + if (s7 !== peg$FAILED) { + s8 = peg$parseURI(); + if (s8 !== peg$FAILED) { + s7 = [s7, s8]; + s6 = s7; + } + else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } + else { + peg$currPos = s6; + s6 = peg$FAILED; + } + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$currPos; + s7 = []; + s8 = peg$parseSP(); + if (s8 !== peg$FAILED) { + while (s8 !== peg$FAILED) { + s7.push(s8); + s8 = peg$parseSP(); + } + } + else { + s7 = peg$FAILED; + } + if (s7 !== peg$FAILED) { + s8 = peg$parseURI(); + if (s8 !== peg$FAILED) { + s7 = [s7, s8]; + s6 = s7; + } + else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } + else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parseRDQUOT(); + if (s6 !== peg$FAILED) { + s1 = [s1, s2, s3, s4, s5, s6]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseURI() { + var s0; + s0 = peg$parseabsoluteURI(); + if (s0 === peg$FAILED) { + s0 = peg$parseabs_path(); + } + return s0; + } + function peg$parsenonce() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.substr(peg$currPos, 5).toLowerCase() === peg$c271) { + s1 = input.substr(peg$currPos, 5); + peg$currPos += 5; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c272); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parsenonce_value(); + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsenonce_value() { + var s0, s1; + s0 = peg$currPos; + s1 = peg$parsequoted_string_clean(); + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c273(s1); + } + s0 = s1; + return s0; + } + function peg$parseopaque() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.substr(peg$currPos, 6).toLowerCase() === peg$c274) { + s1 = input.substr(peg$currPos, 6); + peg$currPos += 6; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c275); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parsequoted_string_clean(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c276(s3); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsestale() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + if (input.substr(peg$currPos, 5).toLowerCase() === peg$c277) { + s1 = input.substr(peg$currPos, 5); + peg$currPos += 5; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c278); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$currPos; + if (input.substr(peg$currPos, 4).toLowerCase() === peg$c279) { + s4 = input.substr(peg$currPos, 4); + peg$currPos += 4; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c280); + } + } + if (s4 !== peg$FAILED) { + peg$savedPos = s3; + s4 = peg$c281(); + } + s3 = s4; + if (s3 === peg$FAILED) { + s3 = peg$currPos; + if (input.substr(peg$currPos, 5).toLowerCase() === peg$c282) { + s4 = input.substr(peg$currPos, 5); + peg$currPos += 5; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c283); + } + } + if (s4 !== peg$FAILED) { + peg$savedPos = s3; + s4 = peg$c284(); + } + s3 = s4; + } + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsealgorithm() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.substr(peg$currPos, 9).toLowerCase() === peg$c285) { + s1 = input.substr(peg$currPos, 9); + peg$currPos += 9; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c286); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + if (input.substr(peg$currPos, 3).toLowerCase() === peg$c287) { + s3 = input.substr(peg$currPos, 3); + peg$currPos += 3; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c288); + } + } + if (s3 === peg$FAILED) { + if (input.substr(peg$currPos, 8).toLowerCase() === peg$c289) { + s3 = input.substr(peg$currPos, 8); + peg$currPos += 8; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c290); + } + } + if (s3 === peg$FAILED) { + s3 = peg$parsetoken(); + } + } + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c291(s3); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseqop_options() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9; + s0 = peg$currPos; + if (input.substr(peg$currPos, 3).toLowerCase() === peg$c292) { + s1 = input.substr(peg$currPos, 3); + peg$currPos += 3; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c293); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parseLDQUOT(); + if (s3 !== peg$FAILED) { + s4 = peg$currPos; + s5 = peg$parseqop_value(); + if (s5 !== peg$FAILED) { + s6 = []; + s7 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 44) { + s8 = peg$c36; + peg$currPos++; + } + else { + s8 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c37); + } + } + if (s8 !== peg$FAILED) { + s9 = peg$parseqop_value(); + if (s9 !== peg$FAILED) { + s8 = [s8, s9]; + s7 = s8; + } + else { + peg$currPos = s7; + s7 = peg$FAILED; + } + } + else { + peg$currPos = s7; + s7 = peg$FAILED; + } + while (s7 !== peg$FAILED) { + s6.push(s7); + s7 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 44) { + s8 = peg$c36; + peg$currPos++; + } + else { + s8 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c37); + } + } + if (s8 !== peg$FAILED) { + s9 = peg$parseqop_value(); + if (s9 !== peg$FAILED) { + s8 = [s8, s9]; + s7 = s8; + } + else { + peg$currPos = s7; + s7 = peg$FAILED; + } + } + else { + peg$currPos = s7; + s7 = peg$FAILED; + } + } + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + if (s4 !== peg$FAILED) { + s5 = peg$parseRDQUOT(); + if (s5 !== peg$FAILED) { + s1 = [s1, s2, s3, s4, s5]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseqop_value() { + var s0, s1; + s0 = peg$currPos; + if (input.substr(peg$currPos, 8).toLowerCase() === peg$c294) { + s1 = input.substr(peg$currPos, 8); + peg$currPos += 8; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c295); + } + } + if (s1 === peg$FAILED) { + if (input.substr(peg$currPos, 4).toLowerCase() === peg$c296) { + s1 = input.substr(peg$currPos, 4); + peg$currPos += 4; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c297); + } + } + if (s1 === peg$FAILED) { + s1 = peg$parsetoken(); + } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c298(s1); + } + s0 = s1; + return s0; + } + function peg$parseProxy_Require() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parsetoken(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseCOMMA(); + if (s4 !== peg$FAILED) { + s5 = peg$parsetoken(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseCOMMA(); + if (s4 !== peg$FAILED) { + s5 = peg$parsetoken(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseRAck() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parseRAck_value(); + if (s1 !== peg$FAILED) { + s2 = peg$parseLWS(); + if (s2 !== peg$FAILED) { + s3 = peg$parseRAck_value(); + if (s3 !== peg$FAILED) { + s4 = peg$parseLWS(); + if (s4 !== peg$FAILED) { + s5 = peg$parseMethod(); + if (s5 !== peg$FAILED) { + s1 = [s1, s2, s3, s4, s5]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseRAck_value() { + var s0, s1, s2; + s0 = peg$currPos; + s1 = []; + s2 = peg$parseDIGIT(); + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseDIGIT(); + } + } + else { + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c299(s1); + } + s0 = s1; + return s0; + } + function peg$parseRecord_Route() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parserec_route(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseCOMMA(); + if (s4 !== peg$FAILED) { + s5 = peg$parserec_route(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseCOMMA(); + if (s4 !== peg$FAILED) { + s5 = peg$parserec_route(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c300(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parserec_route() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parsename_addr(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsegeneric_param(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsegeneric_param(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c301(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseRefer_To() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parseSIP_URI_noparams(); + if (s1 === peg$FAILED) { + s1 = peg$parsename_addr(); + if (s1 === peg$FAILED) { + s1 = peg$currPos; + s2 = peg$parseLAQUOT(); + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + s3 = peg$parseabsoluteURI(); + if (s3 !== peg$FAILED) { + s4 = peg$parseRAQUOT(); + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s2 = [s2, s3, s4]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsegeneric_param(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsegeneric_param(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c302(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseReplaces() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parsereplaces_call_id(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsereplaces_params(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsereplaces_params(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c303(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsereplaces_call_id() { + var s0, s1; + s0 = peg$currPos; + s1 = peg$parseCall_ID(); + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c304(); + } + s0 = s1; + return s0; + } + function peg$parsereplaces_params() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.substr(peg$currPos, 8).toLowerCase() === peg$c305) { + s1 = input.substr(peg$currPos, 8); + peg$currPos += 8; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c306); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parsetoken(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c307(s3); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 6).toLowerCase() === peg$c308) { + s1 = input.substr(peg$currPos, 6); + peg$currPos += 6; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c309); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parsetoken(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c310(s3); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 10).toLowerCase() === peg$c311) { + s1 = input.substr(peg$currPos, 10); + peg$currPos += 10; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c312); + } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c313(); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$parsegeneric_param(); + } + } + } + return s0; + } + function peg$parseRequire() { + var s0, s1, s2, s3, s4, s5, s6; + s0 = peg$currPos; + s1 = peg$currPos; + s2 = peg$parsetoken(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$currPos; + s5 = peg$parseCOMMA(); + if (s5 !== peg$FAILED) { + s6 = peg$parsetoken(); + if (s6 !== peg$FAILED) { + peg$savedPos = s4; + s5 = peg$c314(s2, s6); + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$currPos; + s5 = peg$parseCOMMA(); + if (s5 !== peg$FAILED) { + s6 = peg$parsetoken(); + if (s6 !== peg$FAILED) { + peg$savedPos = s4; + s5 = peg$c314(s2, s6); + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + if (s3 !== peg$FAILED) { + peg$savedPos = s1; + s2 = peg$c315(s2, s3); + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c316(s1); + } + s0 = s1; + return s0; + } + function peg$parseRoute() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parseroute_param(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseCOMMA(); + if (s4 !== peg$FAILED) { + s5 = peg$parseroute_param(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseCOMMA(); + if (s4 !== peg$FAILED) { + s5 = peg$parseroute_param(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseroute_param() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parsename_addr(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsegeneric_param(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsegeneric_param(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseRSeq() { + var s0, s1, s2; + s0 = peg$currPos; + s1 = []; + s2 = peg$parseDIGIT(); + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseDIGIT(); + } + } + else { + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c317(s1); + } + s0 = s1; + return s0; + } + function peg$parseSubscription_State() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parsesubstate_value(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsesubexp_params(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsesubexp_params(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsesubstate_value() { + var s0, s1; + s0 = peg$currPos; + if (input.substr(peg$currPos, 6).toLowerCase() === peg$c318) { + s1 = input.substr(peg$currPos, 6); + peg$currPos += 6; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c319); + } + } + if (s1 === peg$FAILED) { + if (input.substr(peg$currPos, 7).toLowerCase() === peg$c320) { + s1 = input.substr(peg$currPos, 7); + peg$currPos += 7; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c321); + } + } + if (s1 === peg$FAILED) { + if (input.substr(peg$currPos, 10).toLowerCase() === peg$c322) { + s1 = input.substr(peg$currPos, 10); + peg$currPos += 10; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c323); + } + } + if (s1 === peg$FAILED) { + s1 = peg$parsetoken(); + } + } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c324(); + } + s0 = s1; + return s0; + } + function peg$parsesubexp_params() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.substr(peg$currPos, 6).toLowerCase() === peg$c325) { + s1 = input.substr(peg$currPos, 6); + peg$currPos += 6; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c326); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parseevent_reason_value(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c327(s3); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 7).toLowerCase() === peg$c213) { + s1 = input.substr(peg$currPos, 7); + peg$currPos += 7; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c214); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parsedelta_seconds(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c328(s3); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 11).toLowerCase() === peg$c329) { + s1 = input.substr(peg$currPos, 11); + peg$currPos += 11; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c330); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parsedelta_seconds(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c331(s3); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$parsegeneric_param(); + } + } + } + return s0; + } + function peg$parseevent_reason_value() { + var s0; + if (input.substr(peg$currPos, 11).toLowerCase() === peg$c332) { + s0 = input.substr(peg$currPos, 11); + peg$currPos += 11; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c333); + } + } + if (s0 === peg$FAILED) { + if (input.substr(peg$currPos, 9).toLowerCase() === peg$c334) { + s0 = input.substr(peg$currPos, 9); + peg$currPos += 9; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c335); + } + } + if (s0 === peg$FAILED) { + if (input.substr(peg$currPos, 8).toLowerCase() === peg$c336) { + s0 = input.substr(peg$currPos, 8); + peg$currPos += 8; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c337); + } + } + if (s0 === peg$FAILED) { + if (input.substr(peg$currPos, 7).toLowerCase() === peg$c338) { + s0 = input.substr(peg$currPos, 7); + peg$currPos += 7; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c339); + } + } + if (s0 === peg$FAILED) { + if (input.substr(peg$currPos, 6).toLowerCase() === peg$c340) { + s0 = input.substr(peg$currPos, 6); + peg$currPos += 6; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c341); + } + } + if (s0 === peg$FAILED) { + if (input.substr(peg$currPos, 10).toLowerCase() === peg$c342) { + s0 = input.substr(peg$currPos, 10); + peg$currPos += 10; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c343); + } + } + if (s0 === peg$FAILED) { + if (input.substr(peg$currPos, 9).toLowerCase() === peg$c344) { + s0 = input.substr(peg$currPos, 9); + peg$currPos += 9; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c345); + } + } + if (s0 === peg$FAILED) { + s0 = peg$parsetoken(); + } + } + } + } + } + } + } + return s0; + } + function peg$parseSubject() { + var s0; + s0 = peg$parseTEXT_UTF8_TRIM(); + if (s0 === peg$FAILED) { + s0 = null; + } + return s0; + } + function peg$parseSupported() { + var s0, s1, s2, s3, s4, s5, s6; + s0 = peg$currPos; + s1 = peg$currPos; + s2 = peg$parsetoken(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$currPos; + s5 = peg$parseCOMMA(); + if (s5 !== peg$FAILED) { + s6 = peg$parsetoken(); + if (s6 !== peg$FAILED) { + peg$savedPos = s4; + s5 = peg$c314(s2, s6); + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$currPos; + s5 = peg$parseCOMMA(); + if (s5 !== peg$FAILED) { + s6 = peg$parsetoken(); + if (s6 !== peg$FAILED) { + peg$savedPos = s4; + s5 = peg$c314(s2, s6); + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + if (s3 !== peg$FAILED) { + peg$savedPos = s1; + s2 = peg$c315(s2, s3); + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c346(s1); + } + s0 = s1; + return s0; + } + function peg$parseTo() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parseSIP_URI_noparams(); + if (s1 === peg$FAILED) { + s1 = peg$parsename_addr(); + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parseto_param(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parseto_param(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c347(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseto_param() { + var s0; + s0 = peg$parsetag_param(); + if (s0 === peg$FAILED) { + s0 = peg$parsegeneric_param(); + } + return s0; + } + function peg$parseVia() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parsevia_parm(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseCOMMA(); + if (s4 !== peg$FAILED) { + s5 = peg$parsevia_parm(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseCOMMA(); + if (s4 !== peg$FAILED) { + s5 = peg$parsevia_parm(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsevia_parm() { + var s0, s1, s2, s3, s4, s5, s6, s7; + s0 = peg$currPos; + s1 = peg$parsesent_protocol(); + if (s1 !== peg$FAILED) { + s2 = peg$parseLWS(); + if (s2 !== peg$FAILED) { + s3 = peg$parsesent_by(); + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$currPos; + s6 = peg$parseSEMI(); + if (s6 !== peg$FAILED) { + s7 = peg$parsevia_params(); + if (s7 !== peg$FAILED) { + s6 = [s6, s7]; + s5 = s6; + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$currPos; + s6 = peg$parseSEMI(); + if (s6 !== peg$FAILED) { + s7 = peg$parsevia_params(); + if (s7 !== peg$FAILED) { + s6 = [s6, s7]; + s5 = s6; + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + if (s4 !== peg$FAILED) { + s1 = [s1, s2, s3, s4]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsevia_params() { + var s0; + s0 = peg$parsevia_ttl(); + if (s0 === peg$FAILED) { + s0 = peg$parsevia_maddr(); + if (s0 === peg$FAILED) { + s0 = peg$parsevia_received(); + if (s0 === peg$FAILED) { + s0 = peg$parsevia_branch(); + if (s0 === peg$FAILED) { + s0 = peg$parseresponse_port(); + if (s0 === peg$FAILED) { + s0 = peg$parsegeneric_param(); + } + } + } + } + } + return s0; + } + function peg$parsevia_ttl() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.substr(peg$currPos, 3).toLowerCase() === peg$c348) { + s1 = input.substr(peg$currPos, 3); + peg$currPos += 3; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c349); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parsettl(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c350(s3); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsevia_maddr() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.substr(peg$currPos, 5).toLowerCase() === peg$c351) { + s1 = input.substr(peg$currPos, 5); + peg$currPos += 5; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c352); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parsehost(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c353(s3); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsevia_received() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.substr(peg$currPos, 8).toLowerCase() === peg$c354) { + s1 = input.substr(peg$currPos, 8); + peg$currPos += 8; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c355); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parseIPv4address(); + if (s3 === peg$FAILED) { + s3 = peg$parseIPv6address(); + if (s3 === peg$FAILED) { + s3 = peg$parseIPv6reference(); + } + } + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c356(s3); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsevia_branch() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.substr(peg$currPos, 6).toLowerCase() === peg$c357) { + s1 = input.substr(peg$currPos, 6); + peg$currPos += 6; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c358); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parsetoken(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c359(s3); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseresponse_port() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + if (input.substr(peg$currPos, 5).toLowerCase() === peg$c360) { + s1 = input.substr(peg$currPos, 5); + peg$currPos += 5; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c361); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseDIGIT(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseDIGIT(); + } + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c362(s3); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsesent_protocol() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parseprotocol_name(); + if (s1 !== peg$FAILED) { + s2 = peg$parseSLASH(); + if (s2 !== peg$FAILED) { + s3 = peg$parsetoken(); + if (s3 !== peg$FAILED) { + s4 = peg$parseSLASH(); + if (s4 !== peg$FAILED) { + s5 = peg$parsetransport(); + if (s5 !== peg$FAILED) { + s1 = [s1, s2, s3, s4, s5]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseprotocol_name() { + var s0, s1; + s0 = peg$currPos; + if (input.substr(peg$currPos, 3).toLowerCase() === peg$c114) { + s1 = input.substr(peg$currPos, 3); + peg$currPos += 3; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c179); + } + } + if (s1 === peg$FAILED) { + s1 = peg$parsetoken(); + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c363(s1); + } + s0 = s1; + return s0; + } + function peg$parsetransport() { + var s0, s1; + s0 = peg$currPos; + if (input.substr(peg$currPos, 3).toLowerCase() === peg$c145) { + s1 = input.substr(peg$currPos, 3); + peg$currPos += 3; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c364); + } + } + if (s1 === peg$FAILED) { + if (input.substr(peg$currPos, 3).toLowerCase() === peg$c147) { + s1 = input.substr(peg$currPos, 3); + peg$currPos += 3; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c365); + } + } + if (s1 === peg$FAILED) { + if (input.substr(peg$currPos, 3).toLowerCase() === peg$c151) { + s1 = input.substr(peg$currPos, 3); + peg$currPos += 3; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c366); + } + } + if (s1 === peg$FAILED) { + if (input.substr(peg$currPos, 4).toLowerCase() === peg$c149) { + s1 = input.substr(peg$currPos, 4); + peg$currPos += 4; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c367); + } + } + if (s1 === peg$FAILED) { + s1 = peg$parsetoken(); + } + } + } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c368(s1); + } + s0 = s1; + return s0; + } + function peg$parsesent_by() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + s1 = peg$parseviaHost(); + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + s3 = peg$parseCOLON(); + if (s3 !== peg$FAILED) { + s4 = peg$parsevia_port(); + if (s4 !== peg$FAILED) { + s3 = [s3, s4]; + s2 = s3; + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseviaHost() { + var s0, s1; + s0 = peg$currPos; + s1 = peg$parsehostname(); + if (s1 === peg$FAILED) { + s1 = peg$parseIPv4address(); + if (s1 === peg$FAILED) { + s1 = peg$parseIPv6reference(); + } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c369(); + } + s0 = s1; + return s0; + } + function peg$parsevia_port() { + var s0, s1, s2, s3, s4, s5, s6; + s0 = peg$currPos; + s1 = peg$currPos; + s2 = peg$parseDIGIT(); + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + s3 = peg$parseDIGIT(); + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + s4 = peg$parseDIGIT(); + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s5 = peg$parseDIGIT(); + if (s5 === peg$FAILED) { + s5 = null; + } + if (s5 !== peg$FAILED) { + s6 = peg$parseDIGIT(); + if (s6 === peg$FAILED) { + s6 = null; + } + if (s6 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c370(s1); + } + s0 = s1; + return s0; + } + function peg$parsettl() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + s1 = peg$currPos; + s2 = peg$parseDIGIT(); + if (s2 !== peg$FAILED) { + s3 = peg$parseDIGIT(); + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + s4 = peg$parseDIGIT(); + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s2 = [s2, s3, s4]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c371(s1); + } + s0 = s1; + return s0; + } + function peg$parseWWW_Authenticate() { + var s0; + s0 = peg$parsechallenge(); + return s0; + } + function peg$parseSession_Expires() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parsedelta_seconds(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsese_params(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsese_params(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c372(s1); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsese_params() { + var s0; + s0 = peg$parserefresher_param(); + if (s0 === peg$FAILED) { + s0 = peg$parsegeneric_param(); + } + return s0; + } + function peg$parserefresher_param() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.substr(peg$currPos, 9) === peg$c373) { + s1 = peg$c373; + peg$currPos += 9; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c374); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + if (input.substr(peg$currPos, 3) === peg$c375) { + s3 = peg$c375; + peg$currPos += 3; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c376); + } + } + if (s3 === peg$FAILED) { + if (input.substr(peg$currPos, 3) === peg$c377) { + s3 = peg$c377; + peg$currPos += 3; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c378); + } + } + } + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c379(s3); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseMin_SE() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parsedelta_seconds(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsegeneric_param(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsegeneric_param(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c380(s1); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseextension_header() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parsetoken(); + if (s1 !== peg$FAILED) { + s2 = peg$parseHCOLON(); + if (s2 !== peg$FAILED) { + s3 = peg$parseheader_value(); + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseheader_value() { + var s0, s1; + s0 = []; + s1 = peg$parseTEXT_UTF8char(); + if (s1 === peg$FAILED) { + s1 = peg$parseUTF8_CONT(); + if (s1 === peg$FAILED) { + s1 = peg$parseLWS(); + } + } + while (s1 !== peg$FAILED) { + s0.push(s1); + s1 = peg$parseTEXT_UTF8char(); + if (s1 === peg$FAILED) { + s1 = peg$parseUTF8_CONT(); + if (s1 === peg$FAILED) { + s1 = peg$parseLWS(); + } + } + } + return s0; + } + function peg$parsemessage_body() { + var s0, s1; + s0 = []; + s1 = peg$parseOCTET(); + while (s1 !== peg$FAILED) { + s0.push(s1); + s1 = peg$parseOCTET(); + } + return s0; + } + function peg$parsestun_URI() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parsestun_scheme(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s2 = peg$c24; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parsestun_host_port(); + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsestun_scheme() { + var s0, s1; + s0 = peg$currPos; + if (input.substr(peg$currPos, 5).toLowerCase() === peg$c381) { + s1 = input.substr(peg$currPos, 5); + peg$currPos += 5; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c382); + } + } + if (s1 === peg$FAILED) { + if (input.substr(peg$currPos, 4).toLowerCase() === peg$c383) { + s1 = input.substr(peg$currPos, 4); + peg$currPos += 4; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c384); + } + } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c385(s1); + } + s0 = s1; + return s0; + } + function peg$parsestun_host_port() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + s1 = peg$parsestun_host(); + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s3 = peg$c24; + peg$currPos++; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s3 !== peg$FAILED) { + s4 = peg$parseport(); + if (s4 !== peg$FAILED) { + s3 = [s3, s4]; + s2 = s3; + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsestun_host() { + var s0, s1; + s0 = peg$currPos; + s1 = peg$parseIPv4address(); + if (s1 === peg$FAILED) { + s1 = peg$parseIPv6reference(); + if (s1 === peg$FAILED) { + s1 = peg$parsereg_name(); + } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c386(s1); + } + s0 = s1; + return s0; + } + function peg$parsestun_unreserved() { + var s0; + s0 = peg$parseALPHA(); + if (s0 === peg$FAILED) { + s0 = peg$parseDIGIT(); + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s0 = peg$c38; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c39); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s0 = peg$c42; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c43); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 95) { + s0 = peg$c40; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c41); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 126) { + s0 = peg$c46; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c47); + } + } + } + } + } + } + } + return s0; + } + function peg$parsesub_delims() { + var s0; + if (input.charCodeAt(peg$currPos) === 33) { + s0 = peg$c44; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c45); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 36) { + s0 = peg$c34; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c35); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 38) { + s0 = peg$c28; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c29); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 39) { + s0 = peg$c50; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c51); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 40) { + s0 = peg$c52; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c53); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s0 = peg$c54; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c55); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 42) { + s0 = peg$c48; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c49); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s0 = peg$c32; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s0 = peg$c36; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c37); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 59) { + s0 = peg$c18; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c19); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s0 = peg$c30; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c31); + } + } + } + } + } + } + } + } + } + } + } + } + return s0; + } + function peg$parseturn_URI() { + var s0, s1, s2, s3, s4, s5, s6; + s0 = peg$currPos; + s1 = peg$parseturn_scheme(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s2 = peg$c24; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parsestun_host_port(); + if (s3 !== peg$FAILED) { + s4 = peg$currPos; + if (input.substr(peg$currPos, 11) === peg$c387) { + s5 = peg$c387; + peg$currPos += 11; + } + else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c388); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parsetransport(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s1 = [s1, s2, s3, s4]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseturn_scheme() { + var s0, s1; + s0 = peg$currPos; + if (input.substr(peg$currPos, 5).toLowerCase() === peg$c389) { + s1 = input.substr(peg$currPos, 5); + peg$currPos += 5; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c390); + } + } + if (s1 === peg$FAILED) { + if (input.substr(peg$currPos, 4).toLowerCase() === peg$c391) { + s1 = input.substr(peg$currPos, 4); + peg$currPos += 4; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c392); + } + } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c385(s1); + } + s0 = s1; + return s0; + } + function peg$parseturn_transport() { + var s0, s1, s2; + s0 = peg$currPos; + if (input.substr(peg$currPos, 3).toLowerCase() === peg$c145) { + s1 = input.substr(peg$currPos, 3); + peg$currPos += 3; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c146); + } + } + if (s1 === peg$FAILED) { + if (input.substr(peg$currPos, 3).toLowerCase() === peg$c147) { + s1 = input.substr(peg$currPos, 3); + peg$currPos += 3; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c148); + } + } + if (s1 === peg$FAILED) { + s1 = []; + s2 = peg$parseunreserved(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseunreserved(); + } + } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c393(s1); + } + s0 = s1; + return s0; + } + function peg$parseuuid() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9; + s0 = peg$currPos; + s1 = peg$parsehex8(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s2 = peg$c38; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c39); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parsehex4(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s4 = peg$c38; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c39); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parsehex4(); + if (s5 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s6 = peg$c38; + peg$currPos++; + } + else { + s6 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c39); + } + } + if (s6 !== peg$FAILED) { + s7 = peg$parsehex4(); + if (s7 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s8 = peg$c38; + peg$currPos++; + } + else { + s8 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c39); + } + } + if (s8 !== peg$FAILED) { + s9 = peg$parsehex12(); + if (s9 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c394(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsehex4() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + s1 = peg$parseHEXDIG(); + if (s1 !== peg$FAILED) { + s2 = peg$parseHEXDIG(); + if (s2 !== peg$FAILED) { + s3 = peg$parseHEXDIG(); + if (s3 !== peg$FAILED) { + s4 = peg$parseHEXDIG(); + if (s4 !== peg$FAILED) { + s1 = [s1, s2, s3, s4]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsehex8() { + var s0, s1, s2; + s0 = peg$currPos; + s1 = peg$parsehex4(); + if (s1 !== peg$FAILED) { + s2 = peg$parsehex4(); + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsehex12() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parsehex4(); + if (s1 !== peg$FAILED) { + s2 = peg$parsehex4(); + if (s2 !== peg$FAILED) { + s3 = peg$parsehex4(); + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsesipfrag() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parseRequest_Response(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseheader(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseheader(); + } + if (s2 !== peg$FAILED) { + s3 = peg$currPos; + s4 = peg$parseCRLF(); + if (s4 !== peg$FAILED) { + s5 = peg$parsemessage_body(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseReferred_By() { + var s0, s1, s2, s3, s4, s5, s6, s7; + s0 = peg$currPos; + if (input.substr(peg$currPos, 11) === peg$c395) { + s1 = peg$c395; + peg$currPos += 11; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c396); + } + } + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 98) { + s1 = peg$c397; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c398); + } + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseHCOLON(); + if (s2 !== peg$FAILED) { + s3 = peg$parsereferrer_uri(); + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$currPos; + s6 = peg$parseSEMI(); + if (s6 !== peg$FAILED) { + s7 = peg$parsereferredby_id_param(); + if (s7 === peg$FAILED) { + s7 = peg$parsegeneric_param(); + } + if (s7 !== peg$FAILED) { + s6 = [s6, s7]; + s5 = s6; + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$currPos; + s6 = peg$parseSEMI(); + if (s6 !== peg$FAILED) { + s7 = peg$parsereferredby_id_param(); + if (s7 === peg$FAILED) { + s7 = peg$parsegeneric_param(); + } + if (s7 !== peg$FAILED) { + s6 = [s6, s7]; + s5 = s6; + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + if (s4 !== peg$FAILED) { + s1 = [s1, s2, s3, s4]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsereferrer_uri() { + var s0; + s0 = peg$parsename_addr(); + if (s0 === peg$FAILED) { + s0 = peg$parseSIP_URI_noparams(); + } + return s0; + } + function peg$parsereferredby_id_param() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.substr(peg$currPos, 3) === peg$c399) { + s1 = peg$c399; + peg$currPos += 3; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c400); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parsesip_clean_msg_id(); + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsesip_clean_msg_id() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parseLDQUOT(); + if (s1 !== peg$FAILED) { + s2 = peg$parsemark(); + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 64) { + s3 = peg$c26; + peg$currPos++; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c27); + } + } + if (s3 !== peg$FAILED) { + s4 = peg$parsemark(); + if (s4 === peg$FAILED) { + s4 = peg$parsehost(); + } + if (s4 !== peg$FAILED) { + s5 = peg$parseRDQUOT(); + if (s5 !== peg$FAILED) { + s1 = [s1, s2, s3, s4, s5]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + options.data = {}; // Object to which header attributes will be assigned during parsing + function list(head, tail) { + return [head].concat(tail); + } + peg$result = peg$startRuleFunction(); + if (peg$result !== peg$FAILED && peg$currPos === input.length) { + return peg$result; + } + else { + if (peg$result !== peg$FAILED && peg$currPos < input.length) { + peg$fail(peg$endExpectation()); + } + throw peg$buildStructuredError(peg$maxFailExpected, peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null, peg$maxFailPos < input.length + ? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1) + : peg$computeLocation(peg$maxFailPos, peg$maxFailPos)); + } +} +exports.parse = peg$parse; + + +/***/ }), +/* 9 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Enums_1 = __webpack_require__(5); +var URI_1 = __webpack_require__(10); +/** + * @class Class creating a Name Address SIP header. + * + * @param {SIP.URI} uri + * @param {String} [displayName] + * @param {Object} [parameters] + * + */ +var NameAddrHeader = /** @class */ (function (_super) { + __extends(NameAddrHeader, _super); + function NameAddrHeader(uri, displayName, parameters) { + var _this = _super.call(this, parameters) || this; + _this.type = Enums_1.TypeStrings.NameAddrHeader; + // Checks + if (!uri || !(uri.type === Enums_1.TypeStrings.URI)) { + throw new TypeError('missing or invalid "uri" parameter'); + } + _this.uri = uri; + _this._displayName = displayName; + return _this; + } + Object.defineProperty(NameAddrHeader.prototype, "friendlyName", { + get: function () { + return this.displayName || this.uri.aor; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(NameAddrHeader.prototype, "displayName", { + get: function () { return this._displayName; }, + set: function (value) { + this._displayName = value; + }, + enumerable: true, + configurable: true + }); + NameAddrHeader.prototype.clone = function () { + return new NameAddrHeader(this.uri.clone(), this._displayName, JSON.parse(JSON.stringify(this.parameters))); + }; + NameAddrHeader.prototype.toString = function () { + var body = (this.displayName || this.displayName === "0") ? '"' + this.displayName + '" ' : ""; + body += "<" + this.uri.toString() + ">"; + for (var parameter in this.parameters) { + if (this.parameters.hasOwnProperty(parameter)) { + body += ";" + parameter; + if (this.parameters[parameter] !== null) { + body += "=" + this.parameters[parameter]; + } + } + } + return body; + }; + return NameAddrHeader; +}(URI_1.Parameters)); +exports.NameAddrHeader = NameAddrHeader; + + +/***/ }), +/* 10 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Constants_1 = __webpack_require__(3); +var Enums_1 = __webpack_require__(5); +var Parameters = /** @class */ (function () { + function Parameters(parameters) { + this.parameters = {}; + this.type = Enums_1.TypeStrings.Parameters; + for (var param in parameters) { + if (parameters.hasOwnProperty(param)) { + this.setParam(param, parameters[param]); + } + } + } + Parameters.prototype.setParam = function (key, value) { + if (key) { + this.parameters[key.toLowerCase()] = (typeof value === "undefined" || value === null) ? null : value.toString(); + } + }; + Parameters.prototype.getParam = function (key) { + if (key) { + return this.parameters[key.toLowerCase()]; + } + }; + Parameters.prototype.hasParam = function (key) { + if (key) { + return !!this.parameters.hasOwnProperty(key.toLowerCase()); + } + return false; + }; + Parameters.prototype.deleteParam = function (parameter) { + parameter = parameter.toLowerCase(); + if (this.parameters.hasOwnProperty(parameter)) { + var value = this.parameters[parameter]; + delete this.parameters[parameter]; + return value; + } + }; + Parameters.prototype.clearParams = function () { + this.parameters = {}; + }; + return Parameters; +}()); +exports.Parameters = Parameters; +/** + * @class Class creating a SIP URI. + * + * @param {String} [scheme] + * @param {String} [user] + * @param {String} host + * @param {String} [port] + * @param {Object} [parameters] + * @param {Object} [headers] + * + */ +// tslint:disable-next-line:max-classes-per-file +var URI = /** @class */ (function (_super) { + __extends(URI, _super); + function URI(scheme, user, host, port, parameters, headers) { + var _this = _super.call(this, parameters) || this; + _this.headers = {}; + _this.type = Enums_1.TypeStrings.URI; + // Checks + if (!host) { + throw new TypeError('missing or invalid "host" parameter'); + } + // Initialize parameters + scheme = scheme || Constants_1.C.SIP; + for (var header in headers) { + if (headers.hasOwnProperty(header)) { + _this.setHeader(header, headers[header]); + } + } + // Raw URI + _this.raw = { + scheme: scheme, + user: user, + host: host, + port: port + }; + // Normalized URI + _this.normal = { + scheme: scheme.toLowerCase(), + user: user, + host: host.toLowerCase(), + port: port + }; + return _this; + } + Object.defineProperty(URI.prototype, "_normal", { + get: function () { return this.normal; }, + enumerable: true, + configurable: true + }); + Object.defineProperty(URI.prototype, "_raw", { + get: function () { return this.raw; }, + enumerable: true, + configurable: true + }); + Object.defineProperty(URI.prototype, "scheme", { + get: function () { return this.normal.scheme; }, + set: function (value) { + this.raw.scheme = value; + this.normal.scheme = value.toLowerCase(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(URI.prototype, "user", { + get: function () { return this.normal.user; }, + set: function (value) { + this.normal.user = this.raw.user = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(URI.prototype, "host", { + get: function () { return this.normal.host; }, + set: function (value) { + this.raw.host = value; + this.normal.host = value.toLowerCase(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(URI.prototype, "aor", { + get: function () { return this.normal.user + "@" + this.normal.host; }, + enumerable: true, + configurable: true + }); + Object.defineProperty(URI.prototype, "port", { + get: function () { return this.normal.port; }, + set: function (value) { + this.normal.port = this.raw.port = value === 0 ? value : value; + }, + enumerable: true, + configurable: true + }); + URI.prototype.setHeader = function (name, value) { + this.headers[this.headerize(name)] = (value instanceof Array) ? value : [value]; + }; + URI.prototype.getHeader = function (name) { + if (name) { + return this.headers[this.headerize(name)]; + } + }; + URI.prototype.hasHeader = function (name) { + return !!name && !!this.headers.hasOwnProperty(this.headerize(name)); + }; + URI.prototype.deleteHeader = function (header) { + header = this.headerize(header); + if (this.headers.hasOwnProperty(header)) { + var value = this.headers[header]; + delete this.headers[header]; + return value; + } + }; + URI.prototype.clearHeaders = function () { + this.headers = {}; + }; + URI.prototype.clone = function () { + return new URI(this._raw.scheme, this._raw.user || "", this._raw.host, this._raw.port, JSON.parse(JSON.stringify(this.parameters)), JSON.parse(JSON.stringify(this.headers))); + }; + URI.prototype.toRaw = function () { + return this._toString(this._raw); + }; + URI.prototype.toString = function () { + return this._toString(this._normal); + }; + URI.prototype._toString = function (uri) { + var uriString = uri.scheme + ":"; + // add slashes if it's not a sip(s) URI + if (!uri.scheme.toLowerCase().match("^sips?$")) { + uriString += "//"; + } + if (uri.user) { + uriString += this.escapeUser(uri.user) + "@"; + } + uriString += uri.host; + if (uri.port || uri.port === 0) { + uriString += ":" + uri.port; + } + for (var parameter in this.parameters) { + if (this.parameters.hasOwnProperty(parameter)) { + uriString += ";" + parameter; + if (this.parameters[parameter] !== null) { + uriString += "=" + this.parameters[parameter]; + } + } + } + var headers = []; + for (var header in this.headers) { + if (this.headers.hasOwnProperty(header)) { + for (var idx in this.headers[header]) { + if (this.headers[header].hasOwnProperty(idx)) { + headers.push(header + "=" + this.headers[header][idx]); + } + } + } + } + if (headers.length > 0) { + uriString += "?" + headers.join("&"); + } + return uriString; + }; + // The following two functions were copied from Utils to break a circular dependency + /* + * Hex-escape a SIP URI user. + * @private + * @param {String} user + */ + URI.prototype.escapeUser = function (user) { + // Don't hex-escape ':' (%3A), '+' (%2B), '?' (%3F"), '/' (%2F). + return encodeURIComponent(decodeURIComponent(user)) + .replace(/%3A/ig, ":") + .replace(/%2B/ig, "+") + .replace(/%3F/ig, "?") + .replace(/%2F/ig, "/"); + }; + URI.prototype.headerize = function (str) { + var exceptions = { + "Call-Id": "Call-ID", + "Cseq": "CSeq", + "Min-Se": "Min-SE", + "Rack": "RAck", + "Rseq": "RSeq", + "Www-Authenticate": "WWW-Authenticate", + }; + var name = str.toLowerCase().replace(/_/g, "-").split("-"); + var parts = name.length; + var hname = ""; + for (var part = 0; part < parts; part++) { + if (part !== 0) { + hname += "-"; + } + hname += name[part].charAt(0).toUpperCase() + name[part].substring(1); + } + if (exceptions[hname]) { + hname = exceptions[hname]; + } + return hname; + }; + return URI; +}(Parameters)); +exports.URI = URI; + + +/***/ }), +/* 11 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +var Constants_1 = __webpack_require__(3); +var Enums_1 = __webpack_require__(5); +var Grammar_1 = __webpack_require__(7); +var Utils; +(function (Utils) { + function defer() { + var deferred = {}; + deferred.promise = new Promise(function (resolve, reject) { + deferred.resolve = resolve; + deferred.reject = reject; + }); + return deferred; + } + Utils.defer = defer; + function reducePromises(arr, val) { + return arr.reduce(function (acc, fn) { + acc = acc.then(fn); + return acc; + }, Promise.resolve(val)); + } + Utils.reducePromises = reducePromises; + function str_utf8_length(str) { + return encodeURIComponent(str).replace(/%[A-F\d]{2}/g, "U").length; + } + Utils.str_utf8_length = str_utf8_length; + function generateFakeSDP(body) { + if (!body) { + return; + } + var start = body.indexOf("o="); + var end = body.indexOf("\r\n", start); + return "v=0\r\n" + body.slice(start, end) + "\r\ns=-\r\nt=0 0\r\nc=IN IP4 0.0.0.0"; + } + Utils.generateFakeSDP = generateFakeSDP; + function isDecimal(num) { + var numAsNum = parseInt(num, 10); + return !isNaN(numAsNum) && (parseFloat(num) === numAsNum); + } + Utils.isDecimal = isDecimal; + function createRandomToken(size, base) { + if (base === void 0) { base = 32; } + var token = ""; + for (var i = 0; i < size; i++) { + var r = Math.floor(Math.random() * base); + token += r.toString(base); + } + return token; + } + Utils.createRandomToken = createRandomToken; + function newTag() { + // used to use the constant in UA + return Utils.createRandomToken(10); + } + Utils.newTag = newTag; + // http://stackoverflow.com/users/109538/broofa + function newUUID() { + var UUID = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) { + var r = Math.floor(Math.random() * 16); + var v = c === "x" ? r : (r % 4 + 8); + return v.toString(16); + }); + return UUID; + } + Utils.newUUID = newUUID; + /* + * Normalize SIP URI. + * NOTE: It does not allow a SIP URI without username. + * Accepts 'sip', 'sips' and 'tel' URIs and convert them into 'sip'. + * Detects the domain part (if given) and properly hex-escapes the user portion. + * If the user portion has only 'tel' number symbols the user portion is clean of 'tel' visual separators. + * @private + * @param {String} target + * @param {String} [domain] + */ + function normalizeTarget(target, domain) { + // If no target is given then raise an error. + if (!target) { + return; + // If a SIP.URI instance is given then return it. + } + else if (target.type === Enums_1.TypeStrings.URI) { + return target; + // If a string is given split it by '@': + // - Last fragment is the desired domain. + // - Otherwise append the given domain argument. + } + else if (typeof target === "string") { + var targetArray = target.split("@"); + var targetUser = void 0; + var targetDomain = void 0; + switch (targetArray.length) { + case 1: + if (!domain) { + return; + } + targetUser = target; + targetDomain = domain; + break; + case 2: + targetUser = targetArray[0]; + targetDomain = targetArray[1]; + break; + default: + targetUser = targetArray.slice(0, targetArray.length - 1).join("@"); + targetDomain = targetArray[targetArray.length - 1]; + } + // Remove the URI scheme (if present). + targetUser = targetUser.replace(/^(sips?|tel):/i, ""); + // Remove 'tel' visual separators if the user portion just contains 'tel' number symbols. + if (/^[\-\.\(\)]*\+?[0-9\-\.\(\)]+$/.test(targetUser)) { + targetUser = targetUser.replace(/[\-\.\(\)]/g, ""); + } + // Build the complete SIP URI. + target = Constants_1.C.SIP + ":" + Utils.escapeUser(targetUser) + "@" + targetDomain; + // Finally parse the resulting URI. + return Grammar_1.Grammar.URIParse(target); + } + else { + return; + } + } + Utils.normalizeTarget = normalizeTarget; + /* + * Hex-escape a SIP URI user. + * @private + * @param {String} user + */ + function escapeUser(user) { + // Don't hex-escape ':' (%3A), '+' (%2B), '?' (%3F"), '/' (%2F). + return encodeURIComponent(decodeURIComponent(user)) + .replace(/%3A/ig, ":") + .replace(/%2B/ig, "+") + .replace(/%3F/ig, "?") + .replace(/%2F/ig, "/"); + } + Utils.escapeUser = escapeUser; + function headerize(str) { + var exceptions = { + "Call-Id": "Call-ID", + "Cseq": "CSeq", + "Min-Se": "Min-SE", + "Rack": "RAck", + "Rseq": "RSeq", + "Www-Authenticate": "WWW-Authenticate", + }; + var name = str.toLowerCase().replace(/_/g, "-").split("-"); + var parts = name.length; + var hname = ""; + for (var part = 0; part < parts; part++) { + if (part !== 0) { + hname += "-"; + } + hname += name[part].charAt(0).toUpperCase() + name[part].substring(1); + } + if (exceptions[hname]) { + hname = exceptions[hname]; + } + return hname; + } + Utils.headerize = headerize; + function sipErrorCause(statusCode) { + for (var cause in Constants_1.C.SIP_ERROR_CAUSES) { + if (Constants_1.C.SIP_ERROR_CAUSES[cause].indexOf(statusCode) !== -1) { + return Constants_1.C.causes[cause]; + } + } + return Constants_1.C.causes.SIP_FAILURE_CODE; + } + Utils.sipErrorCause = sipErrorCause; + function getReasonPhrase(code, specific) { + return specific || Constants_1.C.REASON_PHRASE[code] || ""; + } + Utils.getReasonPhrase = getReasonPhrase; + function getReasonHeaderValue(code, reason) { + reason = Utils.getReasonPhrase(code, reason); + return "SIP;cause=" + code + ';text="' + reason + '"'; + } + Utils.getReasonHeaderValue = getReasonHeaderValue; + function getCancelReason(code, reason) { + if (code && code < 200 || code > 699) { + throw new TypeError("Invalid statusCode: " + code); + } + else if (code) { + return Utils.getReasonHeaderValue(code, reason); + } + } + Utils.getCancelReason = getCancelReason; + function buildStatusLine(code, reason) { + // Validate code and reason values + if (!code || (code < 100 || code > 699)) { + throw new TypeError("Invalid statusCode: " + code); + } + else if (reason && typeof reason !== "string" && !(reason instanceof String)) { + throw new TypeError("Invalid reason: " + reason); + } + reason = Utils.getReasonPhrase(code, reason); + return "SIP/2.0 " + code + " " + reason + "\r\n"; + } + Utils.buildStatusLine = buildStatusLine; +})(Utils = exports.Utils || (exports.Utils = {})); + + +/***/ }), +/* 12 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +var crypto_js_1 = __webpack_require__(13); +var Enums_1 = __webpack_require__(5); +var Utils_1 = __webpack_require__(11); +/** + * SIP Digest Authentication. + * @function Digest Authentication + * @param {SIP.UA} ua + */ +var DigestAuthentication = /** @class */ (function () { + function DigestAuthentication(ua) { + this.type = Enums_1.TypeStrings.DigestAuthentication; + this.logger = ua.getLogger("sipjs.digestauthentication"); + this.username = ua.configuration.authorizationUser; + this.password = ua.configuration.password; + this.nc = 0; + this.ncHex = "00000000"; + } + /** + * Performs Digest authentication given a SIP request and the challenge + * received in a response to that request. + * Returns true if credentials were successfully generated, false otherwise. + * + * @param {SIP.OutgoingRequest} request + * @param {Object} challenge + */ + DigestAuthentication.prototype.authenticate = function (request, challenge, body) { + // Inspect and validate the challenge. + this.algorithm = challenge.algorithm; + this.realm = challenge.realm; + this.nonce = challenge.nonce; + this.opaque = challenge.opaque; + this.stale = challenge.stale; + if (this.algorithm) { + if (this.algorithm !== "MD5") { + this.logger.warn("challenge with Digest algorithm different than 'MD5', authentication aborted"); + return false; + } + } + else { + this.algorithm = "MD5"; + } + if (!this.realm) { + this.logger.warn("challenge without Digest realm, authentication aborted"); + return false; + } + if (!this.nonce) { + this.logger.warn("challenge without Digest nonce, authentication aborted"); + return false; + } + // 'qop' can contain a list of values (Array). Let's choose just one. + if (challenge.qop) { + if (challenge.qop.indexOf("auth") > -1) { + this.qop = "auth"; + } + else if (challenge.qop.indexOf("auth-int") > -1) { + this.qop = "auth-int"; + } + else { + // Otherwise 'qop' is present but does not contain 'auth' or 'auth-int', so abort here. + this.logger.warn("challenge without Digest qop different than 'auth' or 'auth-int', authentication aborted"); + return false; + } + } + else { + this.qop = undefined; + } + // Fill other attributes. + this.method = request.method; + this.uri = request.ruri; + this.cnonce = Utils_1.Utils.createRandomToken(12); + this.nc += 1; + this.updateNcHex(); + // nc-value = 8LHEX. Max value = 'FFFFFFFF'. + if (this.nc === 4294967296) { + this.nc = 1; + this.ncHex = "00000001"; + } + // Calculate the Digest "response" value. + this.calculateResponse(body); + return true; + }; + /** + * Return the Proxy-Authorization or WWW-Authorization header value. + */ + DigestAuthentication.prototype.toString = function () { + var authParams = []; + if (!this.response) { + throw new Error("response field does not exist, cannot generate Authorization header"); + } + authParams.push("algorithm=" + this.algorithm); + authParams.push('username="' + this.username + '"'); + authParams.push('realm="' + this.realm + '"'); + authParams.push('nonce="' + this.nonce + '"'); + authParams.push('uri="' + this.uri + '"'); + authParams.push('response="' + this.response + '"'); + if (this.opaque) { + authParams.push('opaque="' + this.opaque + '"'); + } + if (this.qop) { + authParams.push("qop=" + this.qop); + authParams.push('cnonce="' + this.cnonce + '"'); + authParams.push("nc=" + this.ncHex); + } + return "Digest " + authParams.join(", "); + }; + /** + * Generate the 'nc' value as required by Digest in this.ncHex by reading this.nc. + * @private + */ + DigestAuthentication.prototype.updateNcHex = function () { + var hex = Number(this.nc).toString(16); + this.ncHex = "00000000".substr(0, 8 - hex.length) + hex; + }; + /** + * Generate Digest 'response' value. + * @private + */ + DigestAuthentication.prototype.calculateResponse = function (body) { + var ha2; + // HA1 = MD5(A1) = MD5(username:realm:password) + var ha1 = crypto_js_1.MD5(this.username + ":" + this.realm + ":" + this.password); + if (this.qop === "auth") { + // HA2 = MD5(A2) = MD5(method:digestURI) + ha2 = crypto_js_1.MD5(this.method + ":" + this.uri); + // response = MD5(HA1:nonce:nonceCount:credentialsNonce:qop:HA2) + this.response = crypto_js_1.MD5(ha1 + ":" + this.nonce + ":" + this.ncHex + ":" + this.cnonce + ":auth:" + ha2); + } + else if (this.qop === "auth-int") { + // HA2 = MD5(A2) = MD5(method:digestURI:MD5(entityBody)) + ha2 = crypto_js_1.MD5(this.method + ":" + this.uri + ":" + crypto_js_1.MD5(body ? body : "")); + // response = MD5(HA1:nonce:nonceCount:credentialsNonce:qop:HA2) + this.response = crypto_js_1.MD5(ha1 + ":" + this.nonce + ":" + this.ncHex + ":" + this.cnonce + ":auth-int:" + ha2); + } + else if (this.qop === undefined) { + // HA2 = MD5(A2) = MD5(method:digestURI) + ha2 = crypto_js_1.MD5(this.method + ":" + this.uri); + // response = MD5(HA1:nonce:HA2) + this.response = crypto_js_1.MD5(ha1 + ":" + this.nonce + ":" + ha2); + } + }; + return DigestAuthentication; +}()); +exports.DigestAuthentication = DigestAuthentication; + + +/***/ }), +/* 13 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory, undef) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14), __webpack_require__(15), __webpack_require__(16), __webpack_require__(17), __webpack_require__(18), __webpack_require__(19), __webpack_require__(20), __webpack_require__(21), __webpack_require__(22), __webpack_require__(23), __webpack_require__(24), __webpack_require__(25), __webpack_require__(26), __webpack_require__(27), __webpack_require__(28), __webpack_require__(29), __webpack_require__(30), __webpack_require__(31), __webpack_require__(32), __webpack_require__(33), __webpack_require__(34), __webpack_require__(35), __webpack_require__(36), __webpack_require__(37), __webpack_require__(38), __webpack_require__(39), __webpack_require__(40), __webpack_require__(41), __webpack_require__(42), __webpack_require__(43), __webpack_require__(44), __webpack_require__(45), __webpack_require__(46)); + } + else {} +}(this, function (CryptoJS) { + + return CryptoJS; + +})); + +/***/ }), +/* 14 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory) { + if (true) { + // CommonJS + module.exports = exports = factory(); + } + else {} +}(this, function () { + + /** + * CryptoJS core components. + */ + var CryptoJS = CryptoJS || (function (Math, undefined) { + /* + * Local polyfil of Object.create + */ + var create = Object.create || (function () { + function F() {}; + + return function (obj) { + var subtype; + + F.prototype = obj; + + subtype = new F(); + + F.prototype = null; + + return subtype; + }; + }()) + + /** + * CryptoJS namespace. + */ + var C = {}; + + /** + * Library namespace. + */ + var C_lib = C.lib = {}; + + /** + * Base object for prototypal inheritance. + */ + var Base = C_lib.Base = (function () { + + + return { + /** + * Creates a new object that inherits from this object. + * + * @param {Object} overrides Properties to copy into the new object. + * + * @return {Object} The new object. + * + * @static + * + * @example + * + * var MyType = CryptoJS.lib.Base.extend({ + * field: 'value', + * + * method: function () { + * } + * }); + */ + extend: function (overrides) { + // Spawn + var subtype = create(this); + + // Augment + if (overrides) { + subtype.mixIn(overrides); + } + + // Create default initializer + if (!subtype.hasOwnProperty('init') || this.init === subtype.init) { + subtype.init = function () { + subtype.$super.init.apply(this, arguments); + }; + } + + // Initializer's prototype is the subtype object + subtype.init.prototype = subtype; + + // Reference supertype + subtype.$super = this; + + return subtype; + }, + + /** + * Extends this object and runs the init method. + * Arguments to create() will be passed to init(). + * + * @return {Object} The new object. + * + * @static + * + * @example + * + * var instance = MyType.create(); + */ + create: function () { + var instance = this.extend(); + instance.init.apply(instance, arguments); + + return instance; + }, + + /** + * Initializes a newly created object. + * Override this method to add some logic when your objects are created. + * + * @example + * + * var MyType = CryptoJS.lib.Base.extend({ + * init: function () { + * // ... + * } + * }); + */ + init: function () { + }, + + /** + * Copies properties into this object. + * + * @param {Object} properties The properties to mix in. + * + * @example + * + * MyType.mixIn({ + * field: 'value' + * }); + */ + mixIn: function (properties) { + for (var propertyName in properties) { + if (properties.hasOwnProperty(propertyName)) { + this[propertyName] = properties[propertyName]; + } + } + + // IE won't copy toString using the loop above + if (properties.hasOwnProperty('toString')) { + this.toString = properties.toString; + } + }, + + /** + * Creates a copy of this object. + * + * @return {Object} The clone. + * + * @example + * + * var clone = instance.clone(); + */ + clone: function () { + return this.init.prototype.extend(this); + } + }; + }()); + + /** + * An array of 32-bit words. + * + * @property {Array} words The array of 32-bit words. + * @property {number} sigBytes The number of significant bytes in this word array. + */ + var WordArray = C_lib.WordArray = Base.extend({ + /** + * Initializes a newly created word array. + * + * @param {Array} words (Optional) An array of 32-bit words. + * @param {number} sigBytes (Optional) The number of significant bytes in the words. + * + * @example + * + * var wordArray = CryptoJS.lib.WordArray.create(); + * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]); + * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6); + */ + init: function (words, sigBytes) { + words = this.words = words || []; + + if (sigBytes != undefined) { + this.sigBytes = sigBytes; + } else { + this.sigBytes = words.length * 4; + } + }, + + /** + * Converts this word array to a string. + * + * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex + * + * @return {string} The stringified word array. + * + * @example + * + * var string = wordArray + ''; + * var string = wordArray.toString(); + * var string = wordArray.toString(CryptoJS.enc.Utf8); + */ + toString: function (encoder) { + return (encoder || Hex).stringify(this); + }, + + /** + * Concatenates a word array to this word array. + * + * @param {WordArray} wordArray The word array to append. + * + * @return {WordArray} This word array. + * + * @example + * + * wordArray1.concat(wordArray2); + */ + concat: function (wordArray) { + // Shortcuts + var thisWords = this.words; + var thatWords = wordArray.words; + var thisSigBytes = this.sigBytes; + var thatSigBytes = wordArray.sigBytes; + + // Clamp excess bits + this.clamp(); + + // Concat + if (thisSigBytes % 4) { + // Copy one byte at a time + for (var i = 0; i < thatSigBytes; i++) { + var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; + thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8); + } + } else { + // Copy one word at a time + for (var i = 0; i < thatSigBytes; i += 4) { + thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2]; + } + } + this.sigBytes += thatSigBytes; + + // Chainable + return this; + }, + + /** + * Removes insignificant bits. + * + * @example + * + * wordArray.clamp(); + */ + clamp: function () { + // Shortcuts + var words = this.words; + var sigBytes = this.sigBytes; + + // Clamp + words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8); + words.length = Math.ceil(sigBytes / 4); + }, + + /** + * Creates a copy of this word array. + * + * @return {WordArray} The clone. + * + * @example + * + * var clone = wordArray.clone(); + */ + clone: function () { + var clone = Base.clone.call(this); + clone.words = this.words.slice(0); + + return clone; + }, + + /** + * Creates a word array filled with random bytes. + * + * @param {number} nBytes The number of random bytes to generate. + * + * @return {WordArray} The random word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.lib.WordArray.random(16); + */ + random: function (nBytes) { + var words = []; + + var r = (function (m_w) { + var m_w = m_w; + var m_z = 0x3ade68b1; + var mask = 0xffffffff; + + return function () { + m_z = (0x9069 * (m_z & 0xFFFF) + (m_z >> 0x10)) & mask; + m_w = (0x4650 * (m_w & 0xFFFF) + (m_w >> 0x10)) & mask; + var result = ((m_z << 0x10) + m_w) & mask; + result /= 0x100000000; + result += 0.5; + return result * (Math.random() > .5 ? 1 : -1); + } + }); + + for (var i = 0, rcache; i < nBytes; i += 4) { + var _r = r((rcache || Math.random()) * 0x100000000); + + rcache = _r() * 0x3ade67b7; + words.push((_r() * 0x100000000) | 0); + } + + return new WordArray.init(words, nBytes); + } + }); + + /** + * Encoder namespace. + */ + var C_enc = C.enc = {}; + + /** + * Hex encoding strategy. + */ + var Hex = C_enc.Hex = { + /** + * Converts a word array to a hex string. + * + * @param {WordArray} wordArray The word array. + * + * @return {string} The hex string. + * + * @static + * + * @example + * + * var hexString = CryptoJS.enc.Hex.stringify(wordArray); + */ + stringify: function (wordArray) { + // Shortcuts + var words = wordArray.words; + var sigBytes = wordArray.sigBytes; + + // Convert + var hexChars = []; + for (var i = 0; i < sigBytes; i++) { + var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; + hexChars.push((bite >>> 4).toString(16)); + hexChars.push((bite & 0x0f).toString(16)); + } + + return hexChars.join(''); + }, + + /** + * Converts a hex string to a word array. + * + * @param {string} hexStr The hex string. + * + * @return {WordArray} The word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.enc.Hex.parse(hexString); + */ + parse: function (hexStr) { + // Shortcut + var hexStrLength = hexStr.length; + + // Convert + var words = []; + for (var i = 0; i < hexStrLength; i += 2) { + words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4); + } + + return new WordArray.init(words, hexStrLength / 2); + } + }; + + /** + * Latin1 encoding strategy. + */ + var Latin1 = C_enc.Latin1 = { + /** + * Converts a word array to a Latin1 string. + * + * @param {WordArray} wordArray The word array. + * + * @return {string} The Latin1 string. + * + * @static + * + * @example + * + * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray); + */ + stringify: function (wordArray) { + // Shortcuts + var words = wordArray.words; + var sigBytes = wordArray.sigBytes; + + // Convert + var latin1Chars = []; + for (var i = 0; i < sigBytes; i++) { + var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; + latin1Chars.push(String.fromCharCode(bite)); + } + + return latin1Chars.join(''); + }, + + /** + * Converts a Latin1 string to a word array. + * + * @param {string} latin1Str The Latin1 string. + * + * @return {WordArray} The word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.enc.Latin1.parse(latin1String); + */ + parse: function (latin1Str) { + // Shortcut + var latin1StrLength = latin1Str.length; + + // Convert + var words = []; + for (var i = 0; i < latin1StrLength; i++) { + words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8); + } + + return new WordArray.init(words, latin1StrLength); + } + }; + + /** + * UTF-8 encoding strategy. + */ + var Utf8 = C_enc.Utf8 = { + /** + * Converts a word array to a UTF-8 string. + * + * @param {WordArray} wordArray The word array. + * + * @return {string} The UTF-8 string. + * + * @static + * + * @example + * + * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray); + */ + stringify: function (wordArray) { + try { + return decodeURIComponent(escape(Latin1.stringify(wordArray))); + } catch (e) { + throw new Error('Malformed UTF-8 data'); + } + }, + + /** + * Converts a UTF-8 string to a word array. + * + * @param {string} utf8Str The UTF-8 string. + * + * @return {WordArray} The word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.enc.Utf8.parse(utf8String); + */ + parse: function (utf8Str) { + return Latin1.parse(unescape(encodeURIComponent(utf8Str))); + } + }; + + /** + * Abstract buffered block algorithm template. + * + * The property blockSize must be implemented in a concrete subtype. + * + * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0 + */ + var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({ + /** + * Resets this block algorithm's data buffer to its initial state. + * + * @example + * + * bufferedBlockAlgorithm.reset(); + */ + reset: function () { + // Initial values + this._data = new WordArray.init(); + this._nDataBytes = 0; + }, + + /** + * Adds new data to this block algorithm's buffer. + * + * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8. + * + * @example + * + * bufferedBlockAlgorithm._append('data'); + * bufferedBlockAlgorithm._append(wordArray); + */ + _append: function (data) { + // Convert string to WordArray, else assume WordArray already + if (typeof data == 'string') { + data = Utf8.parse(data); + } + + // Append + this._data.concat(data); + this._nDataBytes += data.sigBytes; + }, + + /** + * Processes available data blocks. + * + * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype. + * + * @param {boolean} doFlush Whether all blocks and partial blocks should be processed. + * + * @return {WordArray} The processed data. + * + * @example + * + * var processedData = bufferedBlockAlgorithm._process(); + * var processedData = bufferedBlockAlgorithm._process(!!'flush'); + */ + _process: function (doFlush) { + // Shortcuts + var data = this._data; + var dataWords = data.words; + var dataSigBytes = data.sigBytes; + var blockSize = this.blockSize; + var blockSizeBytes = blockSize * 4; + + // Count blocks ready + var nBlocksReady = dataSigBytes / blockSizeBytes; + if (doFlush) { + // Round up to include partial blocks + nBlocksReady = Math.ceil(nBlocksReady); + } else { + // Round down to include only full blocks, + // less the number of blocks that must remain in the buffer + nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0); + } + + // Count words ready + var nWordsReady = nBlocksReady * blockSize; + + // Count bytes ready + var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes); + + // Process blocks + if (nWordsReady) { + for (var offset = 0; offset < nWordsReady; offset += blockSize) { + // Perform concrete-algorithm logic + this._doProcessBlock(dataWords, offset); + } + + // Remove processed words + var processedWords = dataWords.splice(0, nWordsReady); + data.sigBytes -= nBytesReady; + } + + // Return processed words + return new WordArray.init(processedWords, nBytesReady); + }, + + /** + * Creates a copy of this object. + * + * @return {Object} The clone. + * + * @example + * + * var clone = bufferedBlockAlgorithm.clone(); + */ + clone: function () { + var clone = Base.clone.call(this); + clone._data = this._data.clone(); + + return clone; + }, + + _minBufferSize: 0 + }); + + /** + * Abstract hasher template. + * + * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits) + */ + var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({ + /** + * Configuration options. + */ + cfg: Base.extend(), + + /** + * Initializes a newly created hasher. + * + * @param {Object} cfg (Optional) The configuration options to use for this hash computation. + * + * @example + * + * var hasher = CryptoJS.algo.SHA256.create(); + */ + init: function (cfg) { + // Apply config defaults + this.cfg = this.cfg.extend(cfg); + + // Set initial values + this.reset(); + }, + + /** + * Resets this hasher to its initial state. + * + * @example + * + * hasher.reset(); + */ + reset: function () { + // Reset data buffer + BufferedBlockAlgorithm.reset.call(this); + + // Perform concrete-hasher logic + this._doReset(); + }, + + /** + * Updates this hasher with a message. + * + * @param {WordArray|string} messageUpdate The message to append. + * + * @return {Hasher} This hasher. + * + * @example + * + * hasher.update('message'); + * hasher.update(wordArray); + */ + update: function (messageUpdate) { + // Append + this._append(messageUpdate); + + // Update the hash + this._process(); + + // Chainable + return this; + }, + + /** + * Finalizes the hash computation. + * Note that the finalize operation is effectively a destructive, read-once operation. + * + * @param {WordArray|string} messageUpdate (Optional) A final message update. + * + * @return {WordArray} The hash. + * + * @example + * + * var hash = hasher.finalize(); + * var hash = hasher.finalize('message'); + * var hash = hasher.finalize(wordArray); + */ + finalize: function (messageUpdate) { + // Final message update + if (messageUpdate) { + this._append(messageUpdate); + } + + // Perform concrete-hasher logic + var hash = this._doFinalize(); + + return hash; + }, + + blockSize: 512/32, + + /** + * Creates a shortcut function to a hasher's object interface. + * + * @param {Hasher} hasher The hasher to create a helper for. + * + * @return {Function} The shortcut function. + * + * @static + * + * @example + * + * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256); + */ + _createHelper: function (hasher) { + return function (message, cfg) { + return new hasher.init(cfg).finalize(message); + }; + }, + + /** + * Creates a shortcut function to the HMAC's object interface. + * + * @param {Hasher} hasher The hasher to use in this HMAC helper. + * + * @return {Function} The shortcut function. + * + * @static + * + * @example + * + * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256); + */ + _createHmacHelper: function (hasher) { + return function (message, key) { + return new C_algo.HMAC.init(hasher, key).finalize(message); + }; + } + }); + + /** + * Algorithm namespace. + */ + var C_algo = C.algo = {}; + + return C; + }(Math)); + + + return CryptoJS; + +})); + +/***/ }), +/* 15 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14)); + } + else {} +}(this, function (CryptoJS) { + + (function (undefined) { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var Base = C_lib.Base; + var X32WordArray = C_lib.WordArray; + + /** + * x64 namespace. + */ + var C_x64 = C.x64 = {}; + + /** + * A 64-bit word. + */ + var X64Word = C_x64.Word = Base.extend({ + /** + * Initializes a newly created 64-bit word. + * + * @param {number} high The high 32 bits. + * @param {number} low The low 32 bits. + * + * @example + * + * var x64Word = CryptoJS.x64.Word.create(0x00010203, 0x04050607); + */ + init: function (high, low) { + this.high = high; + this.low = low; + } + + /** + * Bitwise NOTs this word. + * + * @return {X64Word} A new x64-Word object after negating. + * + * @example + * + * var negated = x64Word.not(); + */ + // not: function () { + // var high = ~this.high; + // var low = ~this.low; + + // return X64Word.create(high, low); + // }, + + /** + * Bitwise ANDs this word with the passed word. + * + * @param {X64Word} word The x64-Word to AND with this word. + * + * @return {X64Word} A new x64-Word object after ANDing. + * + * @example + * + * var anded = x64Word.and(anotherX64Word); + */ + // and: function (word) { + // var high = this.high & word.high; + // var low = this.low & word.low; + + // return X64Word.create(high, low); + // }, + + /** + * Bitwise ORs this word with the passed word. + * + * @param {X64Word} word The x64-Word to OR with this word. + * + * @return {X64Word} A new x64-Word object after ORing. + * + * @example + * + * var ored = x64Word.or(anotherX64Word); + */ + // or: function (word) { + // var high = this.high | word.high; + // var low = this.low | word.low; + + // return X64Word.create(high, low); + // }, + + /** + * Bitwise XORs this word with the passed word. + * + * @param {X64Word} word The x64-Word to XOR with this word. + * + * @return {X64Word} A new x64-Word object after XORing. + * + * @example + * + * var xored = x64Word.xor(anotherX64Word); + */ + // xor: function (word) { + // var high = this.high ^ word.high; + // var low = this.low ^ word.low; + + // return X64Word.create(high, low); + // }, + + /** + * Shifts this word n bits to the left. + * + * @param {number} n The number of bits to shift. + * + * @return {X64Word} A new x64-Word object after shifting. + * + * @example + * + * var shifted = x64Word.shiftL(25); + */ + // shiftL: function (n) { + // if (n < 32) { + // var high = (this.high << n) | (this.low >>> (32 - n)); + // var low = this.low << n; + // } else { + // var high = this.low << (n - 32); + // var low = 0; + // } + + // return X64Word.create(high, low); + // }, + + /** + * Shifts this word n bits to the right. + * + * @param {number} n The number of bits to shift. + * + * @return {X64Word} A new x64-Word object after shifting. + * + * @example + * + * var shifted = x64Word.shiftR(7); + */ + // shiftR: function (n) { + // if (n < 32) { + // var low = (this.low >>> n) | (this.high << (32 - n)); + // var high = this.high >>> n; + // } else { + // var low = this.high >>> (n - 32); + // var high = 0; + // } + + // return X64Word.create(high, low); + // }, + + /** + * Rotates this word n bits to the left. + * + * @param {number} n The number of bits to rotate. + * + * @return {X64Word} A new x64-Word object after rotating. + * + * @example + * + * var rotated = x64Word.rotL(25); + */ + // rotL: function (n) { + // return this.shiftL(n).or(this.shiftR(64 - n)); + // }, + + /** + * Rotates this word n bits to the right. + * + * @param {number} n The number of bits to rotate. + * + * @return {X64Word} A new x64-Word object after rotating. + * + * @example + * + * var rotated = x64Word.rotR(7); + */ + // rotR: function (n) { + // return this.shiftR(n).or(this.shiftL(64 - n)); + // }, + + /** + * Adds this word with the passed word. + * + * @param {X64Word} word The x64-Word to add with this word. + * + * @return {X64Word} A new x64-Word object after adding. + * + * @example + * + * var added = x64Word.add(anotherX64Word); + */ + // add: function (word) { + // var low = (this.low + word.low) | 0; + // var carry = (low >>> 0) < (this.low >>> 0) ? 1 : 0; + // var high = (this.high + word.high + carry) | 0; + + // return X64Word.create(high, low); + // } + }); + + /** + * An array of 64-bit words. + * + * @property {Array} words The array of CryptoJS.x64.Word objects. + * @property {number} sigBytes The number of significant bytes in this word array. + */ + var X64WordArray = C_x64.WordArray = Base.extend({ + /** + * Initializes a newly created word array. + * + * @param {Array} words (Optional) An array of CryptoJS.x64.Word objects. + * @param {number} sigBytes (Optional) The number of significant bytes in the words. + * + * @example + * + * var wordArray = CryptoJS.x64.WordArray.create(); + * + * var wordArray = CryptoJS.x64.WordArray.create([ + * CryptoJS.x64.Word.create(0x00010203, 0x04050607), + * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) + * ]); + * + * var wordArray = CryptoJS.x64.WordArray.create([ + * CryptoJS.x64.Word.create(0x00010203, 0x04050607), + * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) + * ], 10); + */ + init: function (words, sigBytes) { + words = this.words = words || []; + + if (sigBytes != undefined) { + this.sigBytes = sigBytes; + } else { + this.sigBytes = words.length * 8; + } + }, + + /** + * Converts this 64-bit word array to a 32-bit word array. + * + * @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array. + * + * @example + * + * var x32WordArray = x64WordArray.toX32(); + */ + toX32: function () { + // Shortcuts + var x64Words = this.words; + var x64WordsLength = x64Words.length; + + // Convert + var x32Words = []; + for (var i = 0; i < x64WordsLength; i++) { + var x64Word = x64Words[i]; + x32Words.push(x64Word.high); + x32Words.push(x64Word.low); + } + + return X32WordArray.create(x32Words, this.sigBytes); + }, + + /** + * Creates a copy of this word array. + * + * @return {X64WordArray} The clone. + * + * @example + * + * var clone = x64WordArray.clone(); + */ + clone: function () { + var clone = Base.clone.call(this); + + // Clone "words" array + var words = clone.words = this.words.slice(0); + + // Clone each X64Word object + var wordsLength = words.length; + for (var i = 0; i < wordsLength; i++) { + words[i] = words[i].clone(); + } + + return clone; + } + }); + }()); + + + return CryptoJS; + +})); + +/***/ }), +/* 16 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14)); + } + else {} +}(this, function (CryptoJS) { + + (function () { + // Check if typed arrays are supported + if (typeof ArrayBuffer != 'function') { + return; + } + + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + + // Reference original init + var superInit = WordArray.init; + + // Augment WordArray.init to handle typed arrays + var subInit = WordArray.init = function (typedArray) { + // Convert buffers to uint8 + if (typedArray instanceof ArrayBuffer) { + typedArray = new Uint8Array(typedArray); + } + + // Convert other array views to uint8 + if ( + typedArray instanceof Int8Array || + (typeof Uint8ClampedArray !== "undefined" && typedArray instanceof Uint8ClampedArray) || + typedArray instanceof Int16Array || + typedArray instanceof Uint16Array || + typedArray instanceof Int32Array || + typedArray instanceof Uint32Array || + typedArray instanceof Float32Array || + typedArray instanceof Float64Array + ) { + typedArray = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength); + } + + // Handle Uint8Array + if (typedArray instanceof Uint8Array) { + // Shortcut + var typedArrayByteLength = typedArray.byteLength; + + // Extract bytes + var words = []; + for (var i = 0; i < typedArrayByteLength; i++) { + words[i >>> 2] |= typedArray[i] << (24 - (i % 4) * 8); + } + + // Initialize this word array + superInit.call(this, words, typedArrayByteLength); + } else { + // Else call normal init + superInit.apply(this, arguments); + } + }; + + subInit.prototype = WordArray; + }()); + + + return CryptoJS.lib.WordArray; + +})); + +/***/ }), +/* 17 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14)); + } + else {} +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var C_enc = C.enc; + + /** + * UTF-16 BE encoding strategy. + */ + var Utf16BE = C_enc.Utf16 = C_enc.Utf16BE = { + /** + * Converts a word array to a UTF-16 BE string. + * + * @param {WordArray} wordArray The word array. + * + * @return {string} The UTF-16 BE string. + * + * @static + * + * @example + * + * var utf16String = CryptoJS.enc.Utf16.stringify(wordArray); + */ + stringify: function (wordArray) { + // Shortcuts + var words = wordArray.words; + var sigBytes = wordArray.sigBytes; + + // Convert + var utf16Chars = []; + for (var i = 0; i < sigBytes; i += 2) { + var codePoint = (words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff; + utf16Chars.push(String.fromCharCode(codePoint)); + } + + return utf16Chars.join(''); + }, + + /** + * Converts a UTF-16 BE string to a word array. + * + * @param {string} utf16Str The UTF-16 BE string. + * + * @return {WordArray} The word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.enc.Utf16.parse(utf16String); + */ + parse: function (utf16Str) { + // Shortcut + var utf16StrLength = utf16Str.length; + + // Convert + var words = []; + for (var i = 0; i < utf16StrLength; i++) { + words[i >>> 1] |= utf16Str.charCodeAt(i) << (16 - (i % 2) * 16); + } + + return WordArray.create(words, utf16StrLength * 2); + } + }; + + /** + * UTF-16 LE encoding strategy. + */ + C_enc.Utf16LE = { + /** + * Converts a word array to a UTF-16 LE string. + * + * @param {WordArray} wordArray The word array. + * + * @return {string} The UTF-16 LE string. + * + * @static + * + * @example + * + * var utf16Str = CryptoJS.enc.Utf16LE.stringify(wordArray); + */ + stringify: function (wordArray) { + // Shortcuts + var words = wordArray.words; + var sigBytes = wordArray.sigBytes; + + // Convert + var utf16Chars = []; + for (var i = 0; i < sigBytes; i += 2) { + var codePoint = swapEndian((words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff); + utf16Chars.push(String.fromCharCode(codePoint)); + } + + return utf16Chars.join(''); + }, + + /** + * Converts a UTF-16 LE string to a word array. + * + * @param {string} utf16Str The UTF-16 LE string. + * + * @return {WordArray} The word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.enc.Utf16LE.parse(utf16Str); + */ + parse: function (utf16Str) { + // Shortcut + var utf16StrLength = utf16Str.length; + + // Convert + var words = []; + for (var i = 0; i < utf16StrLength; i++) { + words[i >>> 1] |= swapEndian(utf16Str.charCodeAt(i) << (16 - (i % 2) * 16)); + } + + return WordArray.create(words, utf16StrLength * 2); + } + }; + + function swapEndian(word) { + return ((word << 8) & 0xff00ff00) | ((word >>> 8) & 0x00ff00ff); + } + }()); + + + return CryptoJS.enc.Utf16; + +})); + +/***/ }), +/* 18 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14)); + } + else {} +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var C_enc = C.enc; + + /** + * Base64 encoding strategy. + */ + var Base64 = C_enc.Base64 = { + /** + * Converts a word array to a Base64 string. + * + * @param {WordArray} wordArray The word array. + * + * @return {string} The Base64 string. + * + * @static + * + * @example + * + * var base64String = CryptoJS.enc.Base64.stringify(wordArray); + */ + stringify: function (wordArray) { + // Shortcuts + var words = wordArray.words; + var sigBytes = wordArray.sigBytes; + var map = this._map; + + // Clamp excess bits + wordArray.clamp(); + + // Convert + var base64Chars = []; + for (var i = 0; i < sigBytes; i += 3) { + var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; + var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff; + var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff; + + var triplet = (byte1 << 16) | (byte2 << 8) | byte3; + + for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) { + base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f)); + } + } + + // Add padding + var paddingChar = map.charAt(64); + if (paddingChar) { + while (base64Chars.length % 4) { + base64Chars.push(paddingChar); + } + } + + return base64Chars.join(''); + }, + + /** + * Converts a Base64 string to a word array. + * + * @param {string} base64Str The Base64 string. + * + * @return {WordArray} The word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.enc.Base64.parse(base64String); + */ + parse: function (base64Str) { + // Shortcuts + var base64StrLength = base64Str.length; + var map = this._map; + var reverseMap = this._reverseMap; + + if (!reverseMap) { + reverseMap = this._reverseMap = []; + for (var j = 0; j < map.length; j++) { + reverseMap[map.charCodeAt(j)] = j; + } + } + + // Ignore padding + var paddingChar = map.charAt(64); + if (paddingChar) { + var paddingIndex = base64Str.indexOf(paddingChar); + if (paddingIndex !== -1) { + base64StrLength = paddingIndex; + } + } + + // Convert + return parseLoop(base64Str, base64StrLength, reverseMap); + + }, + + _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=' + }; + + function parseLoop(base64Str, base64StrLength, reverseMap) { + var words = []; + var nBytes = 0; + for (var i = 0; i < base64StrLength; i++) { + if (i % 4) { + var bits1 = reverseMap[base64Str.charCodeAt(i - 1)] << ((i % 4) * 2); + var bits2 = reverseMap[base64Str.charCodeAt(i)] >>> (6 - (i % 4) * 2); + words[nBytes >>> 2] |= (bits1 | bits2) << (24 - (nBytes % 4) * 8); + nBytes++; + } + } + return WordArray.create(words, nBytes); + } + }()); + + + return CryptoJS.enc.Base64; + +})); + +/***/ }), +/* 19 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14)); + } + else {} +}(this, function (CryptoJS) { + + (function (Math) { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var Hasher = C_lib.Hasher; + var C_algo = C.algo; + + // Constants table + var T = []; + + // Compute constants + (function () { + for (var i = 0; i < 64; i++) { + T[i] = (Math.abs(Math.sin(i + 1)) * 0x100000000) | 0; + } + }()); + + /** + * MD5 hash algorithm. + */ + var MD5 = C_algo.MD5 = Hasher.extend({ + _doReset: function () { + this._hash = new WordArray.init([ + 0x67452301, 0xefcdab89, + 0x98badcfe, 0x10325476 + ]); + }, + + _doProcessBlock: function (M, offset) { + // Swap endian + for (var i = 0; i < 16; i++) { + // Shortcuts + var offset_i = offset + i; + var M_offset_i = M[offset_i]; + + M[offset_i] = ( + (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | + (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) + ); + } + + // Shortcuts + var H = this._hash.words; + + var M_offset_0 = M[offset + 0]; + var M_offset_1 = M[offset + 1]; + var M_offset_2 = M[offset + 2]; + var M_offset_3 = M[offset + 3]; + var M_offset_4 = M[offset + 4]; + var M_offset_5 = M[offset + 5]; + var M_offset_6 = M[offset + 6]; + var M_offset_7 = M[offset + 7]; + var M_offset_8 = M[offset + 8]; + var M_offset_9 = M[offset + 9]; + var M_offset_10 = M[offset + 10]; + var M_offset_11 = M[offset + 11]; + var M_offset_12 = M[offset + 12]; + var M_offset_13 = M[offset + 13]; + var M_offset_14 = M[offset + 14]; + var M_offset_15 = M[offset + 15]; + + // Working varialbes + var a = H[0]; + var b = H[1]; + var c = H[2]; + var d = H[3]; + + // Computation + a = FF(a, b, c, d, M_offset_0, 7, T[0]); + d = FF(d, a, b, c, M_offset_1, 12, T[1]); + c = FF(c, d, a, b, M_offset_2, 17, T[2]); + b = FF(b, c, d, a, M_offset_3, 22, T[3]); + a = FF(a, b, c, d, M_offset_4, 7, T[4]); + d = FF(d, a, b, c, M_offset_5, 12, T[5]); + c = FF(c, d, a, b, M_offset_6, 17, T[6]); + b = FF(b, c, d, a, M_offset_7, 22, T[7]); + a = FF(a, b, c, d, M_offset_8, 7, T[8]); + d = FF(d, a, b, c, M_offset_9, 12, T[9]); + c = FF(c, d, a, b, M_offset_10, 17, T[10]); + b = FF(b, c, d, a, M_offset_11, 22, T[11]); + a = FF(a, b, c, d, M_offset_12, 7, T[12]); + d = FF(d, a, b, c, M_offset_13, 12, T[13]); + c = FF(c, d, a, b, M_offset_14, 17, T[14]); + b = FF(b, c, d, a, M_offset_15, 22, T[15]); + + a = GG(a, b, c, d, M_offset_1, 5, T[16]); + d = GG(d, a, b, c, M_offset_6, 9, T[17]); + c = GG(c, d, a, b, M_offset_11, 14, T[18]); + b = GG(b, c, d, a, M_offset_0, 20, T[19]); + a = GG(a, b, c, d, M_offset_5, 5, T[20]); + d = GG(d, a, b, c, M_offset_10, 9, T[21]); + c = GG(c, d, a, b, M_offset_15, 14, T[22]); + b = GG(b, c, d, a, M_offset_4, 20, T[23]); + a = GG(a, b, c, d, M_offset_9, 5, T[24]); + d = GG(d, a, b, c, M_offset_14, 9, T[25]); + c = GG(c, d, a, b, M_offset_3, 14, T[26]); + b = GG(b, c, d, a, M_offset_8, 20, T[27]); + a = GG(a, b, c, d, M_offset_13, 5, T[28]); + d = GG(d, a, b, c, M_offset_2, 9, T[29]); + c = GG(c, d, a, b, M_offset_7, 14, T[30]); + b = GG(b, c, d, a, M_offset_12, 20, T[31]); + + a = HH(a, b, c, d, M_offset_5, 4, T[32]); + d = HH(d, a, b, c, M_offset_8, 11, T[33]); + c = HH(c, d, a, b, M_offset_11, 16, T[34]); + b = HH(b, c, d, a, M_offset_14, 23, T[35]); + a = HH(a, b, c, d, M_offset_1, 4, T[36]); + d = HH(d, a, b, c, M_offset_4, 11, T[37]); + c = HH(c, d, a, b, M_offset_7, 16, T[38]); + b = HH(b, c, d, a, M_offset_10, 23, T[39]); + a = HH(a, b, c, d, M_offset_13, 4, T[40]); + d = HH(d, a, b, c, M_offset_0, 11, T[41]); + c = HH(c, d, a, b, M_offset_3, 16, T[42]); + b = HH(b, c, d, a, M_offset_6, 23, T[43]); + a = HH(a, b, c, d, M_offset_9, 4, T[44]); + d = HH(d, a, b, c, M_offset_12, 11, T[45]); + c = HH(c, d, a, b, M_offset_15, 16, T[46]); + b = HH(b, c, d, a, M_offset_2, 23, T[47]); + + a = II(a, b, c, d, M_offset_0, 6, T[48]); + d = II(d, a, b, c, M_offset_7, 10, T[49]); + c = II(c, d, a, b, M_offset_14, 15, T[50]); + b = II(b, c, d, a, M_offset_5, 21, T[51]); + a = II(a, b, c, d, M_offset_12, 6, T[52]); + d = II(d, a, b, c, M_offset_3, 10, T[53]); + c = II(c, d, a, b, M_offset_10, 15, T[54]); + b = II(b, c, d, a, M_offset_1, 21, T[55]); + a = II(a, b, c, d, M_offset_8, 6, T[56]); + d = II(d, a, b, c, M_offset_15, 10, T[57]); + c = II(c, d, a, b, M_offset_6, 15, T[58]); + b = II(b, c, d, a, M_offset_13, 21, T[59]); + a = II(a, b, c, d, M_offset_4, 6, T[60]); + d = II(d, a, b, c, M_offset_11, 10, T[61]); + c = II(c, d, a, b, M_offset_2, 15, T[62]); + b = II(b, c, d, a, M_offset_9, 21, T[63]); + + // Intermediate hash value + H[0] = (H[0] + a) | 0; + H[1] = (H[1] + b) | 0; + H[2] = (H[2] + c) | 0; + H[3] = (H[3] + d) | 0; + }, + + _doFinalize: function () { + // Shortcuts + var data = this._data; + var dataWords = data.words; + + var nBitsTotal = this._nDataBytes * 8; + var nBitsLeft = data.sigBytes * 8; + + // Add padding + dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); + + var nBitsTotalH = Math.floor(nBitsTotal / 0x100000000); + var nBitsTotalL = nBitsTotal; + dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = ( + (((nBitsTotalH << 8) | (nBitsTotalH >>> 24)) & 0x00ff00ff) | + (((nBitsTotalH << 24) | (nBitsTotalH >>> 8)) & 0xff00ff00) + ); + dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( + (((nBitsTotalL << 8) | (nBitsTotalL >>> 24)) & 0x00ff00ff) | + (((nBitsTotalL << 24) | (nBitsTotalL >>> 8)) & 0xff00ff00) + ); + + data.sigBytes = (dataWords.length + 1) * 4; + + // Hash final blocks + this._process(); + + // Shortcuts + var hash = this._hash; + var H = hash.words; + + // Swap endian + for (var i = 0; i < 4; i++) { + // Shortcut + var H_i = H[i]; + + H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | + (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); + } + + // Return final computed hash + return hash; + }, + + clone: function () { + var clone = Hasher.clone.call(this); + clone._hash = this._hash.clone(); + + return clone; + } + }); + + function FF(a, b, c, d, x, s, t) { + var n = a + ((b & c) | (~b & d)) + x + t; + return ((n << s) | (n >>> (32 - s))) + b; + } + + function GG(a, b, c, d, x, s, t) { + var n = a + ((b & d) | (c & ~d)) + x + t; + return ((n << s) | (n >>> (32 - s))) + b; + } + + function HH(a, b, c, d, x, s, t) { + var n = a + (b ^ c ^ d) + x + t; + return ((n << s) | (n >>> (32 - s))) + b; + } + + function II(a, b, c, d, x, s, t) { + var n = a + (c ^ (b | ~d)) + x + t; + return ((n << s) | (n >>> (32 - s))) + b; + } + + /** + * Shortcut function to the hasher's object interface. + * + * @param {WordArray|string} message The message to hash. + * + * @return {WordArray} The hash. + * + * @static + * + * @example + * + * var hash = CryptoJS.MD5('message'); + * var hash = CryptoJS.MD5(wordArray); + */ + C.MD5 = Hasher._createHelper(MD5); + + /** + * Shortcut function to the HMAC's object interface. + * + * @param {WordArray|string} message The message to hash. + * @param {WordArray|string} key The secret key. + * + * @return {WordArray} The HMAC. + * + * @static + * + * @example + * + * var hmac = CryptoJS.HmacMD5(message, key); + */ + C.HmacMD5 = Hasher._createHmacHelper(MD5); + }(Math)); + + + return CryptoJS.MD5; + +})); + +/***/ }), +/* 20 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14)); + } + else {} +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var Hasher = C_lib.Hasher; + var C_algo = C.algo; + + // Reusable object + var W = []; + + /** + * SHA-1 hash algorithm. + */ + var SHA1 = C_algo.SHA1 = Hasher.extend({ + _doReset: function () { + this._hash = new WordArray.init([ + 0x67452301, 0xefcdab89, + 0x98badcfe, 0x10325476, + 0xc3d2e1f0 + ]); + }, + + _doProcessBlock: function (M, offset) { + // Shortcut + var H = this._hash.words; + + // Working variables + var a = H[0]; + var b = H[1]; + var c = H[2]; + var d = H[3]; + var e = H[4]; + + // Computation + for (var i = 0; i < 80; i++) { + if (i < 16) { + W[i] = M[offset + i] | 0; + } else { + var n = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; + W[i] = (n << 1) | (n >>> 31); + } + + var t = ((a << 5) | (a >>> 27)) + e + W[i]; + if (i < 20) { + t += ((b & c) | (~b & d)) + 0x5a827999; + } else if (i < 40) { + t += (b ^ c ^ d) + 0x6ed9eba1; + } else if (i < 60) { + t += ((b & c) | (b & d) | (c & d)) - 0x70e44324; + } else /* if (i < 80) */ { + t += (b ^ c ^ d) - 0x359d3e2a; + } + + e = d; + d = c; + c = (b << 30) | (b >>> 2); + b = a; + a = t; + } + + // Intermediate hash value + H[0] = (H[0] + a) | 0; + H[1] = (H[1] + b) | 0; + H[2] = (H[2] + c) | 0; + H[3] = (H[3] + d) | 0; + H[4] = (H[4] + e) | 0; + }, + + _doFinalize: function () { + // Shortcuts + var data = this._data; + var dataWords = data.words; + + var nBitsTotal = this._nDataBytes * 8; + var nBitsLeft = data.sigBytes * 8; + + // Add padding + dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); + dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000); + dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal; + data.sigBytes = dataWords.length * 4; + + // Hash final blocks + this._process(); + + // Return final computed hash + return this._hash; + }, + + clone: function () { + var clone = Hasher.clone.call(this); + clone._hash = this._hash.clone(); + + return clone; + } + }); + + /** + * Shortcut function to the hasher's object interface. + * + * @param {WordArray|string} message The message to hash. + * + * @return {WordArray} The hash. + * + * @static + * + * @example + * + * var hash = CryptoJS.SHA1('message'); + * var hash = CryptoJS.SHA1(wordArray); + */ + C.SHA1 = Hasher._createHelper(SHA1); + + /** + * Shortcut function to the HMAC's object interface. + * + * @param {WordArray|string} message The message to hash. + * @param {WordArray|string} key The secret key. + * + * @return {WordArray} The HMAC. + * + * @static + * + * @example + * + * var hmac = CryptoJS.HmacSHA1(message, key); + */ + C.HmacSHA1 = Hasher._createHmacHelper(SHA1); + }()); + + + return CryptoJS.SHA1; + +})); + +/***/ }), +/* 21 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14)); + } + else {} +}(this, function (CryptoJS) { + + (function (Math) { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var Hasher = C_lib.Hasher; + var C_algo = C.algo; + + // Initialization and round constants tables + var H = []; + var K = []; + + // Compute constants + (function () { + function isPrime(n) { + var sqrtN = Math.sqrt(n); + for (var factor = 2; factor <= sqrtN; factor++) { + if (!(n % factor)) { + return false; + } + } + + return true; + } + + function getFractionalBits(n) { + return ((n - (n | 0)) * 0x100000000) | 0; + } + + var n = 2; + var nPrime = 0; + while (nPrime < 64) { + if (isPrime(n)) { + if (nPrime < 8) { + H[nPrime] = getFractionalBits(Math.pow(n, 1 / 2)); + } + K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3)); + + nPrime++; + } + + n++; + } + }()); + + // Reusable object + var W = []; + + /** + * SHA-256 hash algorithm. + */ + var SHA256 = C_algo.SHA256 = Hasher.extend({ + _doReset: function () { + this._hash = new WordArray.init(H.slice(0)); + }, + + _doProcessBlock: function (M, offset) { + // Shortcut + var H = this._hash.words; + + // Working variables + var a = H[0]; + var b = H[1]; + var c = H[2]; + var d = H[3]; + var e = H[4]; + var f = H[5]; + var g = H[6]; + var h = H[7]; + + // Computation + for (var i = 0; i < 64; i++) { + if (i < 16) { + W[i] = M[offset + i] | 0; + } else { + var gamma0x = W[i - 15]; + var gamma0 = ((gamma0x << 25) | (gamma0x >>> 7)) ^ + ((gamma0x << 14) | (gamma0x >>> 18)) ^ + (gamma0x >>> 3); + + var gamma1x = W[i - 2]; + var gamma1 = ((gamma1x << 15) | (gamma1x >>> 17)) ^ + ((gamma1x << 13) | (gamma1x >>> 19)) ^ + (gamma1x >>> 10); + + W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]; + } + + var ch = (e & f) ^ (~e & g); + var maj = (a & b) ^ (a & c) ^ (b & c); + + var sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22)); + var sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7) | (e >>> 25)); + + var t1 = h + sigma1 + ch + K[i] + W[i]; + var t2 = sigma0 + maj; + + h = g; + g = f; + f = e; + e = (d + t1) | 0; + d = c; + c = b; + b = a; + a = (t1 + t2) | 0; + } + + // Intermediate hash value + H[0] = (H[0] + a) | 0; + H[1] = (H[1] + b) | 0; + H[2] = (H[2] + c) | 0; + H[3] = (H[3] + d) | 0; + H[4] = (H[4] + e) | 0; + H[5] = (H[5] + f) | 0; + H[6] = (H[6] + g) | 0; + H[7] = (H[7] + h) | 0; + }, + + _doFinalize: function () { + // Shortcuts + var data = this._data; + var dataWords = data.words; + + var nBitsTotal = this._nDataBytes * 8; + var nBitsLeft = data.sigBytes * 8; + + // Add padding + dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); + dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000); + dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal; + data.sigBytes = dataWords.length * 4; + + // Hash final blocks + this._process(); + + // Return final computed hash + return this._hash; + }, + + clone: function () { + var clone = Hasher.clone.call(this); + clone._hash = this._hash.clone(); + + return clone; + } + }); + + /** + * Shortcut function to the hasher's object interface. + * + * @param {WordArray|string} message The message to hash. + * + * @return {WordArray} The hash. + * + * @static + * + * @example + * + * var hash = CryptoJS.SHA256('message'); + * var hash = CryptoJS.SHA256(wordArray); + */ + C.SHA256 = Hasher._createHelper(SHA256); + + /** + * Shortcut function to the HMAC's object interface. + * + * @param {WordArray|string} message The message to hash. + * @param {WordArray|string} key The secret key. + * + * @return {WordArray} The HMAC. + * + * @static + * + * @example + * + * var hmac = CryptoJS.HmacSHA256(message, key); + */ + C.HmacSHA256 = Hasher._createHmacHelper(SHA256); + }(Math)); + + + return CryptoJS.SHA256; + +})); + +/***/ }), +/* 22 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory, undef) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14), __webpack_require__(21)); + } + else {} +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var C_algo = C.algo; + var SHA256 = C_algo.SHA256; + + /** + * SHA-224 hash algorithm. + */ + var SHA224 = C_algo.SHA224 = SHA256.extend({ + _doReset: function () { + this._hash = new WordArray.init([ + 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, + 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 + ]); + }, + + _doFinalize: function () { + var hash = SHA256._doFinalize.call(this); + + hash.sigBytes -= 4; + + return hash; + } + }); + + /** + * Shortcut function to the hasher's object interface. + * + * @param {WordArray|string} message The message to hash. + * + * @return {WordArray} The hash. + * + * @static + * + * @example + * + * var hash = CryptoJS.SHA224('message'); + * var hash = CryptoJS.SHA224(wordArray); + */ + C.SHA224 = SHA256._createHelper(SHA224); + + /** + * Shortcut function to the HMAC's object interface. + * + * @param {WordArray|string} message The message to hash. + * @param {WordArray|string} key The secret key. + * + * @return {WordArray} The HMAC. + * + * @static + * + * @example + * + * var hmac = CryptoJS.HmacSHA224(message, key); + */ + C.HmacSHA224 = SHA256._createHmacHelper(SHA224); + }()); + + + return CryptoJS.SHA224; + +})); + +/***/ }), +/* 23 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory, undef) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14), __webpack_require__(15)); + } + else {} +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var Hasher = C_lib.Hasher; + var C_x64 = C.x64; + var X64Word = C_x64.Word; + var X64WordArray = C_x64.WordArray; + var C_algo = C.algo; + + function X64Word_create() { + return X64Word.create.apply(X64Word, arguments); + } + + // Constants + var K = [ + X64Word_create(0x428a2f98, 0xd728ae22), X64Word_create(0x71374491, 0x23ef65cd), + X64Word_create(0xb5c0fbcf, 0xec4d3b2f), X64Word_create(0xe9b5dba5, 0x8189dbbc), + X64Word_create(0x3956c25b, 0xf348b538), X64Word_create(0x59f111f1, 0xb605d019), + X64Word_create(0x923f82a4, 0xaf194f9b), X64Word_create(0xab1c5ed5, 0xda6d8118), + X64Word_create(0xd807aa98, 0xa3030242), X64Word_create(0x12835b01, 0x45706fbe), + X64Word_create(0x243185be, 0x4ee4b28c), X64Word_create(0x550c7dc3, 0xd5ffb4e2), + X64Word_create(0x72be5d74, 0xf27b896f), X64Word_create(0x80deb1fe, 0x3b1696b1), + X64Word_create(0x9bdc06a7, 0x25c71235), X64Word_create(0xc19bf174, 0xcf692694), + X64Word_create(0xe49b69c1, 0x9ef14ad2), X64Word_create(0xefbe4786, 0x384f25e3), + X64Word_create(0x0fc19dc6, 0x8b8cd5b5), X64Word_create(0x240ca1cc, 0x77ac9c65), + X64Word_create(0x2de92c6f, 0x592b0275), X64Word_create(0x4a7484aa, 0x6ea6e483), + X64Word_create(0x5cb0a9dc, 0xbd41fbd4), X64Word_create(0x76f988da, 0x831153b5), + X64Word_create(0x983e5152, 0xee66dfab), X64Word_create(0xa831c66d, 0x2db43210), + X64Word_create(0xb00327c8, 0x98fb213f), X64Word_create(0xbf597fc7, 0xbeef0ee4), + X64Word_create(0xc6e00bf3, 0x3da88fc2), X64Word_create(0xd5a79147, 0x930aa725), + X64Word_create(0x06ca6351, 0xe003826f), X64Word_create(0x14292967, 0x0a0e6e70), + X64Word_create(0x27b70a85, 0x46d22ffc), X64Word_create(0x2e1b2138, 0x5c26c926), + X64Word_create(0x4d2c6dfc, 0x5ac42aed), X64Word_create(0x53380d13, 0x9d95b3df), + X64Word_create(0x650a7354, 0x8baf63de), X64Word_create(0x766a0abb, 0x3c77b2a8), + X64Word_create(0x81c2c92e, 0x47edaee6), X64Word_create(0x92722c85, 0x1482353b), + X64Word_create(0xa2bfe8a1, 0x4cf10364), X64Word_create(0xa81a664b, 0xbc423001), + X64Word_create(0xc24b8b70, 0xd0f89791), X64Word_create(0xc76c51a3, 0x0654be30), + X64Word_create(0xd192e819, 0xd6ef5218), X64Word_create(0xd6990624, 0x5565a910), + X64Word_create(0xf40e3585, 0x5771202a), X64Word_create(0x106aa070, 0x32bbd1b8), + X64Word_create(0x19a4c116, 0xb8d2d0c8), X64Word_create(0x1e376c08, 0x5141ab53), + X64Word_create(0x2748774c, 0xdf8eeb99), X64Word_create(0x34b0bcb5, 0xe19b48a8), + X64Word_create(0x391c0cb3, 0xc5c95a63), X64Word_create(0x4ed8aa4a, 0xe3418acb), + X64Word_create(0x5b9cca4f, 0x7763e373), X64Word_create(0x682e6ff3, 0xd6b2b8a3), + X64Word_create(0x748f82ee, 0x5defb2fc), X64Word_create(0x78a5636f, 0x43172f60), + X64Word_create(0x84c87814, 0xa1f0ab72), X64Word_create(0x8cc70208, 0x1a6439ec), + X64Word_create(0x90befffa, 0x23631e28), X64Word_create(0xa4506ceb, 0xde82bde9), + X64Word_create(0xbef9a3f7, 0xb2c67915), X64Word_create(0xc67178f2, 0xe372532b), + X64Word_create(0xca273ece, 0xea26619c), X64Word_create(0xd186b8c7, 0x21c0c207), + X64Word_create(0xeada7dd6, 0xcde0eb1e), X64Word_create(0xf57d4f7f, 0xee6ed178), + X64Word_create(0x06f067aa, 0x72176fba), X64Word_create(0x0a637dc5, 0xa2c898a6), + X64Word_create(0x113f9804, 0xbef90dae), X64Word_create(0x1b710b35, 0x131c471b), + X64Word_create(0x28db77f5, 0x23047d84), X64Word_create(0x32caab7b, 0x40c72493), + X64Word_create(0x3c9ebe0a, 0x15c9bebc), X64Word_create(0x431d67c4, 0x9c100d4c), + X64Word_create(0x4cc5d4be, 0xcb3e42b6), X64Word_create(0x597f299c, 0xfc657e2a), + X64Word_create(0x5fcb6fab, 0x3ad6faec), X64Word_create(0x6c44198c, 0x4a475817) + ]; + + // Reusable objects + var W = []; + (function () { + for (var i = 0; i < 80; i++) { + W[i] = X64Word_create(); + } + }()); + + /** + * SHA-512 hash algorithm. + */ + var SHA512 = C_algo.SHA512 = Hasher.extend({ + _doReset: function () { + this._hash = new X64WordArray.init([ + new X64Word.init(0x6a09e667, 0xf3bcc908), new X64Word.init(0xbb67ae85, 0x84caa73b), + new X64Word.init(0x3c6ef372, 0xfe94f82b), new X64Word.init(0xa54ff53a, 0x5f1d36f1), + new X64Word.init(0x510e527f, 0xade682d1), new X64Word.init(0x9b05688c, 0x2b3e6c1f), + new X64Word.init(0x1f83d9ab, 0xfb41bd6b), new X64Word.init(0x5be0cd19, 0x137e2179) + ]); + }, + + _doProcessBlock: function (M, offset) { + // Shortcuts + var H = this._hash.words; + + var H0 = H[0]; + var H1 = H[1]; + var H2 = H[2]; + var H3 = H[3]; + var H4 = H[4]; + var H5 = H[5]; + var H6 = H[6]; + var H7 = H[7]; + + var H0h = H0.high; + var H0l = H0.low; + var H1h = H1.high; + var H1l = H1.low; + var H2h = H2.high; + var H2l = H2.low; + var H3h = H3.high; + var H3l = H3.low; + var H4h = H4.high; + var H4l = H4.low; + var H5h = H5.high; + var H5l = H5.low; + var H6h = H6.high; + var H6l = H6.low; + var H7h = H7.high; + var H7l = H7.low; + + // Working variables + var ah = H0h; + var al = H0l; + var bh = H1h; + var bl = H1l; + var ch = H2h; + var cl = H2l; + var dh = H3h; + var dl = H3l; + var eh = H4h; + var el = H4l; + var fh = H5h; + var fl = H5l; + var gh = H6h; + var gl = H6l; + var hh = H7h; + var hl = H7l; + + // Rounds + for (var i = 0; i < 80; i++) { + // Shortcut + var Wi = W[i]; + + // Extend message + if (i < 16) { + var Wih = Wi.high = M[offset + i * 2] | 0; + var Wil = Wi.low = M[offset + i * 2 + 1] | 0; + } else { + // Gamma0 + var gamma0x = W[i - 15]; + var gamma0xh = gamma0x.high; + var gamma0xl = gamma0x.low; + var gamma0h = ((gamma0xh >>> 1) | (gamma0xl << 31)) ^ ((gamma0xh >>> 8) | (gamma0xl << 24)) ^ (gamma0xh >>> 7); + var gamma0l = ((gamma0xl >>> 1) | (gamma0xh << 31)) ^ ((gamma0xl >>> 8) | (gamma0xh << 24)) ^ ((gamma0xl >>> 7) | (gamma0xh << 25)); + + // Gamma1 + var gamma1x = W[i - 2]; + var gamma1xh = gamma1x.high; + var gamma1xl = gamma1x.low; + var gamma1h = ((gamma1xh >>> 19) | (gamma1xl << 13)) ^ ((gamma1xh << 3) | (gamma1xl >>> 29)) ^ (gamma1xh >>> 6); + var gamma1l = ((gamma1xl >>> 19) | (gamma1xh << 13)) ^ ((gamma1xl << 3) | (gamma1xh >>> 29)) ^ ((gamma1xl >>> 6) | (gamma1xh << 26)); + + // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] + var Wi7 = W[i - 7]; + var Wi7h = Wi7.high; + var Wi7l = Wi7.low; + + var Wi16 = W[i - 16]; + var Wi16h = Wi16.high; + var Wi16l = Wi16.low; + + var Wil = gamma0l + Wi7l; + var Wih = gamma0h + Wi7h + ((Wil >>> 0) < (gamma0l >>> 0) ? 1 : 0); + var Wil = Wil + gamma1l; + var Wih = Wih + gamma1h + ((Wil >>> 0) < (gamma1l >>> 0) ? 1 : 0); + var Wil = Wil + Wi16l; + var Wih = Wih + Wi16h + ((Wil >>> 0) < (Wi16l >>> 0) ? 1 : 0); + + Wi.high = Wih; + Wi.low = Wil; + } + + var chh = (eh & fh) ^ (~eh & gh); + var chl = (el & fl) ^ (~el & gl); + var majh = (ah & bh) ^ (ah & ch) ^ (bh & ch); + var majl = (al & bl) ^ (al & cl) ^ (bl & cl); + + var sigma0h = ((ah >>> 28) | (al << 4)) ^ ((ah << 30) | (al >>> 2)) ^ ((ah << 25) | (al >>> 7)); + var sigma0l = ((al >>> 28) | (ah << 4)) ^ ((al << 30) | (ah >>> 2)) ^ ((al << 25) | (ah >>> 7)); + var sigma1h = ((eh >>> 14) | (el << 18)) ^ ((eh >>> 18) | (el << 14)) ^ ((eh << 23) | (el >>> 9)); + var sigma1l = ((el >>> 14) | (eh << 18)) ^ ((el >>> 18) | (eh << 14)) ^ ((el << 23) | (eh >>> 9)); + + // t1 = h + sigma1 + ch + K[i] + W[i] + var Ki = K[i]; + var Kih = Ki.high; + var Kil = Ki.low; + + var t1l = hl + sigma1l; + var t1h = hh + sigma1h + ((t1l >>> 0) < (hl >>> 0) ? 1 : 0); + var t1l = t1l + chl; + var t1h = t1h + chh + ((t1l >>> 0) < (chl >>> 0) ? 1 : 0); + var t1l = t1l + Kil; + var t1h = t1h + Kih + ((t1l >>> 0) < (Kil >>> 0) ? 1 : 0); + var t1l = t1l + Wil; + var t1h = t1h + Wih + ((t1l >>> 0) < (Wil >>> 0) ? 1 : 0); + + // t2 = sigma0 + maj + var t2l = sigma0l + majl; + var t2h = sigma0h + majh + ((t2l >>> 0) < (sigma0l >>> 0) ? 1 : 0); + + // Update working variables + hh = gh; + hl = gl; + gh = fh; + gl = fl; + fh = eh; + fl = el; + el = (dl + t1l) | 0; + eh = (dh + t1h + ((el >>> 0) < (dl >>> 0) ? 1 : 0)) | 0; + dh = ch; + dl = cl; + ch = bh; + cl = bl; + bh = ah; + bl = al; + al = (t1l + t2l) | 0; + ah = (t1h + t2h + ((al >>> 0) < (t1l >>> 0) ? 1 : 0)) | 0; + } + + // Intermediate hash value + H0l = H0.low = (H0l + al); + H0.high = (H0h + ah + ((H0l >>> 0) < (al >>> 0) ? 1 : 0)); + H1l = H1.low = (H1l + bl); + H1.high = (H1h + bh + ((H1l >>> 0) < (bl >>> 0) ? 1 : 0)); + H2l = H2.low = (H2l + cl); + H2.high = (H2h + ch + ((H2l >>> 0) < (cl >>> 0) ? 1 : 0)); + H3l = H3.low = (H3l + dl); + H3.high = (H3h + dh + ((H3l >>> 0) < (dl >>> 0) ? 1 : 0)); + H4l = H4.low = (H4l + el); + H4.high = (H4h + eh + ((H4l >>> 0) < (el >>> 0) ? 1 : 0)); + H5l = H5.low = (H5l + fl); + H5.high = (H5h + fh + ((H5l >>> 0) < (fl >>> 0) ? 1 : 0)); + H6l = H6.low = (H6l + gl); + H6.high = (H6h + gh + ((H6l >>> 0) < (gl >>> 0) ? 1 : 0)); + H7l = H7.low = (H7l + hl); + H7.high = (H7h + hh + ((H7l >>> 0) < (hl >>> 0) ? 1 : 0)); + }, + + _doFinalize: function () { + // Shortcuts + var data = this._data; + var dataWords = data.words; + + var nBitsTotal = this._nDataBytes * 8; + var nBitsLeft = data.sigBytes * 8; + + // Add padding + dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); + dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 30] = Math.floor(nBitsTotal / 0x100000000); + dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 31] = nBitsTotal; + data.sigBytes = dataWords.length * 4; + + // Hash final blocks + this._process(); + + // Convert hash to 32-bit word array before returning + var hash = this._hash.toX32(); + + // Return final computed hash + return hash; + }, + + clone: function () { + var clone = Hasher.clone.call(this); + clone._hash = this._hash.clone(); + + return clone; + }, + + blockSize: 1024/32 + }); + + /** + * Shortcut function to the hasher's object interface. + * + * @param {WordArray|string} message The message to hash. + * + * @return {WordArray} The hash. + * + * @static + * + * @example + * + * var hash = CryptoJS.SHA512('message'); + * var hash = CryptoJS.SHA512(wordArray); + */ + C.SHA512 = Hasher._createHelper(SHA512); + + /** + * Shortcut function to the HMAC's object interface. + * + * @param {WordArray|string} message The message to hash. + * @param {WordArray|string} key The secret key. + * + * @return {WordArray} The HMAC. + * + * @static + * + * @example + * + * var hmac = CryptoJS.HmacSHA512(message, key); + */ + C.HmacSHA512 = Hasher._createHmacHelper(SHA512); + }()); + + + return CryptoJS.SHA512; + +})); + +/***/ }), +/* 24 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory, undef) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14), __webpack_require__(15), __webpack_require__(23)); + } + else {} +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_x64 = C.x64; + var X64Word = C_x64.Word; + var X64WordArray = C_x64.WordArray; + var C_algo = C.algo; + var SHA512 = C_algo.SHA512; + + /** + * SHA-384 hash algorithm. + */ + var SHA384 = C_algo.SHA384 = SHA512.extend({ + _doReset: function () { + this._hash = new X64WordArray.init([ + new X64Word.init(0xcbbb9d5d, 0xc1059ed8), new X64Word.init(0x629a292a, 0x367cd507), + new X64Word.init(0x9159015a, 0x3070dd17), new X64Word.init(0x152fecd8, 0xf70e5939), + new X64Word.init(0x67332667, 0xffc00b31), new X64Word.init(0x8eb44a87, 0x68581511), + new X64Word.init(0xdb0c2e0d, 0x64f98fa7), new X64Word.init(0x47b5481d, 0xbefa4fa4) + ]); + }, + + _doFinalize: function () { + var hash = SHA512._doFinalize.call(this); + + hash.sigBytes -= 16; + + return hash; + } + }); + + /** + * Shortcut function to the hasher's object interface. + * + * @param {WordArray|string} message The message to hash. + * + * @return {WordArray} The hash. + * + * @static + * + * @example + * + * var hash = CryptoJS.SHA384('message'); + * var hash = CryptoJS.SHA384(wordArray); + */ + C.SHA384 = SHA512._createHelper(SHA384); + + /** + * Shortcut function to the HMAC's object interface. + * + * @param {WordArray|string} message The message to hash. + * @param {WordArray|string} key The secret key. + * + * @return {WordArray} The HMAC. + * + * @static + * + * @example + * + * var hmac = CryptoJS.HmacSHA384(message, key); + */ + C.HmacSHA384 = SHA512._createHmacHelper(SHA384); + }()); + + + return CryptoJS.SHA384; + +})); + +/***/ }), +/* 25 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory, undef) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14), __webpack_require__(15)); + } + else {} +}(this, function (CryptoJS) { + + (function (Math) { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var Hasher = C_lib.Hasher; + var C_x64 = C.x64; + var X64Word = C_x64.Word; + var C_algo = C.algo; + + // Constants tables + var RHO_OFFSETS = []; + var PI_INDEXES = []; + var ROUND_CONSTANTS = []; + + // Compute Constants + (function () { + // Compute rho offset constants + var x = 1, y = 0; + for (var t = 0; t < 24; t++) { + RHO_OFFSETS[x + 5 * y] = ((t + 1) * (t + 2) / 2) % 64; + + var newX = y % 5; + var newY = (2 * x + 3 * y) % 5; + x = newX; + y = newY; + } + + // Compute pi index constants + for (var x = 0; x < 5; x++) { + for (var y = 0; y < 5; y++) { + PI_INDEXES[x + 5 * y] = y + ((2 * x + 3 * y) % 5) * 5; + } + } + + // Compute round constants + var LFSR = 0x01; + for (var i = 0; i < 24; i++) { + var roundConstantMsw = 0; + var roundConstantLsw = 0; + + for (var j = 0; j < 7; j++) { + if (LFSR & 0x01) { + var bitPosition = (1 << j) - 1; + if (bitPosition < 32) { + roundConstantLsw ^= 1 << bitPosition; + } else /* if (bitPosition >= 32) */ { + roundConstantMsw ^= 1 << (bitPosition - 32); + } + } + + // Compute next LFSR + if (LFSR & 0x80) { + // Primitive polynomial over GF(2): x^8 + x^6 + x^5 + x^4 + 1 + LFSR = (LFSR << 1) ^ 0x71; + } else { + LFSR <<= 1; + } + } + + ROUND_CONSTANTS[i] = X64Word.create(roundConstantMsw, roundConstantLsw); + } + }()); + + // Reusable objects for temporary values + var T = []; + (function () { + for (var i = 0; i < 25; i++) { + T[i] = X64Word.create(); + } + }()); + + /** + * SHA-3 hash algorithm. + */ + var SHA3 = C_algo.SHA3 = Hasher.extend({ + /** + * Configuration options. + * + * @property {number} outputLength + * The desired number of bits in the output hash. + * Only values permitted are: 224, 256, 384, 512. + * Default: 512 + */ + cfg: Hasher.cfg.extend({ + outputLength: 512 + }), + + _doReset: function () { + var state = this._state = [] + for (var i = 0; i < 25; i++) { + state[i] = new X64Word.init(); + } + + this.blockSize = (1600 - 2 * this.cfg.outputLength) / 32; + }, + + _doProcessBlock: function (M, offset) { + // Shortcuts + var state = this._state; + var nBlockSizeLanes = this.blockSize / 2; + + // Absorb + for (var i = 0; i < nBlockSizeLanes; i++) { + // Shortcuts + var M2i = M[offset + 2 * i]; + var M2i1 = M[offset + 2 * i + 1]; + + // Swap endian + M2i = ( + (((M2i << 8) | (M2i >>> 24)) & 0x00ff00ff) | + (((M2i << 24) | (M2i >>> 8)) & 0xff00ff00) + ); + M2i1 = ( + (((M2i1 << 8) | (M2i1 >>> 24)) & 0x00ff00ff) | + (((M2i1 << 24) | (M2i1 >>> 8)) & 0xff00ff00) + ); + + // Absorb message into state + var lane = state[i]; + lane.high ^= M2i1; + lane.low ^= M2i; + } + + // Rounds + for (var round = 0; round < 24; round++) { + // Theta + for (var x = 0; x < 5; x++) { + // Mix column lanes + var tMsw = 0, tLsw = 0; + for (var y = 0; y < 5; y++) { + var lane = state[x + 5 * y]; + tMsw ^= lane.high; + tLsw ^= lane.low; + } + + // Temporary values + var Tx = T[x]; + Tx.high = tMsw; + Tx.low = tLsw; + } + for (var x = 0; x < 5; x++) { + // Shortcuts + var Tx4 = T[(x + 4) % 5]; + var Tx1 = T[(x + 1) % 5]; + var Tx1Msw = Tx1.high; + var Tx1Lsw = Tx1.low; + + // Mix surrounding columns + var tMsw = Tx4.high ^ ((Tx1Msw << 1) | (Tx1Lsw >>> 31)); + var tLsw = Tx4.low ^ ((Tx1Lsw << 1) | (Tx1Msw >>> 31)); + for (var y = 0; y < 5; y++) { + var lane = state[x + 5 * y]; + lane.high ^= tMsw; + lane.low ^= tLsw; + } + } + + // Rho Pi + for (var laneIndex = 1; laneIndex < 25; laneIndex++) { + // Shortcuts + var lane = state[laneIndex]; + var laneMsw = lane.high; + var laneLsw = lane.low; + var rhoOffset = RHO_OFFSETS[laneIndex]; + + // Rotate lanes + if (rhoOffset < 32) { + var tMsw = (laneMsw << rhoOffset) | (laneLsw >>> (32 - rhoOffset)); + var tLsw = (laneLsw << rhoOffset) | (laneMsw >>> (32 - rhoOffset)); + } else /* if (rhoOffset >= 32) */ { + var tMsw = (laneLsw << (rhoOffset - 32)) | (laneMsw >>> (64 - rhoOffset)); + var tLsw = (laneMsw << (rhoOffset - 32)) | (laneLsw >>> (64 - rhoOffset)); + } + + // Transpose lanes + var TPiLane = T[PI_INDEXES[laneIndex]]; + TPiLane.high = tMsw; + TPiLane.low = tLsw; + } + + // Rho pi at x = y = 0 + var T0 = T[0]; + var state0 = state[0]; + T0.high = state0.high; + T0.low = state0.low; + + // Chi + for (var x = 0; x < 5; x++) { + for (var y = 0; y < 5; y++) { + // Shortcuts + var laneIndex = x + 5 * y; + var lane = state[laneIndex]; + var TLane = T[laneIndex]; + var Tx1Lane = T[((x + 1) % 5) + 5 * y]; + var Tx2Lane = T[((x + 2) % 5) + 5 * y]; + + // Mix rows + lane.high = TLane.high ^ (~Tx1Lane.high & Tx2Lane.high); + lane.low = TLane.low ^ (~Tx1Lane.low & Tx2Lane.low); + } + } + + // Iota + var lane = state[0]; + var roundConstant = ROUND_CONSTANTS[round]; + lane.high ^= roundConstant.high; + lane.low ^= roundConstant.low;; + } + }, + + _doFinalize: function () { + // Shortcuts + var data = this._data; + var dataWords = data.words; + var nBitsTotal = this._nDataBytes * 8; + var nBitsLeft = data.sigBytes * 8; + var blockSizeBits = this.blockSize * 32; + + // Add padding + dataWords[nBitsLeft >>> 5] |= 0x1 << (24 - nBitsLeft % 32); + dataWords[((Math.ceil((nBitsLeft + 1) / blockSizeBits) * blockSizeBits) >>> 5) - 1] |= 0x80; + data.sigBytes = dataWords.length * 4; + + // Hash final blocks + this._process(); + + // Shortcuts + var state = this._state; + var outputLengthBytes = this.cfg.outputLength / 8; + var outputLengthLanes = outputLengthBytes / 8; + + // Squeeze + var hashWords = []; + for (var i = 0; i < outputLengthLanes; i++) { + // Shortcuts + var lane = state[i]; + var laneMsw = lane.high; + var laneLsw = lane.low; + + // Swap endian + laneMsw = ( + (((laneMsw << 8) | (laneMsw >>> 24)) & 0x00ff00ff) | + (((laneMsw << 24) | (laneMsw >>> 8)) & 0xff00ff00) + ); + laneLsw = ( + (((laneLsw << 8) | (laneLsw >>> 24)) & 0x00ff00ff) | + (((laneLsw << 24) | (laneLsw >>> 8)) & 0xff00ff00) + ); + + // Squeeze state to retrieve hash + hashWords.push(laneLsw); + hashWords.push(laneMsw); + } + + // Return final computed hash + return new WordArray.init(hashWords, outputLengthBytes); + }, + + clone: function () { + var clone = Hasher.clone.call(this); + + var state = clone._state = this._state.slice(0); + for (var i = 0; i < 25; i++) { + state[i] = state[i].clone(); + } + + return clone; + } + }); + + /** + * Shortcut function to the hasher's object interface. + * + * @param {WordArray|string} message The message to hash. + * + * @return {WordArray} The hash. + * + * @static + * + * @example + * + * var hash = CryptoJS.SHA3('message'); + * var hash = CryptoJS.SHA3(wordArray); + */ + C.SHA3 = Hasher._createHelper(SHA3); + + /** + * Shortcut function to the HMAC's object interface. + * + * @param {WordArray|string} message The message to hash. + * @param {WordArray|string} key The secret key. + * + * @return {WordArray} The HMAC. + * + * @static + * + * @example + * + * var hmac = CryptoJS.HmacSHA3(message, key); + */ + C.HmacSHA3 = Hasher._createHmacHelper(SHA3); + }(Math)); + + + return CryptoJS.SHA3; + +})); + +/***/ }), +/* 26 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14)); + } + else {} +}(this, function (CryptoJS) { + + /** @preserve + (c) 2012 by Cédric Mesnil. All rights reserved. + + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + + (function (Math) { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var Hasher = C_lib.Hasher; + var C_algo = C.algo; + + // Constants table + var _zl = WordArray.create([ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, + 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, + 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, + 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13]); + var _zr = WordArray.create([ + 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, + 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, + 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, + 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, + 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11]); + var _sl = WordArray.create([ + 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, + 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, + 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, + 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, + 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 ]); + var _sr = WordArray.create([ + 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, + 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, + 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, + 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, + 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ]); + + var _hl = WordArray.create([ 0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E]); + var _hr = WordArray.create([ 0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000]); + + /** + * RIPEMD160 hash algorithm. + */ + var RIPEMD160 = C_algo.RIPEMD160 = Hasher.extend({ + _doReset: function () { + this._hash = WordArray.create([0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]); + }, + + _doProcessBlock: function (M, offset) { + + // Swap endian + for (var i = 0; i < 16; i++) { + // Shortcuts + var offset_i = offset + i; + var M_offset_i = M[offset_i]; + + // Swap + M[offset_i] = ( + (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | + (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) + ); + } + // Shortcut + var H = this._hash.words; + var hl = _hl.words; + var hr = _hr.words; + var zl = _zl.words; + var zr = _zr.words; + var sl = _sl.words; + var sr = _sr.words; + + // Working variables + var al, bl, cl, dl, el; + var ar, br, cr, dr, er; + + ar = al = H[0]; + br = bl = H[1]; + cr = cl = H[2]; + dr = dl = H[3]; + er = el = H[4]; + // Computation + var t; + for (var i = 0; i < 80; i += 1) { + t = (al + M[offset+zl[i]])|0; + if (i<16){ + t += f1(bl,cl,dl) + hl[0]; + } else if (i<32) { + t += f2(bl,cl,dl) + hl[1]; + } else if (i<48) { + t += f3(bl,cl,dl) + hl[2]; + } else if (i<64) { + t += f4(bl,cl,dl) + hl[3]; + } else {// if (i<80) { + t += f5(bl,cl,dl) + hl[4]; + } + t = t|0; + t = rotl(t,sl[i]); + t = (t+el)|0; + al = el; + el = dl; + dl = rotl(cl, 10); + cl = bl; + bl = t; + + t = (ar + M[offset+zr[i]])|0; + if (i<16){ + t += f5(br,cr,dr) + hr[0]; + } else if (i<32) { + t += f4(br,cr,dr) + hr[1]; + } else if (i<48) { + t += f3(br,cr,dr) + hr[2]; + } else if (i<64) { + t += f2(br,cr,dr) + hr[3]; + } else {// if (i<80) { + t += f1(br,cr,dr) + hr[4]; + } + t = t|0; + t = rotl(t,sr[i]) ; + t = (t+er)|0; + ar = er; + er = dr; + dr = rotl(cr, 10); + cr = br; + br = t; + } + // Intermediate hash value + t = (H[1] + cl + dr)|0; + H[1] = (H[2] + dl + er)|0; + H[2] = (H[3] + el + ar)|0; + H[3] = (H[4] + al + br)|0; + H[4] = (H[0] + bl + cr)|0; + H[0] = t; + }, + + _doFinalize: function () { + // Shortcuts + var data = this._data; + var dataWords = data.words; + + var nBitsTotal = this._nDataBytes * 8; + var nBitsLeft = data.sigBytes * 8; + + // Add padding + dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); + dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( + (((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) | + (((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00) + ); + data.sigBytes = (dataWords.length + 1) * 4; + + // Hash final blocks + this._process(); + + // Shortcuts + var hash = this._hash; + var H = hash.words; + + // Swap endian + for (var i = 0; i < 5; i++) { + // Shortcut + var H_i = H[i]; + + // Swap + H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | + (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); + } + + // Return final computed hash + return hash; + }, + + clone: function () { + var clone = Hasher.clone.call(this); + clone._hash = this._hash.clone(); + + return clone; + } + }); + + + function f1(x, y, z) { + return ((x) ^ (y) ^ (z)); + + } + + function f2(x, y, z) { + return (((x)&(y)) | ((~x)&(z))); + } + + function f3(x, y, z) { + return (((x) | (~(y))) ^ (z)); + } + + function f4(x, y, z) { + return (((x) & (z)) | ((y)&(~(z)))); + } + + function f5(x, y, z) { + return ((x) ^ ((y) |(~(z)))); + + } + + function rotl(x,n) { + return (x<>>(32-n)); + } + + + /** + * Shortcut function to the hasher's object interface. + * + * @param {WordArray|string} message The message to hash. + * + * @return {WordArray} The hash. + * + * @static + * + * @example + * + * var hash = CryptoJS.RIPEMD160('message'); + * var hash = CryptoJS.RIPEMD160(wordArray); + */ + C.RIPEMD160 = Hasher._createHelper(RIPEMD160); + + /** + * Shortcut function to the HMAC's object interface. + * + * @param {WordArray|string} message The message to hash. + * @param {WordArray|string} key The secret key. + * + * @return {WordArray} The HMAC. + * + * @static + * + * @example + * + * var hmac = CryptoJS.HmacRIPEMD160(message, key); + */ + C.HmacRIPEMD160 = Hasher._createHmacHelper(RIPEMD160); + }(Math)); + + + return CryptoJS.RIPEMD160; + +})); + +/***/ }), +/* 27 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14)); + } + else {} +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var Base = C_lib.Base; + var C_enc = C.enc; + var Utf8 = C_enc.Utf8; + var C_algo = C.algo; + + /** + * HMAC algorithm. + */ + var HMAC = C_algo.HMAC = Base.extend({ + /** + * Initializes a newly created HMAC. + * + * @param {Hasher} hasher The hash algorithm to use. + * @param {WordArray|string} key The secret key. + * + * @example + * + * var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key); + */ + init: function (hasher, key) { + // Init hasher + hasher = this._hasher = new hasher.init(); + + // Convert string to WordArray, else assume WordArray already + if (typeof key == 'string') { + key = Utf8.parse(key); + } + + // Shortcuts + var hasherBlockSize = hasher.blockSize; + var hasherBlockSizeBytes = hasherBlockSize * 4; + + // Allow arbitrary length keys + if (key.sigBytes > hasherBlockSizeBytes) { + key = hasher.finalize(key); + } + + // Clamp excess bits + key.clamp(); + + // Clone key for inner and outer pads + var oKey = this._oKey = key.clone(); + var iKey = this._iKey = key.clone(); + + // Shortcuts + var oKeyWords = oKey.words; + var iKeyWords = iKey.words; + + // XOR keys with pad constants + for (var i = 0; i < hasherBlockSize; i++) { + oKeyWords[i] ^= 0x5c5c5c5c; + iKeyWords[i] ^= 0x36363636; + } + oKey.sigBytes = iKey.sigBytes = hasherBlockSizeBytes; + + // Set initial values + this.reset(); + }, + + /** + * Resets this HMAC to its initial state. + * + * @example + * + * hmacHasher.reset(); + */ + reset: function () { + // Shortcut + var hasher = this._hasher; + + // Reset + hasher.reset(); + hasher.update(this._iKey); + }, + + /** + * Updates this HMAC with a message. + * + * @param {WordArray|string} messageUpdate The message to append. + * + * @return {HMAC} This HMAC instance. + * + * @example + * + * hmacHasher.update('message'); + * hmacHasher.update(wordArray); + */ + update: function (messageUpdate) { + this._hasher.update(messageUpdate); + + // Chainable + return this; + }, + + /** + * Finalizes the HMAC computation. + * Note that the finalize operation is effectively a destructive, read-once operation. + * + * @param {WordArray|string} messageUpdate (Optional) A final message update. + * + * @return {WordArray} The HMAC. + * + * @example + * + * var hmac = hmacHasher.finalize(); + * var hmac = hmacHasher.finalize('message'); + * var hmac = hmacHasher.finalize(wordArray); + */ + finalize: function (messageUpdate) { + // Shortcut + var hasher = this._hasher; + + // Compute HMAC + var innerHash = hasher.finalize(messageUpdate); + hasher.reset(); + var hmac = hasher.finalize(this._oKey.clone().concat(innerHash)); + + return hmac; + } + }); + }()); + + +})); + +/***/ }), +/* 28 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory, undef) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14), __webpack_require__(20), __webpack_require__(27)); + } + else {} +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var Base = C_lib.Base; + var WordArray = C_lib.WordArray; + var C_algo = C.algo; + var SHA1 = C_algo.SHA1; + var HMAC = C_algo.HMAC; + + /** + * Password-Based Key Derivation Function 2 algorithm. + */ + var PBKDF2 = C_algo.PBKDF2 = Base.extend({ + /** + * Configuration options. + * + * @property {number} keySize The key size in words to generate. Default: 4 (128 bits) + * @property {Hasher} hasher The hasher to use. Default: SHA1 + * @property {number} iterations The number of iterations to perform. Default: 1 + */ + cfg: Base.extend({ + keySize: 128/32, + hasher: SHA1, + iterations: 1 + }), + + /** + * Initializes a newly created key derivation function. + * + * @param {Object} cfg (Optional) The configuration options to use for the derivation. + * + * @example + * + * var kdf = CryptoJS.algo.PBKDF2.create(); + * var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8 }); + * var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8, iterations: 1000 }); + */ + init: function (cfg) { + this.cfg = this.cfg.extend(cfg); + }, + + /** + * Computes the Password-Based Key Derivation Function 2. + * + * @param {WordArray|string} password The password. + * @param {WordArray|string} salt A salt. + * + * @return {WordArray} The derived key. + * + * @example + * + * var key = kdf.compute(password, salt); + */ + compute: function (password, salt) { + // Shortcut + var cfg = this.cfg; + + // Init HMAC + var hmac = HMAC.create(cfg.hasher, password); + + // Initial values + var derivedKey = WordArray.create(); + var blockIndex = WordArray.create([0x00000001]); + + // Shortcuts + var derivedKeyWords = derivedKey.words; + var blockIndexWords = blockIndex.words; + var keySize = cfg.keySize; + var iterations = cfg.iterations; + + // Generate key + while (derivedKeyWords.length < keySize) { + var block = hmac.update(salt).finalize(blockIndex); + hmac.reset(); + + // Shortcuts + var blockWords = block.words; + var blockWordsLength = blockWords.length; + + // Iterations + var intermediate = block; + for (var i = 1; i < iterations; i++) { + intermediate = hmac.finalize(intermediate); + hmac.reset(); + + // Shortcut + var intermediateWords = intermediate.words; + + // XOR intermediate with block + for (var j = 0; j < blockWordsLength; j++) { + blockWords[j] ^= intermediateWords[j]; + } + } + + derivedKey.concat(block); + blockIndexWords[0]++; + } + derivedKey.sigBytes = keySize * 4; + + return derivedKey; + } + }); + + /** + * Computes the Password-Based Key Derivation Function 2. + * + * @param {WordArray|string} password The password. + * @param {WordArray|string} salt A salt. + * @param {Object} cfg (Optional) The configuration options to use for this computation. + * + * @return {WordArray} The derived key. + * + * @static + * + * @example + * + * var key = CryptoJS.PBKDF2(password, salt); + * var key = CryptoJS.PBKDF2(password, salt, { keySize: 8 }); + * var key = CryptoJS.PBKDF2(password, salt, { keySize: 8, iterations: 1000 }); + */ + C.PBKDF2 = function (password, salt, cfg) { + return PBKDF2.create(cfg).compute(password, salt); + }; + }()); + + + return CryptoJS.PBKDF2; + +})); + +/***/ }), +/* 29 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory, undef) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14), __webpack_require__(20), __webpack_require__(27)); + } + else {} +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var Base = C_lib.Base; + var WordArray = C_lib.WordArray; + var C_algo = C.algo; + var MD5 = C_algo.MD5; + + /** + * This key derivation function is meant to conform with EVP_BytesToKey. + * www.openssl.org/docs/crypto/EVP_BytesToKey.html + */ + var EvpKDF = C_algo.EvpKDF = Base.extend({ + /** + * Configuration options. + * + * @property {number} keySize The key size in words to generate. Default: 4 (128 bits) + * @property {Hasher} hasher The hash algorithm to use. Default: MD5 + * @property {number} iterations The number of iterations to perform. Default: 1 + */ + cfg: Base.extend({ + keySize: 128/32, + hasher: MD5, + iterations: 1 + }), + + /** + * Initializes a newly created key derivation function. + * + * @param {Object} cfg (Optional) The configuration options to use for the derivation. + * + * @example + * + * var kdf = CryptoJS.algo.EvpKDF.create(); + * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 }); + * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 }); + */ + init: function (cfg) { + this.cfg = this.cfg.extend(cfg); + }, + + /** + * Derives a key from a password. + * + * @param {WordArray|string} password The password. + * @param {WordArray|string} salt A salt. + * + * @return {WordArray} The derived key. + * + * @example + * + * var key = kdf.compute(password, salt); + */ + compute: function (password, salt) { + // Shortcut + var cfg = this.cfg; + + // Init hasher + var hasher = cfg.hasher.create(); + + // Initial values + var derivedKey = WordArray.create(); + + // Shortcuts + var derivedKeyWords = derivedKey.words; + var keySize = cfg.keySize; + var iterations = cfg.iterations; + + // Generate key + while (derivedKeyWords.length < keySize) { + if (block) { + hasher.update(block); + } + var block = hasher.update(password).finalize(salt); + hasher.reset(); + + // Iterations + for (var i = 1; i < iterations; i++) { + block = hasher.finalize(block); + hasher.reset(); + } + + derivedKey.concat(block); + } + derivedKey.sigBytes = keySize * 4; + + return derivedKey; + } + }); + + /** + * Derives a key from a password. + * + * @param {WordArray|string} password The password. + * @param {WordArray|string} salt A salt. + * @param {Object} cfg (Optional) The configuration options to use for this computation. + * + * @return {WordArray} The derived key. + * + * @static + * + * @example + * + * var key = CryptoJS.EvpKDF(password, salt); + * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8 }); + * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8, iterations: 1000 }); + */ + C.EvpKDF = function (password, salt, cfg) { + return EvpKDF.create(cfg).compute(password, salt); + }; + }()); + + + return CryptoJS.EvpKDF; + +})); + +/***/ }), +/* 30 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory, undef) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14), __webpack_require__(29)); + } + else {} +}(this, function (CryptoJS) { + + /** + * Cipher core components. + */ + CryptoJS.lib.Cipher || (function (undefined) { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var Base = C_lib.Base; + var WordArray = C_lib.WordArray; + var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm; + var C_enc = C.enc; + var Utf8 = C_enc.Utf8; + var Base64 = C_enc.Base64; + var C_algo = C.algo; + var EvpKDF = C_algo.EvpKDF; + + /** + * Abstract base cipher template. + * + * @property {number} keySize This cipher's key size. Default: 4 (128 bits) + * @property {number} ivSize This cipher's IV size. Default: 4 (128 bits) + * @property {number} _ENC_XFORM_MODE A constant representing encryption mode. + * @property {number} _DEC_XFORM_MODE A constant representing decryption mode. + */ + var Cipher = C_lib.Cipher = BufferedBlockAlgorithm.extend({ + /** + * Configuration options. + * + * @property {WordArray} iv The IV to use for this operation. + */ + cfg: Base.extend(), + + /** + * Creates this cipher in encryption mode. + * + * @param {WordArray} key The key. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @return {Cipher} A cipher instance. + * + * @static + * + * @example + * + * var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray }); + */ + createEncryptor: function (key, cfg) { + return this.create(this._ENC_XFORM_MODE, key, cfg); + }, + + /** + * Creates this cipher in decryption mode. + * + * @param {WordArray} key The key. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @return {Cipher} A cipher instance. + * + * @static + * + * @example + * + * var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray }); + */ + createDecryptor: function (key, cfg) { + return this.create(this._DEC_XFORM_MODE, key, cfg); + }, + + /** + * Initializes a newly created cipher. + * + * @param {number} xformMode Either the encryption or decryption transormation mode constant. + * @param {WordArray} key The key. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @example + * + * var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray }); + */ + init: function (xformMode, key, cfg) { + // Apply config defaults + this.cfg = this.cfg.extend(cfg); + + // Store transform mode and key + this._xformMode = xformMode; + this._key = key; + + // Set initial values + this.reset(); + }, + + /** + * Resets this cipher to its initial state. + * + * @example + * + * cipher.reset(); + */ + reset: function () { + // Reset data buffer + BufferedBlockAlgorithm.reset.call(this); + + // Perform concrete-cipher logic + this._doReset(); + }, + + /** + * Adds data to be encrypted or decrypted. + * + * @param {WordArray|string} dataUpdate The data to encrypt or decrypt. + * + * @return {WordArray} The data after processing. + * + * @example + * + * var encrypted = cipher.process('data'); + * var encrypted = cipher.process(wordArray); + */ + process: function (dataUpdate) { + // Append + this._append(dataUpdate); + + // Process available blocks + return this._process(); + }, + + /** + * Finalizes the encryption or decryption process. + * Note that the finalize operation is effectively a destructive, read-once operation. + * + * @param {WordArray|string} dataUpdate The final data to encrypt or decrypt. + * + * @return {WordArray} The data after final processing. + * + * @example + * + * var encrypted = cipher.finalize(); + * var encrypted = cipher.finalize('data'); + * var encrypted = cipher.finalize(wordArray); + */ + finalize: function (dataUpdate) { + // Final data update + if (dataUpdate) { + this._append(dataUpdate); + } + + // Perform concrete-cipher logic + var finalProcessedData = this._doFinalize(); + + return finalProcessedData; + }, + + keySize: 128/32, + + ivSize: 128/32, + + _ENC_XFORM_MODE: 1, + + _DEC_XFORM_MODE: 2, + + /** + * Creates shortcut functions to a cipher's object interface. + * + * @param {Cipher} cipher The cipher to create a helper for. + * + * @return {Object} An object with encrypt and decrypt shortcut functions. + * + * @static + * + * @example + * + * var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES); + */ + _createHelper: (function () { + function selectCipherStrategy(key) { + if (typeof key == 'string') { + return PasswordBasedCipher; + } else { + return SerializableCipher; + } + } + + return function (cipher) { + return { + encrypt: function (message, key, cfg) { + return selectCipherStrategy(key).encrypt(cipher, message, key, cfg); + }, + + decrypt: function (ciphertext, key, cfg) { + return selectCipherStrategy(key).decrypt(cipher, ciphertext, key, cfg); + } + }; + }; + }()) + }); + + /** + * Abstract base stream cipher template. + * + * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 1 (32 bits) + */ + var StreamCipher = C_lib.StreamCipher = Cipher.extend({ + _doFinalize: function () { + // Process partial blocks + var finalProcessedBlocks = this._process(!!'flush'); + + return finalProcessedBlocks; + }, + + blockSize: 1 + }); + + /** + * Mode namespace. + */ + var C_mode = C.mode = {}; + + /** + * Abstract base block cipher mode template. + */ + var BlockCipherMode = C_lib.BlockCipherMode = Base.extend({ + /** + * Creates this mode for encryption. + * + * @param {Cipher} cipher A block cipher instance. + * @param {Array} iv The IV words. + * + * @static + * + * @example + * + * var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words); + */ + createEncryptor: function (cipher, iv) { + return this.Encryptor.create(cipher, iv); + }, + + /** + * Creates this mode for decryption. + * + * @param {Cipher} cipher A block cipher instance. + * @param {Array} iv The IV words. + * + * @static + * + * @example + * + * var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words); + */ + createDecryptor: function (cipher, iv) { + return this.Decryptor.create(cipher, iv); + }, + + /** + * Initializes a newly created mode. + * + * @param {Cipher} cipher A block cipher instance. + * @param {Array} iv The IV words. + * + * @example + * + * var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words); + */ + init: function (cipher, iv) { + this._cipher = cipher; + this._iv = iv; + } + }); + + /** + * Cipher Block Chaining mode. + */ + var CBC = C_mode.CBC = (function () { + /** + * Abstract base CBC mode. + */ + var CBC = BlockCipherMode.extend(); + + /** + * CBC encryptor. + */ + CBC.Encryptor = CBC.extend({ + /** + * Processes the data block at offset. + * + * @param {Array} words The data words to operate on. + * @param {number} offset The offset where the block starts. + * + * @example + * + * mode.processBlock(data.words, offset); + */ + processBlock: function (words, offset) { + // Shortcuts + var cipher = this._cipher; + var blockSize = cipher.blockSize; + + // XOR and encrypt + xorBlock.call(this, words, offset, blockSize); + cipher.encryptBlock(words, offset); + + // Remember this block to use with next block + this._prevBlock = words.slice(offset, offset + blockSize); + } + }); + + /** + * CBC decryptor. + */ + CBC.Decryptor = CBC.extend({ + /** + * Processes the data block at offset. + * + * @param {Array} words The data words to operate on. + * @param {number} offset The offset where the block starts. + * + * @example + * + * mode.processBlock(data.words, offset); + */ + processBlock: function (words, offset) { + // Shortcuts + var cipher = this._cipher; + var blockSize = cipher.blockSize; + + // Remember this block to use with next block + var thisBlock = words.slice(offset, offset + blockSize); + + // Decrypt and XOR + cipher.decryptBlock(words, offset); + xorBlock.call(this, words, offset, blockSize); + + // This block becomes the previous block + this._prevBlock = thisBlock; + } + }); + + function xorBlock(words, offset, blockSize) { + // Shortcut + var iv = this._iv; + + // Choose mixing block + if (iv) { + var block = iv; + + // Remove IV for subsequent blocks + this._iv = undefined; + } else { + var block = this._prevBlock; + } + + // XOR blocks + for (var i = 0; i < blockSize; i++) { + words[offset + i] ^= block[i]; + } + } + + return CBC; + }()); + + /** + * Padding namespace. + */ + var C_pad = C.pad = {}; + + /** + * PKCS #5/7 padding strategy. + */ + var Pkcs7 = C_pad.Pkcs7 = { + /** + * Pads data using the algorithm defined in PKCS #5/7. + * + * @param {WordArray} data The data to pad. + * @param {number} blockSize The multiple that the data should be padded to. + * + * @static + * + * @example + * + * CryptoJS.pad.Pkcs7.pad(wordArray, 4); + */ + pad: function (data, blockSize) { + // Shortcut + var blockSizeBytes = blockSize * 4; + + // Count padding bytes + var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes; + + // Create padding word + var paddingWord = (nPaddingBytes << 24) | (nPaddingBytes << 16) | (nPaddingBytes << 8) | nPaddingBytes; + + // Create padding + var paddingWords = []; + for (var i = 0; i < nPaddingBytes; i += 4) { + paddingWords.push(paddingWord); + } + var padding = WordArray.create(paddingWords, nPaddingBytes); + + // Add padding + data.concat(padding); + }, + + /** + * Unpads data that had been padded using the algorithm defined in PKCS #5/7. + * + * @param {WordArray} data The data to unpad. + * + * @static + * + * @example + * + * CryptoJS.pad.Pkcs7.unpad(wordArray); + */ + unpad: function (data) { + // Get number of padding bytes from last byte + var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; + + // Remove padding + data.sigBytes -= nPaddingBytes; + } + }; + + /** + * Abstract base block cipher template. + * + * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 4 (128 bits) + */ + var BlockCipher = C_lib.BlockCipher = Cipher.extend({ + /** + * Configuration options. + * + * @property {Mode} mode The block mode to use. Default: CBC + * @property {Padding} padding The padding strategy to use. Default: Pkcs7 + */ + cfg: Cipher.cfg.extend({ + mode: CBC, + padding: Pkcs7 + }), + + reset: function () { + // Reset cipher + Cipher.reset.call(this); + + // Shortcuts + var cfg = this.cfg; + var iv = cfg.iv; + var mode = cfg.mode; + + // Reset block mode + if (this._xformMode == this._ENC_XFORM_MODE) { + var modeCreator = mode.createEncryptor; + } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { + var modeCreator = mode.createDecryptor; + // Keep at least one block in the buffer for unpadding + this._minBufferSize = 1; + } + + if (this._mode && this._mode.__creator == modeCreator) { + this._mode.init(this, iv && iv.words); + } else { + this._mode = modeCreator.call(mode, this, iv && iv.words); + this._mode.__creator = modeCreator; + } + }, + + _doProcessBlock: function (words, offset) { + this._mode.processBlock(words, offset); + }, + + _doFinalize: function () { + // Shortcut + var padding = this.cfg.padding; + + // Finalize + if (this._xformMode == this._ENC_XFORM_MODE) { + // Pad data + padding.pad(this._data, this.blockSize); + + // Process final blocks + var finalProcessedBlocks = this._process(!!'flush'); + } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { + // Process final blocks + var finalProcessedBlocks = this._process(!!'flush'); + + // Unpad data + padding.unpad(finalProcessedBlocks); + } + + return finalProcessedBlocks; + }, + + blockSize: 128/32 + }); + + /** + * A collection of cipher parameters. + * + * @property {WordArray} ciphertext The raw ciphertext. + * @property {WordArray} key The key to this ciphertext. + * @property {WordArray} iv The IV used in the ciphering operation. + * @property {WordArray} salt The salt used with a key derivation function. + * @property {Cipher} algorithm The cipher algorithm. + * @property {Mode} mode The block mode used in the ciphering operation. + * @property {Padding} padding The padding scheme used in the ciphering operation. + * @property {number} blockSize The block size of the cipher. + * @property {Format} formatter The default formatting strategy to convert this cipher params object to a string. + */ + var CipherParams = C_lib.CipherParams = Base.extend({ + /** + * Initializes a newly created cipher params object. + * + * @param {Object} cipherParams An object with any of the possible cipher parameters. + * + * @example + * + * var cipherParams = CryptoJS.lib.CipherParams.create({ + * ciphertext: ciphertextWordArray, + * key: keyWordArray, + * iv: ivWordArray, + * salt: saltWordArray, + * algorithm: CryptoJS.algo.AES, + * mode: CryptoJS.mode.CBC, + * padding: CryptoJS.pad.PKCS7, + * blockSize: 4, + * formatter: CryptoJS.format.OpenSSL + * }); + */ + init: function (cipherParams) { + this.mixIn(cipherParams); + }, + + /** + * Converts this cipher params object to a string. + * + * @param {Format} formatter (Optional) The formatting strategy to use. + * + * @return {string} The stringified cipher params. + * + * @throws Error If neither the formatter nor the default formatter is set. + * + * @example + * + * var string = cipherParams + ''; + * var string = cipherParams.toString(); + * var string = cipherParams.toString(CryptoJS.format.OpenSSL); + */ + toString: function (formatter) { + return (formatter || this.formatter).stringify(this); + } + }); + + /** + * Format namespace. + */ + var C_format = C.format = {}; + + /** + * OpenSSL formatting strategy. + */ + var OpenSSLFormatter = C_format.OpenSSL = { + /** + * Converts a cipher params object to an OpenSSL-compatible string. + * + * @param {CipherParams} cipherParams The cipher params object. + * + * @return {string} The OpenSSL-compatible string. + * + * @static + * + * @example + * + * var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams); + */ + stringify: function (cipherParams) { + // Shortcuts + var ciphertext = cipherParams.ciphertext; + var salt = cipherParams.salt; + + // Format + if (salt) { + var wordArray = WordArray.create([0x53616c74, 0x65645f5f]).concat(salt).concat(ciphertext); + } else { + var wordArray = ciphertext; + } + + return wordArray.toString(Base64); + }, + + /** + * Converts an OpenSSL-compatible string to a cipher params object. + * + * @param {string} openSSLStr The OpenSSL-compatible string. + * + * @return {CipherParams} The cipher params object. + * + * @static + * + * @example + * + * var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString); + */ + parse: function (openSSLStr) { + // Parse base64 + var ciphertext = Base64.parse(openSSLStr); + + // Shortcut + var ciphertextWords = ciphertext.words; + + // Test for salt + if (ciphertextWords[0] == 0x53616c74 && ciphertextWords[1] == 0x65645f5f) { + // Extract salt + var salt = WordArray.create(ciphertextWords.slice(2, 4)); + + // Remove salt from ciphertext + ciphertextWords.splice(0, 4); + ciphertext.sigBytes -= 16; + } + + return CipherParams.create({ ciphertext: ciphertext, salt: salt }); + } + }; + + /** + * A cipher wrapper that returns ciphertext as a serializable cipher params object. + */ + var SerializableCipher = C_lib.SerializableCipher = Base.extend({ + /** + * Configuration options. + * + * @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL + */ + cfg: Base.extend({ + format: OpenSSLFormatter + }), + + /** + * Encrypts a message. + * + * @param {Cipher} cipher The cipher algorithm to use. + * @param {WordArray|string} message The message to encrypt. + * @param {WordArray} key The key. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @return {CipherParams} A cipher params object. + * + * @static + * + * @example + * + * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key); + * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv }); + * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL }); + */ + encrypt: function (cipher, message, key, cfg) { + // Apply config defaults + cfg = this.cfg.extend(cfg); + + // Encrypt + var encryptor = cipher.createEncryptor(key, cfg); + var ciphertext = encryptor.finalize(message); + + // Shortcut + var cipherCfg = encryptor.cfg; + + // Create and return serializable cipher params + return CipherParams.create({ + ciphertext: ciphertext, + key: key, + iv: cipherCfg.iv, + algorithm: cipher, + mode: cipherCfg.mode, + padding: cipherCfg.padding, + blockSize: cipher.blockSize, + formatter: cfg.format + }); + }, + + /** + * Decrypts serialized ciphertext. + * + * @param {Cipher} cipher The cipher algorithm to use. + * @param {CipherParams|string} ciphertext The ciphertext to decrypt. + * @param {WordArray} key The key. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @return {WordArray} The plaintext. + * + * @static + * + * @example + * + * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL }); + * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL }); + */ + decrypt: function (cipher, ciphertext, key, cfg) { + // Apply config defaults + cfg = this.cfg.extend(cfg); + + // Convert string to CipherParams + ciphertext = this._parse(ciphertext, cfg.format); + + // Decrypt + var plaintext = cipher.createDecryptor(key, cfg).finalize(ciphertext.ciphertext); + + return plaintext; + }, + + /** + * Converts serialized ciphertext to CipherParams, + * else assumed CipherParams already and returns ciphertext unchanged. + * + * @param {CipherParams|string} ciphertext The ciphertext. + * @param {Formatter} format The formatting strategy to use to parse serialized ciphertext. + * + * @return {CipherParams} The unserialized ciphertext. + * + * @static + * + * @example + * + * var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format); + */ + _parse: function (ciphertext, format) { + if (typeof ciphertext == 'string') { + return format.parse(ciphertext, this); + } else { + return ciphertext; + } + } + }); + + /** + * Key derivation function namespace. + */ + var C_kdf = C.kdf = {}; + + /** + * OpenSSL key derivation function. + */ + var OpenSSLKdf = C_kdf.OpenSSL = { + /** + * Derives a key and IV from a password. + * + * @param {string} password The password to derive from. + * @param {number} keySize The size in words of the key to generate. + * @param {number} ivSize The size in words of the IV to generate. + * @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly. + * + * @return {CipherParams} A cipher params object with the key, IV, and salt. + * + * @static + * + * @example + * + * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32); + * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt'); + */ + execute: function (password, keySize, ivSize, salt) { + // Generate random salt + if (!salt) { + salt = WordArray.random(64/8); + } + + // Derive key and IV + var key = EvpKDF.create({ keySize: keySize + ivSize }).compute(password, salt); + + // Separate key and IV + var iv = WordArray.create(key.words.slice(keySize), ivSize * 4); + key.sigBytes = keySize * 4; + + // Return params + return CipherParams.create({ key: key, iv: iv, salt: salt }); + } + }; + + /** + * A serializable cipher wrapper that derives the key from a password, + * and returns ciphertext as a serializable cipher params object. + */ + var PasswordBasedCipher = C_lib.PasswordBasedCipher = SerializableCipher.extend({ + /** + * Configuration options. + * + * @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL + */ + cfg: SerializableCipher.cfg.extend({ + kdf: OpenSSLKdf + }), + + /** + * Encrypts a message using a password. + * + * @param {Cipher} cipher The cipher algorithm to use. + * @param {WordArray|string} message The message to encrypt. + * @param {string} password The password. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @return {CipherParams} A cipher params object. + * + * @static + * + * @example + * + * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password'); + * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL }); + */ + encrypt: function (cipher, message, password, cfg) { + // Apply config defaults + cfg = this.cfg.extend(cfg); + + // Derive key and other params + var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize); + + // Add IV to config + cfg.iv = derivedParams.iv; + + // Encrypt + var ciphertext = SerializableCipher.encrypt.call(this, cipher, message, derivedParams.key, cfg); + + // Mix in derived params + ciphertext.mixIn(derivedParams); + + return ciphertext; + }, + + /** + * Decrypts serialized ciphertext using a password. + * + * @param {Cipher} cipher The cipher algorithm to use. + * @param {CipherParams|string} ciphertext The ciphertext to decrypt. + * @param {string} password The password. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @return {WordArray} The plaintext. + * + * @static + * + * @example + * + * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL }); + * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL }); + */ + decrypt: function (cipher, ciphertext, password, cfg) { + // Apply config defaults + cfg = this.cfg.extend(cfg); + + // Convert string to CipherParams + ciphertext = this._parse(ciphertext, cfg.format); + + // Derive key and other params + var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt); + + // Add IV to config + cfg.iv = derivedParams.iv; + + // Decrypt + var plaintext = SerializableCipher.decrypt.call(this, cipher, ciphertext, derivedParams.key, cfg); + + return plaintext; + } + }); + }()); + + +})); + +/***/ }), +/* 31 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory, undef) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14), __webpack_require__(30)); + } + else {} +}(this, function (CryptoJS) { + + /** + * Cipher Feedback block mode. + */ + CryptoJS.mode.CFB = (function () { + var CFB = CryptoJS.lib.BlockCipherMode.extend(); + + CFB.Encryptor = CFB.extend({ + processBlock: function (words, offset) { + // Shortcuts + var cipher = this._cipher; + var blockSize = cipher.blockSize; + + generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher); + + // Remember this block to use with next block + this._prevBlock = words.slice(offset, offset + blockSize); + } + }); + + CFB.Decryptor = CFB.extend({ + processBlock: function (words, offset) { + // Shortcuts + var cipher = this._cipher; + var blockSize = cipher.blockSize; + + // Remember this block to use with next block + var thisBlock = words.slice(offset, offset + blockSize); + + generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher); + + // This block becomes the previous block + this._prevBlock = thisBlock; + } + }); + + function generateKeystreamAndEncrypt(words, offset, blockSize, cipher) { + // Shortcut + var iv = this._iv; + + // Generate keystream + if (iv) { + var keystream = iv.slice(0); + + // Remove IV for subsequent blocks + this._iv = undefined; + } else { + var keystream = this._prevBlock; + } + cipher.encryptBlock(keystream, 0); + + // Encrypt + for (var i = 0; i < blockSize; i++) { + words[offset + i] ^= keystream[i]; + } + } + + return CFB; + }()); + + + return CryptoJS.mode.CFB; + +})); + +/***/ }), +/* 32 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory, undef) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14), __webpack_require__(30)); + } + else {} +}(this, function (CryptoJS) { + + /** + * Counter block mode. + */ + CryptoJS.mode.CTR = (function () { + var CTR = CryptoJS.lib.BlockCipherMode.extend(); + + var Encryptor = CTR.Encryptor = CTR.extend({ + processBlock: function (words, offset) { + // Shortcuts + var cipher = this._cipher + var blockSize = cipher.blockSize; + var iv = this._iv; + var counter = this._counter; + + // Generate keystream + if (iv) { + counter = this._counter = iv.slice(0); + + // Remove IV for subsequent blocks + this._iv = undefined; + } + var keystream = counter.slice(0); + cipher.encryptBlock(keystream, 0); + + // Increment counter + counter[blockSize - 1] = (counter[blockSize - 1] + 1) | 0 + + // Encrypt + for (var i = 0; i < blockSize; i++) { + words[offset + i] ^= keystream[i]; + } + } + }); + + CTR.Decryptor = Encryptor; + + return CTR; + }()); + + + return CryptoJS.mode.CTR; + +})); + +/***/ }), +/* 33 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory, undef) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14), __webpack_require__(30)); + } + else {} +}(this, function (CryptoJS) { + + /** @preserve + * Counter block mode compatible with Dr Brian Gladman fileenc.c + * derived from CryptoJS.mode.CTR + * Jan Hruby jhruby.web@gmail.com + */ + CryptoJS.mode.CTRGladman = (function () { + var CTRGladman = CryptoJS.lib.BlockCipherMode.extend(); + + function incWord(word) + { + if (((word >> 24) & 0xff) === 0xff) { //overflow + var b1 = (word >> 16)&0xff; + var b2 = (word >> 8)&0xff; + var b3 = word & 0xff; + + if (b1 === 0xff) // overflow b1 + { + b1 = 0; + if (b2 === 0xff) + { + b2 = 0; + if (b3 === 0xff) + { + b3 = 0; + } + else + { + ++b3; + } + } + else + { + ++b2; + } + } + else + { + ++b1; + } + + word = 0; + word += (b1 << 16); + word += (b2 << 8); + word += b3; + } + else + { + word += (0x01 << 24); + } + return word; + } + + function incCounter(counter) + { + if ((counter[0] = incWord(counter[0])) === 0) + { + // encr_data in fileenc.c from Dr Brian Gladman's counts only with DWORD j < 8 + counter[1] = incWord(counter[1]); + } + return counter; + } + + var Encryptor = CTRGladman.Encryptor = CTRGladman.extend({ + processBlock: function (words, offset) { + // Shortcuts + var cipher = this._cipher + var blockSize = cipher.blockSize; + var iv = this._iv; + var counter = this._counter; + + // Generate keystream + if (iv) { + counter = this._counter = iv.slice(0); + + // Remove IV for subsequent blocks + this._iv = undefined; + } + + incCounter(counter); + + var keystream = counter.slice(0); + cipher.encryptBlock(keystream, 0); + + // Encrypt + for (var i = 0; i < blockSize; i++) { + words[offset + i] ^= keystream[i]; + } + } + }); + + CTRGladman.Decryptor = Encryptor; + + return CTRGladman; + }()); + + + + + return CryptoJS.mode.CTRGladman; + +})); + +/***/ }), +/* 34 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory, undef) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14), __webpack_require__(30)); + } + else {} +}(this, function (CryptoJS) { + + /** + * Output Feedback block mode. + */ + CryptoJS.mode.OFB = (function () { + var OFB = CryptoJS.lib.BlockCipherMode.extend(); + + var Encryptor = OFB.Encryptor = OFB.extend({ + processBlock: function (words, offset) { + // Shortcuts + var cipher = this._cipher + var blockSize = cipher.blockSize; + var iv = this._iv; + var keystream = this._keystream; + + // Generate keystream + if (iv) { + keystream = this._keystream = iv.slice(0); + + // Remove IV for subsequent blocks + this._iv = undefined; + } + cipher.encryptBlock(keystream, 0); + + // Encrypt + for (var i = 0; i < blockSize; i++) { + words[offset + i] ^= keystream[i]; + } + } + }); + + OFB.Decryptor = Encryptor; + + return OFB; + }()); + + + return CryptoJS.mode.OFB; + +})); + +/***/ }), +/* 35 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory, undef) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14), __webpack_require__(30)); + } + else {} +}(this, function (CryptoJS) { + + /** + * Electronic Codebook block mode. + */ + CryptoJS.mode.ECB = (function () { + var ECB = CryptoJS.lib.BlockCipherMode.extend(); + + ECB.Encryptor = ECB.extend({ + processBlock: function (words, offset) { + this._cipher.encryptBlock(words, offset); + } + }); + + ECB.Decryptor = ECB.extend({ + processBlock: function (words, offset) { + this._cipher.decryptBlock(words, offset); + } + }); + + return ECB; + }()); + + + return CryptoJS.mode.ECB; + +})); + +/***/ }), +/* 36 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory, undef) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14), __webpack_require__(30)); + } + else {} +}(this, function (CryptoJS) { + + /** + * ANSI X.923 padding strategy. + */ + CryptoJS.pad.AnsiX923 = { + pad: function (data, blockSize) { + // Shortcuts + var dataSigBytes = data.sigBytes; + var blockSizeBytes = blockSize * 4; + + // Count padding bytes + var nPaddingBytes = blockSizeBytes - dataSigBytes % blockSizeBytes; + + // Compute last byte position + var lastBytePos = dataSigBytes + nPaddingBytes - 1; + + // Pad + data.clamp(); + data.words[lastBytePos >>> 2] |= nPaddingBytes << (24 - (lastBytePos % 4) * 8); + data.sigBytes += nPaddingBytes; + }, + + unpad: function (data) { + // Get number of padding bytes from last byte + var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; + + // Remove padding + data.sigBytes -= nPaddingBytes; + } + }; + + + return CryptoJS.pad.Ansix923; + +})); + +/***/ }), +/* 37 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory, undef) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14), __webpack_require__(30)); + } + else {} +}(this, function (CryptoJS) { + + /** + * ISO 10126 padding strategy. + */ + CryptoJS.pad.Iso10126 = { + pad: function (data, blockSize) { + // Shortcut + var blockSizeBytes = blockSize * 4; + + // Count padding bytes + var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes; + + // Pad + data.concat(CryptoJS.lib.WordArray.random(nPaddingBytes - 1)). + concat(CryptoJS.lib.WordArray.create([nPaddingBytes << 24], 1)); + }, + + unpad: function (data) { + // Get number of padding bytes from last byte + var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; + + // Remove padding + data.sigBytes -= nPaddingBytes; + } + }; + + + return CryptoJS.pad.Iso10126; + +})); + +/***/ }), +/* 38 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory, undef) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14), __webpack_require__(30)); + } + else {} +}(this, function (CryptoJS) { + + /** + * ISO/IEC 9797-1 Padding Method 2. + */ + CryptoJS.pad.Iso97971 = { + pad: function (data, blockSize) { + // Add 0x80 byte + data.concat(CryptoJS.lib.WordArray.create([0x80000000], 1)); + + // Zero pad the rest + CryptoJS.pad.ZeroPadding.pad(data, blockSize); + }, + + unpad: function (data) { + // Remove zero padding + CryptoJS.pad.ZeroPadding.unpad(data); + + // Remove one more byte -- the 0x80 byte + data.sigBytes--; + } + }; + + + return CryptoJS.pad.Iso97971; + +})); + +/***/ }), +/* 39 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory, undef) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14), __webpack_require__(30)); + } + else {} +}(this, function (CryptoJS) { + + /** + * Zero padding strategy. + */ + CryptoJS.pad.ZeroPadding = { + pad: function (data, blockSize) { + // Shortcut + var blockSizeBytes = blockSize * 4; + + // Pad + data.clamp(); + data.sigBytes += blockSizeBytes - ((data.sigBytes % blockSizeBytes) || blockSizeBytes); + }, + + unpad: function (data) { + // Shortcut + var dataWords = data.words; + + // Unpad + var i = data.sigBytes - 1; + while (!((dataWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff)) { + i--; + } + data.sigBytes = i + 1; + } + }; + + + return CryptoJS.pad.ZeroPadding; + +})); + +/***/ }), +/* 40 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory, undef) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14), __webpack_require__(30)); + } + else {} +}(this, function (CryptoJS) { + + /** + * A noop padding strategy. + */ + CryptoJS.pad.NoPadding = { + pad: function () { + }, + + unpad: function () { + } + }; + + + return CryptoJS.pad.NoPadding; + +})); + +/***/ }), +/* 41 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory, undef) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14), __webpack_require__(30)); + } + else {} +}(this, function (CryptoJS) { + + (function (undefined) { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var CipherParams = C_lib.CipherParams; + var C_enc = C.enc; + var Hex = C_enc.Hex; + var C_format = C.format; + + var HexFormatter = C_format.Hex = { + /** + * Converts the ciphertext of a cipher params object to a hexadecimally encoded string. + * + * @param {CipherParams} cipherParams The cipher params object. + * + * @return {string} The hexadecimally encoded string. + * + * @static + * + * @example + * + * var hexString = CryptoJS.format.Hex.stringify(cipherParams); + */ + stringify: function (cipherParams) { + return cipherParams.ciphertext.toString(Hex); + }, + + /** + * Converts a hexadecimally encoded ciphertext string to a cipher params object. + * + * @param {string} input The hexadecimally encoded string. + * + * @return {CipherParams} The cipher params object. + * + * @static + * + * @example + * + * var cipherParams = CryptoJS.format.Hex.parse(hexString); + */ + parse: function (input) { + var ciphertext = Hex.parse(input); + return CipherParams.create({ ciphertext: ciphertext }); + } + }; + }()); + + + return CryptoJS.format.Hex; + +})); + +/***/ }), +/* 42 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory, undef) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14), __webpack_require__(18), __webpack_require__(19), __webpack_require__(29), __webpack_require__(30)); + } + else {} +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var BlockCipher = C_lib.BlockCipher; + var C_algo = C.algo; + + // Lookup tables + var SBOX = []; + var INV_SBOX = []; + var SUB_MIX_0 = []; + var SUB_MIX_1 = []; + var SUB_MIX_2 = []; + var SUB_MIX_3 = []; + var INV_SUB_MIX_0 = []; + var INV_SUB_MIX_1 = []; + var INV_SUB_MIX_2 = []; + var INV_SUB_MIX_3 = []; + + // Compute lookup tables + (function () { + // Compute double table + var d = []; + for (var i = 0; i < 256; i++) { + if (i < 128) { + d[i] = i << 1; + } else { + d[i] = (i << 1) ^ 0x11b; + } + } + + // Walk GF(2^8) + var x = 0; + var xi = 0; + for (var i = 0; i < 256; i++) { + // Compute sbox + var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4); + sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63; + SBOX[x] = sx; + INV_SBOX[sx] = x; + + // Compute multiplication + var x2 = d[x]; + var x4 = d[x2]; + var x8 = d[x4]; + + // Compute sub bytes, mix columns tables + var t = (d[sx] * 0x101) ^ (sx * 0x1010100); + SUB_MIX_0[x] = (t << 24) | (t >>> 8); + SUB_MIX_1[x] = (t << 16) | (t >>> 16); + SUB_MIX_2[x] = (t << 8) | (t >>> 24); + SUB_MIX_3[x] = t; + + // Compute inv sub bytes, inv mix columns tables + var t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100); + INV_SUB_MIX_0[sx] = (t << 24) | (t >>> 8); + INV_SUB_MIX_1[sx] = (t << 16) | (t >>> 16); + INV_SUB_MIX_2[sx] = (t << 8) | (t >>> 24); + INV_SUB_MIX_3[sx] = t; + + // Compute next counter + if (!x) { + x = xi = 1; + } else { + x = x2 ^ d[d[d[x8 ^ x2]]]; + xi ^= d[d[xi]]; + } + } + }()); + + // Precomputed Rcon lookup + var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]; + + /** + * AES block cipher algorithm. + */ + var AES = C_algo.AES = BlockCipher.extend({ + _doReset: function () { + // Skip reset of nRounds has been set before and key did not change + if (this._nRounds && this._keyPriorReset === this._key) { + return; + } + + // Shortcuts + var key = this._keyPriorReset = this._key; + var keyWords = key.words; + var keySize = key.sigBytes / 4; + + // Compute number of rounds + var nRounds = this._nRounds = keySize + 6; + + // Compute number of key schedule rows + var ksRows = (nRounds + 1) * 4; + + // Compute key schedule + var keySchedule = this._keySchedule = []; + for (var ksRow = 0; ksRow < ksRows; ksRow++) { + if (ksRow < keySize) { + keySchedule[ksRow] = keyWords[ksRow]; + } else { + var t = keySchedule[ksRow - 1]; + + if (!(ksRow % keySize)) { + // Rot word + t = (t << 8) | (t >>> 24); + + // Sub word + t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]; + + // Mix Rcon + t ^= RCON[(ksRow / keySize) | 0] << 24; + } else if (keySize > 6 && ksRow % keySize == 4) { + // Sub word + t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]; + } + + keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t; + } + } + + // Compute inv key schedule + var invKeySchedule = this._invKeySchedule = []; + for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) { + var ksRow = ksRows - invKsRow; + + if (invKsRow % 4) { + var t = keySchedule[ksRow]; + } else { + var t = keySchedule[ksRow - 4]; + } + + if (invKsRow < 4 || ksRow <= 4) { + invKeySchedule[invKsRow] = t; + } else { + invKeySchedule[invKsRow] = INV_SUB_MIX_0[SBOX[t >>> 24]] ^ INV_SUB_MIX_1[SBOX[(t >>> 16) & 0xff]] ^ + INV_SUB_MIX_2[SBOX[(t >>> 8) & 0xff]] ^ INV_SUB_MIX_3[SBOX[t & 0xff]]; + } + } + }, + + encryptBlock: function (M, offset) { + this._doCryptBlock(M, offset, this._keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX); + }, + + decryptBlock: function (M, offset) { + // Swap 2nd and 4th rows + var t = M[offset + 1]; + M[offset + 1] = M[offset + 3]; + M[offset + 3] = t; + + this._doCryptBlock(M, offset, this._invKeySchedule, INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3, INV_SBOX); + + // Inv swap 2nd and 4th rows + var t = M[offset + 1]; + M[offset + 1] = M[offset + 3]; + M[offset + 3] = t; + }, + + _doCryptBlock: function (M, offset, keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX) { + // Shortcut + var nRounds = this._nRounds; + + // Get input, add round key + var s0 = M[offset] ^ keySchedule[0]; + var s1 = M[offset + 1] ^ keySchedule[1]; + var s2 = M[offset + 2] ^ keySchedule[2]; + var s3 = M[offset + 3] ^ keySchedule[3]; + + // Key schedule row counter + var ksRow = 4; + + // Rounds + for (var round = 1; round < nRounds; round++) { + // Shift rows, sub bytes, mix columns, add round key + var t0 = SUB_MIX_0[s0 >>> 24] ^ SUB_MIX_1[(s1 >>> 16) & 0xff] ^ SUB_MIX_2[(s2 >>> 8) & 0xff] ^ SUB_MIX_3[s3 & 0xff] ^ keySchedule[ksRow++]; + var t1 = SUB_MIX_0[s1 >>> 24] ^ SUB_MIX_1[(s2 >>> 16) & 0xff] ^ SUB_MIX_2[(s3 >>> 8) & 0xff] ^ SUB_MIX_3[s0 & 0xff] ^ keySchedule[ksRow++]; + var t2 = SUB_MIX_0[s2 >>> 24] ^ SUB_MIX_1[(s3 >>> 16) & 0xff] ^ SUB_MIX_2[(s0 >>> 8) & 0xff] ^ SUB_MIX_3[s1 & 0xff] ^ keySchedule[ksRow++]; + var t3 = SUB_MIX_0[s3 >>> 24] ^ SUB_MIX_1[(s0 >>> 16) & 0xff] ^ SUB_MIX_2[(s1 >>> 8) & 0xff] ^ SUB_MIX_3[s2 & 0xff] ^ keySchedule[ksRow++]; + + // Update state + s0 = t0; + s1 = t1; + s2 = t2; + s3 = t3; + } + + // Shift rows, sub bytes, add round key + var t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++]; + var t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++]; + var t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++]; + var t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++]; + + // Set output + M[offset] = t0; + M[offset + 1] = t1; + M[offset + 2] = t2; + M[offset + 3] = t3; + }, + + keySize: 256/32 + }); + + /** + * Shortcut functions to the cipher's object interface. + * + * @example + * + * var ciphertext = CryptoJS.AES.encrypt(message, key, cfg); + * var plaintext = CryptoJS.AES.decrypt(ciphertext, key, cfg); + */ + C.AES = BlockCipher._createHelper(AES); + }()); + + + return CryptoJS.AES; + +})); + +/***/ }), +/* 43 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory, undef) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14), __webpack_require__(18), __webpack_require__(19), __webpack_require__(29), __webpack_require__(30)); + } + else {} +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var BlockCipher = C_lib.BlockCipher; + var C_algo = C.algo; + + // Permuted Choice 1 constants + var PC1 = [ + 57, 49, 41, 33, 25, 17, 9, 1, + 58, 50, 42, 34, 26, 18, 10, 2, + 59, 51, 43, 35, 27, 19, 11, 3, + 60, 52, 44, 36, 63, 55, 47, 39, + 31, 23, 15, 7, 62, 54, 46, 38, + 30, 22, 14, 6, 61, 53, 45, 37, + 29, 21, 13, 5, 28, 20, 12, 4 + ]; + + // Permuted Choice 2 constants + var PC2 = [ + 14, 17, 11, 24, 1, 5, + 3, 28, 15, 6, 21, 10, + 23, 19, 12, 4, 26, 8, + 16, 7, 27, 20, 13, 2, + 41, 52, 31, 37, 47, 55, + 30, 40, 51, 45, 33, 48, + 44, 49, 39, 56, 34, 53, + 46, 42, 50, 36, 29, 32 + ]; + + // Cumulative bit shift constants + var BIT_SHIFTS = [1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28]; + + // SBOXes and round permutation constants + var SBOX_P = [ + { + 0x0: 0x808200, + 0x10000000: 0x8000, + 0x20000000: 0x808002, + 0x30000000: 0x2, + 0x40000000: 0x200, + 0x50000000: 0x808202, + 0x60000000: 0x800202, + 0x70000000: 0x800000, + 0x80000000: 0x202, + 0x90000000: 0x800200, + 0xa0000000: 0x8200, + 0xb0000000: 0x808000, + 0xc0000000: 0x8002, + 0xd0000000: 0x800002, + 0xe0000000: 0x0, + 0xf0000000: 0x8202, + 0x8000000: 0x0, + 0x18000000: 0x808202, + 0x28000000: 0x8202, + 0x38000000: 0x8000, + 0x48000000: 0x808200, + 0x58000000: 0x200, + 0x68000000: 0x808002, + 0x78000000: 0x2, + 0x88000000: 0x800200, + 0x98000000: 0x8200, + 0xa8000000: 0x808000, + 0xb8000000: 0x800202, + 0xc8000000: 0x800002, + 0xd8000000: 0x8002, + 0xe8000000: 0x202, + 0xf8000000: 0x800000, + 0x1: 0x8000, + 0x10000001: 0x2, + 0x20000001: 0x808200, + 0x30000001: 0x800000, + 0x40000001: 0x808002, + 0x50000001: 0x8200, + 0x60000001: 0x200, + 0x70000001: 0x800202, + 0x80000001: 0x808202, + 0x90000001: 0x808000, + 0xa0000001: 0x800002, + 0xb0000001: 0x8202, + 0xc0000001: 0x202, + 0xd0000001: 0x800200, + 0xe0000001: 0x8002, + 0xf0000001: 0x0, + 0x8000001: 0x808202, + 0x18000001: 0x808000, + 0x28000001: 0x800000, + 0x38000001: 0x200, + 0x48000001: 0x8000, + 0x58000001: 0x800002, + 0x68000001: 0x2, + 0x78000001: 0x8202, + 0x88000001: 0x8002, + 0x98000001: 0x800202, + 0xa8000001: 0x202, + 0xb8000001: 0x808200, + 0xc8000001: 0x800200, + 0xd8000001: 0x0, + 0xe8000001: 0x8200, + 0xf8000001: 0x808002 + }, + { + 0x0: 0x40084010, + 0x1000000: 0x4000, + 0x2000000: 0x80000, + 0x3000000: 0x40080010, + 0x4000000: 0x40000010, + 0x5000000: 0x40084000, + 0x6000000: 0x40004000, + 0x7000000: 0x10, + 0x8000000: 0x84000, + 0x9000000: 0x40004010, + 0xa000000: 0x40000000, + 0xb000000: 0x84010, + 0xc000000: 0x80010, + 0xd000000: 0x0, + 0xe000000: 0x4010, + 0xf000000: 0x40080000, + 0x800000: 0x40004000, + 0x1800000: 0x84010, + 0x2800000: 0x10, + 0x3800000: 0x40004010, + 0x4800000: 0x40084010, + 0x5800000: 0x40000000, + 0x6800000: 0x80000, + 0x7800000: 0x40080010, + 0x8800000: 0x80010, + 0x9800000: 0x0, + 0xa800000: 0x4000, + 0xb800000: 0x40080000, + 0xc800000: 0x40000010, + 0xd800000: 0x84000, + 0xe800000: 0x40084000, + 0xf800000: 0x4010, + 0x10000000: 0x0, + 0x11000000: 0x40080010, + 0x12000000: 0x40004010, + 0x13000000: 0x40084000, + 0x14000000: 0x40080000, + 0x15000000: 0x10, + 0x16000000: 0x84010, + 0x17000000: 0x4000, + 0x18000000: 0x4010, + 0x19000000: 0x80000, + 0x1a000000: 0x80010, + 0x1b000000: 0x40000010, + 0x1c000000: 0x84000, + 0x1d000000: 0x40004000, + 0x1e000000: 0x40000000, + 0x1f000000: 0x40084010, + 0x10800000: 0x84010, + 0x11800000: 0x80000, + 0x12800000: 0x40080000, + 0x13800000: 0x4000, + 0x14800000: 0x40004000, + 0x15800000: 0x40084010, + 0x16800000: 0x10, + 0x17800000: 0x40000000, + 0x18800000: 0x40084000, + 0x19800000: 0x40000010, + 0x1a800000: 0x40004010, + 0x1b800000: 0x80010, + 0x1c800000: 0x0, + 0x1d800000: 0x4010, + 0x1e800000: 0x40080010, + 0x1f800000: 0x84000 + }, + { + 0x0: 0x104, + 0x100000: 0x0, + 0x200000: 0x4000100, + 0x300000: 0x10104, + 0x400000: 0x10004, + 0x500000: 0x4000004, + 0x600000: 0x4010104, + 0x700000: 0x4010000, + 0x800000: 0x4000000, + 0x900000: 0x4010100, + 0xa00000: 0x10100, + 0xb00000: 0x4010004, + 0xc00000: 0x4000104, + 0xd00000: 0x10000, + 0xe00000: 0x4, + 0xf00000: 0x100, + 0x80000: 0x4010100, + 0x180000: 0x4010004, + 0x280000: 0x0, + 0x380000: 0x4000100, + 0x480000: 0x4000004, + 0x580000: 0x10000, + 0x680000: 0x10004, + 0x780000: 0x104, + 0x880000: 0x4, + 0x980000: 0x100, + 0xa80000: 0x4010000, + 0xb80000: 0x10104, + 0xc80000: 0x10100, + 0xd80000: 0x4000104, + 0xe80000: 0x4010104, + 0xf80000: 0x4000000, + 0x1000000: 0x4010100, + 0x1100000: 0x10004, + 0x1200000: 0x10000, + 0x1300000: 0x4000100, + 0x1400000: 0x100, + 0x1500000: 0x4010104, + 0x1600000: 0x4000004, + 0x1700000: 0x0, + 0x1800000: 0x4000104, + 0x1900000: 0x4000000, + 0x1a00000: 0x4, + 0x1b00000: 0x10100, + 0x1c00000: 0x4010000, + 0x1d00000: 0x104, + 0x1e00000: 0x10104, + 0x1f00000: 0x4010004, + 0x1080000: 0x4000000, + 0x1180000: 0x104, + 0x1280000: 0x4010100, + 0x1380000: 0x0, + 0x1480000: 0x10004, + 0x1580000: 0x4000100, + 0x1680000: 0x100, + 0x1780000: 0x4010004, + 0x1880000: 0x10000, + 0x1980000: 0x4010104, + 0x1a80000: 0x10104, + 0x1b80000: 0x4000004, + 0x1c80000: 0x4000104, + 0x1d80000: 0x4010000, + 0x1e80000: 0x4, + 0x1f80000: 0x10100 + }, + { + 0x0: 0x80401000, + 0x10000: 0x80001040, + 0x20000: 0x401040, + 0x30000: 0x80400000, + 0x40000: 0x0, + 0x50000: 0x401000, + 0x60000: 0x80000040, + 0x70000: 0x400040, + 0x80000: 0x80000000, + 0x90000: 0x400000, + 0xa0000: 0x40, + 0xb0000: 0x80001000, + 0xc0000: 0x80400040, + 0xd0000: 0x1040, + 0xe0000: 0x1000, + 0xf0000: 0x80401040, + 0x8000: 0x80001040, + 0x18000: 0x40, + 0x28000: 0x80400040, + 0x38000: 0x80001000, + 0x48000: 0x401000, + 0x58000: 0x80401040, + 0x68000: 0x0, + 0x78000: 0x80400000, + 0x88000: 0x1000, + 0x98000: 0x80401000, + 0xa8000: 0x400000, + 0xb8000: 0x1040, + 0xc8000: 0x80000000, + 0xd8000: 0x400040, + 0xe8000: 0x401040, + 0xf8000: 0x80000040, + 0x100000: 0x400040, + 0x110000: 0x401000, + 0x120000: 0x80000040, + 0x130000: 0x0, + 0x140000: 0x1040, + 0x150000: 0x80400040, + 0x160000: 0x80401000, + 0x170000: 0x80001040, + 0x180000: 0x80401040, + 0x190000: 0x80000000, + 0x1a0000: 0x80400000, + 0x1b0000: 0x401040, + 0x1c0000: 0x80001000, + 0x1d0000: 0x400000, + 0x1e0000: 0x40, + 0x1f0000: 0x1000, + 0x108000: 0x80400000, + 0x118000: 0x80401040, + 0x128000: 0x0, + 0x138000: 0x401000, + 0x148000: 0x400040, + 0x158000: 0x80000000, + 0x168000: 0x80001040, + 0x178000: 0x40, + 0x188000: 0x80000040, + 0x198000: 0x1000, + 0x1a8000: 0x80001000, + 0x1b8000: 0x80400040, + 0x1c8000: 0x1040, + 0x1d8000: 0x80401000, + 0x1e8000: 0x400000, + 0x1f8000: 0x401040 + }, + { + 0x0: 0x80, + 0x1000: 0x1040000, + 0x2000: 0x40000, + 0x3000: 0x20000000, + 0x4000: 0x20040080, + 0x5000: 0x1000080, + 0x6000: 0x21000080, + 0x7000: 0x40080, + 0x8000: 0x1000000, + 0x9000: 0x20040000, + 0xa000: 0x20000080, + 0xb000: 0x21040080, + 0xc000: 0x21040000, + 0xd000: 0x0, + 0xe000: 0x1040080, + 0xf000: 0x21000000, + 0x800: 0x1040080, + 0x1800: 0x21000080, + 0x2800: 0x80, + 0x3800: 0x1040000, + 0x4800: 0x40000, + 0x5800: 0x20040080, + 0x6800: 0x21040000, + 0x7800: 0x20000000, + 0x8800: 0x20040000, + 0x9800: 0x0, + 0xa800: 0x21040080, + 0xb800: 0x1000080, + 0xc800: 0x20000080, + 0xd800: 0x21000000, + 0xe800: 0x1000000, + 0xf800: 0x40080, + 0x10000: 0x40000, + 0x11000: 0x80, + 0x12000: 0x20000000, + 0x13000: 0x21000080, + 0x14000: 0x1000080, + 0x15000: 0x21040000, + 0x16000: 0x20040080, + 0x17000: 0x1000000, + 0x18000: 0x21040080, + 0x19000: 0x21000000, + 0x1a000: 0x1040000, + 0x1b000: 0x20040000, + 0x1c000: 0x40080, + 0x1d000: 0x20000080, + 0x1e000: 0x0, + 0x1f000: 0x1040080, + 0x10800: 0x21000080, + 0x11800: 0x1000000, + 0x12800: 0x1040000, + 0x13800: 0x20040080, + 0x14800: 0x20000000, + 0x15800: 0x1040080, + 0x16800: 0x80, + 0x17800: 0x21040000, + 0x18800: 0x40080, + 0x19800: 0x21040080, + 0x1a800: 0x0, + 0x1b800: 0x21000000, + 0x1c800: 0x1000080, + 0x1d800: 0x40000, + 0x1e800: 0x20040000, + 0x1f800: 0x20000080 + }, + { + 0x0: 0x10000008, + 0x100: 0x2000, + 0x200: 0x10200000, + 0x300: 0x10202008, + 0x400: 0x10002000, + 0x500: 0x200000, + 0x600: 0x200008, + 0x700: 0x10000000, + 0x800: 0x0, + 0x900: 0x10002008, + 0xa00: 0x202000, + 0xb00: 0x8, + 0xc00: 0x10200008, + 0xd00: 0x202008, + 0xe00: 0x2008, + 0xf00: 0x10202000, + 0x80: 0x10200000, + 0x180: 0x10202008, + 0x280: 0x8, + 0x380: 0x200000, + 0x480: 0x202008, + 0x580: 0x10000008, + 0x680: 0x10002000, + 0x780: 0x2008, + 0x880: 0x200008, + 0x980: 0x2000, + 0xa80: 0x10002008, + 0xb80: 0x10200008, + 0xc80: 0x0, + 0xd80: 0x10202000, + 0xe80: 0x202000, + 0xf80: 0x10000000, + 0x1000: 0x10002000, + 0x1100: 0x10200008, + 0x1200: 0x10202008, + 0x1300: 0x2008, + 0x1400: 0x200000, + 0x1500: 0x10000000, + 0x1600: 0x10000008, + 0x1700: 0x202000, + 0x1800: 0x202008, + 0x1900: 0x0, + 0x1a00: 0x8, + 0x1b00: 0x10200000, + 0x1c00: 0x2000, + 0x1d00: 0x10002008, + 0x1e00: 0x10202000, + 0x1f00: 0x200008, + 0x1080: 0x8, + 0x1180: 0x202000, + 0x1280: 0x200000, + 0x1380: 0x10000008, + 0x1480: 0x10002000, + 0x1580: 0x2008, + 0x1680: 0x10202008, + 0x1780: 0x10200000, + 0x1880: 0x10202000, + 0x1980: 0x10200008, + 0x1a80: 0x2000, + 0x1b80: 0x202008, + 0x1c80: 0x200008, + 0x1d80: 0x0, + 0x1e80: 0x10000000, + 0x1f80: 0x10002008 + }, + { + 0x0: 0x100000, + 0x10: 0x2000401, + 0x20: 0x400, + 0x30: 0x100401, + 0x40: 0x2100401, + 0x50: 0x0, + 0x60: 0x1, + 0x70: 0x2100001, + 0x80: 0x2000400, + 0x90: 0x100001, + 0xa0: 0x2000001, + 0xb0: 0x2100400, + 0xc0: 0x2100000, + 0xd0: 0x401, + 0xe0: 0x100400, + 0xf0: 0x2000000, + 0x8: 0x2100001, + 0x18: 0x0, + 0x28: 0x2000401, + 0x38: 0x2100400, + 0x48: 0x100000, + 0x58: 0x2000001, + 0x68: 0x2000000, + 0x78: 0x401, + 0x88: 0x100401, + 0x98: 0x2000400, + 0xa8: 0x2100000, + 0xb8: 0x100001, + 0xc8: 0x400, + 0xd8: 0x2100401, + 0xe8: 0x1, + 0xf8: 0x100400, + 0x100: 0x2000000, + 0x110: 0x100000, + 0x120: 0x2000401, + 0x130: 0x2100001, + 0x140: 0x100001, + 0x150: 0x2000400, + 0x160: 0x2100400, + 0x170: 0x100401, + 0x180: 0x401, + 0x190: 0x2100401, + 0x1a0: 0x100400, + 0x1b0: 0x1, + 0x1c0: 0x0, + 0x1d0: 0x2100000, + 0x1e0: 0x2000001, + 0x1f0: 0x400, + 0x108: 0x100400, + 0x118: 0x2000401, + 0x128: 0x2100001, + 0x138: 0x1, + 0x148: 0x2000000, + 0x158: 0x100000, + 0x168: 0x401, + 0x178: 0x2100400, + 0x188: 0x2000001, + 0x198: 0x2100000, + 0x1a8: 0x0, + 0x1b8: 0x2100401, + 0x1c8: 0x100401, + 0x1d8: 0x400, + 0x1e8: 0x2000400, + 0x1f8: 0x100001 + }, + { + 0x0: 0x8000820, + 0x1: 0x20000, + 0x2: 0x8000000, + 0x3: 0x20, + 0x4: 0x20020, + 0x5: 0x8020820, + 0x6: 0x8020800, + 0x7: 0x800, + 0x8: 0x8020000, + 0x9: 0x8000800, + 0xa: 0x20800, + 0xb: 0x8020020, + 0xc: 0x820, + 0xd: 0x0, + 0xe: 0x8000020, + 0xf: 0x20820, + 0x80000000: 0x800, + 0x80000001: 0x8020820, + 0x80000002: 0x8000820, + 0x80000003: 0x8000000, + 0x80000004: 0x8020000, + 0x80000005: 0x20800, + 0x80000006: 0x20820, + 0x80000007: 0x20, + 0x80000008: 0x8000020, + 0x80000009: 0x820, + 0x8000000a: 0x20020, + 0x8000000b: 0x8020800, + 0x8000000c: 0x0, + 0x8000000d: 0x8020020, + 0x8000000e: 0x8000800, + 0x8000000f: 0x20000, + 0x10: 0x20820, + 0x11: 0x8020800, + 0x12: 0x20, + 0x13: 0x800, + 0x14: 0x8000800, + 0x15: 0x8000020, + 0x16: 0x8020020, + 0x17: 0x20000, + 0x18: 0x0, + 0x19: 0x20020, + 0x1a: 0x8020000, + 0x1b: 0x8000820, + 0x1c: 0x8020820, + 0x1d: 0x20800, + 0x1e: 0x820, + 0x1f: 0x8000000, + 0x80000010: 0x20000, + 0x80000011: 0x800, + 0x80000012: 0x8020020, + 0x80000013: 0x20820, + 0x80000014: 0x20, + 0x80000015: 0x8020000, + 0x80000016: 0x8000000, + 0x80000017: 0x8000820, + 0x80000018: 0x8020820, + 0x80000019: 0x8000020, + 0x8000001a: 0x8000800, + 0x8000001b: 0x0, + 0x8000001c: 0x20800, + 0x8000001d: 0x820, + 0x8000001e: 0x20020, + 0x8000001f: 0x8020800 + } + ]; + + // Masks that select the SBOX input + var SBOX_MASK = [ + 0xf8000001, 0x1f800000, 0x01f80000, 0x001f8000, + 0x0001f800, 0x00001f80, 0x000001f8, 0x8000001f + ]; + + /** + * DES block cipher algorithm. + */ + var DES = C_algo.DES = BlockCipher.extend({ + _doReset: function () { + // Shortcuts + var key = this._key; + var keyWords = key.words; + + // Select 56 bits according to PC1 + var keyBits = []; + for (var i = 0; i < 56; i++) { + var keyBitPos = PC1[i] - 1; + keyBits[i] = (keyWords[keyBitPos >>> 5] >>> (31 - keyBitPos % 32)) & 1; + } + + // Assemble 16 subkeys + var subKeys = this._subKeys = []; + for (var nSubKey = 0; nSubKey < 16; nSubKey++) { + // Create subkey + var subKey = subKeys[nSubKey] = []; + + // Shortcut + var bitShift = BIT_SHIFTS[nSubKey]; + + // Select 48 bits according to PC2 + for (var i = 0; i < 24; i++) { + // Select from the left 28 key bits + subKey[(i / 6) | 0] |= keyBits[((PC2[i] - 1) + bitShift) % 28] << (31 - i % 6); + + // Select from the right 28 key bits + subKey[4 + ((i / 6) | 0)] |= keyBits[28 + (((PC2[i + 24] - 1) + bitShift) % 28)] << (31 - i % 6); + } + + // Since each subkey is applied to an expanded 32-bit input, + // the subkey can be broken into 8 values scaled to 32-bits, + // which allows the key to be used without expansion + subKey[0] = (subKey[0] << 1) | (subKey[0] >>> 31); + for (var i = 1; i < 7; i++) { + subKey[i] = subKey[i] >>> ((i - 1) * 4 + 3); + } + subKey[7] = (subKey[7] << 5) | (subKey[7] >>> 27); + } + + // Compute inverse subkeys + var invSubKeys = this._invSubKeys = []; + for (var i = 0; i < 16; i++) { + invSubKeys[i] = subKeys[15 - i]; + } + }, + + encryptBlock: function (M, offset) { + this._doCryptBlock(M, offset, this._subKeys); + }, + + decryptBlock: function (M, offset) { + this._doCryptBlock(M, offset, this._invSubKeys); + }, + + _doCryptBlock: function (M, offset, subKeys) { + // Get input + this._lBlock = M[offset]; + this._rBlock = M[offset + 1]; + + // Initial permutation + exchangeLR.call(this, 4, 0x0f0f0f0f); + exchangeLR.call(this, 16, 0x0000ffff); + exchangeRL.call(this, 2, 0x33333333); + exchangeRL.call(this, 8, 0x00ff00ff); + exchangeLR.call(this, 1, 0x55555555); + + // Rounds + for (var round = 0; round < 16; round++) { + // Shortcuts + var subKey = subKeys[round]; + var lBlock = this._lBlock; + var rBlock = this._rBlock; + + // Feistel function + var f = 0; + for (var i = 0; i < 8; i++) { + f |= SBOX_P[i][((rBlock ^ subKey[i]) & SBOX_MASK[i]) >>> 0]; + } + this._lBlock = rBlock; + this._rBlock = lBlock ^ f; + } + + // Undo swap from last round + var t = this._lBlock; + this._lBlock = this._rBlock; + this._rBlock = t; + + // Final permutation + exchangeLR.call(this, 1, 0x55555555); + exchangeRL.call(this, 8, 0x00ff00ff); + exchangeRL.call(this, 2, 0x33333333); + exchangeLR.call(this, 16, 0x0000ffff); + exchangeLR.call(this, 4, 0x0f0f0f0f); + + // Set output + M[offset] = this._lBlock; + M[offset + 1] = this._rBlock; + }, + + keySize: 64/32, + + ivSize: 64/32, + + blockSize: 64/32 + }); + + // Swap bits across the left and right words + function exchangeLR(offset, mask) { + var t = ((this._lBlock >>> offset) ^ this._rBlock) & mask; + this._rBlock ^= t; + this._lBlock ^= t << offset; + } + + function exchangeRL(offset, mask) { + var t = ((this._rBlock >>> offset) ^ this._lBlock) & mask; + this._lBlock ^= t; + this._rBlock ^= t << offset; + } + + /** + * Shortcut functions to the cipher's object interface. + * + * @example + * + * var ciphertext = CryptoJS.DES.encrypt(message, key, cfg); + * var plaintext = CryptoJS.DES.decrypt(ciphertext, key, cfg); + */ + C.DES = BlockCipher._createHelper(DES); + + /** + * Triple-DES block cipher algorithm. + */ + var TripleDES = C_algo.TripleDES = BlockCipher.extend({ + _doReset: function () { + // Shortcuts + var key = this._key; + var keyWords = key.words; + + // Create DES instances + this._des1 = DES.createEncryptor(WordArray.create(keyWords.slice(0, 2))); + this._des2 = DES.createEncryptor(WordArray.create(keyWords.slice(2, 4))); + this._des3 = DES.createEncryptor(WordArray.create(keyWords.slice(4, 6))); + }, + + encryptBlock: function (M, offset) { + this._des1.encryptBlock(M, offset); + this._des2.decryptBlock(M, offset); + this._des3.encryptBlock(M, offset); + }, + + decryptBlock: function (M, offset) { + this._des3.decryptBlock(M, offset); + this._des2.encryptBlock(M, offset); + this._des1.decryptBlock(M, offset); + }, + + keySize: 192/32, + + ivSize: 64/32, + + blockSize: 64/32 + }); + + /** + * Shortcut functions to the cipher's object interface. + * + * @example + * + * var ciphertext = CryptoJS.TripleDES.encrypt(message, key, cfg); + * var plaintext = CryptoJS.TripleDES.decrypt(ciphertext, key, cfg); + */ + C.TripleDES = BlockCipher._createHelper(TripleDES); + }()); + + + return CryptoJS.TripleDES; + +})); + +/***/ }), +/* 44 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory, undef) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14), __webpack_require__(18), __webpack_require__(19), __webpack_require__(29), __webpack_require__(30)); + } + else {} +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var StreamCipher = C_lib.StreamCipher; + var C_algo = C.algo; + + /** + * RC4 stream cipher algorithm. + */ + var RC4 = C_algo.RC4 = StreamCipher.extend({ + _doReset: function () { + // Shortcuts + var key = this._key; + var keyWords = key.words; + var keySigBytes = key.sigBytes; + + // Init sbox + var S = this._S = []; + for (var i = 0; i < 256; i++) { + S[i] = i; + } + + // Key setup + for (var i = 0, j = 0; i < 256; i++) { + var keyByteIndex = i % keySigBytes; + var keyByte = (keyWords[keyByteIndex >>> 2] >>> (24 - (keyByteIndex % 4) * 8)) & 0xff; + + j = (j + S[i] + keyByte) % 256; + + // Swap + var t = S[i]; + S[i] = S[j]; + S[j] = t; + } + + // Counters + this._i = this._j = 0; + }, + + _doProcessBlock: function (M, offset) { + M[offset] ^= generateKeystreamWord.call(this); + }, + + keySize: 256/32, + + ivSize: 0 + }); + + function generateKeystreamWord() { + // Shortcuts + var S = this._S; + var i = this._i; + var j = this._j; + + // Generate keystream word + var keystreamWord = 0; + for (var n = 0; n < 4; n++) { + i = (i + 1) % 256; + j = (j + S[i]) % 256; + + // Swap + var t = S[i]; + S[i] = S[j]; + S[j] = t; + + keystreamWord |= S[(S[i] + S[j]) % 256] << (24 - n * 8); + } + + // Update counters + this._i = i; + this._j = j; + + return keystreamWord; + } + + /** + * Shortcut functions to the cipher's object interface. + * + * @example + * + * var ciphertext = CryptoJS.RC4.encrypt(message, key, cfg); + * var plaintext = CryptoJS.RC4.decrypt(ciphertext, key, cfg); + */ + C.RC4 = StreamCipher._createHelper(RC4); + + /** + * Modified RC4 stream cipher algorithm. + */ + var RC4Drop = C_algo.RC4Drop = RC4.extend({ + /** + * Configuration options. + * + * @property {number} drop The number of keystream words to drop. Default 192 + */ + cfg: RC4.cfg.extend({ + drop: 192 + }), + + _doReset: function () { + RC4._doReset.call(this); + + // Drop + for (var i = this.cfg.drop; i > 0; i--) { + generateKeystreamWord.call(this); + } + } + }); + + /** + * Shortcut functions to the cipher's object interface. + * + * @example + * + * var ciphertext = CryptoJS.RC4Drop.encrypt(message, key, cfg); + * var plaintext = CryptoJS.RC4Drop.decrypt(ciphertext, key, cfg); + */ + C.RC4Drop = StreamCipher._createHelper(RC4Drop); + }()); + + + return CryptoJS.RC4; + +})); + +/***/ }), +/* 45 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory, undef) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14), __webpack_require__(18), __webpack_require__(19), __webpack_require__(29), __webpack_require__(30)); + } + else {} +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var StreamCipher = C_lib.StreamCipher; + var C_algo = C.algo; + + // Reusable objects + var S = []; + var C_ = []; + var G = []; + + /** + * Rabbit stream cipher algorithm + */ + var Rabbit = C_algo.Rabbit = StreamCipher.extend({ + _doReset: function () { + // Shortcuts + var K = this._key.words; + var iv = this.cfg.iv; + + // Swap endian + for (var i = 0; i < 4; i++) { + K[i] = (((K[i] << 8) | (K[i] >>> 24)) & 0x00ff00ff) | + (((K[i] << 24) | (K[i] >>> 8)) & 0xff00ff00); + } + + // Generate initial state values + var X = this._X = [ + K[0], (K[3] << 16) | (K[2] >>> 16), + K[1], (K[0] << 16) | (K[3] >>> 16), + K[2], (K[1] << 16) | (K[0] >>> 16), + K[3], (K[2] << 16) | (K[1] >>> 16) + ]; + + // Generate initial counter values + var C = this._C = [ + (K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff), + (K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff), + (K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff), + (K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff) + ]; + + // Carry bit + this._b = 0; + + // Iterate the system four times + for (var i = 0; i < 4; i++) { + nextState.call(this); + } + + // Modify the counters + for (var i = 0; i < 8; i++) { + C[i] ^= X[(i + 4) & 7]; + } + + // IV setup + if (iv) { + // Shortcuts + var IV = iv.words; + var IV_0 = IV[0]; + var IV_1 = IV[1]; + + // Generate four subvectors + var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00); + var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00); + var i1 = (i0 >>> 16) | (i2 & 0xffff0000); + var i3 = (i2 << 16) | (i0 & 0x0000ffff); + + // Modify counter values + C[0] ^= i0; + C[1] ^= i1; + C[2] ^= i2; + C[3] ^= i3; + C[4] ^= i0; + C[5] ^= i1; + C[6] ^= i2; + C[7] ^= i3; + + // Iterate the system four times + for (var i = 0; i < 4; i++) { + nextState.call(this); + } + } + }, + + _doProcessBlock: function (M, offset) { + // Shortcut + var X = this._X; + + // Iterate the system + nextState.call(this); + + // Generate four keystream words + S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16); + S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16); + S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16); + S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16); + + for (var i = 0; i < 4; i++) { + // Swap endian + S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) | + (((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00); + + // Encrypt + M[offset + i] ^= S[i]; + } + }, + + blockSize: 128/32, + + ivSize: 64/32 + }); + + function nextState() { + // Shortcuts + var X = this._X; + var C = this._C; + + // Save old counter values + for (var i = 0; i < 8; i++) { + C_[i] = C[i]; + } + + // Calculate new counter values + C[0] = (C[0] + 0x4d34d34d + this._b) | 0; + C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0; + C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0; + C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0; + C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0; + C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0; + C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0; + C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0; + this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0; + + // Calculate the g-values + for (var i = 0; i < 8; i++) { + var gx = X[i] + C[i]; + + // Construct high and low argument for squaring + var ga = gx & 0xffff; + var gb = gx >>> 16; + + // Calculate high and low result of squaring + var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb; + var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0); + + // High XOR low + G[i] = gh ^ gl; + } + + // Calculate new state values + X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0; + X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0; + X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0; + X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0; + X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0; + X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0; + X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0; + X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0; + } + + /** + * Shortcut functions to the cipher's object interface. + * + * @example + * + * var ciphertext = CryptoJS.Rabbit.encrypt(message, key, cfg); + * var plaintext = CryptoJS.Rabbit.decrypt(ciphertext, key, cfg); + */ + C.Rabbit = StreamCipher._createHelper(Rabbit); + }()); + + + return CryptoJS.Rabbit; + +})); + +/***/ }), +/* 46 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory, undef) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14), __webpack_require__(18), __webpack_require__(19), __webpack_require__(29), __webpack_require__(30)); + } + else {} +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var StreamCipher = C_lib.StreamCipher; + var C_algo = C.algo; + + // Reusable objects + var S = []; + var C_ = []; + var G = []; + + /** + * Rabbit stream cipher algorithm. + * + * This is a legacy version that neglected to convert the key to little-endian. + * This error doesn't affect the cipher's security, + * but it does affect its compatibility with other implementations. + */ + var RabbitLegacy = C_algo.RabbitLegacy = StreamCipher.extend({ + _doReset: function () { + // Shortcuts + var K = this._key.words; + var iv = this.cfg.iv; + + // Generate initial state values + var X = this._X = [ + K[0], (K[3] << 16) | (K[2] >>> 16), + K[1], (K[0] << 16) | (K[3] >>> 16), + K[2], (K[1] << 16) | (K[0] >>> 16), + K[3], (K[2] << 16) | (K[1] >>> 16) + ]; + + // Generate initial counter values + var C = this._C = [ + (K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff), + (K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff), + (K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff), + (K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff) + ]; + + // Carry bit + this._b = 0; + + // Iterate the system four times + for (var i = 0; i < 4; i++) { + nextState.call(this); + } + + // Modify the counters + for (var i = 0; i < 8; i++) { + C[i] ^= X[(i + 4) & 7]; + } + + // IV setup + if (iv) { + // Shortcuts + var IV = iv.words; + var IV_0 = IV[0]; + var IV_1 = IV[1]; + + // Generate four subvectors + var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00); + var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00); + var i1 = (i0 >>> 16) | (i2 & 0xffff0000); + var i3 = (i2 << 16) | (i0 & 0x0000ffff); + + // Modify counter values + C[0] ^= i0; + C[1] ^= i1; + C[2] ^= i2; + C[3] ^= i3; + C[4] ^= i0; + C[5] ^= i1; + C[6] ^= i2; + C[7] ^= i3; + + // Iterate the system four times + for (var i = 0; i < 4; i++) { + nextState.call(this); + } + } + }, + + _doProcessBlock: function (M, offset) { + // Shortcut + var X = this._X; + + // Iterate the system + nextState.call(this); + + // Generate four keystream words + S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16); + S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16); + S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16); + S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16); + + for (var i = 0; i < 4; i++) { + // Swap endian + S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) | + (((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00); + + // Encrypt + M[offset + i] ^= S[i]; + } + }, + + blockSize: 128/32, + + ivSize: 64/32 + }); + + function nextState() { + // Shortcuts + var X = this._X; + var C = this._C; + + // Save old counter values + for (var i = 0; i < 8; i++) { + C_[i] = C[i]; + } + + // Calculate new counter values + C[0] = (C[0] + 0x4d34d34d + this._b) | 0; + C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0; + C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0; + C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0; + C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0; + C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0; + C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0; + C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0; + this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0; + + // Calculate the g-values + for (var i = 0; i < 8; i++) { + var gx = X[i] + C[i]; + + // Construct high and low argument for squaring + var ga = gx & 0xffff; + var gb = gx >>> 16; + + // Calculate high and low result of squaring + var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb; + var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0); + + // High XOR low + G[i] = gh ^ gl; + } + + // Calculate new state values + X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0; + X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0; + X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0; + X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0; + X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0; + X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0; + X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0; + X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0; + } + + /** + * Shortcut functions to the cipher's object interface. + * + * @example + * + * var ciphertext = CryptoJS.RabbitLegacy.encrypt(message, key, cfg); + * var plaintext = CryptoJS.RabbitLegacy.decrypt(ciphertext, key, cfg); + */ + C.RabbitLegacy = StreamCipher._createHelper(RabbitLegacy); + }()); + + + return CryptoJS.RabbitLegacy; + +})); + +/***/ }), +/* 47 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Enums_1 = __webpack_require__(5); +// tslint:disable:max-classes-per-file +/** + * An Exception is considered a condition that a reasonable application may wish to catch. + * An Error indicates serious problems that a reasonable application should not try to catch. + */ +var Exception = /** @class */ (function (_super) { + __extends(Exception, _super); + function Exception(message) { + var _newTarget = this.constructor; + var _this = _super.call(this, message) || this; + Object.setPrototypeOf(_this, _newTarget.prototype); // restore prototype chain + return _this; + } + return Exception; +}(Error)); +exports.Exception = Exception; +var Exceptions; +(function (Exceptions) { + /** + * Indicates that the operation could not be completed given the current transaction state. + */ + var TransactionStateError = /** @class */ (function (_super) { + __extends(TransactionStateError, _super); + function TransactionStateError(message) { + return _super.call(this, message ? message : "Transaction state error.") || this; + } + return TransactionStateError; + }(Exception)); + Exceptions.TransactionStateError = TransactionStateError; + /** + * Indicates the session description handler has closed. + * Occurs when getDescription() or setDescription() are called after close() has been called. + * Occurs when close() is called while getDescription() or setDescription() are in progress. + */ + var ClosedSessionDescriptionHandlerError = /** @class */ (function (_super) { + __extends(ClosedSessionDescriptionHandlerError, _super); + function ClosedSessionDescriptionHandlerError() { + return _super.call(this, "The session description handler has closed.") || this; + } + return ClosedSessionDescriptionHandlerError; + }(Exception)); + Exceptions.ClosedSessionDescriptionHandlerError = ClosedSessionDescriptionHandlerError; + /** + * Indicates the session terminated before the action completed. + */ + var TerminatedSessionError = /** @class */ (function (_super) { + __extends(TerminatedSessionError, _super); + function TerminatedSessionError() { + return _super.call(this, "The session has terminated.") || this; + } + return TerminatedSessionError; + }(Exception)); + Exceptions.TerminatedSessionError = TerminatedSessionError; + /** + * Transport error. + */ + var TransportError = /** @class */ (function (_super) { + __extends(TransportError, _super); + function TransportError(message) { + return _super.call(this, message ? message : "Unspecified transport error.") || this; + } + return TransportError; + }(Exception)); + Exceptions.TransportError = TransportError; + /** + * Unsupported session description content type. + */ + var UnsupportedSessionDescriptionContentTypeError = /** @class */ (function (_super) { + __extends(UnsupportedSessionDescriptionContentTypeError, _super); + function UnsupportedSessionDescriptionContentTypeError(message) { + return _super.call(this, message ? message : "Unsupported session description content type.") || this; + } + return UnsupportedSessionDescriptionContentTypeError; + }(Exception)); + Exceptions.UnsupportedSessionDescriptionContentTypeError = UnsupportedSessionDescriptionContentTypeError; +})(Exceptions = exports.Exceptions || (exports.Exceptions = {})); +/** + * DEPRECATED: The original implementation of exceptions in this library attempted to + * deal with the lack of type checking in JavaScript by adding a "type" attribute + * to objects and using that to discriminate. On top of that it layered allcoated + * "code" numbers and constant "name" strings. All of that is unnecessary when using + * TypeScript, inheriting from Error and properly setting up the prototype chain... + */ +var LegacyException = /** @class */ (function (_super) { + __extends(LegacyException, _super); + function LegacyException(code, name, message) { + var _this = _super.call(this, message) || this; + _this.code = code; + _this.name = name; + _this.message = message; + return _this; + } + return LegacyException; +}(Exception)); +(function (Exceptions) { + var ConfigurationError = /** @class */ (function (_super) { + __extends(ConfigurationError, _super); + function ConfigurationError(parameter, value) { + var _this = _super.call(this, 1, "CONFIGURATION_ERROR", (!value) ? "Missing parameter: " + parameter : + "Invalid value " + JSON.stringify(value) + " for parameter '" + parameter + "'") || this; + _this.type = Enums_1.TypeStrings.ConfigurationError; + _this.parameter = parameter; + _this.value = value; + return _this; + } + return ConfigurationError; + }(LegacyException)); + Exceptions.ConfigurationError = ConfigurationError; + var InvalidStateError = /** @class */ (function (_super) { + __extends(InvalidStateError, _super); + function InvalidStateError(status) { + var _this = _super.call(this, 2, "INVALID_STATE_ERROR", "Invalid status: " + status) || this; + _this.type = Enums_1.TypeStrings.InvalidStateError; + _this.status = status; + return _this; + } + return InvalidStateError; + }(LegacyException)); + Exceptions.InvalidStateError = InvalidStateError; + var NotSupportedError = /** @class */ (function (_super) { + __extends(NotSupportedError, _super); + function NotSupportedError(message) { + var _this = _super.call(this, 3, "NOT_SUPPORTED_ERROR", message) || this; + _this.type = Enums_1.TypeStrings.NotSupportedError; + return _this; + } + return NotSupportedError; + }(LegacyException)); + Exceptions.NotSupportedError = NotSupportedError; + // 4 was GetDescriptionError, which was deprecated and now removed + var RenegotiationError = /** @class */ (function (_super) { + __extends(RenegotiationError, _super); + function RenegotiationError(message) { + var _this = _super.call(this, 5, "RENEGOTIATION_ERROR", message) || this; + _this.type = Enums_1.TypeStrings.RenegotiationError; + return _this; + } + return RenegotiationError; + }(LegacyException)); + Exceptions.RenegotiationError = RenegotiationError; + var MethodParameterError = /** @class */ (function (_super) { + __extends(MethodParameterError, _super); + function MethodParameterError(method, parameter, value) { + var _this = _super.call(this, 6, "METHOD_PARAMETER_ERROR", (!value) ? + "Missing parameter: " + parameter : + "Invalid value " + JSON.stringify(value) + " for parameter '" + parameter + "'") || this; + _this.type = Enums_1.TypeStrings.MethodParameterError; + _this.method = method; + _this.parameter = parameter; + _this.value = value; + return _this; + } + return MethodParameterError; + }(LegacyException)); + Exceptions.MethodParameterError = MethodParameterError; + // 7 was TransportError, which was replaced + var SessionDescriptionHandlerError = /** @class */ (function (_super) { + __extends(SessionDescriptionHandlerError, _super); + function SessionDescriptionHandlerError(method, error, message) { + var _this = _super.call(this, 8, "SESSION_DESCRIPTION_HANDLER_ERROR", message || "Error with Session Description Handler") || this; + _this.type = Enums_1.TypeStrings.SessionDescriptionHandlerError; + _this.method = method; + _this.error = error; + return _this; + } + return SessionDescriptionHandlerError; + }(LegacyException)); + Exceptions.SessionDescriptionHandlerError = SessionDescriptionHandlerError; +})(Exceptions = exports.Exceptions || (exports.Exceptions = {})); + + +/***/ }), +/* 48 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +var Enums_1 = __webpack_require__(5); +var Levels; +(function (Levels) { + Levels[Levels["error"] = 0] = "error"; + Levels[Levels["warn"] = 1] = "warn"; + Levels[Levels["log"] = 2] = "log"; + Levels[Levels["debug"] = 3] = "debug"; +})(Levels = exports.Levels || (exports.Levels = {})); +var LoggerFactory = /** @class */ (function () { + function LoggerFactory() { + this.builtinEnabled = true; + // tslint:disable-next-line:variable-name + this._level = Levels.log; + this.loggers = {}; + this.type = Enums_1.TypeStrings.LoggerFactory; + this.logger = this.getLogger("sip:loggerfactory"); + } + Object.defineProperty(LoggerFactory.prototype, "level", { + get: function () { return this._level; }, + set: function (newLevel) { + if (newLevel >= 0 && newLevel <= 3) { + this._level = newLevel; + } + else if (newLevel > 3) { + this._level = 3; + } + else if (Levels.hasOwnProperty(newLevel)) { + this._level = newLevel; + } + else { + this.logger.error("invalid 'level' parameter value: " + JSON.stringify(newLevel)); + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(LoggerFactory.prototype, "connector", { + get: function () { + return this._connector; + }, + set: function (value) { + if (!value) { + this._connector = undefined; + } + else if (typeof value === "function") { + this._connector = value; + } + else { + this.logger.error("invalid 'connector' parameter value: " + JSON.stringify(value)); + } + }, + enumerable: true, + configurable: true + }); + LoggerFactory.prototype.getLogger = function (category, label) { + if (label && this.level === 3) { + return new Logger(this, category, label); + } + else if (this.loggers[category]) { + return this.loggers[category]; + } + else { + var logger = new Logger(this, category); + this.loggers[category] = logger; + return logger; + } + }; + LoggerFactory.prototype.genericLog = function (levelToLog, category, label, content) { + if (this.level >= levelToLog) { + if (this.builtinEnabled) { + this.print(levelToLog, category, label, content); + } + } + if (this.connector) { + this.connector(Levels[levelToLog], category, label, content); + } + }; + LoggerFactory.prototype.print = function (levelToLog, category, label, content) { + if (typeof content === "string") { + var prefix = [new Date(), category]; + if (label) { + prefix.push(label); + } + content = prefix.concat(content).join(" | "); + } + switch (levelToLog) { + case Levels.error: + // tslint:disable-next-line:no-console + console.error(content); + break; + case Levels.warn: + // tslint:disable-next-line:no-console + console.warn(content); + break; + case Levels.log: + // tslint:disable-next-line:no-console + console.log(content); + break; + case Levels.debug: + // tslint:disable-next-line:no-console + console.debug(content); + break; + default: + break; + } + }; + return LoggerFactory; +}()); +exports.LoggerFactory = LoggerFactory; +// tslint:disable-next-line:max-classes-per-file +var Logger = /** @class */ (function () { + function Logger(logger, category, label) { + this.type = Enums_1.TypeStrings.Logger; + this.logger = logger; + this.category = category; + this.label = label; + } + Logger.prototype.error = function (content) { this.genericLog(Levels.error, content); }; + Logger.prototype.warn = function (content) { this.genericLog(Levels.warn, content); }; + Logger.prototype.log = function (content) { this.genericLog(Levels.log, content); }; + Logger.prototype.debug = function (content) { this.genericLog(Levels.debug, content); }; + Logger.prototype.genericLog = function (level, content) { + this.logger.genericLog(level, this.category, this.label, content); + }; + return Logger; +}()); +exports.Logger = Logger; + + +/***/ }), +/* 49 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +var Enums_1 = __webpack_require__(5); +var Grammar_1 = __webpack_require__(7); +var SIPMessage_1 = __webpack_require__(6); +// SIP.Parser = Parser; +/** + * Extract and parse every header of a SIP message. + * @namespace + */ +var Parser; +(function (Parser) { + function getHeader(data, headerStart) { + // 'start' position of the header. + var start = headerStart; + // 'end' position of the header. + var end = 0; + // 'partial end' position of the header. + var partialEnd = 0; + // End of message. + if (data.substring(start, start + 2).match(/(^\r\n)/)) { + return -2; + } + while (end === 0) { + // Partial End of Header. + partialEnd = data.indexOf("\r\n", start); + // 'indexOf' returns -1 if the value to be found never occurs. + if (partialEnd === -1) { + return partialEnd; + } + if (!data.substring(partialEnd + 2, partialEnd + 4).match(/(^\r\n)/) && + data.charAt(partialEnd + 2).match(/(^\s+)/)) { + // Not the end of the message. Continue from the next position. + start = partialEnd + 2; + } + else { + end = partialEnd; + } + } + return end; + } + Parser.getHeader = getHeader; + function parseHeader(message, data, headerStart, headerEnd) { + var hcolonIndex = data.indexOf(":", headerStart); + var headerName = data.substring(headerStart, hcolonIndex).trim(); + var headerValue = data.substring(hcolonIndex + 1, headerEnd).trim(); + var parsed; + // If header-field is well-known, parse it. + switch (headerName.toLowerCase()) { + case "via": + case "v": + message.addHeader("via", headerValue); + if (message.getHeaders("via").length === 1) { + parsed = message.parseHeader("Via"); + if (parsed) { + message.via = parsed; + message.viaBranch = parsed.branch; + } + } + else { + parsed = 0; + } + break; + case "from": + case "f": + message.setHeader("from", headerValue); + parsed = message.parseHeader("from"); + if (parsed) { + message.from = parsed; + message.fromTag = parsed.getParam("tag"); + } + break; + case "to": + case "t": + message.setHeader("to", headerValue); + parsed = message.parseHeader("to"); + if (parsed) { + message.to = parsed; + message.toTag = parsed.getParam("tag"); + } + break; + case "record-route": + parsed = Grammar_1.Grammar.parse(headerValue, "Record_Route"); + if (parsed === -1) { + parsed = undefined; + break; + } + for (var header in parsed) { + if (parsed[header]) { + message.addHeader("record-route", headerValue.substring(parsed[header].position, parsed[header].offset)); + message.headers["Record-Route"][message.getHeaders("record-route").length - 1].parsed = + parsed[header].parsed; + } + } + break; + case "call-id": + case "i": + message.setHeader("call-id", headerValue); + parsed = message.parseHeader("call-id"); + if (parsed) { + message.callId = headerValue; + } + break; + case "contact": + case "m": + parsed = Grammar_1.Grammar.parse(headerValue, "Contact"); + if (parsed === -1) { + parsed = undefined; + break; + } + if (!(parsed instanceof Array)) { + parsed = undefined; + break; + } + parsed.forEach(function (header) { + message.addHeader("contact", headerValue.substring(header.position, header.offset)); + message.headers.Contact[message.getHeaders("contact").length - 1].parsed = header.parsed; + }); + break; + case "content-length": + case "l": + message.setHeader("content-length", headerValue); + parsed = message.parseHeader("content-length"); + break; + case "content-type": + case "c": + message.setHeader("content-type", headerValue); + parsed = message.parseHeader("content-type"); + break; + case "cseq": + message.setHeader("cseq", headerValue); + parsed = message.parseHeader("cseq"); + if (parsed) { + message.cseq = parsed.value; + } + if (message.type === Enums_1.TypeStrings.IncomingResponse) { + message.method = parsed.method; + } + break; + case "max-forwards": + message.setHeader("max-forwards", headerValue); + parsed = message.parseHeader("max-forwards"); + break; + case "www-authenticate": + message.setHeader("www-authenticate", headerValue); + parsed = message.parseHeader("www-authenticate"); + break; + case "proxy-authenticate": + message.setHeader("proxy-authenticate", headerValue); + parsed = message.parseHeader("proxy-authenticate"); + break; + case "refer-to": + case "r": + message.setHeader("refer-to", headerValue); + parsed = message.parseHeader("refer-to"); + if (parsed) { + message.referTo = parsed; + } + break; + default: + // Do not parse this header. + message.setHeader(headerName, headerValue); + parsed = 0; + } + if (parsed === undefined) { + return { + error: "error parsing header '" + headerName + "'" + }; + } + else { + return true; + } + } + Parser.parseHeader = parseHeader; + /** Parse SIP Message + * @function + * @param {String} message SIP message. + * @param {Object} logger object. + * @returns {SIP.IncomingRequest|SIP.IncomingResponse|undefined} + */ + function parseMessage(data, ua) { + var headerStart = 0; + var headerEnd = data.indexOf("\r\n"); + var logger = ua.getLogger("sip.parser"); + if (headerEnd === -1) { + logger.warn("no CRLF found, not a SIP message, discarded"); + return; + } + // Parse first line. Check if it is a Request or a Reply. + var firstLine = data.substring(0, headerEnd); + var parsed = Grammar_1.Grammar.parse(firstLine, "Request_Response"); + var message; + if (parsed === -1) { + logger.warn('error parsing first line of SIP message: "' + firstLine + '"'); + return; + } + else if (!parsed.status_code) { + message = new SIPMessage_1.IncomingRequest(ua); + message.method = parsed.method; + message.ruri = parsed.uri; + } + else { + message = new SIPMessage_1.IncomingResponse(ua); + message.statusCode = parsed.status_code; + message.reasonPhrase = parsed.reason_phrase; + } + message.data = data; + headerStart = headerEnd + 2; + /* Loop over every line in data. Detect the end of each header and parse + * it or simply add to the headers collection. + */ + var bodyStart; + while (true) { + headerEnd = getHeader(data, headerStart); + // The SIP message has normally finished. + if (headerEnd === -2) { + bodyStart = headerStart + 2; + break; + } + else if (headerEnd === -1) { + // data.indexOf returned -1 due to a malformed message. + logger.error("malformed message"); + return; + } + var parsedHeader = parseHeader(message, data, headerStart, headerEnd); + if (parsedHeader !== true) { + logger.error(parsed.error); + return; + } + headerStart = headerEnd + 2; + } + /* RFC3261 18.3. + * If there are additional bytes in the transport packet + * beyond the end of the body, they MUST be discarded. + */ + if (message.hasHeader("content-length")) { + message.body = data.substr(bodyStart, Number(message.getHeader("content-length"))); + } + else { + message.body = data.substring(bodyStart); + } + return message; + } + Parser.parseMessage = parseMessage; +})(Parser = exports.Parser || (exports.Parser = {})); + + +/***/ }), +/* 50 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var ClientContext_1 = __webpack_require__(1); +var Constants_1 = __webpack_require__(3); +var Enums_1 = __webpack_require__(5); +var Exceptions_1 = __webpack_require__(47); +var SIPMessage_1 = __webpack_require__(6); +var Utils_1 = __webpack_require__(11); +/** + * SIP Publish (SIP Extension for Event State Publication RFC3903) + * @class Class creating a SIP PublishContext. + */ +var PublishContext = /** @class */ (function (_super) { + __extends(PublishContext, _super); + function PublishContext(ua, target, event, options) { + if (options === void 0) { options = {}; } + var _this = this; + options.extraHeaders = (options.extraHeaders || []).slice(); + options.contentType = (options.contentType || "text/plain"); + if (typeof options.expires !== "number" || (options.expires % 1) !== 0) { + options.expires = 3600; + } + else { + options.expires = Number(options.expires); + } + if (typeof (options.unpublishOnClose) !== "boolean") { + options.unpublishOnClose = true; + } + if (target === undefined || target === null || target === "") { + throw new Exceptions_1.Exceptions.MethodParameterError("Publish", "Target", target); + } + else { + target = ua.normalizeTarget(target); + if (target === undefined) { + throw new Exceptions_1.Exceptions.MethodParameterError("Publish", "Target", target); + } + } + _this = _super.call(this, ua, Constants_1.C.PUBLISH, target, options) || this; + _this.type = Enums_1.TypeStrings.PublishContext; + _this.options = options; + _this.target = target; + if (event === undefined || event === null || event === "") { + throw new Exceptions_1.Exceptions.MethodParameterError("Publish", "Event", event); + } + else { + _this.event = event; + } + _this.logger = ua.getLogger("sip.publish"); + _this.pubRequestExpires = _this.options.expires; + ua.on("transportCreated", function (transport) { + transport.on("transportError", function () { return _this.onTransportError(); }); + }); + return _this; + } + /** + * Publish + * @param {string} Event body to publish, optional + */ + PublishContext.prototype.publish = function (body) { + // Clean up before the run + if (this.publishRefreshTimer) { + clearTimeout(this.publishRefreshTimer); + this.publishRefreshTimer = undefined; + } + // is Inital or Modify request + this.options.body = body; + this.pubRequestBody = this.options.body; + if (this.pubRequestExpires === 0) { + // This is Initial request after unpublish + this.pubRequestExpires = this.options.expires; + this.pubRequestEtag = undefined; + } + if (!(this.ua.publishers[this.target.toString() + ":" + this.event])) { + this.ua.publishers[this.target.toString() + ":" + this.event] = this; + } + this.sendPublishRequest(); + }; + /** + * Unpublish + */ + PublishContext.prototype.unpublish = function () { + // Clean up before the run + if (this.publishRefreshTimer) { + clearTimeout(this.publishRefreshTimer); + this.publishRefreshTimer = undefined; + } + this.pubRequestBody = undefined; + this.pubRequestExpires = 0; + if (this.pubRequestEtag !== undefined) { + this.sendPublishRequest(); + } + }; + /** + * Close + */ + PublishContext.prototype.close = function () { + // Send unpublish, if requested + if (this.options.unpublishOnClose) { + this.unpublish(); + } + else { + if (this.publishRefreshTimer) { + clearTimeout(this.publishRefreshTimer); + this.publishRefreshTimer = undefined; + } + this.pubRequestBody = undefined; + this.pubRequestExpires = 0; + this.pubRequestEtag = undefined; + } + if (this.ua.publishers[this.target.toString() + ":" + this.event]) { + delete this.ua.publishers[this.target.toString() + ":" + this.event]; + } + }; + PublishContext.prototype.onRequestTimeout = function () { + _super.prototype.onRequestTimeout.call(this); + this.emit("unpublished", undefined, Constants_1.C.causes.REQUEST_TIMEOUT); + }; + PublishContext.prototype.onTransportError = function () { + _super.prototype.onTransportError.call(this); + this.emit("unpublished", undefined, Constants_1.C.causes.CONNECTION_ERROR); + }; + PublishContext.prototype.receiveResponse = function (response) { + var _this = this; + var statusCode = response.statusCode || 0; + var cause = Utils_1.Utils.getReasonPhrase(statusCode); + switch (true) { + case /^1[0-9]{2}$/.test(statusCode.toString()): + this.emit("progress", response, cause); + break; + case /^2[0-9]{2}$/.test(statusCode.toString()): + // Set SIP-Etag + if (response.hasHeader("SIP-ETag")) { + this.pubRequestEtag = response.getHeader("SIP-ETag"); + } + else { + this.logger.warn("SIP-ETag header missing in a 200-class response to PUBLISH"); + } + // Update Expire + if (response.hasHeader("Expires")) { + var expires = Number(response.getHeader("Expires")); + if (typeof expires === "number" && expires >= 0 && expires <= this.pubRequestExpires) { + this.pubRequestExpires = expires; + } + else { + this.logger.warn("Bad Expires header in a 200-class response to PUBLISH"); + } + } + else { + this.logger.warn("Expires header missing in a 200-class response to PUBLISH"); + } + if (this.pubRequestExpires !== 0) { + // Schedule refresh + this.publishRefreshTimer = setTimeout(function () { return _this.refreshRequest(); }, this.pubRequestExpires * 900); + this.emit("published", response, cause); + } + else { + this.emit("unpublished", response, cause); + } + break; + case /^412$/.test(statusCode.toString()): + // 412 code means no matching ETag - possibly the PUBLISH expired + // Resubmit as new request, if the current request is not a "remove" + if (this.pubRequestEtag !== undefined && this.pubRequestExpires !== 0) { + this.logger.warn("412 response to PUBLISH, recovering"); + this.pubRequestEtag = undefined; + this.emit("progress", response, cause); + this.publish(this.options.body); + } + else { + this.logger.warn("412 response to PUBLISH, recovery failed"); + this.pubRequestExpires = 0; + this.emit("failed", response, cause); + this.emit("unpublished", response, cause); + } + break; + case /^423$/.test(statusCode.toString()): + // 423 code means we need to adjust the Expires interval up + if (this.pubRequestExpires !== 0 && response.hasHeader("Min-Expires")) { + var minExpires = Number(response.getHeader("Min-Expires")); + if (typeof minExpires === "number" || minExpires > this.pubRequestExpires) { + this.logger.warn("423 code in response to PUBLISH, adjusting the Expires value and trying to recover"); + this.pubRequestExpires = minExpires; + this.emit("progress", response, cause); + this.publish(this.options.body); + } + else { + this.logger.warn("Bad 423 response Min-Expires header received for PUBLISH"); + this.pubRequestExpires = 0; + this.emit("failed", response, cause); + this.emit("unpublished", response, cause); + } + } + else { + this.logger.warn("423 response to PUBLISH, recovery failed"); + this.pubRequestExpires = 0; + this.emit("failed", response, cause); + this.emit("unpublished", response, cause); + } + break; + default: + this.pubRequestExpires = 0; + this.emit("failed", response, cause); + this.emit("unpublished", response, cause); + break; + } + // Do the cleanup + if (this.pubRequestExpires === 0) { + if (this.publishRefreshTimer) { + clearTimeout(this.publishRefreshTimer); + this.publishRefreshTimer = undefined; + } + this.pubRequestBody = undefined; + this.pubRequestEtag = undefined; + } + }; + PublishContext.prototype.send = function () { + var _this = this; + this.ua.userAgentCore.publish(this.request, { + onAccept: function (response) { return _this.receiveResponse(response.message); }, + onProgress: function (response) { return _this.receiveResponse(response.message); }, + onRedirect: function (response) { return _this.receiveResponse(response.message); }, + onReject: function (response) { return _this.receiveResponse(response.message); }, + onTrying: function (response) { return _this.receiveResponse(response.message); } + }); + return this; + }; + PublishContext.prototype.refreshRequest = function () { + // Clean up before the run + if (this.publishRefreshTimer) { + clearTimeout(this.publishRefreshTimer); + this.publishRefreshTimer = undefined; + } + // This is Refresh request + this.pubRequestBody = undefined; + if (this.pubRequestEtag === undefined) { + // Request not valid + throw new Exceptions_1.Exceptions.MethodParameterError("Publish", "Body", undefined); + } + if (this.pubRequestExpires === 0) { + // Request not valid + throw new Exceptions_1.Exceptions.MethodParameterError("Publish", "Expire", this.pubRequestExpires); + } + this.sendPublishRequest(); + }; + PublishContext.prototype.sendPublishRequest = function () { + var reqOptions = Object.create(this.options || Object.prototype); + reqOptions.extraHeaders = (this.options.extraHeaders || []).slice(); + reqOptions.extraHeaders.push("Event: " + this.event); + reqOptions.extraHeaders.push("Expires: " + this.pubRequestExpires); + if (this.pubRequestEtag !== undefined) { + reqOptions.extraHeaders.push("SIP-If-Match: " + this.pubRequestEtag); + } + this.request = new SIPMessage_1.OutgoingRequest(Constants_1.C.PUBLISH, this.target, this.ua, this.options.params, reqOptions.extraHeaders); + if (this.pubRequestBody !== undefined) { + this.request.body = { + body: this.pubRequestBody, + contentType: this.options.contentType + }; + } + this.send(); + }; + return PublishContext; +}(ClientContext_1.ClientContext)); +exports.PublishContext = PublishContext; + + +/***/ }), +/* 51 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var ClientContext_1 = __webpack_require__(1); +var Constants_1 = __webpack_require__(3); +var transactions_1 = __webpack_require__(52); +var Enums_1 = __webpack_require__(5); +var Exceptions_1 = __webpack_require__(47); +var Grammar_1 = __webpack_require__(7); +var ServerContext_1 = __webpack_require__(62); +var SIPMessage_1 = __webpack_require__(6); +// tslint:disable-next-line:max-classes-per-file +var ReferClientContext = /** @class */ (function (_super) { + __extends(ReferClientContext, _super); + function ReferClientContext(ua, applicant, target, options) { + if (options === void 0) { options = {}; } + var _this = this; + if (ua === undefined || applicant === undefined || target === undefined) { + throw new TypeError("Not enough arguments"); + } + _this = _super.call(this, ua, Constants_1.C.REFER, applicant.remoteIdentity.uri.toString(), options) || this; + _this.type = Enums_1.TypeStrings.ReferClientContext; + _this.options = options; + _this.extraHeaders = (_this.options.extraHeaders || []).slice(); + _this.applicant = applicant; + _this.target = _this.initReferTo(target); + if (_this.ua) { + _this.extraHeaders.push("Referred-By: <" + _this.ua.configuration.uri + ">"); + } + // TODO: Check that this is correct isc/icc + _this.extraHeaders.push("Contact: " + applicant.contact); + // this is UA.C.ALLOWED_METHODS, removed to get around circular dependency + _this.extraHeaders.push("Allow: " + [ + "ACK", + "CANCEL", + "INVITE", + "MESSAGE", + "BYE", + "OPTIONS", + "INFO", + "NOTIFY", + "REFER" + ].toString()); + _this.extraHeaders.push("Refer-To: " + _this.target); + _this.errorListener = _this.onTransportError.bind(_this); + if (ua.transport) { + ua.transport.on("transportError", _this.errorListener); + } + return _this; + } + ReferClientContext.prototype.refer = function (options) { + var _this = this; + if (options === void 0) { options = {}; } + var extraHeaders = (this.extraHeaders || []).slice(); + if (options.extraHeaders) { + extraHeaders.concat(options.extraHeaders); + } + this.applicant.sendRequest(Constants_1.C.REFER, { + extraHeaders: this.extraHeaders, + receiveResponse: function (response) { + var statusCode = response && response.statusCode ? response.statusCode.toString() : ""; + if (/^1[0-9]{2}$/.test(statusCode)) { + _this.emit("referRequestProgress", _this); + } + else if (/^2[0-9]{2}$/.test(statusCode)) { + _this.emit("referRequestAccepted", _this); + } + else if (/^[4-6][0-9]{2}$/.test(statusCode)) { + _this.emit("referRequestRejected", _this); + } + if (options.receiveResponse) { + options.receiveResponse(response); + } + } + }); + return this; + }; + ReferClientContext.prototype.receiveNotify = function (request) { + // If we can correctly handle this, then we need to send a 200 OK! + var contentType = request.message.hasHeader("Content-Type") ? + request.message.getHeader("Content-Type") : undefined; + if (contentType && contentType.search(/^message\/sipfrag/) !== -1) { + var messageBody = Grammar_1.Grammar.parse(request.message.body, "sipfrag"); + if (messageBody === -1) { + request.reject({ + statusCode: 489, + reasonPhrase: "Bad Event" + }); + return; + } + switch (true) { + case (/^1[0-9]{2}$/.test(messageBody.status_code)): + this.emit("referProgress", this); + break; + case (/^2[0-9]{2}$/.test(messageBody.status_code)): + this.emit("referAccepted", this); + if (!this.options.activeAfterTransfer && this.applicant.terminate) { + this.applicant.terminate(); + } + break; + default: + this.emit("referRejected", this); + break; + } + request.accept(); + this.emit("notify", request.message); + return; + } + request.reject({ + statusCode: 489, + reasonPhrase: "Bad Event" + }); + }; + ReferClientContext.prototype.initReferTo = function (target) { + var stringOrURI; + if (typeof target === "string") { + // REFER without Replaces (Blind Transfer) + var targetString = Grammar_1.Grammar.parse(target, "Refer_To"); + stringOrURI = targetString && targetString.uri ? targetString.uri : target; + // Check target validity + var targetUri = this.ua.normalizeTarget(target); + if (!targetUri) { + throw new TypeError("Invalid target: " + target); + } + stringOrURI = targetUri; + } + else { + // REFER with Replaces (Attended Transfer) + if (!target.session) { + throw new Error("Session undefined."); + } + var displayName = target.remoteIdentity.friendlyName; + var remoteTarget = target.session.remoteTarget.toString(); + var callId = target.session.callId; + var remoteTag = target.session.remoteTag; + var localTag = target.session.localTag; + var replaces = encodeURIComponent(callId + ";to-tag=" + remoteTag + ";from-tag=" + localTag); + stringOrURI = "\"" + displayName + "\" <" + remoteTarget + "?Replaces=" + replaces + ">"; + } + return stringOrURI; + }; + return ReferClientContext; +}(ClientContext_1.ClientContext)); +exports.ReferClientContext = ReferClientContext; +// tslint:disable-next-line:max-classes-per-file +var ReferServerContext = /** @class */ (function (_super) { + __extends(ReferServerContext, _super); + function ReferServerContext(ua, incomingRequest, session) { + var _this = _super.call(this, ua, incomingRequest) || this; + _this.session = session; + _this.type = Enums_1.TypeStrings.ReferServerContext; + _this.ua = ua; + _this.status = Enums_1.SessionStatus.STATUS_INVITE_RECEIVED; + _this.fromTag = _this.request.fromTag; + _this.id = _this.request.callId + _this.fromTag; + _this.contact = _this.ua.contact.toString(); + _this.logger = ua.getLogger("sip.referservercontext", _this.id); + // Needed to send the NOTIFY's + _this.cseq = Math.floor(Math.random() * 10000); + _this.callId = _this.request.callId; + _this.fromUri = _this.request.to.uri; + _this.fromTag = _this.request.to.parameters.tag; + _this.remoteTarget = _this.request.headers.Contact[0].parsed.uri; + _this.toUri = _this.request.from.uri; + _this.toTag = _this.request.fromTag; + _this.routeSet = _this.request.getHeaders("record-route"); + // RFC 3515 2.4.1 + if (!_this.request.hasHeader("refer-to")) { + _this.logger.warn("Invalid REFER packet. A refer-to header is required. Rejecting refer."); + _this.reject(); + return _this; + } + _this.referTo = _this.request.parseHeader("refer-to"); + // TODO: Must set expiration timer and send 202 if there is no response by then + _this.referredSession = _this.ua.findSession(_this.request); + if (_this.request.hasHeader("referred-by")) { + _this.referredBy = _this.request.getHeader("referred-by"); + } + if (_this.referTo.uri.hasHeader("replaces")) { + _this.replaces = _this.referTo.uri.getHeader("replaces"); + } + _this.errorListener = _this.onTransportError.bind(_this); + if (ua.transport) { + ua.transport.on("transportError", _this.errorListener); + } + _this.status = Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER; + return _this; + } + ReferServerContext.prototype.progress = function () { + if (this.status !== Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER) { + throw new Exceptions_1.Exceptions.InvalidStateError(this.status); + } + this.incomingRequest.trying(); + }; + ReferServerContext.prototype.reject = function (options) { + if (options === void 0) { options = {}; } + if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { + throw new Exceptions_1.Exceptions.InvalidStateError(this.status); + } + this.logger.log("Rejecting refer"); + this.status = Enums_1.SessionStatus.STATUS_TERMINATED; + _super.prototype.reject.call(this, options); + this.emit("referRequestRejected", this); + }; + ReferServerContext.prototype.accept = function (options, modifiers) { + var _this = this; + if (options === void 0) { options = {}; } + if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER) { + this.status = Enums_1.SessionStatus.STATUS_ANSWERED; + } + else { + throw new Exceptions_1.Exceptions.InvalidStateError(this.status); + } + this.incomingRequest.accept({ + statusCode: 202, + reasonPhrase: "Accepted" + }); + this.emit("referRequestAccepted", this); + if (options.followRefer) { + this.logger.log("Accepted refer, attempting to automatically follow it"); + var target = this.referTo.uri; + if (!target.scheme || !target.scheme.match("^sips?$")) { + this.logger.error("SIP.js can only automatically follow SIP refer target"); + this.reject(); + return; + } + var inviteOptions = options.inviteOptions || {}; + var extraHeaders = (inviteOptions.extraHeaders || []).slice(); + if (this.replaces) { + // decodeURIComponent is a holdover from 2c086eb4. Not sure that it is actually necessary + extraHeaders.push("Replaces: " + decodeURIComponent(this.replaces)); + } + if (this.referredBy) { + extraHeaders.push("Referred-By: " + this.referredBy); + } + inviteOptions.extraHeaders = extraHeaders; + target.clearHeaders(); + this.targetSession = this.ua.invite(target.toString(), inviteOptions, modifiers); + this.emit("referInviteSent", this); + if (this.targetSession) { + this.targetSession.once("progress", function (response) { + var statusCode = response.statusCode || 100; + var reasonPhrase = response.reasonPhrase; + _this.sendNotify(("SIP/2.0 " + statusCode + " " + reasonPhrase).trim()); + _this.emit("referProgress", _this); + if (_this.referredSession) { + _this.referredSession.emit("referProgress", _this); + } + }); + this.targetSession.once("accepted", function () { + _this.logger.log("Successfully followed the refer"); + _this.sendNotify("SIP/2.0 200 OK"); + _this.emit("referAccepted", _this); + if (_this.referredSession) { + _this.referredSession.emit("referAccepted", _this); + } + }); + var referFailed = function (response) { + if (_this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { + return; // No throw here because it is possible this gets called multiple times + } + _this.logger.log("Refer was not successful. Resuming session"); + if (response && response.statusCode === 429) { + _this.logger.log("Alerting referrer that identity is required."); + _this.sendNotify("SIP/2.0 429 Provide Referrer Identity"); + return; + } + _this.sendNotify("SIP/2.0 603 Declined"); + // Must change the status after sending the final Notify or it will not send due to check + _this.status = Enums_1.SessionStatus.STATUS_TERMINATED; + _this.emit("referRejected", _this); + if (_this.referredSession) { + _this.referredSession.emit("referRejected"); + } + }; + this.targetSession.once("rejected", referFailed); + this.targetSession.once("failed", referFailed); + } + } + else { + this.logger.log("Accepted refer, but did not automatically follow it"); + this.sendNotify("SIP/2.0 200 OK"); + this.emit("referAccepted", this); + if (this.referredSession) { + this.referredSession.emit("referAccepted", this); + } + } + }; + ReferServerContext.prototype.sendNotify = function (body) { + // FIXME: Ported this. Clean it up. Session knows its state. + if (this.status !== Enums_1.SessionStatus.STATUS_ANSWERED) { + throw new Exceptions_1.Exceptions.InvalidStateError(this.status); + } + if (Grammar_1.Grammar.parse(body, "sipfrag") === -1) { + throw new Error("sipfrag body is required to send notify for refer"); + } + // NOTIFY requests sent in same dialog as in dialog REFER. + if (this.session) { + this.session.notify(undefined, { + extraHeaders: [ + "Event: refer", + "Subscription-State: terminated", + ], + body: { + contentDisposition: "render", + contentType: "message/sipfrag", + content: body + } + }); + return; + } + // The implicit subscription created by a REFER is the same as a + // subscription created with a SUBSCRIBE request. The agent issuing the + // REFER can terminate this subscription prematurely by unsubscribing + // using the mechanisms described in [2]. Terminating a subscription, + // either by explicitly unsubscribing or rejecting NOTIFY, is not an + // indication that the referenced request should be withdrawn or + // abandoned. + // https://tools.ietf.org/html/rfc3515#section-2.4.4 + // NOTIFY requests sent in new dialog for out of dialog REFER. + // FIXME: TODO: This should be done in a subscribe dialog to satisfy the above. + var request = new SIPMessage_1.OutgoingRequest(Constants_1.C.NOTIFY, this.remoteTarget, this.ua, { + cseq: this.cseq += 1, + callId: this.callId, + fromUri: this.fromUri, + fromTag: this.fromTag, + toUri: this.toUri, + toTag: this.toTag, + routeSet: this.routeSet + }, [ + "Event: refer", + "Subscription-State: terminated", + "Content-Type: message/sipfrag" + ], body); + var transport = this.ua.transport; + if (!transport) { + throw new Error("Transport undefined."); + } + var user = { + loggerFactory: this.ua.getLoggerFactory() + }; + var nic = new transactions_1.NonInviteClientTransaction(request, transport, user); + }; + ReferServerContext.prototype.on = function (name, callback) { return _super.prototype.on.call(this, name, callback); }; + return ReferServerContext; +}(ServerContext_1.ServerContext)); +exports.ReferServerContext = ReferServerContext; + + +/***/ }), +/* 52 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +function __export(m) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; +} +Object.defineProperty(exports, "__esModule", { value: true }); +__export(__webpack_require__(53)); +__export(__webpack_require__(55)); +__export(__webpack_require__(58)); +__export(__webpack_require__(60)); +__export(__webpack_require__(61)); +__export(__webpack_require__(55)); +__export(__webpack_require__(59)); +__export(__webpack_require__(57)); +__export(__webpack_require__(54)); + + +/***/ }), +/* 53 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var transaction_1 = __webpack_require__(54); +/** + * Client Transaction + * + * The client transaction provides its functionality through the + * maintenance of a state machine. + * + * The TU communicates with the client transaction through a simple + * interface. When the TU wishes to initiate a new transaction, it + * creates a client transaction and passes it the SIP request to send + * and an IP address, port, and transport to which to send it. The + * client transaction begins execution of its state machine. Valid + * responses are passed up to the TU from the client transaction. + * https://tools.ietf.org/html/rfc3261#section-17.1 + */ +var ClientTransaction = /** @class */ (function (_super) { + __extends(ClientTransaction, _super); + function ClientTransaction(_request, transport, user, state, loggerCategory) { + var _this = _super.call(this, transport, user, ClientTransaction.makeId(_request), state, loggerCategory) || this; + _this._request = _request; + _this.user = user; + // The Via header field indicates the transport used for the transaction + // and identifies the location where the response is to be sent. A Via + // header field value is added only after the transport that will be + // used to reach the next hop has been selected (which may involve the + // usage of the procedures in [4]). + // https://tools.ietf.org/html/rfc3261#section-8.1.1.7 + _request.setViaHeader(_this.id, transport); + return _this; + } + ClientTransaction.makeId = function (request) { + if (request.method === "CANCEL") { + if (!request.branch) { + throw new Error("Outgoing CANCEL request without a branch."); + } + return request.branch; + } + else { + return "z9hG4bK" + Math.floor(Math.random() * 10000000); + } + }; + Object.defineProperty(ClientTransaction.prototype, "request", { + /** The outgoing request the transaction handling. */ + get: function () { + return this._request; + }, + enumerable: true, + configurable: true + }); + /** + * A 408 to non-INVITE will always arrive too late to be useful ([3]), + * The client already has full knowledge of the timeout. The only + * information this message would convey is whether or not the server + * believed the transaction timed out. However, with the current design + * of the NIT, a client cannot do anything with this knowledge. Thus, + * the 408 is simply wasting network resources and contributes to the + * response bombardment illustrated in [3]. + * https://tools.ietf.org/html/rfc4320#section-4.1 + */ + ClientTransaction.prototype.onRequestTimeout = function () { + if (this.user.onRequestTimeout) { + this.user.onRequestTimeout(); + } + }; + return ClientTransaction; +}(transaction_1.Transaction)); +exports.ClientTransaction = ClientTransaction; + + +/***/ }), +/* 54 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var events_1 = __webpack_require__(2); +var Exceptions_1 = __webpack_require__(47); +/** + * Transaction + * + * SIP is a transactional protocol: interactions between components take + * place in a series of independent message exchanges. Specifically, a + * SIP transaction consists of a single request and any responses to + * that request, which include zero or more provisional responses and + * one or more final responses. In the case of a transaction where the + * request was an INVITE (known as an INVITE transaction), the + * transaction also includes the ACK only if the final response was not + * a 2xx response. If the response was a 2xx, the ACK is not considered + * part of the transaction. + * https://tools.ietf.org/html/rfc3261#section-17 + */ +var Transaction = /** @class */ (function (_super) { + __extends(Transaction, _super); + function Transaction(_transport, _user, _id, _state, loggerCategory) { + var _this = _super.call(this) || this; + _this._transport = _transport; + _this._user = _user; + _this._id = _id; + _this._state = _state; + _this.logger = _user.loggerFactory.getLogger(loggerCategory, _id); + _this.logger.debug("Constructing " + _this.typeToString() + " with id " + _this.id + "."); + return _this; + } + /** + * Destructor. + * Once the transaction is in the "terminated" state, it is destroyed + * immediately and there is no need to call `dispose`. However, if a + * transaction needs to be ended prematurely, the transaction user may + * do so by calling this method (for example, perhaps the UA is shutting down). + * No state transition will occur upon calling this method, all outstanding + * transmission timers will be cancelled, and use of the transaction after + * calling `dispose` is undefined. + */ + Transaction.prototype.dispose = function () { + this.logger.debug("Destroyed " + this.typeToString() + " with id " + this.id + "."); + }; + Object.defineProperty(Transaction.prototype, "id", { + /** Transaction id. */ + get: function () { + return this._id; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Transaction.prototype, "kind", { + /** Transaction kind. Deprecated. */ + get: function () { + throw new Error("Invalid kind."); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Transaction.prototype, "state", { + /** Transaction state. */ + get: function () { + return this._state; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Transaction.prototype, "transport", { + /** Transaction transport. */ + get: function () { + return this._transport; + }, + enumerable: true, + configurable: true + }); + Transaction.prototype.on = function (name, callback) { return _super.prototype.on.call(this, name, callback); }; + Transaction.prototype.logTransportError = function (error, message) { + this.logger.error(error.message); + this.logger.error("Transport error occurred in " + this.typeToString() + " with id " + this.id + "."); + this.logger.error(message); + }; + /** + * Pass message to transport for transmission. If transport fails, + * the transaction user is notified by callback to onTransportError(). + * @throws {TransportError} If transport fails. + */ + Transaction.prototype.send = function (message) { + var _this = this; + return this.transport.send(message).catch(function (error) { + // FIXME: Transport is not, yet, typed and it is not clear + // yet what send() may or may not send our way. So for now, + // make sure we convert it to a TransportError if need be. + if (error instanceof Exceptions_1.Exceptions.TransportError) { + _this.onTransportError(error); + return; + } + var transportError; + if (error && typeof error.message === "string") { + transportError = new Exceptions_1.Exceptions.TransportError(error.message); + } + else { + transportError = new Exceptions_1.Exceptions.TransportError(); + } + _this.onTransportError(transportError); + throw transportError; + }); + }; + Transaction.prototype.setState = function (state) { + this.logger.debug("State change to \"" + state + "\" on " + this.typeToString() + " with id " + this.id + "."); + this._state = state; + if (this._user.onStateChange) { + this._user.onStateChange(state); + } + this.emit("stateChanged"); + }; + Transaction.prototype.typeToString = function () { + return "UnknownType"; + }; + return Transaction; +}(events_1.EventEmitter)); +exports.Transaction = Transaction; + + +/***/ }), +/* 55 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Timers_1 = __webpack_require__(56); +var client_transaction_1 = __webpack_require__(53); +var transaction_state_1 = __webpack_require__(57); +/** + * INVITE Client Transaction + * + * The INVITE transaction consists of a three-way handshake. The client + * transaction sends an INVITE, the server transaction sends responses, + * and the client transaction sends an ACK. + * https://tools.ietf.org/html/rfc3261#section-17.1.1 + */ +var InviteClientTransaction = /** @class */ (function (_super) { + __extends(InviteClientTransaction, _super); + /** + * Constructor. + * Upon construction, the outgoing request's Via header is updated by calling `setViaHeader`. + * Then `toString` is called on the outgoing request and the message is sent via the transport. + * After construction the transaction will be in the "calling" state and the transaction id + * will equal the branch parameter set in the Via header of the outgoing request. + * https://tools.ietf.org/html/rfc3261#section-17.1.1 + * @param request The outgoing INVITE request. + * @param transport The transport. + * @param user The transaction user. + */ + function InviteClientTransaction(request, transport, user) { + var _this = _super.call(this, request, transport, user, transaction_state_1.TransactionState.Calling, "sip.transaction.ict") || this; + /** + * Map of 2xx to-tag => ACK. + * If value is not undefined, value is the ACK which was sent. + * If key exists but value is undefined, a 2xx was received but the ACK not yet sent. + * Otherwise, a 2xx was not (yet) received for this transaction. + */ + _this.ackRetransmissionCache = new Map(); + // FIXME: Timer A for unreliable transport not implemented + // + // If an unreliable transport is being used, the client transaction + // MUST start timer A with a value of T1. If a reliable transport is being used, + // the client transaction SHOULD NOT start timer A (Timer A controls request retransmissions). + // For any transport, the client transaction MUST start timer B with a value + // of 64*T1 seconds (Timer B controls transaction timeouts). + // https://tools.ietf.org/html/rfc3261#section-17.1.1.2 + // + // While not spelled out in the RFC, Timer B is the maximum amount of time that a sender + // will wait for an INVITE message to be acknowledged (a SIP response message is received). + // So Timer B should be cleared when the transaction state proceeds from "Calling". + _this.B = setTimeout(function () { return _this.timer_B(); }, Timers_1.Timers.TIMER_B); + _this.send(request.toString()).catch(function (error) { + _this.logTransportError(error, "Failed to send initial outgoing request."); + }); + return _this; + } + /** + * Destructor. + */ + InviteClientTransaction.prototype.dispose = function () { + if (this.B) { + clearTimeout(this.B); + this.B = undefined; + } + if (this.D) { + clearTimeout(this.D); + this.D = undefined; + } + if (this.M) { + clearTimeout(this.M); + this.M = undefined; + } + _super.prototype.dispose.call(this); + }; + Object.defineProperty(InviteClientTransaction.prototype, "kind", { + /** Transaction kind. Deprecated. */ + get: function () { + return "ict"; + }, + enumerable: true, + configurable: true + }); + /** + * ACK a 2xx final response. + * + * The transaction includes the ACK only if the final response was not a 2xx response (the + * transaction will generate and send the ACK to the transport automagically). If the + * final response was a 2xx, the ACK is not considered part of the transaction (the + * transaction user needs to generate and send the ACK). + * + * This library is not strictly RFC compliant with regard to ACK handling for 2xx final + * responses. Specifically, retransmissions of ACKs to a 2xx final responses is handled + * by the transaction layer (instead of the UAC core). The "standard" approach is for + * the UAC core to receive all 2xx responses and manage sending ACK retransmissions to + * the transport directly. Herein the transaction layer manages sending ACKs to 2xx responses + * and any retransmissions of those ACKs as needed. + * + * @param ack The outgoing ACK request. + */ + InviteClientTransaction.prototype.ackResponse = function (ack) { + var _this = this; + var toTag = ack.toTag; + if (!toTag) { + throw new Error("To tag undefined."); + } + var id = "z9hG4bK" + Math.floor(Math.random() * 10000000); + ack.setViaHeader(id, this.transport); + this.ackRetransmissionCache.set(toTag, ack); // Add to ACK retransmission cache + this.send(ack.toString()).catch(function (error) { + _this.logTransportError(error, "Failed to send ACK to 2xx response."); + }); + }; + /** + * Handler for incoming responses from the transport which match this transaction. + * @param response The incoming response. + */ + InviteClientTransaction.prototype.receiveResponse = function (response) { + var _this = this; + var statusCode = response.statusCode; + if (!statusCode || statusCode < 100 || statusCode > 699) { + throw new Error("Invalid status code " + statusCode); + } + switch (this.state) { + case transaction_state_1.TransactionState.Calling: + // If the client transaction receives a provisional response while in + // the "Calling" state, it transitions to the "Proceeding" state. In the + // "Proceeding" state, the client transaction SHOULD NOT retransmit the + // request any longer. Furthermore, the provisional response MUST be + // passed to the TU. Any further provisional responses MUST be passed + // up to the TU while in the "Proceeding" state. + // https://tools.ietf.org/html/rfc3261#section-17.1.1.2 + if (statusCode >= 100 && statusCode <= 199) { + this.stateTransition(transaction_state_1.TransactionState.Proceeding); + if (this.user.receiveResponse) { + this.user.receiveResponse(response); + } + return; + } + // When a 2xx response is received while in either the "Calling" or + // "Proceeding" states, the client transaction MUST transition to + // the "Accepted" state... The 2xx response MUST be passed up to the TU. + // The client transaction MUST NOT generate an ACK to the 2xx response -- its + // handling is delegated to the TU. A UAC core will send an ACK to + // the 2xx response using a new transaction. + // https://tools.ietf.org/html/rfc6026#section-8.4 + if (statusCode >= 200 && statusCode <= 299) { + this.ackRetransmissionCache.set(response.toTag, undefined); // Prime the ACK cache + this.stateTransition(transaction_state_1.TransactionState.Accepted); + if (this.user.receiveResponse) { + this.user.receiveResponse(response); + } + return; + } + // When in either the "Calling" or "Proceeding" states, reception of + // a response with status code from 300-699 MUST cause the client + // transaction to transition to "Completed". The client transaction + // MUST pass the received response up to the TU, and the client + // transaction MUST generate an ACK request, even if the transport is + // reliable (guidelines for constructing the ACK from the response + // are given in Section 17.1.1.3), and then pass the ACK to the + // transport layer for transmission. The ACK MUST be sent to the + // same address, port, and transport to which the original request was sent. + // https://tools.ietf.org/html/rfc6026#section-8.4 + if (statusCode >= 300 && statusCode <= 699) { + this.stateTransition(transaction_state_1.TransactionState.Completed); + this.ack(response); + if (this.user.receiveResponse) { + this.user.receiveResponse(response); + } + return; + } + break; + case transaction_state_1.TransactionState.Proceeding: + // In the "Proceeding" state, the client transaction SHOULD NOT retransmit the + // request any longer. Furthermore, the provisional response MUST be + // passed to the TU. Any further provisional responses MUST be passed + // up to the TU while in the "Proceeding" state. + // https://tools.ietf.org/html/rfc3261#section-17.1.1.2 + if (statusCode >= 100 && statusCode <= 199) { + if (this.user.receiveResponse) { + this.user.receiveResponse(response); + } + return; + } + // When a 2xx response is received while in either the "Calling" or "Proceeding" states, + // the client transaction MUST transition to the "Accepted" state... + // The 2xx response MUST be passed up to the TU. The client + // transaction MUST NOT generate an ACK to the 2xx response -- its + // handling is delegated to the TU. A UAC core will send an ACK to + // the 2xx response using a new transaction. + // https://tools.ietf.org/html/rfc6026#section-8.4 + if (statusCode >= 200 && statusCode <= 299) { + this.ackRetransmissionCache.set(response.toTag, undefined); // Prime the ACK cache + this.stateTransition(transaction_state_1.TransactionState.Accepted); + if (this.user.receiveResponse) { + this.user.receiveResponse(response); + } + return; + } + // When in either the "Calling" or "Proceeding" states, reception of + // a response with status code from 300-699 MUST cause the client + // transaction to transition to "Completed". The client transaction + // MUST pass the received response up to the TU, and the client + // transaction MUST generate an ACK request, even if the transport is + // reliable (guidelines for constructing the ACK from the response + // are given in Section 17.1.1.3), and then pass the ACK to the + // transport layer for transmission. The ACK MUST be sent to the + // same address, port, and transport to which the original request was sent. + // https://tools.ietf.org/html/rfc6026#section-8.4 + if (statusCode >= 300 && statusCode <= 699) { + this.stateTransition(transaction_state_1.TransactionState.Completed); + this.ack(response); + if (this.user.receiveResponse) { + this.user.receiveResponse(response); + } + return; + } + break; + case transaction_state_1.TransactionState.Accepted: + // The purpose of the "Accepted" state is to allow the client + // transaction to continue to exist to receive, and pass to the TU, + // any retransmissions of the 2xx response and any additional 2xx + // responses from other branches of the INVITE if it forked + // downstream. Timer M reflects the amount of time that the + // transaction user will wait for such messages. + // + // Any 2xx responses that match this client transaction and that are + // received while in the "Accepted" state MUST be passed up to the + // TU. The client transaction MUST NOT generate an ACK to the 2xx + // response. The client transaction takes no further action. + // https://tools.ietf.org/html/rfc6026#section-8.4 + if (statusCode >= 200 && statusCode <= 299) { + // NOTE: This implementation herein is intentionally not RFC compliant. + // While the first 2xx response for a given branch is passed up to the TU, + // retransmissions of 2xx responses are absorbed and the ACK associated + // with the original response is resent. This approach is taken because + // our current transaction users are not currently in a good position to + // deal with 2xx retransmission. This SHOULD NOT cause any compliance issues - ;) + // + // If we don't have a cache hit, pass the response to the TU. + if (!this.ackRetransmissionCache.has(response.toTag)) { + this.ackRetransmissionCache.set(response.toTag, undefined); // Prime the ACK cache + if (this.user.receiveResponse) { + this.user.receiveResponse(response); + } + return; + } + // If we have a cache hit, try pulling the ACK from cache and retransmitting it. + var ack = this.ackRetransmissionCache.get(response.toTag); + if (ack) { + this.send(ack.toString()).catch(function (error) { + _this.logTransportError(error, "Failed to send retransmission of ACK to 2xx response."); + }); + return; + } + // If an ACK was not found in cache then we have received a retransmitted 2xx + // response before the TU responded to the original response (we don't have an ACK yet). + // So discard this response under the assumption that the TU will eventually + // get us a ACK for the original response. + return; + } + break; + case transaction_state_1.TransactionState.Completed: + // Any retransmissions of a response with status code 300-699 that + // are received while in the "Completed" state MUST cause the ACK to + // be re-passed to the transport layer for retransmission, but the + // newly received response MUST NOT be passed up to the TU. + // https://tools.ietf.org/html/rfc6026#section-8.4 + if (statusCode >= 300 && statusCode <= 699) { + this.ack(response); + return; + } + break; + case transaction_state_1.TransactionState.Terminated: + break; + default: + throw new Error("Invalid state " + this.state); + } + // Any response received that does not match an existing client + // transaction state machine is simply dropped. (Implementations are, + // of course, free to log or do other implementation-specific things + // with such responses, but the implementer should be sure to consider + // the impact of large numbers of malicious stray responses.) + // https://tools.ietf.org/html/rfc6026#section-7.2 + var message = "Received unexpected " + statusCode + " response while in state " + this.state + "."; + this.logger.warn(message); + return; + }; + /** + * The client transaction SHOULD inform the TU that a transport failure + * has occurred, and the client transaction SHOULD transition directly + * to the "Terminated" state. The TU will handle the failover + * mechanisms described in [4]. + * https://tools.ietf.org/html/rfc3261#section-17.1.4 + * @param error The error. + */ + InviteClientTransaction.prototype.onTransportError = function (error) { + if (this.user.onTransportError) { + this.user.onTransportError(error); + } + this.stateTransition(transaction_state_1.TransactionState.Terminated, true); + }; + /** For logging. */ + InviteClientTransaction.prototype.typeToString = function () { + return "INVITE client transaction"; + }; + InviteClientTransaction.prototype.ack = function (response) { + var _this = this; + // The ACK request constructed by the client transaction MUST contain + // values for the Call-ID, From, and Request-URI that are equal to the + // values of those header fields in the request passed to the transport + // by the client transaction (call this the "original request"). The To + // header field in the ACK MUST equal the To header field in the + // response being acknowledged, and therefore will usually differ from + // the To header field in the original request by the addition of the + // tag parameter. The ACK MUST contain a single Via header field, and + // this MUST be equal to the top Via header field of the original + // request. The CSeq header field in the ACK MUST contain the same + // value for the sequence number as was present in the original request, + // but the method parameter MUST be equal to "ACK". + // + // If the INVITE request whose response is being acknowledged had Route + // header fields, those header fields MUST appear in the ACK. This is + // to ensure that the ACK can be routed properly through any downstream + // stateless proxies. + // https://tools.ietf.org/html/rfc3261#section-17.1.1.3 + var ruri = this.request.ruri; + var callId = this.request.callId; + var cseq = this.request.cseq; + var from = this.request.getHeader("from"); + var to = response.getHeader("to"); + var via = this.request.getHeader("via"); + var route = this.request.getHeader("route"); + if (!from) { + throw new Error("From undefined."); + } + if (!to) { + throw new Error("To undefined."); + } + if (!via) { + throw new Error("Via undefined."); + } + var ack = "ACK " + ruri + " SIP/2.0\r\n"; + if (route) { + ack += "Route: " + route + "\r\n"; + } + ack += "Via: " + via + "\r\n"; + ack += "To: " + to + "\r\n"; + ack += "From: " + from + "\r\n"; + ack += "Call-ID: " + callId + "\r\n"; + ack += "CSeq: " + cseq + " ACK\r\n"; + ack += "Max-Forwards: 70\r\n"; + ack += "Content-Length: 0\r\n\r\n"; + // TOOO: "User-Agent" header + this.send(ack).catch(function (error) { + _this.logTransportError(error, "Failed to send ACK to non-2xx response."); + }); + return; + }; + /** + * Execute a state transition. + * @param newState New state. + */ + InviteClientTransaction.prototype.stateTransition = function (newState, dueToTransportError) { + var _this = this; + if (dueToTransportError === void 0) { dueToTransportError = false; } + // Assert valid state transitions. + var invalidStateTransition = function () { + throw new Error("Invalid state transition from " + _this.state + " to " + newState); + }; + switch (newState) { + case transaction_state_1.TransactionState.Calling: + invalidStateTransition(); + break; + case transaction_state_1.TransactionState.Proceeding: + if (this.state !== transaction_state_1.TransactionState.Calling) { + invalidStateTransition(); + } + break; + case transaction_state_1.TransactionState.Accepted: + case transaction_state_1.TransactionState.Completed: + if (this.state !== transaction_state_1.TransactionState.Calling && + this.state !== transaction_state_1.TransactionState.Proceeding) { + invalidStateTransition(); + } + break; + case transaction_state_1.TransactionState.Terminated: + if (this.state !== transaction_state_1.TransactionState.Calling && + this.state !== transaction_state_1.TransactionState.Accepted && + this.state !== transaction_state_1.TransactionState.Completed) { + if (!dueToTransportError) { + invalidStateTransition(); + } + } + break; + default: + invalidStateTransition(); + } + // While not spelled out in the RFC, Timer B is the maximum amount of time that a sender + // will wait for an INVITE message to be acknowledged (a SIP response message is received). + // So Timer B should be cleared when the transaction state proceeds from "Calling". + if (this.B) { + clearTimeout(this.B); + this.B = undefined; + } + if (newState === transaction_state_1.TransactionState.Proceeding) { + // Timers have no effect on "Proceeding" state. + // In the "Proceeding" state, the client transaction + // SHOULD NOT retransmit the request any longer. + // https://tools.ietf.org/html/rfc3261#section-17.1.1.2 + } + // The client transaction MUST start Timer D when it enters the "Completed" state + // for any reason, with a value of at least 32 seconds for unreliable transports, + // and a value of zero seconds for reliable transports. + // https://tools.ietf.org/html/rfc6026#section-8.4 + if (newState === transaction_state_1.TransactionState.Completed) { + this.D = setTimeout(function () { return _this.timer_D(); }, Timers_1.Timers.TIMER_D); + } + // The client transaction MUST transition to the "Accepted" state, + // and Timer M MUST be started with a value of 64*T1. + // https://tools.ietf.org/html/rfc6026#section-8.4 + if (newState === transaction_state_1.TransactionState.Accepted) { + this.M = setTimeout(function () { return _this.timer_M(); }, Timers_1.Timers.TIMER_M); + } + // Once the transaction is in the "Terminated" state, it MUST be destroyed immediately. + // https://tools.ietf.org/html/rfc6026#section-8.7 + if (newState === transaction_state_1.TransactionState.Terminated) { + this.dispose(); + } + // Update state. + this.setState(newState); + }; + /** + * When timer A fires, the client transaction MUST retransmit the + * request by passing it to the transport layer, and MUST reset the + * timer with a value of 2*T1. + * When timer A fires 2*T1 seconds later, the request MUST be + * retransmitted again (assuming the client transaction is still in this + * state). This process MUST continue so that the request is + * retransmitted with intervals that double after each transmission. + * These retransmissions SHOULD only be done while the client + * transaction is in the "Calling" state. + * https://tools.ietf.org/html/rfc3261#section-17.1.1.2 + */ + InviteClientTransaction.prototype.timer_A = function () { + // TODO + }; + /** + * If the client transaction is still in the "Calling" state when timer + * B fires, the client transaction SHOULD inform the TU that a timeout + * has occurred. The client transaction MUST NOT generate an ACK. + * https://tools.ietf.org/html/rfc3261#section-17.1.1.2 + */ + InviteClientTransaction.prototype.timer_B = function () { + this.logger.debug("Timer B expired for INVITE client transaction " + this.id + "."); + if (this.state === transaction_state_1.TransactionState.Calling) { + this.onRequestTimeout(); + this.stateTransition(transaction_state_1.TransactionState.Terminated); + } + }; + /** + * If Timer D fires while the client transaction is in the "Completed" state, + * the client transaction MUST move to the "Terminated" state. + * https://tools.ietf.org/html/rfc6026#section-8.4 + */ + InviteClientTransaction.prototype.timer_D = function () { + this.logger.debug("Timer D expired for INVITE client transaction " + this.id + "."); + if (this.state === transaction_state_1.TransactionState.Completed) { + this.stateTransition(transaction_state_1.TransactionState.Terminated); + } + }; + /** + * If Timer M fires while the client transaction is in the "Accepted" + * state, the client transaction MUST move to the "Terminated" state. + * https://tools.ietf.org/html/rfc6026#section-8.4 + */ + InviteClientTransaction.prototype.timer_M = function () { + this.logger.debug("Timer M expired for INVITE client transaction " + this.id + "."); + if (this.state === transaction_state_1.TransactionState.Accepted) { + this.stateTransition(transaction_state_1.TransactionState.Terminated); + } + }; + return InviteClientTransaction; +}(client_transaction_1.ClientTransaction)); +exports.InviteClientTransaction = InviteClientTransaction; + + +/***/ }), +/* 56 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +var T1 = 500; +var T2 = 4000; +var T4 = 5000; +exports.Timers = { + T1: T1, + T2: T2, + T4: T4, + TIMER_B: 64 * T1, + TIMER_D: 0 * T1, + TIMER_F: 64 * T1, + TIMER_H: 64 * T1, + TIMER_I: 0 * T4, + TIMER_J: 0 * T1, + TIMER_K: 0 * T4, + TIMER_L: 64 * T1, + TIMER_M: 64 * T1, + TIMER_N: 64 * T1, + PROVISIONAL_RESPONSE_INTERVAL: 60000 // See RFC 3261 Section 13.3.1.1 +}; + + +/***/ }), +/* 57 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +/** Transaction state. */ +var TransactionState; +(function (TransactionState) { + TransactionState["Accepted"] = "Accepted"; + TransactionState["Calling"] = "Calling"; + TransactionState["Completed"] = "Completed"; + TransactionState["Confirmed"] = "Confirmed"; + TransactionState["Proceeding"] = "Proceeding"; + TransactionState["Terminated"] = "Terminated"; + TransactionState["Trying"] = "Trying"; +})(TransactionState = exports.TransactionState || (exports.TransactionState = {})); + + +/***/ }), +/* 58 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Constants_1 = __webpack_require__(3); +var Timers_1 = __webpack_require__(56); +var server_transaction_1 = __webpack_require__(59); +var transaction_state_1 = __webpack_require__(57); +/** + * INVITE Server Transaction + * https://tools.ietf.org/html/rfc3261#section-17.2.1 + */ +var InviteServerTransaction = /** @class */ (function (_super) { + __extends(InviteServerTransaction, _super); + /** + * Constructor. + * Upon construction, a "100 Trying" reply will be immediately sent. + * After construction the transaction will be in the "proceeding" state and the transaction + * `id` will equal the branch parameter set in the Via header of the incoming request. + * https://tools.ietf.org/html/rfc3261#section-17.2.1 + * @param request Incoming INVITE request from the transport. + * @param transport The transport. + * @param user The transaction user. + */ + function InviteServerTransaction(request, transport, user) { + return _super.call(this, request, transport, user, transaction_state_1.TransactionState.Proceeding, "sip.transaction.ist") || this; + } + /** + * Destructor. + */ + InviteServerTransaction.prototype.dispose = function () { + this.stopProgressExtensionTimer(); + if (this.H) { + clearTimeout(this.H); + this.H = undefined; + } + if (this.I) { + clearTimeout(this.I); + this.I = undefined; + } + if (this.L) { + clearTimeout(this.L); + this.L = undefined; + } + _super.prototype.dispose.call(this); + }; + Object.defineProperty(InviteServerTransaction.prototype, "kind", { + /** Transaction kind. Deprecated. */ + get: function () { + return "ist"; + }, + enumerable: true, + configurable: true + }); + /** + * Receive requests from transport matching this transaction. + * @param request Request matching this transaction. + */ + InviteServerTransaction.prototype.receiveRequest = function (request) { + var _this = this; + switch (this.state) { + case transaction_state_1.TransactionState.Proceeding: + // If a request retransmission is received while in the "Proceeding" state, the most + // recent provisional response that was received from the TU MUST be passed to the + // transport layer for retransmission. + // https://tools.ietf.org/html/rfc3261#section-17.2.1 + if (request.method === Constants_1.C.INVITE) { + if (this.lastProvisionalResponse) { + this.send(this.lastProvisionalResponse).catch(function (error) { + _this.logTransportError(error, "Failed to send retransmission of provisional response."); + }); + } + return; + } + break; + case transaction_state_1.TransactionState.Accepted: + // While in the "Accepted" state, any retransmissions of the INVITE + // received will match this transaction state machine and will be + // absorbed by the machine without changing its state. These + // retransmissions are not passed onto the TU. + // https://tools.ietf.org/html/rfc6026#section-7.1 + if (request.method === Constants_1.C.INVITE) { + return; + } + break; + case transaction_state_1.TransactionState.Completed: + // Furthermore, while in the "Completed" state, if a request retransmission is + // received, the server SHOULD pass the response to the transport for retransmission. + // https://tools.ietf.org/html/rfc3261#section-17.2.1 + if (request.method === Constants_1.C.INVITE) { + if (!this.lastFinalResponse) { + throw new Error("Last final response undefined."); + } + this.send(this.lastFinalResponse).catch(function (error) { + _this.logTransportError(error, "Failed to send retransmission of final response."); + }); + return; + } + // If an ACK is received while the server transaction is in the "Completed" state, + // the server transaction MUST transition to the "Confirmed" state. + // https://tools.ietf.org/html/rfc3261#section-17.2.1 + if (request.method === Constants_1.C.ACK) { + this.stateTransition(transaction_state_1.TransactionState.Confirmed); + return; + } + break; + case transaction_state_1.TransactionState.Confirmed: + // The purpose of the "Confirmed" state is to absorb any additional ACK messages that arrive, + // triggered from retransmissions of the final response. + // https://tools.ietf.org/html/rfc3261#section-17.2.1 + if (request.method === Constants_1.C.INVITE || request.method === Constants_1.C.ACK) { + return; + } + break; + case transaction_state_1.TransactionState.Terminated: + // For good measure absorb any additional messages that arrive (should not happen). + if (request.method === Constants_1.C.INVITE || request.method === Constants_1.C.ACK) { + return; + } + break; + default: + throw new Error("Invalid state " + this.state); + } + var message = "INVITE server transaction received unexpected " + request.method + " request while in state " + this.state + "."; + this.logger.warn(message); + return; + }; + /** + * Receive responses from TU for this transaction. + * @param statusCode Status code of response. + * @param response Response. + */ + InviteServerTransaction.prototype.receiveResponse = function (statusCode, response) { + var _this = this; + if (statusCode < 100 || statusCode > 699) { + throw new Error("Invalid status code " + statusCode); + } + switch (this.state) { + case transaction_state_1.TransactionState.Proceeding: + // The TU passes any number of provisional responses to the server + // transaction. So long as the server transaction is in the + // "Proceeding" state, each of these MUST be passed to the transport + // layer for transmission. They are not sent reliably by the + // transaction layer (they are not retransmitted by it) and do not cause + // a change in the state of the server transaction. + // https://tools.ietf.org/html/rfc3261#section-17.2.1 + if (statusCode >= 100 && statusCode <= 199) { + this.lastProvisionalResponse = response; + // Start the progress extension timer only for a non-100 provisional response. + if (statusCode > 100) { + this.startProgressExtensionTimer(); // FIXME: remove + } + this.send(response).catch(function (error) { + _this.logTransportError(error, "Failed to send 1xx response."); + }); + return; + } + // If, while in the "Proceeding" state, the TU passes a 2xx response + // to the server transaction, the server transaction MUST pass this + // response to the transport layer for transmission. It is not + // retransmitted by the server transaction; retransmissions of 2xx + // responses are handled by the TU. The server transaction MUST then + // transition to the "Accepted" state. + // https://tools.ietf.org/html/rfc6026#section-8.5 + if (statusCode >= 200 && statusCode <= 299) { + this.lastFinalResponse = response; + this.stateTransition(transaction_state_1.TransactionState.Accepted); + this.send(response).catch(function (error) { + _this.logTransportError(error, "Failed to send 2xx response."); + }); + return; + } + // While in the "Proceeding" state, if the TU passes a response with + // status code from 300 to 699 to the server transaction, the response + // MUST be passed to the transport layer for transmission, and the state + // machine MUST enter the "Completed" state. + // https://tools.ietf.org/html/rfc3261#section-17.2.1 + if (statusCode >= 300 && statusCode <= 699) { + this.lastFinalResponse = response; + this.stateTransition(transaction_state_1.TransactionState.Completed); + this.send(response).catch(function (error) { + _this.logTransportError(error, "Failed to send non-2xx final response."); + }); + return; + } + break; + case transaction_state_1.TransactionState.Accepted: + // While in the "Accepted" state, if the TU passes a 2xx response, + // the server transaction MUST pass the response to the transport layer for transmission. + // https://tools.ietf.org/html/rfc6026#section-8.7 + if (statusCode >= 200 && statusCode <= 299) { + this.send(response).catch(function (error) { + _this.logTransportError(error, "Failed to send 2xx response."); + }); + return; + } + break; + case transaction_state_1.TransactionState.Completed: + break; + case transaction_state_1.TransactionState.Confirmed: + break; + case transaction_state_1.TransactionState.Terminated: + break; + default: + throw new Error("Invalid state " + this.state); + } + var message = "INVITE server transaction received unexpected " + statusCode + " response from TU while in state " + this.state + "."; + this.logger.error(message); + throw new Error(message); + }; + /** + * Retransmit the last 2xx response. This is a noop if not in the "accepted" state. + */ + InviteServerTransaction.prototype.retransmitAcceptedResponse = function () { + var _this = this; + if (this.state === transaction_state_1.TransactionState.Accepted && this.lastFinalResponse) { + this.send(this.lastFinalResponse).catch(function (error) { + _this.logTransportError(error, "Failed to send 2xx response."); + }); + } + }; + /** + * First, the procedures in [4] are followed, which attempt to deliver the response to a backup. + * If those should all fail, based on the definition of failure in [4], the server transaction SHOULD + * inform the TU that a failure has occurred, and MUST remain in the current state. + * https://tools.ietf.org/html/rfc6026#section-8.8 + */ + InviteServerTransaction.prototype.onTransportError = function (error) { + if (this.user.onTransportError) { + this.user.onTransportError(error); + } + }; + /** For logging. */ + InviteServerTransaction.prototype.typeToString = function () { + return "INVITE server transaction"; + }; + /** + * Execute a state transition. + * @param newState New state. + */ + InviteServerTransaction.prototype.stateTransition = function (newState) { + var _this = this; + // Assert valid state transitions. + var invalidStateTransition = function () { + throw new Error("Invalid state transition from " + _this.state + " to " + newState); + }; + switch (newState) { + case transaction_state_1.TransactionState.Proceeding: + invalidStateTransition(); + break; + case transaction_state_1.TransactionState.Accepted: + case transaction_state_1.TransactionState.Completed: + if (this.state !== transaction_state_1.TransactionState.Proceeding) { + invalidStateTransition(); + } + break; + case transaction_state_1.TransactionState.Confirmed: + if (this.state !== transaction_state_1.TransactionState.Completed) { + invalidStateTransition(); + } + break; + case transaction_state_1.TransactionState.Terminated: + if (this.state !== transaction_state_1.TransactionState.Accepted && + this.state !== transaction_state_1.TransactionState.Completed && + this.state !== transaction_state_1.TransactionState.Confirmed) { + invalidStateTransition(); + } + break; + default: + invalidStateTransition(); + } + // On any state transition, stop resending provisonal responses + this.stopProgressExtensionTimer(); + // The purpose of the "Accepted" state is to absorb retransmissions of an accepted INVITE request. + // Any such retransmissions are absorbed entirely within the server transaction. + // They are not passed up to the TU since any downstream UAS cores that accepted the request have + // taken responsibility for reliability and will already retransmit their 2xx responses if necessary. + // https://tools.ietf.org/html/rfc6026#section-8.7 + if (newState === transaction_state_1.TransactionState.Accepted) { + this.L = setTimeout(function () { return _this.timer_L(); }, Timers_1.Timers.TIMER_L); + } + // When the "Completed" state is entered, timer H MUST be set to fire in 64*T1 seconds for all transports. + // Timer H determines when the server transaction abandons retransmitting the response. + // If an ACK is received while the server transaction is in the "Completed" state, + // the server transaction MUST transition to the "Confirmed" state. + // https://tools.ietf.org/html/rfc3261#section-17.2.1 + if (newState === transaction_state_1.TransactionState.Completed) { + // FIXME: Missing timer G for unreliable transports. + this.H = setTimeout(function () { return _this.timer_H(); }, Timers_1.Timers.TIMER_H); + } + // The purpose of the "Confirmed" state is to absorb any additional ACK messages that arrive, + // triggered from retransmissions of the final response. When this state is entered, timer I + // is set to fire in T4 seconds for unreliable transports, and zero seconds for reliable + // transports. Once timer I fires, the server MUST transition to the "Terminated" state. + // https://tools.ietf.org/html/rfc3261#section-17.2.1 + if (newState === transaction_state_1.TransactionState.Confirmed) { + // FIXME: This timer is not getting set correctly for unreliable transports. + this.I = setTimeout(function () { return _this.timer_I(); }, Timers_1.Timers.TIMER_I); + } + // Once the transaction is in the "Terminated" state, it MUST be destroyed immediately. + // https://tools.ietf.org/html/rfc6026#section-8.7 + if (newState === transaction_state_1.TransactionState.Terminated) { + this.dispose(); + } + // Update state. + this.setState(newState); + }; + /** + * FIXME: UAS Provisional Retransmission Timer. See RFC 3261 Section 13.3.1.1 + * This is in the wrong place. This is not a transaction level thing. It's a UAS level thing. + */ + InviteServerTransaction.prototype.startProgressExtensionTimer = function () { + var _this = this; + // Start the progress extension timer only for the first non-100 provisional response. + if (this.progressExtensionTimer === undefined) { + this.progressExtensionTimer = setInterval(function () { + _this.logger.debug("Progress extension timer expired for INVITE server transaction " + _this.id + "."); + if (!_this.lastProvisionalResponse) { + throw new Error("Last provisional response undefined."); + } + _this.send(_this.lastProvisionalResponse).catch(function (error) { + _this.logTransportError(error, "Failed to send retransmission of provisional response."); + }); + }, Timers_1.Timers.PROVISIONAL_RESPONSE_INTERVAL); + } + }; + /** + * FIXME: UAS Provisional Retransmission Timer id. See RFC 3261 Section 13.3.1.1 + * This is in the wrong place. This is not a transaction level thing. It's a UAS level thing. + */ + InviteServerTransaction.prototype.stopProgressExtensionTimer = function () { + if (this.progressExtensionTimer !== undefined) { + clearInterval(this.progressExtensionTimer); + this.progressExtensionTimer = undefined; + } + }; + /** + * While in the "Proceeding" state, if the TU passes a response with status code + * from 300 to 699 to the server transaction, the response MUST be passed to the + * transport layer for transmission, and the state machine MUST enter the "Completed" state. + * For unreliable transports, timer G is set to fire in T1 seconds, and is not set to fire for + * reliable transports. If timer G fires, the response is passed to the transport layer once + * more for retransmission, and timer G is set to fire in MIN(2*T1, T2) seconds. From then on, + * when timer G fires, the response is passed to the transport again for transmission, and + * timer G is reset with a value that doubles, unless that value exceeds T2, in which case + * it is reset with the value of T2. + * https://tools.ietf.org/html/rfc3261#section-17.2.1 + */ + InviteServerTransaction.prototype.timer_G = function () { + // TODO + }; + /** + * If timer H fires while in the "Completed" state, it implies that the ACK was never received. + * In this case, the server transaction MUST transition to the "Terminated" state, and MUST + * indicate to the TU that a transaction failure has occurred. + * https://tools.ietf.org/html/rfc3261#section-17.2.1 + */ + InviteServerTransaction.prototype.timer_H = function () { + this.logger.debug("Timer H expired for INVITE server transaction " + this.id + "."); + if (this.state === transaction_state_1.TransactionState.Completed) { + this.logger.warn("ACK to negative final response was never received, terminating transaction."); + this.stateTransition(transaction_state_1.TransactionState.Terminated); + } + }; + /** + * Once timer I fires, the server MUST transition to the "Terminated" state. + * https://tools.ietf.org/html/rfc3261#section-17.2.1 + */ + InviteServerTransaction.prototype.timer_I = function () { + this.logger.debug("Timer I expired for INVITE server transaction " + this.id + "."); + this.stateTransition(transaction_state_1.TransactionState.Terminated); + }; + /** + * When Timer L fires and the state machine is in the "Accepted" state, the machine MUST + * transition to the "Terminated" state. Once the transaction is in the "Terminated" state, + * it MUST be destroyed immediately. Timer L reflects the amount of time the server + * transaction could receive 2xx responses for retransmission from the + * TU while it is waiting to receive an ACK. + * https://tools.ietf.org/html/rfc6026#section-7.1 + * https://tools.ietf.org/html/rfc6026#section-8.7 + */ + InviteServerTransaction.prototype.timer_L = function () { + this.logger.debug("Timer L expired for INVITE server transaction " + this.id + "."); + if (this.state === transaction_state_1.TransactionState.Accepted) { + this.stateTransition(transaction_state_1.TransactionState.Terminated); + } + }; + return InviteServerTransaction; +}(server_transaction_1.ServerTransaction)); +exports.InviteServerTransaction = InviteServerTransaction; + + +/***/ }), +/* 59 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var transaction_1 = __webpack_require__(54); +/** + * Server Transaction + * The server transaction is responsible for the delivery of requests to + * the TU and the reliable transmission of responses. It accomplishes + * this through a state machine. Server transactions are created by the + * core when a request is received, and transaction handling is desired + * for that request (this is not always the case). + * https://tools.ietf.org/html/rfc3261#section-17.2 + */ +var ServerTransaction = /** @class */ (function (_super) { + __extends(ServerTransaction, _super); + function ServerTransaction(_request, transport, user, state, loggerCategory) { + var _this = _super.call(this, transport, user, _request.viaBranch, state, loggerCategory) || this; + _this._request = _request; + _this.user = user; + return _this; + } + Object.defineProperty(ServerTransaction.prototype, "request", { + /** The incoming request the transaction handling. */ + get: function () { + return this._request; + }, + enumerable: true, + configurable: true + }); + return ServerTransaction; +}(transaction_1.Transaction)); +exports.ServerTransaction = ServerTransaction; + + +/***/ }), +/* 60 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Timers_1 = __webpack_require__(56); +var client_transaction_1 = __webpack_require__(53); +var transaction_state_1 = __webpack_require__(57); +/** + * Non-INVITE Client Transaction + * + * Non-INVITE transactions do not make use of ACK. + * They are simple request-response interactions. + * https://tools.ietf.org/html/rfc3261#section-17.1.2 + */ +var NonInviteClientTransaction = /** @class */ (function (_super) { + __extends(NonInviteClientTransaction, _super); + /** + * Constructor + * Upon construction, the outgoing request's Via header is updated by calling `setViaHeader`. + * Then `toString` is called on the outgoing request and the message is sent via the transport. + * After construction the transaction will be in the "calling" state and the transaction id + * will equal the branch parameter set in the Via header of the outgoing request. + * https://tools.ietf.org/html/rfc3261#section-17.1.2 + * @param request The outgoing Non-INVITE request. + * @param transport The transport. + * @param user The transaction user. + */ + function NonInviteClientTransaction(request, transport, user) { + var _this = _super.call(this, request, transport, user, transaction_state_1.TransactionState.Trying, "sip.transaction.nict") || this; + // FIXME: Timer E for unreliable transports not implemented. + // + // The "Trying" state is entered when the TU initiates a new client + // transaction with a request. When entering this state, the client + // transaction SHOULD set timer F to fire in 64*T1 seconds. The request + // MUST be passed to the transport layer for transmission. + // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 + _this.F = setTimeout(function () { return _this.timer_F(); }, Timers_1.Timers.TIMER_F); + _this.send(request.toString()).catch(function (error) { + _this.logTransportError(error, "Failed to send initial outgoing request."); + }); + return _this; + } + /** + * Destructor. + */ + NonInviteClientTransaction.prototype.dispose = function () { + if (this.F) { + clearTimeout(this.F); + this.F = undefined; + } + if (this.K) { + clearTimeout(this.K); + this.K = undefined; + } + _super.prototype.dispose.call(this); + }; + Object.defineProperty(NonInviteClientTransaction.prototype, "kind", { + /** Transaction kind. Deprecated. */ + get: function () { + return "nict"; + }, + enumerable: true, + configurable: true + }); + /** + * Handler for incoming responses from the transport which match this transaction. + * @param response The incoming response. + */ + NonInviteClientTransaction.prototype.receiveResponse = function (response) { + var statusCode = response.statusCode; + if (!statusCode || statusCode < 100 || statusCode > 699) { + throw new Error("Invalid status code " + statusCode); + } + switch (this.state) { + case transaction_state_1.TransactionState.Trying: + // If a provisional response is received while in the "Trying" state, the + // response MUST be passed to the TU, and then the client transaction + // SHOULD move to the "Proceeding" state. + // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 + if (statusCode >= 100 && statusCode <= 199) { + this.stateTransition(transaction_state_1.TransactionState.Proceeding); + if (this.user.receiveResponse) { + this.user.receiveResponse(response); + } + return; + } + // If a final response (status codes 200-699) is received while in the + // "Trying" state, the response MUST be passed to the TU, and the + // client transaction MUST transition to the "Completed" state. + // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 + if (statusCode >= 200 && statusCode <= 699) { + this.stateTransition(transaction_state_1.TransactionState.Completed); + if (statusCode === 408) { + this.onRequestTimeout(); + return; + } + if (this.user.receiveResponse) { + this.user.receiveResponse(response); + } + return; + } + break; + case transaction_state_1.TransactionState.Proceeding: + // If a provisional response is received while in the "Proceeding" state, + // the response MUST be passed to the TU. (From Figure 6) + // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 + if (statusCode >= 100 && statusCode <= 199) { + if (this.user.receiveResponse) { + return this.user.receiveResponse(response); + } + } + // If a final response (status codes 200-699) is received while in the + // "Proceeding" state, the response MUST be passed to the TU, and the + // client transaction MUST transition to the "Completed" state. + // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 + if (statusCode >= 200 && statusCode <= 699) { + this.stateTransition(transaction_state_1.TransactionState.Completed); + if (statusCode === 408) { + this.onRequestTimeout(); + return; + } + if (this.user.receiveResponse) { + this.user.receiveResponse(response); + } + return; + } + case transaction_state_1.TransactionState.Completed: + // The "Completed" state exists to buffer any additional response + // retransmissions that may be received (which is why the client + // transaction remains there only for unreliable transports). + // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 + return; + case transaction_state_1.TransactionState.Terminated: + // For good measure just absorb additional response retransmissions. + return; + default: + throw new Error("Invalid state " + this.state); + } + var message = "Non-INVITE client transaction received unexpected " + statusCode + " response while in state " + this.state + "."; + this.logger.warn(message); + return; + }; + /** + * The client transaction SHOULD inform the TU that a transport failure has occurred, + * and the client transaction SHOULD transition directly to the "Terminated" state. + * The TU will handle the failover mechanisms described in [4]. + * https://tools.ietf.org/html/rfc3261#section-17.1.4 + * @param error Trasnsport error + */ + NonInviteClientTransaction.prototype.onTransportError = function (error) { + if (this.user.onTransportError) { + this.user.onTransportError(error); + } + this.stateTransition(transaction_state_1.TransactionState.Terminated, true); + }; + /** For logging. */ + NonInviteClientTransaction.prototype.typeToString = function () { + return "non-INVITE client transaction"; + }; + /** + * Execute a state transition. + * @param newState New state. + */ + NonInviteClientTransaction.prototype.stateTransition = function (newState, dueToTransportError) { + var _this = this; + if (dueToTransportError === void 0) { dueToTransportError = false; } + // Assert valid state transitions. + var invalidStateTransition = function () { + throw new Error("Invalid state transition from " + _this.state + " to " + newState); + }; + switch (newState) { + case transaction_state_1.TransactionState.Trying: + invalidStateTransition(); + break; + case transaction_state_1.TransactionState.Proceeding: + if (this.state !== transaction_state_1.TransactionState.Trying) { + invalidStateTransition(); + } + break; + case transaction_state_1.TransactionState.Completed: + if (this.state !== transaction_state_1.TransactionState.Trying && + this.state !== transaction_state_1.TransactionState.Proceeding) { + invalidStateTransition(); + } + break; + case transaction_state_1.TransactionState.Terminated: + if (this.state !== transaction_state_1.TransactionState.Trying && + this.state !== transaction_state_1.TransactionState.Proceeding && + this.state !== transaction_state_1.TransactionState.Completed) { + if (!dueToTransportError) { + invalidStateTransition(); + } + } + break; + default: + invalidStateTransition(); + } + // Once the client transaction enters the "Completed" state, it MUST set + // Timer K to fire in T4 seconds for unreliable transports, and zero + // seconds for reliable transports The "Completed" state exists to + // buffer any additional response retransmissions that may be received + // (which is why the client transaction remains there only for unreliable transports). + // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 + if (newState === transaction_state_1.TransactionState.Completed) { + if (this.F) { + clearTimeout(this.F); + this.F = undefined; + } + this.K = setTimeout(function () { return _this.timer_K(); }, Timers_1.Timers.TIMER_K); + } + // Once the transaction is in the terminated state, it MUST be destroyed immediately. + // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 + if (newState === transaction_state_1.TransactionState.Terminated) { + this.dispose(); + } + // Update state. + this.setState(newState); + }; + /** + * If Timer F fires while the client transaction is still in the + * "Trying" state, the client transaction SHOULD inform the TU about the + * timeout, and then it SHOULD enter the "Terminated" state. + * If timer F fires while in the "Proceeding" state, the TU MUST be informed of + * a timeout, and the client transaction MUST transition to the terminated state. + * https://tools.ietf.org/html/rfc3261#section-17.1.2.2 + */ + NonInviteClientTransaction.prototype.timer_F = function () { + this.logger.debug("Timer F expired for non-INVITE client transaction " + this.id + "."); + if (this.state === transaction_state_1.TransactionState.Trying || this.state === transaction_state_1.TransactionState.Proceeding) { + this.onRequestTimeout(); + this.stateTransition(transaction_state_1.TransactionState.Terminated); + } + }; + /** + * If Timer K fires while in this (COMPLETED) state, the client transaction + * MUST transition to the "Terminated" state. + * https://tools.ietf.org/html/rfc3261#section-17.1.2.2 + */ + NonInviteClientTransaction.prototype.timer_K = function () { + if (this.state === transaction_state_1.TransactionState.Completed) { + this.stateTransition(transaction_state_1.TransactionState.Terminated); + } + }; + return NonInviteClientTransaction; +}(client_transaction_1.ClientTransaction)); +exports.NonInviteClientTransaction = NonInviteClientTransaction; + + +/***/ }), +/* 61 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Timers_1 = __webpack_require__(56); +var server_transaction_1 = __webpack_require__(59); +var transaction_state_1 = __webpack_require__(57); +/** + * Non-INVITE Server Transaction + * https://tools.ietf.org/html/rfc3261#section-17.2.2 + */ +var NonInviteServerTransaction = /** @class */ (function (_super) { + __extends(NonInviteServerTransaction, _super); + /** + * Constructor. + * After construction the transaction will be in the "trying": state and the transaction + * `id` will equal the branch parameter set in the Via header of the incoming request. + * https://tools.ietf.org/html/rfc3261#section-17.2.2 + * @param request Incoming Non-INVITE request from the transport. + * @param transport The transport. + * @param user The transaction user. + */ + function NonInviteServerTransaction(request, transport, user) { + return _super.call(this, request, transport, user, transaction_state_1.TransactionState.Trying, "sip.transaction.nist") || this; + } + /** + * Destructor. + */ + NonInviteServerTransaction.prototype.dispose = function () { + if (this.J) { + clearTimeout(this.J); + this.J = undefined; + } + _super.prototype.dispose.call(this); + }; + Object.defineProperty(NonInviteServerTransaction.prototype, "kind", { + /** Transaction kind. Deprecated. */ + get: function () { + return "nist"; + }, + enumerable: true, + configurable: true + }); + /** + * Receive requests from transport matching this transaction. + * @param request Request matching this transaction. + */ + NonInviteServerTransaction.prototype.receiveRequest = function (request) { + var _this = this; + switch (this.state) { + case transaction_state_1.TransactionState.Trying: + // Once in the "Trying" state, any further request retransmissions are discarded. + // https://tools.ietf.org/html/rfc3261#section-17.2.2 + break; + case transaction_state_1.TransactionState.Proceeding: + // If a retransmission of the request is received while in the "Proceeding" state, + // the most recently sent provisional response MUST be passed to the transport layer for retransmission. + // https://tools.ietf.org/html/rfc3261#section-17.2.2 + if (!this.lastResponse) { + throw new Error("Last response undefined."); + } + this.send(this.lastResponse).catch(function (error) { + _this.logTransportError(error, "Failed to send retransmission of provisional response."); + }); + break; + case transaction_state_1.TransactionState.Completed: + // While in the "Completed" state, the server transaction MUST pass the final response to the transport + // layer for retransmission whenever a retransmission of the request is received. Any other final responses + // passed by the TU to the server transaction MUST be discarded while in the "Completed" state. + // https://tools.ietf.org/html/rfc3261#section-17.2.2 + if (!this.lastResponse) { + throw new Error("Last response undefined."); + } + this.send(this.lastResponse).catch(function (error) { + _this.logTransportError(error, "Failed to send retransmission of final response."); + }); + break; + case transaction_state_1.TransactionState.Terminated: + break; + default: + throw new Error("Invalid state " + this.state); + } + }; + /** + * Receive responses from TU for this transaction. + * @param statusCode Status code of repsonse. 101-199 not allowed per RFC 4320. + * @param response Response to send. + */ + NonInviteServerTransaction.prototype.receiveResponse = function (statusCode, response) { + var _this = this; + if (statusCode < 100 || statusCode > 699) { + throw new Error("Invalid status code " + statusCode); + } + // An SIP element MUST NOT send any provisional response with a + // Status-Code other than 100 to a non-INVITE request. + // An SIP element MUST NOT respond to a non-INVITE request with a + // Status-Code of 100 over any unreliable transport, such as UDP, + // before the amount of time it takes a client transaction's Timer E to be reset to T2. + // An SIP element MAY respond to a non-INVITE request with a + // Status-Code of 100 over a reliable transport at any time. + // https://tools.ietf.org/html/rfc4320#section-4.1 + if (statusCode > 100 && statusCode <= 199) { + throw new Error("Provisional response other than 100 not allowed."); + } + switch (this.state) { + case transaction_state_1.TransactionState.Trying: + // While in the "Trying" state, if the TU passes a provisional response + // to the server transaction, the server transaction MUST enter the "Proceeding" state. + // The response MUST be passed to the transport layer for transmission. + // https://tools.ietf.org/html/rfc3261#section-17.2.2 + this.lastResponse = response; + if (statusCode >= 100 && statusCode < 200) { + this.stateTransition(transaction_state_1.TransactionState.Proceeding); + this.send(response).catch(function (error) { + _this.logTransportError(error, "Failed to send provisional response."); + }); + return; + } + if (statusCode >= 200 && statusCode <= 699) { + this.stateTransition(transaction_state_1.TransactionState.Completed); + this.send(response).catch(function (error) { + _this.logTransportError(error, "Failed to send final response."); + }); + return; + } + break; + case transaction_state_1.TransactionState.Proceeding: + // Any further provisional responses that are received from the TU while + // in the "Proceeding" state MUST be passed to the transport layer for transmission. + // If the TU passes a final response (status codes 200-699) to the server while in + // the "Proceeding" state, the transaction MUST enter the "Completed" state, and + // the response MUST be passed to the transport layer for transmission. + // https://tools.ietf.org/html/rfc3261#section-17.2.2 + this.lastResponse = response; + if (statusCode >= 200 && statusCode <= 699) { + this.stateTransition(transaction_state_1.TransactionState.Completed); + this.send(response).catch(function (error) { + _this.logTransportError(error, "Failed to send final response."); + }); + return; + } + break; + case transaction_state_1.TransactionState.Completed: + // Any other final responses passed by the TU to the server + // transaction MUST be discarded while in the "Completed" state. + // https://tools.ietf.org/html/rfc3261#section-17.2.2 + return; + case transaction_state_1.TransactionState.Terminated: + break; + default: + throw new Error("Invalid state " + this.state); + } + var message = "Non-INVITE server transaction received unexpected " + statusCode + " response from TU while in state " + this.state + "."; + this.logger.error(message); + throw new Error(message); + }; + /** + * First, the procedures in [4] are followed, which attempt to deliver the response to a backup. + * If those should all fail, based on the definition of failure in [4], the server transaction SHOULD + * inform the TU that a failure has occurred, and SHOULD transition to the terminated state. + * https://tools.ietf.org/html/rfc3261#section-17.2.4 + */ + NonInviteServerTransaction.prototype.onTransportError = function (error) { + if (this.user.onTransportError) { + this.user.onTransportError(error); + } + this.stateTransition(transaction_state_1.TransactionState.Terminated, true); + }; + /** For logging. */ + NonInviteServerTransaction.prototype.typeToString = function () { + return "non-INVITE server transaction"; + }; + NonInviteServerTransaction.prototype.stateTransition = function (newState, dueToTransportError) { + var _this = this; + if (dueToTransportError === void 0) { dueToTransportError = false; } + // Assert valid state transitions. + var invalidStateTransition = function () { + throw new Error("Invalid state transition from " + _this.state + " to " + newState); + }; + switch (newState) { + case transaction_state_1.TransactionState.Trying: + invalidStateTransition(); + break; + case transaction_state_1.TransactionState.Proceeding: + if (this.state !== transaction_state_1.TransactionState.Trying) { + invalidStateTransition(); + } + break; + case transaction_state_1.TransactionState.Completed: + if (this.state !== transaction_state_1.TransactionState.Trying && this.state !== transaction_state_1.TransactionState.Proceeding) { + invalidStateTransition(); + } + break; + case transaction_state_1.TransactionState.Terminated: + if (this.state !== transaction_state_1.TransactionState.Proceeding && this.state !== transaction_state_1.TransactionState.Completed) { + if (!dueToTransportError) { + invalidStateTransition(); + } + } + break; + default: + invalidStateTransition(); + } + // When the server transaction enters the "Completed" state, it MUST set Timer J to fire + // in 64*T1 seconds for unreliable transports, and zero seconds for reliable transports. + // https://tools.ietf.org/html/rfc3261#section-17.2.2 + if (newState === transaction_state_1.TransactionState.Completed) { + this.J = setTimeout(function () { return _this.timer_J(); }, Timers_1.Timers.TIMER_J); + } + // The server transaction MUST be destroyed the instant it enters the "Terminated" state. + // https://tools.ietf.org/html/rfc3261#section-17.2.2 + if (newState === transaction_state_1.TransactionState.Terminated) { + this.dispose(); + } + this.setState(newState); + }; + /** + * The server transaction remains in this state until Timer J fires, + * at which point it MUST transition to the "Terminated" state. + * https://tools.ietf.org/html/rfc3261#section-17.2.2 + */ + NonInviteServerTransaction.prototype.timer_J = function () { + this.logger.debug("Timer J expired for NON-INVITE server transaction " + this.id + "."); + if (this.state === transaction_state_1.TransactionState.Completed) { + this.stateTransition(transaction_state_1.TransactionState.Terminated); + } + }; + return NonInviteServerTransaction; +}(server_transaction_1.ServerTransaction)); +exports.NonInviteServerTransaction = NonInviteServerTransaction; + + +/***/ }), +/* 62 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var events_1 = __webpack_require__(2); +var Constants_1 = __webpack_require__(3); +var messages_1 = __webpack_require__(63); +var Enums_1 = __webpack_require__(5); +var Grammar_1 = __webpack_require__(7); +var Utils_1 = __webpack_require__(11); +var ServerContext = /** @class */ (function (_super) { + __extends(ServerContext, _super); + function ServerContext(ua, incomingRequest) { + var _this = _super.call(this) || this; + _this.incomingRequest = incomingRequest; + _this.data = {}; + ServerContext.initializer(_this, ua, incomingRequest); + return _this; + } + // hack to get around our multiple inheritance issues + ServerContext.initializer = function (objectToConstruct, ua, incomingRequest) { + var request = incomingRequest.message; + objectToConstruct.type = Enums_1.TypeStrings.ServerContext; + objectToConstruct.ua = ua; + objectToConstruct.logger = ua.getLogger("sip.servercontext"); + objectToConstruct.request = request; + if (request.body) { + objectToConstruct.body = request.body; + } + if (request.hasHeader("Content-Type")) { + objectToConstruct.contentType = request.getHeader("Content-Type"); + } + objectToConstruct.method = request.method; + objectToConstruct.localIdentity = request.to; + objectToConstruct.remoteIdentity = request.from; + var hasAssertedIdentity = request.hasHeader("P-Asserted-Identity"); + if (hasAssertedIdentity) { + var assertedIdentity = request.getHeader("P-Asserted-Identity"); + if (assertedIdentity) { + objectToConstruct.assertedIdentity = Grammar_1.Grammar.nameAddrHeaderParse(assertedIdentity); + } + } + }; + ServerContext.prototype.progress = function (options) { + if (options === void 0) { options = {}; } + options.statusCode = options.statusCode || 180; + options.minCode = 100; + options.maxCode = 199; + options.events = ["progress"]; + return this.reply(options); + }; + ServerContext.prototype.accept = function (options) { + if (options === void 0) { options = {}; } + options.statusCode = options.statusCode || 200; + options.minCode = 200; + options.maxCode = 299; + options.events = ["accepted"]; + return this.reply(options); + }; + ServerContext.prototype.reject = function (options) { + if (options === void 0) { options = {}; } + options.statusCode = options.statusCode || 480; + options.minCode = 300; + options.maxCode = 699; + options.events = ["rejected", "failed"]; + return this.reply(options); + }; + ServerContext.prototype.reply = function (options) { + var _this = this; + if (options === void 0) { options = {}; } + var statusCode = options.statusCode || 100; + var minCode = options.minCode || 100; + var maxCode = options.maxCode || 699; + var reasonPhrase = Utils_1.Utils.getReasonPhrase(statusCode, options.reasonPhrase); + var extraHeaders = options.extraHeaders || []; + var body = options.body ? messages_1.fromBodyLegacy(options.body) : undefined; + var events = options.events || []; + if (statusCode < minCode || statusCode > maxCode) { + throw new TypeError("Invalid statusCode: " + statusCode); + } + var responseOptions = { + statusCode: statusCode, + reasonPhrase: reasonPhrase, + extraHeaders: extraHeaders, + body: body + }; + var response; + var statusCodeString = statusCode.toString(); + switch (true) { + case /^100$/.test(statusCodeString): + response = this.incomingRequest.trying(responseOptions).message; + break; + case /^1[0-9]{2}$/.test(statusCodeString): + response = this.incomingRequest.progress(responseOptions).message; + break; + case /^2[0-9]{2}$/.test(statusCodeString): + response = this.incomingRequest.accept(responseOptions).message; + break; + case /^3[0-9]{2}$/.test(statusCodeString): + response = this.incomingRequest.redirect([], responseOptions).message; + break; + case /^[4-6][0-9]{2}$/.test(statusCodeString): + response = this.incomingRequest.reject(responseOptions).message; + break; + default: + throw new Error("Invalid status code " + statusCode); + } + events.forEach(function (event) { + _this.emit(event, response, reasonPhrase); + }); + return this; + }; + ServerContext.prototype.onRequestTimeout = function () { + this.emit("failed", undefined, Constants_1.C.causes.REQUEST_TIMEOUT); + }; + ServerContext.prototype.onTransportError = function () { + this.emit("failed", undefined, Constants_1.C.causes.CONNECTION_ERROR); + }; + return ServerContext; +}(events_1.EventEmitter)); +exports.ServerContext = ServerContext; + + +/***/ }), +/* 63 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +function __export(m) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; +} +Object.defineProperty(exports, "__esModule", { value: true }); +__export(__webpack_require__(64)); +__export(__webpack_require__(65)); + + +/***/ }), +/* 64 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +var SIPMessage_1 = __webpack_require__(6); +/** + * Create a Body given a BodyObj. + * @param bodyObj Body Object + */ +function fromBodyObj(bodyObj) { + var content = bodyObj.body; + var contentType = bodyObj.contentType; + var contentDisposition = contentTypeToContentDisposition(contentType); + var body = { contentDisposition: contentDisposition, contentType: contentType, content: content }; + return body; +} +exports.fromBodyObj = fromBodyObj; +/** + * Create a Body given a BodyObj. + * @param bodyObj Body Object + */ +function fromBodyLegacy(bodyLegacy) { + var content = (typeof bodyLegacy === "string") ? bodyLegacy : bodyLegacy.body; + var contentType = (typeof bodyLegacy === "string") ? "application/sdp" : bodyLegacy.contentType; + var contentDisposition = contentTypeToContentDisposition(contentType); + var body = { contentDisposition: contentDisposition, contentType: contentType, content: content }; + return body; +} +exports.fromBodyLegacy = fromBodyLegacy; +/** + * Given a message, get a normalized body. + * The content disposition is inferred if not set. + * @param message The message. + */ +function getBody(message) { + var contentDisposition; + var contentType; + var content; + // We're in UAS role, receiving incoming request + if (message instanceof SIPMessage_1.IncomingRequest) { + if (message.body) { + // FIXME: Parsing needs typing + var parse = message.parseHeader("Content-Disposition"); + contentDisposition = parse ? parse.type : undefined; + contentType = message.parseHeader("Content-Type"); + content = message.body; + } + } + // We're in UAC role, receiving incoming response + if (message instanceof SIPMessage_1.IncomingResponse) { + if (message.body) { + // FIXME: Parsing needs typing + var parse = message.parseHeader("Content-Disposition"); + contentDisposition = parse ? parse.type : undefined; + contentType = message.parseHeader("Content-Type"); + content = message.body; + } + } + // We're in UAC role, sending outgoing request + if (message instanceof SIPMessage_1.OutgoingRequest) { + if (message.body) { + contentDisposition = message.getHeader("Content-Disposition"); + contentType = message.getHeader("Content-Type"); + if (typeof message.body === "string") { + // FIXME: OutgoingRequest should not allow a "string" body without a "Content-Type" header. + if (!contentType) { + throw new Error("Header content type header does not equal body content type."); + } + content = message.body; + } + else { + // FIXME: OutgoingRequest should not allow the "Content-Type" header not to match th body content type + if (contentType && contentType !== message.body.contentType) { + throw new Error("Header content type header does not equal body content type."); + } + contentType = message.body.contentType; + content = message.body.body; + } + } + } + // We're in UAS role, sending outgoing response + if (isBody(message)) { + contentDisposition = message.contentDisposition; + contentType = message.contentType; + content = message.content; + } + // No content, no body. + if (!content) { + return undefined; + } + if (contentType && !contentDisposition) { + contentDisposition = contentTypeToContentDisposition(contentType); + } + if (!contentDisposition) { + throw new Error("Content disposition undefined."); + } + if (!contentType) { + throw new Error("Content type undefined."); + } + return { + contentDisposition: contentDisposition, + contentType: contentType, + content: content + }; +} +exports.getBody = getBody; +/** + * User-Defined Type Guard for Body. + * @param body Body to check. + */ +function isBody(body) { + return body && + typeof body.content === "string" && + typeof body.contentType === "string" && + body.contentDisposition === undefined ? true : typeof body.contentDisposition === "string"; +} +exports.isBody = isBody; +/** + * Create a BodyObj given a Body. + * @param bodyObj Body Object + */ +function toBodyObj(body) { + var bodyObj = { + body: body.content, + contentType: body.contentType + }; + return bodyObj; +} +exports.toBodyObj = toBodyObj; +// If the Content-Disposition header field is missing, bodies of +// Content-Type application/sdp imply the disposition "session", while +// other content types imply "render". +// https://tools.ietf.org/html/rfc3261#section-13.2.1 +function contentTypeToContentDisposition(contentType) { + if (contentType === "application/sdp") { + return "session"; + } + else { + return "render"; + } +} + + +/***/ }), +/* 65 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +var SIPMessage_1 = __webpack_require__(6); +var Utils_1 = __webpack_require__(11); +/** + * When a UAS wishes to construct a response to a request, it follows + * the general procedures detailed in the following subsections. + * Additional behaviors specific to the response code in question, which + * are not detailed in this section, may also be required. + * https://tools.ietf.org/html/rfc3261#section-8.2.6 + */ +function constructOutgoingResponse(message, options) { + var CRLF = "\r\n"; + // SIP responses are distinguished from requests by having a Status-Line + // as their start-line. A Status-Line consists of the protocol version + // followed by a numeric Status-Code and its associated textual phrase, + // with each element separated by a single SP character. + // https://tools.ietf.org/html/rfc3261#section-7.2 + var response = Utils_1.Utils.buildStatusLine(options.statusCode, options.reasonPhrase); + // One largely non-method-specific guideline for the generation of + // responses is that UASs SHOULD NOT issue a provisional response for a + // non-INVITE request. Rather, UASs SHOULD generate a final response to + // a non-INVITE request as soon as possible. + // https://tools.ietf.org/html/rfc3261#section-8.2.6.1 + if (options.statusCode >= 100 && options.statusCode < 200) { + // TODO + } + // When a 100 (Trying) response is generated, any Timestamp header field + // present in the request MUST be copied into this 100 (Trying) + // response. If there is a delay in generating the response, the UAS + // SHOULD add a delay value into the Timestamp value in the response. + // This value MUST contain the difference between the time of sending of + // the response and receipt of the request, measured in seconds. + // https://tools.ietf.org/html/rfc3261#section-8.2.6.1 + if (options.statusCode === 100) { + // TODO + } + // The From field of the response MUST equal the From header field of + // the request. The Call-ID header field of the response MUST equal the + // Call-ID header field of the request. The CSeq header field of the + // response MUST equal the CSeq field of the request. The Via header + // field values in the response MUST equal the Via header field values + // in the request and MUST maintain the same ordering. + // https://tools.ietf.org/html/rfc3261#section-8.2.6.2 + var fromHeader = "From: " + message.getHeader("From") + CRLF; + var callIdHeader = "Call-ID: " + message.callId + CRLF; + var cSeqHeader = "CSeq: " + message.cseq + " " + message.method + CRLF; + var viaHeaders = message.getHeaders("via").reduce(function (previous, current) { + return previous + "Via: " + current + CRLF; + }, ""); + // If a request contained a To tag in the request, the To header field + // in the response MUST equal that of the request. However, if the To + // header field in the request did not contain a tag, the URI in the To + // header field in the response MUST equal the URI in the To header + // field; additionally, the UAS MUST add a tag to the To header field in + // the response (with the exception of the 100 (Trying) response, in + // which a tag MAY be present). This serves to identify the UAS that is + // responding, possibly resulting in a component of a dialog ID. The + // same tag MUST be used for all responses to that request, both final + // and provisional (again excepting the 100 (Trying)). + // https://tools.ietf.org/html/rfc3261#section-8.2.6.2 + var toHeader = "To: " + message.getHeader("to"); + if (options.statusCode > 100 && !message.parseHeader("to").hasParam("tag")) { + var toTag = options.toTag; + if (!toTag) { + // Stateless UAS Behavior... + // o To header tags MUST be generated for responses in a stateless + // manner - in a manner that will generate the same tag for the + // same request consistently. For information on tag construction + // see Section 19.3. + // https://tools.ietf.org/html/rfc3261#section-8.2.7 + toTag = Utils_1.Utils.newTag(); // FIXME: Utils.newTag() currently generates random tags + } + toHeader += ";tag=" + toTag; + } + toHeader += CRLF; + // FIXME: TODO: needs review... moved to InviteUserAgentServer (as it is specific to that) + // let recordRouteHeaders = ""; + // if (request.method === C.INVITE && statusCode > 100 && statusCode <= 200) { + // recordRouteHeaders = request.getHeaders("record-route").reduce((previous, current) => { + // return previous + "Record-Route: " + current + CRLF; + // }, ""); + // } + // FIXME: TODO: needs review... + var supportedHeader = SIPMessage_1.getSupportedHeader(message); + // FIXME: TODO: needs review... + var userAgentHeader = ""; + if (options.userAgent) { + userAgentHeader = "User-Agent: " + options.userAgent + CRLF; + } + var extensionHeaders = ""; + if (options.extraHeaders) { + extensionHeaders = options.extraHeaders.reduce(function (previous, current) { + return previous + current.trim() + CRLF; + }, ""); + } + // The relative order of header fields with different field names is not + // significant. However, it is RECOMMENDED that header fields which are + // needed for proxy processing (Via, Route, Record-Route, Proxy-Require, + // Max-Forwards, and Proxy-Authorization, for example) appear towards + // the top of the message to facilitate rapid parsing. + // https://tools.ietf.org/html/rfc3261#section-7.3.1 + // response += recordRouteHeaders; + response += viaHeaders; + response += fromHeader; + response += toHeader; + response += cSeqHeader; + response += callIdHeader; + response += supportedHeader; + response += userAgentHeader; + response += extensionHeaders; + if (options.body) { + response += "Content-Type: " + options.body.contentType + CRLF; + response += "Content-Length: " + Utils_1.Utils.str_utf8_length(options.body.content) + CRLF + CRLF; + response += options.body.content; + } + else { + response += "Content-Length: " + 0 + CRLF + CRLF; + } + return { message: response }; +} +exports.constructOutgoingResponse = constructOutgoingResponse; + + +/***/ }), +/* 66 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +var ClientContext_1 = __webpack_require__(1); +var Constants_1 = __webpack_require__(3); +var Enums_1 = __webpack_require__(5); +var Exceptions_1 = __webpack_require__(47); +var Grammar_1 = __webpack_require__(7); +var Utils_1 = __webpack_require__(11); +/** + * Configuration load. + * @private + * returns {any} + */ +function loadConfig(configuration) { + var settings = { + expires: 600, + extraContactHeaderParams: [], + instanceId: undefined, + params: {}, + regId: undefined, + registrar: undefined, + }; + var configCheck = getConfigurationCheck(); + // Check Mandatory parameters + for (var parameter in configCheck.mandatory) { + if (!configuration.hasOwnProperty(parameter)) { + throw new Exceptions_1.Exceptions.ConfigurationError(parameter); + } + else { + var value = configuration[parameter]; + var checkedValue = configCheck.mandatory[parameter](value); + if (checkedValue !== undefined) { + settings[parameter] = checkedValue; + } + else { + throw new Exceptions_1.Exceptions.ConfigurationError(parameter, value); + } + } + } + // Check Optional parameters + for (var parameter in configCheck.optional) { + if (configuration.hasOwnProperty(parameter)) { + var value = configuration[parameter]; + // If the parameter value is an empty array, but shouldn't be, apply its default value. + if (value instanceof Array && value.length === 0) { + continue; + } + // If the parameter value is null, empty string, or undefined then apply its default value. + // If it's a number with NaN value then also apply its default value. + // NOTE: JS does not allow "value === NaN", the following does the work: + if (value === null || value === "" || value === undefined || + (typeof (value) === "number" && isNaN(value))) { + continue; + } + var checkedValue = configCheck.optional[parameter](value); + if (checkedValue !== undefined) { + settings[parameter] = checkedValue; + } + else { + throw new Exceptions_1.Exceptions.ConfigurationError(parameter, value); + } + } + } + return settings; +} +function getConfigurationCheck() { + return { + mandatory: {}, + optional: { + expires: function (expires) { + if (Utils_1.Utils.isDecimal(expires)) { + var value = Number(expires); + if (value >= 0) { + return value; + } + } + }, + extraContactHeaderParams: function (extraContactHeaderParams) { + if (extraContactHeaderParams instanceof Array) { + return extraContactHeaderParams.filter(function (contactHeaderParam) { return (typeof contactHeaderParam === "string"); }); + } + }, + instanceId: function (instanceId) { + if (typeof instanceId !== "string") { + return; + } + if ((/^uuid:/i.test(instanceId))) { + instanceId = instanceId.substr(5); + } + if (Grammar_1.Grammar.parse(instanceId, "uuid") === -1) { + return; + } + else { + return instanceId; + } + }, + params: function (params) { + if (typeof params === "object") { + return params; + } + }, + regId: function (regId) { + if (Utils_1.Utils.isDecimal(regId)) { + var value = Number(regId); + if (value >= 0) { + return value; + } + } + }, + registrar: function (registrar) { + if (typeof registrar !== "string") { + return; + } + if (!/^sip:/i.test(registrar)) { + registrar = Constants_1.C.SIP + ":" + registrar; + } + var parsed = Grammar_1.Grammar.URIParse(registrar); + if (!parsed) { + return; + } + else if (parsed.user) { + return; + } + else { + return parsed; + } + } + } + }; +} +var RegisterContext = /** @class */ (function (_super) { + __extends(RegisterContext, _super); + function RegisterContext(ua, options) { + if (options === void 0) { options = {}; } + var _this = this; + var settings = loadConfig(options); + if (settings.regId && !settings.instanceId) { + settings.instanceId = Utils_1.Utils.newUUID(); + } + else if (!settings.regId && settings.instanceId) { + settings.regId = 1; + } + settings.params.toUri = settings.params.toUri || ua.configuration.uri; + settings.params.toDisplayName = settings.params.toDisplayName || ua.configuration.displayName; + settings.params.callId = settings.params.callId || Utils_1.Utils.createRandomToken(22); + settings.params.cseq = settings.params.cseq || Math.floor(Math.random() * 10000); + /* If no 'registrarServer' is set use the 'uri' value without user portion. */ + if (!settings.registrar) { + var registrarServer = {}; + if (typeof ua.configuration.uri === "object") { + registrarServer = ua.configuration.uri.clone(); + registrarServer.user = undefined; + } + else { + registrarServer = ua.configuration.uri; + } + settings.registrar = registrarServer; + } + _this = _super.call(this, ua, Constants_1.C.REGISTER, settings.registrar, settings) || this; + _this.type = Enums_1.TypeStrings.RegisterContext; + _this.options = settings; + _this.logger = ua.getLogger("sip.registercontext"); + _this.logger.log("configuration parameters for RegisterContext after validation:"); + for (var parameter in settings) { + if (settings.hasOwnProperty(parameter)) { + _this.logger.log("· " + parameter + ": " + JSON.stringify(settings[parameter])); + } + } + // Registration expires + _this.expires = settings.expires; + // Contact header + _this.contact = ua.contact.toString(); + // Set status + _this.registered = false; + ua.on("transportCreated", function (transport) { + transport.on("disconnected", function () { return _this.onTransportDisconnected(); }); + }); + return _this; + } + RegisterContext.prototype.register = function (options) { + var _this = this; + if (options === void 0) { options = {}; } + // Handle Options + this.options = __assign({}, this.options, options); + var extraHeaders = (this.options.extraHeaders || []).slice(); + extraHeaders.push("Contact: " + this.generateContactHeader(this.expires)); + // this is UA.C.ALLOWED_METHODS, removed to get around circular dependency + extraHeaders.push("Allow: " + [ + "ACK", + "CANCEL", + "INVITE", + "MESSAGE", + "BYE", + "OPTIONS", + "INFO", + "NOTIFY", + "REFER" + ].toString()); + // Save original extraHeaders to be used in .close + this.closeHeaders = this.options.closeWithHeaders ? + (this.options.extraHeaders || []).slice() : []; + this.receiveResponse = function (response) { + // Discard responses to older REGISTER/un-REGISTER requests. + if (response.cseq !== _this.request.cseq) { + return; + } + // Clear registration timer + if (_this.registrationTimer !== undefined) { + clearTimeout(_this.registrationTimer); + _this.registrationTimer = undefined; + } + var statusCode = (response.statusCode || 0).toString(); + switch (true) { + case /^1[0-9]{2}$/.test(statusCode): + _this.emit("progress", response); + break; + case /^2[0-9]{2}$/.test(statusCode): + _this.emit("accepted", response); + var expires = void 0; + if (response.hasHeader("expires")) { + expires = Number(response.getHeader("expires")); + } + if (_this.registrationExpiredTimer !== undefined) { + clearTimeout(_this.registrationExpiredTimer); + _this.registrationExpiredTimer = undefined; + } + // Search the Contact pointing to us and update the expires value accordingly. + var contacts = response.getHeaders("contact").length; + if (!contacts) { + _this.logger.warn("no Contact header in response to REGISTER, response ignored"); + break; + } + var contact = void 0; + while (contacts--) { + contact = response.parseHeader("contact", contacts); + if (contact.uri.user === _this.ua.contact.uri.user) { + expires = contact.getParam("expires"); + break; + } + else { + contact = undefined; + } + } + if (!contact) { + _this.logger.warn("no Contact header pointing to us, response ignored"); + break; + } + if (expires === undefined) { + expires = _this.expires; + } + // Re-Register before the expiration interval has elapsed. + // For that, decrease the expires value. ie: 3 seconds + _this.registrationTimer = setTimeout(function () { + _this.registrationTimer = undefined; + _this.register(_this.options); + }, (expires * 1000) - 3000); + _this.registrationExpiredTimer = setTimeout(function () { + _this.logger.warn("registration expired"); + if (_this.registered) { + _this.unregistered(undefined, Constants_1.C.causes.EXPIRES); + } + }, expires * 1000); + // Save gruu values + if (contact.hasParam("temp-gruu")) { + _this.ua.contact.tempGruu = Grammar_1.Grammar.URIParse(contact.getParam("temp-gruu").replace(/"/g, "")); + } + if (contact.hasParam("pub-gruu")) { + _this.ua.contact.pubGruu = Grammar_1.Grammar.URIParse(contact.getParam("pub-gruu").replace(/"/g, "")); + } + _this.registered = true; + _this.emit("registered", response || undefined); + break; + // Interval too brief RFC3261 10.2.8 + case /^423$/.test(statusCode): + if (response.hasHeader("min-expires")) { + // Increase our registration interval to the suggested minimum + _this.expires = Number(response.getHeader("min-expires")); + // Attempt the registration again immediately + _this.register(_this.options); + } + else { // This response MUST contain a Min-Expires header field + _this.logger.warn("423 response received for REGISTER without Min-Expires"); + _this.registrationFailure(response, Constants_1.C.causes.SIP_FAILURE_CODE); + } + break; + default: + _this.registrationFailure(response, Utils_1.Utils.sipErrorCause(response.statusCode || 0)); + } + }; + this.onRequestTimeout = function () { + _this.registrationFailure(undefined, Constants_1.C.causes.REQUEST_TIMEOUT); + }; + this.onTransportError = function () { + _this.registrationFailure(undefined, Constants_1.C.causes.CONNECTION_ERROR); + }; + this.request.cseq++; + this.request.setHeader("cseq", this.request.cseq + " REGISTER"); + this.request.extraHeaders = extraHeaders; + this.send(); + }; + RegisterContext.prototype.close = function () { + var options = { + all: false, + extraHeaders: this.closeHeaders + }; + this.registeredBefore = this.registered; + if (this.registered) { + this.unregister(options); + } + }; + RegisterContext.prototype.unregister = function (options) { + var _this = this; + if (options === void 0) { options = {}; } + if (!this.registered && !options.all) { + this.logger.warn("Already unregistered, but sending an unregister anyways."); + } + var extraHeaders = (options.extraHeaders || []).slice(); + this.registered = false; + // Clear the registration timer. + if (this.registrationTimer !== undefined) { + clearTimeout(this.registrationTimer); + this.registrationTimer = undefined; + } + if (options.all) { + extraHeaders.push("Contact: *"); + extraHeaders.push("Expires: 0"); + } + else { + extraHeaders.push("Contact: " + this.generateContactHeader(0)); + } + this.receiveResponse = function (response) { + var statusCode = (response && response.statusCode) ? response.statusCode.toString() : ""; + switch (true) { + case /^1[0-9]{2}$/.test(statusCode): + _this.emit("progress", response); + break; + case /^2[0-9]{2}$/.test(statusCode): + _this.emit("accepted", response); + if (_this.registrationExpiredTimer !== undefined) { + clearTimeout(_this.registrationExpiredTimer); + _this.registrationExpiredTimer = undefined; + } + _this.unregistered(response); + break; + default: + _this.unregistered(response, Utils_1.Utils.sipErrorCause(response.statusCode || 0)); + } + }; + this.onRequestTimeout = function () { + // Not actually unregistered... + // this.unregistered(undefined, SIP.C.causes.REQUEST_TIMEOUT); + }; + this.request.cseq++; + this.request.setHeader("cseq", this.request.cseq + " REGISTER"); + this.request.extraHeaders = extraHeaders; + this.send(); + }; + RegisterContext.prototype.unregistered = function (response, cause) { + this.registered = false; + this.emit("unregistered", response || undefined, cause || undefined); + }; + RegisterContext.prototype.send = function () { + var _this = this; + this.ua.userAgentCore.register(this.request, { + onAccept: function (response) { return _this.receiveResponse(response.message); }, + onProgress: function (response) { return _this.receiveResponse(response.message); }, + onRedirect: function (response) { return _this.receiveResponse(response.message); }, + onReject: function (response) { return _this.receiveResponse(response.message); }, + onTrying: function (response) { return _this.receiveResponse(response.message); } + }); + return this; + }; + RegisterContext.prototype.registrationFailure = function (response, cause) { + this.emit("failed", response || undefined, cause || undefined); + }; + RegisterContext.prototype.onTransportDisconnected = function () { + this.registeredBefore = this.registered; + if (this.registrationTimer !== undefined) { + clearTimeout(this.registrationTimer); + this.registrationTimer = undefined; + } + if (this.registrationExpiredTimer !== undefined) { + clearTimeout(this.registrationExpiredTimer); + this.registrationExpiredTimer = undefined; + } + if (this.registered) { + this.unregistered(undefined, Constants_1.C.causes.CONNECTION_ERROR); + } + }; + /** + * Helper Function to generate Contact Header + * @private + * returns {String} + */ + RegisterContext.prototype.generateContactHeader = function (expires) { + if (expires === void 0) { expires = 0; } + var contact = this.contact; + if (this.options.regId && this.options.instanceId) { + contact += ";reg-id=" + this.options.regId; + contact += ';+sip.instance=""'; + } + if (this.options.extraContactHeaderParams) { + this.options.extraContactHeaderParams.forEach(function (header) { + contact += ";" + header; + }); + } + contact += ";expires=" + expires; + return contact; + }; + return RegisterContext; +}(ClientContext_1.ClientContext)); +exports.RegisterContext = RegisterContext; + + +/***/ }), +/* 67 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var events_1 = __webpack_require__(2); +var ClientContext_1 = __webpack_require__(1); +var Constants_1 = __webpack_require__(3); +var messages_1 = __webpack_require__(63); +var session_1 = __webpack_require__(68); +var Enums_1 = __webpack_require__(5); +var Exceptions_1 = __webpack_require__(47); +var Grammar_1 = __webpack_require__(7); +var ReferContext_1 = __webpack_require__(51); +var ServerContext_1 = __webpack_require__(62); +var DTMF_1 = __webpack_require__(70); +var Timers_1 = __webpack_require__(56); +var Utils_1 = __webpack_require__(11); +/* + * @param {function returning SIP.sessionDescriptionHandler} [sessionDescriptionHandlerFactory] + * (See the documentation for the sessionDescriptionHandlerFactory argument of the UA constructor.) + */ +var Session = /** @class */ (function (_super) { + __extends(Session, _super); + function Session(sessionDescriptionHandlerFactory) { + var _this = _super.call(this) || this; + _this.data = {}; + _this.type = Enums_1.TypeStrings.Session; + if (!sessionDescriptionHandlerFactory) { + throw new Exceptions_1.Exceptions.SessionDescriptionHandlerError("A session description handler is required for the session to function"); + } + _this.status = Session.C.STATUS_NULL; + _this.pendingReinvite = false; + _this.sessionDescriptionHandlerFactory = sessionDescriptionHandlerFactory; + _this.hasOffer = false; + _this.hasAnswer = false; + // Session Timers + _this.timers = { + ackTimer: undefined, + expiresTimer: undefined, + invite2xxTimer: undefined, + userNoAnswerTimer: undefined, + rel1xxTimer: undefined, + prackTimer: undefined + }; + // Session info + _this.startTime = undefined; + _this.endTime = undefined; + _this.tones = undefined; + // Hold state + _this.localHold = false; + _this.earlySdp = undefined; + _this.rel100 = Constants_1.C.supported.UNSUPPORTED; + return _this; + } + Session.prototype.dtmf = function (tones, options) { + var _this = this; + if (options === void 0) { options = {}; } + // Check Session Status + if (this.status !== Enums_1.SessionStatus.STATUS_CONFIRMED && this.status !== Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK) { + throw new Exceptions_1.Exceptions.InvalidStateError(this.status); + } + // Check tones + if (!tones || !tones.toString().match(/^[0-9A-D#*,]+$/i)) { + throw new TypeError("Invalid tones: " + tones); + } + var sendDTMF = function () { + if (_this.status === Enums_1.SessionStatus.STATUS_TERMINATED || !_this.tones || _this.tones.length === 0) { + // Stop sending DTMF + _this.tones = undefined; + return; + } + var dtmf = _this.tones.shift(); + var timeout; + if (dtmf.tone === ",") { + timeout = 2000; + } + else { + dtmf.on("failed", function () { _this.tones = undefined; }); + dtmf.send(options); + timeout = dtmf.duration + dtmf.interToneGap; + } + // Set timeout for the next tone + setTimeout(sendDTMF, timeout); + }; + tones = tones.toString(); + var dtmfType = this.ua.configuration.dtmfType; + if (this.sessionDescriptionHandler && dtmfType === Constants_1.C.dtmfType.RTP) { + var sent = this.sessionDescriptionHandler.sendDtmf(tones, options); + if (!sent) { + this.logger.warn("Attempt to use dtmfType 'RTP' has failed, falling back to INFO packet method"); + dtmfType = Constants_1.C.dtmfType.INFO; + } + } + if (dtmfType === Constants_1.C.dtmfType.INFO) { + var dtmfs = []; + var tonesArray = tones.split(""); + while (tonesArray.length > 0) { + dtmfs.push(new DTMF_1.DTMF(this, tonesArray.shift(), options)); + } + if (this.tones) { + // Tones are already queued, just add to the queue + this.tones = this.tones.concat(dtmfs); + return this; + } + this.tones = dtmfs; + sendDTMF(); + } + return this; + }; + Session.prototype.bye = function (options) { + if (options === void 0) { options = {}; } + // Check Session Status + if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { + this.logger.error("Error: Attempted to send BYE in a terminated session."); + return this; + } + this.logger.log("terminating Session"); + var statusCode = options.statusCode; + if (statusCode && (statusCode < 200 || statusCode >= 700)) { + throw new TypeError("Invalid statusCode: " + statusCode); + } + options.receiveResponse = function () { }; + return this.sendRequest(Constants_1.C.BYE, options).terminated(); + }; + Session.prototype.refer = function (target, options) { + if (options === void 0) { options = {}; } + // Check Session Status + if (this.status !== Enums_1.SessionStatus.STATUS_CONFIRMED) { + throw new Exceptions_1.Exceptions.InvalidStateError(this.status); + } + this.referContext = new ReferContext_1.ReferClientContext(this.ua, this, target, options); + this.emit("referRequested", this.referContext); + this.referContext.refer(options); + return this.referContext; + }; + /** + * Sends in dialog request. + * @param method Request method. + * @param options Options bucket. + */ + Session.prototype.sendRequest = function (method, options) { + if (options === void 0) { options = {}; } + if (!this.session) { + throw new Error("Session undefined."); + } + // Convert any "body" option to a Body. + if (options.body) { + options.body = messages_1.fromBodyObj(options.body); + } + // Convert any "receiveResponse" callback option passed to an OutgoingRequestDelegate. + var delegate; + var callback = options.receiveResponse; + if (callback) { + delegate = { + onAccept: function (response) { return callback(response.message); }, + onProgress: function (response) { return callback(response.message); }, + onRedirect: function (response) { return callback(response.message); }, + onReject: function (response) { return callback(response.message); }, + onTrying: function (response) { return callback(response.message); } + }; + } + var request; + var requestOptions = options; + switch (method) { + case Constants_1.C.BYE: + request = this.session.bye(delegate, requestOptions); + break; + case Constants_1.C.INVITE: + request = this.session.invite(delegate, requestOptions); + break; + case Constants_1.C.REFER: + request = this.session.refer(delegate, requestOptions); + break; + default: + throw new Error("Unexpected " + method + ". Method not implemented by user agent core."); + } + // Ported - Emit the request event + this.emit(method.toLowerCase(), request.message); + return this; + }; + Session.prototype.close = function () { + if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { + return this; + } + this.logger.log("closing INVITE session " + this.id); + // 1st Step. Terminate media. + if (this.sessionDescriptionHandler) { + this.sessionDescriptionHandler.close(); + } + // 2nd Step. Terminate signaling. + // Clear session timers + for (var timer in this.timers) { + if (this.timers[timer]) { + clearTimeout(this.timers[timer]); + } + } + this.status = Enums_1.SessionStatus.STATUS_TERMINATED; + if (this.ua.transport) { + this.ua.transport.removeListener("transportError", this.errorListener); + } + delete this.ua.sessions[this.id]; + return this; + }; + Session.prototype.hold = function (options, modifiers) { + if (options === void 0) { options = {}; } + if (modifiers === void 0) { modifiers = []; } + if (this.status !== Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK && this.status !== Enums_1.SessionStatus.STATUS_CONFIRMED) { + throw new Exceptions_1.Exceptions.InvalidStateError(this.status); + } + if (this.localHold) { + this.logger.log("Session is already on hold, cannot put it on hold again"); + return; + } + options.modifiers = modifiers; + if (this.sessionDescriptionHandler) { + options.modifiers.push(this.sessionDescriptionHandler.holdModifier); + } + this.localHold = true; + this.sendReinvite(options); + }; + Session.prototype.unhold = function (options, modifiers) { + if (options === void 0) { options = {}; } + if (modifiers === void 0) { modifiers = []; } + if (this.status !== Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK && this.status !== Enums_1.SessionStatus.STATUS_CONFIRMED) { + throw new Exceptions_1.Exceptions.InvalidStateError(this.status); + } + if (!this.localHold) { + this.logger.log("Session is not on hold, cannot unhold it"); + return; + } + options.modifiers = modifiers; + this.localHold = false; + this.sendReinvite(options); + }; + Session.prototype.reinvite = function (options, modifiers) { + if (options === void 0) { options = {}; } + if (modifiers === void 0) { modifiers = []; } + options.modifiers = modifiers; + return this.sendReinvite(options); + }; + Session.prototype.terminate = function (options) { + // here for types and to be overridden + return this; + }; + Session.prototype.onTransportError = function () { + if (this.status !== Enums_1.SessionStatus.STATUS_CONFIRMED && this.status !== Enums_1.SessionStatus.STATUS_TERMINATED) { + this.failed(undefined, Constants_1.C.causes.CONNECTION_ERROR); + } + }; + Session.prototype.onRequestTimeout = function () { + if (this.status === Enums_1.SessionStatus.STATUS_CONFIRMED) { + this.terminated(undefined, Constants_1.C.causes.REQUEST_TIMEOUT); + } + else if (this.status !== Enums_1.SessionStatus.STATUS_TERMINATED) { + this.failed(undefined, Constants_1.C.causes.REQUEST_TIMEOUT); + this.terminated(undefined, Constants_1.C.causes.REQUEST_TIMEOUT); + } + }; + Session.prototype.onDialogError = function (response) { + if (this.status === Enums_1.SessionStatus.STATUS_CONFIRMED) { + this.terminated(response, Constants_1.C.causes.DIALOG_ERROR); + } + else if (this.status !== Enums_1.SessionStatus.STATUS_TERMINATED) { + this.failed(response, Constants_1.C.causes.DIALOG_ERROR); + this.terminated(response, Constants_1.C.causes.DIALOG_ERROR); + } + }; + Session.prototype.on = function (name, callback) { + return _super.prototype.on.call(this, name, callback); + }; + Session.prototype.onAck = function (incomingRequest) { + var _this = this; + var confirmSession = function () { + clearTimeout(_this.timers.ackTimer); + clearTimeout(_this.timers.invite2xxTimer); + _this.status = Enums_1.SessionStatus.STATUS_CONFIRMED; + var contentDisp = incomingRequest.message.getHeader("Content-Disposition"); + if (contentDisp && contentDisp.type === "render") { + _this.renderbody = incomingRequest.message.body; + _this.rendertype = incomingRequest.message.getHeader("Content-Type"); + } + _this.emit("confirmed", incomingRequest.message); + }; + if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK) { + if (this.sessionDescriptionHandler && + this.sessionDescriptionHandler.hasDescription(incomingRequest.message.getHeader("Content-Type") || "")) { + this.hasAnswer = true; + this.sessionDescriptionHandler.setDescription(incomingRequest.message.body, this.sessionDescriptionHandlerOptions, this.modifiers).catch(function (e) { + _this.logger.warn(e); + _this.terminate({ + statusCode: "488", + reasonPhrase: "Bad Media Description" + }); + _this.failed(incomingRequest.message, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); + _this.terminated(incomingRequest.message, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); + throw e; + }).then(function () { return confirmSession(); }); + } + else { + confirmSession(); + } + } + }; + Session.prototype.receiveRequest = function (incomingRequest) { + switch (incomingRequest.message.method) { // TODO: This needs a default case + case Constants_1.C.BYE: + incomingRequest.accept(); + if (this.status === Enums_1.SessionStatus.STATUS_CONFIRMED) { + this.emit("bye", incomingRequest.message); + this.terminated(incomingRequest.message, Constants_1.C.BYE); + } + break; + case Constants_1.C.INVITE: + if (this.status === Enums_1.SessionStatus.STATUS_CONFIRMED) { + this.logger.log("re-INVITE received"); + this.receiveReinvite(incomingRequest); + } + break; + case Constants_1.C.INFO: + if (this.status === Enums_1.SessionStatus.STATUS_CONFIRMED || this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK) { + if (this.onInfo) { + return this.onInfo(incomingRequest.message); + } + var contentType = incomingRequest.message.getHeader("content-type"); + if (contentType) { + if (contentType.match(/^application\/dtmf-relay/i)) { + if (incomingRequest.message.body) { + var body = incomingRequest.message.body.split("\r\n", 2); + if (body.length === 2) { + var tone = void 0; + var duration = void 0; + var regTone = /^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/; + if (regTone.test(body[0])) { + tone = body[0].replace(regTone, "$2"); + } + var regDuration = /^(Duration\s?=\s?)([0-9]{1,4})(\s)?.*/; + if (regDuration.test(body[1])) { + duration = parseInt(body[1].replace(regDuration, "$2"), 10); + } + if (tone && duration) { + new DTMF_1.DTMF(this, tone, { duration: duration }).init_incoming(incomingRequest); + } + } + } + } + else { + incomingRequest.reject({ + statusCode: 415, + extraHeaders: ["Accept: application/dtmf-relay"] + }); + } + } + } + break; + case Constants_1.C.REFER: + if (this.status === Enums_1.SessionStatus.STATUS_CONFIRMED) { + this.logger.log("REFER received"); + this.referContext = new ReferContext_1.ReferServerContext(this.ua, incomingRequest, this.session); + if (this.listeners("referRequested").length) { + this.emit("referRequested", this.referContext); + } + else { + this.logger.log("No referRequested listeners, automatically accepting and following the refer"); + var options = { followRefer: true }; + if (this.passedOptions) { + options.inviteOptions = this.passedOptions; + } + this.referContext.accept(options, this.modifiers); + } + } + break; + case Constants_1.C.NOTIFY: + if (this.referContext && + this.referContext.type === Enums_1.TypeStrings.ReferClientContext && + incomingRequest.message.hasHeader("event") && + /^refer(;.*)?$/.test(incomingRequest.message.getHeader("event"))) { + this.referContext.receiveNotify(incomingRequest); + return; + } + incomingRequest.accept(); + this.emit("notify", incomingRequest.message); + break; + } + }; + // In dialog INVITE Reception + Session.prototype.receiveReinvite = function (incomingRequest) { + // TODO: Should probably check state of the session + var _this = this; + this.emit("reinvite", this, incomingRequest.message); + if (incomingRequest.message.hasHeader("P-Asserted-Identity")) { + this.assertedIdentity = + Grammar_1.Grammar.nameAddrHeaderParse(incomingRequest.message.getHeader("P-Asserted-Identity")); + } + var promise; + if (!this.sessionDescriptionHandler) { + this.logger.warn("No SessionDescriptionHandler to reinvite"); + return; + } + if (incomingRequest.message.getHeader("Content-Length") === "0" && + !incomingRequest.message.getHeader("Content-Type")) { // Invite w/o SDP + promise = this.sessionDescriptionHandler.getDescription(this.sessionDescriptionHandlerOptions, this.modifiers); + } + else if (this.sessionDescriptionHandler.hasDescription(incomingRequest.message.getHeader("Content-Type") || "")) { + // Invite w/ SDP + promise = this.sessionDescriptionHandler.setDescription(incomingRequest.message.body, this.sessionDescriptionHandlerOptions, this.modifiers).then(this.sessionDescriptionHandler.getDescription.bind(this.sessionDescriptionHandler, this.sessionDescriptionHandlerOptions, this.modifiers)); + } + else { // Bad Packet (should never get hit) + incomingRequest.reject({ statusCode: 415 }); + this.emit("reinviteFailed", this); + return; + } + promise.catch(function (e) { + var statusCode; + if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { + statusCode = 500; + } + else if (e.type === Enums_1.TypeStrings.RenegotiationError) { + _this.emit("renegotiationError", e); + _this.logger.warn(e.toString()); + statusCode = 488; + } + else { + _this.logger.error(e); + statusCode = 488; + } + incomingRequest.reject({ statusCode: statusCode }); + _this.emit("reinviteFailed", _this); + // TODO: This could be better + throw e; + }).then(function (description) { + var extraHeaders = ["Contact: " + _this.contact]; + incomingRequest.accept({ + statusCode: 200, + extraHeaders: extraHeaders, + body: messages_1.fromBodyObj(description) + }); + _this.status = Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK; + _this.emit("reinviteAccepted", _this); + }); + }; + Session.prototype.sendReinvite = function (options) { + var _this = this; + if (options === void 0) { options = {}; } + if (this.pendingReinvite) { + this.logger.warn("Reinvite in progress. Please wait until complete, then try again."); + return; + } + if (!this.sessionDescriptionHandler) { + this.logger.warn("No SessionDescriptionHandler, can't reinvite.."); + return; + } + this.pendingReinvite = true; + options.modifiers = options.modifiers || []; + var extraHeaders = (options.extraHeaders || []).slice(); + extraHeaders.push("Contact: " + this.contact); + // this is UA.C.ALLOWED_METHODS, removed to get around circular dependency + extraHeaders.push("Allow: " + [ + "ACK", + "CANCEL", + "INVITE", + "MESSAGE", + "BYE", + "OPTIONS", + "INFO", + "NOTIFY", + "REFER" + ].toString()); + this.sessionDescriptionHandler.getDescription(options.sessionDescriptionHandlerOptions, options.modifiers) + .then(function (description) { + if (!_this.session) { + throw new Error("Session undefined."); + } + var delegate = { + onAccept: function (response) { + if (_this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { + _this.logger.error("Received reinvite response, but in STATUS_TERMINATED"); + // TODO: Do we need to send a SIP response? + return; + } + if (!_this.pendingReinvite) { + _this.logger.error("Received reinvite response, but have no pending reinvite"); + // TODO: Do we need to send a SIP response? + return; + } + // FIXME: Why is this set here? + _this.status = Enums_1.SessionStatus.STATUS_CONFIRMED; + // 17.1.1.1 - For each final response that is received at the client transaction, + // the client transaction sends an ACK, + _this.emit("ack", response.ack()); + _this.pendingReinvite = false; + // TODO: All of these timers should move into the Transaction layer + clearTimeout(_this.timers.invite2xxTimer); + if (!_this.sessionDescriptionHandler || + !_this.sessionDescriptionHandler.hasDescription(response.message.getHeader("Content-Type") || "")) { + _this.logger.error("2XX response received to re-invite but did not have a description"); + _this.emit("reinviteFailed", _this); + _this.emit("renegotiationError", new Exceptions_1.Exceptions.RenegotiationError("2XX response received to re-invite but did not have a description")); + return; + } + _this.sessionDescriptionHandler + .setDescription(response.message.body, _this.sessionDescriptionHandlerOptions, _this.modifiers) + .catch(function (e) { + _this.logger.error("Could not set the description in 2XX response"); + _this.logger.error(e); + _this.emit("reinviteFailed", _this); + _this.emit("renegotiationError", e); + _this.sendRequest(Constants_1.C.BYE, { + extraHeaders: ["Reason: " + Utils_1.Utils.getReasonHeaderValue(488, "Not Acceptable Here")] + }); + _this.terminated(undefined, Constants_1.C.causes.INCOMPATIBLE_SDP); + throw e; + }) + .then(function () { + _this.emit("reinviteAccepted", _this); + }); + }, + onProgress: function (response) { + return; + }, + onRedirect: function (response) { + // FIXME: Does ACK need to be sent? + _this.pendingReinvite = false; + _this.logger.log("Received a non 1XX or 2XX response to a re-invite"); + _this.emit("reinviteFailed", _this); + _this.emit("renegotiationError", new Exceptions_1.Exceptions.RenegotiationError("Invalid response to a re-invite")); + }, + onReject: function (response) { + // FIXME: Does ACK need to be sent? + _this.pendingReinvite = false; + _this.logger.log("Received a non 1XX or 2XX response to a re-invite"); + _this.emit("reinviteFailed", _this); + _this.emit("renegotiationError", new Exceptions_1.Exceptions.RenegotiationError("Invalid response to a re-invite")); + }, + onTrying: function (response) { + return; + } + }; + var requestOptions = { + extraHeaders: extraHeaders, + body: messages_1.fromBodyObj(description) + }; + _this.session.invite(delegate, requestOptions); + }).catch(function (e) { + if (e.type === Enums_1.TypeStrings.RenegotiationError) { + _this.pendingReinvite = false; + _this.emit("renegotiationError", e); + _this.logger.warn("Renegotiation Error"); + _this.logger.warn(e.toString()); + throw e; + } + _this.logger.error("sessionDescriptionHandler error"); + _this.logger.error(e); + throw e; + }); + }; + Session.prototype.failed = function (response, cause) { + if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { + return this; + } + this.emit("failed", response, cause); + return this; + }; + Session.prototype.rejected = function (response, cause) { + this.emit("rejected", response, cause); + return this; + }; + Session.prototype.canceled = function () { + if (this.sessionDescriptionHandler) { + this.sessionDescriptionHandler.close(); + } + this.emit("cancel"); + return this; + }; + Session.prototype.accepted = function (response, cause) { + if (!(response instanceof String)) { + cause = Utils_1.Utils.getReasonPhrase((response && response.statusCode) || 0, cause); + } + this.startTime = new Date(); + if (this.replacee) { + this.replacee.emit("replaced", this); + this.replacee.terminate(); + } + this.emit("accepted", response, cause); + return this; + }; + Session.prototype.terminated = function (message, cause) { + if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { + return this; + } + this.endTime = new Date(); + this.close(); + this.emit("terminated", message, cause); + return this; + }; + Session.prototype.connecting = function (request) { + this.emit("connecting", { request: request }); + return this; + }; + Session.C = Enums_1.SessionStatus; + return Session; +}(events_1.EventEmitter)); +exports.Session = Session; +// tslint:disable-next-line:max-classes-per-file +var InviteServerContext = /** @class */ (function (_super) { + __extends(InviteServerContext, _super); + function InviteServerContext(ua, incomingInviteRequest) { + var _this = this; + if (!ua.configuration.sessionDescriptionHandlerFactory) { + ua.logger.warn("Can't build ISC without SDH Factory"); + throw new Error("ISC Constructor Failed"); + } + _this = _super.call(this, ua.configuration.sessionDescriptionHandlerFactory) || this; + _this._canceled = false; + _this.rseq = Math.floor(Math.random() * 10000); + _this.incomingRequest = incomingInviteRequest; + var request = incomingInviteRequest.message; + ServerContext_1.ServerContext.initializer(_this, ua, incomingInviteRequest); + _this.type = Enums_1.TypeStrings.InviteServerContext; + var contentDisp = request.parseHeader("Content-Disposition"); + if (contentDisp && contentDisp.type === "render") { + _this.renderbody = request.body; + _this.rendertype = request.getHeader("Content-Type"); + } + _this.status = Enums_1.SessionStatus.STATUS_INVITE_RECEIVED; + _this.fromTag = request.fromTag; + _this.id = request.callId + _this.fromTag; + _this.request = request; + _this.contact = _this.ua.contact.toString(); + _this.logger = ua.getLogger("sip.inviteservercontext", _this.id); + // Save the session into the ua sessions collection. + _this.ua.sessions[_this.id] = _this; + // Set 100rel if necessary + var set100rel = function (header, relSetting) { + if (request.hasHeader(header) && request.getHeader(header).toLowerCase().indexOf("100rel") >= 0) { + _this.rel100 = relSetting; + } + }; + set100rel("require", Constants_1.C.supported.REQUIRED); + set100rel("supported", Constants_1.C.supported.SUPPORTED); + // Set the toTag on the incoming request to the toTag which + // will be used in the response to the incoming request!!! + // FIXME: HACK: This is a hack to port an existing behavior. + // The behavior being ported appears to be a hack itself, + // so this is a hack to port a hack. At least one test spec + // relies on it (which is yet another hack). + _this.request.toTag = incomingInviteRequest.toTag; + _this.status = Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER; + // Set userNoAnswerTimer + _this.timers.userNoAnswerTimer = setTimeout(function () { + incomingInviteRequest.reject({ statusCode: 408 }); + _this.failed(request, Constants_1.C.causes.NO_ANSWER); + _this.terminated(request, Constants_1.C.causes.NO_ANSWER); + }, _this.ua.configuration.noAnswerTimeout || 60); + /* Set expiresTimer + * RFC3261 13.3.1 + */ + // Get the Expires header value if exists + if (request.hasHeader("expires")) { + var expires = Number(request.getHeader("expires") || 0) * 1000; + _this.timers.expiresTimer = setTimeout(function () { + if (_this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER) { + incomingInviteRequest.reject({ statusCode: 487 }); + _this.failed(request, Constants_1.C.causes.EXPIRES); + _this.terminated(request, Constants_1.C.causes.EXPIRES); + } + }, expires); + } + _this.errorListener = _this.onTransportError.bind(_this); + if (ua.transport) { + ua.transport.on("transportError", _this.errorListener); + } + return _this; + } + Object.defineProperty(InviteServerContext.prototype, "autoSendAnInitialProvisionalResponse", { + /** + * If true, a first provisional response after the 100 Trying + * will be sent automatically. This is false it the UAC required + * reliable provisional responses (100rel in Require header), + * otherwise it is true. The provisional is sent by calling + * `progress()` without any options. + * + * FIXME: TODO: It seems reasonable that the ISC user should + * be able to optionally disable this behavior. As the provisional + * is sent prior to the "invite" event being emitted, it's a known + * issue that the ISC user cannot register listeners or do any other + * setup prior to the call to `progress()`. As an example why this is + * an issue, setting `ua.configuration.rel100` to REQUIRED will result + * in an attempt by `progress()` to send a 183 with SDP produced by + * calling `getDescription()` on a session description handler, but + * the ISC user cannot perform any potentially required session description + * handler initialization (thus preventing the utilization of setting + * `ua.configuration.rel100` to REQUIRED). That begs the question of + * why this behavior is disabled when the UAC requires 100rel but not + * when the UAS requires 100rel? But ignoring that, it's just one example + * of a class of cases where the ISC user needs to do something prior + * to the first call to `progress()` and is unable to do so. + */ + get: function () { + return this.rel100 === Constants_1.C.supported.REQUIRED ? false : true; + }, + enumerable: true, + configurable: true + }); + // type hack for servercontext interface + InviteServerContext.prototype.reply = function (options) { + if (options === void 0) { options = {}; } + return this; + }; + // typing note: this was the only function using its super in ServerContext + // so the bottom half of this function is copied and paired down from that + InviteServerContext.prototype.reject = function (options) { + var _this = this; + if (options === void 0) { options = {}; } + // Check Session Status + if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { + throw new Exceptions_1.Exceptions.InvalidStateError(this.status); + } + this.logger.log("rejecting RTCSession"); + var statusCode = options.statusCode || 480; + var reasonPhrase = Utils_1.Utils.getReasonPhrase(statusCode, options.reasonPhrase); + var extraHeaders = options.extraHeaders || []; + if (statusCode < 300 || statusCode > 699) { + throw new TypeError("Invalid statusCode: " + statusCode); + } + var body = options.body ? messages_1.fromBodyLegacy(options.body) : undefined; + // FIXME: Need to redirect to someplae + var response = statusCode < 400 ? + this.incomingRequest.redirect([], { statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }) : + this.incomingRequest.reject({ statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }); + (["rejected", "failed"]).forEach(function (event) { + _this.emit(event, response.message, reasonPhrase); + }); + return this.terminated(); + }; + /** + * Accept the incoming INVITE request to start a Session. + * Replies to the INVITE request with a 200 Ok response. + * @param options Options bucket. + */ + InviteServerContext.prototype.accept = function (options) { + var _this = this; + if (options === void 0) { options = {}; } + // FIXME: Need guard against calling more than once. + this._accept(options) + .then(function (_a) { + var message = _a.message, session = _a.session; + session.delegate = { + onAck: function (ackRequest) { return _this.onAck(ackRequest); }, + onAckTimeout: function () { return _this.onAckTimeout(); }, + onBye: function (byeRequest) { return _this.receiveRequest(byeRequest); }, + onInfo: function (infoRequest) { return _this.receiveRequest(infoRequest); }, + onInvite: function (inviteRequest) { return _this.receiveRequest(inviteRequest); }, + onNotify: function (notifyRequest) { return _this.receiveRequest(notifyRequest); }, + onPrack: function (prackRequest) { return _this.receiveRequest(prackRequest); }, + onRefer: function (referRequest) { return _this.receiveRequest(referRequest); } + }; + _this.session = session; + _this.status = Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK; + _this.accepted(message, Utils_1.Utils.getReasonPhrase(200)); + }) + .catch(function (error) { + _this.onContextError(error); + // FIXME: Assuming error due to async race on CANCEL and eating error. + if (!_this._canceled) { + throw error; + } + }); + return this; + }; + /** + * Report progress to the the caller. + * Replies to the INVITE request with a 1xx provisional response. + * @param options Options bucket. + */ + InviteServerContext.prototype.progress = function (options) { + var _this = this; + if (options === void 0) { options = {}; } + // Ported + var statusCode = options.statusCode || 180; + if (statusCode < 100 || statusCode > 199) { + throw new TypeError("Invalid statusCode: " + statusCode); + } + // Ported + if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { + this.logger.warn("Unexpected call for progress while terminated, ignoring"); + return this; + } + // Added + if (this.status === Enums_1.SessionStatus.STATUS_ANSWERED) { + this.logger.warn("Unexpected call for progress while answered, ignoring"); + return this; + } + // Added + if (this.status === Enums_1.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK) { + this.logger.warn("Unexpected call for progress while answered (waiting for prack), ignoring"); + return this; + } + // After the first reliable provisional response for a request has been + // acknowledged, the UAS MAY send additional reliable provisional + // responses. The UAS MUST NOT send a second reliable provisional + // response until the first is acknowledged. After the first, it is + // RECOMMENDED that the UAS not send an additional reliable provisional + // response until the previous is acknowledged. The first reliable + // provisional response receives special treatment because it conveys + // the initial sequence number. If additional reliable provisional + // responses were sent before the first was acknowledged, the UAS could + // not be certain these were received in order. + // https://tools.ietf.org/html/rfc3262#section-3 + if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_PRACK) { + this.logger.warn("Unexpected call for progress while waiting for prack, ignoring"); + return this; + } + // Ported + if (options.statusCode === 100) { + try { + this.incomingRequest.trying(); + } + catch (error) { + this.onContextError(error); + // FIXME: Assuming error due to async race on CANCEL and eating error. + if (!this._canceled) { + throw error; + } + } + return this; + } + // Standard provisional response. + if (!(this.rel100 === Constants_1.C.supported.REQUIRED) && + !(this.rel100 === Constants_1.C.supported.SUPPORTED && options.rel100) && + !(this.rel100 === Constants_1.C.supported.SUPPORTED && this.ua.configuration.rel100 === Constants_1.C.supported.REQUIRED)) { + this._progress(options) + .catch(function (error) { + _this.onContextError(error); + // FIXME: Assuming error due to async race on CANCEL and eating error. + if (!_this._canceled) { + throw error; + } + }); + return this; + } + // Reliable provisional response. + this._reliableProgressWaitForPrack(options) + .catch(function (error) { + _this.onContextError(error); + // FIXME: Assuming error due to async race on CANCEL and eating error. + if (!_this._canceled) { + throw error; + } + }); + return this; + }; + /** + * Reject an unaccepted incoming INVITE request or send BYE if established session. + * @param options Options bucket. FIXME: This options bucket needs to be typed. + */ + InviteServerContext.prototype.terminate = function (options) { + // The caller's UA MAY send a BYE for either confirmed or early dialogs, + // and the callee's UA MAY send a BYE on confirmed dialogs, but MUST NOT + // send a BYE on early dialogs. However, the callee's UA MUST NOT send a + // BYE on a confirmed dialog until it has received an ACK for its 2xx + // response or until the server transaction times out. + // https://tools.ietf.org/html/rfc3261#section-15 + var _this = this; + if (options === void 0) { options = {}; } + // We don't yet have a dialog, so reject request. + if (!this.session) { + this.reject(options); + return this; + } + switch (this.session.sessionState) { + case session_1.SessionState.Initial: + this.reject(options); + return this; + case session_1.SessionState.Early: + this.reject(options); + return this; + case session_1.SessionState.AckWait: + this.session.delegate = { + // When ACK shows up, say BYE. + onAck: function () { + _this.sendRequest(Constants_1.C.BYE, options); + }, + // Or the server transaction times out before the ACK arrives. + onAckTimeout: function () { + _this.sendRequest(Constants_1.C.BYE, options); + } + }; + // Ported + this.emit("bye", this.request); + this.terminated(); + return this; + case session_1.SessionState.Confirmed: + this.bye(options); + return this; + case session_1.SessionState.Terminated: + return this; + default: + return this; + } + }; + InviteServerContext.prototype.onCancel = function (message) { + if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER || + this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_PRACK || + this.status === Enums_1.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK || + this.status === Enums_1.SessionStatus.STATUS_EARLY_MEDIA || + this.status === Enums_1.SessionStatus.STATUS_ANSWERED) { + this.status = Enums_1.SessionStatus.STATUS_CANCELED; + this.incomingRequest.reject({ statusCode: 487 }); + this.canceled(); + this.rejected(message, Constants_1.C.causes.CANCELED); + this.failed(message, Constants_1.C.causes.CANCELED); + this.terminated(message, Constants_1.C.causes.CANCELED); + } + }; + InviteServerContext.prototype.receiveRequest = function (incomingRequest) { + var _this = this; + switch (incomingRequest.message.method) { + case Constants_1.C.PRACK: + if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_PRACK || + this.status === Enums_1.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK) { + if (!this.hasAnswer) { + this.sessionDescriptionHandler = this.setupSessionDescriptionHandler(); + this.emit("SessionDescriptionHandler-created", this.sessionDescriptionHandler); + if (this.sessionDescriptionHandler.hasDescription(incomingRequest.message.getHeader("Content-Type") || "")) { + this.hasAnswer = true; + this.sessionDescriptionHandler.setDescription(incomingRequest.message.body, this.sessionDescriptionHandlerOptions, this.modifiers).then(function () { + clearTimeout(_this.timers.rel1xxTimer); + clearTimeout(_this.timers.prackTimer); + incomingRequest.accept(); + if (_this.status === Enums_1.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK) { + _this.status = Enums_1.SessionStatus.STATUS_EARLY_MEDIA; + _this.accept(); + } + _this.status = Enums_1.SessionStatus.STATUS_EARLY_MEDIA; + }, function (e) { + _this.logger.warn(e); + _this.terminate({ + statusCode: "488", + reasonPhrase: "Bad Media Description" + }); + _this.failed(incomingRequest.message, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); + _this.terminated(incomingRequest.message, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); + }); + } + else { + this.terminate({ + statusCode: "488", + reasonPhrase: "Bad Media Description" + }); + this.failed(incomingRequest.message, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); + this.terminated(incomingRequest.message, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); + } + } + else { + clearTimeout(this.timers.rel1xxTimer); + clearTimeout(this.timers.prackTimer); + incomingRequest.accept(); + if (this.status === Enums_1.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK) { + this.status = Enums_1.SessionStatus.STATUS_EARLY_MEDIA; + this.accept(); + } + this.status = Enums_1.SessionStatus.STATUS_EARLY_MEDIA; + } + } + else if (this.status === Enums_1.SessionStatus.STATUS_EARLY_MEDIA) { + incomingRequest.accept(); + } + break; + default: + _super.prototype.receiveRequest.call(this, incomingRequest); + break; + } + }; + // Internal Function to setup the handler consistently + InviteServerContext.prototype.setupSessionDescriptionHandler = function () { + if (this.sessionDescriptionHandler) { + return this.sessionDescriptionHandler; + } + return this.sessionDescriptionHandlerFactory(this, this.ua.configuration.sessionDescriptionHandlerFactoryOptions); + }; + InviteServerContext.prototype.generateResponseOfferAnswer = function (options) { + if (!this.session) { + var body = messages_1.getBody(this.incomingRequest.message); + if (!body || body.contentDisposition !== "session") { + return this.getOffer(options); + } + else { + return this.setOfferAndGetAnswer(body, options); + } + } + else { + switch (this.session.signalingState) { + case session_1.SignalingState.Initial: + return this.getOffer(options); + case session_1.SignalingState.Stable: + return Promise.resolve(undefined); + case session_1.SignalingState.HaveLocalOffer: + // o Once the UAS has sent or received an answer to the initial + // offer, it MUST NOT generate subsequent offers in any responses + // to the initial INVITE. This means that a UAS based on this + // specification alone can never generate subsequent offers until + // completion of the initial transaction. + // https://tools.ietf.org/html/rfc3261#section-13.2.1 + return Promise.resolve(undefined); + case session_1.SignalingState.HaveRemoteOffer: + if (!this.session.offer) { + throw new Error("Session offer undefined"); + } + return this.setOfferAndGetAnswer(this.session.offer, options); + case session_1.SignalingState.Closed: + throw new Error("Invalid signaling state " + this.session.signalingState + "."); + default: + throw new Error("Invalid signaling state " + this.session.signalingState + "."); + } + } + }; + InviteServerContext.prototype.handlePrackOfferAnswer = function (request, options) { + if (!this.session) { + throw new Error("Session undefined."); + } + // If the PRACK doesn't have an offer/answer, nothing to be done. + var body = messages_1.getBody(request.message); + if (!body || body.contentDisposition !== "session") { + return Promise.resolve(undefined); + } + // If the UAC receives a reliable provisional response with an offer + // (this would occur if the UAC sent an INVITE without an offer, in + // which case the first reliable provisional response will contain the + // offer), it MUST generate an answer in the PRACK. If the UAC receives + // a reliable provisional response with an answer, it MAY generate an + // additional offer in the PRACK. If the UAS receives a PRACK with an + // offer, it MUST place the answer in the 2xx to the PRACK. + // https://tools.ietf.org/html/rfc3262#section-5 + switch (this.session.signalingState) { + case session_1.SignalingState.Initial: + // State should never be reached as first reliable provisional response must have answer/offer. + throw new Error("Invalid signaling state " + this.session.signalingState + "."); + case session_1.SignalingState.Stable: + // Receved answer. + return this.setAnswer(body, options).then(function () { return undefined; }); + case session_1.SignalingState.HaveLocalOffer: + // State should never be reached as local offer would be answered by this PRACK + throw new Error("Invalid signaling state " + this.session.signalingState + "."); + case session_1.SignalingState.HaveRemoteOffer: + // Receved offer, generate answer. + return this.setOfferAndGetAnswer(body, options); + case session_1.SignalingState.Closed: + throw new Error("Invalid signaling state " + this.session.signalingState + "."); + default: + throw new Error("Invalid signaling state " + this.session.signalingState + "."); + } + }; + /** + * Called when session canceled. + */ + InviteServerContext.prototype.canceled = function () { + this._canceled = true; + return _super.prototype.canceled.call(this); + }; + /** + * Called when session terminated. + * Using it here just for the PRACK timeout. + */ + InviteServerContext.prototype.terminated = function (message, cause) { + this.prackNeverArrived(); + return _super.prototype.terminated.call(this, message, cause); + }; + /** + * A version of `accept` which resolves a session when the 200 Ok response is sent. + * @param options Options bucket. + * @throws {ClosedSessionDescriptionHandlerError} The session description handler closed before method completed. + * @throws {TransactionStateError} The transaction state does not allow for `accept()` to be called. + * Note that the transaction state can change while this call is in progress. + */ + InviteServerContext.prototype._accept = function (options) { + var _this = this; + if (options === void 0) { options = {}; } + // FIXME: Ported - callback for in dialog INFO requests. + // Turns out accept() can be called more than once if we are waiting + // for a PRACK in which case "options" get completely tossed away. + // So this is broken in that case (and potentially other uses of options). + // Tempted to just try to fix it now, but leaving it broken for the moment. + this.onInfo = options.onInfo; + // The UAS MAY send a final response to the initial request before + // having received PRACKs for all unacknowledged reliable provisional + // responses, unless the final response is 2xx and any of the + // unacknowledged reliable provisional responses contained a session + // description. In that case, it MUST NOT send a final response until + // those provisional responses are acknowledged. If the UAS does send a + // final response when reliable responses are still unacknowledged, it + // SHOULD NOT continue to retransmit the unacknowledged reliable + // provisional responses, but it MUST be prepared to process PRACK + // requests for those outstanding responses. A UAS MUST NOT send new + // reliable provisional responses (as opposed to retransmissions of + // unacknowledged ones) after sending a final response to a request. + // https://tools.ietf.org/html/rfc3262#section-3 + if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_PRACK) { + this.status = Enums_1.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK; + return this.waitForArrivalOfPrack() + .then(function () { + _this.status = Enums_1.SessionStatus.STATUS_ANSWERED; + clearTimeout(_this.timers.userNoAnswerTimer); // Ported + }) + .then(function () { return _this.generateResponseOfferAnswer(options); }) + .then(function (body) { return _this.incomingRequest.accept({ statusCode: 200, body: body }); }); + } + // Ported + if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER) { + this.status = Enums_1.SessionStatus.STATUS_ANSWERED; + } + else { + return Promise.reject(new Exceptions_1.Exceptions.InvalidStateError(this.status)); + } + this.status = Enums_1.SessionStatus.STATUS_ANSWERED; + clearTimeout(this.timers.userNoAnswerTimer); // Ported + return this.generateResponseOfferAnswer(options) + .then(function (body) { return _this.incomingRequest.accept({ statusCode: 200, body: body }); }); + }; + /** + * A version of `progress` which resolves when the provisional response is sent. + * @param options Options bucket. + * @throws {ClosedSessionDescriptionHandlerError} The session description handler closed before method completed. + * @throws {TransactionStateError} The transaction state does not allow for `progress()` to be called. + * Note that the transaction state can change while this call is in progress. + */ + InviteServerContext.prototype._progress = function (options) { + if (options === void 0) { options = {}; } + // Ported + var statusCode = options.statusCode || 180; + var reasonPhrase = options.reasonPhrase; + var extraHeaders = (options.extraHeaders || []).slice(); + var body = options.body ? messages_1.fromBodyLegacy(options.body) : undefined; + try { + var progressResponse = this.incomingRequest.progress({ statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }); + this.emit("progress", progressResponse.message, reasonPhrase); // Ported + this.session = progressResponse.session; + return Promise.resolve(progressResponse); + } + catch (error) { + return Promise.reject(error); + } + }; + /** + * A version of `progress` which resolves when the reliable provisional response is sent. + * @param options Options bucket. + * @throws {ClosedSessionDescriptionHandlerError} The session description handler closed before method completed. + * @throws {TransactionStateError} The transaction state does not allow for `progress()` to be called. + * Note that the transaction state can change while this call is in progress. + */ + InviteServerContext.prototype._reliableProgress = function (options) { + var _this = this; + if (options === void 0) { options = {}; } + var statusCode = options.statusCode || 183; + var reasonPhrase = options.reasonPhrase; + var extraHeaders = (options.extraHeaders || []).slice(); + extraHeaders.push("Require: 100rel"); + extraHeaders.push("RSeq: " + Math.floor(Math.random() * 10000)); + // Get an offer/answer and send a reply. + return this.generateResponseOfferAnswer(options) + .then(function (body) { return _this.incomingRequest.progress({ statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }); }) + .then(function (progressResponse) { + _this.emit("progress", progressResponse.message, reasonPhrase); // Ported + _this.session = progressResponse.session; + return progressResponse; + }); + }; + /** + * A version of `progress` which resolves when the reliable provisional response is acknowledged. + * @param options Options bucket. + * @throws {ClosedSessionDescriptionHandlerError} The session description handler closed before method completed. + * @throws {TransactionStateError} The transaction state does not allow for `progress()` to be called. + * Note that the transaction state can change while this call is in progress. + */ + InviteServerContext.prototype._reliableProgressWaitForPrack = function (options) { + var _this = this; + if (options === void 0) { options = {}; } + var statusCode = options.statusCode || 183; + var reasonPhrase = options.reasonPhrase; + var extraHeaders = (options.extraHeaders || []).slice(); + extraHeaders.push("Require: 100rel"); + extraHeaders.push("RSeq: " + this.rseq++); + var body; + // Ported - set status. + this.status = Enums_1.SessionStatus.STATUS_WAITING_FOR_PRACK; + return new Promise(function (resolve, reject) { + var waitingForPrack = true; + return _this.generateResponseOfferAnswer(options) + .then(function (offerAnswer) { + body = offerAnswer; + return _this.incomingRequest.progress({ statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }); + }) + .then(function (progressResponse) { + _this.emit("progress", progressResponse.message, reasonPhrase); // Ported + _this.session = progressResponse.session; + var prackRequest; + var prackResponse; + progressResponse.session.delegate = { + onPrack: function (request) { + prackRequest = request; + clearTimeout(prackWaitTimeoutTimer); + clearTimeout(rel1xxRetransmissionTimer); + if (!waitingForPrack) { + return; + } + waitingForPrack = false; + _this.handlePrackOfferAnswer(prackRequest, options) + .then(function (prackResponseBody) { + try { + prackResponse = prackRequest.accept({ statusCode: 200, body: prackResponseBody }); + // Ported - set status. + if (_this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_PRACK) { + _this.status = Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER; + } + _this.prackArrived(); + resolve({ prackRequest: prackRequest, prackResponse: prackResponse, progressResponse: progressResponse }); + } + catch (error) { + reject(error); + } + }); + } + }; + // https://tools.ietf.org/html/rfc3262#section-3 + var prackWaitTimeout = function () { + if (!waitingForPrack) { + return; + } + waitingForPrack = false; + _this.logger.warn("No PRACK received, rejecting INVITE."); + clearTimeout(rel1xxRetransmissionTimer); + try { + _this.incomingRequest.reject({ statusCode: 504 }); + _this.terminated(undefined, Constants_1.C.causes.NO_PRACK); + reject(new Exceptions_1.Exceptions.TerminatedSessionError()); + } + catch (error) { + reject(error); + } + }; + var prackWaitTimeoutTimer = setTimeout(prackWaitTimeout, Timers_1.Timers.T1 * 64); + // https://tools.ietf.org/html/rfc3262#section-3 + var rel1xxRetransmission = function () { + try { + _this.incomingRequest.progress({ statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }); + } + catch (error) { + waitingForPrack = false; + reject(error); + return; + } + rel1xxRetransmissionTimer = setTimeout(rel1xxRetransmission, timeout *= 2); + }; + var timeout = Timers_1.Timers.T1; + var rel1xxRetransmissionTimer = setTimeout(rel1xxRetransmission, timeout); + }); + }); + }; + /** + * Callback for when ACK for a 2xx response is never received. + * @param session Session the ACK never arrived for + */ + InviteServerContext.prototype.onAckTimeout = function () { + if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK) { + this.logger.log("no ACK received for an extended period of time, terminating the call"); + if (!this.session) { + throw new Error("Session undefined."); + } + this.session.bye(); + this.terminated(undefined, Constants_1.C.causes.NO_ACK); + } + }; + /** + * FIXME: TODO: The current library interface presents async methods without a + * proper async error handling mechanism. Arguably a promise based interface + * would be an improvement over the pattern of returning `this`. The approach has + * been generally along the lines of log a error and terminate. + */ + InviteServerContext.prototype.onContextError = function (error) { + var statusCode = 480; + if (error instanceof Exceptions_1.Exception) { // There might be interest in catching these Exceptions. + if (error instanceof Exceptions_1.Exceptions.SessionDescriptionHandlerError) { + this.logger.error(error.message); + if (error.error) { + this.logger.error(error.error); + } + } + else if (error instanceof Exceptions_1.Exceptions.TerminatedSessionError) { + // PRACK never arrived, so we timed out waiting for it. + this.logger.warn("Incoming session terminated while waiting for PRACK."); + } + else if (error instanceof Exceptions_1.Exceptions.UnsupportedSessionDescriptionContentTypeError) { + statusCode = 415; + } + else if (error instanceof Exceptions_1.Exception) { + this.logger.error(error.message); + } + } + else if (error instanceof Error) { // Other Errors hould go uncaught. + this.logger.error(error.message); + } + else { + // We don't actually know what a session description handler implementation might throw + // our way, so as a last resort, just assume we are getting an "any" and log it. + this.logger.error("An error occurred in the session description handler."); + this.logger.error(error); + } + try { + this.incomingRequest.reject({ statusCode: statusCode }); // "Temporarily Unavailable" + this.failed(this.incomingRequest.message, error.message); + this.terminated(this.incomingRequest.message, error.message); + } + catch (error) { + return; + } + }; + InviteServerContext.prototype.prackArrived = function () { + if (this.waitingForPrackResolve) { + this.waitingForPrackResolve(); + } + this.waitingForPrackPromise = undefined; + this.waitingForPrackResolve = undefined; + this.waitingForPrackReject = undefined; + }; + InviteServerContext.prototype.prackNeverArrived = function () { + if (this.waitingForPrackReject) { + this.waitingForPrackReject(new Exceptions_1.Exceptions.TerminatedSessionError()); + } + this.waitingForPrackPromise = undefined; + this.waitingForPrackResolve = undefined; + this.waitingForPrackReject = undefined; + }; + /** + * @throws {Exceptions.TerminatedSessionError} The session terminated before being accepted (i.e. cancel arrived). + */ + InviteServerContext.prototype.waitForArrivalOfPrack = function () { + var _this = this; + if (this.waitingForPrackPromise) { + throw new Error("Already waiting for PRACK"); + } + this.waitingForPrackPromise = new Promise(function (resolve, reject) { + _this.waitingForPrackResolve = resolve; + _this.waitingForPrackReject = reject; + }); + return this.waitingForPrackPromise; + }; + InviteServerContext.prototype.getOffer = function (options) { + this.hasOffer = true; + var sdh = this.getSessionDescriptionHandler(); + return sdh + .getDescription(options.sessionDescriptionHandlerOptions, options.modifiers) + .then(function (bodyObj) { return messages_1.fromBodyObj(bodyObj); }); + }; + InviteServerContext.prototype.setAnswer = function (answer, options) { + this.hasAnswer = true; + var sdh = this.getSessionDescriptionHandler(); + if (!sdh.hasDescription(answer.contentType)) { + return Promise.reject(new Exceptions_1.Exceptions.UnsupportedSessionDescriptionContentTypeError()); + } + return sdh + .setDescription(answer.content, options.sessionDescriptionHandlerOptions, options.modifiers); + }; + InviteServerContext.prototype.setOfferAndGetAnswer = function (offer, options) { + this.hasOffer = true; + this.hasAnswer = true; + var sdh = this.getSessionDescriptionHandler(); + if (!sdh.hasDescription(offer.contentType)) { + return Promise.reject(new Exceptions_1.Exceptions.UnsupportedSessionDescriptionContentTypeError()); + } + return sdh + .setDescription(offer.content, options.sessionDescriptionHandlerOptions, options.modifiers) + .then(function () { return sdh.getDescription(options.sessionDescriptionHandlerOptions, options.modifiers); }) + .then(function (bodyObj) { return messages_1.fromBodyObj(bodyObj); }); + }; + InviteServerContext.prototype.getSessionDescriptionHandler = function () { + // Create our session description handler if not already done so... + var sdh = this.sessionDescriptionHandler = this.setupSessionDescriptionHandler(); + // FIXME: Ported - this can get emitted multiple times even when only created once... don't we care? + this.emit("SessionDescriptionHandler-created", this.sessionDescriptionHandler); + // Return. + return sdh; + }; + return InviteServerContext; +}(Session)); +exports.InviteServerContext = InviteServerContext; +// tslint:disable-next-line:max-classes-per-file +var InviteClientContext = /** @class */ (function (_super) { + __extends(InviteClientContext, _super); + function InviteClientContext(ua, target, options, modifiers) { + if (options === void 0) { options = {}; } + if (modifiers === void 0) { modifiers = []; } + var _this = this; + if (!ua.configuration.sessionDescriptionHandlerFactory) { + ua.logger.warn("Can't build ISC without SDH Factory"); + throw new Error("ICC Constructor Failed"); + } + options.params = options.params || {}; + var anonymous = options.anonymous || false; + var fromTag = Utils_1.Utils.newTag(); + options.params.fromTag = fromTag; + /* Do not add ;ob in initial forming dialog requests if the registration over + * the current connection got a GRUU URI. + */ + var contact = ua.contact.toString({ + anonymous: anonymous, + outbound: anonymous ? !ua.contact.tempGruu : !ua.contact.pubGruu + }); + var extraHeaders = (options.extraHeaders || []).slice(); + if (anonymous && ua.configuration.uri) { + options.params.from_displayName = "Anonymous"; + options.params.from_uri = "sip:anonymous@anonymous.invalid"; + extraHeaders.push("P-Preferred-Identity: " + ua.configuration.uri.toString()); + extraHeaders.push("Privacy: id"); + } + extraHeaders.push("Contact: " + contact); + // this is UA.C.ALLOWED_METHODS, removed to get around circular dependency + extraHeaders.push("Allow: " + [ + "ACK", + "CANCEL", + "INVITE", + "MESSAGE", + "BYE", + "OPTIONS", + "INFO", + "NOTIFY", + "REFER" + ].toString()); + if (ua.configuration.rel100 === Constants_1.C.supported.REQUIRED) { + extraHeaders.push("Require: 100rel"); + } + if (ua.configuration.replaces === Constants_1.C.supported.REQUIRED) { + extraHeaders.push("Require: replaces"); + } + options.extraHeaders = extraHeaders; + _this = _super.call(this, ua.configuration.sessionDescriptionHandlerFactory) || this; + ClientContext_1.ClientContext.initializer(_this, ua, Constants_1.C.INVITE, target, options); + _this.earlyMediaSessionDescriptionHandlers = new Map(); + _this.type = Enums_1.TypeStrings.InviteClientContext; + _this.passedOptions = options; // Save for later to use with refer + _this.sessionDescriptionHandlerOptions = options.sessionDescriptionHandlerOptions || {}; + _this.modifiers = modifiers; + _this.inviteWithoutSdp = options.inviteWithoutSdp || false; + // Set anonymous property + _this.anonymous = options.anonymous || false; + // Custom data to be sent either in INVITE or in ACK + _this.renderbody = options.renderbody || undefined; + _this.rendertype = options.rendertype || "text/plain"; + // Session parameter initialization + _this.fromTag = fromTag; + _this.contact = contact; + // Check Session Status + if (_this.status !== Enums_1.SessionStatus.STATUS_NULL) { + throw new Exceptions_1.Exceptions.InvalidStateError(_this.status); + } + // OutgoingSession specific parameters + _this.isCanceled = false; + _this.received100 = false; + _this.method = Constants_1.C.INVITE; + _this.logger = ua.getLogger("sip.inviteclientcontext"); + ua.applicants[_this.toString()] = _this; + _this.id = _this.request.callId + _this.fromTag; + _this.onInfo = options.onInfo; + _this.errorListener = _this.onTransportError.bind(_this); + if (ua.transport) { + ua.transport.on("transportError", _this.errorListener); + } + return _this; + } + InviteClientContext.prototype.receiveResponse = function (response) { + throw new Error("Unimplemented."); + }; + // hack for getting around ClientContext interface + InviteClientContext.prototype.send = function () { + this.sendInvite(); + return this; + }; + InviteClientContext.prototype.invite = function () { + var _this = this; + // Save the session into the ua sessions collection. + // Note: placing in constructor breaks call to request.cancel on close... User does not need this anyway + this.ua.sessions[this.id] = this; + // This should allow the function to return so that listeners can be set up for these events + Promise.resolve().then(function () { + // FIXME: There is a race condition where cancel (or terminate) can be called synchronously after invite. + if (_this.isCanceled || _this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { + return; + } + if (_this.inviteWithoutSdp) { + // just send an invite with no sdp... + _this.request.body = _this.renderbody; + _this.status = Enums_1.SessionStatus.STATUS_INVITE_SENT; + _this.send(); + } + else { + // Initialize Media Session + _this.sessionDescriptionHandler = _this.sessionDescriptionHandlerFactory(_this, _this.ua.configuration.sessionDescriptionHandlerFactoryOptions || {}); + _this.emit("SessionDescriptionHandler-created", _this.sessionDescriptionHandler); + _this.sessionDescriptionHandler.getDescription(_this.sessionDescriptionHandlerOptions, _this.modifiers) + .then(function (description) { + // FIXME: There is a race condition where cancel (or terminate) can be called (a)synchronously after invite. + if (_this.isCanceled || _this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { + return; + } + _this.hasOffer = true; + _this.request.body = description; + _this.status = Enums_1.SessionStatus.STATUS_INVITE_SENT; + _this.send(); + }, function (err) { + if (err.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { + _this.logger.log(err.message); + if (err.error) { + _this.logger.log(err.error); + } + } + if (_this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { + return; + } + _this.failed(undefined, Constants_1.C.causes.WEBRTC_ERROR); + _this.terminated(undefined, Constants_1.C.causes.WEBRTC_ERROR); + }); + } + }); + return this; + }; + InviteClientContext.prototype.cancel = function (options) { + if (options === void 0) { options = {}; } + // Check Session Status + if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED || this.status === Enums_1.SessionStatus.STATUS_CONFIRMED) { + throw new Exceptions_1.Exceptions.InvalidStateError(this.status); + } + if (this.isCanceled) { + throw new Exceptions_1.Exceptions.InvalidStateError(Enums_1.SessionStatus.STATUS_CANCELED); + } + this.isCanceled = true; + this.logger.log("Canceling session"); + var cancelReason = Utils_1.Utils.getCancelReason(options.statusCode, options.reasonPhrase); + options.extraHeaders = (options.extraHeaders || []).slice(); + if (this.outgoingInviteRequest) { + this.logger.warn("Canceling session before it was created"); + this.outgoingInviteRequest.cancel(cancelReason, options); + } + return this.canceled(); + }; + InviteClientContext.prototype.terminate = function (options) { + if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { + return this; + } + if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK || this.status === Enums_1.SessionStatus.STATUS_CONFIRMED) { + this.bye(options); + } + else { + this.cancel(options); + } + return this; + }; + /** + * 13.2.1 Creating the Initial INVITE + * + * Since the initial INVITE represents a request outside of a dialog, + * its construction follows the procedures of Section 8.1.1. Additional + * processing is required for the specific case of INVITE. + * + * An Allow header field (Section 20.5) SHOULD be present in the INVITE. + * It indicates what methods can be invoked within a dialog, on the UA + * sending the INVITE, for the duration of the dialog. For example, a + * UA capable of receiving INFO requests within a dialog [34] SHOULD + * include an Allow header field listing the INFO method. + * + * A Supported header field (Section 20.37) SHOULD be present in the + * INVITE. It enumerates all the extensions understood by the UAC. + * + * An Accept (Section 20.1) header field MAY be present in the INVITE. + * It indicates which Content-Types are acceptable to the UA, in both + * the response received by it, and in any subsequent requests sent to + * it within dialogs established by the INVITE. The Accept header field + * is especially useful for indicating support of various session + * description formats. + * + * The UAC MAY add an Expires header field (Section 20.19) to limit the + * validity of the invitation. If the time indicated in the Expires + * header field is reached and no final answer for the INVITE has been + * received, the UAC core SHOULD generate a CANCEL request for the + * INVITE, as per Section 9. + * + * A UAC MAY also find it useful to add, among others, Subject (Section + * 20.36), Organization (Section 20.25) and User-Agent (Section 20.41) + * header fields. They all contain information related to the INVITE. + * + * The UAC MAY choose to add a message body to the INVITE. Section + * 8.1.1.10 deals with how to construct the header fields -- Content- + * Type among others -- needed to describe the message body. + * + * https://tools.ietf.org/html/rfc3261#section-13.2.1 + */ + InviteClientContext.prototype.sendInvite = function () { + // There are special rules for message bodies that contain a session + // description - their corresponding Content-Disposition is "session". + // SIP uses an offer/answer model where one UA sends a session + // description, called the offer, which contains a proposed description + // of the session. The offer indicates the desired communications means + // (audio, video, games), parameters of those means (such as codec + // types) and addresses for receiving media from the answerer. The + // other UA responds with another session description, called the + // answer, which indicates which communications means are accepted, the + // parameters that apply to those means, and addresses for receiving + // media from the offerer. An offer/answer exchange is within the + // context of a dialog, so that if a SIP INVITE results in multiple + // dialogs, each is a separate offer/answer exchange. The offer/answer + // model defines restrictions on when offers and answers can be made + // (for example, you cannot make a new offer while one is in progress). + // This results in restrictions on where the offers and answers can + // appear in SIP messages. In this specification, offers and answers + // can only appear in INVITE requests and responses, and ACK. The usage + // of offers and answers is further restricted. For the initial INVITE + // transaction, the rules are: + // + // o The initial offer MUST be in either an INVITE or, if not there, + // in the first reliable non-failure message from the UAS back to + // the UAC. In this specification, that is the final 2xx + // response. + // + // o If the initial offer is in an INVITE, the answer MUST be in a + // reliable non-failure message from UAS back to UAC which is + // correlated to that INVITE. For this specification, that is + // only the final 2xx response to that INVITE. That same exact + // answer MAY also be placed in any provisional responses sent + // prior to the answer. The UAC MUST treat the first session + // description it receives as the answer, and MUST ignore any + // session descriptions in subsequent responses to the initial + // INVITE. + // + // o If the initial offer is in the first reliable non-failure + // message from the UAS back to UAC, the answer MUST be in the + // acknowledgement for that message (in this specification, ACK + // for a 2xx response). + // + // o After having sent or received an answer to the first offer, the + // UAC MAY generate subsequent offers in requests based on rules + // specified for that method, but only if it has received answers + // to any previous offers, and has not sent any offers to which it + // hasn't gotten an answer. + // + // o Once the UAS has sent or received an answer to the initial + // offer, it MUST NOT generate subsequent offers in any responses + // to the initial INVITE. This means that a UAS based on this + // specification alone can never generate subsequent offers until + // completion of the initial transaction. + // + // https://tools.ietf.org/html/rfc3261#section-13.2.1 + var _this = this; + // 5 The Offer/Answer Model and PRACK + // + // RFC 3261 describes guidelines for the sets of messages in which + // offers and answers [3] can appear. Based on those guidelines, this + // extension provides additional opportunities for offer/answer + // exchanges. + // If the INVITE contained an offer, the UAS MAY generate an answer in a + // reliable provisional response (assuming these are supported by the + // UAC). That results in the establishment of the session before + // completion of the call. Similarly, if a reliable provisional + // response is the first reliable message sent back to the UAC, and the + // INVITE did not contain an offer, one MUST appear in that reliable + // provisional response. + // If the UAC receives a reliable provisional response with an offer + // (this would occur if the UAC sent an INVITE without an offer, in + // which case the first reliable provisional response will contain the + // offer), it MUST generate an answer in the PRACK. If the UAC receives + // a reliable provisional response with an answer, it MAY generate an + // additional offer in the PRACK. If the UAS receives a PRACK with an + // offer, it MUST place the answer in the 2xx to the PRACK. + // Once an answer has been sent or received, the UA SHOULD establish the + // session based on the parameters of the offer and answer, even if the + // original INVITE itself has not been responded to. + // If the UAS had placed a session description in any reliable + // provisional response that is unacknowledged when the INVITE is + // accepted, the UAS MUST delay sending the 2xx until the provisional + // response is acknowledged. Otherwise, the reliability of the 1xx + // cannot be guaranteed, and reliability is needed for proper operation + // of the offer/answer exchange. + // All user agents that support this extension MUST support all + // offer/answer exchanges that are possible based on the rules in + // Section 13.2 of RFC 3261, based on the existence of INVITE and PRACK + // as requests, and 2xx and reliable 1xx as non-failure reliable + // responses. + // + // https://tools.ietf.org/html/rfc3262#section-5 + //// + // The Offer/Answer Model Implementation + // + // The offer/answer model is straight forward, but one MUST READ the specifications... + // + // 13.2.1 Creating the Initial INVITE (paragraph 8 in particular) + // https://tools.ietf.org/html/rfc3261#section-13.2.1 + // + // 5 The Offer/Answer Model and PRACK + // https://tools.ietf.org/html/rfc3262#section-5 + // + // Session Initiation Protocol (SIP) Usage of the Offer/Answer Model + // https://tools.ietf.org/html/rfc6337 + // + // *** IMPORTANT IMPLEMENTATION CHOICES *** + // + // TLDR... + // + // 1) Only one offer/answer exchange permitted during initial INVITE. + // 2) No "early media" if the initial offer is in an INVITE. + // + // + // 1) Initial Offer/Answer Restriction. + // + // Our implementation replaces the following bullet point... + // + // o After having sent or received an answer to the first offer, the + // UAC MAY generate subsequent offers in requests based on rules + // specified for that method, but only if it has received answers + // to any previous offers, and has not sent any offers to which it + // hasn't gotten an answer. + // https://tools.ietf.org/html/rfc3261#section-13.2.1 + // + // ...with... + // + // o After having sent or received an answer to the first offer, the + // UAC MUST NOT generate subsequent offers in requests based on rules + // specified for that method. + // + // ...which in combination with this bullet point... + // + // o Once the UAS has sent or received an answer to the initial + // offer, it MUST NOT generate subsequent offers in any responses + // to the initial INVITE. This means that a UAS based on this + // specification alone can never generate subsequent offers until + // completion of the initial transaction. + // https://tools.ietf.org/html/rfc3261#section-13.2.1 + // + // ...ensures that EXACTLY ONE offer/answer exchange will occur + // during an initial out of dialog INVITE request made by our UAC. + // + // + // 2) Early Media Restriction. + // + // While our implementation adheres to the following bullet point... + // + // o If the initial offer is in an INVITE, the answer MUST be in a + // reliable non-failure message from UAS back to UAC which is + // correlated to that INVITE. For this specification, that is + // only the final 2xx response to that INVITE. That same exact + // answer MAY also be placed in any provisional responses sent + // prior to the answer. The UAC MUST treat the first session + // description it receives as the answer, and MUST ignore any + // session descriptions in subsequent responses to the initial + // INVITE. + // https://tools.ietf.org/html/rfc3261#section-13.2.1 + // + // We have made the following implementation decision with regard to early media... + // + // o If the initial offer is in the INVITE, the answer from the + // UAS back to the UAC will establish a media session only + // only after the final 2xx response to that INVITE is received. + // + // The reason for this decision is rooted in a restriction currently + // inherent in WebRTC. Specifically, while a SIP INVITE request with an + // initial offer may fork resulting in more than one provisional answer, + // there is currently no easy/good way to to "fork" an offer generated + // by a peer connection. In particular, a WebRTC offer currently may only + // be matched with one answer and we have no good way to know which + // "provisional answer" is going to be the "final answer". So we have + // decided to punt and not create any "early media" sessions in this case. + // + // The upshot is that if you want "early media", you must not put the + // initial offer in the INVITE. Instead, force the UAS to provide the + // initial offer by sending an INVITE without an offer. In the WebRTC + // case this allows us to create a unique peer connection with a unique + // answer for every provisional offer with "early media" on all of them. + //// + //// + // ROADMAP: The Offer/Answer Model Implementation + // + // The "no early media if offer in INVITE" implementation is not a + // welcome one. The masses want it. The want it and they want it + // to work for WebRTC (so they want to have their cake and eat too). + // + // So while we currently cannot make the offer in INVITE+forking+webrtc + // case work, we decided to do the following... + // + // 1) modify SDH Factory to provide an initial offer without giving us the SDH, and then... + // 2) stick that offer in the initial INVITE, and when 183 with initial answer is received... + // 3) ask SDH Factory if it supports "earlyRemoteAnswer" + // a) if true, ask SDH Factory to createSDH(localOffer).then((sdh) => sdh.setDescription(remoteAnswer) + // b) if false, defer getting a SDH until 2xx response is received + // + // Our supplied WebRTC SDH will default to behavior 3b which works in forking environment (without) + // early media if initial offer is in the INVITE). We will, however, provide an "inviteWillNotFork" + // option which if set to "true" will have our supplied WebRTC SDH behave in the 3a manner. + // That will result in + // - early media working with initial offer in the INVITE, and... + // - if the INVITE forks, the session terminating with an ERROR that reads like + // "You set 'inviteWillNotFork' to true but the INVITE forked. You can't eat your cake, and have it too." + // - furthermore, we accept that users will report that error to us as "bug" regardless + // + // So, SDH Factory is going to end up with a new interface along the lines of... + // + // interface SessionDescriptionHandlerFactory { + // makeLocalOffer(): Promise; + // makeSessionDescriptionHandler( + // initialOffer: ContentTypeAndBody, offerType: "local" | "remote" + // ): Promise; + // supportsEarlyRemoteAnswer: boolean; + // supportsContentType(contentType: string): boolean; + // getDescription(description: ContentTypeAndBody): Promise + // setDescription(description: ContentTypeAndBody): Promise + // } + // + // We should be able to get rid of all the hasOffer/hasAnswer tracking code and otherwise code + // it up to the same interaction with the SDH Factory and SDH regardless of signaling scenario. + //// + // Send the INVITE request. + this.outgoingInviteRequest = this.ua.userAgentCore.invite(this.request, { + onAccept: function (inviteResponse) { return _this.onAccept(inviteResponse); }, + onProgress: function (inviteResponse) { return _this.onProgress(inviteResponse); }, + onRedirect: function (inviteResponse) { return _this.onRedirect(inviteResponse); }, + onReject: function (inviteResponse) { return _this.onReject(inviteResponse); }, + onTrying: function (inviteResponse) { return _this.onTrying(inviteResponse); } + }); + }; + InviteClientContext.prototype.ackAndBye = function (inviteResponse, session, statusCode, reasonPhrase) { + if (!this.ua.userAgentCore) { + throw new Error("Method requires user agent core."); + } + var extraHeaders = []; + if (statusCode) { + extraHeaders.push("Reason: " + Utils_1.Utils.getReasonHeaderValue(statusCode, reasonPhrase)); + } + var outgoingAckRequest = inviteResponse.ack(); + this.emit("ack", outgoingAckRequest.message); + var outgoingByeRequest = session.bye(undefined, { extraHeaders: extraHeaders }); + this.emit("bye", outgoingByeRequest.message); + }; + InviteClientContext.prototype.disposeEarlyMedia = function () { + if (!this.earlyMediaSessionDescriptionHandlers) { + throw new Error("Early media session description handlers undefined."); + } + this.earlyMediaSessionDescriptionHandlers.forEach(function (sessionDescriptionHandler) { + sessionDescriptionHandler.close(); + }); + }; + /** + * Handle final response to initial INVITE. + * @param inviteResponse 2xx response. + */ + InviteClientContext.prototype.onAccept = function (inviteResponse) { + var _this = this; + if (!this.earlyMediaSessionDescriptionHandlers) { + throw new Error("Early media session description handlers undefined."); + } + var response = inviteResponse.message; + var session = inviteResponse.session; + // Our transaction layer is "non-standard" in that it will only + // pass us a 2xx response once per branch, so there is no need to + // worry about dealing with 2xx retransmissions. However, we can + // and do still get 2xx responses for multiple branches (when an + // INVITE is forked) which may create multiple confirmed dialogs. + // Herein we are acking and sending a bye to any confirmed dialogs + // which arrive beyond the first one. This is the desired behavior + // for most applications (but certainly not all). + // If we already received a confirmed dialog, ack & bye this session. + if (this.session) { + this.ackAndBye(inviteResponse, session); + return; + } + // If the user requested cancellation, ack & bye this session. + if (this.isCanceled) { + this.ackAndBye(inviteResponse, session); + this.emit("bye", this.request); // FIXME: Ported this odd second "bye" emit + return; + } + // Ported behavior. + if (response.hasHeader("P-Asserted-Identity")) { + this.assertedIdentity = Grammar_1.Grammar.nameAddrHeaderParse(response.getHeader("P-Asserted-Identity")); + } + // We have a confirmed dialog. + this.session = session; + this.session.delegate = { + onAck: function (ackRequest) { return _this.onAck(ackRequest); }, + onBye: function (byeRequest) { return _this.receiveRequest(byeRequest); }, + onInfo: function (infoRequest) { return _this.receiveRequest(infoRequest); }, + onInvite: function (inviteRequest) { return _this.receiveRequest(inviteRequest); }, + onNotify: function (notifyRequest) { return _this.receiveRequest(notifyRequest); }, + onPrack: function (prackRequest) { return _this.receiveRequest(prackRequest); }, + onRefer: function (referRequest) { return _this.receiveRequest(referRequest); } + }; + switch (session.signalingState) { + case session_1.SignalingState.Initial: + // INVITE without Offer, so MUST have Offer at this point, so invalid state. + this.ackAndBye(inviteResponse, session, 400, "Missing session description"); + this.failed(response, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); + break; + case session_1.SignalingState.HaveLocalOffer: + // INVITE with Offer, so MUST have Answer at this point, so invalid state. + this.ackAndBye(inviteResponse, session, 400, "Missing session description"); + this.failed(response, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); + break; + case session_1.SignalingState.HaveRemoteOffer: + // INVITE without Offer, received offer in 2xx, so MUST send Answer in ACK. + var sdh_1 = this.sessionDescriptionHandlerFactory(this, this.ua.configuration.sessionDescriptionHandlerFactoryOptions || {}); + this.sessionDescriptionHandler = sdh_1; + this.emit("SessionDescriptionHandler-created", this.sessionDescriptionHandler); + if (!sdh_1.hasDescription(response.getHeader("Content-Type") || "")) { + this.ackAndBye(inviteResponse, session, 400, "Missing session description"); + this.failed(response, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); + break; + } + this.hasOffer = true; + sdh_1 + .setDescription(response.body, this.sessionDescriptionHandlerOptions, this.modifiers) + .then(function () { return sdh_1.getDescription(_this.sessionDescriptionHandlerOptions, _this.modifiers); }) + .then(function (description) { + if (_this.isCanceled || _this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { + return; + } + _this.status = Enums_1.SessionStatus.STATUS_CONFIRMED; + _this.hasAnswer = true; + var body = { + contentDisposition: "session", contentType: description.contentType, content: description.body + }; + var ackRequest = inviteResponse.ack({ body: body }); + _this.emit("ack", ackRequest.message); + _this.accepted(response); + }) + .catch(function (e) { + if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { + _this.logger.warn("invalid description"); + _this.logger.warn(e.toString()); + // TODO: This message is inconsistent + _this.ackAndBye(inviteResponse, session, 488, "Invalid session description"); + _this.failed(response, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); + } + else { + throw e; + } + }); + break; + case session_1.SignalingState.Stable: + // This session has completed an initial offer/answer exchange... + var options_1; + if (this.renderbody && this.rendertype) { + options_1 = { body: { contentDisposition: "render", contentType: this.rendertype, content: this.renderbody } }; + } + // If INVITE with Offer and we have been waiting till now to apply the answer. + if (this.hasOffer && !this.hasAnswer) { + if (!this.sessionDescriptionHandler) { + throw new Error("Session description handler undefined."); + } + var answer = session.answer; + if (!answer) { + throw new Error("Answer is undefined."); + } + this.sessionDescriptionHandler + .setDescription(answer.content, this.sessionDescriptionHandlerOptions, this.modifiers) + .then(function () { + _this.hasAnswer = true; + _this.status = Enums_1.SessionStatus.STATUS_CONFIRMED; + var ackRequest = inviteResponse.ack(options_1); + _this.emit("ack", ackRequest.message); + _this.accepted(response); + }) + .catch(function (error) { + _this.logger.error(error); + _this.ackAndBye(inviteResponse, session, 488, "Not Acceptable Here"); + _this.failed(response, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); + // FIME: DON'T EAT UNHANDLED ERRORS! + }); + } + else { + // Otherwise INVITE with or without Offer and we have already completed the initial exchange. + this.sessionDescriptionHandler = this.earlyMediaSessionDescriptionHandlers.get(session.id); + if (!this.sessionDescriptionHandler) { + throw new Error("Session description handler undefined."); + } + this.earlyMediaSessionDescriptionHandlers.delete(session.id); + this.hasOffer = true; + this.hasAnswer = true; + this.status = Enums_1.SessionStatus.STATUS_CONFIRMED; + var ackRequest = inviteResponse.ack(); + this.emit("ack", ackRequest.message); + this.accepted(response); + } + break; + case session_1.SignalingState.Closed: + // Dialog has terminated. + break; + default: + throw new Error("Unknown session signaling state."); + } + this.disposeEarlyMedia(); + }; + /** + * Handle provisional response to initial INVITE. + * @param inviteResponse 1xx response. + */ + InviteClientContext.prototype.onProgress = function (inviteResponse) { + var _this = this; + // Ported - User requested cancellation. + if (this.isCanceled) { + return; + } + if (!this.outgoingInviteRequest) { + throw new Error("Outgoing INVITE request undefined."); + } + if (!this.earlyMediaSessionDescriptionHandlers) { + throw new Error("Early media session description handlers undefined."); + } + var response = inviteResponse.message; + var session = inviteResponse.session; + // Ported - Set status. + this.status = Enums_1.SessionStatus.STATUS_1XX_RECEIVED; + // Ported - Set assertedIdentity. + if (response.hasHeader("P-Asserted-Identity")) { + this.assertedIdentity = Grammar_1.Grammar.nameAddrHeaderParse(response.getHeader("P-Asserted-Identity")); + } + // The provisional response MUST establish a dialog if one is not yet created. + // https://tools.ietf.org/html/rfc3262#section-4 + if (!session) { + // A response with a to tag MUST create a session (should never get here). + throw new Error("Session undefined."); + } + // If a provisional response is received for an initial request, and + // that response contains a Require header field containing the option + // tag 100rel, the response is to be sent reliably. If the response is + // a 100 (Trying) (as opposed to 101 to 199), this option tag MUST be + // ignored, and the procedures below MUST NOT be used. + // https://tools.ietf.org/html/rfc3262#section-4 + var requireHeader = response.getHeader("require"); + var rseqHeader = response.getHeader("rseq"); + var rseq = requireHeader && requireHeader.includes("100rel") && rseqHeader ? Number(rseqHeader) : undefined; + var responseReliable = !!rseq; + var extraHeaders = []; + if (responseReliable) { + extraHeaders.push("RAck: " + response.getHeader("rseq") + " " + response.getHeader("cseq")); + } + // INVITE without Offer and session still has no offer (and no answer). + if (session.signalingState === session_1.SignalingState.Initial) { + // Similarly, if a reliable provisional + // response is the first reliable message sent back to the UAC, and the + // INVITE did not contain an offer, one MUST appear in that reliable + // provisional response. + // https://tools.ietf.org/html/rfc3262#section-5 + if (responseReliable) { + this.logger.warn("First reliable provisional response received MUST contain an offer when INVITE does not contain an offer."); + // FIXME: Known popular UA's currently end up here... + inviteResponse.prack({ extraHeaders: extraHeaders }); + } + this.emit("progress", response); + return; + } + // INVITE with Offer and session only has that initial local offer. + if (session.signalingState === session_1.SignalingState.HaveLocalOffer) { + if (responseReliable) { + inviteResponse.prack({ extraHeaders: extraHeaders }); + } + this.emit("progress", response); + return; + } + // INVITE without Offer and received initial offer in provisional response + if (session.signalingState === session_1.SignalingState.HaveRemoteOffer) { + // The initial offer MUST be in either an INVITE or, if not there, + // in the first reliable non-failure message from the UAS back to + // the UAC. + // https://tools.ietf.org/html/rfc3261#section-13.2.1 + // According to Section 13.2.1 of [RFC3261], 'The first reliable + // non-failure message' must have an offer if there is no offer in the + // INVITE request. This means that the User Agent (UA) that receives + // the INVITE request without an offer must include an offer in the + // first reliable response with 100rel extension. If no reliable + // provisional response has been sent, the User Agent Server (UAS) must + // include an offer when sending 2xx response. + // https://tools.ietf.org/html/rfc6337#section-2.2 + if (!responseReliable) { + this.logger.warn("Non-reliable provisional response MUST NOT contain an initial offer, discarding response."); + return; + } + // If the initial offer is in the first reliable non-failure + // message from the UAS back to UAC, the answer MUST be in the + // acknowledgement for that message + var sdh_2 = this.sessionDescriptionHandlerFactory(this, this.ua.configuration.sessionDescriptionHandlerFactoryOptions || {}); + this.emit("SessionDescriptionHandler-created", sdh_2); + this.earlyMediaSessionDescriptionHandlers.set(session.id, sdh_2); + sdh_2 + .setDescription(response.body, this.sessionDescriptionHandlerOptions, this.modifiers) + .then(function () { return sdh_2.getDescription(_this.sessionDescriptionHandlerOptions, _this.modifiers); }) + .then(function (description) { + var body = { + contentDisposition: "session", contentType: description.contentType, content: description.body + }; + inviteResponse.prack({ extraHeaders: extraHeaders, body: body }); + _this.status = Enums_1.SessionStatus.STATUS_EARLY_MEDIA; + _this.emit("progress", response); + }) + .catch(function (error) { + if (_this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { + return; + } + _this.failed(undefined, Constants_1.C.causes.WEBRTC_ERROR); + _this.terminated(undefined, Constants_1.C.causes.WEBRTC_ERROR); + }); + return; + } + // This session has completed an initial offer/answer exchange, so... + // - INVITE with SDP and this provisional response MAY be reliable + // - INVITE without SDP and this provisional response MAY be reliable + if (session.signalingState === session_1.SignalingState.Stable) { + if (responseReliable) { + inviteResponse.prack({ extraHeaders: extraHeaders }); + } + // Note: As documented, no early media if offer was in INVITE, so nothing to be done. + // FIXME: TODO: Add a flag/hack to allow early media in this case. There are people + // in non-forking environments (think straight to FreeSWITCH) who want + // early media on a 183. Not sure how to actually make it work, basically + // something like... + if (false) {} + this.emit("progress", response); + return; + } + }; + /** + * Handle final response to initial INVITE. + * @param inviteResponse 3xx response. + */ + InviteClientContext.prototype.onRedirect = function (inviteResponse) { + this.disposeEarlyMedia(); + var response = inviteResponse.message; + var statusCode = response.statusCode; + var cause = Utils_1.Utils.sipErrorCause(statusCode || 0); + this.rejected(response, cause); + this.failed(response, cause); + this.terminated(response, cause); + }; + /** + * Handle final response to initial INVITE. + * @param inviteResponse 4xx, 5xx, or 6xx response. + */ + InviteClientContext.prototype.onReject = function (inviteResponse) { + this.disposeEarlyMedia(); + var response = inviteResponse.message; + var statusCode = response.statusCode; + var cause = Utils_1.Utils.sipErrorCause(statusCode || 0); + this.rejected(response, cause); + this.failed(response, cause); + this.terminated(response, cause); + }; + /** + * Handle final response to initial INVITE. + * @param inviteResponse 100 response. + */ + InviteClientContext.prototype.onTrying = function (inviteResponse) { + this.received100 = true; + this.emit("progress", inviteResponse.message); + }; + return InviteClientContext; +}(Session)); +exports.InviteClientContext = InviteClientContext; + + +/***/ }), +/* 68 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +function __export(m) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; +} +Object.defineProperty(exports, "__esModule", { value: true }); +__export(__webpack_require__(69)); + + +/***/ }), +/* 69 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +/** + * Session state. + * https://tools.ietf.org/html/rfc3261#section-13 + */ +var SessionState; +(function (SessionState) { + SessionState["Initial"] = "Initial"; + SessionState["Early"] = "Early"; + SessionState["AckWait"] = "AckWait"; + SessionState["Confirmed"] = "Confirmed"; + SessionState["Terminated"] = "Terminated"; +})(SessionState = exports.SessionState || (exports.SessionState = {})); +/** + * Offer/Answer State + * + * Offer Answer RFC Ini Est Early + * ------------------------------------------------------------------- + * 1. INVITE Req. 2xx INVITE Resp. RFC 3261 Y Y N + * 2. 2xx INVITE Resp. ACK Req. RFC 3261 Y Y N + * 3. INVITE Req. 1xx-rel INVITE Resp. RFC 3262 Y Y N + * 4. 1xx-rel INVITE Resp. PRACK Req. RFC 3262 Y Y N + * 5. PRACK Req. 200 PRACK Resp. RFC 3262 N Y Y + * 6. UPDATE Req. 2xx UPDATE Resp. RFC 3311 N Y Y + * + * Table 1: Summary of SIP Usage of the Offer/Answer Model + * https://tools.ietf.org/html/rfc6337#section-2.2 + */ +var SignalingState; +(function (SignalingState) { + SignalingState["Initial"] = "Initial"; + SignalingState["HaveLocalOffer"] = "HaveLocalOffer"; + SignalingState["HaveRemoteOffer"] = "HaveRemoteOffer"; + SignalingState["Stable"] = "Stable"; + SignalingState["Closed"] = "Closed"; +})(SignalingState = exports.SignalingState || (exports.SignalingState = {})); + + +/***/ }), +/* 70 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var events_1 = __webpack_require__(2); +var Constants_1 = __webpack_require__(3); +var messages_1 = __webpack_require__(63); +var Enums_1 = __webpack_require__(5); +var Exceptions_1 = __webpack_require__(47); +var Utils_1 = __webpack_require__(11); +/** + * @class DTMF + * @param {SIP.Session} session + */ +var DTMF = /** @class */ (function (_super) { + __extends(DTMF, _super); + function DTMF(session, tone, options) { + if (options === void 0) { options = {}; } + var _this = _super.call(this) || this; + _this.C = { + MIN_DURATION: 70, + MAX_DURATION: 6000, + DEFAULT_DURATION: 100, + MIN_INTER_TONE_GAP: 50, + DEFAULT_INTER_TONE_GAP: 500 + }; + _this.type = Enums_1.TypeStrings.DTMF; + if (tone === undefined) { + throw new TypeError("Not enough arguments"); + } + _this.logger = session.ua.getLogger("sip.invitecontext.dtmf", session.id); + _this.owner = session; + // Check tone type + if (typeof tone === "string") { + tone = tone.toUpperCase(); + } + else if (typeof tone === "number") { + tone = tone.toString(); + } + else { + throw new TypeError("Invalid tone: " + tone); + } + // Check tone value + if (!tone.match(/^[0-9A-D#*]$/)) { + throw new TypeError("Invalid tone: " + tone); + } + else { + _this.tone = tone; + } + var duration = options.duration; + var interToneGap = options.interToneGap; + // Check duration + if (duration && !Utils_1.Utils.isDecimal(duration)) { + throw new TypeError("Invalid tone duration: " + duration); + } + else if (!duration) { + duration = _this.C.DEFAULT_DURATION; + } + else if (duration < _this.C.MIN_DURATION) { + _this.logger.warn("'duration' value is lower than the minimum allowed, setting it to " + + _this.C.MIN_DURATION + " milliseconds"); + duration = _this.C.MIN_DURATION; + } + else if (duration > _this.C.MAX_DURATION) { + _this.logger.warn("'duration' value is greater than the maximum allowed, setting it to " + + _this.C.MAX_DURATION + " milliseconds"); + duration = _this.C.MAX_DURATION; + } + else { + duration = Math.abs(duration); + } + _this.duration = duration; + // Check interToneGap + if (interToneGap && !Utils_1.Utils.isDecimal(interToneGap)) { + throw new TypeError("Invalid interToneGap: " + interToneGap); + } + else if (!interToneGap) { + interToneGap = _this.C.DEFAULT_INTER_TONE_GAP; + } + else if (interToneGap < _this.C.MIN_INTER_TONE_GAP) { + _this.logger.warn("'interToneGap' value is lower than the minimum allowed, setting it to " + + _this.C.MIN_INTER_TONE_GAP + " milliseconds"); + interToneGap = _this.C.MIN_INTER_TONE_GAP; + } + else { + interToneGap = Math.abs(interToneGap); + } + _this.interToneGap = interToneGap; + return _this; + } + DTMF.prototype.send = function (options) { + if (options === void 0) { options = {}; } + // Check RTCSession Status + if (this.owner.status !== Enums_1.SessionStatus.STATUS_CONFIRMED && + this.owner.status !== Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK) { + throw new Exceptions_1.Exceptions.InvalidStateError(this.owner.status); + } + // Get DTMF options + var extraHeaders = options.extraHeaders ? options.extraHeaders.slice() : []; + var body = { + contentType: "application/dtmf-relay", + body: "Signal= " + this.tone + "\r\nDuration= " + this.duration + }; + if (this.owner.session) { + var request = this.owner.session.info(undefined, { + extraHeaders: extraHeaders, + body: messages_1.fromBodyObj(body) + }); + this.owner.emit("dtmf", request.message, this); + return; + } + }; + DTMF.prototype.init_incoming = function (request) { + request.accept(); + if (!this.tone || !this.duration) { + this.logger.warn("invalid INFO DTMF received, discarded"); + } + else { + this.owner.emit("dtmf", request.message, this); + } + }; + DTMF.prototype.receiveResponse = function (response) { + var statusCode = response && response.statusCode ? response.statusCode : 0; + switch (true) { + case /^1[0-9]{2}$/.test(statusCode.toString()): + // Ignore provisional responses. + break; + case /^2[0-9]{2}$/.test(statusCode.toString()): + this.emit("succeeded", { + originator: "remote", + response: response + }); + break; + default: + var cause = Utils_1.Utils.sipErrorCause(statusCode); + this.emit("failed", response, cause); + break; + } + }; + DTMF.prototype.onRequestTimeout = function () { + this.emit("failed", undefined, Constants_1.C.causes.REQUEST_TIMEOUT); + this.owner.onRequestTimeout(); + }; + DTMF.prototype.onTransportError = function () { + this.emit("failed", undefined, Constants_1.C.causes.CONNECTION_ERROR); + this.owner.onTransportError(); + }; + DTMF.prototype.onDialogError = function (response) { + this.emit("failed", response, Constants_1.C.causes.DIALOG_ERROR); + this.owner.onDialogError(response); + }; + return DTMF; +}(events_1.EventEmitter)); +exports.DTMF = DTMF; + + +/***/ }), +/* 71 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var events_1 = __webpack_require__(2); +var Constants_1 = __webpack_require__(3); +var messages_1 = __webpack_require__(63); +var subscription_1 = __webpack_require__(72); +var allowed_methods_1 = __webpack_require__(74); +var Enums_1 = __webpack_require__(5); +var Utils_1 = __webpack_require__(11); +/** + * While this class is named `Subscription`, it is closer to + * an implementation of a "subscriber" as defined in RFC 6665 + * "SIP-Specific Event Notifications". + * https://tools.ietf.org/html/rfc6665 + * @class Class creating a SIP Subscriber. + */ +var Subscription = /** @class */ (function (_super) { + __extends(Subscription, _super); + /** + * Constructor. + * @param ua User agent. + * @param target Subscription target. + * @param event Subscription event. + * @param options Options bucket. + */ + function Subscription(ua, target, event, options) { + if (options === void 0) { options = {}; } + var _this = _super.call(this) || this; + _this.data = {}; + _this.method = Constants_1.C.SUBSCRIBE; + _this.body = undefined; + // ClientContext interface + _this.type = Enums_1.TypeStrings.Subscription; + _this.ua = ua; + _this.logger = ua.getLogger("sip.subscription"); + if (options.body) { + _this.body = { + body: options.body, + contentType: options.contentType ? options.contentType : "application/sdp" + }; + } + // Target URI + var uri = ua.normalizeTarget(target); + if (!uri) { + throw new TypeError("Invalid target: " + target); + } + _this.uri = uri; + // Subscription event + _this.event = event; + // Subscription expires + if (options.expires === undefined) { + _this.expires = 3600; + } + else if (typeof options.expires !== "number") { // pre-typescript type guard + ua.logger.warn("Option \"expires\" must be a number. Using default of 3600."); + _this.expires = 3600; + } + else { + _this.expires = options.expires; + } + // Subscription extra headers + _this.extraHeaders = (options.extraHeaders || []).slice(); + // Subscription context. + _this.context = _this.initContext(); + _this.disposed = false; + // ClientContext interface + _this.request = _this.context.message; + if (!_this.request.from) { + throw new Error("From undefined."); + } + if (!_this.request.to) { + throw new Error("From undefined."); + } + _this.localIdentity = _this.request.from; + _this.remoteIdentity = _this.request.to; + return _this; + } + /** + * Destructor. + */ + Subscription.prototype.dispose = function () { + if (this.disposed) { + return; + } + if (this.retryAfterTimer) { + clearTimeout(this.retryAfterTimer); + this.retryAfterTimer = undefined; + } + this.context.dispose(); + this.disposed = true; + }; + Subscription.prototype.on = function (name, callback) { + return _super.prototype.on.call(this, name, callback); + }; + Subscription.prototype.emit = function (event) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + return _super.prototype.emit.apply(this, [event].concat(args)); + }; + /** + * Gracefully terminate. + */ + Subscription.prototype.close = function () { + if (this.disposed) { + return; + } + this.dispose(); + switch (this.context.state) { + case subscription_1.SubscriptionState.Initial: + this.onTerminated(); + break; + case subscription_1.SubscriptionState.NotifyWait: + this.onTerminated(); + break; + case subscription_1.SubscriptionState.Pending: + this.unsubscribe(); + break; + case subscription_1.SubscriptionState.Active: + this.unsubscribe(); + break; + case subscription_1.SubscriptionState.Terminated: + this.onTerminated(); + break; + default: + break; + } + }; + /** + * Send a re-SUBSCRIBE request if there is an "active" subscription. + */ + Subscription.prototype.refresh = function () { + var _this = this; + switch (this.context.state) { + case subscription_1.SubscriptionState.Initial: + break; + case subscription_1.SubscriptionState.NotifyWait: + break; + case subscription_1.SubscriptionState.Pending: + break; + case subscription_1.SubscriptionState.Active: + if (this.subscription) { + var request = this.subscription.refresh(); + request.delegate = { + onAccept: (function (response) { return _this.onAccepted(response); }), + onRedirect: (function (response) { return _this.onFailed(response); }), + onReject: (function (response) { return _this.onFailed(response); }), + }; + } + break; + case subscription_1.SubscriptionState.Terminated: + break; + default: + break; + } + }; + /** + * Send an initial SUBSCRIBE request if no subscription. + * Send a re-SUBSCRIBE request if there is an "active" subscription. + */ + Subscription.prototype.subscribe = function () { + var _this = this; + switch (this.context.state) { + case subscription_1.SubscriptionState.Initial: + this.context.subscribe().then(function (result) { + if (result.success) { + if (result.success.subscription) { + _this.subscription = result.success.subscription; + _this.subscription.delegate = { + onNotify: function (request) { return _this.onNotify(request); }, + onRefresh: function (request) { return _this.onRefresh(request); }, + onTerminated: function () { return _this.close(); } + }; + } + _this.onNotify(result.success.request); + } + else if (result.failure) { + _this.onFailed(result.failure.response); + } + }); + break; + case subscription_1.SubscriptionState.NotifyWait: + break; + case subscription_1.SubscriptionState.Pending: + break; + case subscription_1.SubscriptionState.Active: + this.refresh(); + break; + case subscription_1.SubscriptionState.Terminated: + break; + default: + break; + } + return this; + }; + /** + * Send a re-SUBSCRIBE request if there is a "pending" or "active" subscription. + */ + Subscription.prototype.unsubscribe = function () { + this.dispose(); + switch (this.context.state) { + case subscription_1.SubscriptionState.Initial: + break; + case subscription_1.SubscriptionState.NotifyWait: + break; + case subscription_1.SubscriptionState.Pending: + if (this.subscription) { + this.subscription.unsubscribe(); + // responses intentionally ignored + } + break; + case subscription_1.SubscriptionState.Active: + if (this.subscription) { + this.subscription.unsubscribe(); + // responses intentionally ignored + } + break; + case subscription_1.SubscriptionState.Terminated: + break; + default: + break; + } + this.onTerminated(); + }; + Subscription.prototype.onAccepted = function (response) { + var statusCode = response.message.statusCode ? response.message.statusCode : 0; + var cause = Utils_1.Utils.getReasonPhrase(statusCode); + this.emit("accepted", response.message, cause); + }; + Subscription.prototype.onFailed = function (response) { + this.close(); + if (response) { + var statusCode = response.message.statusCode ? response.message.statusCode : 0; + var cause = Utils_1.Utils.getReasonPhrase(statusCode); + this.emit("failed", response.message, cause); + this.emit("rejected", response.message, cause); + } + }; + Subscription.prototype.onNotify = function (request) { + var _this = this; + request.accept(); // Send 200 response. + this.emit("notify", { request: request.message }); + // If we've set state to done, no further processing should take place + // and we are only interested in cleaning up after the appropriate NOTIFY. + if (this.disposed) { + return; + } + // If the "Subscription-State" value is "terminated", the subscriber + // MUST consider the subscription terminated. The "expires" parameter + // has no semantics for "terminated" -- notifiers SHOULD NOT include an + // "expires" parameter on a "Subscription-State" header field with a + // value of "terminated", and subscribers MUST ignore any such + // parameter, if present. If a reason code is present, the client + // should behave as described below. If no reason code or an unknown + // reason code is present, the client MAY attempt to re-subscribe at any + // time (unless a "retry-after" parameter is present, in which case the + // client SHOULD NOT attempt re-subscription until after the number of + // seconds specified by the "retry-after" parameter). The reason codes + // defined by this document are: + // https://tools.ietf.org/html/rfc6665#section-4.1.3 + var subscriptionState = request.message.parseHeader("Subscription-State"); + if (subscriptionState && subscriptionState.state) { + switch (subscriptionState.state) { + case "terminated": + if (subscriptionState.reason) { + this.logger.log("Terminated subscription with reason " + subscriptionState.reason); + switch (subscriptionState.reason) { + case "deactivated": + case "timeout": + this.initContext(); + this.subscribe(); + return; + case "probation": + case "giveup": + this.initContext(); + if (subscriptionState.params && subscriptionState.params["retry-after"]) { + this.retryAfterTimer = setTimeout(function () { return _this.subscribe(); }, subscriptionState.params["retry-after"]); + } + else { + this.subscribe(); + } + return; + case "rejected": + case "noresource": + case "invariant": + break; + } + } + this.close(); + break; + default: + break; + } + } + }; + Subscription.prototype.onRefresh = function (request) { + var _this = this; + request.delegate = { + onAccept: function (response) { return _this.onAccepted(response); } + }; + }; + Subscription.prototype.onTerminated = function () { + this.emit("terminated"); + }; + Subscription.prototype.initContext = function () { + var _this = this; + var options = { + extraHeaders: this.extraHeaders, + body: this.body ? messages_1.fromBodyObj(this.body) : undefined + }; + this.context = new SubscribeClientContext(this.ua.userAgentCore, this.uri, this.event, this.expires, options); + this.context.delegate = { + onAccept: (function (response) { return _this.onAccepted(response); }) + }; + return this.context; + }; + return Subscription; +}(events_1.EventEmitter)); +exports.Subscription = Subscription; +// tslint:disable-next-line:max-classes-per-file +var SubscribeClientContext = /** @class */ (function () { + function SubscribeClientContext(core, target, event, expires, options, delegate) { + this.core = core; + this.target = target; + this.event = event; + this.expires = expires; + this.subscribed = false; + this.logger = core.loggerFactory.getLogger("sip.subscription"); + this.delegate = delegate; + var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); + var extraHeaders = (options && options.extraHeaders || []).slice(); + extraHeaders.push(allowHeader); + extraHeaders.push("Event: " + this.event); + extraHeaders.push("Expires: " + this.expires); + extraHeaders.push("Contact: " + this.core.configuration.contact.toString()); + var body = options && options.body ? messages_1.toBodyObj(options.body) : undefined; + this.message = this.core.configuration.outgoingRequestMessageFactory(Constants_1.C.SUBSCRIBE, this.target, {}, extraHeaders, body); + } + /** Destructor. */ + SubscribeClientContext.prototype.dispose = function () { + if (this.subscription) { + this.subscription.dispose(); + } + if (this.request) { + this.request.waitNotifyStop(); + this.request.dispose(); + } + }; + Object.defineProperty(SubscribeClientContext.prototype, "state", { + /** Subscription state. */ + get: function () { + if (this.subscription) { + return this.subscription.subscriptionState; + } + else if (this.subscribed) { + return subscription_1.SubscriptionState.NotifyWait; + } + else { + return subscription_1.SubscriptionState.Initial; + } + }, + enumerable: true, + configurable: true + }); + /** + * Establish subscription. + * @param options Options bucket. + */ + SubscribeClientContext.prototype.subscribe = function () { + var _this = this; + if (this.subscribed) { + return Promise.reject(new Error("Not in initial state. Did you call subscribe more than once?")); + } + this.subscribed = true; + return new Promise(function (resolve, reject) { + if (!_this.message) { + throw new Error("Message undefined."); + } + _this.request = _this.core.subscribe(_this.message, { + // This SUBSCRIBE request will be confirmed with a final response. + // 200-class responses indicate that the subscription has been accepted + // and that a NOTIFY request will be sent immediately. + // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 + onAccept: function (response) { + if (_this.delegate && _this.delegate.onAccept) { + _this.delegate.onAccept(response); + } + }, + // Due to the potential for out-of-order messages, packet loss, and + // forking, the subscriber MUST be prepared to receive NOTIFY requests + // before the SUBSCRIBE transaction has completed. + // https://tools.ietf.org/html/rfc6665#section-4.1.2.4 + onNotify: function (requestWithSubscription) { + _this.subscription = requestWithSubscription.subscription; + if (_this.subscription) { + _this.subscription.autoRefresh = true; + } + resolve({ success: requestWithSubscription }); + }, + // If this Timer N expires prior to the receipt of a NOTIFY request, + // the subscriber considers the subscription failed, and cleans up + // any state associated with the subscription attempt. + // https://tools.ietf.org/html/rfc6665#section-4.1.2.4 + onNotifyTimeout: function () { + resolve({ failure: {} }); + }, + // This SUBSCRIBE request will be confirmed with a final response. + // Non-200-class final responses indicate that no subscription or new + // dialog usage has been created, and no subsequent NOTIFY request will + // be sent. + // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 + onRedirect: function (response) { + resolve({ failure: { response: response } }); + }, + // This SUBSCRIBE request will be confirmed with a final response. + // Non-200-class final responses indicate that no subscription or new + // dialog usage has been created, and no subsequent NOTIFY request will + // be sent. + // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 + onReject: function (response) { + resolve({ failure: { response: response } }); + } + }); + }); + }; + return SubscribeClientContext; +}()); + + +/***/ }), +/* 72 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +function __export(m) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; +} +Object.defineProperty(exports, "__esModule", { value: true }); +__export(__webpack_require__(73)); + + +/***/ }), +/* 73 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +/** + * Subscription state. + * https://tools.ietf.org/html/rfc6665#section-4.1.2 + */ +var SubscriptionState; +(function (SubscriptionState) { + SubscriptionState["Initial"] = "Initial"; + SubscriptionState["NotifyWait"] = "NotifyWait"; + SubscriptionState["Pending"] = "Pending"; + SubscriptionState["Active"] = "Active"; + SubscriptionState["Terminated"] = "Terminated"; +})(SubscriptionState = exports.SubscriptionState || (exports.SubscriptionState = {})); + + +/***/ }), +/* 74 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +var Constants_1 = __webpack_require__(3); +/** + * FIXME: TODO: Should be configurable/variable. + */ +exports.AllowedMethods = [ + Constants_1.C.ACK, + Constants_1.C.BYE, + Constants_1.C.CANCEL, + Constants_1.C.INFO, + Constants_1.C.INVITE, + Constants_1.C.MESSAGE, + Constants_1.C.NOTIFY, + Constants_1.C.OPTIONS, + Constants_1.C.PRACK, + Constants_1.C.REFER, + Constants_1.C.SUBSCRIBE +]; + + +/***/ }), +/* 75 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var events_1 = __webpack_require__(2); +var Enums_1 = __webpack_require__(5); +/* Transport + * @class Abstract transport layer parent class + * @param {Logger} logger + * @param {Object} [options] + */ +var Transport = /** @class */ (function (_super) { + __extends(Transport, _super); + function Transport(logger, options) { + var _this = _super.call(this) || this; + _this.type = Enums_1.TypeStrings.Transport; + _this.logger = logger; + return _this; + } + /** + * Returns the promise designated by the child layer then emits a connected event. + * Automatically emits an event upon resolution, unless overrideEvent is set. If you + * override the event in this fashion, you should emit it in your implementation of connectPromise + * @param {Object} [options] + * @returns {Promise} + */ + Transport.prototype.connect = function (options) { + var _this = this; + if (options === void 0) { options = {}; } + return this.connectPromise(options).then(function (data) { + if (!data.overrideEvent) { + _this.emit("connected"); + } + }); + }; + /** + * Sends a message then emits a 'messageSent' event. Automatically emits an + * event upon resolution, unless data.overrideEvent is set. If you override + * the event in this fashion, you should emit it in your implementation of sendPromise + * @param {String} msg + * @param {Object} options + * @returns {Promise} + */ + Transport.prototype.send = function (msg, options) { + var _this = this; + if (options === void 0) { options = {}; } + return this.sendPromise(msg).then(function (data) { + if (!data.overrideEvent) { + _this.emit("messageSent", data.msg); + } + }); + }; + /** + * Returns the promise designated by the child layer then emits a + * disconnected event. Automatically emits an event upon resolution, + * unless overrideEvent is set. If you override the event in this fashion, + * you should emit it in your implementation of disconnectPromise + * @param {Object} [options] + * @returns {Promise} + */ + Transport.prototype.disconnect = function (options) { + var _this = this; + if (options === void 0) { options = {}; } + return this.disconnectPromise(options).then(function (data) { + if (!data.overrideEvent) { + _this.emit("disconnected"); + } + }); + }; + Transport.prototype.afterConnected = function (callback) { + if (this.isConnected()) { + callback(); + } + else { + this.once("connected", callback); + } + }; + /** + * Returns a promise which resolves once the UA is connected. DEPRECATION WARNING: just use afterConnected() + * @returns {Promise} + */ + Transport.prototype.waitForConnected = function () { + var _this = this; + // tslint:disable-next-line:no-console + console.warn("DEPRECATION WARNING Transport.waitForConnected(): use afterConnected() instead"); + return new Promise(function (resolve) { + _this.afterConnected(resolve); + }); + }; + return Transport; +}(events_1.EventEmitter)); +exports.Transport = Transport; + + +/***/ }), +/* 76 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(global) { +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var events_1 = __webpack_require__(2); +var ClientContext_1 = __webpack_require__(1); +var Constants_1 = __webpack_require__(3); +var user_agent_core_1 = __webpack_require__(78); +var DigestAuthentication_1 = __webpack_require__(12); +var Enums_1 = __webpack_require__(5); +var Exceptions_1 = __webpack_require__(47); +var Grammar_1 = __webpack_require__(7); +var LoggerFactory_1 = __webpack_require__(48); +var Parser_1 = __webpack_require__(49); +var PublishContext_1 = __webpack_require__(50); +var ReferContext_1 = __webpack_require__(51); +var RegisterContext_1 = __webpack_require__(66); +var ServerContext_1 = __webpack_require__(62); +var Session_1 = __webpack_require__(67); +var SIPMessage_1 = __webpack_require__(6); +var Subscription_1 = __webpack_require__(71); +var URI_1 = __webpack_require__(10); +var Utils_1 = __webpack_require__(11); +var SessionDescriptionHandler_1 = __webpack_require__(111); +var Transport_1 = __webpack_require__(114); +var environment = global.window || global; +/** + * @class Class creating a SIP User Agent. + * @param {function returning SIP.sessionDescriptionHandler} [configuration.sessionDescriptionHandlerFactory] + * A function will be invoked by each of the UA's Sessions to build the sessionDescriptionHandler for that Session. + * If no (or a falsy) value is provided, each Session will use a default (WebRTC) sessionDescriptionHandler. + */ +var UA = /** @class */ (function (_super) { + __extends(UA, _super); + function UA(configuration) { + var _this = _super.call(this) || this; + _this.type = Enums_1.TypeStrings.UA; + _this.log = new LoggerFactory_1.LoggerFactory(); + _this.logger = _this.getLogger("sip.ua"); + _this.configuration = {}; + // User actions outside any session/dialog (MESSAGE) + _this.applicants = {}; + _this.data = {}; + _this.sessions = {}; + _this.publishers = {}; + _this.status = Enums_1.UAStatus.STATUS_INIT; + /** + * Load configuration + * + * @throws {SIP.Exceptions.ConfigurationError} + * @throws {TypeError} + */ + if (configuration === undefined) { + configuration = {}; + } + else if (typeof configuration === "string" || configuration instanceof String) { + configuration = { + uri: configuration + }; + } + // Apply log configuration if present + if (configuration.log) { + if (configuration.log.hasOwnProperty("builtinEnabled")) { + _this.log.builtinEnabled = configuration.log.builtinEnabled; + } + if (configuration.log.hasOwnProperty("connector")) { + _this.log.connector = configuration.log.connector; + } + if (configuration.log.hasOwnProperty("level")) { + var level = configuration.log.level; + // const normalized: Levels = typeof level === "string" ? Levels[level] : level; + var normalized = void 0; + switch (level) { + case "error": + normalized = LoggerFactory_1.Levels.error; + break; + case "warn": + normalized = LoggerFactory_1.Levels.warn; + break; + case "log": + normalized = LoggerFactory_1.Levels.log; + break; + case "debug": + normalized = LoggerFactory_1.Levels.debug; + break; + default: + break; + } + // avoid setting level when invalid, use default level instead + if (normalized === undefined) { + _this.logger.error("Invalid \"level\" parameter value: " + JSON.stringify(level)); + } + else { + _this.log.level = normalized; + } + } + } + try { + _this.loadConfig(configuration); + } + catch (e) { + _this.status = Enums_1.UAStatus.STATUS_NOT_READY; + _this.error = UA.C.CONFIGURATION_ERROR; + throw e; + } + var userAgentCoreConfiguration = user_agent_core_1.makeUserAgentCoreConfigurationFromUA(_this); + // The Replaces header contains information used to match an existing + // SIP dialog (call-id, to-tag, and from-tag). Upon receiving an INVITE + // with a Replaces header, the User Agent (UA) attempts to match this + // information with a confirmed or early dialog. + // https://tools.ietf.org/html/rfc3891#section-3 + var handleInviteWithReplacesHeader = function (context, request) { + if (_this.configuration.replaces !== Constants_1.C.supported.UNSUPPORTED) { + var replaces = request.parseHeader("replaces"); + if (replaces) { + var targetSession = _this.sessions[replaces.call_id + replaces.replaces_from_tag] || + _this.sessions[replaces.call_id + replaces.replaces_to_tag] || + undefined; + if (!targetSession) { + _this.userAgentCore.replyStateless(request, { statusCode: 481 }); + return; + } + if (targetSession.status === Enums_1.SessionStatus.STATUS_TERMINATED) { + _this.userAgentCore.replyStateless(request, { statusCode: 603 }); + return; + } + var targetDialogId = replaces.call_id + replaces.replaces_to_tag + replaces.replaces_from_tag; + var targetDialog = _this.userAgentCore.dialogs.get(targetDialogId); + if (!targetDialog) { + _this.userAgentCore.replyStateless(request, { statusCode: 481 }); + return; + } + if (!targetDialog.early && replaces.early_only) { + _this.userAgentCore.replyStateless(request, { statusCode: 486 }); + return; + } + context.replacee = targetSession; + } + } + }; + var userAgentCoreDelegate = { + onInvite: function (incomingInviteRequest) { + // FIXME: Ported - 100 Trying send should be configurable. + // Only required if TU will not respond in 200ms. + // https://tools.ietf.org/html/rfc3261#section-17.2.1 + incomingInviteRequest.trying(); + incomingInviteRequest.delegate = { + onCancel: function (cancel) { + context.onCancel(cancel); + }, + onTransportError: function (error) { + context.onTransportError(); + } + }; + var context = new Session_1.InviteServerContext(_this, incomingInviteRequest); + // Ported - handling of out of dialog INVITE with Replaces. + handleInviteWithReplacesHeader(context, incomingInviteRequest.message); + // Ported - make the first call to progress automatically. + if (context.autoSendAnInitialProvisionalResponse) { + context.progress(); + } + _this.emit("invite", context); + }, + onMessage: function (incomingMessageRequest) { + // Ported - handling of out of dialog MESSAGE. + var serverContext = new ServerContext_1.ServerContext(_this, incomingMessageRequest); + serverContext.body = incomingMessageRequest.message.body; + serverContext.contentType = incomingMessageRequest.message.getHeader("Content-Type") || "text/plain"; + incomingMessageRequest.accept(); + _this.emit("message", serverContext); // TODO: Review. Why is a "ServerContext" emitted? What use it is? + }, + onNotify: function (incomingNotifyRequest) { + // DEPRECATED: Out of dialog NOTIFY is an obsolete usage. + // Ported - handling of out of dialog NOTIFY. + if (_this.configuration.allowLegacyNotifications && _this.listeners("notify").length > 0) { + incomingNotifyRequest.accept(); + _this.emit("notify", { request: incomingNotifyRequest.message }); + } + else { + incomingNotifyRequest.reject({ statusCode: 481 }); + } + }, + onRefer: function (incomingReferRequest) { + // Ported - handling of out of dialog REFER. + _this.logger.log("Received an out of dialog refer"); + if (!_this.configuration.allowOutOfDialogRefers) { + incomingReferRequest.reject({ statusCode: 405 }); + } + _this.logger.log("Allow out of dialog refers is enabled on the UA"); + var referContext = new ReferContext_1.ReferServerContext(_this, incomingReferRequest); + if (_this.listeners("outOfDialogReferRequested").length) { + _this.emit("outOfDialogReferRequested", referContext); + } + else { + _this.logger.log("No outOfDialogReferRequest listeners, automatically accepting and following the out of dialog refer"); + referContext.accept({ followRefer: true }); + } + }, + onSubscribe: function (incomingSubscribeRequest) { + _this.emit("subscribe", incomingSubscribeRequest); + }, + }; + _this.userAgentCore = new user_agent_core_1.UserAgentCore(userAgentCoreConfiguration, userAgentCoreDelegate); + // Initialize registerContext + _this.registerContext = new RegisterContext_1.RegisterContext(_this, configuration.registerOptions); + _this.registerContext.on("failed", _this.emit.bind(_this, "registrationFailed")); + _this.registerContext.on("registered", _this.emit.bind(_this, "registered")); + _this.registerContext.on("unregistered", _this.emit.bind(_this, "unregistered")); + if (_this.configuration.autostart) { + _this.start(); + } + return _this; + } + // ================= + // High Level API + // ================= + UA.prototype.register = function (options) { + if (options === void 0) { options = {}; } + if (options.register) { + this.configuration.register = true; + } + this.registerContext.register(options); + return this; + }; + /** + * Unregister. + * + * @param {Boolean} [all] unregister all user bindings. + * + */ + UA.prototype.unregister = function (options) { + var _this = this; + this.configuration.register = false; + if (this.transport) { + this.transport.afterConnected(function () { + _this.registerContext.unregister(options); + }); + } + return this; + }; + UA.prototype.isRegistered = function () { + return this.registerContext.registered; + }; + /** + * Make an outgoing call. + * + * @param {String} target + * @param {Object} views + * @param {Object} [options.media] gets passed to SIP.sessionDescriptionHandler.getDescription as mediaHint + * + * @throws {TypeError} + * + */ + UA.prototype.invite = function (target, options, modifiers) { + var _this = this; + var context = new Session_1.InviteClientContext(this, target, options, modifiers); + // Delay sending actual invite until the next 'tick' if we are already + // connected, so that API consumers can register to events fired by the + // the session. + if (this.transport) { + this.transport.afterConnected(function () { + context.invite(); + _this.emit("inviteSent", context); + }); + } + return context; + }; + UA.prototype.subscribe = function (target, event, options) { + var sub = new Subscription_1.Subscription(this, target, event, options); + if (this.transport) { + this.transport.afterConnected(function () { return sub.subscribe(); }); + } + return sub; + }; + /** + * Send PUBLISH Event State Publication (RFC3903) + * + * @param {String} target + * @param {String} event + * @param {String} body + * @param {Object} [options] + * + * @throws {SIP.Exceptions.MethodParameterError} + */ + UA.prototype.publish = function (target, event, body, options) { + var pub = new PublishContext_1.PublishContext(this, target, event, options); + if (this.transport) { + this.transport.afterConnected(function () { + pub.publish(body); + }); + } + return pub; + }; + /** + * Send a message. + * + * @param {String} target + * @param {String} body + * @param {Object} [options] + * + * @throws {TypeError} + */ + UA.prototype.message = function (target, body, options) { + if (options === void 0) { options = {}; } + if (body === undefined) { + throw new TypeError("Not enough arguments"); + } + // There is no Message module, so it is okay that the UA handles defaults here. + options.contentType = options.contentType || "text/plain"; + options.body = body; + return this.request(Constants_1.C.MESSAGE, target, options); + }; + UA.prototype.request = function (method, target, options) { + var req = new ClientContext_1.ClientContext(this, method, target, options); + if (this.transport) { + this.transport.afterConnected(function () { return req.send(); }); + } + return req; + }; + /** + * Gracefully close. + */ + UA.prototype.stop = function () { + this.logger.log("user requested closure..."); + if (this.status === Enums_1.UAStatus.STATUS_USER_CLOSED) { + this.logger.warn("UA already closed"); + return this; + } + // Close registerContext + this.logger.log("closing registerContext"); + this.registerContext.close(); + // Run _terminate_ on every Session + for (var session in this.sessions) { + if (this.sessions[session]) { + this.logger.log("closing session " + session); + this.sessions[session].terminate(); + } + } + // Run _close_ on every Publisher + for (var publisher in this.publishers) { + if (this.publishers[publisher]) { + this.logger.log("unpublish " + publisher); + this.publishers[publisher].close(); + } + } + // Run _close_ on every applicant + for (var applicant in this.applicants) { + if (this.applicants[applicant]) { + this.applicants[applicant].close(); + } + } + this.status = Enums_1.UAStatus.STATUS_USER_CLOSED; + if (typeof environment.removeEventListener === "function") { + // Google Chrome Packaged Apps don't allow 'unload' listeners: + // unload is not available in packaged apps + if (!(global.chrome && global.chrome.app && global.chrome.app.runtime)) { + environment.removeEventListener("unload", this.environListener); + } + } + return this; + }; + /** + * Connect to the WS server if status = STATUS_INIT. + * Resume UA after being closed. + * + */ + UA.prototype.start = function () { + var _this = this; + this.logger.log("user requested startup..."); + if (this.status === Enums_1.UAStatus.STATUS_INIT) { + this.status = Enums_1.UAStatus.STATUS_STARTING; + if (!this.configuration.transportConstructor) { + throw new Exceptions_1.Exceptions.TransportError("Transport constructor not set"); + } + this.transport = new this.configuration.transportConstructor(this.getLogger("sip.transport"), this.configuration.transportOptions); + this.setTransportListeners(); + this.emit("transportCreated", this.transport); + this.transport.connect(); + } + else if (this.status === Enums_1.UAStatus.STATUS_USER_CLOSED) { + this.logger.log("resuming"); + this.status = Enums_1.UAStatus.STATUS_READY; + if (this.transport) { + this.transport.connect(); + } + } + else if (this.status === Enums_1.UAStatus.STATUS_STARTING) { + this.logger.log("UA is in STARTING status, not opening new connection"); + } + else if (this.status === Enums_1.UAStatus.STATUS_READY) { + this.logger.log("UA is in READY status, not resuming"); + } + else { + this.logger.error("Connection is down. Auto-Recovery system is trying to connect"); + } + if (this.configuration.autostop && typeof environment.addEventListener === "function") { + // Google Chrome Packaged Apps don't allow 'unload' listeners: + // unload is not available in packaged apps + if (!(global.chrome && global.chrome.app && global.chrome.app.runtime)) { + this.environListener = this.stop; + environment.addEventListener("unload", function () { return _this.environListener(); }); + } + } + return this; + }; + /** + * Normalize a string into a valid SIP request URI + * + * @param {String} target + * + * @returns {SIP.URI|undefined} + */ + UA.prototype.normalizeTarget = function (target) { + return Utils_1.Utils.normalizeTarget(target, this.configuration.hostportParams); + }; + UA.prototype.getLogger = function (category, label) { + return this.log.getLogger(category, label); + }; + UA.prototype.getLoggerFactory = function () { + return this.log; + }; + /** + * Get the session to which the request belongs to, if any. + * @param {SIP.IncomingRequest} request. + * @returns {SIP.OutgoingSession|SIP.IncomingSession|undefined} + */ + UA.prototype.findSession = function (request) { + return this.sessions[request.callId + request.fromTag] || + this.sessions[request.callId + request.toTag] || + undefined; + }; + UA.prototype.on = function (name, callback) { return _super.prototype.on.call(this, name, callback); }; + // ============================== + // Event Handlers + // ============================== + UA.prototype.onTransportError = function () { + if (this.status === Enums_1.UAStatus.STATUS_USER_CLOSED) { + return; + } + if (!this.error || this.error !== UA.C.NETWORK_ERROR) { + this.status = Enums_1.UAStatus.STATUS_NOT_READY; + this.error = UA.C.NETWORK_ERROR; + } + }; + /** + * Helper function. Sets transport listeners + */ + UA.prototype.setTransportListeners = function () { + var _this = this; + if (this.transport) { + this.transport.on("connected", function () { return _this.onTransportConnected(); }); + this.transport.on("message", function (message) { return _this.onTransportReceiveMsg(message); }); + this.transport.on("transportError", function () { return _this.onTransportError(); }); + } + }; + /** + * Transport connection event. + * @event + * @param {SIP.Transport} transport. + */ + UA.prototype.onTransportConnected = function () { + var _this = this; + if (this.configuration.register) { + // In an effor to maintain behavior from when we "initialized" an + // authentication factory, this is in a Promise.then + Promise.resolve().then(function () { return _this.registerContext.register(); }); + } + }; + /** + * Handle SIP message received from the transport. + * @param messageString The message. + */ + UA.prototype.onTransportReceiveMsg = function (messageString) { + var _this = this; + var message = Parser_1.Parser.parseMessage(messageString, this); + if (!message) { + this.logger.warn("UA failed to parse incoming SIP message - discarding."); + return; + } + if (this.status === Enums_1.UAStatus.STATUS_USER_CLOSED && message instanceof SIPMessage_1.IncomingRequest) { + this.logger.warn("UA received message when status = USER_CLOSED - aborting"); + return; + } + // A valid SIP request formulated by a UAC MUST, at a minimum, contain + // the following header fields: To, From, CSeq, Call-ID, Max-Forwards, + // and Via; all of these header fields are mandatory in all SIP + // requests. + // https://tools.ietf.org/html/rfc3261#section-8.1.1 + var hasMinimumHeaders = function () { + var mandatoryHeaders = ["from", "to", "call_id", "cseq", "via"]; + for (var _i = 0, mandatoryHeaders_1 = mandatoryHeaders; _i < mandatoryHeaders_1.length; _i++) { + var header = mandatoryHeaders_1[_i]; + if (!message.hasHeader(header)) { + _this.logger.warn("Missing mandatory header field : " + header + "."); + return false; + } + } + return true; + }; + // Request Checks + if (message instanceof SIPMessage_1.IncomingRequest) { + // This is port of SanityCheck.minimumHeaders(). + if (!hasMinimumHeaders()) { + this.logger.warn("Request missing mandatory header field. Dropping."); + return; + } + // FIXME: This is non-standard and should be a configruable behavior (desirable regardless). + // Custom SIP.js check to reject request from ourself (this instance of SIP.js). + // This is port of SanityCheck.rfc3261_16_3_4(). + if (!message.toTag && message.callId.substr(0, 5) === this.configuration.sipjsId) { + this.userAgentCore.replyStateless(message, { statusCode: 482 }); + return; + } + // FIXME: This should be Transport check before we get here (Section 18). + // Custom SIP.js check to reject requests if body length wrong. + // This is port of SanityCheck.rfc3261_18_3_request(). + var len = Utils_1.Utils.str_utf8_length(message.body); + var contentLength = message.getHeader("content-length"); + if (contentLength && len < Number(contentLength)) { + this.userAgentCore.replyStateless(message, { statusCode: 400 }); + return; + } + } + // Reponse Checks + if (message instanceof SIPMessage_1.IncomingResponse) { + // This is port of SanityCheck.minimumHeaders(). + if (!hasMinimumHeaders()) { + this.logger.warn("Response missing mandatory header field. Dropping."); + return; + } + // Custom SIP.js check to drop responses if multiple Via headers. + // This is port of SanityCheck.rfc3261_8_1_3_3(). + if (message.getHeaders("via").length > 1) { + this.logger.warn("More than one Via header field present in the response. Dropping."); + return; + } + // FIXME: This should be Transport check before we get here (Section 18). + // Custom SIP.js check to drop responses if bad Via header. + // This is port of SanityCheck.rfc3261_18_1_2(). + if (message.via.host !== this.configuration.viaHost || message.via.port !== undefined) { + this.logger.warn("Via sent-by in the response does not match UA Via host value. Dropping."); + return; + } + // FIXME: This should be Transport check before we get here (Section 18). + // Custom SIP.js check to reject requests if body length wrong. + // This is port of SanityCheck.rfc3261_18_3_response(). + var len = Utils_1.Utils.str_utf8_length(message.body); + var contentLength = message.getHeader("content-length"); + if (contentLength && len < Number(contentLength)) { + this.logger.warn("Message body length is lower than the value in Content-Length header field. Dropping."); + return; + } + } + // Handle Request + if (message instanceof SIPMessage_1.IncomingRequest) { + this.userAgentCore.receiveIncomingRequestFromTransport(message); + return; + } + // Handle Response + if (message instanceof SIPMessage_1.IncomingResponse) { + this.userAgentCore.receiveIncomingResponseFromTransport(message); + return; + } + throw new Error("Invalid message type."); + }; + // ================= + // Utils + // ================= + UA.prototype.checkAuthenticationFactory = function (authenticationFactory) { + if (!(authenticationFactory instanceof Function)) { + return; + } + if (!authenticationFactory.initialize) { + authenticationFactory.initialize = function () { + return Promise.resolve(); + }; + } + return authenticationFactory; + }; + /** + * Configuration load. + * returns {void} + */ + UA.prototype.loadConfig = function (configuration) { + var _this = this; + // Settings and default values + var settings = { + /* Host address + * Value to be set in Via sent_by and host part of Contact FQDN + */ + viaHost: Utils_1.Utils.createRandomToken(12) + ".invalid", + uri: new URI_1.URI("sip", "anonymous." + Utils_1.Utils.createRandomToken(6), "anonymous.invalid", undefined, undefined), + // Custom Configuration Settings + custom: {}, + // Display name + displayName: "", + // Password + password: undefined, + register: true, + // Registration parameters + registerOptions: {}, + // Transport related parameters + transportConstructor: Transport_1.Transport, + transportOptions: {}, + // string to be inserted into User-Agent request header + userAgentString: Constants_1.C.USER_AGENT, + // Session parameters + noAnswerTimeout: 60, + // Hacks + hackViaTcp: false, + hackIpInContact: false, + hackWssInTransport: false, + hackAllowUnregisteredOptionTags: false, + // Session Description Handler Options + sessionDescriptionHandlerFactoryOptions: { + constraints: {}, + peerConnectionOptions: {} + }, + extraSupported: [], + contactName: Utils_1.Utils.createRandomToken(8), + contactTransport: "ws", + forceRport: false, + // autostarting + autostart: true, + autostop: true, + // Reliable Provisional Responses + rel100: Constants_1.C.supported.UNSUPPORTED, + // DTMF type: 'info' or 'rtp' (RFC 4733) + // RTP Payload Spec: https://tools.ietf.org/html/rfc4733 + // WebRTC Audio Spec: https://tools.ietf.org/html/rfc7874 + dtmfType: Constants_1.C.dtmfType.INFO, + // Replaces header (RFC 3891) + // http://tools.ietf.org/html/rfc3891 + replaces: Constants_1.C.supported.UNSUPPORTED, + sessionDescriptionHandlerFactory: SessionDescriptionHandler_1.SessionDescriptionHandler.defaultFactory, + authenticationFactory: this.checkAuthenticationFactory(function (ua) { + return new DigestAuthentication_1.DigestAuthentication(ua); + }), + allowLegacyNotifications: false, + allowOutOfDialogRefers: false, + experimentalFeatures: false + }; + var configCheck = this.getConfigurationCheck(); + // Check Mandatory parameters + for (var parameter in configCheck.mandatory) { + if (!configuration.hasOwnProperty(parameter)) { + throw new Exceptions_1.Exceptions.ConfigurationError(parameter); + } + else { + var value = configuration[parameter]; + var checkedValue = configCheck.mandatory[parameter](value); + if (checkedValue !== undefined) { + settings[parameter] = checkedValue; + } + else { + throw new Exceptions_1.Exceptions.ConfigurationError(parameter, value); + } + } + } + // Check Optional parameters + for (var parameter in configCheck.optional) { + if (configuration.hasOwnProperty(parameter)) { + var value = configuration[parameter]; + // If the parameter value is an empty array, but shouldn't be, apply its default value. + // If the parameter value is null, empty string, or undefined then apply its default value. + // If it's a number with NaN value then also apply its default value. + // NOTE: JS does not allow "value === NaN", the following does the work: + if ((value instanceof Array && value.length === 0) || + (value === null || value === "" || value === undefined) || + (typeof (value) === "number" && isNaN(value))) { + continue; + } + var checkedValue = configCheck.optional[parameter](value); + if (checkedValue !== undefined) { + settings[parameter] = checkedValue; + } + else { + throw new Exceptions_1.Exceptions.ConfigurationError(parameter, value); + } + } + } + // Post Configuration Process + // Allow passing 0 number as displayName. + if (settings.displayName === 0) { + settings.displayName = "0"; + } + // sipjsId instance parameter. Static random tag of length 5 + settings.sipjsId = Utils_1.Utils.createRandomToken(5); + // String containing settings.uri without scheme and user. + var hostportParams = settings.uri.clone(); + hostportParams.user = undefined; + settings.hostportParams = hostportParams.toRaw().replace(/^sip:/i, ""); + /* Check whether authorizationUser is explicitly defined. + * Take 'settings.uri.user' value if not. + */ + if (!settings.authorizationUser) { + settings.authorizationUser = settings.uri.user; + } + // User noAnswerTimeout + settings.noAnswerTimeout = settings.noAnswerTimeout * 1000; + // Via Host + if (settings.hackIpInContact) { + if (typeof settings.hackIpInContact === "boolean") { + var from = 1; + var to = 254; + var octet = Math.floor(Math.random() * (to - from + 1) + from); + // random Test-Net IP (http://tools.ietf.org/html/rfc5735) + settings.viaHost = "192.0.2." + octet; + } + else if (typeof settings.hackIpInContact === "string") { + settings.viaHost = settings.hackIpInContact; + } + } + // Contact transport parameter + if (settings.hackWssInTransport) { + settings.contactTransport = "wss"; + } + this.contact = { + pubGruu: undefined, + tempGruu: undefined, + uri: new URI_1.URI("sip", settings.contactName, settings.viaHost, undefined, { transport: settings.contactTransport }), + toString: function (options) { + if (options === void 0) { options = {}; } + var anonymous = options.anonymous || false; + var outbound = options.outbound || false; + var contact = "<"; + if (anonymous) { + contact += (_this.contact.tempGruu || + ("sip:anonymous@anonymous.invalid;transport=" + settings.contactTransport)).toString(); + } + else { + contact += (_this.contact.pubGruu || _this.contact.uri).toString(); + } + if (outbound) { + contact += ";ob"; + } + contact += ">"; + return contact; + } + }; + var skeleton = {}; + // Fill the value of the configuration_skeleton + for (var parameter in settings) { + if (settings.hasOwnProperty(parameter)) { + skeleton[parameter] = settings[parameter]; + } + } + Object.assign(this.configuration, skeleton); + this.logger.log("configuration parameters after validation:"); + for (var parameter in settings) { + if (settings.hasOwnProperty(parameter)) { + switch (parameter) { + case "uri": + case "sessionDescriptionHandlerFactory": + this.logger.log("· " + parameter + ": " + settings[parameter]); + break; + case "password": + this.logger.log("· " + parameter + ": " + "NOT SHOWN"); + break; + case "transportConstructor": + this.logger.log("· " + parameter + ": " + settings[parameter].name); + break; + default: + this.logger.log("· " + parameter + ": " + JSON.stringify(settings[parameter])); + } + } + } + return; + }; + /** + * Configuration checker. + * @return {Boolean} + */ + UA.prototype.getConfigurationCheck = function () { + return { + mandatory: {}, + optional: { + uri: function (uri) { + if (!(/^sip:/i).test(uri)) { + uri = Constants_1.C.SIP + ":" + uri; + } + var parsed = Grammar_1.Grammar.URIParse(uri); + if (!parsed || !parsed.user) { + return; + } + else { + return parsed; + } + }, + transportConstructor: function (transportConstructor) { + if (transportConstructor instanceof Function) { + return transportConstructor; + } + }, + transportOptions: function (transportOptions) { + if (typeof transportOptions === "object") { + return transportOptions; + } + }, + authorizationUser: function (authorizationUser) { + if (Grammar_1.Grammar.parse('"' + authorizationUser + '"', "quoted_string") === -1) { + return; + } + else { + return authorizationUser; + } + }, + displayName: function (displayName) { + if (Grammar_1.Grammar.parse('"' + displayName + '"', "displayName") === -1) { + return; + } + else { + return displayName; + } + }, + dtmfType: function (dtmfType) { + switch (dtmfType) { + case Constants_1.C.dtmfType.RTP: + return Constants_1.C.dtmfType.RTP; + case Constants_1.C.dtmfType.INFO: + // Fall through + default: + return Constants_1.C.dtmfType.INFO; + } + }, + hackViaTcp: function (hackViaTcp) { + if (typeof hackViaTcp === "boolean") { + return hackViaTcp; + } + }, + hackIpInContact: function (hackIpInContact) { + if (typeof hackIpInContact === "boolean") { + return hackIpInContact; + } + else if (typeof hackIpInContact === "string" && Grammar_1.Grammar.parse(hackIpInContact, "host") !== -1) { + return hackIpInContact; + } + }, + hackWssInTransport: function (hackWssInTransport) { + if (typeof hackWssInTransport === "boolean") { + return hackWssInTransport; + } + }, + hackAllowUnregisteredOptionTags: function (hackAllowUnregisteredOptionTags) { + if (typeof hackAllowUnregisteredOptionTags === "boolean") { + return hackAllowUnregisteredOptionTags; + } + }, + contactTransport: function (contactTransport) { + if (typeof contactTransport === "string") { + return contactTransport; + } + }, + extraSupported: function (optionTags) { + if (!(optionTags instanceof Array)) { + return; + } + for (var _i = 0, optionTags_1 = optionTags; _i < optionTags_1.length; _i++) { + var tag = optionTags_1[_i]; + if (typeof tag !== "string") { + return; + } + } + return optionTags; + }, + forceRport: function (forceRport) { + if (typeof forceRport === "boolean") { + return forceRport; + } + }, + noAnswerTimeout: function (noAnswerTimeout) { + if (Utils_1.Utils.isDecimal(noAnswerTimeout)) { + var value = Number(noAnswerTimeout); + if (value > 0) { + return value; + } + } + }, + password: function (password) { + return String(password); + }, + rel100: function (rel100) { + if (rel100 === Constants_1.C.supported.REQUIRED) { + return Constants_1.C.supported.REQUIRED; + } + else if (rel100 === Constants_1.C.supported.SUPPORTED) { + return Constants_1.C.supported.SUPPORTED; + } + else { + return Constants_1.C.supported.UNSUPPORTED; + } + }, + replaces: function (replaces) { + if (replaces === Constants_1.C.supported.REQUIRED) { + return Constants_1.C.supported.REQUIRED; + } + else if (replaces === Constants_1.C.supported.SUPPORTED) { + return Constants_1.C.supported.SUPPORTED; + } + else { + return Constants_1.C.supported.UNSUPPORTED; + } + }, + register: function (register) { + if (typeof register === "boolean") { + return register; + } + }, + registerOptions: function (registerOptions) { + if (typeof registerOptions === "object") { + return registerOptions; + } + }, + userAgentString: function (userAgentString) { + if (typeof userAgentString === "string") { + return userAgentString; + } + }, + autostart: function (autostart) { + if (typeof autostart === "boolean") { + return autostart; + } + }, + autostop: function (autostop) { + if (typeof autostop === "boolean") { + return autostop; + } + }, + sessionDescriptionHandlerFactory: function (sessionDescriptionHandlerFactory) { + if (sessionDescriptionHandlerFactory instanceof Function) { + return sessionDescriptionHandlerFactory; + } + }, + sessionDescriptionHandlerFactoryOptions: function (options) { + if (typeof options === "object") { + return options; + } + }, + authenticationFactory: this.checkAuthenticationFactory, + allowLegacyNotifications: function (allowLegacyNotifications) { + if (typeof allowLegacyNotifications === "boolean") { + return allowLegacyNotifications; + } + }, + custom: function (custom) { + if (typeof custom === "object") { + return custom; + } + }, + contactName: function (contactName) { + if (typeof contactName === "string") { + return contactName; + } + }, + experimentalFeatures: function (experimentalFeatures) { + if (typeof experimentalFeatures === "boolean") { + return experimentalFeatures; + } + }, + } + }; + }; + UA.C = { + // UA status codes + STATUS_INIT: 0, + STATUS_STARTING: 1, + STATUS_READY: 2, + STATUS_USER_CLOSED: 3, + STATUS_NOT_READY: 4, + // UA error codes + CONFIGURATION_ERROR: 1, + NETWORK_ERROR: 2, + ALLOWED_METHODS: [ + "ACK", + "CANCEL", + "INVITE", + "MESSAGE", + "BYE", + "OPTIONS", + "INFO", + "NOTIFY", + "REFER" + ], + ACCEPTED_BODY_TYPES: [ + "application/sdp", + "application/dtmf-relay" + ], + MAX_FORWARDS: 70, + TAG_LENGTH: 10 + }; + return UA; +}(events_1.EventEmitter)); +exports.UA = UA; +(function (UA) { + var DtmfType; + (function (DtmfType) { + DtmfType["RTP"] = "rtp"; + DtmfType["INFO"] = "info"; + })(DtmfType = UA.DtmfType || (UA.DtmfType = {})); +})(UA = exports.UA || (exports.UA = {})); +exports.UA = UA; + +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(77))) + +/***/ }), +/* 77 */ +/***/ (function(module, exports) { + +var g; + +// This works in non-strict mode +g = (function() { + return this; +})(); + +try { + // This works if eval is allowed (see CSP) + g = g || new Function("return this")(); +} catch (e) { + // This works if the window reference is available + if (typeof window === "object") g = window; +} + +// g can still be undefined, but nothing to do about it... +// We return undefined, instead of nothing here, so it's +// easier to handle this case. if(!global) { ...} + +module.exports = g; + + +/***/ }), +/* 78 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +function __export(m) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; +} +Object.defineProperty(exports, "__esModule", { value: true }); +__export(__webpack_require__(79)); +__export(__webpack_require__(110)); + + +/***/ }), +/* 79 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +var Constants_1 = __webpack_require__(3); +var messages_1 = __webpack_require__(63); +var transactions_1 = __webpack_require__(52); +var user_agents_1 = __webpack_require__(80); +var allowed_methods_1 = __webpack_require__(74); +/** + * This is ported from UA.C.ACCEPTED_BODY_TYPES. + * FIXME: TODO: Should be configurable/variable. + */ +var acceptedBodyTypes = [ + "application/sdp", + "application/dtmf-relay" +]; +/** + * Core: Core designates the functions specific to a particular type + * of SIP entity, i.e., specific to either a stateful or stateless + * proxy, a user agent or registrar. All cores, except those for + * the stateless proxy, are transaction users. + * https://tools.ietf.org/html/rfc3261#section-6 + * + * UAC Core: The set of processing functions required of a UAC that + * reside above the transaction and transport layers. + * https://tools.ietf.org/html/rfc3261#section-6 + * + * UAS Core: The set of processing functions required at a UAS that + * resides above the transaction and transport layers. + * https://tools.ietf.org/html/rfc3261#section-6 + */ +var UserAgentCore = /** @class */ (function () { + /** + * Constructor. + * @param configuration Configuration. + * @param delegate Delegate. + */ + function UserAgentCore(configuration, delegate) { + if (delegate === void 0) { delegate = {}; } + /** UACs. */ + this.userAgentClients = new Map(); + /** UASs. */ + this.userAgentServers = new Map(); + this.configuration = configuration; + this.delegate = delegate; + this.dialogs = new Map(); + this.subscribers = new Map(); + this.logger = configuration.loggerFactory.getLogger("sip.user-agent-core"); + } + /** Destructor. */ + UserAgentCore.prototype.dispose = function () { + this.dialogs.forEach(function (dialog) { return dialog.dispose(); }); + this.dialogs.clear(); + this.subscribers.forEach(function (subscriber) { return subscriber.dispose(); }); + this.subscribers.clear(); + this.userAgentClients.forEach(function (uac) { return uac.dispose(); }); + this.userAgentClients.clear(); + this.userAgentServers.forEach(function (uac) { return uac.dispose(); }); + this.userAgentServers.clear(); + }; + Object.defineProperty(UserAgentCore.prototype, "loggerFactory", { + /** Logger factory. */ + get: function () { + return this.configuration.loggerFactory; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(UserAgentCore.prototype, "transport", { + /** Transport. */ + get: function () { + var transport = this.configuration.transportAccessor(); + if (!transport) { + throw new Error("Transport undefined."); + } + return transport; + }, + enumerable: true, + configurable: true + }); + /** + * Send INVITE. + * @param request Outgoing request. + * @param delegate Request delegate. + */ + UserAgentCore.prototype.invite = function (request, delegate) { + return new user_agents_1.InviteUserAgentClient(this, request, delegate); + }; + /** + * Send MESSAGE. + * @param request Outgoing request. + * @param delegate Request delegate. + */ + UserAgentCore.prototype.message = function (request, delegate) { + return new user_agents_1.MessageUserAgentClient(this, request, delegate); + }; + /** + * Send PUBLISH. + * @param request Outgoing request. + * @param delegate Request delegate. + */ + UserAgentCore.prototype.publish = function (request, delegate) { + return new user_agents_1.PublishUserAgentClient(this, request, delegate); + }; + /** + * Send REGISTER. + * @param request Outgoing request. + * @param delegate Request delegate. + */ + UserAgentCore.prototype.register = function (request, delegate) { + return new user_agents_1.RegisterUserAgentClient(this, request, delegate); + }; + /** + * Send SUBSCRIBE. + * @param request Outgoing request. + * @param delegate Request delegate. + */ + UserAgentCore.prototype.subscribe = function (request, delegate) { + return new user_agents_1.SubscribeUserAgentClient(this, request, delegate); + }; + /** + * Send a request. + * @param request Outgoing request. + * @param delegate Request delegate. + */ + UserAgentCore.prototype.request = function (request, delegate) { + return new user_agents_1.UserAgentClient(transactions_1.NonInviteClientTransaction, this, request, delegate); + }; + /** + * Handle an incoming request message from the transport. + * @param message Incoming request message from transport layer. + */ + UserAgentCore.prototype.receiveIncomingRequestFromTransport = function (message) { + this.receiveRequestFromTransport(message); + }; + /** + * Handle an incoming response message from the transport. + * @param message Incoming response message from transport layer. + */ + UserAgentCore.prototype.receiveIncomingResponseFromTransport = function (message) { + this.receiveResponseFromTransport(message); + }; + /** + * A stateless UAS is a UAS that does not maintain transaction state. + * It replies to requests normally, but discards any state that would + * ordinarily be retained by a UAS after a response has been sent. If a + * stateless UAS receives a retransmission of a request, it regenerates + * the response and re-sends it, just as if it were replying to the first + * instance of the request. A UAS cannot be stateless unless the request + * processing for that method would always result in the same response + * if the requests are identical. This rules out stateless registrars, + * for example. Stateless UASs do not use a transaction layer; they + * receive requests directly from the transport layer and send responses + * directly to the transport layer. + * https://tools.ietf.org/html/rfc3261#section-8.2.7 + * @param message Incoming request message to reply to. + * @param statusCode Status code to reply with. + */ + UserAgentCore.prototype.replyStateless = function (message, options) { + var userAgent = this.configuration.userAgentHeaderFieldValue; + options = __assign({}, options, { userAgent: userAgent }); + var response = messages_1.constructOutgoingResponse(message, options); + this.transport.send(response.message); + return response; + }; + /** + * In Section 18.2.1, replace the last paragraph with: + * + * Next, the server transport attempts to match the request to a + * server transaction. It does so using the matching rules described + * in Section 17.2.3. If a matching server transaction is found, the + * request is passed to that transaction for processing. If no match + * is found, the request is passed to the core, which may decide to + * construct a new server transaction for that request. + * https://tools.ietf.org/html/rfc6026#section-8.10 + * @param message Incoming request message from transport layer. + */ + UserAgentCore.prototype.receiveRequestFromTransport = function (message) { + // When a request is received from the network by the server, it has to + // be matched to an existing transaction. This is accomplished in the + // following manner. + // + // The branch parameter in the topmost Via header field of the request + // is examined. If it is present and begins with the magic cookie + // "z9hG4bK", the request was generated by a client transaction + // compliant to this specification. Therefore, the branch parameter + // will be unique across all transactions sent by that client. The + // request matches a transaction if: + // + // 1. the branch parameter in the request is equal to the one in the + // top Via header field of the request that created the + // transaction, and + // + // 2. the sent-by value in the top Via of the request is equal to the + // one in the request that created the transaction, and + // + // 3. the method of the request matches the one that created the + // transaction, except for ACK, where the method of the request + // that created the transaction is INVITE. + // + // This matching rule applies to both INVITE and non-INVITE transactions + // alike. + // + // The sent-by value is used as part of the matching process because + // there could be accidental or malicious duplication of branch + // parameters from different clients. + // https://tools.ietf.org/html/rfc3261#section-17.2.3 + var transactionId = message.viaBranch; // FIXME: Currently only using rule 1... + var uas = this.userAgentServers.get(transactionId); + // When receiving an ACK that matches an existing INVITE server + // transaction and that does not contain a branch parameter containing + // the magic cookie defined in RFC 3261, the matching transaction MUST + // be checked to see if it is in the "Accepted" state. If it is, then + // the ACK must be passed directly to the transaction user instead of + // being absorbed by the transaction state machine. This is necessary + // as requests from RFC 2543 clients will not include a unique branch + // parameter, and the mechanisms for calculating the transaction ID from + // such a request will be the same for both INVITE and ACKs. + // https://tools.ietf.org/html/rfc6026#section-6 + // Any ACKs received from the network while in the "Accepted" state MUST be + // passed directly to the TU and not absorbed. + // https://tools.ietf.org/html/rfc6026#section-7.1 + if (message.method === Constants_1.C.ACK) { + if (uas && uas.transaction.state === transactions_1.TransactionState.Accepted) { + if (uas instanceof user_agents_1.InviteUserAgentServer) { + // These are ACKs matching an INVITE server transaction. + // These should never happen with RFC 3261 compliant user agents + // (would be a broken ACK to negative final response or something) + // but is apparently how RFC 2543 user agents do things. + // We are not currently supporting this case. + // NOTE: Not backwards compatible with RFC 2543 (no support for strict-routing). + this.logger.warn("Discarding out of dialog ACK after 2xx response sent on transaction " + transactionId + "."); + return; + } + } + } + // The CANCEL method requests that the TU at the server side cancel a + // pending transaction. The TU determines the transaction to be + // cancelled by taking the CANCEL request, and then assuming that the + // request method is anything but CANCEL or ACK and applying the + // transaction matching procedures of Section 17.2.3. The matching + // transaction is the one to be cancelled. + // https://tools.ietf.org/html/rfc3261#section-9.2 + if (message.method === Constants_1.C.CANCEL) { + if (uas) { + // Regardless of the method of the original request, as long as the + // CANCEL matched an existing transaction, the UAS answers the CANCEL + // request itself with a 200 (OK) response. + // https://tools.ietf.org/html/rfc3261#section-9.2 + this.replyStateless(message, { statusCode: 200 }); + // If the transaction for the original request still exists, the behavior + // of the UAS on receiving a CANCEL request depends on whether it has already + // sent a final response for the original request. If it has, the CANCEL + // request has no effect on the processing of the original request, no + // effect on any session state, and no effect on the responses generated + // for the original request. If the UAS has not issued a final response + // for the original request, its behavior depends on the method of the + // original request. If the original request was an INVITE, the UAS + // SHOULD immediately respond to the INVITE with a 487 (Request + // Terminated). + // https://tools.ietf.org/html/rfc3261#section-9.2 + if (uas.transaction instanceof transactions_1.InviteServerTransaction && + uas.transaction.state === transactions_1.TransactionState.Proceeding) { + if (uas instanceof user_agents_1.InviteUserAgentServer) { + uas.receiveCancel(message); + } + // A CANCEL request has no impact on the processing of + // transactions with any other method defined in this specification. + // https://tools.ietf.org/html/rfc3261#section-9.2 + } + } + else { + // If the UAS did not find a matching transaction for the CANCEL + // according to the procedure above, it SHOULD respond to the CANCEL + // with a 481 (Call Leg/Transaction Does Not Exist). + // https://tools.ietf.org/html/rfc3261#section-9.2 + this.replyStateless(message, { statusCode: 481 }); + } + return; + } + // If a matching server transaction is found, the request is passed to that + // transaction for processing. + // https://tools.ietf.org/html/rfc6026#section-8.10 + if (uas) { + uas.transaction.receiveRequest(message); + return; + } + // If no match is found, the request is passed to the core, which may decide to + // construct a new server transaction for that request. + // https://tools.ietf.org/html/rfc6026#section-8.10 + this.receiveRequest(message); + return; + }; + /** + * UAC and UAS procedures depend strongly on two factors. First, based + * on whether the request or response is inside or outside of a dialog, + * and second, based on the method of a request. Dialogs are discussed + * thoroughly in Section 12; they represent a peer-to-peer relationship + * between user agents and are established by specific SIP methods, such + * as INVITE. + * @param message Incoming request message. + */ + UserAgentCore.prototype.receiveRequest = function (message) { + // 8.2 UAS Behavior + // UASs SHOULD process the requests in the order of the steps that + // follow in this section (that is, starting with authentication, then + // inspecting the method, the header fields, and so on throughout the + // remainder of this section). + // https://tools.ietf.org/html/rfc3261#section-8.2 + // 8.2.1 Method Inspection + // Once a request is authenticated (or authentication is skipped), the + // UAS MUST inspect the method of the request. If the UAS recognizes + // but does not support the method of a request, it MUST generate a 405 + // (Method Not Allowed) response. Procedures for generating responses + // are described in Section 8.2.6. The UAS MUST also add an Allow + // header field to the 405 (Method Not Allowed) response. The Allow + // header field MUST list the set of methods supported by the UAS + // generating the message. + // https://tools.ietf.org/html/rfc3261#section-8.2.1 + if (!allowed_methods_1.AllowedMethods.includes(message.method)) { + var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); + this.replyStateless(message, { + statusCode: 405, + extraHeaders: [allowHeader] + }); + return; + } + // 8.2.2 Header Inspection + // https://tools.ietf.org/html/rfc3261#section-8.2.2 + if (!message.ruri) { // FIXME: A request message should always have an ruri + throw new Error("Request-URI undefined."); + } + // 8.2.2.1 To and Request-URI + // If the Request-URI uses a scheme not supported by the UAS, it SHOULD + // reject the request with a 416 (Unsupported URI Scheme) response. + // https://tools.ietf.org/html/rfc3261#section-8.2.2.1 + if (message.ruri.scheme !== Constants_1.C.SIP) { + this.replyStateless(message, { statusCode: 416 }); + return; + } + // 8.2.2.1 To and Request-URI + // If the Request-URI does not identify an address that the + // UAS is willing to accept requests for, it SHOULD reject + // the request with a 404 (Not Found) response. + // https://tools.ietf.org/html/rfc3261#section-8.2.2.1 + var ruri = message.ruri; + var ruriMatches = function (uri) { + return !!uri && uri.user === ruri.user; + }; + if (!ruriMatches(this.configuration.aor) && + !(ruriMatches(this.configuration.contact.uri) || + ruriMatches(this.configuration.contact.pubGruu) || + ruriMatches(this.configuration.contact.tempGruu))) { + this.logger.warn("Request-URI does not point to us."); + if (message.method !== Constants_1.C.ACK) { + this.replyStateless(message, { statusCode: 404 }); + } + return; + } + // 8.2.2.1 To and Request-URI + // Other potential sources of received Request-URIs include + // the Contact header fields of requests and responses sent by the UA + // that establish or refresh dialogs. + // https://tools.ietf.org/html/rfc3261#section-8.2.2.1 + if (message.method === Constants_1.C.INVITE) { + if (!message.hasHeader("Contact")) { + this.replyStateless(message, { + statusCode: 400, + reasonPhrase: "Missing Contact Header" + }); + return; + } + } + // 8.2.2.2 Merged Requests + // If the request has no tag in the To header field, the UAS core MUST + // check the request against ongoing transactions. If the From tag, + // Call-ID, and CSeq exactly match those associated with an ongoing + // transaction, but the request does not match that transaction (based + // on the matching rules in Section 17.2.3), the UAS core SHOULD + // generate a 482 (Loop Detected) response and pass it to the server + // transaction. + // + // The same request has arrived at the UAS more than once, following + // different paths, most likely due to forking. The UAS processes + // the first such request received and responds with a 482 (Loop + // Detected) to the rest of them. + // https://tools.ietf.org/html/rfc3261#section-8.2.2.2 + if (!message.toTag) { + var transactionId = message.viaBranch; + if (!this.userAgentServers.has(transactionId)) { + var mergedRequest = Array.from(this.userAgentServers.values()) + .some(function (uas) { + return uas.transaction.request.fromTag === message.fromTag && + uas.transaction.request.callId === message.callId && + uas.transaction.request.cseq === message.cseq; + }); + if (mergedRequest) { + this.replyStateless(message, { statusCode: 482 }); + return; + } + } + } + // 8.2.2.3 Require + // https://tools.ietf.org/html/rfc3261#section-8.2.2.3 + // TODO + // 8.2.3 Content Processing + // https://tools.ietf.org/html/rfc3261#section-8.2.3 + // TODO + // 8.2.4 Applying Extensions + // https://tools.ietf.org/html/rfc3261#section-8.2.4 + // TODO + // 8.2.5 Processing the Request + // Assuming all of the checks in the previous subsections are passed, + // the UAS processing becomes method-specific. + // https://tools.ietf.org/html/rfc3261#section-8.2.5 + // The UAS will receive the request from the transaction layer. If the + // request has a tag in the To header field, the UAS core computes the + // dialog identifier corresponding to the request and compares it with + // existing dialogs. If there is a match, this is a mid-dialog request. + // In that case, the UAS first applies the same processing rules for + // requests outside of a dialog, discussed in Section 8.2. + // https://tools.ietf.org/html/rfc3261#section-12.2.2 + if (message.toTag) { + this.receiveInsideDialogRequest(message); + } + else { + this.receiveOutsideDialogRequest(message); + } + return; + }; + /** + * Once a dialog has been established between two UAs, either of them + * MAY initiate new transactions as needed within the dialog. The UA + * sending the request will take the UAC role for the transaction. The + * UA receiving the request will take the UAS role. Note that these may + * be different roles than the UAs held during the transaction that + * established the dialog. + * https://tools.ietf.org/html/rfc3261#section-12.2 + * @param message Incoming request message. + */ + UserAgentCore.prototype.receiveInsideDialogRequest = function (message) { + // NOTIFY requests are matched to such SUBSCRIBE requests if they + // contain the same "Call-ID", a "To" header field "tag" parameter that + // matches the "From" header field "tag" parameter of the SUBSCRIBE + // request, and the same "Event" header field. Rules for comparisons of + // the "Event" header fields are described in Section 8.2.1. + // https://tools.ietf.org/html/rfc6665#section-4.4.1 + if (message.method === Constants_1.C.NOTIFY) { + var event_1 = message.parseHeader("Event"); + if (!event_1 || !event_1.event) { + this.replyStateless(message, { statusCode: 489 }); + return; + } + // FIXME: Subscriber id should also matching on event id. + var subscriberId = message.callId + message.toTag + event_1.event; + var subscriber = this.subscribers.get(subscriberId); + if (subscriber) { + var uas = new user_agents_1.NotifyUserAgentServer(this, message); + subscriber.onNotify(uas); + return; + } + } + // Requests sent within a dialog, as any other requests, are atomic. If + // a particular request is accepted by the UAS, all the state changes + // associated with it are performed. If the request is rejected, none + // of the state changes are performed. + // + // Note that some requests, such as INVITEs, affect several pieces of + // state. + // + // The UAS will receive the request from the transaction layer. If the + // request has a tag in the To header field, the UAS core computes the + // dialog identifier corresponding to the request and compares it with + // existing dialogs. If there is a match, this is a mid-dialog request. + // https://tools.ietf.org/html/rfc3261#section-12.2.2 + var dialogId = message.callId + message.toTag + message.fromTag; + var dialog = this.dialogs.get(dialogId); + if (dialog) { + // [Sip-implementors] Reg. SIP reinvite, UPDATE and OPTIONS + // You got the question right. + // + // And you got the right answer too. :-) + // + // Thanks, + // Paul + // + // Robert Sparks wrote: + // > So I've lost track of the question during the musing. + // > + // > I _think_ the fundamental question being asked is this: + // > + // > Is an endpoint required to reject (with a 481) an OPTIONS request that + // > arrives with at to-tag but does not match any existing dialog state. + // > (Assuming some earlier requirement hasn't forced another error code). Or + // > is it OK if it just sends + // > a 200 OK anyhow. + // > + // > My take on the collection of specs is that its _not_ ok for it to send + // > the 200 OK anyhow and that it is required to send + // > the 481. I base this primarily on these sentences from 11.2 in 3261: + // > + // > The response to an OPTIONS is constructed using the standard rules + // > for a SIP response as discussed in Section 8.2.6. The response code + // > chosen MUST be the same that would have been chosen had the request + // > been an INVITE. + // > + // > Did I miss the point of the question? + // > + // > On May 15, 2008, at 12:48 PM, Paul Kyzivat wrote: + // > + // >> [Including Robert in hopes of getting his insight on this.] + // https://lists.cs.columbia.edu/pipermail/sip-implementors/2008-May/019178.html + // + // Requests that do not change in any way the state of a dialog may be + // received within a dialog (for example, an OPTIONS request). They are + // processed as if they had been received outside the dialog. + // https://tools.ietf.org/html/rfc3261#section-12.2.2 + if (message.method === Constants_1.C.OPTIONS) { + var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); + var acceptHeader = "Accept: " + acceptedBodyTypes.toString(); + this.replyStateless(message, { + statusCode: 200, + extraHeaders: [allowHeader, acceptHeader] + }); + return; + } + // Pass the incoming request to the dialog for further handling. + dialog.receiveRequest(message); + return; + } + // The most important behaviors of a stateless UAS are the following: + // ... + // o A stateless UAS MUST ignore ACK requests. + // ... + // https://tools.ietf.org/html/rfc3261#section-8.2.7 + if (message.method === Constants_1.C.ACK) { + // If a final response to an INVITE was sent statelessly, + // the corresponding ACK: + // - will not match an existing transaction + // - may have tag in the To header field + // - not not match any existing dialogs + // Absorb unmatched ACKs. + return; + } + // If the request has a tag in the To header field, but the dialog + // identifier does not match any existing dialogs, the UAS may have + // crashed and restarted, or it may have received a request for a + // different (possibly failed) UAS (the UASs can construct the To tags + // so that a UAS can identify that the tag was for a UAS for which it is + // providing recovery). Another possibility is that the incoming + // request has been simply mis-routed. Based on the To tag, the UAS MAY + // either accept or reject the request. Accepting the request for + // acceptable To tags provides robustness, so that dialogs can persist + // even through crashes. UAs wishing to support this capability must + // take into consideration some issues such as choosing monotonically + // increasing CSeq sequence numbers even across reboots, reconstructing + // the route set, and accepting out-of-range RTP timestamps and sequence + // numbers. + // + // If the UAS wishes to reject the request because it does not wish to + // recreate the dialog, it MUST respond to the request with a 481 + // (Call/Transaction Does Not Exist) status code and pass that to the + // server transaction. + // https://tools.ietf.org/html/rfc3261#section-12.2.2 + this.replyStateless(message, { statusCode: 481 }); + return; + }; + /** + * Assuming all of the checks in the previous subsections are passed, + * the UAS processing becomes method-specific. + * https://tools.ietf.org/html/rfc3261#section-8.2.5 + * @param message Incoming request message. + */ + UserAgentCore.prototype.receiveOutsideDialogRequest = function (message) { + switch (message.method) { + case Constants_1.C.ACK: + // Absorb stray out of dialog ACKs + break; + case Constants_1.C.BYE: + // If the BYE does not match an existing dialog, the UAS core SHOULD + // generate a 481 (Call/Transaction Does Not Exist) response and pass + // that to the server transaction. This rule means that a BYE sent + // without tags by a UAC will be rejected. + // https://tools.ietf.org/html/rfc3261#section-15.1.2 + this.replyStateless(message, { statusCode: 481 }); + break; + case Constants_1.C.CANCEL: + throw new Error("Unexpected out of dialog request method " + message.method + "."); + break; + case Constants_1.C.INFO: + // Use of the INFO method does not constitute a separate dialog usage. + // INFO messages are always part of, and share the fate of, an invite + // dialog usage [RFC5057]. INFO messages cannot be sent as part of + // other dialog usages, or outside an existing dialog. + // https://tools.ietf.org/html/rfc6086#section-1 + this.replyStateless(message, { statusCode: 405 }); // Should never happen + break; + case Constants_1.C.INVITE: + // https://tools.ietf.org/html/rfc3261#section-13.3.1 + { + var uas = new user_agents_1.InviteUserAgentServer(this, message); + this.delegate.onInvite ? + this.delegate.onInvite(uas) : + uas.reject(); + } + break; + case Constants_1.C.MESSAGE: + // MESSAGE requests are discouraged inside a dialog. Implementations + // are restricted from creating a usage for the purpose of carrying a + // sequence of MESSAGE requests (though some implementations use it that + // way, against the standard recommendation). + // https://tools.ietf.org/html/rfc5057#section-5.3 + { + var uas = new user_agents_1.MessageUserAgentServer(this, message); + this.delegate.onMessage ? + this.delegate.onMessage(uas) : + uas.accept(); + } + break; + case Constants_1.C.NOTIFY: + // Obsoleted by: RFC 6665 + // If any non-SUBSCRIBE mechanisms are defined to create subscriptions, + // it is the responsibility of the parties defining those mechanisms to + // ensure that correlation of a NOTIFY message to the corresponding + // subscription is possible. Designers of such mechanisms are also + // warned to make a distinction between sending a NOTIFY message to a + // subscriber who is aware of the subscription, and sending a NOTIFY + // message to an unsuspecting node. The latter behavior is invalid, and + // MUST receive a "481 Subscription does not exist" response (unless + // some other 400- or 500-class error code is more applicable), as + // described in section 3.2.4. In other words, knowledge of a + // subscription must exist in both the subscriber and the notifier to be + // valid, even if installed via a non-SUBSCRIBE mechanism. + // https://tools.ietf.org/html/rfc3265#section-3.2 + // + // NOTIFY requests are sent to inform subscribers of changes in state to + // which the subscriber has a subscription. Subscriptions are created + // using the SUBSCRIBE method. In legacy implementations, it is + // possible that other means of subscription creation have been used. + // However, this specification does not allow the creation of + // subscriptions except through SUBSCRIBE requests and (for backwards- + // compatibility) REFER requests [RFC3515]. + // https://tools.ietf.org/html/rfc6665#section-3.2 + { + var uas = new user_agents_1.NotifyUserAgentServer(this, message); + this.delegate.onNotify ? + this.delegate.onNotify(uas) : + this.replyStateless(message, { statusCode: 405 }); + } + break; + case Constants_1.C.OPTIONS: + // https://tools.ietf.org/html/rfc3261#section-11.2 + { + var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); + var acceptHeader = "Accept: " + acceptedBodyTypes.toString(); + this.replyStateless(message, { + statusCode: 200, + extraHeaders: [allowHeader, acceptHeader] + }); + } + break; + case Constants_1.C.REFER: + // https://tools.ietf.org/html/rfc3515#section-2.4.2 + { + var uas = new user_agents_1.ReferUserAgentServer(this, message); + this.delegate.onRefer ? + this.delegate.onRefer(uas) : + this.replyStateless(message, { statusCode: 405 }); + } + break; + case Constants_1.C.SUBSCRIBE: + // https://tools.ietf.org/html/rfc6665#section-4.2 + { + var uas = new user_agents_1.SubscribeUserAgentServer(this, message); + this.delegate.onSubscribe ? + this.delegate.onSubscribe(uas) : + uas.reject(); + } + break; + default: + throw new Error("Unexpected out of dialog request method " + message.method + "."); + } + return; + }; + /** + * Responses are first processed by the transport layer and then passed + * up to the transaction layer. The transaction layer performs its + * processing and then passes the response up to the TU. The majority + * of response processing in the TU is method specific. However, there + * are some general behaviors independent of the method. + * https://tools.ietf.org/html/rfc3261#section-8.1.3 + * @param message Incoming response message from transport layer. + */ + UserAgentCore.prototype.receiveResponseFromTransport = function (message) { + // 8.1.3.1 Transaction Layer Errors + // https://tools.ietf.org/html/rfc3261#section-8.1.3.1 + // Handled by transaction layer callbacks. + // 8.1.3.2 Unrecognized Responses + // https://tools.ietf.org/html/rfc3261#section-8.1.3.1 + // TODO + // 8.1.3.3 Vias + // https://tools.ietf.org/html/rfc3261#section-8.1.3.3 + if (message.getHeaders("via").length > 1) { + this.logger.warn("More than one Via header field present in the response, dropping"); + return; + } + // 8.1.3.4 Processing 3xx Responses + // https://tools.ietf.org/html/rfc3261#section-8.1.3.4 + // TODO + // 8.1.3.5 Processing 4xx Responses + // https://tools.ietf.org/html/rfc3261#section-8.1.3.5 + // TODO + // When the transport layer in the client receives a response, it has to + // determine which client transaction will handle the response, so that + // the processing of Sections 17.1.1 and 17.1.2 can take place. The + // branch parameter in the top Via header field is used for this + // purpose. A response matches a client transaction under two + // conditions: + // + // 1. If the response has the same value of the branch parameter in + // the top Via header field as the branch parameter in the top + // Via header field of the request that created the transaction. + // + // 2. If the method parameter in the CSeq header field matches the + // method of the request that created the transaction. The + // method is needed since a CANCEL request constitutes a + // different transaction, but shares the same value of the branch + // parameter. + // https://tools.ietf.org/html/rfc3261#section-17.1.3 + var userAgentClientId = message.viaBranch + message.method; + var userAgentClient = this.userAgentClients.get(userAgentClientId); + // The client transport uses the matching procedures of Section + // 17.1.3 to attempt to match the response to an existing + // transaction. If there is a match, the response MUST be passed to + // that transaction. Otherwise, any element other than a stateless + // proxy MUST silently discard the response. + // https://tools.ietf.org/html/rfc6026#section-8.9 + if (userAgentClient) { + userAgentClient.transaction.receiveResponse(message); + } + else { + this.logger.warn("Discarding unmatched " + message.statusCode + " response to " + message.method + " " + userAgentClientId + "."); + } + }; + return UserAgentCore; +}()); +exports.UserAgentCore = UserAgentCore; + + +/***/ }), +/* 80 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +function __export(m) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; +} +Object.defineProperty(exports, "__esModule", { value: true }); +__export(__webpack_require__(81)); +__export(__webpack_require__(83)); +__export(__webpack_require__(85)); +__export(__webpack_require__(86)); +__export(__webpack_require__(87)); +__export(__webpack_require__(102)); +__export(__webpack_require__(103)); +__export(__webpack_require__(104)); +__export(__webpack_require__(92)); +__export(__webpack_require__(93)); +__export(__webpack_require__(105)); +__export(__webpack_require__(94)); +__export(__webpack_require__(95)); +__export(__webpack_require__(96)); +__export(__webpack_require__(97)); +__export(__webpack_require__(101)); +__export(__webpack_require__(106)); +__export(__webpack_require__(98)); +__export(__webpack_require__(99)); +__export(__webpack_require__(107)); +__export(__webpack_require__(108)); +__export(__webpack_require__(109)); +__export(__webpack_require__(82)); +__export(__webpack_require__(84)); + + +/***/ }), +/* 81 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Constants_1 = __webpack_require__(3); +var transactions_1 = __webpack_require__(52); +var user_agent_client_1 = __webpack_require__(82); +var ByeUserAgentClient = /** @class */ (function (_super) { + __extends(ByeUserAgentClient, _super); + function ByeUserAgentClient(dialog, delegate, options) { + var _this = this; + var message = dialog.createOutgoingRequestMessage(Constants_1.C.BYE, options); + _this = _super.call(this, transactions_1.NonInviteClientTransaction, dialog.userAgentCore, message, delegate) || this; + dialog.dispose(); + return _this; + } + return ByeUserAgentClient; +}(user_agent_client_1.UserAgentClient)); +exports.ByeUserAgentClient = ByeUserAgentClient; + + +/***/ }), +/* 82 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +var Constants_1 = __webpack_require__(3); +var SIPMessage_1 = __webpack_require__(6); +var transactions_1 = __webpack_require__(52); +/* + * User Agent Client (UAC): A user agent client is a logical entity + * that creates a new request, and then uses the client + * transaction state machinery to send it. The role of UAC lasts + * only for the duration of that transaction. In other words, if + * a piece of software initiates a request, it acts as a UAC for + * the duration of that transaction. If it receives a request + * later, it assumes the role of a user agent server for the + * processing of that transaction. + * https://tools.ietf.org/html/rfc3261#section-6 + */ +var UserAgentClient = /** @class */ (function () { + function UserAgentClient(transactionConstructor, core, message, delegate) { + this.transactionConstructor = transactionConstructor; + this.core = core; + this.message = message; + this.delegate = delegate; + this.challenged = false; + this.stale = false; + this.logger = this.loggerFactory.getLogger("sip.user-agent-client"); + this.init(); + } + UserAgentClient.prototype.dispose = function () { + this.transaction.dispose(); + }; + Object.defineProperty(UserAgentClient.prototype, "loggerFactory", { + get: function () { + return this.core.loggerFactory; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(UserAgentClient.prototype, "transaction", { + /** The transaction associated with this request. */ + get: function () { + if (!this._transaction) { + throw new Error("Transaction undefined."); + } + return this._transaction; + }, + enumerable: true, + configurable: true + }); + /** + * Since requests other than INVITE are responded to immediately, sending a + * CANCEL for a non-INVITE request would always create a race condition. + * A CANCEL request SHOULD NOT be sent to cancel a request other than INVITE. + * https://tools.ietf.org/html/rfc3261#section-9.1 + * @param options Cancel options bucket. + */ + UserAgentClient.prototype.cancel = function (reason, options) { + var _this = this; + if (options === void 0) { options = {}; } + if (!this.transaction) { + throw new Error("Transaction undefined."); + } + if (!this.message.to) { + throw new Error("To undefined."); + } + if (!this.message.from) { + throw new Error("From undefined."); + } + // The following procedures are used to construct a CANCEL request. The + // Request-URI, Call-ID, To, the numeric part of CSeq, and From header + // fields in the CANCEL request MUST be identical to those in the + // request being cancelled, including tags. A CANCEL constructed by a + // client MUST have only a single Via header field value matching the + // top Via value in the request being cancelled. Using the same values + // for these header fields allows the CANCEL to be matched with the + // request it cancels (Section 9.2 indicates how such matching occurs). + // However, the method part of the CSeq header field MUST have a value + // of CANCEL. This allows it to be identified and processed as a + // transaction in its own right (See Section 17). + // https://tools.ietf.org/html/rfc3261#section-9.1 + var message = new SIPMessage_1.OutgoingRequest(Constants_1.C.CANCEL, this.message.ruri, this.message.ua, { + toUri: this.message.to.uri, + toTag: this.message.toTag, + fromUri: this.message.from.uri, + fromTag: this.message.fromTag, + callId: this.message.callId, + cseq: this.message.cseq + }, options.extraHeaders); + message.callId = this.message.callId; + message.cseq = this.message.cseq; + // TODO: Revisit this. + // The CANCEL needs to use the same branch parameter so that + // it matches the INVITE transaction, but this is a hacky way to do this. + // Or at the very least not well documented. If the the branch parameter + // is set on the outgoing request, the transaction will use it. + // Otherwise the transaction will make a new one. + message.branch = this.message.branch; + if (this.message.headers.Route) { + message.headers.Route = this.message.headers.Route; + } + if (reason) { + message.setHeader("Reason", reason); + } + // If no provisional response has been received, the CANCEL request MUST + // NOT be sent; rather, the client MUST wait for the arrival of a + // provisional response before sending the request. If the original + // request has generated a final response, the CANCEL SHOULD NOT be + // sent, as it is an effective no-op, since CANCEL has no effect on + // requests that have already generated a final response. + // https://tools.ietf.org/html/rfc3261#section-9.1 + if (this.transaction.state === transactions_1.TransactionState.Proceeding) { + var uac = new UserAgentClient(transactions_1.NonInviteClientTransaction, this.core, message); + } + else { + this.transaction.once("stateChanged", function () { + if (_this.transaction && _this.transaction.state === transactions_1.TransactionState.Proceeding) { + var uac = new UserAgentClient(transactions_1.NonInviteClientTransaction, _this.core, message); + } + }); + } + return message; + }; + /** + * If a 401 (Unauthorized) or 407 (Proxy Authentication Required) + * response is received, the UAC SHOULD follow the authorization + * procedures of Section 22.2 and Section 22.3 to retry the request with + * credentials. + * https://tools.ietf.org/html/rfc3261#section-8.1.3.5 + * 22 Usage of HTTP Authentication + * https://tools.ietf.org/html/rfc3261#section-22 + * 22.1 Framework + * https://tools.ietf.org/html/rfc3261#section-22.1 + * 22.2 User-to-User Authentication + * https://tools.ietf.org/html/rfc3261#section-22.2 + * 22.3 Proxy-to-User Authentication + * https://tools.ietf.org/html/rfc3261#section-22.3 + * + * FIXME: This "guard for and retry the request with credentials" + * implementation is not complete and at best minimally passable. + * @param response The incoming response to guard. + * @returns True if the program execution is to continue in the branch in question. + * Otherwise the request is retried with credentials and current request processing must stop. + */ + UserAgentClient.prototype.authenticationGuard = function (message) { + var statusCode = message.statusCode; + if (!statusCode) { + throw new Error("Response status code undefined."); + } + // If a 401 (Unauthorized) or 407 (Proxy Authentication Required) + // response is received, the UAC SHOULD follow the authorization + // procedures of Section 22.2 and Section 22.3 to retry the request with + // credentials. + // https://tools.ietf.org/html/rfc3261#section-8.1.3.5 + if (statusCode !== 401 && statusCode !== 407) { + return true; + } + // Get and parse the appropriate WWW-Authenticate or Proxy-Authenticate header. + var challenge; + var authorizationHeaderName; + if (statusCode === 401) { + challenge = message.parseHeader("www-authenticate"); + authorizationHeaderName = "authorization"; + } + else { + challenge = message.parseHeader("proxy-authenticate"); + authorizationHeaderName = "proxy-authorization"; + } + // Verify it seems a valid challenge. + if (!challenge) { + this.logger.warn(statusCode + " with wrong or missing challenge, cannot authenticate"); + return true; + } + // Avoid infinite authentications. + if (this.challenged && (this.stale || challenge.stale !== true)) { + this.logger.warn(statusCode + " apparently in authentication loop, cannot authenticate"); + return true; + } + // Get credentials. + if (!this.credentials) { + this.credentials = this.core.configuration.authenticationFactory(); + if (!this.credentials) { + this.logger.warn("Unable to obtain credentials, cannot authenticate"); + return true; + } + } + // Verify that the challenge is really valid. + if (!this.credentials.authenticate(this.message, challenge)) { + return true; + } + this.challenged = true; + if (challenge.stale) { + this.stale = true; + } + var cseq = this.message.cseq += 1; + this.message.setHeader("cseq", cseq + " " + this.message.method); + this.message.setHeader(authorizationHeaderName, this.credentials.toString()); + // Calling init (again) will swap out our existing client transaction with a new one. + // FIXME: HACK: An assumption is being made here that there is nothing that needs to + // be cleaned up beyond the client transaction which is being replaced. For example, + // it is assumed that no early dialogs have been created. + this.init(); + return false; + }; + /** + * Receive a response from the transaction layer. + * @param message Incoming response message. + */ + UserAgentClient.prototype.receiveResponse = function (message) { + if (!this.authenticationGuard(message)) { + return; + } + var statusCode = message.statusCode ? message.statusCode.toString() : ""; + if (!statusCode) { + throw new Error("Response status code undefined."); + } + switch (true) { + case /^100$/.test(statusCode): + if (this.delegate && this.delegate.onTrying) { + this.delegate.onTrying({ message: message }); + } + break; + case /^1[0-9]{2}$/.test(statusCode): + if (this.delegate && this.delegate.onProgress) { + this.delegate.onProgress({ message: message }); + } + break; + case /^2[0-9]{2}$/.test(statusCode): + if (this.delegate && this.delegate.onAccept) { + this.delegate.onAccept({ message: message }); + } + break; + case /^3[0-9]{2}$/.test(statusCode): + if (this.delegate && this.delegate.onRedirect) { + this.delegate.onRedirect({ message: message }); + } + break; + case /^[4-6][0-9]{2}$/.test(statusCode): + if (this.delegate && this.delegate.onReject) { + this.delegate.onReject({ message: message }); + } + break; + default: + throw new Error("Invalid status code " + statusCode); + } + }; + UserAgentClient.prototype.init = function () { + var _this = this; + // We are the transaction user. + var user = { + loggerFactory: this.loggerFactory, + onRequestTimeout: function () { return _this.onRequestTimeout(); }, + onStateChange: function (newState) { + if (newState === transactions_1.TransactionState.Terminated) { + // Remove the terminated transaction from the core. + _this.core.userAgentClients.delete(userAgentClientId); + // FIXME: HACK: Our transaction may have been swapped out with a new one + // post authentication (see above), so make sure to only to dispose of + // ourselves if this terminating transaction is our current transaction. + if (transaction === _this._transaction) { + _this.dispose(); + } + } + }, + onTransportError: function (error) { return _this.onTransportError(error); }, + receiveResponse: function (message) { return _this.receiveResponse(message); } + }; + // Create a new transaction with us as the user. + var transaction = new this.transactionConstructor(this.message, this.core.transport, user); + this._transaction = transaction; + // Add the new transaction to the core. + var userAgentClientId = transaction.id + transaction.request.method; + this.core.userAgentClients.set(userAgentClientId, this); + }; + /** + * 8.1.3.1 Transaction Layer Errors + * In some cases, the response returned by the transaction layer will + * not be a SIP message, but rather a transaction layer error. When a + * timeout error is received from the transaction layer, it MUST be + * treated as if a 408 (Request Timeout) status code has been received. + * If a fatal transport error is reported by the transport layer + * (generally, due to fatal ICMP errors in UDP or connection failures in + * TCP), the condition MUST be treated as a 503 (Service Unavailable) + * status code. + * https://tools.ietf.org/html/rfc3261#section-8.1.3.1 + */ + UserAgentClient.prototype.onRequestTimeout = function () { + this.logger.warn("User agent client request timed out. Generating internal 408 Request Timeout."); + var message = this.core.configuration.onRequestTimeoutResponseMessageFactory(); + this.receiveResponse(message); + return; + }; + /** + * 8.1.3.1 Transaction Layer Errors + * In some cases, the response returned by the transaction layer will + * not be a SIP message, but rather a transaction layer error. When a + * timeout error is received from the transaction layer, it MUST be + * treated as if a 408 (Request Timeout) status code has been received. + * If a fatal transport error is reported by the transport layer + * (generally, due to fatal ICMP errors in UDP or connection failures in + * TCP), the condition MUST be treated as a 503 (Service Unavailable) + * status code. + * https://tools.ietf.org/html/rfc3261#section-8.1.3.1 + */ + UserAgentClient.prototype.onTransportError = function (error) { + this.logger.error(error.message); + this.logger.error("User agent client request transport error. Generating internal 503 Service Unavailable."); + var message = this.core.configuration.onTransportErrorResponseMessageFactory(); + this.receiveResponse(message); + }; + return UserAgentClient; +}()); +exports.UserAgentClient = UserAgentClient; + + +/***/ }), +/* 83 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var transactions_1 = __webpack_require__(52); +var user_agent_server_1 = __webpack_require__(84); +var ByeUserAgentServer = /** @class */ (function (_super) { + __extends(ByeUserAgentServer, _super); + function ByeUserAgentServer(dialog, message, delegate) { + return _super.call(this, transactions_1.NonInviteServerTransaction, dialog.userAgentCore, message, delegate) || this; + } + return ByeUserAgentServer; +}(user_agent_server_1.UserAgentServer)); +exports.ByeUserAgentServer = ByeUserAgentServer; + + +/***/ }), +/* 84 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +var Exceptions_1 = __webpack_require__(47); +var Utils_1 = __webpack_require__(11); +var messages_1 = __webpack_require__(63); +var transactions_1 = __webpack_require__(52); +/** + * User Agent Server (UAS): A user agent server is a logical entity + * that generates a response to a SIP request. The response + * accepts, rejects, or redirects the request. This role lasts + * only for the duration of that transaction. In other words, if + * a piece of software responds to a request, it acts as a UAS for + * the duration of that transaction. If it generates a request + * later, it assumes the role of a user agent client for the + * processing of that transaction. + * https://tools.ietf.org/html/rfc3261#section-6 + */ +var UserAgentServer = /** @class */ (function () { + function UserAgentServer(transactionConstructor, core, message, delegate) { + this.transactionConstructor = transactionConstructor; + this.core = core; + this.message = message; + this.delegate = delegate; + this.logger = this.loggerFactory.getLogger("sip.user-agent-server"); + this.toTag = message.toTag ? message.toTag : Utils_1.Utils.newTag(); + this.init(); + } + UserAgentServer.prototype.dispose = function () { + this.transaction.dispose(); + }; + Object.defineProperty(UserAgentServer.prototype, "loggerFactory", { + get: function () { + return this.core.loggerFactory; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(UserAgentServer.prototype, "transaction", { + /** The transaction associated with this request. */ + get: function () { + if (!this._transaction) { + throw new Error("Transaction undefined."); + } + return this._transaction; + }, + enumerable: true, + configurable: true + }); + UserAgentServer.prototype.accept = function (options) { + if (options === void 0) { options = { statusCode: 200 }; } + if (!this.acceptable) { + throw new Exceptions_1.Exceptions.TransactionStateError(this.message.method + " not acceptable in state " + this.transaction.state + "."); + } + var statusCode = options.statusCode; + if (statusCode < 200 || statusCode > 299) { + throw new TypeError("Invalid statusCode: " + statusCode); + } + var response = this.reply(options); + return response; + }; + UserAgentServer.prototype.progress = function (options) { + if (options === void 0) { options = { statusCode: 180 }; } + if (!this.progressable) { + throw new Exceptions_1.Exceptions.TransactionStateError(this.message.method + " not progressable in state " + this.transaction.state + "."); + } + var statusCode = options.statusCode; + if (statusCode < 101 || statusCode > 199) { + throw new TypeError("Invalid statusCode: " + statusCode); + } + var response = this.reply(options); + return response; + }; + UserAgentServer.prototype.redirect = function (contacts, options) { + if (options === void 0) { options = { statusCode: 302 }; } + if (!this.redirectable) { + throw new Exceptions_1.Exceptions.TransactionStateError(this.message.method + " not redirectable in state " + this.transaction.state + "."); + } + var statusCode = options.statusCode; + if (statusCode < 300 || statusCode > 399) { + throw new TypeError("Invalid statusCode: " + statusCode); + } + var contactHeaders = new Array(); + contacts.forEach(function (contact) { return contactHeaders.push("Contact: " + contact.toString()); }); + options.extraHeaders = (options.extraHeaders || []).concat(contactHeaders); + var response = this.reply(options); + return response; + }; + UserAgentServer.prototype.reject = function (options) { + if (options === void 0) { options = { statusCode: 480 }; } + if (!this.rejectable) { + throw new Exceptions_1.Exceptions.TransactionStateError(this.message.method + " not rejectable in state " + this.transaction.state + "."); + } + var statusCode = options.statusCode; + if (statusCode < 400 || statusCode > 699) { + throw new TypeError("Invalid statusCode: " + statusCode); + } + var response = this.reply(options); + return response; + }; + UserAgentServer.prototype.trying = function (options) { + if (!this.tryingable) { + throw new Exceptions_1.Exceptions.TransactionStateError(this.message.method + " not tryingable in state " + this.transaction.state + "."); + } + var response = this.reply({ statusCode: 100 }); + return response; + }; + /** + * If the UAS did not find a matching transaction for the CANCEL + * according to the procedure above, it SHOULD respond to the CANCEL + * with a 481 (Call Leg/Transaction Does Not Exist). If the transaction + * for the original request still exists, the behavior of the UAS on + * receiving a CANCEL request depends on whether it has already sent a + * final response for the original request. If it has, the CANCEL + * request has no effect on the processing of the original request, no + * effect on any session state, and no effect on the responses generated + * for the original request. If the UAS has not issued a final response + * for the original request, its behavior depends on the method of the + * original request. If the original request was an INVITE, the UAS + * SHOULD immediately respond to the INVITE with a 487 (Request + * Terminated). A CANCEL request has no impact on the processing of + * transactions with any other method defined in this specification. + * https://tools.ietf.org/html/rfc3261#section-9.2 + * @param request Incoming CANCEL request. + */ + UserAgentServer.prototype.receiveCancel = function (message) { + // Note: Currently CANCEL is being handled as a special case. + // No UAS is created to handle the CANCEL and the response to + // it CANCEL is being handled statelessly by the user agent core. + // As such, there is currently no way to externally impact the + // response to the a CANCEL request. + if (this.delegate && this.delegate.onCancel) { + this.delegate.onCancel(message); + } + }; + Object.defineProperty(UserAgentServer.prototype, "acceptable", { + get: function () { + if (this.transaction instanceof transactions_1.InviteServerTransaction) { + return (this.transaction.state === transactions_1.TransactionState.Proceeding || + this.transaction.state === transactions_1.TransactionState.Accepted); + } + if (this.transaction instanceof transactions_1.NonInviteServerTransaction) { + return (this.transaction.state === transactions_1.TransactionState.Trying || + this.transaction.state === transactions_1.TransactionState.Proceeding); + } + throw new Error("Unknown transaction type."); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(UserAgentServer.prototype, "progressable", { + get: function () { + if (this.transaction instanceof transactions_1.InviteServerTransaction) { + return this.transaction.state === transactions_1.TransactionState.Proceeding; + } + if (this.transaction instanceof transactions_1.NonInviteServerTransaction) { + return false; // https://tools.ietf.org/html/rfc4320#section-4.1 + } + throw new Error("Unknown transaction type."); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(UserAgentServer.prototype, "redirectable", { + get: function () { + if (this.transaction instanceof transactions_1.InviteServerTransaction) { + return this.transaction.state === transactions_1.TransactionState.Proceeding; + } + if (this.transaction instanceof transactions_1.NonInviteServerTransaction) { + return (this.transaction.state === transactions_1.TransactionState.Trying || + this.transaction.state === transactions_1.TransactionState.Proceeding); + } + throw new Error("Unknown transaction type."); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(UserAgentServer.prototype, "rejectable", { + get: function () { + if (this.transaction instanceof transactions_1.InviteServerTransaction) { + return this.transaction.state === transactions_1.TransactionState.Proceeding; + } + if (this.transaction instanceof transactions_1.NonInviteServerTransaction) { + return (this.transaction.state === transactions_1.TransactionState.Trying || + this.transaction.state === transactions_1.TransactionState.Proceeding); + } + throw new Error("Unknown transaction type."); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(UserAgentServer.prototype, "tryingable", { + get: function () { + if (this.transaction instanceof transactions_1.InviteServerTransaction) { + return this.transaction.state === transactions_1.TransactionState.Proceeding; + } + if (this.transaction instanceof transactions_1.NonInviteServerTransaction) { + return this.transaction.state === transactions_1.TransactionState.Trying; + } + throw new Error("Unknown transaction type."); + }, + enumerable: true, + configurable: true + }); + /** + * When a UAS wishes to construct a response to a request, it follows + * the general procedures detailed in the following subsections. + * Additional behaviors specific to the response code in question, which + * are not detailed in this section, may also be required. + * + * Once all procedures associated with the creation of a response have + * been completed, the UAS hands the response back to the server + * transaction from which it received the request. + * https://tools.ietf.org/html/rfc3261#section-8.2.6 + * @param statusCode Status code to reply with. + * @param options Reply options bucket. + */ + UserAgentServer.prototype.reply = function (options) { + if (!options.toTag && options.statusCode !== 100) { + options.toTag = this.toTag; + } + options.userAgent = options.userAgent || this.core.configuration.userAgentHeaderFieldValue; + var response = messages_1.constructOutgoingResponse(this.message, options); + this.transaction.receiveResponse(options.statusCode, response.message); + return response; + }; + UserAgentServer.prototype.init = function () { + var _this = this; + // We are the transaction user. + var user = { + loggerFactory: this.loggerFactory, + onStateChange: function (newState) { + if (newState === transactions_1.TransactionState.Terminated) { + // Remove the terminated transaction from the core. + _this.core.userAgentServers.delete(userAgentServerId); + _this.dispose(); + } + }, + onTransportError: function (error) { + _this.logger.error(error.message); + if (_this.delegate && _this.delegate.onTransportError) { + _this.delegate.onTransportError(error); + } + else { + _this.logger.error("User agent server response transport error."); + } + } + }; + // Create a new transaction with us as the user. + var transaction = new this.transactionConstructor(this.message, this.core.transport, user); + this._transaction = transaction; + // Add the new transaction to the core. + var userAgentServerId = transaction.id; + this.core.userAgentServers.set(transaction.id, this); + }; + return UserAgentServer; +}()); +exports.UserAgentServer = UserAgentServer; + + +/***/ }), +/* 85 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var transactions_1 = __webpack_require__(52); +var user_agent_client_1 = __webpack_require__(82); +var CancelUserAgentClient = /** @class */ (function (_super) { + __extends(CancelUserAgentClient, _super); + function CancelUserAgentClient(core, message, delegate) { + return _super.call(this, transactions_1.NonInviteClientTransaction, core, message, delegate) || this; + } + return CancelUserAgentClient; +}(user_agent_client_1.UserAgentClient)); +exports.CancelUserAgentClient = CancelUserAgentClient; + + +/***/ }), +/* 86 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var transactions_1 = __webpack_require__(52); +var user_agent_server_1 = __webpack_require__(84); +var InfoUserAgentServer = /** @class */ (function (_super) { + __extends(InfoUserAgentServer, _super); + function InfoUserAgentServer(dialog, message, delegate) { + return _super.call(this, transactions_1.NonInviteServerTransaction, dialog.userAgentCore, message, delegate) || this; + } + return InfoUserAgentServer; +}(user_agent_server_1.UserAgentServer)); +exports.InfoUserAgentServer = InfoUserAgentServer; + + +/***/ }), +/* 87 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var dialogs_1 = __webpack_require__(88); +var transactions_1 = __webpack_require__(52); +var user_agent_client_1 = __webpack_require__(82); +/** + * 13 Initiating a Session + * https://tools.ietf.org/html/rfc3261#section-13 + * 13.1 Overview + * https://tools.ietf.org/html/rfc3261#section-13.1 + * 13.2 UAC Processing + * https://tools.ietf.org/html/rfc3261#section-13.2 + */ +var InviteUserAgentClient = /** @class */ (function (_super) { + __extends(InviteUserAgentClient, _super); + function InviteUserAgentClient(core, message, delegate) { + var _this = _super.call(this, transactions_1.InviteClientTransaction, core, message, delegate) || this; + _this.confirmedDialogAcks = new Map(); + _this.confirmedDialogs = new Map(); + _this.earlyDialogs = new Map(); + _this.delegate = delegate; + return _this; + } + InviteUserAgentClient.prototype.dispose = function () { + // The UAC core considers the INVITE transaction completed 64*T1 seconds + // after the reception of the first 2xx response. At this point all the + // early dialogs that have not transitioned to established dialogs are + // terminated. Once the INVITE transaction is considered completed by + // the UAC core, no more new 2xx responses are expected to arrive. + // + // If, after acknowledging any 2xx response to an INVITE, the UAC does + // not want to continue with that dialog, then the UAC MUST terminate + // the dialog by sending a BYE request as described in Section 15. + // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 + this.earlyDialogs.forEach(function (earlyDialog) { return earlyDialog.dispose(); }); + this.earlyDialogs.clear(); + _super.prototype.dispose.call(this); + }; + /** + * Once the INVITE has been passed to the INVITE client transaction, the + * UAC waits for responses for the INVITE. + * https://tools.ietf.org/html/rfc3261#section-13.2.2 + * @param incomingResponse Incoming response to INVITE request. + */ + InviteUserAgentClient.prototype.receiveResponse = function (message) { + var _this = this; + if (!this.authenticationGuard(message)) { + return; + } + var statusCode = message.statusCode ? message.statusCode.toString() : ""; + if (!statusCode) { + throw new Error("Response status code undefined."); + } + switch (true) { + case /^100$/.test(statusCode): + if (this.delegate && this.delegate.onTrying) { + this.delegate.onTrying({ message: message }); + } + return; + case /^1[0-9]{2}$/.test(statusCode): + // Zero, one or multiple provisional responses may arrive before one or + // more final responses are received. Provisional responses for an + // INVITE request can create "early dialogs". If a provisional response + // has a tag in the To field, and if the dialog ID of the response does + // not match an existing dialog, one is constructed using the procedures + // defined in Section 12.1.2. + // + // The early dialog will only be needed if the UAC needs to send a + // request to its peer within the dialog before the initial INVITE + // transaction completes. Header fields present in a provisional + // response are applicable as long as the dialog is in the early state + // (for example, an Allow header field in a provisional response + // contains the methods that can be used in the dialog while this is in + // the early state). + // https://tools.ietf.org/html/rfc3261#section-13.2.2.1 + { + // Provisional without to tag, no dialog to create. + if (!message.toTag) { + this.logger.warn("Non-100 1xx INVITE response received without a to tag, dropping."); + return; + } + // Compute dialog state. + var dialogState = dialogs_1.Dialog.initialDialogStateForUserAgentClient(this.message, message); + // Have existing early dialog or create a new one. + var earlyDialog = this.earlyDialogs.get(dialogState.id); + if (!earlyDialog) { + var transaction = this.transaction; + if (!(transaction instanceof transactions_1.InviteClientTransaction)) { + throw new Error("Transaction not instance of InviteClientTransaction."); + } + earlyDialog = new dialogs_1.SessionDialog(transaction, this.core, dialogState); + this.earlyDialogs.set(earlyDialog.id, earlyDialog); + } + // Guard against out of order reliable provisional responses. + // Note that this is where the rseq tracking is done. + if (!earlyDialog.reliableSequenceGuard(message)) { + this.logger.warn("1xx INVITE reliable response received out of order, dropping."); + return; + } + // Update dialog signaling state if need be. + earlyDialog.signalingStateTransition(message); + // Pass response to delegate. + var session_1 = earlyDialog; + if (this.delegate && this.delegate.onProgress) { + this.delegate.onProgress({ + message: message, + session: session_1, + prack: function (options) { + var outgoingPrackRequest = session_1.prack(undefined, options); + return outgoingPrackRequest; + } + }); + } + } + return; + case /^2[0-9]{2}$/.test(statusCode): + // Multiple 2xx responses may arrive at the UAC for a single INVITE + // request due to a forking proxy. Each response is distinguished by + // the tag parameter in the To header field, and each represents a + // distinct dialog, with a distinct dialog identifier. + // + // If the dialog identifier in the 2xx response matches the dialog + // identifier of an existing dialog, the dialog MUST be transitioned to + // the "confirmed" state, and the route set for the dialog MUST be + // recomputed based on the 2xx response using the procedures of Section + // 12.2.1.2. Otherwise, a new dialog in the "confirmed" state MUST be + // constructed using the procedures of Section 12.1.2. + // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 + { + // Compute dialog state. + var dialogState = dialogs_1.Dialog.initialDialogStateForUserAgentClient(this.message, message); + // NOTE: Currently our transaction layer is caching the 2xx ACKs and + // handling retransmissions of the ACK which is an approach which is + // not to spec. In any event, this block is intended to provide a to + // spec implementation of ACK retransmissions, but it should not be + // hit currently. + var dialog = this.confirmedDialogs.get(dialogState.id); + if (dialog) { + // Once the ACK has been constructed, the procedures of [4] are used to + // determine the destination address, port and transport. However, the + // request is passed to the transport layer directly for transmission, + // rather than a client transaction. This is because the UAC core + // handles retransmissions of the ACK, not the transaction layer. The + // ACK MUST be passed to the client transport every time a + // retransmission of the 2xx final response that triggered the ACK + // arrives. + // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 + var outgoingAckRequest = this.confirmedDialogAcks.get(dialogState.id); + if (outgoingAckRequest) { + var transaction = this.transaction; + if (!(transaction instanceof transactions_1.InviteClientTransaction)) { + throw new Error("Client transaction not instance of InviteClientTransaction."); + } + transaction.ackResponse(outgoingAckRequest.message); + } + else { + // If still waiting for an ACK, drop the retransmission of the 2xx final response. + } + return; + } + // If the dialog identifier in the 2xx response matches the dialog + // identifier of an existing dialog, the dialog MUST be transitioned to + // the "confirmed" state, and the route set for the dialog MUST be + // recomputed based on the 2xx response using the procedures of Section + // 12.2.1.2. Otherwise, a new dialog in the "confirmed" state MUST be + // constructed using the procedures of Section 12.1.2. + // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 + dialog = this.earlyDialogs.get(dialogState.id); + if (dialog) { + dialog.confirm(); + dialog.recomputeRouteSet(message); + this.earlyDialogs.delete(dialog.id); + this.confirmedDialogs.set(dialog.id, dialog); + } + else { + var transaction = this.transaction; + if (!(transaction instanceof transactions_1.InviteClientTransaction)) { + throw new Error("Transaction not instance of InviteClientTransaction."); + } + dialog = new dialogs_1.SessionDialog(transaction, this.core, dialogState); + this.confirmedDialogs.set(dialog.id, dialog); + } + // Update dialog signaling state if need be. + dialog.signalingStateTransition(message); + // Session Initiated! :) + var session_2 = dialog; + // The UAC core MUST generate an ACK request for each 2xx received from + // the transaction layer. The header fields of the ACK are constructed + // in the same way as for any request sent within a dialog (see Section + // 12) with the exception of the CSeq and the header fields related to + // authentication. The sequence number of the CSeq header field MUST be + // the same as the INVITE being acknowledged, but the CSeq method MUST + // be ACK. The ACK MUST contain the same credentials as the INVITE. If + // the 2xx contains an offer (based on the rules above), the ACK MUST + // carry an answer in its body. If the offer in the 2xx response is not + // acceptable, the UAC core MUST generate a valid answer in the ACK and + // then send a BYE immediately. + // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 + if (this.delegate && this.delegate.onAccept) { + this.delegate.onAccept({ + message: message, + session: session_2, + ack: function (options) { + var outgoingAckRequest = session_2.ack(options); + _this.confirmedDialogAcks.set(session_2.id, outgoingAckRequest); + return outgoingAckRequest; + } + }); + } + else { + var outgoingAckRequest = session_2.ack(); + this.confirmedDialogAcks.set(session_2.id, outgoingAckRequest); + } + } + return; + case /^3[0-9]{2}$/.test(statusCode): + // 12.3 Termination of a Dialog + // + // Independent of the method, if a request outside of a dialog generates + // a non-2xx final response, any early dialogs created through + // provisional responses to that request are terminated. The mechanism + // for terminating confirmed dialogs is method specific. In this + // specification, the BYE method terminates a session and the dialog + // associated with it. See Section 15 for details. + // https://tools.ietf.org/html/rfc3261#section-12.3 + // All early dialogs are considered terminated upon reception of the + // non-2xx final response. + // + // After having received the non-2xx final response the UAC core + // considers the INVITE transaction completed. The INVITE client + // transaction handles the generation of ACKs for the response (see + // Section 17). + // https://tools.ietf.org/html/rfc3261#section-13.2.2.3 + this.earlyDialogs.forEach(function (earlyDialog) { return earlyDialog.dispose(); }); + this.earlyDialogs.clear(); + // A 3xx response may contain one or more Contact header field values + // providing new addresses where the callee might be reachable. + // Depending on the status code of the 3xx response (see Section 21.3), + // the UAC MAY choose to try those new addresses. + // https://tools.ietf.org/html/rfc3261#section-13.2.2.2 + if (this.delegate && this.delegate.onRedirect) { + this.delegate.onRedirect({ message: message }); + } + return; + case /^[4-6][0-9]{2}$/.test(statusCode): + // 12.3 Termination of a Dialog + // + // Independent of the method, if a request outside of a dialog generates + // a non-2xx final response, any early dialogs created through + // provisional responses to that request are terminated. The mechanism + // for terminating confirmed dialogs is method specific. In this + // specification, the BYE method terminates a session and the dialog + // associated with it. See Section 15 for details. + // https://tools.ietf.org/html/rfc3261#section-12.3 + // All early dialogs are considered terminated upon reception of the + // non-2xx final response. + // + // After having received the non-2xx final response the UAC core + // considers the INVITE transaction completed. The INVITE client + // transaction handles the generation of ACKs for the response (see + // Section 17). + // https://tools.ietf.org/html/rfc3261#section-13.2.2.3 + this.earlyDialogs.forEach(function (earlyDialog) { return earlyDialog.dispose(); }); + this.earlyDialogs.clear(); + // A single non-2xx final response may be received for the INVITE. 4xx, + // 5xx and 6xx responses may contain a Contact header field value + // indicating the location where additional information about the error + // can be found. Subsequent final responses (which would only arrive + // under error conditions) MUST be ignored. + // https://tools.ietf.org/html/rfc3261#section-13.2.2.3 + if (this.delegate && this.delegate.onReject) { + this.delegate.onReject({ message: message }); + } + return; + default: + throw new Error("Invalid status code " + statusCode); + } + throw new Error("Executing what should be an unreachable code path receiving " + statusCode + " response."); + }; + return InviteUserAgentClient; +}(user_agent_client_1.UserAgentClient)); +exports.InviteUserAgentClient = InviteUserAgentClient; + + +/***/ }), +/* 88 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +function __export(m) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; +} +Object.defineProperty(exports, "__esModule", { value: true }); +__export(__webpack_require__(89)); +__export(__webpack_require__(90)); +__export(__webpack_require__(100)); + + +/***/ }), +/* 89 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +var Constants_1 = __webpack_require__(3); +var NameAddrHeader_1 = __webpack_require__(9); +/** + * A key concept for a user agent is that of a dialog. A dialog + * represents a peer-to-peer SIP relationship between two user agents + * that persists for some time. The dialog facilitates sequencing of + * messages between the user agents and proper routing of requests + * between both of them. The dialog represents a context in which to + * interpret SIP messages. + * https://tools.ietf.org/html/rfc3261#section-12 + */ +var Dialog = /** @class */ (function () { + /** + * Dialog constructor. + * @param core User agent core. + * @param dialogState Initial dialog state. + */ + function Dialog(core, dialogState) { + this.core = core; + this.dialogState = dialogState; + this.core.dialogs.set(this.id, this); + } + /** + * When a UAC receives a response that establishes a dialog, it + * constructs the state of the dialog. This state MUST be maintained + * for the duration of the dialog. + * https://tools.ietf.org/html/rfc3261#section-12.1.2 + * @param outgoingRequestMessage Outgoing request message for dialog. + * @param incomingResponseMessage Incoming response message creating dialog. + */ + Dialog.initialDialogStateForUserAgentClient = function (outgoingRequestMessage, incomingResponseMessage) { + // If the request was sent over TLS, and the Request-URI contained a + // SIPS URI, the "secure" flag is set to TRUE. + // https://tools.ietf.org/html/rfc3261#section-12.1.2 + var secure = false; // FIXME: Currently no support for TLS. + // The route set MUST be set to the list of URIs in the Record-Route + // header field from the response, taken in reverse order and preserving + // all URI parameters. If no Record-Route header field is present in + // the response, the route set MUST be set to the empty set. This route + // set, even if empty, overrides any pre-existing route set for future + // requests in this dialog. The remote target MUST be set to the URI + // from the Contact header field of the response. + // https://tools.ietf.org/html/rfc3261#section-12.1.2 + var routeSet = incomingResponseMessage.getHeaders("record-route").reverse(); + var contact = incomingResponseMessage.parseHeader("contact"); + if (!contact) { // TODO: Review to make sure this will never happen + throw new Error("Contact undefined."); + } + if (!(contact instanceof NameAddrHeader_1.NameAddrHeader)) { + throw new Error("Contact not instance of NameAddrHeader."); + } + var remoteTarget = contact.uri; + // The local sequence number MUST be set to the value of the sequence + // number in the CSeq header field of the request. The remote sequence + // number MUST be empty (it is established when the remote UA sends a + // request within the dialog). The call identifier component of the + // dialog ID MUST be set to the value of the Call-ID in the request. + // The local tag component of the dialog ID MUST be set to the tag in + // the From field in the request, and the remote tag component of the + // dialog ID MUST be set to the tag in the To field of the response. A + // UAC MUST be prepared to receive a response without a tag in the To + // field, in which case the tag is considered to have a value of null. + // + // This is to maintain backwards compatibility with RFC 2543, which + // did not mandate To tags. + // + // https://tools.ietf.org/html/rfc3261#section-12.1.2 + var localSequenceNumber = outgoingRequestMessage.cseq; + var remoteSequenceNumber = undefined; + var callId = outgoingRequestMessage.callId; + var localTag = outgoingRequestMessage.fromTag; + var remoteTag = incomingResponseMessage.toTag; + if (!callId) { // TODO: Review to make sure this will never happen + throw new Error("Call id undefined."); + } + if (!localTag) { // TODO: Review to make sure this will never happen + throw new Error("From tag undefined."); + } + if (!remoteTag) { // TODO: Review to make sure this will never happen + throw new Error("To tag undefined."); // FIXME: No backwards compatibility with RFC 2543 + } + // The remote URI MUST be set to the URI in the To field, and the local + // URI MUST be set to the URI in the From field. + // https://tools.ietf.org/html/rfc3261#section-12.1.2 + if (!outgoingRequestMessage.from) { // TODO: Review to make sure this will never happen + throw new Error("From undefined."); + } + if (!outgoingRequestMessage.to) { // TODO: Review to make sure this will never happen + throw new Error("To undefined."); + } + var localURI = outgoingRequestMessage.from.uri; + var remoteURI = outgoingRequestMessage.to.uri; + // A dialog can also be in the "early" state, which occurs when it is + // created with a provisional response, and then transition to the + // "confirmed" state when a 2xx final response arrives. + // https://tools.ietf.org/html/rfc3261#section-12 + if (!incomingResponseMessage.statusCode) { + throw new Error("Incoming response status code undefined."); + } + var early = incomingResponseMessage.statusCode < 200 ? true : false; + var dialogState = { + id: callId + localTag + remoteTag, + early: early, + callId: callId, + localTag: localTag, + remoteTag: remoteTag, + localSequenceNumber: localSequenceNumber, + remoteSequenceNumber: remoteSequenceNumber, + localURI: localURI, + remoteURI: remoteURI, + remoteTarget: remoteTarget, + routeSet: routeSet, + secure: secure + }; + return dialogState; + }; + /** + * The UAS then constructs the state of the dialog. This state MUST be + * maintained for the duration of the dialog. + * https://tools.ietf.org/html/rfc3261#section-12.1.1 + * @param incomingRequestMessage Incoming request message creating dialog. + * @param toTag Tag in the To field in the response to the incoming request. + */ + Dialog.initialDialogStateForUserAgentServer = function (incomingRequestMessage, toTag, early) { + if (early === void 0) { early = false; } + // If the request arrived over TLS, and the Request-URI contained a SIPS + // URI, the "secure" flag is set to TRUE. + // https://tools.ietf.org/html/rfc3261#section-12.1.1 + var secure = false; // FIXME: Currently no support for TLS. + // The route set MUST be set to the list of URIs in the Record-Route + // header field from the request, taken in order and preserving all URI + // parameters. If no Record-Route header field is present in the + // request, the route set MUST be set to the empty set. This route set, + // even if empty, overrides any pre-existing route set for future + // requests in this dialog. The remote target MUST be set to the URI + // from the Contact header field of the request. + // https://tools.ietf.org/html/rfc3261#section-12.1.1 + var routeSet = incomingRequestMessage.getHeaders("record-route"); + var contact = incomingRequestMessage.parseHeader("contact"); + if (!contact) { // TODO: Review to make sure this will never happen + throw new Error("Contact undefined."); + } + if (!(contact instanceof NameAddrHeader_1.NameAddrHeader)) { + throw new Error("Contact not instance of NameAddrHeader."); + } + var remoteTarget = contact.uri; + // The remote sequence number MUST be set to the value of the sequence + // number in the CSeq header field of the request. The local sequence + // number MUST be empty. The call identifier component of the dialog ID + // MUST be set to the value of the Call-ID in the request. The local + // tag component of the dialog ID MUST be set to the tag in the To field + // in the response to the request (which always includes a tag), and the + // remote tag component of the dialog ID MUST be set to the tag from the + // From field in the request. A UAS MUST be prepared to receive a + // request without a tag in the From field, in which case the tag is + // considered to have a value of null. + // + // This is to maintain backwards compatibility with RFC 2543, which + // did not mandate From tags. + // + // https://tools.ietf.org/html/rfc3261#section-12.1.1 + var remoteSequenceNumber = incomingRequestMessage.cseq; + var localSequenceNumber = undefined; + var callId = incomingRequestMessage.callId; + var localTag = toTag; + var remoteTag = incomingRequestMessage.fromTag; + // The remote URI MUST be set to the URI in the From field, and the + // local URI MUST be set to the URI in the To field. + // https://tools.ietf.org/html/rfc3261#section-12.1.1 + var remoteURI = incomingRequestMessage.from.uri; + var localURI = incomingRequestMessage.to.uri; + var dialogState = { + id: callId + localTag + remoteTag, + early: early, + callId: callId, + localTag: localTag, + remoteTag: remoteTag, + localSequenceNumber: localSequenceNumber, + remoteSequenceNumber: remoteSequenceNumber, + localURI: localURI, + remoteURI: remoteURI, + remoteTarget: remoteTarget, + routeSet: routeSet, + secure: secure + }; + return dialogState; + }; + /** Destructor. */ + Dialog.prototype.dispose = function () { + this.core.dialogs.delete(this.id); + }; + Object.defineProperty(Dialog.prototype, "id", { + /** + * A dialog is identified at each UA with a dialog ID, which consists of + * a Call-ID value, a local tag and a remote tag. The dialog ID at each + * UA involved in the dialog is not the same. Specifically, the local + * tag at one UA is identical to the remote tag at the peer UA. The + * tags are opaque tokens that facilitate the generation of unique + * dialog IDs. + * https://tools.ietf.org/html/rfc3261#section-12 + */ + get: function () { + return this.dialogState.id; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Dialog.prototype, "early", { + /** + * A dialog can also be in the "early" state, which occurs when it is + * created with a provisional response, and then it transition to the + * "confirmed" state when a 2xx final response received or is sent. + * + * Note: RFC 3261 is concise on when a dialog is "confirmed", but it + * can be a point of confusion if an INVITE dialog is "confirmed" after + * a 2xx is sent or after receiving the ACK for the 2xx response. + * With careful reading it can be inferred a dialog is always is + * "confirmed" when the 2xx is sent (regardless of type of dialog). + * However a INVITE dialog does have additional considerations + * when it is confirmed but an ACK has not yet been received (in + * particular with regard to a callee sending BYE requests). + */ + get: function () { + return this.dialogState.early; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Dialog.prototype, "callId", { + /** Call identifier component of the dialog id. */ + get: function () { + return this.dialogState.callId; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Dialog.prototype, "localTag", { + /** Local tag component of the dialog id. */ + get: function () { + return this.dialogState.localTag; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Dialog.prototype, "remoteTag", { + /** Remote tag component of the dialog id. */ + get: function () { + return this.dialogState.remoteTag; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Dialog.prototype, "localSequenceNumber", { + /** Local sequence number (used to order requests from the UA to its peer). */ + get: function () { + return this.dialogState.localSequenceNumber; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Dialog.prototype, "remoteSequenceNumber", { + /** Remote sequence number (used to order requests from its peer to the UA). */ + get: function () { + return this.dialogState.remoteSequenceNumber; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Dialog.prototype, "localURI", { + /** Local URI. */ + get: function () { + return this.dialogState.localURI; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Dialog.prototype, "remoteURI", { + /** Remote URI. */ + get: function () { + return this.dialogState.remoteURI; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Dialog.prototype, "remoteTarget", { + /** Remote target. */ + get: function () { + return this.dialogState.remoteTarget; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Dialog.prototype, "routeSet", { + /** + * Route set, which is an ordered list of URIs. The route set is the + * list of servers that need to be traversed to send a request to the peer. + */ + get: function () { + return this.dialogState.routeSet; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Dialog.prototype, "secure", { + /** + * If the request was sent over TLS, and the Request-URI contained + * a SIPS URI, the "secure" flag is set to true. *NOT IMPLEMENTED* + */ + get: function () { + return this.dialogState.secure; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Dialog.prototype, "userAgentCore", { + /** The user agent core servicing this dialog. */ + get: function () { + return this.core; + }, + enumerable: true, + configurable: true + }); + /** Confirm the dialog. Only matters if dialog is currently early. */ + Dialog.prototype.confirm = function () { + this.dialogState.early = false; + }; + /** + * Requests sent within a dialog, as any other requests, are atomic. If + * a particular request is accepted by the UAS, all the state changes + * associated with it are performed. If the request is rejected, none + * of the state changes are performed. + * + * Note that some requests, such as INVITEs, affect several pieces of + * state. + * + * https://tools.ietf.org/html/rfc3261#section-12.2.2 + * @param message Incoming request message within this dialog. + */ + Dialog.prototype.receiveRequest = function (message) { + // ACK guard. + // By convention, the handling of ACKs is the responsibility + // the particular dialog implementation. For example, see SessionDialog. + // Furthermore, ACKs have same sequence number as the associated INVITE. + if (message.method === Constants_1.C.ACK) { + return; + } + // If the remote sequence number was not empty, but the sequence number + // of the request is lower than the remote sequence number, the request + // is out of order and MUST be rejected with a 500 (Server Internal + // Error) response. If the remote sequence number was not empty, and + // the sequence number of the request is greater than the remote + // sequence number, the request is in order. It is possible for the + // CSeq sequence number to be higher than the remote sequence number by + // more than one. This is not an error condition, and a UAS SHOULD be + // prepared to receive and process requests with CSeq values more than + // one higher than the previous received request. The UAS MUST then set + // the remote sequence number to the value of the sequence number in the + // CSeq header field value in the request. + // + // If a proxy challenges a request generated by the UAC, the UAC has + // to resubmit the request with credentials. The resubmitted request + // will have a new CSeq number. The UAS will never see the first + // request, and thus, it will notice a gap in the CSeq number space. + // Such a gap does not represent any error condition. + // + // https://tools.ietf.org/html/rfc3261#section-12.2.2 + if (this.remoteSequenceNumber) { + if (message.cseq <= this.remoteSequenceNumber) { + throw new Error("Out of sequence in dialog request. Did you forget to call sequenceGuard()?"); + } + this.dialogState.remoteSequenceNumber = message.cseq; + } + // If the remote sequence number is empty, it MUST be set to the value + // of the sequence number in the CSeq header field value in the request. + // https://tools.ietf.org/html/rfc3261#section-12.2.2 + if (!this.remoteSequenceNumber) { + this.dialogState.remoteSequenceNumber = message.cseq; + } + // When a UAS receives a target refresh request, it MUST replace the + // dialog's remote target URI with the URI from the Contact header field + // in that request, if present. + // https://tools.ietf.org/html/rfc3261#section-12.2.2 + // Note: "target refresh request" processing delegated to sub-class. + }; + /** + * If the dialog identifier in the 2xx response matches the dialog + * identifier of an existing dialog, the dialog MUST be transitioned to + * the "confirmed" state, and the route set for the dialog MUST be + * recomputed based on the 2xx response using the procedures of Section + * 12.2.1.2. Otherwise, a new dialog in the "confirmed" state MUST be + * constructed using the procedures of Section 12.1.2. + * + * Note that the only piece of state that is recomputed is the route + * set. Other pieces of state such as the highest sequence numbers + * (remote and local) sent within the dialog are not recomputed. The + * route set only is recomputed for backwards compatibility. RFC + * 2543 did not mandate mirroring of the Record-Route header field in + * a 1xx, only 2xx. However, we cannot update the entire state of + * the dialog, since mid-dialog requests may have been sent within + * the early dialog, modifying the sequence numbers, for example. + * + * https://tools.ietf.org/html/rfc3261#section-13.2.2.4 + */ + Dialog.prototype.recomputeRouteSet = function (message) { + this.dialogState.routeSet = message.getHeaders("record-route").reverse(); + }; + /** + * A request within a dialog is constructed by using many of the + * components of the state stored as part of the dialog. + * https://tools.ietf.org/html/rfc3261#section-12.2.1.1 + * @param method Outgoing request method. + */ + Dialog.prototype.createOutgoingRequestMessage = function (method, options) { + // The URI in the To field of the request MUST be set to the remote URI + // from the dialog state. The tag in the To header field of the request + // MUST be set to the remote tag of the dialog ID. The From URI of the + // request MUST be set to the local URI from the dialog state. The tag + // in the From header field of the request MUST be set to the local tag + // of the dialog ID. If the value of the remote or local tags is null, + // the tag parameter MUST be omitted from the To or From header fields, + // respectively. + // + // Usage of the URI from the To and From fields in the original + // request within subsequent requests is done for backwards + // compatibility with RFC 2543, which used the URI for dialog + // identification. In this specification, only the tags are used for + // dialog identification. It is expected that mandatory reflection + // of the original To and From URI in mid-dialog requests will be + // deprecated in a subsequent revision of this specification. + // https://tools.ietf.org/html/rfc3261#section-12.2.1.1 + var toUri = this.remoteURI; + var toTag = this.remoteTag; + var fromUri = this.localURI; + var fromTag = this.localTag; + // The Call-ID of the request MUST be set to the Call-ID of the dialog. + // Requests within a dialog MUST contain strictly monotonically + // increasing and contiguous CSeq sequence numbers (increasing-by-one) + // in each direction (excepting ACK and CANCEL of course, whose numbers + // equal the requests being acknowledged or cancelled). Therefore, if + // the local sequence number is not empty, the value of the local + // sequence number MUST be incremented by one, and this value MUST be + // placed into the CSeq header field. If the local sequence number is + // empty, an initial value MUST be chosen using the guidelines of + // Section 8.1.1.5. The method field in the CSeq header field value + // MUST match the method of the request. + // https://tools.ietf.org/html/rfc3261#section-12.2.1.1 + var callId = this.callId; + var cseq; + if (options && options.cseq) { + cseq = options.cseq; + } + else if (!this.dialogState.localSequenceNumber) { + cseq = this.dialogState.localSequenceNumber = 1; // https://tools.ietf.org/html/rfc3261#section-8.1.1.5 + } + else { + cseq = this.dialogState.localSequenceNumber += 1; + } + // The UAC uses the remote target and route set to build the Request-URI + // and Route header field of the request. + // + // If the route set is empty, the UAC MUST place the remote target URI + // into the Request-URI. The UAC MUST NOT add a Route header field to + // the request. + // + // If the route set is not empty, and the first URI in the route set + // contains the lr parameter (see Section 19.1.1), the UAC MUST place + // the remote target URI into the Request-URI and MUST include a Route + // header field containing the route set values in order, including all + // parameters. + // + // If the route set is not empty, and its first URI does not contain the + // lr parameter, the UAC MUST place the first URI from the route set + // into the Request-URI, stripping any parameters that are not allowed + // in a Request-URI. The UAC MUST add a Route header field containing + // the remainder of the route set values in order, including all + // parameters. The UAC MUST then place the remote target URI into the + // Route header field as the last value. + // https://tools.ietf.org/html/rfc3261#section-12.2.1.1 + // The lr parameter, when present, indicates that the element + // responsible for this resource implements the routing mechanisms + // specified in this document. This parameter will be used in the + // URIs proxies place into Record-Route header field values, and + // may appear in the URIs in a pre-existing route set. + // + // This parameter is used to achieve backwards compatibility with + // systems implementing the strict-routing mechanisms of RFC 2543 + // and the rfc2543bis drafts up to bis-05. An element preparing + // to send a request based on a URI not containing this parameter + // can assume the receiving element implements strict-routing and + // reformat the message to preserve the information in the + // Request-URI. + // https://tools.ietf.org/html/rfc3261#section-19.1.1 + // NOTE: Not backwards compatible with RFC 2543 (no support for strict-routing). + var ruri = this.remoteTarget; + var routeSet = this.routeSet; + var extraHeaders = options && options.extraHeaders; + var body = options && options.body ? + { contentType: options.body.contentType, body: options.body.content } : + undefined; + // The relative order of header fields with different field names is not + // significant. However, it is RECOMMENDED that header fields which are + // needed for proxy processing (Via, Route, Record-Route, Proxy-Require, + // Max-Forwards, and Proxy-Authorization, for example) appear towards + // the top of the message to facilitate rapid parsing. + // https://tools.ietf.org/html/rfc3261#section-7.3.1 + var message = this.core.configuration.outgoingRequestMessageFactory(method, ruri, { + callId: callId, + cseq: cseq, + fromUri: fromUri, + fromTag: fromTag, + toUri: toUri, + toTag: toTag, + routeSet: routeSet + }, extraHeaders, body); + return message; + }; + /** + * If the remote sequence number was not empty, but the sequence number + * of the request is lower than the remote sequence number, the request + * is out of order and MUST be rejected with a 500 (Server Internal + * Error) response. + * https://tools.ietf.org/html/rfc3261#section-12.2.2 + * @param request Incoming request to guard. + * @returns True if the program execution is to continue in the branch in question. + * Otherwise a 500 Server Internal Error was stateless sent and request processing must stop. + */ + Dialog.prototype.sequenceGuard = function (message) { + // ACK guard. + // By convention, handling of unexpected ACKs is responsibility + // the particular dialog implementation. For example, see SessionDialog. + // Furthermore, we cannot reply to an "out of sequence" ACK. + if (message.method === Constants_1.C.ACK) { + return true; + } + // Note: We are rejecting on "less than or equal to" the remote + // sequence number (excepting ACK whose numbers equal the requests + // being acknowledged or cancelled), which is the correct thing to + // do in our case. The only time a request with the same sequence number + // will show up here if is a) it is a very late retransmission of a + // request we already handled or b) it is a different request with the + // same sequence number which would be violation of the standard. + // Request retransmissions are absorbed by the transaction layer, + // so any request with a duplicate sequence number getting here + // would have to be a retransmission after the transaction terminated + // or a broken request (with unique via branch value). + // Requests within a dialog MUST contain strictly monotonically + // increasing and contiguous CSeq sequence numbers (increasing-by-one) + // in each direction (excepting ACK and CANCEL of course, whose numbers + // equal the requests being acknowledged or cancelled). Therefore, if + // the local sequence number is not empty, the value of the local + // sequence number MUST be incremented by one, and this value MUST be + // placed into the CSeq header field. + // https://tools.ietf.org/html/rfc3261#section-12.2.1.1 + if (this.remoteSequenceNumber && message.cseq <= this.remoteSequenceNumber) { + this.core.replyStateless(message, { statusCode: 500 }); + return false; + } + return true; + }; + return Dialog; +}()); +exports.Dialog = Dialog; + + +/***/ }), +/* 90 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Constants_1 = __webpack_require__(3); +var NameAddrHeader_1 = __webpack_require__(9); +var SIPMessage_1 = __webpack_require__(6); +var Timers_1 = __webpack_require__(56); +var messages_1 = __webpack_require__(63); +var session_1 = __webpack_require__(68); +var transactions_1 = __webpack_require__(52); +var bye_user_agent_client_1 = __webpack_require__(81); +var bye_user_agent_server_1 = __webpack_require__(83); +var info_user_agent_client_1 = __webpack_require__(91); +var info_user_agent_server_1 = __webpack_require__(86); +var notify_user_agent_client_1 = __webpack_require__(92); +var notify_user_agent_server_1 = __webpack_require__(93); +var prack_user_agent_client_1 = __webpack_require__(94); +var prack_user_agent_server_1 = __webpack_require__(95); +var re_invite_user_agent_client_1 = __webpack_require__(96); +var re_invite_user_agent_server_1 = __webpack_require__(97); +var refer_user_agent_client_1 = __webpack_require__(98); +var refer_user_agent_server_1 = __webpack_require__(99); +var dialog_1 = __webpack_require__(89); +var SessionDialog = /** @class */ (function (_super) { + __extends(SessionDialog, _super); + function SessionDialog(initialTransaction, core, state, delegate) { + var _this = _super.call(this, core, state) || this; + _this.initialTransaction = initialTransaction; + /** The state of the offer/answer exchange. */ + _this._signalingState = session_1.SignalingState.Initial; + /** True if waiting for an ACK to the initial transaction 2xx (UAS only). */ + _this.ackWait = false; + _this.delegate = delegate; + if (initialTransaction instanceof transactions_1.InviteServerTransaction) { + // If we're created by an invite server transaction, we're + // going to be waiting for an ACK if are to be confirmed. + _this.ackWait = true; + } + // If we're confirmed upon creation start the retransmitting whatever + // the 2xx final response was that confirmed us into existence. + if (!_this.early) { + _this.start2xxRetransmissionTimer(); + } + _this.signalingStateTransition(initialTransaction.request); + _this.logger = core.loggerFactory.getLogger("sip.invite-dialog"); + _this.logger.log("INVITE dialog " + _this.id + " constructed"); + return _this; + } + SessionDialog.prototype.dispose = function () { + _super.prototype.dispose.call(this); + this._signalingState = session_1.SignalingState.Closed; + this._offer = undefined; + this._answer = undefined; + if (this.invite2xxTimer) { + clearTimeout(this.invite2xxTimer); + this.invite2xxTimer = undefined; + } + // The UAS MUST still respond to any pending requests received for that + // dialog. It is RECOMMENDED that a 487 (Request Terminated) response + // be generated to those pending requests. + // https://tools.ietf.org/html/rfc3261#section-15.1.2 + // TODO: + // this.userAgentServers.forEach((uas) => uas.reply(487)); + this.logger.log("INVITE dialog " + this.id + " destroyed"); + }; + Object.defineProperty(SessionDialog.prototype, "sessionState", { + // FIXME: Need real state machine + get: function () { + if (this.early) { + return session_1.SessionState.Early; + } + else if (this.ackWait) { + return session_1.SessionState.AckWait; + } + else if (this._signalingState === session_1.SignalingState.Closed) { + return session_1.SessionState.Terminated; + } + else { + return session_1.SessionState.Confirmed; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SessionDialog.prototype, "signalingState", { + /** The state of the offer/answer exchange. */ + get: function () { + return this._signalingState; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SessionDialog.prototype, "offer", { + /** The current offer. Undefined unless signaling state HaveLocalOffer, HaveRemoteOffer, of Stable. */ + get: function () { + return this._offer; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SessionDialog.prototype, "answer", { + /** The current answer. Undefined unless signaling state Stable. */ + get: function () { + return this._answer; + }, + enumerable: true, + configurable: true + }); + /** Confirm the dialog. Only matters if dialog is currently early. */ + SessionDialog.prototype.confirm = function () { + // When we're confirmed start the retransmitting whatever + // the 2xx final response that may have confirmed us. + if (this.early) { + this.start2xxRetransmissionTimer(); + } + _super.prototype.confirm.call(this); + }; + /** Re-confirm the dialog. Only matters if handling re-INVITE request. */ + SessionDialog.prototype.reConfirm = function () { + // When we're confirmed start the retransmitting whatever + // the 2xx final response that may have confirmed us. + if (this.reinviteUserAgentServer) { + this.startReInvite2xxRetransmissionTimer(); + } + }; + /** + * The UAC core MUST generate an ACK request for each 2xx received from + * the transaction layer. The header fields of the ACK are constructed + * in the same way as for any request sent within a dialog (see Section + * 12) with the exception of the CSeq and the header fields related to + * authentication. The sequence number of the CSeq header field MUST be + * the same as the INVITE being acknowledged, but the CSeq method MUST + * be ACK. The ACK MUST contain the same credentials as the INVITE. If + * the 2xx contains an offer (based on the rules above), the ACK MUST + * carry an answer in its body. If the offer in the 2xx response is not + * acceptable, the UAC core MUST generate a valid answer in the ACK and + * then send a BYE immediately. + * https://tools.ietf.org/html/rfc3261#section-13.2.2.4 + * @param options ACK options bucket. + */ + SessionDialog.prototype.ack = function (options) { + if (options === void 0) { options = {}; } + this.logger.log("INVITE dialog " + this.id + " sending ACK request"); + var transaction; + if (this.reinviteUserAgentClient) { + // We're sending ACK for a re-INVITE + if (!(this.reinviteUserAgentClient.transaction instanceof transactions_1.InviteClientTransaction)) { + throw new Error("Transaction not instance of InviteClientTransaction."); + } + transaction = this.reinviteUserAgentClient.transaction; + this.reinviteUserAgentClient = undefined; + } + else { + // We're sending ACK for the initial INVITE + if (!(this.initialTransaction instanceof transactions_1.InviteClientTransaction)) { + throw new Error("Initial transaction not instance of InviteClientTransaction."); + } + transaction = this.initialTransaction; + } + options.cseq = transaction.request.cseq; // ACK cseq is INVITE cseq + var message = this.createOutgoingRequestMessage(Constants_1.C.ACK, options); + transaction.ackResponse(message); // See InviteClientTransaction for details. + this.signalingStateTransition(message); + return { message: message }; + }; + /** + * Terminating a Session + * + * This section describes the procedures for terminating a session + * established by SIP. The state of the session and the state of the + * dialog are very closely related. When a session is initiated with an + * INVITE, each 1xx or 2xx response from a distinct UAS creates a + * dialog, and if that response completes the offer/answer exchange, it + * also creates a session. As a result, each session is "associated" + * with a single dialog - the one which resulted in its creation. If an + * initial INVITE generates a non-2xx final response, that terminates + * all sessions (if any) and all dialogs (if any) that were created + * through responses to the request. By virtue of completing the + * transaction, a non-2xx final response also prevents further sessions + * from being created as a result of the INVITE. The BYE request is + * used to terminate a specific session or attempted session. In this + * case, the specific session is the one with the peer UA on the other + * side of the dialog. When a BYE is received on a dialog, any session + * associated with that dialog SHOULD terminate. A UA MUST NOT send a + * BYE outside of a dialog. The caller's UA MAY send a BYE for either + * confirmed or early dialogs, and the callee's UA MAY send a BYE on + * confirmed dialogs, but MUST NOT send a BYE on early dialogs. + * + * However, the callee's UA MUST NOT send a BYE on a confirmed dialog + * until it has received an ACK for its 2xx response or until the server + * transaction times out. If no SIP extensions have defined other + * application layer states associated with the dialog, the BYE also + * terminates the dialog. + * + * https://tools.ietf.org/html/rfc3261#section-15 + * FIXME: Make these proper Exceptions... + * @param options BYE options bucket. + * @throws {Error} If callee's UA attempts a BYE on an early dialog. + * @throws {Error} If callee's UA attempts a BYE on a confirmed dialog + * while it's waiting on the ACK for its 2xx response. + */ + SessionDialog.prototype.bye = function (delegate, options) { + this.logger.log("INVITE dialog " + this.id + " sending BYE request"); + // The caller's UA MAY send a BYE for either + // confirmed or early dialogs, and the callee's UA MAY send a BYE on + // confirmed dialogs, but MUST NOT send a BYE on early dialogs. + // + // However, the callee's UA MUST NOT send a BYE on a confirmed dialog + // until it has received an ACK for its 2xx response or until the server + // transaction times out. + // https://tools.ietf.org/html/rfc3261#section-15 + if (this.initialTransaction instanceof transactions_1.InviteServerTransaction) { + if (this.early) { + // FIXME: TODO: This should throw a proper exception. + throw new Error("UAS MUST NOT send a BYE on early dialogs."); + } + if (this.ackWait && this.initialTransaction.state !== transactions_1.TransactionState.Terminated) { + // FIXME: TODO: This should throw a proper exception. + throw new Error("UAS MUST NOT send a BYE on a confirmed dialog " + + "until it has received an ACK for its 2xx response " + + "or until the server transaction times out."); + } + } + // A BYE request is constructed as would any other request within a + // dialog, as described in Section 12. + // + // Once the BYE is constructed, the UAC core creates a new non-INVITE + // client transaction, and passes it the BYE request. The UAC MUST + // consider the session terminated (and therefore stop sending or + // listening for media) as soon as the BYE request is passed to the + // client transaction. If the response for the BYE is a 481 + // (Call/Transaction Does Not Exist) or a 408 (Request Timeout) or no + // response at all is received for the BYE (that is, a timeout is + // returned by the client transaction), the UAC MUST consider the + // session and the dialog terminated. + // https://tools.ietf.org/html/rfc3261#section-15.1.1 + return new bye_user_agent_client_1.ByeUserAgentClient(this, delegate, options); + }; + /** + * An INFO request can be associated with an Info Package (see + * Section 5), or associated with a legacy INFO usage (see Section 2). + * + * The construction of the INFO request is the same as any other + * non-target refresh request within an existing invite dialog usage as + * described in Section 12.2 of RFC 3261. + * https://tools.ietf.org/html/rfc6086#section-4.2.1 + * @param options Options bucket. + */ + SessionDialog.prototype.info = function (delegate, options) { + this.logger.log("INVITE dialog " + this.id + " sending INFO request"); + if (this.early) { + // FIXME: TODO: This should throw a proper exception. + throw new Error("Dialog not confirmed."); + } + return new info_user_agent_client_1.InfoUserAgentClient(this, delegate, options); + }; + /** + * Modifying an Existing Session + * + * A successful INVITE request (see Section 13) establishes both a + * dialog between two user agents and a session using the offer-answer + * model. Section 12 explains how to modify an existing dialog using a + * target refresh request (for example, changing the remote target URI + * of the dialog). This section describes how to modify the actual + * session. This modification can involve changing addresses or ports, + * adding a media stream, deleting a media stream, and so on. This is + * accomplished by sending a new INVITE request within the same dialog + * that established the session. An INVITE request sent within an + * existing dialog is known as a re-INVITE. + * + * Note that a single re-INVITE can modify the dialog and the + * parameters of the session at the same time. + * + * Either the caller or callee can modify an existing session. + * https://tools.ietf.org/html/rfc3261#section-14 + * @param options Options bucket + */ + SessionDialog.prototype.invite = function (delegate, options) { + this.logger.log("INVITE dialog " + this.id + " sending INVITE request"); + if (this.early) { + // FIXME: TODO: This should throw a proper exception. + throw new Error("Dialog not confirmed."); + } + // Note that a UAC MUST NOT initiate a new INVITE transaction within a + // dialog while another INVITE transaction is in progress in either + // direction. + // + // 1. If there is an ongoing INVITE client transaction, the TU MUST + // wait until the transaction reaches the completed or terminated + // state before initiating the new INVITE. + // + // 2. If there is an ongoing INVITE server transaction, the TU MUST + // wait until the transaction reaches the confirmed or terminated + // state before initiating the new INVITE. + // + // However, a UA MAY initiate a regular transaction while an INVITE + // transaction is in progress. A UA MAY also initiate an INVITE + // transaction while a regular transaction is in progress. + // https://tools.ietf.org/html/rfc3261#section-14.1 + if (this.reinviteUserAgentClient) { + // FIXME: TODO: This should throw a proper exception. + throw new Error("There is an ongoing re-INVITE client transaction."); + } + if (this.reinviteUserAgentServer) { + // FIXME: TODO: This should throw a proper exception. + throw new Error("There is an ongoing re-INVITE server transaction."); + } + return new re_invite_user_agent_client_1.ReInviteUserAgentClient(this, delegate, options); + }; + /** + * The NOTIFY mechanism defined in [2] MUST be used to inform the agent + * sending the REFER of the status of the reference. + * https://tools.ietf.org/html/rfc3515#section-2.4.4 + * @param options Options bucket. + */ + SessionDialog.prototype.notify = function (delegate, options) { + this.logger.log("INVITE dialog " + this.id + " sending NOTIFY request"); + if (this.early) { + // FIXME: TODO: This should throw a proper exception. + throw new Error("Dialog not confirmed."); + } + return new notify_user_agent_client_1.NotifyUserAgentClient(this, delegate, options); + }; + /** + * Assuming the response is to be transmitted reliably, the UAC MUST + * create a new request with method PRACK. This request is sent within + * the dialog associated with the provisional response (indeed, the + * provisional response may have created the dialog). PRACK requests + * MAY contain bodies, which are interpreted according to their type and + * disposition. + * https://tools.ietf.org/html/rfc3262#section-4 + * @param options Options bucket. + */ + SessionDialog.prototype.prack = function (delegate, options) { + this.logger.log("INVITE dialog " + this.id + " sending PRACK request"); + return new prack_user_agent_client_1.PrackUserAgentClient(this, delegate, options); + }; + /** + * REFER is a SIP request and is constructed as defined in [1]. A REFER + * request MUST contain exactly one Refer-To header field value. + * https://tools.ietf.org/html/rfc3515#section-2.4.1 + * @param options Options bucket. + */ + SessionDialog.prototype.refer = function (delegate, options) { + this.logger.log("INVITE dialog " + this.id + " sending REFER request"); + if (this.early) { + // FIXME: TODO: This should throw a proper exception. + throw new Error("Dialog not confirmed."); + } + // FIXME: TODO: Validate Refer-To header field value. + return new refer_user_agent_client_1.ReferUserAgentClient(this, delegate, options); + }; + /** + * Requests sent within a dialog, as any other requests, are atomic. If + * a particular request is accepted by the UAS, all the state changes + * associated with it are performed. If the request is rejected, none + * of the state changes are performed. + * https://tools.ietf.org/html/rfc3261#section-12.2.2 + * @param message Incoming request message within this dialog. + */ + SessionDialog.prototype.receiveRequest = function (message) { + this.logger.log("INVITE dialog " + this.id + " received " + message.method + " request"); + // Response retransmissions cease when an ACK request for the + // response is received. This is independent of whatever transport + // protocols are used to send the response. + // https://tools.ietf.org/html/rfc6026#section-8.1 + if (message.method === Constants_1.C.ACK) { + // If ackWait is true, then this is the ACK to the initial INVITE, + // otherwise this is an ACK to an in dialog INVITE. In either case, + // guard to make sure the sequence number of the ACK matches the INVITE. + if (this.ackWait) { + if (this.initialTransaction instanceof transactions_1.InviteClientTransaction) { + this.logger.warn("INVITE dialog " + this.id + " received unexpected " + message.method + " request, dropping."); + return; + } + if (this.initialTransaction.request.cseq !== message.cseq) { + this.logger.warn("INVITE dialog " + this.id + " received unexpected " + message.method + " request, dropping."); + return; + } + this.ackWait = false; + } + else { + if (!this.reinviteUserAgentServer) { + this.logger.warn("INVITE dialog " + this.id + " received unexpected " + message.method + " request, dropping."); + return; + } + if (this.reinviteUserAgentServer.transaction.request.cseq !== message.cseq) { + this.logger.warn("INVITE dialog " + this.id + " received unexpected " + message.method + " request, dropping."); + return; + } + this.reinviteUserAgentServer = undefined; + } + this.signalingStateTransition(message); + if (this.delegate && this.delegate.onAck) { + this.delegate.onAck({ message: message }); + } + return; + } + // Request within a dialog out of sequence guard. + // https://tools.ietf.org/html/rfc3261#section-12.2.2 + if (!this.sequenceGuard(message)) { + this.logger.log("INVITE dialog " + this.id + " rejected out of order " + message.method + " request."); + return; + } + if (message.method === Constants_1.C.INVITE) { + // A UAS that receives a second INVITE before it sends the final + // response to a first INVITE with a lower CSeq sequence number on the + // same dialog MUST return a 500 (Server Internal Error) response to the + // second INVITE and MUST include a Retry-After header field with a + // randomly chosen value of between 0 and 10 seconds. + // https://tools.ietf.org/html/rfc3261#section-14.2 + if (this.reinviteUserAgentServer) { + // https://tools.ietf.org/html/rfc3261#section-20.33 + var retryAfter = Math.floor((Math.random() * 10)) + 1; + var extraHeaders = ["Retry-After: " + retryAfter]; + this.core.replyStateless(message, { statusCode: 500, extraHeaders: extraHeaders }); + return; + } + // A UAS that receives an INVITE on a dialog while an INVITE it had sent + // on that dialog is in progress MUST return a 491 (Request Pending) + // response to the received INVITE. + // https://tools.ietf.org/html/rfc3261#section-14.2 + if (this.reinviteUserAgentClient) { + this.core.replyStateless(message, { statusCode: 491 }); + return; + } + } + // Request within a dialog common processing. + // https://tools.ietf.org/html/rfc3261#section-12.2.2 + _super.prototype.receiveRequest.call(this, message); + // Requests within a dialog MAY contain Record-Route and Contact header + // fields. However, these requests do not cause the dialog's route set + // to be modified, although they may modify the remote target URI. + // Specifically, requests that are not target refresh requests do not + // modify the dialog's remote target URI, and requests that are target + // refresh requests do. For dialogs that have been established with an + // INVITE, the only target refresh request defined is re-INVITE (see + // Section 14). Other extensions may define different target refresh + // requests for dialogs established in other ways. + // + // Note that an ACK is NOT a target refresh request. + // + // Target refresh requests only update the dialog's remote target URI, + // and not the route set formed from the Record-Route. Updating the + // latter would introduce severe backwards compatibility problems with + // RFC 2543-compliant systems. + // https://tools.ietf.org/html/rfc3261#section-15 + if (message.method === Constants_1.C.INVITE) { + // FIXME: parser needs to be typed... + var contact = message.parseHeader("contact"); + if (!contact) { // TODO: Review to make sure this will never happen + throw new Error("Contact undefined."); + } + if (!(contact instanceof NameAddrHeader_1.NameAddrHeader)) { + throw new Error("Contact not instance of NameAddrHeader."); + } + this.dialogState.remoteTarget = contact.uri; + } + // Switch on method and then delegate. + switch (message.method) { + case Constants_1.C.BYE: + // A UAS core receiving a BYE request for an existing dialog MUST follow + // the procedures of Section 12.2.2 to process the request. Once done, + // the UAS SHOULD terminate the session (and therefore stop sending and + // listening for media). The only case where it can elect not to are + // multicast sessions, where participation is possible even if the other + // participant in the dialog has terminated its involvement in the + // session. Whether or not it ends its participation on the session, + // the UAS core MUST generate a 2xx response to the BYE, and MUST pass + // that to the server transaction for transmission. + // + // The UAS MUST still respond to any pending requests received for that + // dialog. It is RECOMMENDED that a 487 (Request Terminated) response + // be generated to those pending requests. + // https://tools.ietf.org/html/rfc3261#section-15.1.2 + { + var uas = new bye_user_agent_server_1.ByeUserAgentServer(this, message); + this.delegate && this.delegate.onBye ? + this.delegate.onBye(uas) : + uas.accept(); + this.dispose(); + } + break; + case Constants_1.C.INFO: + // If a UA receives an INFO request associated with an Info Package that + // the UA has not indicated willingness to receive, the UA MUST send a + // 469 (Bad Info Package) response (see Section 11.6), which contains a + // Recv-Info header field with Info Packages for which the UA is willing + // to receive INFO requests. + { + var uas = new info_user_agent_server_1.InfoUserAgentServer(this, message); + this.delegate && this.delegate.onInfo ? + this.delegate.onInfo(uas) : + uas.reject({ + statusCode: 469, + extraHeaders: ["Recv-Info :"] + }); + } + break; + case Constants_1.C.INVITE: + // If the new session description is not acceptable, the UAS can reject + // it by returning a 488 (Not Acceptable Here) response for the re- + // INVITE. This response SHOULD include a Warning header field. + // https://tools.ietf.org/html/rfc3261#section-14.2 + { + var uas = new re_invite_user_agent_server_1.ReInviteUserAgentServer(this, message); + this.delegate && this.delegate.onInvite ? + this.delegate.onInvite(uas) : + uas.reject({ statusCode: 488 }); // TODO: Warning header field. + } + break; + case Constants_1.C.NOTIFY: + // https://tools.ietf.org/html/rfc3515#section-2.4.4 + { + var uas = new notify_user_agent_server_1.NotifyUserAgentServer(this, message); + this.delegate && this.delegate.onNotify ? + this.delegate.onNotify(uas) : + uas.accept(); + } + break; + case Constants_1.C.PRACK: + // https://tools.ietf.org/html/rfc3262#section-4 + { + var uas = new prack_user_agent_server_1.PrackUserAgentServer(this, message); + this.delegate && this.delegate.onPrack ? + this.delegate.onPrack(uas) : + uas.accept(); + } + break; + case Constants_1.C.REFER: + // https://tools.ietf.org/html/rfc3515#section-2.4.2 + { + var uas = new refer_user_agent_server_1.ReferUserAgentServer(this, message); + this.delegate && this.delegate.onRefer ? + this.delegate.onRefer(uas) : + uas.reject(); + } + break; + default: + { + this.logger.log("INVITE dialog " + this.id + " received unimplemented " + message.method + " request"); + this.core.replyStateless(message, { statusCode: 501 }); + } + break; + } + }; + SessionDialog.prototype.reliableSequenceGuard = function (message) { + var statusCode = message.statusCode; + if (!statusCode) { + throw new Error("Status code undefined"); + } + if (statusCode > 100 && statusCode < 200) { + // If a provisional response is received for an initial request, and + // that response contains a Require header field containing the option + // tag 100rel, the response is to be sent reliably. If the response is + // a 100 (Trying) (as opposed to 101 to 199), this option tag MUST be + // ignored, and the procedures below MUST NOT be used. + // https://tools.ietf.org/html/rfc3262#section-4 + var requireHeader = message.getHeader("require"); + var rseqHeader = message.getHeader("rseq"); + var rseq = requireHeader && requireHeader.includes("100rel") && rseqHeader ? Number(rseqHeader) : undefined; + if (rseq) { + // Handling of subsequent reliable provisional responses for the same + // initial request follows the same rules as above, with the following + // difference: reliable provisional responses are guaranteed to be in + // order. As a result, if the UAC receives another reliable provisional + // response to the same request, and its RSeq value is not one higher + // than the value of the sequence number, that response MUST NOT be + // acknowledged with a PRACK, and MUST NOT be processed further by the + // UAC. An implementation MAY discard the response, or MAY cache the + // response in the hopes of receiving the missing responses. + // https://tools.ietf.org/html/rfc3262#section-4 + if (this.rseq && this.rseq + 1 !== rseq) { + return false; + } + // Once a reliable provisional response is received, retransmissions of + // that response MUST be discarded. A response is a retransmission when + // its dialog ID, CSeq, and RSeq match the original response. The UAC + // MUST maintain a sequence number that indicates the most recently + // received in-order reliable provisional response for the initial + // request. This sequence number MUST be maintained until a final + // response is received for the initial request. Its value MUST be + // initialized to the RSeq header field in the first reliable + // provisional response received for the initial request. + // https://tools.ietf.org/html/rfc3262#section-4 + if (!this.rseq) { + this.rseq = rseq; + } + } + } + return true; + }; + /** + * Update the signaling state of the dialog. + * @param message The message to base the update off of. + */ + SessionDialog.prototype.signalingStateTransition = function (message) { + var body = messages_1.getBody(message); + // No body, no session. No, woman, no cry. + if (!body || body.contentDisposition !== "session") { + return; + } + // We're in UAS role, receiving incoming request with session description + if (message instanceof SIPMessage_1.IncomingRequest) { + switch (this._signalingState) { + case session_1.SignalingState.Initial: + case session_1.SignalingState.Stable: + this._signalingState = session_1.SignalingState.HaveRemoteOffer; + this._offer = body; + this._answer = undefined; + break; + case session_1.SignalingState.HaveLocalOffer: + this._signalingState = session_1.SignalingState.Stable; + this._answer = body; + break; + case session_1.SignalingState.HaveRemoteOffer: + // You cannot make a new offer while one is in progress. + // https://tools.ietf.org/html/rfc3261#section-13.2.1 + // FIXME: What to do here? + break; + case session_1.SignalingState.Closed: + break; + default: + throw new Error("Unexpected signaling state."); + } + } + // We're in UAC role, receiving incoming response with session description + if (message instanceof SIPMessage_1.IncomingResponse) { + switch (this._signalingState) { + case session_1.SignalingState.Initial: + case session_1.SignalingState.Stable: + this._signalingState = session_1.SignalingState.HaveRemoteOffer; + this._offer = body; + this._answer = undefined; + break; + case session_1.SignalingState.HaveLocalOffer: + this._signalingState = session_1.SignalingState.Stable; + this._answer = body; + break; + case session_1.SignalingState.HaveRemoteOffer: + // You cannot make a new offer while one is in progress. + // https://tools.ietf.org/html/rfc3261#section-13.2.1 + // FIXME: What to do here? + break; + case session_1.SignalingState.Closed: + break; + default: + throw new Error("Unexpected signaling state."); + } + } + // We're in UAC role, sending outgoing request with session description + if (message instanceof SIPMessage_1.OutgoingRequest) { + switch (this._signalingState) { + case session_1.SignalingState.Initial: + case session_1.SignalingState.Stable: + this._signalingState = session_1.SignalingState.HaveLocalOffer; + this._offer = body; + this._answer = undefined; + break; + case session_1.SignalingState.HaveLocalOffer: + // You cannot make a new offer while one is in progress. + // https://tools.ietf.org/html/rfc3261#section-13.2.1 + // FIXME: What to do here? + break; + case session_1.SignalingState.HaveRemoteOffer: + this._signalingState = session_1.SignalingState.Stable; + this._answer = body; + break; + case session_1.SignalingState.Closed: + break; + default: + throw new Error("Unexpected signaling state."); + } + } + // We're in UAS role, sending outgoing response with session description + if (messages_1.isBody(message)) { + switch (this._signalingState) { + case session_1.SignalingState.Initial: + case session_1.SignalingState.Stable: + this._signalingState = session_1.SignalingState.HaveLocalOffer; + this._offer = body; + this._answer = undefined; + break; + case session_1.SignalingState.HaveLocalOffer: + // You cannot make a new offer while one is in progress. + // https://tools.ietf.org/html/rfc3261#section-13.2.1 + // FIXME: What to do here? + break; + case session_1.SignalingState.HaveRemoteOffer: + this._signalingState = session_1.SignalingState.Stable; + this._answer = body; + break; + case session_1.SignalingState.Closed: + break; + default: + throw new Error("Unexpected signaling state."); + } + } + }; + SessionDialog.prototype.start2xxRetransmissionTimer = function () { + var _this = this; + if (this.initialTransaction instanceof transactions_1.InviteServerTransaction) { + var transaction_1 = this.initialTransaction; + // Once the response has been constructed, it is passed to the INVITE + // server transaction. In order to ensure reliable end-to-end + // transport of the response, it is necessary to periodically pass + // the response directly to the transport until the ACK arrives. The + // 2xx response is passed to the transport with an interval that + // starts at T1 seconds and doubles for each retransmission until it + // reaches T2 seconds (T1 and T2 are defined in Section 17). + // Response retransmissions cease when an ACK request for the + // response is received. This is independent of whatever transport + // protocols are used to send the response. + // https://tools.ietf.org/html/rfc6026#section-8.1 + var timeout_1 = Timers_1.Timers.T1; + var retransmission_1 = function () { + if (!_this.ackWait) { + _this.invite2xxTimer = undefined; + return; + } + _this.logger.log("No ACK for 2xx response received, attempting retransmission"); + transaction_1.retransmitAcceptedResponse(); + timeout_1 = Math.min(timeout_1 * 2, Timers_1.Timers.T2); + _this.invite2xxTimer = setTimeout(retransmission_1, timeout_1); + }; + this.invite2xxTimer = setTimeout(retransmission_1, timeout_1); + // If the server retransmits the 2xx response for 64*T1 seconds without + // receiving an ACK, the dialog is confirmed, but the session SHOULD be + // terminated. This is accomplished with a BYE, as described in Section 15. + // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 + var stateChanged_1 = function () { + if (transaction_1.state === transactions_1.TransactionState.Terminated) { + transaction_1.removeListener("stateChanged", stateChanged_1); + if (_this.invite2xxTimer) { + clearTimeout(_this.invite2xxTimer); + _this.invite2xxTimer = undefined; + } + if (_this.ackWait) { + if (_this.delegate && _this.delegate.onAckTimeout) { + _this.delegate.onAckTimeout(); + } + else { + _this.bye(); + } + } + } + }; + transaction_1.addListener("stateChanged", stateChanged_1); + } + }; + // FIXME: Refactor + SessionDialog.prototype.startReInvite2xxRetransmissionTimer = function () { + var _this = this; + if (this.reinviteUserAgentServer && this.reinviteUserAgentServer.transaction instanceof transactions_1.InviteServerTransaction) { + var transaction_2 = this.reinviteUserAgentServer.transaction; + // Once the response has been constructed, it is passed to the INVITE + // server transaction. In order to ensure reliable end-to-end + // transport of the response, it is necessary to periodically pass + // the response directly to the transport until the ACK arrives. The + // 2xx response is passed to the transport with an interval that + // starts at T1 seconds and doubles for each retransmission until it + // reaches T2 seconds (T1 and T2 are defined in Section 17). + // Response retransmissions cease when an ACK request for the + // response is received. This is independent of whatever transport + // protocols are used to send the response. + // https://tools.ietf.org/html/rfc6026#section-8.1 + var timeout_2 = Timers_1.Timers.T1; + var retransmission_2 = function () { + if (!_this.reinviteUserAgentServer) { + _this.invite2xxTimer = undefined; + return; + } + _this.logger.log("No ACK for 2xx response received, attempting retransmission"); + transaction_2.retransmitAcceptedResponse(); + timeout_2 = Math.min(timeout_2 * 2, Timers_1.Timers.T2); + _this.invite2xxTimer = setTimeout(retransmission_2, timeout_2); + }; + this.invite2xxTimer = setTimeout(retransmission_2, timeout_2); + // If the server retransmits the 2xx response for 64*T1 seconds without + // receiving an ACK, the dialog is confirmed, but the session SHOULD be + // terminated. This is accomplished with a BYE, as described in Section 15. + // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 + var stateChanged_2 = function () { + if (transaction_2.state === transactions_1.TransactionState.Terminated) { + transaction_2.removeListener("stateChanged", stateChanged_2); + if (_this.invite2xxTimer) { + clearTimeout(_this.invite2xxTimer); + _this.invite2xxTimer = undefined; + } + if (_this.reinviteUserAgentServer) { + // FIXME: TODO: What to do here + } + } + }; + transaction_2.addListener("stateChanged", stateChanged_2); + } + }; + return SessionDialog; +}(dialog_1.Dialog)); +exports.SessionDialog = SessionDialog; + + +/***/ }), +/* 91 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Constants_1 = __webpack_require__(3); +var transactions_1 = __webpack_require__(52); +var user_agent_client_1 = __webpack_require__(82); +var InfoUserAgentClient = /** @class */ (function (_super) { + __extends(InfoUserAgentClient, _super); + function InfoUserAgentClient(dialog, delegate, options) { + var _this = this; + var message = dialog.createOutgoingRequestMessage(Constants_1.C.INFO, options); + _this = _super.call(this, transactions_1.NonInviteClientTransaction, dialog.userAgentCore, message, delegate) || this; + return _this; + } + return InfoUserAgentClient; +}(user_agent_client_1.UserAgentClient)); +exports.InfoUserAgentClient = InfoUserAgentClient; + + +/***/ }), +/* 92 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Constants_1 = __webpack_require__(3); +var transactions_1 = __webpack_require__(52); +var user_agent_client_1 = __webpack_require__(82); +var NotifyUserAgentClient = /** @class */ (function (_super) { + __extends(NotifyUserAgentClient, _super); + function NotifyUserAgentClient(dialog, delegate, options) { + var _this = this; + var message = dialog.createOutgoingRequestMessage(Constants_1.C.NOTIFY, options); + _this = _super.call(this, transactions_1.NonInviteClientTransaction, dialog.userAgentCore, message, delegate) || this; + return _this; + } + return NotifyUserAgentClient; +}(user_agent_client_1.UserAgentClient)); +exports.NotifyUserAgentClient = NotifyUserAgentClient; + + +/***/ }), +/* 93 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var transactions_1 = __webpack_require__(52); +var user_agent_server_1 = __webpack_require__(84); +var NotifyUserAgentServer = /** @class */ (function (_super) { + __extends(NotifyUserAgentServer, _super); + /** + * NOTIFY UAS constructor. + * @param dialogOrCore Dialog for in dialog NOTIFY, UserAgentCore for out of dialog NOTIFY (deprecated). + * @param message Incoming NOTIFY request message. + */ + function NotifyUserAgentServer(dialogOrCore, message, delegate) { + var _this = this; + var userAgentCore = instanceOfDialog(dialogOrCore) ? + dialogOrCore.userAgentCore : + dialogOrCore; + _this = _super.call(this, transactions_1.NonInviteServerTransaction, userAgentCore, message, delegate) || this; + return _this; + } + return NotifyUserAgentServer; +}(user_agent_server_1.UserAgentServer)); +exports.NotifyUserAgentServer = NotifyUserAgentServer; +function instanceOfDialog(object) { + return object.userAgentCore !== undefined; +} + + +/***/ }), +/* 94 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Constants_1 = __webpack_require__(3); +var transactions_1 = __webpack_require__(52); +var user_agent_client_1 = __webpack_require__(82); +var PrackUserAgentClient = /** @class */ (function (_super) { + __extends(PrackUserAgentClient, _super); + function PrackUserAgentClient(dialog, delegate, options) { + var _this = this; + var message = dialog.createOutgoingRequestMessage(Constants_1.C.PRACK, options); + _this = _super.call(this, transactions_1.NonInviteClientTransaction, dialog.userAgentCore, message, delegate) || this; + dialog.signalingStateTransition(message); + return _this; + } + return PrackUserAgentClient; +}(user_agent_client_1.UserAgentClient)); +exports.PrackUserAgentClient = PrackUserAgentClient; + + +/***/ }), +/* 95 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var transactions_1 = __webpack_require__(52); +var user_agent_server_1 = __webpack_require__(84); +var PrackUserAgentServer = /** @class */ (function (_super) { + __extends(PrackUserAgentServer, _super); + function PrackUserAgentServer(dialog, message, delegate) { + var _this = _super.call(this, transactions_1.NonInviteServerTransaction, dialog.userAgentCore, message, delegate) || this; + // Update dialog signaling state with offer/answer in body + dialog.signalingStateTransition(message); + _this.dialog = dialog; + return _this; + } + /** + * Update the dialog signaling state on a 2xx response. + * @param options Options bucket. + */ + PrackUserAgentServer.prototype.accept = function (options) { + if (options === void 0) { options = { statusCode: 200 }; } + if (options.body) { + // Update dialog signaling state with offer/answer in body + this.dialog.signalingStateTransition(options.body); + } + return _super.prototype.accept.call(this, options); + }; + return PrackUserAgentServer; +}(user_agent_server_1.UserAgentServer)); +exports.PrackUserAgentServer = PrackUserAgentServer; + + +/***/ }), +/* 96 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Constants_1 = __webpack_require__(3); +var transactions_1 = __webpack_require__(52); +var user_agent_client_1 = __webpack_require__(82); +/** + * 14 Modifying an Existing Session + * https://tools.ietf.org/html/rfc3261#section-14 + * 14.1 UAC Behavior + * https://tools.ietf.org/html/rfc3261#section-14.1 + */ +var ReInviteUserAgentClient = /** @class */ (function (_super) { + __extends(ReInviteUserAgentClient, _super); + function ReInviteUserAgentClient(dialog, delegate, options) { + var _this = this; + var message = dialog.createOutgoingRequestMessage(Constants_1.C.INVITE, options); + _this = _super.call(this, transactions_1.InviteClientTransaction, dialog.userAgentCore, message, delegate) || this; + _this.delegate = delegate; + dialog.signalingStateTransition(message); + // FIXME: TODO: next line obviously needs to be improved... + dialog.reinviteUserAgentClient = _this; // let the dialog know re-invite request sent + _this.dialog = dialog; + return _this; + } + ReInviteUserAgentClient.prototype.receiveResponse = function (message) { + var _this = this; + var statusCode = message.statusCode ? message.statusCode.toString() : ""; + if (!statusCode) { + throw new Error("Response status code undefined."); + } + switch (true) { + case /^100$/.test(statusCode): + if (this.delegate && this.delegate.onTrying) { + this.delegate.onTrying({ message: message }); + } + break; + case /^1[0-9]{2}$/.test(statusCode): + if (this.delegate && this.delegate.onProgress) { + this.delegate.onProgress({ + message: message, + session: this.dialog, + prack: function (options) { + throw new Error("Unimplemented."); + } + }); + } + break; + case /^2[0-9]{2}$/.test(statusCode): + // Update dialog signaling state with offer/answer in body + this.dialog.signalingStateTransition(message); + if (this.delegate && this.delegate.onAccept) { + this.delegate.onAccept({ + message: message, + session: this.dialog, + ack: function (options) { + var outgoingAckRequest = _this.dialog.ack(options); + return outgoingAckRequest; + } + }); + } + break; + case /^3[0-9]{2}$/.test(statusCode): + if (this.delegate && this.delegate.onRedirect) { + this.delegate.onRedirect({ message: message }); + } + break; + case /^[4-6][0-9]{2}$/.test(statusCode): + if (this.delegate && this.delegate.onReject) { + this.delegate.onReject({ message: message }); + } + else { + // If a UA receives a non-2xx final response to a re-INVITE, the session + // parameters MUST remain unchanged, as if no re-INVITE had been issued. + // Note that, as stated in Section 12.2.1.2, if the non-2xx final + // response is a 481 (Call/Transaction Does Not Exist), or a 408 + // (Request Timeout), or no response at all is received for the re- + // INVITE (that is, a timeout is returned by the INVITE client + // transaction), the UAC will terminate the dialog. + // + // If a UAC receives a 491 response to a re-INVITE, it SHOULD start a + // timer with a value T chosen as follows: + // + // 1. If the UAC is the owner of the Call-ID of the dialog ID + // (meaning it generated the value), T has a randomly chosen value + // between 2.1 and 4 seconds in units of 10 ms. + // + // 2. If the UAC is not the owner of the Call-ID of the dialog ID, T + // has a randomly chosen value of between 0 and 2 seconds in units + // of 10 ms. + // + // When the timer fires, the UAC SHOULD attempt the re-INVITE once more, + // if it still desires for that session modification to take place. For + // example, if the call was already hung up with a BYE, the re-INVITE + // would not take place. + // https://tools.ietf.org/html/rfc3261#section-14.1 + // FIXME: TODO: The above. + } + break; + default: + throw new Error("Invalid status code " + statusCode); + } + }; + return ReInviteUserAgentClient; +}(user_agent_client_1.UserAgentClient)); +exports.ReInviteUserAgentClient = ReInviteUserAgentClient; + + +/***/ }), +/* 97 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +var transactions_1 = __webpack_require__(52); +var user_agent_server_1 = __webpack_require__(84); +/** + * 14 Modifying an Existing Session + * https://tools.ietf.org/html/rfc3261#section-14 + * 14.2 UAS Behavior + * https://tools.ietf.org/html/rfc3261#section-14.2 + */ +var ReInviteUserAgentServer = /** @class */ (function (_super) { + __extends(ReInviteUserAgentServer, _super); + function ReInviteUserAgentServer(dialog, message, delegate) { + var _this = _super.call(this, transactions_1.InviteServerTransaction, dialog.userAgentCore, message, delegate) || this; + dialog.reinviteUserAgentServer = _this; + _this.dialog = dialog; + return _this; + } + /** + * Update the dialog signaling state on a 2xx response. + * @param options Options bucket. + */ + ReInviteUserAgentServer.prototype.accept = function (options) { + if (options === void 0) { options = { statusCode: 200 }; } + // FIXME: The next two lines SHOULD go away, but I suppose it's technically harmless... + // These are here because some versions of SIP.js prior to 0.13.8 set the route set + // of all in dialog ACKs based on the Record-Route headers in the associated 2xx + // response. While this worked for dialog forming 2xx responses, it was technically + // broken for re-INVITE ACKS as it only worked if the UAS populated the Record-Route + // headers in the re-INVITE 2xx response (which is not required and a waste of bandwidth + // as the should be ignored if present in re-INVITE ACKS) and the UAS populated + // the Record-Route headers with the correct values (would be weird not too, but...). + // Anyway, for now the technically useless Record-Route headers are being added + // to maintain "backwards compatibility" with the older broken versions of SIP.js. + options.extraHeaders = options.extraHeaders || []; + options.extraHeaders = options.extraHeaders.concat(this.dialog.routeSet.map(function (route) { return "Record-Route: " + route; })); + // Send and return the response + var response = _super.prototype.accept.call(this, options); + var session = this.dialog; + var result = __assign({}, response, { session: session }); + if (options.body) { + // Update dialog signaling state with offer/answer in body + this.dialog.signalingStateTransition(options.body); + } + // Update dialog + this.dialog.reConfirm(); + return result; + }; + /** + * Update the dialog signaling state on a 1xx response. + * @param options Progress options bucket. + */ + ReInviteUserAgentServer.prototype.progress = function (options) { + if (options === void 0) { options = { statusCode: 180 }; } + // Send and return the response + var response = _super.prototype.progress.call(this, options); + var session = this.dialog; + var result = __assign({}, response, { session: session }); + // Update dialog signaling state + if (options.body) { + this.dialog.signalingStateTransition(options.body); + } + return result; + }; + return ReInviteUserAgentServer; +}(user_agent_server_1.UserAgentServer)); +exports.ReInviteUserAgentServer = ReInviteUserAgentServer; + + +/***/ }), +/* 98 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Constants_1 = __webpack_require__(3); +var transactions_1 = __webpack_require__(52); +var user_agent_client_1 = __webpack_require__(82); +var ReferUserAgentClient = /** @class */ (function (_super) { + __extends(ReferUserAgentClient, _super); + function ReferUserAgentClient(dialog, delegate, options) { + var _this = this; + var message = dialog.createOutgoingRequestMessage(Constants_1.C.REFER, options); + _this = _super.call(this, transactions_1.NonInviteClientTransaction, dialog.userAgentCore, message, delegate) || this; + return _this; + } + return ReferUserAgentClient; +}(user_agent_client_1.UserAgentClient)); +exports.ReferUserAgentClient = ReferUserAgentClient; + + +/***/ }), +/* 99 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var transactions_1 = __webpack_require__(52); +var user_agent_server_1 = __webpack_require__(84); +var ReferUserAgentServer = /** @class */ (function (_super) { + __extends(ReferUserAgentServer, _super); + /** + * REFER UAS constructor. + * @param dialogOrCore Dialog for in dialog REFER, UserAgentCore for out of dialog REFER. + * @param message Incoming REFER request message. + */ + function ReferUserAgentServer(dialogOrCore, message, delegate) { + var _this = this; + var userAgentCore = instanceOfSessionDialog(dialogOrCore) ? + dialogOrCore.userAgentCore : + dialogOrCore; + _this = _super.call(this, transactions_1.NonInviteServerTransaction, userAgentCore, message, delegate) || this; + return _this; + } + return ReferUserAgentServer; +}(user_agent_server_1.UserAgentServer)); +exports.ReferUserAgentServer = ReferUserAgentServer; +function instanceOfSessionDialog(object) { + return object.userAgentCore !== undefined; +} + + +/***/ }), +/* 100 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Constants_1 = __webpack_require__(3); +var NameAddrHeader_1 = __webpack_require__(9); +var Timers_1 = __webpack_require__(56); +var subscription_1 = __webpack_require__(72); +var allowed_methods_1 = __webpack_require__(74); +var notify_user_agent_server_1 = __webpack_require__(93); +var re_subscribe_user_agent_client_1 = __webpack_require__(101); +var dialog_1 = __webpack_require__(89); +/** + * SIP-Specific Event Notification + * + * Abstract + * + * This document describes an extension to the Session Initiation + * Protocol (SIP) defined by RFC 3261. The purpose of this extension is + * to provide an extensible framework by which SIP nodes can request + * notification from remote nodes indicating that certain events have + * occurred. + * + * Note that the event notification mechanisms defined herein are NOT + * intended to be a general-purpose infrastructure for all classes of + * event subscription and notification. + * + * This document represents a backwards-compatible improvement on the + * original mechanism described by RFC 3265, taking into account several + * years of implementation experience. Accordingly, this document + * obsoletes RFC 3265. This document also updates RFC 4660 slightly to + * accommodate some small changes to the mechanism that were discussed + * in that document. + * + * https://tools.ietf.org/html/rfc6665 + */ +var SubscriptionDialog = /** @class */ (function (_super) { + __extends(SubscriptionDialog, _super); + function SubscriptionDialog(subscriptionEvent, subscriptionExpires, subscriptionState, core, state, delegate) { + var _this = _super.call(this, core, state) || this; + _this.delegate = delegate; + _this._autoRefresh = false; + _this._subscriptionEvent = subscriptionEvent; + _this._subscriptionExpires = subscriptionExpires; + _this._subscriptionExpiresInitial = subscriptionExpires; + _this._subscriptionExpiresLastSet = Math.floor(Date.now() / 1000); + _this._subscriptionRefresh = undefined; + _this._subscriptionRefreshLastSet = undefined; + _this._subscriptionState = subscriptionState; + _this.logger = core.loggerFactory.getLogger("sip.subscribe-dialog"); + _this.logger.log("SUBSCRIBE dialog " + _this.id + " constructed"); + return _this; + } + /** + * When a UAC receives a response that establishes a dialog, it + * constructs the state of the dialog. This state MUST be maintained + * for the duration of the dialog. + * https://tools.ietf.org/html/rfc3261#section-12.1.2 + * @param outgoingRequestMessage Outgoing request message for dialog. + * @param incomingResponseMessage Incoming response message creating dialog. + */ + SubscriptionDialog.initialDialogStateForSubscription = function (outgoingSubscribeRequestMessage, incomingNotifyRequestMessage) { + // If the request was sent over TLS, and the Request-URI contained a + // SIPS URI, the "secure" flag is set to TRUE. + // https://tools.ietf.org/html/rfc3261#section-12.1.2 + var secure = false; // FIXME: Currently no support for TLS. + // The route set MUST be set to the list of URIs in the Record-Route + // header field from the response, taken in reverse order and preserving + // all URI parameters. If no Record-Route header field is present in + // the response, the route set MUST be set to the empty set. This route + // set, even if empty, overrides any pre-existing route set for future + // requests in this dialog. The remote target MUST be set to the URI + // from the Contact header field of the response. + // https://tools.ietf.org/html/rfc3261#section-12.1.2 + var routeSet = incomingNotifyRequestMessage.getHeaders("record-route"); + var contact = incomingNotifyRequestMessage.parseHeader("contact"); + if (!contact) { // TODO: Review to make sure this will never happen + throw new Error("Contact undefined."); + } + if (!(contact instanceof NameAddrHeader_1.NameAddrHeader)) { + throw new Error("Contact not instance of NameAddrHeader."); + } + var remoteTarget = contact.uri; + // The local sequence number MUST be set to the value of the sequence + // number in the CSeq header field of the request. The remote sequence + // number MUST be empty (it is established when the remote UA sends a + // request within the dialog). The call identifier component of the + // dialog ID MUST be set to the value of the Call-ID in the request. + // The local tag component of the dialog ID MUST be set to the tag in + // the From field in the request, and the remote tag component of the + // dialog ID MUST be set to the tag in the To field of the response. A + // UAC MUST be prepared to receive a response without a tag in the To + // field, in which case the tag is considered to have a value of null. + // + // This is to maintain backwards compatibility with RFC 2543, which + // did not mandate To tags. + // + // https://tools.ietf.org/html/rfc3261#section-12.1.2 + var localSequenceNumber = outgoingSubscribeRequestMessage.cseq; + var remoteSequenceNumber = undefined; + var callId = outgoingSubscribeRequestMessage.callId; + var localTag = outgoingSubscribeRequestMessage.fromTag; + var remoteTag = incomingNotifyRequestMessage.fromTag; + if (!callId) { // TODO: Review to make sure this will never happen + throw new Error("Call id undefined."); + } + if (!localTag) { // TODO: Review to make sure this will never happen + throw new Error("From tag undefined."); + } + if (!remoteTag) { // TODO: Review to make sure this will never happen + throw new Error("To tag undefined."); // FIXME: No backwards compatibility with RFC 2543 + } + // The remote URI MUST be set to the URI in the To field, and the local + // URI MUST be set to the URI in the From field. + // https://tools.ietf.org/html/rfc3261#section-12.1.2 + if (!outgoingSubscribeRequestMessage.from) { // TODO: Review to make sure this will never happen + throw new Error("From undefined."); + } + if (!outgoingSubscribeRequestMessage.to) { // TODO: Review to make sure this will never happen + throw new Error("To undefined."); + } + var localURI = outgoingSubscribeRequestMessage.from.uri; + var remoteURI = outgoingSubscribeRequestMessage.to.uri; + // A dialog can also be in the "early" state, which occurs when it is + // created with a provisional response, and then transition to the + // "confirmed" state when a 2xx final response arrives. + // https://tools.ietf.org/html/rfc3261#section-12 + var early = false; + var dialogState = { + id: callId + localTag + remoteTag, + early: early, + callId: callId, + localTag: localTag, + remoteTag: remoteTag, + localSequenceNumber: localSequenceNumber, + remoteSequenceNumber: remoteSequenceNumber, + localURI: localURI, + remoteURI: remoteURI, + remoteTarget: remoteTarget, + routeSet: routeSet, + secure: secure + }; + return dialogState; + }; + SubscriptionDialog.prototype.dispose = function () { + _super.prototype.dispose.call(this); + if (this.N) { + clearTimeout(this.N); + this.N = undefined; + } + this.refreshTimerClear(); + this.logger.log("SUBSCRIBE dialog " + this.id + " destroyed"); + }; + Object.defineProperty(SubscriptionDialog.prototype, "autoRefresh", { + get: function () { + return this._autoRefresh; + }, + set: function (autoRefresh) { + this._autoRefresh = true; + this.refreshTimerSet(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SubscriptionDialog.prototype, "subscriptionEvent", { + get: function () { + return this._subscriptionEvent; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SubscriptionDialog.prototype, "subscriptionExpires", { + /** Number of seconds until subscription expires. */ + get: function () { + var secondsSinceLastSet = Math.floor(Date.now() / 1000) - this._subscriptionExpiresLastSet; + var secondsUntilExpires = this._subscriptionExpires - secondsSinceLastSet; + return Math.max(secondsUntilExpires, 0); + }, + set: function (expires) { + if (expires < 0) { + throw new Error("Expires must be greater than or equal to zero."); + } + this._subscriptionExpires = expires; + this._subscriptionExpiresLastSet = Math.floor(Date.now() / 1000); + if (this.autoRefresh) { + var refresh = this.subscriptionRefresh; + if (refresh === undefined || refresh >= expires) { + this.refreshTimerSet(); + } + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SubscriptionDialog.prototype, "subscriptionExpiresInitial", { + get: function () { + return this._subscriptionExpiresInitial; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SubscriptionDialog.prototype, "subscriptionRefresh", { + /** Number of seconds until subscription auto refresh. */ + get: function () { + if (this._subscriptionRefresh === undefined || this._subscriptionRefreshLastSet === undefined) { + return undefined; + } + var secondsSinceLastSet = Math.floor(Date.now() / 1000) - this._subscriptionRefreshLastSet; + var secondsUntilExpires = this._subscriptionRefresh - secondsSinceLastSet; + return Math.max(secondsUntilExpires, 0); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SubscriptionDialog.prototype, "subscriptionState", { + get: function () { + return this._subscriptionState; + }, + enumerable: true, + configurable: true + }); + /** + * Receive in dialog request message from transport. + * @param message The incoming request message. + */ + SubscriptionDialog.prototype.receiveRequest = function (message) { + this.logger.log("SUBSCRIBE dialog " + this.id + " received " + message.method + " request"); + // Request within a dialog out of sequence guard. + // https://tools.ietf.org/html/rfc3261#section-12.2.2 + if (!this.sequenceGuard(message)) { + this.logger.log("SUBSCRIBE dialog " + this.id + " rejected out of order " + message.method + " request."); + return; + } + // Request within a dialog common processing. + // https://tools.ietf.org/html/rfc3261#section-12.2.2 + _super.prototype.receiveRequest.call(this, message); + // Switch on method and then delegate. + switch (message.method) { + case Constants_1.C.NOTIFY: + this.onNotify(message); + break; + default: + this.logger.log("SUBSCRIBE dialog " + this.id + " received unimplemented " + message.method + " request"); + this.core.replyStateless(message, { statusCode: 501 }); + break; + } + }; + /** + * 4.1.2.2. Refreshing of Subscriptions + * https://tools.ietf.org/html/rfc6665#section-4.1.2.2 + */ + SubscriptionDialog.prototype.refresh = function () { + var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); + var options = {}; + options.extraHeaders = (options.extraHeaders || []).slice(); + options.extraHeaders.push(allowHeader); + options.extraHeaders.push("Event: " + this.subscriptionEvent); + options.extraHeaders.push("Expires: " + this.subscriptionExpiresInitial); + options.extraHeaders.push("Contact: " + this.core.configuration.contact.toString()); + return this.subscribe(undefined, options); + }; + /** + * 4.1.2.2. Refreshing of Subscriptions + * https://tools.ietf.org/html/rfc6665#section-4.1.2.2 + * @param delegate Delegate to handle responses. + * @param options Options bucket. + */ + SubscriptionDialog.prototype.subscribe = function (delegate, options) { + var _this = this; + if (options === void 0) { options = {}; } + if (this.subscriptionState !== subscription_1.SubscriptionState.Pending && this.subscriptionState !== subscription_1.SubscriptionState.Active) { + // FIXME: This needs to be a proper exception + throw new Error("Invalid state " + this.subscriptionState + ". May only re-subscribe while in state \"pending\" or \"active\"."); + } + this.logger.log("SUBSCRIBE dialog " + this.id + " sending SUBSCRIBE request"); + var uac = new re_subscribe_user_agent_client_1.ReSubscribeUserAgentClient(this, delegate, options); + // When refreshing a subscription, a subscriber starts Timer N, set to + // 64*T1, when it sends the SUBSCRIBE request. + // https://tools.ietf.org/html/rfc6665#section-4.1.2.2 + this.N = setTimeout(function () { return _this.timer_N(); }, Timers_1.Timers.TIMER_N); + return uac; + }; + /** + * 4.4.1. Dialog Creation and Termination + * A subscription is destroyed after a notifier sends a NOTIFY request + * with a "Subscription-State" of "terminated", or in certain error + * situations described elsewhere in this document. + * https://tools.ietf.org/html/rfc6665#section-4.4.1 + */ + SubscriptionDialog.prototype.terminate = function () { + this.stateTransition(subscription_1.SubscriptionState.Terminated); + this.onTerminated(); + }; + /** + * 4.1.2.3. Unsubscribing + * https://tools.ietf.org/html/rfc6665#section-4.1.2.3 + */ + SubscriptionDialog.prototype.unsubscribe = function () { + var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); + var options = {}; + options.extraHeaders = (options.extraHeaders || []).slice(); + options.extraHeaders.push(allowHeader); + options.extraHeaders.push("Event: " + this.subscriptionEvent); + options.extraHeaders.push("Expires: 0"); + options.extraHeaders.push("Contact: " + this.core.configuration.contact.toString()); + return this.subscribe(undefined, options); + }; + /** + * Handle in dialog NOTIFY requests. + * This does not include the first NOTIFY which created the dialog. + * @param message The incoming NOTIFY request message. + */ + SubscriptionDialog.prototype.onNotify = function (message) { + // If, for some reason, the event package designated in the "Event" + // header field of the NOTIFY request is not supported, the subscriber + // will respond with a 489 (Bad Event) response. + // https://tools.ietf.org/html/rfc6665#section-4.1.3 + var event = message.parseHeader("Event").event; + if (!event || event !== this.subscriptionEvent) { + this.core.replyStateless(message, { statusCode: 489 }); + return; + } + // In the state diagram, "Re-subscription times out" means that an + // attempt to refresh or update the subscription using a new SUBSCRIBE + // request does not result in a NOTIFY request before the corresponding + // Timer N expires. + // https://tools.ietf.org/html/rfc6665#section-4.1.2 + if (this.N) { + clearTimeout(this.N); + this.N = undefined; + } + // NOTIFY requests MUST contain "Subscription-State" header fields that + // indicate the status of the subscription. + // https://tools.ietf.org/html/rfc6665#section-4.1.3 + var subscriptionState = message.parseHeader("Subscription-State"); + if (!subscriptionState || !subscriptionState.state) { + this.core.replyStateless(message, { statusCode: 489 }); + return; + } + var state = subscriptionState.state; + var expires = subscriptionState.expires ? Math.max(subscriptionState.expires, 0) : undefined; + // Update our state and expiration. + switch (state) { + case "pending": + this.stateTransition(subscription_1.SubscriptionState.Pending, expires); + break; + case "active": + this.stateTransition(subscription_1.SubscriptionState.Active, expires); + break; + case "terminated": + this.stateTransition(subscription_1.SubscriptionState.Terminated, expires); + break; + default: + this.logger.warn("Unrecognized subscription state."); + break; + } + // Delegate remainder of NOTIFY handling. + var uas = new notify_user_agent_server_1.NotifyUserAgentServer(this, message); + if (this.delegate && this.delegate.onNotify) { + this.delegate.onNotify(uas); + } + else { + uas.accept(); + } + }; + SubscriptionDialog.prototype.onRefresh = function (request) { + if (this.delegate && this.delegate.onRefresh) { + this.delegate.onRefresh(request); + } + }; + SubscriptionDialog.prototype.onTerminated = function () { + if (this.delegate && this.delegate.onTerminated) { + this.delegate.onTerminated(); + } + }; + SubscriptionDialog.prototype.refreshTimerClear = function () { + if (this.refreshTimer) { + clearTimeout(this.refreshTimer); + this.refreshTimer = undefined; + } + }; + SubscriptionDialog.prototype.refreshTimerSet = function () { + var _this = this; + this.refreshTimerClear(); + if (this.autoRefresh && this.subscriptionExpires > 0) { + var refresh = this.subscriptionExpires * 900; + this._subscriptionRefresh = Math.floor(refresh / 1000); + this._subscriptionRefreshLastSet = Math.floor(Date.now() / 1000); + this.refreshTimer = setTimeout(function () { + _this.refreshTimer = undefined; + _this._subscriptionRefresh = undefined; + _this._subscriptionRefreshLastSet = undefined; + _this.onRefresh(_this.refresh()); + }, refresh); + } + }; + SubscriptionDialog.prototype.stateTransition = function (newState, newExpires) { + var _this = this; + // Assert valid state transitions. + var invalidStateTransition = function () { + _this.logger.warn("Invalid subscription state transition from " + _this.subscriptionState + " to " + newState); + }; + switch (newState) { + case subscription_1.SubscriptionState.Initial: + invalidStateTransition(); + return; + case subscription_1.SubscriptionState.NotifyWait: + invalidStateTransition(); + return; + case subscription_1.SubscriptionState.Pending: + if (this.subscriptionState !== subscription_1.SubscriptionState.NotifyWait && + this.subscriptionState !== subscription_1.SubscriptionState.Pending) { + invalidStateTransition(); + return; + } + break; + case subscription_1.SubscriptionState.Active: + if (this.subscriptionState !== subscription_1.SubscriptionState.NotifyWait && + this.subscriptionState !== subscription_1.SubscriptionState.Pending && + this.subscriptionState !== subscription_1.SubscriptionState.Active) { + invalidStateTransition(); + return; + } + break; + case subscription_1.SubscriptionState.Terminated: + if (this.subscriptionState !== subscription_1.SubscriptionState.NotifyWait && + this.subscriptionState !== subscription_1.SubscriptionState.Pending && + this.subscriptionState !== subscription_1.SubscriptionState.Active) { + invalidStateTransition(); + return; + } + break; + default: + invalidStateTransition(); + return; + } + // If the "Subscription-State" value is "pending", the subscription has + // been received by the notifier, but there is insufficient policy + // information to grant or deny the subscription yet. If the header + // field also contains an "expires" parameter, the subscriber SHOULD + // take it as the authoritative subscription duration and adjust + // accordingly. No further action is necessary on the part of the + // subscriber. The "retry-after" and "reason" parameters have no + // semantics for "pending". + // https://tools.ietf.org/html/rfc6665#section-4.1.3 + if (newState === subscription_1.SubscriptionState.Pending) { + if (newExpires) { + this.subscriptionExpires = newExpires; + } + } + // If the "Subscription-State" header field value is "active", it means + // that the subscription has been accepted and (in general) has been + // authorized. If the header field also contains an "expires" + // parameter, the subscriber SHOULD take it as the authoritative + // subscription duration and adjust accordingly. The "retry-after" and + // "reason" parameters have no semantics for "active". + // https://tools.ietf.org/html/rfc6665#section-4.1.3 + if (newState === subscription_1.SubscriptionState.Active) { + if (newExpires) { + this.subscriptionExpires = newExpires; + } + } + // If the "Subscription-State" value is "terminated", the subscriber + // MUST consider the subscription terminated. The "expires" parameter + // has no semantics for "terminated" -- notifiers SHOULD NOT include an + // "expires" parameter on a "Subscription-State" header field with a + // value of "terminated", and subscribers MUST ignore any such + // parameter, if present. + if (newState === subscription_1.SubscriptionState.Terminated) { + this.dispose(); + } + this._subscriptionState = newState; + }; + /** + * When refreshing a subscription, a subscriber starts Timer N, set to + * 64*T1, when it sends the SUBSCRIBE request. If this Timer N expires + * prior to the receipt of a NOTIFY request, the subscriber considers + * the subscription terminated. If the subscriber receives a success + * response to the SUBSCRIBE request that indicates that no NOTIFY + * request will be generated -- such as the 204 response defined for use + * with the optional extension described in [RFC5839] -- then it MUST + * cancel Timer N. + * https://tools.ietf.org/html/rfc6665#section-4.1.2.2 + */ + SubscriptionDialog.prototype.timer_N = function () { + if (this.subscriptionState !== subscription_1.SubscriptionState.Terminated) { + this.stateTransition(subscription_1.SubscriptionState.Terminated); + this.onTerminated(); + } + }; + return SubscriptionDialog; +}(dialog_1.Dialog)); +exports.SubscriptionDialog = SubscriptionDialog; + + +/***/ }), +/* 101 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Constants_1 = __webpack_require__(3); +var transactions_1 = __webpack_require__(52); +var user_agent_client_1 = __webpack_require__(82); +var ReSubscribeUserAgentClient = /** @class */ (function (_super) { + __extends(ReSubscribeUserAgentClient, _super); + function ReSubscribeUserAgentClient(dialog, delegate, options) { + var _this = this; + var message = dialog.createOutgoingRequestMessage(Constants_1.C.SUBSCRIBE, options); + _this = _super.call(this, transactions_1.NonInviteClientTransaction, dialog.userAgentCore, message, delegate) || this; + _this.dialog = dialog; + return _this; + } + ReSubscribeUserAgentClient.prototype.waitNotifyStop = function () { + // TODO: Placeholder. Not utilized currently. + return; + }; + /** + * Receive a response from the transaction layer. + * @param message Incoming response message. + */ + ReSubscribeUserAgentClient.prototype.receiveResponse = function (message) { + if (message.statusCode && message.statusCode >= 200 && message.statusCode < 300) { + // The "Expires" header field in a 200-class response to SUBSCRIBE + // request indicates the actual duration for which the subscription will + // remain active (unless refreshed). The received value might be + // smaller than the value indicated in the SUBSCRIBE request but cannot + // be larger; see Section 4.2.1 for details. + // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 + var expires = message.getHeader("Expires"); + if (!expires) { + this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE"); + } + else { + var subscriptionExpiresReceived = Number(expires); + if (this.dialog.subscriptionExpires > subscriptionExpiresReceived) { + this.dialog.subscriptionExpires = subscriptionExpiresReceived; + } + } + } + if (message.statusCode && message.statusCode >= 400 && message.statusCode < 700) { + // If a SUBSCRIBE request to refresh a subscription receives a 404, 405, + // 410, 416, 480-485, 489, 501, or 604 response, the subscriber MUST + // consider the subscription terminated. (See [RFC5057] for further + // details and notes about the effect of error codes on dialogs and + // usages within dialog, such as subscriptions). If the subscriber + // wishes to re-subscribe to the state, he does so by composing an + // unrelated initial SUBSCRIBE request with a freshly generated Call-ID + // and a new, unique "From" tag (see Section 4.1.2.1). + // https://tools.ietf.org/html/rfc6665#section-4.1.2.2 + var errorCodes = [404, 405, 410, 416, 480, 481, 482, 483, 484, 485, 489, 501, 604]; + if (errorCodes.includes(message.statusCode)) { + this.dialog.terminate(); + } + // If a SUBSCRIBE request to refresh a subscription fails with any error + // code other than those listed above, the original subscription is + // still considered valid for the duration of the most recently known + // "Expires" value as negotiated by the most recent successful SUBSCRIBE + // transaction, or as communicated by a NOTIFY request in its + // "Subscription-State" header field "expires" parameter. + // https://tools.ietf.org/html/rfc6665#section-4.1.2.2 + } + _super.prototype.receiveResponse.call(this, message); + }; + return ReSubscribeUserAgentClient; +}(user_agent_client_1.UserAgentClient)); +exports.ReSubscribeUserAgentClient = ReSubscribeUserAgentClient; + + +/***/ }), +/* 102 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +var Exceptions_1 = __webpack_require__(47); +var dialogs_1 = __webpack_require__(88); +var session_1 = __webpack_require__(68); +var transactions_1 = __webpack_require__(52); +var allowed_methods_1 = __webpack_require__(74); +var user_agent_server_1 = __webpack_require__(84); +/** + * 13 Initiating a Session + * https://tools.ietf.org/html/rfc3261#section-13 + * 13.1 Overview + * https://tools.ietf.org/html/rfc3261#section-13.1 + * 13.3 UAS Processing + * https://tools.ietf.org/html/rfc3261#section-13.3 + */ +var InviteUserAgentServer = /** @class */ (function (_super) { + __extends(InviteUserAgentServer, _super); + function InviteUserAgentServer(core, message, delegate) { + var _this = _super.call(this, transactions_1.InviteServerTransaction, core, message, delegate) || this; + _this.core = core; + return _this; + } + InviteUserAgentServer.prototype.dispose = function () { + if (this.earlyDialog) { + this.earlyDialog.dispose(); + } + _super.prototype.dispose.call(this); + }; + /** + * 13.3.1.4 The INVITE is Accepted + * The UAS core generates a 2xx response. This response establishes a + * dialog, and therefore follows the procedures of Section 12.1.1 in + * addition to those of Section 8.2.6. + * https://tools.ietf.org/html/rfc3261#section-13.3.1.4 + * @param options Accept options bucket. + */ + InviteUserAgentServer.prototype.accept = function (options) { + if (options === void 0) { options = { statusCode: 200 }; } + if (!this.acceptable) { + throw new Exceptions_1.Exceptions.TransactionStateError(this.message.method + " not acceptable in state " + this.transaction.state + "."); + } + // This response establishes a dialog... + // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 + if (!this.confirmedDialog) { + if (this.earlyDialog) { + this.earlyDialog.confirm(); + this.confirmedDialog = this.earlyDialog; + this.earlyDialog = undefined; + } + else { + var transaction = this.transaction; + if (!(transaction instanceof transactions_1.InviteServerTransaction)) { + throw new Error("Transaction not instance of InviteClientTransaction."); + } + var state = dialogs_1.Dialog.initialDialogStateForUserAgentServer(this.message, this.toTag); + this.confirmedDialog = new dialogs_1.SessionDialog(transaction, this.core, state); + } + } + // When a UAS responds to a request with a response that establishes a + // dialog (such as a 2xx to INVITE), the UAS MUST copy all Record-Route + // header field values from the request into the response (including the + // URIs, URI parameters, and any Record-Route header field parameters, + // whether they are known or unknown to the UAS) and MUST maintain the + // order of those values. The UAS MUST add a Contact header field to + // the response. The Contact header field contains an address where the + // UAS would like to be contacted for subsequent requests in the dialog + // (which includes the ACK for a 2xx response in the case of an INVITE). + // Generally, the host portion of this URI is the IP address or FQDN of + // the host. The URI provided in the Contact header field MUST be a SIP + // or SIPS URI. If the request that initiated the dialog contained a + // SIPS URI in the Request-URI or in the top Record-Route header field + // value, if there was any, or the Contact header field if there was no + // Record-Route header field, the Contact header field in the response + // MUST be a SIPS URI. The URI SHOULD have global scope (that is, the + // same URI can be used in messages outside this dialog). The same way, + // the scope of the URI in the Contact header field of the INVITE is not + // limited to this dialog either. It can therefore be used in messages + // to the UAC even outside this dialog. + // https://tools.ietf.org/html/rfc3261#section-12.1.1 + var recordRouteHeader = this.message + .getHeaders("record-route") + .map(function (header) { return "Record-Route: " + header; }); + var contactHeader = "Contact: " + this.core.configuration.contact.toString(); + // A 2xx response to an INVITE SHOULD contain the Allow header field and + // the Supported header field, and MAY contain the Accept header field. + // Including these header fields allows the UAC to determine the + // features and extensions supported by the UAS for the duration of the + // call, without probing. + // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 + // FIXME: TODO: This should not be hard coded. + var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); + // FIXME: TODO: Supported header (see reply()) + // FIXME: TODO: Accept header + // If the INVITE request contained an offer, and the UAS had not yet + // sent an answer, the 2xx MUST contain an answer. If the INVITE did + // not contain an offer, the 2xx MUST contain an offer if the UAS had + // not yet sent an offer. + // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 + if (!options.body) { + if (this.confirmedDialog.signalingState === session_1.SignalingState.Initial || + this.confirmedDialog.signalingState === session_1.SignalingState.HaveRemoteOffer) { + throw new Error("Response must have a body."); + } + } + // FIXME: TODO: Guard offer/answer + options.statusCode = options.statusCode || 200; + options.extraHeaders = options.extraHeaders || []; + options.extraHeaders = options.extraHeaders.concat(recordRouteHeader); + options.extraHeaders.push(allowHeader); + options.extraHeaders.push(contactHeader); + var response = _super.prototype.accept.call(this, options); + var session = this.confirmedDialog; + var result = __assign({}, response, { session: session }); + // Update dialog signaling state + if (options.body) { + this.confirmedDialog.signalingStateTransition(options.body); + } + return result; + }; + /** + * 13.3.1.1 Progress + * If the UAS is not able to answer the invitation immediately, it can + * choose to indicate some kind of progress to the UAC (for example, an + * indication that a phone is ringing). This is accomplished with a + * provisional response between 101 and 199. These provisional + * responses establish early dialogs and therefore follow the procedures + * of Section 12.1.1 in addition to those of Section 8.2.6. A UAS MAY + * send as many provisional responses as it likes. Each of these MUST + * indicate the same dialog ID. However, these will not be delivered + * reliably. + * + * If the UAS desires an extended period of time to answer the INVITE, + * it will need to ask for an "extension" in order to prevent proxies + * from canceling the transaction. A proxy has the option of canceling + * a transaction when there is a gap of 3 minutes between responses in a + * transaction. To prevent cancellation, the UAS MUST send a non-100 + * provisional response at every minute, to handle the possibility of + * lost provisional responses. + * https://tools.ietf.org/html/rfc3261#section-13.3.1.1 + * @param options Progress options bucket. + */ + InviteUserAgentServer.prototype.progress = function (options) { + if (options === void 0) { options = { statusCode: 180 }; } + if (!this.progressable) { + throw new Exceptions_1.Exceptions.TransactionStateError(this.message.method + " not progressable in state " + this.transaction.state + "."); + } + // This response establishes a dialog... + // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 + if (!this.earlyDialog) { + var transaction = this.transaction; + if (!(transaction instanceof transactions_1.InviteServerTransaction)) { + throw new Error("Transaction not instance of InviteClientTransaction."); + } + var state = dialogs_1.Dialog.initialDialogStateForUserAgentServer(this.message, this.toTag, true); + this.earlyDialog = new dialogs_1.SessionDialog(transaction, this.core, state); + } + // When a UAS responds to a request with a response that establishes a + // dialog (such as a 2xx to INVITE), the UAS MUST copy all Record-Route + // header field values from the request into the response (including the + // URIs, URI parameters, and any Record-Route header field parameters, + // whether they are known or unknown to the UAS) and MUST maintain the + // order of those values. The UAS MUST add a Contact header field to + // the response. The Contact header field contains an address where the + // UAS would like to be contacted for subsequent requests in the dialog + // (which includes the ACK for a 2xx response in the case of an INVITE). + // Generally, the host portion of this URI is the IP address or FQDN of + // the host. The URI provided in the Contact header field MUST be a SIP + // or SIPS URI. If the request that initiated the dialog contained a + // SIPS URI in the Request-URI or in the top Record-Route header field + // value, if there was any, or the Contact header field if there was no + // Record-Route header field, the Contact header field in the response + // MUST be a SIPS URI. The URI SHOULD have global scope (that is, the + // same URI can be used in messages outside this dialog). The same way, + // the scope of the URI in the Contact header field of the INVITE is not + // limited to this dialog either. It can therefore be used in messages + // to the UAC even outside this dialog. + // https://tools.ietf.org/html/rfc3261#section-12.1.1 + var recordRouteHeader = this.message + .getHeaders("record-route") + .map(function (header) { return "Record-Route: " + header; }); + var contactHeader = "Contact: " + this.core.configuration.contact; + options.extraHeaders = options.extraHeaders || []; + options.extraHeaders = options.extraHeaders.concat(recordRouteHeader); + options.extraHeaders.push(contactHeader); + var response = _super.prototype.progress.call(this, options); + var session = this.earlyDialog; + var result = __assign({}, response, { session: session }); + // Update dialog signaling state + if (options.body) { + this.earlyDialog.signalingStateTransition(options.body); + } + return result; + }; + /** + * 13.3.1.2 The INVITE is Redirected + * If the UAS decides to redirect the call, a 3xx response is sent. A + * 300 (Multiple Choices), 301 (Moved Permanently) or 302 (Moved + * Temporarily) response SHOULD contain a Contact header field + * containing one or more URIs of new addresses to be tried. The + * response is passed to the INVITE server transaction, which will deal + * with its retransmissions. + * https://tools.ietf.org/html/rfc3261#section-13.3.1.2 + * @param options Reject options bucket. + */ + InviteUserAgentServer.prototype.redirect = function (contacts, options) { + if (options === void 0) { options = { statusCode: 302 }; } + return _super.prototype.redirect.call(this, contacts, options); + }; + /** + * 13.3.1.3 The INVITE is Rejected + * A common scenario occurs when the callee is currently not willing or + * able to take additional calls at this end system. A 486 (Busy Here) + * SHOULD be returned in such a scenario. + * https://tools.ietf.org/html/rfc3261#section-13.3.1.3 + * @param options Reject options bucket. + */ + InviteUserAgentServer.prototype.reject = function (options) { + if (options === void 0) { options = { statusCode: 486 }; } + return _super.prototype.reject.call(this, options); + }; + return InviteUserAgentServer; +}(user_agent_server_1.UserAgentServer)); +exports.InviteUserAgentServer = InviteUserAgentServer; + + +/***/ }), +/* 103 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var transactions_1 = __webpack_require__(52); +var user_agent_client_1 = __webpack_require__(82); +var MessageUserAgentClient = /** @class */ (function (_super) { + __extends(MessageUserAgentClient, _super); + function MessageUserAgentClient(core, message, delegate) { + return _super.call(this, transactions_1.NonInviteClientTransaction, core, message, delegate) || this; + } + return MessageUserAgentClient; +}(user_agent_client_1.UserAgentClient)); +exports.MessageUserAgentClient = MessageUserAgentClient; + + +/***/ }), +/* 104 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var transactions_1 = __webpack_require__(52); +var user_agent_server_1 = __webpack_require__(84); +var MessageUserAgentServer = /** @class */ (function (_super) { + __extends(MessageUserAgentServer, _super); + function MessageUserAgentServer(core, message, delegate) { + var _this = _super.call(this, transactions_1.NonInviteServerTransaction, core, message, delegate) || this; + _this.core = core; + return _this; + } + return MessageUserAgentServer; +}(user_agent_server_1.UserAgentServer)); +exports.MessageUserAgentServer = MessageUserAgentServer; + + +/***/ }), +/* 105 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var transactions_1 = __webpack_require__(52); +var user_agent_client_1 = __webpack_require__(82); +var PublishUserAgentClient = /** @class */ (function (_super) { + __extends(PublishUserAgentClient, _super); + function PublishUserAgentClient(core, message, delegate) { + return _super.call(this, transactions_1.NonInviteClientTransaction, core, message, delegate) || this; + } + return PublishUserAgentClient; +}(user_agent_client_1.UserAgentClient)); +exports.PublishUserAgentClient = PublishUserAgentClient; + + +/***/ }), +/* 106 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var transactions_1 = __webpack_require__(52); +var user_agent_server_1 = __webpack_require__(84); +var ReSubscribeUserAgentServer = /** @class */ (function (_super) { + __extends(ReSubscribeUserAgentServer, _super); + function ReSubscribeUserAgentServer(dialog, message, delegate) { + return _super.call(this, transactions_1.NonInviteServerTransaction, dialog.userAgentCore, message, delegate) || this; + } + return ReSubscribeUserAgentServer; +}(user_agent_server_1.UserAgentServer)); +exports.ReSubscribeUserAgentServer = ReSubscribeUserAgentServer; + + +/***/ }), +/* 107 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var transactions_1 = __webpack_require__(52); +var user_agent_client_1 = __webpack_require__(82); +var RegisterUserAgentClient = /** @class */ (function (_super) { + __extends(RegisterUserAgentClient, _super); + function RegisterUserAgentClient(core, message, delegate) { + return _super.call(this, transactions_1.NonInviteClientTransaction, core, message, delegate) || this; + } + return RegisterUserAgentClient; +}(user_agent_client_1.UserAgentClient)); +exports.RegisterUserAgentClient = RegisterUserAgentClient; + + +/***/ }), +/* 108 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Timers_1 = __webpack_require__(56); +var subscription_dialog_1 = __webpack_require__(100); +var subscription_1 = __webpack_require__(72); +var transactions_1 = __webpack_require__(52); +var user_agent_client_1 = __webpack_require__(82); +/** + * 4.1. Subscriber Behavior + * https://tools.ietf.org/html/rfc6665#section-4.1 + * + * User agent client for installation of a single subscription per SUBSCRIBE request. + * TODO: Support for installation of multiple subscriptions on forked SUBSCRIBE reqeuests. + */ +var SubscribeUserAgentClient = /** @class */ (function (_super) { + __extends(SubscribeUserAgentClient, _super); + function SubscribeUserAgentClient(core, message, delegate) { + var _this = this; + // Get event from request message. + var event = message.getHeader("Event"); + if (!event) { + throw new Error("Event undefined"); + } + // Get expires from reqeust message. + var expires = message.getHeader("Expires"); + if (!expires) { + throw new Error("Expires undefined"); + } + _this = _super.call(this, transactions_1.NonInviteClientTransaction, core, message, delegate) || this; + _this.delegate = delegate; + // FIXME: Subscriber id should also be matching on event id. + _this.subscriberId = message.callId + message.fromTag + event; + _this.subscriptionExpiresRequested = _this.subscriptionExpires = Number(expires); + _this.subscriptionEvent = event; + _this.subscriptionState = subscription_1.SubscriptionState.NotifyWait; + // Start waiting for a NOTIFY we can use to create a subscription. + _this.waitNotifyStart(); + return _this; + } + /** + * Destructor. + * Note that Timer N may live on waiting for an initial NOTIFY and + * the delegate may still receive that NOTIFY. If you don't want + * that behavior then either clear the delegate so the delegate + * doesn't get called (a 200 will be sent in response to the NOTIFY) + * or call `waitNotifyStop` which will clear Timer N and remove this + * UAC from the core (a 481 will be sent in response to the NOTIFY). + */ + SubscribeUserAgentClient.prototype.dispose = function () { + _super.prototype.dispose.call(this); + }; + /** + * Handle out of dialog NOTIFY assoicated with SUBSCRIBE request. + * This is the first NOTIFY received after the SUBSCRIBE request. + * @param uas User agent server handling the subscription creating NOTIFY. + */ + SubscribeUserAgentClient.prototype.onNotify = function (uas) { + // NOTIFY requests are matched to such SUBSCRIBE requests if they + // contain the same "Call-ID", a "To" header field "tag" parameter that + // matches the "From" header field "tag" parameter of the SUBSCRIBE + // request, and the same "Event" header field. Rules for comparisons of + // the "Event" header fields are described in Section 8.2.1. + // https://tools.ietf.org/html/rfc6665#section-4.4.1 + var event = uas.message.parseHeader("Event").event; + if (!event || event !== this.subscriptionEvent) { + this.logger.warn("Failed to parse event."); + uas.reject({ statusCode: 489 }); + return; + } + // NOTIFY requests MUST contain "Subscription-State" header fields that + // indicate the status of the subscription. + // https://tools.ietf.org/html/rfc6665#section-4.1.3 + var subscriptionState = uas.message.parseHeader("Subscription-State"); + if (!subscriptionState || !subscriptionState.state) { + this.logger.warn("Failed to parse subscription state."); + uas.reject({ statusCode: 489 }); + return; + } + // Validate subscription state. + var state = subscriptionState.state; + switch (state) { + case "pending": + break; + case "active": + break; + case "terminated": + break; + default: + this.logger.warn("Invalid subscription state " + state); + uas.reject({ statusCode: 489 }); + return; + } + // Dialogs usages are created upon completion of a NOTIFY transaction + // for a new subscription, unless the NOTIFY request contains a + // "Subscription-State" of "terminated." + // https://tools.ietf.org/html/rfc6665#section-4.4.1 + if (state !== "terminated") { + // The Contact header field MUST be present and contain exactly one SIP + // or SIPS URI in any request that can result in the establishment of a + // dialog. + // https://tools.ietf.org/html/rfc3261#section-8.1.1.8 + var contact = uas.message.parseHeader("contact"); + if (!contact) { + this.logger.warn("Failed to parse contact."); + uas.reject({ statusCode: 489 }); + return; + } + } + // In accordance with the rules for proxying non-INVITE requests as + // defined in [RFC3261], successful SUBSCRIBE requests will receive only + // one 200-class response; however, due to forking, the subscription may + // have been accepted by multiple nodes. The subscriber MUST therefore + // be prepared to receive NOTIFY requests with "From:" tags that differ + // from the "To:" tag received in the SUBSCRIBE 200-class response. + // + // If multiple NOTIFY requests are received in different dialogs in + // response to a single SUBSCRIBE request, each dialog represents a + // different destination to which the SUBSCRIBE request was forked. + // Subscriber handling in such situations varies by event package; see + // Section 5.4.9 for details. + // https://tools.ietf.org/html/rfc6665#section-4.1.4 + // Each event package MUST specify whether forked SUBSCRIBE requests are + // allowed to install multiple subscriptions. + // + // If such behavior is not allowed, the first potential dialog- + // establishing message will create a dialog. All subsequent NOTIFY + // requests that correspond to the SUBSCRIBE request (i.e., have + // matching "To", "From", "Call-ID", and "Event" header fields, as well + // as "From" header field "tag" parameter and "Event" header field "id" + // parameter) but that do not match the dialog would be rejected with a + // 481 response. Note that the 200-class response to the SUBSCRIBE + // request can arrive after a matching NOTIFY request has been received; + // such responses might not correlate to the same dialog established by + // the NOTIFY request. Except as required to complete the SUBSCRIBE + // transaction, such non-matching 200-class responses are ignored. + // + // If installing of multiple subscriptions by way of a single forked + // SUBSCRIBE request is allowed, the subscriber establishes a new dialog + // towards each notifier by returning a 200-class response to each + // NOTIFY request. Each dialog is then handled as its own entity and is + // refreshed independently of the other dialogs. + // + // In the case that multiple subscriptions are allowed, the event + // package MUST specify whether merging of the notifications to form a + // single state is required, and how such merging is to be performed. + // Note that it is possible that some event packages may be defined in + // such a way that each dialog is tied to a mutually exclusive state + // that is unaffected by the other dialogs; this MUST be clearly stated + // if it is the case. + // https://tools.ietf.org/html/rfc6665#section-5.4.9 + // *** NOTE: This implementation is only for event packages which + // do not allow forked requests to install muliple subscriptions. + // As such and in accordance with the specificaiton, we stop waiting + // and any future NOTIFY requests will be rejected with a 481. + if (this.dialog) { + throw new Error("Dialog already created. This implementation only supports install of single subscriptions."); + } + this.waitNotifyStop(); + // Update expires. + this.subscriptionExpires = + subscriptionState.expires ? + Math.min(this.subscriptionExpires, Math.max(subscriptionState.expires, 0)) : + this.subscriptionExpires; + // Update subscriptoin state. + switch (state) { + case "pending": + this.subscriptionState = subscription_1.SubscriptionState.Pending; + break; + case "active": + this.subscriptionState = subscription_1.SubscriptionState.Active; + break; + case "terminated": + this.subscriptionState = subscription_1.SubscriptionState.Terminated; + break; + default: + throw new Error("Unrecognized state " + state + "."); + } + // Dialogs usages are created upon completion of a NOTIFY transaction + // for a new subscription, unless the NOTIFY request contains a + // "Subscription-State" of "terminated." + // https://tools.ietf.org/html/rfc6665#section-4.4.1 + if (this.subscriptionState !== subscription_1.SubscriptionState.Terminated) { + // Because the dialog usage is established by the NOTIFY request, the + // route set at the subscriber is taken from the NOTIFY request itself, + // as opposed to the route set present in the 200-class response to the + // SUBSCRIBE request. + // https://tools.ietf.org/html/rfc6665#section-4.4.1 + var dialogState = subscription_dialog_1.SubscriptionDialog.initialDialogStateForSubscription(this.message, uas.message); + // Subscription Initiated! :) + this.dialog = new subscription_dialog_1.SubscriptionDialog(this.subscriptionEvent, this.subscriptionExpires, this.subscriptionState, this.core, dialogState); + } + // Delegate. + if (this.delegate && this.delegate.onNotify) { + var request = uas; + var subscription = this.dialog; + this.delegate.onNotify({ request: request, subscription: subscription }); + } + else { + uas.accept(); + } + }; + SubscribeUserAgentClient.prototype.waitNotifyStart = function () { + var _this = this; + if (!this.N) { + // Add ourselves to the core's subscriber map. + // This allows the core to route out of dialog NOTIFY messages to us. + this.core.subscribers.set(this.subscriberId, this); + this.N = setTimeout(function () { return _this.timer_N(); }, Timers_1.Timers.TIMER_N); + } + }; + SubscribeUserAgentClient.prototype.waitNotifyStop = function () { + if (this.N) { + // Remove ourselves to the core's subscriber map. + // Any future out of dialog NOTIFY messages will be rejected with a 481. + this.core.subscribers.delete(this.subscriberId); + clearTimeout(this.N); + this.N = undefined; + } + }; + /** + * Receive a response from the transaction layer. + * @param message Incoming response message. + */ + SubscribeUserAgentClient.prototype.receiveResponse = function (message) { + if (!this.authenticationGuard(message)) { + return; + } + if (message.statusCode && message.statusCode >= 200 && message.statusCode < 300) { + // The "Expires" header field in a 200-class response to SUBSCRIBE + // request indicates the actual duration for which the subscription will + // remain active (unless refreshed). The received value might be + // smaller than the value indicated in the SUBSCRIBE request but cannot + // be larger; see Section 4.2.1 for details. + // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 + // The "Expires" values present in SUBSCRIBE 200-class responses behave + // in the same way as they do in REGISTER responses: the server MAY + // shorten the interval but MUST NOT lengthen it. + // + // If the duration specified in a SUBSCRIBE request is unacceptably + // short, the notifier may be able to send a 423 response, as + // described earlier in this section. + // + // 200-class responses to SUBSCRIBE requests will not generally contain + // any useful information beyond subscription duration; their primary + // purpose is to serve as a reliability mechanism. State information + // will be communicated via a subsequent NOTIFY request from the + // notifier. + // https://tools.ietf.org/html/rfc6665#section-4.2.1.1 + var expires = message.getHeader("Expires"); + if (!expires) { + this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE"); + } + else { + var subscriptionExpiresReceived = Number(expires); + if (subscriptionExpiresReceived > this.subscriptionExpiresRequested) { + this.logger.warn("Expires header in a 200-class response to SUBSCRIBE with a higher value than the one in the request"); + } + if (subscriptionExpiresReceived < this.subscriptionExpires) { + this.subscriptionExpires = subscriptionExpiresReceived; + } + } + // If a NOTIFY arrived before 200-class response a dialog may have been created. + // Updated the dialogs expiration only if this indicates earlier expiration. + if (this.dialog) { + if (this.dialog.subscriptionExpires > this.subscriptionExpires) { + this.dialog.subscriptionExpires = this.subscriptionExpires; + } + } + } + if (message.statusCode && message.statusCode >= 300 && message.statusCode < 700) { + this.waitNotifyStop(); // No NOTIFY will be sent after a negative final response. + } + _super.prototype.receiveResponse.call(this, message); + }; + /** + * To ensure that subscribers do not wait indefinitely for a + * subscription to be established, a subscriber starts a Timer N, set to + * 64*T1, when it sends a SUBSCRIBE request. If this Timer N expires + * prior to the receipt of a NOTIFY request, the subscriber considers + * the subscription failed, and cleans up any state associated with the + * subscription attempt. + * https://tools.ietf.org/html/rfc6665#section-4.1.2.4 + */ + SubscribeUserAgentClient.prototype.timer_N = function () { + this.logger.warn("Timer N expired for SUBSCRIBE user agent client. Timed out waiting for NOTIFY."); + this.waitNotifyStop(); + if (this.delegate && this.delegate.onNotifyTimeout) { + this.delegate.onNotifyTimeout(); + } + }; + return SubscribeUserAgentClient; +}(user_agent_client_1.UserAgentClient)); +exports.SubscribeUserAgentClient = SubscribeUserAgentClient; + + +/***/ }), +/* 109 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var transactions_1 = __webpack_require__(52); +var user_agent_server_1 = __webpack_require__(84); +var SubscribeUserAgentServer = /** @class */ (function (_super) { + __extends(SubscribeUserAgentServer, _super); + function SubscribeUserAgentServer(core, message, delegate) { + var _this = _super.call(this, transactions_1.NonInviteServerTransaction, core, message, delegate) || this; + _this.core = core; + return _this; + } + return SubscribeUserAgentServer; +}(user_agent_server_1.UserAgentServer)); +exports.SubscribeUserAgentServer = SubscribeUserAgentServer; + + +/***/ }), +/* 110 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +var SIPMessage_1 = __webpack_require__(6); +var URI_1 = __webpack_require__(10); +/** + * Factory function to generate configuration give a UA. + * @param ua UA + */ +function makeUserAgentCoreConfigurationFromUA(ua) { + // FIXME: Configuration URI is a bad mix of types currently. It also needs to exist. + if (!(ua.configuration.uri instanceof URI_1.URI)) { + throw new Error("Configuration URI not instance of URI."); + } + var configuration = { + aor: ua.configuration.uri, + contact: ua.contact, + loggerFactory: ua.getLoggerFactory(), + userAgentHeaderFieldValue: ua.configuration.userAgentString, + authenticationFactory: function () { + if (ua.configuration.authenticationFactory) { + return ua.configuration.authenticationFactory(ua); + } + return undefined; + }, + onRequestTimeoutResponseMessageFactory: function () { + var message = new SIPMessage_1.IncomingResponse(ua); + message.statusCode = 408; + message.reasonPhrase = "Request Timeout"; + return message; + }, + onTransportErrorResponseMessageFactory: function () { + var message = new SIPMessage_1.IncomingResponse(ua); + message.statusCode = 503; + message.reasonPhrase = "Service Unavailable"; + return message; + }, + outgoingRequestMessageFactory: function (method, ruri, params, extraHeaders, body) { return new SIPMessage_1.OutgoingRequest(method, ruri, ua, params, extraHeaders, body); }, + transportAccessor: function () { return ua.transport; } + }; + return configuration; +} +exports.makeUserAgentCoreConfigurationFromUA = makeUserAgentCoreConfigurationFromUA; + + +/***/ }), +/* 111 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(global) { +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var events_1 = __webpack_require__(2); +var Enums_1 = __webpack_require__(5); +var Exceptions_1 = __webpack_require__(47); +var Utils_1 = __webpack_require__(11); +var Modifiers = __webpack_require__(112); +var SessionDescriptionHandlerObserver_1 = __webpack_require__(113); +/* SessionDescriptionHandler + * @class PeerConnection helper Class. + * @param {SIP.Session} session + * @param {Object} [options] + */ +var SessionDescriptionHandler = /** @class */ (function (_super) { + __extends(SessionDescriptionHandler, _super); + function SessionDescriptionHandler(logger, observer, options) { + var _this = _super.call(this) || this; + _this.type = Enums_1.TypeStrings.SessionDescriptionHandler; + // TODO: Validate the options + _this.options = options || {}; + _this.logger = logger; + _this.observer = observer; + _this.dtmfSender = undefined; + _this.shouldAcquireMedia = true; + _this.CONTENT_TYPE = "application/sdp"; + _this.C = { + DIRECTION: { + NULL: null, + SENDRECV: "sendrecv", + SENDONLY: "sendonly", + RECVONLY: "recvonly", + INACTIVE: "inactive" + } + }; + _this.logger.log("SessionDescriptionHandlerOptions: " + JSON.stringify(_this.options)); + _this.direction = _this.C.DIRECTION.NULL; + _this.modifiers = _this.options.modifiers || []; + if (!Array.isArray(_this.modifiers)) { + _this.modifiers = [_this.modifiers]; + } + var environment = global.window || global; + _this.WebRTC = { + MediaStream: environment.MediaStream, + getUserMedia: environment.navigator.mediaDevices.getUserMedia.bind(environment.navigator.mediaDevices), + RTCPeerConnection: environment.RTCPeerConnection + }; + _this.iceGatheringTimeout = false; + _this.initPeerConnection(_this.options.peerConnectionOptions); + _this.constraints = _this.checkAndDefaultConstraints(_this.options.constraints); + return _this; + } + /** + * @param {SIP.Session} session + * @param {Object} [options] + */ + SessionDescriptionHandler.defaultFactory = function (session, options) { + var logger = session.ua.getLogger("sip.invitecontext.sessionDescriptionHandler", session.id); + var observer = new SessionDescriptionHandlerObserver_1.SessionDescriptionHandlerObserver(session, options); + return new SessionDescriptionHandler(logger, observer, options); + }; + // Functions the sesssion can use + /** + * Destructor + */ + SessionDescriptionHandler.prototype.close = function () { + this.logger.log("closing PeerConnection"); + // have to check signalingState since this.close() gets called multiple times + if (this.peerConnection && this.peerConnection.signalingState !== "closed") { + if (this.peerConnection.getSenders) { + this.peerConnection.getSenders().forEach(function (sender) { + if (sender.track) { + sender.track.stop(); + } + }); + } + else { + this.logger.warn("Using getLocalStreams which is deprecated"); + this.peerConnection.getLocalStreams().forEach(function (stream) { + stream.getTracks().forEach(function (track) { + track.stop(); + }); + }); + } + if (this.peerConnection.getReceivers) { + this.peerConnection.getReceivers().forEach(function (receiver) { + if (receiver.track) { + receiver.track.stop(); + } + }); + } + else { + this.logger.warn("Using getRemoteStreams which is deprecated"); + this.peerConnection.getRemoteStreams().forEach(function (stream) { + stream.getTracks().forEach(function (track) { + track.stop(); + }); + }); + } + this.resetIceGatheringComplete(); + this.peerConnection.close(); + } + }; + /** + * Gets the local description from the underlying media implementation + * @param {Object} [options] Options object to be used by getDescription + * @param {MediaStreamConstraints} [options.constraints] MediaStreamConstraints + * https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamConstraints + * @param {Object} [options.peerConnectionOptions] If this is set it will recreate the peer + * connection with the new options + * @param {Array} [modifiers] Array with one time use description modifiers + * @returns {Promise} Promise that resolves with the local description to be used for the session + */ + SessionDescriptionHandler.prototype.getDescription = function (options, modifiers) { + var _this = this; + if (options === void 0) { options = {}; } + if (modifiers === void 0) { modifiers = []; } + if (options.peerConnectionOptions) { + this.initPeerConnection(options.peerConnectionOptions); + } + // Merge passed constraints with saved constraints and save + var newConstraints = Object.assign({}, this.constraints, options.constraints); + newConstraints = this.checkAndDefaultConstraints(newConstraints); + if (JSON.stringify(newConstraints) !== JSON.stringify(this.constraints)) { + this.constraints = newConstraints; + this.shouldAcquireMedia = true; + } + if (!Array.isArray(modifiers)) { + modifiers = [modifiers]; + } + modifiers = modifiers.concat(this.modifiers); + return Promise.resolve().then(function () { + if (_this.shouldAcquireMedia) { + return _this.acquire(_this.constraints).then(function () { + _this.shouldAcquireMedia = false; + }); + } + }).then(function () { return _this.createOfferOrAnswer(options.RTCOfferOptions, modifiers); }) + .then(function (description) { + if (description.sdp === undefined) { + throw new Exceptions_1.Exceptions.SessionDescriptionHandlerError("getDescription", undefined, "SDP undefined"); + } + _this.emit("getDescription", description); + return { + body: description.sdp, + contentType: _this.CONTENT_TYPE + }; + }); + }; + /** + * Check if the Session Description Handler can handle the Content-Type described by a SIP Message + * @param {String} contentType The content type that is in the SIP Message + * @returns {boolean} + */ + SessionDescriptionHandler.prototype.hasDescription = function (contentType) { + return contentType === this.CONTENT_TYPE; + }; + /** + * The modifier that should be used when the session would like to place the call on hold + * @param {String} [sdp] The description that will be modified + * @returns {Promise} Promise that resolves with modified SDP + */ + SessionDescriptionHandler.prototype.holdModifier = function (description) { + if (!description.sdp) { + return Promise.resolve(description); + } + if (!(/a=(sendrecv|sendonly|recvonly|inactive)/).test(description.sdp)) { + description.sdp = description.sdp.replace(/(m=[^\r]*\r\n)/g, "$1a=sendonly\r\n"); + } + else { + description.sdp = description.sdp.replace(/a=sendrecv\r\n/g, "a=sendonly\r\n"); + description.sdp = description.sdp.replace(/a=recvonly\r\n/g, "a=inactive\r\n"); + } + return Promise.resolve(description); + }; + /** + * Set the remote description to the underlying media implementation + * @param {String} sessionDescription The description provided by a SIP message to be set on the media implementation + * @param {Object} [options] Options object to be used by getDescription + * @param {MediaStreamConstraints} [options.constraints] MediaStreamConstraints + * https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamConstraints + * @param {Object} [options.peerConnectionOptions] If this is set it will recreate the peer + * connection with the new options + * @param {Array} [modifiers] Array with one time use description modifiers + * @returns {Promise} Promise that resolves once the description is set + */ + SessionDescriptionHandler.prototype.setDescription = function (sessionDescription, options, modifiers) { + var _this = this; + if (options === void 0) { options = {}; } + if (modifiers === void 0) { modifiers = []; } + if (options.peerConnectionOptions) { + this.initPeerConnection(options.peerConnectionOptions); + } + if (!Array.isArray(modifiers)) { + modifiers = [modifiers]; + } + modifiers = modifiers.concat(this.modifiers); + var description = { + type: this.hasOffer("local") ? "answer" : "offer", + sdp: sessionDescription + }; + return Promise.resolve().then(function () { + // Media should be acquired in getDescription unless we need to do it sooner for some reason (FF61+) + if (_this.shouldAcquireMedia && _this.options.alwaysAcquireMediaFirst) { + return _this.acquire(_this.constraints).then(function () { + _this.shouldAcquireMedia = false; + }); + } + }).then(function () { return Utils_1.Utils.reducePromises(modifiers, description); }) + .catch(function (e) { + if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { + throw e; + } + var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("setDescription", e, "The modifiers did not resolve successfully"); + _this.logger.error(error.message); + _this.emit("peerConnection-setRemoteDescriptionFailed", error); + throw error; + }).then(function (modifiedDescription) { + _this.emit("setDescription", modifiedDescription); + return _this.peerConnection.setRemoteDescription(modifiedDescription); + }).catch(function (e) { + if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { + throw e; + } + // Check the original SDP for video, and ensure that we have want to do audio fallback + if ((/^m=video.+$/gm).test(sessionDescription) && !options.disableAudioFallback) { + // Do not try to audio fallback again + options.disableAudioFallback = true; + // Remove video first, then do the other modifiers + return _this.setDescription(sessionDescription, options, [Modifiers.stripVideo].concat(modifiers)); + } + var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("setDescription", e); + if (error.error) { + _this.logger.error(error.error); + } + _this.emit("peerConnection-setRemoteDescriptionFailed", error); + throw error; + }).then(function () { + if (_this.peerConnection.getReceivers) { + _this.emit("setRemoteDescription", _this.peerConnection.getReceivers()); + } + else { + _this.emit("setRemoteDescription", _this.peerConnection.getRemoteStreams()); + } + _this.emit("confirmed", _this); + }); + }; + /** + * Send DTMF via RTP (RFC 4733) + * @param {String} tones A string containing DTMF digits + * @param {Object} [options] Options object to be used by sendDtmf + * @returns {boolean} true if DTMF send is successful, false otherwise + */ + SessionDescriptionHandler.prototype.sendDtmf = function (tones, options) { + if (options === void 0) { options = {}; } + if (!this.dtmfSender && this.hasBrowserGetSenderSupport()) { + var senders = this.peerConnection.getSenders(); + if (senders.length > 0) { + this.dtmfSender = senders[0].dtmf; + } + } + if (!this.dtmfSender && this.hasBrowserTrackSupport()) { + var streams = this.peerConnection.getLocalStreams(); + if (streams.length > 0) { + var audioTracks = streams[0].getAudioTracks(); + if (audioTracks.length > 0) { + this.dtmfSender = this.peerConnection.createDTMFSender(audioTracks[0]); + } + } + } + if (!this.dtmfSender) { + return false; + } + try { + this.dtmfSender.insertDTMF(tones, options.duration, options.interToneGap); + } + catch (e) { + if (e.type === "InvalidStateError" || e.type === "InvalidCharacterError") { + this.logger.error(e); + return false; + } + else { + throw e; + } + } + this.logger.log("DTMF sent via RTP: " + tones.toString()); + return true; + }; + /** + * Get the direction of the session description + * @returns {String} direction of the description + */ + SessionDescriptionHandler.prototype.getDirection = function () { + return this.direction; + }; + SessionDescriptionHandler.prototype.on = function (name, callback) { return _super.prototype.on.call(this, name, callback); }; + // Internal functions + SessionDescriptionHandler.prototype.createOfferOrAnswer = function (RTCOfferOptions, modifiers) { + var _this = this; + if (RTCOfferOptions === void 0) { RTCOfferOptions = {}; } + if (modifiers === void 0) { modifiers = []; } + var methodName = this.hasOffer("remote") ? "createAnswer" : "createOffer"; + var pc = this.peerConnection; + this.logger.log(methodName); + var method = this.hasOffer("remote") ? pc.createAnswer : pc.createOffer; + return method(RTCOfferOptions).catch(function (e) { + if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { + throw e; + } + var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("createOfferOrAnswer", e, "peerConnection-" + methodName + "Failed"); + _this.emit("peerConnection-" + methodName + "Failed", error); + throw error; + }).then(function (sdp) { + return Utils_1.Utils.reducePromises(modifiers, _this.createRTCSessionDescriptionInit(sdp)); + }).then(function (sdp) { + _this.resetIceGatheringComplete(); + _this.logger.log("Setting local sdp."); + _this.logger.log("sdp is " + sdp.sdp || false); + return pc.setLocalDescription(sdp); + }).catch(function (e) { + if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { + throw e; + } + var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("createOfferOrAnswer", e, "peerConnection-SetLocalDescriptionFailed"); + _this.emit("peerConnection-SetLocalDescriptionFailed", error); + throw error; + }).then(function () { return _this.waitForIceGatheringComplete(); }) + .then(function () { + var localDescription = _this.createRTCSessionDescriptionInit(_this.peerConnection.localDescription); + return Utils_1.Utils.reducePromises(modifiers, localDescription); + }).then(function (localDescription) { + _this.setDirection(localDescription.sdp || ""); + return localDescription; + }).catch(function (e) { + if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { + throw e; + } + var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("createOfferOrAnswer", e); + _this.logger.error(error.toString()); + throw error; + }); + }; + // Creates an RTCSessionDescriptionInit from an RTCSessionDescription + SessionDescriptionHandler.prototype.createRTCSessionDescriptionInit = function (RTCSessionDescription) { + return { + type: RTCSessionDescription.type, + sdp: RTCSessionDescription.sdp + }; + }; + SessionDescriptionHandler.prototype.addDefaultIceCheckingTimeout = function (peerConnectionOptions) { + if (peerConnectionOptions.iceCheckingTimeout === undefined) { + peerConnectionOptions.iceCheckingTimeout = 5000; + } + return peerConnectionOptions; + }; + SessionDescriptionHandler.prototype.addDefaultIceServers = function (rtcConfiguration) { + if (!rtcConfiguration.iceServers) { + rtcConfiguration.iceServers = [{ urls: "stun:stun.l.google.com:19302" }]; + } + return rtcConfiguration; + }; + SessionDescriptionHandler.prototype.checkAndDefaultConstraints = function (constraints) { + var defaultConstraints = { audio: true, video: !this.options.alwaysAcquireMediaFirst }; + constraints = constraints || defaultConstraints; + // Empty object check + if (Object.keys(constraints).length === 0 && constraints.constructor === Object) { + return defaultConstraints; + } + return constraints; + }; + SessionDescriptionHandler.prototype.hasBrowserTrackSupport = function () { + return Boolean(this.peerConnection.addTrack); + }; + SessionDescriptionHandler.prototype.hasBrowserGetSenderSupport = function () { + return Boolean(this.peerConnection.getSenders); + }; + SessionDescriptionHandler.prototype.initPeerConnection = function (options) { + var _this = this; + if (options === void 0) { options = {}; } + options = this.addDefaultIceCheckingTimeout(options); + options.rtcConfiguration = options.rtcConfiguration || {}; + options.rtcConfiguration = this.addDefaultIceServers(options.rtcConfiguration); + this.logger.log("initPeerConnection"); + if (this.peerConnection) { + this.logger.log("Already have a peer connection for this session. Tearing down."); + this.resetIceGatheringComplete(); + this.peerConnection.close(); + } + this.peerConnection = new this.WebRTC.RTCPeerConnection(options.rtcConfiguration); + this.logger.log("New peer connection created"); + if ("ontrack" in this.peerConnection) { + this.peerConnection.addEventListener("track", function (e) { + _this.logger.log("track added"); + _this.observer.trackAdded(); + _this.emit("addTrack", e); + }); + } + else { + this.logger.warn("Using onaddstream which is deprecated"); + this.peerConnection.onaddstream = function (e) { + _this.logger.log("stream added"); + _this.emit("addStream", e); + }; + } + this.peerConnection.onicecandidate = function (e) { + _this.emit("iceCandidate", e); + if (e.candidate) { + _this.logger.log("ICE candidate received: " + + (e.candidate.candidate === null ? null : e.candidate.candidate.trim())); + } + else if (e.candidate === null) { + // indicates the end of candidate gathering + _this.logger.log("ICE candidate gathering complete"); + _this.triggerIceGatheringComplete(); + } + }; + this.peerConnection.onicegatheringstatechange = function () { + _this.logger.log("RTCIceGatheringState changed: " + _this.peerConnection.iceGatheringState); + switch (_this.peerConnection.iceGatheringState) { + case "gathering": + _this.emit("iceGathering", _this); + if (!_this.iceGatheringTimer && options.iceCheckingTimeout) { + _this.iceGatheringTimeout = false; + _this.iceGatheringTimer = setTimeout(function () { + _this.logger.log("RTCIceChecking Timeout Triggered after " + options.iceCheckingTimeout + " milliseconds"); + _this.iceGatheringTimeout = true; + _this.triggerIceGatheringComplete(); + }, options.iceCheckingTimeout); + } + break; + case "complete": + _this.triggerIceGatheringComplete(); + break; + } + }; + this.peerConnection.oniceconnectionstatechange = function () { + var stateEvent; + switch (_this.peerConnection.iceConnectionState) { + case "new": + stateEvent = "iceConnection"; + break; + case "checking": + stateEvent = "iceConnectionChecking"; + break; + case "connected": + stateEvent = "iceConnectionConnected"; + break; + case "completed": + stateEvent = "iceConnectionCompleted"; + break; + case "failed": + stateEvent = "iceConnectionFailed"; + break; + case "disconnected": + stateEvent = "iceConnectionDisconnected"; + break; + case "closed": + stateEvent = "iceConnectionClosed"; + break; + default: + _this.logger.warn("Unknown iceConnection state: " + _this.peerConnection.iceConnectionState); + return; + } + _this.logger.log("ICE Connection State changed to " + stateEvent); + _this.emit(stateEvent, _this); + }; + }; + SessionDescriptionHandler.prototype.acquire = function (constraints) { + var _this = this; + // Default audio & video to true + constraints = this.checkAndDefaultConstraints(constraints); + return new Promise(function (resolve, reject) { + /* + * Make the call asynchronous, so that ICCs have a chance + * to define callbacks to `userMediaRequest` + */ + _this.logger.log("acquiring local media"); + _this.emit("userMediaRequest", constraints); + if (constraints.audio || constraints.video) { + _this.WebRTC.getUserMedia(constraints).then(function (streams) { + _this.observer.trackAdded(); + _this.emit("userMedia", streams); + resolve(streams); + }).catch(function (e) { + _this.emit("userMediaFailed", e); + reject(e); + }); + } + else { + // Local streams were explicitly excluded. + resolve([]); + } + }).catch(function (e) { + if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { + throw e; + } + var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("acquire", e, "unable to acquire streams"); + _this.logger.error(error.message); + if (error.error) { + _this.logger.error(error.error); + } + throw error; + }).then(function (streams) { + _this.logger.log("acquired local media streams"); + try { + // Remove old tracks + if (_this.peerConnection.removeTrack) { + _this.peerConnection.getSenders().forEach(function (sender) { + _this.peerConnection.removeTrack(sender); + }); + } + return streams; + } + catch (e) { + return Promise.reject(e); + } + }).catch(function (e) { + if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { + throw e; + } + var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("acquire", e, "error removing streams"); + _this.logger.error(error.message); + if (error.error) { + _this.logger.error(error.error); + } + throw error; + }).then(function (streams) { + try { + streams = [].concat(streams); + streams.forEach(function (stream) { + if (_this.peerConnection.addTrack) { + stream.getTracks().forEach(function (track) { + _this.peerConnection.addTrack(track, stream); + }); + } + else { + // Chrome 59 does not support addTrack + _this.peerConnection.addStream(stream); + } + }); + } + catch (e) { + return Promise.reject(e); + } + return Promise.resolve(); + }).catch(function (e) { + if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { + throw e; + } + var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("acquire", e, "error adding stream"); + _this.logger.error(error.message); + if (error.error) { + _this.logger.error(error.error); + } + throw error; + }); + }; + SessionDescriptionHandler.prototype.hasOffer = function (where) { + var offerState = "have-" + where + "-offer"; + return this.peerConnection.signalingState === offerState; + }; + // ICE gathering state handling + SessionDescriptionHandler.prototype.isIceGatheringComplete = function () { + return this.peerConnection.iceGatheringState === "complete" || this.iceGatheringTimeout; + }; + SessionDescriptionHandler.prototype.resetIceGatheringComplete = function () { + this.iceGatheringTimeout = false; + this.logger.log("resetIceGatheringComplete"); + if (this.iceGatheringTimer) { + clearTimeout(this.iceGatheringTimer); + this.iceGatheringTimer = undefined; + } + if (this.iceGatheringDeferred) { + this.iceGatheringDeferred.reject(); + this.iceGatheringDeferred = undefined; + } + }; + SessionDescriptionHandler.prototype.setDirection = function (sdp) { + var match = sdp.match(/a=(sendrecv|sendonly|recvonly|inactive)/); + if (match === null) { + this.direction = this.C.DIRECTION.NULL; + this.observer.directionChanged(); + return; + } + var direction = match[1]; + switch (direction) { + case this.C.DIRECTION.SENDRECV: + case this.C.DIRECTION.SENDONLY: + case this.C.DIRECTION.RECVONLY: + case this.C.DIRECTION.INACTIVE: + this.direction = direction; + break; + default: + this.direction = this.C.DIRECTION.NULL; + break; + } + this.observer.directionChanged(); + }; + SessionDescriptionHandler.prototype.triggerIceGatheringComplete = function () { + if (this.isIceGatheringComplete()) { + this.emit("iceGatheringComplete", this); + if (this.iceGatheringTimer) { + clearTimeout(this.iceGatheringTimer); + this.iceGatheringTimer = undefined; + } + if (this.iceGatheringDeferred) { + this.iceGatheringDeferred.resolve(); + this.iceGatheringDeferred = undefined; + } + } + }; + SessionDescriptionHandler.prototype.waitForIceGatheringComplete = function () { + this.logger.log("waitForIceGatheringComplete"); + if (this.isIceGatheringComplete()) { + this.logger.log("ICE is already complete. Return resolved."); + return Promise.resolve(); + } + else if (!this.iceGatheringDeferred) { + this.iceGatheringDeferred = Utils_1.Utils.defer(); + } + this.logger.log("ICE is not complete. Returning promise"); + return this.iceGatheringDeferred ? this.iceGatheringDeferred.promise : Promise.resolve(); + }; + return SessionDescriptionHandler; +}(events_1.EventEmitter)); +exports.SessionDescriptionHandler = SessionDescriptionHandler; + +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(77))) + +/***/ }), +/* 112 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +var stripPayload = function (sdp, payload) { + var mediaDescs = []; + var lines = sdp.split(/\r\n/); + var currentMediaDesc; + for (var i = 0; i < lines.length;) { + var line = lines[i]; + if (/^m=(?:audio|video)/.test(line)) { + currentMediaDesc = { + index: i, + stripped: [] + }; + mediaDescs.push(currentMediaDesc); + } + else if (currentMediaDesc) { + var rtpmap = /^a=rtpmap:(\d+) ([^/]+)\//.exec(line); + if (rtpmap && payload === rtpmap[2]) { + lines.splice(i, 1); + currentMediaDesc.stripped.push(rtpmap[1]); + continue; // Don't increment 'i' + } + } + i++; + } + for (var _i = 0, mediaDescs_1 = mediaDescs; _i < mediaDescs_1.length; _i++) { + var mediaDesc = mediaDescs_1[_i]; + var mline = lines[mediaDesc.index].split(" "); + // Ignore the first 3 parameters of the mline. The codec information is after that + for (var j = 3; j < mline.length;) { + if (mediaDesc.stripped.indexOf(mline[j]) !== -1) { + mline.splice(j, 1); + continue; + } + j++; + } + lines[mediaDesc.index] = mline.join(" "); + } + return lines.join("\r\n"); +}; +var stripMediaDescription = function (sdp, description) { + var descriptionRegExp = new RegExp("m=" + description + ".*$", "gm"); + var groupRegExp = new RegExp("^a=group:.*$", "gm"); + if (descriptionRegExp.test(sdp)) { + var midLineToRemove_1; + sdp = sdp.split(/^m=/gm).filter(function (section) { + if (section.substr(0, description.length) === description) { + midLineToRemove_1 = section.match(/^a=mid:.*$/gm); + if (midLineToRemove_1) { + var step = midLineToRemove_1[0].match(/:.+$/g); + if (step) { + midLineToRemove_1 = step[0].substr(1); + } + } + return false; + } + return true; + }).join("m="); + var groupLine = sdp.match(groupRegExp); + if (groupLine && groupLine.length === 1) { + var groupLinePortion = groupLine[0]; + var groupRegExpReplace = new RegExp("\ *" + midLineToRemove_1 + "[^\ ]*", "g"); + groupLinePortion = groupLinePortion.replace(groupRegExpReplace, ""); + sdp = sdp.split(groupRegExp).join(groupLinePortion); + } + } + return sdp; +}; +function stripTcpCandidates(description) { + description.sdp = (description.sdp || "").replace(/^a=candidate:\d+ \d+ tcp .*?\r\n/img, ""); + return Promise.resolve(description); +} +exports.stripTcpCandidates = stripTcpCandidates; +function stripTelephoneEvent(description) { + description.sdp = stripPayload(description.sdp || "", "telephone-event"); + return Promise.resolve(description); +} +exports.stripTelephoneEvent = stripTelephoneEvent; +function cleanJitsiSdpImageattr(description) { + description.sdp = (description.sdp || "").replace(/^(a=imageattr:.*?)(x|y)=\[0-/gm, "$1$2=[1:"); + return Promise.resolve(description); +} +exports.cleanJitsiSdpImageattr = cleanJitsiSdpImageattr; +function stripG722(description) { + description.sdp = stripPayload(description.sdp || "", "G722"); + return Promise.resolve(description); +} +exports.stripG722 = stripG722; +function stripRtpPayload(payload) { + return function (description) { + description.sdp = stripPayload(description.sdp || "", payload); + return Promise.resolve(description); + }; +} +exports.stripRtpPayload = stripRtpPayload; +function stripVideo(description) { + description.sdp = stripMediaDescription(description.sdp || "", "video"); + return Promise.resolve(description); +} +exports.stripVideo = stripVideo; +function addMidLines(description) { + var sdp = description.sdp || ""; + if (sdp.search(/^a=mid.*$/gm) === -1) { + var mlines_1 = sdp.match(/^m=.*$/gm); + var sdpArray_1 = sdp.split(/^m=.*$/gm); + if (mlines_1) { + mlines_1.forEach(function (elem, idx) { + mlines_1[idx] = elem + "\na=mid:" + idx; + }); + } + sdpArray_1.forEach(function (elem, idx) { + if (mlines_1 && mlines_1[idx]) { + sdpArray_1[idx] = elem + mlines_1[idx]; + } + }); + sdp = sdpArray_1.join(""); + description.sdp = sdp; + } + return Promise.resolve(description); +} +exports.addMidLines = addMidLines; + + +/***/ }), +/* 113 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +var Enums_1 = __webpack_require__(5); +/* SessionDescriptionHandlerObserver + * @class SessionDescriptionHandler Observer Class. + * @param {SIP.Session} session + * @param {Object} [options] + */ +var SessionDescriptionHandlerObserver = /** @class */ (function () { + function SessionDescriptionHandlerObserver(session, options) { + this.type = Enums_1.TypeStrings.SessionDescriptionHandlerObserver; + this.session = session; + this.options = options; + } + SessionDescriptionHandlerObserver.prototype.trackAdded = function () { + this.session.emit("trackAdded"); + }; + SessionDescriptionHandlerObserver.prototype.directionChanged = function () { + this.session.emit("directionChanged"); + }; + return SessionDescriptionHandlerObserver; +}()); +exports.SessionDescriptionHandlerObserver = SessionDescriptionHandlerObserver; + + +/***/ }), +/* 114 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(global) { +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Enums_1 = __webpack_require__(5); +var Exceptions_1 = __webpack_require__(47); +var Grammar_1 = __webpack_require__(7); +var Transport_1 = __webpack_require__(75); +var Utils_1 = __webpack_require__(11); +var TransportStatus; +(function (TransportStatus) { + TransportStatus[TransportStatus["STATUS_CONNECTING"] = 0] = "STATUS_CONNECTING"; + TransportStatus[TransportStatus["STATUS_OPEN"] = 1] = "STATUS_OPEN"; + TransportStatus[TransportStatus["STATUS_CLOSING"] = 2] = "STATUS_CLOSING"; + TransportStatus[TransportStatus["STATUS_CLOSED"] = 3] = "STATUS_CLOSED"; +})(TransportStatus = exports.TransportStatus || (exports.TransportStatus = {})); +/** + * Compute an amount of time in seconds to wait before sending another + * keep-alive. + * @returns {Number} + */ +var computeKeepAliveTimeout = function (upperBound) { + var lowerBound = upperBound * 0.8; + return 1000 * (Math.random() * (upperBound - lowerBound) + lowerBound); +}; +/** + * @class Transport + * @param {Object} options + */ +var Transport = /** @class */ (function (_super) { + __extends(Transport, _super); + function Transport(logger, options) { + if (options === void 0) { options = {}; } + var _this = _super.call(this, logger, options) || this; + _this.WebSocket = (global.window || global).WebSocket; + _this.type = Enums_1.TypeStrings.Transport; + _this.reconnectionAttempts = 0; + _this.status = TransportStatus.STATUS_CONNECTING; + _this.configuration = _this.loadConfig(options); + _this.server = _this.configuration.wsServers[0]; + return _this; + } + /** + * @returns {Boolean} + */ + Transport.prototype.isConnected = function () { + return this.status === TransportStatus.STATUS_OPEN; + }; + /** + * Send a message. + * @param {SIP.OutgoingRequest|String} msg + * @param {Object} [options] + * @returns {Promise} + */ + Transport.prototype.sendPromise = function (msg, options) { + if (options === void 0) { options = {}; } + if (!this.statusAssert(TransportStatus.STATUS_OPEN, options.force)) { + this.onError("unable to send message - WebSocket not open"); + return Promise.reject(); + } + var message = msg.toString(); + if (this.ws) { + if (this.configuration.traceSip === true) { + this.logger.log("sending WebSocket message:\n\n" + message + "\n"); + } + this.ws.send(message); + return Promise.resolve({ msg: message }); + } + else { + this.onError("unable to send message - WebSocket does not exist"); + return Promise.reject(); + } + }; + /** + * Disconnect socket. + */ + Transport.prototype.disconnectPromise = function (options) { + var _this = this; + if (options === void 0) { options = {}; } + if (this.disconnectionPromise) { // Already disconnecting. Just return this. + return this.disconnectionPromise; + } + options.code = options.code || 1000; + if (!this.statusTransition(TransportStatus.STATUS_CLOSING, options.force)) { + if (this.status === TransportStatus.STATUS_CLOSED) { // Websocket is already closed + return Promise.resolve({ overrideEvent: true }); + } + else if (this.connectionPromise) { // Websocket is connecting, cannot move to disconneting yet + return this.connectionPromise.then(function () { return Promise.reject("The websocket did not disconnect"); }) + .catch(function () { return Promise.resolve({ overrideEvent: true }); }); + } + else { + // Cannot move to disconnecting, but not in connecting state. + return Promise.reject("The websocket did not disconnect"); + } + } + this.emit("disconnecting"); + this.disconnectionPromise = new Promise(function (resolve, reject) { + _this.disconnectDeferredResolve = resolve; + if (_this.reconnectTimer) { + clearTimeout(_this.reconnectTimer); + _this.reconnectTimer = undefined; + } + if (_this.ws) { + _this.stopSendingKeepAlives(); + _this.logger.log("closing WebSocket " + _this.server.wsUri); + _this.ws.close(options.code, options.reason); + } + else { + reject("Attempted to disconnect but the websocket doesn't exist"); + } + }); + return this.disconnectionPromise; + }; + /** + * Connect socket. + */ + Transport.prototype.connectPromise = function (options) { + var _this = this; + if (options === void 0) { options = {}; } + if (this.status === TransportStatus.STATUS_CLOSING && !options.force) { + return Promise.reject("WebSocket " + this.server.wsUri + " is closing"); + } + if (this.connectionPromise) { + return this.connectionPromise; + } + this.server = this.server || this.getNextWsServer(options.force); + this.connectionPromise = new Promise(function (resolve, reject) { + if ((_this.status === TransportStatus.STATUS_OPEN || _this.status === TransportStatus.STATUS_CLOSING) + && !options.force) { + _this.logger.warn("WebSocket " + _this.server.wsUri + " is already connected"); + reject("Failed status check - attempted to open a connection but already open/closing"); + return; + } + _this.connectDeferredResolve = resolve; + _this.status = TransportStatus.STATUS_CONNECTING; + _this.emit("connecting"); + _this.logger.log("connecting to WebSocket " + _this.server.wsUri); + _this.disposeWs(); + try { + _this.ws = new WebSocket(_this.server.wsUri, "sip"); + } + catch (e) { + _this.ws = null; + _this.status = TransportStatus.STATUS_CLOSED; // force status to closed in error case + _this.onError("error connecting to WebSocket " + _this.server.wsUri + ":" + e); + reject("Failed to create a websocket"); + return; + } + if (!_this.ws) { + reject("Unexpected instance websocket not set"); + return; + } + _this.connectionTimeout = setTimeout(function () { + _this.statusTransition(TransportStatus.STATUS_CLOSED); + _this.logger.warn("took too long to connect - exceeded time set in configuration.connectionTimeout: " + + _this.configuration.connectionTimeout + "s"); + _this.emit("disconnected", { code: 1000 }); + _this.connectionPromise = undefined; + reject("Connection timeout"); + }, _this.configuration.connectionTimeout * 1000); + _this.boundOnOpen = _this.onOpen.bind(_this); + _this.boundOnMessage = _this.onMessage.bind(_this); + _this.boundOnClose = _this.onClose.bind(_this); + _this.boundOnError = _this.onWebsocketError.bind(_this); + _this.ws.addEventListener("open", _this.boundOnOpen); + _this.ws.addEventListener("message", _this.boundOnMessage); + _this.ws.addEventListener("close", _this.boundOnClose); + _this.ws.addEventListener("error", _this.boundOnError); + }); + return this.connectionPromise; + }; + /** + * @event + * @param {event} e + */ + Transport.prototype.onMessage = function (e) { + var data = e.data; + var finishedData; + // CRLF Keep Alive response from server. Clear our keep alive timeout. + if (/^(\r\n)+$/.test(data)) { + this.clearKeepAliveTimeout(); + if (this.configuration.traceSip === true) { + this.logger.log("received WebSocket message with CRLF Keep Alive response"); + } + return; + } + else if (!data) { + this.logger.warn("received empty message, message discarded"); + return; + } + else if (typeof data !== "string") { // WebSocket binary message. + try { + // the UInt8Data was here prior to types, and doesn't check + finishedData = String.fromCharCode.apply(null, new Uint8Array(data)); + } + catch (err) { + this.logger.warn("received WebSocket binary message failed to be converted into string, message discarded"); + return; + } + if (this.configuration.traceSip === true) { + this.logger.log("received WebSocket binary message:\n\n" + data + "\n"); + } + } + else { // WebSocket text message. + if (this.configuration.traceSip === true) { + this.logger.log("received WebSocket text message:\n\n" + data + "\n"); + } + finishedData = data; + } + this.emit("message", finishedData); + }; + // Transport Event Handlers + /** + * @event + * @param {event} e + */ + Transport.prototype.onOpen = function () { + if (this.status === TransportStatus.STATUS_CLOSED) { // Indicated that the transport thinks the ws is dead already + var ws = this.ws; + this.disposeWs(); + ws.close(1000); + return; + } + this.status = TransportStatus.STATUS_OPEN; // quietly force status to open + this.emit("connected"); + if (this.connectionTimeout) { + clearTimeout(this.connectionTimeout); + this.connectionTimeout = undefined; + } + this.logger.log("WebSocket " + this.server.wsUri + " connected"); + // Clear reconnectTimer since we are not disconnected + if (this.reconnectTimer !== undefined) { + clearTimeout(this.reconnectTimer); + this.reconnectTimer = undefined; + } + // Reset reconnectionAttempts + this.reconnectionAttempts = 0; + // Reset disconnection promise so we can disconnect from a fresh state + this.disconnectionPromise = undefined; + this.disconnectDeferredResolve = undefined; + // Start sending keep-alives + this.startSendingKeepAlives(); + if (this.connectDeferredResolve) { + this.connectDeferredResolve({ overrideEvent: true }); + } + else { + this.logger.warn("Unexpected websocket.onOpen with no connectDeferredResolve"); + } + }; + /** + * @event + * @param {event} e + */ + Transport.prototype.onClose = function (e) { + this.logger.log("WebSocket disconnected (code: " + e.code + (e.reason ? "| reason: " + e.reason : "") + ")"); + if (this.status !== TransportStatus.STATUS_CLOSING) { + this.logger.warn("WebSocket closed without SIP.js requesting it"); + this.emit("transportError"); + } + this.stopSendingKeepAlives(); + // Clean up connection variables so we can connect again from a fresh state + if (this.connectionTimeout) { + clearTimeout(this.connectionTimeout); + } + this.connectionTimeout = undefined; + this.connectionPromise = undefined; + this.connectDeferredResolve = undefined; + // Check whether the user requested to close. + if (this.disconnectDeferredResolve) { + this.disconnectDeferredResolve({ overrideEvent: true }); + this.statusTransition(TransportStatus.STATUS_CLOSED); + this.disconnectDeferredResolve = undefined; + return; + } + this.status = TransportStatus.STATUS_CLOSED; // quietly force status to closed + this.emit("disconnected", { code: e.code, reason: e.reason }); + this.reconnect(); + }; + /** + * Removes event listeners and clears the instance ws + */ + Transport.prototype.disposeWs = function () { + if (this.ws) { + this.ws.removeEventListener("open", this.boundOnOpen); + this.ws.removeEventListener("message", this.boundOnMessage); + this.ws.removeEventListener("close", this.boundOnClose); + this.ws.removeEventListener("error", this.boundOnError); + this.ws = undefined; + } + }; + /** + * @event + * @param {string} e + */ + Transport.prototype.onError = function (e) { + this.logger.warn("Transport error: " + e); + this.emit("transportError"); + }; + /** + * @event + * @private + */ + Transport.prototype.onWebsocketError = function () { + this.onError("The Websocket had an error"); + }; + /** + * Reconnection attempt logic. + */ + Transport.prototype.reconnect = function () { + var _this = this; + if (this.reconnectionAttempts > 0) { + this.logger.log("Reconnection attempt " + this.reconnectionAttempts + " failed"); + } + if (this.noAvailableServers()) { + this.logger.warn("attempted to get next ws server but there are no available ws servers left"); + this.logger.warn("no available ws servers left - going to closed state"); + this.status = TransportStatus.STATUS_CLOSED; + this.emit("closed"); + this.resetServerErrorStatus(); + return; + } + if (this.isConnected()) { + this.logger.warn("attempted to reconnect while connected - forcing disconnect"); + this.disconnect({ force: true }); + } + this.reconnectionAttempts += 1; + if (this.reconnectionAttempts > this.configuration.maxReconnectionAttempts) { + this.logger.warn("maximum reconnection attempts for WebSocket " + this.server.wsUri); + this.logger.log("transport " + this.server.wsUri + " failed | connection state set to 'error'"); + this.server.isError = true; + this.emit("transportError"); + if (!this.noAvailableServers()) { + this.server = this.getNextWsServer(); + } + // When there are no available servers, the reconnect function ends on the next recursive call + // after checking for no available servers again. + this.reconnectionAttempts = 0; + this.reconnect(); + } + else { + this.logger.log("trying to reconnect to WebSocket " + + this.server.wsUri + " (reconnection attempt " + this.reconnectionAttempts + ")"); + this.reconnectTimer = setTimeout(function () { + _this.connect(); + _this.reconnectTimer = undefined; + }, (this.reconnectionAttempts === 1) ? 0 : this.configuration.reconnectionTimeout * 1000); + } + }; + /** + * Resets the error state of all servers in the configuration + */ + Transport.prototype.resetServerErrorStatus = function () { + for (var _i = 0, _a = this.configuration.wsServers; _i < _a.length; _i++) { + var websocket = _a[_i]; + websocket.isError = false; + } + }; + /** + * Retrieve the next server to which connect. + * @param {Boolean} force allows bypass of server error status checking + * @returns {Object} WsServer + */ + Transport.prototype.getNextWsServer = function (force) { + if (force === void 0) { force = false; } + if (this.noAvailableServers()) { + this.logger.warn("attempted to get next ws server but there are no available ws servers left"); + throw new Error("Attempted to get next ws server, but there are no available ws servers left."); + } + // Order servers by weight + var candidates = []; + for (var _i = 0, _a = this.configuration.wsServers; _i < _a.length; _i++) { + var wsServer = _a[_i]; + if (wsServer.isError && !force) { + continue; + } + else if (candidates.length === 0) { + candidates.push(wsServer); + } + else if (wsServer.weight > candidates[0].weight) { + candidates = [wsServer]; + } + else if (wsServer.weight === candidates[0].weight) { + candidates.push(wsServer); + } + } + var idx = Math.floor(Math.random() * candidates.length); + return candidates[idx]; + }; + /** + * Checks all configuration servers, returns true if all of them have isError: true and false otherwise + * @returns {Boolean} + */ + Transport.prototype.noAvailableServers = function () { + for (var _i = 0, _a = this.configuration.wsServers; _i < _a.length; _i++) { + var server = _a[_i]; + if (!server.isError) { + return false; + } + } + return true; + }; + // ============================== + // KeepAlive Stuff + // ============================== + /** + * Send a keep-alive (a double-CRLF sequence). + * @returns {Boolean} + */ + Transport.prototype.sendKeepAlive = function () { + var _this = this; + if (this.keepAliveDebounceTimeout) { + // We already have an outstanding keep alive, do not send another. + return; + } + this.keepAliveDebounceTimeout = setTimeout(function () { + _this.emit("keepAliveDebounceTimeout"); + _this.clearKeepAliveTimeout(); + }, this.configuration.keepAliveDebounce * 1000); + return this.send("\r\n\r\n"); + }; + Transport.prototype.clearKeepAliveTimeout = function () { + if (this.keepAliveDebounceTimeout) { + clearTimeout(this.keepAliveDebounceTimeout); + } + this.keepAliveDebounceTimeout = undefined; + }; + /** + * Start sending keep-alives. + */ + Transport.prototype.startSendingKeepAlives = function () { + var _this = this; + if (this.configuration.keepAliveInterval && !this.keepAliveInterval) { + this.keepAliveInterval = setInterval(function () { + _this.sendKeepAlive(); + _this.startSendingKeepAlives(); + }, computeKeepAliveTimeout(this.configuration.keepAliveInterval)); + } + }; + /** + * Stop sending keep-alives. + */ + Transport.prototype.stopSendingKeepAlives = function () { + if (this.keepAliveInterval) { + clearInterval(this.keepAliveInterval); + } + if (this.keepAliveDebounceTimeout) { + clearTimeout(this.keepAliveDebounceTimeout); + } + this.keepAliveInterval = undefined; + this.keepAliveDebounceTimeout = undefined; + }; + // ============================== + // Status Stuff + // ============================== + /** + * Checks given status against instance current status. Returns true if they match + * @param {Number} status + * @param {Boolean} [force] + * @returns {Boolean} + */ + Transport.prototype.statusAssert = function (status, force) { + if (status === this.status) { + return true; + } + else { + if (force) { + this.logger.warn("Attempted to assert " + + Object.keys(TransportStatus)[this.status] + " as " + + Object.keys(TransportStatus)[status] + "- continuing with option: 'force'"); + return true; + } + else { + this.logger.warn("Tried to assert " + + Object.keys(TransportStatus)[status] + " but is currently " + + Object.keys(TransportStatus)[this.status]); + return false; + } + } + }; + /** + * Transitions the status. Checks for legal transition via assertion beforehand + * @param {Number} status + * @param {Boolean} [force] + * @returns {Boolean} + */ + Transport.prototype.statusTransition = function (status, force) { + if (force === void 0) { force = false; } + this.logger.log("Attempting to transition status from " + + Object.keys(TransportStatus)[this.status] + " to " + + Object.keys(TransportStatus)[status]); + if ((status === TransportStatus.STATUS_CONNECTING && this.statusAssert(TransportStatus.STATUS_CLOSED, force)) || + (status === TransportStatus.STATUS_OPEN && this.statusAssert(TransportStatus.STATUS_CONNECTING, force)) || + (status === TransportStatus.STATUS_CLOSING && this.statusAssert(TransportStatus.STATUS_OPEN, force)) || + (status === TransportStatus.STATUS_CLOSED)) { + this.status = status; + return true; + } + else { + this.logger.warn("Status transition failed - result: no-op - reason:" + + " either gave an nonexistent status or attempted illegal transition"); + return false; + } + }; + // ============================== + // Configuration Handling + // ============================== + /** + * Configuration load. + * returns {Configuration} + */ + Transport.prototype.loadConfig = function (configuration) { + var settings = { + wsServers: [{ + scheme: "WSS", + sipUri: "", + weight: 0, + wsUri: "wss://edge.sip.onsip.com", + isError: false + }], + connectionTimeout: 5, + maxReconnectionAttempts: 3, + reconnectionTimeout: 4, + keepAliveInterval: 0, + keepAliveDebounce: 10, + // Logging + traceSip: false + }; + var configCheck = this.getConfigurationCheck(); + // Check Mandatory parameters + for (var parameter in configCheck.mandatory) { + if (!configuration.hasOwnProperty(parameter)) { + throw new Exceptions_1.Exceptions.ConfigurationError(parameter); + } + else { + var value = configuration[parameter]; + var checkedValue = configCheck.mandatory[parameter](value); + if (checkedValue !== undefined) { + settings[parameter] = checkedValue; + } + else { + throw new Exceptions_1.Exceptions.ConfigurationError(parameter, value); + } + } + } + // Check Optional parameters + for (var parameter in configCheck.optional) { + if (configuration.hasOwnProperty(parameter)) { + var value = configuration[parameter]; + // If the parameter value is an empty array, but shouldn't be, apply its default value. + // If the parameter value is null, empty string, or undefined then apply its default value. + // If it's a number with NaN value then also apply its default value. + // NOTE: JS does not allow "value === NaN", the following does the work: + if ((value instanceof Array && value.length === 0) || + (value === null || value === "" || value === undefined) || + (typeof (value) === "number" && isNaN(value))) { + continue; + } + var checkedValue = configCheck.optional[parameter](value); + if (checkedValue !== undefined) { + settings[parameter] = checkedValue; + } + else { + throw new Exceptions_1.Exceptions.ConfigurationError(parameter, value); + } + } + } + var skeleton = {}; // Fill the value of the configuration_skeleton + for (var parameter in settings) { + if (settings.hasOwnProperty(parameter)) { + skeleton[parameter] = { + value: settings[parameter], + }; + } + } + var returnConfiguration = Object.defineProperties({}, skeleton); + this.logger.log("configuration parameters after validation:"); + for (var parameter in settings) { + if (settings.hasOwnProperty(parameter)) { + this.logger.log("· " + parameter + ": " + JSON.stringify(settings[parameter])); + } + } + return returnConfiguration; + }; + /** + * Configuration checker. + * @return {Boolean} + */ + Transport.prototype.getConfigurationCheck = function () { + return { + mandatory: {}, + optional: { + // Note: this function used to call 'this.logger.error' but calling 'this' with anything here is invalid + wsServers: function (wsServers) { + /* Allow defining wsServers parameter as: + * String: "host" + * Array of Strings: ["host1", "host2"] + * Array of Objects: [{wsUri:"host1", weight:1}, {wsUri:"host2", weight:0}] + * Array of Objects and Strings: [{wsUri:"host1"}, "host2"] + */ + if (typeof wsServers === "string") { + wsServers = [{ wsUri: wsServers }]; + } + else if (wsServers instanceof Array) { + for (var idx = 0; idx < wsServers.length; idx++) { + if (typeof wsServers[idx] === "string") { + wsServers[idx] = { wsUri: wsServers[idx] }; + } + } + } + else { + return; + } + if (wsServers.length === 0) { + return false; + } + for (var _i = 0, wsServers_1 = wsServers; _i < wsServers_1.length; _i++) { + var wsServer = wsServers_1[_i]; + if (!wsServer.wsUri) { + return; + } + if (wsServer.weight && !Number(wsServer.weight)) { + return; + } + var url = Grammar_1.Grammar.parse(wsServer.wsUri, "absoluteURI"); + if (url === -1) { + return; + } + else if (["wss", "ws", "udp"].indexOf(url.scheme) < 0) { + return; + } + else { + wsServer.sipUri = ""; + if (!wsServer.weight) { + wsServer.weight = 0; + } + wsServer.isError = false; + wsServer.scheme = url.scheme.toUpperCase(); + } + } + return wsServers; + }, + keepAliveInterval: function (keepAliveInterval) { + if (Utils_1.Utils.isDecimal(keepAliveInterval)) { + var value = Number(keepAliveInterval); + if (value > 0) { + return value; + } + } + }, + keepAliveDebounce: function (keepAliveDebounce) { + if (Utils_1.Utils.isDecimal(keepAliveDebounce)) { + var value = Number(keepAliveDebounce); + if (value > 0) { + return value; + } + } + }, + traceSip: function (traceSip) { + if (typeof traceSip === "boolean") { + return traceSip; + } + }, + connectionTimeout: function (connectionTimeout) { + if (Utils_1.Utils.isDecimal(connectionTimeout)) { + var value = Number(connectionTimeout); + if (value > 0) { + return value; + } + } + }, + maxReconnectionAttempts: function (maxReconnectionAttempts) { + if (Utils_1.Utils.isDecimal(maxReconnectionAttempts)) { + var value = Number(maxReconnectionAttempts); + if (value >= 0) { + return value; + } + } + }, + reconnectionTimeout: function (reconnectionTimeout) { + if (Utils_1.Utils.isDecimal(reconnectionTimeout)) { + var value = Number(reconnectionTimeout); + if (value > 0) { + return value; + } + } + } + } + }; + }; + Transport.C = TransportStatus; + return Transport; +}(Transport_1.Transport)); +exports.Transport = Transport; + +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(77))) + +/***/ }), +/* 115 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +var Modifiers = __webpack_require__(112); +exports.Modifiers = Modifiers; +var Simple_1 = __webpack_require__(116); +exports.Simple = Simple_1.Simple; +var SessionDescriptionHandler_1 = __webpack_require__(111); +exports.SessionDescriptionHandler = SessionDescriptionHandler_1.SessionDescriptionHandler; +var Transport_1 = __webpack_require__(114); +exports.Transport = Transport_1.Transport; + + +/***/ }), +/* 116 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(global) { +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var events_1 = __webpack_require__(2); +var UA_1 = __webpack_require__(76); +var Modifiers = __webpack_require__(112); +/* Simple + * @class Simple + */ +var SimpleStatus; +(function (SimpleStatus) { + SimpleStatus[SimpleStatus["STATUS_NULL"] = 0] = "STATUS_NULL"; + SimpleStatus[SimpleStatus["STATUS_NEW"] = 1] = "STATUS_NEW"; + SimpleStatus[SimpleStatus["STATUS_CONNECTING"] = 2] = "STATUS_CONNECTING"; + SimpleStatus[SimpleStatus["STATUS_CONNECTED"] = 3] = "STATUS_CONNECTED"; + SimpleStatus[SimpleStatus["STATUS_COMPLETED"] = 4] = "STATUS_COMPLETED"; +})(SimpleStatus = exports.SimpleStatus || (exports.SimpleStatus = {})); +var Simple = /** @class */ (function (_super) { + __extends(Simple, _super); + function Simple(options) { + var _this = _super.call(this) || this; + /* + * { + * media: { + * remote: { + * audio: , + * video: + * }, + * local: { + * video: + * } + * }, + * ua: { + * + * } + * } + */ + if (options.media.remote.video) { + _this.video = true; + } + else { + _this.video = false; + } + if (options.media.remote.audio) { + _this.audio = true; + } + else { + _this.audio = false; + } + if (!_this.audio && !_this.video) { + // Need to do at least audio or video + // Error + throw new Error("At least one remote audio or video element is required for Simple."); + } + _this.options = options; + // https://stackoverflow.com/questions/7944460/detect-safari-browser + var browserUa = global.navigator.userAgent.toLowerCase(); + var isSafari = false; + var isFirefox = false; + if (browserUa.indexOf("safari") > -1 && browserUa.indexOf("chrome") < 0) { + isSafari = true; + } + else if (browserUa.indexOf("firefox") > -1 && browserUa.indexOf("chrome") < 0) { + isFirefox = true; + } + var sessionDescriptionHandlerFactoryOptions = {}; + if (isSafari) { + sessionDescriptionHandlerFactoryOptions.modifiers = [Modifiers.stripG722]; + } + if (isFirefox) { + sessionDescriptionHandlerFactoryOptions.alwaysAcquireMediaFirst = true; + } + if (!_this.options.ua.uri) { + _this.anonymous = true; + } + else { + _this.anonymous = false; + } + _this.ua = new UA_1.UA({ + // User Configurable Options + uri: _this.options.ua.uri, + authorizationUser: _this.options.ua.authorizationUser, + password: _this.options.ua.password, + displayName: _this.options.ua.displayName, + // Undocumented "Advanced" Options + userAgentString: _this.options.ua.userAgentString, + // Fixed Options + register: true, + sessionDescriptionHandlerFactoryOptions: sessionDescriptionHandlerFactoryOptions, + transportOptions: { + traceSip: _this.options.ua.traceSip, + wsServers: _this.options.ua.wsServers + } + }); + _this.state = SimpleStatus.STATUS_NULL; + _this.logger = _this.ua.getLogger("sip.simple"); + _this.ua.on("registered", function () { + _this.emit("registered", _this.ua); + }); + _this.ua.on("unregistered", function () { + _this.emit("unregistered", _this.ua); + }); + _this.ua.on("registrationFailed", function () { + _this.emit("unregistered", _this.ua); + }); + _this.ua.on("invite", function (session) { + // If there is already an active session reject the incoming session + if (_this.state !== SimpleStatus.STATUS_NULL && _this.state !== SimpleStatus.STATUS_COMPLETED) { + _this.logger.warn("Rejecting incoming call. Simple only supports 1 call at a time"); + session.reject(); + return; + } + _this.session = session; + _this.setupSession(); + _this.emit("ringing", _this.session); + }); + _this.ua.on("message", function (message) { + _this.emit("message", message); + }); + return _this; + } + Simple.prototype.call = function (destination) { + if (!this.ua || !this.checkRegistration()) { + this.logger.warn("A registered UA is required for calling"); + return; + } + if (this.state !== SimpleStatus.STATUS_NULL && this.state !== SimpleStatus.STATUS_COMPLETED) { + this.logger.warn("Cannot make more than a single call with Simple"); + return; + } + // Safari hack, because you cannot call .play() from a non user action + if (this.options.media.remote.audio) { + this.options.media.remote.audio.autoplay = true; + } + if (this.options.media.remote.video) { + this.options.media.remote.video.autoplay = true; + } + if (this.options.media.local && this.options.media.local.video) { + this.options.media.local.video.autoplay = true; + this.options.media.local.video.volume = 0; + } + this.session = this.ua.invite(destination, { + sessionDescriptionHandlerOptions: { + constraints: { + audio: this.audio, + video: this.video + } + } + }); + this.setupSession(); + return this.session; + }; + Simple.prototype.answer = function () { + if (this.state !== SimpleStatus.STATUS_NEW && this.state !== SimpleStatus.STATUS_CONNECTING) { + this.logger.warn("No call to answer"); + return; + } + // Safari hack, because you cannot call .play() from a non user action + if (this.options.media.remote.audio) { + this.options.media.remote.audio.autoplay = true; + } + if (this.options.media.remote.video) { + this.options.media.remote.video.autoplay = true; + } + return this.session.accept({ + sessionDescriptionHandlerOptions: { + constraints: { + audio: this.audio, + video: this.video + } + } + }); + // emit call is active + }; + Simple.prototype.reject = function () { + if (this.state !== SimpleStatus.STATUS_NEW && this.state !== SimpleStatus.STATUS_CONNECTING) { + this.logger.warn("Call is already answered"); + return; + } + return this.session.reject(); + }; + Simple.prototype.hangup = function () { + if (this.state !== SimpleStatus.STATUS_CONNECTED && + this.state !== SimpleStatus.STATUS_CONNECTING && + this.state !== SimpleStatus.STATUS_NEW) { + this.logger.warn("No active call to hang up on"); + return; + } + if (this.state !== SimpleStatus.STATUS_CONNECTED) { + return this.session.cancel(); + } + else if (this.session) { + return this.session.bye(); + } + }; + Simple.prototype.hold = function () { + if (this.state !== SimpleStatus.STATUS_CONNECTED || !this.session || this.session.localHold) { + this.logger.warn("Cannot put call on hold"); + return; + } + this.mute(); + this.logger.log("Placing session on hold"); + return this.session.hold(); + }; + Simple.prototype.unhold = function () { + if (this.state !== SimpleStatus.STATUS_CONNECTED || !this.session || !this.session.localHold) { + this.logger.warn("Cannot unhold a call that is not on hold"); + return; + } + this.unmute(); + this.logger.log("Placing call off hold"); + return this.session.unhold(); + }; + Simple.prototype.mute = function () { + if (this.state !== SimpleStatus.STATUS_CONNECTED) { + this.logger.warn("An acitve call is required to mute audio"); + return; + } + this.logger.log("Muting Audio"); + this.toggleMute(true); + this.emit("mute", this); + }; + Simple.prototype.unmute = function () { + if (this.state !== SimpleStatus.STATUS_CONNECTED) { + this.logger.warn("An active call is required to unmute audio"); + return; + } + this.logger.log("Unmuting Audio"); + this.toggleMute(false); + this.emit("unmute", this); + }; + Simple.prototype.sendDTMF = function (tone) { + if (this.state !== SimpleStatus.STATUS_CONNECTED || !this.session) { + this.logger.warn("An active call is required to send a DTMF tone"); + return; + } + this.logger.log("Sending DTMF tone: " + tone); + this.session.dtmf(tone); + }; + Simple.prototype.message = function (destination, message) { + if (!this.ua || !this.checkRegistration()) { + this.logger.warn("A registered UA is required to send a message"); + return; + } + if (!destination || !message) { + this.logger.warn("A destination and message are required to send a message"); + return; + } + this.ua.message(destination, message); + }; + // Private Helpers + Simple.prototype.checkRegistration = function () { + return (this.anonymous || (this.ua && this.ua.isRegistered())); + }; + Simple.prototype.setupRemoteMedia = function () { + var _this = this; + if (!this.session) { + this.logger.warn("No session to set remote media on"); + return; + } + // If there is a video track, it will attach the video and audio to the same element + var pc = this.session.sessionDescriptionHandler.peerConnection; + var remoteStream; + if (pc.getReceivers) { + remoteStream = new global.window.MediaStream(); + pc.getReceivers().forEach(function (receiver) { + var track = receiver.track; + if (track) { + remoteStream.addTrack(track); + } + }); + } + else { + remoteStream = pc.getRemoteStreams()[0]; + } + if (this.video) { + this.options.media.remote.video.srcObject = remoteStream; + this.options.media.remote.video.play().catch(function () { + _this.logger.log("play was rejected"); + }); + } + else if (this.audio) { + this.options.media.remote.audio.srcObject = remoteStream; + this.options.media.remote.audio.play().catch(function () { + _this.logger.log("play was rejected"); + }); + } + }; + Simple.prototype.setupLocalMedia = function () { + if (!this.session) { + this.logger.warn("No session to set local media on"); + return; + } + if (this.video && this.options.media.local && this.options.media.local.video) { + var pc = this.session.sessionDescriptionHandler.peerConnection; + var localStream_1; + if (pc.getSenders) { + localStream_1 = new global.window.MediaStream(); + pc.getSenders().forEach(function (sender) { + var track = sender.track; + if (track && track.kind === "video") { + localStream_1.addTrack(track); + } + }); + } + else { + localStream_1 = pc.getLocalStreams()[0]; + } + this.options.media.local.video.srcObject = localStream_1; + this.options.media.local.video.volume = 0; + this.options.media.local.video.play(); + } + }; + Simple.prototype.cleanupMedia = function () { + if (this.video) { + this.options.media.remote.video.srcObject = null; + this.options.media.remote.video.pause(); + if (this.options.media.local && this.options.media.local.video) { + this.options.media.local.video.srcObject = null; + this.options.media.local.video.pause(); + } + } + if (this.audio) { + this.options.media.remote.audio.srcObject = null; + this.options.media.remote.audio.pause(); + } + }; + Simple.prototype.setupSession = function () { + var _this = this; + if (!this.session) { + this.logger.warn("No session to set up"); + return; + } + this.state = SimpleStatus.STATUS_NEW; + this.emit("new", this.session); + this.session.on("progress", function () { return _this.onProgress(); }); + this.session.on("accepted", function () { return _this.onAccepted(); }); + this.session.on("rejected", function () { return _this.onEnded(); }); + this.session.on("failed", function () { return _this.onFailed(); }); + this.session.on("terminated", function () { return _this.onEnded(); }); + }; + Simple.prototype.destroyMedia = function () { + if (this.session && this.session.sessionDescriptionHandler) { + this.session.sessionDescriptionHandler.close(); + } + }; + Simple.prototype.toggleMute = function (mute) { + if (!this.session) { + this.logger.warn("No session to toggle mute"); + return; + } + var pc = this.session.sessionDescriptionHandler.peerConnection; + if (pc.getSenders) { + pc.getSenders().forEach(function (sender) { + if (sender.track) { + sender.track.enabled = !mute; + } + }); + } + else { + pc.getLocalStreams().forEach(function (stream) { + stream.getAudioTracks().forEach(function (track) { + track.enabled = !mute; + }); + stream.getVideoTracks().forEach(function (track) { + track.enabled = !mute; + }); + }); + } + }; + Simple.prototype.onAccepted = function () { + var _this = this; + if (!this.session) { + this.logger.warn("No session for accepting"); + return; + } + this.state = SimpleStatus.STATUS_CONNECTED; + this.emit("connected", this.session); + this.setupLocalMedia(); + this.setupRemoteMedia(); + if (this.session.sessionDescriptionHandler) { + this.session.sessionDescriptionHandler.on("addTrack", function () { + _this.logger.log("A track has been added, triggering new remoteMedia setup"); + _this.setupRemoteMedia(); + }); + this.session.sessionDescriptionHandler.on("addStream", function () { + _this.logger.log("A stream has been added, trigger new remoteMedia setup"); + _this.setupRemoteMedia(); + }); + } + this.session.on("dtmf", function (request, dtmf) { + _this.emit("dtmf", dtmf.tone); + }); + this.session.on("bye", function () { return _this.onEnded(); }); + }; + Simple.prototype.onProgress = function () { + this.state = SimpleStatus.STATUS_CONNECTING; + this.emit("connecting", this.session); + }; + Simple.prototype.onFailed = function () { + this.onEnded(); + }; + Simple.prototype.onEnded = function () { + this.state = SimpleStatus.STATUS_COMPLETED; + this.emit("ended", this.session); + this.cleanupMedia(); + }; + Simple.C = SimpleStatus; + return Simple; +}(events_1.EventEmitter)); +exports.Simple = Simple; + +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(77))) + +/***/ }) +/******/ ]); +}); \ No newline at end of file diff --git a/dist/sip-0.14.0.min.js b/dist/sip-0.14.0.min.js new file mode 100644 index 000000000..52669b285 --- /dev/null +++ b/dist/sip-0.14.0.min.js @@ -0,0 +1 @@ +!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.SIP=t():e.SIP=t()}(this,function(){return function(e){var t={};function r(n){if(t[n])return t[n].exports;var i=t[n]={i:n,l:!1,exports:{}};return e[n].call(i.exports,i,i.exports,r),i.l=!0,i.exports}return r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var i in e)r.d(n,i,function(t){return e[t]}.bind(null,i));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=64)}([function(e,t,r){var n;e.exports=(n=n||function(e,t){var r=Object.create||function(){function e(){}return function(t){var r;return e.prototype=t,r=new e,e.prototype=null,r}}(),n={},i=n.lib={},o=i.Base={extend:function(e){var t=r(this);return e&&t.mixIn(e),t.hasOwnProperty("init")&&this.init!==t.init||(t.init=function(){t.$super.init.apply(this,arguments)}),t.init.prototype=t,t.$super=this,t},create:function(){var e=this.extend();return e.init.apply(e,arguments),e},init:function(){},mixIn:function(e){for(var t in e)e.hasOwnProperty(t)&&(this[t]=e[t]);e.hasOwnProperty("toString")&&(this.toString=e.toString)},clone:function(){return this.init.prototype.extend(this)}},s=i.WordArray=o.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=null!=t?t:4*e.length},toString:function(e){return(e||c).stringify(this)},concat:function(e){var t=this.words,r=e.words,n=this.sigBytes,i=e.sigBytes;if(this.clamp(),n%4)for(var o=0;o>>2]>>>24-o%4*8&255;t[n+o>>>2]|=s<<24-(n+o)%4*8}else for(var o=0;o>>2]=r[o>>>2];return this.sigBytes+=i,this},clamp:function(){var t=this.words,r=this.sigBytes;t[r>>>2]&=4294967295<<32-r%4*8,t.length=e.ceil(r/4)},clone:function(){var e=o.clone.call(this);return e.words=this.words.slice(0),e},random:function(t){for(var r,n=[],i=function(t){var t=t,r=987654321,n=4294967295;return function(){var i=((r=36969*(65535&r)+(r>>16)&n)<<16)+(t=18e3*(65535&t)+(t>>16)&n)&n;return i/=4294967296,(i+=.5)*(e.random()>.5?1:-1)}},o=0;o>>2]>>>24-i%4*8&255;n.push((o>>>4).toString(16)),n.push((15&o).toString(16))}return n.join("")},parse:function(e){for(var t=e.length,r=[],n=0;n>>3]|=parseInt(e.substr(n,2),16)<<24-n%8*4;return new s.init(r,t/2)}},u=a.Latin1={stringify:function(e){for(var t=e.words,r=e.sigBytes,n=[],i=0;i>>2]>>>24-i%4*8&255;n.push(String.fromCharCode(o))}return n.join("")},parse:function(e){for(var t=e.length,r=[],n=0;n>>2]|=(255&e.charCodeAt(n))<<24-n%4*8;return new s.init(r,t)}},d=a.Utf8={stringify:function(e){try{return decodeURIComponent(escape(u.stringify(e)))}catch(e){throw new Error("Malformed UTF-8 data")}},parse:function(e){return u.parse(unescape(encodeURIComponent(e)))}},h=i.BufferedBlockAlgorithm=o.extend({reset:function(){this._data=new s.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=d.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var r=this._data,n=r.words,i=r.sigBytes,o=this.blockSize,a=4*o,c=i/a,u=(c=t?e.ceil(c):e.max((0|c)-this._minBufferSize,0))*o,d=e.min(4*u,i);if(u){for(var h=0;h>>2];e.sigBytes-=t}},m=(r.BlockCipher=h.extend({cfg:h.cfg.extend({mode:f,padding:v}),reset:function(){h.reset.call(this);var e=this.cfg,t=e.iv,r=e.mode;if(this._xformMode==this._ENC_XFORM_MODE)var n=r.createEncryptor;else{var n=r.createDecryptor;this._minBufferSize=1}this._mode&&this._mode.__creator==n?this._mode.init(this,t&&t.words):(this._mode=n.call(r,this,t&&t.words),this._mode.__creator=n)},_doProcessBlock:function(e,t){this._mode.processBlock(e,t)},_doFinalize:function(){var e=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE){e.pad(this._data,this.blockSize);var t=this._process(!0)}else{var t=this._process(!0);e.unpad(t)}return t},blockSize:4}),r.CipherParams=i.extend({init:function(e){this.mixIn(e)},toString:function(e){return(e||this.formatter).stringify(this)}})),y=t.format={},S=y.OpenSSL={stringify:function(e){var t=e.ciphertext,r=e.salt;if(r)var n=o.create([1398893684,1701076831]).concat(r).concat(t);else var n=t;return n.toString(c)},parse:function(e){var t=c.parse(e),r=t.words;if(1398893684==r[0]&&1701076831==r[1]){var n=o.create(r.slice(2,4));r.splice(0,4),t.sigBytes-=16}return m.create({ciphertext:t,salt:n})}},T=r.SerializableCipher=i.extend({cfg:i.extend({format:S}),encrypt:function(e,t,r,n){n=this.cfg.extend(n);var i=e.createEncryptor(r,n),o=i.finalize(t),s=i.cfg;return m.create({ciphertext:o,key:r,iv:s.iv,algorithm:e,mode:s.mode,padding:s.padding,blockSize:e.blockSize,formatter:n.format})},decrypt:function(e,t,r,n){n=this.cfg.extend(n),t=this._parse(t,n.format);var i=e.createDecryptor(r,n).finalize(t.ciphertext);return i},_parse:function(e,t){return"string"==typeof e?t.parse(e,this):e}}),C=t.kdf={},b=C.OpenSSL={execute:function(e,t,r,n){n||(n=o.random(8));var i=d.create({keySize:t+r}).compute(e,n),s=o.create(i.words.slice(t),4*r);return i.sigBytes=4*t,m.create({key:i,iv:s,salt:n})}},_=r.PasswordBasedCipher=T.extend({cfg:T.cfg.extend({kdf:b}),encrypt:function(e,t,r,n){var i=(n=this.cfg.extend(n)).kdf.execute(r,e.keySize,e.ivSize);n.iv=i.iv;var o=T.encrypt.call(this,e,t,i.key,n);return o.mixIn(i),o},decrypt:function(e,t,r,n){n=this.cfg.extend(n),t=this._parse(t,n.format);var i=n.kdf.execute(r,e.keySize,e.ivSize,t.salt);n.iv=i.iv;var o=T.decrypt.call(this,e,t,i.key,n);return o}})}()))},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(2),i=r(3),o=r(11);!function(e){e.defer=function(){var e={};return e.promise=new Promise(function(t,r){e.resolve=t,e.reject=r}),e},e.reducePromises=function(e,t){return e.reduce(function(e,t){return e=e.then(t)},Promise.resolve(t))},e.str_utf8_length=function(e){return encodeURIComponent(e).replace(/%[A-F\d]{2}/g,"U").length},e.generateFakeSDP=function(e){if(e){var t=e.indexOf("o="),r=e.indexOf("\r\n",t);return"v=0\r\n"+e.slice(t,r)+"\r\ns=-\r\nt=0 0\r\nc=IN IP4 0.0.0.0"}},e.isDecimal=function(e){var t=parseInt(e,10);return!isNaN(t)&&parseFloat(e)===t},e.createRandomToken=function(e,t){void 0===t&&(t=32);for(var r="",n=0;n699)throw new TypeError("Invalid statusCode: "+t);if(t)return e.getReasonHeaderValue(t,r)},e.buildStatusLine=function(t,r){if(!t||t<100||t>699)throw new TypeError("Invalid statusCode: "+t);if(r&&"string"!=typeof r&&!(r instanceof String))throw new TypeError("Invalid reason: "+r);return"SIP/2.0 "+t+" "+(r=e.getReasonPhrase(t,r))+"\r\n"}}(t.Utils||(t.Utils={}))},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(2),i=r(8),o=r(1),s=function(){function e(e,t,r,n){this.transactionConstructor=e,this.core=t,this.message=r,this.delegate=n,this.challenged=!1,this.stale=!1,this.logger=this.loggerFactory.getLogger("sip.user-agent-client"),this.init()}return e.prototype.dispose=function(){this.transaction.dispose()},Object.defineProperty(e.prototype,"loggerFactory",{get:function(){return this.core.loggerFactory},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"transaction",{get:function(){if(!this._transaction)throw new Error("Transaction undefined.");return this._transaction},enumerable:!0,configurable:!0}),e.prototype.cancel=function(t,r){var s=this;if(void 0===r&&(r={}),!this.transaction)throw new Error("Transaction undefined.");if(!this.message.to)throw new Error("To undefined.");if(!this.message.from)throw new Error("From undefined.");var a=new i.OutgoingRequest(n.C.CANCEL,this.message.ruri,this.message.ua,{toUri:this.message.to.uri,toTag:this.message.toTag,fromUri:this.message.from.uri,fromTag:this.message.fromTag,callId:this.message.callId,cseq:this.message.cseq},r.extraHeaders);if(a.callId=this.message.callId,a.cseq=this.message.cseq,a.branch=this.message.branch,this.message.headers.Route&&(a.headers.Route=this.message.headers.Route),t&&a.setHeader("Reason",t),this.transaction.state===o.TransactionState.Proceeding)new e(o.NonInviteClientTransaction,this.core,a);else this.transaction.once("stateChanged",function(){if(s.transaction&&s.transaction.state===o.TransactionState.Proceeding)new e(o.NonInviteClientTransaction,s.core,a)});return a},e.prototype.authenticationGuard=function(e){var t,r,n=e.statusCode;if(!n)throw new Error("Response status code undefined.");if(401!==n&&407!==n)return!0;if(401===n?(t=e.parseHeader("www-authenticate"),r="authorization"):(t=e.parseHeader("proxy-authenticate"),r="proxy-authorization"),!t)return this.logger.warn(n+" with wrong or missing challenge, cannot authenticate"),!0;if(this.challenged&&(this.stale||!0!==t.stale))return this.logger.warn(n+" apparently in authentication loop, cannot authenticate"),!0;if(!this.credentials&&(this.credentials=this.core.configuration.authenticationFactory(),!this.credentials))return this.logger.warn("Unable to obtain credentials, cannot authenticate"),!0;if(!this.credentials.authenticate(this.message,t))return!0;this.challenged=!0,t.stale&&(this.stale=!0);var i=this.message.cseq+=1;return this.message.setHeader("cseq",i+" "+this.message.method),this.message.setHeader(r,this.credentials.toString()),this.init(),!1},e.prototype.receiveResponse=function(e){if(this.authenticationGuard(e)){var t=e.statusCode?e.statusCode.toString():"";if(!t)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(t):this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e});break;case/^1[0-9]{2}$/.test(t):this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e});break;case/^2[0-9]{2}$/.test(t):this.delegate&&this.delegate.onAccept&&this.delegate.onAccept({message:e});break;case/^3[0-9]{2}$/.test(t):this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e});break;case/^[4-6][0-9]{2}$/.test(t):this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e});break;default:throw new Error("Invalid status code "+t)}}},e.prototype.init=function(){var e=this,t={loggerFactory:this.loggerFactory,onRequestTimeout:function(){return e.onRequestTimeout()},onStateChange:function(t){t===o.TransactionState.Terminated&&(e.core.userAgentClients.delete(n),r===e._transaction&&e.dispose())},onTransportError:function(t){return e.onTransportError(t)},receiveResponse:function(t){return e.receiveResponse(t)}},r=new this.transactionConstructor(this.message,this.core.transport,t);this._transaction=r;var n=r.id+r.request.method;this.core.userAgentClients.set(n,this)},e.prototype.onRequestTimeout=function(){this.logger.warn("User agent client request timed out. Generating internal 408 Request Timeout.");var e=this.core.configuration.onRequestTimeoutResponseMessageFactory();this.receiveResponse(e)},e.prototype.onTransportError=function(e){this.logger.error(e.message),this.logger.error("User agent client request transport error. Generating internal 503 Service Unavailable.");var t=this.core.configuration.onTransportErrorResponseMessageFactory();this.receiveResponse(t)},e}();t.UserAgentClient=s},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(3),s=function(e){function t(t){var r=this.constructor,n=e.call(this,t)||this;return Object.setPrototypeOf(n,r.prototype),n}return i(t,e),t}(Error);t.Exception=s,function(e){var t=function(e){function t(t){return e.call(this,t||"Transaction state error.")||this}return i(t,e),t}(s);e.TransactionStateError=t;var r=function(e){function t(){return e.call(this,"The session description handler has closed.")||this}return i(t,e),t}(s);e.ClosedSessionDescriptionHandlerError=r;var n=function(e){function t(){return e.call(this,"The session has terminated.")||this}return i(t,e),t}(s);e.TerminatedSessionError=n;var o=function(e){function t(t){return e.call(this,t||"Unspecified transport error.")||this}return i(t,e),t}(s);e.TransportError=o;var a=function(e){function t(t){return e.call(this,t||"Unsupported session description content type.")||this}return i(t,e),t}(s);e.UnsupportedSessionDescriptionContentTypeError=a}(t.Exceptions||(t.Exceptions={}));var a=function(e){function t(t,r,n){var i=e.call(this,n)||this;return i.code=t,i.name=r,i.message=n,i}return i(t,e),t}(s);!function(e){var t=function(e){function t(t,r){var n=e.call(this,1,"CONFIGURATION_ERROR",r?"Invalid value "+JSON.stringify(r)+" for parameter '"+t+"'":"Missing parameter: "+t)||this;return n.type=o.TypeStrings.ConfigurationError,n.parameter=t,n.value=r,n}return i(t,e),t}(a);e.ConfigurationError=t;var r=function(e){function t(t){var r=e.call(this,2,"INVALID_STATE_ERROR","Invalid status: "+t)||this;return r.type=o.TypeStrings.InvalidStateError,r.status=t,r}return i(t,e),t}(a);e.InvalidStateError=r;var n=function(e){function t(t){var r=e.call(this,3,"NOT_SUPPORTED_ERROR",t)||this;return r.type=o.TypeStrings.NotSupportedError,r}return i(t,e),t}(a);e.NotSupportedError=n;var s=function(e){function t(t){var r=e.call(this,5,"RENEGOTIATION_ERROR",t)||this;return r.type=o.TypeStrings.RenegotiationError,r}return i(t,e),t}(a);e.RenegotiationError=s;var c=function(e){function t(t,r,n){var i=e.call(this,6,"METHOD_PARAMETER_ERROR",n?"Invalid value "+JSON.stringify(n)+" for parameter '"+r+"'":"Missing parameter: "+r)||this;return i.type=o.TypeStrings.MethodParameterError,i.method=t,i.parameter=r,i.value=n,i}return i(t,e),t}(a);e.MethodParameterError=c;var u=function(e){function t(t,r,n){var i=e.call(this,8,"SESSION_DESCRIPTION_HANDLER_ERROR",n||"Error with Session Description Handler")||this;return i.type=o.TypeStrings.SessionDescriptionHandlerError,i.method=t,i.error=r,i}return i(t,e),t}(a);e.SessionDescriptionHandlerError=u}(t.Exceptions||(t.Exceptions={}))},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(2),s=r(3),a=r(11),c=r(5);t.getSupportedHeader=function(e){var t=[];e.method===o.C.REGISTER?t.push("path","gruu"):e.method===o.C.INVITE&&(e.ua.contact.pubGruu||e.ua.contact.tempGruu)&&t.push("gruu"),e.ua.configuration.rel100===o.C.supported.SUPPORTED&&t.push("100rel"),e.ua.configuration.replaces===o.C.supported.SUPPORTED&&t.push("replaces"),t.push("outbound"),t=t.concat(e.ua.configuration.extraSupported||[]);var r=e.ua.configuration.hackAllowUnregisteredOptionTags||!1,n={};return"Supported: "+(t=t.filter(function(e){var t=o.C.OPTION_TAGS[e],i=!n[e];return n[e]=!0,(t||r)&&i})).join(", ")+"\r\n"};var u=function(){function e(e,t,r,n,i,o){void 0===n&&(n={}),this.type=s.TypeStrings.OutgoingRequest,this.ua=r,this.headers={},this.method=e,this.ruri=t,this.body=o,this.extraHeaders=(i||[]).slice(),n.routeSet?this.setHeader("route",n.routeSet):r.configuration.usePreloadedRoute&&r.transport&&this.setHeader("route",r.transport.server.sipUri),this.setHeader("via",""),this.setHeader("max-forwards","70");var u=n.toUri||t;this.toTag=n.toTag;var d=n.toDisplayName||0===n.toDisplayName?'"'+n.toDisplayName+'" ':"";d+="<"+(u.type===s.TypeStrings.URI?u.toRaw():u)+">",d+=this.toTag?";tag="+this.toTag:"",this.to=a.Grammar.nameAddrHeaderParse(d),this.setHeader("to",d);var h,p=n.fromUri||r.configuration.uri||"";this.fromTag=n.fromTag||c.Utils.newTag(),h=n.fromDisplayName||0===n.fromDisplayName?'"'+n.fromDisplayName+'" ':r.configuration.displayName?'"'+r.configuration.displayName+'" ':"",h+="<"+(p.type===s.TypeStrings.URI?p.toRaw():p)+">;tag=",h+=this.fromTag,this.from=a.Grammar.nameAddrHeaderParse(h),this.setHeader("from",h),this.callId=n.callId||r.configuration.sipjsId+c.Utils.createRandomToken(15),this.setHeader("call-id",this.callId),this.cseq=n.cseq||Math.floor(1e4*Math.random()),this.setHeader("cseq",this.cseq+" "+e)}return e.prototype.getHeader=function(e){var t=this.headers[c.Utils.headerize(e)];if(t){if(t[0])return t[0]}else for(var r=new RegExp("^\\s*"+e+"\\s*:","i"),n=0,i=this.extraHeaders;n=this.headers[e].length)){var r=this.headers[e][t],n=r.raw;if(r.parsed)return r.parsed;var i=a.Grammar.parse(n,e.replace(/-/g,"_"));return-1===i?void this.headers[e].splice(t,1):(r.parsed=i,i)}},e.prototype.s=function(e,t){return void 0===t&&(t=0),this.parseHeader(e,t)},e.prototype.setHeader=function(e,t){this.headers[c.Utils.headerize(e)]=[{raw:t}]},e.prototype.toString=function(){return this.data},e}();t.IncomingMessage=d;var h=function(e){function t(t){var r=e.call(this)||this;return r.ua=t,r.type=s.TypeStrings.IncomingRequest,r}return i(t,e),t}(d);t.IncomingRequest=h;var p=function(e){function t(t){var r=e.call(this)||this;return r.ua=t,r.type=s.TypeStrings.IncomingResponse,r.headers={},r}return i(t,e),t}(d);t.IncomingResponse=p},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(7),i=r(5),o=r(14),s=r(1),a=function(){function e(e,t,r,n){this.transactionConstructor=e,this.core=t,this.message=r,this.delegate=n,this.logger=this.loggerFactory.getLogger("sip.user-agent-server"),this.toTag=r.toTag?r.toTag:i.Utils.newTag(),this.init()}return e.prototype.dispose=function(){this.transaction.dispose()},Object.defineProperty(e.prototype,"loggerFactory",{get:function(){return this.core.loggerFactory},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"transaction",{get:function(){if(!this._transaction)throw new Error("Transaction undefined.");return this._transaction},enumerable:!0,configurable:!0}),e.prototype.accept=function(e){if(void 0===e&&(e={statusCode:200}),!this.acceptable)throw new n.Exceptions.TransactionStateError(this.message.method+" not acceptable in state "+this.transaction.state+".");var t=e.statusCode;if(t<200||t>299)throw new TypeError("Invalid statusCode: "+t);return this.reply(e)},e.prototype.progress=function(e){if(void 0===e&&(e={statusCode:180}),!this.progressable)throw new n.Exceptions.TransactionStateError(this.message.method+" not progressable in state "+this.transaction.state+".");var t=e.statusCode;if(t<101||t>199)throw new TypeError("Invalid statusCode: "+t);return this.reply(e)},e.prototype.redirect=function(e,t){if(void 0===t&&(t={statusCode:302}),!this.redirectable)throw new n.Exceptions.TransactionStateError(this.message.method+" not redirectable in state "+this.transaction.state+".");var r=t.statusCode;if(r<300||r>399)throw new TypeError("Invalid statusCode: "+r);var i=new Array;return e.forEach(function(e){return i.push("Contact: "+e.toString())}),t.extraHeaders=(t.extraHeaders||[]).concat(i),this.reply(t)},e.prototype.reject=function(e){if(void 0===e&&(e={statusCode:480}),!this.rejectable)throw new n.Exceptions.TransactionStateError(this.message.method+" not rejectable in state "+this.transaction.state+".");var t=e.statusCode;if(t<400||t>699)throw new TypeError("Invalid statusCode: "+t);return this.reply(e)},e.prototype.trying=function(e){if(!this.tryingable)throw new n.Exceptions.TransactionStateError(this.message.method+" not tryingable in state "+this.transaction.state+".");return this.reply({statusCode:100})},e.prototype.receiveCancel=function(e){this.delegate&&this.delegate.onCancel&&this.delegate.onCancel(e)},Object.defineProperty(e.prototype,"acceptable",{get:function(){if(this.transaction instanceof s.InviteServerTransaction)return this.transaction.state===s.TransactionState.Proceeding||this.transaction.state===s.TransactionState.Accepted;if(this.transaction instanceof s.NonInviteServerTransaction)return this.transaction.state===s.TransactionState.Trying||this.transaction.state===s.TransactionState.Proceeding;throw new Error("Unknown transaction type.")},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"progressable",{get:function(){if(this.transaction instanceof s.InviteServerTransaction)return this.transaction.state===s.TransactionState.Proceeding;if(this.transaction instanceof s.NonInviteServerTransaction)return!1;throw new Error("Unknown transaction type.")},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"redirectable",{get:function(){if(this.transaction instanceof s.InviteServerTransaction)return this.transaction.state===s.TransactionState.Proceeding;if(this.transaction instanceof s.NonInviteServerTransaction)return this.transaction.state===s.TransactionState.Trying||this.transaction.state===s.TransactionState.Proceeding;throw new Error("Unknown transaction type.")},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"rejectable",{get:function(){if(this.transaction instanceof s.InviteServerTransaction)return this.transaction.state===s.TransactionState.Proceeding;if(this.transaction instanceof s.NonInviteServerTransaction)return this.transaction.state===s.TransactionState.Trying||this.transaction.state===s.TransactionState.Proceeding;throw new Error("Unknown transaction type.")},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"tryingable",{get:function(){if(this.transaction instanceof s.InviteServerTransaction)return this.transaction.state===s.TransactionState.Proceeding;if(this.transaction instanceof s.NonInviteServerTransaction)return this.transaction.state===s.TransactionState.Trying;throw new Error("Unknown transaction type.")},enumerable:!0,configurable:!0}),e.prototype.reply=function(e){e.toTag||100===e.statusCode||(e.toTag=this.toTag),e.userAgent=e.userAgent||this.core.configuration.userAgentHeaderFieldValue;var t=o.constructOutgoingResponse(this.message,e);return this.transaction.receiveResponse(e.statusCode,t.message),t},e.prototype.init=function(){var e=this,t={loggerFactory:this.loggerFactory,onStateChange:function(t){t===s.TransactionState.Terminated&&(e.core.userAgentServers.delete(n),e.dispose())},onTransportError:function(t){e.logger.error(t.message),e.delegate&&e.delegate.onTransportError?e.delegate.onTransportError(t):e.logger.error("User agent server response transport error.")}},r=new this.transactionConstructor(this.message,this.core.transport,t);this._transaction=r;var n=r.id;this.core.userAgentServers.set(r.id,this)},e}();t.UserAgentServer=a},function(e,t,r){"use strict";var n,i="object"==typeof Reflect?Reflect:null,o=i&&"function"==typeof i.apply?i.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)};n=i&&"function"==typeof i.ownKeys?i.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var s=Number.isNaN||function(e){return e!=e};function a(){a.init.call(this)}e.exports=a,a.EventEmitter=a,a.prototype._events=void 0,a.prototype._eventsCount=0,a.prototype._maxListeners=void 0;var c=10;function u(e){return void 0===e._maxListeners?a.defaultMaxListeners:e._maxListeners}function d(e,t,r,n){var i,o,s,a;if("function"!=typeof r)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof r);if(void 0===(o=e._events)?(o=e._events=Object.create(null),e._eventsCount=0):(void 0!==o.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),o=e._events),s=o[t]),void 0===s)s=o[t]=r,++e._eventsCount;else if("function"==typeof s?s=o[t]=n?[r,s]:[s,r]:n?s.unshift(r):s.push(r),(i=u(e))>0&&s.length>i&&!s.warned){s.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=s.length,a=c,console&&console.warn&&console.warn(a)}return e}function h(e,t,r){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},i=function(){for(var e=[],t=0;t0&&(s=t[0]),s instanceof Error)throw s;var a=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw a.context=s,a}var c=i[e];if(void 0===c)return!1;if("function"==typeof c)o(c,this,t);else{var u=c.length,d=f(c,u);for(r=0;r=0;o--)if(r[o]===t||r[o].listener===t){s=r[o].listener,i=o;break}if(i<0)return this;0===i?r.shift():function(e,t){for(;t+1=0;n--)this.removeListener(e,t[n]);return this},a.prototype.listeners=function(e){return p(this,e,!0)},a.prototype.rawListeners=function(e){return p(this,e,!1)},a.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):l.call(e,t)},a.prototype.listenerCount=l,a.prototype.eventNames=function(){return this._eventsCount>0?n(this._events):[]}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(65);!function(e){e.parse=function(e,t){var r={startRule:t};try{n.parse(e,r)}catch(e){r.data=-1}return r.data},e.nameAddrHeaderParse=function(t){var r=e.parse(t,"Name_Addr_Header");return-1!==r?r:void 0},e.URIParse=function(t){var r=e.parse(t,"SIP_URI");return-1!==r?r:void 0}}(t.Grammar||(t.Grammar={}))},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=500;t.Timers={T1:n,T2:4e3,T4:5e3,TIMER_B:32e3,TIMER_D:0,TIMER_F:32e3,TIMER_H:32e3,TIMER_I:0,TIMER_J:0,TIMER_K:0,TIMER_L:32e3,TIMER_M:32e3,TIMER_N:32e3,PROVISIONAL_RESPONSE_INTERVAL:6e4}},function(e,t,r){var n,i,o,s,a,c,u,d;e.exports=(n=r(0),r(25),r(26),o=(i=n).lib,s=o.Base,a=o.WordArray,c=i.algo,u=c.MD5,d=c.EvpKDF=s.extend({cfg:s.extend({keySize:4,hasher:u,iterations:1}),init:function(e){this.cfg=this.cfg.extend(e)},compute:function(e,t){for(var r=this.cfg,n=r.hasher.create(),i=a.create(),o=i.words,s=r.keySize,c=r.iterations;o.length>>2]>>>24-o%4*8&255)<<16|(t[o+1>>>2]>>>24-(o+1)%4*8&255)<<8|t[o+2>>>2]>>>24-(o+2)%4*8&255,a=0;a<4&&o+.75*a>>6*(3-a)&63));var c=n.charAt(64);if(c)for(;i.length%4;)i.push(c);return i.join("")},parse:function(e){var t=e.length,r=this._map,n=this._reverseMap;if(!n){n=this._reverseMap=[];for(var i=0;i>>6-s%4*2;n[i>>>2]|=(a|c)<<24-i%4*8,i++}return o.create(n,i)}(e,t,n)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="},n.enc.Base64)},function(e,t,r){var n;e.exports=(n=r(0),function(e){var t=n,r=t.lib,i=r.WordArray,o=r.Hasher,s=t.algo,a=[];!function(){for(var t=0;t<64;t++)a[t]=4294967296*e.abs(e.sin(t+1))|0}();var c=s.MD5=o.extend({_doReset:function(){this._hash=new i.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(e,t){for(var r=0;r<16;r++){var n=t+r,i=e[n];e[n]=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8)}var o=this._hash.words,s=e[t+0],c=e[t+1],l=e[t+2],f=e[t+3],g=e[t+4],v=e[t+5],m=e[t+6],y=e[t+7],S=e[t+8],T=e[t+9],C=e[t+10],b=e[t+11],_=e[t+12],A=e[t+13],w=e[t+14],E=e[t+15],R=o[0],I=o[1],O=o[2],x=o[3];R=u(R,I,O,x,s,7,a[0]),x=u(x,R,I,O,c,12,a[1]),O=u(O,x,R,I,l,17,a[2]),I=u(I,O,x,R,f,22,a[3]),R=u(R,I,O,x,g,7,a[4]),x=u(x,R,I,O,v,12,a[5]),O=u(O,x,R,I,m,17,a[6]),I=u(I,O,x,R,y,22,a[7]),R=u(R,I,O,x,S,7,a[8]),x=u(x,R,I,O,T,12,a[9]),O=u(O,x,R,I,C,17,a[10]),I=u(I,O,x,R,b,22,a[11]),R=u(R,I,O,x,_,7,a[12]),x=u(x,R,I,O,A,12,a[13]),O=u(O,x,R,I,w,17,a[14]),R=d(R,I=u(I,O,x,R,E,22,a[15]),O,x,c,5,a[16]),x=d(x,R,I,O,m,9,a[17]),O=d(O,x,R,I,b,14,a[18]),I=d(I,O,x,R,s,20,a[19]),R=d(R,I,O,x,v,5,a[20]),x=d(x,R,I,O,C,9,a[21]),O=d(O,x,R,I,E,14,a[22]),I=d(I,O,x,R,g,20,a[23]),R=d(R,I,O,x,T,5,a[24]),x=d(x,R,I,O,w,9,a[25]),O=d(O,x,R,I,f,14,a[26]),I=d(I,O,x,R,S,20,a[27]),R=d(R,I,O,x,A,5,a[28]),x=d(x,R,I,O,l,9,a[29]),O=d(O,x,R,I,y,14,a[30]),R=h(R,I=d(I,O,x,R,_,20,a[31]),O,x,v,4,a[32]),x=h(x,R,I,O,S,11,a[33]),O=h(O,x,R,I,b,16,a[34]),I=h(I,O,x,R,w,23,a[35]),R=h(R,I,O,x,c,4,a[36]),x=h(x,R,I,O,g,11,a[37]),O=h(O,x,R,I,y,16,a[38]),I=h(I,O,x,R,C,23,a[39]),R=h(R,I,O,x,A,4,a[40]),x=h(x,R,I,O,s,11,a[41]),O=h(O,x,R,I,f,16,a[42]),I=h(I,O,x,R,m,23,a[43]),R=h(R,I,O,x,T,4,a[44]),x=h(x,R,I,O,_,11,a[45]),O=h(O,x,R,I,E,16,a[46]),R=p(R,I=h(I,O,x,R,l,23,a[47]),O,x,s,6,a[48]),x=p(x,R,I,O,y,10,a[49]),O=p(O,x,R,I,w,15,a[50]),I=p(I,O,x,R,v,21,a[51]),R=p(R,I,O,x,_,6,a[52]),x=p(x,R,I,O,f,10,a[53]),O=p(O,x,R,I,C,15,a[54]),I=p(I,O,x,R,c,21,a[55]),R=p(R,I,O,x,S,6,a[56]),x=p(x,R,I,O,E,10,a[57]),O=p(O,x,R,I,m,15,a[58]),I=p(I,O,x,R,A,21,a[59]),R=p(R,I,O,x,g,6,a[60]),x=p(x,R,I,O,b,10,a[61]),O=p(O,x,R,I,l,15,a[62]),I=p(I,O,x,R,T,21,a[63]),o[0]=o[0]+R|0,o[1]=o[1]+I|0,o[2]=o[2]+O|0,o[3]=o[3]+x|0},_doFinalize:function(){var t=this._data,r=t.words,n=8*this._nDataBytes,i=8*t.sigBytes;r[i>>>5]|=128<<24-i%32;var o=e.floor(n/4294967296),s=n;r[15+(i+64>>>9<<4)]=16711935&(o<<8|o>>>24)|4278255360&(o<<24|o>>>8),r[14+(i+64>>>9<<4)]=16711935&(s<<8|s>>>24)|4278255360&(s<<24|s>>>8),t.sigBytes=4*(r.length+1),this._process();for(var a=this._hash,c=a.words,u=0;u<4;u++){var d=c[u];c[u]=16711935&(d<<8|d>>>24)|4278255360&(d<<24|d>>>8)}return a},clone:function(){var e=o.clone.call(this);return e._hash=this._hash.clone(),e}});function u(e,t,r,n,i,o,s){var a=e+(t&r|~t&n)+i+s;return(a<>>32-o)+t}function d(e,t,r,n,i,o,s){var a=e+(t&n|r&~n)+i+s;return(a<>>32-o)+t}function h(e,t,r,n,i,o,s){var a=e+(t^r^n)+i+s;return(a<>>32-o)+t}function p(e,t,r,n,i,o,s){var a=e+(r^(t|~n))+i+s;return(a<>>32-o)+t}t.MD5=o._createHelper(c),t.HmacMD5=o._createHmacHelper(c)}(Math),n.MD5)},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(3),s=function(e){function t(t,r,n){var i=e.call(this,n)||this;if(i.type=o.TypeStrings.NameAddrHeader,!t||t.type!==o.TypeStrings.URI)throw new TypeError('missing or invalid "uri" parameter');return i.uri=t,i._displayName=r,i}return i(t,e),Object.defineProperty(t.prototype,"friendlyName",{get:function(){return this.displayName||this.uri.aor},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"displayName",{get:function(){return this._displayName},set:function(e){this._displayName=e},enumerable:!0,configurable:!0}),t.prototype.clone=function(){return new t(this.uri.clone(),this._displayName,JSON.parse(JSON.stringify(this.parameters)))},t.prototype.toString=function(){var e=this.displayName||"0"===this.displayName?'"'+this.displayName+'" ':"";for(var t in e+="<"+this.uri.toString()+">",this.parameters)this.parameters.hasOwnProperty(t)&&(e+=";"+t,null!==this.parameters[t]&&(e+="="+this.parameters[t]));return e},t}(r(19).Parameters);t.NameAddrHeader=s},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(2),s=r(3),a=function(){function e(e){for(var t in this.parameters={},this.type=s.TypeStrings.Parameters,e)e.hasOwnProperty(t)&&this.setParam(t,e[t])}return e.prototype.setParam=function(e,t){e&&(this.parameters[e.toLowerCase()]=null==t?null:t.toString())},e.prototype.getParam=function(e){if(e)return this.parameters[e.toLowerCase()]},e.prototype.hasParam=function(e){return!!e&&!!this.parameters.hasOwnProperty(e.toLowerCase())},e.prototype.deleteParam=function(e){if(e=e.toLowerCase(),this.parameters.hasOwnProperty(e)){var t=this.parameters[e];return delete this.parameters[e],t}},e.prototype.clearParams=function(){this.parameters={}},e}();t.Parameters=a;var c=function(e){function t(t,r,n,i,a,c){var u=e.call(this,a)||this;if(u.headers={},u.type=s.TypeStrings.URI,!n)throw new TypeError('missing or invalid "host" parameter');for(var d in t=t||o.C.SIP,c)c.hasOwnProperty(d)&&u.setHeader(d,c[d]);return u.raw={scheme:t,user:r,host:n,port:i},u.normal={scheme:t.toLowerCase(),user:r,host:n.toLowerCase(),port:i},u}return i(t,e),Object.defineProperty(t.prototype,"_normal",{get:function(){return this.normal},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"_raw",{get:function(){return this.raw},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"scheme",{get:function(){return this.normal.scheme},set:function(e){this.raw.scheme=e,this.normal.scheme=e.toLowerCase()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"user",{get:function(){return this.normal.user},set:function(e){this.normal.user=this.raw.user=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"host",{get:function(){return this.normal.host},set:function(e){this.raw.host=e,this.normal.host=e.toLowerCase()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"aor",{get:function(){return this.normal.user+"@"+this.normal.host},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"port",{get:function(){return this.normal.port},set:function(e){this.normal.port=this.raw.port=e},enumerable:!0,configurable:!0}),t.prototype.setHeader=function(e,t){this.headers[this.headerize(e)]=t instanceof Array?t:[t]},t.prototype.getHeader=function(e){if(e)return this.headers[this.headerize(e)]},t.prototype.hasHeader=function(e){return!!e&&!!this.headers.hasOwnProperty(this.headerize(e))},t.prototype.deleteHeader=function(e){if(e=this.headerize(e),this.headers.hasOwnProperty(e)){var t=this.headers[e];return delete this.headers[e],t}},t.prototype.clearHeaders=function(){this.headers={}},t.prototype.clone=function(){return new t(this._raw.scheme,this._raw.user||"",this._raw.host,this._raw.port,JSON.parse(JSON.stringify(this.parameters)),JSON.parse(JSON.stringify(this.headers)))},t.prototype.toRaw=function(){return this._toString(this._raw)},t.prototype.toString=function(){return this._toString(this._normal)},t.prototype._toString=function(e){var t=e.scheme+":";for(var r in e.scheme.toLowerCase().match("^sips?$")||(t+="//"),e.user&&(t+=this.escapeUser(e.user)+"@"),t+=e.host,(e.port||0===e.port)&&(t+=":"+e.port),this.parameters)this.parameters.hasOwnProperty(r)&&(t+=";"+r,null!==this.parameters[r]&&(t+="="+this.parameters[r]));var n=[];for(var i in this.headers)if(this.headers.hasOwnProperty(i))for(var o in this.headers[i])this.headers[i].hasOwnProperty(o)&&n.push(i+"="+this.headers[i][o]);return n.length>0&&(t+="?"+n.join("&")),t},t.prototype.escapeUser=function(e){return encodeURIComponent(decodeURIComponent(e)).replace(/%3A/gi,":").replace(/%2B/gi,"+").replace(/%3F/gi,"?").replace(/%2F/gi,"/")},t.prototype.headerize=function(e){for(var t={"Call-Id":"Call-ID",Cseq:"CSeq","Min-Se":"Min-SE",Rack:"RAck",Rseq:"RSeq","Www-Authenticate":"WWW-Authenticate"},r=e.toLowerCase().replace(/_/g,"-").split("-"),n=r.length,i="",o=0;oi)throw new TypeError("Invalid statusCode: "+r);var h,p={statusCode:r,reasonPhrase:o,extraHeaders:s,body:c},l=r.toString();switch(!0){case/^100$/.test(l):h=this.incomingRequest.trying(p).message;break;case/^1[0-9]{2}$/.test(l):h=this.incomingRequest.progress(p).message;break;case/^2[0-9]{2}$/.test(l):h=this.incomingRequest.accept(p).message;break;case/^3[0-9]{2}$/.test(l):h=this.incomingRequest.redirect([],p).message;break;case/^[4-6][0-9]{2}$/.test(l):h=this.incomingRequest.reject(p).message;break;default:throw new Error("Invalid status code "+r)}return u.forEach(function(e){t.emit(e,h,o)}),this},t.prototype.onRequestTimeout=function(){this.emit("failed",void 0,s.C.causes.REQUEST_TIMEOUT)},t.prototype.onTransportError=function(){this.emit("failed",void 0,s.C.causes.CONNECTION_ERROR)},t}(o.EventEmitter);t.ServerContext=h},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(2);t.AllowedMethods=[n.C.ACK,n.C.BYE,n.C.CANCEL,n.C.INFO,n.C.INVITE,n.C.MESSAGE,n.C.NOTIFY,n.C.OPTIONS,n.C.PRACK,n.C.REFER,n.C.SUBSCRIBE]},function(e,t){var r;r=function(){return this}();try{r=r||new Function("return this")()}catch(e){"object"==typeof window&&(r=window)}e.exports=r},function(e,t,r){var n,i,o,s,a,c,u,d;e.exports=(n=r(0),o=(i=n).lib,s=o.WordArray,a=o.Hasher,c=i.algo,u=[],d=c.SHA1=a.extend({_doReset:function(){this._hash=new s.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(e,t){for(var r=this._hash.words,n=r[0],i=r[1],o=r[2],s=r[3],a=r[4],c=0;c<80;c++){if(c<16)u[c]=0|e[t+c];else{var d=u[c-3]^u[c-8]^u[c-14]^u[c-16];u[c]=d<<1|d>>>31}var h=(n<<5|n>>>27)+a+u[c];h+=c<20?1518500249+(i&o|~i&s):c<40?1859775393+(i^o^s):c<60?(i&o|i&s|o&s)-1894007588:(i^o^s)-899497514,a=s,s=o,o=i<<30|i>>>2,i=n,n=h}r[0]=r[0]+n|0,r[1]=r[1]+i|0,r[2]=r[2]+o|0,r[3]=r[3]+s|0,r[4]=r[4]+a|0},_doFinalize:function(){var e=this._data,t=e.words,r=8*this._nDataBytes,n=8*e.sigBytes;return t[n>>>5]|=128<<24-n%32,t[14+(n+64>>>9<<4)]=Math.floor(r/4294967296),t[15+(n+64>>>9<<4)]=r,e.sigBytes=4*t.length,this._process(),this._hash},clone:function(){var e=a.clone.call(this);return e._hash=this._hash.clone(),e}}),i.SHA1=a._createHelper(d),i.HmacSHA1=a._createHmacHelper(d),n.SHA1)},function(e,t,r){var n,i,o,s,a,c,u;e.exports=(n=r(0),o=(i=n).lib,s=o.Base,a=i.enc,c=a.Utf8,u=i.algo,void(u.HMAC=s.extend({init:function(e,t){e=this._hasher=new e.init,"string"==typeof t&&(t=c.parse(t));var r=e.blockSize,n=4*r;t.sigBytes>n&&(t=e.finalize(t)),t.clamp();for(var i=this._oKey=t.clone(),o=this._iKey=t.clone(),s=i.words,a=o.words,u=0;u"),o.extraHeaders.push("Contact: "+r.contact),o.extraHeaders.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),o.extraHeaders.push("Refer-To: "+o.target),o.errorListener=o.onTransportError.bind(o),t.transport&&t.transport.on("transportError",o.errorListener),o}return i(t,e),t.prototype.refer=function(e){var t=this;void 0===e&&(e={});var r=(this.extraHeaders||[]).slice();return e.extraHeaders&&r.concat(e.extraHeaders),this.applicant.sendRequest(s.C.REFER,{extraHeaders:this.extraHeaders,receiveResponse:function(r){var n=r&&r.statusCode?r.statusCode.toString():"";/^1[0-9]{2}$/.test(n)?t.emit("referRequestProgress",t):/^2[0-9]{2}$/.test(n)?t.emit("referRequestAccepted",t):/^[4-6][0-9]{2}$/.test(n)&&t.emit("referRequestRejected",t),e.receiveResponse&&e.receiveResponse(r)}}),this},t.prototype.receiveNotify=function(e){var t=e.message.hasHeader("Content-Type")?e.message.getHeader("Content-Type"):void 0;if(t&&-1!==t.search(/^message\/sipfrag/)){var r=d.Grammar.parse(e.message.body,"sipfrag");if(-1===r)return void e.reject({statusCode:489,reasonPhrase:"Bad Event"});switch(!0){case/^1[0-9]{2}$/.test(r.status_code):this.emit("referProgress",this);break;case/^2[0-9]{2}$/.test(r.status_code):this.emit("referAccepted",this),!this.options.activeAfterTransfer&&this.applicant.terminate&&this.applicant.terminate();break;default:this.emit("referRejected",this)}return e.accept(),void this.emit("notify",e.message)}e.reject({statusCode:489,reasonPhrase:"Bad Event"})},t.prototype.initReferTo=function(e){var t;if("string"==typeof e){var r=d.Grammar.parse(e,"Refer_To");t=r&&r.uri?r.uri:e;var n=this.ua.normalizeTarget(e);if(!n)throw new TypeError("Invalid target: "+e);t=n}else{if(!e.session)throw new Error("Session undefined.");var i=e.remoteIdentity.friendlyName,o=e.session.remoteTarget.toString(),s=e.session.callId,a=e.session.remoteTag,c=e.session.localTag;t='"'+i+'" <'+o+"?Replaces="+encodeURIComponent(s+";to-tag="+a+";from-tag="+c)+">"}return t},t}(o.ClientContext);t.ReferClientContext=l;var f=function(e){function t(t,r,n){var i=e.call(this,t,r)||this;return i.session=n,i.type=c.TypeStrings.ReferServerContext,i.ua=t,i.status=c.SessionStatus.STATUS_INVITE_RECEIVED,i.fromTag=i.request.fromTag,i.id=i.request.callId+i.fromTag,i.contact=i.ua.contact.toString(),i.logger=t.getLogger("sip.referservercontext",i.id),i.cseq=Math.floor(1e4*Math.random()),i.callId=i.request.callId,i.fromUri=i.request.to.uri,i.fromTag=i.request.to.parameters.tag,i.remoteTarget=i.request.headers.Contact[0].parsed.uri,i.toUri=i.request.from.uri,i.toTag=i.request.fromTag,i.routeSet=i.request.getHeaders("record-route"),i.request.hasHeader("refer-to")?(i.referTo=i.request.parseHeader("refer-to"),i.referredSession=i.ua.findSession(i.request),i.request.hasHeader("referred-by")&&(i.referredBy=i.request.getHeader("referred-by")),i.referTo.uri.hasHeader("replaces")&&(i.replaces=i.referTo.uri.getHeader("replaces")),i.errorListener=i.onTransportError.bind(i),t.transport&&t.transport.on("transportError",i.errorListener),i.status=c.SessionStatus.STATUS_WAITING_FOR_ANSWER,i):(i.logger.warn("Invalid REFER packet. A refer-to header is required. Rejecting refer."),i.reject(),i)}return i(t,e),t.prototype.progress=function(){if(this.status!==c.SessionStatus.STATUS_WAITING_FOR_ANSWER)throw new u.Exceptions.InvalidStateError(this.status);this.incomingRequest.trying()},t.prototype.reject=function(t){if(void 0===t&&(t={}),this.status===c.SessionStatus.STATUS_TERMINATED)throw new u.Exceptions.InvalidStateError(this.status);this.logger.log("Rejecting refer"),this.status=c.SessionStatus.STATUS_TERMINATED,e.prototype.reject.call(this,t),this.emit("referRequestRejected",this)},t.prototype.accept=function(e,t){var r=this;if(void 0===e&&(e={}),this.status!==c.SessionStatus.STATUS_WAITING_FOR_ANSWER)throw new u.Exceptions.InvalidStateError(this.status);if(this.status=c.SessionStatus.STATUS_ANSWERED,this.incomingRequest.accept({statusCode:202,reasonPhrase:"Accepted"}),this.emit("referRequestAccepted",this),e.followRefer){this.logger.log("Accepted refer, attempting to automatically follow it");var n=this.referTo.uri;if(!n.scheme||!n.scheme.match("^sips?$"))return this.logger.error("SIP.js can only automatically follow SIP refer target"),void this.reject();var i=e.inviteOptions||{},o=(i.extraHeaders||[]).slice();if(this.replaces&&o.push("Replaces: "+decodeURIComponent(this.replaces)),this.referredBy&&o.push("Referred-By: "+this.referredBy),i.extraHeaders=o,n.clearHeaders(),this.targetSession=this.ua.invite(n.toString(),i,t),this.emit("referInviteSent",this),this.targetSession){this.targetSession.once("progress",function(e){var t=e.statusCode||100,n=e.reasonPhrase;r.sendNotify(("SIP/2.0 "+t+" "+n).trim()),r.emit("referProgress",r),r.referredSession&&r.referredSession.emit("referProgress",r)}),this.targetSession.once("accepted",function(){r.logger.log("Successfully followed the refer"),r.sendNotify("SIP/2.0 200 OK"),r.emit("referAccepted",r),r.referredSession&&r.referredSession.emit("referAccepted",r)});var s=function(e){if(r.status!==c.SessionStatus.STATUS_TERMINATED){if(r.logger.log("Refer was not successful. Resuming session"),e&&429===e.statusCode)return r.logger.log("Alerting referrer that identity is required."),void r.sendNotify("SIP/2.0 429 Provide Referrer Identity");r.sendNotify("SIP/2.0 603 Declined"),r.status=c.SessionStatus.STATUS_TERMINATED,r.emit("referRejected",r),r.referredSession&&r.referredSession.emit("referRejected")}};this.targetSession.once("rejected",s),this.targetSession.once("failed",s)}}else this.logger.log("Accepted refer, but did not automatically follow it"),this.sendNotify("SIP/2.0 200 OK"),this.emit("referAccepted",this),this.referredSession&&this.referredSession.emit("referAccepted",this)},t.prototype.sendNotify=function(e){if(this.status!==c.SessionStatus.STATUS_ANSWERED)throw new u.Exceptions.InvalidStateError(this.status);if(-1===d.Grammar.parse(e,"sipfrag"))throw new Error("sipfrag body is required to send notify for refer");if(this.session)this.session.notify(void 0,{extraHeaders:["Event: refer","Subscription-State: terminated"],body:{contentDisposition:"render",contentType:"message/sipfrag",content:e}});else{var t=new p.OutgoingRequest(s.C.NOTIFY,this.remoteTarget,this.ua,{cseq:this.cseq+=1,callId:this.callId,fromUri:this.fromUri,fromTag:this.fromTag,toUri:this.toUri,toTag:this.toTag,routeSet:this.routeSet},["Event: refer","Subscription-State: terminated","Content-Type: message/sipfrag"],e),r=this.ua.transport;if(!r)throw new Error("Transport undefined.");var n={loggerFactory:this.ua.getLoggerFactory()};new a.NonInviteClientTransaction(t,r,n)}},t.prototype.on=function(t,r){return e.prototype.on.call(this,t,r)},t}(h.ServerContext);t.ReferServerContext=f},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=function(e){function t(r,n,i,o,s){var a=e.call(this,n,i,t.makeId(r),o,s)||this;return a._request=r,a.user=i,r.setViaHeader(a.id,n),a}return i(t,e),t.makeId=function(e){if("CANCEL"===e.method){if(!e.branch)throw new Error("Outgoing CANCEL request without a branch.");return e.branch}return"z9hG4bK"+Math.floor(1e7*Math.random())},Object.defineProperty(t.prototype,"request",{get:function(){return this._request},enumerable:!0,configurable:!0}),t.prototype.onRequestTimeout=function(){this.user.onRequestTimeout&&this.user.onRequestTimeout()},t}(r(29).Transaction);t.ClientTransaction=o},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(10),s=r(7),a=function(e){function t(t,r,n,i,o){var s=e.call(this)||this;return s._transport=t,s._user=r,s._id=n,s._state=i,s.logger=r.loggerFactory.getLogger(o,n),s.logger.debug("Constructing "+s.typeToString()+" with id "+s.id+"."),s}return i(t,e),t.prototype.dispose=function(){this.logger.debug("Destroyed "+this.typeToString()+" with id "+this.id+".")},Object.defineProperty(t.prototype,"id",{get:function(){return this._id},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"kind",{get:function(){throw new Error("Invalid kind.")},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"state",{get:function(){return this._state},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"transport",{get:function(){return this._transport},enumerable:!0,configurable:!0}),t.prototype.on=function(t,r){return e.prototype.on.call(this,t,r)},t.prototype.logTransportError=function(e,t){this.logger.error(e.message),this.logger.error("Transport error occurred in "+this.typeToString()+" with id "+this.id+"."),this.logger.error(t)},t.prototype.send=function(e){var t=this;return this.transport.send(e).catch(function(e){var r;if(!(e instanceof s.Exceptions.TransportError))throw r=e&&"string"==typeof e.message?new s.Exceptions.TransportError(e.message):new s.Exceptions.TransportError,t.onTransportError(r),r;t.onTransportError(e)})},t.prototype.setState=function(e){this.logger.debug('State change to "'+e+'" on '+this.typeToString()+" with id "+this.id+"."),this._state=e,this._user.onStateChange&&this._user.onStateChange(e),this.emit("stateChanged")},t.prototype.typeToString=function(){return"UnknownType"},t}(o.EventEmitter);t.Transaction=a},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=function(e){function t(t,r,n,i,o){var s=e.call(this,r,n,t.viaBranch,i,o)||this;return s._request=t,s.user=n,s}return i(t,e),Object.defineProperty(t.prototype,"request",{get:function(){return this._request},enumerable:!0,configurable:!0}),t}(r(29).Transaction);t.ServerTransaction=o},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e){for(var r in e)t.hasOwnProperty(r)||(t[r]=e[r])}(r(95))},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e){for(var r in e)t.hasOwnProperty(r)||(t[r]=e[r])}(r(97))},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(2),i=r(18),o=function(){function e(e,t){this.core=e,this.dialogState=t,this.core.dialogs.set(this.id,this)}return e.initialDialogStateForUserAgentClient=function(e,t){var r=t.getHeaders("record-route").reverse(),n=t.parseHeader("contact");if(!n)throw new Error("Contact undefined.");if(!(n instanceof i.NameAddrHeader))throw new Error("Contact not instance of NameAddrHeader.");var o=n.uri,s=e.cseq,a=e.callId,c=e.fromTag,u=t.toTag;if(!a)throw new Error("Call id undefined.");if(!c)throw new Error("From tag undefined.");if(!u)throw new Error("To tag undefined.");if(!e.from)throw new Error("From undefined.");if(!e.to)throw new Error("To undefined.");var d=e.from.uri,h=e.to.uri;if(!t.statusCode)throw new Error("Incoming response status code undefined.");return{id:a+c+u,early:t.statusCode<200,callId:a,localTag:c,remoteTag:u,localSequenceNumber:s,remoteSequenceNumber:void 0,localURI:d,remoteURI:h,remoteTarget:o,routeSet:r,secure:!1}},e.initialDialogStateForUserAgentServer=function(e,t,r){void 0===r&&(r=!1);var n=e.getHeaders("record-route"),o=e.parseHeader("contact");if(!o)throw new Error("Contact undefined.");if(!(o instanceof i.NameAddrHeader))throw new Error("Contact not instance of NameAddrHeader.");var s=o.uri,a=e.cseq,c=e.callId,u=t,d=e.fromTag,h=e.from.uri;return{id:c+u+d,early:r,callId:c,localTag:u,remoteTag:d,localSequenceNumber:void 0,remoteSequenceNumber:a,localURI:e.to.uri,remoteURI:h,remoteTarget:s,routeSet:n,secure:!1}},e.prototype.dispose=function(){this.core.dialogs.delete(this.id)},Object.defineProperty(e.prototype,"id",{get:function(){return this.dialogState.id},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"early",{get:function(){return this.dialogState.early},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"callId",{get:function(){return this.dialogState.callId},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"localTag",{get:function(){return this.dialogState.localTag},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"remoteTag",{get:function(){return this.dialogState.remoteTag},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"localSequenceNumber",{get:function(){return this.dialogState.localSequenceNumber},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"remoteSequenceNumber",{get:function(){return this.dialogState.remoteSequenceNumber},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"localURI",{get:function(){return this.dialogState.localURI},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"remoteURI",{get:function(){return this.dialogState.remoteURI},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"remoteTarget",{get:function(){return this.dialogState.remoteTarget},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"routeSet",{get:function(){return this.dialogState.routeSet},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"secure",{get:function(){return this.dialogState.secure},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"userAgentCore",{get:function(){return this.core},enumerable:!0,configurable:!0}),e.prototype.confirm=function(){this.dialogState.early=!1},e.prototype.receiveRequest=function(e){if(e.method!==n.C.ACK){if(this.remoteSequenceNumber){if(e.cseq<=this.remoteSequenceNumber)throw new Error("Out of sequence in dialog request. Did you forget to call sequenceGuard()?");this.dialogState.remoteSequenceNumber=e.cseq}this.remoteSequenceNumber||(this.dialogState.remoteSequenceNumber=e.cseq)}},e.prototype.recomputeRouteSet=function(e){this.dialogState.routeSet=e.getHeaders("record-route").reverse()},e.prototype.createOutgoingRequestMessage=function(e,t){var r,n=this.remoteURI,i=this.remoteTag,o=this.localURI,s=this.localTag,a=this.callId;r=t&&t.cseq?t.cseq:this.dialogState.localSequenceNumber?this.dialogState.localSequenceNumber+=1:this.dialogState.localSequenceNumber=1;var c=this.remoteTarget,u=this.routeSet,d=t&&t.extraHeaders,h=t&&t.body?{contentType:t.body.contentType,body:t.body.content}:void 0;return this.core.configuration.outgoingRequestMessageFactory(e,c,{callId:a,cseq:r,fromUri:o,fromTag:s,toUri:n,toTag:i,routeSet:u},d,h)},e.prototype.sequenceGuard=function(e){return e.method===n.C.ACK||(!(this.remoteSequenceNumber&&e.cseq<=this.remoteSequenceNumber)||(this.core.replyStateless(e,{statusCode:500}),!1))},e}();t.Dialog=o},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(1),s=function(e){function t(t,r,n){var i=void 0!==t.userAgentCore?t.userAgentCore:t;return e.call(this,o.NonInviteServerTransaction,i,r,n)||this}return i(t,e),t}(r(9).UserAgentServer);t.NotifyUserAgentServer=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=function(e,t){for(var r,n=[],i=e.split(/\r\n/),o=0;o (https://sipjs.com/aboutus/)",contributors:[{url:"https://github.com/onsip/SIP.js/blob/master/THANKS.md"}],repository:{type:"git",url:"https://github.com/onsip/SIP.js.git"},keywords:["sip","webrtc","library","websocket","javascript","typescript"],dependencies:{"crypto-js":"^3.1.9-1"},devDependencies:{"@types/crypto-js":"^3.1.43","@types/jasmine":"^3.3.11","@types/node":"^12.0.2","circular-dependency-plugin":"^5.0.2","jasmine-core":"^3.4.0",karma:"^4.1.0","karma-chrome-launcher":"^2.2.0","karma-cli":"^2.0.0","karma-jasmine":"^2.0.1","karma-jasmine-html-reporter":"^1.4.2","karma-mocha-reporter":"^2.2.5","karma-sourcemap-loader":"^0.3.7","karma-webpack":"^3.0.5",pegjs:"^0.10.0","ts-loader":"^6.0.1","ts-pegjs":"0.2.3",tslint:"^5.16.0",typescript:"^3.4.5",webpack:"^4.32.0","webpack-cli":"^3.3.2"},engines:{node:">=8.0"},scripts:{prebuild:"tslint -p tsconfig-base.json -c tslint.json","generate-grammar":"node build/grammarGenerator.js","build-reg-bundle":"webpack --progress --config build/webpack.config.js --env.buildType reg","build-min-bundle":"webpack --progress --config build/webpack.config.js --env.buildType min","build-bundles":"npm run build-reg-bundle && npm run build-min-bundle","build-lib":"tsc -p src","build-test":"tsc -p test","copy-dist-files":"cp dist/sip.js dist/sip-$npm_package_version.js && cp dist/sip.min.js dist/sip-$npm_package_version.min.js",build:"npm run generate-grammar && npm run build-lib && npm run build-reg-bundle && npm run build-min-bundle && npm run copy-dist-files",browserTest:"npm run build-test && sleep 2 && open http://0.0.0.0:9876/debug.html & karma start --reporters kjhtml --no-single-run",commandLineTest:"npm run build-test && karma start --reporters mocha --browsers ChromeHeadless --single-run",buildAndTest:"npm run build && npm run commandLineTest",buildAndBrowserTest:"npm run build && npm run browserTest"}}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(66),i=r(3),o=r(5),s=function(){function e(e){this.type=i.TypeStrings.DigestAuthentication,this.logger=e.getLogger("sipjs.digestauthentication"),this.username=e.configuration.authorizationUser,this.password=e.configuration.password,this.nc=0,this.ncHex="00000000"}return e.prototype.authenticate=function(e,t,r){if(this.algorithm=t.algorithm,this.realm=t.realm,this.nonce=t.nonce,this.opaque=t.opaque,this.stale=t.stale,this.algorithm){if("MD5"!==this.algorithm)return this.logger.warn("challenge with Digest algorithm different than 'MD5', authentication aborted"),!1}else this.algorithm="MD5";if(!this.realm)return this.logger.warn("challenge without Digest realm, authentication aborted"),!1;if(!this.nonce)return this.logger.warn("challenge without Digest nonce, authentication aborted"),!1;if(t.qop)if(t.qop.indexOf("auth")>-1)this.qop="auth";else{if(!(t.qop.indexOf("auth-int")>-1))return this.logger.warn("challenge without Digest qop different than 'auth' or 'auth-int', authentication aborted"),!1;this.qop="auth-int"}else this.qop=void 0;return this.method=e.method,this.uri=e.ruri,this.cnonce=o.Utils.createRandomToken(12),this.nc+=1,this.updateNcHex(),4294967296===this.nc&&(this.nc=1,this.ncHex="00000001"),this.calculateResponse(r),!0},e.prototype.toString=function(){var e=[];if(!this.response)throw new Error("response field does not exist, cannot generate Authorization header");return e.push("algorithm="+this.algorithm),e.push('username="'+this.username+'"'),e.push('realm="'+this.realm+'"'),e.push('nonce="'+this.nonce+'"'),e.push('uri="'+this.uri+'"'),e.push('response="'+this.response+'"'),this.opaque&&e.push('opaque="'+this.opaque+'"'),this.qop&&(e.push("qop="+this.qop),e.push('cnonce="'+this.cnonce+'"'),e.push("nc="+this.ncHex)),"Digest "+e.join(", ")},e.prototype.updateNcHex=function(){var e=Number(this.nc).toString(16);this.ncHex="00000000".substr(0,8-e.length)+e},e.prototype.calculateResponse=function(e){var t,r=n.MD5(this.username+":"+this.realm+":"+this.password);"auth"===this.qop?(t=n.MD5(this.method+":"+this.uri),this.response=n.MD5(r+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth:"+t)):"auth-int"===this.qop?(t=n.MD5(this.method+":"+this.uri+":"+n.MD5(e||"")),this.response=n.MD5(r+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth-int:"+t)):void 0===this.qop&&(t=n.MD5(this.method+":"+this.uri),this.response=n.MD5(r+":"+this.nonce+":"+t))},e}();t.DigestAuthentication=s},function(e,t,r){var n;e.exports=(n=r(0),function(e){var t=n,r=t.lib,i=r.WordArray,o=r.Hasher,s=t.algo,a=[],c=[];!function(){function t(t){for(var r=e.sqrt(t),n=2;n<=r;n++)if(!(t%n))return!1;return!0}function r(e){return 4294967296*(e-(0|e))|0}for(var n=2,i=0;i<64;)t(n)&&(i<8&&(a[i]=r(e.pow(n,.5))),c[i]=r(e.pow(n,1/3)),i++),n++}();var u=[],d=s.SHA256=o.extend({_doReset:function(){this._hash=new i.init(a.slice(0))},_doProcessBlock:function(e,t){for(var r=this._hash.words,n=r[0],i=r[1],o=r[2],s=r[3],a=r[4],d=r[5],h=r[6],p=r[7],l=0;l<64;l++){if(l<16)u[l]=0|e[t+l];else{var f=u[l-15],g=(f<<25|f>>>7)^(f<<14|f>>>18)^f>>>3,v=u[l-2],m=(v<<15|v>>>17)^(v<<13|v>>>19)^v>>>10;u[l]=g+u[l-7]+m+u[l-16]}var y=n&i^n&o^i&o,S=(n<<30|n>>>2)^(n<<19|n>>>13)^(n<<10|n>>>22),T=p+((a<<26|a>>>6)^(a<<21|a>>>11)^(a<<7|a>>>25))+(a&d^~a&h)+c[l]+u[l];p=h,h=d,d=a,a=s+T|0,s=o,o=i,i=n,n=T+(S+y)|0}r[0]=r[0]+n|0,r[1]=r[1]+i|0,r[2]=r[2]+o|0,r[3]=r[3]+s|0,r[4]=r[4]+a|0,r[5]=r[5]+d|0,r[6]=r[6]+h|0,r[7]=r[7]+p|0},_doFinalize:function(){var t=this._data,r=t.words,n=8*this._nDataBytes,i=8*t.sigBytes;return r[i>>>5]|=128<<24-i%32,r[14+(i+64>>>9<<4)]=e.floor(n/4294967296),r[15+(i+64>>>9<<4)]=n,t.sigBytes=4*r.length,this._process(),this._hash},clone:function(){var e=o.clone.call(this);return e._hash=this._hash.clone(),e}});t.SHA256=o._createHelper(d),t.HmacSHA256=o._createHmacHelper(d)}(Math),n.SHA256)},function(e,t,r){var n;e.exports=(n=r(0),r(21),function(){var e=n,t=e.lib.Hasher,r=e.x64,i=r.Word,o=r.WordArray,s=e.algo;function a(){return i.create.apply(i,arguments)}var c=[a(1116352408,3609767458),a(1899447441,602891725),a(3049323471,3964484399),a(3921009573,2173295548),a(961987163,4081628472),a(1508970993,3053834265),a(2453635748,2937671579),a(2870763221,3664609560),a(3624381080,2734883394),a(310598401,1164996542),a(607225278,1323610764),a(1426881987,3590304994),a(1925078388,4068182383),a(2162078206,991336113),a(2614888103,633803317),a(3248222580,3479774868),a(3835390401,2666613458),a(4022224774,944711139),a(264347078,2341262773),a(604807628,2007800933),a(770255983,1495990901),a(1249150122,1856431235),a(1555081692,3175218132),a(1996064986,2198950837),a(2554220882,3999719339),a(2821834349,766784016),a(2952996808,2566594879),a(3210313671,3203337956),a(3336571891,1034457026),a(3584528711,2466948901),a(113926993,3758326383),a(338241895,168717936),a(666307205,1188179964),a(773529912,1546045734),a(1294757372,1522805485),a(1396182291,2643833823),a(1695183700,2343527390),a(1986661051,1014477480),a(2177026350,1206759142),a(2456956037,344077627),a(2730485921,1290863460),a(2820302411,3158454273),a(3259730800,3505952657),a(3345764771,106217008),a(3516065817,3606008344),a(3600352804,1432725776),a(4094571909,1467031594),a(275423344,851169720),a(430227734,3100823752),a(506948616,1363258195),a(659060556,3750685593),a(883997877,3785050280),a(958139571,3318307427),a(1322822218,3812723403),a(1537002063,2003034995),a(1747873779,3602036899),a(1955562222,1575990012),a(2024104815,1125592928),a(2227730452,2716904306),a(2361852424,442776044),a(2428436474,593698344),a(2756734187,3733110249),a(3204031479,2999351573),a(3329325298,3815920427),a(3391569614,3928383900),a(3515267271,566280711),a(3940187606,3454069534),a(4118630271,4000239992),a(116418474,1914138554),a(174292421,2731055270),a(289380356,3203993006),a(460393269,320620315),a(685471733,587496836),a(852142971,1086792851),a(1017036298,365543100),a(1126000580,2618297676),a(1288033470,3409855158),a(1501505948,4234509866),a(1607167915,987167468),a(1816402316,1246189591)],u=[];!function(){for(var e=0;e<80;e++)u[e]=a()}();var d=s.SHA512=t.extend({_doReset:function(){this._hash=new o.init([new i.init(1779033703,4089235720),new i.init(3144134277,2227873595),new i.init(1013904242,4271175723),new i.init(2773480762,1595750129),new i.init(1359893119,2917565137),new i.init(2600822924,725511199),new i.init(528734635,4215389547),new i.init(1541459225,327033209)])},_doProcessBlock:function(e,t){for(var r=this._hash.words,n=r[0],i=r[1],o=r[2],s=r[3],a=r[4],d=r[5],h=r[6],p=r[7],l=n.high,f=n.low,g=i.high,v=i.low,m=o.high,y=o.low,S=s.high,T=s.low,C=a.high,b=a.low,_=d.high,A=d.low,w=h.high,E=h.low,R=p.high,I=p.low,O=l,x=f,P=g,N=v,D=m,U=y,H=S,k=T,M=C,q=b,j=_,L=A,F=w,B=E,G=R,W=I,z=0;z<80;z++){var K=u[z];if(z<16)var V=K.high=0|e[t+2*z],Y=K.low=0|e[t+2*z+1];else{var $=u[z-15],X=$.high,J=$.low,Q=(X>>>1|J<<31)^(X>>>8|J<<24)^X>>>7,Z=(J>>>1|X<<31)^(J>>>8|X<<24)^(J>>>7|X<<25),ee=u[z-2],te=ee.high,re=ee.low,ne=(te>>>19|re<<13)^(te<<3|re>>>29)^te>>>6,ie=(re>>>19|te<<13)^(re<<3|te>>>29)^(re>>>6|te<<26),oe=u[z-7],se=oe.high,ae=oe.low,ce=u[z-16],ue=ce.high,de=ce.low;V=(V=(V=Q+se+((Y=Z+ae)>>>0>>0?1:0))+ne+((Y+=ie)>>>0>>0?1:0))+ue+((Y+=de)>>>0>>0?1:0),K.high=V,K.low=Y}var he,pe=M&j^~M&F,le=q&L^~q&B,fe=O&P^O&D^P&D,ge=x&N^x&U^N&U,ve=(O>>>28|x<<4)^(O<<30|x>>>2)^(O<<25|x>>>7),me=(x>>>28|O<<4)^(x<<30|O>>>2)^(x<<25|O>>>7),ye=(M>>>14|q<<18)^(M>>>18|q<<14)^(M<<23|q>>>9),Se=(q>>>14|M<<18)^(q>>>18|M<<14)^(q<<23|M>>>9),Te=c[z],Ce=Te.high,be=Te.low,_e=G+ye+((he=W+Se)>>>0>>0?1:0),Ae=me+ge;G=F,W=B,F=j,B=L,j=M,L=q,M=H+(_e=(_e=(_e=_e+pe+((he+=le)>>>0>>0?1:0))+Ce+((he+=be)>>>0>>0?1:0))+V+((he+=Y)>>>0>>0?1:0))+((q=k+he|0)>>>0>>0?1:0)|0,H=D,k=U,D=P,U=N,P=O,N=x,O=_e+(ve+fe+(Ae>>>0>>0?1:0))+((x=he+Ae|0)>>>0>>0?1:0)|0}f=n.low=f+x,n.high=l+O+(f>>>0>>0?1:0),v=i.low=v+N,i.high=g+P+(v>>>0>>0?1:0),y=o.low=y+U,o.high=m+D+(y>>>0>>0?1:0),T=s.low=T+k,s.high=S+H+(T>>>0>>0?1:0),b=a.low=b+q,a.high=C+M+(b>>>0>>0?1:0),A=d.low=A+L,d.high=_+j+(A>>>0>>0?1:0),E=h.low=E+B,h.high=w+F+(E>>>0>>0?1:0),I=p.low=I+W,p.high=R+G+(I>>>0>>0?1:0)},_doFinalize:function(){var e=this._data,t=e.words,r=8*this._nDataBytes,n=8*e.sigBytes;return t[n>>>5]|=128<<24-n%32,t[30+(n+128>>>10<<5)]=Math.floor(r/4294967296),t[31+(n+128>>>10<<5)]=r,e.sigBytes=4*t.length,this._process(),this._hash.toX32()},clone:function(){var e=t.clone.call(this);return e._hash=this._hash.clone(),e},blockSize:32});e.SHA512=t._createHelper(d),e.HmacSHA512=t._createHmacHelper(d)}(),n.SHA512)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n,i=r(3);!function(e){e[e.error=0]="error",e[e.warn=1]="warn",e[e.log=2]="log",e[e.debug=3]="debug"}(n=t.Levels||(t.Levels={}));var o=function(){function e(){this.builtinEnabled=!0,this._level=n.log,this.loggers={},this.type=i.TypeStrings.LoggerFactory,this.logger=this.getLogger("sip:loggerfactory")}return Object.defineProperty(e.prototype,"level",{get:function(){return this._level},set:function(e){e>=0&&e<=3?this._level=e:e>3?this._level=3:n.hasOwnProperty(e)?this._level=e:this.logger.error("invalid 'level' parameter value: "+JSON.stringify(e))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"connector",{get:function(){return this._connector},set:function(e){e?"function"==typeof e?this._connector=e:this.logger.error("invalid 'connector' parameter value: "+JSON.stringify(e)):this._connector=void 0},enumerable:!0,configurable:!0}),e.prototype.getLogger=function(e,t){if(t&&3===this.level)return new s(this,e,t);if(this.loggers[e])return this.loggers[e];var r=new s(this,e);return this.loggers[e]=r,r},e.prototype.genericLog=function(e,t,r,i){this.level>=e&&this.builtinEnabled&&this.print(e,t,r,i),this.connector&&this.connector(n[e],t,r,i)},e.prototype.print=function(e,t,r,i){if("string"==typeof i){var o=[new Date,t];r&&o.push(r),i=o.concat(i).join(" | ")}switch(e){case n.error:console.error(i);break;case n.warn:console.warn(i);break;case n.log:console.log(i);break;case n.debug:console.debug(i)}},e}();t.LoggerFactory=o;var s=function(){function e(e,t,r){this.type=i.TypeStrings.Logger,this.logger=e,this.category=t,this.label=r}return e.prototype.error=function(e){this.genericLog(n.error,e)},e.prototype.warn=function(e){this.genericLog(n.warn,e)},e.prototype.log=function(e){this.genericLog(n.log,e)},e.prototype.debug=function(e){this.genericLog(n.debug,e)},e.prototype.genericLog=function(e,t){this.logger.genericLog(e,this.category,this.label,t)},e}();t.Logger=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(3),i=r(11),o=r(8);!function(e){function t(e,t){var r=t,n=0,i=0;if(e.substring(r,r+2).match(/(^\r\n)/))return-2;for(;0===n;){if(-1===(i=e.indexOf("\r\n",r)))return i;!e.substring(i+2,i+4).match(/(^\r\n)/)&&e.charAt(i+2).match(/(^\s+)/)?r=i+2:n=i}return n}function r(e,t,r,o){var s,a=t.indexOf(":",r),c=t.substring(r,a).trim(),u=t.substring(a+1,o).trim();switch(c.toLowerCase()){case"via":case"v":e.addHeader("via",u),1===e.getHeaders("via").length?(s=e.parseHeader("Via"))&&(e.via=s,e.viaBranch=s.branch):s=0;break;case"from":case"f":e.setHeader("from",u),(s=e.parseHeader("from"))&&(e.from=s,e.fromTag=s.getParam("tag"));break;case"to":case"t":e.setHeader("to",u),(s=e.parseHeader("to"))&&(e.to=s,e.toTag=s.getParam("tag"));break;case"record-route":if(-1===(s=i.Grammar.parse(u,"Record_Route"))){s=void 0;break}for(var d in s)s[d]&&(e.addHeader("record-route",u.substring(s[d].position,s[d].offset)),e.headers["Record-Route"][e.getHeaders("record-route").length-1].parsed=s[d].parsed);break;case"call-id":case"i":e.setHeader("call-id",u),(s=e.parseHeader("call-id"))&&(e.callId=u);break;case"contact":case"m":if(-1===(s=i.Grammar.parse(u,"Contact"))){s=void 0;break}if(!(s instanceof Array)){s=void 0;break}s.forEach(function(t){e.addHeader("contact",u.substring(t.position,t.offset)),e.headers.Contact[e.getHeaders("contact").length-1].parsed=t.parsed});break;case"content-length":case"l":e.setHeader("content-length",u),s=e.parseHeader("content-length");break;case"content-type":case"c":e.setHeader("content-type",u),s=e.parseHeader("content-type");break;case"cseq":e.setHeader("cseq",u),(s=e.parseHeader("cseq"))&&(e.cseq=s.value),e.type===n.TypeStrings.IncomingResponse&&(e.method=s.method);break;case"max-forwards":e.setHeader("max-forwards",u),s=e.parseHeader("max-forwards");break;case"www-authenticate":e.setHeader("www-authenticate",u),s=e.parseHeader("www-authenticate");break;case"proxy-authenticate":e.setHeader("proxy-authenticate",u),s=e.parseHeader("proxy-authenticate");break;case"refer-to":case"r":e.setHeader("refer-to",u),(s=e.parseHeader("refer-to"))&&(e.referTo=s);break;default:e.setHeader(c,u),s=0}return void 0!==s||{error:"error parsing header '"+c+"'"}}e.getHeader=t,e.parseHeader=r,e.parseMessage=function(e,n){var s=0,a=e.indexOf("\r\n"),c=n.getLogger("sip.parser");if(-1!==a){var u,d=e.substring(0,a),h=i.Grammar.parse(d,"Request_Response");if(-1!==h){var p;for(h.status_code?((u=new o.IncomingResponse(n)).statusCode=h.status_code,u.reasonPhrase=h.reason_phrase):((u=new o.IncomingRequest(n)).method=h.method,u.ruri=h.uri),u.data=e,s=a+2;;){if(-2===(a=t(e,s))){p=s+2;break}if(-1===a)return void c.error("malformed message");if(!0!==r(u,e,s,a))return void c.error(h.error);s=a+2}return u.hasHeader("content-length")?u.body=e.substr(p,Number(u.getHeader("content-length"))):u.body=e.substring(p),u}c.warn('error parsing first line of SIP message: "'+d+'"')}else c.warn("no CRLF found, not a SIP message, discarded")}}(t.Parser||(t.Parser={}))},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(15),s=r(2),a=r(3),c=r(7),u=r(8),d=r(5),h=function(e){function t(t,r,n,i){void 0===i&&(i={});var o=this;if(i.extraHeaders=(i.extraHeaders||[]).slice(),i.contentType=i.contentType||"text/plain","number"!=typeof i.expires||i.expires%1!=0?i.expires=3600:i.expires=Number(i.expires),"boolean"!=typeof i.unpublishOnClose&&(i.unpublishOnClose=!0),null==r||""===r)throw new c.Exceptions.MethodParameterError("Publish","Target",r);if(void 0===(r=t.normalizeTarget(r)))throw new c.Exceptions.MethodParameterError("Publish","Target",r);if((o=e.call(this,t,s.C.PUBLISH,r,i)||this).type=a.TypeStrings.PublishContext,o.options=i,o.target=r,null==n||""===n)throw new c.Exceptions.MethodParameterError("Publish","Event",n);return o.event=n,o.logger=t.getLogger("sip.publish"),o.pubRequestExpires=o.options.expires,t.on("transportCreated",function(e){e.on("transportError",function(){return o.onTransportError()})}),o}return i(t,e),t.prototype.publish=function(e){this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.options.body=e,this.pubRequestBody=this.options.body,0===this.pubRequestExpires&&(this.pubRequestExpires=this.options.expires,this.pubRequestEtag=void 0),this.ua.publishers[this.target.toString()+":"+this.event]||(this.ua.publishers[this.target.toString()+":"+this.event]=this),this.sendPublishRequest()},t.prototype.unpublish=function(){this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.pubRequestBody=void 0,this.pubRequestExpires=0,void 0!==this.pubRequestEtag&&this.sendPublishRequest()},t.prototype.close=function(){this.options.unpublishOnClose?this.unpublish():(this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.pubRequestBody=void 0,this.pubRequestExpires=0,this.pubRequestEtag=void 0),this.ua.publishers[this.target.toString()+":"+this.event]&&delete this.ua.publishers[this.target.toString()+":"+this.event]},t.prototype.onRequestTimeout=function(){e.prototype.onRequestTimeout.call(this),this.emit("unpublished",void 0,s.C.causes.REQUEST_TIMEOUT)},t.prototype.onTransportError=function(){e.prototype.onTransportError.call(this),this.emit("unpublished",void 0,s.C.causes.CONNECTION_ERROR)},t.prototype.receiveResponse=function(e){var t=this,r=e.statusCode||0,n=d.Utils.getReasonPhrase(r);switch(!0){case/^1[0-9]{2}$/.test(r.toString()):this.emit("progress",e,n);break;case/^2[0-9]{2}$/.test(r.toString()):if(e.hasHeader("SIP-ETag")?this.pubRequestEtag=e.getHeader("SIP-ETag"):this.logger.warn("SIP-ETag header missing in a 200-class response to PUBLISH"),e.hasHeader("Expires")){var i=Number(e.getHeader("Expires"));"number"==typeof i&&i>=0&&i<=this.pubRequestExpires?this.pubRequestExpires=i:this.logger.warn("Bad Expires header in a 200-class response to PUBLISH")}else this.logger.warn("Expires header missing in a 200-class response to PUBLISH");0!==this.pubRequestExpires?(this.publishRefreshTimer=setTimeout(function(){return t.refreshRequest()},900*this.pubRequestExpires),this.emit("published",e,n)):this.emit("unpublished",e,n);break;case/^412$/.test(r.toString()):void 0!==this.pubRequestEtag&&0!==this.pubRequestExpires?(this.logger.warn("412 response to PUBLISH, recovering"),this.pubRequestEtag=void 0,this.emit("progress",e,n),this.publish(this.options.body)):(this.logger.warn("412 response to PUBLISH, recovery failed"),this.pubRequestExpires=0,this.emit("failed",e,n),this.emit("unpublished",e,n));break;case/^423$/.test(r.toString()):if(0!==this.pubRequestExpires&&e.hasHeader("Min-Expires")){var o=Number(e.getHeader("Min-Expires"));"number"==typeof o||o>this.pubRequestExpires?(this.logger.warn("423 code in response to PUBLISH, adjusting the Expires value and trying to recover"),this.pubRequestExpires=o,this.emit("progress",e,n),this.publish(this.options.body)):(this.logger.warn("Bad 423 response Min-Expires header received for PUBLISH"),this.pubRequestExpires=0,this.emit("failed",e,n),this.emit("unpublished",e,n))}else this.logger.warn("423 response to PUBLISH, recovery failed"),this.pubRequestExpires=0,this.emit("failed",e,n),this.emit("unpublished",e,n);break;default:this.pubRequestExpires=0,this.emit("failed",e,n),this.emit("unpublished",e,n)}0===this.pubRequestExpires&&(this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.pubRequestBody=void 0,this.pubRequestEtag=void 0)},t.prototype.send=function(){var e=this;return this.ua.userAgentCore.publish(this.request,{onAccept:function(t){return e.receiveResponse(t.message)},onProgress:function(t){return e.receiveResponse(t.message)},onRedirect:function(t){return e.receiveResponse(t.message)},onReject:function(t){return e.receiveResponse(t.message)},onTrying:function(t){return e.receiveResponse(t.message)}}),this},t.prototype.refreshRequest=function(){if(this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.pubRequestBody=void 0,void 0===this.pubRequestEtag)throw new c.Exceptions.MethodParameterError("Publish","Body",void 0);if(0===this.pubRequestExpires)throw new c.Exceptions.MethodParameterError("Publish","Expire",this.pubRequestExpires);this.sendPublishRequest()},t.prototype.sendPublishRequest=function(){var e=Object.create(this.options||Object.prototype);e.extraHeaders=(this.options.extraHeaders||[]).slice(),e.extraHeaders.push("Event: "+this.event),e.extraHeaders.push("Expires: "+this.pubRequestExpires),void 0!==this.pubRequestEtag&&e.extraHeaders.push("SIP-If-Match: "+this.pubRequestEtag),this.request=new u.OutgoingRequest(s.C.PUBLISH,this.target,this.ua,this.options.params,e.extraHeaders),void 0!==this.pubRequestBody&&(this.request.body={body:this.pubRequestBody,contentType:this.options.contentType}),this.send()},t}(o.ClientContext);t.PublishContext=h},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(12),s=r(28),a=r(20),c=function(e){function t(t,r,n){var i=e.call(this,t,r,n,a.TransactionState.Calling,"sip.transaction.ict")||this;return i.ackRetransmissionCache=new Map,i.B=setTimeout(function(){return i.timer_B()},o.Timers.TIMER_B),i.send(t.toString()).catch(function(e){i.logTransportError(e,"Failed to send initial outgoing request.")}),i}return i(t,e),t.prototype.dispose=function(){this.B&&(clearTimeout(this.B),this.B=void 0),this.D&&(clearTimeout(this.D),this.D=void 0),this.M&&(clearTimeout(this.M),this.M=void 0),e.prototype.dispose.call(this)},Object.defineProperty(t.prototype,"kind",{get:function(){return"ict"},enumerable:!0,configurable:!0}),t.prototype.ackResponse=function(e){var t=this,r=e.toTag;if(!r)throw new Error("To tag undefined.");var n="z9hG4bK"+Math.floor(1e7*Math.random());e.setViaHeader(n,this.transport),this.ackRetransmissionCache.set(r,e),this.send(e.toString()).catch(function(e){t.logTransportError(e,"Failed to send ACK to 2xx response.")})},t.prototype.receiveResponse=function(e){var t=this,r=e.statusCode;if(!r||r<100||r>699)throw new Error("Invalid status code "+r);switch(this.state){case a.TransactionState.Calling:if(r>=100&&r<=199)return this.stateTransition(a.TransactionState.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(r>=200&&r<=299)return this.ackRetransmissionCache.set(e.toTag,void 0),this.stateTransition(a.TransactionState.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(r>=300&&r<=699)return this.stateTransition(a.TransactionState.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case a.TransactionState.Proceeding:if(r>=100&&r<=199)return void(this.user.receiveResponse&&this.user.receiveResponse(e));if(r>=200&&r<=299)return this.ackRetransmissionCache.set(e.toTag,void 0),this.stateTransition(a.TransactionState.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(r>=300&&r<=699)return this.stateTransition(a.TransactionState.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case a.TransactionState.Accepted:if(r>=200&&r<=299){if(!this.ackRetransmissionCache.has(e.toTag))return this.ackRetransmissionCache.set(e.toTag,void 0),void(this.user.receiveResponse&&this.user.receiveResponse(e));var n=this.ackRetransmissionCache.get(e.toTag);return n?void this.send(n.toString()).catch(function(e){t.logTransportError(e,"Failed to send retransmission of ACK to 2xx response.")}):void 0}break;case a.TransactionState.Completed:if(r>=300&&r<=699)return void this.ack(e);break;case a.TransactionState.Terminated:break;default:throw new Error("Invalid state "+this.state)}var i="Received unexpected "+r+" response while in state "+this.state+".";this.logger.warn(i)},t.prototype.onTransportError=function(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(a.TransactionState.Terminated,!0)},t.prototype.typeToString=function(){return"INVITE client transaction"},t.prototype.ack=function(e){var t=this,r=this.request.ruri,n=this.request.callId,i=this.request.cseq,o=this.request.getHeader("from"),s=e.getHeader("to"),a=this.request.getHeader("via"),c=this.request.getHeader("route");if(!o)throw new Error("From undefined.");if(!s)throw new Error("To undefined.");if(!a)throw new Error("Via undefined.");var u="ACK "+r+" SIP/2.0\r\n";c&&(u+="Route: "+c+"\r\n"),u+="Via: "+a+"\r\n",u+="To: "+s+"\r\n",u+="From: "+o+"\r\n",u+="Call-ID: "+n+"\r\n",u+="CSeq: "+i+" ACK\r\n",u+="Max-Forwards: 70\r\n",u+="Content-Length: 0\r\n\r\n",this.send(u).catch(function(e){t.logTransportError(e,"Failed to send ACK to non-2xx response.")})},t.prototype.stateTransition=function(e,t){var r=this;void 0===t&&(t=!1);var n=function(){throw new Error("Invalid state transition from "+r.state+" to "+e)};switch(e){case a.TransactionState.Calling:n();break;case a.TransactionState.Proceeding:this.state!==a.TransactionState.Calling&&n();break;case a.TransactionState.Accepted:case a.TransactionState.Completed:this.state!==a.TransactionState.Calling&&this.state!==a.TransactionState.Proceeding&&n();break;case a.TransactionState.Terminated:this.state!==a.TransactionState.Calling&&this.state!==a.TransactionState.Accepted&&this.state!==a.TransactionState.Completed&&(t||n());break;default:n()}this.B&&(clearTimeout(this.B),this.B=void 0),a.TransactionState.Proceeding,e===a.TransactionState.Completed&&(this.D=setTimeout(function(){return r.timer_D()},o.Timers.TIMER_D)),e===a.TransactionState.Accepted&&(this.M=setTimeout(function(){return r.timer_M()},o.Timers.TIMER_M)),e===a.TransactionState.Terminated&&this.dispose(),this.setState(e)},t.prototype.timer_A=function(){},t.prototype.timer_B=function(){this.logger.debug("Timer B expired for INVITE client transaction "+this.id+"."),this.state===a.TransactionState.Calling&&(this.onRequestTimeout(),this.stateTransition(a.TransactionState.Terminated))},t.prototype.timer_D=function(){this.logger.debug("Timer D expired for INVITE client transaction "+this.id+"."),this.state===a.TransactionState.Completed&&this.stateTransition(a.TransactionState.Terminated)},t.prototype.timer_M=function(){this.logger.debug("Timer M expired for INVITE client transaction "+this.id+"."),this.state===a.TransactionState.Accepted&&this.stateTransition(a.TransactionState.Terminated)},t}(s.ClientTransaction);t.InviteClientTransaction=c},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}),o=this&&this.__assign||function(){return(o=Object.assign||function(e){for(var t,r=1,n=arguments.length;r=0)return t}},extraContactHeaderParams:function(e){if(e instanceof Array)return e.filter(function(e){return"string"==typeof e})},instanceId:function(e){if("string"==typeof e)return/^uuid:/i.test(e)&&(e=e.substr(5)),-1===d.Grammar.parse(e,"uuid")?void 0:e},params:function(e){if("object"==typeof e)return e},regId:function(e){if(h.Utils.isDecimal(e)){var t=Number(e);if(t>=0)return t}},registrar:function(e){if("string"==typeof e){/^sip:/i.test(e)||(e=a.C.SIP+":"+e);var t=d.Grammar.URIParse(e);return t?t.user?void 0:t:void 0}}}};for(var n in r.mandatory){if(!e.hasOwnProperty(n))throw new u.Exceptions.ConfigurationError(n);var i=e[n];if(void 0===(o=r.mandatory[n](i)))throw new u.Exceptions.ConfigurationError(n,i);t[n]=o}for(var n in r.optional)if(e.hasOwnProperty(n)){var o;if((i=e[n])instanceof Array&&0===i.length)continue;if(null===i||""===i||void 0===i||"number"==typeof i&&isNaN(i))continue;if(void 0===(o=r.optional[n](i)))throw new u.Exceptions.ConfigurationError(n,i);t[n]=o}return t}var l=function(e){function t(t,r){void 0===r&&(r={});var n=this,i=p(r);if(i.regId&&!i.instanceId?i.instanceId=h.Utils.newUUID():!i.regId&&i.instanceId&&(i.regId=1),i.params.toUri=i.params.toUri||t.configuration.uri,i.params.toDisplayName=i.params.toDisplayName||t.configuration.displayName,i.params.callId=i.params.callId||h.Utils.createRandomToken(22),i.params.cseq=i.params.cseq||Math.floor(1e4*Math.random()),!i.registrar){var o={};"object"==typeof t.configuration.uri?(o=t.configuration.uri.clone()).user=void 0:o=t.configuration.uri,i.registrar=o}for(var s in(n=e.call(this,t,a.C.REGISTER,i.registrar,i)||this).type=c.TypeStrings.RegisterContext,n.options=i,n.logger=t.getLogger("sip.registercontext"),n.logger.log("configuration parameters for RegisterContext after validation:"),i)i.hasOwnProperty(s)&&n.logger.log("\xb7 "+s+": "+JSON.stringify(i[s]));return n.expires=i.expires,n.contact=t.contact.toString(),n.registered=!1,t.on("transportCreated",function(e){e.on("disconnected",function(){return n.onTransportDisconnected()})}),n}return i(t,e),t.prototype.register=function(e){var t=this;void 0===e&&(e={}),this.options=o({},this.options,e);var r=(this.options.extraHeaders||[]).slice();r.push("Contact: "+this.generateContactHeader(this.expires)),r.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),this.closeHeaders=this.options.closeWithHeaders?(this.options.extraHeaders||[]).slice():[],this.receiveResponse=function(e){if(e.cseq===t.request.cseq){void 0!==t.registrationTimer&&(clearTimeout(t.registrationTimer),t.registrationTimer=void 0);var r=(e.statusCode||0).toString();switch(!0){case/^1[0-9]{2}$/.test(r):t.emit("progress",e);break;case/^2[0-9]{2}$/.test(r):t.emit("accepted",e);var n=void 0;e.hasHeader("expires")&&(n=Number(e.getHeader("expires"))),void 0!==t.registrationExpiredTimer&&(clearTimeout(t.registrationExpiredTimer),t.registrationExpiredTimer=void 0);var i=e.getHeaders("contact").length;if(!i){t.logger.warn("no Contact header in response to REGISTER, response ignored");break}for(var o=void 0;i--;){if((o=e.parseHeader("contact",i)).uri.user===t.ua.contact.uri.user){n=o.getParam("expires");break}o=void 0}if(!o){t.logger.warn("no Contact header pointing to us, response ignored");break}void 0===n&&(n=t.expires),t.registrationTimer=setTimeout(function(){t.registrationTimer=void 0,t.register(t.options)},1e3*n-3e3),t.registrationExpiredTimer=setTimeout(function(){t.logger.warn("registration expired"),t.registered&&t.unregistered(void 0,a.C.causes.EXPIRES)},1e3*n),o.hasParam("temp-gruu")&&(t.ua.contact.tempGruu=d.Grammar.URIParse(o.getParam("temp-gruu").replace(/"/g,""))),o.hasParam("pub-gruu")&&(t.ua.contact.pubGruu=d.Grammar.URIParse(o.getParam("pub-gruu").replace(/"/g,""))),t.registered=!0,t.emit("registered",e||void 0);break;case/^423$/.test(r):e.hasHeader("min-expires")?(t.expires=Number(e.getHeader("min-expires")),t.register(t.options)):(t.logger.warn("423 response received for REGISTER without Min-Expires"),t.registrationFailure(e,a.C.causes.SIP_FAILURE_CODE));break;default:t.registrationFailure(e,h.Utils.sipErrorCause(e.statusCode||0))}}},this.onRequestTimeout=function(){t.registrationFailure(void 0,a.C.causes.REQUEST_TIMEOUT)},this.onTransportError=function(){t.registrationFailure(void 0,a.C.causes.CONNECTION_ERROR)},this.request.cseq++,this.request.setHeader("cseq",this.request.cseq+" REGISTER"),this.request.extraHeaders=r,this.send()},t.prototype.close=function(){var e={all:!1,extraHeaders:this.closeHeaders};this.registeredBefore=this.registered,this.registered&&this.unregister(e)},t.prototype.unregister=function(e){var t=this;void 0===e&&(e={}),this.registered||e.all||this.logger.warn("Already unregistered, but sending an unregister anyways.");var r=(e.extraHeaders||[]).slice();this.registered=!1,void 0!==this.registrationTimer&&(clearTimeout(this.registrationTimer),this.registrationTimer=void 0),e.all?(r.push("Contact: *"),r.push("Expires: 0")):r.push("Contact: "+this.generateContactHeader(0)),this.receiveResponse=function(e){var r=e&&e.statusCode?e.statusCode.toString():"";switch(!0){case/^1[0-9]{2}$/.test(r):t.emit("progress",e);break;case/^2[0-9]{2}$/.test(r):t.emit("accepted",e),void 0!==t.registrationExpiredTimer&&(clearTimeout(t.registrationExpiredTimer),t.registrationExpiredTimer=void 0),t.unregistered(e);break;default:t.unregistered(e,h.Utils.sipErrorCause(e.statusCode||0))}},this.onRequestTimeout=function(){},this.request.cseq++,this.request.setHeader("cseq",this.request.cseq+" REGISTER"),this.request.extraHeaders=r,this.send()},t.prototype.unregistered=function(e,t){this.registered=!1,this.emit("unregistered",e||void 0,t||void 0)},t.prototype.send=function(){var e=this;return this.ua.userAgentCore.register(this.request,{onAccept:function(t){return e.receiveResponse(t.message)},onProgress:function(t){return e.receiveResponse(t.message)},onRedirect:function(t){return e.receiveResponse(t.message)},onReject:function(t){return e.receiveResponse(t.message)},onTrying:function(t){return e.receiveResponse(t.message)}}),this},t.prototype.registrationFailure=function(e,t){this.emit("failed",e||void 0,t||void 0)},t.prototype.onTransportDisconnected=function(){this.registeredBefore=this.registered,void 0!==this.registrationTimer&&(clearTimeout(this.registrationTimer),this.registrationTimer=void 0),void 0!==this.registrationExpiredTimer&&(clearTimeout(this.registrationExpiredTimer),this.registrationExpiredTimer=void 0),this.registered&&this.unregistered(void 0,a.C.causes.CONNECTION_ERROR)},t.prototype.generateContactHeader=function(e){void 0===e&&(e=0);var t=this.contact;return this.options.regId&&this.options.instanceId&&(t+=";reg-id="+this.options.regId,t+=';+sip.instance=""'),this.options.extraContactHeaderParams&&this.options.extraContactHeaderParams.forEach(function(e){t+=";"+e}),t+=";expires="+e},t}(s.ClientContext);t.RegisterContext=l},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(10),s=r(15),a=r(2),c=r(14),u=r(31),d=r(3),h=r(7),p=r(11),l=r(27),f=r(22),g=r(96),v=r(12),m=r(5),y=function(e){function t(r){var n=e.call(this)||this;if(n.data={},n.type=d.TypeStrings.Session,!r)throw new h.Exceptions.SessionDescriptionHandlerError("A session description handler is required for the session to function");return n.status=t.C.STATUS_NULL,n.pendingReinvite=!1,n.sessionDescriptionHandlerFactory=r,n.hasOffer=!1,n.hasAnswer=!1,n.timers={ackTimer:void 0,expiresTimer:void 0,invite2xxTimer:void 0,userNoAnswerTimer:void 0,rel1xxTimer:void 0,prackTimer:void 0},n.startTime=void 0,n.endTime=void 0,n.tones=void 0,n.localHold=!1,n.earlySdp=void 0,n.rel100=a.C.supported.UNSUPPORTED,n}return i(t,e),t.prototype.dtmf=function(e,t){var r=this;if(void 0===t&&(t={}),this.status!==d.SessionStatus.STATUS_CONFIRMED&&this.status!==d.SessionStatus.STATUS_WAITING_FOR_ACK)throw new h.Exceptions.InvalidStateError(this.status);if(!e||!e.toString().match(/^[0-9A-D#*,]+$/i))throw new TypeError("Invalid tones: "+e);var n=function(){if(r.status!==d.SessionStatus.STATUS_TERMINATED&&r.tones&&0!==r.tones.length){var e,i=r.tones.shift();","===i.tone?e=2e3:(i.on("failed",function(){r.tones=void 0}),i.send(t),e=i.duration+i.interToneGap),setTimeout(n,e)}else r.tones=void 0};e=e.toString();var i=this.ua.configuration.dtmfType;this.sessionDescriptionHandler&&i===a.C.dtmfType.RTP&&(this.sessionDescriptionHandler.sendDtmf(e,t)||(this.logger.warn("Attempt to use dtmfType 'RTP' has failed, falling back to INFO packet method"),i=a.C.dtmfType.INFO));if(i===a.C.dtmfType.INFO){for(var o=[],s=e.split("");s.length>0;)o.push(new g.DTMF(this,s.shift(),t));if(this.tones)return this.tones=this.tones.concat(o),this;this.tones=o,n()}return this},t.prototype.bye=function(e){if(void 0===e&&(e={}),this.status===d.SessionStatus.STATUS_TERMINATED)return this.logger.error("Error: Attempted to send BYE in a terminated session."),this;this.logger.log("terminating Session");var t=e.statusCode;if(t&&(t<200||t>=700))throw new TypeError("Invalid statusCode: "+t);return e.receiveResponse=function(){},this.sendRequest(a.C.BYE,e).terminated()},t.prototype.refer=function(e,t){if(void 0===t&&(t={}),this.status!==d.SessionStatus.STATUS_CONFIRMED)throw new h.Exceptions.InvalidStateError(this.status);return this.referContext=new l.ReferClientContext(this.ua,this,e,t),this.emit("referRequested",this.referContext),this.referContext.refer(t),this.referContext},t.prototype.sendRequest=function(e,t){if(void 0===t&&(t={}),!this.session)throw new Error("Session undefined.");var r;t.body&&(t.body=c.fromBodyObj(t.body));var n,i=t.receiveResponse;i&&(r={onAccept:function(e){return i(e.message)},onProgress:function(e){return i(e.message)},onRedirect:function(e){return i(e.message)},onReject:function(e){return i(e.message)},onTrying:function(e){return i(e.message)}});var o=t;switch(e){case a.C.BYE:n=this.session.bye(r,o);break;case a.C.INVITE:n=this.session.invite(r,o);break;case a.C.REFER:n=this.session.refer(r,o);break;default:throw new Error("Unexpected "+e+". Method not implemented by user agent core.")}return this.emit(e.toLowerCase(),n.message),this},t.prototype.close=function(){if(this.status===d.SessionStatus.STATUS_TERMINATED)return this;for(var e in this.logger.log("closing INVITE session "+this.id),this.sessionDescriptionHandler&&this.sessionDescriptionHandler.close(),this.timers)this.timers[e]&&clearTimeout(this.timers[e]);return this.status=d.SessionStatus.STATUS_TERMINATED,this.ua.transport&&this.ua.transport.removeListener("transportError",this.errorListener),delete this.ua.sessions[this.id],this},t.prototype.hold=function(e,t){if(void 0===e&&(e={}),void 0===t&&(t=[]),this.status!==d.SessionStatus.STATUS_WAITING_FOR_ACK&&this.status!==d.SessionStatus.STATUS_CONFIRMED)throw new h.Exceptions.InvalidStateError(this.status);this.localHold?this.logger.log("Session is already on hold, cannot put it on hold again"):(e.modifiers=t,this.sessionDescriptionHandler&&e.modifiers.push(this.sessionDescriptionHandler.holdModifier),this.localHold=!0,this.sendReinvite(e))},t.prototype.unhold=function(e,t){if(void 0===e&&(e={}),void 0===t&&(t=[]),this.status!==d.SessionStatus.STATUS_WAITING_FOR_ACK&&this.status!==d.SessionStatus.STATUS_CONFIRMED)throw new h.Exceptions.InvalidStateError(this.status);this.localHold?(e.modifiers=t,this.localHold=!1,this.sendReinvite(e)):this.logger.log("Session is not on hold, cannot unhold it")},t.prototype.reinvite=function(e,t){return void 0===e&&(e={}),void 0===t&&(t=[]),e.modifiers=t,this.sendReinvite(e)},t.prototype.terminate=function(e){return this},t.prototype.onTransportError=function(){this.status!==d.SessionStatus.STATUS_CONFIRMED&&this.status!==d.SessionStatus.STATUS_TERMINATED&&this.failed(void 0,a.C.causes.CONNECTION_ERROR)},t.prototype.onRequestTimeout=function(){this.status===d.SessionStatus.STATUS_CONFIRMED?this.terminated(void 0,a.C.causes.REQUEST_TIMEOUT):this.status!==d.SessionStatus.STATUS_TERMINATED&&(this.failed(void 0,a.C.causes.REQUEST_TIMEOUT),this.terminated(void 0,a.C.causes.REQUEST_TIMEOUT))},t.prototype.onDialogError=function(e){this.status===d.SessionStatus.STATUS_CONFIRMED?this.terminated(e,a.C.causes.DIALOG_ERROR):this.status!==d.SessionStatus.STATUS_TERMINATED&&(this.failed(e,a.C.causes.DIALOG_ERROR),this.terminated(e,a.C.causes.DIALOG_ERROR))},t.prototype.on=function(t,r){return e.prototype.on.call(this,t,r)},t.prototype.onAck=function(e){var t=this,r=function(){clearTimeout(t.timers.ackTimer),clearTimeout(t.timers.invite2xxTimer),t.status=d.SessionStatus.STATUS_CONFIRMED;var r=e.message.getHeader("Content-Disposition");r&&"render"===r.type&&(t.renderbody=e.message.body,t.rendertype=e.message.getHeader("Content-Type")),t.emit("confirmed",e.message)};this.status===d.SessionStatus.STATUS_WAITING_FOR_ACK&&(this.sessionDescriptionHandler&&this.sessionDescriptionHandler.hasDescription(e.message.getHeader("Content-Type")||"")?(this.hasAnswer=!0,this.sessionDescriptionHandler.setDescription(e.message.body,this.sessionDescriptionHandlerOptions,this.modifiers).catch(function(r){throw t.logger.warn(r),t.terminate({statusCode:"488",reasonPhrase:"Bad Media Description"}),t.failed(e.message,a.C.causes.BAD_MEDIA_DESCRIPTION),t.terminated(e.message,a.C.causes.BAD_MEDIA_DESCRIPTION),r}).then(function(){return r()})):r())},t.prototype.receiveRequest=function(e){switch(e.message.method){case a.C.BYE:e.accept(),this.status===d.SessionStatus.STATUS_CONFIRMED&&(this.emit("bye",e.message),this.terminated(e.message,a.C.BYE));break;case a.C.INVITE:this.status===d.SessionStatus.STATUS_CONFIRMED&&(this.logger.log("re-INVITE received"),this.receiveReinvite(e));break;case a.C.INFO:if(this.status===d.SessionStatus.STATUS_CONFIRMED||this.status===d.SessionStatus.STATUS_WAITING_FOR_ACK){if(this.onInfo)return this.onInfo(e.message);var t=e.message.getHeader("content-type");if(t)if(t.match(/^application\/dtmf-relay/i)){if(e.message.body){var r=e.message.body.split("\r\n",2);if(2===r.length){var n=void 0,i=void 0,o=/^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/;o.test(r[0])&&(n=r[0].replace(o,"$2"));var s=/^(Duration\s?=\s?)([0-9]{1,4})(\s)?.*/;s.test(r[1])&&(i=parseInt(r[1].replace(s,"$2"),10)),n&&i&&new g.DTMF(this,n,{duration:i}).init_incoming(e)}}}else e.reject({statusCode:415,extraHeaders:["Accept: application/dtmf-relay"]})}break;case a.C.REFER:if(this.status===d.SessionStatus.STATUS_CONFIRMED)if(this.logger.log("REFER received"),this.referContext=new l.ReferServerContext(this.ua,e,this.session),this.listeners("referRequested").length)this.emit("referRequested",this.referContext);else{this.logger.log("No referRequested listeners, automatically accepting and following the refer");var c={followRefer:!0};this.passedOptions&&(c.inviteOptions=this.passedOptions),this.referContext.accept(c,this.modifiers)}break;case a.C.NOTIFY:if(this.referContext&&this.referContext.type===d.TypeStrings.ReferClientContext&&e.message.hasHeader("event")&&/^refer(;.*)?$/.test(e.message.getHeader("event")))return void this.referContext.receiveNotify(e);e.accept(),this.emit("notify",e.message)}},t.prototype.receiveReinvite=function(e){var t,r=this;if(this.emit("reinvite",this,e.message),e.message.hasHeader("P-Asserted-Identity")&&(this.assertedIdentity=p.Grammar.nameAddrHeaderParse(e.message.getHeader("P-Asserted-Identity"))),this.sessionDescriptionHandler){if("0"!==e.message.getHeader("Content-Length")||e.message.getHeader("Content-Type")){if(!this.sessionDescriptionHandler.hasDescription(e.message.getHeader("Content-Type")||""))return e.reject({statusCode:415}),void this.emit("reinviteFailed",this);t=this.sessionDescriptionHandler.setDescription(e.message.body,this.sessionDescriptionHandlerOptions,this.modifiers).then(this.sessionDescriptionHandler.getDescription.bind(this.sessionDescriptionHandler,this.sessionDescriptionHandlerOptions,this.modifiers))}else t=this.sessionDescriptionHandler.getDescription(this.sessionDescriptionHandlerOptions,this.modifiers);t.catch(function(t){var n;throw t.type===d.TypeStrings.SessionDescriptionHandlerError?n=500:t.type===d.TypeStrings.RenegotiationError?(r.emit("renegotiationError",t),r.logger.warn(t.toString()),n=488):(r.logger.error(t),n=488),e.reject({statusCode:n}),r.emit("reinviteFailed",r),t}).then(function(t){var n=["Contact: "+r.contact];e.accept({statusCode:200,extraHeaders:n,body:c.fromBodyObj(t)}),r.status=d.SessionStatus.STATUS_WAITING_FOR_ACK,r.emit("reinviteAccepted",r)})}else this.logger.warn("No SessionDescriptionHandler to reinvite")},t.prototype.sendReinvite=function(e){var t=this;if(void 0===e&&(e={}),this.pendingReinvite)this.logger.warn("Reinvite in progress. Please wait until complete, then try again.");else if(this.sessionDescriptionHandler){this.pendingReinvite=!0,e.modifiers=e.modifiers||[];var r=(e.extraHeaders||[]).slice();r.push("Contact: "+this.contact),r.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),this.sessionDescriptionHandler.getDescription(e.sessionDescriptionHandlerOptions,e.modifiers).then(function(e){if(!t.session)throw new Error("Session undefined.");var n={onAccept:function(e){if(t.status!==d.SessionStatus.STATUS_TERMINATED)if(t.pendingReinvite){if(t.status=d.SessionStatus.STATUS_CONFIRMED,t.emit("ack",e.ack()),t.pendingReinvite=!1,clearTimeout(t.timers.invite2xxTimer),!t.sessionDescriptionHandler||!t.sessionDescriptionHandler.hasDescription(e.message.getHeader("Content-Type")||""))return t.logger.error("2XX response received to re-invite but did not have a description"),t.emit("reinviteFailed",t),void t.emit("renegotiationError",new h.Exceptions.RenegotiationError("2XX response received to re-invite but did not have a description"));t.sessionDescriptionHandler.setDescription(e.message.body,t.sessionDescriptionHandlerOptions,t.modifiers).catch(function(e){throw t.logger.error("Could not set the description in 2XX response"),t.logger.error(e),t.emit("reinviteFailed",t),t.emit("renegotiationError",e),t.sendRequest(a.C.BYE,{extraHeaders:["Reason: "+m.Utils.getReasonHeaderValue(488,"Not Acceptable Here")]}),t.terminated(void 0,a.C.causes.INCOMPATIBLE_SDP),e}).then(function(){t.emit("reinviteAccepted",t)})}else t.logger.error("Received reinvite response, but have no pending reinvite");else t.logger.error("Received reinvite response, but in STATUS_TERMINATED")},onProgress:function(e){},onRedirect:function(e){t.pendingReinvite=!1,t.logger.log("Received a non 1XX or 2XX response to a re-invite"),t.emit("reinviteFailed",t),t.emit("renegotiationError",new h.Exceptions.RenegotiationError("Invalid response to a re-invite"))},onReject:function(e){t.pendingReinvite=!1,t.logger.log("Received a non 1XX or 2XX response to a re-invite"),t.emit("reinviteFailed",t),t.emit("renegotiationError",new h.Exceptions.RenegotiationError("Invalid response to a re-invite"))},onTrying:function(e){}},i={extraHeaders:r,body:c.fromBodyObj(e)};t.session.invite(n,i)}).catch(function(e){if(e.type===d.TypeStrings.RenegotiationError)throw t.pendingReinvite=!1,t.emit("renegotiationError",e),t.logger.warn("Renegotiation Error"),t.logger.warn(e.toString()),e;throw t.logger.error("sessionDescriptionHandler error"),t.logger.error(e),e})}else this.logger.warn("No SessionDescriptionHandler, can't reinvite..")},t.prototype.failed=function(e,t){return this.status===d.SessionStatus.STATUS_TERMINATED?this:(this.emit("failed",e,t),this)},t.prototype.rejected=function(e,t){return this.emit("rejected",e,t),this},t.prototype.canceled=function(){return this.sessionDescriptionHandler&&this.sessionDescriptionHandler.close(),this.emit("cancel"),this},t.prototype.accepted=function(e,t){return e instanceof String||(t=m.Utils.getReasonPhrase(e&&e.statusCode||0,t)),this.startTime=new Date,this.replacee&&(this.replacee.emit("replaced",this),this.replacee.terminate()),this.emit("accepted",e,t),this},t.prototype.terminated=function(e,t){return this.status===d.SessionStatus.STATUS_TERMINATED?this:(this.endTime=new Date,this.close(),this.emit("terminated",e,t),this)},t.prototype.connecting=function(e){return this.emit("connecting",{request:e}),this},t.C=d.SessionStatus,t}(o.EventEmitter);t.Session=y;var S=function(e){function t(t,r){var n=this;if(!t.configuration.sessionDescriptionHandlerFactory)throw t.logger.warn("Can't build ISC without SDH Factory"),new Error("ISC Constructor Failed");(n=e.call(this,t.configuration.sessionDescriptionHandlerFactory)||this)._canceled=!1,n.rseq=Math.floor(1e4*Math.random()),n.incomingRequest=r;var i=r.message;f.ServerContext.initializer(n,t,r),n.type=d.TypeStrings.InviteServerContext;var o=i.parseHeader("Content-Disposition");o&&"render"===o.type&&(n.renderbody=i.body,n.rendertype=i.getHeader("Content-Type")),n.status=d.SessionStatus.STATUS_INVITE_RECEIVED,n.fromTag=i.fromTag,n.id=i.callId+n.fromTag,n.request=i,n.contact=n.ua.contact.toString(),n.logger=t.getLogger("sip.inviteservercontext",n.id),n.ua.sessions[n.id]=n;var s=function(e,t){i.hasHeader(e)&&i.getHeader(e).toLowerCase().indexOf("100rel")>=0&&(n.rel100=t)};if(s("require",a.C.supported.REQUIRED),s("supported",a.C.supported.SUPPORTED),n.request.toTag=r.toTag,n.status=d.SessionStatus.STATUS_WAITING_FOR_ANSWER,n.timers.userNoAnswerTimer=setTimeout(function(){r.reject({statusCode:408}),n.failed(i,a.C.causes.NO_ANSWER),n.terminated(i,a.C.causes.NO_ANSWER)},n.ua.configuration.noAnswerTimeout||60),i.hasHeader("expires")){var c=1e3*Number(i.getHeader("expires")||0);n.timers.expiresTimer=setTimeout(function(){n.status===d.SessionStatus.STATUS_WAITING_FOR_ANSWER&&(r.reject({statusCode:487}),n.failed(i,a.C.causes.EXPIRES),n.terminated(i,a.C.causes.EXPIRES))},c)}return n.errorListener=n.onTransportError.bind(n),t.transport&&t.transport.on("transportError",n.errorListener),n}return i(t,e),Object.defineProperty(t.prototype,"autoSendAnInitialProvisionalResponse",{get:function(){return this.rel100!==a.C.supported.REQUIRED},enumerable:!0,configurable:!0}),t.prototype.reply=function(e){return void 0===e&&(e={}),this},t.prototype.reject=function(e){var t=this;if(void 0===e&&(e={}),this.status===d.SessionStatus.STATUS_TERMINATED)throw new h.Exceptions.InvalidStateError(this.status);this.logger.log("rejecting RTCSession");var r=e.statusCode||480,n=m.Utils.getReasonPhrase(r,e.reasonPhrase),i=e.extraHeaders||[];if(r<300||r>699)throw new TypeError("Invalid statusCode: "+r);var o=e.body?c.fromBodyLegacy(e.body):void 0,s=r<400?this.incomingRequest.redirect([],{statusCode:r,reasonPhrase:n,extraHeaders:i,body:o}):this.incomingRequest.reject({statusCode:r,reasonPhrase:n,extraHeaders:i,body:o});return["rejected","failed"].forEach(function(e){t.emit(e,s.message,n)}),this.terminated()},t.prototype.accept=function(e){var t=this;return void 0===e&&(e={}),this._accept(e).then(function(e){var r=e.message,n=e.session;n.delegate={onAck:function(e){return t.onAck(e)},onAckTimeout:function(){return t.onAckTimeout()},onBye:function(e){return t.receiveRequest(e)},onInfo:function(e){return t.receiveRequest(e)},onInvite:function(e){return t.receiveRequest(e)},onNotify:function(e){return t.receiveRequest(e)},onPrack:function(e){return t.receiveRequest(e)},onRefer:function(e){return t.receiveRequest(e)}},t.session=n,t.status=d.SessionStatus.STATUS_WAITING_FOR_ACK,t.accepted(r,m.Utils.getReasonPhrase(200))}).catch(function(e){if(t.onContextError(e),!t._canceled)throw e}),this},t.prototype.progress=function(e){var t=this;void 0===e&&(e={});var r=e.statusCode||180;if(r<100||r>199)throw new TypeError("Invalid statusCode: "+r);if(this.status===d.SessionStatus.STATUS_TERMINATED)return this.logger.warn("Unexpected call for progress while terminated, ignoring"),this;if(this.status===d.SessionStatus.STATUS_ANSWERED)return this.logger.warn("Unexpected call for progress while answered, ignoring"),this;if(this.status===d.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK)return this.logger.warn("Unexpected call for progress while answered (waiting for prack), ignoring"),this;if(this.status===d.SessionStatus.STATUS_WAITING_FOR_PRACK)return this.logger.warn("Unexpected call for progress while waiting for prack, ignoring"),this;if(100===e.statusCode){try{this.incomingRequest.trying()}catch(e){if(this.onContextError(e),!this._canceled)throw e}return this}return this.rel100===a.C.supported.REQUIRED||this.rel100===a.C.supported.SUPPORTED&&e.rel100||this.rel100===a.C.supported.SUPPORTED&&this.ua.configuration.rel100===a.C.supported.REQUIRED?(this._reliableProgressWaitForPrack(e).catch(function(e){if(t.onContextError(e),!t._canceled)throw e}),this):(this._progress(e).catch(function(e){if(t.onContextError(e),!t._canceled)throw e}),this)},t.prototype.terminate=function(e){var t=this;if(void 0===e&&(e={}),!this.session)return this.reject(e),this;switch(this.session.sessionState){case u.SessionState.Initial:case u.SessionState.Early:return this.reject(e),this;case u.SessionState.AckWait:return this.session.delegate={onAck:function(){t.sendRequest(a.C.BYE,e)},onAckTimeout:function(){t.sendRequest(a.C.BYE,e)}},this.emit("bye",this.request),this.terminated(),this;case u.SessionState.Confirmed:return this.bye(e),this;case u.SessionState.Terminated:default:return this}},t.prototype.onCancel=function(e){this.status!==d.SessionStatus.STATUS_WAITING_FOR_ANSWER&&this.status!==d.SessionStatus.STATUS_WAITING_FOR_PRACK&&this.status!==d.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK&&this.status!==d.SessionStatus.STATUS_EARLY_MEDIA&&this.status!==d.SessionStatus.STATUS_ANSWERED||(this.status=d.SessionStatus.STATUS_CANCELED,this.incomingRequest.reject({statusCode:487}),this.canceled(),this.rejected(e,a.C.causes.CANCELED),this.failed(e,a.C.causes.CANCELED),this.terminated(e,a.C.causes.CANCELED))},t.prototype.receiveRequest=function(t){var r=this;switch(t.message.method){case a.C.PRACK:this.status===d.SessionStatus.STATUS_WAITING_FOR_PRACK||this.status===d.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK?this.hasAnswer?(clearTimeout(this.timers.rel1xxTimer),clearTimeout(this.timers.prackTimer),t.accept(),this.status===d.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK&&(this.status=d.SessionStatus.STATUS_EARLY_MEDIA,this.accept()),this.status=d.SessionStatus.STATUS_EARLY_MEDIA):(this.sessionDescriptionHandler=this.setupSessionDescriptionHandler(),this.emit("SessionDescriptionHandler-created",this.sessionDescriptionHandler),this.sessionDescriptionHandler.hasDescription(t.message.getHeader("Content-Type")||"")?(this.hasAnswer=!0,this.sessionDescriptionHandler.setDescription(t.message.body,this.sessionDescriptionHandlerOptions,this.modifiers).then(function(){clearTimeout(r.timers.rel1xxTimer),clearTimeout(r.timers.prackTimer),t.accept(),r.status===d.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK&&(r.status=d.SessionStatus.STATUS_EARLY_MEDIA,r.accept()),r.status=d.SessionStatus.STATUS_EARLY_MEDIA},function(e){r.logger.warn(e),r.terminate({statusCode:"488",reasonPhrase:"Bad Media Description"}),r.failed(t.message,a.C.causes.BAD_MEDIA_DESCRIPTION),r.terminated(t.message,a.C.causes.BAD_MEDIA_DESCRIPTION)})):(this.terminate({statusCode:"488",reasonPhrase:"Bad Media Description"}),this.failed(t.message,a.C.causes.BAD_MEDIA_DESCRIPTION),this.terminated(t.message,a.C.causes.BAD_MEDIA_DESCRIPTION))):this.status===d.SessionStatus.STATUS_EARLY_MEDIA&&t.accept();break;default:e.prototype.receiveRequest.call(this,t)}},t.prototype.setupSessionDescriptionHandler=function(){return this.sessionDescriptionHandler?this.sessionDescriptionHandler:this.sessionDescriptionHandlerFactory(this,this.ua.configuration.sessionDescriptionHandlerFactoryOptions)},t.prototype.generateResponseOfferAnswer=function(e){if(!this.session){var t=c.getBody(this.incomingRequest.message);return t&&"session"===t.contentDisposition?this.setOfferAndGetAnswer(t,e):this.getOffer(e)}switch(this.session.signalingState){case u.SignalingState.Initial:return this.getOffer(e);case u.SignalingState.Stable:case u.SignalingState.HaveLocalOffer:return Promise.resolve(void 0);case u.SignalingState.HaveRemoteOffer:if(!this.session.offer)throw new Error("Session offer undefined");return this.setOfferAndGetAnswer(this.session.offer,e);case u.SignalingState.Closed:default:throw new Error("Invalid signaling state "+this.session.signalingState+".")}},t.prototype.handlePrackOfferAnswer=function(e,t){if(!this.session)throw new Error("Session undefined.");var r=c.getBody(e.message);if(!r||"session"!==r.contentDisposition)return Promise.resolve(void 0);switch(this.session.signalingState){case u.SignalingState.Initial:throw new Error("Invalid signaling state "+this.session.signalingState+".");case u.SignalingState.Stable:return this.setAnswer(r,t).then(function(){});case u.SignalingState.HaveLocalOffer:throw new Error("Invalid signaling state "+this.session.signalingState+".");case u.SignalingState.HaveRemoteOffer:return this.setOfferAndGetAnswer(r,t);case u.SignalingState.Closed:default:throw new Error("Invalid signaling state "+this.session.signalingState+".")}},t.prototype.canceled=function(){return this._canceled=!0,e.prototype.canceled.call(this)},t.prototype.terminated=function(t,r){return this.prackNeverArrived(),e.prototype.terminated.call(this,t,r)},t.prototype._accept=function(e){var t=this;return void 0===e&&(e={}),this.onInfo=e.onInfo,this.status===d.SessionStatus.STATUS_WAITING_FOR_PRACK?(this.status=d.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK,this.waitForArrivalOfPrack().then(function(){t.status=d.SessionStatus.STATUS_ANSWERED,clearTimeout(t.timers.userNoAnswerTimer)}).then(function(){return t.generateResponseOfferAnswer(e)}).then(function(e){return t.incomingRequest.accept({statusCode:200,body:e})})):this.status!==d.SessionStatus.STATUS_WAITING_FOR_ANSWER?Promise.reject(new h.Exceptions.InvalidStateError(this.status)):(this.status=d.SessionStatus.STATUS_ANSWERED,this.status=d.SessionStatus.STATUS_ANSWERED,clearTimeout(this.timers.userNoAnswerTimer),this.generateResponseOfferAnswer(e).then(function(e){return t.incomingRequest.accept({statusCode:200,body:e})}))},t.prototype._progress=function(e){void 0===e&&(e={});var t=e.statusCode||180,r=e.reasonPhrase,n=(e.extraHeaders||[]).slice(),i=e.body?c.fromBodyLegacy(e.body):void 0;try{var o=this.incomingRequest.progress({statusCode:t,reasonPhrase:r,extraHeaders:n,body:i});return this.emit("progress",o.message,r),this.session=o.session,Promise.resolve(o)}catch(e){return Promise.reject(e)}},t.prototype._reliableProgress=function(e){var t=this;void 0===e&&(e={});var r=e.statusCode||183,n=e.reasonPhrase,i=(e.extraHeaders||[]).slice();return i.push("Require: 100rel"),i.push("RSeq: "+Math.floor(1e4*Math.random())),this.generateResponseOfferAnswer(e).then(function(e){return t.incomingRequest.progress({statusCode:r,reasonPhrase:n,extraHeaders:i,body:e})}).then(function(e){return t.emit("progress",e.message,n),t.session=e.session,e})},t.prototype._reliableProgressWaitForPrack=function(e){var t=this;void 0===e&&(e={});var r,n=e.statusCode||183,i=e.reasonPhrase,o=(e.extraHeaders||[]).slice();return o.push("Require: 100rel"),o.push("RSeq: "+this.rseq++),this.status=d.SessionStatus.STATUS_WAITING_FOR_PRACK,new Promise(function(s,c){var u=!0;return t.generateResponseOfferAnswer(e).then(function(e){return r=e,t.incomingRequest.progress({statusCode:n,reasonPhrase:i,extraHeaders:o,body:r})}).then(function(p){var l,f;t.emit("progress",p.message,i),t.session=p.session,p.session.delegate={onPrack:function(r){l=r,clearTimeout(g),clearTimeout(S),u&&(u=!1,t.handlePrackOfferAnswer(l,e).then(function(e){try{f=l.accept({statusCode:200,body:e}),t.status===d.SessionStatus.STATUS_WAITING_FOR_PRACK&&(t.status=d.SessionStatus.STATUS_WAITING_FOR_ANSWER),t.prackArrived(),s({prackRequest:l,prackResponse:f,progressResponse:p})}catch(e){c(e)}}))}};var g=setTimeout(function(){if(u){u=!1,t.logger.warn("No PRACK received, rejecting INVITE."),clearTimeout(S);try{t.incomingRequest.reject({statusCode:504}),t.terminated(void 0,a.C.causes.NO_PRACK),c(new h.Exceptions.TerminatedSessionError)}catch(e){c(e)}}},64*v.Timers.T1),m=function(){try{t.incomingRequest.progress({statusCode:n,reasonPhrase:i,extraHeaders:o,body:r})}catch(e){return u=!1,void c(e)}S=setTimeout(m,y*=2)},y=v.Timers.T1,S=setTimeout(m,y)})})},t.prototype.onAckTimeout=function(){if(this.status===d.SessionStatus.STATUS_WAITING_FOR_ACK){if(this.logger.log("no ACK received for an extended period of time, terminating the call"),!this.session)throw new Error("Session undefined.");this.session.bye(),this.terminated(void 0,a.C.causes.NO_ACK)}},t.prototype.onContextError=function(e){var t=480;e instanceof h.Exception?e instanceof h.Exceptions.SessionDescriptionHandlerError?(this.logger.error(e.message),e.error&&this.logger.error(e.error)):e instanceof h.Exceptions.TerminatedSessionError?this.logger.warn("Incoming session terminated while waiting for PRACK."):e instanceof h.Exceptions.UnsupportedSessionDescriptionContentTypeError?t=415:e instanceof h.Exception&&this.logger.error(e.message):e instanceof Error?this.logger.error(e.message):(this.logger.error("An error occurred in the session description handler."),this.logger.error(e));try{this.incomingRequest.reject({statusCode:t}),this.failed(this.incomingRequest.message,e.message),this.terminated(this.incomingRequest.message,e.message)}catch(e){return}},t.prototype.prackArrived=function(){this.waitingForPrackResolve&&this.waitingForPrackResolve(),this.waitingForPrackPromise=void 0,this.waitingForPrackResolve=void 0,this.waitingForPrackReject=void 0},t.prototype.prackNeverArrived=function(){this.waitingForPrackReject&&this.waitingForPrackReject(new h.Exceptions.TerminatedSessionError),this.waitingForPrackPromise=void 0,this.waitingForPrackResolve=void 0,this.waitingForPrackReject=void 0},t.prototype.waitForArrivalOfPrack=function(){var e=this;if(this.waitingForPrackPromise)throw new Error("Already waiting for PRACK");return this.waitingForPrackPromise=new Promise(function(t,r){e.waitingForPrackResolve=t,e.waitingForPrackReject=r}),this.waitingForPrackPromise},t.prototype.getOffer=function(e){return this.hasOffer=!0,this.getSessionDescriptionHandler().getDescription(e.sessionDescriptionHandlerOptions,e.modifiers).then(function(e){return c.fromBodyObj(e)})},t.prototype.setAnswer=function(e,t){this.hasAnswer=!0;var r=this.getSessionDescriptionHandler();return r.hasDescription(e.contentType)?r.setDescription(e.content,t.sessionDescriptionHandlerOptions,t.modifiers):Promise.reject(new h.Exceptions.UnsupportedSessionDescriptionContentTypeError)},t.prototype.setOfferAndGetAnswer=function(e,t){this.hasOffer=!0,this.hasAnswer=!0;var r=this.getSessionDescriptionHandler();return r.hasDescription(e.contentType)?r.setDescription(e.content,t.sessionDescriptionHandlerOptions,t.modifiers).then(function(){return r.getDescription(t.sessionDescriptionHandlerOptions,t.modifiers)}).then(function(e){return c.fromBodyObj(e)}):Promise.reject(new h.Exceptions.UnsupportedSessionDescriptionContentTypeError)},t.prototype.getSessionDescriptionHandler=function(){var e=this.sessionDescriptionHandler=this.setupSessionDescriptionHandler();return this.emit("SessionDescriptionHandler-created",this.sessionDescriptionHandler),e},t}(y);t.InviteServerContext=S;var T=function(e){function t(t,r,n,i){void 0===n&&(n={}),void 0===i&&(i=[]);var o=this;if(!t.configuration.sessionDescriptionHandlerFactory)throw t.logger.warn("Can't build ISC without SDH Factory"),new Error("ICC Constructor Failed");n.params=n.params||{};var c=n.anonymous||!1,u=m.Utils.newTag();n.params.fromTag=u;var p=t.contact.toString({anonymous:c,outbound:c?!t.contact.tempGruu:!t.contact.pubGruu}),l=(n.extraHeaders||[]).slice();if(c&&t.configuration.uri&&(n.params.from_displayName="Anonymous",n.params.from_uri="sip:anonymous@anonymous.invalid",l.push("P-Preferred-Identity: "+t.configuration.uri.toString()),l.push("Privacy: id")),l.push("Contact: "+p),l.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),t.configuration.rel100===a.C.supported.REQUIRED&&l.push("Require: 100rel"),t.configuration.replaces===a.C.supported.REQUIRED&&l.push("Require: replaces"),n.extraHeaders=l,o=e.call(this,t.configuration.sessionDescriptionHandlerFactory)||this,s.ClientContext.initializer(o,t,a.C.INVITE,r,n),o.earlyMediaSessionDescriptionHandlers=new Map,o.type=d.TypeStrings.InviteClientContext,o.passedOptions=n,o.sessionDescriptionHandlerOptions=n.sessionDescriptionHandlerOptions||{},o.modifiers=i,o.inviteWithoutSdp=n.inviteWithoutSdp||!1,o.anonymous=n.anonymous||!1,o.renderbody=n.renderbody||void 0,o.rendertype=n.rendertype||"text/plain",o.fromTag=u,o.contact=p,o.status!==d.SessionStatus.STATUS_NULL)throw new h.Exceptions.InvalidStateError(o.status);return o.isCanceled=!1,o.received100=!1,o.method=a.C.INVITE,o.logger=t.getLogger("sip.inviteclientcontext"),t.applicants[o.toString()]=o,o.id=o.request.callId+o.fromTag,o.onInfo=n.onInfo,o.errorListener=o.onTransportError.bind(o),t.transport&&t.transport.on("transportError",o.errorListener),o}return i(t,e),t.prototype.receiveResponse=function(e){throw new Error("Unimplemented.")},t.prototype.send=function(){return this.sendInvite(),this},t.prototype.invite=function(){var e=this;return this.ua.sessions[this.id]=this,Promise.resolve().then(function(){e.isCanceled||e.status===d.SessionStatus.STATUS_TERMINATED||(e.inviteWithoutSdp?(e.request.body=e.renderbody,e.status=d.SessionStatus.STATUS_INVITE_SENT,e.send()):(e.sessionDescriptionHandler=e.sessionDescriptionHandlerFactory(e,e.ua.configuration.sessionDescriptionHandlerFactoryOptions||{}),e.emit("SessionDescriptionHandler-created",e.sessionDescriptionHandler),e.sessionDescriptionHandler.getDescription(e.sessionDescriptionHandlerOptions,e.modifiers).then(function(t){e.isCanceled||e.status===d.SessionStatus.STATUS_TERMINATED||(e.hasOffer=!0,e.request.body=t,e.status=d.SessionStatus.STATUS_INVITE_SENT,e.send())},function(t){t.type===d.TypeStrings.SessionDescriptionHandlerError&&(e.logger.log(t.message),t.error&&e.logger.log(t.error)),e.status!==d.SessionStatus.STATUS_TERMINATED&&(e.failed(void 0,a.C.causes.WEBRTC_ERROR),e.terminated(void 0,a.C.causes.WEBRTC_ERROR))})))}),this},t.prototype.cancel=function(e){if(void 0===e&&(e={}),this.status===d.SessionStatus.STATUS_TERMINATED||this.status===d.SessionStatus.STATUS_CONFIRMED)throw new h.Exceptions.InvalidStateError(this.status);if(this.isCanceled)throw new h.Exceptions.InvalidStateError(d.SessionStatus.STATUS_CANCELED);this.isCanceled=!0,this.logger.log("Canceling session");var t=m.Utils.getCancelReason(e.statusCode,e.reasonPhrase);return e.extraHeaders=(e.extraHeaders||[]).slice(),this.outgoingInviteRequest&&(this.logger.warn("Canceling session before it was created"),this.outgoingInviteRequest.cancel(t,e)),this.canceled()},t.prototype.terminate=function(e){return this.status===d.SessionStatus.STATUS_TERMINATED?this:(this.status===d.SessionStatus.STATUS_WAITING_FOR_ACK||this.status===d.SessionStatus.STATUS_CONFIRMED?this.bye(e):this.cancel(e),this)},t.prototype.sendInvite=function(){var e=this;this.outgoingInviteRequest=this.ua.userAgentCore.invite(this.request,{onAccept:function(t){return e.onAccept(t)},onProgress:function(t){return e.onProgress(t)},onRedirect:function(t){return e.onRedirect(t)},onReject:function(t){return e.onReject(t)},onTrying:function(t){return e.onTrying(t)}})},t.prototype.ackAndBye=function(e,t,r,n){if(!this.ua.userAgentCore)throw new Error("Method requires user agent core.");var i=[];r&&i.push("Reason: "+m.Utils.getReasonHeaderValue(r,n));var o=e.ack();this.emit("ack",o.message);var s=t.bye(void 0,{extraHeaders:i});this.emit("bye",s.message)},t.prototype.disposeEarlyMedia=function(){if(!this.earlyMediaSessionDescriptionHandlers)throw new Error("Early media session description handlers undefined.");this.earlyMediaSessionDescriptionHandlers.forEach(function(e){e.close()})},t.prototype.onAccept=function(e){var t=this;if(!this.earlyMediaSessionDescriptionHandlers)throw new Error("Early media session description handlers undefined.");var r=e.message,n=e.session;if(this.session)this.ackAndBye(e,n);else{if(this.isCanceled)return this.ackAndBye(e,n),void this.emit("bye",this.request);switch(r.hasHeader("P-Asserted-Identity")&&(this.assertedIdentity=p.Grammar.nameAddrHeaderParse(r.getHeader("P-Asserted-Identity"))),this.session=n,this.session.delegate={onAck:function(e){return t.onAck(e)},onBye:function(e){return t.receiveRequest(e)},onInfo:function(e){return t.receiveRequest(e)},onInvite:function(e){return t.receiveRequest(e)},onNotify:function(e){return t.receiveRequest(e)},onPrack:function(e){return t.receiveRequest(e)},onRefer:function(e){return t.receiveRequest(e)}},n.signalingState){case u.SignalingState.Initial:case u.SignalingState.HaveLocalOffer:this.ackAndBye(e,n,400,"Missing session description"),this.failed(r,a.C.causes.BAD_MEDIA_DESCRIPTION);break;case u.SignalingState.HaveRemoteOffer:var i=this.sessionDescriptionHandlerFactory(this,this.ua.configuration.sessionDescriptionHandlerFactoryOptions||{});if(this.sessionDescriptionHandler=i,this.emit("SessionDescriptionHandler-created",this.sessionDescriptionHandler),!i.hasDescription(r.getHeader("Content-Type")||"")){this.ackAndBye(e,n,400,"Missing session description"),this.failed(r,a.C.causes.BAD_MEDIA_DESCRIPTION);break}this.hasOffer=!0,i.setDescription(r.body,this.sessionDescriptionHandlerOptions,this.modifiers).then(function(){return i.getDescription(t.sessionDescriptionHandlerOptions,t.modifiers)}).then(function(n){if(!t.isCanceled&&t.status!==d.SessionStatus.STATUS_TERMINATED){t.status=d.SessionStatus.STATUS_CONFIRMED,t.hasAnswer=!0;var i={contentDisposition:"session",contentType:n.contentType,content:n.body},o=e.ack({body:i});t.emit("ack",o.message),t.accepted(r)}}).catch(function(i){if(i.type!==d.TypeStrings.SessionDescriptionHandlerError)throw i;t.logger.warn("invalid description"),t.logger.warn(i.toString()),t.ackAndBye(e,n,488,"Invalid session description"),t.failed(r,a.C.causes.BAD_MEDIA_DESCRIPTION)});break;case u.SignalingState.Stable:var o;if(this.renderbody&&this.rendertype&&(o={body:{contentDisposition:"render",contentType:this.rendertype,content:this.renderbody}}),this.hasOffer&&!this.hasAnswer){if(!this.sessionDescriptionHandler)throw new Error("Session description handler undefined.");var s=n.answer;if(!s)throw new Error("Answer is undefined.");this.sessionDescriptionHandler.setDescription(s.content,this.sessionDescriptionHandlerOptions,this.modifiers).then(function(){t.hasAnswer=!0,t.status=d.SessionStatus.STATUS_CONFIRMED;var n=e.ack(o);t.emit("ack",n.message),t.accepted(r)}).catch(function(i){t.logger.error(i),t.ackAndBye(e,n,488,"Not Acceptable Here"),t.failed(r,a.C.causes.BAD_MEDIA_DESCRIPTION)})}else{if(this.sessionDescriptionHandler=this.earlyMediaSessionDescriptionHandlers.get(n.id),!this.sessionDescriptionHandler)throw new Error("Session description handler undefined.");this.earlyMediaSessionDescriptionHandlers.delete(n.id),this.hasOffer=!0,this.hasAnswer=!0,this.status=d.SessionStatus.STATUS_CONFIRMED;var c=e.ack();this.emit("ack",c.message),this.accepted(r)}break;case u.SignalingState.Closed:break;default:throw new Error("Unknown session signaling state.")}this.disposeEarlyMedia()}},t.prototype.onProgress=function(e){var t=this;if(!this.isCanceled){if(!this.outgoingInviteRequest)throw new Error("Outgoing INVITE request undefined.");if(!this.earlyMediaSessionDescriptionHandlers)throw new Error("Early media session description handlers undefined.");var r=e.message,n=e.session;if(this.status=d.SessionStatus.STATUS_1XX_RECEIVED,r.hasHeader("P-Asserted-Identity")&&(this.assertedIdentity=p.Grammar.nameAddrHeaderParse(r.getHeader("P-Asserted-Identity"))),!n)throw new Error("Session undefined.");var i=r.getHeader("require"),o=r.getHeader("rseq"),s=!!(i&&i.includes("100rel")&&o?Number(o):void 0),c=[];if(s&&c.push("RAck: "+r.getHeader("rseq")+" "+r.getHeader("cseq")),n.signalingState===u.SignalingState.Initial)return s&&(this.logger.warn("First reliable provisional response received MUST contain an offer when INVITE does not contain an offer."),e.prack({extraHeaders:c})),void this.emit("progress",r);if(n.signalingState===u.SignalingState.HaveLocalOffer)return s&&e.prack({extraHeaders:c}),void this.emit("progress",r);if(n.signalingState===u.SignalingState.HaveRemoteOffer){if(!s)return void this.logger.warn("Non-reliable provisional response MUST NOT contain an initial offer, discarding response.");var h=this.sessionDescriptionHandlerFactory(this,this.ua.configuration.sessionDescriptionHandlerFactoryOptions||{});return this.emit("SessionDescriptionHandler-created",h),this.earlyMediaSessionDescriptionHandlers.set(n.id,h),void h.setDescription(r.body,this.sessionDescriptionHandlerOptions,this.modifiers).then(function(){return h.getDescription(t.sessionDescriptionHandlerOptions,t.modifiers)}).then(function(n){var i={contentDisposition:"session",contentType:n.contentType,content:n.body};e.prack({extraHeaders:c,body:i}),t.status=d.SessionStatus.STATUS_EARLY_MEDIA,t.emit("progress",r)}).catch(function(e){t.status!==d.SessionStatus.STATUS_TERMINATED&&(t.failed(void 0,a.C.causes.WEBRTC_ERROR),t.terminated(void 0,a.C.causes.WEBRTC_ERROR))})}return n.signalingState===u.SignalingState.Stable?(s&&e.prack({extraHeaders:c}),void this.emit("progress",r)):void 0}},t.prototype.onRedirect=function(e){this.disposeEarlyMedia();var t=e.message,r=t.statusCode,n=m.Utils.sipErrorCause(r||0);this.rejected(t,n),this.failed(t,n),this.terminated(t,n)},t.prototype.onReject=function(e){this.disposeEarlyMedia();var t=e.message,r=t.statusCode,n=m.Utils.sipErrorCause(r||0);this.rejected(t,n),this.failed(t,n),this.terminated(t,n)},t.prototype.onTrying=function(e){this.received100=!0,this.emit("progress",e.message)},t}(y);t.InviteClientContext=T},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(10),s=r(2),a=r(14),c=r(32),u=r(23),d=r(3),h=r(5),p=function(e){function t(t,r,n,i){void 0===i&&(i={});var o=e.call(this)||this;o.data={},o.method=s.C.SUBSCRIBE,o.body=void 0,o.type=d.TypeStrings.Subscription,o.ua=t,o.logger=t.getLogger("sip.subscription"),i.body&&(o.body={body:i.body,contentType:i.contentType?i.contentType:"application/sdp"});var a=t.normalizeTarget(r);if(!a)throw new TypeError("Invalid target: "+r);if(o.uri=a,o.event=n,void 0===i.expires?o.expires=3600:"number"!=typeof i.expires?(t.logger.warn('Option "expires" must be a number. Using default of 3600.'),o.expires=3600):o.expires=i.expires,o.extraHeaders=(i.extraHeaders||[]).slice(),o.context=o.initContext(),o.disposed=!1,o.request=o.context.message,!o.request.from)throw new Error("From undefined.");if(!o.request.to)throw new Error("From undefined.");return o.localIdentity=o.request.from,o.remoteIdentity=o.request.to,o}return i(t,e),t.prototype.dispose=function(){this.disposed||(this.retryAfterTimer&&(clearTimeout(this.retryAfterTimer),this.retryAfterTimer=void 0),this.context.dispose(),this.disposed=!0)},t.prototype.on=function(t,r){return e.prototype.on.call(this,t,r)},t.prototype.emit=function(t){for(var r=[],n=1;n0?(e.accept(),n.emit("notify",{request:e.message})):e.reject({statusCode:481})},onRefer:function(e){n.logger.log("Received an out of dialog refer"),n.configuration.allowOutOfDialogRefers||e.reject({statusCode:405}),n.logger.log("Allow out of dialog refers is enabled on the UA");var t=new v.ReferServerContext(n,e);n.listeners("outOfDialogReferRequested").length?n.emit("outOfDialogReferRequested",t):(n.logger.log("No outOfDialogReferRequest listeners, automatically accepting and following the out of dialog refer"),t.accept({followRefer:!0}))},onSubscribe:function(e){n.emit("subscribe",e)}};return n.userAgentCore=new c.UserAgentCore(s,u),n.registerContext=new m.RegisterContext(n,e.registerOptions),n.registerContext.on("failed",n.emit.bind(n,"registrationFailed")),n.registerContext.on("registered",n.emit.bind(n,"registered")),n.registerContext.on("unregistered",n.emit.bind(n,"unregistered")),n.configuration.autostart&&n.start(),n}return i(r,t),r.prototype.register=function(e){return void 0===e&&(e={}),e.register&&(this.configuration.register=!0),this.registerContext.register(e),this},r.prototype.unregister=function(e){var t=this;return this.configuration.register=!1,this.transport&&this.transport.afterConnected(function(){t.registerContext.unregister(e)}),this},r.prototype.isRegistered=function(){return this.registerContext.registered},r.prototype.invite=function(e,t,r){var n=this,i=new S.InviteClientContext(this,e,t,r);return this.transport&&this.transport.afterConnected(function(){i.invite(),n.emit("inviteSent",i)}),i},r.prototype.subscribe=function(e,t,r){var n=new C.Subscription(this,e,t,r);return this.transport&&this.transport.afterConnected(function(){return n.subscribe()}),n},r.prototype.publish=function(e,t,r,n){var i=new g.PublishContext(this,e,t,n);return this.transport&&this.transport.afterConnected(function(){i.publish(r)}),i},r.prototype.message=function(e,t,r){if(void 0===r&&(r={}),void 0===t)throw new TypeError("Not enough arguments");return r.contentType=r.contentType||"text/plain",r.body=t,this.request(a.C.MESSAGE,e,r)},r.prototype.request=function(e,t,r){var n=new s.ClientContext(this,e,t,r);return this.transport&&this.transport.afterConnected(function(){return n.send()}),n},r.prototype.stop=function(){if(this.logger.log("user requested closure..."),this.status===d.UAStatus.STATUS_USER_CLOSED)return this.logger.warn("UA already closed"),this;for(var t in this.logger.log("closing registerContext"),this.registerContext.close(),this.sessions)this.sessions[t]&&(this.logger.log("closing session "+t),this.sessions[t].terminate());for(var r in this.publishers)this.publishers[r]&&(this.logger.log("unpublish "+r),this.publishers[r].close());for(var n in this.applicants)this.applicants[n]&&this.applicants[n].close();return this.status=d.UAStatus.STATUS_USER_CLOSED,"function"==typeof E.removeEventListener&&(e.chrome&&e.chrome.app&&e.chrome.app.runtime||E.removeEventListener("unload",this.environListener)),this},r.prototype.start=function(){var t=this;if(this.logger.log("user requested startup..."),this.status===d.UAStatus.STATUS_INIT){if(this.status=d.UAStatus.STATUS_STARTING,!this.configuration.transportConstructor)throw new h.Exceptions.TransportError("Transport constructor not set");this.transport=new this.configuration.transportConstructor(this.getLogger("sip.transport"),this.configuration.transportOptions),this.setTransportListeners(),this.emit("transportCreated",this.transport),this.transport.connect()}else this.status===d.UAStatus.STATUS_USER_CLOSED?(this.logger.log("resuming"),this.status=d.UAStatus.STATUS_READY,this.transport&&this.transport.connect()):this.status===d.UAStatus.STATUS_STARTING?this.logger.log("UA is in STARTING status, not opening new connection"):this.status===d.UAStatus.STATUS_READY?this.logger.log("UA is in READY status, not resuming"):this.logger.error("Connection is down. Auto-Recovery system is trying to connect");return this.configuration.autostop&&"function"==typeof E.addEventListener&&(e.chrome&&e.chrome.app&&e.chrome.app.runtime||(this.environListener=this.stop,E.addEventListener("unload",function(){return t.environListener()}))),this},r.prototype.normalizeTarget=function(e){return _.Utils.normalizeTarget(e,this.configuration.hostportParams)},r.prototype.getLogger=function(e,t){return this.log.getLogger(e,t)},r.prototype.getLoggerFactory=function(){return this.log},r.prototype.findSession=function(e){return this.sessions[e.callId+e.fromTag]||this.sessions[e.callId+e.toTag]||void 0},r.prototype.on=function(e,r){return t.prototype.on.call(this,e,r)},r.prototype.onTransportError=function(){this.status!==d.UAStatus.STATUS_USER_CLOSED&&(this.error&&this.error===r.C.NETWORK_ERROR||(this.status=d.UAStatus.STATUS_NOT_READY,this.error=r.C.NETWORK_ERROR))},r.prototype.setTransportListeners=function(){var e=this;this.transport&&(this.transport.on("connected",function(){return e.onTransportConnected()}),this.transport.on("message",function(t){return e.onTransportReceiveMsg(t)}),this.transport.on("transportError",function(){return e.onTransportError()}))},r.prototype.onTransportConnected=function(){var e=this;this.configuration.register&&Promise.resolve().then(function(){return e.registerContext.register()})},r.prototype.onTransportReceiveMsg=function(e){var t=this,r=f.Parser.parseMessage(e,this);if(r)if(this.status===d.UAStatus.STATUS_USER_CLOSED&&r instanceof T.IncomingRequest)this.logger.warn("UA received message when status = USER_CLOSED - aborting");else{var n=function(){for(var e=0,n=["from","to","call_id","cseq","via"];e1)return void this.logger.warn("More than one Via header field present in the response. Dropping.");if(r.via.host!==this.configuration.viaHost||void 0!==r.via.port)return void this.logger.warn("Via sent-by in the response does not match UA Via host value. Dropping.");var o;i=_.Utils.str_utf8_length(r.body);if((o=r.getHeader("content-length"))&&i"}};var p={};for(var i in r)r.hasOwnProperty(i)&&(p[i]=r[i]);for(var i in Object.assign(this.configuration,p),this.logger.log("configuration parameters after validation:"),r)if(r.hasOwnProperty(i))switch(i){case"uri":case"sessionDescriptionHandlerFactory":this.logger.log("\xb7 "+i+": "+r[i]);break;case"password":this.logger.log("\xb7 "+i+": NOT SHOWN");break;case"transportConstructor":this.logger.log("\xb7 "+i+": "+r[i].name);break;default:this.logger.log("\xb7 "+i+": "+JSON.stringify(r[i]))}},r.prototype.getConfigurationCheck=function(){return{mandatory:{},optional:{uri:function(e){/^sip:/i.test(e)||(e=a.C.SIP+":"+e);var t=p.Grammar.URIParse(e);return t&&t.user?t:void 0},transportConstructor:function(e){if(e instanceof Function)return e},transportOptions:function(e){if("object"==typeof e)return e},authorizationUser:function(e){return-1===p.Grammar.parse('"'+e+'"',"quoted_string")?void 0:e},displayName:function(e){return-1===p.Grammar.parse('"'+e+'"',"displayName")?void 0:e},dtmfType:function(e){switch(e){case a.C.dtmfType.RTP:return a.C.dtmfType.RTP;case a.C.dtmfType.INFO:default:return a.C.dtmfType.INFO}},hackViaTcp:function(e){if("boolean"==typeof e)return e},hackIpInContact:function(e){return"boolean"==typeof e?e:"string"==typeof e&&-1!==p.Grammar.parse(e,"host")?e:void 0},hackWssInTransport:function(e){if("boolean"==typeof e)return e},hackAllowUnregisteredOptionTags:function(e){if("boolean"==typeof e)return e},contactTransport:function(e){if("string"==typeof e)return e},extraSupported:function(e){if(e instanceof Array){for(var t=0,r=e;t0)return t}},password:function(e){return String(e)},rel100:function(e){return e===a.C.supported.REQUIRED?a.C.supported.REQUIRED:e===a.C.supported.SUPPORTED?a.C.supported.SUPPORTED:a.C.supported.UNSUPPORTED},replaces:function(e){return e===a.C.supported.REQUIRED?a.C.supported.REQUIRED:e===a.C.supported.SUPPORTED?a.C.supported.SUPPORTED:a.C.supported.UNSUPPORTED},register:function(e){if("boolean"==typeof e)return e},registerOptions:function(e){if("object"==typeof e)return e},userAgentString:function(e){if("string"==typeof e)return e},autostart:function(e){if("boolean"==typeof e)return e},autostop:function(e){if("boolean"==typeof e)return e},sessionDescriptionHandlerFactory:function(e){if(e instanceof Function)return e},sessionDescriptionHandlerFactoryOptions:function(e){if("object"==typeof e)return e},authenticationFactory:this.checkAuthenticationFactory,allowLegacyNotifications:function(e){if("boolean"==typeof e)return e},custom:function(e){if("object"==typeof e)return e},contactName:function(e){if("string"==typeof e)return e},experimentalFeatures:function(e){if("boolean"==typeof e)return e}}}},r.C={STATUS_INIT:0,STATUS_STARTING:1,STATUS_READY:2,STATUS_USER_CLOSED:3,STATUS_NOT_READY:4,CONFIGURATION_ERROR:1,NETWORK_ERROR:2,ALLOWED_METHODS:["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"],ACCEPTED_BODY_TYPES:["application/sdp","application/dtmf-relay"],MAX_FORWARDS:70,TAG_LENGTH:10},r}(o.EventEmitter);t.UA=R,function(e){!function(e){e.RTP="rtp",e.INFO="info"}(e.DtmfType||(e.DtmfType={}))}(R=t.UA||(t.UA={})),t.UA=R}).call(this,r(24))},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(2),s=r(1),a=function(e){function t(t,r,n){var i,a=t.createOutgoingRequestMessage(o.C.BYE,n);return i=e.call(this,s.NonInviteClientTransaction,t.userAgentCore,a,r)||this,t.dispose(),i}return i(t,e),t}(r(6).UserAgentClient);t.ByeUserAgentClient=a},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(1),s=function(e){function t(t,r,n){return e.call(this,o.NonInviteServerTransaction,t.userAgentCore,r,n)||this}return i(t,e),t}(r(9).UserAgentServer);t.ByeUserAgentServer=s},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(1),s=function(e){function t(t,r,n){return e.call(this,o.NonInviteServerTransaction,t.userAgentCore,r,n)||this}return i(t,e),t}(r(9).UserAgentServer);t.InfoUserAgentServer=s},function(e,t,r){"use strict";function n(e){for(var r in e)t.hasOwnProperty(r)||(t[r]=e[r])}Object.defineProperty(t,"__esModule",{value:!0}),n(r(33)),n(r(103)),n(r(60))},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(2),s=r(1),a=function(e){function t(t,r,n){var i=t.createOutgoingRequestMessage(o.C.NOTIFY,n);return e.call(this,s.NonInviteClientTransaction,t.userAgentCore,i,r)||this}return i(t,e),t}(r(6).UserAgentClient);t.NotifyUserAgentClient=a},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(2),s=r(1),a=function(e){function t(t,r,n){var i,a=t.createOutgoingRequestMessage(o.C.PRACK,n);return i=e.call(this,s.NonInviteClientTransaction,t.userAgentCore,a,r)||this,t.signalingStateTransition(a),i}return i(t,e),t}(r(6).UserAgentClient);t.PrackUserAgentClient=a},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(1),s=function(e){function t(t,r,n){var i=e.call(this,o.NonInviteServerTransaction,t.userAgentCore,r,n)||this;return t.signalingStateTransition(r),i.dialog=t,i}return i(t,e),t.prototype.accept=function(t){return void 0===t&&(t={statusCode:200}),t.body&&this.dialog.signalingStateTransition(t.body),e.prototype.accept.call(this,t)},t}(r(9).UserAgentServer);t.PrackUserAgentServer=s},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(2),s=r(1),a=function(e){function t(t,r,n){var i=this,a=t.createOutgoingRequestMessage(o.C.INVITE,n);return(i=e.call(this,s.InviteClientTransaction,t.userAgentCore,a,r)||this).delegate=r,t.signalingStateTransition(a),t.reinviteUserAgentClient=i,i.dialog=t,i}return i(t,e),t.prototype.receiveResponse=function(e){var t=this,r=e.statusCode?e.statusCode.toString():"";if(!r)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(r):this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e});break;case/^1[0-9]{2}$/.test(r):this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e,session:this.dialog,prack:function(e){throw new Error("Unimplemented.")}});break;case/^2[0-9]{2}$/.test(r):this.dialog.signalingStateTransition(e),this.delegate&&this.delegate.onAccept&&this.delegate.onAccept({message:e,session:this.dialog,ack:function(e){return t.dialog.ack(e)}});break;case/^3[0-9]{2}$/.test(r):this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e});break;case/^[4-6][0-9]{2}$/.test(r):this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e});break;default:throw new Error("Invalid status code "+r)}},t}(r(6).UserAgentClient);t.ReInviteUserAgentClient=a},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}),o=this&&this.__assign||function(){return(o=Object.assign||function(e){for(var t,r=1,n=arguments.length;r=e)&&this.refreshTimerSet()}},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"subscriptionExpiresInitial",{get:function(){return this._subscriptionExpiresInitial},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"subscriptionRefresh",{get:function(){if(void 0!==this._subscriptionRefresh&&void 0!==this._subscriptionRefreshLastSet){var e=Math.floor(Date.now()/1e3)-this._subscriptionRefreshLastSet,t=this._subscriptionRefresh-e;return Math.max(t,0)}},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"subscriptionState",{get:function(){return this._subscriptionState},enumerable:!0,configurable:!0}),t.prototype.receiveRequest=function(t){if(this.logger.log("SUBSCRIBE dialog "+this.id+" received "+t.method+" request"),this.sequenceGuard(t))switch(e.prototype.receiveRequest.call(this,t),t.method){case o.C.NOTIFY:this.onNotify(t);break;default:this.logger.log("SUBSCRIBE dialog "+this.id+" received unimplemented "+t.method+" request"),this.core.replyStateless(t,{statusCode:501})}else this.logger.log("SUBSCRIBE dialog "+this.id+" rejected out of order "+t.method+" request.")},t.prototype.refresh=function(){var e="Allow: "+u.AllowedMethods.toString(),t={};return t.extraHeaders=(t.extraHeaders||[]).slice(),t.extraHeaders.push(e),t.extraHeaders.push("Event: "+this.subscriptionEvent),t.extraHeaders.push("Expires: "+this.subscriptionExpiresInitial),t.extraHeaders.push("Contact: "+this.core.configuration.contact.toString()),this.subscribe(void 0,t)},t.prototype.subscribe=function(e,t){var r=this;if(void 0===t&&(t={}),this.subscriptionState!==c.SubscriptionState.Pending&&this.subscriptionState!==c.SubscriptionState.Active)throw new Error("Invalid state "+this.subscriptionState+'. May only re-subscribe while in state "pending" or "active".');this.logger.log("SUBSCRIBE dialog "+this.id+" sending SUBSCRIBE request");var n=new h.ReSubscribeUserAgentClient(this,e,t);return this.N=setTimeout(function(){return r.timer_N()},a.Timers.TIMER_N),n},t.prototype.terminate=function(){this.stateTransition(c.SubscriptionState.Terminated),this.onTerminated()},t.prototype.unsubscribe=function(){var e="Allow: "+u.AllowedMethods.toString(),t={};return t.extraHeaders=(t.extraHeaders||[]).slice(),t.extraHeaders.push(e),t.extraHeaders.push("Event: "+this.subscriptionEvent),t.extraHeaders.push("Expires: 0"),t.extraHeaders.push("Contact: "+this.core.configuration.contact.toString()),this.subscribe(void 0,t)},t.prototype.onNotify=function(e){var t=e.parseHeader("Event").event;if(t&&t===this.subscriptionEvent){this.N&&(clearTimeout(this.N),this.N=void 0);var r=e.parseHeader("Subscription-State");if(r&&r.state){var n=r.state,i=r.expires?Math.max(r.expires,0):void 0;switch(n){case"pending":this.stateTransition(c.SubscriptionState.Pending,i);break;case"active":this.stateTransition(c.SubscriptionState.Active,i);break;case"terminated":this.stateTransition(c.SubscriptionState.Terminated,i);break;default:this.logger.warn("Unrecognized subscription state.")}var o=new d.NotifyUserAgentServer(this,e);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(o):o.accept()}else this.core.replyStateless(e,{statusCode:489})}else this.core.replyStateless(e,{statusCode:489})},t.prototype.onRefresh=function(e){this.delegate&&this.delegate.onRefresh&&this.delegate.onRefresh(e)},t.prototype.onTerminated=function(){this.delegate&&this.delegate.onTerminated&&this.delegate.onTerminated()},t.prototype.refreshTimerClear=function(){this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=void 0)},t.prototype.refreshTimerSet=function(){var e=this;if(this.refreshTimerClear(),this.autoRefresh&&this.subscriptionExpires>0){var t=900*this.subscriptionExpires;this._subscriptionRefresh=Math.floor(t/1e3),this._subscriptionRefreshLastSet=Math.floor(Date.now()/1e3),this.refreshTimer=setTimeout(function(){e.refreshTimer=void 0,e._subscriptionRefresh=void 0,e._subscriptionRefreshLastSet=void 0,e.onRefresh(e.refresh())},t)}},t.prototype.stateTransition=function(e,t){var r=this,n=function(){r.logger.warn("Invalid subscription state transition from "+r.subscriptionState+" to "+e)};switch(e){case c.SubscriptionState.Initial:case c.SubscriptionState.NotifyWait:return void n();case c.SubscriptionState.Pending:if(this.subscriptionState!==c.SubscriptionState.NotifyWait&&this.subscriptionState!==c.SubscriptionState.Pending)return void n();break;case c.SubscriptionState.Active:case c.SubscriptionState.Terminated:if(this.subscriptionState!==c.SubscriptionState.NotifyWait&&this.subscriptionState!==c.SubscriptionState.Pending&&this.subscriptionState!==c.SubscriptionState.Active)return void n();break;default:return void n()}e===c.SubscriptionState.Pending&&t&&(this.subscriptionExpires=t),e===c.SubscriptionState.Active&&t&&(this.subscriptionExpires=t),e===c.SubscriptionState.Terminated&&this.dispose(),this._subscriptionState=e},t.prototype.timer_N=function(){this.subscriptionState!==c.SubscriptionState.Terminated&&(this.stateTransition(c.SubscriptionState.Terminated),this.onTerminated())},t}(r(33).Dialog);t.SubscriptionDialog=p},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(2),s=r(1),a=function(e){function t(t,r,n){var i=this,a=t.createOutgoingRequestMessage(o.C.SUBSCRIBE,n);return(i=e.call(this,s.NonInviteClientTransaction,t.userAgentCore,a,r)||this).dialog=t,i}return i(t,e),t.prototype.waitNotifyStop=function(){},t.prototype.receiveResponse=function(t){if(t.statusCode&&t.statusCode>=200&&t.statusCode<300){var r=t.getHeader("Expires");if(r){var n=Number(r);this.dialog.subscriptionExpires>n&&(this.dialog.subscriptionExpires=n)}else this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE")}if(t.statusCode&&t.statusCode>=400&&t.statusCode<700){[404,405,410,416,480,481,482,483,484,485,489,501,604].includes(t.statusCode)&&this.dialog.terminate()}e.prototype.receiveResponse.call(this,t)},t}(r(6).UserAgentClient);t.ReSubscribeUserAgentClient=a},function(e,t,r){"use strict";(function(e){var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(10),s=r(3),a=r(7),c=r(5),u=r(35),d=r(114),h=function(t){function r(r,n,i){var o=t.call(this)||this;o.type=s.TypeStrings.SessionDescriptionHandler,o.options=i||{},o.logger=r,o.observer=n,o.dtmfSender=void 0,o.shouldAcquireMedia=!0,o.CONTENT_TYPE="application/sdp",o.C={DIRECTION:{NULL:null,SENDRECV:"sendrecv",SENDONLY:"sendonly",RECVONLY:"recvonly",INACTIVE:"inactive"}},o.logger.log("SessionDescriptionHandlerOptions: "+JSON.stringify(o.options)),o.direction=o.C.DIRECTION.NULL,o.modifiers=o.options.modifiers||[],Array.isArray(o.modifiers)||(o.modifiers=[o.modifiers]);var a=e.window||e;return o.WebRTC={MediaStream:a.MediaStream,getUserMedia:a.navigator.mediaDevices.getUserMedia.bind(a.navigator.mediaDevices),RTCPeerConnection:a.RTCPeerConnection},o.iceGatheringTimeout=!1,o.initPeerConnection(o.options.peerConnectionOptions),o.constraints=o.checkAndDefaultConstraints(o.options.constraints),o}return i(r,t),r.defaultFactory=function(e,t){return new r(e.ua.getLogger("sip.invitecontext.sessionDescriptionHandler",e.id),new d.SessionDescriptionHandlerObserver(e,t),t)},r.prototype.close=function(){this.logger.log("closing PeerConnection"),this.peerConnection&&"closed"!==this.peerConnection.signalingState&&(this.peerConnection.getSenders?this.peerConnection.getSenders().forEach(function(e){e.track&&e.track.stop()}):(this.logger.warn("Using getLocalStreams which is deprecated"),this.peerConnection.getLocalStreams().forEach(function(e){e.getTracks().forEach(function(e){e.stop()})})),this.peerConnection.getReceivers?this.peerConnection.getReceivers().forEach(function(e){e.track&&e.track.stop()}):(this.logger.warn("Using getRemoteStreams which is deprecated"),this.peerConnection.getRemoteStreams().forEach(function(e){e.getTracks().forEach(function(e){e.stop()})})),this.resetIceGatheringComplete(),this.peerConnection.close())},r.prototype.getDescription=function(e,t){var r=this;void 0===e&&(e={}),void 0===t&&(t=[]),e.peerConnectionOptions&&this.initPeerConnection(e.peerConnectionOptions);var n=Object.assign({},this.constraints,e.constraints);return n=this.checkAndDefaultConstraints(n),JSON.stringify(n)!==JSON.stringify(this.constraints)&&(this.constraints=n,this.shouldAcquireMedia=!0),Array.isArray(t)||(t=[t]),t=t.concat(this.modifiers),Promise.resolve().then(function(){if(r.shouldAcquireMedia)return r.acquire(r.constraints).then(function(){r.shouldAcquireMedia=!1})}).then(function(){return r.createOfferOrAnswer(e.RTCOfferOptions,t)}).then(function(e){if(void 0===e.sdp)throw new a.Exceptions.SessionDescriptionHandlerError("getDescription",void 0,"SDP undefined");return r.emit("getDescription",e),{body:e.sdp,contentType:r.CONTENT_TYPE}})},r.prototype.hasDescription=function(e){return e===this.CONTENT_TYPE},r.prototype.holdModifier=function(e){return e.sdp?(/a=(sendrecv|sendonly|recvonly|inactive)/.test(e.sdp)?(e.sdp=e.sdp.replace(/a=sendrecv\r\n/g,"a=sendonly\r\n"),e.sdp=e.sdp.replace(/a=recvonly\r\n/g,"a=inactive\r\n")):e.sdp=e.sdp.replace(/(m=[^\r]*\r\n)/g,"$1a=sendonly\r\n"),Promise.resolve(e)):Promise.resolve(e)},r.prototype.setDescription=function(e,t,r){var n=this;void 0===t&&(t={}),void 0===r&&(r=[]),t.peerConnectionOptions&&this.initPeerConnection(t.peerConnectionOptions),Array.isArray(r)||(r=[r]),r=r.concat(this.modifiers);var i={type:this.hasOffer("local")?"answer":"offer",sdp:e};return Promise.resolve().then(function(){if(n.shouldAcquireMedia&&n.options.alwaysAcquireMediaFirst)return n.acquire(n.constraints).then(function(){n.shouldAcquireMedia=!1})}).then(function(){return c.Utils.reducePromises(r,i)}).catch(function(e){if(e.type===s.TypeStrings.SessionDescriptionHandlerError)throw e;var t=new a.Exceptions.SessionDescriptionHandlerError("setDescription",e,"The modifiers did not resolve successfully");throw n.logger.error(t.message),n.emit("peerConnection-setRemoteDescriptionFailed",t),t}).then(function(e){return n.emit("setDescription",e),n.peerConnection.setRemoteDescription(e)}).catch(function(i){if(i.type===s.TypeStrings.SessionDescriptionHandlerError)throw i;if(/^m=video.+$/gm.test(e)&&!t.disableAudioFallback)return t.disableAudioFallback=!0,n.setDescription(e,t,[u.stripVideo].concat(r));var o=new a.Exceptions.SessionDescriptionHandlerError("setDescription",i);throw o.error&&n.logger.error(o.error),n.emit("peerConnection-setRemoteDescriptionFailed",o),o}).then(function(){n.peerConnection.getReceivers?n.emit("setRemoteDescription",n.peerConnection.getReceivers()):n.emit("setRemoteDescription",n.peerConnection.getRemoteStreams()),n.emit("confirmed",n)})},r.prototype.sendDtmf=function(e,t){if(void 0===t&&(t={}),!this.dtmfSender&&this.hasBrowserGetSenderSupport()){var r=this.peerConnection.getSenders();r.length>0&&(this.dtmfSender=r[0].dtmf)}if(!this.dtmfSender&&this.hasBrowserTrackSupport()){var n=this.peerConnection.getLocalStreams();if(n.length>0){var i=n[0].getAudioTracks();i.length>0&&(this.dtmfSender=this.peerConnection.createDTMFSender(i[0]))}}if(!this.dtmfSender)return!1;try{this.dtmfSender.insertDTMF(e,t.duration,t.interToneGap)}catch(e){if("InvalidStateError"===e.type||"InvalidCharacterError"===e.type)return this.logger.error(e),!1;throw e}return this.logger.log("DTMF sent via RTP: "+e.toString()),!0},r.prototype.getDirection=function(){return this.direction},r.prototype.on=function(e,r){return t.prototype.on.call(this,e,r)},r.prototype.createOfferOrAnswer=function(e,t){var r=this;void 0===e&&(e={}),void 0===t&&(t=[]);var n=this.hasOffer("remote")?"createAnswer":"createOffer",i=this.peerConnection;return this.logger.log(n),(this.hasOffer("remote")?i.createAnswer:i.createOffer)(e).catch(function(e){if(e.type===s.TypeStrings.SessionDescriptionHandlerError)throw e;var t=new a.Exceptions.SessionDescriptionHandlerError("createOfferOrAnswer",e,"peerConnection-"+n+"Failed");throw r.emit("peerConnection-"+n+"Failed",t),t}).then(function(e){return c.Utils.reducePromises(t,r.createRTCSessionDescriptionInit(e))}).then(function(e){return r.resetIceGatheringComplete(),r.logger.log("Setting local sdp."),r.logger.log("sdp is "+e.sdp||!1),i.setLocalDescription(e)}).catch(function(e){if(e.type===s.TypeStrings.SessionDescriptionHandlerError)throw e;var t=new a.Exceptions.SessionDescriptionHandlerError("createOfferOrAnswer",e,"peerConnection-SetLocalDescriptionFailed");throw r.emit("peerConnection-SetLocalDescriptionFailed",t),t}).then(function(){return r.waitForIceGatheringComplete()}).then(function(){var e=r.createRTCSessionDescriptionInit(r.peerConnection.localDescription);return c.Utils.reducePromises(t,e)}).then(function(e){return r.setDirection(e.sdp||""),e}).catch(function(e){if(e.type===s.TypeStrings.SessionDescriptionHandlerError)throw e;var t=new a.Exceptions.SessionDescriptionHandlerError("createOfferOrAnswer",e);throw r.logger.error(t.toString()),t})},r.prototype.createRTCSessionDescriptionInit=function(e){return{type:e.type,sdp:e.sdp}},r.prototype.addDefaultIceCheckingTimeout=function(e){return void 0===e.iceCheckingTimeout&&(e.iceCheckingTimeout=5e3),e},r.prototype.addDefaultIceServers=function(e){return e.iceServers||(e.iceServers=[{urls:"stun:stun.l.google.com:19302"}]),e},r.prototype.checkAndDefaultConstraints=function(e){var t={audio:!0,video:!this.options.alwaysAcquireMediaFirst};return e=e||t,0===Object.keys(e).length&&e.constructor===Object?t:e},r.prototype.hasBrowserTrackSupport=function(){return Boolean(this.peerConnection.addTrack)},r.prototype.hasBrowserGetSenderSupport=function(){return Boolean(this.peerConnection.getSenders)},r.prototype.initPeerConnection=function(e){var t=this;void 0===e&&(e={}),(e=this.addDefaultIceCheckingTimeout(e)).rtcConfiguration=e.rtcConfiguration||{},e.rtcConfiguration=this.addDefaultIceServers(e.rtcConfiguration),this.logger.log("initPeerConnection"),this.peerConnection&&(this.logger.log("Already have a peer connection for this session. Tearing down."),this.resetIceGatheringComplete(),this.peerConnection.close()),this.peerConnection=new this.WebRTC.RTCPeerConnection(e.rtcConfiguration),this.logger.log("New peer connection created"),"ontrack"in this.peerConnection?this.peerConnection.addEventListener("track",function(e){t.logger.log("track added"),t.observer.trackAdded(),t.emit("addTrack",e)}):(this.logger.warn("Using onaddstream which is deprecated"),this.peerConnection.onaddstream=function(e){t.logger.log("stream added"),t.emit("addStream",e)}),this.peerConnection.onicecandidate=function(e){t.emit("iceCandidate",e),e.candidate?t.logger.log("ICE candidate received: "+(null===e.candidate.candidate?null:e.candidate.candidate.trim())):null===e.candidate&&(t.logger.log("ICE candidate gathering complete"),t.triggerIceGatheringComplete())},this.peerConnection.onicegatheringstatechange=function(){switch(t.logger.log("RTCIceGatheringState changed: "+t.peerConnection.iceGatheringState),t.peerConnection.iceGatheringState){case"gathering":t.emit("iceGathering",t),!t.iceGatheringTimer&&e.iceCheckingTimeout&&(t.iceGatheringTimeout=!1,t.iceGatheringTimer=setTimeout(function(){t.logger.log("RTCIceChecking Timeout Triggered after "+e.iceCheckingTimeout+" milliseconds"),t.iceGatheringTimeout=!0,t.triggerIceGatheringComplete()},e.iceCheckingTimeout));break;case"complete":t.triggerIceGatheringComplete()}},this.peerConnection.oniceconnectionstatechange=function(){var e;switch(t.peerConnection.iceConnectionState){case"new":e="iceConnection";break;case"checking":e="iceConnectionChecking";break;case"connected":e="iceConnectionConnected";break;case"completed":e="iceConnectionCompleted";break;case"failed":e="iceConnectionFailed";break;case"disconnected":e="iceConnectionDisconnected";break;case"closed":e="iceConnectionClosed";break;default:return void t.logger.warn("Unknown iceConnection state: "+t.peerConnection.iceConnectionState)}t.logger.log("ICE Connection State changed to "+e),t.emit(e,t)}},r.prototype.acquire=function(e){var t=this;return e=this.checkAndDefaultConstraints(e),new Promise(function(r,n){t.logger.log("acquiring local media"),t.emit("userMediaRequest",e),e.audio||e.video?t.WebRTC.getUserMedia(e).then(function(e){t.observer.trackAdded(),t.emit("userMedia",e),r(e)}).catch(function(e){t.emit("userMediaFailed",e),n(e)}):r([])}).catch(function(e){if(e.type===s.TypeStrings.SessionDescriptionHandlerError)throw e;var r=new a.Exceptions.SessionDescriptionHandlerError("acquire",e,"unable to acquire streams");throw t.logger.error(r.message),r.error&&t.logger.error(r.error),r}).then(function(e){t.logger.log("acquired local media streams");try{return t.peerConnection.removeTrack&&t.peerConnection.getSenders().forEach(function(e){t.peerConnection.removeTrack(e)}),e}catch(e){return Promise.reject(e)}}).catch(function(e){if(e.type===s.TypeStrings.SessionDescriptionHandlerError)throw e;var r=new a.Exceptions.SessionDescriptionHandlerError("acquire",e,"error removing streams");throw t.logger.error(r.message),r.error&&t.logger.error(r.error),r}).then(function(e){try{(e=[].concat(e)).forEach(function(e){t.peerConnection.addTrack?e.getTracks().forEach(function(r){t.peerConnection.addTrack(r,e)}):t.peerConnection.addStream(e)})}catch(e){return Promise.reject(e)}return Promise.resolve()}).catch(function(e){if(e.type===s.TypeStrings.SessionDescriptionHandlerError)throw e;var r=new a.Exceptions.SessionDescriptionHandlerError("acquire",e,"error adding stream");throw t.logger.error(r.message),r.error&&t.logger.error(r.error),r})},r.prototype.hasOffer=function(e){var t="have-"+e+"-offer";return this.peerConnection.signalingState===t},r.prototype.isIceGatheringComplete=function(){return"complete"===this.peerConnection.iceGatheringState||this.iceGatheringTimeout},r.prototype.resetIceGatheringComplete=function(){this.iceGatheringTimeout=!1,this.logger.log("resetIceGatheringComplete"),this.iceGatheringTimer&&(clearTimeout(this.iceGatheringTimer),this.iceGatheringTimer=void 0),this.iceGatheringDeferred&&(this.iceGatheringDeferred.reject(),this.iceGatheringDeferred=void 0)},r.prototype.setDirection=function(e){var t=e.match(/a=(sendrecv|sendonly|recvonly|inactive)/);if(null===t)return this.direction=this.C.DIRECTION.NULL,void this.observer.directionChanged();var r=t[1];switch(r){case this.C.DIRECTION.SENDRECV:case this.C.DIRECTION.SENDONLY:case this.C.DIRECTION.RECVONLY:case this.C.DIRECTION.INACTIVE:this.direction=r;break;default:this.direction=this.C.DIRECTION.NULL}this.observer.directionChanged()},r.prototype.triggerIceGatheringComplete=function(){this.isIceGatheringComplete()&&(this.emit("iceGatheringComplete",this),this.iceGatheringTimer&&(clearTimeout(this.iceGatheringTimer),this.iceGatheringTimer=void 0),this.iceGatheringDeferred&&(this.iceGatheringDeferred.resolve(),this.iceGatheringDeferred=void 0))},r.prototype.waitForIceGatheringComplete=function(){return this.logger.log("waitForIceGatheringComplete"),this.isIceGatheringComplete()?(this.logger.log("ICE is already complete. Return resolved."),Promise.resolve()):(this.iceGatheringDeferred||(this.iceGatheringDeferred=c.Utils.defer()),this.logger.log("ICE is not complete. Returning promise"),this.iceGatheringDeferred?this.iceGatheringDeferred.promise:Promise.resolve())},r}(o.EventEmitter);t.SessionDescriptionHandler=h}).call(this,r(24))},function(e,t,r){"use strict";(function(e){var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o,s=r(3),a=r(7),c=r(11),u=r(47),d=r(5);!function(e){e[e.STATUS_CONNECTING=0]="STATUS_CONNECTING",e[e.STATUS_OPEN=1]="STATUS_OPEN",e[e.STATUS_CLOSING=2]="STATUS_CLOSING",e[e.STATUS_CLOSED=3]="STATUS_CLOSED"}(o=t.TransportStatus||(t.TransportStatus={}));var h=function(t){function r(r,n){void 0===n&&(n={});var i=t.call(this,r,n)||this;return i.WebSocket=(e.window||e).WebSocket,i.type=s.TypeStrings.Transport,i.reconnectionAttempts=0,i.status=o.STATUS_CONNECTING,i.configuration=i.loadConfig(n),i.server=i.configuration.wsServers[0],i}return i(r,t),r.prototype.isConnected=function(){return this.status===o.STATUS_OPEN},r.prototype.sendPromise=function(e,t){if(void 0===t&&(t={}),!this.statusAssert(o.STATUS_OPEN,t.force))return this.onError("unable to send message - WebSocket not open"),Promise.reject();var r=e.toString();return this.ws?(!0===this.configuration.traceSip&&this.logger.log("sending WebSocket message:\n\n"+r+"\n"),this.ws.send(r),Promise.resolve({msg:r})):(this.onError("unable to send message - WebSocket does not exist"),Promise.reject())},r.prototype.disconnectPromise=function(e){var t=this;return void 0===e&&(e={}),this.disconnectionPromise?this.disconnectionPromise:(e.code=e.code||1e3,this.statusTransition(o.STATUS_CLOSING,e.force)?(this.emit("disconnecting"),this.disconnectionPromise=new Promise(function(r,n){t.disconnectDeferredResolve=r,t.reconnectTimer&&(clearTimeout(t.reconnectTimer),t.reconnectTimer=void 0),t.ws?(t.stopSendingKeepAlives(),t.logger.log("closing WebSocket "+t.server.wsUri),t.ws.close(e.code,e.reason)):n("Attempted to disconnect but the websocket doesn't exist")}),this.disconnectionPromise):this.status===o.STATUS_CLOSED?Promise.resolve({overrideEvent:!0}):this.connectionPromise?this.connectionPromise.then(function(){return Promise.reject("The websocket did not disconnect")}).catch(function(){return Promise.resolve({overrideEvent:!0})}):Promise.reject("The websocket did not disconnect"))},r.prototype.connectPromise=function(e){var t=this;return void 0===e&&(e={}),this.status!==o.STATUS_CLOSING||e.force?this.connectionPromise?this.connectionPromise:(this.server=this.server||this.getNextWsServer(e.force),this.connectionPromise=new Promise(function(r,n){if((t.status===o.STATUS_OPEN||t.status===o.STATUS_CLOSING)&&!e.force)return t.logger.warn("WebSocket "+t.server.wsUri+" is already connected"),void n("Failed status check - attempted to open a connection but already open/closing");t.connectDeferredResolve=r,t.status=o.STATUS_CONNECTING,t.emit("connecting"),t.logger.log("connecting to WebSocket "+t.server.wsUri),t.disposeWs();try{t.ws=new WebSocket(t.server.wsUri,"sip")}catch(e){return t.ws=null,t.status=o.STATUS_CLOSED,t.onError("error connecting to WebSocket "+t.server.wsUri+":"+e),void n("Failed to create a websocket")}t.ws?(t.connectionTimeout=setTimeout(function(){t.statusTransition(o.STATUS_CLOSED),t.logger.warn("took too long to connect - exceeded time set in configuration.connectionTimeout: "+t.configuration.connectionTimeout+"s"),t.emit("disconnected",{code:1e3}),t.connectionPromise=void 0,n("Connection timeout")},1e3*t.configuration.connectionTimeout),t.boundOnOpen=t.onOpen.bind(t),t.boundOnMessage=t.onMessage.bind(t),t.boundOnClose=t.onClose.bind(t),t.boundOnError=t.onWebsocketError.bind(t),t.ws.addEventListener("open",t.boundOnOpen),t.ws.addEventListener("message",t.boundOnMessage),t.ws.addEventListener("close",t.boundOnClose),t.ws.addEventListener("error",t.boundOnError)):n("Unexpected instance websocket not set")}),this.connectionPromise):Promise.reject("WebSocket "+this.server.wsUri+" is closing")},r.prototype.onMessage=function(e){var t,r=e.data;if(/^(\r\n)+$/.test(r))return this.clearKeepAliveTimeout(),void(!0===this.configuration.traceSip&&this.logger.log("received WebSocket message with CRLF Keep Alive response"));if(r){if("string"!=typeof r){try{t=String.fromCharCode.apply(null,new Uint8Array(r))}catch(e){return void this.logger.warn("received WebSocket binary message failed to be converted into string, message discarded")}!0===this.configuration.traceSip&&this.logger.log("received WebSocket binary message:\n\n"+r+"\n")}else!0===this.configuration.traceSip&&this.logger.log("received WebSocket text message:\n\n"+r+"\n"),t=r;this.emit("message",t)}else this.logger.warn("received empty message, message discarded")},r.prototype.onOpen=function(){if(this.status===o.STATUS_CLOSED){var e=this.ws;return this.disposeWs(),void e.close(1e3)}this.status=o.STATUS_OPEN,this.emit("connected"),this.connectionTimeout&&(clearTimeout(this.connectionTimeout),this.connectionTimeout=void 0),this.logger.log("WebSocket "+this.server.wsUri+" connected"),void 0!==this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.reconnectionAttempts=0,this.disconnectionPromise=void 0,this.disconnectDeferredResolve=void 0,this.startSendingKeepAlives(),this.connectDeferredResolve?this.connectDeferredResolve({overrideEvent:!0}):this.logger.warn("Unexpected websocket.onOpen with no connectDeferredResolve")},r.prototype.onClose=function(e){if(this.logger.log("WebSocket disconnected (code: "+e.code+(e.reason?"| reason: "+e.reason:"")+")"),this.status!==o.STATUS_CLOSING&&(this.logger.warn("WebSocket closed without SIP.js requesting it"),this.emit("transportError")),this.stopSendingKeepAlives(),this.connectionTimeout&&clearTimeout(this.connectionTimeout),this.connectionTimeout=void 0,this.connectionPromise=void 0,this.connectDeferredResolve=void 0,this.disconnectDeferredResolve)return this.disconnectDeferredResolve({overrideEvent:!0}),this.statusTransition(o.STATUS_CLOSED),void(this.disconnectDeferredResolve=void 0);this.status=o.STATUS_CLOSED,this.emit("disconnected",{code:e.code,reason:e.reason}),this.reconnect()},r.prototype.disposeWs=function(){this.ws&&(this.ws.removeEventListener("open",this.boundOnOpen),this.ws.removeEventListener("message",this.boundOnMessage),this.ws.removeEventListener("close",this.boundOnClose),this.ws.removeEventListener("error",this.boundOnError),this.ws=void 0)},r.prototype.onError=function(e){this.logger.warn("Transport error: "+e),this.emit("transportError")},r.prototype.onWebsocketError=function(){this.onError("The Websocket had an error")},r.prototype.reconnect=function(){var e=this;if(this.reconnectionAttempts>0&&this.logger.log("Reconnection attempt "+this.reconnectionAttempts+" failed"),this.noAvailableServers())return this.logger.warn("attempted to get next ws server but there are no available ws servers left"),this.logger.warn("no available ws servers left - going to closed state"),this.status=o.STATUS_CLOSED,this.emit("closed"),void this.resetServerErrorStatus();this.isConnected()&&(this.logger.warn("attempted to reconnect while connected - forcing disconnect"),this.disconnect({force:!0})),this.reconnectionAttempts+=1,this.reconnectionAttempts>this.configuration.maxReconnectionAttempts?(this.logger.warn("maximum reconnection attempts for WebSocket "+this.server.wsUri),this.logger.log("transport "+this.server.wsUri+" failed | connection state set to 'error'"),this.server.isError=!0,this.emit("transportError"),this.noAvailableServers()||(this.server=this.getNextWsServer()),this.reconnectionAttempts=0,this.reconnect()):(this.logger.log("trying to reconnect to WebSocket "+this.server.wsUri+" (reconnection attempt "+this.reconnectionAttempts+")"),this.reconnectTimer=setTimeout(function(){e.connect(),e.reconnectTimer=void 0},1===this.reconnectionAttempts?0:1e3*this.configuration.reconnectionTimeout))},r.prototype.resetServerErrorStatus=function(){for(var e=0,t=this.configuration.wsServers;et[0].weight?t=[i]:i.weight===t[0].weight&&t.push(i))}return t[Math.floor(Math.random()*t.length)]},r.prototype.noAvailableServers=function(){for(var e=0,t=this.configuration.wsServers;e",weight:0,wsUri:"wss://edge.sip.onsip.com",isError:!1}],connectionTimeout:5,maxReconnectionAttempts:3,reconnectionTimeout:4,keepAliveInterval:0,keepAliveDebounce:10,traceSip:!1},r=this.getConfigurationCheck();for(var n in r.mandatory){if(!e.hasOwnProperty(n))throw new a.Exceptions.ConfigurationError(n);var i=e[n];if(void 0===(o=r.mandatory[n](i)))throw new a.Exceptions.ConfigurationError(n,i);t[n]=o}for(var n in r.optional)if(e.hasOwnProperty(n)){var o;if((i=e[n])instanceof Array&&0===i.length||null===i||""===i||void 0===i||"number"==typeof i&&isNaN(i))continue;if(void 0===(o=r.optional[n](i)))throw new a.Exceptions.ConfigurationError(n,i);t[n]=o}var s={};for(var n in t)t.hasOwnProperty(n)&&(s[n]={value:t[n]});var c=Object.defineProperties({},s);for(var n in this.logger.log("configuration parameters after validation:"),t)t.hasOwnProperty(n)&&this.logger.log("\xb7 "+n+": "+JSON.stringify(t[n]));return c},r.prototype.getConfigurationCheck=function(){return{mandatory:{},optional:{wsServers:function(e){if("string"==typeof e)e=[{wsUri:e}];else{if(!(e instanceof Array))return;for(var t=0;t",i.weight||(i.weight=0),i.isError=!1,i.scheme=o.scheme.toUpperCase()}return e},keepAliveInterval:function(e){if(d.Utils.isDecimal(e)){var t=Number(e);if(t>0)return t}},keepAliveDebounce:function(e){if(d.Utils.isDecimal(e)){var t=Number(e);if(t>0)return t}},traceSip:function(e){if("boolean"==typeof e)return e},connectionTimeout:function(e){if(d.Utils.isDecimal(e)){var t=Number(e);if(t>0)return t}},maxReconnectionAttempts:function(e){if(d.Utils.isDecimal(e)){var t=Number(e);if(t>=0)return t}},reconnectionTimeout:function(e){if(d.Utils.isDecimal(e)){var t=Number(e);if(t>0)return t}}}}},r.C=o,r}(u.Transport);t.Transport=h}).call(this,r(24))},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(15);t.ClientContext=n.ClientContext;var i=r(2);t.C=i.C;var o=r(37);t.DigestAuthentication=o.DigestAuthentication;var s=r(3);t.DialogStatus=s.DialogStatus,t.SessionStatus=s.SessionStatus,t.TypeStrings=s.TypeStrings,t.UAStatus=s.UAStatus;var a=r(7);t.Exceptions=a.Exceptions;var c=r(11);t.Grammar=c.Grammar;var u=r(40);t.LoggerFactory=u.LoggerFactory;var d=r(18);t.NameAddrHeader=d.NameAddrHeader;var h=r(41);t.Parser=h.Parser;var p=r(42);t.PublishContext=p.PublishContext;var l=r(27);t.ReferClientContext=l.ReferClientContext,t.ReferServerContext=l.ReferServerContext;var f=r(44);t.RegisterContext=f.RegisterContext;var g=r(22);t.ServerContext=g.ServerContext;var v=r(45);t.InviteClientContext=v.InviteClientContext,t.InviteServerContext=v.InviteServerContext,t.Session=v.Session;var m=r(8);t.IncomingRequest=m.IncomingRequest,t.IncomingResponse=m.IncomingResponse,t.OutgoingRequest=m.OutgoingRequest;var y=r(46);t.Subscription=y.Subscription;var S=r(12);t.Timers=S.Timers;var T=r(1),C={InviteClientTransaction:T.InviteClientTransaction,InviteServerTransaction:T.InviteServerTransaction,NonInviteClientTransaction:T.NonInviteClientTransaction,NonInviteServerTransaction:T.NonInviteServerTransaction};t.Transactions=C;var b=r(47);t.Transport=b.Transport;var _=r(48);t.UA=_.UA;var A=r(19);t.URI=A.URI;var w=r(5);t.Utils=w.Utils;var E=r(115);t.Web=E;var R=r(36),I=R.title;t.name=I;var O=R.version;t.version=O},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(18),s=r(19),a=function(e){function t(r,n,i,o){var s=e.call(this)||this;return s.message=r,s.expected=n,s.found=i,s.location=o,s.name="SyntaxError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(s,t),s}return i(t,e),t.buildMessage=function(e,t){function r(e){return e.charCodeAt(0).toString(16).toUpperCase()}function n(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,function(e){return"\\x0"+r(e)}).replace(/[\x10-\x1F\x7F-\x9F]/g,function(e){return"\\x"+r(e)})}function i(e){return e.replace(/\\/g,"\\\\").replace(/\]/g,"\\]").replace(/\^/g,"\\^").replace(/-/g,"\\-").replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,function(e){return"\\x0"+r(e)}).replace(/[\x10-\x1F\x7F-\x9F]/g,function(e){return"\\x"+r(e)})}function o(e){switch(e.type){case"literal":return'"'+n(e.text)+'"';case"class":var t=e.parts.map(function(e){return Array.isArray(e)?i(e[0])+"-"+i(e[1]):i(e)});return"["+(e.inverted?"^":"")+t+"]";case"any":return"any character";case"end":return"end of input";case"other":return e.description}}return"Expected "+function(e){var t,r,n=e.map(o);if(n.sort(),n.length>0){for(t=1,r=1;t",Ae=ws(">",!1),we="\\",Ee=ws("\\",!1),Re="[",Ie=ws("[",!1),Oe="]",xe=ws("]",!1),Pe="{",Ne=ws("{",!1),De="}",Ue=ws("}",!1),He=function(){return"*"},ke=function(){return"/"},Me=function(){return"="},qe=function(){return">"},je=function(){return"<"},Le=function(){return","},Fe=function(){return";"},Be=function(){return":"},Ge=function(){return'"'},We=(Es([["!","'"]],!1,!1),Es([["*","["]],!1,!1),/^[\]-~]/),ze=Es([["]","~"]],!1,!1),Ke=function(e){return e},Ve=/^[#-[]/,Ye=Es([["#","["]],!1,!1),$e=/^[\0-\t]/,Xe=Es([["\0","\t"]],!1,!1),Je=/^[\x0B-\f]/,Qe=Es([["\v","\f"]],!1,!1),Ze=/^[\x0E-\x7F]/,et=Es([["\x0e","\x7f"]],!1,!1),tt=function(){(t=t||{data:{}}).data.uri=new s.URI(t.data.scheme,t.data.user,t.data.host,t.data.port),delete t.data.scheme,delete t.data.user,delete t.data.host,delete t.data.host_type,delete t.data.port},rt=function(){(t=t||{data:{}}).data.uri=new s.URI(t.data.scheme,t.data.user,t.data.host,t.data.port,t.data.uri_params,t.data.uri_headers),delete t.data.scheme,delete t.data.user,delete t.data.host,delete t.data.host_type,delete t.data.port,delete t.data.uri_params,"SIP_URI"===t.startRule&&(t.data=t.data.uri)},nt="sips",it=ws("sips",!0),ot="sip",st=ws("sip",!0),at=function(e){(t=t||{data:{}}).data.scheme=e},ct=function(){(t=t||{data:{}}).data.user=decodeURIComponent(_s().slice(0,-1))},ut=function(){(t=t||{data:{}}).data.password=_s()},dt=function(){return(t=t||{data:{}}).data.host=_s(),t.data.host},ht=function(){return(t=t||{data:{}}).data.host_type="domain",_s()},pt=/^[a-zA-Z0-9_\-]/,lt=Es([["a","z"],["A","Z"],["0","9"],"_","-"],!1,!1),ft=/^[a-zA-Z0-9\-]/,gt=Es([["a","z"],["A","Z"],["0","9"],"-"],!1,!1),vt=function(){return(t=t||{data:{}}).data.host_type="IPv6",_s()},mt="::",yt=ws("::",!1),St=function(){return(t=t||{data:{}}).data.host_type="IPv6",_s()},Tt=function(){return(t=t||{data:{}}).data.host_type="IPv4",_s()},Ct="25",bt=ws("25",!1),_t=/^[0-5]/,At=Es([["0","5"]],!1,!1),wt="2",Et=ws("2",!1),Rt=/^[0-4]/,It=Es([["0","4"]],!1,!1),Ot="1",xt=ws("1",!1),Pt=/^[1-9]/,Nt=Es([["1","9"]],!1,!1),Dt=function(e){return t=t||{data:{}},e=parseInt(e.join("")),t.data.port=e,e},Ut="transport=",Ht=ws("transport=",!0),kt="udp",Mt=ws("udp",!0),qt="tcp",jt=ws("tcp",!0),Lt="sctp",Ft=ws("sctp",!0),Bt="tls",Gt=ws("tls",!0),Wt=function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.transport=e.toLowerCase()},zt="user=",Kt=ws("user=",!0),Vt="phone",Yt=ws("phone",!0),$t="ip",Xt=ws("ip",!0),Jt=function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.user=e.toLowerCase()},Qt="method=",Zt=ws("method=",!0),er=function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.method=e},tr="ttl=",rr=ws("ttl=",!0),nr=function(e){(t=t||{data:{}}).data.params||(t.data.params={}),t.data.params.ttl=e},ir="maddr=",or=ws("maddr=",!0),sr=function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.maddr=e},ar="lr",cr=ws("lr",!0),ur=function(){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.lr=void 0},dr=function(e,r){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),r=null===r?void 0:r[1],t.data.uri_params[e.toLowerCase()]=r},hr=function(e,r){e=e.join("").toLowerCase(),r=r.join(""),(t=t||{data:{}}).data.uri_headers||(t.data.uri_headers={}),t.data.uri_headers[e]?t.data.uri_headers[e].push(r):t.data.uri_headers[e]=[r]},pr=function(){"Refer_To"===(t=t||{data:{}}).startRule&&(t.data.uri=new s.URI(t.data.scheme,t.data.user,t.data.host,t.data.port,t.data.uri_params,t.data.uri_headers),delete t.data.scheme,delete t.data.user,delete t.data.host,delete t.data.host_type,delete t.data.port,delete t.data.uri_params)},lr="//",fr=ws("//",!1),gr=function(){(t=t||{data:{}}).data.scheme=_s()},vr=ws("SIP",!0),mr=function(){(t=t||{data:{}}).data.sip_version=_s()},yr="INVITE",Sr=ws("INVITE",!1),Tr="ACK",Cr=ws("ACK",!1),br=(ws("VXACH",!1),"OPTIONS"),_r=ws("OPTIONS",!1),Ar="BYE",wr=ws("BYE",!1),Er="CANCEL",Rr=ws("CANCEL",!1),Ir="REGISTER",Or=ws("REGISTER",!1),xr="SUBSCRIBE",Pr=ws("SUBSCRIBE",!1),Nr="NOTIFY",Dr=ws("NOTIFY",!1),Ur="REFER",Hr=ws("REFER",!1),kr="PUBLISH",Mr=ws("PUBLISH",!1),qr=function(){return(t=t||{data:{}}).data.method=_s(),t.data.method},jr=function(e){(t=t||{data:{}}).data.status_code=parseInt(e.join(""))},Lr=function(){(t=t||{data:{}}).data.reason_phrase=_s()},Fr=function(){(t=t||{data:{}}).data=_s()},Br=function(){var e,r;for(r=(t=t||{data:{}}).data.multi_header.length,e=0;eTs&&(Ts=ms,Cs=[]),Cs.push(e))}function xs(e,t,r){return new a(a.buildMessage(e,t),e,t,r)}function Ps(){var t;return e.substr(ms,2)===u?(t=u,ms+=2):(t=n,0===bs&&Os(d)),t}function Ns(){var t;return h.test(e.charAt(ms))?(t=e.charAt(ms),ms++):(t=n,0===bs&&Os(p)),t}function Ds(){var t;return l.test(e.charAt(ms))?(t=e.charAt(ms),ms++):(t=n,0===bs&&Os(f)),t}function Us(){var t;return g.test(e.charAt(ms))?(t=e.charAt(ms),ms++):(t=n,0===bs&&Os(v)),t}function Hs(){var e;return(e=qs())===n&&(e=js()),e}function ks(){var t;return m.test(e.charAt(ms))?(t=e.charAt(ms),ms++):(t=n,0===bs&&Os(y)),t}function Ms(){var t;return S.test(e.charAt(ms))?(t=e.charAt(ms),ms++):(t=n,0===bs&&Os(T)),t}function qs(){var t;return 32===e.charCodeAt(ms)?(t=C,ms++):(t=n,0===bs&&Os(b)),t}function js(){var t;return 9===e.charCodeAt(ms)?(t=_,ms++):(t=n,0===bs&&Os(A)),t}function Ls(){var t;return w.test(e.charAt(ms))?(t=e.charAt(ms),ms++):(t=n,0===bs&&Os(E)),t}function Fs(){var t;return 59===e.charCodeAt(ms)?(t=R,ms++):(t=n,0===bs&&Os(I)),t===n&&(47===e.charCodeAt(ms)?(t=O,ms++):(t=n,0===bs&&Os(x)),t===n&&(63===e.charCodeAt(ms)?(t=P,ms++):(t=n,0===bs&&Os(N)),t===n&&(58===e.charCodeAt(ms)?(t=D,ms++):(t=n,0===bs&&Os(U)),t===n&&(64===e.charCodeAt(ms)?(t=H,ms++):(t=n,0===bs&&Os(k)),t===n&&(38===e.charCodeAt(ms)?(t=M,ms++):(t=n,0===bs&&Os(q)),t===n&&(61===e.charCodeAt(ms)?(t=j,ms++):(t=n,0===bs&&Os(L)),t===n&&(43===e.charCodeAt(ms)?(t=F,ms++):(t=n,0===bs&&Os(B)),t===n&&(36===e.charCodeAt(ms)?(t=G,ms++):(t=n,0===bs&&Os(W)),t===n&&(44===e.charCodeAt(ms)?(t=z,ms++):(t=n,0===bs&&Os(K))))))))))),t}function Bs(){var e;return(e=Ls())===n&&(e=Gs()),e}function Gs(){var t;return 45===e.charCodeAt(ms)?(t=V,ms++):(t=n,0===bs&&Os(Y)),t===n&&(95===e.charCodeAt(ms)?(t=$,ms++):(t=n,0===bs&&Os(X)),t===n&&(46===e.charCodeAt(ms)?(t=J,ms++):(t=n,0===bs&&Os(Q)),t===n&&(33===e.charCodeAt(ms)?(t=Z,ms++):(t=n,0===bs&&Os(ee)),t===n&&(126===e.charCodeAt(ms)?(t=te,ms++):(t=n,0===bs&&Os(re)),t===n&&(42===e.charCodeAt(ms)?(t=ne,ms++):(t=n,0===bs&&Os(ie)),t===n&&(39===e.charCodeAt(ms)?(t=oe,ms++):(t=n,0===bs&&Os(se)),t===n&&(40===e.charCodeAt(ms)?(t=ae,ms++):(t=n,0===bs&&Os(ce)),t===n&&(41===e.charCodeAt(ms)?(t=ue,ms++):(t=n,0===bs&&Os(de)))))))))),t}function Ws(){var t,r,i,o,s;return t=ms,r=ms,37===e.charCodeAt(ms)?(i=he,ms++):(i=n,0===bs&&Os(pe)),i!==n&&(o=Us())!==n&&(s=Us())!==n?r=i=[i,o,s]:(ms=r,r=n),t=r!==n?e.substring(t,ms):r}function zs(){var e,t,r,i;for(e=ms,t=ms,r=[],i=Hs();i!==n;)r.push(i),i=Hs();if(r!==n&&(i=Ps())!==n?t=r=[r,i]:(ms=t,t=n),t===n&&(t=null),t!==n){if(r=[],(i=Hs())!==n)for(;i!==n;)r.push(i),i=Hs();else r=n;r!==n?(ys=e,e=t=le()):(ms=e,e=n)}else ms=e,e=n;return e}function Ks(){var e;return(e=zs())===n&&(e=null),e}function Vs(){var t,r,i;for(t=ms,r=[],(i=qs())===n&&(i=js());i!==n;)r.push(i),(i=qs())===n&&(i=js());return r!==n?(58===e.charCodeAt(ms)?(i=D,ms++):(i=n,0===bs&&Os(U)),i!==n&&Ks()!==n?(ys=t,t=r=fe()):(ms=t,t=n)):(ms=t,t=n),t}function Ys(){var t;return ge.test(e.charAt(ms))?(t=e.charAt(ms),ms++):(t=n,0===bs&&Os(ve)),t}function $s(){var t;return me.test(e.charAt(ms))?(t=e.charAt(ms),ms++):(t=n,0===bs&&Os(ye)),t}function Xs(){var t,r,i;if(t=ms,r=[],(i=Ls())===n&&(45===e.charCodeAt(ms)?(i=V,ms++):(i=n,0===bs&&Os(Y)),i===n&&(46===e.charCodeAt(ms)?(i=J,ms++):(i=n,0===bs&&Os(Q)),i===n&&(33===e.charCodeAt(ms)?(i=Z,ms++):(i=n,0===bs&&Os(ee)),i===n&&(37===e.charCodeAt(ms)?(i=he,ms++):(i=n,0===bs&&Os(pe)),i===n&&(42===e.charCodeAt(ms)?(i=ne,ms++):(i=n,0===bs&&Os(ie)),i===n&&(95===e.charCodeAt(ms)?(i=$,ms++):(i=n,0===bs&&Os(X)),i===n&&(43===e.charCodeAt(ms)?(i=F,ms++):(i=n,0===bs&&Os(B)),i===n&&(96===e.charCodeAt(ms)?(i=Se,ms++):(i=n,0===bs&&Os(Te)),i===n&&(39===e.charCodeAt(ms)?(i=oe,ms++):(i=n,0===bs&&Os(se)),i===n&&(126===e.charCodeAt(ms)?(i=te,ms++):(i=n,0===bs&&Os(re)))))))))))),i!==n)for(;i!==n;)r.push(i),(i=Ls())===n&&(45===e.charCodeAt(ms)?(i=V,ms++):(i=n,0===bs&&Os(Y)),i===n&&(46===e.charCodeAt(ms)?(i=J,ms++):(i=n,0===bs&&Os(Q)),i===n&&(33===e.charCodeAt(ms)?(i=Z,ms++):(i=n,0===bs&&Os(ee)),i===n&&(37===e.charCodeAt(ms)?(i=he,ms++):(i=n,0===bs&&Os(pe)),i===n&&(42===e.charCodeAt(ms)?(i=ne,ms++):(i=n,0===bs&&Os(ie)),i===n&&(95===e.charCodeAt(ms)?(i=$,ms++):(i=n,0===bs&&Os(X)),i===n&&(43===e.charCodeAt(ms)?(i=F,ms++):(i=n,0===bs&&Os(B)),i===n&&(96===e.charCodeAt(ms)?(i=Se,ms++):(i=n,0===bs&&Os(Te)),i===n&&(39===e.charCodeAt(ms)?(i=oe,ms++):(i=n,0===bs&&Os(se)),i===n&&(126===e.charCodeAt(ms)?(i=te,ms++):(i=n,0===bs&&Os(re))))))))))));else r=n;return t=r!==n?e.substring(t,ms):r}function Js(){var t,r,i;if(t=ms,r=[],(i=Ls())===n&&(45===e.charCodeAt(ms)?(i=V,ms++):(i=n,0===bs&&Os(Y)),i===n&&(33===e.charCodeAt(ms)?(i=Z,ms++):(i=n,0===bs&&Os(ee)),i===n&&(37===e.charCodeAt(ms)?(i=he,ms++):(i=n,0===bs&&Os(pe)),i===n&&(42===e.charCodeAt(ms)?(i=ne,ms++):(i=n,0===bs&&Os(ie)),i===n&&(95===e.charCodeAt(ms)?(i=$,ms++):(i=n,0===bs&&Os(X)),i===n&&(43===e.charCodeAt(ms)?(i=F,ms++):(i=n,0===bs&&Os(B)),i===n&&(96===e.charCodeAt(ms)?(i=Se,ms++):(i=n,0===bs&&Os(Te)),i===n&&(39===e.charCodeAt(ms)?(i=oe,ms++):(i=n,0===bs&&Os(se)),i===n&&(126===e.charCodeAt(ms)?(i=te,ms++):(i=n,0===bs&&Os(re))))))))))),i!==n)for(;i!==n;)r.push(i),(i=Ls())===n&&(45===e.charCodeAt(ms)?(i=V,ms++):(i=n,0===bs&&Os(Y)),i===n&&(33===e.charCodeAt(ms)?(i=Z,ms++):(i=n,0===bs&&Os(ee)),i===n&&(37===e.charCodeAt(ms)?(i=he,ms++):(i=n,0===bs&&Os(pe)),i===n&&(42===e.charCodeAt(ms)?(i=ne,ms++):(i=n,0===bs&&Os(ie)),i===n&&(95===e.charCodeAt(ms)?(i=$,ms++):(i=n,0===bs&&Os(X)),i===n&&(43===e.charCodeAt(ms)?(i=F,ms++):(i=n,0===bs&&Os(B)),i===n&&(96===e.charCodeAt(ms)?(i=Se,ms++):(i=n,0===bs&&Os(Te)),i===n&&(39===e.charCodeAt(ms)?(i=oe,ms++):(i=n,0===bs&&Os(se)),i===n&&(126===e.charCodeAt(ms)?(i=te,ms++):(i=n,0===bs&&Os(re)))))))))));else r=n;return t=r!==n?e.substring(t,ms):r}function Qs(){var t,r,i;if(t=ms,r=[],(i=Ls())===n&&(45===e.charCodeAt(ms)?(i=V,ms++):(i=n,0===bs&&Os(Y)),i===n&&(46===e.charCodeAt(ms)?(i=J,ms++):(i=n,0===bs&&Os(Q)),i===n&&(33===e.charCodeAt(ms)?(i=Z,ms++):(i=n,0===bs&&Os(ee)),i===n&&(37===e.charCodeAt(ms)?(i=he,ms++):(i=n,0===bs&&Os(pe)),i===n&&(42===e.charCodeAt(ms)?(i=ne,ms++):(i=n,0===bs&&Os(ie)),i===n&&(95===e.charCodeAt(ms)?(i=$,ms++):(i=n,0===bs&&Os(X)),i===n&&(43===e.charCodeAt(ms)?(i=F,ms++):(i=n,0===bs&&Os(B)),i===n&&(96===e.charCodeAt(ms)?(i=Se,ms++):(i=n,0===bs&&Os(Te)),i===n&&(39===e.charCodeAt(ms)?(i=oe,ms++):(i=n,0===bs&&Os(se)),i===n&&(126===e.charCodeAt(ms)?(i=te,ms++):(i=n,0===bs&&Os(re)),i===n&&(40===e.charCodeAt(ms)?(i=ae,ms++):(i=n,0===bs&&Os(ce)),i===n&&(41===e.charCodeAt(ms)?(i=ue,ms++):(i=n,0===bs&&Os(de)),i===n&&(60===e.charCodeAt(ms)?(i=Ce,ms++):(i=n,0===bs&&Os(be)),i===n&&(62===e.charCodeAt(ms)?(i=_e,ms++):(i=n,0===bs&&Os(Ae)),i===n&&(58===e.charCodeAt(ms)?(i=D,ms++):(i=n,0===bs&&Os(U)),i===n&&(92===e.charCodeAt(ms)?(i=we,ms++):(i=n,0===bs&&Os(Ee)),i===n&&(i=Ms())===n&&(47===e.charCodeAt(ms)?(i=O,ms++):(i=n,0===bs&&Os(x)),i===n&&(91===e.charCodeAt(ms)?(i=Re,ms++):(i=n,0===bs&&Os(Ie)),i===n&&(93===e.charCodeAt(ms)?(i=Oe,ms++):(i=n,0===bs&&Os(xe)),i===n&&(63===e.charCodeAt(ms)?(i=P,ms++):(i=n,0===bs&&Os(N)),i===n&&(123===e.charCodeAt(ms)?(i=Pe,ms++):(i=n,0===bs&&Os(Ne)),i===n&&(125===e.charCodeAt(ms)?(i=De,ms++):(i=n,0===bs&&Os(Ue)))))))))))))))))))))))),i!==n)for(;i!==n;)r.push(i),(i=Ls())===n&&(45===e.charCodeAt(ms)?(i=V,ms++):(i=n,0===bs&&Os(Y)),i===n&&(46===e.charCodeAt(ms)?(i=J,ms++):(i=n,0===bs&&Os(Q)),i===n&&(33===e.charCodeAt(ms)?(i=Z,ms++):(i=n,0===bs&&Os(ee)),i===n&&(37===e.charCodeAt(ms)?(i=he,ms++):(i=n,0===bs&&Os(pe)),i===n&&(42===e.charCodeAt(ms)?(i=ne,ms++):(i=n,0===bs&&Os(ie)),i===n&&(95===e.charCodeAt(ms)?(i=$,ms++):(i=n,0===bs&&Os(X)),i===n&&(43===e.charCodeAt(ms)?(i=F,ms++):(i=n,0===bs&&Os(B)),i===n&&(96===e.charCodeAt(ms)?(i=Se,ms++):(i=n,0===bs&&Os(Te)),i===n&&(39===e.charCodeAt(ms)?(i=oe,ms++):(i=n,0===bs&&Os(se)),i===n&&(126===e.charCodeAt(ms)?(i=te,ms++):(i=n,0===bs&&Os(re)),i===n&&(40===e.charCodeAt(ms)?(i=ae,ms++):(i=n,0===bs&&Os(ce)),i===n&&(41===e.charCodeAt(ms)?(i=ue,ms++):(i=n,0===bs&&Os(de)),i===n&&(60===e.charCodeAt(ms)?(i=Ce,ms++):(i=n,0===bs&&Os(be)),i===n&&(62===e.charCodeAt(ms)?(i=_e,ms++):(i=n,0===bs&&Os(Ae)),i===n&&(58===e.charCodeAt(ms)?(i=D,ms++):(i=n,0===bs&&Os(U)),i===n&&(92===e.charCodeAt(ms)?(i=we,ms++):(i=n,0===bs&&Os(Ee)),i===n&&(i=Ms())===n&&(47===e.charCodeAt(ms)?(i=O,ms++):(i=n,0===bs&&Os(x)),i===n&&(91===e.charCodeAt(ms)?(i=Re,ms++):(i=n,0===bs&&Os(Ie)),i===n&&(93===e.charCodeAt(ms)?(i=Oe,ms++):(i=n,0===bs&&Os(xe)),i===n&&(63===e.charCodeAt(ms)?(i=P,ms++):(i=n,0===bs&&Os(N)),i===n&&(123===e.charCodeAt(ms)?(i=Pe,ms++):(i=n,0===bs&&Os(Ne)),i===n&&(125===e.charCodeAt(ms)?(i=De,ms++):(i=n,0===bs&&Os(Ue))))))))))))))))))))))));else r=n;return t=r!==n?e.substring(t,ms):r}function Zs(){var t,r;return t=ms,Ks()!==n?(47===e.charCodeAt(ms)?(r=O,ms++):(r=n,0===bs&&Os(x)),r!==n&&Ks()!==n?(ys=t,t=ke()):(ms=t,t=n)):(ms=t,t=n),t}function ea(){var t,r;return t=ms,Ks()!==n?(61===e.charCodeAt(ms)?(r=j,ms++):(r=n,0===bs&&Os(L)),r!==n&&Ks()!==n?(ys=t,t=Me()):(ms=t,t=n)):(ms=t,t=n),t}function ta(){var t,r;return t=ms,62===e.charCodeAt(ms)?(r=_e,ms++):(r=n,0===bs&&Os(Ae)),r!==n&&Ks()!==n?(ys=t,t=r=qe()):(ms=t,t=n),t}function ra(){var t,r;return t=ms,Ks()!==n?(60===e.charCodeAt(ms)?(r=Ce,ms++):(r=n,0===bs&&Os(be)),r!==n?(ys=t,t=je()):(ms=t,t=n)):(ms=t,t=n),t}function na(){var t,r;return t=ms,Ks()!==n?(44===e.charCodeAt(ms)?(r=z,ms++):(r=n,0===bs&&Os(K)),r!==n&&Ks()!==n?(ys=t,t=Le()):(ms=t,t=n)):(ms=t,t=n),t}function ia(){var t,r;return t=ms,Ks()!==n?(59===e.charCodeAt(ms)?(r=R,ms++):(r=n,0===bs&&Os(I)),r!==n&&Ks()!==n?(ys=t,t=Fe()):(ms=t,t=n)):(ms=t,t=n),t}function oa(){var e;return e=ms,Ks()!==n&&Ms()!==n?(ys=e,e=Ge()):(ms=e,e=n),e}function sa(){var e;return e=ms,Ms()!==n&&Ks()!==n?(ys=e,e=Ge()):(ms=e,e=n),e}function aa(){var t,r,i,o,s,a;if(t=ms,r=ms,(i=Ks())!==n)if((o=Ms())!==n){for(s=[],(a=ua())===n&&(a=da());a!==n;)s.push(a),(a=ua())===n&&(a=da());s!==n&&(a=Ms())!==n?r=i=[i,o,s,a]:(ms=r,r=n)}else ms=r,r=n;else ms=r,r=n;return t=r!==n?e.substring(t,ms):r}function ca(){var t,r,i,o;if(t=ms,Ks()!==n)if(Ms()!==n){for(r=ms,i=[],(o=ua())===n&&(o=da());o!==n;)i.push(o),(o=ua())===n&&(o=da());(r=i!==n?e.substring(r,ms):i)!==n&&(i=Ms())!==n?(ys=t,t=Ke(r)):(ms=t,t=n)}else ms=t,t=n;else ms=t,t=n;return t}function ua(){var t;return(t=zs())===n&&(33===e.charCodeAt(ms)?(t=Z,ms++):(t=n,0===bs&&Os(ee)),t===n&&(Ve.test(e.charAt(ms))?(t=e.charAt(ms),ms++):(t=n,0===bs&&Os(Ye)),t===n&&(We.test(e.charAt(ms))?(t=e.charAt(ms),ms++):(t=n,0===bs&&Os(ze)),t===n&&(t=Ys())))),t}function da(){var t,r,i;return t=ms,92===e.charCodeAt(ms)?(r=we,ms++):(r=n,0===bs&&Os(Ee)),r!==n?($e.test(e.charAt(ms))?(i=e.charAt(ms),ms++):(i=n,0===bs&&Os(Xe)),i===n&&(Je.test(e.charAt(ms))?(i=e.charAt(ms),ms++):(i=n,0===bs&&Os(Qe)),i===n&&(Ze.test(e.charAt(ms))?(i=e.charAt(ms),ms++):(i=n,0===bs&&Os(et)))),i!==n?t=r=[r,i]:(ms=t,t=n)):(ms=t,t=n),t}function ha(){var t,r,i;return t=ms,la()!==n?(58===e.charCodeAt(ms)?(r=D,ms++):(r=n,0===bs&&Os(U)),r!==n?((i=fa())===n&&(i=null),i!==n&&va()!==n?(ys=t,t=tt()):(ms=t,t=n)):(ms=t,t=n)):(ms=t,t=n),t}function pa(){var t,r,i,o;return t=ms,la()!==n?(58===e.charCodeAt(ms)?(r=D,ms++):(r=n,0===bs&&Os(U)),r!==n?((i=fa())===n&&(i=null),i!==n&&va()!==n&&function(){var t,r,i,o;for(t=[],r=ms,59===e.charCodeAt(ms)?(i=R,ms++):(i=n,0===bs&&Os(I)),i!==n&&(o=Ra())!==n?r=i=[i,o]:(ms=r,r=n);r!==n;)t.push(r),r=ms,59===e.charCodeAt(ms)?(i=R,ms++):(i=n,0===bs&&Os(I)),i!==n&&(o=Ra())!==n?r=i=[i,o]:(ms=r,r=n);return t}()!==n?((o=function(){var t,r,i,o,s,a,c;if(t=ms,63===e.charCodeAt(ms)?(r=P,ms++):(r=n,0===bs&&Os(N)),r!==n)if((i=Oa())!==n){for(o=[],s=ms,38===e.charCodeAt(ms)?(a=M,ms++):(a=n,0===bs&&Os(q)),a!==n&&(c=Oa())!==n?s=a=[a,c]:(ms=s,s=n);s!==n;)o.push(s),s=ms,38===e.charCodeAt(ms)?(a=M,ms++):(a=n,0===bs&&Os(q)),a!==n&&(c=Oa())!==n?s=a=[a,c]:(ms=s,s=n);o!==n?t=r=[r,i,o]:(ms=t,t=n)}else ms=t,t=n;else ms=t,t=n;return t}())===n&&(o=null),o!==n?(ys=t,t=rt()):(ms=t,t=n)):(ms=t,t=n)):(ms=t,t=n)):(ms=t,t=n),t}function la(){var t,r;return t=ms,e.substr(ms,4).toLowerCase()===nt?(r=e.substr(ms,4),ms+=4):(r=n,0===bs&&Os(it)),r===n&&(e.substr(ms,3).toLowerCase()===ot?(r=e.substr(ms,3),ms+=3):(r=n,0===bs&&Os(st))),r!==n&&(ys=t,r=at(r)),t=r}function fa(){var t,r,i,o;return t=ms,function(){var e,t;if(e=[],(t=Bs())===n&&(t=Ws())===n&&(t=ga()),t!==n)for(;t!==n;)e.push(t),(t=Bs())===n&&(t=Ws())===n&&(t=ga());else e=n;return e}()!==n?(r=ms,58===e.charCodeAt(ms)?(i=D,ms++):(i=n,0===bs&&Os(U)),i!==n&&(o=function(){var t,r,i;for(t=ms,r=[],(i=Bs())===n&&(i=Ws())===n&&(38===e.charCodeAt(ms)?(i=M,ms++):(i=n,0===bs&&Os(q)),i===n&&(61===e.charCodeAt(ms)?(i=j,ms++):(i=n,0===bs&&Os(L)),i===n&&(43===e.charCodeAt(ms)?(i=F,ms++):(i=n,0===bs&&Os(B)),i===n&&(36===e.charCodeAt(ms)?(i=G,ms++):(i=n,0===bs&&Os(W)),i===n&&(44===e.charCodeAt(ms)?(i=z,ms++):(i=n,0===bs&&Os(K)))))));i!==n;)r.push(i),(i=Bs())===n&&(i=Ws())===n&&(38===e.charCodeAt(ms)?(i=M,ms++):(i=n,0===bs&&Os(q)),i===n&&(61===e.charCodeAt(ms)?(i=j,ms++):(i=n,0===bs&&Os(L)),i===n&&(43===e.charCodeAt(ms)?(i=F,ms++):(i=n,0===bs&&Os(B)),i===n&&(36===e.charCodeAt(ms)?(i=G,ms++):(i=n,0===bs&&Os(W)),i===n&&(44===e.charCodeAt(ms)?(i=z,ms++):(i=n,0===bs&&Os(K)))))));return r!==n&&(ys=t,r=ut()),t=r}())!==n?r=i=[i,o]:(ms=r,r=n),r===n&&(r=null),r!==n?(64===e.charCodeAt(ms)?(i=H,ms++):(i=n,0===bs&&Os(k)),i!==n?(ys=t,t=ct()):(ms=t,t=n)):(ms=t,t=n)):(ms=t,t=n),t}function ga(){var t;return 38===e.charCodeAt(ms)?(t=M,ms++):(t=n,0===bs&&Os(q)),t===n&&(61===e.charCodeAt(ms)?(t=j,ms++):(t=n,0===bs&&Os(L)),t===n&&(43===e.charCodeAt(ms)?(t=F,ms++):(t=n,0===bs&&Os(B)),t===n&&(36===e.charCodeAt(ms)?(t=G,ms++):(t=n,0===bs&&Os(W)),t===n&&(44===e.charCodeAt(ms)?(t=z,ms++):(t=n,0===bs&&Os(K)),t===n&&(59===e.charCodeAt(ms)?(t=R,ms++):(t=n,0===bs&&Os(I)),t===n&&(63===e.charCodeAt(ms)?(t=P,ms++):(t=n,0===bs&&Os(N)),t===n&&(47===e.charCodeAt(ms)?(t=O,ms++):(t=n,0===bs&&Os(x))))))))),t}function va(){var t,r,i,o,s;return t=ms,(r=ma())!==n?(i=ms,58===e.charCodeAt(ms)?(o=D,ms++):(o=n,0===bs&&Os(U)),o!==n&&(s=Ea())!==n?i=o=[o,s]:(ms=i,i=n),i===n&&(i=null),i!==n?t=r=[r,i]:(ms=t,t=n)):(ms=t,t=n),t}function ma(){var e,t;return e=ms,(t=ya())===n&&(t=Aa())===n&&(t=Ta()),t!==n&&(ys=e,t=dt()),e=t}function ya(){var t,r,i,o,s;for(t=ms,r=[],i=ms,(o=Sa())!==n?(46===e.charCodeAt(ms)?(s=J,ms++):(s=n,0===bs&&Os(Q)),s!==n?i=o=[o,s]:(ms=i,i=n)):(ms=i,i=n);i!==n;)r.push(i),i=ms,(o=Sa())!==n?(46===e.charCodeAt(ms)?(s=J,ms++):(s=n,0===bs&&Os(Q)),s!==n?i=o=[o,s]:(ms=i,i=n)):(ms=i,i=n);return r!==n&&(i=function(){var t,r,i,o;if(t=ms,l.test(e.charAt(ms))?(r=e.charAt(ms),ms++):(r=n,0===bs&&Os(f)),r!==n){for(i=[],ft.test(e.charAt(ms))?(o=e.charAt(ms),ms++):(o=n,0===bs&&Os(gt));o!==n;)i.push(o),ft.test(e.charAt(ms))?(o=e.charAt(ms),ms++):(o=n,0===bs&&Os(gt));i!==n?t=r=[r,i]:(ms=t,t=n)}else ms=t,t=n;return t}())!==n?(46===e.charCodeAt(ms)?(o=J,ms++):(o=n,0===bs&&Os(Q)),o===n&&(o=null),o!==n?(ys=t,t=r=ht()):(ms=t,t=n)):(ms=t,t=n),t}function Sa(){var t,r;if(t=[],pt.test(e.charAt(ms))?(r=e.charAt(ms),ms++):(r=n,0===bs&&Os(lt)),r!==n)for(;r!==n;)t.push(r),pt.test(e.charAt(ms))?(r=e.charAt(ms),ms++):(r=n,0===bs&&Os(lt));else t=n;return t}function Ta(){var t,r,i;return t=ms,91===e.charCodeAt(ms)?(r=Re,ms++):(r=n,0===bs&&Os(Ie)),r!==n&&Ca()!==n?(93===e.charCodeAt(ms)?(i=Oe,ms++):(i=n,0===bs&&Os(xe)),i!==n?(ys=t,t=r=vt()):(ms=t,t=n)):(ms=t,t=n),t}function Ca(){var t,r,i,o,s,a,c,u,d,h,p,l,f,g,v;return t=ms,r=ms,(i=ba())!==n?(58===e.charCodeAt(ms)?(o=D,ms++):(o=n,0===bs&&Os(U)),o!==n&&(s=ba())!==n?(58===e.charCodeAt(ms)?(a=D,ms++):(a=n,0===bs&&Os(U)),a!==n&&(c=ba())!==n?(58===e.charCodeAt(ms)?(u=D,ms++):(u=n,0===bs&&Os(U)),u!==n&&(d=ba())!==n?(58===e.charCodeAt(ms)?(h=D,ms++):(h=n,0===bs&&Os(U)),h!==n&&(p=ba())!==n?(58===e.charCodeAt(ms)?(l=D,ms++):(l=n,0===bs&&Os(U)),l!==n&&(f=ba())!==n?(58===e.charCodeAt(ms)?(g=D,ms++):(g=n,0===bs&&Os(U)),g!==n&&(v=_a())!==n?r=i=[i,o,s,a,c,u,d,h,p,l,f,g,v]:(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n),r===n&&(r=ms,e.substr(ms,2)===mt?(i=mt,ms+=2):(i=n,0===bs&&Os(yt)),i!==n&&(o=ba())!==n?(58===e.charCodeAt(ms)?(s=D,ms++):(s=n,0===bs&&Os(U)),s!==n&&(a=ba())!==n?(58===e.charCodeAt(ms)?(c=D,ms++):(c=n,0===bs&&Os(U)),c!==n&&(u=ba())!==n?(58===e.charCodeAt(ms)?(d=D,ms++):(d=n,0===bs&&Os(U)),d!==n&&(h=ba())!==n?(58===e.charCodeAt(ms)?(p=D,ms++):(p=n,0===bs&&Os(U)),p!==n&&(l=ba())!==n?(58===e.charCodeAt(ms)?(f=D,ms++):(f=n,0===bs&&Os(U)),f!==n&&(g=_a())!==n?r=i=[i,o,s,a,c,u,d,h,p,l,f,g]:(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n),r===n&&(r=ms,e.substr(ms,2)===mt?(i=mt,ms+=2):(i=n,0===bs&&Os(yt)),i!==n&&(o=ba())!==n?(58===e.charCodeAt(ms)?(s=D,ms++):(s=n,0===bs&&Os(U)),s!==n&&(a=ba())!==n?(58===e.charCodeAt(ms)?(c=D,ms++):(c=n,0===bs&&Os(U)),c!==n&&(u=ba())!==n?(58===e.charCodeAt(ms)?(d=D,ms++):(d=n,0===bs&&Os(U)),d!==n&&(h=ba())!==n?(58===e.charCodeAt(ms)?(p=D,ms++):(p=n,0===bs&&Os(U)),p!==n&&(l=_a())!==n?r=i=[i,o,s,a,c,u,d,h,p,l]:(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n),r===n&&(r=ms,e.substr(ms,2)===mt?(i=mt,ms+=2):(i=n,0===bs&&Os(yt)),i!==n&&(o=ba())!==n?(58===e.charCodeAt(ms)?(s=D,ms++):(s=n,0===bs&&Os(U)),s!==n&&(a=ba())!==n?(58===e.charCodeAt(ms)?(c=D,ms++):(c=n,0===bs&&Os(U)),c!==n&&(u=ba())!==n?(58===e.charCodeAt(ms)?(d=D,ms++):(d=n,0===bs&&Os(U)),d!==n&&(h=_a())!==n?r=i=[i,o,s,a,c,u,d,h]:(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n),r===n&&(r=ms,e.substr(ms,2)===mt?(i=mt,ms+=2):(i=n,0===bs&&Os(yt)),i!==n&&(o=ba())!==n?(58===e.charCodeAt(ms)?(s=D,ms++):(s=n,0===bs&&Os(U)),s!==n&&(a=ba())!==n?(58===e.charCodeAt(ms)?(c=D,ms++):(c=n,0===bs&&Os(U)),c!==n&&(u=_a())!==n?r=i=[i,o,s,a,c,u]:(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n),r===n&&(r=ms,e.substr(ms,2)===mt?(i=mt,ms+=2):(i=n,0===bs&&Os(yt)),i!==n&&(o=ba())!==n?(58===e.charCodeAt(ms)?(s=D,ms++):(s=n,0===bs&&Os(U)),s!==n&&(a=_a())!==n?r=i=[i,o,s,a]:(ms=r,r=n)):(ms=r,r=n),r===n&&(r=ms,e.substr(ms,2)===mt?(i=mt,ms+=2):(i=n,0===bs&&Os(yt)),i!==n&&(o=_a())!==n?r=i=[i,o]:(ms=r,r=n),r===n&&(r=ms,e.substr(ms,2)===mt?(i=mt,ms+=2):(i=n,0===bs&&Os(yt)),i!==n&&(o=ba())!==n?r=i=[i,o]:(ms=r,r=n),r===n&&(r=ms,(i=ba())!==n?(e.substr(ms,2)===mt?(o=mt,ms+=2):(o=n,0===bs&&Os(yt)),o!==n&&(s=ba())!==n?(58===e.charCodeAt(ms)?(a=D,ms++):(a=n,0===bs&&Os(U)),a!==n&&(c=ba())!==n?(58===e.charCodeAt(ms)?(u=D,ms++):(u=n,0===bs&&Os(U)),u!==n&&(d=ba())!==n?(58===e.charCodeAt(ms)?(h=D,ms++):(h=n,0===bs&&Os(U)),h!==n&&(p=ba())!==n?(58===e.charCodeAt(ms)?(l=D,ms++):(l=n,0===bs&&Os(U)),l!==n&&(f=_a())!==n?r=i=[i,o,s,a,c,u,d,h,p,l,f]:(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n),r===n&&(r=ms,(i=ba())!==n?(o=ms,58===e.charCodeAt(ms)?(s=D,ms++):(s=n,0===bs&&Os(U)),s!==n&&(a=ba())!==n?o=s=[s,a]:(ms=o,o=n),o===n&&(o=null),o!==n?(e.substr(ms,2)===mt?(s=mt,ms+=2):(s=n,0===bs&&Os(yt)),s!==n&&(a=ba())!==n?(58===e.charCodeAt(ms)?(c=D,ms++):(c=n,0===bs&&Os(U)),c!==n&&(u=ba())!==n?(58===e.charCodeAt(ms)?(d=D,ms++):(d=n,0===bs&&Os(U)),d!==n&&(h=ba())!==n?(58===e.charCodeAt(ms)?(p=D,ms++):(p=n,0===bs&&Os(U)),p!==n&&(l=_a())!==n?r=i=[i,o,s,a,c,u,d,h,p,l]:(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n),r===n&&(r=ms,(i=ba())!==n?(o=ms,58===e.charCodeAt(ms)?(s=D,ms++):(s=n,0===bs&&Os(U)),s!==n&&(a=ba())!==n?o=s=[s,a]:(ms=o,o=n),o===n&&(o=null),o!==n?(s=ms,58===e.charCodeAt(ms)?(a=D,ms++):(a=n,0===bs&&Os(U)),a!==n&&(c=ba())!==n?s=a=[a,c]:(ms=s,s=n),s===n&&(s=null),s!==n?(e.substr(ms,2)===mt?(a=mt,ms+=2):(a=n,0===bs&&Os(yt)),a!==n&&(c=ba())!==n?(58===e.charCodeAt(ms)?(u=D,ms++):(u=n,0===bs&&Os(U)),u!==n&&(d=ba())!==n?(58===e.charCodeAt(ms)?(h=D,ms++):(h=n,0===bs&&Os(U)),h!==n&&(p=_a())!==n?r=i=[i,o,s,a,c,u,d,h,p]:(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n),r===n&&(r=ms,(i=ba())!==n?(o=ms,58===e.charCodeAt(ms)?(s=D,ms++):(s=n,0===bs&&Os(U)),s!==n&&(a=ba())!==n?o=s=[s,a]:(ms=o,o=n),o===n&&(o=null),o!==n?(s=ms,58===e.charCodeAt(ms)?(a=D,ms++):(a=n,0===bs&&Os(U)),a!==n&&(c=ba())!==n?s=a=[a,c]:(ms=s,s=n),s===n&&(s=null),s!==n?(a=ms,58===e.charCodeAt(ms)?(c=D,ms++):(c=n,0===bs&&Os(U)),c!==n&&(u=ba())!==n?a=c=[c,u]:(ms=a,a=n),a===n&&(a=null),a!==n?(e.substr(ms,2)===mt?(c=mt,ms+=2):(c=n,0===bs&&Os(yt)),c!==n&&(u=ba())!==n?(58===e.charCodeAt(ms)?(d=D,ms++):(d=n,0===bs&&Os(U)),d!==n&&(h=_a())!==n?r=i=[i,o,s,a,c,u,d,h]:(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n),r===n&&(r=ms,(i=ba())!==n?(o=ms,58===e.charCodeAt(ms)?(s=D,ms++):(s=n,0===bs&&Os(U)),s!==n&&(a=ba())!==n?o=s=[s,a]:(ms=o,o=n),o===n&&(o=null),o!==n?(s=ms,58===e.charCodeAt(ms)?(a=D,ms++):(a=n,0===bs&&Os(U)),a!==n&&(c=ba())!==n?s=a=[a,c]:(ms=s,s=n),s===n&&(s=null),s!==n?(a=ms,58===e.charCodeAt(ms)?(c=D,ms++):(c=n,0===bs&&Os(U)),c!==n&&(u=ba())!==n?a=c=[c,u]:(ms=a,a=n),a===n&&(a=null),a!==n?(c=ms,58===e.charCodeAt(ms)?(u=D,ms++):(u=n,0===bs&&Os(U)),u!==n&&(d=ba())!==n?c=u=[u,d]:(ms=c,c=n),c===n&&(c=null),c!==n?(e.substr(ms,2)===mt?(u=mt,ms+=2):(u=n,0===bs&&Os(yt)),u!==n&&(d=_a())!==n?r=i=[i,o,s,a,c,u,d]:(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n),r===n&&(r=ms,(i=ba())!==n?(o=ms,58===e.charCodeAt(ms)?(s=D,ms++):(s=n,0===bs&&Os(U)),s!==n&&(a=ba())!==n?o=s=[s,a]:(ms=o,o=n),o===n&&(o=null),o!==n?(s=ms,58===e.charCodeAt(ms)?(a=D,ms++):(a=n,0===bs&&Os(U)),a!==n&&(c=ba())!==n?s=a=[a,c]:(ms=s,s=n),s===n&&(s=null),s!==n?(a=ms,58===e.charCodeAt(ms)?(c=D,ms++):(c=n,0===bs&&Os(U)),c!==n&&(u=ba())!==n?a=c=[c,u]:(ms=a,a=n),a===n&&(a=null),a!==n?(c=ms,58===e.charCodeAt(ms)?(u=D,ms++):(u=n,0===bs&&Os(U)),u!==n&&(d=ba())!==n?c=u=[u,d]:(ms=c,c=n),c===n&&(c=null),c!==n?(u=ms,58===e.charCodeAt(ms)?(d=D,ms++):(d=n,0===bs&&Os(U)),d!==n&&(h=ba())!==n?u=d=[d,h]:(ms=u,u=n),u===n&&(u=null),u!==n?(e.substr(ms,2)===mt?(d=mt,ms+=2):(d=n,0===bs&&Os(yt)),d!==n&&(h=ba())!==n?r=i=[i,o,s,a,c,u,d,h]:(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n),r===n&&(r=ms,(i=ba())!==n?(o=ms,58===e.charCodeAt(ms)?(s=D,ms++):(s=n,0===bs&&Os(U)),s!==n&&(a=ba())!==n?o=s=[s,a]:(ms=o,o=n),o===n&&(o=null),o!==n?(s=ms,58===e.charCodeAt(ms)?(a=D,ms++):(a=n,0===bs&&Os(U)),a!==n&&(c=ba())!==n?s=a=[a,c]:(ms=s,s=n),s===n&&(s=null),s!==n?(a=ms,58===e.charCodeAt(ms)?(c=D,ms++):(c=n,0===bs&&Os(U)),c!==n&&(u=ba())!==n?a=c=[c,u]:(ms=a,a=n),a===n&&(a=null),a!==n?(c=ms,58===e.charCodeAt(ms)?(u=D,ms++):(u=n,0===bs&&Os(U)),u!==n&&(d=ba())!==n?c=u=[u,d]:(ms=c,c=n),c===n&&(c=null),c!==n?(u=ms,58===e.charCodeAt(ms)?(d=D,ms++):(d=n,0===bs&&Os(U)),d!==n&&(h=ba())!==n?u=d=[d,h]:(ms=u,u=n),u===n&&(u=null),u!==n?(d=ms,58===e.charCodeAt(ms)?(h=D,ms++):(h=n,0===bs&&Os(U)),h!==n&&(p=ba())!==n?d=h=[h,p]:(ms=d,d=n),d===n&&(d=null),d!==n?(e.substr(ms,2)===mt?(h=mt,ms+=2):(h=n,0===bs&&Os(yt)),h!==n?r=i=[i,o,s,a,c,u,d,h]:(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n))))))))))))))),r!==n&&(ys=t,r=St()),t=r}function ba(){var e,t,r,i,o;return e=ms,(t=Us())!==n?((r=Us())===n&&(r=null),r!==n?((i=Us())===n&&(i=null),i!==n?((o=Us())===n&&(o=null),o!==n?e=t=[t,r,i,o]:(ms=e,e=n)):(ms=e,e=n)):(ms=e,e=n)):(ms=e,e=n),e}function _a(){var t,r,i,o;return t=ms,(r=ba())!==n?(58===e.charCodeAt(ms)?(i=D,ms++):(i=n,0===bs&&Os(U)),i!==n&&(o=ba())!==n?t=r=[r,i,o]:(ms=t,t=n)):(ms=t,t=n),t===n&&(t=Aa()),t}function Aa(){var t,r,i,o;return t=ms,wa()!==n?(46===e.charCodeAt(ms)?(r=J,ms++):(r=n,0===bs&&Os(Q)),r!==n&&wa()!==n?(46===e.charCodeAt(ms)?(i=J,ms++):(i=n,0===bs&&Os(Q)),i!==n&&wa()!==n?(46===e.charCodeAt(ms)?(o=J,ms++):(o=n,0===bs&&Os(Q)),o!==n&&wa()!==n?(ys=t,t=Tt()):(ms=t,t=n)):(ms=t,t=n)):(ms=t,t=n)):(ms=t,t=n),t}function wa(){var t,r,i,o;return t=ms,e.substr(ms,2)===Ct?(r=Ct,ms+=2):(r=n,0===bs&&Os(bt)),r!==n?(_t.test(e.charAt(ms))?(i=e.charAt(ms),ms++):(i=n,0===bs&&Os(At)),i!==n?t=r=[r,i]:(ms=t,t=n)):(ms=t,t=n),t===n&&(t=ms,50===e.charCodeAt(ms)?(r=wt,ms++):(r=n,0===bs&&Os(Et)),r!==n?(Rt.test(e.charAt(ms))?(i=e.charAt(ms),ms++):(i=n,0===bs&&Os(It)),i!==n&&(o=Ns())!==n?t=r=[r,i,o]:(ms=t,t=n)):(ms=t,t=n),t===n&&(t=ms,49===e.charCodeAt(ms)?(r=Ot,ms++):(r=n,0===bs&&Os(xt)),r!==n&&(i=Ns())!==n&&(o=Ns())!==n?t=r=[r,i,o]:(ms=t,t=n),t===n&&(t=ms,Pt.test(e.charAt(ms))?(r=e.charAt(ms),ms++):(r=n,0===bs&&Os(Nt)),r!==n&&(i=Ns())!==n?t=r=[r,i]:(ms=t,t=n),t===n&&(t=Ns())))),t}function Ea(){var e,t,r,i,o,s,a;return e=ms,t=ms,(r=Ns())===n&&(r=null),r!==n?((i=Ns())===n&&(i=null),i!==n?((o=Ns())===n&&(o=null),o!==n?((s=Ns())===n&&(s=null),s!==n?((a=Ns())===n&&(a=null),a!==n?t=r=[r,i,o,s,a]:(ms=t,t=n)):(ms=t,t=n)):(ms=t,t=n)):(ms=t,t=n)):(ms=t,t=n),t!==n&&(ys=e,t=Dt(t)),e=t}function Ra(){var t;return(t=function(){var t,r,i;return t=ms,e.substr(ms,10).toLowerCase()===Ut?(r=e.substr(ms,10),ms+=10):(r=n,0===bs&&Os(Ht)),r!==n?(e.substr(ms,3).toLowerCase()===kt?(i=e.substr(ms,3),ms+=3):(i=n,0===bs&&Os(Mt)),i===n&&(e.substr(ms,3).toLowerCase()===qt?(i=e.substr(ms,3),ms+=3):(i=n,0===bs&&Os(jt)),i===n&&(e.substr(ms,4).toLowerCase()===Lt?(i=e.substr(ms,4),ms+=4):(i=n,0===bs&&Os(Ft)),i===n&&(e.substr(ms,3).toLowerCase()===Bt?(i=e.substr(ms,3),ms+=3):(i=n,0===bs&&Os(Gt)),i===n&&(i=Xs())))),i!==n?(ys=t,r=Wt(i),t=r):(ms=t,t=n)):(ms=t,t=n),t}())===n&&(t=function(){var t,r,i;return t=ms,e.substr(ms,5).toLowerCase()===zt?(r=e.substr(ms,5),ms+=5):(r=n,0===bs&&Os(Kt)),r!==n?(e.substr(ms,5).toLowerCase()===Vt?(i=e.substr(ms,5),ms+=5):(i=n,0===bs&&Os(Yt)),i===n&&(e.substr(ms,2).toLowerCase()===$t?(i=e.substr(ms,2),ms+=2):(i=n,0===bs&&Os(Xt)),i===n&&(i=Xs())),i!==n?(ys=t,r=Jt(i),t=r):(ms=t,t=n)):(ms=t,t=n),t}())===n&&(t=function(){var t,r,i;return t=ms,e.substr(ms,7).toLowerCase()===Qt?(r=e.substr(ms,7),ms+=7):(r=n,0===bs&&Os(Zt)),r!==n&&(i=La())!==n?(ys=t,r=er(i),t=r):(ms=t,t=n),t}())===n&&(t=function(){var t,r,i;return t=ms,e.substr(ms,4).toLowerCase()===tr?(r=e.substr(ms,4),ms+=4):(r=n,0===bs&&Os(rr)),r!==n&&(i=lc())!==n?(ys=t,r=nr(i),t=r):(ms=t,t=n),t}())===n&&(t=function(){var t,r,i;return t=ms,e.substr(ms,6).toLowerCase()===ir?(r=e.substr(ms,6),ms+=6):(r=n,0===bs&&Os(or)),r!==n&&(i=ma())!==n?(ys=t,r=sr(i),t=r):(ms=t,t=n),t}())===n&&(t=function(){var t,r,i,o,s;return t=ms,e.substr(ms,2).toLowerCase()===ar?(r=e.substr(ms,2),ms+=2):(r=n,0===bs&&Os(cr)),r!==n?(i=ms,61===e.charCodeAt(ms)?(o=j,ms++):(o=n,0===bs&&Os(L)),o!==n&&(s=Xs())!==n?i=o=[o,s]:(ms=i,i=n),i===n&&(i=null),i!==n?(ys=t,r=ur(),t=r):(ms=t,t=n)):(ms=t,t=n),t}())===n&&(t=function(){var t,r,i,o,s;return t=ms,(r=function(){var t,r,i;if(t=ms,r=[],(i=Ia())!==n)for(;i!==n;)r.push(i),i=Ia();else r=n;return t=r!==n?e.substring(t,ms):r}())!==n?(i=ms,61===e.charCodeAt(ms)?(o=j,ms++):(o=n,0===bs&&Os(L)),o!==n&&(s=function(){var t,r,i;if(t=ms,r=[],(i=Ia())!==n)for(;i!==n;)r.push(i),i=Ia();else r=n;return t=r!==n?e.substring(t,ms):r}())!==n?i=o=[o,s]:(ms=i,i=n),i===n&&(i=null),i!==n?(ys=t,r=dr(r,i),t=r):(ms=t,t=n)):(ms=t,t=n),t}()),t}function Ia(){var t;return(t=function(){var t;return 91===e.charCodeAt(ms)?(t=Re,ms++):(t=n,0===bs&&Os(Ie)),t===n&&(93===e.charCodeAt(ms)?(t=Oe,ms++):(t=n,0===bs&&Os(xe)),t===n&&(47===e.charCodeAt(ms)?(t=O,ms++):(t=n,0===bs&&Os(x)),t===n&&(58===e.charCodeAt(ms)?(t=D,ms++):(t=n,0===bs&&Os(U)),t===n&&(38===e.charCodeAt(ms)?(t=M,ms++):(t=n,0===bs&&Os(q)),t===n&&(43===e.charCodeAt(ms)?(t=F,ms++):(t=n,0===bs&&Os(B)),t===n&&(36===e.charCodeAt(ms)?(t=G,ms++):(t=n,0===bs&&Os(W)))))))),t}())===n&&(t=Bs())===n&&(t=Ws()),t}function Oa(){var t,r,i,o;return t=ms,(r=function(){var e,t;if(e=[],(t=xa())===n&&(t=Bs())===n&&(t=Ws()),t!==n)for(;t!==n;)e.push(t),(t=xa())===n&&(t=Bs())===n&&(t=Ws());else e=n;return e}())!==n?(61===e.charCodeAt(ms)?(i=j,ms++):(i=n,0===bs&&Os(L)),i!==n&&(o=function(){var e,t;for(e=[],(t=xa())===n&&(t=Bs())===n&&(t=Ws());t!==n;)e.push(t),(t=xa())===n&&(t=Bs())===n&&(t=Ws());return e}())!==n?(ys=t,t=r=hr(r,o)):(ms=t,t=n)):(ms=t,t=n),t}function xa(){var t;return 91===e.charCodeAt(ms)?(t=Re,ms++):(t=n,0===bs&&Os(Ie)),t===n&&(93===e.charCodeAt(ms)?(t=Oe,ms++):(t=n,0===bs&&Os(xe)),t===n&&(47===e.charCodeAt(ms)?(t=O,ms++):(t=n,0===bs&&Os(x)),t===n&&(63===e.charCodeAt(ms)?(t=P,ms++):(t=n,0===bs&&Os(N)),t===n&&(58===e.charCodeAt(ms)?(t=D,ms++):(t=n,0===bs&&Os(U)),t===n&&(43===e.charCodeAt(ms)?(t=F,ms++):(t=n,0===bs&&Os(B)),t===n&&(36===e.charCodeAt(ms)?(t=G,ms++):(t=n,0===bs&&Os(W)))))))),t}function Pa(){var e;return(e=function(){var e,t,r,i,o,s;return e=ms,(t=ja())!==n&&(r=qs())!==n&&(i=function(){var e,t;return e=ms,(t=function(){var e,t,r,i;return e=ms,(t=Ns())!==n&&(r=Ns())!==n&&(i=Ns())!==n?e=t=[t,r,i]:(ms=e,e=n),e}())!==n&&(ys=e,t=jr(t)),e=t}())!==n&&(o=qs())!==n&&(s=function(){var e,t,r;for(e=ms,t=[],(r=Fs())===n&&(r=Bs())===n&&(r=Ws())===n&&(r=Ys())===n&&(r=$s())===n&&(r=qs())===n&&(r=js());r!==n;)t.push(r),(r=Fs())===n&&(r=Bs())===n&&(r=Ws())===n&&(r=Ys())===n&&(r=$s())===n&&(r=qs())===n&&(r=js());return t!==n&&(ys=e,t=Lr()),e=t}())!==n?e=t=[t,r,i,o,s]:(ms=e,e=n),e}())===n&&(e=function(){var e,t,r,i,o,s;return e=ms,(t=La())!==n&&(r=qs())!==n&&(i=function(){var e;return(e=pa())===n&&(e=Na()),e}())!==n&&(o=qs())!==n&&(s=ja())!==n?e=t=[t,r,i,o,s]:(ms=e,e=n),e}()),e}function Na(){var t,r,i;return t=ms,function(){var t,r,i,o,s;if(t=ms,r=ms,(i=Ds())!==n){for(o=[],(s=Ds())===n&&(s=Ns())===n&&(43===e.charCodeAt(ms)?(s=F,ms++):(s=n,0===bs&&Os(B)),s===n&&(45===e.charCodeAt(ms)?(s=V,ms++):(s=n,0===bs&&Os(Y)),s===n&&(46===e.charCodeAt(ms)?(s=J,ms++):(s=n,0===bs&&Os(Q)))));s!==n;)o.push(s),(s=Ds())===n&&(s=Ns())===n&&(43===e.charCodeAt(ms)?(s=F,ms++):(s=n,0===bs&&Os(B)),s===n&&(45===e.charCodeAt(ms)?(s=V,ms++):(s=n,0===bs&&Os(Y)),s===n&&(46===e.charCodeAt(ms)?(s=J,ms++):(s=n,0===bs&&Os(Q)))));o!==n?r=i=[i,o]:(ms=r,r=n)}else ms=r,r=n;return r!==n&&(ys=t,r=gr()),t=r}()!==n?(58===e.charCodeAt(ms)?(r=D,ms++):(r=n,0===bs&&Os(U)),r!==n?((i=function(){var t,r,i,o,s;return t=ms,(r=function(){var t,r,i,o;return t=ms,e.substr(ms,2)===lr?(r=lr,ms+=2):(r=n,0===bs&&Os(fr)),r!==n&&(i=function(){var t;return(t=function(){var t,r,i,o;return t=ms,r=ms,(i=fa())!==n?(64===e.charCodeAt(ms)?(o=H,ms++):(o=n,0===bs&&Os(k)),o!==n?r=i=[i,o]:(ms=r,r=n)):(ms=r,r=n),r===n&&(r=null),r!==n&&(i=va())!==n?t=r=[r,i]:(ms=t,t=n),t===n&&(t=null),t}())===n&&(t=qa()),t}())!==n?((o=Da())===n&&(o=null),o!==n?t=r=[r,i,o]:(ms=t,t=n)):(ms=t,t=n),t}())===n&&(r=Da()),r!==n?(i=ms,63===e.charCodeAt(ms)?(o=P,ms++):(o=n,0===bs&&Os(N)),o!==n&&(s=function(){var e,t;for(e=[],t=Ua();t!==n;)e.push(t),t=Ua();return e}())!==n?i=o=[o,s]:(ms=i,i=n),i===n&&(i=null),i!==n?t=r=[r,i]:(ms=t,t=n)):(ms=t,t=n),t}())===n&&(i=function(){var t,r,i,o;if(t=ms,(r=function(){var t;return(t=Bs())===n&&(t=Ws())===n&&(59===e.charCodeAt(ms)?(t=R,ms++):(t=n,0===bs&&Os(I)),t===n&&(63===e.charCodeAt(ms)?(t=P,ms++):(t=n,0===bs&&Os(N)),t===n&&(58===e.charCodeAt(ms)?(t=D,ms++):(t=n,0===bs&&Os(U)),t===n&&(64===e.charCodeAt(ms)?(t=H,ms++):(t=n,0===bs&&Os(k)),t===n&&(38===e.charCodeAt(ms)?(t=M,ms++):(t=n,0===bs&&Os(q)),t===n&&(61===e.charCodeAt(ms)?(t=j,ms++):(t=n,0===bs&&Os(L)),t===n&&(43===e.charCodeAt(ms)?(t=F,ms++):(t=n,0===bs&&Os(B)),t===n&&(36===e.charCodeAt(ms)?(t=G,ms++):(t=n,0===bs&&Os(W)),t===n&&(44===e.charCodeAt(ms)?(t=z,ms++):(t=n,0===bs&&Os(K))))))))))),t}())!==n){for(i=[],o=Ua();o!==n;)i.push(o),o=Ua();i!==n?t=r=[r,i]:(ms=t,t=n)}else ms=t,t=n;return t}()),i!==n?(ys=t,t=pr()):(ms=t,t=n)):(ms=t,t=n)):(ms=t,t=n),t}function Da(){var t,r,i;return t=ms,47===e.charCodeAt(ms)?(r=O,ms++):(r=n,0===bs&&Os(x)),r!==n&&(i=function(){var t,r,i,o,s,a;if(t=ms,(r=Ha())!==n){for(i=[],o=ms,47===e.charCodeAt(ms)?(s=O,ms++):(s=n,0===bs&&Os(x)),s!==n&&(a=Ha())!==n?o=s=[s,a]:(ms=o,o=n);o!==n;)i.push(o),o=ms,47===e.charCodeAt(ms)?(s=O,ms++):(s=n,0===bs&&Os(x)),s!==n&&(a=Ha())!==n?o=s=[s,a]:(ms=o,o=n);i!==n?t=r=[r,i]:(ms=t,t=n)}else ms=t,t=n;return t}())!==n?t=r=[r,i]:(ms=t,t=n),t}function Ua(){var e;return(e=Fs())===n&&(e=Bs())===n&&(e=Ws()),e}function Ha(){var t,r,i,o,s,a;for(t=ms,r=[],i=Ma();i!==n;)r.push(i),i=Ma();if(r!==n){for(i=[],o=ms,59===e.charCodeAt(ms)?(s=R,ms++):(s=n,0===bs&&Os(I)),s!==n&&(a=ka())!==n?o=s=[s,a]:(ms=o,o=n);o!==n;)i.push(o),o=ms,59===e.charCodeAt(ms)?(s=R,ms++):(s=n,0===bs&&Os(I)),s!==n&&(a=ka())!==n?o=s=[s,a]:(ms=o,o=n);i!==n?t=r=[r,i]:(ms=t,t=n)}else ms=t,t=n;return t}function ka(){var e,t;for(e=[],t=Ma();t!==n;)e.push(t),t=Ma();return e}function Ma(){var t;return(t=Bs())===n&&(t=Ws())===n&&(58===e.charCodeAt(ms)?(t=D,ms++):(t=n,0===bs&&Os(U)),t===n&&(64===e.charCodeAt(ms)?(t=H,ms++):(t=n,0===bs&&Os(k)),t===n&&(38===e.charCodeAt(ms)?(t=M,ms++):(t=n,0===bs&&Os(q)),t===n&&(61===e.charCodeAt(ms)?(t=j,ms++):(t=n,0===bs&&Os(L)),t===n&&(43===e.charCodeAt(ms)?(t=F,ms++):(t=n,0===bs&&Os(B)),t===n&&(36===e.charCodeAt(ms)?(t=G,ms++):(t=n,0===bs&&Os(W)),t===n&&(44===e.charCodeAt(ms)?(t=z,ms++):(t=n,0===bs&&Os(K))))))))),t}function qa(){var t,r;if(t=[],(r=Bs())===n&&(r=Ws())===n&&(36===e.charCodeAt(ms)?(r=G,ms++):(r=n,0===bs&&Os(W)),r===n&&(44===e.charCodeAt(ms)?(r=z,ms++):(r=n,0===bs&&Os(K)),r===n&&(59===e.charCodeAt(ms)?(r=R,ms++):(r=n,0===bs&&Os(I)),r===n&&(58===e.charCodeAt(ms)?(r=D,ms++):(r=n,0===bs&&Os(U)),r===n&&(64===e.charCodeAt(ms)?(r=H,ms++):(r=n,0===bs&&Os(k)),r===n&&(38===e.charCodeAt(ms)?(r=M,ms++):(r=n,0===bs&&Os(q)),r===n&&(61===e.charCodeAt(ms)?(r=j,ms++):(r=n,0===bs&&Os(L)),r===n&&(43===e.charCodeAt(ms)?(r=F,ms++):(r=n,0===bs&&Os(B)))))))))),r!==n)for(;r!==n;)t.push(r),(r=Bs())===n&&(r=Ws())===n&&(36===e.charCodeAt(ms)?(r=G,ms++):(r=n,0===bs&&Os(W)),r===n&&(44===e.charCodeAt(ms)?(r=z,ms++):(r=n,0===bs&&Os(K)),r===n&&(59===e.charCodeAt(ms)?(r=R,ms++):(r=n,0===bs&&Os(I)),r===n&&(58===e.charCodeAt(ms)?(r=D,ms++):(r=n,0===bs&&Os(U)),r===n&&(64===e.charCodeAt(ms)?(r=H,ms++):(r=n,0===bs&&Os(k)),r===n&&(38===e.charCodeAt(ms)?(r=M,ms++):(r=n,0===bs&&Os(q)),r===n&&(61===e.charCodeAt(ms)?(r=j,ms++):(r=n,0===bs&&Os(L)),r===n&&(43===e.charCodeAt(ms)?(r=F,ms++):(r=n,0===bs&&Os(B))))))))));else t=n;return t}function ja(){var t,r,i,o,s,a,c;if(t=ms,e.substr(ms,3).toLowerCase()===ot?(r=e.substr(ms,3),ms+=3):(r=n,0===bs&&Os(vr)),r!==n)if(47===e.charCodeAt(ms)?(i=O,ms++):(i=n,0===bs&&Os(x)),i!==n){if(o=[],(s=Ns())!==n)for(;s!==n;)o.push(s),s=Ns();else o=n;if(o!==n)if(46===e.charCodeAt(ms)?(s=J,ms++):(s=n,0===bs&&Os(Q)),s!==n){if(a=[],(c=Ns())!==n)for(;c!==n;)a.push(c),c=Ns();else a=n;a!==n?(ys=t,t=r=mr()):(ms=t,t=n)}else ms=t,t=n;else ms=t,t=n}else ms=t,t=n;else ms=t,t=n;return t}function La(){var t,r;return t=ms,(r=function(){var t;return e.substr(ms,6)===yr?(t=yr,ms+=6):(t=n,0===bs&&Os(Sr)),t}())===n&&(r=function(){var t;return e.substr(ms,3)===Tr?(t=Tr,ms+=3):(t=n,0===bs&&Os(Cr)),t}())===n&&(r=function(){var t;return e.substr(ms,7)===br?(t=br,ms+=7):(t=n,0===bs&&Os(_r)),t}())===n&&(r=function(){var t;return e.substr(ms,3)===Ar?(t=Ar,ms+=3):(t=n,0===bs&&Os(wr)),t}())===n&&(r=function(){var t;return e.substr(ms,6)===Er?(t=Er,ms+=6):(t=n,0===bs&&Os(Rr)),t}())===n&&(r=function(){var t;return e.substr(ms,8)===Ir?(t=Ir,ms+=8):(t=n,0===bs&&Os(Or)),t}())===n&&(r=function(){var t;return e.substr(ms,9)===xr?(t=xr,ms+=9):(t=n,0===bs&&Os(Pr)),t}())===n&&(r=function(){var t;return e.substr(ms,7)===kr?(t=kr,ms+=7):(t=n,0===bs&&Os(Mr)),t}())===n&&(r=function(){var t;return e.substr(ms,6)===Nr?(t=Nr,ms+=6):(t=n,0===bs&&Os(Dr)),t}())===n&&(r=function(){var t;return e.substr(ms,5)===Ur?(t=Ur,ms+=5):(t=n,0===bs&&Os(Hr)),t}())===n&&(r=Xs()),r!==n&&(ys=t,r=qr()),t=r}function Fa(){var t,r,i,o;return t=ms,Qs()!==n?(r=ms,64===e.charCodeAt(ms)?(i=H,ms++):(i=n,0===bs&&Os(k)),i!==n&&(o=Qs())!==n?r=i=[i,o]:(ms=r,r=n),r===n&&(r=null),r!==n?(ys=t,t=Fr()):(ms=t,t=n)):(ms=t,t=n),t}function Ba(){var t,r,i,o,s,a,c;if(t=ms,(r=function(){var t,r;return t=ms,Ks()!==n?(42===e.charCodeAt(ms)?(r=ne,ms++):(r=n,0===bs&&Os(ie)),r!==n&&Ks()!==n?(ys=t,t=He()):(ms=t,t=n)):(ms=t,t=n),t}())===n)if(r=ms,(i=Ga())!==n){for(o=[],s=ms,(a=na())!==n&&(c=Ga())!==n?s=a=[a,c]:(ms=s,s=n);s!==n;)o.push(s),s=ms,(a=na())!==n&&(c=Ga())!==n?s=a=[a,c]:(ms=s,s=n);o!==n?r=i=[i,o]:(ms=r,r=n)}else ms=r,r=n;return r!==n&&(ys=t,r=Br()),t=r}function Ga(){var e,t,r,i,o,s;if(e=ms,(t=ha())===n&&(t=Wa()),t!==n){for(r=[],i=ms,(o=ia())!==n&&(s=Ka())!==n?i=o=[o,s]:(ms=i,i=n);i!==n;)r.push(i),i=ms,(o=ia())!==n&&(s=Ka())!==n?i=o=[o,s]:(ms=i,i=n);r!==n?(ys=e,e=t=Gr()):(ms=e,e=n)}else ms=e,e=n;return e}function Wa(){var e,t,r,i,o;return e=ms,(t=za())===n&&(t=null),t!==n&&(r=ra())!==n&&(i=pa())!==n&&(o=ta())!==n?e=t=[t,r,i,o]:(ms=e,e=n),e}function za(){var e,t,r,i,o,s,a;if(e=ms,t=ms,(r=Xs())!==n){for(i=[],o=ms,(s=zs())!==n&&(a=Xs())!==n?o=s=[s,a]:(ms=o,o=n);o!==n;)i.push(o),o=ms,(s=zs())!==n&&(a=Xs())!==n?o=s=[s,a]:(ms=o,o=n);i!==n?t=r=[r,i]:(ms=t,t=n)}else ms=t,t=n;return t===n&&(t=aa()),t!==n&&(ys=e,t=Wr(t)),e=t}function Ka(){var t;return(t=function(){var t,r,i;return t=ms,e.substr(ms,1).toLowerCase()===zr?(r=e.charAt(ms),ms++):(r=n,0===bs&&Os(Kr)),r!==n&&ea()!==n&&(i=function(){var t,r,i,o,s,a,c;return t=ms,48===e.charCodeAt(ms)?(r=Qr,ms++):(r=n,0===bs&&Os(Zr)),r!==n?(i=ms,46===e.charCodeAt(ms)?(o=J,ms++):(o=n,0===bs&&Os(Q)),o!==n?((s=Ns())===n&&(s=null),s!==n?((a=Ns())===n&&(a=null),a!==n?((c=Ns())===n&&(c=null),c!==n?i=o=[o,s,a,c]:(ms=i,i=n)):(ms=i,i=n)):(ms=i,i=n)):(ms=i,i=n),i===n&&(i=null),i!==n?(ys=t,r=en(),t=r):(ms=t,t=n)):(ms=t,t=n),t}())!==n?(ys=t,r=Vr(i),t=r):(ms=t,t=n),t}())===n&&(t=function(){var t,r,i;return t=ms,e.substr(ms,7).toLowerCase()===Yr?(r=e.substr(ms,7),ms+=7):(r=n,0===bs&&Os($r)),r!==n&&ea()!==n&&(i=Va())!==n?(ys=t,r=Xr(i),t=r):(ms=t,t=n),t}())===n&&(t=Ya()),t}function Va(){var e,t,r;if(e=ms,t=[],(r=Ns())!==n)for(;r!==n;)t.push(r),r=Ns();else t=n;return t!==n&&(ys=e,t=Jr(t)),e=t}function Ya(){var e,t,r,i,o;return e=ms,(t=Xs())!==n?(r=ms,(i=ea())!==n&&(o=function(){var e;return(e=Xs())===n&&(e=ma())===n&&(e=aa()),e}())!==n?r=i=[i,o]:(ms=r,r=n),r===n&&(r=null),r!==n?(ys=e,e=t=tn(t,r)):(ms=e,e=n)):(ms=e,e=n),e}function $a(){var t;return(t=function(){var t,r,i,o;return t=ms,e.substr(ms,8).toLowerCase()===pn?(r=e.substr(ms,8),ms+=8):(r=n,0===bs&&Os(ln)),r!==n&&(i=ea())!==n?(e.substr(ms,8).toLowerCase()===fn?(o=e.substr(ms,8),ms+=8):(o=n,0===bs&&Os(gn)),o===n&&(e.substr(ms,8).toLowerCase()===vn?(o=e.substr(ms,8),ms+=8):(o=n,0===bs&&Os(mn)),o===n&&(o=Xs())),o!==n?t=r=[r,i,o]:(ms=t,t=n)):(ms=t,t=n),t}())===n&&(t=Ya()),t}function Xa(){var t;return(t=Xs())===n&&(t=function(){var t,r,i;return t=ms,e.substr(ms,2).toLowerCase()===Un?(r=e.substr(ms,2),ms+=2):(r=n,0===bs&&Os(Hn)),r!==n&&(i=Xs())!==n?t=r=[r,i]:(ms=t,t=n),t}()),t}function Ja(){var e,t,r,i;return e=ms,(t=Xs())!==n&&(r=ea())!==n&&(i=function(){var e;return(e=Xs())===n&&(e=aa()),e}())!==n?e=t=[t,r,i]:(ms=e,e=n),e}function Qa(){var t,r,i,o,s,a,c;if(t=ms,r=ms,(i=Js())!==n){for(o=[],s=ms,46===e.charCodeAt(ms)?(a=J,ms++):(a=n,0===bs&&Os(Q)),a!==n&&(c=Js())!==n?s=a=[a,c]:(ms=s,s=n);s!==n;)o.push(s),s=ms,46===e.charCodeAt(ms)?(a=J,ms++):(a=n,0===bs&&Os(Q)),a!==n&&(c=Js())!==n?s=a=[a,c]:(ms=s,s=n);o!==n?r=i=[i,o]:(ms=r,r=n)}else ms=r,r=n;return t=r!==n?e.substring(t,ms):r}function Za(){var e;return(e=ec())===n&&(e=Ya()),e}function ec(){var t,r,i;return t=ms,e.substr(ms,3).toLowerCase()===jn?(r=e.substr(ms,3),ms+=3):(r=n,0===bs&&Os(Ln)),r!==n&&ea()!==n&&(i=Xs())!==n?(ys=t,t=r=Fn(i)):(ms=t,t=n),t}function tc(){var t,r,i,o,s,a,c,u;if(t=ms,e.substr(ms,6).toLowerCase()===Wn?(r=e.substr(ms,6),ms+=6):(r=n,0===bs&&Os(zn)),r!==n)if((i=zs())!==n)if((o=nc())!==n){for(s=[],a=ms,(c=na())!==n&&(u=nc())!==n?a=c=[c,u]:(ms=a,a=n);a!==n;)s.push(a),a=ms,(c=na())!==n&&(u=nc())!==n?a=c=[c,u]:(ms=a,a=n);s!==n?t=r=[r,i,o,s]:(ms=t,t=n)}else ms=t,t=n;else ms=t,t=n;else ms=t,t=n;return t===n&&(t=function(){var e,t,r,i,o,s,a,c;if(e=ms,(t=Xs())!==n)if((r=zs())!==n)if((i=rc())!==n){for(o=[],s=ms,(a=na())!==n&&(c=rc())!==n?s=a=[a,c]:(ms=s,s=n);s!==n;)o.push(s),s=ms,(a=na())!==n&&(c=rc())!==n?s=a=[a,c]:(ms=s,s=n);o!==n?e=t=[t,r,i,o]:(ms=e,e=n)}else ms=e,e=n;else ms=e,e=n;else ms=e,e=n;return e}()),t}function rc(){var e,t,r,i;return e=ms,(t=Xs())!==n&&(r=ea())!==n?((i=Xs())===n&&(i=aa()),i!==n?e=t=[t,r,i]:(ms=e,e=n)):(ms=e,e=n),e}function nc(){var t;return(t=function(){var t,r,i,o;return t=ms,e.substr(ms,5).toLowerCase()===Kn?(r=e.substr(ms,5),ms+=5):(r=n,0===bs&&Os(Vn)),r!==n&&(i=ea())!==n&&(o=function(){var e,t;return e=ms,(t=ca())!==n&&(ys=e,t=Yn(t)),e=t}())!==n?t=r=[r,i,o]:(ms=t,t=n),t}())===n&&(t=function(){var t,r,i,o,s,a,c,u,d;if(t=ms,e.substr(ms,6).toLowerCase()===$n?(r=e.substr(ms,6),ms+=6):(r=n,0===bs&&Os(Xn)),r!==n)if((i=ea())!==n)if((o=oa())!==n)if((s=ic())!==n){if(a=[],c=ms,u=[],(d=qs())!==n)for(;d!==n;)u.push(d),d=qs();else u=n;for(u!==n&&(d=ic())!==n?c=u=[u,d]:(ms=c,c=n);c!==n;){if(a.push(c),c=ms,u=[],(d=qs())!==n)for(;d!==n;)u.push(d),d=qs();else u=n;u!==n&&(d=ic())!==n?c=u=[u,d]:(ms=c,c=n)}a!==n&&(c=sa())!==n?t=r=[r,i,o,s,a,c]:(ms=t,t=n)}else ms=t,t=n;else ms=t,t=n;else ms=t,t=n;else ms=t,t=n;return t}())===n&&(t=function(){var t,r,i,o;return t=ms,e.substr(ms,5).toLowerCase()===Jn?(r=e.substr(ms,5),ms+=5):(r=n,0===bs&&Os(Qn)),r!==n&&(i=ea())!==n&&(o=function(){var e,t;return e=ms,(t=ca())!==n&&(ys=e,t=Zn(t)),e=t}())!==n?t=r=[r,i,o]:(ms=t,t=n),t}())===n&&(t=function(){var t,r,i;return t=ms,e.substr(ms,6).toLowerCase()===ei?(r=e.substr(ms,6),ms+=6):(r=n,0===bs&&Os(ti)),r!==n&&ea()!==n&&(i=ca())!==n?(ys=t,r=ri(i),t=r):(ms=t,t=n),t}())===n&&(t=function(){var t,r,i,o,s;return t=ms,e.substr(ms,5).toLowerCase()===ni?(r=e.substr(ms,5),ms+=5):(r=n,0===bs&&Os(ii)),r!==n&&(i=ea())!==n?(o=ms,e.substr(ms,4).toLowerCase()===oi?(s=e.substr(ms,4),ms+=4):(s=n,0===bs&&Os(si)),s!==n&&(ys=o,s=ai()),(o=s)===n&&(o=ms,e.substr(ms,5).toLowerCase()===ci?(s=e.substr(ms,5),ms+=5):(s=n,0===bs&&Os(ui)),s!==n&&(ys=o,s=di()),o=s),o!==n?t=r=[r,i,o]:(ms=t,t=n)):(ms=t,t=n),t}())===n&&(t=function(){var t,r,i;return t=ms,e.substr(ms,9).toLowerCase()===hi?(r=e.substr(ms,9),ms+=9):(r=n,0===bs&&Os(pi)),r!==n&&ea()!==n?(e.substr(ms,3).toLowerCase()===li?(i=e.substr(ms,3),ms+=3):(i=n,0===bs&&Os(fi)),i===n&&(e.substr(ms,8).toLowerCase()===gi?(i=e.substr(ms,8),ms+=8):(i=n,0===bs&&Os(vi)),i===n&&(i=Xs())),i!==n?(ys=t,r=mi(i),t=r):(ms=t,t=n)):(ms=t,t=n),t}())===n&&(t=function(){var t,r,i,o,s,a,c,u,d,h;if(t=ms,e.substr(ms,3).toLowerCase()===yi?(r=e.substr(ms,3),ms+=3):(r=n,0===bs&&Os(Si)),r!==n)if((i=ea())!==n)if((o=oa())!==n){if(s=ms,(a=oc())!==n){for(c=[],u=ms,44===e.charCodeAt(ms)?(d=z,ms++):(d=n,0===bs&&Os(K)),d!==n&&(h=oc())!==n?u=d=[d,h]:(ms=u,u=n);u!==n;)c.push(u),u=ms,44===e.charCodeAt(ms)?(d=z,ms++):(d=n,0===bs&&Os(K)),d!==n&&(h=oc())!==n?u=d=[d,h]:(ms=u,u=n);c!==n?s=a=[a,c]:(ms=s,s=n)}else ms=s,s=n;s!==n&&(a=sa())!==n?t=r=[r,i,o,s,a]:(ms=t,t=n)}else ms=t,t=n;else ms=t,t=n;else ms=t,t=n;return t}())===n&&(t=rc()),t}function ic(){var e;return(e=Na())===n&&(e=Da()),e}function oc(){var t,r;return t=ms,e.substr(ms,8).toLowerCase()===Ti?(r=e.substr(ms,8),ms+=8):(r=n,0===bs&&Os(Ci)),r===n&&(e.substr(ms,4).toLowerCase()===bi?(r=e.substr(ms,4),ms+=4):(r=n,0===bs&&Os(_i)),r===n&&(r=Xs())),r!==n&&(ys=t,r=Ai(r)),t=r}function sc(){var e,t,r,i,o;if(e=ms,Wa()!==n){for(t=[],r=ms,(i=ia())!==n&&(o=Ya())!==n?r=i=[i,o]:(ms=r,r=n);r!==n;)t.push(r),r=ms,(i=ia())!==n&&(o=Ya())!==n?r=i=[i,o]:(ms=r,r=n);t!==n?(ys=e,e=Ei()):(ms=e,e=n)}else ms=e,e=n;return e}function ac(){var t,r,i;return t=ms,e.substr(ms,8).toLowerCase()===xi?(r=e.substr(ms,8),ms+=8):(r=n,0===bs&&Os(Pi)),r!==n&&ea()!==n&&(i=Xs())!==n?(ys=t,t=r=Ni(i)):(ms=t,t=n),t===n&&(t=ms,e.substr(ms,6).toLowerCase()===Di?(r=e.substr(ms,6),ms+=6):(r=n,0===bs&&Os(Ui)),r!==n&&ea()!==n&&(i=Xs())!==n?(ys=t,t=r=Hi(i)):(ms=t,t=n),t===n&&(t=ms,e.substr(ms,10).toLowerCase()===ki?(r=e.substr(ms,10),ms+=10):(r=n,0===bs&&Os(Mi)),r!==n&&(ys=t,r=qi()),(t=r)===n&&(t=Ya()))),t}function cc(){var t,r,i;return t=ms,e.substr(ms,6).toLowerCase()===$i?(r=e.substr(ms,6),ms+=6):(r=n,0===bs&&Os(Xi)),r!==n&&ea()!==n&&(i=function(){var t;return e.substr(ms,11).toLowerCase()===ro?(t=e.substr(ms,11),ms+=11):(t=n,0===bs&&Os(no)),t===n&&(e.substr(ms,9).toLowerCase()===io?(t=e.substr(ms,9),ms+=9):(t=n,0===bs&&Os(oo)),t===n&&(e.substr(ms,8).toLowerCase()===so?(t=e.substr(ms,8),ms+=8):(t=n,0===bs&&Os(ao)),t===n&&(e.substr(ms,7).toLowerCase()===co?(t=e.substr(ms,7),ms+=7):(t=n,0===bs&&Os(uo)),t===n&&(e.substr(ms,6).toLowerCase()===ho?(t=e.substr(ms,6),ms+=6):(t=n,0===bs&&Os(po)),t===n&&(e.substr(ms,10).toLowerCase()===lo?(t=e.substr(ms,10),ms+=10):(t=n,0===bs&&Os(fo)),t===n&&(e.substr(ms,9).toLowerCase()===go?(t=e.substr(ms,9),ms+=9):(t=n,0===bs&&Os(vo)),t===n&&(t=Xs()))))))),t}())!==n?(ys=t,t=r=Ji(i)):(ms=t,t=n),t===n&&(t=ms,e.substr(ms,7).toLowerCase()===Yr?(r=e.substr(ms,7),ms+=7):(r=n,0===bs&&Os($r)),r!==n&&ea()!==n&&(i=Va())!==n?(ys=t,t=r=Qi(i)):(ms=t,t=n),t===n&&(t=ms,e.substr(ms,11).toLowerCase()===Zi?(r=e.substr(ms,11),ms+=11):(r=n,0===bs&&Os(eo)),r!==n&&ea()!==n&&(i=Va())!==n?(ys=t,t=r=to(i)):(ms=t,t=n),t===n&&(t=Ya()))),t}function uc(){var e;return(e=ec())===n&&(e=Ya()),e}function dc(){var t,r,i,o,s,a,c,u;if(t=ms,(r=function(){var t,r,i,o,s,a;return t=ms,(r=function(){var t,r;return t=ms,e.substr(ms,3).toLowerCase()===ot?(r=e.substr(ms,3),ms+=3):(r=n,0===bs&&Os(vr)),r===n&&(r=Xs()),r!==n&&(ys=t,r=Uo(r)),t=r}())!==n&&(i=Zs())!==n&&(o=Xs())!==n&&(s=Zs())!==n&&(a=pc())!==n?t=r=[r,i,o,s,a]:(ms=t,t=n),t}())!==n)if((i=zs())!==n)if((o=function(){var t,r,i,o,s;return t=ms,(r=function(){var e,t;return e=ms,(t=ya())===n&&(t=Aa())===n&&(t=Ta()),t!==n&&(ys=e,t=Lo()),e=t}())!==n?(i=ms,(o=function(){var t,r;return t=ms,Ks()!==n?(58===e.charCodeAt(ms)?(r=D,ms++):(r=n,0===bs&&Os(U)),r!==n&&Ks()!==n?(ys=t,t=Be()):(ms=t,t=n)):(ms=t,t=n),t}())!==n&&(s=function(){var e,t,r,i,o,s,a;return e=ms,t=ms,(r=Ns())===n&&(r=null),r!==n?((i=Ns())===n&&(i=null),i!==n?((o=Ns())===n&&(o=null),o!==n?((s=Ns())===n&&(s=null),s!==n?((a=Ns())===n&&(a=null),a!==n?t=r=[r,i,o,s,a]:(ms=t,t=n)):(ms=t,t=n)):(ms=t,t=n)):(ms=t,t=n)):(ms=t,t=n),t!==n&&(ys=e,t=Fo(t)),e=t}())!==n?i=o=[o,s]:(ms=i,i=n),i===n&&(i=null),i!==n?t=r=[r,i]:(ms=t,t=n)):(ms=t,t=n),t}())!==n){for(s=[],a=ms,(c=ia())!==n&&(u=hc())!==n?a=c=[c,u]:(ms=a,a=n);a!==n;)s.push(a),a=ms,(c=ia())!==n&&(u=hc())!==n?a=c=[c,u]:(ms=a,a=n);s!==n?t=r=[r,i,o,s]:(ms=t,t=n)}else ms=t,t=n;else ms=t,t=n;else ms=t,t=n;return t}function hc(){var t;return(t=function(){var t,r,i;return t=ms,e.substr(ms,3).toLowerCase()===So?(r=e.substr(ms,3),ms+=3):(r=n,0===bs&&Os(To)),r!==n&&ea()!==n&&(i=lc())!==n?(ys=t,r=Co(i),t=r):(ms=t,t=n),t}())===n&&(t=function(){var t,r,i;return t=ms,e.substr(ms,5).toLowerCase()===bo?(r=e.substr(ms,5),ms+=5):(r=n,0===bs&&Os(_o)),r!==n&&ea()!==n&&(i=ma())!==n?(ys=t,r=Ao(i),t=r):(ms=t,t=n),t}())===n&&(t=function(){var t,r,i;return t=ms,e.substr(ms,8).toLowerCase()===wo?(r=e.substr(ms,8),ms+=8):(r=n,0===bs&&Os(Eo)),r!==n&&ea()!==n?((i=Aa())===n&&(i=Ca())===n&&(i=Ta()),i!==n?(ys=t,r=Ro(i),t=r):(ms=t,t=n)):(ms=t,t=n),t}())===n&&(t=function(){var t,r,i;return t=ms,e.substr(ms,6).toLowerCase()===Io?(r=e.substr(ms,6),ms+=6):(r=n,0===bs&&Os(Oo)),r!==n&&ea()!==n&&(i=Xs())!==n?(ys=t,r=xo(i),t=r):(ms=t,t=n),t}())===n&&(t=function(){var t,r,i,o;if(t=ms,e.substr(ms,5).toLowerCase()===Po?(r=e.substr(ms,5),ms+=5):(r=n,0===bs&&Os(No)),r!==n)if(ea()!==n){for(i=[],o=Ns();o!==n;)i.push(o),o=Ns();i!==n?(ys=t,r=Do(i),t=r):(ms=t,t=n)}else ms=t,t=n;else ms=t,t=n;return t}())===n&&(t=Ya()),t}function pc(){var t,r;return t=ms,e.substr(ms,3).toLowerCase()===kt?(r=e.substr(ms,3),ms+=3):(r=n,0===bs&&Os(Ho)),r===n&&(e.substr(ms,3).toLowerCase()===qt?(r=e.substr(ms,3),ms+=3):(r=n,0===bs&&Os(ko)),r===n&&(e.substr(ms,3).toLowerCase()===Bt?(r=e.substr(ms,3),ms+=3):(r=n,0===bs&&Os(Mo)),r===n&&(e.substr(ms,4).toLowerCase()===Lt?(r=e.substr(ms,4),ms+=4):(r=n,0===bs&&Os(qo)),r===n&&(r=Xs())))),r!==n&&(ys=t,r=jo(r)),t=r}function lc(){var e,t,r,i,o;return e=ms,t=ms,(r=Ns())!==n?((i=Ns())===n&&(i=null),i!==n?((o=Ns())===n&&(o=null),o!==n?t=r=[r,i,o]:(ms=t,t=n)):(ms=t,t=n)):(ms=t,t=n),t!==n&&(ys=e,t=Bo(t)),e=t}function fc(){var t;return(t=function(){var t,r,i;return t=ms,e.substr(ms,9)===Wo?(r=Wo,ms+=9):(r=n,0===bs&&Os(zo)),r!==n&&ea()!==n?(e.substr(ms,3)===Ko?(i=Ko,ms+=3):(i=n,0===bs&&Os(Vo)),i===n&&(e.substr(ms,3)===Yo?(i=Yo,ms+=3):(i=n,0===bs&&Os($o))),i!==n?(ys=t,r=Xo(i),t=r):(ms=t,t=n)):(ms=t,t=n),t}())===n&&(t=Ya()),t}function gc(){var t,r,i,o,s;return t=ms,(r=function(){var e,t;return e=ms,(t=Aa())===n&&(t=Ta())===n&&(t=qa()),t!==n&&(ys=e,t=ns(t)),e=t}())!==n?(i=ms,58===e.charCodeAt(ms)?(o=D,ms++):(o=n,0===bs&&Os(U)),o!==n&&(s=Ea())!==n?i=o=[o,s]:(ms=i,i=n),i===n&&(i=null),i!==n?t=r=[r,i]:(ms=t,t=n)):(ms=t,t=n),t}function vc(){var e,t,r,i,o;return e=ms,(t=Us())!==n&&(r=Us())!==n&&(i=Us())!==n&&(o=Us())!==n?e=t=[t,r,i,o]:(ms=e,e=n),e}function mc(){var t,r,i,o;return t=ms,e.substr(ms,3)===gs?(r=gs,ms+=3):(r=n,0===bs&&Os(vs)),r!==n&&(i=ea())!==n&&(o=function(){var t,r,i,o,s,a;return t=ms,(r=oa())!==n&&(i=Gs())!==n?(64===e.charCodeAt(ms)?(o=H,ms++):(o=n,0===bs&&Os(k)),o!==n?((s=Gs())===n&&(s=ma()),s!==n&&(a=sa())!==n?t=r=[r,i,o,s,a]:(ms=t,t=n)):(ms=t,t=n)):(ms=t,t=n),t}())!==n?t=r=[r,i,o]:(ms=t,t=n),t}if(t.data={},(r=c())!==n&&ms===e.length)return r;throw r!==n&&ms>>2]|=e[i]<<24-i%4*8;t.call(this,n,r)}else t.apply(this,arguments)}).prototype=e}}(),n.lib.WordArray)},function(e,t,r){var n;e.exports=(n=r(0),function(){var e=n,t=e.lib.WordArray,r=e.enc;function i(e){return e<<8&4278255360|e>>>8&16711935}r.Utf16=r.Utf16BE={stringify:function(e){for(var t=e.words,r=e.sigBytes,n=[],i=0;i>>2]>>>16-i%4*8&65535;n.push(String.fromCharCode(o))}return n.join("")},parse:function(e){for(var r=e.length,n=[],i=0;i>>1]|=e.charCodeAt(i)<<16-i%2*16;return t.create(n,2*r)}},r.Utf16LE={stringify:function(e){for(var t=e.words,r=e.sigBytes,n=[],o=0;o>>2]>>>16-o%4*8&65535);n.push(String.fromCharCode(s))}return n.join("")},parse:function(e){for(var r=e.length,n=[],o=0;o>>1]|=i(e.charCodeAt(o)<<16-o%2*16);return t.create(n,2*r)}}}(),n.enc.Utf16)},function(e,t,r){var n,i,o,s,a,c;e.exports=(n=r(0),r(38),o=(i=n).lib.WordArray,s=i.algo,a=s.SHA256,c=s.SHA224=a.extend({_doReset:function(){this._hash=new o.init([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428])},_doFinalize:function(){var e=a._doFinalize.call(this);return e.sigBytes-=4,e}}),i.SHA224=a._createHelper(c),i.HmacSHA224=a._createHmacHelper(c),n.SHA224)},function(e,t,r){var n,i,o,s,a,c,u,d;e.exports=(n=r(0),r(21),r(39),o=(i=n).x64,s=o.Word,a=o.WordArray,c=i.algo,u=c.SHA512,d=c.SHA384=u.extend({_doReset:function(){this._hash=new a.init([new s.init(3418070365,3238371032),new s.init(1654270250,914150663),new s.init(2438529370,812702999),new s.init(355462360,4144912697),new s.init(1731405415,4290775857),new s.init(2394180231,1750603025),new s.init(3675008525,1694076839),new s.init(1203062813,3204075428)])},_doFinalize:function(){var e=u._doFinalize.call(this);return e.sigBytes-=16,e}}),i.SHA384=u._createHelper(d),i.HmacSHA384=u._createHmacHelper(d),n.SHA384)},function(e,t,r){var n;e.exports=(n=r(0),r(21),function(e){var t=n,r=t.lib,i=r.WordArray,o=r.Hasher,s=t.x64.Word,a=t.algo,c=[],u=[],d=[];!function(){for(var e=1,t=0,r=0;r<24;r++){c[e+5*t]=(r+1)*(r+2)/2%64;var n=(2*e+3*t)%5;e=t%5,t=n}for(e=0;e<5;e++)for(t=0;t<5;t++)u[e+5*t]=t+(2*e+3*t)%5*5;for(var i=1,o=0;o<24;o++){for(var a=0,h=0,p=0;p<7;p++){if(1&i){var l=(1<>>24)|4278255360&(o<<24|o>>>8),s=16711935&(s<<8|s>>>24)|4278255360&(s<<24|s>>>8),(I=r[i]).high^=s,I.low^=o}for(var a=0;a<24;a++){for(var p=0;p<5;p++){for(var l=0,f=0,g=0;g<5;g++)l^=(I=r[p+5*g]).high,f^=I.low;var v=h[p];v.high=l,v.low=f}for(p=0;p<5;p++){var m=h[(p+4)%5],y=h[(p+1)%5],S=y.high,T=y.low;for(l=m.high^(S<<1|T>>>31),f=m.low^(T<<1|S>>>31),g=0;g<5;g++)(I=r[p+5*g]).high^=l,I.low^=f}for(var C=1;C<25;C++){var b=(I=r[C]).high,_=I.low,A=c[C];A<32?(l=b<>>32-A,f=_<>>32-A):(l=_<>>64-A,f=b<>>64-A);var w=h[u[C]];w.high=l,w.low=f}var E=h[0],R=r[0];for(E.high=R.high,E.low=R.low,p=0;p<5;p++)for(g=0;g<5;g++){var I=r[C=p+5*g],O=h[C],x=h[(p+1)%5+5*g],P=h[(p+2)%5+5*g];I.high=O.high^~x.high&P.high,I.low=O.low^~x.low&P.low}I=r[0];var N=d[a];I.high^=N.high,I.low^=N.low}},_doFinalize:function(){var t=this._data,r=t.words,n=(this._nDataBytes,8*t.sigBytes),o=32*this.blockSize;r[n>>>5]|=1<<24-n%32,r[(e.ceil((n+1)/o)*o>>>5)-1]|=128,t.sigBytes=4*r.length,this._process();for(var s=this._state,a=this.cfg.outputLength/8,c=a/8,u=[],d=0;d>>24)|4278255360&(p<<24|p>>>8),l=16711935&(l<<8|l>>>24)|4278255360&(l<<24|l>>>8),u.push(l),u.push(p)}return new i.init(u,a)},clone:function(){for(var e=o.clone.call(this),t=e._state=this._state.slice(0),r=0;r<25;r++)t[r]=t[r].clone();return e}});t.SHA3=o._createHelper(p),t.HmacSHA3=o._createHmacHelper(p)}(Math),n.SHA3)},function(e,t,r){var n;e.exports=(n=r(0),function(e){var t=n,r=t.lib,i=r.WordArray,o=r.Hasher,s=t.algo,a=i.create([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13]),c=i.create([5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11]),u=i.create([11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6]),d=i.create([8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]),h=i.create([0,1518500249,1859775393,2400959708,2840853838]),p=i.create([1352829926,1548603684,1836072691,2053994217,0]),l=s.RIPEMD160=o.extend({_doReset:function(){this._hash=i.create([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(e,t){for(var r=0;r<16;r++){var n=t+r,i=e[n];e[n]=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8)}var o,s,l,T,C,b,_,A,w,E,R,I=this._hash.words,O=h.words,x=p.words,P=a.words,N=c.words,D=u.words,U=d.words;for(b=o=I[0],_=s=I[1],A=l=I[2],w=T=I[3],E=C=I[4],r=0;r<80;r+=1)R=o+e[t+P[r]]|0,R+=r<16?f(s,l,T)+O[0]:r<32?g(s,l,T)+O[1]:r<48?v(s,l,T)+O[2]:r<64?m(s,l,T)+O[3]:y(s,l,T)+O[4],R=(R=S(R|=0,D[r]))+C|0,o=C,C=T,T=S(l,10),l=s,s=R,R=b+e[t+N[r]]|0,R+=r<16?y(_,A,w)+x[0]:r<32?m(_,A,w)+x[1]:r<48?v(_,A,w)+x[2]:r<64?g(_,A,w)+x[3]:f(_,A,w)+x[4],R=(R=S(R|=0,U[r]))+E|0,b=E,E=w,w=S(A,10),A=_,_=R;R=I[1]+l+w|0,I[1]=I[2]+T+E|0,I[2]=I[3]+C+b|0,I[3]=I[4]+o+_|0,I[4]=I[0]+s+A|0,I[0]=R},_doFinalize:function(){var e=this._data,t=e.words,r=8*this._nDataBytes,n=8*e.sigBytes;t[n>>>5]|=128<<24-n%32,t[14+(n+64>>>9<<4)]=16711935&(r<<8|r>>>24)|4278255360&(r<<24|r>>>8),e.sigBytes=4*(t.length+1),this._process();for(var i=this._hash,o=i.words,s=0;s<5;s++){var a=o[s];o[s]=16711935&(a<<8|a>>>24)|4278255360&(a<<24|a>>>8)}return i},clone:function(){var e=o.clone.call(this);return e._hash=this._hash.clone(),e}});function f(e,t,r){return e^t^r}function g(e,t,r){return e&t|~e&r}function v(e,t,r){return(e|~t)^r}function m(e,t,r){return e&r|t&~r}function y(e,t,r){return e^(t|~r)}function S(e,t){return e<>>32-t}t.RIPEMD160=o._createHelper(l),t.HmacRIPEMD160=o._createHmacHelper(l)}(Math),n.RIPEMD160)},function(e,t,r){var n,i,o,s,a,c,u,d,h;e.exports=(n=r(0),r(25),r(26),o=(i=n).lib,s=o.Base,a=o.WordArray,c=i.algo,u=c.SHA1,d=c.HMAC,h=c.PBKDF2=s.extend({cfg:s.extend({keySize:4,hasher:u,iterations:1}),init:function(e){this.cfg=this.cfg.extend(e)},compute:function(e,t){for(var r=this.cfg,n=d.create(r.hasher,e),i=a.create(),o=a.create([1]),s=i.words,c=o.words,u=r.keySize,h=r.iterations;s.length>24&255)){var t=e>>16&255,r=e>>8&255,n=255&e;255===t?(t=0,255===r?(r=0,255===n?n=0:++n):++r):++t,e=0,e+=t<<16,e+=r<<8,e+=n}else e+=1<<24;return e}var r=e.Encryptor=e.extend({processBlock:function(e,r){var n=this._cipher,i=n.blockSize,o=this._iv,s=this._counter;o&&(s=this._counter=o.slice(0),this._iv=void 0),function(e){0===(e[0]=t(e[0]))&&(e[1]=t(e[1]))}(s);var a=s.slice(0);n.encryptBlock(a,0);for(var c=0;c>>2]|=i<<24-o%4*8,e.sigBytes+=i},unpad:function(e){var t=255&e.words[e.sigBytes-1>>>2];e.sigBytes-=t}},n.pad.Ansix923)},function(e,t,r){var n;e.exports=(n=r(0),r(4),n.pad.Iso10126={pad:function(e,t){var r=4*t,i=r-e.sigBytes%r;e.concat(n.lib.WordArray.random(i-1)).concat(n.lib.WordArray.create([i<<24],1))},unpad:function(e){var t=255&e.words[e.sigBytes-1>>>2];e.sigBytes-=t}},n.pad.Iso10126)},function(e,t,r){var n;e.exports=(n=r(0),r(4),n.pad.Iso97971={pad:function(e,t){e.concat(n.lib.WordArray.create([2147483648],1)),n.pad.ZeroPadding.pad(e,t)},unpad:function(e){n.pad.ZeroPadding.unpad(e),e.sigBytes--}},n.pad.Iso97971)},function(e,t,r){var n;e.exports=(n=r(0),r(4),n.pad.ZeroPadding={pad:function(e,t){var r=4*t;e.clamp(),e.sigBytes+=r-(e.sigBytes%r||r)},unpad:function(e){for(var t=e.words,r=e.sigBytes-1;!(t[r>>>2]>>>24-r%4*8&255);)r--;e.sigBytes=r+1}},n.pad.ZeroPadding)},function(e,t,r){var n;e.exports=(n=r(0),r(4),n.pad.NoPadding={pad:function(){},unpad:function(){}},n.pad.NoPadding)},function(e,t,r){var n,i,o,s;e.exports=(n=r(0),r(4),o=(i=n).lib.CipherParams,s=i.enc.Hex,i.format.Hex={stringify:function(e){return e.ciphertext.toString(s)},parse:function(e){var t=s.parse(e);return o.create({ciphertext:t})}},n.format.Hex)},function(e,t,r){var n;e.exports=(n=r(0),r(16),r(17),r(13),r(4),function(){var e=n,t=e.lib.BlockCipher,r=e.algo,i=[],o=[],s=[],a=[],c=[],u=[],d=[],h=[],p=[],l=[];!function(){for(var e=[],t=0;t<256;t++)e[t]=t<128?t<<1:t<<1^283;var r=0,n=0;for(t=0;t<256;t++){var f=n^n<<1^n<<2^n<<3^n<<4;f=f>>>8^255&f^99,i[r]=f,o[f]=r;var g=e[r],v=e[g],m=e[v],y=257*e[f]^16843008*f;s[r]=y<<24|y>>>8,a[r]=y<<16|y>>>16,c[r]=y<<8|y>>>24,u[r]=y,y=16843009*m^65537*v^257*g^16843008*r,d[f]=y<<24|y>>>8,h[f]=y<<16|y>>>16,p[f]=y<<8|y>>>24,l[f]=y,r?(r=g^e[e[e[m^g]]],n^=e[e[n]]):r=n=1}}();var f=[0,1,2,4,8,16,32,64,128,27,54],g=r.AES=t.extend({_doReset:function(){if(!this._nRounds||this._keyPriorReset!==this._key){for(var e=this._keyPriorReset=this._key,t=e.words,r=e.sigBytes/4,n=4*((this._nRounds=r+6)+1),o=this._keySchedule=[],s=0;s6&&s%r==4&&(a=i[a>>>24]<<24|i[a>>>16&255]<<16|i[a>>>8&255]<<8|i[255&a]):(a=i[(a=a<<8|a>>>24)>>>24]<<24|i[a>>>16&255]<<16|i[a>>>8&255]<<8|i[255&a],a^=f[s/r|0]<<24),o[s]=o[s-r]^a}for(var c=this._invKeySchedule=[],u=0;u>>24]]^h[i[a>>>16&255]]^p[i[a>>>8&255]]^l[i[255&a]]}},encryptBlock:function(e,t){this._doCryptBlock(e,t,this._keySchedule,s,a,c,u,i)},decryptBlock:function(e,t){var r=e[t+1];e[t+1]=e[t+3],e[t+3]=r,this._doCryptBlock(e,t,this._invKeySchedule,d,h,p,l,o),r=e[t+1],e[t+1]=e[t+3],e[t+3]=r},_doCryptBlock:function(e,t,r,n,i,o,s,a){for(var c=this._nRounds,u=e[t]^r[0],d=e[t+1]^r[1],h=e[t+2]^r[2],p=e[t+3]^r[3],l=4,f=1;f>>24]^i[d>>>16&255]^o[h>>>8&255]^s[255&p]^r[l++],v=n[d>>>24]^i[h>>>16&255]^o[p>>>8&255]^s[255&u]^r[l++],m=n[h>>>24]^i[p>>>16&255]^o[u>>>8&255]^s[255&d]^r[l++],y=n[p>>>24]^i[u>>>16&255]^o[d>>>8&255]^s[255&h]^r[l++];u=g,d=v,h=m,p=y}g=(a[u>>>24]<<24|a[d>>>16&255]<<16|a[h>>>8&255]<<8|a[255&p])^r[l++],v=(a[d>>>24]<<24|a[h>>>16&255]<<16|a[p>>>8&255]<<8|a[255&u])^r[l++],m=(a[h>>>24]<<24|a[p>>>16&255]<<16|a[u>>>8&255]<<8|a[255&d])^r[l++],y=(a[p>>>24]<<24|a[u>>>16&255]<<16|a[d>>>8&255]<<8|a[255&h])^r[l++],e[t]=g,e[t+1]=v,e[t+2]=m,e[t+3]=y},keySize:8});e.AES=t._createHelper(g)}(),n.AES)},function(e,t,r){var n;e.exports=(n=r(0),r(16),r(17),r(13),r(4),function(){var e=n,t=e.lib,r=t.WordArray,i=t.BlockCipher,o=e.algo,s=[57,49,41,33,25,17,9,1,58,50,42,34,26,18,10,2,59,51,43,35,27,19,11,3,60,52,44,36,63,55,47,39,31,23,15,7,62,54,46,38,30,22,14,6,61,53,45,37,29,21,13,5,28,20,12,4],a=[14,17,11,24,1,5,3,28,15,6,21,10,23,19,12,4,26,8,16,7,27,20,13,2,41,52,31,37,47,55,30,40,51,45,33,48,44,49,39,56,34,53,46,42,50,36,29,32],c=[1,2,4,6,8,10,12,14,15,17,19,21,23,25,27,28],u=[{0:8421888,268435456:32768,536870912:8421378,805306368:2,1073741824:512,1342177280:8421890,1610612736:8389122,1879048192:8388608,2147483648:514,2415919104:8389120,2684354560:33280,2952790016:8421376,3221225472:32770,3489660928:8388610,3758096384:0,4026531840:33282,134217728:0,402653184:8421890,671088640:33282,939524096:32768,1207959552:8421888,1476395008:512,1744830464:8421378,2013265920:2,2281701376:8389120,2550136832:33280,2818572288:8421376,3087007744:8389122,3355443200:8388610,3623878656:32770,3892314112:514,4160749568:8388608,1:32768,268435457:2,536870913:8421888,805306369:8388608,1073741825:8421378,1342177281:33280,1610612737:512,1879048193:8389122,2147483649:8421890,2415919105:8421376,2684354561:8388610,2952790017:33282,3221225473:514,3489660929:8389120,3758096385:32770,4026531841:0,134217729:8421890,402653185:8421376,671088641:8388608,939524097:512,1207959553:32768,1476395009:8388610,1744830465:2,2013265921:33282,2281701377:32770,2550136833:8389122,2818572289:514,3087007745:8421888,3355443201:8389120,3623878657:0,3892314113:33280,4160749569:8421378},{0:1074282512,16777216:16384,33554432:524288,50331648:1074266128,67108864:1073741840,83886080:1074282496,100663296:1073758208,117440512:16,134217728:540672,150994944:1073758224,167772160:1073741824,184549376:540688,201326592:524304,218103808:0,234881024:16400,251658240:1074266112,8388608:1073758208,25165824:540688,41943040:16,58720256:1073758224,75497472:1074282512,92274688:1073741824,109051904:524288,125829120:1074266128,142606336:524304,159383552:0,176160768:16384,192937984:1074266112,209715200:1073741840,226492416:540672,243269632:1074282496,260046848:16400,268435456:0,285212672:1074266128,301989888:1073758224,318767104:1074282496,335544320:1074266112,352321536:16,369098752:540688,385875968:16384,402653184:16400,419430400:524288,436207616:524304,452984832:1073741840,469762048:540672,486539264:1073758208,503316480:1073741824,520093696:1074282512,276824064:540688,293601280:524288,310378496:1074266112,327155712:16384,343932928:1073758208,360710144:1074282512,377487360:16,394264576:1073741824,411041792:1074282496,427819008:1073741840,444596224:1073758224,461373440:524304,478150656:0,494927872:16400,511705088:1074266128,528482304:540672},{0:260,1048576:0,2097152:67109120,3145728:65796,4194304:65540,5242880:67108868,6291456:67174660,7340032:67174400,8388608:67108864,9437184:67174656,10485760:65792,11534336:67174404,12582912:67109124,13631488:65536,14680064:4,15728640:256,524288:67174656,1572864:67174404,2621440:0,3670016:67109120,4718592:67108868,5767168:65536,6815744:65540,7864320:260,8912896:4,9961472:256,11010048:67174400,12058624:65796,13107200:65792,14155776:67109124,15204352:67174660,16252928:67108864,16777216:67174656,17825792:65540,18874368:65536,19922944:67109120,20971520:256,22020096:67174660,23068672:67108868,24117248:0,25165824:67109124,26214400:67108864,27262976:4,28311552:65792,29360128:67174400,30408704:260,31457280:65796,32505856:67174404,17301504:67108864,18350080:260,19398656:67174656,20447232:0,21495808:65540,22544384:67109120,23592960:256,24641536:67174404,25690112:65536,26738688:67174660,27787264:65796,28835840:67108868,29884416:67109124,30932992:67174400,31981568:4,33030144:65792},{0:2151682048,65536:2147487808,131072:4198464,196608:2151677952,262144:0,327680:4198400,393216:2147483712,458752:4194368,524288:2147483648,589824:4194304,655360:64,720896:2147487744,786432:2151678016,851968:4160,917504:4096,983040:2151682112,32768:2147487808,98304:64,163840:2151678016,229376:2147487744,294912:4198400,360448:2151682112,425984:0,491520:2151677952,557056:4096,622592:2151682048,688128:4194304,753664:4160,819200:2147483648,884736:4194368,950272:4198464,1015808:2147483712,1048576:4194368,1114112:4198400,1179648:2147483712,1245184:0,1310720:4160,1376256:2151678016,1441792:2151682048,1507328:2147487808,1572864:2151682112,1638400:2147483648,1703936:2151677952,1769472:4198464,1835008:2147487744,1900544:4194304,1966080:64,2031616:4096,1081344:2151677952,1146880:2151682112,1212416:0,1277952:4198400,1343488:4194368,1409024:2147483648,1474560:2147487808,1540096:64,1605632:2147483712,1671168:4096,1736704:2147487744,1802240:2151678016,1867776:4160,1933312:2151682048,1998848:4194304,2064384:4198464},{0:128,4096:17039360,8192:262144,12288:536870912,16384:537133184,20480:16777344,24576:553648256,28672:262272,32768:16777216,36864:537133056,40960:536871040,45056:553910400,49152:553910272,53248:0,57344:17039488,61440:553648128,2048:17039488,6144:553648256,10240:128,14336:17039360,18432:262144,22528:537133184,26624:553910272,30720:536870912,34816:537133056,38912:0,43008:553910400,47104:16777344,51200:536871040,55296:553648128,59392:16777216,63488:262272,65536:262144,69632:128,73728:536870912,77824:553648256,81920:16777344,86016:553910272,90112:537133184,94208:16777216,98304:553910400,102400:553648128,106496:17039360,110592:537133056,114688:262272,118784:536871040,122880:0,126976:17039488,67584:553648256,71680:16777216,75776:17039360,79872:537133184,83968:536870912,88064:17039488,92160:128,96256:553910272,100352:262272,104448:553910400,108544:0,112640:553648128,116736:16777344,120832:262144,124928:537133056,129024:536871040},{0:268435464,256:8192,512:270532608,768:270540808,1024:268443648,1280:2097152,1536:2097160,1792:268435456,2048:0,2304:268443656,2560:2105344,2816:8,3072:270532616,3328:2105352,3584:8200,3840:270540800,128:270532608,384:270540808,640:8,896:2097152,1152:2105352,1408:268435464,1664:268443648,1920:8200,2176:2097160,2432:8192,2688:268443656,2944:270532616,3200:0,3456:270540800,3712:2105344,3968:268435456,4096:268443648,4352:270532616,4608:270540808,4864:8200,5120:2097152,5376:268435456,5632:268435464,5888:2105344,6144:2105352,6400:0,6656:8,6912:270532608,7168:8192,7424:268443656,7680:270540800,7936:2097160,4224:8,4480:2105344,4736:2097152,4992:268435464,5248:268443648,5504:8200,5760:270540808,6016:270532608,6272:270540800,6528:270532616,6784:8192,7040:2105352,7296:2097160,7552:0,7808:268435456,8064:268443656},{0:1048576,16:33555457,32:1024,48:1049601,64:34604033,80:0,96:1,112:34603009,128:33555456,144:1048577,160:33554433,176:34604032,192:34603008,208:1025,224:1049600,240:33554432,8:34603009,24:0,40:33555457,56:34604032,72:1048576,88:33554433,104:33554432,120:1025,136:1049601,152:33555456,168:34603008,184:1048577,200:1024,216:34604033,232:1,248:1049600,256:33554432,272:1048576,288:33555457,304:34603009,320:1048577,336:33555456,352:34604032,368:1049601,384:1025,400:34604033,416:1049600,432:1,448:0,464:34603008,480:33554433,496:1024,264:1049600,280:33555457,296:34603009,312:1,328:33554432,344:1048576,360:1025,376:34604032,392:33554433,408:34603008,424:0,440:34604033,456:1049601,472:1024,488:33555456,504:1048577},{0:134219808,1:131072,2:134217728,3:32,4:131104,5:134350880,6:134350848,7:2048,8:134348800,9:134219776,10:133120,11:134348832,12:2080,13:0,14:134217760,15:133152,2147483648:2048,2147483649:134350880,2147483650:134219808,2147483651:134217728,2147483652:134348800,2147483653:133120,2147483654:133152,2147483655:32,2147483656:134217760,2147483657:2080,2147483658:131104,2147483659:134350848,2147483660:0,2147483661:134348832,2147483662:134219776,2147483663:131072,16:133152,17:134350848,18:32,19:2048,20:134219776,21:134217760,22:134348832,23:131072,24:0,25:131104,26:134348800,27:134219808,28:134350880,29:133120,30:2080,31:134217728,2147483664:131072,2147483665:2048,2147483666:134348832,2147483667:133152,2147483668:32,2147483669:134348800,2147483670:134217728,2147483671:134219808,2147483672:134350880,2147483673:134217760,2147483674:134219776,2147483675:0,2147483676:133120,2147483677:2080,2147483678:131104,2147483679:134350848}],d=[4160749569,528482304,33030144,2064384,129024,8064,504,2147483679],h=o.DES=i.extend({_doReset:function(){for(var e=this._key.words,t=[],r=0;r<56;r++){var n=s[r]-1;t[r]=e[n>>>5]>>>31-n%32&1}for(var i=this._subKeys=[],o=0;o<16;o++){var u=i[o]=[],d=c[o];for(r=0;r<24;r++)u[r/6|0]|=t[(a[r]-1+d)%28]<<31-r%6,u[4+(r/6|0)]|=t[28+(a[r+24]-1+d)%28]<<31-r%6;for(u[0]=u[0]<<1|u[0]>>>31,r=1;r<7;r++)u[r]=u[r]>>>4*(r-1)+3;u[7]=u[7]<<5|u[7]>>>27}var h=this._invSubKeys=[];for(r=0;r<16;r++)h[r]=i[15-r]},encryptBlock:function(e,t){this._doCryptBlock(e,t,this._subKeys)},decryptBlock:function(e,t){this._doCryptBlock(e,t,this._invSubKeys)},_doCryptBlock:function(e,t,r){this._lBlock=e[t],this._rBlock=e[t+1],p.call(this,4,252645135),p.call(this,16,65535),l.call(this,2,858993459),l.call(this,8,16711935),p.call(this,1,1431655765);for(var n=0;n<16;n++){for(var i=r[n],o=this._lBlock,s=this._rBlock,a=0,c=0;c<8;c++)a|=u[c][((s^i[c])&d[c])>>>0];this._lBlock=s,this._rBlock=o^a}var h=this._lBlock;this._lBlock=this._rBlock,this._rBlock=h,p.call(this,1,1431655765),l.call(this,8,16711935),l.call(this,2,858993459),p.call(this,16,65535),p.call(this,4,252645135),e[t]=this._lBlock,e[t+1]=this._rBlock},keySize:2,ivSize:2,blockSize:2});function p(e,t){var r=(this._lBlock>>>e^this._rBlock)&t;this._rBlock^=r,this._lBlock^=r<>>e^this._lBlock)&t;this._lBlock^=r,this._rBlock^=r<>>2]>>>24-s%4*8&255;o=(o+n[i]+a)%256;var c=n[i];n[i]=n[o],n[o]=c}this._i=this._j=0},_doProcessBlock:function(e,t){e[t]^=o.call(this)},keySize:8,ivSize:0});function o(){for(var e=this._S,t=this._i,r=this._j,n=0,i=0;i<4;i++){r=(r+e[t=(t+1)%256])%256;var o=e[t];e[t]=e[r],e[r]=o,n|=e[(e[t]+e[r])%256]<<24-8*i}return this._i=t,this._j=r,n}e.RC4=t._createHelper(i);var s=r.RC4Drop=i.extend({cfg:i.cfg.extend({drop:192}),_doReset:function(){i._doReset.call(this);for(var e=this.cfg.drop;e>0;e--)o.call(this)}});e.RC4Drop=t._createHelper(s)}(),n.RC4)},function(e,t,r){var n;e.exports=(n=r(0),r(16),r(17),r(13),r(4),function(){var e=n,t=e.lib.StreamCipher,r=e.algo,i=[],o=[],s=[],a=r.Rabbit=t.extend({_doReset:function(){for(var e=this._key.words,t=this.cfg.iv,r=0;r<4;r++)e[r]=16711935&(e[r]<<8|e[r]>>>24)|4278255360&(e[r]<<24|e[r]>>>8);var n=this._X=[e[0],e[3]<<16|e[2]>>>16,e[1],e[0]<<16|e[3]>>>16,e[2],e[1]<<16|e[0]>>>16,e[3],e[2]<<16|e[1]>>>16],i=this._C=[e[2]<<16|e[2]>>>16,4294901760&e[0]|65535&e[1],e[3]<<16|e[3]>>>16,4294901760&e[1]|65535&e[2],e[0]<<16|e[0]>>>16,4294901760&e[2]|65535&e[3],e[1]<<16|e[1]>>>16,4294901760&e[3]|65535&e[0]];for(this._b=0,r=0;r<4;r++)c.call(this);for(r=0;r<8;r++)i[r]^=n[r+4&7];if(t){var o=t.words,s=o[0],a=o[1],u=16711935&(s<<8|s>>>24)|4278255360&(s<<24|s>>>8),d=16711935&(a<<8|a>>>24)|4278255360&(a<<24|a>>>8),h=u>>>16|4294901760&d,p=d<<16|65535&u;for(i[0]^=u,i[1]^=h,i[2]^=d,i[3]^=p,i[4]^=u,i[5]^=h,i[6]^=d,i[7]^=p,r=0;r<4;r++)c.call(this)}},_doProcessBlock:function(e,t){var r=this._X;c.call(this),i[0]=r[0]^r[5]>>>16^r[3]<<16,i[1]=r[2]^r[7]>>>16^r[5]<<16,i[2]=r[4]^r[1]>>>16^r[7]<<16,i[3]=r[6]^r[3]>>>16^r[1]<<16;for(var n=0;n<4;n++)i[n]=16711935&(i[n]<<8|i[n]>>>24)|4278255360&(i[n]<<24|i[n]>>>8),e[t+n]^=i[n]},blockSize:4,ivSize:2});function c(){for(var e=this._X,t=this._C,r=0;r<8;r++)o[r]=t[r];for(t[0]=t[0]+1295307597+this._b|0,t[1]=t[1]+3545052371+(t[0]>>>0>>0?1:0)|0,t[2]=t[2]+886263092+(t[1]>>>0>>0?1:0)|0,t[3]=t[3]+1295307597+(t[2]>>>0>>0?1:0)|0,t[4]=t[4]+3545052371+(t[3]>>>0>>0?1:0)|0,t[5]=t[5]+886263092+(t[4]>>>0>>0?1:0)|0,t[6]=t[6]+1295307597+(t[5]>>>0>>0?1:0)|0,t[7]=t[7]+3545052371+(t[6]>>>0>>0?1:0)|0,this._b=t[7]>>>0>>0?1:0,r=0;r<8;r++){var n=e[r]+t[r],i=65535&n,a=n>>>16,c=((i*i>>>17)+i*a>>>15)+a*a,u=((4294901760&n)*n|0)+((65535&n)*n|0);s[r]=c^u}e[0]=s[0]+(s[7]<<16|s[7]>>>16)+(s[6]<<16|s[6]>>>16)|0,e[1]=s[1]+(s[0]<<8|s[0]>>>24)+s[7]|0,e[2]=s[2]+(s[1]<<16|s[1]>>>16)+(s[0]<<16|s[0]>>>16)|0,e[3]=s[3]+(s[2]<<8|s[2]>>>24)+s[1]|0,e[4]=s[4]+(s[3]<<16|s[3]>>>16)+(s[2]<<16|s[2]>>>16)|0,e[5]=s[5]+(s[4]<<8|s[4]>>>24)+s[3]|0,e[6]=s[6]+(s[5]<<16|s[5]>>>16)+(s[4]<<16|s[4]>>>16)|0,e[7]=s[7]+(s[6]<<8|s[6]>>>24)+s[5]|0}e.Rabbit=t._createHelper(a)}(),n.Rabbit)},function(e,t,r){var n;e.exports=(n=r(0),r(16),r(17),r(13),r(4),function(){var e=n,t=e.lib.StreamCipher,r=e.algo,i=[],o=[],s=[],a=r.RabbitLegacy=t.extend({_doReset:function(){var e=this._key.words,t=this.cfg.iv,r=this._X=[e[0],e[3]<<16|e[2]>>>16,e[1],e[0]<<16|e[3]>>>16,e[2],e[1]<<16|e[0]>>>16,e[3],e[2]<<16|e[1]>>>16],n=this._C=[e[2]<<16|e[2]>>>16,4294901760&e[0]|65535&e[1],e[3]<<16|e[3]>>>16,4294901760&e[1]|65535&e[2],e[0]<<16|e[0]>>>16,4294901760&e[2]|65535&e[3],e[1]<<16|e[1]>>>16,4294901760&e[3]|65535&e[0]];this._b=0;for(var i=0;i<4;i++)c.call(this);for(i=0;i<8;i++)n[i]^=r[i+4&7];if(t){var o=t.words,s=o[0],a=o[1],u=16711935&(s<<8|s>>>24)|4278255360&(s<<24|s>>>8),d=16711935&(a<<8|a>>>24)|4278255360&(a<<24|a>>>8),h=u>>>16|4294901760&d,p=d<<16|65535&u;for(n[0]^=u,n[1]^=h,n[2]^=d,n[3]^=p,n[4]^=u,n[5]^=h,n[6]^=d,n[7]^=p,i=0;i<4;i++)c.call(this)}},_doProcessBlock:function(e,t){var r=this._X;c.call(this),i[0]=r[0]^r[5]>>>16^r[3]<<16,i[1]=r[2]^r[7]>>>16^r[5]<<16,i[2]=r[4]^r[1]>>>16^r[7]<<16,i[3]=r[6]^r[3]>>>16^r[1]<<16;for(var n=0;n<4;n++)i[n]=16711935&(i[n]<<8|i[n]>>>24)|4278255360&(i[n]<<24|i[n]>>>8),e[t+n]^=i[n]},blockSize:4,ivSize:2});function c(){for(var e=this._X,t=this._C,r=0;r<8;r++)o[r]=t[r];for(t[0]=t[0]+1295307597+this._b|0,t[1]=t[1]+3545052371+(t[0]>>>0>>0?1:0)|0,t[2]=t[2]+886263092+(t[1]>>>0>>0?1:0)|0,t[3]=t[3]+1295307597+(t[2]>>>0>>0?1:0)|0,t[4]=t[4]+3545052371+(t[3]>>>0>>0?1:0)|0,t[5]=t[5]+886263092+(t[4]>>>0>>0?1:0)|0,t[6]=t[6]+1295307597+(t[5]>>>0>>0?1:0)|0,t[7]=t[7]+3545052371+(t[6]>>>0>>0?1:0)|0,this._b=t[7]>>>0>>0?1:0,r=0;r<8;r++){var n=e[r]+t[r],i=65535&n,a=n>>>16,c=((i*i>>>17)+i*a>>>15)+a*a,u=((4294901760&n)*n|0)+((65535&n)*n|0);s[r]=c^u}e[0]=s[0]+(s[7]<<16|s[7]>>>16)+(s[6]<<16|s[6]>>>16)|0,e[1]=s[1]+(s[0]<<8|s[0]>>>24)+s[7]|0,e[2]=s[2]+(s[1]<<16|s[1]>>>16)+(s[0]<<16|s[0]>>>16)|0,e[3]=s[3]+(s[2]<<8|s[2]>>>24)+s[1]|0,e[4]=s[4]+(s[3]<<16|s[3]>>>16)+(s[2]<<16|s[2]>>>16)|0,e[5]=s[5]+(s[4]<<8|s[4]>>>24)+s[3]|0,e[6]=s[6]+(s[5]<<16|s[5]>>>16)+(s[4]<<16|s[4]>>>16)|0,e[7]=s[7]+(s[6]<<8|s[6]>>>24)+s[5]|0}e.RabbitLegacy=t._createHelper(a)}(),n.RabbitLegacy)},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(2),s=r(12),a=r(30),c=r(20),u=function(e){function t(t,r,n){return e.call(this,t,r,n,c.TransactionState.Proceeding,"sip.transaction.ist")||this}return i(t,e),t.prototype.dispose=function(){this.stopProgressExtensionTimer(),this.H&&(clearTimeout(this.H),this.H=void 0),this.I&&(clearTimeout(this.I),this.I=void 0),this.L&&(clearTimeout(this.L),this.L=void 0),e.prototype.dispose.call(this)},Object.defineProperty(t.prototype,"kind",{get:function(){return"ist"},enumerable:!0,configurable:!0}),t.prototype.receiveRequest=function(e){var t=this;switch(this.state){case c.TransactionState.Proceeding:if(e.method===o.C.INVITE)return void(this.lastProvisionalResponse&&this.send(this.lastProvisionalResponse).catch(function(e){t.logTransportError(e,"Failed to send retransmission of provisional response.")}));break;case c.TransactionState.Accepted:if(e.method===o.C.INVITE)return;break;case c.TransactionState.Completed:if(e.method===o.C.INVITE){if(!this.lastFinalResponse)throw new Error("Last final response undefined.");return void this.send(this.lastFinalResponse).catch(function(e){t.logTransportError(e,"Failed to send retransmission of final response.")})}if(e.method===o.C.ACK)return void this.stateTransition(c.TransactionState.Confirmed);break;case c.TransactionState.Confirmed:case c.TransactionState.Terminated:if(e.method===o.C.INVITE||e.method===o.C.ACK)return;break;default:throw new Error("Invalid state "+this.state)}var r="INVITE server transaction received unexpected "+e.method+" request while in state "+this.state+".";this.logger.warn(r)},t.prototype.receiveResponse=function(e,t){var r=this;if(e<100||e>699)throw new Error("Invalid status code "+e);switch(this.state){case c.TransactionState.Proceeding:if(e>=100&&e<=199)return this.lastProvisionalResponse=t,e>100&&this.startProgressExtensionTimer(),void this.send(t).catch(function(e){r.logTransportError(e,"Failed to send 1xx response.")});if(e>=200&&e<=299)return this.lastFinalResponse=t,this.stateTransition(c.TransactionState.Accepted),void this.send(t).catch(function(e){r.logTransportError(e,"Failed to send 2xx response.")});if(e>=300&&e<=699)return this.lastFinalResponse=t,this.stateTransition(c.TransactionState.Completed),void this.send(t).catch(function(e){r.logTransportError(e,"Failed to send non-2xx final response.")});break;case c.TransactionState.Accepted:if(e>=200&&e<=299)return void this.send(t).catch(function(e){r.logTransportError(e,"Failed to send 2xx response.")});break;case c.TransactionState.Completed:case c.TransactionState.Confirmed:case c.TransactionState.Terminated:break;default:throw new Error("Invalid state "+this.state)}var n="INVITE server transaction received unexpected "+e+" response from TU while in state "+this.state+".";throw this.logger.error(n),new Error(n)},t.prototype.retransmitAcceptedResponse=function(){var e=this;this.state===c.TransactionState.Accepted&&this.lastFinalResponse&&this.send(this.lastFinalResponse).catch(function(t){e.logTransportError(t,"Failed to send 2xx response.")})},t.prototype.onTransportError=function(e){this.user.onTransportError&&this.user.onTransportError(e)},t.prototype.typeToString=function(){return"INVITE server transaction"},t.prototype.stateTransition=function(e){var t=this,r=function(){throw new Error("Invalid state transition from "+t.state+" to "+e)};switch(e){case c.TransactionState.Proceeding:r();break;case c.TransactionState.Accepted:case c.TransactionState.Completed:this.state!==c.TransactionState.Proceeding&&r();break;case c.TransactionState.Confirmed:this.state!==c.TransactionState.Completed&&r();break;case c.TransactionState.Terminated:this.state!==c.TransactionState.Accepted&&this.state!==c.TransactionState.Completed&&this.state!==c.TransactionState.Confirmed&&r();break;default:r()}this.stopProgressExtensionTimer(),e===c.TransactionState.Accepted&&(this.L=setTimeout(function(){return t.timer_L()},s.Timers.TIMER_L)),e===c.TransactionState.Completed&&(this.H=setTimeout(function(){return t.timer_H()},s.Timers.TIMER_H)),e===c.TransactionState.Confirmed&&(this.I=setTimeout(function(){return t.timer_I()},s.Timers.TIMER_I)),e===c.TransactionState.Terminated&&this.dispose(),this.setState(e)},t.prototype.startProgressExtensionTimer=function(){var e=this;void 0===this.progressExtensionTimer&&(this.progressExtensionTimer=setInterval(function(){if(e.logger.debug("Progress extension timer expired for INVITE server transaction "+e.id+"."),!e.lastProvisionalResponse)throw new Error("Last provisional response undefined.");e.send(e.lastProvisionalResponse).catch(function(t){e.logTransportError(t,"Failed to send retransmission of provisional response.")})},s.Timers.PROVISIONAL_RESPONSE_INTERVAL))},t.prototype.stopProgressExtensionTimer=function(){void 0!==this.progressExtensionTimer&&(clearInterval(this.progressExtensionTimer),this.progressExtensionTimer=void 0)},t.prototype.timer_G=function(){},t.prototype.timer_H=function(){this.logger.debug("Timer H expired for INVITE server transaction "+this.id+"."),this.state===c.TransactionState.Completed&&(this.logger.warn("ACK to negative final response was never received, terminating transaction."),this.stateTransition(c.TransactionState.Terminated))},t.prototype.timer_I=function(){this.logger.debug("Timer I expired for INVITE server transaction "+this.id+"."),this.stateTransition(c.TransactionState.Terminated)},t.prototype.timer_L=function(){this.logger.debug("Timer L expired for INVITE server transaction "+this.id+"."),this.state===c.TransactionState.Accepted&&this.stateTransition(c.TransactionState.Terminated)},t}(a.ServerTransaction);t.InviteServerTransaction=u},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(12),s=r(28),a=r(20),c=function(e){function t(t,r,n){var i=e.call(this,t,r,n,a.TransactionState.Trying,"sip.transaction.nict")||this;return i.F=setTimeout(function(){return i.timer_F()},o.Timers.TIMER_F),i.send(t.toString()).catch(function(e){i.logTransportError(e,"Failed to send initial outgoing request.")}),i}return i(t,e),t.prototype.dispose=function(){this.F&&(clearTimeout(this.F),this.F=void 0),this.K&&(clearTimeout(this.K),this.K=void 0),e.prototype.dispose.call(this)},Object.defineProperty(t.prototype,"kind",{get:function(){return"nict"},enumerable:!0,configurable:!0}),t.prototype.receiveResponse=function(e){var t=e.statusCode;if(!t||t<100||t>699)throw new Error("Invalid status code "+t);switch(this.state){case a.TransactionState.Trying:if(t>=100&&t<=199)return this.stateTransition(a.TransactionState.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=699)return this.stateTransition(a.TransactionState.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case a.TransactionState.Proceeding:if(t>=100&&t<=199&&this.user.receiveResponse)return this.user.receiveResponse(e);if(t>=200&&t<=699)return this.stateTransition(a.TransactionState.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));case a.TransactionState.Completed:case a.TransactionState.Terminated:return;default:throw new Error("Invalid state "+this.state)}var r="Non-INVITE client transaction received unexpected "+t+" response while in state "+this.state+".";this.logger.warn(r)},t.prototype.onTransportError=function(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(a.TransactionState.Terminated,!0)},t.prototype.typeToString=function(){return"non-INVITE client transaction"},t.prototype.stateTransition=function(e,t){var r=this;void 0===t&&(t=!1);var n=function(){throw new Error("Invalid state transition from "+r.state+" to "+e)};switch(e){case a.TransactionState.Trying:n();break;case a.TransactionState.Proceeding:this.state!==a.TransactionState.Trying&&n();break;case a.TransactionState.Completed:this.state!==a.TransactionState.Trying&&this.state!==a.TransactionState.Proceeding&&n();break;case a.TransactionState.Terminated:this.state!==a.TransactionState.Trying&&this.state!==a.TransactionState.Proceeding&&this.state!==a.TransactionState.Completed&&(t||n());break;default:n()}e===a.TransactionState.Completed&&(this.F&&(clearTimeout(this.F),this.F=void 0),this.K=setTimeout(function(){return r.timer_K()},o.Timers.TIMER_K)),e===a.TransactionState.Terminated&&this.dispose(),this.setState(e)},t.prototype.timer_F=function(){this.logger.debug("Timer F expired for non-INVITE client transaction "+this.id+"."),this.state!==a.TransactionState.Trying&&this.state!==a.TransactionState.Proceeding||(this.onRequestTimeout(),this.stateTransition(a.TransactionState.Terminated))},t.prototype.timer_K=function(){this.state===a.TransactionState.Completed&&this.stateTransition(a.TransactionState.Terminated)},t}(s.ClientTransaction);t.NonInviteClientTransaction=c},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(12),s=r(30),a=r(20),c=function(e){function t(t,r,n){return e.call(this,t,r,n,a.TransactionState.Trying,"sip.transaction.nist")||this}return i(t,e),t.prototype.dispose=function(){this.J&&(clearTimeout(this.J),this.J=void 0),e.prototype.dispose.call(this)},Object.defineProperty(t.prototype,"kind",{get:function(){return"nist"},enumerable:!0,configurable:!0}),t.prototype.receiveRequest=function(e){var t=this;switch(this.state){case a.TransactionState.Trying:break;case a.TransactionState.Proceeding:if(!this.lastResponse)throw new Error("Last response undefined.");this.send(this.lastResponse).catch(function(e){t.logTransportError(e,"Failed to send retransmission of provisional response.")});break;case a.TransactionState.Completed:if(!this.lastResponse)throw new Error("Last response undefined.");this.send(this.lastResponse).catch(function(e){t.logTransportError(e,"Failed to send retransmission of final response.")});break;case a.TransactionState.Terminated:break;default:throw new Error("Invalid state "+this.state)}},t.prototype.receiveResponse=function(e,t){var r=this;if(e<100||e>699)throw new Error("Invalid status code "+e);if(e>100&&e<=199)throw new Error("Provisional response other than 100 not allowed.");switch(this.state){case a.TransactionState.Trying:if(this.lastResponse=t,e>=100&&e<200)return this.stateTransition(a.TransactionState.Proceeding),void this.send(t).catch(function(e){r.logTransportError(e,"Failed to send provisional response.")});if(e>=200&&e<=699)return this.stateTransition(a.TransactionState.Completed),void this.send(t).catch(function(e){r.logTransportError(e,"Failed to send final response.")});break;case a.TransactionState.Proceeding:if(this.lastResponse=t,e>=200&&e<=699)return this.stateTransition(a.TransactionState.Completed),void this.send(t).catch(function(e){r.logTransportError(e,"Failed to send final response.")});break;case a.TransactionState.Completed:return;case a.TransactionState.Terminated:break;default:throw new Error("Invalid state "+this.state)}var n="Non-INVITE server transaction received unexpected "+e+" response from TU while in state "+this.state+".";throw this.logger.error(n),new Error(n)},t.prototype.onTransportError=function(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(a.TransactionState.Terminated,!0)},t.prototype.typeToString=function(){return"non-INVITE server transaction"},t.prototype.stateTransition=function(e,t){var r=this;void 0===t&&(t=!1);var n=function(){throw new Error("Invalid state transition from "+r.state+" to "+e)};switch(e){case a.TransactionState.Trying:n();break;case a.TransactionState.Proceeding:this.state!==a.TransactionState.Trying&&n();break;case a.TransactionState.Completed:this.state!==a.TransactionState.Trying&&this.state!==a.TransactionState.Proceeding&&n();break;case a.TransactionState.Terminated:this.state!==a.TransactionState.Proceeding&&this.state!==a.TransactionState.Completed&&(t||n());break;default:n()}e===a.TransactionState.Completed&&(this.J=setTimeout(function(){return r.timer_J()},o.Timers.TIMER_J)),e===a.TransactionState.Terminated&&this.dispose(),this.setState(e)},t.prototype.timer_J=function(){this.logger.debug("Timer J expired for NON-INVITE server transaction "+this.id+"."),this.state===a.TransactionState.Completed&&this.stateTransition(a.TransactionState.Terminated)},t}(s.ServerTransaction);t.NonInviteServerTransaction=c},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(8);function i(e){return!(!e||"string"!=typeof e.content||"string"!=typeof e.contentType||void 0!==e.contentDisposition)||"string"==typeof e.contentDisposition}function o(e){return"application/sdp"===e?"session":"render"}t.fromBodyObj=function(e){var t=e.body,r=e.contentType;return{contentDisposition:o(r),contentType:r,content:t}},t.fromBodyLegacy=function(e){var t="string"==typeof e?e:e.body,r="string"==typeof e?"application/sdp":e.contentType;return{contentDisposition:o(r),contentType:r,content:t}},t.getBody=function(e){var t,r,s,a;if(e instanceof n.IncomingRequest&&e.body&&(t=(a=e.parseHeader("Content-Disposition"))?a.type:void 0,r=e.parseHeader("Content-Type"),s=e.body),e instanceof n.IncomingResponse&&e.body&&(t=(a=e.parseHeader("Content-Disposition"))?a.type:void 0,r=e.parseHeader("Content-Type"),s=e.body),e instanceof n.OutgoingRequest&&e.body)if(t=e.getHeader("Content-Disposition"),r=e.getHeader("Content-Type"),"string"==typeof e.body){if(!r)throw new Error("Header content type header does not equal body content type.");s=e.body}else{if(r&&r!==e.body.contentType)throw new Error("Header content type header does not equal body content type.");r=e.body.contentType,s=e.body.body}if(i(e)&&(t=e.contentDisposition,r=e.contentType,s=e.content),s){if(r&&!t&&(t=o(r)),!t)throw new Error("Content disposition undefined.");if(!r)throw new Error("Content type undefined.");return{contentDisposition:t,contentType:r,content:s}}},t.isBody=i,t.toBodyObj=function(e){return{body:e.content,contentType:e.contentType}}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(8),i=r(5);t.constructOutgoingResponse=function(e,t){var r="\r\n",o=i.Utils.buildStatusLine(t.statusCode,t.reasonPhrase);t.statusCode>=100&&t.statusCode,t.statusCode;var s="From: "+e.getHeader("From")+r,a="Call-ID: "+e.callId+r,c="CSeq: "+e.cseq+" "+e.method+r,u=e.getHeaders("via").reduce(function(e,t){return e+"Via: "+t+r},""),d="To: "+e.getHeader("to");if(t.statusCode>100&&!e.parseHeader("to").hasParam("tag")){var h=t.toTag;h||(h=i.Utils.newTag()),d+=";tag="+h}d+=r;var p=n.getSupportedHeader(e),l="";t.userAgent&&(l="User-Agent: "+t.userAgent+r);var f="";return t.extraHeaders&&(f=t.extraHeaders.reduce(function(e,t){return e+t.trim()+r},"")),o+=u,o+=s,o+=d,o+=c,o+=a,o+=p,o+=l,o+=f,t.body?(o+="Content-Type: "+t.body.contentType+r,o+="Content-Length: "+i.Utils.str_utf8_length(t.body.content)+r+r,o+=t.body.content):o+="Content-Length: 0\r\n\r\n",{message:o}}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e){e.Initial="Initial",e.Early="Early",e.AckWait="AckWait",e.Confirmed="Confirmed",e.Terminated="Terminated"}(t.SessionState||(t.SessionState={})),function(e){e.Initial="Initial",e.HaveLocalOffer="HaveLocalOffer",e.HaveRemoteOffer="HaveRemoteOffer",e.Stable="Stable",e.Closed="Closed"}(t.SignalingState||(t.SignalingState={}))},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(10),s=r(2),a=r(14),c=r(3),u=r(7),d=r(5),h=function(e){function t(t,r,n){void 0===n&&(n={});var i=e.call(this)||this;if(i.C={MIN_DURATION:70,MAX_DURATION:6e3,DEFAULT_DURATION:100,MIN_INTER_TONE_GAP:50,DEFAULT_INTER_TONE_GAP:500},i.type=c.TypeStrings.DTMF,void 0===r)throw new TypeError("Not enough arguments");if(i.logger=t.ua.getLogger("sip.invitecontext.dtmf",t.id),i.owner=t,"string"==typeof r)r=r.toUpperCase();else{if("number"!=typeof r)throw new TypeError("Invalid tone: "+r);r=r.toString()}if(!r.match(/^[0-9A-D#*]$/))throw new TypeError("Invalid tone: "+r);i.tone=r;var o=n.duration,s=n.interToneGap;if(o&&!d.Utils.isDecimal(o))throw new TypeError("Invalid tone duration: "+o);if(o?oi.C.MAX_DURATION?(i.logger.warn("'duration' value is greater than the maximum allowed, setting it to "+i.C.MAX_DURATION+" milliseconds"),o=i.C.MAX_DURATION):o=Math.abs(o):o=i.C.DEFAULT_DURATION,i.duration=o,s&&!d.Utils.isDecimal(s))throw new TypeError("Invalid interToneGap: "+s);return s?s1)this.logger.warn("More than one Via header field present in the response, dropping");else{var t=e.viaBranch+e.method,r=this.userAgentClients.get(t);r?r.transaction.receiveResponse(e):this.logger.warn("Discarding unmatched "+e.statusCode+" response to "+e.method+" "+t+".")}},e}();t.UserAgentCore=d},function(e,t,r){"use strict";function n(e){for(var r in e)t.hasOwnProperty(r)||(t[r]=e[r])}Object.defineProperty(t,"__esModule",{value:!0}),n(r(49)),n(r(50)),n(r(101)),n(r(51)),n(r(102)),n(r(105)),n(r(106)),n(r(107)),n(r(53)),n(r(34)),n(r(108)),n(r(54)),n(r(55)),n(r(56)),n(r(57)),n(r(61)),n(r(109)),n(r(58)),n(r(59)),n(r(110)),n(r(111)),n(r(112)),n(r(6)),n(r(9))},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(1),s=function(e){function t(t,r,n){return e.call(this,o.NonInviteClientTransaction,t,r,n)||this}return i(t,e),t}(r(6).UserAgentClient);t.CancelUserAgentClient=s},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(52),s=r(1),a=function(e){function t(t,r,n){var i=e.call(this,s.InviteClientTransaction,t,r,n)||this;return i.confirmedDialogAcks=new Map,i.confirmedDialogs=new Map,i.earlyDialogs=new Map,i.delegate=n,i}return i(t,e),t.prototype.dispose=function(){this.earlyDialogs.forEach(function(e){return e.dispose()}),this.earlyDialogs.clear(),e.prototype.dispose.call(this)},t.prototype.receiveResponse=function(e){var t=this;if(this.authenticationGuard(e)){var r=e.statusCode?e.statusCode.toString():"";if(!r)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(r):return void(this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e}));case/^1[0-9]{2}$/.test(r):if(!e.toTag)return void this.logger.warn("Non-100 1xx INVITE response received without a to tag, dropping.");var n=o.Dialog.initialDialogStateForUserAgentClient(this.message,e),i=this.earlyDialogs.get(n.id);if(!i){if(!((u=this.transaction)instanceof s.InviteClientTransaction))throw new Error("Transaction not instance of InviteClientTransaction.");i=new o.SessionDialog(u,this.core,n),this.earlyDialogs.set(i.id,i)}if(!i.reliableSequenceGuard(e))return void this.logger.warn("1xx INVITE reliable response received out of order, dropping.");i.signalingStateTransition(e);var a=i;return void(this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e,session:a,prack:function(e){return a.prack(void 0,e)}}));case/^2[0-9]{2}$/.test(r):n=o.Dialog.initialDialogStateForUserAgentClient(this.message,e);var c=this.confirmedDialogs.get(n.id);if(c){if(h=this.confirmedDialogAcks.get(n.id)){if(!((u=this.transaction)instanceof s.InviteClientTransaction))throw new Error("Client transaction not instance of InviteClientTransaction.");u.ackResponse(h.message)}return}if(c=this.earlyDialogs.get(n.id))c.confirm(),c.recomputeRouteSet(e),this.earlyDialogs.delete(c.id),this.confirmedDialogs.set(c.id,c);else{var u;if(!((u=this.transaction)instanceof s.InviteClientTransaction))throw new Error("Transaction not instance of InviteClientTransaction.");c=new o.SessionDialog(u,this.core,n),this.confirmedDialogs.set(c.id,c)}c.signalingStateTransition(e);var d=c;if(this.delegate&&this.delegate.onAccept)this.delegate.onAccept({message:e,session:d,ack:function(e){var r=d.ack(e);return t.confirmedDialogAcks.set(d.id,r),r}});else{var h=d.ack();this.confirmedDialogAcks.set(d.id,h)}return;case/^3[0-9]{2}$/.test(r):return this.earlyDialogs.forEach(function(e){return e.dispose()}),this.earlyDialogs.clear(),void(this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e}));case/^[4-6][0-9]{2}$/.test(r):return this.earlyDialogs.forEach(function(e){return e.dispose()}),this.earlyDialogs.clear(),void(this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e}));default:throw new Error("Invalid status code "+r)}throw new Error("Executing what should be an unreachable code path receiving "+r+" response.")}},t}(r(6).UserAgentClient);t.InviteUserAgentClient=a},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(2),s=r(18),a=r(8),c=r(12),u=r(14),d=r(31),h=r(1),p=r(49),l=r(50),f=r(104),g=r(51),v=r(53),m=r(34),y=r(54),S=r(55),T=r(56),C=r(57),b=r(58),_=r(59),A=function(e){function t(t,r,n,i){var o=e.call(this,r,n)||this;return o.initialTransaction=t,o._signalingState=d.SignalingState.Initial,o.ackWait=!1,o.delegate=i,t instanceof h.InviteServerTransaction&&(o.ackWait=!0),o.early||o.start2xxRetransmissionTimer(),o.signalingStateTransition(t.request),o.logger=r.loggerFactory.getLogger("sip.invite-dialog"),o.logger.log("INVITE dialog "+o.id+" constructed"),o}return i(t,e),t.prototype.dispose=function(){e.prototype.dispose.call(this),this._signalingState=d.SignalingState.Closed,this._offer=void 0,this._answer=void 0,this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.logger.log("INVITE dialog "+this.id+" destroyed")},Object.defineProperty(t.prototype,"sessionState",{get:function(){return this.early?d.SessionState.Early:this.ackWait?d.SessionState.AckWait:this._signalingState===d.SignalingState.Closed?d.SessionState.Terminated:d.SessionState.Confirmed},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"signalingState",{get:function(){return this._signalingState},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"offer",{get:function(){return this._offer},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"answer",{get:function(){return this._answer},enumerable:!0,configurable:!0}),t.prototype.confirm=function(){this.early&&this.start2xxRetransmissionTimer(),e.prototype.confirm.call(this)},t.prototype.reConfirm=function(){this.reinviteUserAgentServer&&this.startReInvite2xxRetransmissionTimer()},t.prototype.ack=function(e){var t;if(void 0===e&&(e={}),this.logger.log("INVITE dialog "+this.id+" sending ACK request"),this.reinviteUserAgentClient){if(!(this.reinviteUserAgentClient.transaction instanceof h.InviteClientTransaction))throw new Error("Transaction not instance of InviteClientTransaction.");t=this.reinviteUserAgentClient.transaction,this.reinviteUserAgentClient=void 0}else{if(!(this.initialTransaction instanceof h.InviteClientTransaction))throw new Error("Initial transaction not instance of InviteClientTransaction.");t=this.initialTransaction}e.cseq=t.request.cseq;var r=this.createOutgoingRequestMessage(o.C.ACK,e);return t.ackResponse(r),this.signalingStateTransition(r),{message:r}},t.prototype.bye=function(e,t){if(this.logger.log("INVITE dialog "+this.id+" sending BYE request"),this.initialTransaction instanceof h.InviteServerTransaction){if(this.early)throw new Error("UAS MUST NOT send a BYE on early dialogs.");if(this.ackWait&&this.initialTransaction.state!==h.TransactionState.Terminated)throw new Error("UAS MUST NOT send a BYE on a confirmed dialog until it has received an ACK for its 2xx response or until the server transaction times out.")}return new p.ByeUserAgentClient(this,e,t)},t.prototype.info=function(e,t){if(this.logger.log("INVITE dialog "+this.id+" sending INFO request"),this.early)throw new Error("Dialog not confirmed.");return new f.InfoUserAgentClient(this,e,t)},t.prototype.invite=function(e,t){if(this.logger.log("INVITE dialog "+this.id+" sending INVITE request"),this.early)throw new Error("Dialog not confirmed.");if(this.reinviteUserAgentClient)throw new Error("There is an ongoing re-INVITE client transaction.");if(this.reinviteUserAgentServer)throw new Error("There is an ongoing re-INVITE server transaction.");return new T.ReInviteUserAgentClient(this,e,t)},t.prototype.notify=function(e,t){if(this.logger.log("INVITE dialog "+this.id+" sending NOTIFY request"),this.early)throw new Error("Dialog not confirmed.");return new v.NotifyUserAgentClient(this,e,t)},t.prototype.prack=function(e,t){return this.logger.log("INVITE dialog "+this.id+" sending PRACK request"),new y.PrackUserAgentClient(this,e,t)},t.prototype.refer=function(e,t){if(this.logger.log("INVITE dialog "+this.id+" sending REFER request"),this.early)throw new Error("Dialog not confirmed.");return new b.ReferUserAgentClient(this,e,t)},t.prototype.receiveRequest=function(t){if(this.logger.log("INVITE dialog "+this.id+" received "+t.method+" request"),t.method===o.C.ACK){if(this.ackWait){if(this.initialTransaction instanceof h.InviteClientTransaction)return void this.logger.warn("INVITE dialog "+this.id+" received unexpected "+t.method+" request, dropping.");if(this.initialTransaction.request.cseq!==t.cseq)return void this.logger.warn("INVITE dialog "+this.id+" received unexpected "+t.method+" request, dropping.");this.ackWait=!1}else{if(!this.reinviteUserAgentServer)return void this.logger.warn("INVITE dialog "+this.id+" received unexpected "+t.method+" request, dropping.");if(this.reinviteUserAgentServer.transaction.request.cseq!==t.cseq)return void this.logger.warn("INVITE dialog "+this.id+" received unexpected "+t.method+" request, dropping.");this.reinviteUserAgentServer=void 0}return this.signalingStateTransition(t),void(this.delegate&&this.delegate.onAck&&this.delegate.onAck({message:t}))}if(this.sequenceGuard(t)){if(t.method===o.C.INVITE){if(this.reinviteUserAgentServer){var r=["Retry-After: "+(Math.floor(10*Math.random())+1)];return void this.core.replyStateless(t,{statusCode:500,extraHeaders:r})}if(this.reinviteUserAgentClient)return void this.core.replyStateless(t,{statusCode:491})}if(e.prototype.receiveRequest.call(this,t),t.method===o.C.INVITE){var n=t.parseHeader("contact");if(!n)throw new Error("Contact undefined.");if(!(n instanceof s.NameAddrHeader))throw new Error("Contact not instance of NameAddrHeader.");this.dialogState.remoteTarget=n.uri}switch(t.method){case o.C.BYE:var i=new l.ByeUserAgentServer(this,t);this.delegate&&this.delegate.onBye?this.delegate.onBye(i):i.accept(),this.dispose();break;case o.C.INFO:i=new g.InfoUserAgentServer(this,t);this.delegate&&this.delegate.onInfo?this.delegate.onInfo(i):i.reject({statusCode:469,extraHeaders:["Recv-Info :"]});break;case o.C.INVITE:i=new C.ReInviteUserAgentServer(this,t);this.delegate&&this.delegate.onInvite?this.delegate.onInvite(i):i.reject({statusCode:488});break;case o.C.NOTIFY:i=new m.NotifyUserAgentServer(this,t);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(i):i.accept();break;case o.C.PRACK:i=new S.PrackUserAgentServer(this,t);this.delegate&&this.delegate.onPrack?this.delegate.onPrack(i):i.accept();break;case o.C.REFER:i=new _.ReferUserAgentServer(this,t);this.delegate&&this.delegate.onRefer?this.delegate.onRefer(i):i.reject();break;default:this.logger.log("INVITE dialog "+this.id+" received unimplemented "+t.method+" request"),this.core.replyStateless(t,{statusCode:501})}}else this.logger.log("INVITE dialog "+this.id+" rejected out of order "+t.method+" request.")},t.prototype.reliableSequenceGuard=function(e){var t=e.statusCode;if(!t)throw new Error("Status code undefined");if(t>100&&t<200){var r=e.getHeader("require"),n=e.getHeader("rseq"),i=r&&r.includes("100rel")&&n?Number(n):void 0;if(i){if(this.rseq&&this.rseq+1!==i)return!1;this.rseq||(this.rseq=i)}}return!0},t.prototype.signalingStateTransition=function(e){var t=u.getBody(e);if(t&&"session"===t.contentDisposition){if(e instanceof a.IncomingRequest)switch(this._signalingState){case d.SignalingState.Initial:case d.SignalingState.Stable:this._signalingState=d.SignalingState.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case d.SignalingState.HaveLocalOffer:this._signalingState=d.SignalingState.Stable,this._answer=t;break;case d.SignalingState.HaveRemoteOffer:case d.SignalingState.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof a.IncomingResponse)switch(this._signalingState){case d.SignalingState.Initial:case d.SignalingState.Stable:this._signalingState=d.SignalingState.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case d.SignalingState.HaveLocalOffer:this._signalingState=d.SignalingState.Stable,this._answer=t;break;case d.SignalingState.HaveRemoteOffer:case d.SignalingState.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof a.OutgoingRequest)switch(this._signalingState){case d.SignalingState.Initial:case d.SignalingState.Stable:this._signalingState=d.SignalingState.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case d.SignalingState.HaveLocalOffer:break;case d.SignalingState.HaveRemoteOffer:this._signalingState=d.SignalingState.Stable,this._answer=t;break;case d.SignalingState.Closed:break;default:throw new Error("Unexpected signaling state.")}if(u.isBody(e))switch(this._signalingState){case d.SignalingState.Initial:case d.SignalingState.Stable:this._signalingState=d.SignalingState.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case d.SignalingState.HaveLocalOffer:break;case d.SignalingState.HaveRemoteOffer:this._signalingState=d.SignalingState.Stable,this._answer=t;break;case d.SignalingState.Closed:break;default:throw new Error("Unexpected signaling state.")}}},t.prototype.start2xxRetransmissionTimer=function(){var e=this;if(this.initialTransaction instanceof h.InviteServerTransaction){var t=this.initialTransaction,r=c.Timers.T1,n=function(){e.ackWait?(e.logger.log("No ACK for 2xx response received, attempting retransmission"),t.retransmitAcceptedResponse(),r=Math.min(2*r,c.Timers.T2),e.invite2xxTimer=setTimeout(n,r)):e.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(n,r);var i=function(){t.state===h.TransactionState.Terminated&&(t.removeListener("stateChanged",i),e.invite2xxTimer&&(clearTimeout(e.invite2xxTimer),e.invite2xxTimer=void 0),e.ackWait&&(e.delegate&&e.delegate.onAckTimeout?e.delegate.onAckTimeout():e.bye()))};t.addListener("stateChanged",i)}},t.prototype.startReInvite2xxRetransmissionTimer=function(){var e=this;if(this.reinviteUserAgentServer&&this.reinviteUserAgentServer.transaction instanceof h.InviteServerTransaction){var t=this.reinviteUserAgentServer.transaction,r=c.Timers.T1,n=function(){e.reinviteUserAgentServer?(e.logger.log("No ACK for 2xx response received, attempting retransmission"),t.retransmitAcceptedResponse(),r=Math.min(2*r,c.Timers.T2),e.invite2xxTimer=setTimeout(n,r)):e.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(n,r);var i=function(){t.state===h.TransactionState.Terminated&&(t.removeListener("stateChanged",i),e.invite2xxTimer&&(clearTimeout(e.invite2xxTimer),e.invite2xxTimer=void 0),e.reinviteUserAgentServer)};t.addListener("stateChanged",i)}},t}(r(33).Dialog);t.SessionDialog=A},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(2),s=r(1),a=function(e){function t(t,r,n){var i=t.createOutgoingRequestMessage(o.C.INFO,n);return e.call(this,s.NonInviteClientTransaction,t.userAgentCore,i,r)||this}return i(t,e),t}(r(6).UserAgentClient);t.InfoUserAgentClient=a},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}),o=this&&this.__assign||function(){return(o=Object.assign||function(e){for(var t,r=1,n=arguments.length;r=200&&t.statusCode<300){var r=t.getHeader("Expires");if(r){var n=Number(r);n>this.subscriptionExpiresRequested&&this.logger.warn("Expires header in a 200-class response to SUBSCRIBE with a higher value than the one in the request"),nthis.subscriptionExpires&&(this.dialog.subscriptionExpires=this.subscriptionExpires)}t.statusCode&&t.statusCode>=300&&t.statusCode<700&&this.waitNotifyStop(),e.prototype.receiveResponse.call(this,t)}},t.prototype.timer_N=function(){this.logger.warn("Timer N expired for SUBSCRIBE user agent client. Timed out waiting for NOTIFY."),this.waitNotifyStop(),this.delegate&&this.delegate.onNotifyTimeout&&this.delegate.onNotifyTimeout()},t}(r(6).UserAgentClient);t.SubscribeUserAgentClient=u},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(1),s=function(e){function t(t,r,n){var i=e.call(this,o.NonInviteServerTransaction,t,r,n)||this;return i.core=t,i}return i(t,e),t}(r(9).UserAgentServer);t.SubscribeUserAgentServer=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(8),i=r(19);t.makeUserAgentCoreConfigurationFromUA=function(e){if(!(e.configuration.uri instanceof i.URI))throw new Error("Configuration URI not instance of URI.");return{aor:e.configuration.uri,contact:e.contact,loggerFactory:e.getLoggerFactory(),userAgentHeaderFieldValue:e.configuration.userAgentString,authenticationFactory:function(){if(e.configuration.authenticationFactory)return e.configuration.authenticationFactory(e)},onRequestTimeoutResponseMessageFactory:function(){var t=new n.IncomingResponse(e);return t.statusCode=408,t.reasonPhrase="Request Timeout",t},onTransportErrorResponseMessageFactory:function(){var t=new n.IncomingResponse(e);return t.statusCode=503,t.reasonPhrase="Service Unavailable",t},outgoingRequestMessageFactory:function(t,r,i,o,s){return new n.OutgoingRequest(t,r,e,i,o,s)},transportAccessor:function(){return e.transport}}}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(3),i=function(){function e(e,t){this.type=n.TypeStrings.SessionDescriptionHandlerObserver,this.session=e,this.options=t}return e.prototype.trackAdded=function(){this.session.emit("trackAdded")},e.prototype.directionChanged=function(){this.session.emit("directionChanged")},e}();t.SessionDescriptionHandlerObserver=i},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(35);t.Modifiers=n;var i=r(116);t.Simple=i.Simple;var o=r(62);t.SessionDescriptionHandler=o.SessionDescriptionHandler;var s=r(63);t.Transport=s.Transport},function(e,t,r){"use strict";(function(e){var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o,s=r(10),a=r(48),c=r(35);!function(e){e[e.STATUS_NULL=0]="STATUS_NULL",e[e.STATUS_NEW=1]="STATUS_NEW",e[e.STATUS_CONNECTING=2]="STATUS_CONNECTING",e[e.STATUS_CONNECTED=3]="STATUS_CONNECTED",e[e.STATUS_COMPLETED=4]="STATUS_COMPLETED"}(o=t.SimpleStatus||(t.SimpleStatus={}));var u=function(t){function r(r){var n=t.call(this)||this;if(r.media.remote.video?n.video=!0:n.video=!1,r.media.remote.audio?n.audio=!0:n.audio=!1,!n.audio&&!n.video)throw new Error("At least one remote audio or video element is required for Simple.");n.options=r;var i=e.navigator.userAgent.toLowerCase(),s=!1,u=!1;i.indexOf("safari")>-1&&i.indexOf("chrome")<0?s=!0:i.indexOf("firefox")>-1&&i.indexOf("chrome")<0&&(u=!0);var d={};return s&&(d.modifiers=[c.stripG722]),u&&(d.alwaysAcquireMediaFirst=!0),n.options.ua.uri?n.anonymous=!1:n.anonymous=!0,n.ua=new a.UA({uri:n.options.ua.uri,authorizationUser:n.options.ua.authorizationUser,password:n.options.ua.password,displayName:n.options.ua.displayName,userAgentString:n.options.ua.userAgentString,register:!0,sessionDescriptionHandlerFactoryOptions:d,transportOptions:{traceSip:n.options.ua.traceSip,wsServers:n.options.ua.wsServers}}),n.state=o.STATUS_NULL,n.logger=n.ua.getLogger("sip.simple"),n.ua.on("registered",function(){n.emit("registered",n.ua)}),n.ua.on("unregistered",function(){n.emit("unregistered",n.ua)}),n.ua.on("registrationFailed",function(){n.emit("unregistered",n.ua)}),n.ua.on("invite",function(e){if(n.state!==o.STATUS_NULL&&n.state!==o.STATUS_COMPLETED)return n.logger.warn("Rejecting incoming call. Simple only supports 1 call at a time"),void e.reject();n.session=e,n.setupSession(),n.emit("ringing",n.session)}),n.ua.on("message",function(e){n.emit("message",e)}),n}return i(r,t),r.prototype.call=function(e){if(this.ua&&this.checkRegistration()){if(this.state===o.STATUS_NULL||this.state===o.STATUS_COMPLETED)return this.options.media.remote.audio&&(this.options.media.remote.audio.autoplay=!0),this.options.media.remote.video&&(this.options.media.remote.video.autoplay=!0),this.options.media.local&&this.options.media.local.video&&(this.options.media.local.video.autoplay=!0,this.options.media.local.video.volume=0),this.session=this.ua.invite(e,{sessionDescriptionHandlerOptions:{constraints:{audio:this.audio,video:this.video}}}),this.setupSession(),this.session;this.logger.warn("Cannot make more than a single call with Simple")}else this.logger.warn("A registered UA is required for calling")},r.prototype.answer=function(){if(this.state===o.STATUS_NEW||this.state===o.STATUS_CONNECTING)return this.options.media.remote.audio&&(this.options.media.remote.audio.autoplay=!0),this.options.media.remote.video&&(this.options.media.remote.video.autoplay=!0),this.session.accept({sessionDescriptionHandlerOptions:{constraints:{audio:this.audio,video:this.video}}});this.logger.warn("No call to answer")},r.prototype.reject=function(){if(this.state===o.STATUS_NEW||this.state===o.STATUS_CONNECTING)return this.session.reject();this.logger.warn("Call is already answered")},r.prototype.hangup=function(){if(this.state===o.STATUS_CONNECTED||this.state===o.STATUS_CONNECTING||this.state===o.STATUS_NEW)return this.state!==o.STATUS_CONNECTED?this.session.cancel():this.session?this.session.bye():void 0;this.logger.warn("No active call to hang up on")},r.prototype.hold=function(){if(this.state===o.STATUS_CONNECTED&&this.session&&!this.session.localHold)return this.mute(),this.logger.log("Placing session on hold"),this.session.hold();this.logger.warn("Cannot put call on hold")},r.prototype.unhold=function(){if(this.state===o.STATUS_CONNECTED&&this.session&&this.session.localHold)return this.unmute(),this.logger.log("Placing call off hold"),this.session.unhold();this.logger.warn("Cannot unhold a call that is not on hold")},r.prototype.mute=function(){this.state===o.STATUS_CONNECTED?(this.logger.log("Muting Audio"),this.toggleMute(!0),this.emit("mute",this)):this.logger.warn("An acitve call is required to mute audio")},r.prototype.unmute=function(){this.state===o.STATUS_CONNECTED?(this.logger.log("Unmuting Audio"),this.toggleMute(!1),this.emit("unmute",this)):this.logger.warn("An active call is required to unmute audio")},r.prototype.sendDTMF=function(e){this.state===o.STATUS_CONNECTED&&this.session?(this.logger.log("Sending DTMF tone: "+e),this.session.dtmf(e)):this.logger.warn("An active call is required to send a DTMF tone")},r.prototype.message=function(e,t){this.ua&&this.checkRegistration()?e&&t?this.ua.message(e,t):this.logger.warn("A destination and message are required to send a message"):this.logger.warn("A registered UA is required to send a message")},r.prototype.checkRegistration=function(){return this.anonymous||this.ua&&this.ua.isRegistered()},r.prototype.setupRemoteMedia=function(){var t=this;if(this.session){var r,n=this.session.sessionDescriptionHandler.peerConnection;n.getReceivers?(r=new e.window.MediaStream,n.getReceivers().forEach(function(e){var t=e.track;t&&r.addTrack(t)})):r=n.getRemoteStreams()[0],this.video?(this.options.media.remote.video.srcObject=r,this.options.media.remote.video.play().catch(function(){t.logger.log("play was rejected")})):this.audio&&(this.options.media.remote.audio.srcObject=r,this.options.media.remote.audio.play().catch(function(){t.logger.log("play was rejected")}))}else this.logger.warn("No session to set remote media on")},r.prototype.setupLocalMedia=function(){if(this.session){if(this.video&&this.options.media.local&&this.options.media.local.video){var t,r=this.session.sessionDescriptionHandler.peerConnection;r.getSenders?(t=new e.window.MediaStream,r.getSenders().forEach(function(e){var r=e.track;r&&"video"===r.kind&&t.addTrack(r)})):t=r.getLocalStreams()[0],this.options.media.local.video.srcObject=t,this.options.media.local.video.volume=0,this.options.media.local.video.play()}}else this.logger.warn("No session to set local media on")},r.prototype.cleanupMedia=function(){this.video&&(this.options.media.remote.video.srcObject=null,this.options.media.remote.video.pause(),this.options.media.local&&this.options.media.local.video&&(this.options.media.local.video.srcObject=null,this.options.media.local.video.pause())),this.audio&&(this.options.media.remote.audio.srcObject=null,this.options.media.remote.audio.pause())},r.prototype.setupSession=function(){var e=this;this.session?(this.state=o.STATUS_NEW,this.emit("new",this.session),this.session.on("progress",function(){return e.onProgress()}),this.session.on("accepted",function(){return e.onAccepted()}),this.session.on("rejected",function(){return e.onEnded()}),this.session.on("failed",function(){return e.onFailed()}),this.session.on("terminated",function(){return e.onEnded()})):this.logger.warn("No session to set up")},r.prototype.destroyMedia=function(){this.session&&this.session.sessionDescriptionHandler&&this.session.sessionDescriptionHandler.close()},r.prototype.toggleMute=function(e){if(this.session){var t=this.session.sessionDescriptionHandler.peerConnection;t.getSenders?t.getSenders().forEach(function(t){t.track&&(t.track.enabled=!e)}):t.getLocalStreams().forEach(function(t){t.getAudioTracks().forEach(function(t){t.enabled=!e}),t.getVideoTracks().forEach(function(t){t.enabled=!e})})}else this.logger.warn("No session to toggle mute")},r.prototype.onAccepted=function(){var e=this;this.session?(this.state=o.STATUS_CONNECTED,this.emit("connected",this.session),this.setupLocalMedia(),this.setupRemoteMedia(),this.session.sessionDescriptionHandler&&(this.session.sessionDescriptionHandler.on("addTrack",function(){e.logger.log("A track has been added, triggering new remoteMedia setup"),e.setupRemoteMedia()}),this.session.sessionDescriptionHandler.on("addStream",function(){e.logger.log("A stream has been added, trigger new remoteMedia setup"),e.setupRemoteMedia()})),this.session.on("dtmf",function(t,r){e.emit("dtmf",r.tone)}),this.session.on("bye",function(){return e.onEnded()})):this.logger.warn("No session for accepting")},r.prototype.onProgress=function(){this.state=o.STATUS_CONNECTING,this.emit("connecting",this.session)},r.prototype.onFailed=function(){this.onEnded()},r.prototype.onEnded=function(){this.state=o.STATUS_COMPLETED,this.emit("ended",this.session),this.cleanupMedia()},r.C=o,r}(s.EventEmitter);t.Simple=u}).call(this,r(24))}])}); \ No newline at end of file diff --git a/dist/sip.js b/dist/sip.js new file mode 100644 index 000000000..9139d3d8f --- /dev/null +++ b/dist/sip.js @@ -0,0 +1,38134 @@ +/*! + * + * SIP version 0.14.0 + * Copyright (c) 2014-2019 Junction Networks, Inc + * Homepage: https://sipjs.com + * License: https://sipjs.com/license/ + * + * + * ~~~SIP.js contains substantial portions of JsSIP under the following license~~~ + * Homepage: http://jssip.net + * Copyright (c) 2012-2013 José Luis Millán - Versatica + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * ~~~ end JsSIP license ~~~ + * + * + * + * + */ +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(); + else if(typeof define === 'function' && define.amd) + define([], factory); + else if(typeof exports === 'object') + exports["SIP"] = factory(); + else + root["SIP"] = factory(); +})(this, function() { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) { +/******/ return installedModules[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ i: moduleId, +/******/ l: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.l = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; +/******/ +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; +/******/ +/******/ // define getter function for harmony exports +/******/ __webpack_require__.d = function(exports, name, getter) { +/******/ if(!__webpack_require__.o(exports, name)) { +/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); +/******/ } +/******/ }; +/******/ +/******/ // define __esModule on exports +/******/ __webpack_require__.r = function(exports) { +/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { +/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); +/******/ } +/******/ Object.defineProperty(exports, '__esModule', { value: true }); +/******/ }; +/******/ +/******/ // create a fake namespace object +/******/ // mode & 1: value is a module id, require it +/******/ // mode & 2: merge all properties of value into the ns +/******/ // mode & 4: return value when already ns object +/******/ // mode & 8|1: behave like require +/******/ __webpack_require__.t = function(value, mode) { +/******/ if(mode & 1) value = __webpack_require__(value); +/******/ if(mode & 8) return value; +/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; +/******/ var ns = Object.create(null); +/******/ __webpack_require__.r(ns); +/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); +/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); +/******/ return ns; +/******/ }; +/******/ +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = function(module) { +/******/ var getter = module && module.__esModule ? +/******/ function getDefault() { return module['default']; } : +/******/ function getModuleExports() { return module; }; +/******/ __webpack_require__.d(getter, 'a', getter); +/******/ return getter; +/******/ }; +/******/ +/******/ // Object.prototype.hasOwnProperty.call +/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; +/******/ +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; +/******/ +/******/ +/******/ // Load entry module and return exports +/******/ return __webpack_require__(__webpack_require__.s = 0); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +var ClientContext_1 = __webpack_require__(1); +exports.ClientContext = ClientContext_1.ClientContext; +var Constants_1 = __webpack_require__(3); +exports.C = Constants_1.C; +var DigestAuthentication_1 = __webpack_require__(12); +exports.DigestAuthentication = DigestAuthentication_1.DigestAuthentication; +var Enums_1 = __webpack_require__(5); +exports.DialogStatus = Enums_1.DialogStatus; +exports.SessionStatus = Enums_1.SessionStatus; +exports.TypeStrings = Enums_1.TypeStrings; +exports.UAStatus = Enums_1.UAStatus; +var Exceptions_1 = __webpack_require__(47); +exports.Exceptions = Exceptions_1.Exceptions; +var Grammar_1 = __webpack_require__(7); +exports.Grammar = Grammar_1.Grammar; +var LoggerFactory_1 = __webpack_require__(48); +exports.LoggerFactory = LoggerFactory_1.LoggerFactory; +var NameAddrHeader_1 = __webpack_require__(9); +exports.NameAddrHeader = NameAddrHeader_1.NameAddrHeader; +var Parser_1 = __webpack_require__(49); +exports.Parser = Parser_1.Parser; +var PublishContext_1 = __webpack_require__(50); +exports.PublishContext = PublishContext_1.PublishContext; +var ReferContext_1 = __webpack_require__(51); +exports.ReferClientContext = ReferContext_1.ReferClientContext; +exports.ReferServerContext = ReferContext_1.ReferServerContext; +var RegisterContext_1 = __webpack_require__(66); +exports.RegisterContext = RegisterContext_1.RegisterContext; +var ServerContext_1 = __webpack_require__(62); +exports.ServerContext = ServerContext_1.ServerContext; +var Session_1 = __webpack_require__(67); +exports.InviteClientContext = Session_1.InviteClientContext; +exports.InviteServerContext = Session_1.InviteServerContext; +exports.Session = Session_1.Session; +var SIPMessage_1 = __webpack_require__(6); +exports.IncomingRequest = SIPMessage_1.IncomingRequest; +exports.IncomingResponse = SIPMessage_1.IncomingResponse; +exports.OutgoingRequest = SIPMessage_1.OutgoingRequest; +var Subscription_1 = __webpack_require__(71); +exports.Subscription = Subscription_1.Subscription; +var Timers_1 = __webpack_require__(56); +exports.Timers = Timers_1.Timers; +var transactions_1 = __webpack_require__(52); +var Transactions = { + InviteClientTransaction: transactions_1.InviteClientTransaction, + InviteServerTransaction: transactions_1.InviteServerTransaction, + NonInviteClientTransaction: transactions_1.NonInviteClientTransaction, + NonInviteServerTransaction: transactions_1.NonInviteServerTransaction +}; +exports.Transactions = Transactions; +var Transport_1 = __webpack_require__(75); +exports.Transport = Transport_1.Transport; +var UA_1 = __webpack_require__(76); +exports.UA = UA_1.UA; +var URI_1 = __webpack_require__(10); +exports.URI = URI_1.URI; +var Utils_1 = __webpack_require__(11); +exports.Utils = Utils_1.Utils; +var Web = __webpack_require__(115); +exports.Web = Web; +// tslint:disable-next-line:no-var-requires +var pkg = __webpack_require__(4); +var name = pkg.title; +exports.name = name; +var version = pkg.version; +exports.version = version; + + +/***/ }), +/* 1 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var events_1 = __webpack_require__(2); +var Constants_1 = __webpack_require__(3); +var Enums_1 = __webpack_require__(5); +var SIPMessage_1 = __webpack_require__(6); +var Utils_1 = __webpack_require__(11); +var ClientContext = /** @class */ (function (_super) { + __extends(ClientContext, _super); + function ClientContext(ua, method, target, options) { + var _this = _super.call(this) || this; + _this.data = {}; + ClientContext.initializer(_this, ua, method, target, options); + return _this; + } + ClientContext.initializer = function (objToConstruct, ua, method, originalTarget, options) { + objToConstruct.type = Enums_1.TypeStrings.ClientContext; + // Validate arguments + if (originalTarget === undefined) { + throw new TypeError("Not enough arguments"); + } + objToConstruct.ua = ua; + objToConstruct.logger = ua.getLogger("sip.clientcontext"); + objToConstruct.method = method; + var target = ua.normalizeTarget(originalTarget); + if (!target) { + throw new TypeError("Invalid target: " + originalTarget); + } + /* Options + * - extraHeaders + * - params + * - contentType + * - body + */ + options = Object.create(options || Object.prototype); + options.extraHeaders = (options.extraHeaders || []).slice(); + // Build the request + objToConstruct.request = new SIPMessage_1.OutgoingRequest(objToConstruct.method, target, objToConstruct.ua, options.params, options.extraHeaders); + if (options.body) { + var body = options.body; + var contentType = options.contentType ? options.contentType : "application/sdp"; + var bodyObj = { + body: body, + contentType: contentType + }; + objToConstruct.body = bodyObj; + objToConstruct.request.body = bodyObj; + } + /* Set other properties from the request */ + if (objToConstruct.request.from) { + objToConstruct.localIdentity = objToConstruct.request.from; + } + if (objToConstruct.request.to) { + objToConstruct.remoteIdentity = objToConstruct.request.to; + } + }; + ClientContext.prototype.send = function () { + var _this = this; + this.ua.userAgentCore.request(this.request, { + onAccept: function (response) { return _this.receiveResponse(response.message); }, + onProgress: function (response) { return _this.receiveResponse(response.message); }, + onRedirect: function (response) { return _this.receiveResponse(response.message); }, + onReject: function (response) { return _this.receiveResponse(response.message); }, + onTrying: function (response) { return _this.receiveResponse(response.message); } + }); + return this; + }; + ClientContext.prototype.receiveResponse = function (response) { + var statusCode = response.statusCode || 0; + var cause = Utils_1.Utils.getReasonPhrase(statusCode); + switch (true) { + case /^1[0-9]{2}$/.test(statusCode.toString()): + this.emit("progress", response, cause); + break; + case /^2[0-9]{2}$/.test(statusCode.toString()): + if (this.ua.applicants[this.toString()]) { + delete this.ua.applicants[this.toString()]; + } + this.emit("accepted", response, cause); + break; + default: + if (this.ua.applicants[this.toString()]) { + delete this.ua.applicants[this.toString()]; + } + this.emit("rejected", response, cause); + this.emit("failed", response, cause); + break; + } + }; + ClientContext.prototype.onRequestTimeout = function () { + this.emit("failed", undefined, Constants_1.C.causes.REQUEST_TIMEOUT); + }; + ClientContext.prototype.onTransportError = function () { + this.emit("failed", undefined, Constants_1.C.causes.CONNECTION_ERROR); + }; + return ClientContext; +}(events_1.EventEmitter)); +exports.ClientContext = ClientContext; + + +/***/ }), +/* 2 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + +var R = typeof Reflect === 'object' ? Reflect : null +var ReflectApply = R && typeof R.apply === 'function' + ? R.apply + : function ReflectApply(target, receiver, args) { + return Function.prototype.apply.call(target, receiver, args); + } + +var ReflectOwnKeys +if (R && typeof R.ownKeys === 'function') { + ReflectOwnKeys = R.ownKeys +} else if (Object.getOwnPropertySymbols) { + ReflectOwnKeys = function ReflectOwnKeys(target) { + return Object.getOwnPropertyNames(target) + .concat(Object.getOwnPropertySymbols(target)); + }; +} else { + ReflectOwnKeys = function ReflectOwnKeys(target) { + return Object.getOwnPropertyNames(target); + }; +} + +function ProcessEmitWarning(warning) { + if (console && console.warn) console.warn(warning); +} + +var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) { + return value !== value; +} + +function EventEmitter() { + EventEmitter.init.call(this); +} +module.exports = EventEmitter; + +// Backwards-compat with node 0.10.x +EventEmitter.EventEmitter = EventEmitter; + +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._eventsCount = 0; +EventEmitter.prototype._maxListeners = undefined; + +// By default EventEmitters will print a warning if more than 10 listeners are +// added to it. This is a useful default which helps finding memory leaks. +var defaultMaxListeners = 10; + +Object.defineProperty(EventEmitter, 'defaultMaxListeners', { + enumerable: true, + get: function() { + return defaultMaxListeners; + }, + set: function(arg) { + if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) { + throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.'); + } + defaultMaxListeners = arg; + } +}); + +EventEmitter.init = function() { + + if (this._events === undefined || + this._events === Object.getPrototypeOf(this)._events) { + this._events = Object.create(null); + this._eventsCount = 0; + } + + this._maxListeners = this._maxListeners || undefined; +}; + +// Obviously not all Emitters should be limited to 10. This function allows +// that to be increased. Set to zero for unlimited. +EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { + if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) { + throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.'); + } + this._maxListeners = n; + return this; +}; + +function $getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter.defaultMaxListeners; + return that._maxListeners; +} + +EventEmitter.prototype.getMaxListeners = function getMaxListeners() { + return $getMaxListeners(this); +}; + +EventEmitter.prototype.emit = function emit(type) { + var args = []; + for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); + var doError = (type === 'error'); + + var events = this._events; + if (events !== undefined) + doError = (doError && events.error === undefined); + else if (!doError) + return false; + + // If there is no 'error' event listener then throw. + if (doError) { + var er; + if (args.length > 0) + er = args[0]; + if (er instanceof Error) { + // Note: The comments on the `throw` lines are intentional, they show + // up in Node's output if this results in an unhandled exception. + throw er; // Unhandled 'error' event + } + // At least give some kind of context to the user + var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : '')); + err.context = er; + throw err; // Unhandled 'error' event + } + + var handler = events[type]; + + if (handler === undefined) + return false; + + if (typeof handler === 'function') { + ReflectApply(handler, this, args); + } else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + ReflectApply(listeners[i], this, args); + } + + return true; +}; + +function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; + + if (typeof listener !== 'function') { + throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); + } + + events = target._events; + if (events === undefined) { + events = target._events = Object.create(null); + target._eventsCount = 0; + } else { + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (events.newListener !== undefined) { + target.emit('newListener', type, + listener.listener ? listener.listener : listener); + + // Re-assign `events` because a newListener handler could have caused the + // this._events to be assigned to a new object + events = target._events; + } + existing = events[type]; + } + + if (existing === undefined) { + // Optimize the case of one listener. Don't need the extra array object. + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === 'function') { + // Adding the second element, need to change to array. + existing = events[type] = + prepend ? [listener, existing] : [existing, listener]; + // If we've already got an array, just append. + } else if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + + // Check for listener leak + m = $getMaxListeners(target); + if (m > 0 && existing.length > m && !existing.warned) { + existing.warned = true; + // No error code for this since it is a Warning + // eslint-disable-next-line no-restricted-syntax + var w = new Error('Possible EventEmitter memory leak detected. ' + + existing.length + ' ' + String(type) + ' listeners ' + + 'added. Use emitter.setMaxListeners() to ' + + 'increase limit'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + ProcessEmitWarning(w); + } + } + + return target; +} + +EventEmitter.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); +}; + +EventEmitter.prototype.on = EventEmitter.prototype.addListener; + +EventEmitter.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; + +function onceWrapper() { + var args = []; + for (var i = 0; i < arguments.length; i++) args.push(arguments[i]); + if (!this.fired) { + this.target.removeListener(this.type, this.wrapFn); + this.fired = true; + ReflectApply(this.listener, this.target, args); + } +} + +function _onceWrap(target, type, listener) { + var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; + var wrapped = onceWrapper.bind(state); + wrapped.listener = listener; + state.wrapFn = wrapped; + return wrapped; +} + +EventEmitter.prototype.once = function once(type, listener) { + if (typeof listener !== 'function') { + throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); + } + this.on(type, _onceWrap(this, type, listener)); + return this; +}; + +EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + if (typeof listener !== 'function') { + throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); + } + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; + +// Emits a 'removeListener' event if and only if the listener was removed. +EventEmitter.prototype.removeListener = + function removeListener(type, listener) { + var list, events, position, i, originalListener; + + if (typeof listener !== 'function') { + throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); + } + + events = this._events; + if (events === undefined) + return this; + + list = events[type]; + if (list === undefined) + return this; + + if (list === listener || list.listener === listener) { + if (--this._eventsCount === 0) + this._events = Object.create(null); + else { + delete events[type]; + if (events.removeListener) + this.emit('removeListener', type, list.listener || listener); + } + } else if (typeof list !== 'function') { + position = -1; + + for (i = list.length - 1; i >= 0; i--) { + if (list[i] === listener || list[i].listener === listener) { + originalListener = list[i].listener; + position = i; + break; + } + } + + if (position < 0) + return this; + + if (position === 0) + list.shift(); + else { + spliceOne(list, position); + } + + if (list.length === 1) + events[type] = list[0]; + + if (events.removeListener !== undefined) + this.emit('removeListener', type, originalListener || listener); + } + + return this; + }; + +EventEmitter.prototype.off = EventEmitter.prototype.removeListener; + +EventEmitter.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events, i; + + events = this._events; + if (events === undefined) + return this; + + // not listening for removeListener, no need to emit + if (events.removeListener === undefined) { + if (arguments.length === 0) { + this._events = Object.create(null); + this._eventsCount = 0; + } else if (events[type] !== undefined) { + if (--this._eventsCount === 0) + this._events = Object.create(null); + else + delete events[type]; + } + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + var keys = Object.keys(events); + var key; + for (i = 0; i < keys.length; ++i) { + key = keys[i]; + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = Object.create(null); + this._eventsCount = 0; + return this; + } + + listeners = events[type]; + + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners !== undefined) { + // LIFO order + for (i = listeners.length - 1; i >= 0; i--) { + this.removeListener(type, listeners[i]); + } + } + + return this; + }; + +function _listeners(target, type, unwrap) { + var events = target._events; + + if (events === undefined) + return []; + + var evlistener = events[type]; + if (evlistener === undefined) + return []; + + if (typeof evlistener === 'function') + return unwrap ? [evlistener.listener || evlistener] : [evlistener]; + + return unwrap ? + unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); +} + +EventEmitter.prototype.listeners = function listeners(type) { + return _listeners(this, type, true); +}; + +EventEmitter.prototype.rawListeners = function rawListeners(type) { + return _listeners(this, type, false); +}; + +EventEmitter.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount.call(emitter, type); + } +}; + +EventEmitter.prototype.listenerCount = listenerCount; +function listenerCount(type) { + var events = this._events; + + if (events !== undefined) { + var evlistener = events[type]; + + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener !== undefined) { + return evlistener.length; + } + } + + return 0; +} + +EventEmitter.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; +}; + +function arrayClone(arr, n) { + var copy = new Array(n); + for (var i = 0; i < n; ++i) + copy[i] = arr[i]; + return copy; +} + +function spliceOne(list, index) { + for (; index + 1 < list.length; index++) + list[index] = list[index + 1]; + list.pop(); +} + +function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; +} + + +/***/ }), +/* 3 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +// tslint:disable-next-line:no-var-requires +var pkg = __webpack_require__(4); +var C; +(function (C) { + C.USER_AGENT = pkg.title + "/" + pkg.version; + // SIP scheme + C.SIP = "sip"; + C.SIPS = "sips"; + // End and Failure causes + var causes; + (function (causes) { + // Generic error causes + causes["CONNECTION_ERROR"] = "Connection Error"; + causes["INTERNAL_ERROR"] = "Internal Error"; + causes["REQUEST_TIMEOUT"] = "Request Timeout"; + causes["SIP_FAILURE_CODE"] = "SIP Failure Code"; + // SIP error causes + causes["ADDRESS_INCOMPLETE"] = "Address Incomplete"; + causes["AUTHENTICATION_ERROR"] = "Authentication Error"; + causes["BUSY"] = "Busy"; + causes["DIALOG_ERROR"] = "Dialog Error"; + causes["INCOMPATIBLE_SDP"] = "Incompatible SDP"; + causes["NOT_FOUND"] = "Not Found"; + causes["REDIRECTED"] = "Redirected"; + causes["REJECTED"] = "Rejected"; + causes["UNAVAILABLE"] = "Unavailable"; + // Session error causes + causes["BAD_MEDIA_DESCRIPTION"] = "Bad Media Description"; + causes["CANCELED"] = "Canceled"; + causes["EXPIRES"] = "Expires"; + causes["NO_ACK"] = "No ACK"; + causes["NO_ANSWER"] = "No Answer"; + causes["NO_PRACK"] = "No PRACK"; + causes["RTP_TIMEOUT"] = "RTP Timeout"; + causes["USER_DENIED_MEDIA_ACCESS"] = "User Denied Media Access"; + causes["WEBRTC_ERROR"] = "WebRTC Error"; + causes["WEBRTC_NOT_SUPPORTED"] = "WebRTC Not Supported"; + })(causes = C.causes || (C.causes = {})); + var supported; + (function (supported) { + supported["REQUIRED"] = "required"; + supported["SUPPORTED"] = "supported"; + supported["UNSUPPORTED"] = "none"; + })(supported = C.supported || (C.supported = {})); + C.SIP_ERROR_CAUSES = { + ADDRESS_INCOMPLETE: [484], + AUTHENTICATION_ERROR: [401, 407], + BUSY: [486, 600], + INCOMPATIBLE_SDP: [488, 606], + NOT_FOUND: [404, 604], + REDIRECTED: [300, 301, 302, 305, 380], + REJECTED: [403, 603], + UNAVAILABLE: [480, 410, 408, 430] + }; + // SIP Methods + C.ACK = "ACK"; + C.BYE = "BYE"; + C.CANCEL = "CANCEL"; + C.INFO = "INFO"; + C.INVITE = "INVITE"; + C.MESSAGE = "MESSAGE"; + C.NOTIFY = "NOTIFY"; + C.OPTIONS = "OPTIONS"; + C.REGISTER = "REGISTER"; + C.UPDATE = "UPDATE"; + C.SUBSCRIBE = "SUBSCRIBE"; + C.PUBLISH = "PUBLISH"; + C.REFER = "REFER"; + C.PRACK = "PRACK"; + /* SIP Response Reasons + * DOC: http://www.iana.org/assignments/sip-parameters + * Copied from https://github.com/versatica/OverSIP/blob/master/lib/oversip/sip/constants.rb#L7 + */ + C.REASON_PHRASE = { + 100: "Trying", + 180: "Ringing", + 181: "Call Is Being Forwarded", + 182: "Queued", + 183: "Session Progress", + 199: "Early Dialog Terminated", + 200: "OK", + 202: "Accepted", + 204: "No Notification", + 300: "Multiple Choices", + 301: "Moved Permanently", + 302: "Moved Temporarily", + 305: "Use Proxy", + 380: "Alternative Service", + 400: "Bad Request", + 401: "Unauthorized", + 402: "Payment Required", + 403: "Forbidden", + 404: "Not Found", + 405: "Method Not Allowed", + 406: "Not Acceptable", + 407: "Proxy Authentication Required", + 408: "Request Timeout", + 410: "Gone", + 412: "Conditional Request Failed", + 413: "Request Entity Too Large", + 414: "Request-URI Too Long", + 415: "Unsupported Media Type", + 416: "Unsupported URI Scheme", + 417: "Unknown Resource-Priority", + 420: "Bad Extension", + 421: "Extension Required", + 422: "Session Interval Too Small", + 423: "Interval Too Brief", + 428: "Use Identity Header", + 429: "Provide Referrer Identity", + 430: "Flow Failed", + 433: "Anonymity Disallowed", + 436: "Bad Identity-Info", + 437: "Unsupported Certificate", + 438: "Invalid Identity Header", + 439: "First Hop Lacks Outbound Support", + 440: "Max-Breadth Exceeded", + 469: "Bad Info Package", + 470: "Consent Needed", + 478: "Unresolvable Destination", + 480: "Temporarily Unavailable", + 481: "Call/Transaction Does Not Exist", + 482: "Loop Detected", + 483: "Too Many Hops", + 484: "Address Incomplete", + 485: "Ambiguous", + 486: "Busy Here", + 487: "Request Terminated", + 488: "Not Acceptable Here", + 489: "Bad Event", + 491: "Request Pending", + 493: "Undecipherable", + 494: "Security Agreement Required", + 500: "Internal Server Error", + 501: "Not Implemented", + 502: "Bad Gateway", + 503: "Service Unavailable", + 504: "Server Time-out", + 505: "Version Not Supported", + 513: "Message Too Large", + 580: "Precondition Failure", + 600: "Busy Everywhere", + 603: "Decline", + 604: "Does Not Exist Anywhere", + 606: "Not Acceptable" + }; + /* SIP Option Tags + * DOC: http://www.iana.org/assignments/sip-parameters/sip-parameters.xhtml#sip-parameters-4 + */ + C.OPTION_TAGS = { + "100rel": true, + "199": true, + "answermode": true, + "early-session": true, + "eventlist": true, + "explicitsub": true, + "from-change": true, + "geolocation-http": true, + "geolocation-sip": true, + "gin": true, + "gruu": true, + "histinfo": true, + "ice": true, + "join": true, + "multiple-refer": true, + "norefersub": true, + "nosub": true, + "outbound": true, + "path": true, + "policy": true, + "precondition": true, + "pref": true, + "privacy": true, + "recipient-list-invite": true, + "recipient-list-message": true, + "recipient-list-subscribe": true, + "replaces": true, + "resource-priority": true, + "sdp-anat": true, + "sec-agree": true, + "tdialog": true, + "timer": true, + "uui": true // RFC 7433 + }; + var dtmfType; + (function (dtmfType) { + dtmfType["INFO"] = "info"; + dtmfType["RTP"] = "rtp"; + })(dtmfType = C.dtmfType || (C.dtmfType = {})); +})(C = exports.C || (exports.C = {})); + + +/***/ }), +/* 4 */ +/***/ (function(module) { + +module.exports = {"name":"sip.js","title":"SIP.js","description":"A simple, intuitive, and powerful JavaScript signaling library","version":"0.14.0","license":"MIT","main":"./lib/index.js","types":"./lib/index.d.ts","homepage":"https://sipjs.com","author":"OnSIP (https://sipjs.com/aboutus/)","contributors":[{"url":"https://github.com/onsip/SIP.js/blob/master/THANKS.md"}],"repository":{"type":"git","url":"https://github.com/onsip/SIP.js.git"},"keywords":["sip","webrtc","library","websocket","javascript","typescript"],"dependencies":{"crypto-js":"^3.1.9-1"},"devDependencies":{"@types/crypto-js":"^3.1.43","@types/jasmine":"^3.3.11","@types/node":"^12.0.2","circular-dependency-plugin":"^5.0.2","jasmine-core":"^3.4.0","karma":"^4.1.0","karma-chrome-launcher":"^2.2.0","karma-cli":"^2.0.0","karma-jasmine":"^2.0.1","karma-jasmine-html-reporter":"^1.4.2","karma-mocha-reporter":"^2.2.5","karma-sourcemap-loader":"^0.3.7","karma-webpack":"^3.0.5","pegjs":"^0.10.0","ts-loader":"^6.0.1","ts-pegjs":"0.2.3","tslint":"^5.16.0","typescript":"^3.4.5","webpack":"^4.32.0","webpack-cli":"^3.3.2"},"engines":{"node":">=8.0"},"scripts":{"prebuild":"tslint -p tsconfig-base.json -c tslint.json","generate-grammar":"node build/grammarGenerator.js","build-reg-bundle":"webpack --progress --config build/webpack.config.js --env.buildType reg","build-min-bundle":"webpack --progress --config build/webpack.config.js --env.buildType min","build-bundles":"npm run build-reg-bundle && npm run build-min-bundle","build-lib":"tsc -p src","build-test":"tsc -p test","copy-dist-files":"cp dist/sip.js dist/sip-$npm_package_version.js && cp dist/sip.min.js dist/sip-$npm_package_version.min.js","build":"npm run generate-grammar && npm run build-lib && npm run build-reg-bundle && npm run build-min-bundle && npm run copy-dist-files","browserTest":"npm run build-test && sleep 2 && open http://0.0.0.0:9876/debug.html & karma start --reporters kjhtml --no-single-run","commandLineTest":"npm run build-test && karma start --reporters mocha --browsers ChromeHeadless --single-run","buildAndTest":"npm run build && npm run commandLineTest","buildAndBrowserTest":"npm run build && npm run browserTest"}}; + +/***/ }), +/* 5 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +// enums can't really be declared, so they are set here. +// pulled out of individual files to avoid circular dependencies +Object.defineProperty(exports, "__esModule", { value: true }); +var DialogStatus; +(function (DialogStatus) { + DialogStatus[DialogStatus["STATUS_EARLY"] = 1] = "STATUS_EARLY"; + DialogStatus[DialogStatus["STATUS_CONFIRMED"] = 2] = "STATUS_CONFIRMED"; +})(DialogStatus = exports.DialogStatus || (exports.DialogStatus = {})); +var SessionStatus; +(function (SessionStatus) { + // Session states + SessionStatus[SessionStatus["STATUS_NULL"] = 0] = "STATUS_NULL"; + SessionStatus[SessionStatus["STATUS_INVITE_SENT"] = 1] = "STATUS_INVITE_SENT"; + SessionStatus[SessionStatus["STATUS_1XX_RECEIVED"] = 2] = "STATUS_1XX_RECEIVED"; + SessionStatus[SessionStatus["STATUS_INVITE_RECEIVED"] = 3] = "STATUS_INVITE_RECEIVED"; + SessionStatus[SessionStatus["STATUS_WAITING_FOR_ANSWER"] = 4] = "STATUS_WAITING_FOR_ANSWER"; + SessionStatus[SessionStatus["STATUS_ANSWERED"] = 5] = "STATUS_ANSWERED"; + SessionStatus[SessionStatus["STATUS_WAITING_FOR_PRACK"] = 6] = "STATUS_WAITING_FOR_PRACK"; + SessionStatus[SessionStatus["STATUS_WAITING_FOR_ACK"] = 7] = "STATUS_WAITING_FOR_ACK"; + SessionStatus[SessionStatus["STATUS_CANCELED"] = 8] = "STATUS_CANCELED"; + SessionStatus[SessionStatus["STATUS_TERMINATED"] = 9] = "STATUS_TERMINATED"; + SessionStatus[SessionStatus["STATUS_ANSWERED_WAITING_FOR_PRACK"] = 10] = "STATUS_ANSWERED_WAITING_FOR_PRACK"; + SessionStatus[SessionStatus["STATUS_EARLY_MEDIA"] = 11] = "STATUS_EARLY_MEDIA"; + SessionStatus[SessionStatus["STATUS_CONFIRMED"] = 12] = "STATUS_CONFIRMED"; +})(SessionStatus = exports.SessionStatus || (exports.SessionStatus = {})); +var TypeStrings; +(function (TypeStrings) { + TypeStrings[TypeStrings["ClientContext"] = 0] = "ClientContext"; + TypeStrings[TypeStrings["ConfigurationError"] = 1] = "ConfigurationError"; + TypeStrings[TypeStrings["Dialog"] = 2] = "Dialog"; + TypeStrings[TypeStrings["DigestAuthentication"] = 3] = "DigestAuthentication"; + TypeStrings[TypeStrings["DTMF"] = 4] = "DTMF"; + TypeStrings[TypeStrings["IncomingMessage"] = 5] = "IncomingMessage"; + TypeStrings[TypeStrings["IncomingRequest"] = 6] = "IncomingRequest"; + TypeStrings[TypeStrings["IncomingResponse"] = 7] = "IncomingResponse"; + TypeStrings[TypeStrings["InvalidStateError"] = 8] = "InvalidStateError"; + TypeStrings[TypeStrings["InviteClientContext"] = 9] = "InviteClientContext"; + TypeStrings[TypeStrings["InviteServerContext"] = 10] = "InviteServerContext"; + TypeStrings[TypeStrings["Logger"] = 11] = "Logger"; + TypeStrings[TypeStrings["LoggerFactory"] = 12] = "LoggerFactory"; + TypeStrings[TypeStrings["MethodParameterError"] = 13] = "MethodParameterError"; + TypeStrings[TypeStrings["NameAddrHeader"] = 14] = "NameAddrHeader"; + TypeStrings[TypeStrings["NotSupportedError"] = 15] = "NotSupportedError"; + TypeStrings[TypeStrings["OutgoingRequest"] = 16] = "OutgoingRequest"; + TypeStrings[TypeStrings["Parameters"] = 17] = "Parameters"; + TypeStrings[TypeStrings["PublishContext"] = 18] = "PublishContext"; + TypeStrings[TypeStrings["ReferClientContext"] = 19] = "ReferClientContext"; + TypeStrings[TypeStrings["ReferServerContext"] = 20] = "ReferServerContext"; + TypeStrings[TypeStrings["RegisterContext"] = 21] = "RegisterContext"; + TypeStrings[TypeStrings["RenegotiationError"] = 22] = "RenegotiationError"; + TypeStrings[TypeStrings["RequestSender"] = 23] = "RequestSender"; + TypeStrings[TypeStrings["ServerContext"] = 24] = "ServerContext"; + TypeStrings[TypeStrings["Session"] = 25] = "Session"; + TypeStrings[TypeStrings["SessionDescriptionHandler"] = 26] = "SessionDescriptionHandler"; + TypeStrings[TypeStrings["SessionDescriptionHandlerError"] = 27] = "SessionDescriptionHandlerError"; + TypeStrings[TypeStrings["SessionDescriptionHandlerObserver"] = 28] = "SessionDescriptionHandlerObserver"; + TypeStrings[TypeStrings["Subscription"] = 29] = "Subscription"; + TypeStrings[TypeStrings["Transport"] = 30] = "Transport"; + TypeStrings[TypeStrings["UA"] = 31] = "UA"; + TypeStrings[TypeStrings["URI"] = 32] = "URI"; +})(TypeStrings = exports.TypeStrings || (exports.TypeStrings = {})); +// UA status codes +var UAStatus; +(function (UAStatus) { + UAStatus[UAStatus["STATUS_INIT"] = 0] = "STATUS_INIT"; + UAStatus[UAStatus["STATUS_STARTING"] = 1] = "STATUS_STARTING"; + UAStatus[UAStatus["STATUS_READY"] = 2] = "STATUS_READY"; + UAStatus[UAStatus["STATUS_USER_CLOSED"] = 3] = "STATUS_USER_CLOSED"; + UAStatus[UAStatus["STATUS_NOT_READY"] = 4] = "STATUS_NOT_READY"; +})(UAStatus = exports.UAStatus || (exports.UAStatus = {})); + + +/***/ }), +/* 6 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Constants_1 = __webpack_require__(3); +var Enums_1 = __webpack_require__(5); +var Grammar_1 = __webpack_require__(7); +var Utils_1 = __webpack_require__(11); +exports.getSupportedHeader = function (request) { + var optionTags = []; + if (request.method === Constants_1.C.REGISTER) { + optionTags.push("path", "gruu"); + } + else if (request.method === Constants_1.C.INVITE && + (request.ua.contact.pubGruu || request.ua.contact.tempGruu)) { + optionTags.push("gruu"); + } + if (request.ua.configuration.rel100 === Constants_1.C.supported.SUPPORTED) { + optionTags.push("100rel"); + } + if (request.ua.configuration.replaces === Constants_1.C.supported.SUPPORTED) { + optionTags.push("replaces"); + } + optionTags.push("outbound"); + optionTags = optionTags.concat(request.ua.configuration.extraSupported || []); + var allowUnregistered = request.ua.configuration.hackAllowUnregisteredOptionTags || false; + var optionTagSet = {}; + optionTags = optionTags.filter(function (optionTag) { + var registered = Constants_1.C.OPTION_TAGS[optionTag]; + var unique = !optionTagSet[optionTag]; + optionTagSet[optionTag] = true; + return (registered || allowUnregistered) && unique; + }); + return "Supported: " + optionTags.join(", ") + "\r\n"; +}; +/** + * @class Class for outgoing SIP request. + * @param {String} method request method + * @param {String} ruri request uri + * @param {SIP.UA} ua + * @param {Object} params parameters that will have priority over ua.configuration parameters: + *
+ * - cseq, callId, fromTag, fromUri, fromDisplayName, toUri, toTag, routeSet + * @param {Object} [headers] extra headers + * @param {String} [body] + */ +var OutgoingRequest = /** @class */ (function () { + function OutgoingRequest(method, ruri, ua, params, extraHeaders, body) { + if (params === void 0) { params = {}; } + this.type = Enums_1.TypeStrings.OutgoingRequest; + this.ua = ua; + this.headers = {}; + this.method = method; + this.ruri = ruri; + this.body = body; + this.extraHeaders = (extraHeaders || []).slice(); + // Fill the Common SIP Request Headers + // Route + if (params.routeSet) { + this.setHeader("route", params.routeSet); + } + else if (ua.configuration.usePreloadedRoute && ua.transport) { + this.setHeader("route", ua.transport.server.sipUri); + } + // Via + // Empty Via header. Will be filled by the client transaction. + this.setHeader("via", ""); + // Max-Forwards + // is a constant on ua.c, removed for circular dependency + this.setHeader("max-forwards", "70"); + // To + var toUri = params.toUri || ruri; + this.toTag = params.toTag; + var to = (params.toDisplayName || params.toDisplayName === 0) ? '"' + params.toDisplayName + '" ' : ""; + to += "<" + (toUri.type === Enums_1.TypeStrings.URI ? toUri.toRaw() : toUri) + ">"; + to += this.toTag ? ";tag=" + this.toTag : ""; + this.to = Grammar_1.Grammar.nameAddrHeaderParse(to); + this.setHeader("to", to); + // From + var fromUri = params.fromUri || ua.configuration.uri || ""; + this.fromTag = params.fromTag || Utils_1.Utils.newTag(); + var from; + if (params.fromDisplayName || params.fromDisplayName === 0) { + from = '"' + params.fromDisplayName + '" '; + } + else if (ua.configuration.displayName) { + from = '"' + ua.configuration.displayName + '" '; + } + else { + from = ""; + } + from += "<" + (fromUri.type === Enums_1.TypeStrings.URI ? fromUri.toRaw() : fromUri) + ">;tag="; + from += this.fromTag; + this.from = Grammar_1.Grammar.nameAddrHeaderParse(from); + this.setHeader("from", from); + // Call-ID + this.callId = params.callId || (ua.configuration.sipjsId + Utils_1.Utils.createRandomToken(15)); + this.setHeader("call-id", this.callId); + // CSeq + // Why not make this a "1" if not provided? See: https://tools.ietf.org/html/rfc3261#section-8.1.1.5 + this.cseq = params.cseq || Math.floor(Math.random() * 10000); + this.setHeader("cseq", this.cseq + " " + method); + } + /** + * Get the value of the given header name at the given position. + * @param {String} name header name + * @returns {String|undefined} Returns the specified header, undefined if header doesn't exist. + */ + OutgoingRequest.prototype.getHeader = function (name) { + var header = this.headers[Utils_1.Utils.headerize(name)]; + if (header) { + if (header[0]) { + return header[0]; + } + } + else { + var regexp = new RegExp("^\\s*" + name + "\\s*:", "i"); + for (var _i = 0, _a = this.extraHeaders; _i < _a.length; _i++) { + var exHeader = _a[_i]; + if (regexp.test(exHeader)) { + return exHeader.substring(exHeader.indexOf(":") + 1).trim(); + } + } + } + return; + }; + /** + * Get the header/s of the given name. + * @param {String} name header name + * @returns {Array} Array with all the headers of the specified name. + */ + OutgoingRequest.prototype.getHeaders = function (name) { + var result = []; + var headerArray = this.headers[Utils_1.Utils.headerize(name)]; + if (headerArray) { + for (var _i = 0, headerArray_1 = headerArray; _i < headerArray_1.length; _i++) { + var headerPart = headerArray_1[_i]; + result.push(headerPart); + } + } + else { + var regexp = new RegExp("^\\s*" + name + "\\s*:", "i"); + for (var _a = 0, _b = this.extraHeaders; _a < _b.length; _a++) { + var exHeader = _b[_a]; + if (regexp.test(exHeader)) { + result.push(exHeader.substring(exHeader.indexOf(":") + 1).trim()); + } + } + } + return result; + }; + /** + * Verify the existence of the given header. + * @param {String} name header name + * @returns {boolean} true if header with given name exists, false otherwise + */ + OutgoingRequest.prototype.hasHeader = function (name) { + if (this.headers[Utils_1.Utils.headerize(name)]) { + return true; + } + else { + var regexp = new RegExp("^\\s*" + name + "\\s*:", "i"); + for (var _i = 0, _a = this.extraHeaders; _i < _a.length; _i++) { + var extraHeader = _a[_i]; + if (regexp.test(extraHeader)) { + return true; + } + } + } + return false; + }; + /** + * Replace the the given header by the given value. + * @param {String} name header name + * @param {String | Array} value header value + */ + OutgoingRequest.prototype.setHeader = function (name, value) { + this.headers[Utils_1.Utils.headerize(name)] = (value instanceof Array) ? value : [value]; + }; + /** + * The Via header field indicates the transport used for the transaction + * and identifies the location where the response is to be sent. A Via + * header field value is added only after the transport that will be + * used to reach the next hop has been selected (which may involve the + * usage of the procedures in [4]). + * + * When the UAC creates a request, it MUST insert a Via into that + * request. The protocol name and protocol version in the header field + * MUST be SIP and 2.0, respectively. The Via header field value MUST + * contain a branch parameter. This parameter is used to identify the + * transaction created by that request. This parameter is used by both + * the client and the server. + * https://tools.ietf.org/html/rfc3261#section-8.1.1.7 + * @param branchParameter The branch parameter. + * @param transport The transport. + */ + OutgoingRequest.prototype.setViaHeader = function (branch, transport) { + // FIXME: Default scheme to "WSS" + // This should go away once transport is typed and we can be sure + // we are getting the something valid from there transport. + var scheme = "WSS"; + // FIXME: Transport's server property is not typed (as of writing this). + if (transport.server && transport.server.scheme) { + scheme = transport.server.scheme; + } + // FIXME: Hack + if (this.ua.configuration.hackViaTcp) { + scheme = "TCP"; + } + var via = "SIP/2.0/" + scheme; + via += " " + this.ua.configuration.viaHost + ";branch=" + branch; + if (this.ua.configuration.forceRport) { + via += ";rport"; + } + this.setHeader("via", via); + this.branch = branch; + }; + OutgoingRequest.prototype.toString = function () { + var msg = ""; + msg += this.method + " " + (this.ruri.type === Enums_1.TypeStrings.URI ? + this.ruri.toRaw() : this.ruri) + " SIP/2.0\r\n"; + for (var header in this.headers) { + if (this.headers[header]) { + for (var _i = 0, _a = this.headers[header]; _i < _a.length; _i++) { + var headerPart = _a[_i]; + msg += header + ": " + headerPart + "\r\n"; + } + } + } + for (var _b = 0, _c = this.extraHeaders; _b < _c.length; _b++) { + var header = _c[_b]; + msg += header.trim() + "\r\n"; + } + msg += exports.getSupportedHeader(this); + msg += "User-Agent: " + this.ua.configuration.userAgentString + "\r\n"; + if (this.body) { + if (typeof this.body === "string") { + msg += "Content-Length: " + Utils_1.Utils.str_utf8_length(this.body) + "\r\n\r\n"; + msg += this.body; + } + else { + if (this.body.body && this.body.contentType) { + msg += "Content-Type: " + this.body.contentType + "\r\n"; + msg += "Content-Length: " + Utils_1.Utils.str_utf8_length(this.body.body) + "\r\n\r\n"; + msg += this.body.body; + } + else { + msg += "Content-Length: " + 0 + "\r\n\r\n"; + } + } + } + else { + msg += "Content-Length: " + 0 + "\r\n\r\n"; + } + return msg; + }; + return OutgoingRequest; +}()); +exports.OutgoingRequest = OutgoingRequest; +/** + * @class Class for incoming SIP message. + */ +// tslint:disable-next-line:max-classes-per-file +var IncomingMessage = /** @class */ (function () { + function IncomingMessage() { + this.type = Enums_1.TypeStrings.IncomingMessage; + this.headers = {}; + } + /** + * Insert a header of the given name and value into the last position of the + * header array. + * @param {String} name header name + * @param {String} value header value + */ + IncomingMessage.prototype.addHeader = function (name, value) { + var header = { raw: value }; + name = Utils_1.Utils.headerize(name); + if (this.headers[name]) { + this.headers[name].push(header); + } + else { + this.headers[name] = [header]; + } + }; + /** + * Get the value of the given header name at the given position. + * @param {String} name header name + * @returns {String|undefined} Returns the specified header, undefined if header doesn't exist. + */ + IncomingMessage.prototype.getHeader = function (name) { + var header = this.headers[Utils_1.Utils.headerize(name)]; + if (header) { + if (header[0]) { + return header[0].raw; + } + } + else { + return; + } + }; + /** + * Get the header/s of the given name. + * @param {String} name header name + * @returns {Array} Array with all the headers of the specified name. + */ + IncomingMessage.prototype.getHeaders = function (name) { + var header = this.headers[Utils_1.Utils.headerize(name)]; + var result = []; + if (!header) { + return []; + } + for (var _i = 0, header_1 = header; _i < header_1.length; _i++) { + var headerPart = header_1[_i]; + result.push(headerPart.raw); + } + return result; + }; + /** + * Verify the existence of the given header. + * @param {String} name header name + * @returns {boolean} true if header with given name exists, false otherwise + */ + IncomingMessage.prototype.hasHeader = function (name) { + return !!this.headers[Utils_1.Utils.headerize(name)]; + }; + /** + * Parse the given header on the given index. + * @param {String} name header name + * @param {Number} [idx=0] header index + * @returns {Object|undefined} Parsed header object, undefined if the + * header is not present or in case of a parsing error. + */ + IncomingMessage.prototype.parseHeader = function (name, idx) { + if (idx === void 0) { idx = 0; } + name = Utils_1.Utils.headerize(name); + if (!this.headers[name]) { + // this.logger.log("header '" + name + "' not present"); + return; + } + else if (idx >= this.headers[name].length) { + // this.logger.log("not so many '" + name + "' headers present"); + return; + } + var header = this.headers[name][idx]; + var value = header.raw; + if (header.parsed) { + return header.parsed; + } + // substitute '-' by '_' for grammar rule matching. + var parsed = Grammar_1.Grammar.parse(value, name.replace(/-/g, "_")); + if (parsed === -1) { + this.headers[name].splice(idx, 1); // delete from headers + // this.logger.warn('error parsing "' + name + '" header field with value "' + value + '"'); + return; + } + else { + header.parsed = parsed; + return parsed; + } + }; + /** + * Message Header attribute selector. Alias of parseHeader. + * @param {String} name header name + * @param {Number} [idx=0] header index + * @returns {Object|undefined} Parsed header object, undefined if the + * header is not present or in case of a parsing error. + * + * @example + * message.s('via',3).port + */ + IncomingMessage.prototype.s = function (name, idx) { + if (idx === void 0) { idx = 0; } + return this.parseHeader(name, idx); + }; + /** + * Replace the value of the given header by the value. + * @param {String} name header name + * @param {String} value header value + */ + IncomingMessage.prototype.setHeader = function (name, value) { + this.headers[Utils_1.Utils.headerize(name)] = [{ raw: value }]; + }; + IncomingMessage.prototype.toString = function () { + return this.data; + }; + return IncomingMessage; +}()); +exports.IncomingMessage = IncomingMessage; +/** + * @class Class for incoming SIP request. + */ +// tslint:disable-next-line:max-classes-per-file +var IncomingRequest = /** @class */ (function (_super) { + __extends(IncomingRequest, _super); + function IncomingRequest(ua) { + var _this = _super.call(this) || this; + _this.ua = ua; + _this.type = Enums_1.TypeStrings.IncomingRequest; + return _this; + } + return IncomingRequest; +}(IncomingMessage)); +exports.IncomingRequest = IncomingRequest; +/** + * @class Class for incoming SIP response. + */ +// tslint:disable-next-line:max-classes-per-file +var IncomingResponse = /** @class */ (function (_super) { + __extends(IncomingResponse, _super); + function IncomingResponse(ua) { + var _this = _super.call(this) || this; + _this.ua = ua; + _this.type = Enums_1.TypeStrings.IncomingResponse; + _this.headers = {}; + return _this; + } + return IncomingResponse; +}(IncomingMessage)); +exports.IncomingResponse = IncomingResponse; + + +/***/ }), +/* 7 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +var pegGrammar = __webpack_require__(8); +var Grammar; +(function (Grammar) { + function parse(input, startRule) { + var options = { startRule: startRule }; + try { + pegGrammar.parse(input, options); + } + catch (e) { + options.data = -1; + } + return options.data; + } + Grammar.parse = parse; + /** + * Parse the given string and returns a SIP.NameAddrHeader instance or undefined if + * it is an invalid NameAddrHeader. + * @public + * @param {String} name_addr_header + */ + function nameAddrHeaderParse(nameAddrHeader) { + var parsedNameAddrHeader = Grammar.parse(nameAddrHeader, "Name_Addr_Header"); + return parsedNameAddrHeader !== -1 ? parsedNameAddrHeader : undefined; + } + Grammar.nameAddrHeaderParse = nameAddrHeaderParse; + /** + * Parse the given string and returns a SIP.URI instance or undefined if + * it is an invalid URI. + * @public + * @param {String} uri + */ + function URIParse(uri) { + var parsedUri = Grammar.parse(uri, "SIP_URI"); + return parsedUri !== -1 ? parsedUri : undefined; + } + Grammar.URIParse = URIParse; +})(Grammar = exports.Grammar || (exports.Grammar = {})); + + +/***/ }), +/* 8 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +// tslint:disable:interface-name +// tslint:disable: trailing-comma +// tslint:disable: object-literal-sort-keys +// tslint:disable: max-line-length +// tslint:disable: only-arrow-functions +// tslint:disable: one-variable-per-declaration +// tslint:disable: no-consecutive-blank-lines +// tslint:disable: align +// tslint:disable: radix +// tslint:disable: quotemark +// tslint:disable: semicolon +// tslint:disable: object-literal-shorthand +// tslint:disable: variable-name +// tslint:disable: no-var-keyword +// tslint:disable: whitespace +// tslint:disable: curly +// tslint:disable: prefer-const +// tslint:disable: object-literal-key-quotes +// tslint:disable: no-string-literal +// tslint:disable: one-line +// tslint:disable: no-unused-expression +// tslint:disable: space-before-function-paren +// tslint:disable: arrow-return-shorthand +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +// Generated by PEG.js v. 0.10.0 (ts-pegjs plugin v. 0.2.3 ) +// +// https://pegjs.org/ https://github.com/metadevpro/ts-pegjs +var NameAddrHeader_1 = __webpack_require__(9); +var URI_1 = __webpack_require__(10); +var SyntaxError = /** @class */ (function (_super) { + __extends(SyntaxError, _super); + function SyntaxError(message, expected, found, location) { + var _this = _super.call(this) || this; + _this.message = message; + _this.expected = expected; + _this.found = found; + _this.location = location; + _this.name = "SyntaxError"; + if (typeof Error.captureStackTrace === "function") { + Error.captureStackTrace(_this, SyntaxError); + } + return _this; + } + SyntaxError.buildMessage = function (expected, found) { + function hex(ch) { + return ch.charCodeAt(0).toString(16).toUpperCase(); + } + function literalEscape(s) { + return s + .replace(/\\/g, "\\\\") + .replace(/"/g, "\\\"") + .replace(/\0/g, "\\0") + .replace(/\t/g, "\\t") + .replace(/\n/g, "\\n") + .replace(/\r/g, "\\r") + .replace(/[\x00-\x0F]/g, function (ch) { return "\\x0" + hex(ch); }) + .replace(/[\x10-\x1F\x7F-\x9F]/g, function (ch) { return "\\x" + hex(ch); }); + } + function classEscape(s) { + return s + .replace(/\\/g, "\\\\") + .replace(/\]/g, "\\]") + .replace(/\^/g, "\\^") + .replace(/-/g, "\\-") + .replace(/\0/g, "\\0") + .replace(/\t/g, "\\t") + .replace(/\n/g, "\\n") + .replace(/\r/g, "\\r") + .replace(/[\x00-\x0F]/g, function (ch) { return "\\x0" + hex(ch); }) + .replace(/[\x10-\x1F\x7F-\x9F]/g, function (ch) { return "\\x" + hex(ch); }); + } + function describeExpectation(expectation) { + switch (expectation.type) { + case "literal": + return "\"" + literalEscape(expectation.text) + "\""; + case "class": + var escapedParts = expectation.parts.map(function (part) { + return Array.isArray(part) + ? classEscape(part[0]) + "-" + classEscape(part[1]) + : classEscape(part); + }); + return "[" + (expectation.inverted ? "^" : "") + escapedParts + "]"; + case "any": + return "any character"; + case "end": + return "end of input"; + case "other": + return expectation.description; + } + } + function describeExpected(expected1) { + var descriptions = expected1.map(describeExpectation); + var i; + var j; + descriptions.sort(); + if (descriptions.length > 0) { + for (i = 1, j = 1; i < descriptions.length; i++) { + if (descriptions[i - 1] !== descriptions[i]) { + descriptions[j] = descriptions[i]; + j++; + } + } + descriptions.length = j; + } + switch (descriptions.length) { + case 1: + return descriptions[0]; + case 2: + return descriptions[0] + " or " + descriptions[1]; + default: + return descriptions.slice(0, -1).join(", ") + + ", or " + + descriptions[descriptions.length - 1]; + } + } + function describeFound(found1) { + return found1 ? "\"" + literalEscape(found1) + "\"" : "end of input"; + } + return "Expected " + describeExpected(expected) + " but " + describeFound(found) + " found."; + }; + return SyntaxError; +}(Error)); +exports.SyntaxError = SyntaxError; +function peg$parse(input, options) { + options = options !== undefined ? options : {}; + var peg$FAILED = {}; + var peg$startRuleFunctions = { Contact: peg$parseContact, Name_Addr_Header: peg$parseName_Addr_Header, Record_Route: peg$parseRecord_Route, Request_Response: peg$parseRequest_Response, SIP_URI: peg$parseSIP_URI, Subscription_State: peg$parseSubscription_State, Supported: peg$parseSupported, Require: peg$parseRequire, Via: peg$parseVia, absoluteURI: peg$parseabsoluteURI, Call_ID: peg$parseCall_ID, Content_Disposition: peg$parseContent_Disposition, Content_Length: peg$parseContent_Length, Content_Type: peg$parseContent_Type, CSeq: peg$parseCSeq, displayName: peg$parsedisplayName, Event: peg$parseEvent, From: peg$parseFrom, host: peg$parsehost, Max_Forwards: peg$parseMax_Forwards, Min_SE: peg$parseMin_SE, Proxy_Authenticate: peg$parseProxy_Authenticate, quoted_string: peg$parsequoted_string, Refer_To: peg$parseRefer_To, Replaces: peg$parseReplaces, Session_Expires: peg$parseSession_Expires, stun_URI: peg$parsestun_URI, To: peg$parseTo, turn_URI: peg$parseturn_URI, uuid: peg$parseuuid, WWW_Authenticate: peg$parseWWW_Authenticate, challenge: peg$parsechallenge, sipfrag: peg$parsesipfrag, Referred_By: peg$parseReferred_By }; + var peg$startRuleFunction = peg$parseContact; + var peg$c0 = "\r\n"; + var peg$c1 = peg$literalExpectation("\r\n", false); + var peg$c2 = /^[0-9]/; + var peg$c3 = peg$classExpectation([["0", "9"]], false, false); + var peg$c4 = /^[a-zA-Z]/; + var peg$c5 = peg$classExpectation([["a", "z"], ["A", "Z"]], false, false); + var peg$c6 = /^[0-9a-fA-F]/; + var peg$c7 = peg$classExpectation([["0", "9"], ["a", "f"], ["A", "F"]], false, false); + var peg$c8 = /^[\0-\xFF]/; + var peg$c9 = peg$classExpectation([["\0", "\xFF"]], false, false); + var peg$c10 = /^["]/; + var peg$c11 = peg$classExpectation(["\""], false, false); + var peg$c12 = " "; + var peg$c13 = peg$literalExpectation(" ", false); + var peg$c14 = "\t"; + var peg$c15 = peg$literalExpectation("\t", false); + var peg$c16 = /^[a-zA-Z0-9]/; + var peg$c17 = peg$classExpectation([["a", "z"], ["A", "Z"], ["0", "9"]], false, false); + var peg$c18 = ";"; + var peg$c19 = peg$literalExpectation(";", false); + var peg$c20 = "/"; + var peg$c21 = peg$literalExpectation("/", false); + var peg$c22 = "?"; + var peg$c23 = peg$literalExpectation("?", false); + var peg$c24 = ":"; + var peg$c25 = peg$literalExpectation(":", false); + var peg$c26 = "@"; + var peg$c27 = peg$literalExpectation("@", false); + var peg$c28 = "&"; + var peg$c29 = peg$literalExpectation("&", false); + var peg$c30 = "="; + var peg$c31 = peg$literalExpectation("=", false); + var peg$c32 = "+"; + var peg$c33 = peg$literalExpectation("+", false); + var peg$c34 = "$"; + var peg$c35 = peg$literalExpectation("$", false); + var peg$c36 = ","; + var peg$c37 = peg$literalExpectation(",", false); + var peg$c38 = "-"; + var peg$c39 = peg$literalExpectation("-", false); + var peg$c40 = "_"; + var peg$c41 = peg$literalExpectation("_", false); + var peg$c42 = "."; + var peg$c43 = peg$literalExpectation(".", false); + var peg$c44 = "!"; + var peg$c45 = peg$literalExpectation("!", false); + var peg$c46 = "~"; + var peg$c47 = peg$literalExpectation("~", false); + var peg$c48 = "*"; + var peg$c49 = peg$literalExpectation("*", false); + var peg$c50 = "'"; + var peg$c51 = peg$literalExpectation("'", false); + var peg$c52 = "("; + var peg$c53 = peg$literalExpectation("(", false); + var peg$c54 = ")"; + var peg$c55 = peg$literalExpectation(")", false); + var peg$c56 = "%"; + var peg$c57 = peg$literalExpectation("%", false); + var peg$c58 = function () { return " "; }; + var peg$c59 = function () { return ':'; }; + var peg$c60 = /^[!-~]/; + var peg$c61 = peg$classExpectation([["!", "~"]], false, false); + var peg$c62 = /^[\x80-\uFFFF]/; + var peg$c63 = peg$classExpectation([["\x80", "\uFFFF"]], false, false); + var peg$c64 = /^[\x80-\xBF]/; + var peg$c65 = peg$classExpectation([["\x80", "\xBF"]], false, false); + var peg$c66 = /^[a-f]/; + var peg$c67 = peg$classExpectation([["a", "f"]], false, false); + var peg$c68 = "`"; + var peg$c69 = peg$literalExpectation("`", false); + var peg$c70 = "<"; + var peg$c71 = peg$literalExpectation("<", false); + var peg$c72 = ">"; + var peg$c73 = peg$literalExpectation(">", false); + var peg$c74 = "\\"; + var peg$c75 = peg$literalExpectation("\\", false); + var peg$c76 = "["; + var peg$c77 = peg$literalExpectation("[", false); + var peg$c78 = "]"; + var peg$c79 = peg$literalExpectation("]", false); + var peg$c80 = "{"; + var peg$c81 = peg$literalExpectation("{", false); + var peg$c82 = "}"; + var peg$c83 = peg$literalExpectation("}", false); + var peg$c84 = function () { return "*"; }; + var peg$c85 = function () { return "/"; }; + var peg$c86 = function () { return "="; }; + var peg$c87 = function () { return "("; }; + var peg$c88 = function () { return ")"; }; + var peg$c89 = function () { return ">"; }; + var peg$c90 = function () { return "<"; }; + var peg$c91 = function () { return ","; }; + var peg$c92 = function () { return ";"; }; + var peg$c93 = function () { return ":"; }; + var peg$c94 = function () { return "\""; }; + var peg$c95 = /^[!-']/; + var peg$c96 = peg$classExpectation([["!", "'"]], false, false); + var peg$c97 = /^[*-[]/; + var peg$c98 = peg$classExpectation([["*", "["]], false, false); + var peg$c99 = /^[\]-~]/; + var peg$c100 = peg$classExpectation([["]", "~"]], false, false); + var peg$c101 = function (contents) { + return contents; + }; + var peg$c102 = /^[#-[]/; + var peg$c103 = peg$classExpectation([["#", "["]], false, false); + var peg$c104 = /^[\0-\t]/; + var peg$c105 = peg$classExpectation([["\0", "\t"]], false, false); + var peg$c106 = /^[\x0B-\f]/; + var peg$c107 = peg$classExpectation([["\x0B", "\f"]], false, false); + var peg$c108 = /^[\x0E-\x7F]/; + var peg$c109 = peg$classExpectation([["\x0E", "\x7F"]], false, false); + var peg$c110 = function () { + options = options || { data: {} }; + options.data.uri = new URI_1.URI(options.data.scheme, options.data.user, options.data.host, options.data.port); + delete options.data.scheme; + delete options.data.user; + delete options.data.host; + delete options.data.host_type; + delete options.data.port; + }; + var peg$c111 = function () { + options = options || { data: {} }; + options.data.uri = new URI_1.URI(options.data.scheme, options.data.user, options.data.host, options.data.port, options.data.uri_params, options.data.uri_headers); + delete options.data.scheme; + delete options.data.user; + delete options.data.host; + delete options.data.host_type; + delete options.data.port; + delete options.data.uri_params; + if (options.startRule === 'SIP_URI') { + options.data = options.data.uri; + } + }; + var peg$c112 = "sips"; + var peg$c113 = peg$literalExpectation("sips", true); + var peg$c114 = "sip"; + var peg$c115 = peg$literalExpectation("sip", true); + var peg$c116 = function (uri_scheme) { + options = options || { data: {} }; + options.data.scheme = uri_scheme; + }; + var peg$c117 = function () { + options = options || { data: {} }; + options.data.user = decodeURIComponent(text().slice(0, -1)); + }; + var peg$c118 = function () { + options = options || { data: {} }; + options.data.password = text(); + }; + var peg$c119 = function () { + options = options || { data: {} }; + options.data.host = text(); + return options.data.host; + }; + var peg$c120 = function () { + options = options || { data: {} }; + options.data.host_type = 'domain'; + return text(); + }; + var peg$c121 = /^[a-zA-Z0-9_\-]/; + var peg$c122 = peg$classExpectation([["a", "z"], ["A", "Z"], ["0", "9"], "_", "-"], false, false); + var peg$c123 = /^[a-zA-Z0-9\-]/; + var peg$c124 = peg$classExpectation([["a", "z"], ["A", "Z"], ["0", "9"], "-"], false, false); + var peg$c125 = function () { + options = options || { data: {} }; + options.data.host_type = 'IPv6'; + return text(); + }; + var peg$c126 = "::"; + var peg$c127 = peg$literalExpectation("::", false); + var peg$c128 = function () { + options = options || { data: {} }; + options.data.host_type = 'IPv6'; + return text(); + }; + var peg$c129 = function () { + options = options || { data: {} }; + options.data.host_type = 'IPv4'; + return text(); + }; + var peg$c130 = "25"; + var peg$c131 = peg$literalExpectation("25", false); + var peg$c132 = /^[0-5]/; + var peg$c133 = peg$classExpectation([["0", "5"]], false, false); + var peg$c134 = "2"; + var peg$c135 = peg$literalExpectation("2", false); + var peg$c136 = /^[0-4]/; + var peg$c137 = peg$classExpectation([["0", "4"]], false, false); + var peg$c138 = "1"; + var peg$c139 = peg$literalExpectation("1", false); + var peg$c140 = /^[1-9]/; + var peg$c141 = peg$classExpectation([["1", "9"]], false, false); + var peg$c142 = function (port) { + options = options || { data: {} }; + port = parseInt(port.join('')); + options.data.port = port; + return port; + }; + var peg$c143 = "transport="; + var peg$c144 = peg$literalExpectation("transport=", true); + var peg$c145 = "udp"; + var peg$c146 = peg$literalExpectation("udp", true); + var peg$c147 = "tcp"; + var peg$c148 = peg$literalExpectation("tcp", true); + var peg$c149 = "sctp"; + var peg$c150 = peg$literalExpectation("sctp", true); + var peg$c151 = "tls"; + var peg$c152 = peg$literalExpectation("tls", true); + var peg$c153 = function (transport) { + options = options || { data: {} }; + if (!options.data.uri_params) + options.data.uri_params = {}; + options.data.uri_params['transport'] = transport.toLowerCase(); + }; + var peg$c154 = "user="; + var peg$c155 = peg$literalExpectation("user=", true); + var peg$c156 = "phone"; + var peg$c157 = peg$literalExpectation("phone", true); + var peg$c158 = "ip"; + var peg$c159 = peg$literalExpectation("ip", true); + var peg$c160 = function (user) { + options = options || { data: {} }; + if (!options.data.uri_params) + options.data.uri_params = {}; + options.data.uri_params['user'] = user.toLowerCase(); + }; + var peg$c161 = "method="; + var peg$c162 = peg$literalExpectation("method=", true); + var peg$c163 = function (method) { + options = options || { data: {} }; + if (!options.data.uri_params) + options.data.uri_params = {}; + options.data.uri_params['method'] = method; + }; + var peg$c164 = "ttl="; + var peg$c165 = peg$literalExpectation("ttl=", true); + var peg$c166 = function (ttl) { + options = options || { data: {} }; + if (!options.data.params) + options.data.params = {}; + options.data.params['ttl'] = ttl; + }; + var peg$c167 = "maddr="; + var peg$c168 = peg$literalExpectation("maddr=", true); + var peg$c169 = function (maddr) { + options = options || { data: {} }; + if (!options.data.uri_params) + options.data.uri_params = {}; + options.data.uri_params['maddr'] = maddr; + }; + var peg$c170 = "lr"; + var peg$c171 = peg$literalExpectation("lr", true); + var peg$c172 = function () { + options = options || { data: {} }; + if (!options.data.uri_params) + options.data.uri_params = {}; + options.data.uri_params['lr'] = undefined; + }; + var peg$c173 = function (param, value) { + options = options || { data: {} }; + if (!options.data.uri_params) + options.data.uri_params = {}; + if (value === null) { + value = undefined; + } + else { + value = value[1]; + } + options.data.uri_params[param.toLowerCase()] = value; + }; + var peg$c174 = function (hname, hvalue) { + hname = hname.join('').toLowerCase(); + hvalue = hvalue.join(''); + options = options || { data: {} }; + if (!options.data.uri_headers) + options.data.uri_headers = {}; + if (!options.data.uri_headers[hname]) { + options.data.uri_headers[hname] = [hvalue]; + } + else { + options.data.uri_headers[hname].push(hvalue); + } + }; + var peg$c175 = function () { + options = options || { data: {} }; + // lots of tests fail if this isn't guarded... + if (options.startRule === 'Refer_To') { + options.data.uri = new URI_1.URI(options.data.scheme, options.data.user, options.data.host, options.data.port, options.data.uri_params, options.data.uri_headers); + delete options.data.scheme; + delete options.data.user; + delete options.data.host; + delete options.data.host_type; + delete options.data.port; + delete options.data.uri_params; + } + }; + var peg$c176 = "//"; + var peg$c177 = peg$literalExpectation("//", false); + var peg$c178 = function () { + options = options || { data: {} }; + options.data.scheme = text(); + }; + var peg$c179 = peg$literalExpectation("SIP", true); + var peg$c180 = function () { + options = options || { data: {} }; + options.data.sip_version = text(); + }; + var peg$c181 = "INVITE"; + var peg$c182 = peg$literalExpectation("INVITE", false); + var peg$c183 = "ACK"; + var peg$c184 = peg$literalExpectation("ACK", false); + var peg$c185 = "VXACH"; + var peg$c186 = peg$literalExpectation("VXACH", false); + var peg$c187 = "OPTIONS"; + var peg$c188 = peg$literalExpectation("OPTIONS", false); + var peg$c189 = "BYE"; + var peg$c190 = peg$literalExpectation("BYE", false); + var peg$c191 = "CANCEL"; + var peg$c192 = peg$literalExpectation("CANCEL", false); + var peg$c193 = "REGISTER"; + var peg$c194 = peg$literalExpectation("REGISTER", false); + var peg$c195 = "SUBSCRIBE"; + var peg$c196 = peg$literalExpectation("SUBSCRIBE", false); + var peg$c197 = "NOTIFY"; + var peg$c198 = peg$literalExpectation("NOTIFY", false); + var peg$c199 = "REFER"; + var peg$c200 = peg$literalExpectation("REFER", false); + var peg$c201 = "PUBLISH"; + var peg$c202 = peg$literalExpectation("PUBLISH", false); + var peg$c203 = function () { + options = options || { data: {} }; + options.data.method = text(); + return options.data.method; + }; + var peg$c204 = function (status_code) { + options = options || { data: {} }; + options.data.status_code = parseInt(status_code.join('')); + }; + var peg$c205 = function () { + options = options || { data: {} }; + options.data.reason_phrase = text(); + }; + var peg$c206 = function () { + options = options || { data: {} }; + options.data = text(); + }; + var peg$c207 = function () { + var idx, length; + options = options || { data: {} }; + length = options.data.multi_header.length; + for (idx = 0; idx < length; idx++) { + if (options.data.multi_header[idx].parsed === null) { + options.data = null; + break; + } + } + if (options.data !== null) { + options.data = options.data.multi_header; + } + else { + options.data = -1; + } + }; + var peg$c208 = function () { + var header; + options = options || { data: {} }; + if (!options.data.multi_header) + options.data.multi_header = []; + try { + header = new NameAddrHeader_1.NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); + delete options.data.uri; + delete options.data.displayName; + delete options.data.params; + } + catch (e) { + header = null; + } + options.data.multi_header.push({ 'position': peg$currPos, + 'offset': location().start.offset, + 'parsed': header + }); + }; + var peg$c209 = function (displayName) { + displayName = text().trim(); + if (displayName[0] === '\"') { + displayName = displayName.substring(1, displayName.length - 1); + } + options = options || { data: {} }; + options.data.displayName = displayName; + }; + var peg$c210 = "q"; + var peg$c211 = peg$literalExpectation("q", true); + var peg$c212 = function (q) { + options = options || { data: {} }; + if (!options.data.params) + options.data.params = {}; + options.data.params['q'] = q; + }; + var peg$c213 = "expires"; + var peg$c214 = peg$literalExpectation("expires", true); + var peg$c215 = function (expires) { + options = options || { data: {} }; + if (!options.data.params) + options.data.params = {}; + options.data.params['expires'] = expires; + }; + var peg$c216 = function (delta_seconds) { + return parseInt(delta_seconds.join('')); + }; + var peg$c217 = "0"; + var peg$c218 = peg$literalExpectation("0", false); + var peg$c219 = function () { + return parseFloat(text()); + }; + var peg$c220 = function (param, value) { + options = options || { data: {} }; + if (!options.data.params) + options.data.params = {}; + if (value === null) { + value = undefined; + } + else { + value = value[1]; + } + options.data.params[param.toLowerCase()] = value; + }; + var peg$c221 = "render"; + var peg$c222 = peg$literalExpectation("render", true); + var peg$c223 = "session"; + var peg$c224 = peg$literalExpectation("session", true); + var peg$c225 = "icon"; + var peg$c226 = peg$literalExpectation("icon", true); + var peg$c227 = "alert"; + var peg$c228 = peg$literalExpectation("alert", true); + var peg$c229 = function () { + options = options || { data: {} }; + if (options.startRule === 'Content_Disposition') { + options.data.type = text().toLowerCase(); + } + }; + var peg$c230 = "handling"; + var peg$c231 = peg$literalExpectation("handling", true); + var peg$c232 = "optional"; + var peg$c233 = peg$literalExpectation("optional", true); + var peg$c234 = "required"; + var peg$c235 = peg$literalExpectation("required", true); + var peg$c236 = function (length) { + options = options || { data: {} }; + options.data = parseInt(length.join('')); + }; + var peg$c237 = function () { + options = options || { data: {} }; + options.data = text(); + }; + var peg$c238 = "text"; + var peg$c239 = peg$literalExpectation("text", true); + var peg$c240 = "image"; + var peg$c241 = peg$literalExpectation("image", true); + var peg$c242 = "audio"; + var peg$c243 = peg$literalExpectation("audio", true); + var peg$c244 = "video"; + var peg$c245 = peg$literalExpectation("video", true); + var peg$c246 = "application"; + var peg$c247 = peg$literalExpectation("application", true); + var peg$c248 = "message"; + var peg$c249 = peg$literalExpectation("message", true); + var peg$c250 = "multipart"; + var peg$c251 = peg$literalExpectation("multipart", true); + var peg$c252 = "x-"; + var peg$c253 = peg$literalExpectation("x-", true); + var peg$c254 = function (cseq_value) { + options = options || { data: {} }; + options.data.value = parseInt(cseq_value.join('')); + }; + var peg$c255 = function (expires) { options = options || { data: {} }; options.data = expires; }; + var peg$c256 = function (event_type) { + options = options || { data: {} }; + options.data.event = event_type.toLowerCase(); + }; + var peg$c257 = function () { + options = options || { data: {} }; + var tag = options.data.tag; + options.data = new NameAddrHeader_1.NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); + if (tag) { + options.data.setParam('tag', tag); + } + }; + var peg$c258 = "tag"; + var peg$c259 = peg$literalExpectation("tag", true); + var peg$c260 = function (tag) { options = options || { data: {} }; options.data.tag = tag; }; + var peg$c261 = function (forwards) { + options = options || { data: {} }; + options.data = parseInt(forwards.join('')); + }; + var peg$c262 = function (min_expires) { options = options || { data: {} }; options.data = min_expires; }; + var peg$c263 = function () { + options = options || { data: {} }; + options.data = new NameAddrHeader_1.NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); + }; + var peg$c264 = "digest"; + var peg$c265 = peg$literalExpectation("Digest", true); + var peg$c266 = "realm"; + var peg$c267 = peg$literalExpectation("realm", true); + var peg$c268 = function (realm) { options = options || { data: {} }; options.data.realm = realm; }; + var peg$c269 = "domain"; + var peg$c270 = peg$literalExpectation("domain", true); + var peg$c271 = "nonce"; + var peg$c272 = peg$literalExpectation("nonce", true); + var peg$c273 = function (nonce) { options = options || { data: {} }; options.data.nonce = nonce; }; + var peg$c274 = "opaque"; + var peg$c275 = peg$literalExpectation("opaque", true); + var peg$c276 = function (opaque) { options = options || { data: {} }; options.data.opaque = opaque; }; + var peg$c277 = "stale"; + var peg$c278 = peg$literalExpectation("stale", true); + var peg$c279 = "true"; + var peg$c280 = peg$literalExpectation("true", true); + var peg$c281 = function () { options = options || { data: {} }; options.data.stale = true; }; + var peg$c282 = "false"; + var peg$c283 = peg$literalExpectation("false", true); + var peg$c284 = function () { options = options || { data: {} }; options.data.stale = false; }; + var peg$c285 = "algorithm"; + var peg$c286 = peg$literalExpectation("algorithm", true); + var peg$c287 = "md5"; + var peg$c288 = peg$literalExpectation("MD5", true); + var peg$c289 = "md5-sess"; + var peg$c290 = peg$literalExpectation("MD5-sess", true); + var peg$c291 = function (algorithm) { + options = options || { data: {} }; + options.data.algorithm = algorithm.toUpperCase(); + }; + var peg$c292 = "qop"; + var peg$c293 = peg$literalExpectation("qop", true); + var peg$c294 = "auth-int"; + var peg$c295 = peg$literalExpectation("auth-int", true); + var peg$c296 = "auth"; + var peg$c297 = peg$literalExpectation("auth", true); + var peg$c298 = function (qop_value) { + options = options || { data: {} }; + options.data.qop || (options.data.qop = []); + options.data.qop.push(qop_value.toLowerCase()); + }; + var peg$c299 = function (rack_value) { + options = options || { data: {} }; + options.data.value = parseInt(rack_value.join('')); + }; + var peg$c300 = function () { + var idx, length; + options = options || { data: {} }; + length = options.data.multi_header.length; + for (idx = 0; idx < length; idx++) { + if (options.data.multi_header[idx].parsed === null) { + options.data = null; + break; + } + } + if (options.data !== null) { + options.data = options.data.multi_header; + } + else { + options.data = -1; + } + }; + var peg$c301 = function () { + var header; + options = options || { data: {} }; + if (!options.data.multi_header) + options.data.multi_header = []; + try { + header = new NameAddrHeader_1.NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); + delete options.data.uri; + delete options.data.displayName; + delete options.data.params; + } + catch (e) { + header = null; + } + options.data.multi_header.push({ 'position': peg$currPos, + 'offset': location().start.offset, + 'parsed': header + }); + }; + var peg$c302 = function () { + options = options || { data: {} }; + options.data = new NameAddrHeader_1.NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); + }; + var peg$c303 = function () { + options = options || { data: {} }; + if (!(options.data.replaces_from_tag && options.data.replaces_to_tag)) { + options.data = -1; + } + }; + var peg$c304 = function () { + options = options || { data: {} }; + options.data = { + call_id: options.data + }; + }; + var peg$c305 = "from-tag"; + var peg$c306 = peg$literalExpectation("from-tag", true); + var peg$c307 = function (from_tag) { + options = options || { data: {} }; + options.data.replaces_from_tag = from_tag; + }; + var peg$c308 = "to-tag"; + var peg$c309 = peg$literalExpectation("to-tag", true); + var peg$c310 = function (to_tag) { + options = options || { data: {} }; + options.data.replaces_to_tag = to_tag; + }; + var peg$c311 = "early-only"; + var peg$c312 = peg$literalExpectation("early-only", true); + var peg$c313 = function () { + options = options || { data: {} }; + options.data.early_only = true; + }; + var peg$c314 = function (head, r) { return r; }; + var peg$c315 = function (head, tail) { return list(head, tail); }; + var peg$c316 = function (value) { + options = options || { data: {} }; + if (options.startRule === 'Require') { + options.data = value || []; + } + }; + var peg$c317 = function (rseq_value) { + options = options || { data: {} }; + options.data.value = parseInt(rseq_value.join('')); + }; + var peg$c318 = "active"; + var peg$c319 = peg$literalExpectation("active", true); + var peg$c320 = "pending"; + var peg$c321 = peg$literalExpectation("pending", true); + var peg$c322 = "terminated"; + var peg$c323 = peg$literalExpectation("terminated", true); + var peg$c324 = function () { + options = options || { data: {} }; + options.data.state = text(); + }; + var peg$c325 = "reason"; + var peg$c326 = peg$literalExpectation("reason", true); + var peg$c327 = function (reason) { + options = options || { data: {} }; + if (typeof reason !== 'undefined') + options.data.reason = reason; + }; + var peg$c328 = function (expires) { + options = options || { data: {} }; + if (typeof expires !== 'undefined') + options.data.expires = expires; + }; + var peg$c329 = "retry_after"; + var peg$c330 = peg$literalExpectation("retry_after", true); + var peg$c331 = function (retry_after) { + options = options || { data: {} }; + if (typeof retry_after !== 'undefined') + options.data.retry_after = retry_after; + }; + var peg$c332 = "deactivated"; + var peg$c333 = peg$literalExpectation("deactivated", true); + var peg$c334 = "probation"; + var peg$c335 = peg$literalExpectation("probation", true); + var peg$c336 = "rejected"; + var peg$c337 = peg$literalExpectation("rejected", true); + var peg$c338 = "timeout"; + var peg$c339 = peg$literalExpectation("timeout", true); + var peg$c340 = "giveup"; + var peg$c341 = peg$literalExpectation("giveup", true); + var peg$c342 = "noresource"; + var peg$c343 = peg$literalExpectation("noresource", true); + var peg$c344 = "invariant"; + var peg$c345 = peg$literalExpectation("invariant", true); + var peg$c346 = function (value) { + options = options || { data: {} }; + if (options.startRule === 'Supported') { + options.data = value || []; + } + }; + var peg$c347 = function () { + options = options || { data: {} }; + var tag = options.data.tag; + options.data = new NameAddrHeader_1.NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); + if (tag) { + options.data.setParam('tag', tag); + } + }; + var peg$c348 = "ttl"; + var peg$c349 = peg$literalExpectation("ttl", true); + var peg$c350 = function (via_ttl_value) { + options = options || { data: {} }; + options.data.ttl = via_ttl_value; + }; + var peg$c351 = "maddr"; + var peg$c352 = peg$literalExpectation("maddr", true); + var peg$c353 = function (via_maddr) { + options = options || { data: {} }; + options.data.maddr = via_maddr; + }; + var peg$c354 = "received"; + var peg$c355 = peg$literalExpectation("received", true); + var peg$c356 = function (via_received) { + options = options || { data: {} }; + options.data.received = via_received; + }; + var peg$c357 = "branch"; + var peg$c358 = peg$literalExpectation("branch", true); + var peg$c359 = function (via_branch) { + options = options || { data: {} }; + options.data.branch = via_branch; + }; + var peg$c360 = "rport"; + var peg$c361 = peg$literalExpectation("rport", true); + var peg$c362 = function (response_port) { + options = options || { data: {} }; + if (typeof response_port !== 'undefined') + options.data.rport = response_port.join(''); + }; + var peg$c363 = function (via_protocol) { + options = options || { data: {} }; + options.data.protocol = via_protocol; + }; + var peg$c364 = peg$literalExpectation("UDP", true); + var peg$c365 = peg$literalExpectation("TCP", true); + var peg$c366 = peg$literalExpectation("TLS", true); + var peg$c367 = peg$literalExpectation("SCTP", true); + var peg$c368 = function (via_transport) { + options = options || { data: {} }; + options.data.transport = via_transport; + }; + var peg$c369 = function () { + options = options || { data: {} }; + options.data.host = text(); + }; + var peg$c370 = function (via_sent_by_port) { + options = options || { data: {} }; + options.data.port = parseInt(via_sent_by_port.join('')); + }; + var peg$c371 = function (ttl) { + return parseInt(ttl.join('')); + }; + var peg$c372 = function (deltaSeconds) { + options = options || { data: {} }; + if (options.startRule === 'Session_Expires') { + options.data.deltaSeconds = deltaSeconds; + } + }; + var peg$c373 = "refresher"; + var peg$c374 = peg$literalExpectation("refresher", false); + var peg$c375 = "uas"; + var peg$c376 = peg$literalExpectation("uas", false); + var peg$c377 = "uac"; + var peg$c378 = peg$literalExpectation("uac", false); + var peg$c379 = function (endpoint) { + options = options || { data: {} }; + if (options.startRule === 'Session_Expires') { + options.data.refresher = endpoint; + } + }; + var peg$c380 = function (deltaSeconds) { + options = options || { data: {} }; + if (options.startRule === 'Min_SE') { + options.data = deltaSeconds; + } + }; + var peg$c381 = "stuns"; + var peg$c382 = peg$literalExpectation("stuns", true); + var peg$c383 = "stun"; + var peg$c384 = peg$literalExpectation("stun", true); + var peg$c385 = function (scheme) { + options = options || { data: {} }; + options.data.scheme = scheme; + }; + var peg$c386 = function (host) { + options = options || { data: {} }; + options.data.host = host; + }; + var peg$c387 = "?transport="; + var peg$c388 = peg$literalExpectation("?transport=", false); + var peg$c389 = "turns"; + var peg$c390 = peg$literalExpectation("turns", true); + var peg$c391 = "turn"; + var peg$c392 = peg$literalExpectation("turn", true); + var peg$c393 = function (transport) { + options = options || { data: {} }; + options.data.transport = transport; + }; + var peg$c394 = function () { + options = options || { data: {} }; + options.data = text(); + }; + var peg$c395 = "Referred-By"; + var peg$c396 = peg$literalExpectation("Referred-By", false); + var peg$c397 = "b"; + var peg$c398 = peg$literalExpectation("b", false); + var peg$c399 = "cid"; + var peg$c400 = peg$literalExpectation("cid", false); + var peg$currPos = 0; + var peg$savedPos = 0; + var peg$posDetailsCache = [{ line: 1, column: 1 }]; + var peg$maxFailPos = 0; + var peg$maxFailExpected = []; + var peg$silentFails = 0; + var peg$result; + if (options.startRule !== undefined) { + if (!(options.startRule in peg$startRuleFunctions)) { + throw new Error("Can't start parsing from rule \"" + options.startRule + "\"."); + } + peg$startRuleFunction = peg$startRuleFunctions[options.startRule]; + } + function text() { + return input.substring(peg$savedPos, peg$currPos); + } + function location() { + return peg$computeLocation(peg$savedPos, peg$currPos); + } + function expected(description, location1) { + location1 = location1 !== undefined + ? location1 + : peg$computeLocation(peg$savedPos, peg$currPos); + throw peg$buildStructuredError([peg$otherExpectation(description)], input.substring(peg$savedPos, peg$currPos), location1); + } + function error(message, location1) { + location1 = location1 !== undefined + ? location1 + : peg$computeLocation(peg$savedPos, peg$currPos); + throw peg$buildSimpleError(message, location1); + } + function peg$literalExpectation(text1, ignoreCase) { + return { type: "literal", text: text1, ignoreCase: ignoreCase }; + } + function peg$classExpectation(parts, inverted, ignoreCase) { + return { type: "class", parts: parts, inverted: inverted, ignoreCase: ignoreCase }; + } + function peg$anyExpectation() { + return { type: "any" }; + } + function peg$endExpectation() { + return { type: "end" }; + } + function peg$otherExpectation(description) { + return { type: "other", description: description }; + } + function peg$computePosDetails(pos) { + var details = peg$posDetailsCache[pos]; + var p; + if (details) { + return details; + } + else { + p = pos - 1; + while (!peg$posDetailsCache[p]) { + p--; + } + details = peg$posDetailsCache[p]; + details = { + line: details.line, + column: details.column + }; + while (p < pos) { + if (input.charCodeAt(p) === 10) { + details.line++; + details.column = 1; + } + else { + details.column++; + } + p++; + } + peg$posDetailsCache[pos] = details; + return details; + } + } + function peg$computeLocation(startPos, endPos) { + var startPosDetails = peg$computePosDetails(startPos); + var endPosDetails = peg$computePosDetails(endPos); + return { + start: { + offset: startPos, + line: startPosDetails.line, + column: startPosDetails.column + }, + end: { + offset: endPos, + line: endPosDetails.line, + column: endPosDetails.column + } + }; + } + function peg$fail(expected1) { + if (peg$currPos < peg$maxFailPos) { + return; + } + if (peg$currPos > peg$maxFailPos) { + peg$maxFailPos = peg$currPos; + peg$maxFailExpected = []; + } + peg$maxFailExpected.push(expected1); + } + function peg$buildSimpleError(message, location1) { + return new SyntaxError(message, [], "", location1); + } + function peg$buildStructuredError(expected1, found, location1) { + return new SyntaxError(SyntaxError.buildMessage(expected1, found), expected1, found, location1); + } + function peg$parseCRLF() { + var s0; + if (input.substr(peg$currPos, 2) === peg$c0) { + s0 = peg$c0; + peg$currPos += 2; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c1); + } + } + return s0; + } + function peg$parseDIGIT() { + var s0; + if (peg$c2.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c3); + } + } + return s0; + } + function peg$parseALPHA() { + var s0; + if (peg$c4.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c5); + } + } + return s0; + } + function peg$parseHEXDIG() { + var s0; + if (peg$c6.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c7); + } + } + return s0; + } + function peg$parseWSP() { + var s0; + s0 = peg$parseSP(); + if (s0 === peg$FAILED) { + s0 = peg$parseHTAB(); + } + return s0; + } + function peg$parseOCTET() { + var s0; + if (peg$c8.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c9); + } + } + return s0; + } + function peg$parseDQUOTE() { + var s0; + if (peg$c10.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c11); + } + } + return s0; + } + function peg$parseSP() { + var s0; + if (input.charCodeAt(peg$currPos) === 32) { + s0 = peg$c12; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c13); + } + } + return s0; + } + function peg$parseHTAB() { + var s0; + if (input.charCodeAt(peg$currPos) === 9) { + s0 = peg$c14; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c15); + } + } + return s0; + } + function peg$parsealphanum() { + var s0; + if (peg$c16.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c17); + } + } + return s0; + } + function peg$parsereserved() { + var s0; + if (input.charCodeAt(peg$currPos) === 59) { + s0 = peg$c18; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c19); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 47) { + s0 = peg$c20; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c21); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 63) { + s0 = peg$c22; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c23); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s0 = peg$c24; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 64) { + s0 = peg$c26; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c27); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 38) { + s0 = peg$c28; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c29); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s0 = peg$c30; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c31); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s0 = peg$c32; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 36) { + s0 = peg$c34; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c35); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s0 = peg$c36; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c37); + } + } + } + } + } + } + } + } + } + } + } + return s0; + } + function peg$parseunreserved() { + var s0; + s0 = peg$parsealphanum(); + if (s0 === peg$FAILED) { + s0 = peg$parsemark(); + } + return s0; + } + function peg$parsemark() { + var s0; + if (input.charCodeAt(peg$currPos) === 45) { + s0 = peg$c38; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c39); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 95) { + s0 = peg$c40; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c41); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s0 = peg$c42; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c43); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 33) { + s0 = peg$c44; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c45); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 126) { + s0 = peg$c46; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c47); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 42) { + s0 = peg$c48; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c49); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 39) { + s0 = peg$c50; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c51); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 40) { + s0 = peg$c52; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c53); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s0 = peg$c54; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c55); + } + } + } + } + } + } + } + } + } + } + return s0; + } + function peg$parseescaped() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + s1 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 37) { + s2 = peg$c56; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c57); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseHEXDIG(); + if (s3 !== peg$FAILED) { + s4 = peg$parseHEXDIG(); + if (s4 !== peg$FAILED) { + s2 = [s2, s3, s4]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s0 = input.substring(s0, peg$currPos); + } + else { + s0 = s1; + } + return s0; + } + function peg$parseLWS() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$currPos; + s2 = []; + s3 = peg$parseWSP(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseWSP(); + } + if (s2 !== peg$FAILED) { + s3 = peg$parseCRLF(); + if (s3 !== peg$FAILED) { + s2 = [s2, s3]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseWSP(); + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseWSP(); + } + } + else { + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c58(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseSWS() { + var s0; + s0 = peg$parseLWS(); + if (s0 === peg$FAILED) { + s0 = null; + } + return s0; + } + function peg$parseHCOLON() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = []; + s2 = peg$parseSP(); + if (s2 === peg$FAILED) { + s2 = peg$parseHTAB(); + } + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseSP(); + if (s2 === peg$FAILED) { + s2 = peg$parseHTAB(); + } + } + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s2 = peg$c24; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseSWS(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c59(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseTEXT_UTF8_TRIM() { + var s0, s1, s2, s3, s4, s5, s6; + s0 = peg$currPos; + s1 = peg$currPos; + s2 = []; + s3 = peg$parseTEXT_UTF8char(); + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseTEXT_UTF8char(); + } + } + else { + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$currPos; + s5 = []; + s6 = peg$parseLWS(); + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parseLWS(); + } + if (s5 !== peg$FAILED) { + s6 = peg$parseTEXT_UTF8char(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$currPos; + s5 = []; + s6 = peg$parseLWS(); + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parseLWS(); + } + if (s5 !== peg$FAILED) { + s6 = peg$parseTEXT_UTF8char(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + if (s3 !== peg$FAILED) { + s2 = [s2, s3]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s0 = input.substring(s0, peg$currPos); + } + else { + s0 = s1; + } + return s0; + } + function peg$parseTEXT_UTF8char() { + var s0; + if (peg$c60.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c61); + } + } + if (s0 === peg$FAILED) { + s0 = peg$parseUTF8_NONASCII(); + } + return s0; + } + function peg$parseUTF8_NONASCII() { + var s0; + if (peg$c62.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c63); + } + } + return s0; + } + function peg$parseUTF8_CONT() { + var s0; + if (peg$c64.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c65); + } + } + return s0; + } + function peg$parseLHEX() { + var s0; + s0 = peg$parseDIGIT(); + if (s0 === peg$FAILED) { + if (peg$c66.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c67); + } + } + } + return s0; + } + function peg$parsetoken() { + var s0, s1, s2; + s0 = peg$currPos; + s1 = []; + s2 = peg$parsealphanum(); + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s2 = peg$c38; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c39); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s2 = peg$c42; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c43); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 33) { + s2 = peg$c44; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c45); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 37) { + s2 = peg$c56; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c57); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 42) { + s2 = peg$c48; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c49); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 95) { + s2 = peg$c40; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c41); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s2 = peg$c32; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 96) { + s2 = peg$c68; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c69); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 39) { + s2 = peg$c50; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c51); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 126) { + s2 = peg$c46; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c47); + } + } + } + } + } + } + } + } + } + } + } + } + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parsealphanum(); + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s2 = peg$c38; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c39); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s2 = peg$c42; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c43); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 33) { + s2 = peg$c44; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c45); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 37) { + s2 = peg$c56; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c57); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 42) { + s2 = peg$c48; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c49); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 95) { + s2 = peg$c40; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c41); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s2 = peg$c32; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 96) { + s2 = peg$c68; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c69); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 39) { + s2 = peg$c50; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c51); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 126) { + s2 = peg$c46; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c47); + } + } + } + } + } + } + } + } + } + } + } + } + } + } + else { + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s0 = input.substring(s0, peg$currPos); + } + else { + s0 = s1; + } + return s0; + } + function peg$parsetoken_nodot() { + var s0, s1, s2; + s0 = peg$currPos; + s1 = []; + s2 = peg$parsealphanum(); + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s2 = peg$c38; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c39); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 33) { + s2 = peg$c44; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c45); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 37) { + s2 = peg$c56; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c57); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 42) { + s2 = peg$c48; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c49); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 95) { + s2 = peg$c40; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c41); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s2 = peg$c32; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 96) { + s2 = peg$c68; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c69); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 39) { + s2 = peg$c50; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c51); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 126) { + s2 = peg$c46; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c47); + } + } + } + } + } + } + } + } + } + } + } + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parsealphanum(); + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s2 = peg$c38; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c39); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 33) { + s2 = peg$c44; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c45); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 37) { + s2 = peg$c56; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c57); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 42) { + s2 = peg$c48; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c49); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 95) { + s2 = peg$c40; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c41); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s2 = peg$c32; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 96) { + s2 = peg$c68; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c69); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 39) { + s2 = peg$c50; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c51); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 126) { + s2 = peg$c46; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c47); + } + } + } + } + } + } + } + } + } + } + } + } + } + else { + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s0 = input.substring(s0, peg$currPos); + } + else { + s0 = s1; + } + return s0; + } + function peg$parseseparators() { + var s0; + if (input.charCodeAt(peg$currPos) === 40) { + s0 = peg$c52; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c53); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s0 = peg$c54; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c55); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 60) { + s0 = peg$c70; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c71); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 62) { + s0 = peg$c72; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c73); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 64) { + s0 = peg$c26; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c27); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s0 = peg$c36; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c37); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 59) { + s0 = peg$c18; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c19); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s0 = peg$c24; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 92) { + s0 = peg$c74; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c75); + } + } + if (s0 === peg$FAILED) { + s0 = peg$parseDQUOTE(); + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 47) { + s0 = peg$c20; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c21); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 91) { + s0 = peg$c76; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c77); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s0 = peg$c78; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c79); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 63) { + s0 = peg$c22; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c23); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s0 = peg$c30; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c31); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 123) { + s0 = peg$c80; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c81); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 125) { + s0 = peg$c82; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c83); + } + } + if (s0 === peg$FAILED) { + s0 = peg$parseSP(); + if (s0 === peg$FAILED) { + s0 = peg$parseHTAB(); + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + return s0; + } + function peg$parseword() { + var s0, s1, s2; + s0 = peg$currPos; + s1 = []; + s2 = peg$parsealphanum(); + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s2 = peg$c38; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c39); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s2 = peg$c42; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c43); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 33) { + s2 = peg$c44; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c45); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 37) { + s2 = peg$c56; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c57); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 42) { + s2 = peg$c48; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c49); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 95) { + s2 = peg$c40; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c41); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s2 = peg$c32; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 96) { + s2 = peg$c68; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c69); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 39) { + s2 = peg$c50; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c51); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 126) { + s2 = peg$c46; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c47); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 40) { + s2 = peg$c52; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c53); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s2 = peg$c54; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c55); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 60) { + s2 = peg$c70; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c71); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 62) { + s2 = peg$c72; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c73); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s2 = peg$c24; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 92) { + s2 = peg$c74; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c75); + } + } + if (s2 === peg$FAILED) { + s2 = peg$parseDQUOTE(); + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 47) { + s2 = peg$c20; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c21); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 91) { + s2 = peg$c76; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c77); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s2 = peg$c78; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c79); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 63) { + s2 = peg$c22; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c23); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 123) { + s2 = peg$c80; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c81); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 125) { + s2 = peg$c82; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c83); + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parsealphanum(); + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s2 = peg$c38; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c39); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s2 = peg$c42; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c43); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 33) { + s2 = peg$c44; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c45); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 37) { + s2 = peg$c56; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c57); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 42) { + s2 = peg$c48; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c49); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 95) { + s2 = peg$c40; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c41); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s2 = peg$c32; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 96) { + s2 = peg$c68; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c69); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 39) { + s2 = peg$c50; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c51); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 126) { + s2 = peg$c46; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c47); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 40) { + s2 = peg$c52; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c53); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s2 = peg$c54; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c55); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 60) { + s2 = peg$c70; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c71); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 62) { + s2 = peg$c72; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c73); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s2 = peg$c24; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 92) { + s2 = peg$c74; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c75); + } + } + if (s2 === peg$FAILED) { + s2 = peg$parseDQUOTE(); + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 47) { + s2 = peg$c20; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c21); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 91) { + s2 = peg$c76; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c77); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s2 = peg$c78; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c79); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 63) { + s2 = peg$c22; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c23); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 123) { + s2 = peg$c80; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c81); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 125) { + s2 = peg$c82; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c83); + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + else { + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s0 = input.substring(s0, peg$currPos); + } + else { + s0 = s1; + } + return s0; + } + function peg$parseSTAR() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parseSWS(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 42) { + s2 = peg$c48; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c49); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseSWS(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c84(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseSLASH() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parseSWS(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 47) { + s2 = peg$c20; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c21); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseSWS(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c85(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseEQUAL() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parseSWS(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s2 = peg$c30; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c31); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseSWS(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c86(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseLPAREN() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parseSWS(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 40) { + s2 = peg$c52; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c53); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseSWS(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c87(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseRPAREN() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parseSWS(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s2 = peg$c54; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c55); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseSWS(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c88(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseRAQUOT() { + var s0, s1, s2; + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 62) { + s1 = peg$c72; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c73); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseSWS(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c89(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseLAQUOT() { + var s0, s1, s2; + s0 = peg$currPos; + s1 = peg$parseSWS(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 60) { + s2 = peg$c70; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c71); + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c90(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseCOMMA() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parseSWS(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s2 = peg$c36; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c37); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseSWS(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c91(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseSEMI() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parseSWS(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 59) { + s2 = peg$c18; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c19); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseSWS(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c92(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseCOLON() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parseSWS(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s2 = peg$c24; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseSWS(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c93(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseLDQUOT() { + var s0, s1, s2; + s0 = peg$currPos; + s1 = peg$parseSWS(); + if (s1 !== peg$FAILED) { + s2 = peg$parseDQUOTE(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c94(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseRDQUOT() { + var s0, s1, s2; + s0 = peg$currPos; + s1 = peg$parseDQUOTE(); + if (s1 !== peg$FAILED) { + s2 = peg$parseSWS(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c94(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsecomment() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parseLPAREN(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parsectext(); + if (s3 === peg$FAILED) { + s3 = peg$parsequoted_pair(); + if (s3 === peg$FAILED) { + s3 = peg$parsecomment(); + } + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parsectext(); + if (s3 === peg$FAILED) { + s3 = peg$parsequoted_pair(); + if (s3 === peg$FAILED) { + s3 = peg$parsecomment(); + } + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseRPAREN(); + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsectext() { + var s0; + if (peg$c95.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c96); + } + } + if (s0 === peg$FAILED) { + if (peg$c97.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c98); + } + } + if (s0 === peg$FAILED) { + if (peg$c99.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c100); + } + } + if (s0 === peg$FAILED) { + s0 = peg$parseUTF8_NONASCII(); + if (s0 === peg$FAILED) { + s0 = peg$parseLWS(); + } + } + } + } + return s0; + } + function peg$parsequoted_string() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$currPos; + s2 = peg$parseSWS(); + if (s2 !== peg$FAILED) { + s3 = peg$parseDQUOTE(); + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$parseqdtext(); + if (s5 === peg$FAILED) { + s5 = peg$parsequoted_pair(); + } + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$parseqdtext(); + if (s5 === peg$FAILED) { + s5 = peg$parsequoted_pair(); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseDQUOTE(); + if (s5 !== peg$FAILED) { + s2 = [s2, s3, s4, s5]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s0 = input.substring(s0, peg$currPos); + } + else { + s0 = s1; + } + return s0; + } + function peg$parsequoted_string_clean() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parseSWS(); + if (s1 !== peg$FAILED) { + s2 = peg$parseDQUOTE(); + if (s2 !== peg$FAILED) { + s3 = peg$currPos; + s4 = []; + s5 = peg$parseqdtext(); + if (s5 === peg$FAILED) { + s5 = peg$parsequoted_pair(); + } + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$parseqdtext(); + if (s5 === peg$FAILED) { + s5 = peg$parsequoted_pair(); + } + } + if (s4 !== peg$FAILED) { + s3 = input.substring(s3, peg$currPos); + } + else { + s3 = s4; + } + if (s3 !== peg$FAILED) { + s4 = peg$parseDQUOTE(); + if (s4 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c101(s3); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseqdtext() { + var s0; + s0 = peg$parseLWS(); + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 33) { + s0 = peg$c44; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c45); + } + } + if (s0 === peg$FAILED) { + if (peg$c102.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c103); + } + } + if (s0 === peg$FAILED) { + if (peg$c99.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c100); + } + } + if (s0 === peg$FAILED) { + s0 = peg$parseUTF8_NONASCII(); + } + } + } + } + return s0; + } + function peg$parsequoted_pair() { + var s0, s1, s2; + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 92) { + s1 = peg$c74; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c75); + } + } + if (s1 !== peg$FAILED) { + if (peg$c104.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c105); + } + } + if (s2 === peg$FAILED) { + if (peg$c106.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c107); + } + } + if (s2 === peg$FAILED) { + if (peg$c108.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c109); + } + } + } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseSIP_URI_noparams() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + s1 = peg$parseuri_scheme(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s2 = peg$c24; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseuserinfo(); + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + s4 = peg$parsehostport(); + if (s4 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c110(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseSIP_URI() { + var s0, s1, s2, s3, s4, s5, s6; + s0 = peg$currPos; + s1 = peg$parseuri_scheme(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s2 = peg$c24; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseuserinfo(); + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + s4 = peg$parsehostport(); + if (s4 !== peg$FAILED) { + s5 = peg$parseuri_parameters(); + if (s5 !== peg$FAILED) { + s6 = peg$parseheaders(); + if (s6 === peg$FAILED) { + s6 = null; + } + if (s6 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c111(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseuri_scheme() { + var s0, s1; + s0 = peg$currPos; + if (input.substr(peg$currPos, 4).toLowerCase() === peg$c112) { + s1 = input.substr(peg$currPos, 4); + peg$currPos += 4; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c113); + } + } + if (s1 === peg$FAILED) { + if (input.substr(peg$currPos, 3).toLowerCase() === peg$c114) { + s1 = input.substr(peg$currPos, 3); + peg$currPos += 3; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c115); + } + } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c116(s1); + } + s0 = s1; + return s0; + } + function peg$parseuserinfo() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + s1 = peg$parseuser(); + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s3 = peg$c24; + peg$currPos++; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s3 !== peg$FAILED) { + s4 = peg$parsepassword(); + if (s4 !== peg$FAILED) { + s3 = [s3, s4]; + s2 = s3; + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 64) { + s3 = peg$c26; + peg$currPos++; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c27); + } + } + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c117(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseuser() { + var s0, s1; + s0 = []; + s1 = peg$parseunreserved(); + if (s1 === peg$FAILED) { + s1 = peg$parseescaped(); + if (s1 === peg$FAILED) { + s1 = peg$parseuser_unreserved(); + } + } + if (s1 !== peg$FAILED) { + while (s1 !== peg$FAILED) { + s0.push(s1); + s1 = peg$parseunreserved(); + if (s1 === peg$FAILED) { + s1 = peg$parseescaped(); + if (s1 === peg$FAILED) { + s1 = peg$parseuser_unreserved(); + } + } + } + } + else { + s0 = peg$FAILED; + } + return s0; + } + function peg$parseuser_unreserved() { + var s0; + if (input.charCodeAt(peg$currPos) === 38) { + s0 = peg$c28; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c29); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s0 = peg$c30; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c31); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s0 = peg$c32; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 36) { + s0 = peg$c34; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c35); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s0 = peg$c36; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c37); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 59) { + s0 = peg$c18; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c19); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 63) { + s0 = peg$c22; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c23); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 47) { + s0 = peg$c20; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c21); + } + } + } + } + } + } + } + } + } + return s0; + } + function peg$parsepassword() { + var s0, s1, s2; + s0 = peg$currPos; + s1 = []; + s2 = peg$parseunreserved(); + if (s2 === peg$FAILED) { + s2 = peg$parseescaped(); + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 38) { + s2 = peg$c28; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c29); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s2 = peg$c30; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c31); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s2 = peg$c32; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 36) { + s2 = peg$c34; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c35); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s2 = peg$c36; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c37); + } + } + } + } + } + } + } + } + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseunreserved(); + if (s2 === peg$FAILED) { + s2 = peg$parseescaped(); + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 38) { + s2 = peg$c28; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c29); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s2 = peg$c30; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c31); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s2 = peg$c32; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 36) { + s2 = peg$c34; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c35); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s2 = peg$c36; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c37); + } + } + } + } + } + } + } + } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c118(); + } + s0 = s1; + return s0; + } + function peg$parsehostport() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + s1 = peg$parsehost(); + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s3 = peg$c24; + peg$currPos++; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s3 !== peg$FAILED) { + s4 = peg$parseport(); + if (s4 !== peg$FAILED) { + s3 = [s3, s4]; + s2 = s3; + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsehost() { + var s0, s1; + s0 = peg$currPos; + s1 = peg$parsehostname(); + if (s1 === peg$FAILED) { + s1 = peg$parseIPv4address(); + if (s1 === peg$FAILED) { + s1 = peg$parseIPv6reference(); + } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c119(); + } + s0 = s1; + return s0; + } + function peg$parsehostname() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + s1 = []; + s2 = peg$currPos; + s3 = peg$parsedomainlabel(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c42; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c43); + } + } + if (s4 !== peg$FAILED) { + s3 = [s3, s4]; + s2 = s3; + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$currPos; + s3 = peg$parsedomainlabel(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c42; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c43); + } + } + if (s4 !== peg$FAILED) { + s3 = [s3, s4]; + s2 = s3; + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parsetoplabel(); + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s3 = peg$c42; + peg$currPos++; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c43); + } + } + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c120(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsedomainlabel() { + var s0, s1; + s0 = []; + if (peg$c121.test(input.charAt(peg$currPos))) { + s1 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c122); + } + } + if (s1 !== peg$FAILED) { + while (s1 !== peg$FAILED) { + s0.push(s1); + if (peg$c121.test(input.charAt(peg$currPos))) { + s1 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c122); + } + } + } + } + else { + s0 = peg$FAILED; + } + return s0; + } + function peg$parsetoplabel() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (peg$c4.test(input.charAt(peg$currPos))) { + s1 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c5); + } + } + if (s1 !== peg$FAILED) { + s2 = []; + if (peg$c123.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c124); + } + } + while (s3 !== peg$FAILED) { + s2.push(s3); + if (peg$c123.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c124); + } + } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseIPv6reference() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c76; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c77); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseIPv6address(); + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s3 = peg$c78; + peg$currPos++; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c79); + } + } + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c125(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseIPv6address() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14; + s0 = peg$currPos; + s1 = peg$currPos; + s2 = peg$parseh16(); + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s3 = peg$c24; + peg$currPos++; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s3 !== peg$FAILED) { + s4 = peg$parseh16(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s5 = peg$c24; + peg$currPos++; + } + else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parseh16(); + if (s6 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s7 = peg$c24; + peg$currPos++; + } + else { + s7 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s7 !== peg$FAILED) { + s8 = peg$parseh16(); + if (s8 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s9 = peg$c24; + peg$currPos++; + } + else { + s9 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s9 !== peg$FAILED) { + s10 = peg$parseh16(); + if (s10 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s11 = peg$c24; + peg$currPos++; + } + else { + s11 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s11 !== peg$FAILED) { + s12 = peg$parseh16(); + if (s12 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s13 = peg$c24; + peg$currPos++; + } + else { + s13 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s13 !== peg$FAILED) { + s14 = peg$parsels32(); + if (s14 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c126) { + s2 = peg$c126; + peg$currPos += 2; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c127); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseh16(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s4 = peg$c24; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseh16(); + if (s5 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s6 = peg$c24; + peg$currPos++; + } + else { + s6 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s6 !== peg$FAILED) { + s7 = peg$parseh16(); + if (s7 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s8 = peg$c24; + peg$currPos++; + } + else { + s8 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s8 !== peg$FAILED) { + s9 = peg$parseh16(); + if (s9 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s10 = peg$c24; + peg$currPos++; + } + else { + s10 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s10 !== peg$FAILED) { + s11 = peg$parseh16(); + if (s11 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s12 = peg$c24; + peg$currPos++; + } + else { + s12 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s12 !== peg$FAILED) { + s13 = peg$parsels32(); + if (s13 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c126) { + s2 = peg$c126; + peg$currPos += 2; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c127); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseh16(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s4 = peg$c24; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseh16(); + if (s5 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s6 = peg$c24; + peg$currPos++; + } + else { + s6 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s6 !== peg$FAILED) { + s7 = peg$parseh16(); + if (s7 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s8 = peg$c24; + peg$currPos++; + } + else { + s8 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s8 !== peg$FAILED) { + s9 = peg$parseh16(); + if (s9 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s10 = peg$c24; + peg$currPos++; + } + else { + s10 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s10 !== peg$FAILED) { + s11 = peg$parsels32(); + if (s11 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6, s7, s8, s9, s10, s11]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c126) { + s2 = peg$c126; + peg$currPos += 2; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c127); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseh16(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s4 = peg$c24; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseh16(); + if (s5 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s6 = peg$c24; + peg$currPos++; + } + else { + s6 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s6 !== peg$FAILED) { + s7 = peg$parseh16(); + if (s7 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s8 = peg$c24; + peg$currPos++; + } + else { + s8 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s8 !== peg$FAILED) { + s9 = peg$parsels32(); + if (s9 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6, s7, s8, s9]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c126) { + s2 = peg$c126; + peg$currPos += 2; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c127); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseh16(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s4 = peg$c24; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseh16(); + if (s5 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s6 = peg$c24; + peg$currPos++; + } + else { + s6 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s6 !== peg$FAILED) { + s7 = peg$parsels32(); + if (s7 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6, s7]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c126) { + s2 = peg$c126; + peg$currPos += 2; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c127); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseh16(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s4 = peg$c24; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parsels32(); + if (s5 !== peg$FAILED) { + s2 = [s2, s3, s4, s5]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c126) { + s2 = peg$c126; + peg$currPos += 2; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c127); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parsels32(); + if (s3 !== peg$FAILED) { + s2 = [s2, s3]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c126) { + s2 = peg$c126; + peg$currPos += 2; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c127); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseh16(); + if (s3 !== peg$FAILED) { + s2 = [s2, s3]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = peg$currPos; + s2 = peg$parseh16(); + if (s2 !== peg$FAILED) { + if (input.substr(peg$currPos, 2) === peg$c126) { + s3 = peg$c126; + peg$currPos += 2; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c127); + } + } + if (s3 !== peg$FAILED) { + s4 = peg$parseh16(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s5 = peg$c24; + peg$currPos++; + } + else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parseh16(); + if (s6 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s7 = peg$c24; + peg$currPos++; + } + else { + s7 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s7 !== peg$FAILED) { + s8 = peg$parseh16(); + if (s8 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s9 = peg$c24; + peg$currPos++; + } + else { + s9 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s9 !== peg$FAILED) { + s10 = peg$parseh16(); + if (s10 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s11 = peg$c24; + peg$currPos++; + } + else { + s11 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s11 !== peg$FAILED) { + s12 = peg$parsels32(); + if (s12 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = peg$currPos; + s2 = peg$parseh16(); + if (s2 !== peg$FAILED) { + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s4 = peg$c24; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseh16(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + if (input.substr(peg$currPos, 2) === peg$c126) { + s4 = peg$c126; + peg$currPos += 2; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c127); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseh16(); + if (s5 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s6 = peg$c24; + peg$currPos++; + } + else { + s6 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s6 !== peg$FAILED) { + s7 = peg$parseh16(); + if (s7 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s8 = peg$c24; + peg$currPos++; + } + else { + s8 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s8 !== peg$FAILED) { + s9 = peg$parseh16(); + if (s9 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s10 = peg$c24; + peg$currPos++; + } + else { + s10 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s10 !== peg$FAILED) { + s11 = peg$parsels32(); + if (s11 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6, s7, s8, s9, s10, s11]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = peg$currPos; + s2 = peg$parseh16(); + if (s2 !== peg$FAILED) { + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s4 = peg$c24; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseh16(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + s4 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s5 = peg$c24; + peg$currPos++; + } + else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parseh16(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + if (input.substr(peg$currPos, 2) === peg$c126) { + s5 = peg$c126; + peg$currPos += 2; + } + else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c127); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parseh16(); + if (s6 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s7 = peg$c24; + peg$currPos++; + } + else { + s7 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s7 !== peg$FAILED) { + s8 = peg$parseh16(); + if (s8 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s9 = peg$c24; + peg$currPos++; + } + else { + s9 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s9 !== peg$FAILED) { + s10 = peg$parsels32(); + if (s10 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6, s7, s8, s9, s10]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = peg$currPos; + s2 = peg$parseh16(); + if (s2 !== peg$FAILED) { + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s4 = peg$c24; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseh16(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + s4 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s5 = peg$c24; + peg$currPos++; + } + else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parseh16(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s5 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s6 = peg$c24; + peg$currPos++; + } + else { + s6 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s6 !== peg$FAILED) { + s7 = peg$parseh16(); + if (s7 !== peg$FAILED) { + s6 = [s6, s7]; + s5 = s6; + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + if (s5 === peg$FAILED) { + s5 = null; + } + if (s5 !== peg$FAILED) { + if (input.substr(peg$currPos, 2) === peg$c126) { + s6 = peg$c126; + peg$currPos += 2; + } + else { + s6 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c127); + } + } + if (s6 !== peg$FAILED) { + s7 = peg$parseh16(); + if (s7 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s8 = peg$c24; + peg$currPos++; + } + else { + s8 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s8 !== peg$FAILED) { + s9 = peg$parsels32(); + if (s9 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6, s7, s8, s9]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = peg$currPos; + s2 = peg$parseh16(); + if (s2 !== peg$FAILED) { + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s4 = peg$c24; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseh16(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + s4 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s5 = peg$c24; + peg$currPos++; + } + else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parseh16(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s5 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s6 = peg$c24; + peg$currPos++; + } + else { + s6 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s6 !== peg$FAILED) { + s7 = peg$parseh16(); + if (s7 !== peg$FAILED) { + s6 = [s6, s7]; + s5 = s6; + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + if (s5 === peg$FAILED) { + s5 = null; + } + if (s5 !== peg$FAILED) { + s6 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s7 = peg$c24; + peg$currPos++; + } + else { + s7 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s7 !== peg$FAILED) { + s8 = peg$parseh16(); + if (s8 !== peg$FAILED) { + s7 = [s7, s8]; + s6 = s7; + } + else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } + else { + peg$currPos = s6; + s6 = peg$FAILED; + } + if (s6 === peg$FAILED) { + s6 = null; + } + if (s6 !== peg$FAILED) { + if (input.substr(peg$currPos, 2) === peg$c126) { + s7 = peg$c126; + peg$currPos += 2; + } + else { + s7 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c127); + } + } + if (s7 !== peg$FAILED) { + s8 = peg$parsels32(); + if (s8 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6, s7, s8]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = peg$currPos; + s2 = peg$parseh16(); + if (s2 !== peg$FAILED) { + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s4 = peg$c24; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseh16(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + s4 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s5 = peg$c24; + peg$currPos++; + } + else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parseh16(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s5 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s6 = peg$c24; + peg$currPos++; + } + else { + s6 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s6 !== peg$FAILED) { + s7 = peg$parseh16(); + if (s7 !== peg$FAILED) { + s6 = [s6, s7]; + s5 = s6; + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + if (s5 === peg$FAILED) { + s5 = null; + } + if (s5 !== peg$FAILED) { + s6 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s7 = peg$c24; + peg$currPos++; + } + else { + s7 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s7 !== peg$FAILED) { + s8 = peg$parseh16(); + if (s8 !== peg$FAILED) { + s7 = [s7, s8]; + s6 = s7; + } + else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } + else { + peg$currPos = s6; + s6 = peg$FAILED; + } + if (s6 === peg$FAILED) { + s6 = null; + } + if (s6 !== peg$FAILED) { + s7 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s8 = peg$c24; + peg$currPos++; + } + else { + s8 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s8 !== peg$FAILED) { + s9 = peg$parseh16(); + if (s9 !== peg$FAILED) { + s8 = [s8, s9]; + s7 = s8; + } + else { + peg$currPos = s7; + s7 = peg$FAILED; + } + } + else { + peg$currPos = s7; + s7 = peg$FAILED; + } + if (s7 === peg$FAILED) { + s7 = null; + } + if (s7 !== peg$FAILED) { + if (input.substr(peg$currPos, 2) === peg$c126) { + s8 = peg$c126; + peg$currPos += 2; + } + else { + s8 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c127); + } + } + if (s8 !== peg$FAILED) { + s9 = peg$parseh16(); + if (s9 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6, s7, s8, s9]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = peg$currPos; + s2 = peg$parseh16(); + if (s2 !== peg$FAILED) { + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s4 = peg$c24; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseh16(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + s4 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s5 = peg$c24; + peg$currPos++; + } + else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parseh16(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s5 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s6 = peg$c24; + peg$currPos++; + } + else { + s6 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s6 !== peg$FAILED) { + s7 = peg$parseh16(); + if (s7 !== peg$FAILED) { + s6 = [s6, s7]; + s5 = s6; + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + if (s5 === peg$FAILED) { + s5 = null; + } + if (s5 !== peg$FAILED) { + s6 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s7 = peg$c24; + peg$currPos++; + } + else { + s7 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s7 !== peg$FAILED) { + s8 = peg$parseh16(); + if (s8 !== peg$FAILED) { + s7 = [s7, s8]; + s6 = s7; + } + else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } + else { + peg$currPos = s6; + s6 = peg$FAILED; + } + if (s6 === peg$FAILED) { + s6 = null; + } + if (s6 !== peg$FAILED) { + s7 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s8 = peg$c24; + peg$currPos++; + } + else { + s8 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s8 !== peg$FAILED) { + s9 = peg$parseh16(); + if (s9 !== peg$FAILED) { + s8 = [s8, s9]; + s7 = s8; + } + else { + peg$currPos = s7; + s7 = peg$FAILED; + } + } + else { + peg$currPos = s7; + s7 = peg$FAILED; + } + if (s7 === peg$FAILED) { + s7 = null; + } + if (s7 !== peg$FAILED) { + s8 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s9 = peg$c24; + peg$currPos++; + } + else { + s9 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s9 !== peg$FAILED) { + s10 = peg$parseh16(); + if (s10 !== peg$FAILED) { + s9 = [s9, s10]; + s8 = s9; + } + else { + peg$currPos = s8; + s8 = peg$FAILED; + } + } + else { + peg$currPos = s8; + s8 = peg$FAILED; + } + if (s8 === peg$FAILED) { + s8 = null; + } + if (s8 !== peg$FAILED) { + if (input.substr(peg$currPos, 2) === peg$c126) { + s9 = peg$c126; + peg$currPos += 2; + } + else { + s9 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c127); + } + } + if (s9 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6, s7, s8, s9]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c128(); + } + s0 = s1; + return s0; + } + function peg$parseh16() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + s1 = peg$parseHEXDIG(); + if (s1 !== peg$FAILED) { + s2 = peg$parseHEXDIG(); + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + s3 = peg$parseHEXDIG(); + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + s4 = peg$parseHEXDIG(); + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s1 = [s1, s2, s3, s4]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsels32() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parseh16(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s2 = peg$c24; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseh16(); + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$parseIPv4address(); + } + return s0; + } + function peg$parseIPv4address() { + var s0, s1, s2, s3, s4, s5, s6, s7; + s0 = peg$currPos; + s1 = peg$parsedec_octet(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s2 = peg$c42; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c43); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parsedec_octet(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c42; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c43); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parsedec_octet(); + if (s5 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s6 = peg$c42; + peg$currPos++; + } + else { + s6 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c43); + } + } + if (s6 !== peg$FAILED) { + s7 = peg$parsedec_octet(); + if (s7 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c129(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsedec_octet() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c130) { + s1 = peg$c130; + peg$currPos += 2; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c131); + } + } + if (s1 !== peg$FAILED) { + if (peg$c132.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c133); + } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 50) { + s1 = peg$c134; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c135); + } + } + if (s1 !== peg$FAILED) { + if (peg$c136.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c137); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseDIGIT(); + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 49) { + s1 = peg$c138; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c139); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseDIGIT(); + if (s2 !== peg$FAILED) { + s3 = peg$parseDIGIT(); + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (peg$c140.test(input.charAt(peg$currPos))) { + s1 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c141); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseDIGIT(); + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$parseDIGIT(); + } + } + } + } + return s0; + } + function peg$parseport() { + var s0, s1, s2, s3, s4, s5, s6; + s0 = peg$currPos; + s1 = peg$currPos; + s2 = peg$parseDIGIT(); + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + s3 = peg$parseDIGIT(); + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + s4 = peg$parseDIGIT(); + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s5 = peg$parseDIGIT(); + if (s5 === peg$FAILED) { + s5 = null; + } + if (s5 !== peg$FAILED) { + s6 = peg$parseDIGIT(); + if (s6 === peg$FAILED) { + s6 = null; + } + if (s6 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c142(s1); + } + s0 = s1; + return s0; + } + function peg$parseuri_parameters() { + var s0, s1, s2, s3; + s0 = []; + s1 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 59) { + s2 = peg$c18; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c19); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseuri_parameter(); + if (s3 !== peg$FAILED) { + s2 = [s2, s3]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + while (s1 !== peg$FAILED) { + s0.push(s1); + s1 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 59) { + s2 = peg$c18; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c19); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseuri_parameter(); + if (s3 !== peg$FAILED) { + s2 = [s2, s3]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + return s0; + } + function peg$parseuri_parameter() { + var s0; + s0 = peg$parsetransport_param(); + if (s0 === peg$FAILED) { + s0 = peg$parseuser_param(); + if (s0 === peg$FAILED) { + s0 = peg$parsemethod_param(); + if (s0 === peg$FAILED) { + s0 = peg$parsettl_param(); + if (s0 === peg$FAILED) { + s0 = peg$parsemaddr_param(); + if (s0 === peg$FAILED) { + s0 = peg$parselr_param(); + if (s0 === peg$FAILED) { + s0 = peg$parseother_param(); + } + } + } + } + } + } + return s0; + } + function peg$parsetransport_param() { + var s0, s1, s2; + s0 = peg$currPos; + if (input.substr(peg$currPos, 10).toLowerCase() === peg$c143) { + s1 = input.substr(peg$currPos, 10); + peg$currPos += 10; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c144); + } + } + if (s1 !== peg$FAILED) { + if (input.substr(peg$currPos, 3).toLowerCase() === peg$c145) { + s2 = input.substr(peg$currPos, 3); + peg$currPos += 3; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c146); + } + } + if (s2 === peg$FAILED) { + if (input.substr(peg$currPos, 3).toLowerCase() === peg$c147) { + s2 = input.substr(peg$currPos, 3); + peg$currPos += 3; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c148); + } + } + if (s2 === peg$FAILED) { + if (input.substr(peg$currPos, 4).toLowerCase() === peg$c149) { + s2 = input.substr(peg$currPos, 4); + peg$currPos += 4; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c150); + } + } + if (s2 === peg$FAILED) { + if (input.substr(peg$currPos, 3).toLowerCase() === peg$c151) { + s2 = input.substr(peg$currPos, 3); + peg$currPos += 3; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c152); + } + } + if (s2 === peg$FAILED) { + s2 = peg$parsetoken(); + } + } + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c153(s2); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseuser_param() { + var s0, s1, s2; + s0 = peg$currPos; + if (input.substr(peg$currPos, 5).toLowerCase() === peg$c154) { + s1 = input.substr(peg$currPos, 5); + peg$currPos += 5; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c155); + } + } + if (s1 !== peg$FAILED) { + if (input.substr(peg$currPos, 5).toLowerCase() === peg$c156) { + s2 = input.substr(peg$currPos, 5); + peg$currPos += 5; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c157); + } + } + if (s2 === peg$FAILED) { + if (input.substr(peg$currPos, 2).toLowerCase() === peg$c158) { + s2 = input.substr(peg$currPos, 2); + peg$currPos += 2; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c159); + } + } + if (s2 === peg$FAILED) { + s2 = peg$parsetoken(); + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c160(s2); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsemethod_param() { + var s0, s1, s2; + s0 = peg$currPos; + if (input.substr(peg$currPos, 7).toLowerCase() === peg$c161) { + s1 = input.substr(peg$currPos, 7); + peg$currPos += 7; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c162); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseMethod(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c163(s2); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsettl_param() { + var s0, s1, s2; + s0 = peg$currPos; + if (input.substr(peg$currPos, 4).toLowerCase() === peg$c164) { + s1 = input.substr(peg$currPos, 4); + peg$currPos += 4; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c165); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parsettl(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c166(s2); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsemaddr_param() { + var s0, s1, s2; + s0 = peg$currPos; + if (input.substr(peg$currPos, 6).toLowerCase() === peg$c167) { + s1 = input.substr(peg$currPos, 6); + peg$currPos += 6; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c168); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parsehost(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c169(s2); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parselr_param() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + if (input.substr(peg$currPos, 2).toLowerCase() === peg$c170) { + s1 = input.substr(peg$currPos, 2); + peg$currPos += 2; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c171); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 61) { + s3 = peg$c30; + peg$currPos++; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c31); + } + } + if (s3 !== peg$FAILED) { + s4 = peg$parsetoken(); + if (s4 !== peg$FAILED) { + s3 = [s3, s4]; + s2 = s3; + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c172(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseother_param() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + s1 = peg$parsepname(); + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 61) { + s3 = peg$c30; + peg$currPos++; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c31); + } + } + if (s3 !== peg$FAILED) { + s4 = peg$parsepvalue(); + if (s4 !== peg$FAILED) { + s3 = [s3, s4]; + s2 = s3; + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c173(s1, s2); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsepname() { + var s0, s1, s2; + s0 = peg$currPos; + s1 = []; + s2 = peg$parseparamchar(); + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseparamchar(); + } + } + else { + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s0 = input.substring(s0, peg$currPos); + } + else { + s0 = s1; + } + return s0; + } + function peg$parsepvalue() { + var s0, s1, s2; + s0 = peg$currPos; + s1 = []; + s2 = peg$parseparamchar(); + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseparamchar(); + } + } + else { + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s0 = input.substring(s0, peg$currPos); + } + else { + s0 = s1; + } + return s0; + } + function peg$parseparamchar() { + var s0; + s0 = peg$parseparam_unreserved(); + if (s0 === peg$FAILED) { + s0 = peg$parseunreserved(); + if (s0 === peg$FAILED) { + s0 = peg$parseescaped(); + } + } + return s0; + } + function peg$parseparam_unreserved() { + var s0; + if (input.charCodeAt(peg$currPos) === 91) { + s0 = peg$c76; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c77); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s0 = peg$c78; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c79); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 47) { + s0 = peg$c20; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c21); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s0 = peg$c24; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 38) { + s0 = peg$c28; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c29); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s0 = peg$c32; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 36) { + s0 = peg$c34; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c35); + } + } + } + } + } + } + } + } + return s0; + } + function peg$parseheaders() { + var s0, s1, s2, s3, s4, s5, s6; + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 63) { + s1 = peg$c22; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c23); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseheader(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 38) { + s5 = peg$c28; + peg$currPos++; + } + else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c29); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parseheader(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 38) { + s5 = peg$c28; + peg$currPos++; + } + else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c29); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parseheader(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseheader() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parsehname(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s2 = peg$c30; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c31); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parsehvalue(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c174(s1, s3); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsehname() { + var s0, s1; + s0 = []; + s1 = peg$parsehnv_unreserved(); + if (s1 === peg$FAILED) { + s1 = peg$parseunreserved(); + if (s1 === peg$FAILED) { + s1 = peg$parseescaped(); + } + } + if (s1 !== peg$FAILED) { + while (s1 !== peg$FAILED) { + s0.push(s1); + s1 = peg$parsehnv_unreserved(); + if (s1 === peg$FAILED) { + s1 = peg$parseunreserved(); + if (s1 === peg$FAILED) { + s1 = peg$parseescaped(); + } + } + } + } + else { + s0 = peg$FAILED; + } + return s0; + } + function peg$parsehvalue() { + var s0, s1; + s0 = []; + s1 = peg$parsehnv_unreserved(); + if (s1 === peg$FAILED) { + s1 = peg$parseunreserved(); + if (s1 === peg$FAILED) { + s1 = peg$parseescaped(); + } + } + while (s1 !== peg$FAILED) { + s0.push(s1); + s1 = peg$parsehnv_unreserved(); + if (s1 === peg$FAILED) { + s1 = peg$parseunreserved(); + if (s1 === peg$FAILED) { + s1 = peg$parseescaped(); + } + } + } + return s0; + } + function peg$parsehnv_unreserved() { + var s0; + if (input.charCodeAt(peg$currPos) === 91) { + s0 = peg$c76; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c77); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s0 = peg$c78; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c79); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 47) { + s0 = peg$c20; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c21); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 63) { + s0 = peg$c22; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c23); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s0 = peg$c24; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s0 = peg$c32; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 36) { + s0 = peg$c34; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c35); + } + } + } + } + } + } + } + } + return s0; + } + function peg$parseRequest_Response() { + var s0; + s0 = peg$parseStatus_Line(); + if (s0 === peg$FAILED) { + s0 = peg$parseRequest_Line(); + } + return s0; + } + function peg$parseRequest_Line() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parseMethod(); + if (s1 !== peg$FAILED) { + s2 = peg$parseSP(); + if (s2 !== peg$FAILED) { + s3 = peg$parseRequest_URI(); + if (s3 !== peg$FAILED) { + s4 = peg$parseSP(); + if (s4 !== peg$FAILED) { + s5 = peg$parseSIP_Version(); + if (s5 !== peg$FAILED) { + s1 = [s1, s2, s3, s4, s5]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseRequest_URI() { + var s0; + s0 = peg$parseSIP_URI(); + if (s0 === peg$FAILED) { + s0 = peg$parseabsoluteURI(); + } + return s0; + } + function peg$parseabsoluteURI() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parsescheme(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s2 = peg$c24; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parsehier_part(); + if (s3 === peg$FAILED) { + s3 = peg$parseopaque_part(); + } + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c175(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsehier_part() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + s1 = peg$parsenet_path(); + if (s1 === peg$FAILED) { + s1 = peg$parseabs_path(); + } + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 63) { + s3 = peg$c22; + peg$currPos++; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c23); + } + } + if (s3 !== peg$FAILED) { + s4 = peg$parsequery(); + if (s4 !== peg$FAILED) { + s3 = [s3, s4]; + s2 = s3; + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsenet_path() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c176) { + s1 = peg$c176; + peg$currPos += 2; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c177); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseauthority(); + if (s2 !== peg$FAILED) { + s3 = peg$parseabs_path(); + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseabs_path() { + var s0, s1, s2; + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 47) { + s1 = peg$c20; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c21); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parsepath_segments(); + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseopaque_part() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parseuric_no_slash(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseuric(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseuric(); + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseuric() { + var s0; + s0 = peg$parsereserved(); + if (s0 === peg$FAILED) { + s0 = peg$parseunreserved(); + if (s0 === peg$FAILED) { + s0 = peg$parseescaped(); + } + } + return s0; + } + function peg$parseuric_no_slash() { + var s0; + s0 = peg$parseunreserved(); + if (s0 === peg$FAILED) { + s0 = peg$parseescaped(); + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 59) { + s0 = peg$c18; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c19); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 63) { + s0 = peg$c22; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c23); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s0 = peg$c24; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 64) { + s0 = peg$c26; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c27); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 38) { + s0 = peg$c28; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c29); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s0 = peg$c30; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c31); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s0 = peg$c32; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 36) { + s0 = peg$c34; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c35); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s0 = peg$c36; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c37); + } + } + } + } + } + } + } + } + } + } + } + } + return s0; + } + function peg$parsepath_segments() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parsesegment(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 47) { + s4 = peg$c20; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c21); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parsesegment(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 47) { + s4 = peg$c20; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c21); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parsesegment(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsesegment() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = []; + s2 = peg$parsepchar(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parsepchar(); + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 59) { + s4 = peg$c18; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c19); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseparam(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 59) { + s4 = peg$c18; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c19); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseparam(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseparam() { + var s0, s1; + s0 = []; + s1 = peg$parsepchar(); + while (s1 !== peg$FAILED) { + s0.push(s1); + s1 = peg$parsepchar(); + } + return s0; + } + function peg$parsepchar() { + var s0; + s0 = peg$parseunreserved(); + if (s0 === peg$FAILED) { + s0 = peg$parseescaped(); + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s0 = peg$c24; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 64) { + s0 = peg$c26; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c27); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 38) { + s0 = peg$c28; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c29); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s0 = peg$c30; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c31); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s0 = peg$c32; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 36) { + s0 = peg$c34; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c35); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s0 = peg$c36; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c37); + } + } + } + } + } + } + } + } + } + } + return s0; + } + function peg$parsescheme() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + s1 = peg$currPos; + s2 = peg$parseALPHA(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseALPHA(); + if (s4 === peg$FAILED) { + s4 = peg$parseDIGIT(); + if (s4 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s4 = peg$c32; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + if (s4 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s4 = peg$c38; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c39); + } + } + if (s4 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c42; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c43); + } + } + } + } + } + } + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseALPHA(); + if (s4 === peg$FAILED) { + s4 = peg$parseDIGIT(); + if (s4 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s4 = peg$c32; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + if (s4 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s4 = peg$c38; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c39); + } + } + if (s4 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c42; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c43); + } + } + } + } + } + } + } + if (s3 !== peg$FAILED) { + s2 = [s2, s3]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c178(); + } + s0 = s1; + return s0; + } + function peg$parseauthority() { + var s0; + s0 = peg$parsesrvr(); + if (s0 === peg$FAILED) { + s0 = peg$parsereg_name(); + } + return s0; + } + function peg$parsesrvr() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$currPos; + s2 = peg$parseuserinfo(); + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 64) { + s3 = peg$c26; + peg$currPos++; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c27); + } + } + if (s3 !== peg$FAILED) { + s2 = [s2, s3]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + s2 = peg$parsehostport(); + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = null; + } + return s0; + } + function peg$parsereg_name() { + var s0, s1; + s0 = []; + s1 = peg$parseunreserved(); + if (s1 === peg$FAILED) { + s1 = peg$parseescaped(); + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 36) { + s1 = peg$c34; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c35); + } + } + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s1 = peg$c36; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c37); + } + } + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 59) { + s1 = peg$c18; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c19); + } + } + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s1 = peg$c24; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 64) { + s1 = peg$c26; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c27); + } + } + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 38) { + s1 = peg$c28; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c29); + } + } + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s1 = peg$c30; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c31); + } + } + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s1 = peg$c32; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + } + } + } + } + } + } + } + } + } + if (s1 !== peg$FAILED) { + while (s1 !== peg$FAILED) { + s0.push(s1); + s1 = peg$parseunreserved(); + if (s1 === peg$FAILED) { + s1 = peg$parseescaped(); + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 36) { + s1 = peg$c34; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c35); + } + } + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s1 = peg$c36; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c37); + } + } + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 59) { + s1 = peg$c18; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c19); + } + } + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s1 = peg$c24; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 64) { + s1 = peg$c26; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c27); + } + } + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 38) { + s1 = peg$c28; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c29); + } + } + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s1 = peg$c30; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c31); + } + } + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s1 = peg$c32; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + } + } + } + } + } + } + } + } + } + } + } + else { + s0 = peg$FAILED; + } + return s0; + } + function peg$parsequery() { + var s0, s1; + s0 = []; + s1 = peg$parseuric(); + while (s1 !== peg$FAILED) { + s0.push(s1); + s1 = peg$parseuric(); + } + return s0; + } + function peg$parseSIP_Version() { + var s0, s1, s2, s3, s4, s5, s6; + s0 = peg$currPos; + if (input.substr(peg$currPos, 3).toLowerCase() === peg$c114) { + s1 = input.substr(peg$currPos, 3); + peg$currPos += 3; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c179); + } + } + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 47) { + s2 = peg$c20; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c21); + } + } + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseDIGIT(); + if (s4 !== peg$FAILED) { + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseDIGIT(); + } + } + else { + s3 = peg$FAILED; + } + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c42; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c43); + } + } + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$parseDIGIT(); + if (s6 !== peg$FAILED) { + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parseDIGIT(); + } + } + else { + s5 = peg$FAILED; + } + if (s5 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c180(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseINVITEm() { + var s0; + if (input.substr(peg$currPos, 6) === peg$c181) { + s0 = peg$c181; + peg$currPos += 6; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c182); + } + } + return s0; + } + function peg$parseACKm() { + var s0; + if (input.substr(peg$currPos, 3) === peg$c183) { + s0 = peg$c183; + peg$currPos += 3; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c184); + } + } + return s0; + } + function peg$parsePRACKm() { + var s0; + if (input.substr(peg$currPos, 5) === peg$c185) { + s0 = peg$c185; + peg$currPos += 5; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c186); + } + } + return s0; + } + function peg$parseOPTIONSm() { + var s0; + if (input.substr(peg$currPos, 7) === peg$c187) { + s0 = peg$c187; + peg$currPos += 7; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c188); + } + } + return s0; + } + function peg$parseBYEm() { + var s0; + if (input.substr(peg$currPos, 3) === peg$c189) { + s0 = peg$c189; + peg$currPos += 3; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c190); + } + } + return s0; + } + function peg$parseCANCELm() { + var s0; + if (input.substr(peg$currPos, 6) === peg$c191) { + s0 = peg$c191; + peg$currPos += 6; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c192); + } + } + return s0; + } + function peg$parseREGISTERm() { + var s0; + if (input.substr(peg$currPos, 8) === peg$c193) { + s0 = peg$c193; + peg$currPos += 8; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c194); + } + } + return s0; + } + function peg$parseSUBSCRIBEm() { + var s0; + if (input.substr(peg$currPos, 9) === peg$c195) { + s0 = peg$c195; + peg$currPos += 9; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c196); + } + } + return s0; + } + function peg$parseNOTIFYm() { + var s0; + if (input.substr(peg$currPos, 6) === peg$c197) { + s0 = peg$c197; + peg$currPos += 6; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c198); + } + } + return s0; + } + function peg$parseREFERm() { + var s0; + if (input.substr(peg$currPos, 5) === peg$c199) { + s0 = peg$c199; + peg$currPos += 5; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c200); + } + } + return s0; + } + function peg$parsePUBLISHm() { + var s0; + if (input.substr(peg$currPos, 7) === peg$c201) { + s0 = peg$c201; + peg$currPos += 7; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c202); + } + } + return s0; + } + function peg$parseMethod() { + var s0, s1; + s0 = peg$currPos; + s1 = peg$parseINVITEm(); + if (s1 === peg$FAILED) { + s1 = peg$parseACKm(); + if (s1 === peg$FAILED) { + s1 = peg$parseOPTIONSm(); + if (s1 === peg$FAILED) { + s1 = peg$parseBYEm(); + if (s1 === peg$FAILED) { + s1 = peg$parseCANCELm(); + if (s1 === peg$FAILED) { + s1 = peg$parseREGISTERm(); + if (s1 === peg$FAILED) { + s1 = peg$parseSUBSCRIBEm(); + if (s1 === peg$FAILED) { + s1 = peg$parsePUBLISHm(); + if (s1 === peg$FAILED) { + s1 = peg$parseNOTIFYm(); + if (s1 === peg$FAILED) { + s1 = peg$parseREFERm(); + if (s1 === peg$FAILED) { + s1 = peg$parsetoken(); + } + } + } + } + } + } + } + } + } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c203(); + } + s0 = s1; + return s0; + } + function peg$parseStatus_Line() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parseSIP_Version(); + if (s1 !== peg$FAILED) { + s2 = peg$parseSP(); + if (s2 !== peg$FAILED) { + s3 = peg$parseStatus_Code(); + if (s3 !== peg$FAILED) { + s4 = peg$parseSP(); + if (s4 !== peg$FAILED) { + s5 = peg$parseReason_Phrase(); + if (s5 !== peg$FAILED) { + s1 = [s1, s2, s3, s4, s5]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseStatus_Code() { + var s0, s1; + s0 = peg$currPos; + s1 = peg$parseextension_code(); + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c204(s1); + } + s0 = s1; + return s0; + } + function peg$parseextension_code() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parseDIGIT(); + if (s1 !== peg$FAILED) { + s2 = peg$parseDIGIT(); + if (s2 !== peg$FAILED) { + s3 = peg$parseDIGIT(); + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseReason_Phrase() { + var s0, s1, s2; + s0 = peg$currPos; + s1 = []; + s2 = peg$parsereserved(); + if (s2 === peg$FAILED) { + s2 = peg$parseunreserved(); + if (s2 === peg$FAILED) { + s2 = peg$parseescaped(); + if (s2 === peg$FAILED) { + s2 = peg$parseUTF8_NONASCII(); + if (s2 === peg$FAILED) { + s2 = peg$parseUTF8_CONT(); + if (s2 === peg$FAILED) { + s2 = peg$parseSP(); + if (s2 === peg$FAILED) { + s2 = peg$parseHTAB(); + } + } + } + } + } + } + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parsereserved(); + if (s2 === peg$FAILED) { + s2 = peg$parseunreserved(); + if (s2 === peg$FAILED) { + s2 = peg$parseescaped(); + if (s2 === peg$FAILED) { + s2 = peg$parseUTF8_NONASCII(); + if (s2 === peg$FAILED) { + s2 = peg$parseUTF8_CONT(); + if (s2 === peg$FAILED) { + s2 = peg$parseSP(); + if (s2 === peg$FAILED) { + s2 = peg$parseHTAB(); + } + } + } + } + } + } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c205(); + } + s0 = s1; + return s0; + } + function peg$parseAllow_Events() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parseevent_type(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseCOMMA(); + if (s4 !== peg$FAILED) { + s5 = peg$parseevent_type(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseCOMMA(); + if (s4 !== peg$FAILED) { + s5 = peg$parseevent_type(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseCall_ID() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + s1 = peg$parseword(); + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 64) { + s3 = peg$c26; + peg$currPos++; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c27); + } + } + if (s3 !== peg$FAILED) { + s4 = peg$parseword(); + if (s4 !== peg$FAILED) { + s3 = [s3, s4]; + s2 = s3; + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c206(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseContact() { + var s0, s1, s2, s3, s4, s5, s6; + s0 = peg$currPos; + s1 = peg$parseSTAR(); + if (s1 === peg$FAILED) { + s1 = peg$currPos; + s2 = peg$parsecontact_param(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$currPos; + s5 = peg$parseCOMMA(); + if (s5 !== peg$FAILED) { + s6 = peg$parsecontact_param(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$currPos; + s5 = peg$parseCOMMA(); + if (s5 !== peg$FAILED) { + s6 = peg$parsecontact_param(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + if (s3 !== peg$FAILED) { + s2 = [s2, s3]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c207(); + } + s0 = s1; + return s0; + } + function peg$parsecontact_param() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parseSIP_URI_noparams(); + if (s1 === peg$FAILED) { + s1 = peg$parsename_addr(); + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsecontact_params(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsecontact_params(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c208(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsename_addr() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + s1 = peg$parsedisplayName(); + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + s2 = peg$parseLAQUOT(); + if (s2 !== peg$FAILED) { + s3 = peg$parseSIP_URI(); + if (s3 !== peg$FAILED) { + s4 = peg$parseRAQUOT(); + if (s4 !== peg$FAILED) { + s1 = [s1, s2, s3, s4]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsedisplayName() { + var s0, s1, s2, s3, s4, s5, s6; + s0 = peg$currPos; + s1 = peg$currPos; + s2 = peg$parsetoken(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$currPos; + s5 = peg$parseLWS(); + if (s5 !== peg$FAILED) { + s6 = peg$parsetoken(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$currPos; + s5 = peg$parseLWS(); + if (s5 !== peg$FAILED) { + s6 = peg$parsetoken(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + if (s3 !== peg$FAILED) { + s2 = [s2, s3]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = peg$parsequoted_string(); + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c209(s1); + } + s0 = s1; + return s0; + } + function peg$parsecontact_params() { + var s0; + s0 = peg$parsec_p_q(); + if (s0 === peg$FAILED) { + s0 = peg$parsec_p_expires(); + if (s0 === peg$FAILED) { + s0 = peg$parsegeneric_param(); + } + } + return s0; + } + function peg$parsec_p_q() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.substr(peg$currPos, 1).toLowerCase() === peg$c210) { + s1 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c211); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parseqvalue(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c212(s3); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsec_p_expires() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.substr(peg$currPos, 7).toLowerCase() === peg$c213) { + s1 = input.substr(peg$currPos, 7); + peg$currPos += 7; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c214); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parsedelta_seconds(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c215(s3); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsedelta_seconds() { + var s0, s1, s2; + s0 = peg$currPos; + s1 = []; + s2 = peg$parseDIGIT(); + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseDIGIT(); + } + } + else { + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c216(s1); + } + s0 = s1; + return s0; + } + function peg$parseqvalue() { + var s0, s1, s2, s3, s4, s5, s6; + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 48) { + s1 = peg$c217; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c218); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s3 = peg$c42; + peg$currPos++; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c43); + } + } + if (s3 !== peg$FAILED) { + s4 = peg$parseDIGIT(); + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s5 = peg$parseDIGIT(); + if (s5 === peg$FAILED) { + s5 = null; + } + if (s5 !== peg$FAILED) { + s6 = peg$parseDIGIT(); + if (s6 === peg$FAILED) { + s6 = null; + } + if (s6 !== peg$FAILED) { + s3 = [s3, s4, s5, s6]; + s2 = s3; + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c219(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsegeneric_param() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + s1 = peg$parsetoken(); + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + s3 = peg$parseEQUAL(); + if (s3 !== peg$FAILED) { + s4 = peg$parsegen_value(); + if (s4 !== peg$FAILED) { + s3 = [s3, s4]; + s2 = s3; + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c220(s1, s2); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsegen_value() { + var s0; + s0 = peg$parsetoken(); + if (s0 === peg$FAILED) { + s0 = peg$parsehost(); + if (s0 === peg$FAILED) { + s0 = peg$parsequoted_string(); + } + } + return s0; + } + function peg$parseContent_Disposition() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parsedisp_type(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsedisp_param(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsedisp_param(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsedisp_type() { + var s0, s1; + s0 = peg$currPos; + if (input.substr(peg$currPos, 6).toLowerCase() === peg$c221) { + s1 = input.substr(peg$currPos, 6); + peg$currPos += 6; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c222); + } + } + if (s1 === peg$FAILED) { + if (input.substr(peg$currPos, 7).toLowerCase() === peg$c223) { + s1 = input.substr(peg$currPos, 7); + peg$currPos += 7; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c224); + } + } + if (s1 === peg$FAILED) { + if (input.substr(peg$currPos, 4).toLowerCase() === peg$c225) { + s1 = input.substr(peg$currPos, 4); + peg$currPos += 4; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c226); + } + } + if (s1 === peg$FAILED) { + if (input.substr(peg$currPos, 5).toLowerCase() === peg$c227) { + s1 = input.substr(peg$currPos, 5); + peg$currPos += 5; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c228); + } + } + if (s1 === peg$FAILED) { + s1 = peg$parsetoken(); + } + } + } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c229(); + } + s0 = s1; + return s0; + } + function peg$parsedisp_param() { + var s0; + s0 = peg$parsehandling_param(); + if (s0 === peg$FAILED) { + s0 = peg$parsegeneric_param(); + } + return s0; + } + function peg$parsehandling_param() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.substr(peg$currPos, 8).toLowerCase() === peg$c230) { + s1 = input.substr(peg$currPos, 8); + peg$currPos += 8; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c231); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + if (input.substr(peg$currPos, 8).toLowerCase() === peg$c232) { + s3 = input.substr(peg$currPos, 8); + peg$currPos += 8; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c233); + } + } + if (s3 === peg$FAILED) { + if (input.substr(peg$currPos, 8).toLowerCase() === peg$c234) { + s3 = input.substr(peg$currPos, 8); + peg$currPos += 8; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c235); + } + } + if (s3 === peg$FAILED) { + s3 = peg$parsetoken(); + } + } + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseContent_Encoding() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parsetoken(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseCOMMA(); + if (s4 !== peg$FAILED) { + s5 = peg$parsetoken(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseCOMMA(); + if (s4 !== peg$FAILED) { + s5 = peg$parsetoken(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseContent_Length() { + var s0, s1, s2; + s0 = peg$currPos; + s1 = []; + s2 = peg$parseDIGIT(); + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseDIGIT(); + } + } + else { + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c236(s1); + } + s0 = s1; + return s0; + } + function peg$parseContent_Type() { + var s0, s1; + s0 = peg$currPos; + s1 = peg$parsemedia_type(); + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c237(); + } + s0 = s1; + return s0; + } + function peg$parsemedia_type() { + var s0, s1, s2, s3, s4, s5, s6, s7; + s0 = peg$currPos; + s1 = peg$parsem_type(); + if (s1 !== peg$FAILED) { + s2 = peg$parseSLASH(); + if (s2 !== peg$FAILED) { + s3 = peg$parsem_subtype(); + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$currPos; + s6 = peg$parseSEMI(); + if (s6 !== peg$FAILED) { + s7 = peg$parsem_parameter(); + if (s7 !== peg$FAILED) { + s6 = [s6, s7]; + s5 = s6; + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$currPos; + s6 = peg$parseSEMI(); + if (s6 !== peg$FAILED) { + s7 = peg$parsem_parameter(); + if (s7 !== peg$FAILED) { + s6 = [s6, s7]; + s5 = s6; + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + if (s4 !== peg$FAILED) { + s1 = [s1, s2, s3, s4]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsem_type() { + var s0; + s0 = peg$parsediscrete_type(); + if (s0 === peg$FAILED) { + s0 = peg$parsecomposite_type(); + } + return s0; + } + function peg$parsediscrete_type() { + var s0; + if (input.substr(peg$currPos, 4).toLowerCase() === peg$c238) { + s0 = input.substr(peg$currPos, 4); + peg$currPos += 4; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c239); + } + } + if (s0 === peg$FAILED) { + if (input.substr(peg$currPos, 5).toLowerCase() === peg$c240) { + s0 = input.substr(peg$currPos, 5); + peg$currPos += 5; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c241); + } + } + if (s0 === peg$FAILED) { + if (input.substr(peg$currPos, 5).toLowerCase() === peg$c242) { + s0 = input.substr(peg$currPos, 5); + peg$currPos += 5; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c243); + } + } + if (s0 === peg$FAILED) { + if (input.substr(peg$currPos, 5).toLowerCase() === peg$c244) { + s0 = input.substr(peg$currPos, 5); + peg$currPos += 5; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c245); + } + } + if (s0 === peg$FAILED) { + if (input.substr(peg$currPos, 11).toLowerCase() === peg$c246) { + s0 = input.substr(peg$currPos, 11); + peg$currPos += 11; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c247); + } + } + if (s0 === peg$FAILED) { + s0 = peg$parseextension_token(); + } + } + } + } + } + return s0; + } + function peg$parsecomposite_type() { + var s0; + if (input.substr(peg$currPos, 7).toLowerCase() === peg$c248) { + s0 = input.substr(peg$currPos, 7); + peg$currPos += 7; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c249); + } + } + if (s0 === peg$FAILED) { + if (input.substr(peg$currPos, 9).toLowerCase() === peg$c250) { + s0 = input.substr(peg$currPos, 9); + peg$currPos += 9; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c251); + } + } + if (s0 === peg$FAILED) { + s0 = peg$parseextension_token(); + } + } + return s0; + } + function peg$parseextension_token() { + var s0; + s0 = peg$parsetoken(); + if (s0 === peg$FAILED) { + s0 = peg$parsex_token(); + } + return s0; + } + function peg$parsex_token() { + var s0, s1, s2; + s0 = peg$currPos; + if (input.substr(peg$currPos, 2).toLowerCase() === peg$c252) { + s1 = input.substr(peg$currPos, 2); + peg$currPos += 2; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c253); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parsetoken(); + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsem_subtype() { + var s0; + s0 = peg$parseextension_token(); + if (s0 === peg$FAILED) { + s0 = peg$parsetoken(); + } + return s0; + } + function peg$parsem_parameter() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parsetoken(); + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parsem_value(); + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsem_value() { + var s0; + s0 = peg$parsetoken(); + if (s0 === peg$FAILED) { + s0 = peg$parsequoted_string(); + } + return s0; + } + function peg$parseCSeq() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parseCSeq_value(); + if (s1 !== peg$FAILED) { + s2 = peg$parseLWS(); + if (s2 !== peg$FAILED) { + s3 = peg$parseMethod(); + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseCSeq_value() { + var s0, s1, s2; + s0 = peg$currPos; + s1 = []; + s2 = peg$parseDIGIT(); + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseDIGIT(); + } + } + else { + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c254(s1); + } + s0 = s1; + return s0; + } + function peg$parseExpires() { + var s0, s1; + s0 = peg$currPos; + s1 = peg$parsedelta_seconds(); + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c255(s1); + } + s0 = s1; + return s0; + } + function peg$parseEvent() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parseevent_type(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsegeneric_param(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsegeneric_param(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c256(s1); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseevent_type() { + var s0, s1, s2, s3, s4, s5, s6; + s0 = peg$currPos; + s1 = peg$currPos; + s2 = peg$parsetoken_nodot(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s5 = peg$c42; + peg$currPos++; + } + else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c43); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parsetoken_nodot(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s5 = peg$c42; + peg$currPos++; + } + else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c43); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parsetoken_nodot(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + if (s3 !== peg$FAILED) { + s2 = [s2, s3]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s0 = input.substring(s0, peg$currPos); + } + else { + s0 = s1; + } + return s0; + } + function peg$parseFrom() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parseSIP_URI_noparams(); + if (s1 === peg$FAILED) { + s1 = peg$parsename_addr(); + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsefrom_param(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsefrom_param(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c257(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsefrom_param() { + var s0; + s0 = peg$parsetag_param(); + if (s0 === peg$FAILED) { + s0 = peg$parsegeneric_param(); + } + return s0; + } + function peg$parsetag_param() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.substr(peg$currPos, 3).toLowerCase() === peg$c258) { + s1 = input.substr(peg$currPos, 3); + peg$currPos += 3; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c259); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parsetoken(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c260(s3); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseMax_Forwards() { + var s0, s1, s2; + s0 = peg$currPos; + s1 = []; + s2 = peg$parseDIGIT(); + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseDIGIT(); + } + } + else { + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c261(s1); + } + s0 = s1; + return s0; + } + function peg$parseMin_Expires() { + var s0, s1; + s0 = peg$currPos; + s1 = peg$parsedelta_seconds(); + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c262(s1); + } + s0 = s1; + return s0; + } + function peg$parseName_Addr_Header() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8; + s0 = peg$currPos; + s1 = []; + s2 = peg$parsedisplayName(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parsedisplayName(); + } + if (s1 !== peg$FAILED) { + s2 = peg$parseLAQUOT(); + if (s2 !== peg$FAILED) { + s3 = peg$parseSIP_URI(); + if (s3 !== peg$FAILED) { + s4 = peg$parseRAQUOT(); + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$currPos; + s7 = peg$parseSEMI(); + if (s7 !== peg$FAILED) { + s8 = peg$parsegeneric_param(); + if (s8 !== peg$FAILED) { + s7 = [s7, s8]; + s6 = s7; + } + else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } + else { + peg$currPos = s6; + s6 = peg$FAILED; + } + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$currPos; + s7 = peg$parseSEMI(); + if (s7 !== peg$FAILED) { + s8 = peg$parsegeneric_param(); + if (s8 !== peg$FAILED) { + s7 = [s7, s8]; + s6 = s7; + } + else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } + else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } + if (s5 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c263(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseProxy_Authenticate() { + var s0; + s0 = peg$parsechallenge(); + return s0; + } + function peg$parsechallenge() { + var s0, s1, s2, s3, s4, s5, s6, s7; + s0 = peg$currPos; + if (input.substr(peg$currPos, 6).toLowerCase() === peg$c264) { + s1 = input.substr(peg$currPos, 6); + peg$currPos += 6; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c265); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseLWS(); + if (s2 !== peg$FAILED) { + s3 = peg$parsedigest_cln(); + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$currPos; + s6 = peg$parseCOMMA(); + if (s6 !== peg$FAILED) { + s7 = peg$parsedigest_cln(); + if (s7 !== peg$FAILED) { + s6 = [s6, s7]; + s5 = s6; + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$currPos; + s6 = peg$parseCOMMA(); + if (s6 !== peg$FAILED) { + s7 = peg$parsedigest_cln(); + if (s7 !== peg$FAILED) { + s6 = [s6, s7]; + s5 = s6; + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + if (s4 !== peg$FAILED) { + s1 = [s1, s2, s3, s4]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$parseother_challenge(); + } + return s0; + } + function peg$parseother_challenge() { + var s0, s1, s2, s3, s4, s5, s6, s7; + s0 = peg$currPos; + s1 = peg$parsetoken(); + if (s1 !== peg$FAILED) { + s2 = peg$parseLWS(); + if (s2 !== peg$FAILED) { + s3 = peg$parseauth_param(); + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$currPos; + s6 = peg$parseCOMMA(); + if (s6 !== peg$FAILED) { + s7 = peg$parseauth_param(); + if (s7 !== peg$FAILED) { + s6 = [s6, s7]; + s5 = s6; + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$currPos; + s6 = peg$parseCOMMA(); + if (s6 !== peg$FAILED) { + s7 = peg$parseauth_param(); + if (s7 !== peg$FAILED) { + s6 = [s6, s7]; + s5 = s6; + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + if (s4 !== peg$FAILED) { + s1 = [s1, s2, s3, s4]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseauth_param() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parsetoken(); + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parsetoken(); + if (s3 === peg$FAILED) { + s3 = peg$parsequoted_string(); + } + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsedigest_cln() { + var s0; + s0 = peg$parserealm(); + if (s0 === peg$FAILED) { + s0 = peg$parsedomain(); + if (s0 === peg$FAILED) { + s0 = peg$parsenonce(); + if (s0 === peg$FAILED) { + s0 = peg$parseopaque(); + if (s0 === peg$FAILED) { + s0 = peg$parsestale(); + if (s0 === peg$FAILED) { + s0 = peg$parsealgorithm(); + if (s0 === peg$FAILED) { + s0 = peg$parseqop_options(); + if (s0 === peg$FAILED) { + s0 = peg$parseauth_param(); + } + } + } + } + } + } + } + return s0; + } + function peg$parserealm() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.substr(peg$currPos, 5).toLowerCase() === peg$c266) { + s1 = input.substr(peg$currPos, 5); + peg$currPos += 5; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c267); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parserealm_value(); + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parserealm_value() { + var s0, s1; + s0 = peg$currPos; + s1 = peg$parsequoted_string_clean(); + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c268(s1); + } + s0 = s1; + return s0; + } + function peg$parsedomain() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8; + s0 = peg$currPos; + if (input.substr(peg$currPos, 6).toLowerCase() === peg$c269) { + s1 = input.substr(peg$currPos, 6); + peg$currPos += 6; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c270); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parseLDQUOT(); + if (s3 !== peg$FAILED) { + s4 = peg$parseURI(); + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$currPos; + s7 = []; + s8 = peg$parseSP(); + if (s8 !== peg$FAILED) { + while (s8 !== peg$FAILED) { + s7.push(s8); + s8 = peg$parseSP(); + } + } + else { + s7 = peg$FAILED; + } + if (s7 !== peg$FAILED) { + s8 = peg$parseURI(); + if (s8 !== peg$FAILED) { + s7 = [s7, s8]; + s6 = s7; + } + else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } + else { + peg$currPos = s6; + s6 = peg$FAILED; + } + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$currPos; + s7 = []; + s8 = peg$parseSP(); + if (s8 !== peg$FAILED) { + while (s8 !== peg$FAILED) { + s7.push(s8); + s8 = peg$parseSP(); + } + } + else { + s7 = peg$FAILED; + } + if (s7 !== peg$FAILED) { + s8 = peg$parseURI(); + if (s8 !== peg$FAILED) { + s7 = [s7, s8]; + s6 = s7; + } + else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } + else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parseRDQUOT(); + if (s6 !== peg$FAILED) { + s1 = [s1, s2, s3, s4, s5, s6]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseURI() { + var s0; + s0 = peg$parseabsoluteURI(); + if (s0 === peg$FAILED) { + s0 = peg$parseabs_path(); + } + return s0; + } + function peg$parsenonce() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.substr(peg$currPos, 5).toLowerCase() === peg$c271) { + s1 = input.substr(peg$currPos, 5); + peg$currPos += 5; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c272); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parsenonce_value(); + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsenonce_value() { + var s0, s1; + s0 = peg$currPos; + s1 = peg$parsequoted_string_clean(); + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c273(s1); + } + s0 = s1; + return s0; + } + function peg$parseopaque() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.substr(peg$currPos, 6).toLowerCase() === peg$c274) { + s1 = input.substr(peg$currPos, 6); + peg$currPos += 6; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c275); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parsequoted_string_clean(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c276(s3); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsestale() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + if (input.substr(peg$currPos, 5).toLowerCase() === peg$c277) { + s1 = input.substr(peg$currPos, 5); + peg$currPos += 5; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c278); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$currPos; + if (input.substr(peg$currPos, 4).toLowerCase() === peg$c279) { + s4 = input.substr(peg$currPos, 4); + peg$currPos += 4; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c280); + } + } + if (s4 !== peg$FAILED) { + peg$savedPos = s3; + s4 = peg$c281(); + } + s3 = s4; + if (s3 === peg$FAILED) { + s3 = peg$currPos; + if (input.substr(peg$currPos, 5).toLowerCase() === peg$c282) { + s4 = input.substr(peg$currPos, 5); + peg$currPos += 5; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c283); + } + } + if (s4 !== peg$FAILED) { + peg$savedPos = s3; + s4 = peg$c284(); + } + s3 = s4; + } + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsealgorithm() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.substr(peg$currPos, 9).toLowerCase() === peg$c285) { + s1 = input.substr(peg$currPos, 9); + peg$currPos += 9; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c286); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + if (input.substr(peg$currPos, 3).toLowerCase() === peg$c287) { + s3 = input.substr(peg$currPos, 3); + peg$currPos += 3; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c288); + } + } + if (s3 === peg$FAILED) { + if (input.substr(peg$currPos, 8).toLowerCase() === peg$c289) { + s3 = input.substr(peg$currPos, 8); + peg$currPos += 8; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c290); + } + } + if (s3 === peg$FAILED) { + s3 = peg$parsetoken(); + } + } + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c291(s3); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseqop_options() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9; + s0 = peg$currPos; + if (input.substr(peg$currPos, 3).toLowerCase() === peg$c292) { + s1 = input.substr(peg$currPos, 3); + peg$currPos += 3; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c293); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parseLDQUOT(); + if (s3 !== peg$FAILED) { + s4 = peg$currPos; + s5 = peg$parseqop_value(); + if (s5 !== peg$FAILED) { + s6 = []; + s7 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 44) { + s8 = peg$c36; + peg$currPos++; + } + else { + s8 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c37); + } + } + if (s8 !== peg$FAILED) { + s9 = peg$parseqop_value(); + if (s9 !== peg$FAILED) { + s8 = [s8, s9]; + s7 = s8; + } + else { + peg$currPos = s7; + s7 = peg$FAILED; + } + } + else { + peg$currPos = s7; + s7 = peg$FAILED; + } + while (s7 !== peg$FAILED) { + s6.push(s7); + s7 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 44) { + s8 = peg$c36; + peg$currPos++; + } + else { + s8 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c37); + } + } + if (s8 !== peg$FAILED) { + s9 = peg$parseqop_value(); + if (s9 !== peg$FAILED) { + s8 = [s8, s9]; + s7 = s8; + } + else { + peg$currPos = s7; + s7 = peg$FAILED; + } + } + else { + peg$currPos = s7; + s7 = peg$FAILED; + } + } + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + if (s4 !== peg$FAILED) { + s5 = peg$parseRDQUOT(); + if (s5 !== peg$FAILED) { + s1 = [s1, s2, s3, s4, s5]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseqop_value() { + var s0, s1; + s0 = peg$currPos; + if (input.substr(peg$currPos, 8).toLowerCase() === peg$c294) { + s1 = input.substr(peg$currPos, 8); + peg$currPos += 8; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c295); + } + } + if (s1 === peg$FAILED) { + if (input.substr(peg$currPos, 4).toLowerCase() === peg$c296) { + s1 = input.substr(peg$currPos, 4); + peg$currPos += 4; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c297); + } + } + if (s1 === peg$FAILED) { + s1 = peg$parsetoken(); + } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c298(s1); + } + s0 = s1; + return s0; + } + function peg$parseProxy_Require() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parsetoken(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseCOMMA(); + if (s4 !== peg$FAILED) { + s5 = peg$parsetoken(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseCOMMA(); + if (s4 !== peg$FAILED) { + s5 = peg$parsetoken(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseRAck() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parseRAck_value(); + if (s1 !== peg$FAILED) { + s2 = peg$parseLWS(); + if (s2 !== peg$FAILED) { + s3 = peg$parseRAck_value(); + if (s3 !== peg$FAILED) { + s4 = peg$parseLWS(); + if (s4 !== peg$FAILED) { + s5 = peg$parseMethod(); + if (s5 !== peg$FAILED) { + s1 = [s1, s2, s3, s4, s5]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseRAck_value() { + var s0, s1, s2; + s0 = peg$currPos; + s1 = []; + s2 = peg$parseDIGIT(); + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseDIGIT(); + } + } + else { + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c299(s1); + } + s0 = s1; + return s0; + } + function peg$parseRecord_Route() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parserec_route(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseCOMMA(); + if (s4 !== peg$FAILED) { + s5 = peg$parserec_route(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseCOMMA(); + if (s4 !== peg$FAILED) { + s5 = peg$parserec_route(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c300(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parserec_route() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parsename_addr(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsegeneric_param(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsegeneric_param(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c301(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseRefer_To() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parseSIP_URI_noparams(); + if (s1 === peg$FAILED) { + s1 = peg$parsename_addr(); + if (s1 === peg$FAILED) { + s1 = peg$currPos; + s2 = peg$parseLAQUOT(); + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + s3 = peg$parseabsoluteURI(); + if (s3 !== peg$FAILED) { + s4 = peg$parseRAQUOT(); + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s2 = [s2, s3, s4]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsegeneric_param(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsegeneric_param(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c302(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseReplaces() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parsereplaces_call_id(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsereplaces_params(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsereplaces_params(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c303(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsereplaces_call_id() { + var s0, s1; + s0 = peg$currPos; + s1 = peg$parseCall_ID(); + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c304(); + } + s0 = s1; + return s0; + } + function peg$parsereplaces_params() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.substr(peg$currPos, 8).toLowerCase() === peg$c305) { + s1 = input.substr(peg$currPos, 8); + peg$currPos += 8; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c306); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parsetoken(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c307(s3); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 6).toLowerCase() === peg$c308) { + s1 = input.substr(peg$currPos, 6); + peg$currPos += 6; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c309); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parsetoken(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c310(s3); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 10).toLowerCase() === peg$c311) { + s1 = input.substr(peg$currPos, 10); + peg$currPos += 10; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c312); + } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c313(); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$parsegeneric_param(); + } + } + } + return s0; + } + function peg$parseRequire() { + var s0, s1, s2, s3, s4, s5, s6; + s0 = peg$currPos; + s1 = peg$currPos; + s2 = peg$parsetoken(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$currPos; + s5 = peg$parseCOMMA(); + if (s5 !== peg$FAILED) { + s6 = peg$parsetoken(); + if (s6 !== peg$FAILED) { + peg$savedPos = s4; + s5 = peg$c314(s2, s6); + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$currPos; + s5 = peg$parseCOMMA(); + if (s5 !== peg$FAILED) { + s6 = peg$parsetoken(); + if (s6 !== peg$FAILED) { + peg$savedPos = s4; + s5 = peg$c314(s2, s6); + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + if (s3 !== peg$FAILED) { + peg$savedPos = s1; + s2 = peg$c315(s2, s3); + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c316(s1); + } + s0 = s1; + return s0; + } + function peg$parseRoute() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parseroute_param(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseCOMMA(); + if (s4 !== peg$FAILED) { + s5 = peg$parseroute_param(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseCOMMA(); + if (s4 !== peg$FAILED) { + s5 = peg$parseroute_param(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseroute_param() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parsename_addr(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsegeneric_param(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsegeneric_param(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseRSeq() { + var s0, s1, s2; + s0 = peg$currPos; + s1 = []; + s2 = peg$parseDIGIT(); + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseDIGIT(); + } + } + else { + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c317(s1); + } + s0 = s1; + return s0; + } + function peg$parseSubscription_State() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parsesubstate_value(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsesubexp_params(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsesubexp_params(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsesubstate_value() { + var s0, s1; + s0 = peg$currPos; + if (input.substr(peg$currPos, 6).toLowerCase() === peg$c318) { + s1 = input.substr(peg$currPos, 6); + peg$currPos += 6; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c319); + } + } + if (s1 === peg$FAILED) { + if (input.substr(peg$currPos, 7).toLowerCase() === peg$c320) { + s1 = input.substr(peg$currPos, 7); + peg$currPos += 7; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c321); + } + } + if (s1 === peg$FAILED) { + if (input.substr(peg$currPos, 10).toLowerCase() === peg$c322) { + s1 = input.substr(peg$currPos, 10); + peg$currPos += 10; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c323); + } + } + if (s1 === peg$FAILED) { + s1 = peg$parsetoken(); + } + } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c324(); + } + s0 = s1; + return s0; + } + function peg$parsesubexp_params() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.substr(peg$currPos, 6).toLowerCase() === peg$c325) { + s1 = input.substr(peg$currPos, 6); + peg$currPos += 6; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c326); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parseevent_reason_value(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c327(s3); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 7).toLowerCase() === peg$c213) { + s1 = input.substr(peg$currPos, 7); + peg$currPos += 7; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c214); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parsedelta_seconds(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c328(s3); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 11).toLowerCase() === peg$c329) { + s1 = input.substr(peg$currPos, 11); + peg$currPos += 11; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c330); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parsedelta_seconds(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c331(s3); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$parsegeneric_param(); + } + } + } + return s0; + } + function peg$parseevent_reason_value() { + var s0; + if (input.substr(peg$currPos, 11).toLowerCase() === peg$c332) { + s0 = input.substr(peg$currPos, 11); + peg$currPos += 11; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c333); + } + } + if (s0 === peg$FAILED) { + if (input.substr(peg$currPos, 9).toLowerCase() === peg$c334) { + s0 = input.substr(peg$currPos, 9); + peg$currPos += 9; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c335); + } + } + if (s0 === peg$FAILED) { + if (input.substr(peg$currPos, 8).toLowerCase() === peg$c336) { + s0 = input.substr(peg$currPos, 8); + peg$currPos += 8; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c337); + } + } + if (s0 === peg$FAILED) { + if (input.substr(peg$currPos, 7).toLowerCase() === peg$c338) { + s0 = input.substr(peg$currPos, 7); + peg$currPos += 7; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c339); + } + } + if (s0 === peg$FAILED) { + if (input.substr(peg$currPos, 6).toLowerCase() === peg$c340) { + s0 = input.substr(peg$currPos, 6); + peg$currPos += 6; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c341); + } + } + if (s0 === peg$FAILED) { + if (input.substr(peg$currPos, 10).toLowerCase() === peg$c342) { + s0 = input.substr(peg$currPos, 10); + peg$currPos += 10; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c343); + } + } + if (s0 === peg$FAILED) { + if (input.substr(peg$currPos, 9).toLowerCase() === peg$c344) { + s0 = input.substr(peg$currPos, 9); + peg$currPos += 9; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c345); + } + } + if (s0 === peg$FAILED) { + s0 = peg$parsetoken(); + } + } + } + } + } + } + } + return s0; + } + function peg$parseSubject() { + var s0; + s0 = peg$parseTEXT_UTF8_TRIM(); + if (s0 === peg$FAILED) { + s0 = null; + } + return s0; + } + function peg$parseSupported() { + var s0, s1, s2, s3, s4, s5, s6; + s0 = peg$currPos; + s1 = peg$currPos; + s2 = peg$parsetoken(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$currPos; + s5 = peg$parseCOMMA(); + if (s5 !== peg$FAILED) { + s6 = peg$parsetoken(); + if (s6 !== peg$FAILED) { + peg$savedPos = s4; + s5 = peg$c314(s2, s6); + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$currPos; + s5 = peg$parseCOMMA(); + if (s5 !== peg$FAILED) { + s6 = peg$parsetoken(); + if (s6 !== peg$FAILED) { + peg$savedPos = s4; + s5 = peg$c314(s2, s6); + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + if (s3 !== peg$FAILED) { + peg$savedPos = s1; + s2 = peg$c315(s2, s3); + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c346(s1); + } + s0 = s1; + return s0; + } + function peg$parseTo() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parseSIP_URI_noparams(); + if (s1 === peg$FAILED) { + s1 = peg$parsename_addr(); + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parseto_param(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parseto_param(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c347(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseto_param() { + var s0; + s0 = peg$parsetag_param(); + if (s0 === peg$FAILED) { + s0 = peg$parsegeneric_param(); + } + return s0; + } + function peg$parseVia() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parsevia_parm(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseCOMMA(); + if (s4 !== peg$FAILED) { + s5 = peg$parsevia_parm(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseCOMMA(); + if (s4 !== peg$FAILED) { + s5 = peg$parsevia_parm(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsevia_parm() { + var s0, s1, s2, s3, s4, s5, s6, s7; + s0 = peg$currPos; + s1 = peg$parsesent_protocol(); + if (s1 !== peg$FAILED) { + s2 = peg$parseLWS(); + if (s2 !== peg$FAILED) { + s3 = peg$parsesent_by(); + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$currPos; + s6 = peg$parseSEMI(); + if (s6 !== peg$FAILED) { + s7 = peg$parsevia_params(); + if (s7 !== peg$FAILED) { + s6 = [s6, s7]; + s5 = s6; + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$currPos; + s6 = peg$parseSEMI(); + if (s6 !== peg$FAILED) { + s7 = peg$parsevia_params(); + if (s7 !== peg$FAILED) { + s6 = [s6, s7]; + s5 = s6; + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + if (s4 !== peg$FAILED) { + s1 = [s1, s2, s3, s4]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsevia_params() { + var s0; + s0 = peg$parsevia_ttl(); + if (s0 === peg$FAILED) { + s0 = peg$parsevia_maddr(); + if (s0 === peg$FAILED) { + s0 = peg$parsevia_received(); + if (s0 === peg$FAILED) { + s0 = peg$parsevia_branch(); + if (s0 === peg$FAILED) { + s0 = peg$parseresponse_port(); + if (s0 === peg$FAILED) { + s0 = peg$parsegeneric_param(); + } + } + } + } + } + return s0; + } + function peg$parsevia_ttl() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.substr(peg$currPos, 3).toLowerCase() === peg$c348) { + s1 = input.substr(peg$currPos, 3); + peg$currPos += 3; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c349); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parsettl(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c350(s3); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsevia_maddr() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.substr(peg$currPos, 5).toLowerCase() === peg$c351) { + s1 = input.substr(peg$currPos, 5); + peg$currPos += 5; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c352); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parsehost(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c353(s3); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsevia_received() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.substr(peg$currPos, 8).toLowerCase() === peg$c354) { + s1 = input.substr(peg$currPos, 8); + peg$currPos += 8; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c355); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parseIPv4address(); + if (s3 === peg$FAILED) { + s3 = peg$parseIPv6address(); + if (s3 === peg$FAILED) { + s3 = peg$parseIPv6reference(); + } + } + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c356(s3); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsevia_branch() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.substr(peg$currPos, 6).toLowerCase() === peg$c357) { + s1 = input.substr(peg$currPos, 6); + peg$currPos += 6; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c358); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parsetoken(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c359(s3); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseresponse_port() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + if (input.substr(peg$currPos, 5).toLowerCase() === peg$c360) { + s1 = input.substr(peg$currPos, 5); + peg$currPos += 5; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c361); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseDIGIT(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseDIGIT(); + } + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c362(s3); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsesent_protocol() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parseprotocol_name(); + if (s1 !== peg$FAILED) { + s2 = peg$parseSLASH(); + if (s2 !== peg$FAILED) { + s3 = peg$parsetoken(); + if (s3 !== peg$FAILED) { + s4 = peg$parseSLASH(); + if (s4 !== peg$FAILED) { + s5 = peg$parsetransport(); + if (s5 !== peg$FAILED) { + s1 = [s1, s2, s3, s4, s5]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseprotocol_name() { + var s0, s1; + s0 = peg$currPos; + if (input.substr(peg$currPos, 3).toLowerCase() === peg$c114) { + s1 = input.substr(peg$currPos, 3); + peg$currPos += 3; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c179); + } + } + if (s1 === peg$FAILED) { + s1 = peg$parsetoken(); + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c363(s1); + } + s0 = s1; + return s0; + } + function peg$parsetransport() { + var s0, s1; + s0 = peg$currPos; + if (input.substr(peg$currPos, 3).toLowerCase() === peg$c145) { + s1 = input.substr(peg$currPos, 3); + peg$currPos += 3; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c364); + } + } + if (s1 === peg$FAILED) { + if (input.substr(peg$currPos, 3).toLowerCase() === peg$c147) { + s1 = input.substr(peg$currPos, 3); + peg$currPos += 3; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c365); + } + } + if (s1 === peg$FAILED) { + if (input.substr(peg$currPos, 3).toLowerCase() === peg$c151) { + s1 = input.substr(peg$currPos, 3); + peg$currPos += 3; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c366); + } + } + if (s1 === peg$FAILED) { + if (input.substr(peg$currPos, 4).toLowerCase() === peg$c149) { + s1 = input.substr(peg$currPos, 4); + peg$currPos += 4; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c367); + } + } + if (s1 === peg$FAILED) { + s1 = peg$parsetoken(); + } + } + } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c368(s1); + } + s0 = s1; + return s0; + } + function peg$parsesent_by() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + s1 = peg$parseviaHost(); + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + s3 = peg$parseCOLON(); + if (s3 !== peg$FAILED) { + s4 = peg$parsevia_port(); + if (s4 !== peg$FAILED) { + s3 = [s3, s4]; + s2 = s3; + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseviaHost() { + var s0, s1; + s0 = peg$currPos; + s1 = peg$parsehostname(); + if (s1 === peg$FAILED) { + s1 = peg$parseIPv4address(); + if (s1 === peg$FAILED) { + s1 = peg$parseIPv6reference(); + } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c369(); + } + s0 = s1; + return s0; + } + function peg$parsevia_port() { + var s0, s1, s2, s3, s4, s5, s6; + s0 = peg$currPos; + s1 = peg$currPos; + s2 = peg$parseDIGIT(); + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + s3 = peg$parseDIGIT(); + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + s4 = peg$parseDIGIT(); + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s5 = peg$parseDIGIT(); + if (s5 === peg$FAILED) { + s5 = null; + } + if (s5 !== peg$FAILED) { + s6 = peg$parseDIGIT(); + if (s6 === peg$FAILED) { + s6 = null; + } + if (s6 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c370(s1); + } + s0 = s1; + return s0; + } + function peg$parsettl() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + s1 = peg$currPos; + s2 = peg$parseDIGIT(); + if (s2 !== peg$FAILED) { + s3 = peg$parseDIGIT(); + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + s4 = peg$parseDIGIT(); + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s2 = [s2, s3, s4]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c371(s1); + } + s0 = s1; + return s0; + } + function peg$parseWWW_Authenticate() { + var s0; + s0 = peg$parsechallenge(); + return s0; + } + function peg$parseSession_Expires() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parsedelta_seconds(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsese_params(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsese_params(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c372(s1); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsese_params() { + var s0; + s0 = peg$parserefresher_param(); + if (s0 === peg$FAILED) { + s0 = peg$parsegeneric_param(); + } + return s0; + } + function peg$parserefresher_param() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.substr(peg$currPos, 9) === peg$c373) { + s1 = peg$c373; + peg$currPos += 9; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c374); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + if (input.substr(peg$currPos, 3) === peg$c375) { + s3 = peg$c375; + peg$currPos += 3; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c376); + } + } + if (s3 === peg$FAILED) { + if (input.substr(peg$currPos, 3) === peg$c377) { + s3 = peg$c377; + peg$currPos += 3; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c378); + } + } + } + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c379(s3); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseMin_SE() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parsedelta_seconds(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsegeneric_param(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsegeneric_param(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c380(s1); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseextension_header() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parsetoken(); + if (s1 !== peg$FAILED) { + s2 = peg$parseHCOLON(); + if (s2 !== peg$FAILED) { + s3 = peg$parseheader_value(); + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseheader_value() { + var s0, s1; + s0 = []; + s1 = peg$parseTEXT_UTF8char(); + if (s1 === peg$FAILED) { + s1 = peg$parseUTF8_CONT(); + if (s1 === peg$FAILED) { + s1 = peg$parseLWS(); + } + } + while (s1 !== peg$FAILED) { + s0.push(s1); + s1 = peg$parseTEXT_UTF8char(); + if (s1 === peg$FAILED) { + s1 = peg$parseUTF8_CONT(); + if (s1 === peg$FAILED) { + s1 = peg$parseLWS(); + } + } + } + return s0; + } + function peg$parsemessage_body() { + var s0, s1; + s0 = []; + s1 = peg$parseOCTET(); + while (s1 !== peg$FAILED) { + s0.push(s1); + s1 = peg$parseOCTET(); + } + return s0; + } + function peg$parsestun_URI() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parsestun_scheme(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s2 = peg$c24; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parsestun_host_port(); + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsestun_scheme() { + var s0, s1; + s0 = peg$currPos; + if (input.substr(peg$currPos, 5).toLowerCase() === peg$c381) { + s1 = input.substr(peg$currPos, 5); + peg$currPos += 5; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c382); + } + } + if (s1 === peg$FAILED) { + if (input.substr(peg$currPos, 4).toLowerCase() === peg$c383) { + s1 = input.substr(peg$currPos, 4); + peg$currPos += 4; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c384); + } + } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c385(s1); + } + s0 = s1; + return s0; + } + function peg$parsestun_host_port() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + s1 = peg$parsestun_host(); + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s3 = peg$c24; + peg$currPos++; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s3 !== peg$FAILED) { + s4 = peg$parseport(); + if (s4 !== peg$FAILED) { + s3 = [s3, s4]; + s2 = s3; + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsestun_host() { + var s0, s1; + s0 = peg$currPos; + s1 = peg$parseIPv4address(); + if (s1 === peg$FAILED) { + s1 = peg$parseIPv6reference(); + if (s1 === peg$FAILED) { + s1 = peg$parsereg_name(); + } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c386(s1); + } + s0 = s1; + return s0; + } + function peg$parsestun_unreserved() { + var s0; + s0 = peg$parseALPHA(); + if (s0 === peg$FAILED) { + s0 = peg$parseDIGIT(); + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s0 = peg$c38; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c39); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s0 = peg$c42; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c43); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 95) { + s0 = peg$c40; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c41); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 126) { + s0 = peg$c46; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c47); + } + } + } + } + } + } + } + return s0; + } + function peg$parsesub_delims() { + var s0; + if (input.charCodeAt(peg$currPos) === 33) { + s0 = peg$c44; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c45); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 36) { + s0 = peg$c34; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c35); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 38) { + s0 = peg$c28; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c29); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 39) { + s0 = peg$c50; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c51); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 40) { + s0 = peg$c52; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c53); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s0 = peg$c54; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c55); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 42) { + s0 = peg$c48; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c49); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s0 = peg$c32; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s0 = peg$c36; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c37); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 59) { + s0 = peg$c18; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c19); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s0 = peg$c30; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c31); + } + } + } + } + } + } + } + } + } + } + } + } + return s0; + } + function peg$parseturn_URI() { + var s0, s1, s2, s3, s4, s5, s6; + s0 = peg$currPos; + s1 = peg$parseturn_scheme(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s2 = peg$c24; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parsestun_host_port(); + if (s3 !== peg$FAILED) { + s4 = peg$currPos; + if (input.substr(peg$currPos, 11) === peg$c387) { + s5 = peg$c387; + peg$currPos += 11; + } + else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c388); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parsetransport(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s1 = [s1, s2, s3, s4]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseturn_scheme() { + var s0, s1; + s0 = peg$currPos; + if (input.substr(peg$currPos, 5).toLowerCase() === peg$c389) { + s1 = input.substr(peg$currPos, 5); + peg$currPos += 5; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c390); + } + } + if (s1 === peg$FAILED) { + if (input.substr(peg$currPos, 4).toLowerCase() === peg$c391) { + s1 = input.substr(peg$currPos, 4); + peg$currPos += 4; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c392); + } + } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c385(s1); + } + s0 = s1; + return s0; + } + function peg$parseturn_transport() { + var s0, s1, s2; + s0 = peg$currPos; + if (input.substr(peg$currPos, 3).toLowerCase() === peg$c145) { + s1 = input.substr(peg$currPos, 3); + peg$currPos += 3; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c146); + } + } + if (s1 === peg$FAILED) { + if (input.substr(peg$currPos, 3).toLowerCase() === peg$c147) { + s1 = input.substr(peg$currPos, 3); + peg$currPos += 3; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c148); + } + } + if (s1 === peg$FAILED) { + s1 = []; + s2 = peg$parseunreserved(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseunreserved(); + } + } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c393(s1); + } + s0 = s1; + return s0; + } + function peg$parseuuid() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9; + s0 = peg$currPos; + s1 = peg$parsehex8(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s2 = peg$c38; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c39); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parsehex4(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s4 = peg$c38; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c39); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parsehex4(); + if (s5 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s6 = peg$c38; + peg$currPos++; + } + else { + s6 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c39); + } + } + if (s6 !== peg$FAILED) { + s7 = peg$parsehex4(); + if (s7 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s8 = peg$c38; + peg$currPos++; + } + else { + s8 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c39); + } + } + if (s8 !== peg$FAILED) { + s9 = peg$parsehex12(); + if (s9 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c394(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsehex4() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + s1 = peg$parseHEXDIG(); + if (s1 !== peg$FAILED) { + s2 = peg$parseHEXDIG(); + if (s2 !== peg$FAILED) { + s3 = peg$parseHEXDIG(); + if (s3 !== peg$FAILED) { + s4 = peg$parseHEXDIG(); + if (s4 !== peg$FAILED) { + s1 = [s1, s2, s3, s4]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsehex8() { + var s0, s1, s2; + s0 = peg$currPos; + s1 = peg$parsehex4(); + if (s1 !== peg$FAILED) { + s2 = peg$parsehex4(); + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsehex12() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parsehex4(); + if (s1 !== peg$FAILED) { + s2 = peg$parsehex4(); + if (s2 !== peg$FAILED) { + s3 = peg$parsehex4(); + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsesipfrag() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parseRequest_Response(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseheader(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseheader(); + } + if (s2 !== peg$FAILED) { + s3 = peg$currPos; + s4 = peg$parseCRLF(); + if (s4 !== peg$FAILED) { + s5 = peg$parsemessage_body(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseReferred_By() { + var s0, s1, s2, s3, s4, s5, s6, s7; + s0 = peg$currPos; + if (input.substr(peg$currPos, 11) === peg$c395) { + s1 = peg$c395; + peg$currPos += 11; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c396); + } + } + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 98) { + s1 = peg$c397; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c398); + } + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseHCOLON(); + if (s2 !== peg$FAILED) { + s3 = peg$parsereferrer_uri(); + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$currPos; + s6 = peg$parseSEMI(); + if (s6 !== peg$FAILED) { + s7 = peg$parsereferredby_id_param(); + if (s7 === peg$FAILED) { + s7 = peg$parsegeneric_param(); + } + if (s7 !== peg$FAILED) { + s6 = [s6, s7]; + s5 = s6; + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$currPos; + s6 = peg$parseSEMI(); + if (s6 !== peg$FAILED) { + s7 = peg$parsereferredby_id_param(); + if (s7 === peg$FAILED) { + s7 = peg$parsegeneric_param(); + } + if (s7 !== peg$FAILED) { + s6 = [s6, s7]; + s5 = s6; + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + if (s4 !== peg$FAILED) { + s1 = [s1, s2, s3, s4]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsereferrer_uri() { + var s0; + s0 = peg$parsename_addr(); + if (s0 === peg$FAILED) { + s0 = peg$parseSIP_URI_noparams(); + } + return s0; + } + function peg$parsereferredby_id_param() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.substr(peg$currPos, 3) === peg$c399) { + s1 = peg$c399; + peg$currPos += 3; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c400); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parsesip_clean_msg_id(); + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsesip_clean_msg_id() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parseLDQUOT(); + if (s1 !== peg$FAILED) { + s2 = peg$parsemark(); + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 64) { + s3 = peg$c26; + peg$currPos++; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c27); + } + } + if (s3 !== peg$FAILED) { + s4 = peg$parsemark(); + if (s4 === peg$FAILED) { + s4 = peg$parsehost(); + } + if (s4 !== peg$FAILED) { + s5 = peg$parseRDQUOT(); + if (s5 !== peg$FAILED) { + s1 = [s1, s2, s3, s4, s5]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + options.data = {}; // Object to which header attributes will be assigned during parsing + function list(head, tail) { + return [head].concat(tail); + } + peg$result = peg$startRuleFunction(); + if (peg$result !== peg$FAILED && peg$currPos === input.length) { + return peg$result; + } + else { + if (peg$result !== peg$FAILED && peg$currPos < input.length) { + peg$fail(peg$endExpectation()); + } + throw peg$buildStructuredError(peg$maxFailExpected, peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null, peg$maxFailPos < input.length + ? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1) + : peg$computeLocation(peg$maxFailPos, peg$maxFailPos)); + } +} +exports.parse = peg$parse; + + +/***/ }), +/* 9 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Enums_1 = __webpack_require__(5); +var URI_1 = __webpack_require__(10); +/** + * @class Class creating a Name Address SIP header. + * + * @param {SIP.URI} uri + * @param {String} [displayName] + * @param {Object} [parameters] + * + */ +var NameAddrHeader = /** @class */ (function (_super) { + __extends(NameAddrHeader, _super); + function NameAddrHeader(uri, displayName, parameters) { + var _this = _super.call(this, parameters) || this; + _this.type = Enums_1.TypeStrings.NameAddrHeader; + // Checks + if (!uri || !(uri.type === Enums_1.TypeStrings.URI)) { + throw new TypeError('missing or invalid "uri" parameter'); + } + _this.uri = uri; + _this._displayName = displayName; + return _this; + } + Object.defineProperty(NameAddrHeader.prototype, "friendlyName", { + get: function () { + return this.displayName || this.uri.aor; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(NameAddrHeader.prototype, "displayName", { + get: function () { return this._displayName; }, + set: function (value) { + this._displayName = value; + }, + enumerable: true, + configurable: true + }); + NameAddrHeader.prototype.clone = function () { + return new NameAddrHeader(this.uri.clone(), this._displayName, JSON.parse(JSON.stringify(this.parameters))); + }; + NameAddrHeader.prototype.toString = function () { + var body = (this.displayName || this.displayName === "0") ? '"' + this.displayName + '" ' : ""; + body += "<" + this.uri.toString() + ">"; + for (var parameter in this.parameters) { + if (this.parameters.hasOwnProperty(parameter)) { + body += ";" + parameter; + if (this.parameters[parameter] !== null) { + body += "=" + this.parameters[parameter]; + } + } + } + return body; + }; + return NameAddrHeader; +}(URI_1.Parameters)); +exports.NameAddrHeader = NameAddrHeader; + + +/***/ }), +/* 10 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Constants_1 = __webpack_require__(3); +var Enums_1 = __webpack_require__(5); +var Parameters = /** @class */ (function () { + function Parameters(parameters) { + this.parameters = {}; + this.type = Enums_1.TypeStrings.Parameters; + for (var param in parameters) { + if (parameters.hasOwnProperty(param)) { + this.setParam(param, parameters[param]); + } + } + } + Parameters.prototype.setParam = function (key, value) { + if (key) { + this.parameters[key.toLowerCase()] = (typeof value === "undefined" || value === null) ? null : value.toString(); + } + }; + Parameters.prototype.getParam = function (key) { + if (key) { + return this.parameters[key.toLowerCase()]; + } + }; + Parameters.prototype.hasParam = function (key) { + if (key) { + return !!this.parameters.hasOwnProperty(key.toLowerCase()); + } + return false; + }; + Parameters.prototype.deleteParam = function (parameter) { + parameter = parameter.toLowerCase(); + if (this.parameters.hasOwnProperty(parameter)) { + var value = this.parameters[parameter]; + delete this.parameters[parameter]; + return value; + } + }; + Parameters.prototype.clearParams = function () { + this.parameters = {}; + }; + return Parameters; +}()); +exports.Parameters = Parameters; +/** + * @class Class creating a SIP URI. + * + * @param {String} [scheme] + * @param {String} [user] + * @param {String} host + * @param {String} [port] + * @param {Object} [parameters] + * @param {Object} [headers] + * + */ +// tslint:disable-next-line:max-classes-per-file +var URI = /** @class */ (function (_super) { + __extends(URI, _super); + function URI(scheme, user, host, port, parameters, headers) { + var _this = _super.call(this, parameters) || this; + _this.headers = {}; + _this.type = Enums_1.TypeStrings.URI; + // Checks + if (!host) { + throw new TypeError('missing or invalid "host" parameter'); + } + // Initialize parameters + scheme = scheme || Constants_1.C.SIP; + for (var header in headers) { + if (headers.hasOwnProperty(header)) { + _this.setHeader(header, headers[header]); + } + } + // Raw URI + _this.raw = { + scheme: scheme, + user: user, + host: host, + port: port + }; + // Normalized URI + _this.normal = { + scheme: scheme.toLowerCase(), + user: user, + host: host.toLowerCase(), + port: port + }; + return _this; + } + Object.defineProperty(URI.prototype, "_normal", { + get: function () { return this.normal; }, + enumerable: true, + configurable: true + }); + Object.defineProperty(URI.prototype, "_raw", { + get: function () { return this.raw; }, + enumerable: true, + configurable: true + }); + Object.defineProperty(URI.prototype, "scheme", { + get: function () { return this.normal.scheme; }, + set: function (value) { + this.raw.scheme = value; + this.normal.scheme = value.toLowerCase(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(URI.prototype, "user", { + get: function () { return this.normal.user; }, + set: function (value) { + this.normal.user = this.raw.user = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(URI.prototype, "host", { + get: function () { return this.normal.host; }, + set: function (value) { + this.raw.host = value; + this.normal.host = value.toLowerCase(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(URI.prototype, "aor", { + get: function () { return this.normal.user + "@" + this.normal.host; }, + enumerable: true, + configurable: true + }); + Object.defineProperty(URI.prototype, "port", { + get: function () { return this.normal.port; }, + set: function (value) { + this.normal.port = this.raw.port = value === 0 ? value : value; + }, + enumerable: true, + configurable: true + }); + URI.prototype.setHeader = function (name, value) { + this.headers[this.headerize(name)] = (value instanceof Array) ? value : [value]; + }; + URI.prototype.getHeader = function (name) { + if (name) { + return this.headers[this.headerize(name)]; + } + }; + URI.prototype.hasHeader = function (name) { + return !!name && !!this.headers.hasOwnProperty(this.headerize(name)); + }; + URI.prototype.deleteHeader = function (header) { + header = this.headerize(header); + if (this.headers.hasOwnProperty(header)) { + var value = this.headers[header]; + delete this.headers[header]; + return value; + } + }; + URI.prototype.clearHeaders = function () { + this.headers = {}; + }; + URI.prototype.clone = function () { + return new URI(this._raw.scheme, this._raw.user || "", this._raw.host, this._raw.port, JSON.parse(JSON.stringify(this.parameters)), JSON.parse(JSON.stringify(this.headers))); + }; + URI.prototype.toRaw = function () { + return this._toString(this._raw); + }; + URI.prototype.toString = function () { + return this._toString(this._normal); + }; + URI.prototype._toString = function (uri) { + var uriString = uri.scheme + ":"; + // add slashes if it's not a sip(s) URI + if (!uri.scheme.toLowerCase().match("^sips?$")) { + uriString += "//"; + } + if (uri.user) { + uriString += this.escapeUser(uri.user) + "@"; + } + uriString += uri.host; + if (uri.port || uri.port === 0) { + uriString += ":" + uri.port; + } + for (var parameter in this.parameters) { + if (this.parameters.hasOwnProperty(parameter)) { + uriString += ";" + parameter; + if (this.parameters[parameter] !== null) { + uriString += "=" + this.parameters[parameter]; + } + } + } + var headers = []; + for (var header in this.headers) { + if (this.headers.hasOwnProperty(header)) { + for (var idx in this.headers[header]) { + if (this.headers[header].hasOwnProperty(idx)) { + headers.push(header + "=" + this.headers[header][idx]); + } + } + } + } + if (headers.length > 0) { + uriString += "?" + headers.join("&"); + } + return uriString; + }; + // The following two functions were copied from Utils to break a circular dependency + /* + * Hex-escape a SIP URI user. + * @private + * @param {String} user + */ + URI.prototype.escapeUser = function (user) { + // Don't hex-escape ':' (%3A), '+' (%2B), '?' (%3F"), '/' (%2F). + return encodeURIComponent(decodeURIComponent(user)) + .replace(/%3A/ig, ":") + .replace(/%2B/ig, "+") + .replace(/%3F/ig, "?") + .replace(/%2F/ig, "/"); + }; + URI.prototype.headerize = function (str) { + var exceptions = { + "Call-Id": "Call-ID", + "Cseq": "CSeq", + "Min-Se": "Min-SE", + "Rack": "RAck", + "Rseq": "RSeq", + "Www-Authenticate": "WWW-Authenticate", + }; + var name = str.toLowerCase().replace(/_/g, "-").split("-"); + var parts = name.length; + var hname = ""; + for (var part = 0; part < parts; part++) { + if (part !== 0) { + hname += "-"; + } + hname += name[part].charAt(0).toUpperCase() + name[part].substring(1); + } + if (exceptions[hname]) { + hname = exceptions[hname]; + } + return hname; + }; + return URI; +}(Parameters)); +exports.URI = URI; + + +/***/ }), +/* 11 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +var Constants_1 = __webpack_require__(3); +var Enums_1 = __webpack_require__(5); +var Grammar_1 = __webpack_require__(7); +var Utils; +(function (Utils) { + function defer() { + var deferred = {}; + deferred.promise = new Promise(function (resolve, reject) { + deferred.resolve = resolve; + deferred.reject = reject; + }); + return deferred; + } + Utils.defer = defer; + function reducePromises(arr, val) { + return arr.reduce(function (acc, fn) { + acc = acc.then(fn); + return acc; + }, Promise.resolve(val)); + } + Utils.reducePromises = reducePromises; + function str_utf8_length(str) { + return encodeURIComponent(str).replace(/%[A-F\d]{2}/g, "U").length; + } + Utils.str_utf8_length = str_utf8_length; + function generateFakeSDP(body) { + if (!body) { + return; + } + var start = body.indexOf("o="); + var end = body.indexOf("\r\n", start); + return "v=0\r\n" + body.slice(start, end) + "\r\ns=-\r\nt=0 0\r\nc=IN IP4 0.0.0.0"; + } + Utils.generateFakeSDP = generateFakeSDP; + function isDecimal(num) { + var numAsNum = parseInt(num, 10); + return !isNaN(numAsNum) && (parseFloat(num) === numAsNum); + } + Utils.isDecimal = isDecimal; + function createRandomToken(size, base) { + if (base === void 0) { base = 32; } + var token = ""; + for (var i = 0; i < size; i++) { + var r = Math.floor(Math.random() * base); + token += r.toString(base); + } + return token; + } + Utils.createRandomToken = createRandomToken; + function newTag() { + // used to use the constant in UA + return Utils.createRandomToken(10); + } + Utils.newTag = newTag; + // http://stackoverflow.com/users/109538/broofa + function newUUID() { + var UUID = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) { + var r = Math.floor(Math.random() * 16); + var v = c === "x" ? r : (r % 4 + 8); + return v.toString(16); + }); + return UUID; + } + Utils.newUUID = newUUID; + /* + * Normalize SIP URI. + * NOTE: It does not allow a SIP URI without username. + * Accepts 'sip', 'sips' and 'tel' URIs and convert them into 'sip'. + * Detects the domain part (if given) and properly hex-escapes the user portion. + * If the user portion has only 'tel' number symbols the user portion is clean of 'tel' visual separators. + * @private + * @param {String} target + * @param {String} [domain] + */ + function normalizeTarget(target, domain) { + // If no target is given then raise an error. + if (!target) { + return; + // If a SIP.URI instance is given then return it. + } + else if (target.type === Enums_1.TypeStrings.URI) { + return target; + // If a string is given split it by '@': + // - Last fragment is the desired domain. + // - Otherwise append the given domain argument. + } + else if (typeof target === "string") { + var targetArray = target.split("@"); + var targetUser = void 0; + var targetDomain = void 0; + switch (targetArray.length) { + case 1: + if (!domain) { + return; + } + targetUser = target; + targetDomain = domain; + break; + case 2: + targetUser = targetArray[0]; + targetDomain = targetArray[1]; + break; + default: + targetUser = targetArray.slice(0, targetArray.length - 1).join("@"); + targetDomain = targetArray[targetArray.length - 1]; + } + // Remove the URI scheme (if present). + targetUser = targetUser.replace(/^(sips?|tel):/i, ""); + // Remove 'tel' visual separators if the user portion just contains 'tel' number symbols. + if (/^[\-\.\(\)]*\+?[0-9\-\.\(\)]+$/.test(targetUser)) { + targetUser = targetUser.replace(/[\-\.\(\)]/g, ""); + } + // Build the complete SIP URI. + target = Constants_1.C.SIP + ":" + Utils.escapeUser(targetUser) + "@" + targetDomain; + // Finally parse the resulting URI. + return Grammar_1.Grammar.URIParse(target); + } + else { + return; + } + } + Utils.normalizeTarget = normalizeTarget; + /* + * Hex-escape a SIP URI user. + * @private + * @param {String} user + */ + function escapeUser(user) { + // Don't hex-escape ':' (%3A), '+' (%2B), '?' (%3F"), '/' (%2F). + return encodeURIComponent(decodeURIComponent(user)) + .replace(/%3A/ig, ":") + .replace(/%2B/ig, "+") + .replace(/%3F/ig, "?") + .replace(/%2F/ig, "/"); + } + Utils.escapeUser = escapeUser; + function headerize(str) { + var exceptions = { + "Call-Id": "Call-ID", + "Cseq": "CSeq", + "Min-Se": "Min-SE", + "Rack": "RAck", + "Rseq": "RSeq", + "Www-Authenticate": "WWW-Authenticate", + }; + var name = str.toLowerCase().replace(/_/g, "-").split("-"); + var parts = name.length; + var hname = ""; + for (var part = 0; part < parts; part++) { + if (part !== 0) { + hname += "-"; + } + hname += name[part].charAt(0).toUpperCase() + name[part].substring(1); + } + if (exceptions[hname]) { + hname = exceptions[hname]; + } + return hname; + } + Utils.headerize = headerize; + function sipErrorCause(statusCode) { + for (var cause in Constants_1.C.SIP_ERROR_CAUSES) { + if (Constants_1.C.SIP_ERROR_CAUSES[cause].indexOf(statusCode) !== -1) { + return Constants_1.C.causes[cause]; + } + } + return Constants_1.C.causes.SIP_FAILURE_CODE; + } + Utils.sipErrorCause = sipErrorCause; + function getReasonPhrase(code, specific) { + return specific || Constants_1.C.REASON_PHRASE[code] || ""; + } + Utils.getReasonPhrase = getReasonPhrase; + function getReasonHeaderValue(code, reason) { + reason = Utils.getReasonPhrase(code, reason); + return "SIP;cause=" + code + ';text="' + reason + '"'; + } + Utils.getReasonHeaderValue = getReasonHeaderValue; + function getCancelReason(code, reason) { + if (code && code < 200 || code > 699) { + throw new TypeError("Invalid statusCode: " + code); + } + else if (code) { + return Utils.getReasonHeaderValue(code, reason); + } + } + Utils.getCancelReason = getCancelReason; + function buildStatusLine(code, reason) { + // Validate code and reason values + if (!code || (code < 100 || code > 699)) { + throw new TypeError("Invalid statusCode: " + code); + } + else if (reason && typeof reason !== "string" && !(reason instanceof String)) { + throw new TypeError("Invalid reason: " + reason); + } + reason = Utils.getReasonPhrase(code, reason); + return "SIP/2.0 " + code + " " + reason + "\r\n"; + } + Utils.buildStatusLine = buildStatusLine; +})(Utils = exports.Utils || (exports.Utils = {})); + + +/***/ }), +/* 12 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +var crypto_js_1 = __webpack_require__(13); +var Enums_1 = __webpack_require__(5); +var Utils_1 = __webpack_require__(11); +/** + * SIP Digest Authentication. + * @function Digest Authentication + * @param {SIP.UA} ua + */ +var DigestAuthentication = /** @class */ (function () { + function DigestAuthentication(ua) { + this.type = Enums_1.TypeStrings.DigestAuthentication; + this.logger = ua.getLogger("sipjs.digestauthentication"); + this.username = ua.configuration.authorizationUser; + this.password = ua.configuration.password; + this.nc = 0; + this.ncHex = "00000000"; + } + /** + * Performs Digest authentication given a SIP request and the challenge + * received in a response to that request. + * Returns true if credentials were successfully generated, false otherwise. + * + * @param {SIP.OutgoingRequest} request + * @param {Object} challenge + */ + DigestAuthentication.prototype.authenticate = function (request, challenge, body) { + // Inspect and validate the challenge. + this.algorithm = challenge.algorithm; + this.realm = challenge.realm; + this.nonce = challenge.nonce; + this.opaque = challenge.opaque; + this.stale = challenge.stale; + if (this.algorithm) { + if (this.algorithm !== "MD5") { + this.logger.warn("challenge with Digest algorithm different than 'MD5', authentication aborted"); + return false; + } + } + else { + this.algorithm = "MD5"; + } + if (!this.realm) { + this.logger.warn("challenge without Digest realm, authentication aborted"); + return false; + } + if (!this.nonce) { + this.logger.warn("challenge without Digest nonce, authentication aborted"); + return false; + } + // 'qop' can contain a list of values (Array). Let's choose just one. + if (challenge.qop) { + if (challenge.qop.indexOf("auth") > -1) { + this.qop = "auth"; + } + else if (challenge.qop.indexOf("auth-int") > -1) { + this.qop = "auth-int"; + } + else { + // Otherwise 'qop' is present but does not contain 'auth' or 'auth-int', so abort here. + this.logger.warn("challenge without Digest qop different than 'auth' or 'auth-int', authentication aborted"); + return false; + } + } + else { + this.qop = undefined; + } + // Fill other attributes. + this.method = request.method; + this.uri = request.ruri; + this.cnonce = Utils_1.Utils.createRandomToken(12); + this.nc += 1; + this.updateNcHex(); + // nc-value = 8LHEX. Max value = 'FFFFFFFF'. + if (this.nc === 4294967296) { + this.nc = 1; + this.ncHex = "00000001"; + } + // Calculate the Digest "response" value. + this.calculateResponse(body); + return true; + }; + /** + * Return the Proxy-Authorization or WWW-Authorization header value. + */ + DigestAuthentication.prototype.toString = function () { + var authParams = []; + if (!this.response) { + throw new Error("response field does not exist, cannot generate Authorization header"); + } + authParams.push("algorithm=" + this.algorithm); + authParams.push('username="' + this.username + '"'); + authParams.push('realm="' + this.realm + '"'); + authParams.push('nonce="' + this.nonce + '"'); + authParams.push('uri="' + this.uri + '"'); + authParams.push('response="' + this.response + '"'); + if (this.opaque) { + authParams.push('opaque="' + this.opaque + '"'); + } + if (this.qop) { + authParams.push("qop=" + this.qop); + authParams.push('cnonce="' + this.cnonce + '"'); + authParams.push("nc=" + this.ncHex); + } + return "Digest " + authParams.join(", "); + }; + /** + * Generate the 'nc' value as required by Digest in this.ncHex by reading this.nc. + * @private + */ + DigestAuthentication.prototype.updateNcHex = function () { + var hex = Number(this.nc).toString(16); + this.ncHex = "00000000".substr(0, 8 - hex.length) + hex; + }; + /** + * Generate Digest 'response' value. + * @private + */ + DigestAuthentication.prototype.calculateResponse = function (body) { + var ha2; + // HA1 = MD5(A1) = MD5(username:realm:password) + var ha1 = crypto_js_1.MD5(this.username + ":" + this.realm + ":" + this.password); + if (this.qop === "auth") { + // HA2 = MD5(A2) = MD5(method:digestURI) + ha2 = crypto_js_1.MD5(this.method + ":" + this.uri); + // response = MD5(HA1:nonce:nonceCount:credentialsNonce:qop:HA2) + this.response = crypto_js_1.MD5(ha1 + ":" + this.nonce + ":" + this.ncHex + ":" + this.cnonce + ":auth:" + ha2); + } + else if (this.qop === "auth-int") { + // HA2 = MD5(A2) = MD5(method:digestURI:MD5(entityBody)) + ha2 = crypto_js_1.MD5(this.method + ":" + this.uri + ":" + crypto_js_1.MD5(body ? body : "")); + // response = MD5(HA1:nonce:nonceCount:credentialsNonce:qop:HA2) + this.response = crypto_js_1.MD5(ha1 + ":" + this.nonce + ":" + this.ncHex + ":" + this.cnonce + ":auth-int:" + ha2); + } + else if (this.qop === undefined) { + // HA2 = MD5(A2) = MD5(method:digestURI) + ha2 = crypto_js_1.MD5(this.method + ":" + this.uri); + // response = MD5(HA1:nonce:HA2) + this.response = crypto_js_1.MD5(ha1 + ":" + this.nonce + ":" + ha2); + } + }; + return DigestAuthentication; +}()); +exports.DigestAuthentication = DigestAuthentication; + + +/***/ }), +/* 13 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory, undef) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14), __webpack_require__(15), __webpack_require__(16), __webpack_require__(17), __webpack_require__(18), __webpack_require__(19), __webpack_require__(20), __webpack_require__(21), __webpack_require__(22), __webpack_require__(23), __webpack_require__(24), __webpack_require__(25), __webpack_require__(26), __webpack_require__(27), __webpack_require__(28), __webpack_require__(29), __webpack_require__(30), __webpack_require__(31), __webpack_require__(32), __webpack_require__(33), __webpack_require__(34), __webpack_require__(35), __webpack_require__(36), __webpack_require__(37), __webpack_require__(38), __webpack_require__(39), __webpack_require__(40), __webpack_require__(41), __webpack_require__(42), __webpack_require__(43), __webpack_require__(44), __webpack_require__(45), __webpack_require__(46)); + } + else {} +}(this, function (CryptoJS) { + + return CryptoJS; + +})); + +/***/ }), +/* 14 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory) { + if (true) { + // CommonJS + module.exports = exports = factory(); + } + else {} +}(this, function () { + + /** + * CryptoJS core components. + */ + var CryptoJS = CryptoJS || (function (Math, undefined) { + /* + * Local polyfil of Object.create + */ + var create = Object.create || (function () { + function F() {}; + + return function (obj) { + var subtype; + + F.prototype = obj; + + subtype = new F(); + + F.prototype = null; + + return subtype; + }; + }()) + + /** + * CryptoJS namespace. + */ + var C = {}; + + /** + * Library namespace. + */ + var C_lib = C.lib = {}; + + /** + * Base object for prototypal inheritance. + */ + var Base = C_lib.Base = (function () { + + + return { + /** + * Creates a new object that inherits from this object. + * + * @param {Object} overrides Properties to copy into the new object. + * + * @return {Object} The new object. + * + * @static + * + * @example + * + * var MyType = CryptoJS.lib.Base.extend({ + * field: 'value', + * + * method: function () { + * } + * }); + */ + extend: function (overrides) { + // Spawn + var subtype = create(this); + + // Augment + if (overrides) { + subtype.mixIn(overrides); + } + + // Create default initializer + if (!subtype.hasOwnProperty('init') || this.init === subtype.init) { + subtype.init = function () { + subtype.$super.init.apply(this, arguments); + }; + } + + // Initializer's prototype is the subtype object + subtype.init.prototype = subtype; + + // Reference supertype + subtype.$super = this; + + return subtype; + }, + + /** + * Extends this object and runs the init method. + * Arguments to create() will be passed to init(). + * + * @return {Object} The new object. + * + * @static + * + * @example + * + * var instance = MyType.create(); + */ + create: function () { + var instance = this.extend(); + instance.init.apply(instance, arguments); + + return instance; + }, + + /** + * Initializes a newly created object. + * Override this method to add some logic when your objects are created. + * + * @example + * + * var MyType = CryptoJS.lib.Base.extend({ + * init: function () { + * // ... + * } + * }); + */ + init: function () { + }, + + /** + * Copies properties into this object. + * + * @param {Object} properties The properties to mix in. + * + * @example + * + * MyType.mixIn({ + * field: 'value' + * }); + */ + mixIn: function (properties) { + for (var propertyName in properties) { + if (properties.hasOwnProperty(propertyName)) { + this[propertyName] = properties[propertyName]; + } + } + + // IE won't copy toString using the loop above + if (properties.hasOwnProperty('toString')) { + this.toString = properties.toString; + } + }, + + /** + * Creates a copy of this object. + * + * @return {Object} The clone. + * + * @example + * + * var clone = instance.clone(); + */ + clone: function () { + return this.init.prototype.extend(this); + } + }; + }()); + + /** + * An array of 32-bit words. + * + * @property {Array} words The array of 32-bit words. + * @property {number} sigBytes The number of significant bytes in this word array. + */ + var WordArray = C_lib.WordArray = Base.extend({ + /** + * Initializes a newly created word array. + * + * @param {Array} words (Optional) An array of 32-bit words. + * @param {number} sigBytes (Optional) The number of significant bytes in the words. + * + * @example + * + * var wordArray = CryptoJS.lib.WordArray.create(); + * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]); + * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6); + */ + init: function (words, sigBytes) { + words = this.words = words || []; + + if (sigBytes != undefined) { + this.sigBytes = sigBytes; + } else { + this.sigBytes = words.length * 4; + } + }, + + /** + * Converts this word array to a string. + * + * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex + * + * @return {string} The stringified word array. + * + * @example + * + * var string = wordArray + ''; + * var string = wordArray.toString(); + * var string = wordArray.toString(CryptoJS.enc.Utf8); + */ + toString: function (encoder) { + return (encoder || Hex).stringify(this); + }, + + /** + * Concatenates a word array to this word array. + * + * @param {WordArray} wordArray The word array to append. + * + * @return {WordArray} This word array. + * + * @example + * + * wordArray1.concat(wordArray2); + */ + concat: function (wordArray) { + // Shortcuts + var thisWords = this.words; + var thatWords = wordArray.words; + var thisSigBytes = this.sigBytes; + var thatSigBytes = wordArray.sigBytes; + + // Clamp excess bits + this.clamp(); + + // Concat + if (thisSigBytes % 4) { + // Copy one byte at a time + for (var i = 0; i < thatSigBytes; i++) { + var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; + thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8); + } + } else { + // Copy one word at a time + for (var i = 0; i < thatSigBytes; i += 4) { + thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2]; + } + } + this.sigBytes += thatSigBytes; + + // Chainable + return this; + }, + + /** + * Removes insignificant bits. + * + * @example + * + * wordArray.clamp(); + */ + clamp: function () { + // Shortcuts + var words = this.words; + var sigBytes = this.sigBytes; + + // Clamp + words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8); + words.length = Math.ceil(sigBytes / 4); + }, + + /** + * Creates a copy of this word array. + * + * @return {WordArray} The clone. + * + * @example + * + * var clone = wordArray.clone(); + */ + clone: function () { + var clone = Base.clone.call(this); + clone.words = this.words.slice(0); + + return clone; + }, + + /** + * Creates a word array filled with random bytes. + * + * @param {number} nBytes The number of random bytes to generate. + * + * @return {WordArray} The random word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.lib.WordArray.random(16); + */ + random: function (nBytes) { + var words = []; + + var r = (function (m_w) { + var m_w = m_w; + var m_z = 0x3ade68b1; + var mask = 0xffffffff; + + return function () { + m_z = (0x9069 * (m_z & 0xFFFF) + (m_z >> 0x10)) & mask; + m_w = (0x4650 * (m_w & 0xFFFF) + (m_w >> 0x10)) & mask; + var result = ((m_z << 0x10) + m_w) & mask; + result /= 0x100000000; + result += 0.5; + return result * (Math.random() > .5 ? 1 : -1); + } + }); + + for (var i = 0, rcache; i < nBytes; i += 4) { + var _r = r((rcache || Math.random()) * 0x100000000); + + rcache = _r() * 0x3ade67b7; + words.push((_r() * 0x100000000) | 0); + } + + return new WordArray.init(words, nBytes); + } + }); + + /** + * Encoder namespace. + */ + var C_enc = C.enc = {}; + + /** + * Hex encoding strategy. + */ + var Hex = C_enc.Hex = { + /** + * Converts a word array to a hex string. + * + * @param {WordArray} wordArray The word array. + * + * @return {string} The hex string. + * + * @static + * + * @example + * + * var hexString = CryptoJS.enc.Hex.stringify(wordArray); + */ + stringify: function (wordArray) { + // Shortcuts + var words = wordArray.words; + var sigBytes = wordArray.sigBytes; + + // Convert + var hexChars = []; + for (var i = 0; i < sigBytes; i++) { + var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; + hexChars.push((bite >>> 4).toString(16)); + hexChars.push((bite & 0x0f).toString(16)); + } + + return hexChars.join(''); + }, + + /** + * Converts a hex string to a word array. + * + * @param {string} hexStr The hex string. + * + * @return {WordArray} The word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.enc.Hex.parse(hexString); + */ + parse: function (hexStr) { + // Shortcut + var hexStrLength = hexStr.length; + + // Convert + var words = []; + for (var i = 0; i < hexStrLength; i += 2) { + words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4); + } + + return new WordArray.init(words, hexStrLength / 2); + } + }; + + /** + * Latin1 encoding strategy. + */ + var Latin1 = C_enc.Latin1 = { + /** + * Converts a word array to a Latin1 string. + * + * @param {WordArray} wordArray The word array. + * + * @return {string} The Latin1 string. + * + * @static + * + * @example + * + * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray); + */ + stringify: function (wordArray) { + // Shortcuts + var words = wordArray.words; + var sigBytes = wordArray.sigBytes; + + // Convert + var latin1Chars = []; + for (var i = 0; i < sigBytes; i++) { + var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; + latin1Chars.push(String.fromCharCode(bite)); + } + + return latin1Chars.join(''); + }, + + /** + * Converts a Latin1 string to a word array. + * + * @param {string} latin1Str The Latin1 string. + * + * @return {WordArray} The word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.enc.Latin1.parse(latin1String); + */ + parse: function (latin1Str) { + // Shortcut + var latin1StrLength = latin1Str.length; + + // Convert + var words = []; + for (var i = 0; i < latin1StrLength; i++) { + words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8); + } + + return new WordArray.init(words, latin1StrLength); + } + }; + + /** + * UTF-8 encoding strategy. + */ + var Utf8 = C_enc.Utf8 = { + /** + * Converts a word array to a UTF-8 string. + * + * @param {WordArray} wordArray The word array. + * + * @return {string} The UTF-8 string. + * + * @static + * + * @example + * + * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray); + */ + stringify: function (wordArray) { + try { + return decodeURIComponent(escape(Latin1.stringify(wordArray))); + } catch (e) { + throw new Error('Malformed UTF-8 data'); + } + }, + + /** + * Converts a UTF-8 string to a word array. + * + * @param {string} utf8Str The UTF-8 string. + * + * @return {WordArray} The word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.enc.Utf8.parse(utf8String); + */ + parse: function (utf8Str) { + return Latin1.parse(unescape(encodeURIComponent(utf8Str))); + } + }; + + /** + * Abstract buffered block algorithm template. + * + * The property blockSize must be implemented in a concrete subtype. + * + * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0 + */ + var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({ + /** + * Resets this block algorithm's data buffer to its initial state. + * + * @example + * + * bufferedBlockAlgorithm.reset(); + */ + reset: function () { + // Initial values + this._data = new WordArray.init(); + this._nDataBytes = 0; + }, + + /** + * Adds new data to this block algorithm's buffer. + * + * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8. + * + * @example + * + * bufferedBlockAlgorithm._append('data'); + * bufferedBlockAlgorithm._append(wordArray); + */ + _append: function (data) { + // Convert string to WordArray, else assume WordArray already + if (typeof data == 'string') { + data = Utf8.parse(data); + } + + // Append + this._data.concat(data); + this._nDataBytes += data.sigBytes; + }, + + /** + * Processes available data blocks. + * + * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype. + * + * @param {boolean} doFlush Whether all blocks and partial blocks should be processed. + * + * @return {WordArray} The processed data. + * + * @example + * + * var processedData = bufferedBlockAlgorithm._process(); + * var processedData = bufferedBlockAlgorithm._process(!!'flush'); + */ + _process: function (doFlush) { + // Shortcuts + var data = this._data; + var dataWords = data.words; + var dataSigBytes = data.sigBytes; + var blockSize = this.blockSize; + var blockSizeBytes = blockSize * 4; + + // Count blocks ready + var nBlocksReady = dataSigBytes / blockSizeBytes; + if (doFlush) { + // Round up to include partial blocks + nBlocksReady = Math.ceil(nBlocksReady); + } else { + // Round down to include only full blocks, + // less the number of blocks that must remain in the buffer + nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0); + } + + // Count words ready + var nWordsReady = nBlocksReady * blockSize; + + // Count bytes ready + var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes); + + // Process blocks + if (nWordsReady) { + for (var offset = 0; offset < nWordsReady; offset += blockSize) { + // Perform concrete-algorithm logic + this._doProcessBlock(dataWords, offset); + } + + // Remove processed words + var processedWords = dataWords.splice(0, nWordsReady); + data.sigBytes -= nBytesReady; + } + + // Return processed words + return new WordArray.init(processedWords, nBytesReady); + }, + + /** + * Creates a copy of this object. + * + * @return {Object} The clone. + * + * @example + * + * var clone = bufferedBlockAlgorithm.clone(); + */ + clone: function () { + var clone = Base.clone.call(this); + clone._data = this._data.clone(); + + return clone; + }, + + _minBufferSize: 0 + }); + + /** + * Abstract hasher template. + * + * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits) + */ + var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({ + /** + * Configuration options. + */ + cfg: Base.extend(), + + /** + * Initializes a newly created hasher. + * + * @param {Object} cfg (Optional) The configuration options to use for this hash computation. + * + * @example + * + * var hasher = CryptoJS.algo.SHA256.create(); + */ + init: function (cfg) { + // Apply config defaults + this.cfg = this.cfg.extend(cfg); + + // Set initial values + this.reset(); + }, + + /** + * Resets this hasher to its initial state. + * + * @example + * + * hasher.reset(); + */ + reset: function () { + // Reset data buffer + BufferedBlockAlgorithm.reset.call(this); + + // Perform concrete-hasher logic + this._doReset(); + }, + + /** + * Updates this hasher with a message. + * + * @param {WordArray|string} messageUpdate The message to append. + * + * @return {Hasher} This hasher. + * + * @example + * + * hasher.update('message'); + * hasher.update(wordArray); + */ + update: function (messageUpdate) { + // Append + this._append(messageUpdate); + + // Update the hash + this._process(); + + // Chainable + return this; + }, + + /** + * Finalizes the hash computation. + * Note that the finalize operation is effectively a destructive, read-once operation. + * + * @param {WordArray|string} messageUpdate (Optional) A final message update. + * + * @return {WordArray} The hash. + * + * @example + * + * var hash = hasher.finalize(); + * var hash = hasher.finalize('message'); + * var hash = hasher.finalize(wordArray); + */ + finalize: function (messageUpdate) { + // Final message update + if (messageUpdate) { + this._append(messageUpdate); + } + + // Perform concrete-hasher logic + var hash = this._doFinalize(); + + return hash; + }, + + blockSize: 512/32, + + /** + * Creates a shortcut function to a hasher's object interface. + * + * @param {Hasher} hasher The hasher to create a helper for. + * + * @return {Function} The shortcut function. + * + * @static + * + * @example + * + * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256); + */ + _createHelper: function (hasher) { + return function (message, cfg) { + return new hasher.init(cfg).finalize(message); + }; + }, + + /** + * Creates a shortcut function to the HMAC's object interface. + * + * @param {Hasher} hasher The hasher to use in this HMAC helper. + * + * @return {Function} The shortcut function. + * + * @static + * + * @example + * + * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256); + */ + _createHmacHelper: function (hasher) { + return function (message, key) { + return new C_algo.HMAC.init(hasher, key).finalize(message); + }; + } + }); + + /** + * Algorithm namespace. + */ + var C_algo = C.algo = {}; + + return C; + }(Math)); + + + return CryptoJS; + +})); + +/***/ }), +/* 15 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14)); + } + else {} +}(this, function (CryptoJS) { + + (function (undefined) { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var Base = C_lib.Base; + var X32WordArray = C_lib.WordArray; + + /** + * x64 namespace. + */ + var C_x64 = C.x64 = {}; + + /** + * A 64-bit word. + */ + var X64Word = C_x64.Word = Base.extend({ + /** + * Initializes a newly created 64-bit word. + * + * @param {number} high The high 32 bits. + * @param {number} low The low 32 bits. + * + * @example + * + * var x64Word = CryptoJS.x64.Word.create(0x00010203, 0x04050607); + */ + init: function (high, low) { + this.high = high; + this.low = low; + } + + /** + * Bitwise NOTs this word. + * + * @return {X64Word} A new x64-Word object after negating. + * + * @example + * + * var negated = x64Word.not(); + */ + // not: function () { + // var high = ~this.high; + // var low = ~this.low; + + // return X64Word.create(high, low); + // }, + + /** + * Bitwise ANDs this word with the passed word. + * + * @param {X64Word} word The x64-Word to AND with this word. + * + * @return {X64Word} A new x64-Word object after ANDing. + * + * @example + * + * var anded = x64Word.and(anotherX64Word); + */ + // and: function (word) { + // var high = this.high & word.high; + // var low = this.low & word.low; + + // return X64Word.create(high, low); + // }, + + /** + * Bitwise ORs this word with the passed word. + * + * @param {X64Word} word The x64-Word to OR with this word. + * + * @return {X64Word} A new x64-Word object after ORing. + * + * @example + * + * var ored = x64Word.or(anotherX64Word); + */ + // or: function (word) { + // var high = this.high | word.high; + // var low = this.low | word.low; + + // return X64Word.create(high, low); + // }, + + /** + * Bitwise XORs this word with the passed word. + * + * @param {X64Word} word The x64-Word to XOR with this word. + * + * @return {X64Word} A new x64-Word object after XORing. + * + * @example + * + * var xored = x64Word.xor(anotherX64Word); + */ + // xor: function (word) { + // var high = this.high ^ word.high; + // var low = this.low ^ word.low; + + // return X64Word.create(high, low); + // }, + + /** + * Shifts this word n bits to the left. + * + * @param {number} n The number of bits to shift. + * + * @return {X64Word} A new x64-Word object after shifting. + * + * @example + * + * var shifted = x64Word.shiftL(25); + */ + // shiftL: function (n) { + // if (n < 32) { + // var high = (this.high << n) | (this.low >>> (32 - n)); + // var low = this.low << n; + // } else { + // var high = this.low << (n - 32); + // var low = 0; + // } + + // return X64Word.create(high, low); + // }, + + /** + * Shifts this word n bits to the right. + * + * @param {number} n The number of bits to shift. + * + * @return {X64Word} A new x64-Word object after shifting. + * + * @example + * + * var shifted = x64Word.shiftR(7); + */ + // shiftR: function (n) { + // if (n < 32) { + // var low = (this.low >>> n) | (this.high << (32 - n)); + // var high = this.high >>> n; + // } else { + // var low = this.high >>> (n - 32); + // var high = 0; + // } + + // return X64Word.create(high, low); + // }, + + /** + * Rotates this word n bits to the left. + * + * @param {number} n The number of bits to rotate. + * + * @return {X64Word} A new x64-Word object after rotating. + * + * @example + * + * var rotated = x64Word.rotL(25); + */ + // rotL: function (n) { + // return this.shiftL(n).or(this.shiftR(64 - n)); + // }, + + /** + * Rotates this word n bits to the right. + * + * @param {number} n The number of bits to rotate. + * + * @return {X64Word} A new x64-Word object after rotating. + * + * @example + * + * var rotated = x64Word.rotR(7); + */ + // rotR: function (n) { + // return this.shiftR(n).or(this.shiftL(64 - n)); + // }, + + /** + * Adds this word with the passed word. + * + * @param {X64Word} word The x64-Word to add with this word. + * + * @return {X64Word} A new x64-Word object after adding. + * + * @example + * + * var added = x64Word.add(anotherX64Word); + */ + // add: function (word) { + // var low = (this.low + word.low) | 0; + // var carry = (low >>> 0) < (this.low >>> 0) ? 1 : 0; + // var high = (this.high + word.high + carry) | 0; + + // return X64Word.create(high, low); + // } + }); + + /** + * An array of 64-bit words. + * + * @property {Array} words The array of CryptoJS.x64.Word objects. + * @property {number} sigBytes The number of significant bytes in this word array. + */ + var X64WordArray = C_x64.WordArray = Base.extend({ + /** + * Initializes a newly created word array. + * + * @param {Array} words (Optional) An array of CryptoJS.x64.Word objects. + * @param {number} sigBytes (Optional) The number of significant bytes in the words. + * + * @example + * + * var wordArray = CryptoJS.x64.WordArray.create(); + * + * var wordArray = CryptoJS.x64.WordArray.create([ + * CryptoJS.x64.Word.create(0x00010203, 0x04050607), + * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) + * ]); + * + * var wordArray = CryptoJS.x64.WordArray.create([ + * CryptoJS.x64.Word.create(0x00010203, 0x04050607), + * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) + * ], 10); + */ + init: function (words, sigBytes) { + words = this.words = words || []; + + if (sigBytes != undefined) { + this.sigBytes = sigBytes; + } else { + this.sigBytes = words.length * 8; + } + }, + + /** + * Converts this 64-bit word array to a 32-bit word array. + * + * @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array. + * + * @example + * + * var x32WordArray = x64WordArray.toX32(); + */ + toX32: function () { + // Shortcuts + var x64Words = this.words; + var x64WordsLength = x64Words.length; + + // Convert + var x32Words = []; + for (var i = 0; i < x64WordsLength; i++) { + var x64Word = x64Words[i]; + x32Words.push(x64Word.high); + x32Words.push(x64Word.low); + } + + return X32WordArray.create(x32Words, this.sigBytes); + }, + + /** + * Creates a copy of this word array. + * + * @return {X64WordArray} The clone. + * + * @example + * + * var clone = x64WordArray.clone(); + */ + clone: function () { + var clone = Base.clone.call(this); + + // Clone "words" array + var words = clone.words = this.words.slice(0); + + // Clone each X64Word object + var wordsLength = words.length; + for (var i = 0; i < wordsLength; i++) { + words[i] = words[i].clone(); + } + + return clone; + } + }); + }()); + + + return CryptoJS; + +})); + +/***/ }), +/* 16 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14)); + } + else {} +}(this, function (CryptoJS) { + + (function () { + // Check if typed arrays are supported + if (typeof ArrayBuffer != 'function') { + return; + } + + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + + // Reference original init + var superInit = WordArray.init; + + // Augment WordArray.init to handle typed arrays + var subInit = WordArray.init = function (typedArray) { + // Convert buffers to uint8 + if (typedArray instanceof ArrayBuffer) { + typedArray = new Uint8Array(typedArray); + } + + // Convert other array views to uint8 + if ( + typedArray instanceof Int8Array || + (typeof Uint8ClampedArray !== "undefined" && typedArray instanceof Uint8ClampedArray) || + typedArray instanceof Int16Array || + typedArray instanceof Uint16Array || + typedArray instanceof Int32Array || + typedArray instanceof Uint32Array || + typedArray instanceof Float32Array || + typedArray instanceof Float64Array + ) { + typedArray = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength); + } + + // Handle Uint8Array + if (typedArray instanceof Uint8Array) { + // Shortcut + var typedArrayByteLength = typedArray.byteLength; + + // Extract bytes + var words = []; + for (var i = 0; i < typedArrayByteLength; i++) { + words[i >>> 2] |= typedArray[i] << (24 - (i % 4) * 8); + } + + // Initialize this word array + superInit.call(this, words, typedArrayByteLength); + } else { + // Else call normal init + superInit.apply(this, arguments); + } + }; + + subInit.prototype = WordArray; + }()); + + + return CryptoJS.lib.WordArray; + +})); + +/***/ }), +/* 17 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14)); + } + else {} +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var C_enc = C.enc; + + /** + * UTF-16 BE encoding strategy. + */ + var Utf16BE = C_enc.Utf16 = C_enc.Utf16BE = { + /** + * Converts a word array to a UTF-16 BE string. + * + * @param {WordArray} wordArray The word array. + * + * @return {string} The UTF-16 BE string. + * + * @static + * + * @example + * + * var utf16String = CryptoJS.enc.Utf16.stringify(wordArray); + */ + stringify: function (wordArray) { + // Shortcuts + var words = wordArray.words; + var sigBytes = wordArray.sigBytes; + + // Convert + var utf16Chars = []; + for (var i = 0; i < sigBytes; i += 2) { + var codePoint = (words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff; + utf16Chars.push(String.fromCharCode(codePoint)); + } + + return utf16Chars.join(''); + }, + + /** + * Converts a UTF-16 BE string to a word array. + * + * @param {string} utf16Str The UTF-16 BE string. + * + * @return {WordArray} The word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.enc.Utf16.parse(utf16String); + */ + parse: function (utf16Str) { + // Shortcut + var utf16StrLength = utf16Str.length; + + // Convert + var words = []; + for (var i = 0; i < utf16StrLength; i++) { + words[i >>> 1] |= utf16Str.charCodeAt(i) << (16 - (i % 2) * 16); + } + + return WordArray.create(words, utf16StrLength * 2); + } + }; + + /** + * UTF-16 LE encoding strategy. + */ + C_enc.Utf16LE = { + /** + * Converts a word array to a UTF-16 LE string. + * + * @param {WordArray} wordArray The word array. + * + * @return {string} The UTF-16 LE string. + * + * @static + * + * @example + * + * var utf16Str = CryptoJS.enc.Utf16LE.stringify(wordArray); + */ + stringify: function (wordArray) { + // Shortcuts + var words = wordArray.words; + var sigBytes = wordArray.sigBytes; + + // Convert + var utf16Chars = []; + for (var i = 0; i < sigBytes; i += 2) { + var codePoint = swapEndian((words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff); + utf16Chars.push(String.fromCharCode(codePoint)); + } + + return utf16Chars.join(''); + }, + + /** + * Converts a UTF-16 LE string to a word array. + * + * @param {string} utf16Str The UTF-16 LE string. + * + * @return {WordArray} The word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.enc.Utf16LE.parse(utf16Str); + */ + parse: function (utf16Str) { + // Shortcut + var utf16StrLength = utf16Str.length; + + // Convert + var words = []; + for (var i = 0; i < utf16StrLength; i++) { + words[i >>> 1] |= swapEndian(utf16Str.charCodeAt(i) << (16 - (i % 2) * 16)); + } + + return WordArray.create(words, utf16StrLength * 2); + } + }; + + function swapEndian(word) { + return ((word << 8) & 0xff00ff00) | ((word >>> 8) & 0x00ff00ff); + } + }()); + + + return CryptoJS.enc.Utf16; + +})); + +/***/ }), +/* 18 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14)); + } + else {} +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var C_enc = C.enc; + + /** + * Base64 encoding strategy. + */ + var Base64 = C_enc.Base64 = { + /** + * Converts a word array to a Base64 string. + * + * @param {WordArray} wordArray The word array. + * + * @return {string} The Base64 string. + * + * @static + * + * @example + * + * var base64String = CryptoJS.enc.Base64.stringify(wordArray); + */ + stringify: function (wordArray) { + // Shortcuts + var words = wordArray.words; + var sigBytes = wordArray.sigBytes; + var map = this._map; + + // Clamp excess bits + wordArray.clamp(); + + // Convert + var base64Chars = []; + for (var i = 0; i < sigBytes; i += 3) { + var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; + var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff; + var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff; + + var triplet = (byte1 << 16) | (byte2 << 8) | byte3; + + for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) { + base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f)); + } + } + + // Add padding + var paddingChar = map.charAt(64); + if (paddingChar) { + while (base64Chars.length % 4) { + base64Chars.push(paddingChar); + } + } + + return base64Chars.join(''); + }, + + /** + * Converts a Base64 string to a word array. + * + * @param {string} base64Str The Base64 string. + * + * @return {WordArray} The word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.enc.Base64.parse(base64String); + */ + parse: function (base64Str) { + // Shortcuts + var base64StrLength = base64Str.length; + var map = this._map; + var reverseMap = this._reverseMap; + + if (!reverseMap) { + reverseMap = this._reverseMap = []; + for (var j = 0; j < map.length; j++) { + reverseMap[map.charCodeAt(j)] = j; + } + } + + // Ignore padding + var paddingChar = map.charAt(64); + if (paddingChar) { + var paddingIndex = base64Str.indexOf(paddingChar); + if (paddingIndex !== -1) { + base64StrLength = paddingIndex; + } + } + + // Convert + return parseLoop(base64Str, base64StrLength, reverseMap); + + }, + + _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=' + }; + + function parseLoop(base64Str, base64StrLength, reverseMap) { + var words = []; + var nBytes = 0; + for (var i = 0; i < base64StrLength; i++) { + if (i % 4) { + var bits1 = reverseMap[base64Str.charCodeAt(i - 1)] << ((i % 4) * 2); + var bits2 = reverseMap[base64Str.charCodeAt(i)] >>> (6 - (i % 4) * 2); + words[nBytes >>> 2] |= (bits1 | bits2) << (24 - (nBytes % 4) * 8); + nBytes++; + } + } + return WordArray.create(words, nBytes); + } + }()); + + + return CryptoJS.enc.Base64; + +})); + +/***/ }), +/* 19 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14)); + } + else {} +}(this, function (CryptoJS) { + + (function (Math) { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var Hasher = C_lib.Hasher; + var C_algo = C.algo; + + // Constants table + var T = []; + + // Compute constants + (function () { + for (var i = 0; i < 64; i++) { + T[i] = (Math.abs(Math.sin(i + 1)) * 0x100000000) | 0; + } + }()); + + /** + * MD5 hash algorithm. + */ + var MD5 = C_algo.MD5 = Hasher.extend({ + _doReset: function () { + this._hash = new WordArray.init([ + 0x67452301, 0xefcdab89, + 0x98badcfe, 0x10325476 + ]); + }, + + _doProcessBlock: function (M, offset) { + // Swap endian + for (var i = 0; i < 16; i++) { + // Shortcuts + var offset_i = offset + i; + var M_offset_i = M[offset_i]; + + M[offset_i] = ( + (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | + (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) + ); + } + + // Shortcuts + var H = this._hash.words; + + var M_offset_0 = M[offset + 0]; + var M_offset_1 = M[offset + 1]; + var M_offset_2 = M[offset + 2]; + var M_offset_3 = M[offset + 3]; + var M_offset_4 = M[offset + 4]; + var M_offset_5 = M[offset + 5]; + var M_offset_6 = M[offset + 6]; + var M_offset_7 = M[offset + 7]; + var M_offset_8 = M[offset + 8]; + var M_offset_9 = M[offset + 9]; + var M_offset_10 = M[offset + 10]; + var M_offset_11 = M[offset + 11]; + var M_offset_12 = M[offset + 12]; + var M_offset_13 = M[offset + 13]; + var M_offset_14 = M[offset + 14]; + var M_offset_15 = M[offset + 15]; + + // Working varialbes + var a = H[0]; + var b = H[1]; + var c = H[2]; + var d = H[3]; + + // Computation + a = FF(a, b, c, d, M_offset_0, 7, T[0]); + d = FF(d, a, b, c, M_offset_1, 12, T[1]); + c = FF(c, d, a, b, M_offset_2, 17, T[2]); + b = FF(b, c, d, a, M_offset_3, 22, T[3]); + a = FF(a, b, c, d, M_offset_4, 7, T[4]); + d = FF(d, a, b, c, M_offset_5, 12, T[5]); + c = FF(c, d, a, b, M_offset_6, 17, T[6]); + b = FF(b, c, d, a, M_offset_7, 22, T[7]); + a = FF(a, b, c, d, M_offset_8, 7, T[8]); + d = FF(d, a, b, c, M_offset_9, 12, T[9]); + c = FF(c, d, a, b, M_offset_10, 17, T[10]); + b = FF(b, c, d, a, M_offset_11, 22, T[11]); + a = FF(a, b, c, d, M_offset_12, 7, T[12]); + d = FF(d, a, b, c, M_offset_13, 12, T[13]); + c = FF(c, d, a, b, M_offset_14, 17, T[14]); + b = FF(b, c, d, a, M_offset_15, 22, T[15]); + + a = GG(a, b, c, d, M_offset_1, 5, T[16]); + d = GG(d, a, b, c, M_offset_6, 9, T[17]); + c = GG(c, d, a, b, M_offset_11, 14, T[18]); + b = GG(b, c, d, a, M_offset_0, 20, T[19]); + a = GG(a, b, c, d, M_offset_5, 5, T[20]); + d = GG(d, a, b, c, M_offset_10, 9, T[21]); + c = GG(c, d, a, b, M_offset_15, 14, T[22]); + b = GG(b, c, d, a, M_offset_4, 20, T[23]); + a = GG(a, b, c, d, M_offset_9, 5, T[24]); + d = GG(d, a, b, c, M_offset_14, 9, T[25]); + c = GG(c, d, a, b, M_offset_3, 14, T[26]); + b = GG(b, c, d, a, M_offset_8, 20, T[27]); + a = GG(a, b, c, d, M_offset_13, 5, T[28]); + d = GG(d, a, b, c, M_offset_2, 9, T[29]); + c = GG(c, d, a, b, M_offset_7, 14, T[30]); + b = GG(b, c, d, a, M_offset_12, 20, T[31]); + + a = HH(a, b, c, d, M_offset_5, 4, T[32]); + d = HH(d, a, b, c, M_offset_8, 11, T[33]); + c = HH(c, d, a, b, M_offset_11, 16, T[34]); + b = HH(b, c, d, a, M_offset_14, 23, T[35]); + a = HH(a, b, c, d, M_offset_1, 4, T[36]); + d = HH(d, a, b, c, M_offset_4, 11, T[37]); + c = HH(c, d, a, b, M_offset_7, 16, T[38]); + b = HH(b, c, d, a, M_offset_10, 23, T[39]); + a = HH(a, b, c, d, M_offset_13, 4, T[40]); + d = HH(d, a, b, c, M_offset_0, 11, T[41]); + c = HH(c, d, a, b, M_offset_3, 16, T[42]); + b = HH(b, c, d, a, M_offset_6, 23, T[43]); + a = HH(a, b, c, d, M_offset_9, 4, T[44]); + d = HH(d, a, b, c, M_offset_12, 11, T[45]); + c = HH(c, d, a, b, M_offset_15, 16, T[46]); + b = HH(b, c, d, a, M_offset_2, 23, T[47]); + + a = II(a, b, c, d, M_offset_0, 6, T[48]); + d = II(d, a, b, c, M_offset_7, 10, T[49]); + c = II(c, d, a, b, M_offset_14, 15, T[50]); + b = II(b, c, d, a, M_offset_5, 21, T[51]); + a = II(a, b, c, d, M_offset_12, 6, T[52]); + d = II(d, a, b, c, M_offset_3, 10, T[53]); + c = II(c, d, a, b, M_offset_10, 15, T[54]); + b = II(b, c, d, a, M_offset_1, 21, T[55]); + a = II(a, b, c, d, M_offset_8, 6, T[56]); + d = II(d, a, b, c, M_offset_15, 10, T[57]); + c = II(c, d, a, b, M_offset_6, 15, T[58]); + b = II(b, c, d, a, M_offset_13, 21, T[59]); + a = II(a, b, c, d, M_offset_4, 6, T[60]); + d = II(d, a, b, c, M_offset_11, 10, T[61]); + c = II(c, d, a, b, M_offset_2, 15, T[62]); + b = II(b, c, d, a, M_offset_9, 21, T[63]); + + // Intermediate hash value + H[0] = (H[0] + a) | 0; + H[1] = (H[1] + b) | 0; + H[2] = (H[2] + c) | 0; + H[3] = (H[3] + d) | 0; + }, + + _doFinalize: function () { + // Shortcuts + var data = this._data; + var dataWords = data.words; + + var nBitsTotal = this._nDataBytes * 8; + var nBitsLeft = data.sigBytes * 8; + + // Add padding + dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); + + var nBitsTotalH = Math.floor(nBitsTotal / 0x100000000); + var nBitsTotalL = nBitsTotal; + dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = ( + (((nBitsTotalH << 8) | (nBitsTotalH >>> 24)) & 0x00ff00ff) | + (((nBitsTotalH << 24) | (nBitsTotalH >>> 8)) & 0xff00ff00) + ); + dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( + (((nBitsTotalL << 8) | (nBitsTotalL >>> 24)) & 0x00ff00ff) | + (((nBitsTotalL << 24) | (nBitsTotalL >>> 8)) & 0xff00ff00) + ); + + data.sigBytes = (dataWords.length + 1) * 4; + + // Hash final blocks + this._process(); + + // Shortcuts + var hash = this._hash; + var H = hash.words; + + // Swap endian + for (var i = 0; i < 4; i++) { + // Shortcut + var H_i = H[i]; + + H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | + (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); + } + + // Return final computed hash + return hash; + }, + + clone: function () { + var clone = Hasher.clone.call(this); + clone._hash = this._hash.clone(); + + return clone; + } + }); + + function FF(a, b, c, d, x, s, t) { + var n = a + ((b & c) | (~b & d)) + x + t; + return ((n << s) | (n >>> (32 - s))) + b; + } + + function GG(a, b, c, d, x, s, t) { + var n = a + ((b & d) | (c & ~d)) + x + t; + return ((n << s) | (n >>> (32 - s))) + b; + } + + function HH(a, b, c, d, x, s, t) { + var n = a + (b ^ c ^ d) + x + t; + return ((n << s) | (n >>> (32 - s))) + b; + } + + function II(a, b, c, d, x, s, t) { + var n = a + (c ^ (b | ~d)) + x + t; + return ((n << s) | (n >>> (32 - s))) + b; + } + + /** + * Shortcut function to the hasher's object interface. + * + * @param {WordArray|string} message The message to hash. + * + * @return {WordArray} The hash. + * + * @static + * + * @example + * + * var hash = CryptoJS.MD5('message'); + * var hash = CryptoJS.MD5(wordArray); + */ + C.MD5 = Hasher._createHelper(MD5); + + /** + * Shortcut function to the HMAC's object interface. + * + * @param {WordArray|string} message The message to hash. + * @param {WordArray|string} key The secret key. + * + * @return {WordArray} The HMAC. + * + * @static + * + * @example + * + * var hmac = CryptoJS.HmacMD5(message, key); + */ + C.HmacMD5 = Hasher._createHmacHelper(MD5); + }(Math)); + + + return CryptoJS.MD5; + +})); + +/***/ }), +/* 20 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14)); + } + else {} +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var Hasher = C_lib.Hasher; + var C_algo = C.algo; + + // Reusable object + var W = []; + + /** + * SHA-1 hash algorithm. + */ + var SHA1 = C_algo.SHA1 = Hasher.extend({ + _doReset: function () { + this._hash = new WordArray.init([ + 0x67452301, 0xefcdab89, + 0x98badcfe, 0x10325476, + 0xc3d2e1f0 + ]); + }, + + _doProcessBlock: function (M, offset) { + // Shortcut + var H = this._hash.words; + + // Working variables + var a = H[0]; + var b = H[1]; + var c = H[2]; + var d = H[3]; + var e = H[4]; + + // Computation + for (var i = 0; i < 80; i++) { + if (i < 16) { + W[i] = M[offset + i] | 0; + } else { + var n = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; + W[i] = (n << 1) | (n >>> 31); + } + + var t = ((a << 5) | (a >>> 27)) + e + W[i]; + if (i < 20) { + t += ((b & c) | (~b & d)) + 0x5a827999; + } else if (i < 40) { + t += (b ^ c ^ d) + 0x6ed9eba1; + } else if (i < 60) { + t += ((b & c) | (b & d) | (c & d)) - 0x70e44324; + } else /* if (i < 80) */ { + t += (b ^ c ^ d) - 0x359d3e2a; + } + + e = d; + d = c; + c = (b << 30) | (b >>> 2); + b = a; + a = t; + } + + // Intermediate hash value + H[0] = (H[0] + a) | 0; + H[1] = (H[1] + b) | 0; + H[2] = (H[2] + c) | 0; + H[3] = (H[3] + d) | 0; + H[4] = (H[4] + e) | 0; + }, + + _doFinalize: function () { + // Shortcuts + var data = this._data; + var dataWords = data.words; + + var nBitsTotal = this._nDataBytes * 8; + var nBitsLeft = data.sigBytes * 8; + + // Add padding + dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); + dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000); + dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal; + data.sigBytes = dataWords.length * 4; + + // Hash final blocks + this._process(); + + // Return final computed hash + return this._hash; + }, + + clone: function () { + var clone = Hasher.clone.call(this); + clone._hash = this._hash.clone(); + + return clone; + } + }); + + /** + * Shortcut function to the hasher's object interface. + * + * @param {WordArray|string} message The message to hash. + * + * @return {WordArray} The hash. + * + * @static + * + * @example + * + * var hash = CryptoJS.SHA1('message'); + * var hash = CryptoJS.SHA1(wordArray); + */ + C.SHA1 = Hasher._createHelper(SHA1); + + /** + * Shortcut function to the HMAC's object interface. + * + * @param {WordArray|string} message The message to hash. + * @param {WordArray|string} key The secret key. + * + * @return {WordArray} The HMAC. + * + * @static + * + * @example + * + * var hmac = CryptoJS.HmacSHA1(message, key); + */ + C.HmacSHA1 = Hasher._createHmacHelper(SHA1); + }()); + + + return CryptoJS.SHA1; + +})); + +/***/ }), +/* 21 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14)); + } + else {} +}(this, function (CryptoJS) { + + (function (Math) { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var Hasher = C_lib.Hasher; + var C_algo = C.algo; + + // Initialization and round constants tables + var H = []; + var K = []; + + // Compute constants + (function () { + function isPrime(n) { + var sqrtN = Math.sqrt(n); + for (var factor = 2; factor <= sqrtN; factor++) { + if (!(n % factor)) { + return false; + } + } + + return true; + } + + function getFractionalBits(n) { + return ((n - (n | 0)) * 0x100000000) | 0; + } + + var n = 2; + var nPrime = 0; + while (nPrime < 64) { + if (isPrime(n)) { + if (nPrime < 8) { + H[nPrime] = getFractionalBits(Math.pow(n, 1 / 2)); + } + K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3)); + + nPrime++; + } + + n++; + } + }()); + + // Reusable object + var W = []; + + /** + * SHA-256 hash algorithm. + */ + var SHA256 = C_algo.SHA256 = Hasher.extend({ + _doReset: function () { + this._hash = new WordArray.init(H.slice(0)); + }, + + _doProcessBlock: function (M, offset) { + // Shortcut + var H = this._hash.words; + + // Working variables + var a = H[0]; + var b = H[1]; + var c = H[2]; + var d = H[3]; + var e = H[4]; + var f = H[5]; + var g = H[6]; + var h = H[7]; + + // Computation + for (var i = 0; i < 64; i++) { + if (i < 16) { + W[i] = M[offset + i] | 0; + } else { + var gamma0x = W[i - 15]; + var gamma0 = ((gamma0x << 25) | (gamma0x >>> 7)) ^ + ((gamma0x << 14) | (gamma0x >>> 18)) ^ + (gamma0x >>> 3); + + var gamma1x = W[i - 2]; + var gamma1 = ((gamma1x << 15) | (gamma1x >>> 17)) ^ + ((gamma1x << 13) | (gamma1x >>> 19)) ^ + (gamma1x >>> 10); + + W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]; + } + + var ch = (e & f) ^ (~e & g); + var maj = (a & b) ^ (a & c) ^ (b & c); + + var sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22)); + var sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7) | (e >>> 25)); + + var t1 = h + sigma1 + ch + K[i] + W[i]; + var t2 = sigma0 + maj; + + h = g; + g = f; + f = e; + e = (d + t1) | 0; + d = c; + c = b; + b = a; + a = (t1 + t2) | 0; + } + + // Intermediate hash value + H[0] = (H[0] + a) | 0; + H[1] = (H[1] + b) | 0; + H[2] = (H[2] + c) | 0; + H[3] = (H[3] + d) | 0; + H[4] = (H[4] + e) | 0; + H[5] = (H[5] + f) | 0; + H[6] = (H[6] + g) | 0; + H[7] = (H[7] + h) | 0; + }, + + _doFinalize: function () { + // Shortcuts + var data = this._data; + var dataWords = data.words; + + var nBitsTotal = this._nDataBytes * 8; + var nBitsLeft = data.sigBytes * 8; + + // Add padding + dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); + dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000); + dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal; + data.sigBytes = dataWords.length * 4; + + // Hash final blocks + this._process(); + + // Return final computed hash + return this._hash; + }, + + clone: function () { + var clone = Hasher.clone.call(this); + clone._hash = this._hash.clone(); + + return clone; + } + }); + + /** + * Shortcut function to the hasher's object interface. + * + * @param {WordArray|string} message The message to hash. + * + * @return {WordArray} The hash. + * + * @static + * + * @example + * + * var hash = CryptoJS.SHA256('message'); + * var hash = CryptoJS.SHA256(wordArray); + */ + C.SHA256 = Hasher._createHelper(SHA256); + + /** + * Shortcut function to the HMAC's object interface. + * + * @param {WordArray|string} message The message to hash. + * @param {WordArray|string} key The secret key. + * + * @return {WordArray} The HMAC. + * + * @static + * + * @example + * + * var hmac = CryptoJS.HmacSHA256(message, key); + */ + C.HmacSHA256 = Hasher._createHmacHelper(SHA256); + }(Math)); + + + return CryptoJS.SHA256; + +})); + +/***/ }), +/* 22 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory, undef) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14), __webpack_require__(21)); + } + else {} +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var C_algo = C.algo; + var SHA256 = C_algo.SHA256; + + /** + * SHA-224 hash algorithm. + */ + var SHA224 = C_algo.SHA224 = SHA256.extend({ + _doReset: function () { + this._hash = new WordArray.init([ + 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, + 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 + ]); + }, + + _doFinalize: function () { + var hash = SHA256._doFinalize.call(this); + + hash.sigBytes -= 4; + + return hash; + } + }); + + /** + * Shortcut function to the hasher's object interface. + * + * @param {WordArray|string} message The message to hash. + * + * @return {WordArray} The hash. + * + * @static + * + * @example + * + * var hash = CryptoJS.SHA224('message'); + * var hash = CryptoJS.SHA224(wordArray); + */ + C.SHA224 = SHA256._createHelper(SHA224); + + /** + * Shortcut function to the HMAC's object interface. + * + * @param {WordArray|string} message The message to hash. + * @param {WordArray|string} key The secret key. + * + * @return {WordArray} The HMAC. + * + * @static + * + * @example + * + * var hmac = CryptoJS.HmacSHA224(message, key); + */ + C.HmacSHA224 = SHA256._createHmacHelper(SHA224); + }()); + + + return CryptoJS.SHA224; + +})); + +/***/ }), +/* 23 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory, undef) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14), __webpack_require__(15)); + } + else {} +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var Hasher = C_lib.Hasher; + var C_x64 = C.x64; + var X64Word = C_x64.Word; + var X64WordArray = C_x64.WordArray; + var C_algo = C.algo; + + function X64Word_create() { + return X64Word.create.apply(X64Word, arguments); + } + + // Constants + var K = [ + X64Word_create(0x428a2f98, 0xd728ae22), X64Word_create(0x71374491, 0x23ef65cd), + X64Word_create(0xb5c0fbcf, 0xec4d3b2f), X64Word_create(0xe9b5dba5, 0x8189dbbc), + X64Word_create(0x3956c25b, 0xf348b538), X64Word_create(0x59f111f1, 0xb605d019), + X64Word_create(0x923f82a4, 0xaf194f9b), X64Word_create(0xab1c5ed5, 0xda6d8118), + X64Word_create(0xd807aa98, 0xa3030242), X64Word_create(0x12835b01, 0x45706fbe), + X64Word_create(0x243185be, 0x4ee4b28c), X64Word_create(0x550c7dc3, 0xd5ffb4e2), + X64Word_create(0x72be5d74, 0xf27b896f), X64Word_create(0x80deb1fe, 0x3b1696b1), + X64Word_create(0x9bdc06a7, 0x25c71235), X64Word_create(0xc19bf174, 0xcf692694), + X64Word_create(0xe49b69c1, 0x9ef14ad2), X64Word_create(0xefbe4786, 0x384f25e3), + X64Word_create(0x0fc19dc6, 0x8b8cd5b5), X64Word_create(0x240ca1cc, 0x77ac9c65), + X64Word_create(0x2de92c6f, 0x592b0275), X64Word_create(0x4a7484aa, 0x6ea6e483), + X64Word_create(0x5cb0a9dc, 0xbd41fbd4), X64Word_create(0x76f988da, 0x831153b5), + X64Word_create(0x983e5152, 0xee66dfab), X64Word_create(0xa831c66d, 0x2db43210), + X64Word_create(0xb00327c8, 0x98fb213f), X64Word_create(0xbf597fc7, 0xbeef0ee4), + X64Word_create(0xc6e00bf3, 0x3da88fc2), X64Word_create(0xd5a79147, 0x930aa725), + X64Word_create(0x06ca6351, 0xe003826f), X64Word_create(0x14292967, 0x0a0e6e70), + X64Word_create(0x27b70a85, 0x46d22ffc), X64Word_create(0x2e1b2138, 0x5c26c926), + X64Word_create(0x4d2c6dfc, 0x5ac42aed), X64Word_create(0x53380d13, 0x9d95b3df), + X64Word_create(0x650a7354, 0x8baf63de), X64Word_create(0x766a0abb, 0x3c77b2a8), + X64Word_create(0x81c2c92e, 0x47edaee6), X64Word_create(0x92722c85, 0x1482353b), + X64Word_create(0xa2bfe8a1, 0x4cf10364), X64Word_create(0xa81a664b, 0xbc423001), + X64Word_create(0xc24b8b70, 0xd0f89791), X64Word_create(0xc76c51a3, 0x0654be30), + X64Word_create(0xd192e819, 0xd6ef5218), X64Word_create(0xd6990624, 0x5565a910), + X64Word_create(0xf40e3585, 0x5771202a), X64Word_create(0x106aa070, 0x32bbd1b8), + X64Word_create(0x19a4c116, 0xb8d2d0c8), X64Word_create(0x1e376c08, 0x5141ab53), + X64Word_create(0x2748774c, 0xdf8eeb99), X64Word_create(0x34b0bcb5, 0xe19b48a8), + X64Word_create(0x391c0cb3, 0xc5c95a63), X64Word_create(0x4ed8aa4a, 0xe3418acb), + X64Word_create(0x5b9cca4f, 0x7763e373), X64Word_create(0x682e6ff3, 0xd6b2b8a3), + X64Word_create(0x748f82ee, 0x5defb2fc), X64Word_create(0x78a5636f, 0x43172f60), + X64Word_create(0x84c87814, 0xa1f0ab72), X64Word_create(0x8cc70208, 0x1a6439ec), + X64Word_create(0x90befffa, 0x23631e28), X64Word_create(0xa4506ceb, 0xde82bde9), + X64Word_create(0xbef9a3f7, 0xb2c67915), X64Word_create(0xc67178f2, 0xe372532b), + X64Word_create(0xca273ece, 0xea26619c), X64Word_create(0xd186b8c7, 0x21c0c207), + X64Word_create(0xeada7dd6, 0xcde0eb1e), X64Word_create(0xf57d4f7f, 0xee6ed178), + X64Word_create(0x06f067aa, 0x72176fba), X64Word_create(0x0a637dc5, 0xa2c898a6), + X64Word_create(0x113f9804, 0xbef90dae), X64Word_create(0x1b710b35, 0x131c471b), + X64Word_create(0x28db77f5, 0x23047d84), X64Word_create(0x32caab7b, 0x40c72493), + X64Word_create(0x3c9ebe0a, 0x15c9bebc), X64Word_create(0x431d67c4, 0x9c100d4c), + X64Word_create(0x4cc5d4be, 0xcb3e42b6), X64Word_create(0x597f299c, 0xfc657e2a), + X64Word_create(0x5fcb6fab, 0x3ad6faec), X64Word_create(0x6c44198c, 0x4a475817) + ]; + + // Reusable objects + var W = []; + (function () { + for (var i = 0; i < 80; i++) { + W[i] = X64Word_create(); + } + }()); + + /** + * SHA-512 hash algorithm. + */ + var SHA512 = C_algo.SHA512 = Hasher.extend({ + _doReset: function () { + this._hash = new X64WordArray.init([ + new X64Word.init(0x6a09e667, 0xf3bcc908), new X64Word.init(0xbb67ae85, 0x84caa73b), + new X64Word.init(0x3c6ef372, 0xfe94f82b), new X64Word.init(0xa54ff53a, 0x5f1d36f1), + new X64Word.init(0x510e527f, 0xade682d1), new X64Word.init(0x9b05688c, 0x2b3e6c1f), + new X64Word.init(0x1f83d9ab, 0xfb41bd6b), new X64Word.init(0x5be0cd19, 0x137e2179) + ]); + }, + + _doProcessBlock: function (M, offset) { + // Shortcuts + var H = this._hash.words; + + var H0 = H[0]; + var H1 = H[1]; + var H2 = H[2]; + var H3 = H[3]; + var H4 = H[4]; + var H5 = H[5]; + var H6 = H[6]; + var H7 = H[7]; + + var H0h = H0.high; + var H0l = H0.low; + var H1h = H1.high; + var H1l = H1.low; + var H2h = H2.high; + var H2l = H2.low; + var H3h = H3.high; + var H3l = H3.low; + var H4h = H4.high; + var H4l = H4.low; + var H5h = H5.high; + var H5l = H5.low; + var H6h = H6.high; + var H6l = H6.low; + var H7h = H7.high; + var H7l = H7.low; + + // Working variables + var ah = H0h; + var al = H0l; + var bh = H1h; + var bl = H1l; + var ch = H2h; + var cl = H2l; + var dh = H3h; + var dl = H3l; + var eh = H4h; + var el = H4l; + var fh = H5h; + var fl = H5l; + var gh = H6h; + var gl = H6l; + var hh = H7h; + var hl = H7l; + + // Rounds + for (var i = 0; i < 80; i++) { + // Shortcut + var Wi = W[i]; + + // Extend message + if (i < 16) { + var Wih = Wi.high = M[offset + i * 2] | 0; + var Wil = Wi.low = M[offset + i * 2 + 1] | 0; + } else { + // Gamma0 + var gamma0x = W[i - 15]; + var gamma0xh = gamma0x.high; + var gamma0xl = gamma0x.low; + var gamma0h = ((gamma0xh >>> 1) | (gamma0xl << 31)) ^ ((gamma0xh >>> 8) | (gamma0xl << 24)) ^ (gamma0xh >>> 7); + var gamma0l = ((gamma0xl >>> 1) | (gamma0xh << 31)) ^ ((gamma0xl >>> 8) | (gamma0xh << 24)) ^ ((gamma0xl >>> 7) | (gamma0xh << 25)); + + // Gamma1 + var gamma1x = W[i - 2]; + var gamma1xh = gamma1x.high; + var gamma1xl = gamma1x.low; + var gamma1h = ((gamma1xh >>> 19) | (gamma1xl << 13)) ^ ((gamma1xh << 3) | (gamma1xl >>> 29)) ^ (gamma1xh >>> 6); + var gamma1l = ((gamma1xl >>> 19) | (gamma1xh << 13)) ^ ((gamma1xl << 3) | (gamma1xh >>> 29)) ^ ((gamma1xl >>> 6) | (gamma1xh << 26)); + + // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] + var Wi7 = W[i - 7]; + var Wi7h = Wi7.high; + var Wi7l = Wi7.low; + + var Wi16 = W[i - 16]; + var Wi16h = Wi16.high; + var Wi16l = Wi16.low; + + var Wil = gamma0l + Wi7l; + var Wih = gamma0h + Wi7h + ((Wil >>> 0) < (gamma0l >>> 0) ? 1 : 0); + var Wil = Wil + gamma1l; + var Wih = Wih + gamma1h + ((Wil >>> 0) < (gamma1l >>> 0) ? 1 : 0); + var Wil = Wil + Wi16l; + var Wih = Wih + Wi16h + ((Wil >>> 0) < (Wi16l >>> 0) ? 1 : 0); + + Wi.high = Wih; + Wi.low = Wil; + } + + var chh = (eh & fh) ^ (~eh & gh); + var chl = (el & fl) ^ (~el & gl); + var majh = (ah & bh) ^ (ah & ch) ^ (bh & ch); + var majl = (al & bl) ^ (al & cl) ^ (bl & cl); + + var sigma0h = ((ah >>> 28) | (al << 4)) ^ ((ah << 30) | (al >>> 2)) ^ ((ah << 25) | (al >>> 7)); + var sigma0l = ((al >>> 28) | (ah << 4)) ^ ((al << 30) | (ah >>> 2)) ^ ((al << 25) | (ah >>> 7)); + var sigma1h = ((eh >>> 14) | (el << 18)) ^ ((eh >>> 18) | (el << 14)) ^ ((eh << 23) | (el >>> 9)); + var sigma1l = ((el >>> 14) | (eh << 18)) ^ ((el >>> 18) | (eh << 14)) ^ ((el << 23) | (eh >>> 9)); + + // t1 = h + sigma1 + ch + K[i] + W[i] + var Ki = K[i]; + var Kih = Ki.high; + var Kil = Ki.low; + + var t1l = hl + sigma1l; + var t1h = hh + sigma1h + ((t1l >>> 0) < (hl >>> 0) ? 1 : 0); + var t1l = t1l + chl; + var t1h = t1h + chh + ((t1l >>> 0) < (chl >>> 0) ? 1 : 0); + var t1l = t1l + Kil; + var t1h = t1h + Kih + ((t1l >>> 0) < (Kil >>> 0) ? 1 : 0); + var t1l = t1l + Wil; + var t1h = t1h + Wih + ((t1l >>> 0) < (Wil >>> 0) ? 1 : 0); + + // t2 = sigma0 + maj + var t2l = sigma0l + majl; + var t2h = sigma0h + majh + ((t2l >>> 0) < (sigma0l >>> 0) ? 1 : 0); + + // Update working variables + hh = gh; + hl = gl; + gh = fh; + gl = fl; + fh = eh; + fl = el; + el = (dl + t1l) | 0; + eh = (dh + t1h + ((el >>> 0) < (dl >>> 0) ? 1 : 0)) | 0; + dh = ch; + dl = cl; + ch = bh; + cl = bl; + bh = ah; + bl = al; + al = (t1l + t2l) | 0; + ah = (t1h + t2h + ((al >>> 0) < (t1l >>> 0) ? 1 : 0)) | 0; + } + + // Intermediate hash value + H0l = H0.low = (H0l + al); + H0.high = (H0h + ah + ((H0l >>> 0) < (al >>> 0) ? 1 : 0)); + H1l = H1.low = (H1l + bl); + H1.high = (H1h + bh + ((H1l >>> 0) < (bl >>> 0) ? 1 : 0)); + H2l = H2.low = (H2l + cl); + H2.high = (H2h + ch + ((H2l >>> 0) < (cl >>> 0) ? 1 : 0)); + H3l = H3.low = (H3l + dl); + H3.high = (H3h + dh + ((H3l >>> 0) < (dl >>> 0) ? 1 : 0)); + H4l = H4.low = (H4l + el); + H4.high = (H4h + eh + ((H4l >>> 0) < (el >>> 0) ? 1 : 0)); + H5l = H5.low = (H5l + fl); + H5.high = (H5h + fh + ((H5l >>> 0) < (fl >>> 0) ? 1 : 0)); + H6l = H6.low = (H6l + gl); + H6.high = (H6h + gh + ((H6l >>> 0) < (gl >>> 0) ? 1 : 0)); + H7l = H7.low = (H7l + hl); + H7.high = (H7h + hh + ((H7l >>> 0) < (hl >>> 0) ? 1 : 0)); + }, + + _doFinalize: function () { + // Shortcuts + var data = this._data; + var dataWords = data.words; + + var nBitsTotal = this._nDataBytes * 8; + var nBitsLeft = data.sigBytes * 8; + + // Add padding + dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); + dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 30] = Math.floor(nBitsTotal / 0x100000000); + dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 31] = nBitsTotal; + data.sigBytes = dataWords.length * 4; + + // Hash final blocks + this._process(); + + // Convert hash to 32-bit word array before returning + var hash = this._hash.toX32(); + + // Return final computed hash + return hash; + }, + + clone: function () { + var clone = Hasher.clone.call(this); + clone._hash = this._hash.clone(); + + return clone; + }, + + blockSize: 1024/32 + }); + + /** + * Shortcut function to the hasher's object interface. + * + * @param {WordArray|string} message The message to hash. + * + * @return {WordArray} The hash. + * + * @static + * + * @example + * + * var hash = CryptoJS.SHA512('message'); + * var hash = CryptoJS.SHA512(wordArray); + */ + C.SHA512 = Hasher._createHelper(SHA512); + + /** + * Shortcut function to the HMAC's object interface. + * + * @param {WordArray|string} message The message to hash. + * @param {WordArray|string} key The secret key. + * + * @return {WordArray} The HMAC. + * + * @static + * + * @example + * + * var hmac = CryptoJS.HmacSHA512(message, key); + */ + C.HmacSHA512 = Hasher._createHmacHelper(SHA512); + }()); + + + return CryptoJS.SHA512; + +})); + +/***/ }), +/* 24 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory, undef) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14), __webpack_require__(15), __webpack_require__(23)); + } + else {} +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_x64 = C.x64; + var X64Word = C_x64.Word; + var X64WordArray = C_x64.WordArray; + var C_algo = C.algo; + var SHA512 = C_algo.SHA512; + + /** + * SHA-384 hash algorithm. + */ + var SHA384 = C_algo.SHA384 = SHA512.extend({ + _doReset: function () { + this._hash = new X64WordArray.init([ + new X64Word.init(0xcbbb9d5d, 0xc1059ed8), new X64Word.init(0x629a292a, 0x367cd507), + new X64Word.init(0x9159015a, 0x3070dd17), new X64Word.init(0x152fecd8, 0xf70e5939), + new X64Word.init(0x67332667, 0xffc00b31), new X64Word.init(0x8eb44a87, 0x68581511), + new X64Word.init(0xdb0c2e0d, 0x64f98fa7), new X64Word.init(0x47b5481d, 0xbefa4fa4) + ]); + }, + + _doFinalize: function () { + var hash = SHA512._doFinalize.call(this); + + hash.sigBytes -= 16; + + return hash; + } + }); + + /** + * Shortcut function to the hasher's object interface. + * + * @param {WordArray|string} message The message to hash. + * + * @return {WordArray} The hash. + * + * @static + * + * @example + * + * var hash = CryptoJS.SHA384('message'); + * var hash = CryptoJS.SHA384(wordArray); + */ + C.SHA384 = SHA512._createHelper(SHA384); + + /** + * Shortcut function to the HMAC's object interface. + * + * @param {WordArray|string} message The message to hash. + * @param {WordArray|string} key The secret key. + * + * @return {WordArray} The HMAC. + * + * @static + * + * @example + * + * var hmac = CryptoJS.HmacSHA384(message, key); + */ + C.HmacSHA384 = SHA512._createHmacHelper(SHA384); + }()); + + + return CryptoJS.SHA384; + +})); + +/***/ }), +/* 25 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory, undef) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14), __webpack_require__(15)); + } + else {} +}(this, function (CryptoJS) { + + (function (Math) { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var Hasher = C_lib.Hasher; + var C_x64 = C.x64; + var X64Word = C_x64.Word; + var C_algo = C.algo; + + // Constants tables + var RHO_OFFSETS = []; + var PI_INDEXES = []; + var ROUND_CONSTANTS = []; + + // Compute Constants + (function () { + // Compute rho offset constants + var x = 1, y = 0; + for (var t = 0; t < 24; t++) { + RHO_OFFSETS[x + 5 * y] = ((t + 1) * (t + 2) / 2) % 64; + + var newX = y % 5; + var newY = (2 * x + 3 * y) % 5; + x = newX; + y = newY; + } + + // Compute pi index constants + for (var x = 0; x < 5; x++) { + for (var y = 0; y < 5; y++) { + PI_INDEXES[x + 5 * y] = y + ((2 * x + 3 * y) % 5) * 5; + } + } + + // Compute round constants + var LFSR = 0x01; + for (var i = 0; i < 24; i++) { + var roundConstantMsw = 0; + var roundConstantLsw = 0; + + for (var j = 0; j < 7; j++) { + if (LFSR & 0x01) { + var bitPosition = (1 << j) - 1; + if (bitPosition < 32) { + roundConstantLsw ^= 1 << bitPosition; + } else /* if (bitPosition >= 32) */ { + roundConstantMsw ^= 1 << (bitPosition - 32); + } + } + + // Compute next LFSR + if (LFSR & 0x80) { + // Primitive polynomial over GF(2): x^8 + x^6 + x^5 + x^4 + 1 + LFSR = (LFSR << 1) ^ 0x71; + } else { + LFSR <<= 1; + } + } + + ROUND_CONSTANTS[i] = X64Word.create(roundConstantMsw, roundConstantLsw); + } + }()); + + // Reusable objects for temporary values + var T = []; + (function () { + for (var i = 0; i < 25; i++) { + T[i] = X64Word.create(); + } + }()); + + /** + * SHA-3 hash algorithm. + */ + var SHA3 = C_algo.SHA3 = Hasher.extend({ + /** + * Configuration options. + * + * @property {number} outputLength + * The desired number of bits in the output hash. + * Only values permitted are: 224, 256, 384, 512. + * Default: 512 + */ + cfg: Hasher.cfg.extend({ + outputLength: 512 + }), + + _doReset: function () { + var state = this._state = [] + for (var i = 0; i < 25; i++) { + state[i] = new X64Word.init(); + } + + this.blockSize = (1600 - 2 * this.cfg.outputLength) / 32; + }, + + _doProcessBlock: function (M, offset) { + // Shortcuts + var state = this._state; + var nBlockSizeLanes = this.blockSize / 2; + + // Absorb + for (var i = 0; i < nBlockSizeLanes; i++) { + // Shortcuts + var M2i = M[offset + 2 * i]; + var M2i1 = M[offset + 2 * i + 1]; + + // Swap endian + M2i = ( + (((M2i << 8) | (M2i >>> 24)) & 0x00ff00ff) | + (((M2i << 24) | (M2i >>> 8)) & 0xff00ff00) + ); + M2i1 = ( + (((M2i1 << 8) | (M2i1 >>> 24)) & 0x00ff00ff) | + (((M2i1 << 24) | (M2i1 >>> 8)) & 0xff00ff00) + ); + + // Absorb message into state + var lane = state[i]; + lane.high ^= M2i1; + lane.low ^= M2i; + } + + // Rounds + for (var round = 0; round < 24; round++) { + // Theta + for (var x = 0; x < 5; x++) { + // Mix column lanes + var tMsw = 0, tLsw = 0; + for (var y = 0; y < 5; y++) { + var lane = state[x + 5 * y]; + tMsw ^= lane.high; + tLsw ^= lane.low; + } + + // Temporary values + var Tx = T[x]; + Tx.high = tMsw; + Tx.low = tLsw; + } + for (var x = 0; x < 5; x++) { + // Shortcuts + var Tx4 = T[(x + 4) % 5]; + var Tx1 = T[(x + 1) % 5]; + var Tx1Msw = Tx1.high; + var Tx1Lsw = Tx1.low; + + // Mix surrounding columns + var tMsw = Tx4.high ^ ((Tx1Msw << 1) | (Tx1Lsw >>> 31)); + var tLsw = Tx4.low ^ ((Tx1Lsw << 1) | (Tx1Msw >>> 31)); + for (var y = 0; y < 5; y++) { + var lane = state[x + 5 * y]; + lane.high ^= tMsw; + lane.low ^= tLsw; + } + } + + // Rho Pi + for (var laneIndex = 1; laneIndex < 25; laneIndex++) { + // Shortcuts + var lane = state[laneIndex]; + var laneMsw = lane.high; + var laneLsw = lane.low; + var rhoOffset = RHO_OFFSETS[laneIndex]; + + // Rotate lanes + if (rhoOffset < 32) { + var tMsw = (laneMsw << rhoOffset) | (laneLsw >>> (32 - rhoOffset)); + var tLsw = (laneLsw << rhoOffset) | (laneMsw >>> (32 - rhoOffset)); + } else /* if (rhoOffset >= 32) */ { + var tMsw = (laneLsw << (rhoOffset - 32)) | (laneMsw >>> (64 - rhoOffset)); + var tLsw = (laneMsw << (rhoOffset - 32)) | (laneLsw >>> (64 - rhoOffset)); + } + + // Transpose lanes + var TPiLane = T[PI_INDEXES[laneIndex]]; + TPiLane.high = tMsw; + TPiLane.low = tLsw; + } + + // Rho pi at x = y = 0 + var T0 = T[0]; + var state0 = state[0]; + T0.high = state0.high; + T0.low = state0.low; + + // Chi + for (var x = 0; x < 5; x++) { + for (var y = 0; y < 5; y++) { + // Shortcuts + var laneIndex = x + 5 * y; + var lane = state[laneIndex]; + var TLane = T[laneIndex]; + var Tx1Lane = T[((x + 1) % 5) + 5 * y]; + var Tx2Lane = T[((x + 2) % 5) + 5 * y]; + + // Mix rows + lane.high = TLane.high ^ (~Tx1Lane.high & Tx2Lane.high); + lane.low = TLane.low ^ (~Tx1Lane.low & Tx2Lane.low); + } + } + + // Iota + var lane = state[0]; + var roundConstant = ROUND_CONSTANTS[round]; + lane.high ^= roundConstant.high; + lane.low ^= roundConstant.low;; + } + }, + + _doFinalize: function () { + // Shortcuts + var data = this._data; + var dataWords = data.words; + var nBitsTotal = this._nDataBytes * 8; + var nBitsLeft = data.sigBytes * 8; + var blockSizeBits = this.blockSize * 32; + + // Add padding + dataWords[nBitsLeft >>> 5] |= 0x1 << (24 - nBitsLeft % 32); + dataWords[((Math.ceil((nBitsLeft + 1) / blockSizeBits) * blockSizeBits) >>> 5) - 1] |= 0x80; + data.sigBytes = dataWords.length * 4; + + // Hash final blocks + this._process(); + + // Shortcuts + var state = this._state; + var outputLengthBytes = this.cfg.outputLength / 8; + var outputLengthLanes = outputLengthBytes / 8; + + // Squeeze + var hashWords = []; + for (var i = 0; i < outputLengthLanes; i++) { + // Shortcuts + var lane = state[i]; + var laneMsw = lane.high; + var laneLsw = lane.low; + + // Swap endian + laneMsw = ( + (((laneMsw << 8) | (laneMsw >>> 24)) & 0x00ff00ff) | + (((laneMsw << 24) | (laneMsw >>> 8)) & 0xff00ff00) + ); + laneLsw = ( + (((laneLsw << 8) | (laneLsw >>> 24)) & 0x00ff00ff) | + (((laneLsw << 24) | (laneLsw >>> 8)) & 0xff00ff00) + ); + + // Squeeze state to retrieve hash + hashWords.push(laneLsw); + hashWords.push(laneMsw); + } + + // Return final computed hash + return new WordArray.init(hashWords, outputLengthBytes); + }, + + clone: function () { + var clone = Hasher.clone.call(this); + + var state = clone._state = this._state.slice(0); + for (var i = 0; i < 25; i++) { + state[i] = state[i].clone(); + } + + return clone; + } + }); + + /** + * Shortcut function to the hasher's object interface. + * + * @param {WordArray|string} message The message to hash. + * + * @return {WordArray} The hash. + * + * @static + * + * @example + * + * var hash = CryptoJS.SHA3('message'); + * var hash = CryptoJS.SHA3(wordArray); + */ + C.SHA3 = Hasher._createHelper(SHA3); + + /** + * Shortcut function to the HMAC's object interface. + * + * @param {WordArray|string} message The message to hash. + * @param {WordArray|string} key The secret key. + * + * @return {WordArray} The HMAC. + * + * @static + * + * @example + * + * var hmac = CryptoJS.HmacSHA3(message, key); + */ + C.HmacSHA3 = Hasher._createHmacHelper(SHA3); + }(Math)); + + + return CryptoJS.SHA3; + +})); + +/***/ }), +/* 26 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14)); + } + else {} +}(this, function (CryptoJS) { + + /** @preserve + (c) 2012 by Cédric Mesnil. All rights reserved. + + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + + (function (Math) { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var Hasher = C_lib.Hasher; + var C_algo = C.algo; + + // Constants table + var _zl = WordArray.create([ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, + 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, + 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, + 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13]); + var _zr = WordArray.create([ + 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, + 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, + 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, + 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, + 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11]); + var _sl = WordArray.create([ + 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, + 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, + 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, + 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, + 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 ]); + var _sr = WordArray.create([ + 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, + 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, + 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, + 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, + 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ]); + + var _hl = WordArray.create([ 0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E]); + var _hr = WordArray.create([ 0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000]); + + /** + * RIPEMD160 hash algorithm. + */ + var RIPEMD160 = C_algo.RIPEMD160 = Hasher.extend({ + _doReset: function () { + this._hash = WordArray.create([0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]); + }, + + _doProcessBlock: function (M, offset) { + + // Swap endian + for (var i = 0; i < 16; i++) { + // Shortcuts + var offset_i = offset + i; + var M_offset_i = M[offset_i]; + + // Swap + M[offset_i] = ( + (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | + (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) + ); + } + // Shortcut + var H = this._hash.words; + var hl = _hl.words; + var hr = _hr.words; + var zl = _zl.words; + var zr = _zr.words; + var sl = _sl.words; + var sr = _sr.words; + + // Working variables + var al, bl, cl, dl, el; + var ar, br, cr, dr, er; + + ar = al = H[0]; + br = bl = H[1]; + cr = cl = H[2]; + dr = dl = H[3]; + er = el = H[4]; + // Computation + var t; + for (var i = 0; i < 80; i += 1) { + t = (al + M[offset+zl[i]])|0; + if (i<16){ + t += f1(bl,cl,dl) + hl[0]; + } else if (i<32) { + t += f2(bl,cl,dl) + hl[1]; + } else if (i<48) { + t += f3(bl,cl,dl) + hl[2]; + } else if (i<64) { + t += f4(bl,cl,dl) + hl[3]; + } else {// if (i<80) { + t += f5(bl,cl,dl) + hl[4]; + } + t = t|0; + t = rotl(t,sl[i]); + t = (t+el)|0; + al = el; + el = dl; + dl = rotl(cl, 10); + cl = bl; + bl = t; + + t = (ar + M[offset+zr[i]])|0; + if (i<16){ + t += f5(br,cr,dr) + hr[0]; + } else if (i<32) { + t += f4(br,cr,dr) + hr[1]; + } else if (i<48) { + t += f3(br,cr,dr) + hr[2]; + } else if (i<64) { + t += f2(br,cr,dr) + hr[3]; + } else {// if (i<80) { + t += f1(br,cr,dr) + hr[4]; + } + t = t|0; + t = rotl(t,sr[i]) ; + t = (t+er)|0; + ar = er; + er = dr; + dr = rotl(cr, 10); + cr = br; + br = t; + } + // Intermediate hash value + t = (H[1] + cl + dr)|0; + H[1] = (H[2] + dl + er)|0; + H[2] = (H[3] + el + ar)|0; + H[3] = (H[4] + al + br)|0; + H[4] = (H[0] + bl + cr)|0; + H[0] = t; + }, + + _doFinalize: function () { + // Shortcuts + var data = this._data; + var dataWords = data.words; + + var nBitsTotal = this._nDataBytes * 8; + var nBitsLeft = data.sigBytes * 8; + + // Add padding + dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); + dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( + (((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) | + (((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00) + ); + data.sigBytes = (dataWords.length + 1) * 4; + + // Hash final blocks + this._process(); + + // Shortcuts + var hash = this._hash; + var H = hash.words; + + // Swap endian + for (var i = 0; i < 5; i++) { + // Shortcut + var H_i = H[i]; + + // Swap + H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | + (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); + } + + // Return final computed hash + return hash; + }, + + clone: function () { + var clone = Hasher.clone.call(this); + clone._hash = this._hash.clone(); + + return clone; + } + }); + + + function f1(x, y, z) { + return ((x) ^ (y) ^ (z)); + + } + + function f2(x, y, z) { + return (((x)&(y)) | ((~x)&(z))); + } + + function f3(x, y, z) { + return (((x) | (~(y))) ^ (z)); + } + + function f4(x, y, z) { + return (((x) & (z)) | ((y)&(~(z)))); + } + + function f5(x, y, z) { + return ((x) ^ ((y) |(~(z)))); + + } + + function rotl(x,n) { + return (x<>>(32-n)); + } + + + /** + * Shortcut function to the hasher's object interface. + * + * @param {WordArray|string} message The message to hash. + * + * @return {WordArray} The hash. + * + * @static + * + * @example + * + * var hash = CryptoJS.RIPEMD160('message'); + * var hash = CryptoJS.RIPEMD160(wordArray); + */ + C.RIPEMD160 = Hasher._createHelper(RIPEMD160); + + /** + * Shortcut function to the HMAC's object interface. + * + * @param {WordArray|string} message The message to hash. + * @param {WordArray|string} key The secret key. + * + * @return {WordArray} The HMAC. + * + * @static + * + * @example + * + * var hmac = CryptoJS.HmacRIPEMD160(message, key); + */ + C.HmacRIPEMD160 = Hasher._createHmacHelper(RIPEMD160); + }(Math)); + + + return CryptoJS.RIPEMD160; + +})); + +/***/ }), +/* 27 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14)); + } + else {} +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var Base = C_lib.Base; + var C_enc = C.enc; + var Utf8 = C_enc.Utf8; + var C_algo = C.algo; + + /** + * HMAC algorithm. + */ + var HMAC = C_algo.HMAC = Base.extend({ + /** + * Initializes a newly created HMAC. + * + * @param {Hasher} hasher The hash algorithm to use. + * @param {WordArray|string} key The secret key. + * + * @example + * + * var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key); + */ + init: function (hasher, key) { + // Init hasher + hasher = this._hasher = new hasher.init(); + + // Convert string to WordArray, else assume WordArray already + if (typeof key == 'string') { + key = Utf8.parse(key); + } + + // Shortcuts + var hasherBlockSize = hasher.blockSize; + var hasherBlockSizeBytes = hasherBlockSize * 4; + + // Allow arbitrary length keys + if (key.sigBytes > hasherBlockSizeBytes) { + key = hasher.finalize(key); + } + + // Clamp excess bits + key.clamp(); + + // Clone key for inner and outer pads + var oKey = this._oKey = key.clone(); + var iKey = this._iKey = key.clone(); + + // Shortcuts + var oKeyWords = oKey.words; + var iKeyWords = iKey.words; + + // XOR keys with pad constants + for (var i = 0; i < hasherBlockSize; i++) { + oKeyWords[i] ^= 0x5c5c5c5c; + iKeyWords[i] ^= 0x36363636; + } + oKey.sigBytes = iKey.sigBytes = hasherBlockSizeBytes; + + // Set initial values + this.reset(); + }, + + /** + * Resets this HMAC to its initial state. + * + * @example + * + * hmacHasher.reset(); + */ + reset: function () { + // Shortcut + var hasher = this._hasher; + + // Reset + hasher.reset(); + hasher.update(this._iKey); + }, + + /** + * Updates this HMAC with a message. + * + * @param {WordArray|string} messageUpdate The message to append. + * + * @return {HMAC} This HMAC instance. + * + * @example + * + * hmacHasher.update('message'); + * hmacHasher.update(wordArray); + */ + update: function (messageUpdate) { + this._hasher.update(messageUpdate); + + // Chainable + return this; + }, + + /** + * Finalizes the HMAC computation. + * Note that the finalize operation is effectively a destructive, read-once operation. + * + * @param {WordArray|string} messageUpdate (Optional) A final message update. + * + * @return {WordArray} The HMAC. + * + * @example + * + * var hmac = hmacHasher.finalize(); + * var hmac = hmacHasher.finalize('message'); + * var hmac = hmacHasher.finalize(wordArray); + */ + finalize: function (messageUpdate) { + // Shortcut + var hasher = this._hasher; + + // Compute HMAC + var innerHash = hasher.finalize(messageUpdate); + hasher.reset(); + var hmac = hasher.finalize(this._oKey.clone().concat(innerHash)); + + return hmac; + } + }); + }()); + + +})); + +/***/ }), +/* 28 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory, undef) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14), __webpack_require__(20), __webpack_require__(27)); + } + else {} +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var Base = C_lib.Base; + var WordArray = C_lib.WordArray; + var C_algo = C.algo; + var SHA1 = C_algo.SHA1; + var HMAC = C_algo.HMAC; + + /** + * Password-Based Key Derivation Function 2 algorithm. + */ + var PBKDF2 = C_algo.PBKDF2 = Base.extend({ + /** + * Configuration options. + * + * @property {number} keySize The key size in words to generate. Default: 4 (128 bits) + * @property {Hasher} hasher The hasher to use. Default: SHA1 + * @property {number} iterations The number of iterations to perform. Default: 1 + */ + cfg: Base.extend({ + keySize: 128/32, + hasher: SHA1, + iterations: 1 + }), + + /** + * Initializes a newly created key derivation function. + * + * @param {Object} cfg (Optional) The configuration options to use for the derivation. + * + * @example + * + * var kdf = CryptoJS.algo.PBKDF2.create(); + * var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8 }); + * var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8, iterations: 1000 }); + */ + init: function (cfg) { + this.cfg = this.cfg.extend(cfg); + }, + + /** + * Computes the Password-Based Key Derivation Function 2. + * + * @param {WordArray|string} password The password. + * @param {WordArray|string} salt A salt. + * + * @return {WordArray} The derived key. + * + * @example + * + * var key = kdf.compute(password, salt); + */ + compute: function (password, salt) { + // Shortcut + var cfg = this.cfg; + + // Init HMAC + var hmac = HMAC.create(cfg.hasher, password); + + // Initial values + var derivedKey = WordArray.create(); + var blockIndex = WordArray.create([0x00000001]); + + // Shortcuts + var derivedKeyWords = derivedKey.words; + var blockIndexWords = blockIndex.words; + var keySize = cfg.keySize; + var iterations = cfg.iterations; + + // Generate key + while (derivedKeyWords.length < keySize) { + var block = hmac.update(salt).finalize(blockIndex); + hmac.reset(); + + // Shortcuts + var blockWords = block.words; + var blockWordsLength = blockWords.length; + + // Iterations + var intermediate = block; + for (var i = 1; i < iterations; i++) { + intermediate = hmac.finalize(intermediate); + hmac.reset(); + + // Shortcut + var intermediateWords = intermediate.words; + + // XOR intermediate with block + for (var j = 0; j < blockWordsLength; j++) { + blockWords[j] ^= intermediateWords[j]; + } + } + + derivedKey.concat(block); + blockIndexWords[0]++; + } + derivedKey.sigBytes = keySize * 4; + + return derivedKey; + } + }); + + /** + * Computes the Password-Based Key Derivation Function 2. + * + * @param {WordArray|string} password The password. + * @param {WordArray|string} salt A salt. + * @param {Object} cfg (Optional) The configuration options to use for this computation. + * + * @return {WordArray} The derived key. + * + * @static + * + * @example + * + * var key = CryptoJS.PBKDF2(password, salt); + * var key = CryptoJS.PBKDF2(password, salt, { keySize: 8 }); + * var key = CryptoJS.PBKDF2(password, salt, { keySize: 8, iterations: 1000 }); + */ + C.PBKDF2 = function (password, salt, cfg) { + return PBKDF2.create(cfg).compute(password, salt); + }; + }()); + + + return CryptoJS.PBKDF2; + +})); + +/***/ }), +/* 29 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory, undef) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14), __webpack_require__(20), __webpack_require__(27)); + } + else {} +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var Base = C_lib.Base; + var WordArray = C_lib.WordArray; + var C_algo = C.algo; + var MD5 = C_algo.MD5; + + /** + * This key derivation function is meant to conform with EVP_BytesToKey. + * www.openssl.org/docs/crypto/EVP_BytesToKey.html + */ + var EvpKDF = C_algo.EvpKDF = Base.extend({ + /** + * Configuration options. + * + * @property {number} keySize The key size in words to generate. Default: 4 (128 bits) + * @property {Hasher} hasher The hash algorithm to use. Default: MD5 + * @property {number} iterations The number of iterations to perform. Default: 1 + */ + cfg: Base.extend({ + keySize: 128/32, + hasher: MD5, + iterations: 1 + }), + + /** + * Initializes a newly created key derivation function. + * + * @param {Object} cfg (Optional) The configuration options to use for the derivation. + * + * @example + * + * var kdf = CryptoJS.algo.EvpKDF.create(); + * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 }); + * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 }); + */ + init: function (cfg) { + this.cfg = this.cfg.extend(cfg); + }, + + /** + * Derives a key from a password. + * + * @param {WordArray|string} password The password. + * @param {WordArray|string} salt A salt. + * + * @return {WordArray} The derived key. + * + * @example + * + * var key = kdf.compute(password, salt); + */ + compute: function (password, salt) { + // Shortcut + var cfg = this.cfg; + + // Init hasher + var hasher = cfg.hasher.create(); + + // Initial values + var derivedKey = WordArray.create(); + + // Shortcuts + var derivedKeyWords = derivedKey.words; + var keySize = cfg.keySize; + var iterations = cfg.iterations; + + // Generate key + while (derivedKeyWords.length < keySize) { + if (block) { + hasher.update(block); + } + var block = hasher.update(password).finalize(salt); + hasher.reset(); + + // Iterations + for (var i = 1; i < iterations; i++) { + block = hasher.finalize(block); + hasher.reset(); + } + + derivedKey.concat(block); + } + derivedKey.sigBytes = keySize * 4; + + return derivedKey; + } + }); + + /** + * Derives a key from a password. + * + * @param {WordArray|string} password The password. + * @param {WordArray|string} salt A salt. + * @param {Object} cfg (Optional) The configuration options to use for this computation. + * + * @return {WordArray} The derived key. + * + * @static + * + * @example + * + * var key = CryptoJS.EvpKDF(password, salt); + * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8 }); + * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8, iterations: 1000 }); + */ + C.EvpKDF = function (password, salt, cfg) { + return EvpKDF.create(cfg).compute(password, salt); + }; + }()); + + + return CryptoJS.EvpKDF; + +})); + +/***/ }), +/* 30 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory, undef) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14), __webpack_require__(29)); + } + else {} +}(this, function (CryptoJS) { + + /** + * Cipher core components. + */ + CryptoJS.lib.Cipher || (function (undefined) { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var Base = C_lib.Base; + var WordArray = C_lib.WordArray; + var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm; + var C_enc = C.enc; + var Utf8 = C_enc.Utf8; + var Base64 = C_enc.Base64; + var C_algo = C.algo; + var EvpKDF = C_algo.EvpKDF; + + /** + * Abstract base cipher template. + * + * @property {number} keySize This cipher's key size. Default: 4 (128 bits) + * @property {number} ivSize This cipher's IV size. Default: 4 (128 bits) + * @property {number} _ENC_XFORM_MODE A constant representing encryption mode. + * @property {number} _DEC_XFORM_MODE A constant representing decryption mode. + */ + var Cipher = C_lib.Cipher = BufferedBlockAlgorithm.extend({ + /** + * Configuration options. + * + * @property {WordArray} iv The IV to use for this operation. + */ + cfg: Base.extend(), + + /** + * Creates this cipher in encryption mode. + * + * @param {WordArray} key The key. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @return {Cipher} A cipher instance. + * + * @static + * + * @example + * + * var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray }); + */ + createEncryptor: function (key, cfg) { + return this.create(this._ENC_XFORM_MODE, key, cfg); + }, + + /** + * Creates this cipher in decryption mode. + * + * @param {WordArray} key The key. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @return {Cipher} A cipher instance. + * + * @static + * + * @example + * + * var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray }); + */ + createDecryptor: function (key, cfg) { + return this.create(this._DEC_XFORM_MODE, key, cfg); + }, + + /** + * Initializes a newly created cipher. + * + * @param {number} xformMode Either the encryption or decryption transormation mode constant. + * @param {WordArray} key The key. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @example + * + * var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray }); + */ + init: function (xformMode, key, cfg) { + // Apply config defaults + this.cfg = this.cfg.extend(cfg); + + // Store transform mode and key + this._xformMode = xformMode; + this._key = key; + + // Set initial values + this.reset(); + }, + + /** + * Resets this cipher to its initial state. + * + * @example + * + * cipher.reset(); + */ + reset: function () { + // Reset data buffer + BufferedBlockAlgorithm.reset.call(this); + + // Perform concrete-cipher logic + this._doReset(); + }, + + /** + * Adds data to be encrypted or decrypted. + * + * @param {WordArray|string} dataUpdate The data to encrypt or decrypt. + * + * @return {WordArray} The data after processing. + * + * @example + * + * var encrypted = cipher.process('data'); + * var encrypted = cipher.process(wordArray); + */ + process: function (dataUpdate) { + // Append + this._append(dataUpdate); + + // Process available blocks + return this._process(); + }, + + /** + * Finalizes the encryption or decryption process. + * Note that the finalize operation is effectively a destructive, read-once operation. + * + * @param {WordArray|string} dataUpdate The final data to encrypt or decrypt. + * + * @return {WordArray} The data after final processing. + * + * @example + * + * var encrypted = cipher.finalize(); + * var encrypted = cipher.finalize('data'); + * var encrypted = cipher.finalize(wordArray); + */ + finalize: function (dataUpdate) { + // Final data update + if (dataUpdate) { + this._append(dataUpdate); + } + + // Perform concrete-cipher logic + var finalProcessedData = this._doFinalize(); + + return finalProcessedData; + }, + + keySize: 128/32, + + ivSize: 128/32, + + _ENC_XFORM_MODE: 1, + + _DEC_XFORM_MODE: 2, + + /** + * Creates shortcut functions to a cipher's object interface. + * + * @param {Cipher} cipher The cipher to create a helper for. + * + * @return {Object} An object with encrypt and decrypt shortcut functions. + * + * @static + * + * @example + * + * var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES); + */ + _createHelper: (function () { + function selectCipherStrategy(key) { + if (typeof key == 'string') { + return PasswordBasedCipher; + } else { + return SerializableCipher; + } + } + + return function (cipher) { + return { + encrypt: function (message, key, cfg) { + return selectCipherStrategy(key).encrypt(cipher, message, key, cfg); + }, + + decrypt: function (ciphertext, key, cfg) { + return selectCipherStrategy(key).decrypt(cipher, ciphertext, key, cfg); + } + }; + }; + }()) + }); + + /** + * Abstract base stream cipher template. + * + * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 1 (32 bits) + */ + var StreamCipher = C_lib.StreamCipher = Cipher.extend({ + _doFinalize: function () { + // Process partial blocks + var finalProcessedBlocks = this._process(!!'flush'); + + return finalProcessedBlocks; + }, + + blockSize: 1 + }); + + /** + * Mode namespace. + */ + var C_mode = C.mode = {}; + + /** + * Abstract base block cipher mode template. + */ + var BlockCipherMode = C_lib.BlockCipherMode = Base.extend({ + /** + * Creates this mode for encryption. + * + * @param {Cipher} cipher A block cipher instance. + * @param {Array} iv The IV words. + * + * @static + * + * @example + * + * var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words); + */ + createEncryptor: function (cipher, iv) { + return this.Encryptor.create(cipher, iv); + }, + + /** + * Creates this mode for decryption. + * + * @param {Cipher} cipher A block cipher instance. + * @param {Array} iv The IV words. + * + * @static + * + * @example + * + * var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words); + */ + createDecryptor: function (cipher, iv) { + return this.Decryptor.create(cipher, iv); + }, + + /** + * Initializes a newly created mode. + * + * @param {Cipher} cipher A block cipher instance. + * @param {Array} iv The IV words. + * + * @example + * + * var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words); + */ + init: function (cipher, iv) { + this._cipher = cipher; + this._iv = iv; + } + }); + + /** + * Cipher Block Chaining mode. + */ + var CBC = C_mode.CBC = (function () { + /** + * Abstract base CBC mode. + */ + var CBC = BlockCipherMode.extend(); + + /** + * CBC encryptor. + */ + CBC.Encryptor = CBC.extend({ + /** + * Processes the data block at offset. + * + * @param {Array} words The data words to operate on. + * @param {number} offset The offset where the block starts. + * + * @example + * + * mode.processBlock(data.words, offset); + */ + processBlock: function (words, offset) { + // Shortcuts + var cipher = this._cipher; + var blockSize = cipher.blockSize; + + // XOR and encrypt + xorBlock.call(this, words, offset, blockSize); + cipher.encryptBlock(words, offset); + + // Remember this block to use with next block + this._prevBlock = words.slice(offset, offset + blockSize); + } + }); + + /** + * CBC decryptor. + */ + CBC.Decryptor = CBC.extend({ + /** + * Processes the data block at offset. + * + * @param {Array} words The data words to operate on. + * @param {number} offset The offset where the block starts. + * + * @example + * + * mode.processBlock(data.words, offset); + */ + processBlock: function (words, offset) { + // Shortcuts + var cipher = this._cipher; + var blockSize = cipher.blockSize; + + // Remember this block to use with next block + var thisBlock = words.slice(offset, offset + blockSize); + + // Decrypt and XOR + cipher.decryptBlock(words, offset); + xorBlock.call(this, words, offset, blockSize); + + // This block becomes the previous block + this._prevBlock = thisBlock; + } + }); + + function xorBlock(words, offset, blockSize) { + // Shortcut + var iv = this._iv; + + // Choose mixing block + if (iv) { + var block = iv; + + // Remove IV for subsequent blocks + this._iv = undefined; + } else { + var block = this._prevBlock; + } + + // XOR blocks + for (var i = 0; i < blockSize; i++) { + words[offset + i] ^= block[i]; + } + } + + return CBC; + }()); + + /** + * Padding namespace. + */ + var C_pad = C.pad = {}; + + /** + * PKCS #5/7 padding strategy. + */ + var Pkcs7 = C_pad.Pkcs7 = { + /** + * Pads data using the algorithm defined in PKCS #5/7. + * + * @param {WordArray} data The data to pad. + * @param {number} blockSize The multiple that the data should be padded to. + * + * @static + * + * @example + * + * CryptoJS.pad.Pkcs7.pad(wordArray, 4); + */ + pad: function (data, blockSize) { + // Shortcut + var blockSizeBytes = blockSize * 4; + + // Count padding bytes + var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes; + + // Create padding word + var paddingWord = (nPaddingBytes << 24) | (nPaddingBytes << 16) | (nPaddingBytes << 8) | nPaddingBytes; + + // Create padding + var paddingWords = []; + for (var i = 0; i < nPaddingBytes; i += 4) { + paddingWords.push(paddingWord); + } + var padding = WordArray.create(paddingWords, nPaddingBytes); + + // Add padding + data.concat(padding); + }, + + /** + * Unpads data that had been padded using the algorithm defined in PKCS #5/7. + * + * @param {WordArray} data The data to unpad. + * + * @static + * + * @example + * + * CryptoJS.pad.Pkcs7.unpad(wordArray); + */ + unpad: function (data) { + // Get number of padding bytes from last byte + var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; + + // Remove padding + data.sigBytes -= nPaddingBytes; + } + }; + + /** + * Abstract base block cipher template. + * + * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 4 (128 bits) + */ + var BlockCipher = C_lib.BlockCipher = Cipher.extend({ + /** + * Configuration options. + * + * @property {Mode} mode The block mode to use. Default: CBC + * @property {Padding} padding The padding strategy to use. Default: Pkcs7 + */ + cfg: Cipher.cfg.extend({ + mode: CBC, + padding: Pkcs7 + }), + + reset: function () { + // Reset cipher + Cipher.reset.call(this); + + // Shortcuts + var cfg = this.cfg; + var iv = cfg.iv; + var mode = cfg.mode; + + // Reset block mode + if (this._xformMode == this._ENC_XFORM_MODE) { + var modeCreator = mode.createEncryptor; + } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { + var modeCreator = mode.createDecryptor; + // Keep at least one block in the buffer for unpadding + this._minBufferSize = 1; + } + + if (this._mode && this._mode.__creator == modeCreator) { + this._mode.init(this, iv && iv.words); + } else { + this._mode = modeCreator.call(mode, this, iv && iv.words); + this._mode.__creator = modeCreator; + } + }, + + _doProcessBlock: function (words, offset) { + this._mode.processBlock(words, offset); + }, + + _doFinalize: function () { + // Shortcut + var padding = this.cfg.padding; + + // Finalize + if (this._xformMode == this._ENC_XFORM_MODE) { + // Pad data + padding.pad(this._data, this.blockSize); + + // Process final blocks + var finalProcessedBlocks = this._process(!!'flush'); + } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { + // Process final blocks + var finalProcessedBlocks = this._process(!!'flush'); + + // Unpad data + padding.unpad(finalProcessedBlocks); + } + + return finalProcessedBlocks; + }, + + blockSize: 128/32 + }); + + /** + * A collection of cipher parameters. + * + * @property {WordArray} ciphertext The raw ciphertext. + * @property {WordArray} key The key to this ciphertext. + * @property {WordArray} iv The IV used in the ciphering operation. + * @property {WordArray} salt The salt used with a key derivation function. + * @property {Cipher} algorithm The cipher algorithm. + * @property {Mode} mode The block mode used in the ciphering operation. + * @property {Padding} padding The padding scheme used in the ciphering operation. + * @property {number} blockSize The block size of the cipher. + * @property {Format} formatter The default formatting strategy to convert this cipher params object to a string. + */ + var CipherParams = C_lib.CipherParams = Base.extend({ + /** + * Initializes a newly created cipher params object. + * + * @param {Object} cipherParams An object with any of the possible cipher parameters. + * + * @example + * + * var cipherParams = CryptoJS.lib.CipherParams.create({ + * ciphertext: ciphertextWordArray, + * key: keyWordArray, + * iv: ivWordArray, + * salt: saltWordArray, + * algorithm: CryptoJS.algo.AES, + * mode: CryptoJS.mode.CBC, + * padding: CryptoJS.pad.PKCS7, + * blockSize: 4, + * formatter: CryptoJS.format.OpenSSL + * }); + */ + init: function (cipherParams) { + this.mixIn(cipherParams); + }, + + /** + * Converts this cipher params object to a string. + * + * @param {Format} formatter (Optional) The formatting strategy to use. + * + * @return {string} The stringified cipher params. + * + * @throws Error If neither the formatter nor the default formatter is set. + * + * @example + * + * var string = cipherParams + ''; + * var string = cipherParams.toString(); + * var string = cipherParams.toString(CryptoJS.format.OpenSSL); + */ + toString: function (formatter) { + return (formatter || this.formatter).stringify(this); + } + }); + + /** + * Format namespace. + */ + var C_format = C.format = {}; + + /** + * OpenSSL formatting strategy. + */ + var OpenSSLFormatter = C_format.OpenSSL = { + /** + * Converts a cipher params object to an OpenSSL-compatible string. + * + * @param {CipherParams} cipherParams The cipher params object. + * + * @return {string} The OpenSSL-compatible string. + * + * @static + * + * @example + * + * var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams); + */ + stringify: function (cipherParams) { + // Shortcuts + var ciphertext = cipherParams.ciphertext; + var salt = cipherParams.salt; + + // Format + if (salt) { + var wordArray = WordArray.create([0x53616c74, 0x65645f5f]).concat(salt).concat(ciphertext); + } else { + var wordArray = ciphertext; + } + + return wordArray.toString(Base64); + }, + + /** + * Converts an OpenSSL-compatible string to a cipher params object. + * + * @param {string} openSSLStr The OpenSSL-compatible string. + * + * @return {CipherParams} The cipher params object. + * + * @static + * + * @example + * + * var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString); + */ + parse: function (openSSLStr) { + // Parse base64 + var ciphertext = Base64.parse(openSSLStr); + + // Shortcut + var ciphertextWords = ciphertext.words; + + // Test for salt + if (ciphertextWords[0] == 0x53616c74 && ciphertextWords[1] == 0x65645f5f) { + // Extract salt + var salt = WordArray.create(ciphertextWords.slice(2, 4)); + + // Remove salt from ciphertext + ciphertextWords.splice(0, 4); + ciphertext.sigBytes -= 16; + } + + return CipherParams.create({ ciphertext: ciphertext, salt: salt }); + } + }; + + /** + * A cipher wrapper that returns ciphertext as a serializable cipher params object. + */ + var SerializableCipher = C_lib.SerializableCipher = Base.extend({ + /** + * Configuration options. + * + * @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL + */ + cfg: Base.extend({ + format: OpenSSLFormatter + }), + + /** + * Encrypts a message. + * + * @param {Cipher} cipher The cipher algorithm to use. + * @param {WordArray|string} message The message to encrypt. + * @param {WordArray} key The key. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @return {CipherParams} A cipher params object. + * + * @static + * + * @example + * + * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key); + * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv }); + * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL }); + */ + encrypt: function (cipher, message, key, cfg) { + // Apply config defaults + cfg = this.cfg.extend(cfg); + + // Encrypt + var encryptor = cipher.createEncryptor(key, cfg); + var ciphertext = encryptor.finalize(message); + + // Shortcut + var cipherCfg = encryptor.cfg; + + // Create and return serializable cipher params + return CipherParams.create({ + ciphertext: ciphertext, + key: key, + iv: cipherCfg.iv, + algorithm: cipher, + mode: cipherCfg.mode, + padding: cipherCfg.padding, + blockSize: cipher.blockSize, + formatter: cfg.format + }); + }, + + /** + * Decrypts serialized ciphertext. + * + * @param {Cipher} cipher The cipher algorithm to use. + * @param {CipherParams|string} ciphertext The ciphertext to decrypt. + * @param {WordArray} key The key. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @return {WordArray} The plaintext. + * + * @static + * + * @example + * + * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL }); + * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL }); + */ + decrypt: function (cipher, ciphertext, key, cfg) { + // Apply config defaults + cfg = this.cfg.extend(cfg); + + // Convert string to CipherParams + ciphertext = this._parse(ciphertext, cfg.format); + + // Decrypt + var plaintext = cipher.createDecryptor(key, cfg).finalize(ciphertext.ciphertext); + + return plaintext; + }, + + /** + * Converts serialized ciphertext to CipherParams, + * else assumed CipherParams already and returns ciphertext unchanged. + * + * @param {CipherParams|string} ciphertext The ciphertext. + * @param {Formatter} format The formatting strategy to use to parse serialized ciphertext. + * + * @return {CipherParams} The unserialized ciphertext. + * + * @static + * + * @example + * + * var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format); + */ + _parse: function (ciphertext, format) { + if (typeof ciphertext == 'string') { + return format.parse(ciphertext, this); + } else { + return ciphertext; + } + } + }); + + /** + * Key derivation function namespace. + */ + var C_kdf = C.kdf = {}; + + /** + * OpenSSL key derivation function. + */ + var OpenSSLKdf = C_kdf.OpenSSL = { + /** + * Derives a key and IV from a password. + * + * @param {string} password The password to derive from. + * @param {number} keySize The size in words of the key to generate. + * @param {number} ivSize The size in words of the IV to generate. + * @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly. + * + * @return {CipherParams} A cipher params object with the key, IV, and salt. + * + * @static + * + * @example + * + * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32); + * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt'); + */ + execute: function (password, keySize, ivSize, salt) { + // Generate random salt + if (!salt) { + salt = WordArray.random(64/8); + } + + // Derive key and IV + var key = EvpKDF.create({ keySize: keySize + ivSize }).compute(password, salt); + + // Separate key and IV + var iv = WordArray.create(key.words.slice(keySize), ivSize * 4); + key.sigBytes = keySize * 4; + + // Return params + return CipherParams.create({ key: key, iv: iv, salt: salt }); + } + }; + + /** + * A serializable cipher wrapper that derives the key from a password, + * and returns ciphertext as a serializable cipher params object. + */ + var PasswordBasedCipher = C_lib.PasswordBasedCipher = SerializableCipher.extend({ + /** + * Configuration options. + * + * @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL + */ + cfg: SerializableCipher.cfg.extend({ + kdf: OpenSSLKdf + }), + + /** + * Encrypts a message using a password. + * + * @param {Cipher} cipher The cipher algorithm to use. + * @param {WordArray|string} message The message to encrypt. + * @param {string} password The password. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @return {CipherParams} A cipher params object. + * + * @static + * + * @example + * + * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password'); + * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL }); + */ + encrypt: function (cipher, message, password, cfg) { + // Apply config defaults + cfg = this.cfg.extend(cfg); + + // Derive key and other params + var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize); + + // Add IV to config + cfg.iv = derivedParams.iv; + + // Encrypt + var ciphertext = SerializableCipher.encrypt.call(this, cipher, message, derivedParams.key, cfg); + + // Mix in derived params + ciphertext.mixIn(derivedParams); + + return ciphertext; + }, + + /** + * Decrypts serialized ciphertext using a password. + * + * @param {Cipher} cipher The cipher algorithm to use. + * @param {CipherParams|string} ciphertext The ciphertext to decrypt. + * @param {string} password The password. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @return {WordArray} The plaintext. + * + * @static + * + * @example + * + * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL }); + * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL }); + */ + decrypt: function (cipher, ciphertext, password, cfg) { + // Apply config defaults + cfg = this.cfg.extend(cfg); + + // Convert string to CipherParams + ciphertext = this._parse(ciphertext, cfg.format); + + // Derive key and other params + var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt); + + // Add IV to config + cfg.iv = derivedParams.iv; + + // Decrypt + var plaintext = SerializableCipher.decrypt.call(this, cipher, ciphertext, derivedParams.key, cfg); + + return plaintext; + } + }); + }()); + + +})); + +/***/ }), +/* 31 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory, undef) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14), __webpack_require__(30)); + } + else {} +}(this, function (CryptoJS) { + + /** + * Cipher Feedback block mode. + */ + CryptoJS.mode.CFB = (function () { + var CFB = CryptoJS.lib.BlockCipherMode.extend(); + + CFB.Encryptor = CFB.extend({ + processBlock: function (words, offset) { + // Shortcuts + var cipher = this._cipher; + var blockSize = cipher.blockSize; + + generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher); + + // Remember this block to use with next block + this._prevBlock = words.slice(offset, offset + blockSize); + } + }); + + CFB.Decryptor = CFB.extend({ + processBlock: function (words, offset) { + // Shortcuts + var cipher = this._cipher; + var blockSize = cipher.blockSize; + + // Remember this block to use with next block + var thisBlock = words.slice(offset, offset + blockSize); + + generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher); + + // This block becomes the previous block + this._prevBlock = thisBlock; + } + }); + + function generateKeystreamAndEncrypt(words, offset, blockSize, cipher) { + // Shortcut + var iv = this._iv; + + // Generate keystream + if (iv) { + var keystream = iv.slice(0); + + // Remove IV for subsequent blocks + this._iv = undefined; + } else { + var keystream = this._prevBlock; + } + cipher.encryptBlock(keystream, 0); + + // Encrypt + for (var i = 0; i < blockSize; i++) { + words[offset + i] ^= keystream[i]; + } + } + + return CFB; + }()); + + + return CryptoJS.mode.CFB; + +})); + +/***/ }), +/* 32 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory, undef) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14), __webpack_require__(30)); + } + else {} +}(this, function (CryptoJS) { + + /** + * Counter block mode. + */ + CryptoJS.mode.CTR = (function () { + var CTR = CryptoJS.lib.BlockCipherMode.extend(); + + var Encryptor = CTR.Encryptor = CTR.extend({ + processBlock: function (words, offset) { + // Shortcuts + var cipher = this._cipher + var blockSize = cipher.blockSize; + var iv = this._iv; + var counter = this._counter; + + // Generate keystream + if (iv) { + counter = this._counter = iv.slice(0); + + // Remove IV for subsequent blocks + this._iv = undefined; + } + var keystream = counter.slice(0); + cipher.encryptBlock(keystream, 0); + + // Increment counter + counter[blockSize - 1] = (counter[blockSize - 1] + 1) | 0 + + // Encrypt + for (var i = 0; i < blockSize; i++) { + words[offset + i] ^= keystream[i]; + } + } + }); + + CTR.Decryptor = Encryptor; + + return CTR; + }()); + + + return CryptoJS.mode.CTR; + +})); + +/***/ }), +/* 33 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory, undef) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14), __webpack_require__(30)); + } + else {} +}(this, function (CryptoJS) { + + /** @preserve + * Counter block mode compatible with Dr Brian Gladman fileenc.c + * derived from CryptoJS.mode.CTR + * Jan Hruby jhruby.web@gmail.com + */ + CryptoJS.mode.CTRGladman = (function () { + var CTRGladman = CryptoJS.lib.BlockCipherMode.extend(); + + function incWord(word) + { + if (((word >> 24) & 0xff) === 0xff) { //overflow + var b1 = (word >> 16)&0xff; + var b2 = (word >> 8)&0xff; + var b3 = word & 0xff; + + if (b1 === 0xff) // overflow b1 + { + b1 = 0; + if (b2 === 0xff) + { + b2 = 0; + if (b3 === 0xff) + { + b3 = 0; + } + else + { + ++b3; + } + } + else + { + ++b2; + } + } + else + { + ++b1; + } + + word = 0; + word += (b1 << 16); + word += (b2 << 8); + word += b3; + } + else + { + word += (0x01 << 24); + } + return word; + } + + function incCounter(counter) + { + if ((counter[0] = incWord(counter[0])) === 0) + { + // encr_data in fileenc.c from Dr Brian Gladman's counts only with DWORD j < 8 + counter[1] = incWord(counter[1]); + } + return counter; + } + + var Encryptor = CTRGladman.Encryptor = CTRGladman.extend({ + processBlock: function (words, offset) { + // Shortcuts + var cipher = this._cipher + var blockSize = cipher.blockSize; + var iv = this._iv; + var counter = this._counter; + + // Generate keystream + if (iv) { + counter = this._counter = iv.slice(0); + + // Remove IV for subsequent blocks + this._iv = undefined; + } + + incCounter(counter); + + var keystream = counter.slice(0); + cipher.encryptBlock(keystream, 0); + + // Encrypt + for (var i = 0; i < blockSize; i++) { + words[offset + i] ^= keystream[i]; + } + } + }); + + CTRGladman.Decryptor = Encryptor; + + return CTRGladman; + }()); + + + + + return CryptoJS.mode.CTRGladman; + +})); + +/***/ }), +/* 34 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory, undef) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14), __webpack_require__(30)); + } + else {} +}(this, function (CryptoJS) { + + /** + * Output Feedback block mode. + */ + CryptoJS.mode.OFB = (function () { + var OFB = CryptoJS.lib.BlockCipherMode.extend(); + + var Encryptor = OFB.Encryptor = OFB.extend({ + processBlock: function (words, offset) { + // Shortcuts + var cipher = this._cipher + var blockSize = cipher.blockSize; + var iv = this._iv; + var keystream = this._keystream; + + // Generate keystream + if (iv) { + keystream = this._keystream = iv.slice(0); + + // Remove IV for subsequent blocks + this._iv = undefined; + } + cipher.encryptBlock(keystream, 0); + + // Encrypt + for (var i = 0; i < blockSize; i++) { + words[offset + i] ^= keystream[i]; + } + } + }); + + OFB.Decryptor = Encryptor; + + return OFB; + }()); + + + return CryptoJS.mode.OFB; + +})); + +/***/ }), +/* 35 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory, undef) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14), __webpack_require__(30)); + } + else {} +}(this, function (CryptoJS) { + + /** + * Electronic Codebook block mode. + */ + CryptoJS.mode.ECB = (function () { + var ECB = CryptoJS.lib.BlockCipherMode.extend(); + + ECB.Encryptor = ECB.extend({ + processBlock: function (words, offset) { + this._cipher.encryptBlock(words, offset); + } + }); + + ECB.Decryptor = ECB.extend({ + processBlock: function (words, offset) { + this._cipher.decryptBlock(words, offset); + } + }); + + return ECB; + }()); + + + return CryptoJS.mode.ECB; + +})); + +/***/ }), +/* 36 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory, undef) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14), __webpack_require__(30)); + } + else {} +}(this, function (CryptoJS) { + + /** + * ANSI X.923 padding strategy. + */ + CryptoJS.pad.AnsiX923 = { + pad: function (data, blockSize) { + // Shortcuts + var dataSigBytes = data.sigBytes; + var blockSizeBytes = blockSize * 4; + + // Count padding bytes + var nPaddingBytes = blockSizeBytes - dataSigBytes % blockSizeBytes; + + // Compute last byte position + var lastBytePos = dataSigBytes + nPaddingBytes - 1; + + // Pad + data.clamp(); + data.words[lastBytePos >>> 2] |= nPaddingBytes << (24 - (lastBytePos % 4) * 8); + data.sigBytes += nPaddingBytes; + }, + + unpad: function (data) { + // Get number of padding bytes from last byte + var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; + + // Remove padding + data.sigBytes -= nPaddingBytes; + } + }; + + + return CryptoJS.pad.Ansix923; + +})); + +/***/ }), +/* 37 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory, undef) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14), __webpack_require__(30)); + } + else {} +}(this, function (CryptoJS) { + + /** + * ISO 10126 padding strategy. + */ + CryptoJS.pad.Iso10126 = { + pad: function (data, blockSize) { + // Shortcut + var blockSizeBytes = blockSize * 4; + + // Count padding bytes + var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes; + + // Pad + data.concat(CryptoJS.lib.WordArray.random(nPaddingBytes - 1)). + concat(CryptoJS.lib.WordArray.create([nPaddingBytes << 24], 1)); + }, + + unpad: function (data) { + // Get number of padding bytes from last byte + var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; + + // Remove padding + data.sigBytes -= nPaddingBytes; + } + }; + + + return CryptoJS.pad.Iso10126; + +})); + +/***/ }), +/* 38 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory, undef) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14), __webpack_require__(30)); + } + else {} +}(this, function (CryptoJS) { + + /** + * ISO/IEC 9797-1 Padding Method 2. + */ + CryptoJS.pad.Iso97971 = { + pad: function (data, blockSize) { + // Add 0x80 byte + data.concat(CryptoJS.lib.WordArray.create([0x80000000], 1)); + + // Zero pad the rest + CryptoJS.pad.ZeroPadding.pad(data, blockSize); + }, + + unpad: function (data) { + // Remove zero padding + CryptoJS.pad.ZeroPadding.unpad(data); + + // Remove one more byte -- the 0x80 byte + data.sigBytes--; + } + }; + + + return CryptoJS.pad.Iso97971; + +})); + +/***/ }), +/* 39 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory, undef) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14), __webpack_require__(30)); + } + else {} +}(this, function (CryptoJS) { + + /** + * Zero padding strategy. + */ + CryptoJS.pad.ZeroPadding = { + pad: function (data, blockSize) { + // Shortcut + var blockSizeBytes = blockSize * 4; + + // Pad + data.clamp(); + data.sigBytes += blockSizeBytes - ((data.sigBytes % blockSizeBytes) || blockSizeBytes); + }, + + unpad: function (data) { + // Shortcut + var dataWords = data.words; + + // Unpad + var i = data.sigBytes - 1; + while (!((dataWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff)) { + i--; + } + data.sigBytes = i + 1; + } + }; + + + return CryptoJS.pad.ZeroPadding; + +})); + +/***/ }), +/* 40 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory, undef) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14), __webpack_require__(30)); + } + else {} +}(this, function (CryptoJS) { + + /** + * A noop padding strategy. + */ + CryptoJS.pad.NoPadding = { + pad: function () { + }, + + unpad: function () { + } + }; + + + return CryptoJS.pad.NoPadding; + +})); + +/***/ }), +/* 41 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory, undef) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14), __webpack_require__(30)); + } + else {} +}(this, function (CryptoJS) { + + (function (undefined) { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var CipherParams = C_lib.CipherParams; + var C_enc = C.enc; + var Hex = C_enc.Hex; + var C_format = C.format; + + var HexFormatter = C_format.Hex = { + /** + * Converts the ciphertext of a cipher params object to a hexadecimally encoded string. + * + * @param {CipherParams} cipherParams The cipher params object. + * + * @return {string} The hexadecimally encoded string. + * + * @static + * + * @example + * + * var hexString = CryptoJS.format.Hex.stringify(cipherParams); + */ + stringify: function (cipherParams) { + return cipherParams.ciphertext.toString(Hex); + }, + + /** + * Converts a hexadecimally encoded ciphertext string to a cipher params object. + * + * @param {string} input The hexadecimally encoded string. + * + * @return {CipherParams} The cipher params object. + * + * @static + * + * @example + * + * var cipherParams = CryptoJS.format.Hex.parse(hexString); + */ + parse: function (input) { + var ciphertext = Hex.parse(input); + return CipherParams.create({ ciphertext: ciphertext }); + } + }; + }()); + + + return CryptoJS.format.Hex; + +})); + +/***/ }), +/* 42 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory, undef) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14), __webpack_require__(18), __webpack_require__(19), __webpack_require__(29), __webpack_require__(30)); + } + else {} +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var BlockCipher = C_lib.BlockCipher; + var C_algo = C.algo; + + // Lookup tables + var SBOX = []; + var INV_SBOX = []; + var SUB_MIX_0 = []; + var SUB_MIX_1 = []; + var SUB_MIX_2 = []; + var SUB_MIX_3 = []; + var INV_SUB_MIX_0 = []; + var INV_SUB_MIX_1 = []; + var INV_SUB_MIX_2 = []; + var INV_SUB_MIX_3 = []; + + // Compute lookup tables + (function () { + // Compute double table + var d = []; + for (var i = 0; i < 256; i++) { + if (i < 128) { + d[i] = i << 1; + } else { + d[i] = (i << 1) ^ 0x11b; + } + } + + // Walk GF(2^8) + var x = 0; + var xi = 0; + for (var i = 0; i < 256; i++) { + // Compute sbox + var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4); + sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63; + SBOX[x] = sx; + INV_SBOX[sx] = x; + + // Compute multiplication + var x2 = d[x]; + var x4 = d[x2]; + var x8 = d[x4]; + + // Compute sub bytes, mix columns tables + var t = (d[sx] * 0x101) ^ (sx * 0x1010100); + SUB_MIX_0[x] = (t << 24) | (t >>> 8); + SUB_MIX_1[x] = (t << 16) | (t >>> 16); + SUB_MIX_2[x] = (t << 8) | (t >>> 24); + SUB_MIX_3[x] = t; + + // Compute inv sub bytes, inv mix columns tables + var t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100); + INV_SUB_MIX_0[sx] = (t << 24) | (t >>> 8); + INV_SUB_MIX_1[sx] = (t << 16) | (t >>> 16); + INV_SUB_MIX_2[sx] = (t << 8) | (t >>> 24); + INV_SUB_MIX_3[sx] = t; + + // Compute next counter + if (!x) { + x = xi = 1; + } else { + x = x2 ^ d[d[d[x8 ^ x2]]]; + xi ^= d[d[xi]]; + } + } + }()); + + // Precomputed Rcon lookup + var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]; + + /** + * AES block cipher algorithm. + */ + var AES = C_algo.AES = BlockCipher.extend({ + _doReset: function () { + // Skip reset of nRounds has been set before and key did not change + if (this._nRounds && this._keyPriorReset === this._key) { + return; + } + + // Shortcuts + var key = this._keyPriorReset = this._key; + var keyWords = key.words; + var keySize = key.sigBytes / 4; + + // Compute number of rounds + var nRounds = this._nRounds = keySize + 6; + + // Compute number of key schedule rows + var ksRows = (nRounds + 1) * 4; + + // Compute key schedule + var keySchedule = this._keySchedule = []; + for (var ksRow = 0; ksRow < ksRows; ksRow++) { + if (ksRow < keySize) { + keySchedule[ksRow] = keyWords[ksRow]; + } else { + var t = keySchedule[ksRow - 1]; + + if (!(ksRow % keySize)) { + // Rot word + t = (t << 8) | (t >>> 24); + + // Sub word + t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]; + + // Mix Rcon + t ^= RCON[(ksRow / keySize) | 0] << 24; + } else if (keySize > 6 && ksRow % keySize == 4) { + // Sub word + t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]; + } + + keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t; + } + } + + // Compute inv key schedule + var invKeySchedule = this._invKeySchedule = []; + for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) { + var ksRow = ksRows - invKsRow; + + if (invKsRow % 4) { + var t = keySchedule[ksRow]; + } else { + var t = keySchedule[ksRow - 4]; + } + + if (invKsRow < 4 || ksRow <= 4) { + invKeySchedule[invKsRow] = t; + } else { + invKeySchedule[invKsRow] = INV_SUB_MIX_0[SBOX[t >>> 24]] ^ INV_SUB_MIX_1[SBOX[(t >>> 16) & 0xff]] ^ + INV_SUB_MIX_2[SBOX[(t >>> 8) & 0xff]] ^ INV_SUB_MIX_3[SBOX[t & 0xff]]; + } + } + }, + + encryptBlock: function (M, offset) { + this._doCryptBlock(M, offset, this._keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX); + }, + + decryptBlock: function (M, offset) { + // Swap 2nd and 4th rows + var t = M[offset + 1]; + M[offset + 1] = M[offset + 3]; + M[offset + 3] = t; + + this._doCryptBlock(M, offset, this._invKeySchedule, INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3, INV_SBOX); + + // Inv swap 2nd and 4th rows + var t = M[offset + 1]; + M[offset + 1] = M[offset + 3]; + M[offset + 3] = t; + }, + + _doCryptBlock: function (M, offset, keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX) { + // Shortcut + var nRounds = this._nRounds; + + // Get input, add round key + var s0 = M[offset] ^ keySchedule[0]; + var s1 = M[offset + 1] ^ keySchedule[1]; + var s2 = M[offset + 2] ^ keySchedule[2]; + var s3 = M[offset + 3] ^ keySchedule[3]; + + // Key schedule row counter + var ksRow = 4; + + // Rounds + for (var round = 1; round < nRounds; round++) { + // Shift rows, sub bytes, mix columns, add round key + var t0 = SUB_MIX_0[s0 >>> 24] ^ SUB_MIX_1[(s1 >>> 16) & 0xff] ^ SUB_MIX_2[(s2 >>> 8) & 0xff] ^ SUB_MIX_3[s3 & 0xff] ^ keySchedule[ksRow++]; + var t1 = SUB_MIX_0[s1 >>> 24] ^ SUB_MIX_1[(s2 >>> 16) & 0xff] ^ SUB_MIX_2[(s3 >>> 8) & 0xff] ^ SUB_MIX_3[s0 & 0xff] ^ keySchedule[ksRow++]; + var t2 = SUB_MIX_0[s2 >>> 24] ^ SUB_MIX_1[(s3 >>> 16) & 0xff] ^ SUB_MIX_2[(s0 >>> 8) & 0xff] ^ SUB_MIX_3[s1 & 0xff] ^ keySchedule[ksRow++]; + var t3 = SUB_MIX_0[s3 >>> 24] ^ SUB_MIX_1[(s0 >>> 16) & 0xff] ^ SUB_MIX_2[(s1 >>> 8) & 0xff] ^ SUB_MIX_3[s2 & 0xff] ^ keySchedule[ksRow++]; + + // Update state + s0 = t0; + s1 = t1; + s2 = t2; + s3 = t3; + } + + // Shift rows, sub bytes, add round key + var t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++]; + var t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++]; + var t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++]; + var t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++]; + + // Set output + M[offset] = t0; + M[offset + 1] = t1; + M[offset + 2] = t2; + M[offset + 3] = t3; + }, + + keySize: 256/32 + }); + + /** + * Shortcut functions to the cipher's object interface. + * + * @example + * + * var ciphertext = CryptoJS.AES.encrypt(message, key, cfg); + * var plaintext = CryptoJS.AES.decrypt(ciphertext, key, cfg); + */ + C.AES = BlockCipher._createHelper(AES); + }()); + + + return CryptoJS.AES; + +})); + +/***/ }), +/* 43 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory, undef) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14), __webpack_require__(18), __webpack_require__(19), __webpack_require__(29), __webpack_require__(30)); + } + else {} +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var BlockCipher = C_lib.BlockCipher; + var C_algo = C.algo; + + // Permuted Choice 1 constants + var PC1 = [ + 57, 49, 41, 33, 25, 17, 9, 1, + 58, 50, 42, 34, 26, 18, 10, 2, + 59, 51, 43, 35, 27, 19, 11, 3, + 60, 52, 44, 36, 63, 55, 47, 39, + 31, 23, 15, 7, 62, 54, 46, 38, + 30, 22, 14, 6, 61, 53, 45, 37, + 29, 21, 13, 5, 28, 20, 12, 4 + ]; + + // Permuted Choice 2 constants + var PC2 = [ + 14, 17, 11, 24, 1, 5, + 3, 28, 15, 6, 21, 10, + 23, 19, 12, 4, 26, 8, + 16, 7, 27, 20, 13, 2, + 41, 52, 31, 37, 47, 55, + 30, 40, 51, 45, 33, 48, + 44, 49, 39, 56, 34, 53, + 46, 42, 50, 36, 29, 32 + ]; + + // Cumulative bit shift constants + var BIT_SHIFTS = [1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28]; + + // SBOXes and round permutation constants + var SBOX_P = [ + { + 0x0: 0x808200, + 0x10000000: 0x8000, + 0x20000000: 0x808002, + 0x30000000: 0x2, + 0x40000000: 0x200, + 0x50000000: 0x808202, + 0x60000000: 0x800202, + 0x70000000: 0x800000, + 0x80000000: 0x202, + 0x90000000: 0x800200, + 0xa0000000: 0x8200, + 0xb0000000: 0x808000, + 0xc0000000: 0x8002, + 0xd0000000: 0x800002, + 0xe0000000: 0x0, + 0xf0000000: 0x8202, + 0x8000000: 0x0, + 0x18000000: 0x808202, + 0x28000000: 0x8202, + 0x38000000: 0x8000, + 0x48000000: 0x808200, + 0x58000000: 0x200, + 0x68000000: 0x808002, + 0x78000000: 0x2, + 0x88000000: 0x800200, + 0x98000000: 0x8200, + 0xa8000000: 0x808000, + 0xb8000000: 0x800202, + 0xc8000000: 0x800002, + 0xd8000000: 0x8002, + 0xe8000000: 0x202, + 0xf8000000: 0x800000, + 0x1: 0x8000, + 0x10000001: 0x2, + 0x20000001: 0x808200, + 0x30000001: 0x800000, + 0x40000001: 0x808002, + 0x50000001: 0x8200, + 0x60000001: 0x200, + 0x70000001: 0x800202, + 0x80000001: 0x808202, + 0x90000001: 0x808000, + 0xa0000001: 0x800002, + 0xb0000001: 0x8202, + 0xc0000001: 0x202, + 0xd0000001: 0x800200, + 0xe0000001: 0x8002, + 0xf0000001: 0x0, + 0x8000001: 0x808202, + 0x18000001: 0x808000, + 0x28000001: 0x800000, + 0x38000001: 0x200, + 0x48000001: 0x8000, + 0x58000001: 0x800002, + 0x68000001: 0x2, + 0x78000001: 0x8202, + 0x88000001: 0x8002, + 0x98000001: 0x800202, + 0xa8000001: 0x202, + 0xb8000001: 0x808200, + 0xc8000001: 0x800200, + 0xd8000001: 0x0, + 0xe8000001: 0x8200, + 0xf8000001: 0x808002 + }, + { + 0x0: 0x40084010, + 0x1000000: 0x4000, + 0x2000000: 0x80000, + 0x3000000: 0x40080010, + 0x4000000: 0x40000010, + 0x5000000: 0x40084000, + 0x6000000: 0x40004000, + 0x7000000: 0x10, + 0x8000000: 0x84000, + 0x9000000: 0x40004010, + 0xa000000: 0x40000000, + 0xb000000: 0x84010, + 0xc000000: 0x80010, + 0xd000000: 0x0, + 0xe000000: 0x4010, + 0xf000000: 0x40080000, + 0x800000: 0x40004000, + 0x1800000: 0x84010, + 0x2800000: 0x10, + 0x3800000: 0x40004010, + 0x4800000: 0x40084010, + 0x5800000: 0x40000000, + 0x6800000: 0x80000, + 0x7800000: 0x40080010, + 0x8800000: 0x80010, + 0x9800000: 0x0, + 0xa800000: 0x4000, + 0xb800000: 0x40080000, + 0xc800000: 0x40000010, + 0xd800000: 0x84000, + 0xe800000: 0x40084000, + 0xf800000: 0x4010, + 0x10000000: 0x0, + 0x11000000: 0x40080010, + 0x12000000: 0x40004010, + 0x13000000: 0x40084000, + 0x14000000: 0x40080000, + 0x15000000: 0x10, + 0x16000000: 0x84010, + 0x17000000: 0x4000, + 0x18000000: 0x4010, + 0x19000000: 0x80000, + 0x1a000000: 0x80010, + 0x1b000000: 0x40000010, + 0x1c000000: 0x84000, + 0x1d000000: 0x40004000, + 0x1e000000: 0x40000000, + 0x1f000000: 0x40084010, + 0x10800000: 0x84010, + 0x11800000: 0x80000, + 0x12800000: 0x40080000, + 0x13800000: 0x4000, + 0x14800000: 0x40004000, + 0x15800000: 0x40084010, + 0x16800000: 0x10, + 0x17800000: 0x40000000, + 0x18800000: 0x40084000, + 0x19800000: 0x40000010, + 0x1a800000: 0x40004010, + 0x1b800000: 0x80010, + 0x1c800000: 0x0, + 0x1d800000: 0x4010, + 0x1e800000: 0x40080010, + 0x1f800000: 0x84000 + }, + { + 0x0: 0x104, + 0x100000: 0x0, + 0x200000: 0x4000100, + 0x300000: 0x10104, + 0x400000: 0x10004, + 0x500000: 0x4000004, + 0x600000: 0x4010104, + 0x700000: 0x4010000, + 0x800000: 0x4000000, + 0x900000: 0x4010100, + 0xa00000: 0x10100, + 0xb00000: 0x4010004, + 0xc00000: 0x4000104, + 0xd00000: 0x10000, + 0xe00000: 0x4, + 0xf00000: 0x100, + 0x80000: 0x4010100, + 0x180000: 0x4010004, + 0x280000: 0x0, + 0x380000: 0x4000100, + 0x480000: 0x4000004, + 0x580000: 0x10000, + 0x680000: 0x10004, + 0x780000: 0x104, + 0x880000: 0x4, + 0x980000: 0x100, + 0xa80000: 0x4010000, + 0xb80000: 0x10104, + 0xc80000: 0x10100, + 0xd80000: 0x4000104, + 0xe80000: 0x4010104, + 0xf80000: 0x4000000, + 0x1000000: 0x4010100, + 0x1100000: 0x10004, + 0x1200000: 0x10000, + 0x1300000: 0x4000100, + 0x1400000: 0x100, + 0x1500000: 0x4010104, + 0x1600000: 0x4000004, + 0x1700000: 0x0, + 0x1800000: 0x4000104, + 0x1900000: 0x4000000, + 0x1a00000: 0x4, + 0x1b00000: 0x10100, + 0x1c00000: 0x4010000, + 0x1d00000: 0x104, + 0x1e00000: 0x10104, + 0x1f00000: 0x4010004, + 0x1080000: 0x4000000, + 0x1180000: 0x104, + 0x1280000: 0x4010100, + 0x1380000: 0x0, + 0x1480000: 0x10004, + 0x1580000: 0x4000100, + 0x1680000: 0x100, + 0x1780000: 0x4010004, + 0x1880000: 0x10000, + 0x1980000: 0x4010104, + 0x1a80000: 0x10104, + 0x1b80000: 0x4000004, + 0x1c80000: 0x4000104, + 0x1d80000: 0x4010000, + 0x1e80000: 0x4, + 0x1f80000: 0x10100 + }, + { + 0x0: 0x80401000, + 0x10000: 0x80001040, + 0x20000: 0x401040, + 0x30000: 0x80400000, + 0x40000: 0x0, + 0x50000: 0x401000, + 0x60000: 0x80000040, + 0x70000: 0x400040, + 0x80000: 0x80000000, + 0x90000: 0x400000, + 0xa0000: 0x40, + 0xb0000: 0x80001000, + 0xc0000: 0x80400040, + 0xd0000: 0x1040, + 0xe0000: 0x1000, + 0xf0000: 0x80401040, + 0x8000: 0x80001040, + 0x18000: 0x40, + 0x28000: 0x80400040, + 0x38000: 0x80001000, + 0x48000: 0x401000, + 0x58000: 0x80401040, + 0x68000: 0x0, + 0x78000: 0x80400000, + 0x88000: 0x1000, + 0x98000: 0x80401000, + 0xa8000: 0x400000, + 0xb8000: 0x1040, + 0xc8000: 0x80000000, + 0xd8000: 0x400040, + 0xe8000: 0x401040, + 0xf8000: 0x80000040, + 0x100000: 0x400040, + 0x110000: 0x401000, + 0x120000: 0x80000040, + 0x130000: 0x0, + 0x140000: 0x1040, + 0x150000: 0x80400040, + 0x160000: 0x80401000, + 0x170000: 0x80001040, + 0x180000: 0x80401040, + 0x190000: 0x80000000, + 0x1a0000: 0x80400000, + 0x1b0000: 0x401040, + 0x1c0000: 0x80001000, + 0x1d0000: 0x400000, + 0x1e0000: 0x40, + 0x1f0000: 0x1000, + 0x108000: 0x80400000, + 0x118000: 0x80401040, + 0x128000: 0x0, + 0x138000: 0x401000, + 0x148000: 0x400040, + 0x158000: 0x80000000, + 0x168000: 0x80001040, + 0x178000: 0x40, + 0x188000: 0x80000040, + 0x198000: 0x1000, + 0x1a8000: 0x80001000, + 0x1b8000: 0x80400040, + 0x1c8000: 0x1040, + 0x1d8000: 0x80401000, + 0x1e8000: 0x400000, + 0x1f8000: 0x401040 + }, + { + 0x0: 0x80, + 0x1000: 0x1040000, + 0x2000: 0x40000, + 0x3000: 0x20000000, + 0x4000: 0x20040080, + 0x5000: 0x1000080, + 0x6000: 0x21000080, + 0x7000: 0x40080, + 0x8000: 0x1000000, + 0x9000: 0x20040000, + 0xa000: 0x20000080, + 0xb000: 0x21040080, + 0xc000: 0x21040000, + 0xd000: 0x0, + 0xe000: 0x1040080, + 0xf000: 0x21000000, + 0x800: 0x1040080, + 0x1800: 0x21000080, + 0x2800: 0x80, + 0x3800: 0x1040000, + 0x4800: 0x40000, + 0x5800: 0x20040080, + 0x6800: 0x21040000, + 0x7800: 0x20000000, + 0x8800: 0x20040000, + 0x9800: 0x0, + 0xa800: 0x21040080, + 0xb800: 0x1000080, + 0xc800: 0x20000080, + 0xd800: 0x21000000, + 0xe800: 0x1000000, + 0xf800: 0x40080, + 0x10000: 0x40000, + 0x11000: 0x80, + 0x12000: 0x20000000, + 0x13000: 0x21000080, + 0x14000: 0x1000080, + 0x15000: 0x21040000, + 0x16000: 0x20040080, + 0x17000: 0x1000000, + 0x18000: 0x21040080, + 0x19000: 0x21000000, + 0x1a000: 0x1040000, + 0x1b000: 0x20040000, + 0x1c000: 0x40080, + 0x1d000: 0x20000080, + 0x1e000: 0x0, + 0x1f000: 0x1040080, + 0x10800: 0x21000080, + 0x11800: 0x1000000, + 0x12800: 0x1040000, + 0x13800: 0x20040080, + 0x14800: 0x20000000, + 0x15800: 0x1040080, + 0x16800: 0x80, + 0x17800: 0x21040000, + 0x18800: 0x40080, + 0x19800: 0x21040080, + 0x1a800: 0x0, + 0x1b800: 0x21000000, + 0x1c800: 0x1000080, + 0x1d800: 0x40000, + 0x1e800: 0x20040000, + 0x1f800: 0x20000080 + }, + { + 0x0: 0x10000008, + 0x100: 0x2000, + 0x200: 0x10200000, + 0x300: 0x10202008, + 0x400: 0x10002000, + 0x500: 0x200000, + 0x600: 0x200008, + 0x700: 0x10000000, + 0x800: 0x0, + 0x900: 0x10002008, + 0xa00: 0x202000, + 0xb00: 0x8, + 0xc00: 0x10200008, + 0xd00: 0x202008, + 0xe00: 0x2008, + 0xf00: 0x10202000, + 0x80: 0x10200000, + 0x180: 0x10202008, + 0x280: 0x8, + 0x380: 0x200000, + 0x480: 0x202008, + 0x580: 0x10000008, + 0x680: 0x10002000, + 0x780: 0x2008, + 0x880: 0x200008, + 0x980: 0x2000, + 0xa80: 0x10002008, + 0xb80: 0x10200008, + 0xc80: 0x0, + 0xd80: 0x10202000, + 0xe80: 0x202000, + 0xf80: 0x10000000, + 0x1000: 0x10002000, + 0x1100: 0x10200008, + 0x1200: 0x10202008, + 0x1300: 0x2008, + 0x1400: 0x200000, + 0x1500: 0x10000000, + 0x1600: 0x10000008, + 0x1700: 0x202000, + 0x1800: 0x202008, + 0x1900: 0x0, + 0x1a00: 0x8, + 0x1b00: 0x10200000, + 0x1c00: 0x2000, + 0x1d00: 0x10002008, + 0x1e00: 0x10202000, + 0x1f00: 0x200008, + 0x1080: 0x8, + 0x1180: 0x202000, + 0x1280: 0x200000, + 0x1380: 0x10000008, + 0x1480: 0x10002000, + 0x1580: 0x2008, + 0x1680: 0x10202008, + 0x1780: 0x10200000, + 0x1880: 0x10202000, + 0x1980: 0x10200008, + 0x1a80: 0x2000, + 0x1b80: 0x202008, + 0x1c80: 0x200008, + 0x1d80: 0x0, + 0x1e80: 0x10000000, + 0x1f80: 0x10002008 + }, + { + 0x0: 0x100000, + 0x10: 0x2000401, + 0x20: 0x400, + 0x30: 0x100401, + 0x40: 0x2100401, + 0x50: 0x0, + 0x60: 0x1, + 0x70: 0x2100001, + 0x80: 0x2000400, + 0x90: 0x100001, + 0xa0: 0x2000001, + 0xb0: 0x2100400, + 0xc0: 0x2100000, + 0xd0: 0x401, + 0xe0: 0x100400, + 0xf0: 0x2000000, + 0x8: 0x2100001, + 0x18: 0x0, + 0x28: 0x2000401, + 0x38: 0x2100400, + 0x48: 0x100000, + 0x58: 0x2000001, + 0x68: 0x2000000, + 0x78: 0x401, + 0x88: 0x100401, + 0x98: 0x2000400, + 0xa8: 0x2100000, + 0xb8: 0x100001, + 0xc8: 0x400, + 0xd8: 0x2100401, + 0xe8: 0x1, + 0xf8: 0x100400, + 0x100: 0x2000000, + 0x110: 0x100000, + 0x120: 0x2000401, + 0x130: 0x2100001, + 0x140: 0x100001, + 0x150: 0x2000400, + 0x160: 0x2100400, + 0x170: 0x100401, + 0x180: 0x401, + 0x190: 0x2100401, + 0x1a0: 0x100400, + 0x1b0: 0x1, + 0x1c0: 0x0, + 0x1d0: 0x2100000, + 0x1e0: 0x2000001, + 0x1f0: 0x400, + 0x108: 0x100400, + 0x118: 0x2000401, + 0x128: 0x2100001, + 0x138: 0x1, + 0x148: 0x2000000, + 0x158: 0x100000, + 0x168: 0x401, + 0x178: 0x2100400, + 0x188: 0x2000001, + 0x198: 0x2100000, + 0x1a8: 0x0, + 0x1b8: 0x2100401, + 0x1c8: 0x100401, + 0x1d8: 0x400, + 0x1e8: 0x2000400, + 0x1f8: 0x100001 + }, + { + 0x0: 0x8000820, + 0x1: 0x20000, + 0x2: 0x8000000, + 0x3: 0x20, + 0x4: 0x20020, + 0x5: 0x8020820, + 0x6: 0x8020800, + 0x7: 0x800, + 0x8: 0x8020000, + 0x9: 0x8000800, + 0xa: 0x20800, + 0xb: 0x8020020, + 0xc: 0x820, + 0xd: 0x0, + 0xe: 0x8000020, + 0xf: 0x20820, + 0x80000000: 0x800, + 0x80000001: 0x8020820, + 0x80000002: 0x8000820, + 0x80000003: 0x8000000, + 0x80000004: 0x8020000, + 0x80000005: 0x20800, + 0x80000006: 0x20820, + 0x80000007: 0x20, + 0x80000008: 0x8000020, + 0x80000009: 0x820, + 0x8000000a: 0x20020, + 0x8000000b: 0x8020800, + 0x8000000c: 0x0, + 0x8000000d: 0x8020020, + 0x8000000e: 0x8000800, + 0x8000000f: 0x20000, + 0x10: 0x20820, + 0x11: 0x8020800, + 0x12: 0x20, + 0x13: 0x800, + 0x14: 0x8000800, + 0x15: 0x8000020, + 0x16: 0x8020020, + 0x17: 0x20000, + 0x18: 0x0, + 0x19: 0x20020, + 0x1a: 0x8020000, + 0x1b: 0x8000820, + 0x1c: 0x8020820, + 0x1d: 0x20800, + 0x1e: 0x820, + 0x1f: 0x8000000, + 0x80000010: 0x20000, + 0x80000011: 0x800, + 0x80000012: 0x8020020, + 0x80000013: 0x20820, + 0x80000014: 0x20, + 0x80000015: 0x8020000, + 0x80000016: 0x8000000, + 0x80000017: 0x8000820, + 0x80000018: 0x8020820, + 0x80000019: 0x8000020, + 0x8000001a: 0x8000800, + 0x8000001b: 0x0, + 0x8000001c: 0x20800, + 0x8000001d: 0x820, + 0x8000001e: 0x20020, + 0x8000001f: 0x8020800 + } + ]; + + // Masks that select the SBOX input + var SBOX_MASK = [ + 0xf8000001, 0x1f800000, 0x01f80000, 0x001f8000, + 0x0001f800, 0x00001f80, 0x000001f8, 0x8000001f + ]; + + /** + * DES block cipher algorithm. + */ + var DES = C_algo.DES = BlockCipher.extend({ + _doReset: function () { + // Shortcuts + var key = this._key; + var keyWords = key.words; + + // Select 56 bits according to PC1 + var keyBits = []; + for (var i = 0; i < 56; i++) { + var keyBitPos = PC1[i] - 1; + keyBits[i] = (keyWords[keyBitPos >>> 5] >>> (31 - keyBitPos % 32)) & 1; + } + + // Assemble 16 subkeys + var subKeys = this._subKeys = []; + for (var nSubKey = 0; nSubKey < 16; nSubKey++) { + // Create subkey + var subKey = subKeys[nSubKey] = []; + + // Shortcut + var bitShift = BIT_SHIFTS[nSubKey]; + + // Select 48 bits according to PC2 + for (var i = 0; i < 24; i++) { + // Select from the left 28 key bits + subKey[(i / 6) | 0] |= keyBits[((PC2[i] - 1) + bitShift) % 28] << (31 - i % 6); + + // Select from the right 28 key bits + subKey[4 + ((i / 6) | 0)] |= keyBits[28 + (((PC2[i + 24] - 1) + bitShift) % 28)] << (31 - i % 6); + } + + // Since each subkey is applied to an expanded 32-bit input, + // the subkey can be broken into 8 values scaled to 32-bits, + // which allows the key to be used without expansion + subKey[0] = (subKey[0] << 1) | (subKey[0] >>> 31); + for (var i = 1; i < 7; i++) { + subKey[i] = subKey[i] >>> ((i - 1) * 4 + 3); + } + subKey[7] = (subKey[7] << 5) | (subKey[7] >>> 27); + } + + // Compute inverse subkeys + var invSubKeys = this._invSubKeys = []; + for (var i = 0; i < 16; i++) { + invSubKeys[i] = subKeys[15 - i]; + } + }, + + encryptBlock: function (M, offset) { + this._doCryptBlock(M, offset, this._subKeys); + }, + + decryptBlock: function (M, offset) { + this._doCryptBlock(M, offset, this._invSubKeys); + }, + + _doCryptBlock: function (M, offset, subKeys) { + // Get input + this._lBlock = M[offset]; + this._rBlock = M[offset + 1]; + + // Initial permutation + exchangeLR.call(this, 4, 0x0f0f0f0f); + exchangeLR.call(this, 16, 0x0000ffff); + exchangeRL.call(this, 2, 0x33333333); + exchangeRL.call(this, 8, 0x00ff00ff); + exchangeLR.call(this, 1, 0x55555555); + + // Rounds + for (var round = 0; round < 16; round++) { + // Shortcuts + var subKey = subKeys[round]; + var lBlock = this._lBlock; + var rBlock = this._rBlock; + + // Feistel function + var f = 0; + for (var i = 0; i < 8; i++) { + f |= SBOX_P[i][((rBlock ^ subKey[i]) & SBOX_MASK[i]) >>> 0]; + } + this._lBlock = rBlock; + this._rBlock = lBlock ^ f; + } + + // Undo swap from last round + var t = this._lBlock; + this._lBlock = this._rBlock; + this._rBlock = t; + + // Final permutation + exchangeLR.call(this, 1, 0x55555555); + exchangeRL.call(this, 8, 0x00ff00ff); + exchangeRL.call(this, 2, 0x33333333); + exchangeLR.call(this, 16, 0x0000ffff); + exchangeLR.call(this, 4, 0x0f0f0f0f); + + // Set output + M[offset] = this._lBlock; + M[offset + 1] = this._rBlock; + }, + + keySize: 64/32, + + ivSize: 64/32, + + blockSize: 64/32 + }); + + // Swap bits across the left and right words + function exchangeLR(offset, mask) { + var t = ((this._lBlock >>> offset) ^ this._rBlock) & mask; + this._rBlock ^= t; + this._lBlock ^= t << offset; + } + + function exchangeRL(offset, mask) { + var t = ((this._rBlock >>> offset) ^ this._lBlock) & mask; + this._lBlock ^= t; + this._rBlock ^= t << offset; + } + + /** + * Shortcut functions to the cipher's object interface. + * + * @example + * + * var ciphertext = CryptoJS.DES.encrypt(message, key, cfg); + * var plaintext = CryptoJS.DES.decrypt(ciphertext, key, cfg); + */ + C.DES = BlockCipher._createHelper(DES); + + /** + * Triple-DES block cipher algorithm. + */ + var TripleDES = C_algo.TripleDES = BlockCipher.extend({ + _doReset: function () { + // Shortcuts + var key = this._key; + var keyWords = key.words; + + // Create DES instances + this._des1 = DES.createEncryptor(WordArray.create(keyWords.slice(0, 2))); + this._des2 = DES.createEncryptor(WordArray.create(keyWords.slice(2, 4))); + this._des3 = DES.createEncryptor(WordArray.create(keyWords.slice(4, 6))); + }, + + encryptBlock: function (M, offset) { + this._des1.encryptBlock(M, offset); + this._des2.decryptBlock(M, offset); + this._des3.encryptBlock(M, offset); + }, + + decryptBlock: function (M, offset) { + this._des3.decryptBlock(M, offset); + this._des2.encryptBlock(M, offset); + this._des1.decryptBlock(M, offset); + }, + + keySize: 192/32, + + ivSize: 64/32, + + blockSize: 64/32 + }); + + /** + * Shortcut functions to the cipher's object interface. + * + * @example + * + * var ciphertext = CryptoJS.TripleDES.encrypt(message, key, cfg); + * var plaintext = CryptoJS.TripleDES.decrypt(ciphertext, key, cfg); + */ + C.TripleDES = BlockCipher._createHelper(TripleDES); + }()); + + + return CryptoJS.TripleDES; + +})); + +/***/ }), +/* 44 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory, undef) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14), __webpack_require__(18), __webpack_require__(19), __webpack_require__(29), __webpack_require__(30)); + } + else {} +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var StreamCipher = C_lib.StreamCipher; + var C_algo = C.algo; + + /** + * RC4 stream cipher algorithm. + */ + var RC4 = C_algo.RC4 = StreamCipher.extend({ + _doReset: function () { + // Shortcuts + var key = this._key; + var keyWords = key.words; + var keySigBytes = key.sigBytes; + + // Init sbox + var S = this._S = []; + for (var i = 0; i < 256; i++) { + S[i] = i; + } + + // Key setup + for (var i = 0, j = 0; i < 256; i++) { + var keyByteIndex = i % keySigBytes; + var keyByte = (keyWords[keyByteIndex >>> 2] >>> (24 - (keyByteIndex % 4) * 8)) & 0xff; + + j = (j + S[i] + keyByte) % 256; + + // Swap + var t = S[i]; + S[i] = S[j]; + S[j] = t; + } + + // Counters + this._i = this._j = 0; + }, + + _doProcessBlock: function (M, offset) { + M[offset] ^= generateKeystreamWord.call(this); + }, + + keySize: 256/32, + + ivSize: 0 + }); + + function generateKeystreamWord() { + // Shortcuts + var S = this._S; + var i = this._i; + var j = this._j; + + // Generate keystream word + var keystreamWord = 0; + for (var n = 0; n < 4; n++) { + i = (i + 1) % 256; + j = (j + S[i]) % 256; + + // Swap + var t = S[i]; + S[i] = S[j]; + S[j] = t; + + keystreamWord |= S[(S[i] + S[j]) % 256] << (24 - n * 8); + } + + // Update counters + this._i = i; + this._j = j; + + return keystreamWord; + } + + /** + * Shortcut functions to the cipher's object interface. + * + * @example + * + * var ciphertext = CryptoJS.RC4.encrypt(message, key, cfg); + * var plaintext = CryptoJS.RC4.decrypt(ciphertext, key, cfg); + */ + C.RC4 = StreamCipher._createHelper(RC4); + + /** + * Modified RC4 stream cipher algorithm. + */ + var RC4Drop = C_algo.RC4Drop = RC4.extend({ + /** + * Configuration options. + * + * @property {number} drop The number of keystream words to drop. Default 192 + */ + cfg: RC4.cfg.extend({ + drop: 192 + }), + + _doReset: function () { + RC4._doReset.call(this); + + // Drop + for (var i = this.cfg.drop; i > 0; i--) { + generateKeystreamWord.call(this); + } + } + }); + + /** + * Shortcut functions to the cipher's object interface. + * + * @example + * + * var ciphertext = CryptoJS.RC4Drop.encrypt(message, key, cfg); + * var plaintext = CryptoJS.RC4Drop.decrypt(ciphertext, key, cfg); + */ + C.RC4Drop = StreamCipher._createHelper(RC4Drop); + }()); + + + return CryptoJS.RC4; + +})); + +/***/ }), +/* 45 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory, undef) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14), __webpack_require__(18), __webpack_require__(19), __webpack_require__(29), __webpack_require__(30)); + } + else {} +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var StreamCipher = C_lib.StreamCipher; + var C_algo = C.algo; + + // Reusable objects + var S = []; + var C_ = []; + var G = []; + + /** + * Rabbit stream cipher algorithm + */ + var Rabbit = C_algo.Rabbit = StreamCipher.extend({ + _doReset: function () { + // Shortcuts + var K = this._key.words; + var iv = this.cfg.iv; + + // Swap endian + for (var i = 0; i < 4; i++) { + K[i] = (((K[i] << 8) | (K[i] >>> 24)) & 0x00ff00ff) | + (((K[i] << 24) | (K[i] >>> 8)) & 0xff00ff00); + } + + // Generate initial state values + var X = this._X = [ + K[0], (K[3] << 16) | (K[2] >>> 16), + K[1], (K[0] << 16) | (K[3] >>> 16), + K[2], (K[1] << 16) | (K[0] >>> 16), + K[3], (K[2] << 16) | (K[1] >>> 16) + ]; + + // Generate initial counter values + var C = this._C = [ + (K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff), + (K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff), + (K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff), + (K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff) + ]; + + // Carry bit + this._b = 0; + + // Iterate the system four times + for (var i = 0; i < 4; i++) { + nextState.call(this); + } + + // Modify the counters + for (var i = 0; i < 8; i++) { + C[i] ^= X[(i + 4) & 7]; + } + + // IV setup + if (iv) { + // Shortcuts + var IV = iv.words; + var IV_0 = IV[0]; + var IV_1 = IV[1]; + + // Generate four subvectors + var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00); + var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00); + var i1 = (i0 >>> 16) | (i2 & 0xffff0000); + var i3 = (i2 << 16) | (i0 & 0x0000ffff); + + // Modify counter values + C[0] ^= i0; + C[1] ^= i1; + C[2] ^= i2; + C[3] ^= i3; + C[4] ^= i0; + C[5] ^= i1; + C[6] ^= i2; + C[7] ^= i3; + + // Iterate the system four times + for (var i = 0; i < 4; i++) { + nextState.call(this); + } + } + }, + + _doProcessBlock: function (M, offset) { + // Shortcut + var X = this._X; + + // Iterate the system + nextState.call(this); + + // Generate four keystream words + S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16); + S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16); + S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16); + S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16); + + for (var i = 0; i < 4; i++) { + // Swap endian + S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) | + (((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00); + + // Encrypt + M[offset + i] ^= S[i]; + } + }, + + blockSize: 128/32, + + ivSize: 64/32 + }); + + function nextState() { + // Shortcuts + var X = this._X; + var C = this._C; + + // Save old counter values + for (var i = 0; i < 8; i++) { + C_[i] = C[i]; + } + + // Calculate new counter values + C[0] = (C[0] + 0x4d34d34d + this._b) | 0; + C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0; + C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0; + C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0; + C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0; + C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0; + C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0; + C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0; + this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0; + + // Calculate the g-values + for (var i = 0; i < 8; i++) { + var gx = X[i] + C[i]; + + // Construct high and low argument for squaring + var ga = gx & 0xffff; + var gb = gx >>> 16; + + // Calculate high and low result of squaring + var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb; + var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0); + + // High XOR low + G[i] = gh ^ gl; + } + + // Calculate new state values + X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0; + X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0; + X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0; + X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0; + X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0; + X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0; + X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0; + X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0; + } + + /** + * Shortcut functions to the cipher's object interface. + * + * @example + * + * var ciphertext = CryptoJS.Rabbit.encrypt(message, key, cfg); + * var plaintext = CryptoJS.Rabbit.decrypt(ciphertext, key, cfg); + */ + C.Rabbit = StreamCipher._createHelper(Rabbit); + }()); + + + return CryptoJS.Rabbit; + +})); + +/***/ }), +/* 46 */ +/***/ (function(module, exports, __webpack_require__) { + +;(function (root, factory, undef) { + if (true) { + // CommonJS + module.exports = exports = factory(__webpack_require__(14), __webpack_require__(18), __webpack_require__(19), __webpack_require__(29), __webpack_require__(30)); + } + else {} +}(this, function (CryptoJS) { + + (function () { + // Shortcuts + var C = CryptoJS; + var C_lib = C.lib; + var StreamCipher = C_lib.StreamCipher; + var C_algo = C.algo; + + // Reusable objects + var S = []; + var C_ = []; + var G = []; + + /** + * Rabbit stream cipher algorithm. + * + * This is a legacy version that neglected to convert the key to little-endian. + * This error doesn't affect the cipher's security, + * but it does affect its compatibility with other implementations. + */ + var RabbitLegacy = C_algo.RabbitLegacy = StreamCipher.extend({ + _doReset: function () { + // Shortcuts + var K = this._key.words; + var iv = this.cfg.iv; + + // Generate initial state values + var X = this._X = [ + K[0], (K[3] << 16) | (K[2] >>> 16), + K[1], (K[0] << 16) | (K[3] >>> 16), + K[2], (K[1] << 16) | (K[0] >>> 16), + K[3], (K[2] << 16) | (K[1] >>> 16) + ]; + + // Generate initial counter values + var C = this._C = [ + (K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff), + (K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff), + (K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff), + (K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff) + ]; + + // Carry bit + this._b = 0; + + // Iterate the system four times + for (var i = 0; i < 4; i++) { + nextState.call(this); + } + + // Modify the counters + for (var i = 0; i < 8; i++) { + C[i] ^= X[(i + 4) & 7]; + } + + // IV setup + if (iv) { + // Shortcuts + var IV = iv.words; + var IV_0 = IV[0]; + var IV_1 = IV[1]; + + // Generate four subvectors + var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00); + var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00); + var i1 = (i0 >>> 16) | (i2 & 0xffff0000); + var i3 = (i2 << 16) | (i0 & 0x0000ffff); + + // Modify counter values + C[0] ^= i0; + C[1] ^= i1; + C[2] ^= i2; + C[3] ^= i3; + C[4] ^= i0; + C[5] ^= i1; + C[6] ^= i2; + C[7] ^= i3; + + // Iterate the system four times + for (var i = 0; i < 4; i++) { + nextState.call(this); + } + } + }, + + _doProcessBlock: function (M, offset) { + // Shortcut + var X = this._X; + + // Iterate the system + nextState.call(this); + + // Generate four keystream words + S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16); + S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16); + S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16); + S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16); + + for (var i = 0; i < 4; i++) { + // Swap endian + S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) | + (((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00); + + // Encrypt + M[offset + i] ^= S[i]; + } + }, + + blockSize: 128/32, + + ivSize: 64/32 + }); + + function nextState() { + // Shortcuts + var X = this._X; + var C = this._C; + + // Save old counter values + for (var i = 0; i < 8; i++) { + C_[i] = C[i]; + } + + // Calculate new counter values + C[0] = (C[0] + 0x4d34d34d + this._b) | 0; + C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0; + C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0; + C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0; + C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0; + C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0; + C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0; + C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0; + this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0; + + // Calculate the g-values + for (var i = 0; i < 8; i++) { + var gx = X[i] + C[i]; + + // Construct high and low argument for squaring + var ga = gx & 0xffff; + var gb = gx >>> 16; + + // Calculate high and low result of squaring + var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb; + var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0); + + // High XOR low + G[i] = gh ^ gl; + } + + // Calculate new state values + X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0; + X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0; + X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0; + X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0; + X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0; + X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0; + X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0; + X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0; + } + + /** + * Shortcut functions to the cipher's object interface. + * + * @example + * + * var ciphertext = CryptoJS.RabbitLegacy.encrypt(message, key, cfg); + * var plaintext = CryptoJS.RabbitLegacy.decrypt(ciphertext, key, cfg); + */ + C.RabbitLegacy = StreamCipher._createHelper(RabbitLegacy); + }()); + + + return CryptoJS.RabbitLegacy; + +})); + +/***/ }), +/* 47 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Enums_1 = __webpack_require__(5); +// tslint:disable:max-classes-per-file +/** + * An Exception is considered a condition that a reasonable application may wish to catch. + * An Error indicates serious problems that a reasonable application should not try to catch. + */ +var Exception = /** @class */ (function (_super) { + __extends(Exception, _super); + function Exception(message) { + var _newTarget = this.constructor; + var _this = _super.call(this, message) || this; + Object.setPrototypeOf(_this, _newTarget.prototype); // restore prototype chain + return _this; + } + return Exception; +}(Error)); +exports.Exception = Exception; +var Exceptions; +(function (Exceptions) { + /** + * Indicates that the operation could not be completed given the current transaction state. + */ + var TransactionStateError = /** @class */ (function (_super) { + __extends(TransactionStateError, _super); + function TransactionStateError(message) { + return _super.call(this, message ? message : "Transaction state error.") || this; + } + return TransactionStateError; + }(Exception)); + Exceptions.TransactionStateError = TransactionStateError; + /** + * Indicates the session description handler has closed. + * Occurs when getDescription() or setDescription() are called after close() has been called. + * Occurs when close() is called while getDescription() or setDescription() are in progress. + */ + var ClosedSessionDescriptionHandlerError = /** @class */ (function (_super) { + __extends(ClosedSessionDescriptionHandlerError, _super); + function ClosedSessionDescriptionHandlerError() { + return _super.call(this, "The session description handler has closed.") || this; + } + return ClosedSessionDescriptionHandlerError; + }(Exception)); + Exceptions.ClosedSessionDescriptionHandlerError = ClosedSessionDescriptionHandlerError; + /** + * Indicates the session terminated before the action completed. + */ + var TerminatedSessionError = /** @class */ (function (_super) { + __extends(TerminatedSessionError, _super); + function TerminatedSessionError() { + return _super.call(this, "The session has terminated.") || this; + } + return TerminatedSessionError; + }(Exception)); + Exceptions.TerminatedSessionError = TerminatedSessionError; + /** + * Transport error. + */ + var TransportError = /** @class */ (function (_super) { + __extends(TransportError, _super); + function TransportError(message) { + return _super.call(this, message ? message : "Unspecified transport error.") || this; + } + return TransportError; + }(Exception)); + Exceptions.TransportError = TransportError; + /** + * Unsupported session description content type. + */ + var UnsupportedSessionDescriptionContentTypeError = /** @class */ (function (_super) { + __extends(UnsupportedSessionDescriptionContentTypeError, _super); + function UnsupportedSessionDescriptionContentTypeError(message) { + return _super.call(this, message ? message : "Unsupported session description content type.") || this; + } + return UnsupportedSessionDescriptionContentTypeError; + }(Exception)); + Exceptions.UnsupportedSessionDescriptionContentTypeError = UnsupportedSessionDescriptionContentTypeError; +})(Exceptions = exports.Exceptions || (exports.Exceptions = {})); +/** + * DEPRECATED: The original implementation of exceptions in this library attempted to + * deal with the lack of type checking in JavaScript by adding a "type" attribute + * to objects and using that to discriminate. On top of that it layered allcoated + * "code" numbers and constant "name" strings. All of that is unnecessary when using + * TypeScript, inheriting from Error and properly setting up the prototype chain... + */ +var LegacyException = /** @class */ (function (_super) { + __extends(LegacyException, _super); + function LegacyException(code, name, message) { + var _this = _super.call(this, message) || this; + _this.code = code; + _this.name = name; + _this.message = message; + return _this; + } + return LegacyException; +}(Exception)); +(function (Exceptions) { + var ConfigurationError = /** @class */ (function (_super) { + __extends(ConfigurationError, _super); + function ConfigurationError(parameter, value) { + var _this = _super.call(this, 1, "CONFIGURATION_ERROR", (!value) ? "Missing parameter: " + parameter : + "Invalid value " + JSON.stringify(value) + " for parameter '" + parameter + "'") || this; + _this.type = Enums_1.TypeStrings.ConfigurationError; + _this.parameter = parameter; + _this.value = value; + return _this; + } + return ConfigurationError; + }(LegacyException)); + Exceptions.ConfigurationError = ConfigurationError; + var InvalidStateError = /** @class */ (function (_super) { + __extends(InvalidStateError, _super); + function InvalidStateError(status) { + var _this = _super.call(this, 2, "INVALID_STATE_ERROR", "Invalid status: " + status) || this; + _this.type = Enums_1.TypeStrings.InvalidStateError; + _this.status = status; + return _this; + } + return InvalidStateError; + }(LegacyException)); + Exceptions.InvalidStateError = InvalidStateError; + var NotSupportedError = /** @class */ (function (_super) { + __extends(NotSupportedError, _super); + function NotSupportedError(message) { + var _this = _super.call(this, 3, "NOT_SUPPORTED_ERROR", message) || this; + _this.type = Enums_1.TypeStrings.NotSupportedError; + return _this; + } + return NotSupportedError; + }(LegacyException)); + Exceptions.NotSupportedError = NotSupportedError; + // 4 was GetDescriptionError, which was deprecated and now removed + var RenegotiationError = /** @class */ (function (_super) { + __extends(RenegotiationError, _super); + function RenegotiationError(message) { + var _this = _super.call(this, 5, "RENEGOTIATION_ERROR", message) || this; + _this.type = Enums_1.TypeStrings.RenegotiationError; + return _this; + } + return RenegotiationError; + }(LegacyException)); + Exceptions.RenegotiationError = RenegotiationError; + var MethodParameterError = /** @class */ (function (_super) { + __extends(MethodParameterError, _super); + function MethodParameterError(method, parameter, value) { + var _this = _super.call(this, 6, "METHOD_PARAMETER_ERROR", (!value) ? + "Missing parameter: " + parameter : + "Invalid value " + JSON.stringify(value) + " for parameter '" + parameter + "'") || this; + _this.type = Enums_1.TypeStrings.MethodParameterError; + _this.method = method; + _this.parameter = parameter; + _this.value = value; + return _this; + } + return MethodParameterError; + }(LegacyException)); + Exceptions.MethodParameterError = MethodParameterError; + // 7 was TransportError, which was replaced + var SessionDescriptionHandlerError = /** @class */ (function (_super) { + __extends(SessionDescriptionHandlerError, _super); + function SessionDescriptionHandlerError(method, error, message) { + var _this = _super.call(this, 8, "SESSION_DESCRIPTION_HANDLER_ERROR", message || "Error with Session Description Handler") || this; + _this.type = Enums_1.TypeStrings.SessionDescriptionHandlerError; + _this.method = method; + _this.error = error; + return _this; + } + return SessionDescriptionHandlerError; + }(LegacyException)); + Exceptions.SessionDescriptionHandlerError = SessionDescriptionHandlerError; +})(Exceptions = exports.Exceptions || (exports.Exceptions = {})); + + +/***/ }), +/* 48 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +var Enums_1 = __webpack_require__(5); +var Levels; +(function (Levels) { + Levels[Levels["error"] = 0] = "error"; + Levels[Levels["warn"] = 1] = "warn"; + Levels[Levels["log"] = 2] = "log"; + Levels[Levels["debug"] = 3] = "debug"; +})(Levels = exports.Levels || (exports.Levels = {})); +var LoggerFactory = /** @class */ (function () { + function LoggerFactory() { + this.builtinEnabled = true; + // tslint:disable-next-line:variable-name + this._level = Levels.log; + this.loggers = {}; + this.type = Enums_1.TypeStrings.LoggerFactory; + this.logger = this.getLogger("sip:loggerfactory"); + } + Object.defineProperty(LoggerFactory.prototype, "level", { + get: function () { return this._level; }, + set: function (newLevel) { + if (newLevel >= 0 && newLevel <= 3) { + this._level = newLevel; + } + else if (newLevel > 3) { + this._level = 3; + } + else if (Levels.hasOwnProperty(newLevel)) { + this._level = newLevel; + } + else { + this.logger.error("invalid 'level' parameter value: " + JSON.stringify(newLevel)); + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(LoggerFactory.prototype, "connector", { + get: function () { + return this._connector; + }, + set: function (value) { + if (!value) { + this._connector = undefined; + } + else if (typeof value === "function") { + this._connector = value; + } + else { + this.logger.error("invalid 'connector' parameter value: " + JSON.stringify(value)); + } + }, + enumerable: true, + configurable: true + }); + LoggerFactory.prototype.getLogger = function (category, label) { + if (label && this.level === 3) { + return new Logger(this, category, label); + } + else if (this.loggers[category]) { + return this.loggers[category]; + } + else { + var logger = new Logger(this, category); + this.loggers[category] = logger; + return logger; + } + }; + LoggerFactory.prototype.genericLog = function (levelToLog, category, label, content) { + if (this.level >= levelToLog) { + if (this.builtinEnabled) { + this.print(levelToLog, category, label, content); + } + } + if (this.connector) { + this.connector(Levels[levelToLog], category, label, content); + } + }; + LoggerFactory.prototype.print = function (levelToLog, category, label, content) { + if (typeof content === "string") { + var prefix = [new Date(), category]; + if (label) { + prefix.push(label); + } + content = prefix.concat(content).join(" | "); + } + switch (levelToLog) { + case Levels.error: + // tslint:disable-next-line:no-console + console.error(content); + break; + case Levels.warn: + // tslint:disable-next-line:no-console + console.warn(content); + break; + case Levels.log: + // tslint:disable-next-line:no-console + console.log(content); + break; + case Levels.debug: + // tslint:disable-next-line:no-console + console.debug(content); + break; + default: + break; + } + }; + return LoggerFactory; +}()); +exports.LoggerFactory = LoggerFactory; +// tslint:disable-next-line:max-classes-per-file +var Logger = /** @class */ (function () { + function Logger(logger, category, label) { + this.type = Enums_1.TypeStrings.Logger; + this.logger = logger; + this.category = category; + this.label = label; + } + Logger.prototype.error = function (content) { this.genericLog(Levels.error, content); }; + Logger.prototype.warn = function (content) { this.genericLog(Levels.warn, content); }; + Logger.prototype.log = function (content) { this.genericLog(Levels.log, content); }; + Logger.prototype.debug = function (content) { this.genericLog(Levels.debug, content); }; + Logger.prototype.genericLog = function (level, content) { + this.logger.genericLog(level, this.category, this.label, content); + }; + return Logger; +}()); +exports.Logger = Logger; + + +/***/ }), +/* 49 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +var Enums_1 = __webpack_require__(5); +var Grammar_1 = __webpack_require__(7); +var SIPMessage_1 = __webpack_require__(6); +// SIP.Parser = Parser; +/** + * Extract and parse every header of a SIP message. + * @namespace + */ +var Parser; +(function (Parser) { + function getHeader(data, headerStart) { + // 'start' position of the header. + var start = headerStart; + // 'end' position of the header. + var end = 0; + // 'partial end' position of the header. + var partialEnd = 0; + // End of message. + if (data.substring(start, start + 2).match(/(^\r\n)/)) { + return -2; + } + while (end === 0) { + // Partial End of Header. + partialEnd = data.indexOf("\r\n", start); + // 'indexOf' returns -1 if the value to be found never occurs. + if (partialEnd === -1) { + return partialEnd; + } + if (!data.substring(partialEnd + 2, partialEnd + 4).match(/(^\r\n)/) && + data.charAt(partialEnd + 2).match(/(^\s+)/)) { + // Not the end of the message. Continue from the next position. + start = partialEnd + 2; + } + else { + end = partialEnd; + } + } + return end; + } + Parser.getHeader = getHeader; + function parseHeader(message, data, headerStart, headerEnd) { + var hcolonIndex = data.indexOf(":", headerStart); + var headerName = data.substring(headerStart, hcolonIndex).trim(); + var headerValue = data.substring(hcolonIndex + 1, headerEnd).trim(); + var parsed; + // If header-field is well-known, parse it. + switch (headerName.toLowerCase()) { + case "via": + case "v": + message.addHeader("via", headerValue); + if (message.getHeaders("via").length === 1) { + parsed = message.parseHeader("Via"); + if (parsed) { + message.via = parsed; + message.viaBranch = parsed.branch; + } + } + else { + parsed = 0; + } + break; + case "from": + case "f": + message.setHeader("from", headerValue); + parsed = message.parseHeader("from"); + if (parsed) { + message.from = parsed; + message.fromTag = parsed.getParam("tag"); + } + break; + case "to": + case "t": + message.setHeader("to", headerValue); + parsed = message.parseHeader("to"); + if (parsed) { + message.to = parsed; + message.toTag = parsed.getParam("tag"); + } + break; + case "record-route": + parsed = Grammar_1.Grammar.parse(headerValue, "Record_Route"); + if (parsed === -1) { + parsed = undefined; + break; + } + for (var header in parsed) { + if (parsed[header]) { + message.addHeader("record-route", headerValue.substring(parsed[header].position, parsed[header].offset)); + message.headers["Record-Route"][message.getHeaders("record-route").length - 1].parsed = + parsed[header].parsed; + } + } + break; + case "call-id": + case "i": + message.setHeader("call-id", headerValue); + parsed = message.parseHeader("call-id"); + if (parsed) { + message.callId = headerValue; + } + break; + case "contact": + case "m": + parsed = Grammar_1.Grammar.parse(headerValue, "Contact"); + if (parsed === -1) { + parsed = undefined; + break; + } + if (!(parsed instanceof Array)) { + parsed = undefined; + break; + } + parsed.forEach(function (header) { + message.addHeader("contact", headerValue.substring(header.position, header.offset)); + message.headers.Contact[message.getHeaders("contact").length - 1].parsed = header.parsed; + }); + break; + case "content-length": + case "l": + message.setHeader("content-length", headerValue); + parsed = message.parseHeader("content-length"); + break; + case "content-type": + case "c": + message.setHeader("content-type", headerValue); + parsed = message.parseHeader("content-type"); + break; + case "cseq": + message.setHeader("cseq", headerValue); + parsed = message.parseHeader("cseq"); + if (parsed) { + message.cseq = parsed.value; + } + if (message.type === Enums_1.TypeStrings.IncomingResponse) { + message.method = parsed.method; + } + break; + case "max-forwards": + message.setHeader("max-forwards", headerValue); + parsed = message.parseHeader("max-forwards"); + break; + case "www-authenticate": + message.setHeader("www-authenticate", headerValue); + parsed = message.parseHeader("www-authenticate"); + break; + case "proxy-authenticate": + message.setHeader("proxy-authenticate", headerValue); + parsed = message.parseHeader("proxy-authenticate"); + break; + case "refer-to": + case "r": + message.setHeader("refer-to", headerValue); + parsed = message.parseHeader("refer-to"); + if (parsed) { + message.referTo = parsed; + } + break; + default: + // Do not parse this header. + message.setHeader(headerName, headerValue); + parsed = 0; + } + if (parsed === undefined) { + return { + error: "error parsing header '" + headerName + "'" + }; + } + else { + return true; + } + } + Parser.parseHeader = parseHeader; + /** Parse SIP Message + * @function + * @param {String} message SIP message. + * @param {Object} logger object. + * @returns {SIP.IncomingRequest|SIP.IncomingResponse|undefined} + */ + function parseMessage(data, ua) { + var headerStart = 0; + var headerEnd = data.indexOf("\r\n"); + var logger = ua.getLogger("sip.parser"); + if (headerEnd === -1) { + logger.warn("no CRLF found, not a SIP message, discarded"); + return; + } + // Parse first line. Check if it is a Request or a Reply. + var firstLine = data.substring(0, headerEnd); + var parsed = Grammar_1.Grammar.parse(firstLine, "Request_Response"); + var message; + if (parsed === -1) { + logger.warn('error parsing first line of SIP message: "' + firstLine + '"'); + return; + } + else if (!parsed.status_code) { + message = new SIPMessage_1.IncomingRequest(ua); + message.method = parsed.method; + message.ruri = parsed.uri; + } + else { + message = new SIPMessage_1.IncomingResponse(ua); + message.statusCode = parsed.status_code; + message.reasonPhrase = parsed.reason_phrase; + } + message.data = data; + headerStart = headerEnd + 2; + /* Loop over every line in data. Detect the end of each header and parse + * it or simply add to the headers collection. + */ + var bodyStart; + while (true) { + headerEnd = getHeader(data, headerStart); + // The SIP message has normally finished. + if (headerEnd === -2) { + bodyStart = headerStart + 2; + break; + } + else if (headerEnd === -1) { + // data.indexOf returned -1 due to a malformed message. + logger.error("malformed message"); + return; + } + var parsedHeader = parseHeader(message, data, headerStart, headerEnd); + if (parsedHeader !== true) { + logger.error(parsed.error); + return; + } + headerStart = headerEnd + 2; + } + /* RFC3261 18.3. + * If there are additional bytes in the transport packet + * beyond the end of the body, they MUST be discarded. + */ + if (message.hasHeader("content-length")) { + message.body = data.substr(bodyStart, Number(message.getHeader("content-length"))); + } + else { + message.body = data.substring(bodyStart); + } + return message; + } + Parser.parseMessage = parseMessage; +})(Parser = exports.Parser || (exports.Parser = {})); + + +/***/ }), +/* 50 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var ClientContext_1 = __webpack_require__(1); +var Constants_1 = __webpack_require__(3); +var Enums_1 = __webpack_require__(5); +var Exceptions_1 = __webpack_require__(47); +var SIPMessage_1 = __webpack_require__(6); +var Utils_1 = __webpack_require__(11); +/** + * SIP Publish (SIP Extension for Event State Publication RFC3903) + * @class Class creating a SIP PublishContext. + */ +var PublishContext = /** @class */ (function (_super) { + __extends(PublishContext, _super); + function PublishContext(ua, target, event, options) { + if (options === void 0) { options = {}; } + var _this = this; + options.extraHeaders = (options.extraHeaders || []).slice(); + options.contentType = (options.contentType || "text/plain"); + if (typeof options.expires !== "number" || (options.expires % 1) !== 0) { + options.expires = 3600; + } + else { + options.expires = Number(options.expires); + } + if (typeof (options.unpublishOnClose) !== "boolean") { + options.unpublishOnClose = true; + } + if (target === undefined || target === null || target === "") { + throw new Exceptions_1.Exceptions.MethodParameterError("Publish", "Target", target); + } + else { + target = ua.normalizeTarget(target); + if (target === undefined) { + throw new Exceptions_1.Exceptions.MethodParameterError("Publish", "Target", target); + } + } + _this = _super.call(this, ua, Constants_1.C.PUBLISH, target, options) || this; + _this.type = Enums_1.TypeStrings.PublishContext; + _this.options = options; + _this.target = target; + if (event === undefined || event === null || event === "") { + throw new Exceptions_1.Exceptions.MethodParameterError("Publish", "Event", event); + } + else { + _this.event = event; + } + _this.logger = ua.getLogger("sip.publish"); + _this.pubRequestExpires = _this.options.expires; + ua.on("transportCreated", function (transport) { + transport.on("transportError", function () { return _this.onTransportError(); }); + }); + return _this; + } + /** + * Publish + * @param {string} Event body to publish, optional + */ + PublishContext.prototype.publish = function (body) { + // Clean up before the run + if (this.publishRefreshTimer) { + clearTimeout(this.publishRefreshTimer); + this.publishRefreshTimer = undefined; + } + // is Inital or Modify request + this.options.body = body; + this.pubRequestBody = this.options.body; + if (this.pubRequestExpires === 0) { + // This is Initial request after unpublish + this.pubRequestExpires = this.options.expires; + this.pubRequestEtag = undefined; + } + if (!(this.ua.publishers[this.target.toString() + ":" + this.event])) { + this.ua.publishers[this.target.toString() + ":" + this.event] = this; + } + this.sendPublishRequest(); + }; + /** + * Unpublish + */ + PublishContext.prototype.unpublish = function () { + // Clean up before the run + if (this.publishRefreshTimer) { + clearTimeout(this.publishRefreshTimer); + this.publishRefreshTimer = undefined; + } + this.pubRequestBody = undefined; + this.pubRequestExpires = 0; + if (this.pubRequestEtag !== undefined) { + this.sendPublishRequest(); + } + }; + /** + * Close + */ + PublishContext.prototype.close = function () { + // Send unpublish, if requested + if (this.options.unpublishOnClose) { + this.unpublish(); + } + else { + if (this.publishRefreshTimer) { + clearTimeout(this.publishRefreshTimer); + this.publishRefreshTimer = undefined; + } + this.pubRequestBody = undefined; + this.pubRequestExpires = 0; + this.pubRequestEtag = undefined; + } + if (this.ua.publishers[this.target.toString() + ":" + this.event]) { + delete this.ua.publishers[this.target.toString() + ":" + this.event]; + } + }; + PublishContext.prototype.onRequestTimeout = function () { + _super.prototype.onRequestTimeout.call(this); + this.emit("unpublished", undefined, Constants_1.C.causes.REQUEST_TIMEOUT); + }; + PublishContext.prototype.onTransportError = function () { + _super.prototype.onTransportError.call(this); + this.emit("unpublished", undefined, Constants_1.C.causes.CONNECTION_ERROR); + }; + PublishContext.prototype.receiveResponse = function (response) { + var _this = this; + var statusCode = response.statusCode || 0; + var cause = Utils_1.Utils.getReasonPhrase(statusCode); + switch (true) { + case /^1[0-9]{2}$/.test(statusCode.toString()): + this.emit("progress", response, cause); + break; + case /^2[0-9]{2}$/.test(statusCode.toString()): + // Set SIP-Etag + if (response.hasHeader("SIP-ETag")) { + this.pubRequestEtag = response.getHeader("SIP-ETag"); + } + else { + this.logger.warn("SIP-ETag header missing in a 200-class response to PUBLISH"); + } + // Update Expire + if (response.hasHeader("Expires")) { + var expires = Number(response.getHeader("Expires")); + if (typeof expires === "number" && expires >= 0 && expires <= this.pubRequestExpires) { + this.pubRequestExpires = expires; + } + else { + this.logger.warn("Bad Expires header in a 200-class response to PUBLISH"); + } + } + else { + this.logger.warn("Expires header missing in a 200-class response to PUBLISH"); + } + if (this.pubRequestExpires !== 0) { + // Schedule refresh + this.publishRefreshTimer = setTimeout(function () { return _this.refreshRequest(); }, this.pubRequestExpires * 900); + this.emit("published", response, cause); + } + else { + this.emit("unpublished", response, cause); + } + break; + case /^412$/.test(statusCode.toString()): + // 412 code means no matching ETag - possibly the PUBLISH expired + // Resubmit as new request, if the current request is not a "remove" + if (this.pubRequestEtag !== undefined && this.pubRequestExpires !== 0) { + this.logger.warn("412 response to PUBLISH, recovering"); + this.pubRequestEtag = undefined; + this.emit("progress", response, cause); + this.publish(this.options.body); + } + else { + this.logger.warn("412 response to PUBLISH, recovery failed"); + this.pubRequestExpires = 0; + this.emit("failed", response, cause); + this.emit("unpublished", response, cause); + } + break; + case /^423$/.test(statusCode.toString()): + // 423 code means we need to adjust the Expires interval up + if (this.pubRequestExpires !== 0 && response.hasHeader("Min-Expires")) { + var minExpires = Number(response.getHeader("Min-Expires")); + if (typeof minExpires === "number" || minExpires > this.pubRequestExpires) { + this.logger.warn("423 code in response to PUBLISH, adjusting the Expires value and trying to recover"); + this.pubRequestExpires = minExpires; + this.emit("progress", response, cause); + this.publish(this.options.body); + } + else { + this.logger.warn("Bad 423 response Min-Expires header received for PUBLISH"); + this.pubRequestExpires = 0; + this.emit("failed", response, cause); + this.emit("unpublished", response, cause); + } + } + else { + this.logger.warn("423 response to PUBLISH, recovery failed"); + this.pubRequestExpires = 0; + this.emit("failed", response, cause); + this.emit("unpublished", response, cause); + } + break; + default: + this.pubRequestExpires = 0; + this.emit("failed", response, cause); + this.emit("unpublished", response, cause); + break; + } + // Do the cleanup + if (this.pubRequestExpires === 0) { + if (this.publishRefreshTimer) { + clearTimeout(this.publishRefreshTimer); + this.publishRefreshTimer = undefined; + } + this.pubRequestBody = undefined; + this.pubRequestEtag = undefined; + } + }; + PublishContext.prototype.send = function () { + var _this = this; + this.ua.userAgentCore.publish(this.request, { + onAccept: function (response) { return _this.receiveResponse(response.message); }, + onProgress: function (response) { return _this.receiveResponse(response.message); }, + onRedirect: function (response) { return _this.receiveResponse(response.message); }, + onReject: function (response) { return _this.receiveResponse(response.message); }, + onTrying: function (response) { return _this.receiveResponse(response.message); } + }); + return this; + }; + PublishContext.prototype.refreshRequest = function () { + // Clean up before the run + if (this.publishRefreshTimer) { + clearTimeout(this.publishRefreshTimer); + this.publishRefreshTimer = undefined; + } + // This is Refresh request + this.pubRequestBody = undefined; + if (this.pubRequestEtag === undefined) { + // Request not valid + throw new Exceptions_1.Exceptions.MethodParameterError("Publish", "Body", undefined); + } + if (this.pubRequestExpires === 0) { + // Request not valid + throw new Exceptions_1.Exceptions.MethodParameterError("Publish", "Expire", this.pubRequestExpires); + } + this.sendPublishRequest(); + }; + PublishContext.prototype.sendPublishRequest = function () { + var reqOptions = Object.create(this.options || Object.prototype); + reqOptions.extraHeaders = (this.options.extraHeaders || []).slice(); + reqOptions.extraHeaders.push("Event: " + this.event); + reqOptions.extraHeaders.push("Expires: " + this.pubRequestExpires); + if (this.pubRequestEtag !== undefined) { + reqOptions.extraHeaders.push("SIP-If-Match: " + this.pubRequestEtag); + } + this.request = new SIPMessage_1.OutgoingRequest(Constants_1.C.PUBLISH, this.target, this.ua, this.options.params, reqOptions.extraHeaders); + if (this.pubRequestBody !== undefined) { + this.request.body = { + body: this.pubRequestBody, + contentType: this.options.contentType + }; + } + this.send(); + }; + return PublishContext; +}(ClientContext_1.ClientContext)); +exports.PublishContext = PublishContext; + + +/***/ }), +/* 51 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var ClientContext_1 = __webpack_require__(1); +var Constants_1 = __webpack_require__(3); +var transactions_1 = __webpack_require__(52); +var Enums_1 = __webpack_require__(5); +var Exceptions_1 = __webpack_require__(47); +var Grammar_1 = __webpack_require__(7); +var ServerContext_1 = __webpack_require__(62); +var SIPMessage_1 = __webpack_require__(6); +// tslint:disable-next-line:max-classes-per-file +var ReferClientContext = /** @class */ (function (_super) { + __extends(ReferClientContext, _super); + function ReferClientContext(ua, applicant, target, options) { + if (options === void 0) { options = {}; } + var _this = this; + if (ua === undefined || applicant === undefined || target === undefined) { + throw new TypeError("Not enough arguments"); + } + _this = _super.call(this, ua, Constants_1.C.REFER, applicant.remoteIdentity.uri.toString(), options) || this; + _this.type = Enums_1.TypeStrings.ReferClientContext; + _this.options = options; + _this.extraHeaders = (_this.options.extraHeaders || []).slice(); + _this.applicant = applicant; + _this.target = _this.initReferTo(target); + if (_this.ua) { + _this.extraHeaders.push("Referred-By: <" + _this.ua.configuration.uri + ">"); + } + // TODO: Check that this is correct isc/icc + _this.extraHeaders.push("Contact: " + applicant.contact); + // this is UA.C.ALLOWED_METHODS, removed to get around circular dependency + _this.extraHeaders.push("Allow: " + [ + "ACK", + "CANCEL", + "INVITE", + "MESSAGE", + "BYE", + "OPTIONS", + "INFO", + "NOTIFY", + "REFER" + ].toString()); + _this.extraHeaders.push("Refer-To: " + _this.target); + _this.errorListener = _this.onTransportError.bind(_this); + if (ua.transport) { + ua.transport.on("transportError", _this.errorListener); + } + return _this; + } + ReferClientContext.prototype.refer = function (options) { + var _this = this; + if (options === void 0) { options = {}; } + var extraHeaders = (this.extraHeaders || []).slice(); + if (options.extraHeaders) { + extraHeaders.concat(options.extraHeaders); + } + this.applicant.sendRequest(Constants_1.C.REFER, { + extraHeaders: this.extraHeaders, + receiveResponse: function (response) { + var statusCode = response && response.statusCode ? response.statusCode.toString() : ""; + if (/^1[0-9]{2}$/.test(statusCode)) { + _this.emit("referRequestProgress", _this); + } + else if (/^2[0-9]{2}$/.test(statusCode)) { + _this.emit("referRequestAccepted", _this); + } + else if (/^[4-6][0-9]{2}$/.test(statusCode)) { + _this.emit("referRequestRejected", _this); + } + if (options.receiveResponse) { + options.receiveResponse(response); + } + } + }); + return this; + }; + ReferClientContext.prototype.receiveNotify = function (request) { + // If we can correctly handle this, then we need to send a 200 OK! + var contentType = request.message.hasHeader("Content-Type") ? + request.message.getHeader("Content-Type") : undefined; + if (contentType && contentType.search(/^message\/sipfrag/) !== -1) { + var messageBody = Grammar_1.Grammar.parse(request.message.body, "sipfrag"); + if (messageBody === -1) { + request.reject({ + statusCode: 489, + reasonPhrase: "Bad Event" + }); + return; + } + switch (true) { + case (/^1[0-9]{2}$/.test(messageBody.status_code)): + this.emit("referProgress", this); + break; + case (/^2[0-9]{2}$/.test(messageBody.status_code)): + this.emit("referAccepted", this); + if (!this.options.activeAfterTransfer && this.applicant.terminate) { + this.applicant.terminate(); + } + break; + default: + this.emit("referRejected", this); + break; + } + request.accept(); + this.emit("notify", request.message); + return; + } + request.reject({ + statusCode: 489, + reasonPhrase: "Bad Event" + }); + }; + ReferClientContext.prototype.initReferTo = function (target) { + var stringOrURI; + if (typeof target === "string") { + // REFER without Replaces (Blind Transfer) + var targetString = Grammar_1.Grammar.parse(target, "Refer_To"); + stringOrURI = targetString && targetString.uri ? targetString.uri : target; + // Check target validity + var targetUri = this.ua.normalizeTarget(target); + if (!targetUri) { + throw new TypeError("Invalid target: " + target); + } + stringOrURI = targetUri; + } + else { + // REFER with Replaces (Attended Transfer) + if (!target.session) { + throw new Error("Session undefined."); + } + var displayName = target.remoteIdentity.friendlyName; + var remoteTarget = target.session.remoteTarget.toString(); + var callId = target.session.callId; + var remoteTag = target.session.remoteTag; + var localTag = target.session.localTag; + var replaces = encodeURIComponent(callId + ";to-tag=" + remoteTag + ";from-tag=" + localTag); + stringOrURI = "\"" + displayName + "\" <" + remoteTarget + "?Replaces=" + replaces + ">"; + } + return stringOrURI; + }; + return ReferClientContext; +}(ClientContext_1.ClientContext)); +exports.ReferClientContext = ReferClientContext; +// tslint:disable-next-line:max-classes-per-file +var ReferServerContext = /** @class */ (function (_super) { + __extends(ReferServerContext, _super); + function ReferServerContext(ua, incomingRequest, session) { + var _this = _super.call(this, ua, incomingRequest) || this; + _this.session = session; + _this.type = Enums_1.TypeStrings.ReferServerContext; + _this.ua = ua; + _this.status = Enums_1.SessionStatus.STATUS_INVITE_RECEIVED; + _this.fromTag = _this.request.fromTag; + _this.id = _this.request.callId + _this.fromTag; + _this.contact = _this.ua.contact.toString(); + _this.logger = ua.getLogger("sip.referservercontext", _this.id); + // Needed to send the NOTIFY's + _this.cseq = Math.floor(Math.random() * 10000); + _this.callId = _this.request.callId; + _this.fromUri = _this.request.to.uri; + _this.fromTag = _this.request.to.parameters.tag; + _this.remoteTarget = _this.request.headers.Contact[0].parsed.uri; + _this.toUri = _this.request.from.uri; + _this.toTag = _this.request.fromTag; + _this.routeSet = _this.request.getHeaders("record-route"); + // RFC 3515 2.4.1 + if (!_this.request.hasHeader("refer-to")) { + _this.logger.warn("Invalid REFER packet. A refer-to header is required. Rejecting refer."); + _this.reject(); + return _this; + } + _this.referTo = _this.request.parseHeader("refer-to"); + // TODO: Must set expiration timer and send 202 if there is no response by then + _this.referredSession = _this.ua.findSession(_this.request); + if (_this.request.hasHeader("referred-by")) { + _this.referredBy = _this.request.getHeader("referred-by"); + } + if (_this.referTo.uri.hasHeader("replaces")) { + _this.replaces = _this.referTo.uri.getHeader("replaces"); + } + _this.errorListener = _this.onTransportError.bind(_this); + if (ua.transport) { + ua.transport.on("transportError", _this.errorListener); + } + _this.status = Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER; + return _this; + } + ReferServerContext.prototype.progress = function () { + if (this.status !== Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER) { + throw new Exceptions_1.Exceptions.InvalidStateError(this.status); + } + this.incomingRequest.trying(); + }; + ReferServerContext.prototype.reject = function (options) { + if (options === void 0) { options = {}; } + if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { + throw new Exceptions_1.Exceptions.InvalidStateError(this.status); + } + this.logger.log("Rejecting refer"); + this.status = Enums_1.SessionStatus.STATUS_TERMINATED; + _super.prototype.reject.call(this, options); + this.emit("referRequestRejected", this); + }; + ReferServerContext.prototype.accept = function (options, modifiers) { + var _this = this; + if (options === void 0) { options = {}; } + if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER) { + this.status = Enums_1.SessionStatus.STATUS_ANSWERED; + } + else { + throw new Exceptions_1.Exceptions.InvalidStateError(this.status); + } + this.incomingRequest.accept({ + statusCode: 202, + reasonPhrase: "Accepted" + }); + this.emit("referRequestAccepted", this); + if (options.followRefer) { + this.logger.log("Accepted refer, attempting to automatically follow it"); + var target = this.referTo.uri; + if (!target.scheme || !target.scheme.match("^sips?$")) { + this.logger.error("SIP.js can only automatically follow SIP refer target"); + this.reject(); + return; + } + var inviteOptions = options.inviteOptions || {}; + var extraHeaders = (inviteOptions.extraHeaders || []).slice(); + if (this.replaces) { + // decodeURIComponent is a holdover from 2c086eb4. Not sure that it is actually necessary + extraHeaders.push("Replaces: " + decodeURIComponent(this.replaces)); + } + if (this.referredBy) { + extraHeaders.push("Referred-By: " + this.referredBy); + } + inviteOptions.extraHeaders = extraHeaders; + target.clearHeaders(); + this.targetSession = this.ua.invite(target.toString(), inviteOptions, modifiers); + this.emit("referInviteSent", this); + if (this.targetSession) { + this.targetSession.once("progress", function (response) { + var statusCode = response.statusCode || 100; + var reasonPhrase = response.reasonPhrase; + _this.sendNotify(("SIP/2.0 " + statusCode + " " + reasonPhrase).trim()); + _this.emit("referProgress", _this); + if (_this.referredSession) { + _this.referredSession.emit("referProgress", _this); + } + }); + this.targetSession.once("accepted", function () { + _this.logger.log("Successfully followed the refer"); + _this.sendNotify("SIP/2.0 200 OK"); + _this.emit("referAccepted", _this); + if (_this.referredSession) { + _this.referredSession.emit("referAccepted", _this); + } + }); + var referFailed = function (response) { + if (_this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { + return; // No throw here because it is possible this gets called multiple times + } + _this.logger.log("Refer was not successful. Resuming session"); + if (response && response.statusCode === 429) { + _this.logger.log("Alerting referrer that identity is required."); + _this.sendNotify("SIP/2.0 429 Provide Referrer Identity"); + return; + } + _this.sendNotify("SIP/2.0 603 Declined"); + // Must change the status after sending the final Notify or it will not send due to check + _this.status = Enums_1.SessionStatus.STATUS_TERMINATED; + _this.emit("referRejected", _this); + if (_this.referredSession) { + _this.referredSession.emit("referRejected"); + } + }; + this.targetSession.once("rejected", referFailed); + this.targetSession.once("failed", referFailed); + } + } + else { + this.logger.log("Accepted refer, but did not automatically follow it"); + this.sendNotify("SIP/2.0 200 OK"); + this.emit("referAccepted", this); + if (this.referredSession) { + this.referredSession.emit("referAccepted", this); + } + } + }; + ReferServerContext.prototype.sendNotify = function (body) { + // FIXME: Ported this. Clean it up. Session knows its state. + if (this.status !== Enums_1.SessionStatus.STATUS_ANSWERED) { + throw new Exceptions_1.Exceptions.InvalidStateError(this.status); + } + if (Grammar_1.Grammar.parse(body, "sipfrag") === -1) { + throw new Error("sipfrag body is required to send notify for refer"); + } + // NOTIFY requests sent in same dialog as in dialog REFER. + if (this.session) { + this.session.notify(undefined, { + extraHeaders: [ + "Event: refer", + "Subscription-State: terminated", + ], + body: { + contentDisposition: "render", + contentType: "message/sipfrag", + content: body + } + }); + return; + } + // The implicit subscription created by a REFER is the same as a + // subscription created with a SUBSCRIBE request. The agent issuing the + // REFER can terminate this subscription prematurely by unsubscribing + // using the mechanisms described in [2]. Terminating a subscription, + // either by explicitly unsubscribing or rejecting NOTIFY, is not an + // indication that the referenced request should be withdrawn or + // abandoned. + // https://tools.ietf.org/html/rfc3515#section-2.4.4 + // NOTIFY requests sent in new dialog for out of dialog REFER. + // FIXME: TODO: This should be done in a subscribe dialog to satisfy the above. + var request = new SIPMessage_1.OutgoingRequest(Constants_1.C.NOTIFY, this.remoteTarget, this.ua, { + cseq: this.cseq += 1, + callId: this.callId, + fromUri: this.fromUri, + fromTag: this.fromTag, + toUri: this.toUri, + toTag: this.toTag, + routeSet: this.routeSet + }, [ + "Event: refer", + "Subscription-State: terminated", + "Content-Type: message/sipfrag" + ], body); + var transport = this.ua.transport; + if (!transport) { + throw new Error("Transport undefined."); + } + var user = { + loggerFactory: this.ua.getLoggerFactory() + }; + var nic = new transactions_1.NonInviteClientTransaction(request, transport, user); + }; + ReferServerContext.prototype.on = function (name, callback) { return _super.prototype.on.call(this, name, callback); }; + return ReferServerContext; +}(ServerContext_1.ServerContext)); +exports.ReferServerContext = ReferServerContext; + + +/***/ }), +/* 52 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +function __export(m) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; +} +Object.defineProperty(exports, "__esModule", { value: true }); +__export(__webpack_require__(53)); +__export(__webpack_require__(55)); +__export(__webpack_require__(58)); +__export(__webpack_require__(60)); +__export(__webpack_require__(61)); +__export(__webpack_require__(55)); +__export(__webpack_require__(59)); +__export(__webpack_require__(57)); +__export(__webpack_require__(54)); + + +/***/ }), +/* 53 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var transaction_1 = __webpack_require__(54); +/** + * Client Transaction + * + * The client transaction provides its functionality through the + * maintenance of a state machine. + * + * The TU communicates with the client transaction through a simple + * interface. When the TU wishes to initiate a new transaction, it + * creates a client transaction and passes it the SIP request to send + * and an IP address, port, and transport to which to send it. The + * client transaction begins execution of its state machine. Valid + * responses are passed up to the TU from the client transaction. + * https://tools.ietf.org/html/rfc3261#section-17.1 + */ +var ClientTransaction = /** @class */ (function (_super) { + __extends(ClientTransaction, _super); + function ClientTransaction(_request, transport, user, state, loggerCategory) { + var _this = _super.call(this, transport, user, ClientTransaction.makeId(_request), state, loggerCategory) || this; + _this._request = _request; + _this.user = user; + // The Via header field indicates the transport used for the transaction + // and identifies the location where the response is to be sent. A Via + // header field value is added only after the transport that will be + // used to reach the next hop has been selected (which may involve the + // usage of the procedures in [4]). + // https://tools.ietf.org/html/rfc3261#section-8.1.1.7 + _request.setViaHeader(_this.id, transport); + return _this; + } + ClientTransaction.makeId = function (request) { + if (request.method === "CANCEL") { + if (!request.branch) { + throw new Error("Outgoing CANCEL request without a branch."); + } + return request.branch; + } + else { + return "z9hG4bK" + Math.floor(Math.random() * 10000000); + } + }; + Object.defineProperty(ClientTransaction.prototype, "request", { + /** The outgoing request the transaction handling. */ + get: function () { + return this._request; + }, + enumerable: true, + configurable: true + }); + /** + * A 408 to non-INVITE will always arrive too late to be useful ([3]), + * The client already has full knowledge of the timeout. The only + * information this message would convey is whether or not the server + * believed the transaction timed out. However, with the current design + * of the NIT, a client cannot do anything with this knowledge. Thus, + * the 408 is simply wasting network resources and contributes to the + * response bombardment illustrated in [3]. + * https://tools.ietf.org/html/rfc4320#section-4.1 + */ + ClientTransaction.prototype.onRequestTimeout = function () { + if (this.user.onRequestTimeout) { + this.user.onRequestTimeout(); + } + }; + return ClientTransaction; +}(transaction_1.Transaction)); +exports.ClientTransaction = ClientTransaction; + + +/***/ }), +/* 54 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var events_1 = __webpack_require__(2); +var Exceptions_1 = __webpack_require__(47); +/** + * Transaction + * + * SIP is a transactional protocol: interactions between components take + * place in a series of independent message exchanges. Specifically, a + * SIP transaction consists of a single request and any responses to + * that request, which include zero or more provisional responses and + * one or more final responses. In the case of a transaction where the + * request was an INVITE (known as an INVITE transaction), the + * transaction also includes the ACK only if the final response was not + * a 2xx response. If the response was a 2xx, the ACK is not considered + * part of the transaction. + * https://tools.ietf.org/html/rfc3261#section-17 + */ +var Transaction = /** @class */ (function (_super) { + __extends(Transaction, _super); + function Transaction(_transport, _user, _id, _state, loggerCategory) { + var _this = _super.call(this) || this; + _this._transport = _transport; + _this._user = _user; + _this._id = _id; + _this._state = _state; + _this.logger = _user.loggerFactory.getLogger(loggerCategory, _id); + _this.logger.debug("Constructing " + _this.typeToString() + " with id " + _this.id + "."); + return _this; + } + /** + * Destructor. + * Once the transaction is in the "terminated" state, it is destroyed + * immediately and there is no need to call `dispose`. However, if a + * transaction needs to be ended prematurely, the transaction user may + * do so by calling this method (for example, perhaps the UA is shutting down). + * No state transition will occur upon calling this method, all outstanding + * transmission timers will be cancelled, and use of the transaction after + * calling `dispose` is undefined. + */ + Transaction.prototype.dispose = function () { + this.logger.debug("Destroyed " + this.typeToString() + " with id " + this.id + "."); + }; + Object.defineProperty(Transaction.prototype, "id", { + /** Transaction id. */ + get: function () { + return this._id; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Transaction.prototype, "kind", { + /** Transaction kind. Deprecated. */ + get: function () { + throw new Error("Invalid kind."); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Transaction.prototype, "state", { + /** Transaction state. */ + get: function () { + return this._state; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Transaction.prototype, "transport", { + /** Transaction transport. */ + get: function () { + return this._transport; + }, + enumerable: true, + configurable: true + }); + Transaction.prototype.on = function (name, callback) { return _super.prototype.on.call(this, name, callback); }; + Transaction.prototype.logTransportError = function (error, message) { + this.logger.error(error.message); + this.logger.error("Transport error occurred in " + this.typeToString() + " with id " + this.id + "."); + this.logger.error(message); + }; + /** + * Pass message to transport for transmission. If transport fails, + * the transaction user is notified by callback to onTransportError(). + * @throws {TransportError} If transport fails. + */ + Transaction.prototype.send = function (message) { + var _this = this; + return this.transport.send(message).catch(function (error) { + // FIXME: Transport is not, yet, typed and it is not clear + // yet what send() may or may not send our way. So for now, + // make sure we convert it to a TransportError if need be. + if (error instanceof Exceptions_1.Exceptions.TransportError) { + _this.onTransportError(error); + return; + } + var transportError; + if (error && typeof error.message === "string") { + transportError = new Exceptions_1.Exceptions.TransportError(error.message); + } + else { + transportError = new Exceptions_1.Exceptions.TransportError(); + } + _this.onTransportError(transportError); + throw transportError; + }); + }; + Transaction.prototype.setState = function (state) { + this.logger.debug("State change to \"" + state + "\" on " + this.typeToString() + " with id " + this.id + "."); + this._state = state; + if (this._user.onStateChange) { + this._user.onStateChange(state); + } + this.emit("stateChanged"); + }; + Transaction.prototype.typeToString = function () { + return "UnknownType"; + }; + return Transaction; +}(events_1.EventEmitter)); +exports.Transaction = Transaction; + + +/***/ }), +/* 55 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Timers_1 = __webpack_require__(56); +var client_transaction_1 = __webpack_require__(53); +var transaction_state_1 = __webpack_require__(57); +/** + * INVITE Client Transaction + * + * The INVITE transaction consists of a three-way handshake. The client + * transaction sends an INVITE, the server transaction sends responses, + * and the client transaction sends an ACK. + * https://tools.ietf.org/html/rfc3261#section-17.1.1 + */ +var InviteClientTransaction = /** @class */ (function (_super) { + __extends(InviteClientTransaction, _super); + /** + * Constructor. + * Upon construction, the outgoing request's Via header is updated by calling `setViaHeader`. + * Then `toString` is called on the outgoing request and the message is sent via the transport. + * After construction the transaction will be in the "calling" state and the transaction id + * will equal the branch parameter set in the Via header of the outgoing request. + * https://tools.ietf.org/html/rfc3261#section-17.1.1 + * @param request The outgoing INVITE request. + * @param transport The transport. + * @param user The transaction user. + */ + function InviteClientTransaction(request, transport, user) { + var _this = _super.call(this, request, transport, user, transaction_state_1.TransactionState.Calling, "sip.transaction.ict") || this; + /** + * Map of 2xx to-tag => ACK. + * If value is not undefined, value is the ACK which was sent. + * If key exists but value is undefined, a 2xx was received but the ACK not yet sent. + * Otherwise, a 2xx was not (yet) received for this transaction. + */ + _this.ackRetransmissionCache = new Map(); + // FIXME: Timer A for unreliable transport not implemented + // + // If an unreliable transport is being used, the client transaction + // MUST start timer A with a value of T1. If a reliable transport is being used, + // the client transaction SHOULD NOT start timer A (Timer A controls request retransmissions). + // For any transport, the client transaction MUST start timer B with a value + // of 64*T1 seconds (Timer B controls transaction timeouts). + // https://tools.ietf.org/html/rfc3261#section-17.1.1.2 + // + // While not spelled out in the RFC, Timer B is the maximum amount of time that a sender + // will wait for an INVITE message to be acknowledged (a SIP response message is received). + // So Timer B should be cleared when the transaction state proceeds from "Calling". + _this.B = setTimeout(function () { return _this.timer_B(); }, Timers_1.Timers.TIMER_B); + _this.send(request.toString()).catch(function (error) { + _this.logTransportError(error, "Failed to send initial outgoing request."); + }); + return _this; + } + /** + * Destructor. + */ + InviteClientTransaction.prototype.dispose = function () { + if (this.B) { + clearTimeout(this.B); + this.B = undefined; + } + if (this.D) { + clearTimeout(this.D); + this.D = undefined; + } + if (this.M) { + clearTimeout(this.M); + this.M = undefined; + } + _super.prototype.dispose.call(this); + }; + Object.defineProperty(InviteClientTransaction.prototype, "kind", { + /** Transaction kind. Deprecated. */ + get: function () { + return "ict"; + }, + enumerable: true, + configurable: true + }); + /** + * ACK a 2xx final response. + * + * The transaction includes the ACK only if the final response was not a 2xx response (the + * transaction will generate and send the ACK to the transport automagically). If the + * final response was a 2xx, the ACK is not considered part of the transaction (the + * transaction user needs to generate and send the ACK). + * + * This library is not strictly RFC compliant with regard to ACK handling for 2xx final + * responses. Specifically, retransmissions of ACKs to a 2xx final responses is handled + * by the transaction layer (instead of the UAC core). The "standard" approach is for + * the UAC core to receive all 2xx responses and manage sending ACK retransmissions to + * the transport directly. Herein the transaction layer manages sending ACKs to 2xx responses + * and any retransmissions of those ACKs as needed. + * + * @param ack The outgoing ACK request. + */ + InviteClientTransaction.prototype.ackResponse = function (ack) { + var _this = this; + var toTag = ack.toTag; + if (!toTag) { + throw new Error("To tag undefined."); + } + var id = "z9hG4bK" + Math.floor(Math.random() * 10000000); + ack.setViaHeader(id, this.transport); + this.ackRetransmissionCache.set(toTag, ack); // Add to ACK retransmission cache + this.send(ack.toString()).catch(function (error) { + _this.logTransportError(error, "Failed to send ACK to 2xx response."); + }); + }; + /** + * Handler for incoming responses from the transport which match this transaction. + * @param response The incoming response. + */ + InviteClientTransaction.prototype.receiveResponse = function (response) { + var _this = this; + var statusCode = response.statusCode; + if (!statusCode || statusCode < 100 || statusCode > 699) { + throw new Error("Invalid status code " + statusCode); + } + switch (this.state) { + case transaction_state_1.TransactionState.Calling: + // If the client transaction receives a provisional response while in + // the "Calling" state, it transitions to the "Proceeding" state. In the + // "Proceeding" state, the client transaction SHOULD NOT retransmit the + // request any longer. Furthermore, the provisional response MUST be + // passed to the TU. Any further provisional responses MUST be passed + // up to the TU while in the "Proceeding" state. + // https://tools.ietf.org/html/rfc3261#section-17.1.1.2 + if (statusCode >= 100 && statusCode <= 199) { + this.stateTransition(transaction_state_1.TransactionState.Proceeding); + if (this.user.receiveResponse) { + this.user.receiveResponse(response); + } + return; + } + // When a 2xx response is received while in either the "Calling" or + // "Proceeding" states, the client transaction MUST transition to + // the "Accepted" state... The 2xx response MUST be passed up to the TU. + // The client transaction MUST NOT generate an ACK to the 2xx response -- its + // handling is delegated to the TU. A UAC core will send an ACK to + // the 2xx response using a new transaction. + // https://tools.ietf.org/html/rfc6026#section-8.4 + if (statusCode >= 200 && statusCode <= 299) { + this.ackRetransmissionCache.set(response.toTag, undefined); // Prime the ACK cache + this.stateTransition(transaction_state_1.TransactionState.Accepted); + if (this.user.receiveResponse) { + this.user.receiveResponse(response); + } + return; + } + // When in either the "Calling" or "Proceeding" states, reception of + // a response with status code from 300-699 MUST cause the client + // transaction to transition to "Completed". The client transaction + // MUST pass the received response up to the TU, and the client + // transaction MUST generate an ACK request, even if the transport is + // reliable (guidelines for constructing the ACK from the response + // are given in Section 17.1.1.3), and then pass the ACK to the + // transport layer for transmission. The ACK MUST be sent to the + // same address, port, and transport to which the original request was sent. + // https://tools.ietf.org/html/rfc6026#section-8.4 + if (statusCode >= 300 && statusCode <= 699) { + this.stateTransition(transaction_state_1.TransactionState.Completed); + this.ack(response); + if (this.user.receiveResponse) { + this.user.receiveResponse(response); + } + return; + } + break; + case transaction_state_1.TransactionState.Proceeding: + // In the "Proceeding" state, the client transaction SHOULD NOT retransmit the + // request any longer. Furthermore, the provisional response MUST be + // passed to the TU. Any further provisional responses MUST be passed + // up to the TU while in the "Proceeding" state. + // https://tools.ietf.org/html/rfc3261#section-17.1.1.2 + if (statusCode >= 100 && statusCode <= 199) { + if (this.user.receiveResponse) { + this.user.receiveResponse(response); + } + return; + } + // When a 2xx response is received while in either the "Calling" or "Proceeding" states, + // the client transaction MUST transition to the "Accepted" state... + // The 2xx response MUST be passed up to the TU. The client + // transaction MUST NOT generate an ACK to the 2xx response -- its + // handling is delegated to the TU. A UAC core will send an ACK to + // the 2xx response using a new transaction. + // https://tools.ietf.org/html/rfc6026#section-8.4 + if (statusCode >= 200 && statusCode <= 299) { + this.ackRetransmissionCache.set(response.toTag, undefined); // Prime the ACK cache + this.stateTransition(transaction_state_1.TransactionState.Accepted); + if (this.user.receiveResponse) { + this.user.receiveResponse(response); + } + return; + } + // When in either the "Calling" or "Proceeding" states, reception of + // a response with status code from 300-699 MUST cause the client + // transaction to transition to "Completed". The client transaction + // MUST pass the received response up to the TU, and the client + // transaction MUST generate an ACK request, even if the transport is + // reliable (guidelines for constructing the ACK from the response + // are given in Section 17.1.1.3), and then pass the ACK to the + // transport layer for transmission. The ACK MUST be sent to the + // same address, port, and transport to which the original request was sent. + // https://tools.ietf.org/html/rfc6026#section-8.4 + if (statusCode >= 300 && statusCode <= 699) { + this.stateTransition(transaction_state_1.TransactionState.Completed); + this.ack(response); + if (this.user.receiveResponse) { + this.user.receiveResponse(response); + } + return; + } + break; + case transaction_state_1.TransactionState.Accepted: + // The purpose of the "Accepted" state is to allow the client + // transaction to continue to exist to receive, and pass to the TU, + // any retransmissions of the 2xx response and any additional 2xx + // responses from other branches of the INVITE if it forked + // downstream. Timer M reflects the amount of time that the + // transaction user will wait for such messages. + // + // Any 2xx responses that match this client transaction and that are + // received while in the "Accepted" state MUST be passed up to the + // TU. The client transaction MUST NOT generate an ACK to the 2xx + // response. The client transaction takes no further action. + // https://tools.ietf.org/html/rfc6026#section-8.4 + if (statusCode >= 200 && statusCode <= 299) { + // NOTE: This implementation herein is intentionally not RFC compliant. + // While the first 2xx response for a given branch is passed up to the TU, + // retransmissions of 2xx responses are absorbed and the ACK associated + // with the original response is resent. This approach is taken because + // our current transaction users are not currently in a good position to + // deal with 2xx retransmission. This SHOULD NOT cause any compliance issues - ;) + // + // If we don't have a cache hit, pass the response to the TU. + if (!this.ackRetransmissionCache.has(response.toTag)) { + this.ackRetransmissionCache.set(response.toTag, undefined); // Prime the ACK cache + if (this.user.receiveResponse) { + this.user.receiveResponse(response); + } + return; + } + // If we have a cache hit, try pulling the ACK from cache and retransmitting it. + var ack = this.ackRetransmissionCache.get(response.toTag); + if (ack) { + this.send(ack.toString()).catch(function (error) { + _this.logTransportError(error, "Failed to send retransmission of ACK to 2xx response."); + }); + return; + } + // If an ACK was not found in cache then we have received a retransmitted 2xx + // response before the TU responded to the original response (we don't have an ACK yet). + // So discard this response under the assumption that the TU will eventually + // get us a ACK for the original response. + return; + } + break; + case transaction_state_1.TransactionState.Completed: + // Any retransmissions of a response with status code 300-699 that + // are received while in the "Completed" state MUST cause the ACK to + // be re-passed to the transport layer for retransmission, but the + // newly received response MUST NOT be passed up to the TU. + // https://tools.ietf.org/html/rfc6026#section-8.4 + if (statusCode >= 300 && statusCode <= 699) { + this.ack(response); + return; + } + break; + case transaction_state_1.TransactionState.Terminated: + break; + default: + throw new Error("Invalid state " + this.state); + } + // Any response received that does not match an existing client + // transaction state machine is simply dropped. (Implementations are, + // of course, free to log or do other implementation-specific things + // with such responses, but the implementer should be sure to consider + // the impact of large numbers of malicious stray responses.) + // https://tools.ietf.org/html/rfc6026#section-7.2 + var message = "Received unexpected " + statusCode + " response while in state " + this.state + "."; + this.logger.warn(message); + return; + }; + /** + * The client transaction SHOULD inform the TU that a transport failure + * has occurred, and the client transaction SHOULD transition directly + * to the "Terminated" state. The TU will handle the failover + * mechanisms described in [4]. + * https://tools.ietf.org/html/rfc3261#section-17.1.4 + * @param error The error. + */ + InviteClientTransaction.prototype.onTransportError = function (error) { + if (this.user.onTransportError) { + this.user.onTransportError(error); + } + this.stateTransition(transaction_state_1.TransactionState.Terminated, true); + }; + /** For logging. */ + InviteClientTransaction.prototype.typeToString = function () { + return "INVITE client transaction"; + }; + InviteClientTransaction.prototype.ack = function (response) { + var _this = this; + // The ACK request constructed by the client transaction MUST contain + // values for the Call-ID, From, and Request-URI that are equal to the + // values of those header fields in the request passed to the transport + // by the client transaction (call this the "original request"). The To + // header field in the ACK MUST equal the To header field in the + // response being acknowledged, and therefore will usually differ from + // the To header field in the original request by the addition of the + // tag parameter. The ACK MUST contain a single Via header field, and + // this MUST be equal to the top Via header field of the original + // request. The CSeq header field in the ACK MUST contain the same + // value for the sequence number as was present in the original request, + // but the method parameter MUST be equal to "ACK". + // + // If the INVITE request whose response is being acknowledged had Route + // header fields, those header fields MUST appear in the ACK. This is + // to ensure that the ACK can be routed properly through any downstream + // stateless proxies. + // https://tools.ietf.org/html/rfc3261#section-17.1.1.3 + var ruri = this.request.ruri; + var callId = this.request.callId; + var cseq = this.request.cseq; + var from = this.request.getHeader("from"); + var to = response.getHeader("to"); + var via = this.request.getHeader("via"); + var route = this.request.getHeader("route"); + if (!from) { + throw new Error("From undefined."); + } + if (!to) { + throw new Error("To undefined."); + } + if (!via) { + throw new Error("Via undefined."); + } + var ack = "ACK " + ruri + " SIP/2.0\r\n"; + if (route) { + ack += "Route: " + route + "\r\n"; + } + ack += "Via: " + via + "\r\n"; + ack += "To: " + to + "\r\n"; + ack += "From: " + from + "\r\n"; + ack += "Call-ID: " + callId + "\r\n"; + ack += "CSeq: " + cseq + " ACK\r\n"; + ack += "Max-Forwards: 70\r\n"; + ack += "Content-Length: 0\r\n\r\n"; + // TOOO: "User-Agent" header + this.send(ack).catch(function (error) { + _this.logTransportError(error, "Failed to send ACK to non-2xx response."); + }); + return; + }; + /** + * Execute a state transition. + * @param newState New state. + */ + InviteClientTransaction.prototype.stateTransition = function (newState, dueToTransportError) { + var _this = this; + if (dueToTransportError === void 0) { dueToTransportError = false; } + // Assert valid state transitions. + var invalidStateTransition = function () { + throw new Error("Invalid state transition from " + _this.state + " to " + newState); + }; + switch (newState) { + case transaction_state_1.TransactionState.Calling: + invalidStateTransition(); + break; + case transaction_state_1.TransactionState.Proceeding: + if (this.state !== transaction_state_1.TransactionState.Calling) { + invalidStateTransition(); + } + break; + case transaction_state_1.TransactionState.Accepted: + case transaction_state_1.TransactionState.Completed: + if (this.state !== transaction_state_1.TransactionState.Calling && + this.state !== transaction_state_1.TransactionState.Proceeding) { + invalidStateTransition(); + } + break; + case transaction_state_1.TransactionState.Terminated: + if (this.state !== transaction_state_1.TransactionState.Calling && + this.state !== transaction_state_1.TransactionState.Accepted && + this.state !== transaction_state_1.TransactionState.Completed) { + if (!dueToTransportError) { + invalidStateTransition(); + } + } + break; + default: + invalidStateTransition(); + } + // While not spelled out in the RFC, Timer B is the maximum amount of time that a sender + // will wait for an INVITE message to be acknowledged (a SIP response message is received). + // So Timer B should be cleared when the transaction state proceeds from "Calling". + if (this.B) { + clearTimeout(this.B); + this.B = undefined; + } + if (newState === transaction_state_1.TransactionState.Proceeding) { + // Timers have no effect on "Proceeding" state. + // In the "Proceeding" state, the client transaction + // SHOULD NOT retransmit the request any longer. + // https://tools.ietf.org/html/rfc3261#section-17.1.1.2 + } + // The client transaction MUST start Timer D when it enters the "Completed" state + // for any reason, with a value of at least 32 seconds for unreliable transports, + // and a value of zero seconds for reliable transports. + // https://tools.ietf.org/html/rfc6026#section-8.4 + if (newState === transaction_state_1.TransactionState.Completed) { + this.D = setTimeout(function () { return _this.timer_D(); }, Timers_1.Timers.TIMER_D); + } + // The client transaction MUST transition to the "Accepted" state, + // and Timer M MUST be started with a value of 64*T1. + // https://tools.ietf.org/html/rfc6026#section-8.4 + if (newState === transaction_state_1.TransactionState.Accepted) { + this.M = setTimeout(function () { return _this.timer_M(); }, Timers_1.Timers.TIMER_M); + } + // Once the transaction is in the "Terminated" state, it MUST be destroyed immediately. + // https://tools.ietf.org/html/rfc6026#section-8.7 + if (newState === transaction_state_1.TransactionState.Terminated) { + this.dispose(); + } + // Update state. + this.setState(newState); + }; + /** + * When timer A fires, the client transaction MUST retransmit the + * request by passing it to the transport layer, and MUST reset the + * timer with a value of 2*T1. + * When timer A fires 2*T1 seconds later, the request MUST be + * retransmitted again (assuming the client transaction is still in this + * state). This process MUST continue so that the request is + * retransmitted with intervals that double after each transmission. + * These retransmissions SHOULD only be done while the client + * transaction is in the "Calling" state. + * https://tools.ietf.org/html/rfc3261#section-17.1.1.2 + */ + InviteClientTransaction.prototype.timer_A = function () { + // TODO + }; + /** + * If the client transaction is still in the "Calling" state when timer + * B fires, the client transaction SHOULD inform the TU that a timeout + * has occurred. The client transaction MUST NOT generate an ACK. + * https://tools.ietf.org/html/rfc3261#section-17.1.1.2 + */ + InviteClientTransaction.prototype.timer_B = function () { + this.logger.debug("Timer B expired for INVITE client transaction " + this.id + "."); + if (this.state === transaction_state_1.TransactionState.Calling) { + this.onRequestTimeout(); + this.stateTransition(transaction_state_1.TransactionState.Terminated); + } + }; + /** + * If Timer D fires while the client transaction is in the "Completed" state, + * the client transaction MUST move to the "Terminated" state. + * https://tools.ietf.org/html/rfc6026#section-8.4 + */ + InviteClientTransaction.prototype.timer_D = function () { + this.logger.debug("Timer D expired for INVITE client transaction " + this.id + "."); + if (this.state === transaction_state_1.TransactionState.Completed) { + this.stateTransition(transaction_state_1.TransactionState.Terminated); + } + }; + /** + * If Timer M fires while the client transaction is in the "Accepted" + * state, the client transaction MUST move to the "Terminated" state. + * https://tools.ietf.org/html/rfc6026#section-8.4 + */ + InviteClientTransaction.prototype.timer_M = function () { + this.logger.debug("Timer M expired for INVITE client transaction " + this.id + "."); + if (this.state === transaction_state_1.TransactionState.Accepted) { + this.stateTransition(transaction_state_1.TransactionState.Terminated); + } + }; + return InviteClientTransaction; +}(client_transaction_1.ClientTransaction)); +exports.InviteClientTransaction = InviteClientTransaction; + + +/***/ }), +/* 56 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +var T1 = 500; +var T2 = 4000; +var T4 = 5000; +exports.Timers = { + T1: T1, + T2: T2, + T4: T4, + TIMER_B: 64 * T1, + TIMER_D: 0 * T1, + TIMER_F: 64 * T1, + TIMER_H: 64 * T1, + TIMER_I: 0 * T4, + TIMER_J: 0 * T1, + TIMER_K: 0 * T4, + TIMER_L: 64 * T1, + TIMER_M: 64 * T1, + TIMER_N: 64 * T1, + PROVISIONAL_RESPONSE_INTERVAL: 60000 // See RFC 3261 Section 13.3.1.1 +}; + + +/***/ }), +/* 57 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +/** Transaction state. */ +var TransactionState; +(function (TransactionState) { + TransactionState["Accepted"] = "Accepted"; + TransactionState["Calling"] = "Calling"; + TransactionState["Completed"] = "Completed"; + TransactionState["Confirmed"] = "Confirmed"; + TransactionState["Proceeding"] = "Proceeding"; + TransactionState["Terminated"] = "Terminated"; + TransactionState["Trying"] = "Trying"; +})(TransactionState = exports.TransactionState || (exports.TransactionState = {})); + + +/***/ }), +/* 58 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Constants_1 = __webpack_require__(3); +var Timers_1 = __webpack_require__(56); +var server_transaction_1 = __webpack_require__(59); +var transaction_state_1 = __webpack_require__(57); +/** + * INVITE Server Transaction + * https://tools.ietf.org/html/rfc3261#section-17.2.1 + */ +var InviteServerTransaction = /** @class */ (function (_super) { + __extends(InviteServerTransaction, _super); + /** + * Constructor. + * Upon construction, a "100 Trying" reply will be immediately sent. + * After construction the transaction will be in the "proceeding" state and the transaction + * `id` will equal the branch parameter set in the Via header of the incoming request. + * https://tools.ietf.org/html/rfc3261#section-17.2.1 + * @param request Incoming INVITE request from the transport. + * @param transport The transport. + * @param user The transaction user. + */ + function InviteServerTransaction(request, transport, user) { + return _super.call(this, request, transport, user, transaction_state_1.TransactionState.Proceeding, "sip.transaction.ist") || this; + } + /** + * Destructor. + */ + InviteServerTransaction.prototype.dispose = function () { + this.stopProgressExtensionTimer(); + if (this.H) { + clearTimeout(this.H); + this.H = undefined; + } + if (this.I) { + clearTimeout(this.I); + this.I = undefined; + } + if (this.L) { + clearTimeout(this.L); + this.L = undefined; + } + _super.prototype.dispose.call(this); + }; + Object.defineProperty(InviteServerTransaction.prototype, "kind", { + /** Transaction kind. Deprecated. */ + get: function () { + return "ist"; + }, + enumerable: true, + configurable: true + }); + /** + * Receive requests from transport matching this transaction. + * @param request Request matching this transaction. + */ + InviteServerTransaction.prototype.receiveRequest = function (request) { + var _this = this; + switch (this.state) { + case transaction_state_1.TransactionState.Proceeding: + // If a request retransmission is received while in the "Proceeding" state, the most + // recent provisional response that was received from the TU MUST be passed to the + // transport layer for retransmission. + // https://tools.ietf.org/html/rfc3261#section-17.2.1 + if (request.method === Constants_1.C.INVITE) { + if (this.lastProvisionalResponse) { + this.send(this.lastProvisionalResponse).catch(function (error) { + _this.logTransportError(error, "Failed to send retransmission of provisional response."); + }); + } + return; + } + break; + case transaction_state_1.TransactionState.Accepted: + // While in the "Accepted" state, any retransmissions of the INVITE + // received will match this transaction state machine and will be + // absorbed by the machine without changing its state. These + // retransmissions are not passed onto the TU. + // https://tools.ietf.org/html/rfc6026#section-7.1 + if (request.method === Constants_1.C.INVITE) { + return; + } + break; + case transaction_state_1.TransactionState.Completed: + // Furthermore, while in the "Completed" state, if a request retransmission is + // received, the server SHOULD pass the response to the transport for retransmission. + // https://tools.ietf.org/html/rfc3261#section-17.2.1 + if (request.method === Constants_1.C.INVITE) { + if (!this.lastFinalResponse) { + throw new Error("Last final response undefined."); + } + this.send(this.lastFinalResponse).catch(function (error) { + _this.logTransportError(error, "Failed to send retransmission of final response."); + }); + return; + } + // If an ACK is received while the server transaction is in the "Completed" state, + // the server transaction MUST transition to the "Confirmed" state. + // https://tools.ietf.org/html/rfc3261#section-17.2.1 + if (request.method === Constants_1.C.ACK) { + this.stateTransition(transaction_state_1.TransactionState.Confirmed); + return; + } + break; + case transaction_state_1.TransactionState.Confirmed: + // The purpose of the "Confirmed" state is to absorb any additional ACK messages that arrive, + // triggered from retransmissions of the final response. + // https://tools.ietf.org/html/rfc3261#section-17.2.1 + if (request.method === Constants_1.C.INVITE || request.method === Constants_1.C.ACK) { + return; + } + break; + case transaction_state_1.TransactionState.Terminated: + // For good measure absorb any additional messages that arrive (should not happen). + if (request.method === Constants_1.C.INVITE || request.method === Constants_1.C.ACK) { + return; + } + break; + default: + throw new Error("Invalid state " + this.state); + } + var message = "INVITE server transaction received unexpected " + request.method + " request while in state " + this.state + "."; + this.logger.warn(message); + return; + }; + /** + * Receive responses from TU for this transaction. + * @param statusCode Status code of response. + * @param response Response. + */ + InviteServerTransaction.prototype.receiveResponse = function (statusCode, response) { + var _this = this; + if (statusCode < 100 || statusCode > 699) { + throw new Error("Invalid status code " + statusCode); + } + switch (this.state) { + case transaction_state_1.TransactionState.Proceeding: + // The TU passes any number of provisional responses to the server + // transaction. So long as the server transaction is in the + // "Proceeding" state, each of these MUST be passed to the transport + // layer for transmission. They are not sent reliably by the + // transaction layer (they are not retransmitted by it) and do not cause + // a change in the state of the server transaction. + // https://tools.ietf.org/html/rfc3261#section-17.2.1 + if (statusCode >= 100 && statusCode <= 199) { + this.lastProvisionalResponse = response; + // Start the progress extension timer only for a non-100 provisional response. + if (statusCode > 100) { + this.startProgressExtensionTimer(); // FIXME: remove + } + this.send(response).catch(function (error) { + _this.logTransportError(error, "Failed to send 1xx response."); + }); + return; + } + // If, while in the "Proceeding" state, the TU passes a 2xx response + // to the server transaction, the server transaction MUST pass this + // response to the transport layer for transmission. It is not + // retransmitted by the server transaction; retransmissions of 2xx + // responses are handled by the TU. The server transaction MUST then + // transition to the "Accepted" state. + // https://tools.ietf.org/html/rfc6026#section-8.5 + if (statusCode >= 200 && statusCode <= 299) { + this.lastFinalResponse = response; + this.stateTransition(transaction_state_1.TransactionState.Accepted); + this.send(response).catch(function (error) { + _this.logTransportError(error, "Failed to send 2xx response."); + }); + return; + } + // While in the "Proceeding" state, if the TU passes a response with + // status code from 300 to 699 to the server transaction, the response + // MUST be passed to the transport layer for transmission, and the state + // machine MUST enter the "Completed" state. + // https://tools.ietf.org/html/rfc3261#section-17.2.1 + if (statusCode >= 300 && statusCode <= 699) { + this.lastFinalResponse = response; + this.stateTransition(transaction_state_1.TransactionState.Completed); + this.send(response).catch(function (error) { + _this.logTransportError(error, "Failed to send non-2xx final response."); + }); + return; + } + break; + case transaction_state_1.TransactionState.Accepted: + // While in the "Accepted" state, if the TU passes a 2xx response, + // the server transaction MUST pass the response to the transport layer for transmission. + // https://tools.ietf.org/html/rfc6026#section-8.7 + if (statusCode >= 200 && statusCode <= 299) { + this.send(response).catch(function (error) { + _this.logTransportError(error, "Failed to send 2xx response."); + }); + return; + } + break; + case transaction_state_1.TransactionState.Completed: + break; + case transaction_state_1.TransactionState.Confirmed: + break; + case transaction_state_1.TransactionState.Terminated: + break; + default: + throw new Error("Invalid state " + this.state); + } + var message = "INVITE server transaction received unexpected " + statusCode + " response from TU while in state " + this.state + "."; + this.logger.error(message); + throw new Error(message); + }; + /** + * Retransmit the last 2xx response. This is a noop if not in the "accepted" state. + */ + InviteServerTransaction.prototype.retransmitAcceptedResponse = function () { + var _this = this; + if (this.state === transaction_state_1.TransactionState.Accepted && this.lastFinalResponse) { + this.send(this.lastFinalResponse).catch(function (error) { + _this.logTransportError(error, "Failed to send 2xx response."); + }); + } + }; + /** + * First, the procedures in [4] are followed, which attempt to deliver the response to a backup. + * If those should all fail, based on the definition of failure in [4], the server transaction SHOULD + * inform the TU that a failure has occurred, and MUST remain in the current state. + * https://tools.ietf.org/html/rfc6026#section-8.8 + */ + InviteServerTransaction.prototype.onTransportError = function (error) { + if (this.user.onTransportError) { + this.user.onTransportError(error); + } + }; + /** For logging. */ + InviteServerTransaction.prototype.typeToString = function () { + return "INVITE server transaction"; + }; + /** + * Execute a state transition. + * @param newState New state. + */ + InviteServerTransaction.prototype.stateTransition = function (newState) { + var _this = this; + // Assert valid state transitions. + var invalidStateTransition = function () { + throw new Error("Invalid state transition from " + _this.state + " to " + newState); + }; + switch (newState) { + case transaction_state_1.TransactionState.Proceeding: + invalidStateTransition(); + break; + case transaction_state_1.TransactionState.Accepted: + case transaction_state_1.TransactionState.Completed: + if (this.state !== transaction_state_1.TransactionState.Proceeding) { + invalidStateTransition(); + } + break; + case transaction_state_1.TransactionState.Confirmed: + if (this.state !== transaction_state_1.TransactionState.Completed) { + invalidStateTransition(); + } + break; + case transaction_state_1.TransactionState.Terminated: + if (this.state !== transaction_state_1.TransactionState.Accepted && + this.state !== transaction_state_1.TransactionState.Completed && + this.state !== transaction_state_1.TransactionState.Confirmed) { + invalidStateTransition(); + } + break; + default: + invalidStateTransition(); + } + // On any state transition, stop resending provisonal responses + this.stopProgressExtensionTimer(); + // The purpose of the "Accepted" state is to absorb retransmissions of an accepted INVITE request. + // Any such retransmissions are absorbed entirely within the server transaction. + // They are not passed up to the TU since any downstream UAS cores that accepted the request have + // taken responsibility for reliability and will already retransmit their 2xx responses if necessary. + // https://tools.ietf.org/html/rfc6026#section-8.7 + if (newState === transaction_state_1.TransactionState.Accepted) { + this.L = setTimeout(function () { return _this.timer_L(); }, Timers_1.Timers.TIMER_L); + } + // When the "Completed" state is entered, timer H MUST be set to fire in 64*T1 seconds for all transports. + // Timer H determines when the server transaction abandons retransmitting the response. + // If an ACK is received while the server transaction is in the "Completed" state, + // the server transaction MUST transition to the "Confirmed" state. + // https://tools.ietf.org/html/rfc3261#section-17.2.1 + if (newState === transaction_state_1.TransactionState.Completed) { + // FIXME: Missing timer G for unreliable transports. + this.H = setTimeout(function () { return _this.timer_H(); }, Timers_1.Timers.TIMER_H); + } + // The purpose of the "Confirmed" state is to absorb any additional ACK messages that arrive, + // triggered from retransmissions of the final response. When this state is entered, timer I + // is set to fire in T4 seconds for unreliable transports, and zero seconds for reliable + // transports. Once timer I fires, the server MUST transition to the "Terminated" state. + // https://tools.ietf.org/html/rfc3261#section-17.2.1 + if (newState === transaction_state_1.TransactionState.Confirmed) { + // FIXME: This timer is not getting set correctly for unreliable transports. + this.I = setTimeout(function () { return _this.timer_I(); }, Timers_1.Timers.TIMER_I); + } + // Once the transaction is in the "Terminated" state, it MUST be destroyed immediately. + // https://tools.ietf.org/html/rfc6026#section-8.7 + if (newState === transaction_state_1.TransactionState.Terminated) { + this.dispose(); + } + // Update state. + this.setState(newState); + }; + /** + * FIXME: UAS Provisional Retransmission Timer. See RFC 3261 Section 13.3.1.1 + * This is in the wrong place. This is not a transaction level thing. It's a UAS level thing. + */ + InviteServerTransaction.prototype.startProgressExtensionTimer = function () { + var _this = this; + // Start the progress extension timer only for the first non-100 provisional response. + if (this.progressExtensionTimer === undefined) { + this.progressExtensionTimer = setInterval(function () { + _this.logger.debug("Progress extension timer expired for INVITE server transaction " + _this.id + "."); + if (!_this.lastProvisionalResponse) { + throw new Error("Last provisional response undefined."); + } + _this.send(_this.lastProvisionalResponse).catch(function (error) { + _this.logTransportError(error, "Failed to send retransmission of provisional response."); + }); + }, Timers_1.Timers.PROVISIONAL_RESPONSE_INTERVAL); + } + }; + /** + * FIXME: UAS Provisional Retransmission Timer id. See RFC 3261 Section 13.3.1.1 + * This is in the wrong place. This is not a transaction level thing. It's a UAS level thing. + */ + InviteServerTransaction.prototype.stopProgressExtensionTimer = function () { + if (this.progressExtensionTimer !== undefined) { + clearInterval(this.progressExtensionTimer); + this.progressExtensionTimer = undefined; + } + }; + /** + * While in the "Proceeding" state, if the TU passes a response with status code + * from 300 to 699 to the server transaction, the response MUST be passed to the + * transport layer for transmission, and the state machine MUST enter the "Completed" state. + * For unreliable transports, timer G is set to fire in T1 seconds, and is not set to fire for + * reliable transports. If timer G fires, the response is passed to the transport layer once + * more for retransmission, and timer G is set to fire in MIN(2*T1, T2) seconds. From then on, + * when timer G fires, the response is passed to the transport again for transmission, and + * timer G is reset with a value that doubles, unless that value exceeds T2, in which case + * it is reset with the value of T2. + * https://tools.ietf.org/html/rfc3261#section-17.2.1 + */ + InviteServerTransaction.prototype.timer_G = function () { + // TODO + }; + /** + * If timer H fires while in the "Completed" state, it implies that the ACK was never received. + * In this case, the server transaction MUST transition to the "Terminated" state, and MUST + * indicate to the TU that a transaction failure has occurred. + * https://tools.ietf.org/html/rfc3261#section-17.2.1 + */ + InviteServerTransaction.prototype.timer_H = function () { + this.logger.debug("Timer H expired for INVITE server transaction " + this.id + "."); + if (this.state === transaction_state_1.TransactionState.Completed) { + this.logger.warn("ACK to negative final response was never received, terminating transaction."); + this.stateTransition(transaction_state_1.TransactionState.Terminated); + } + }; + /** + * Once timer I fires, the server MUST transition to the "Terminated" state. + * https://tools.ietf.org/html/rfc3261#section-17.2.1 + */ + InviteServerTransaction.prototype.timer_I = function () { + this.logger.debug("Timer I expired for INVITE server transaction " + this.id + "."); + this.stateTransition(transaction_state_1.TransactionState.Terminated); + }; + /** + * When Timer L fires and the state machine is in the "Accepted" state, the machine MUST + * transition to the "Terminated" state. Once the transaction is in the "Terminated" state, + * it MUST be destroyed immediately. Timer L reflects the amount of time the server + * transaction could receive 2xx responses for retransmission from the + * TU while it is waiting to receive an ACK. + * https://tools.ietf.org/html/rfc6026#section-7.1 + * https://tools.ietf.org/html/rfc6026#section-8.7 + */ + InviteServerTransaction.prototype.timer_L = function () { + this.logger.debug("Timer L expired for INVITE server transaction " + this.id + "."); + if (this.state === transaction_state_1.TransactionState.Accepted) { + this.stateTransition(transaction_state_1.TransactionState.Terminated); + } + }; + return InviteServerTransaction; +}(server_transaction_1.ServerTransaction)); +exports.InviteServerTransaction = InviteServerTransaction; + + +/***/ }), +/* 59 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var transaction_1 = __webpack_require__(54); +/** + * Server Transaction + * The server transaction is responsible for the delivery of requests to + * the TU and the reliable transmission of responses. It accomplishes + * this through a state machine. Server transactions are created by the + * core when a request is received, and transaction handling is desired + * for that request (this is not always the case). + * https://tools.ietf.org/html/rfc3261#section-17.2 + */ +var ServerTransaction = /** @class */ (function (_super) { + __extends(ServerTransaction, _super); + function ServerTransaction(_request, transport, user, state, loggerCategory) { + var _this = _super.call(this, transport, user, _request.viaBranch, state, loggerCategory) || this; + _this._request = _request; + _this.user = user; + return _this; + } + Object.defineProperty(ServerTransaction.prototype, "request", { + /** The incoming request the transaction handling. */ + get: function () { + return this._request; + }, + enumerable: true, + configurable: true + }); + return ServerTransaction; +}(transaction_1.Transaction)); +exports.ServerTransaction = ServerTransaction; + + +/***/ }), +/* 60 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Timers_1 = __webpack_require__(56); +var client_transaction_1 = __webpack_require__(53); +var transaction_state_1 = __webpack_require__(57); +/** + * Non-INVITE Client Transaction + * + * Non-INVITE transactions do not make use of ACK. + * They are simple request-response interactions. + * https://tools.ietf.org/html/rfc3261#section-17.1.2 + */ +var NonInviteClientTransaction = /** @class */ (function (_super) { + __extends(NonInviteClientTransaction, _super); + /** + * Constructor + * Upon construction, the outgoing request's Via header is updated by calling `setViaHeader`. + * Then `toString` is called on the outgoing request and the message is sent via the transport. + * After construction the transaction will be in the "calling" state and the transaction id + * will equal the branch parameter set in the Via header of the outgoing request. + * https://tools.ietf.org/html/rfc3261#section-17.1.2 + * @param request The outgoing Non-INVITE request. + * @param transport The transport. + * @param user The transaction user. + */ + function NonInviteClientTransaction(request, transport, user) { + var _this = _super.call(this, request, transport, user, transaction_state_1.TransactionState.Trying, "sip.transaction.nict") || this; + // FIXME: Timer E for unreliable transports not implemented. + // + // The "Trying" state is entered when the TU initiates a new client + // transaction with a request. When entering this state, the client + // transaction SHOULD set timer F to fire in 64*T1 seconds. The request + // MUST be passed to the transport layer for transmission. + // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 + _this.F = setTimeout(function () { return _this.timer_F(); }, Timers_1.Timers.TIMER_F); + _this.send(request.toString()).catch(function (error) { + _this.logTransportError(error, "Failed to send initial outgoing request."); + }); + return _this; + } + /** + * Destructor. + */ + NonInviteClientTransaction.prototype.dispose = function () { + if (this.F) { + clearTimeout(this.F); + this.F = undefined; + } + if (this.K) { + clearTimeout(this.K); + this.K = undefined; + } + _super.prototype.dispose.call(this); + }; + Object.defineProperty(NonInviteClientTransaction.prototype, "kind", { + /** Transaction kind. Deprecated. */ + get: function () { + return "nict"; + }, + enumerable: true, + configurable: true + }); + /** + * Handler for incoming responses from the transport which match this transaction. + * @param response The incoming response. + */ + NonInviteClientTransaction.prototype.receiveResponse = function (response) { + var statusCode = response.statusCode; + if (!statusCode || statusCode < 100 || statusCode > 699) { + throw new Error("Invalid status code " + statusCode); + } + switch (this.state) { + case transaction_state_1.TransactionState.Trying: + // If a provisional response is received while in the "Trying" state, the + // response MUST be passed to the TU, and then the client transaction + // SHOULD move to the "Proceeding" state. + // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 + if (statusCode >= 100 && statusCode <= 199) { + this.stateTransition(transaction_state_1.TransactionState.Proceeding); + if (this.user.receiveResponse) { + this.user.receiveResponse(response); + } + return; + } + // If a final response (status codes 200-699) is received while in the + // "Trying" state, the response MUST be passed to the TU, and the + // client transaction MUST transition to the "Completed" state. + // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 + if (statusCode >= 200 && statusCode <= 699) { + this.stateTransition(transaction_state_1.TransactionState.Completed); + if (statusCode === 408) { + this.onRequestTimeout(); + return; + } + if (this.user.receiveResponse) { + this.user.receiveResponse(response); + } + return; + } + break; + case transaction_state_1.TransactionState.Proceeding: + // If a provisional response is received while in the "Proceeding" state, + // the response MUST be passed to the TU. (From Figure 6) + // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 + if (statusCode >= 100 && statusCode <= 199) { + if (this.user.receiveResponse) { + return this.user.receiveResponse(response); + } + } + // If a final response (status codes 200-699) is received while in the + // "Proceeding" state, the response MUST be passed to the TU, and the + // client transaction MUST transition to the "Completed" state. + // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 + if (statusCode >= 200 && statusCode <= 699) { + this.stateTransition(transaction_state_1.TransactionState.Completed); + if (statusCode === 408) { + this.onRequestTimeout(); + return; + } + if (this.user.receiveResponse) { + this.user.receiveResponse(response); + } + return; + } + case transaction_state_1.TransactionState.Completed: + // The "Completed" state exists to buffer any additional response + // retransmissions that may be received (which is why the client + // transaction remains there only for unreliable transports). + // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 + return; + case transaction_state_1.TransactionState.Terminated: + // For good measure just absorb additional response retransmissions. + return; + default: + throw new Error("Invalid state " + this.state); + } + var message = "Non-INVITE client transaction received unexpected " + statusCode + " response while in state " + this.state + "."; + this.logger.warn(message); + return; + }; + /** + * The client transaction SHOULD inform the TU that a transport failure has occurred, + * and the client transaction SHOULD transition directly to the "Terminated" state. + * The TU will handle the failover mechanisms described in [4]. + * https://tools.ietf.org/html/rfc3261#section-17.1.4 + * @param error Trasnsport error + */ + NonInviteClientTransaction.prototype.onTransportError = function (error) { + if (this.user.onTransportError) { + this.user.onTransportError(error); + } + this.stateTransition(transaction_state_1.TransactionState.Terminated, true); + }; + /** For logging. */ + NonInviteClientTransaction.prototype.typeToString = function () { + return "non-INVITE client transaction"; + }; + /** + * Execute a state transition. + * @param newState New state. + */ + NonInviteClientTransaction.prototype.stateTransition = function (newState, dueToTransportError) { + var _this = this; + if (dueToTransportError === void 0) { dueToTransportError = false; } + // Assert valid state transitions. + var invalidStateTransition = function () { + throw new Error("Invalid state transition from " + _this.state + " to " + newState); + }; + switch (newState) { + case transaction_state_1.TransactionState.Trying: + invalidStateTransition(); + break; + case transaction_state_1.TransactionState.Proceeding: + if (this.state !== transaction_state_1.TransactionState.Trying) { + invalidStateTransition(); + } + break; + case transaction_state_1.TransactionState.Completed: + if (this.state !== transaction_state_1.TransactionState.Trying && + this.state !== transaction_state_1.TransactionState.Proceeding) { + invalidStateTransition(); + } + break; + case transaction_state_1.TransactionState.Terminated: + if (this.state !== transaction_state_1.TransactionState.Trying && + this.state !== transaction_state_1.TransactionState.Proceeding && + this.state !== transaction_state_1.TransactionState.Completed) { + if (!dueToTransportError) { + invalidStateTransition(); + } + } + break; + default: + invalidStateTransition(); + } + // Once the client transaction enters the "Completed" state, it MUST set + // Timer K to fire in T4 seconds for unreliable transports, and zero + // seconds for reliable transports The "Completed" state exists to + // buffer any additional response retransmissions that may be received + // (which is why the client transaction remains there only for unreliable transports). + // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 + if (newState === transaction_state_1.TransactionState.Completed) { + if (this.F) { + clearTimeout(this.F); + this.F = undefined; + } + this.K = setTimeout(function () { return _this.timer_K(); }, Timers_1.Timers.TIMER_K); + } + // Once the transaction is in the terminated state, it MUST be destroyed immediately. + // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 + if (newState === transaction_state_1.TransactionState.Terminated) { + this.dispose(); + } + // Update state. + this.setState(newState); + }; + /** + * If Timer F fires while the client transaction is still in the + * "Trying" state, the client transaction SHOULD inform the TU about the + * timeout, and then it SHOULD enter the "Terminated" state. + * If timer F fires while in the "Proceeding" state, the TU MUST be informed of + * a timeout, and the client transaction MUST transition to the terminated state. + * https://tools.ietf.org/html/rfc3261#section-17.1.2.2 + */ + NonInviteClientTransaction.prototype.timer_F = function () { + this.logger.debug("Timer F expired for non-INVITE client transaction " + this.id + "."); + if (this.state === transaction_state_1.TransactionState.Trying || this.state === transaction_state_1.TransactionState.Proceeding) { + this.onRequestTimeout(); + this.stateTransition(transaction_state_1.TransactionState.Terminated); + } + }; + /** + * If Timer K fires while in this (COMPLETED) state, the client transaction + * MUST transition to the "Terminated" state. + * https://tools.ietf.org/html/rfc3261#section-17.1.2.2 + */ + NonInviteClientTransaction.prototype.timer_K = function () { + if (this.state === transaction_state_1.TransactionState.Completed) { + this.stateTransition(transaction_state_1.TransactionState.Terminated); + } + }; + return NonInviteClientTransaction; +}(client_transaction_1.ClientTransaction)); +exports.NonInviteClientTransaction = NonInviteClientTransaction; + + +/***/ }), +/* 61 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Timers_1 = __webpack_require__(56); +var server_transaction_1 = __webpack_require__(59); +var transaction_state_1 = __webpack_require__(57); +/** + * Non-INVITE Server Transaction + * https://tools.ietf.org/html/rfc3261#section-17.2.2 + */ +var NonInviteServerTransaction = /** @class */ (function (_super) { + __extends(NonInviteServerTransaction, _super); + /** + * Constructor. + * After construction the transaction will be in the "trying": state and the transaction + * `id` will equal the branch parameter set in the Via header of the incoming request. + * https://tools.ietf.org/html/rfc3261#section-17.2.2 + * @param request Incoming Non-INVITE request from the transport. + * @param transport The transport. + * @param user The transaction user. + */ + function NonInviteServerTransaction(request, transport, user) { + return _super.call(this, request, transport, user, transaction_state_1.TransactionState.Trying, "sip.transaction.nist") || this; + } + /** + * Destructor. + */ + NonInviteServerTransaction.prototype.dispose = function () { + if (this.J) { + clearTimeout(this.J); + this.J = undefined; + } + _super.prototype.dispose.call(this); + }; + Object.defineProperty(NonInviteServerTransaction.prototype, "kind", { + /** Transaction kind. Deprecated. */ + get: function () { + return "nist"; + }, + enumerable: true, + configurable: true + }); + /** + * Receive requests from transport matching this transaction. + * @param request Request matching this transaction. + */ + NonInviteServerTransaction.prototype.receiveRequest = function (request) { + var _this = this; + switch (this.state) { + case transaction_state_1.TransactionState.Trying: + // Once in the "Trying" state, any further request retransmissions are discarded. + // https://tools.ietf.org/html/rfc3261#section-17.2.2 + break; + case transaction_state_1.TransactionState.Proceeding: + // If a retransmission of the request is received while in the "Proceeding" state, + // the most recently sent provisional response MUST be passed to the transport layer for retransmission. + // https://tools.ietf.org/html/rfc3261#section-17.2.2 + if (!this.lastResponse) { + throw new Error("Last response undefined."); + } + this.send(this.lastResponse).catch(function (error) { + _this.logTransportError(error, "Failed to send retransmission of provisional response."); + }); + break; + case transaction_state_1.TransactionState.Completed: + // While in the "Completed" state, the server transaction MUST pass the final response to the transport + // layer for retransmission whenever a retransmission of the request is received. Any other final responses + // passed by the TU to the server transaction MUST be discarded while in the "Completed" state. + // https://tools.ietf.org/html/rfc3261#section-17.2.2 + if (!this.lastResponse) { + throw new Error("Last response undefined."); + } + this.send(this.lastResponse).catch(function (error) { + _this.logTransportError(error, "Failed to send retransmission of final response."); + }); + break; + case transaction_state_1.TransactionState.Terminated: + break; + default: + throw new Error("Invalid state " + this.state); + } + }; + /** + * Receive responses from TU for this transaction. + * @param statusCode Status code of repsonse. 101-199 not allowed per RFC 4320. + * @param response Response to send. + */ + NonInviteServerTransaction.prototype.receiveResponse = function (statusCode, response) { + var _this = this; + if (statusCode < 100 || statusCode > 699) { + throw new Error("Invalid status code " + statusCode); + } + // An SIP element MUST NOT send any provisional response with a + // Status-Code other than 100 to a non-INVITE request. + // An SIP element MUST NOT respond to a non-INVITE request with a + // Status-Code of 100 over any unreliable transport, such as UDP, + // before the amount of time it takes a client transaction's Timer E to be reset to T2. + // An SIP element MAY respond to a non-INVITE request with a + // Status-Code of 100 over a reliable transport at any time. + // https://tools.ietf.org/html/rfc4320#section-4.1 + if (statusCode > 100 && statusCode <= 199) { + throw new Error("Provisional response other than 100 not allowed."); + } + switch (this.state) { + case transaction_state_1.TransactionState.Trying: + // While in the "Trying" state, if the TU passes a provisional response + // to the server transaction, the server transaction MUST enter the "Proceeding" state. + // The response MUST be passed to the transport layer for transmission. + // https://tools.ietf.org/html/rfc3261#section-17.2.2 + this.lastResponse = response; + if (statusCode >= 100 && statusCode < 200) { + this.stateTransition(transaction_state_1.TransactionState.Proceeding); + this.send(response).catch(function (error) { + _this.logTransportError(error, "Failed to send provisional response."); + }); + return; + } + if (statusCode >= 200 && statusCode <= 699) { + this.stateTransition(transaction_state_1.TransactionState.Completed); + this.send(response).catch(function (error) { + _this.logTransportError(error, "Failed to send final response."); + }); + return; + } + break; + case transaction_state_1.TransactionState.Proceeding: + // Any further provisional responses that are received from the TU while + // in the "Proceeding" state MUST be passed to the transport layer for transmission. + // If the TU passes a final response (status codes 200-699) to the server while in + // the "Proceeding" state, the transaction MUST enter the "Completed" state, and + // the response MUST be passed to the transport layer for transmission. + // https://tools.ietf.org/html/rfc3261#section-17.2.2 + this.lastResponse = response; + if (statusCode >= 200 && statusCode <= 699) { + this.stateTransition(transaction_state_1.TransactionState.Completed); + this.send(response).catch(function (error) { + _this.logTransportError(error, "Failed to send final response."); + }); + return; + } + break; + case transaction_state_1.TransactionState.Completed: + // Any other final responses passed by the TU to the server + // transaction MUST be discarded while in the "Completed" state. + // https://tools.ietf.org/html/rfc3261#section-17.2.2 + return; + case transaction_state_1.TransactionState.Terminated: + break; + default: + throw new Error("Invalid state " + this.state); + } + var message = "Non-INVITE server transaction received unexpected " + statusCode + " response from TU while in state " + this.state + "."; + this.logger.error(message); + throw new Error(message); + }; + /** + * First, the procedures in [4] are followed, which attempt to deliver the response to a backup. + * If those should all fail, based on the definition of failure in [4], the server transaction SHOULD + * inform the TU that a failure has occurred, and SHOULD transition to the terminated state. + * https://tools.ietf.org/html/rfc3261#section-17.2.4 + */ + NonInviteServerTransaction.prototype.onTransportError = function (error) { + if (this.user.onTransportError) { + this.user.onTransportError(error); + } + this.stateTransition(transaction_state_1.TransactionState.Terminated, true); + }; + /** For logging. */ + NonInviteServerTransaction.prototype.typeToString = function () { + return "non-INVITE server transaction"; + }; + NonInviteServerTransaction.prototype.stateTransition = function (newState, dueToTransportError) { + var _this = this; + if (dueToTransportError === void 0) { dueToTransportError = false; } + // Assert valid state transitions. + var invalidStateTransition = function () { + throw new Error("Invalid state transition from " + _this.state + " to " + newState); + }; + switch (newState) { + case transaction_state_1.TransactionState.Trying: + invalidStateTransition(); + break; + case transaction_state_1.TransactionState.Proceeding: + if (this.state !== transaction_state_1.TransactionState.Trying) { + invalidStateTransition(); + } + break; + case transaction_state_1.TransactionState.Completed: + if (this.state !== transaction_state_1.TransactionState.Trying && this.state !== transaction_state_1.TransactionState.Proceeding) { + invalidStateTransition(); + } + break; + case transaction_state_1.TransactionState.Terminated: + if (this.state !== transaction_state_1.TransactionState.Proceeding && this.state !== transaction_state_1.TransactionState.Completed) { + if (!dueToTransportError) { + invalidStateTransition(); + } + } + break; + default: + invalidStateTransition(); + } + // When the server transaction enters the "Completed" state, it MUST set Timer J to fire + // in 64*T1 seconds for unreliable transports, and zero seconds for reliable transports. + // https://tools.ietf.org/html/rfc3261#section-17.2.2 + if (newState === transaction_state_1.TransactionState.Completed) { + this.J = setTimeout(function () { return _this.timer_J(); }, Timers_1.Timers.TIMER_J); + } + // The server transaction MUST be destroyed the instant it enters the "Terminated" state. + // https://tools.ietf.org/html/rfc3261#section-17.2.2 + if (newState === transaction_state_1.TransactionState.Terminated) { + this.dispose(); + } + this.setState(newState); + }; + /** + * The server transaction remains in this state until Timer J fires, + * at which point it MUST transition to the "Terminated" state. + * https://tools.ietf.org/html/rfc3261#section-17.2.2 + */ + NonInviteServerTransaction.prototype.timer_J = function () { + this.logger.debug("Timer J expired for NON-INVITE server transaction " + this.id + "."); + if (this.state === transaction_state_1.TransactionState.Completed) { + this.stateTransition(transaction_state_1.TransactionState.Terminated); + } + }; + return NonInviteServerTransaction; +}(server_transaction_1.ServerTransaction)); +exports.NonInviteServerTransaction = NonInviteServerTransaction; + + +/***/ }), +/* 62 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var events_1 = __webpack_require__(2); +var Constants_1 = __webpack_require__(3); +var messages_1 = __webpack_require__(63); +var Enums_1 = __webpack_require__(5); +var Grammar_1 = __webpack_require__(7); +var Utils_1 = __webpack_require__(11); +var ServerContext = /** @class */ (function (_super) { + __extends(ServerContext, _super); + function ServerContext(ua, incomingRequest) { + var _this = _super.call(this) || this; + _this.incomingRequest = incomingRequest; + _this.data = {}; + ServerContext.initializer(_this, ua, incomingRequest); + return _this; + } + // hack to get around our multiple inheritance issues + ServerContext.initializer = function (objectToConstruct, ua, incomingRequest) { + var request = incomingRequest.message; + objectToConstruct.type = Enums_1.TypeStrings.ServerContext; + objectToConstruct.ua = ua; + objectToConstruct.logger = ua.getLogger("sip.servercontext"); + objectToConstruct.request = request; + if (request.body) { + objectToConstruct.body = request.body; + } + if (request.hasHeader("Content-Type")) { + objectToConstruct.contentType = request.getHeader("Content-Type"); + } + objectToConstruct.method = request.method; + objectToConstruct.localIdentity = request.to; + objectToConstruct.remoteIdentity = request.from; + var hasAssertedIdentity = request.hasHeader("P-Asserted-Identity"); + if (hasAssertedIdentity) { + var assertedIdentity = request.getHeader("P-Asserted-Identity"); + if (assertedIdentity) { + objectToConstruct.assertedIdentity = Grammar_1.Grammar.nameAddrHeaderParse(assertedIdentity); + } + } + }; + ServerContext.prototype.progress = function (options) { + if (options === void 0) { options = {}; } + options.statusCode = options.statusCode || 180; + options.minCode = 100; + options.maxCode = 199; + options.events = ["progress"]; + return this.reply(options); + }; + ServerContext.prototype.accept = function (options) { + if (options === void 0) { options = {}; } + options.statusCode = options.statusCode || 200; + options.minCode = 200; + options.maxCode = 299; + options.events = ["accepted"]; + return this.reply(options); + }; + ServerContext.prototype.reject = function (options) { + if (options === void 0) { options = {}; } + options.statusCode = options.statusCode || 480; + options.minCode = 300; + options.maxCode = 699; + options.events = ["rejected", "failed"]; + return this.reply(options); + }; + ServerContext.prototype.reply = function (options) { + var _this = this; + if (options === void 0) { options = {}; } + var statusCode = options.statusCode || 100; + var minCode = options.minCode || 100; + var maxCode = options.maxCode || 699; + var reasonPhrase = Utils_1.Utils.getReasonPhrase(statusCode, options.reasonPhrase); + var extraHeaders = options.extraHeaders || []; + var body = options.body ? messages_1.fromBodyLegacy(options.body) : undefined; + var events = options.events || []; + if (statusCode < minCode || statusCode > maxCode) { + throw new TypeError("Invalid statusCode: " + statusCode); + } + var responseOptions = { + statusCode: statusCode, + reasonPhrase: reasonPhrase, + extraHeaders: extraHeaders, + body: body + }; + var response; + var statusCodeString = statusCode.toString(); + switch (true) { + case /^100$/.test(statusCodeString): + response = this.incomingRequest.trying(responseOptions).message; + break; + case /^1[0-9]{2}$/.test(statusCodeString): + response = this.incomingRequest.progress(responseOptions).message; + break; + case /^2[0-9]{2}$/.test(statusCodeString): + response = this.incomingRequest.accept(responseOptions).message; + break; + case /^3[0-9]{2}$/.test(statusCodeString): + response = this.incomingRequest.redirect([], responseOptions).message; + break; + case /^[4-6][0-9]{2}$/.test(statusCodeString): + response = this.incomingRequest.reject(responseOptions).message; + break; + default: + throw new Error("Invalid status code " + statusCode); + } + events.forEach(function (event) { + _this.emit(event, response, reasonPhrase); + }); + return this; + }; + ServerContext.prototype.onRequestTimeout = function () { + this.emit("failed", undefined, Constants_1.C.causes.REQUEST_TIMEOUT); + }; + ServerContext.prototype.onTransportError = function () { + this.emit("failed", undefined, Constants_1.C.causes.CONNECTION_ERROR); + }; + return ServerContext; +}(events_1.EventEmitter)); +exports.ServerContext = ServerContext; + + +/***/ }), +/* 63 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +function __export(m) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; +} +Object.defineProperty(exports, "__esModule", { value: true }); +__export(__webpack_require__(64)); +__export(__webpack_require__(65)); + + +/***/ }), +/* 64 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +var SIPMessage_1 = __webpack_require__(6); +/** + * Create a Body given a BodyObj. + * @param bodyObj Body Object + */ +function fromBodyObj(bodyObj) { + var content = bodyObj.body; + var contentType = bodyObj.contentType; + var contentDisposition = contentTypeToContentDisposition(contentType); + var body = { contentDisposition: contentDisposition, contentType: contentType, content: content }; + return body; +} +exports.fromBodyObj = fromBodyObj; +/** + * Create a Body given a BodyObj. + * @param bodyObj Body Object + */ +function fromBodyLegacy(bodyLegacy) { + var content = (typeof bodyLegacy === "string") ? bodyLegacy : bodyLegacy.body; + var contentType = (typeof bodyLegacy === "string") ? "application/sdp" : bodyLegacy.contentType; + var contentDisposition = contentTypeToContentDisposition(contentType); + var body = { contentDisposition: contentDisposition, contentType: contentType, content: content }; + return body; +} +exports.fromBodyLegacy = fromBodyLegacy; +/** + * Given a message, get a normalized body. + * The content disposition is inferred if not set. + * @param message The message. + */ +function getBody(message) { + var contentDisposition; + var contentType; + var content; + // We're in UAS role, receiving incoming request + if (message instanceof SIPMessage_1.IncomingRequest) { + if (message.body) { + // FIXME: Parsing needs typing + var parse = message.parseHeader("Content-Disposition"); + contentDisposition = parse ? parse.type : undefined; + contentType = message.parseHeader("Content-Type"); + content = message.body; + } + } + // We're in UAC role, receiving incoming response + if (message instanceof SIPMessage_1.IncomingResponse) { + if (message.body) { + // FIXME: Parsing needs typing + var parse = message.parseHeader("Content-Disposition"); + contentDisposition = parse ? parse.type : undefined; + contentType = message.parseHeader("Content-Type"); + content = message.body; + } + } + // We're in UAC role, sending outgoing request + if (message instanceof SIPMessage_1.OutgoingRequest) { + if (message.body) { + contentDisposition = message.getHeader("Content-Disposition"); + contentType = message.getHeader("Content-Type"); + if (typeof message.body === "string") { + // FIXME: OutgoingRequest should not allow a "string" body without a "Content-Type" header. + if (!contentType) { + throw new Error("Header content type header does not equal body content type."); + } + content = message.body; + } + else { + // FIXME: OutgoingRequest should not allow the "Content-Type" header not to match th body content type + if (contentType && contentType !== message.body.contentType) { + throw new Error("Header content type header does not equal body content type."); + } + contentType = message.body.contentType; + content = message.body.body; + } + } + } + // We're in UAS role, sending outgoing response + if (isBody(message)) { + contentDisposition = message.contentDisposition; + contentType = message.contentType; + content = message.content; + } + // No content, no body. + if (!content) { + return undefined; + } + if (contentType && !contentDisposition) { + contentDisposition = contentTypeToContentDisposition(contentType); + } + if (!contentDisposition) { + throw new Error("Content disposition undefined."); + } + if (!contentType) { + throw new Error("Content type undefined."); + } + return { + contentDisposition: contentDisposition, + contentType: contentType, + content: content + }; +} +exports.getBody = getBody; +/** + * User-Defined Type Guard for Body. + * @param body Body to check. + */ +function isBody(body) { + return body && + typeof body.content === "string" && + typeof body.contentType === "string" && + body.contentDisposition === undefined ? true : typeof body.contentDisposition === "string"; +} +exports.isBody = isBody; +/** + * Create a BodyObj given a Body. + * @param bodyObj Body Object + */ +function toBodyObj(body) { + var bodyObj = { + body: body.content, + contentType: body.contentType + }; + return bodyObj; +} +exports.toBodyObj = toBodyObj; +// If the Content-Disposition header field is missing, bodies of +// Content-Type application/sdp imply the disposition "session", while +// other content types imply "render". +// https://tools.ietf.org/html/rfc3261#section-13.2.1 +function contentTypeToContentDisposition(contentType) { + if (contentType === "application/sdp") { + return "session"; + } + else { + return "render"; + } +} + + +/***/ }), +/* 65 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +var SIPMessage_1 = __webpack_require__(6); +var Utils_1 = __webpack_require__(11); +/** + * When a UAS wishes to construct a response to a request, it follows + * the general procedures detailed in the following subsections. + * Additional behaviors specific to the response code in question, which + * are not detailed in this section, may also be required. + * https://tools.ietf.org/html/rfc3261#section-8.2.6 + */ +function constructOutgoingResponse(message, options) { + var CRLF = "\r\n"; + // SIP responses are distinguished from requests by having a Status-Line + // as their start-line. A Status-Line consists of the protocol version + // followed by a numeric Status-Code and its associated textual phrase, + // with each element separated by a single SP character. + // https://tools.ietf.org/html/rfc3261#section-7.2 + var response = Utils_1.Utils.buildStatusLine(options.statusCode, options.reasonPhrase); + // One largely non-method-specific guideline for the generation of + // responses is that UASs SHOULD NOT issue a provisional response for a + // non-INVITE request. Rather, UASs SHOULD generate a final response to + // a non-INVITE request as soon as possible. + // https://tools.ietf.org/html/rfc3261#section-8.2.6.1 + if (options.statusCode >= 100 && options.statusCode < 200) { + // TODO + } + // When a 100 (Trying) response is generated, any Timestamp header field + // present in the request MUST be copied into this 100 (Trying) + // response. If there is a delay in generating the response, the UAS + // SHOULD add a delay value into the Timestamp value in the response. + // This value MUST contain the difference between the time of sending of + // the response and receipt of the request, measured in seconds. + // https://tools.ietf.org/html/rfc3261#section-8.2.6.1 + if (options.statusCode === 100) { + // TODO + } + // The From field of the response MUST equal the From header field of + // the request. The Call-ID header field of the response MUST equal the + // Call-ID header field of the request. The CSeq header field of the + // response MUST equal the CSeq field of the request. The Via header + // field values in the response MUST equal the Via header field values + // in the request and MUST maintain the same ordering. + // https://tools.ietf.org/html/rfc3261#section-8.2.6.2 + var fromHeader = "From: " + message.getHeader("From") + CRLF; + var callIdHeader = "Call-ID: " + message.callId + CRLF; + var cSeqHeader = "CSeq: " + message.cseq + " " + message.method + CRLF; + var viaHeaders = message.getHeaders("via").reduce(function (previous, current) { + return previous + "Via: " + current + CRLF; + }, ""); + // If a request contained a To tag in the request, the To header field + // in the response MUST equal that of the request. However, if the To + // header field in the request did not contain a tag, the URI in the To + // header field in the response MUST equal the URI in the To header + // field; additionally, the UAS MUST add a tag to the To header field in + // the response (with the exception of the 100 (Trying) response, in + // which a tag MAY be present). This serves to identify the UAS that is + // responding, possibly resulting in a component of a dialog ID. The + // same tag MUST be used for all responses to that request, both final + // and provisional (again excepting the 100 (Trying)). + // https://tools.ietf.org/html/rfc3261#section-8.2.6.2 + var toHeader = "To: " + message.getHeader("to"); + if (options.statusCode > 100 && !message.parseHeader("to").hasParam("tag")) { + var toTag = options.toTag; + if (!toTag) { + // Stateless UAS Behavior... + // o To header tags MUST be generated for responses in a stateless + // manner - in a manner that will generate the same tag for the + // same request consistently. For information on tag construction + // see Section 19.3. + // https://tools.ietf.org/html/rfc3261#section-8.2.7 + toTag = Utils_1.Utils.newTag(); // FIXME: Utils.newTag() currently generates random tags + } + toHeader += ";tag=" + toTag; + } + toHeader += CRLF; + // FIXME: TODO: needs review... moved to InviteUserAgentServer (as it is specific to that) + // let recordRouteHeaders = ""; + // if (request.method === C.INVITE && statusCode > 100 && statusCode <= 200) { + // recordRouteHeaders = request.getHeaders("record-route").reduce((previous, current) => { + // return previous + "Record-Route: " + current + CRLF; + // }, ""); + // } + // FIXME: TODO: needs review... + var supportedHeader = SIPMessage_1.getSupportedHeader(message); + // FIXME: TODO: needs review... + var userAgentHeader = ""; + if (options.userAgent) { + userAgentHeader = "User-Agent: " + options.userAgent + CRLF; + } + var extensionHeaders = ""; + if (options.extraHeaders) { + extensionHeaders = options.extraHeaders.reduce(function (previous, current) { + return previous + current.trim() + CRLF; + }, ""); + } + // The relative order of header fields with different field names is not + // significant. However, it is RECOMMENDED that header fields which are + // needed for proxy processing (Via, Route, Record-Route, Proxy-Require, + // Max-Forwards, and Proxy-Authorization, for example) appear towards + // the top of the message to facilitate rapid parsing. + // https://tools.ietf.org/html/rfc3261#section-7.3.1 + // response += recordRouteHeaders; + response += viaHeaders; + response += fromHeader; + response += toHeader; + response += cSeqHeader; + response += callIdHeader; + response += supportedHeader; + response += userAgentHeader; + response += extensionHeaders; + if (options.body) { + response += "Content-Type: " + options.body.contentType + CRLF; + response += "Content-Length: " + Utils_1.Utils.str_utf8_length(options.body.content) + CRLF + CRLF; + response += options.body.content; + } + else { + response += "Content-Length: " + 0 + CRLF + CRLF; + } + return { message: response }; +} +exports.constructOutgoingResponse = constructOutgoingResponse; + + +/***/ }), +/* 66 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +var ClientContext_1 = __webpack_require__(1); +var Constants_1 = __webpack_require__(3); +var Enums_1 = __webpack_require__(5); +var Exceptions_1 = __webpack_require__(47); +var Grammar_1 = __webpack_require__(7); +var Utils_1 = __webpack_require__(11); +/** + * Configuration load. + * @private + * returns {any} + */ +function loadConfig(configuration) { + var settings = { + expires: 600, + extraContactHeaderParams: [], + instanceId: undefined, + params: {}, + regId: undefined, + registrar: undefined, + }; + var configCheck = getConfigurationCheck(); + // Check Mandatory parameters + for (var parameter in configCheck.mandatory) { + if (!configuration.hasOwnProperty(parameter)) { + throw new Exceptions_1.Exceptions.ConfigurationError(parameter); + } + else { + var value = configuration[parameter]; + var checkedValue = configCheck.mandatory[parameter](value); + if (checkedValue !== undefined) { + settings[parameter] = checkedValue; + } + else { + throw new Exceptions_1.Exceptions.ConfigurationError(parameter, value); + } + } + } + // Check Optional parameters + for (var parameter in configCheck.optional) { + if (configuration.hasOwnProperty(parameter)) { + var value = configuration[parameter]; + // If the parameter value is an empty array, but shouldn't be, apply its default value. + if (value instanceof Array && value.length === 0) { + continue; + } + // If the parameter value is null, empty string, or undefined then apply its default value. + // If it's a number with NaN value then also apply its default value. + // NOTE: JS does not allow "value === NaN", the following does the work: + if (value === null || value === "" || value === undefined || + (typeof (value) === "number" && isNaN(value))) { + continue; + } + var checkedValue = configCheck.optional[parameter](value); + if (checkedValue !== undefined) { + settings[parameter] = checkedValue; + } + else { + throw new Exceptions_1.Exceptions.ConfigurationError(parameter, value); + } + } + } + return settings; +} +function getConfigurationCheck() { + return { + mandatory: {}, + optional: { + expires: function (expires) { + if (Utils_1.Utils.isDecimal(expires)) { + var value = Number(expires); + if (value >= 0) { + return value; + } + } + }, + extraContactHeaderParams: function (extraContactHeaderParams) { + if (extraContactHeaderParams instanceof Array) { + return extraContactHeaderParams.filter(function (contactHeaderParam) { return (typeof contactHeaderParam === "string"); }); + } + }, + instanceId: function (instanceId) { + if (typeof instanceId !== "string") { + return; + } + if ((/^uuid:/i.test(instanceId))) { + instanceId = instanceId.substr(5); + } + if (Grammar_1.Grammar.parse(instanceId, "uuid") === -1) { + return; + } + else { + return instanceId; + } + }, + params: function (params) { + if (typeof params === "object") { + return params; + } + }, + regId: function (regId) { + if (Utils_1.Utils.isDecimal(regId)) { + var value = Number(regId); + if (value >= 0) { + return value; + } + } + }, + registrar: function (registrar) { + if (typeof registrar !== "string") { + return; + } + if (!/^sip:/i.test(registrar)) { + registrar = Constants_1.C.SIP + ":" + registrar; + } + var parsed = Grammar_1.Grammar.URIParse(registrar); + if (!parsed) { + return; + } + else if (parsed.user) { + return; + } + else { + return parsed; + } + } + } + }; +} +var RegisterContext = /** @class */ (function (_super) { + __extends(RegisterContext, _super); + function RegisterContext(ua, options) { + if (options === void 0) { options = {}; } + var _this = this; + var settings = loadConfig(options); + if (settings.regId && !settings.instanceId) { + settings.instanceId = Utils_1.Utils.newUUID(); + } + else if (!settings.regId && settings.instanceId) { + settings.regId = 1; + } + settings.params.toUri = settings.params.toUri || ua.configuration.uri; + settings.params.toDisplayName = settings.params.toDisplayName || ua.configuration.displayName; + settings.params.callId = settings.params.callId || Utils_1.Utils.createRandomToken(22); + settings.params.cseq = settings.params.cseq || Math.floor(Math.random() * 10000); + /* If no 'registrarServer' is set use the 'uri' value without user portion. */ + if (!settings.registrar) { + var registrarServer = {}; + if (typeof ua.configuration.uri === "object") { + registrarServer = ua.configuration.uri.clone(); + registrarServer.user = undefined; + } + else { + registrarServer = ua.configuration.uri; + } + settings.registrar = registrarServer; + } + _this = _super.call(this, ua, Constants_1.C.REGISTER, settings.registrar, settings) || this; + _this.type = Enums_1.TypeStrings.RegisterContext; + _this.options = settings; + _this.logger = ua.getLogger("sip.registercontext"); + _this.logger.log("configuration parameters for RegisterContext after validation:"); + for (var parameter in settings) { + if (settings.hasOwnProperty(parameter)) { + _this.logger.log("· " + parameter + ": " + JSON.stringify(settings[parameter])); + } + } + // Registration expires + _this.expires = settings.expires; + // Contact header + _this.contact = ua.contact.toString(); + // Set status + _this.registered = false; + ua.on("transportCreated", function (transport) { + transport.on("disconnected", function () { return _this.onTransportDisconnected(); }); + }); + return _this; + } + RegisterContext.prototype.register = function (options) { + var _this = this; + if (options === void 0) { options = {}; } + // Handle Options + this.options = __assign({}, this.options, options); + var extraHeaders = (this.options.extraHeaders || []).slice(); + extraHeaders.push("Contact: " + this.generateContactHeader(this.expires)); + // this is UA.C.ALLOWED_METHODS, removed to get around circular dependency + extraHeaders.push("Allow: " + [ + "ACK", + "CANCEL", + "INVITE", + "MESSAGE", + "BYE", + "OPTIONS", + "INFO", + "NOTIFY", + "REFER" + ].toString()); + // Save original extraHeaders to be used in .close + this.closeHeaders = this.options.closeWithHeaders ? + (this.options.extraHeaders || []).slice() : []; + this.receiveResponse = function (response) { + // Discard responses to older REGISTER/un-REGISTER requests. + if (response.cseq !== _this.request.cseq) { + return; + } + // Clear registration timer + if (_this.registrationTimer !== undefined) { + clearTimeout(_this.registrationTimer); + _this.registrationTimer = undefined; + } + var statusCode = (response.statusCode || 0).toString(); + switch (true) { + case /^1[0-9]{2}$/.test(statusCode): + _this.emit("progress", response); + break; + case /^2[0-9]{2}$/.test(statusCode): + _this.emit("accepted", response); + var expires = void 0; + if (response.hasHeader("expires")) { + expires = Number(response.getHeader("expires")); + } + if (_this.registrationExpiredTimer !== undefined) { + clearTimeout(_this.registrationExpiredTimer); + _this.registrationExpiredTimer = undefined; + } + // Search the Contact pointing to us and update the expires value accordingly. + var contacts = response.getHeaders("contact").length; + if (!contacts) { + _this.logger.warn("no Contact header in response to REGISTER, response ignored"); + break; + } + var contact = void 0; + while (contacts--) { + contact = response.parseHeader("contact", contacts); + if (contact.uri.user === _this.ua.contact.uri.user) { + expires = contact.getParam("expires"); + break; + } + else { + contact = undefined; + } + } + if (!contact) { + _this.logger.warn("no Contact header pointing to us, response ignored"); + break; + } + if (expires === undefined) { + expires = _this.expires; + } + // Re-Register before the expiration interval has elapsed. + // For that, decrease the expires value. ie: 3 seconds + _this.registrationTimer = setTimeout(function () { + _this.registrationTimer = undefined; + _this.register(_this.options); + }, (expires * 1000) - 3000); + _this.registrationExpiredTimer = setTimeout(function () { + _this.logger.warn("registration expired"); + if (_this.registered) { + _this.unregistered(undefined, Constants_1.C.causes.EXPIRES); + } + }, expires * 1000); + // Save gruu values + if (contact.hasParam("temp-gruu")) { + _this.ua.contact.tempGruu = Grammar_1.Grammar.URIParse(contact.getParam("temp-gruu").replace(/"/g, "")); + } + if (contact.hasParam("pub-gruu")) { + _this.ua.contact.pubGruu = Grammar_1.Grammar.URIParse(contact.getParam("pub-gruu").replace(/"/g, "")); + } + _this.registered = true; + _this.emit("registered", response || undefined); + break; + // Interval too brief RFC3261 10.2.8 + case /^423$/.test(statusCode): + if (response.hasHeader("min-expires")) { + // Increase our registration interval to the suggested minimum + _this.expires = Number(response.getHeader("min-expires")); + // Attempt the registration again immediately + _this.register(_this.options); + } + else { // This response MUST contain a Min-Expires header field + _this.logger.warn("423 response received for REGISTER without Min-Expires"); + _this.registrationFailure(response, Constants_1.C.causes.SIP_FAILURE_CODE); + } + break; + default: + _this.registrationFailure(response, Utils_1.Utils.sipErrorCause(response.statusCode || 0)); + } + }; + this.onRequestTimeout = function () { + _this.registrationFailure(undefined, Constants_1.C.causes.REQUEST_TIMEOUT); + }; + this.onTransportError = function () { + _this.registrationFailure(undefined, Constants_1.C.causes.CONNECTION_ERROR); + }; + this.request.cseq++; + this.request.setHeader("cseq", this.request.cseq + " REGISTER"); + this.request.extraHeaders = extraHeaders; + this.send(); + }; + RegisterContext.prototype.close = function () { + var options = { + all: false, + extraHeaders: this.closeHeaders + }; + this.registeredBefore = this.registered; + if (this.registered) { + this.unregister(options); + } + }; + RegisterContext.prototype.unregister = function (options) { + var _this = this; + if (options === void 0) { options = {}; } + if (!this.registered && !options.all) { + this.logger.warn("Already unregistered, but sending an unregister anyways."); + } + var extraHeaders = (options.extraHeaders || []).slice(); + this.registered = false; + // Clear the registration timer. + if (this.registrationTimer !== undefined) { + clearTimeout(this.registrationTimer); + this.registrationTimer = undefined; + } + if (options.all) { + extraHeaders.push("Contact: *"); + extraHeaders.push("Expires: 0"); + } + else { + extraHeaders.push("Contact: " + this.generateContactHeader(0)); + } + this.receiveResponse = function (response) { + var statusCode = (response && response.statusCode) ? response.statusCode.toString() : ""; + switch (true) { + case /^1[0-9]{2}$/.test(statusCode): + _this.emit("progress", response); + break; + case /^2[0-9]{2}$/.test(statusCode): + _this.emit("accepted", response); + if (_this.registrationExpiredTimer !== undefined) { + clearTimeout(_this.registrationExpiredTimer); + _this.registrationExpiredTimer = undefined; + } + _this.unregistered(response); + break; + default: + _this.unregistered(response, Utils_1.Utils.sipErrorCause(response.statusCode || 0)); + } + }; + this.onRequestTimeout = function () { + // Not actually unregistered... + // this.unregistered(undefined, SIP.C.causes.REQUEST_TIMEOUT); + }; + this.request.cseq++; + this.request.setHeader("cseq", this.request.cseq + " REGISTER"); + this.request.extraHeaders = extraHeaders; + this.send(); + }; + RegisterContext.prototype.unregistered = function (response, cause) { + this.registered = false; + this.emit("unregistered", response || undefined, cause || undefined); + }; + RegisterContext.prototype.send = function () { + var _this = this; + this.ua.userAgentCore.register(this.request, { + onAccept: function (response) { return _this.receiveResponse(response.message); }, + onProgress: function (response) { return _this.receiveResponse(response.message); }, + onRedirect: function (response) { return _this.receiveResponse(response.message); }, + onReject: function (response) { return _this.receiveResponse(response.message); }, + onTrying: function (response) { return _this.receiveResponse(response.message); } + }); + return this; + }; + RegisterContext.prototype.registrationFailure = function (response, cause) { + this.emit("failed", response || undefined, cause || undefined); + }; + RegisterContext.prototype.onTransportDisconnected = function () { + this.registeredBefore = this.registered; + if (this.registrationTimer !== undefined) { + clearTimeout(this.registrationTimer); + this.registrationTimer = undefined; + } + if (this.registrationExpiredTimer !== undefined) { + clearTimeout(this.registrationExpiredTimer); + this.registrationExpiredTimer = undefined; + } + if (this.registered) { + this.unregistered(undefined, Constants_1.C.causes.CONNECTION_ERROR); + } + }; + /** + * Helper Function to generate Contact Header + * @private + * returns {String} + */ + RegisterContext.prototype.generateContactHeader = function (expires) { + if (expires === void 0) { expires = 0; } + var contact = this.contact; + if (this.options.regId && this.options.instanceId) { + contact += ";reg-id=" + this.options.regId; + contact += ';+sip.instance=""'; + } + if (this.options.extraContactHeaderParams) { + this.options.extraContactHeaderParams.forEach(function (header) { + contact += ";" + header; + }); + } + contact += ";expires=" + expires; + return contact; + }; + return RegisterContext; +}(ClientContext_1.ClientContext)); +exports.RegisterContext = RegisterContext; + + +/***/ }), +/* 67 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var events_1 = __webpack_require__(2); +var ClientContext_1 = __webpack_require__(1); +var Constants_1 = __webpack_require__(3); +var messages_1 = __webpack_require__(63); +var session_1 = __webpack_require__(68); +var Enums_1 = __webpack_require__(5); +var Exceptions_1 = __webpack_require__(47); +var Grammar_1 = __webpack_require__(7); +var ReferContext_1 = __webpack_require__(51); +var ServerContext_1 = __webpack_require__(62); +var DTMF_1 = __webpack_require__(70); +var Timers_1 = __webpack_require__(56); +var Utils_1 = __webpack_require__(11); +/* + * @param {function returning SIP.sessionDescriptionHandler} [sessionDescriptionHandlerFactory] + * (See the documentation for the sessionDescriptionHandlerFactory argument of the UA constructor.) + */ +var Session = /** @class */ (function (_super) { + __extends(Session, _super); + function Session(sessionDescriptionHandlerFactory) { + var _this = _super.call(this) || this; + _this.data = {}; + _this.type = Enums_1.TypeStrings.Session; + if (!sessionDescriptionHandlerFactory) { + throw new Exceptions_1.Exceptions.SessionDescriptionHandlerError("A session description handler is required for the session to function"); + } + _this.status = Session.C.STATUS_NULL; + _this.pendingReinvite = false; + _this.sessionDescriptionHandlerFactory = sessionDescriptionHandlerFactory; + _this.hasOffer = false; + _this.hasAnswer = false; + // Session Timers + _this.timers = { + ackTimer: undefined, + expiresTimer: undefined, + invite2xxTimer: undefined, + userNoAnswerTimer: undefined, + rel1xxTimer: undefined, + prackTimer: undefined + }; + // Session info + _this.startTime = undefined; + _this.endTime = undefined; + _this.tones = undefined; + // Hold state + _this.localHold = false; + _this.earlySdp = undefined; + _this.rel100 = Constants_1.C.supported.UNSUPPORTED; + return _this; + } + Session.prototype.dtmf = function (tones, options) { + var _this = this; + if (options === void 0) { options = {}; } + // Check Session Status + if (this.status !== Enums_1.SessionStatus.STATUS_CONFIRMED && this.status !== Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK) { + throw new Exceptions_1.Exceptions.InvalidStateError(this.status); + } + // Check tones + if (!tones || !tones.toString().match(/^[0-9A-D#*,]+$/i)) { + throw new TypeError("Invalid tones: " + tones); + } + var sendDTMF = function () { + if (_this.status === Enums_1.SessionStatus.STATUS_TERMINATED || !_this.tones || _this.tones.length === 0) { + // Stop sending DTMF + _this.tones = undefined; + return; + } + var dtmf = _this.tones.shift(); + var timeout; + if (dtmf.tone === ",") { + timeout = 2000; + } + else { + dtmf.on("failed", function () { _this.tones = undefined; }); + dtmf.send(options); + timeout = dtmf.duration + dtmf.interToneGap; + } + // Set timeout for the next tone + setTimeout(sendDTMF, timeout); + }; + tones = tones.toString(); + var dtmfType = this.ua.configuration.dtmfType; + if (this.sessionDescriptionHandler && dtmfType === Constants_1.C.dtmfType.RTP) { + var sent = this.sessionDescriptionHandler.sendDtmf(tones, options); + if (!sent) { + this.logger.warn("Attempt to use dtmfType 'RTP' has failed, falling back to INFO packet method"); + dtmfType = Constants_1.C.dtmfType.INFO; + } + } + if (dtmfType === Constants_1.C.dtmfType.INFO) { + var dtmfs = []; + var tonesArray = tones.split(""); + while (tonesArray.length > 0) { + dtmfs.push(new DTMF_1.DTMF(this, tonesArray.shift(), options)); + } + if (this.tones) { + // Tones are already queued, just add to the queue + this.tones = this.tones.concat(dtmfs); + return this; + } + this.tones = dtmfs; + sendDTMF(); + } + return this; + }; + Session.prototype.bye = function (options) { + if (options === void 0) { options = {}; } + // Check Session Status + if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { + this.logger.error("Error: Attempted to send BYE in a terminated session."); + return this; + } + this.logger.log("terminating Session"); + var statusCode = options.statusCode; + if (statusCode && (statusCode < 200 || statusCode >= 700)) { + throw new TypeError("Invalid statusCode: " + statusCode); + } + options.receiveResponse = function () { }; + return this.sendRequest(Constants_1.C.BYE, options).terminated(); + }; + Session.prototype.refer = function (target, options) { + if (options === void 0) { options = {}; } + // Check Session Status + if (this.status !== Enums_1.SessionStatus.STATUS_CONFIRMED) { + throw new Exceptions_1.Exceptions.InvalidStateError(this.status); + } + this.referContext = new ReferContext_1.ReferClientContext(this.ua, this, target, options); + this.emit("referRequested", this.referContext); + this.referContext.refer(options); + return this.referContext; + }; + /** + * Sends in dialog request. + * @param method Request method. + * @param options Options bucket. + */ + Session.prototype.sendRequest = function (method, options) { + if (options === void 0) { options = {}; } + if (!this.session) { + throw new Error("Session undefined."); + } + // Convert any "body" option to a Body. + if (options.body) { + options.body = messages_1.fromBodyObj(options.body); + } + // Convert any "receiveResponse" callback option passed to an OutgoingRequestDelegate. + var delegate; + var callback = options.receiveResponse; + if (callback) { + delegate = { + onAccept: function (response) { return callback(response.message); }, + onProgress: function (response) { return callback(response.message); }, + onRedirect: function (response) { return callback(response.message); }, + onReject: function (response) { return callback(response.message); }, + onTrying: function (response) { return callback(response.message); } + }; + } + var request; + var requestOptions = options; + switch (method) { + case Constants_1.C.BYE: + request = this.session.bye(delegate, requestOptions); + break; + case Constants_1.C.INVITE: + request = this.session.invite(delegate, requestOptions); + break; + case Constants_1.C.REFER: + request = this.session.refer(delegate, requestOptions); + break; + default: + throw new Error("Unexpected " + method + ". Method not implemented by user agent core."); + } + // Ported - Emit the request event + this.emit(method.toLowerCase(), request.message); + return this; + }; + Session.prototype.close = function () { + if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { + return this; + } + this.logger.log("closing INVITE session " + this.id); + // 1st Step. Terminate media. + if (this.sessionDescriptionHandler) { + this.sessionDescriptionHandler.close(); + } + // 2nd Step. Terminate signaling. + // Clear session timers + for (var timer in this.timers) { + if (this.timers[timer]) { + clearTimeout(this.timers[timer]); + } + } + this.status = Enums_1.SessionStatus.STATUS_TERMINATED; + if (this.ua.transport) { + this.ua.transport.removeListener("transportError", this.errorListener); + } + delete this.ua.sessions[this.id]; + return this; + }; + Session.prototype.hold = function (options, modifiers) { + if (options === void 0) { options = {}; } + if (modifiers === void 0) { modifiers = []; } + if (this.status !== Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK && this.status !== Enums_1.SessionStatus.STATUS_CONFIRMED) { + throw new Exceptions_1.Exceptions.InvalidStateError(this.status); + } + if (this.localHold) { + this.logger.log("Session is already on hold, cannot put it on hold again"); + return; + } + options.modifiers = modifiers; + if (this.sessionDescriptionHandler) { + options.modifiers.push(this.sessionDescriptionHandler.holdModifier); + } + this.localHold = true; + this.sendReinvite(options); + }; + Session.prototype.unhold = function (options, modifiers) { + if (options === void 0) { options = {}; } + if (modifiers === void 0) { modifiers = []; } + if (this.status !== Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK && this.status !== Enums_1.SessionStatus.STATUS_CONFIRMED) { + throw new Exceptions_1.Exceptions.InvalidStateError(this.status); + } + if (!this.localHold) { + this.logger.log("Session is not on hold, cannot unhold it"); + return; + } + options.modifiers = modifiers; + this.localHold = false; + this.sendReinvite(options); + }; + Session.prototype.reinvite = function (options, modifiers) { + if (options === void 0) { options = {}; } + if (modifiers === void 0) { modifiers = []; } + options.modifiers = modifiers; + return this.sendReinvite(options); + }; + Session.prototype.terminate = function (options) { + // here for types and to be overridden + return this; + }; + Session.prototype.onTransportError = function () { + if (this.status !== Enums_1.SessionStatus.STATUS_CONFIRMED && this.status !== Enums_1.SessionStatus.STATUS_TERMINATED) { + this.failed(undefined, Constants_1.C.causes.CONNECTION_ERROR); + } + }; + Session.prototype.onRequestTimeout = function () { + if (this.status === Enums_1.SessionStatus.STATUS_CONFIRMED) { + this.terminated(undefined, Constants_1.C.causes.REQUEST_TIMEOUT); + } + else if (this.status !== Enums_1.SessionStatus.STATUS_TERMINATED) { + this.failed(undefined, Constants_1.C.causes.REQUEST_TIMEOUT); + this.terminated(undefined, Constants_1.C.causes.REQUEST_TIMEOUT); + } + }; + Session.prototype.onDialogError = function (response) { + if (this.status === Enums_1.SessionStatus.STATUS_CONFIRMED) { + this.terminated(response, Constants_1.C.causes.DIALOG_ERROR); + } + else if (this.status !== Enums_1.SessionStatus.STATUS_TERMINATED) { + this.failed(response, Constants_1.C.causes.DIALOG_ERROR); + this.terminated(response, Constants_1.C.causes.DIALOG_ERROR); + } + }; + Session.prototype.on = function (name, callback) { + return _super.prototype.on.call(this, name, callback); + }; + Session.prototype.onAck = function (incomingRequest) { + var _this = this; + var confirmSession = function () { + clearTimeout(_this.timers.ackTimer); + clearTimeout(_this.timers.invite2xxTimer); + _this.status = Enums_1.SessionStatus.STATUS_CONFIRMED; + var contentDisp = incomingRequest.message.getHeader("Content-Disposition"); + if (contentDisp && contentDisp.type === "render") { + _this.renderbody = incomingRequest.message.body; + _this.rendertype = incomingRequest.message.getHeader("Content-Type"); + } + _this.emit("confirmed", incomingRequest.message); + }; + if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK) { + if (this.sessionDescriptionHandler && + this.sessionDescriptionHandler.hasDescription(incomingRequest.message.getHeader("Content-Type") || "")) { + this.hasAnswer = true; + this.sessionDescriptionHandler.setDescription(incomingRequest.message.body, this.sessionDescriptionHandlerOptions, this.modifiers).catch(function (e) { + _this.logger.warn(e); + _this.terminate({ + statusCode: "488", + reasonPhrase: "Bad Media Description" + }); + _this.failed(incomingRequest.message, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); + _this.terminated(incomingRequest.message, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); + throw e; + }).then(function () { return confirmSession(); }); + } + else { + confirmSession(); + } + } + }; + Session.prototype.receiveRequest = function (incomingRequest) { + switch (incomingRequest.message.method) { // TODO: This needs a default case + case Constants_1.C.BYE: + incomingRequest.accept(); + if (this.status === Enums_1.SessionStatus.STATUS_CONFIRMED) { + this.emit("bye", incomingRequest.message); + this.terminated(incomingRequest.message, Constants_1.C.BYE); + } + break; + case Constants_1.C.INVITE: + if (this.status === Enums_1.SessionStatus.STATUS_CONFIRMED) { + this.logger.log("re-INVITE received"); + this.receiveReinvite(incomingRequest); + } + break; + case Constants_1.C.INFO: + if (this.status === Enums_1.SessionStatus.STATUS_CONFIRMED || this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK) { + if (this.onInfo) { + return this.onInfo(incomingRequest.message); + } + var contentType = incomingRequest.message.getHeader("content-type"); + if (contentType) { + if (contentType.match(/^application\/dtmf-relay/i)) { + if (incomingRequest.message.body) { + var body = incomingRequest.message.body.split("\r\n", 2); + if (body.length === 2) { + var tone = void 0; + var duration = void 0; + var regTone = /^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/; + if (regTone.test(body[0])) { + tone = body[0].replace(regTone, "$2"); + } + var regDuration = /^(Duration\s?=\s?)([0-9]{1,4})(\s)?.*/; + if (regDuration.test(body[1])) { + duration = parseInt(body[1].replace(regDuration, "$2"), 10); + } + if (tone && duration) { + new DTMF_1.DTMF(this, tone, { duration: duration }).init_incoming(incomingRequest); + } + } + } + } + else { + incomingRequest.reject({ + statusCode: 415, + extraHeaders: ["Accept: application/dtmf-relay"] + }); + } + } + } + break; + case Constants_1.C.REFER: + if (this.status === Enums_1.SessionStatus.STATUS_CONFIRMED) { + this.logger.log("REFER received"); + this.referContext = new ReferContext_1.ReferServerContext(this.ua, incomingRequest, this.session); + if (this.listeners("referRequested").length) { + this.emit("referRequested", this.referContext); + } + else { + this.logger.log("No referRequested listeners, automatically accepting and following the refer"); + var options = { followRefer: true }; + if (this.passedOptions) { + options.inviteOptions = this.passedOptions; + } + this.referContext.accept(options, this.modifiers); + } + } + break; + case Constants_1.C.NOTIFY: + if (this.referContext && + this.referContext.type === Enums_1.TypeStrings.ReferClientContext && + incomingRequest.message.hasHeader("event") && + /^refer(;.*)?$/.test(incomingRequest.message.getHeader("event"))) { + this.referContext.receiveNotify(incomingRequest); + return; + } + incomingRequest.accept(); + this.emit("notify", incomingRequest.message); + break; + } + }; + // In dialog INVITE Reception + Session.prototype.receiveReinvite = function (incomingRequest) { + // TODO: Should probably check state of the session + var _this = this; + this.emit("reinvite", this, incomingRequest.message); + if (incomingRequest.message.hasHeader("P-Asserted-Identity")) { + this.assertedIdentity = + Grammar_1.Grammar.nameAddrHeaderParse(incomingRequest.message.getHeader("P-Asserted-Identity")); + } + var promise; + if (!this.sessionDescriptionHandler) { + this.logger.warn("No SessionDescriptionHandler to reinvite"); + return; + } + if (incomingRequest.message.getHeader("Content-Length") === "0" && + !incomingRequest.message.getHeader("Content-Type")) { // Invite w/o SDP + promise = this.sessionDescriptionHandler.getDescription(this.sessionDescriptionHandlerOptions, this.modifiers); + } + else if (this.sessionDescriptionHandler.hasDescription(incomingRequest.message.getHeader("Content-Type") || "")) { + // Invite w/ SDP + promise = this.sessionDescriptionHandler.setDescription(incomingRequest.message.body, this.sessionDescriptionHandlerOptions, this.modifiers).then(this.sessionDescriptionHandler.getDescription.bind(this.sessionDescriptionHandler, this.sessionDescriptionHandlerOptions, this.modifiers)); + } + else { // Bad Packet (should never get hit) + incomingRequest.reject({ statusCode: 415 }); + this.emit("reinviteFailed", this); + return; + } + promise.catch(function (e) { + var statusCode; + if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { + statusCode = 500; + } + else if (e.type === Enums_1.TypeStrings.RenegotiationError) { + _this.emit("renegotiationError", e); + _this.logger.warn(e.toString()); + statusCode = 488; + } + else { + _this.logger.error(e); + statusCode = 488; + } + incomingRequest.reject({ statusCode: statusCode }); + _this.emit("reinviteFailed", _this); + // TODO: This could be better + throw e; + }).then(function (description) { + var extraHeaders = ["Contact: " + _this.contact]; + incomingRequest.accept({ + statusCode: 200, + extraHeaders: extraHeaders, + body: messages_1.fromBodyObj(description) + }); + _this.status = Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK; + _this.emit("reinviteAccepted", _this); + }); + }; + Session.prototype.sendReinvite = function (options) { + var _this = this; + if (options === void 0) { options = {}; } + if (this.pendingReinvite) { + this.logger.warn("Reinvite in progress. Please wait until complete, then try again."); + return; + } + if (!this.sessionDescriptionHandler) { + this.logger.warn("No SessionDescriptionHandler, can't reinvite.."); + return; + } + this.pendingReinvite = true; + options.modifiers = options.modifiers || []; + var extraHeaders = (options.extraHeaders || []).slice(); + extraHeaders.push("Contact: " + this.contact); + // this is UA.C.ALLOWED_METHODS, removed to get around circular dependency + extraHeaders.push("Allow: " + [ + "ACK", + "CANCEL", + "INVITE", + "MESSAGE", + "BYE", + "OPTIONS", + "INFO", + "NOTIFY", + "REFER" + ].toString()); + this.sessionDescriptionHandler.getDescription(options.sessionDescriptionHandlerOptions, options.modifiers) + .then(function (description) { + if (!_this.session) { + throw new Error("Session undefined."); + } + var delegate = { + onAccept: function (response) { + if (_this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { + _this.logger.error("Received reinvite response, but in STATUS_TERMINATED"); + // TODO: Do we need to send a SIP response? + return; + } + if (!_this.pendingReinvite) { + _this.logger.error("Received reinvite response, but have no pending reinvite"); + // TODO: Do we need to send a SIP response? + return; + } + // FIXME: Why is this set here? + _this.status = Enums_1.SessionStatus.STATUS_CONFIRMED; + // 17.1.1.1 - For each final response that is received at the client transaction, + // the client transaction sends an ACK, + _this.emit("ack", response.ack()); + _this.pendingReinvite = false; + // TODO: All of these timers should move into the Transaction layer + clearTimeout(_this.timers.invite2xxTimer); + if (!_this.sessionDescriptionHandler || + !_this.sessionDescriptionHandler.hasDescription(response.message.getHeader("Content-Type") || "")) { + _this.logger.error("2XX response received to re-invite but did not have a description"); + _this.emit("reinviteFailed", _this); + _this.emit("renegotiationError", new Exceptions_1.Exceptions.RenegotiationError("2XX response received to re-invite but did not have a description")); + return; + } + _this.sessionDescriptionHandler + .setDescription(response.message.body, _this.sessionDescriptionHandlerOptions, _this.modifiers) + .catch(function (e) { + _this.logger.error("Could not set the description in 2XX response"); + _this.logger.error(e); + _this.emit("reinviteFailed", _this); + _this.emit("renegotiationError", e); + _this.sendRequest(Constants_1.C.BYE, { + extraHeaders: ["Reason: " + Utils_1.Utils.getReasonHeaderValue(488, "Not Acceptable Here")] + }); + _this.terminated(undefined, Constants_1.C.causes.INCOMPATIBLE_SDP); + throw e; + }) + .then(function () { + _this.emit("reinviteAccepted", _this); + }); + }, + onProgress: function (response) { + return; + }, + onRedirect: function (response) { + // FIXME: Does ACK need to be sent? + _this.pendingReinvite = false; + _this.logger.log("Received a non 1XX or 2XX response to a re-invite"); + _this.emit("reinviteFailed", _this); + _this.emit("renegotiationError", new Exceptions_1.Exceptions.RenegotiationError("Invalid response to a re-invite")); + }, + onReject: function (response) { + // FIXME: Does ACK need to be sent? + _this.pendingReinvite = false; + _this.logger.log("Received a non 1XX or 2XX response to a re-invite"); + _this.emit("reinviteFailed", _this); + _this.emit("renegotiationError", new Exceptions_1.Exceptions.RenegotiationError("Invalid response to a re-invite")); + }, + onTrying: function (response) { + return; + } + }; + var requestOptions = { + extraHeaders: extraHeaders, + body: messages_1.fromBodyObj(description) + }; + _this.session.invite(delegate, requestOptions); + }).catch(function (e) { + if (e.type === Enums_1.TypeStrings.RenegotiationError) { + _this.pendingReinvite = false; + _this.emit("renegotiationError", e); + _this.logger.warn("Renegotiation Error"); + _this.logger.warn(e.toString()); + throw e; + } + _this.logger.error("sessionDescriptionHandler error"); + _this.logger.error(e); + throw e; + }); + }; + Session.prototype.failed = function (response, cause) { + if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { + return this; + } + this.emit("failed", response, cause); + return this; + }; + Session.prototype.rejected = function (response, cause) { + this.emit("rejected", response, cause); + return this; + }; + Session.prototype.canceled = function () { + if (this.sessionDescriptionHandler) { + this.sessionDescriptionHandler.close(); + } + this.emit("cancel"); + return this; + }; + Session.prototype.accepted = function (response, cause) { + if (!(response instanceof String)) { + cause = Utils_1.Utils.getReasonPhrase((response && response.statusCode) || 0, cause); + } + this.startTime = new Date(); + if (this.replacee) { + this.replacee.emit("replaced", this); + this.replacee.terminate(); + } + this.emit("accepted", response, cause); + return this; + }; + Session.prototype.terminated = function (message, cause) { + if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { + return this; + } + this.endTime = new Date(); + this.close(); + this.emit("terminated", message, cause); + return this; + }; + Session.prototype.connecting = function (request) { + this.emit("connecting", { request: request }); + return this; + }; + Session.C = Enums_1.SessionStatus; + return Session; +}(events_1.EventEmitter)); +exports.Session = Session; +// tslint:disable-next-line:max-classes-per-file +var InviteServerContext = /** @class */ (function (_super) { + __extends(InviteServerContext, _super); + function InviteServerContext(ua, incomingInviteRequest) { + var _this = this; + if (!ua.configuration.sessionDescriptionHandlerFactory) { + ua.logger.warn("Can't build ISC without SDH Factory"); + throw new Error("ISC Constructor Failed"); + } + _this = _super.call(this, ua.configuration.sessionDescriptionHandlerFactory) || this; + _this._canceled = false; + _this.rseq = Math.floor(Math.random() * 10000); + _this.incomingRequest = incomingInviteRequest; + var request = incomingInviteRequest.message; + ServerContext_1.ServerContext.initializer(_this, ua, incomingInviteRequest); + _this.type = Enums_1.TypeStrings.InviteServerContext; + var contentDisp = request.parseHeader("Content-Disposition"); + if (contentDisp && contentDisp.type === "render") { + _this.renderbody = request.body; + _this.rendertype = request.getHeader("Content-Type"); + } + _this.status = Enums_1.SessionStatus.STATUS_INVITE_RECEIVED; + _this.fromTag = request.fromTag; + _this.id = request.callId + _this.fromTag; + _this.request = request; + _this.contact = _this.ua.contact.toString(); + _this.logger = ua.getLogger("sip.inviteservercontext", _this.id); + // Save the session into the ua sessions collection. + _this.ua.sessions[_this.id] = _this; + // Set 100rel if necessary + var set100rel = function (header, relSetting) { + if (request.hasHeader(header) && request.getHeader(header).toLowerCase().indexOf("100rel") >= 0) { + _this.rel100 = relSetting; + } + }; + set100rel("require", Constants_1.C.supported.REQUIRED); + set100rel("supported", Constants_1.C.supported.SUPPORTED); + // Set the toTag on the incoming request to the toTag which + // will be used in the response to the incoming request!!! + // FIXME: HACK: This is a hack to port an existing behavior. + // The behavior being ported appears to be a hack itself, + // so this is a hack to port a hack. At least one test spec + // relies on it (which is yet another hack). + _this.request.toTag = incomingInviteRequest.toTag; + _this.status = Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER; + // Set userNoAnswerTimer + _this.timers.userNoAnswerTimer = setTimeout(function () { + incomingInviteRequest.reject({ statusCode: 408 }); + _this.failed(request, Constants_1.C.causes.NO_ANSWER); + _this.terminated(request, Constants_1.C.causes.NO_ANSWER); + }, _this.ua.configuration.noAnswerTimeout || 60); + /* Set expiresTimer + * RFC3261 13.3.1 + */ + // Get the Expires header value if exists + if (request.hasHeader("expires")) { + var expires = Number(request.getHeader("expires") || 0) * 1000; + _this.timers.expiresTimer = setTimeout(function () { + if (_this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER) { + incomingInviteRequest.reject({ statusCode: 487 }); + _this.failed(request, Constants_1.C.causes.EXPIRES); + _this.terminated(request, Constants_1.C.causes.EXPIRES); + } + }, expires); + } + _this.errorListener = _this.onTransportError.bind(_this); + if (ua.transport) { + ua.transport.on("transportError", _this.errorListener); + } + return _this; + } + Object.defineProperty(InviteServerContext.prototype, "autoSendAnInitialProvisionalResponse", { + /** + * If true, a first provisional response after the 100 Trying + * will be sent automatically. This is false it the UAC required + * reliable provisional responses (100rel in Require header), + * otherwise it is true. The provisional is sent by calling + * `progress()` without any options. + * + * FIXME: TODO: It seems reasonable that the ISC user should + * be able to optionally disable this behavior. As the provisional + * is sent prior to the "invite" event being emitted, it's a known + * issue that the ISC user cannot register listeners or do any other + * setup prior to the call to `progress()`. As an example why this is + * an issue, setting `ua.configuration.rel100` to REQUIRED will result + * in an attempt by `progress()` to send a 183 with SDP produced by + * calling `getDescription()` on a session description handler, but + * the ISC user cannot perform any potentially required session description + * handler initialization (thus preventing the utilization of setting + * `ua.configuration.rel100` to REQUIRED). That begs the question of + * why this behavior is disabled when the UAC requires 100rel but not + * when the UAS requires 100rel? But ignoring that, it's just one example + * of a class of cases where the ISC user needs to do something prior + * to the first call to `progress()` and is unable to do so. + */ + get: function () { + return this.rel100 === Constants_1.C.supported.REQUIRED ? false : true; + }, + enumerable: true, + configurable: true + }); + // type hack for servercontext interface + InviteServerContext.prototype.reply = function (options) { + if (options === void 0) { options = {}; } + return this; + }; + // typing note: this was the only function using its super in ServerContext + // so the bottom half of this function is copied and paired down from that + InviteServerContext.prototype.reject = function (options) { + var _this = this; + if (options === void 0) { options = {}; } + // Check Session Status + if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { + throw new Exceptions_1.Exceptions.InvalidStateError(this.status); + } + this.logger.log("rejecting RTCSession"); + var statusCode = options.statusCode || 480; + var reasonPhrase = Utils_1.Utils.getReasonPhrase(statusCode, options.reasonPhrase); + var extraHeaders = options.extraHeaders || []; + if (statusCode < 300 || statusCode > 699) { + throw new TypeError("Invalid statusCode: " + statusCode); + } + var body = options.body ? messages_1.fromBodyLegacy(options.body) : undefined; + // FIXME: Need to redirect to someplae + var response = statusCode < 400 ? + this.incomingRequest.redirect([], { statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }) : + this.incomingRequest.reject({ statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }); + (["rejected", "failed"]).forEach(function (event) { + _this.emit(event, response.message, reasonPhrase); + }); + return this.terminated(); + }; + /** + * Accept the incoming INVITE request to start a Session. + * Replies to the INVITE request with a 200 Ok response. + * @param options Options bucket. + */ + InviteServerContext.prototype.accept = function (options) { + var _this = this; + if (options === void 0) { options = {}; } + // FIXME: Need guard against calling more than once. + this._accept(options) + .then(function (_a) { + var message = _a.message, session = _a.session; + session.delegate = { + onAck: function (ackRequest) { return _this.onAck(ackRequest); }, + onAckTimeout: function () { return _this.onAckTimeout(); }, + onBye: function (byeRequest) { return _this.receiveRequest(byeRequest); }, + onInfo: function (infoRequest) { return _this.receiveRequest(infoRequest); }, + onInvite: function (inviteRequest) { return _this.receiveRequest(inviteRequest); }, + onNotify: function (notifyRequest) { return _this.receiveRequest(notifyRequest); }, + onPrack: function (prackRequest) { return _this.receiveRequest(prackRequest); }, + onRefer: function (referRequest) { return _this.receiveRequest(referRequest); } + }; + _this.session = session; + _this.status = Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK; + _this.accepted(message, Utils_1.Utils.getReasonPhrase(200)); + }) + .catch(function (error) { + _this.onContextError(error); + // FIXME: Assuming error due to async race on CANCEL and eating error. + if (!_this._canceled) { + throw error; + } + }); + return this; + }; + /** + * Report progress to the the caller. + * Replies to the INVITE request with a 1xx provisional response. + * @param options Options bucket. + */ + InviteServerContext.prototype.progress = function (options) { + var _this = this; + if (options === void 0) { options = {}; } + // Ported + var statusCode = options.statusCode || 180; + if (statusCode < 100 || statusCode > 199) { + throw new TypeError("Invalid statusCode: " + statusCode); + } + // Ported + if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { + this.logger.warn("Unexpected call for progress while terminated, ignoring"); + return this; + } + // Added + if (this.status === Enums_1.SessionStatus.STATUS_ANSWERED) { + this.logger.warn("Unexpected call for progress while answered, ignoring"); + return this; + } + // Added + if (this.status === Enums_1.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK) { + this.logger.warn("Unexpected call for progress while answered (waiting for prack), ignoring"); + return this; + } + // After the first reliable provisional response for a request has been + // acknowledged, the UAS MAY send additional reliable provisional + // responses. The UAS MUST NOT send a second reliable provisional + // response until the first is acknowledged. After the first, it is + // RECOMMENDED that the UAS not send an additional reliable provisional + // response until the previous is acknowledged. The first reliable + // provisional response receives special treatment because it conveys + // the initial sequence number. If additional reliable provisional + // responses were sent before the first was acknowledged, the UAS could + // not be certain these were received in order. + // https://tools.ietf.org/html/rfc3262#section-3 + if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_PRACK) { + this.logger.warn("Unexpected call for progress while waiting for prack, ignoring"); + return this; + } + // Ported + if (options.statusCode === 100) { + try { + this.incomingRequest.trying(); + } + catch (error) { + this.onContextError(error); + // FIXME: Assuming error due to async race on CANCEL and eating error. + if (!this._canceled) { + throw error; + } + } + return this; + } + // Standard provisional response. + if (!(this.rel100 === Constants_1.C.supported.REQUIRED) && + !(this.rel100 === Constants_1.C.supported.SUPPORTED && options.rel100) && + !(this.rel100 === Constants_1.C.supported.SUPPORTED && this.ua.configuration.rel100 === Constants_1.C.supported.REQUIRED)) { + this._progress(options) + .catch(function (error) { + _this.onContextError(error); + // FIXME: Assuming error due to async race on CANCEL and eating error. + if (!_this._canceled) { + throw error; + } + }); + return this; + } + // Reliable provisional response. + this._reliableProgressWaitForPrack(options) + .catch(function (error) { + _this.onContextError(error); + // FIXME: Assuming error due to async race on CANCEL and eating error. + if (!_this._canceled) { + throw error; + } + }); + return this; + }; + /** + * Reject an unaccepted incoming INVITE request or send BYE if established session. + * @param options Options bucket. FIXME: This options bucket needs to be typed. + */ + InviteServerContext.prototype.terminate = function (options) { + // The caller's UA MAY send a BYE for either confirmed or early dialogs, + // and the callee's UA MAY send a BYE on confirmed dialogs, but MUST NOT + // send a BYE on early dialogs. However, the callee's UA MUST NOT send a + // BYE on a confirmed dialog until it has received an ACK for its 2xx + // response or until the server transaction times out. + // https://tools.ietf.org/html/rfc3261#section-15 + var _this = this; + if (options === void 0) { options = {}; } + // We don't yet have a dialog, so reject request. + if (!this.session) { + this.reject(options); + return this; + } + switch (this.session.sessionState) { + case session_1.SessionState.Initial: + this.reject(options); + return this; + case session_1.SessionState.Early: + this.reject(options); + return this; + case session_1.SessionState.AckWait: + this.session.delegate = { + // When ACK shows up, say BYE. + onAck: function () { + _this.sendRequest(Constants_1.C.BYE, options); + }, + // Or the server transaction times out before the ACK arrives. + onAckTimeout: function () { + _this.sendRequest(Constants_1.C.BYE, options); + } + }; + // Ported + this.emit("bye", this.request); + this.terminated(); + return this; + case session_1.SessionState.Confirmed: + this.bye(options); + return this; + case session_1.SessionState.Terminated: + return this; + default: + return this; + } + }; + InviteServerContext.prototype.onCancel = function (message) { + if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER || + this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_PRACK || + this.status === Enums_1.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK || + this.status === Enums_1.SessionStatus.STATUS_EARLY_MEDIA || + this.status === Enums_1.SessionStatus.STATUS_ANSWERED) { + this.status = Enums_1.SessionStatus.STATUS_CANCELED; + this.incomingRequest.reject({ statusCode: 487 }); + this.canceled(); + this.rejected(message, Constants_1.C.causes.CANCELED); + this.failed(message, Constants_1.C.causes.CANCELED); + this.terminated(message, Constants_1.C.causes.CANCELED); + } + }; + InviteServerContext.prototype.receiveRequest = function (incomingRequest) { + var _this = this; + switch (incomingRequest.message.method) { + case Constants_1.C.PRACK: + if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_PRACK || + this.status === Enums_1.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK) { + if (!this.hasAnswer) { + this.sessionDescriptionHandler = this.setupSessionDescriptionHandler(); + this.emit("SessionDescriptionHandler-created", this.sessionDescriptionHandler); + if (this.sessionDescriptionHandler.hasDescription(incomingRequest.message.getHeader("Content-Type") || "")) { + this.hasAnswer = true; + this.sessionDescriptionHandler.setDescription(incomingRequest.message.body, this.sessionDescriptionHandlerOptions, this.modifiers).then(function () { + clearTimeout(_this.timers.rel1xxTimer); + clearTimeout(_this.timers.prackTimer); + incomingRequest.accept(); + if (_this.status === Enums_1.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK) { + _this.status = Enums_1.SessionStatus.STATUS_EARLY_MEDIA; + _this.accept(); + } + _this.status = Enums_1.SessionStatus.STATUS_EARLY_MEDIA; + }, function (e) { + _this.logger.warn(e); + _this.terminate({ + statusCode: "488", + reasonPhrase: "Bad Media Description" + }); + _this.failed(incomingRequest.message, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); + _this.terminated(incomingRequest.message, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); + }); + } + else { + this.terminate({ + statusCode: "488", + reasonPhrase: "Bad Media Description" + }); + this.failed(incomingRequest.message, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); + this.terminated(incomingRequest.message, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); + } + } + else { + clearTimeout(this.timers.rel1xxTimer); + clearTimeout(this.timers.prackTimer); + incomingRequest.accept(); + if (this.status === Enums_1.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK) { + this.status = Enums_1.SessionStatus.STATUS_EARLY_MEDIA; + this.accept(); + } + this.status = Enums_1.SessionStatus.STATUS_EARLY_MEDIA; + } + } + else if (this.status === Enums_1.SessionStatus.STATUS_EARLY_MEDIA) { + incomingRequest.accept(); + } + break; + default: + _super.prototype.receiveRequest.call(this, incomingRequest); + break; + } + }; + // Internal Function to setup the handler consistently + InviteServerContext.prototype.setupSessionDescriptionHandler = function () { + if (this.sessionDescriptionHandler) { + return this.sessionDescriptionHandler; + } + return this.sessionDescriptionHandlerFactory(this, this.ua.configuration.sessionDescriptionHandlerFactoryOptions); + }; + InviteServerContext.prototype.generateResponseOfferAnswer = function (options) { + if (!this.session) { + var body = messages_1.getBody(this.incomingRequest.message); + if (!body || body.contentDisposition !== "session") { + return this.getOffer(options); + } + else { + return this.setOfferAndGetAnswer(body, options); + } + } + else { + switch (this.session.signalingState) { + case session_1.SignalingState.Initial: + return this.getOffer(options); + case session_1.SignalingState.Stable: + return Promise.resolve(undefined); + case session_1.SignalingState.HaveLocalOffer: + // o Once the UAS has sent or received an answer to the initial + // offer, it MUST NOT generate subsequent offers in any responses + // to the initial INVITE. This means that a UAS based on this + // specification alone can never generate subsequent offers until + // completion of the initial transaction. + // https://tools.ietf.org/html/rfc3261#section-13.2.1 + return Promise.resolve(undefined); + case session_1.SignalingState.HaveRemoteOffer: + if (!this.session.offer) { + throw new Error("Session offer undefined"); + } + return this.setOfferAndGetAnswer(this.session.offer, options); + case session_1.SignalingState.Closed: + throw new Error("Invalid signaling state " + this.session.signalingState + "."); + default: + throw new Error("Invalid signaling state " + this.session.signalingState + "."); + } + } + }; + InviteServerContext.prototype.handlePrackOfferAnswer = function (request, options) { + if (!this.session) { + throw new Error("Session undefined."); + } + // If the PRACK doesn't have an offer/answer, nothing to be done. + var body = messages_1.getBody(request.message); + if (!body || body.contentDisposition !== "session") { + return Promise.resolve(undefined); + } + // If the UAC receives a reliable provisional response with an offer + // (this would occur if the UAC sent an INVITE without an offer, in + // which case the first reliable provisional response will contain the + // offer), it MUST generate an answer in the PRACK. If the UAC receives + // a reliable provisional response with an answer, it MAY generate an + // additional offer in the PRACK. If the UAS receives a PRACK with an + // offer, it MUST place the answer in the 2xx to the PRACK. + // https://tools.ietf.org/html/rfc3262#section-5 + switch (this.session.signalingState) { + case session_1.SignalingState.Initial: + // State should never be reached as first reliable provisional response must have answer/offer. + throw new Error("Invalid signaling state " + this.session.signalingState + "."); + case session_1.SignalingState.Stable: + // Receved answer. + return this.setAnswer(body, options).then(function () { return undefined; }); + case session_1.SignalingState.HaveLocalOffer: + // State should never be reached as local offer would be answered by this PRACK + throw new Error("Invalid signaling state " + this.session.signalingState + "."); + case session_1.SignalingState.HaveRemoteOffer: + // Receved offer, generate answer. + return this.setOfferAndGetAnswer(body, options); + case session_1.SignalingState.Closed: + throw new Error("Invalid signaling state " + this.session.signalingState + "."); + default: + throw new Error("Invalid signaling state " + this.session.signalingState + "."); + } + }; + /** + * Called when session canceled. + */ + InviteServerContext.prototype.canceled = function () { + this._canceled = true; + return _super.prototype.canceled.call(this); + }; + /** + * Called when session terminated. + * Using it here just for the PRACK timeout. + */ + InviteServerContext.prototype.terminated = function (message, cause) { + this.prackNeverArrived(); + return _super.prototype.terminated.call(this, message, cause); + }; + /** + * A version of `accept` which resolves a session when the 200 Ok response is sent. + * @param options Options bucket. + * @throws {ClosedSessionDescriptionHandlerError} The session description handler closed before method completed. + * @throws {TransactionStateError} The transaction state does not allow for `accept()` to be called. + * Note that the transaction state can change while this call is in progress. + */ + InviteServerContext.prototype._accept = function (options) { + var _this = this; + if (options === void 0) { options = {}; } + // FIXME: Ported - callback for in dialog INFO requests. + // Turns out accept() can be called more than once if we are waiting + // for a PRACK in which case "options" get completely tossed away. + // So this is broken in that case (and potentially other uses of options). + // Tempted to just try to fix it now, but leaving it broken for the moment. + this.onInfo = options.onInfo; + // The UAS MAY send a final response to the initial request before + // having received PRACKs for all unacknowledged reliable provisional + // responses, unless the final response is 2xx and any of the + // unacknowledged reliable provisional responses contained a session + // description. In that case, it MUST NOT send a final response until + // those provisional responses are acknowledged. If the UAS does send a + // final response when reliable responses are still unacknowledged, it + // SHOULD NOT continue to retransmit the unacknowledged reliable + // provisional responses, but it MUST be prepared to process PRACK + // requests for those outstanding responses. A UAS MUST NOT send new + // reliable provisional responses (as opposed to retransmissions of + // unacknowledged ones) after sending a final response to a request. + // https://tools.ietf.org/html/rfc3262#section-3 + if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_PRACK) { + this.status = Enums_1.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK; + return this.waitForArrivalOfPrack() + .then(function () { + _this.status = Enums_1.SessionStatus.STATUS_ANSWERED; + clearTimeout(_this.timers.userNoAnswerTimer); // Ported + }) + .then(function () { return _this.generateResponseOfferAnswer(options); }) + .then(function (body) { return _this.incomingRequest.accept({ statusCode: 200, body: body }); }); + } + // Ported + if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER) { + this.status = Enums_1.SessionStatus.STATUS_ANSWERED; + } + else { + return Promise.reject(new Exceptions_1.Exceptions.InvalidStateError(this.status)); + } + this.status = Enums_1.SessionStatus.STATUS_ANSWERED; + clearTimeout(this.timers.userNoAnswerTimer); // Ported + return this.generateResponseOfferAnswer(options) + .then(function (body) { return _this.incomingRequest.accept({ statusCode: 200, body: body }); }); + }; + /** + * A version of `progress` which resolves when the provisional response is sent. + * @param options Options bucket. + * @throws {ClosedSessionDescriptionHandlerError} The session description handler closed before method completed. + * @throws {TransactionStateError} The transaction state does not allow for `progress()` to be called. + * Note that the transaction state can change while this call is in progress. + */ + InviteServerContext.prototype._progress = function (options) { + if (options === void 0) { options = {}; } + // Ported + var statusCode = options.statusCode || 180; + var reasonPhrase = options.reasonPhrase; + var extraHeaders = (options.extraHeaders || []).slice(); + var body = options.body ? messages_1.fromBodyLegacy(options.body) : undefined; + try { + var progressResponse = this.incomingRequest.progress({ statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }); + this.emit("progress", progressResponse.message, reasonPhrase); // Ported + this.session = progressResponse.session; + return Promise.resolve(progressResponse); + } + catch (error) { + return Promise.reject(error); + } + }; + /** + * A version of `progress` which resolves when the reliable provisional response is sent. + * @param options Options bucket. + * @throws {ClosedSessionDescriptionHandlerError} The session description handler closed before method completed. + * @throws {TransactionStateError} The transaction state does not allow for `progress()` to be called. + * Note that the transaction state can change while this call is in progress. + */ + InviteServerContext.prototype._reliableProgress = function (options) { + var _this = this; + if (options === void 0) { options = {}; } + var statusCode = options.statusCode || 183; + var reasonPhrase = options.reasonPhrase; + var extraHeaders = (options.extraHeaders || []).slice(); + extraHeaders.push("Require: 100rel"); + extraHeaders.push("RSeq: " + Math.floor(Math.random() * 10000)); + // Get an offer/answer and send a reply. + return this.generateResponseOfferAnswer(options) + .then(function (body) { return _this.incomingRequest.progress({ statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }); }) + .then(function (progressResponse) { + _this.emit("progress", progressResponse.message, reasonPhrase); // Ported + _this.session = progressResponse.session; + return progressResponse; + }); + }; + /** + * A version of `progress` which resolves when the reliable provisional response is acknowledged. + * @param options Options bucket. + * @throws {ClosedSessionDescriptionHandlerError} The session description handler closed before method completed. + * @throws {TransactionStateError} The transaction state does not allow for `progress()` to be called. + * Note that the transaction state can change while this call is in progress. + */ + InviteServerContext.prototype._reliableProgressWaitForPrack = function (options) { + var _this = this; + if (options === void 0) { options = {}; } + var statusCode = options.statusCode || 183; + var reasonPhrase = options.reasonPhrase; + var extraHeaders = (options.extraHeaders || []).slice(); + extraHeaders.push("Require: 100rel"); + extraHeaders.push("RSeq: " + this.rseq++); + var body; + // Ported - set status. + this.status = Enums_1.SessionStatus.STATUS_WAITING_FOR_PRACK; + return new Promise(function (resolve, reject) { + var waitingForPrack = true; + return _this.generateResponseOfferAnswer(options) + .then(function (offerAnswer) { + body = offerAnswer; + return _this.incomingRequest.progress({ statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }); + }) + .then(function (progressResponse) { + _this.emit("progress", progressResponse.message, reasonPhrase); // Ported + _this.session = progressResponse.session; + var prackRequest; + var prackResponse; + progressResponse.session.delegate = { + onPrack: function (request) { + prackRequest = request; + clearTimeout(prackWaitTimeoutTimer); + clearTimeout(rel1xxRetransmissionTimer); + if (!waitingForPrack) { + return; + } + waitingForPrack = false; + _this.handlePrackOfferAnswer(prackRequest, options) + .then(function (prackResponseBody) { + try { + prackResponse = prackRequest.accept({ statusCode: 200, body: prackResponseBody }); + // Ported - set status. + if (_this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_PRACK) { + _this.status = Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER; + } + _this.prackArrived(); + resolve({ prackRequest: prackRequest, prackResponse: prackResponse, progressResponse: progressResponse }); + } + catch (error) { + reject(error); + } + }); + } + }; + // https://tools.ietf.org/html/rfc3262#section-3 + var prackWaitTimeout = function () { + if (!waitingForPrack) { + return; + } + waitingForPrack = false; + _this.logger.warn("No PRACK received, rejecting INVITE."); + clearTimeout(rel1xxRetransmissionTimer); + try { + _this.incomingRequest.reject({ statusCode: 504 }); + _this.terminated(undefined, Constants_1.C.causes.NO_PRACK); + reject(new Exceptions_1.Exceptions.TerminatedSessionError()); + } + catch (error) { + reject(error); + } + }; + var prackWaitTimeoutTimer = setTimeout(prackWaitTimeout, Timers_1.Timers.T1 * 64); + // https://tools.ietf.org/html/rfc3262#section-3 + var rel1xxRetransmission = function () { + try { + _this.incomingRequest.progress({ statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }); + } + catch (error) { + waitingForPrack = false; + reject(error); + return; + } + rel1xxRetransmissionTimer = setTimeout(rel1xxRetransmission, timeout *= 2); + }; + var timeout = Timers_1.Timers.T1; + var rel1xxRetransmissionTimer = setTimeout(rel1xxRetransmission, timeout); + }); + }); + }; + /** + * Callback for when ACK for a 2xx response is never received. + * @param session Session the ACK never arrived for + */ + InviteServerContext.prototype.onAckTimeout = function () { + if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK) { + this.logger.log("no ACK received for an extended period of time, terminating the call"); + if (!this.session) { + throw new Error("Session undefined."); + } + this.session.bye(); + this.terminated(undefined, Constants_1.C.causes.NO_ACK); + } + }; + /** + * FIXME: TODO: The current library interface presents async methods without a + * proper async error handling mechanism. Arguably a promise based interface + * would be an improvement over the pattern of returning `this`. The approach has + * been generally along the lines of log a error and terminate. + */ + InviteServerContext.prototype.onContextError = function (error) { + var statusCode = 480; + if (error instanceof Exceptions_1.Exception) { // There might be interest in catching these Exceptions. + if (error instanceof Exceptions_1.Exceptions.SessionDescriptionHandlerError) { + this.logger.error(error.message); + if (error.error) { + this.logger.error(error.error); + } + } + else if (error instanceof Exceptions_1.Exceptions.TerminatedSessionError) { + // PRACK never arrived, so we timed out waiting for it. + this.logger.warn("Incoming session terminated while waiting for PRACK."); + } + else if (error instanceof Exceptions_1.Exceptions.UnsupportedSessionDescriptionContentTypeError) { + statusCode = 415; + } + else if (error instanceof Exceptions_1.Exception) { + this.logger.error(error.message); + } + } + else if (error instanceof Error) { // Other Errors hould go uncaught. + this.logger.error(error.message); + } + else { + // We don't actually know what a session description handler implementation might throw + // our way, so as a last resort, just assume we are getting an "any" and log it. + this.logger.error("An error occurred in the session description handler."); + this.logger.error(error); + } + try { + this.incomingRequest.reject({ statusCode: statusCode }); // "Temporarily Unavailable" + this.failed(this.incomingRequest.message, error.message); + this.terminated(this.incomingRequest.message, error.message); + } + catch (error) { + return; + } + }; + InviteServerContext.prototype.prackArrived = function () { + if (this.waitingForPrackResolve) { + this.waitingForPrackResolve(); + } + this.waitingForPrackPromise = undefined; + this.waitingForPrackResolve = undefined; + this.waitingForPrackReject = undefined; + }; + InviteServerContext.prototype.prackNeverArrived = function () { + if (this.waitingForPrackReject) { + this.waitingForPrackReject(new Exceptions_1.Exceptions.TerminatedSessionError()); + } + this.waitingForPrackPromise = undefined; + this.waitingForPrackResolve = undefined; + this.waitingForPrackReject = undefined; + }; + /** + * @throws {Exceptions.TerminatedSessionError} The session terminated before being accepted (i.e. cancel arrived). + */ + InviteServerContext.prototype.waitForArrivalOfPrack = function () { + var _this = this; + if (this.waitingForPrackPromise) { + throw new Error("Already waiting for PRACK"); + } + this.waitingForPrackPromise = new Promise(function (resolve, reject) { + _this.waitingForPrackResolve = resolve; + _this.waitingForPrackReject = reject; + }); + return this.waitingForPrackPromise; + }; + InviteServerContext.prototype.getOffer = function (options) { + this.hasOffer = true; + var sdh = this.getSessionDescriptionHandler(); + return sdh + .getDescription(options.sessionDescriptionHandlerOptions, options.modifiers) + .then(function (bodyObj) { return messages_1.fromBodyObj(bodyObj); }); + }; + InviteServerContext.prototype.setAnswer = function (answer, options) { + this.hasAnswer = true; + var sdh = this.getSessionDescriptionHandler(); + if (!sdh.hasDescription(answer.contentType)) { + return Promise.reject(new Exceptions_1.Exceptions.UnsupportedSessionDescriptionContentTypeError()); + } + return sdh + .setDescription(answer.content, options.sessionDescriptionHandlerOptions, options.modifiers); + }; + InviteServerContext.prototype.setOfferAndGetAnswer = function (offer, options) { + this.hasOffer = true; + this.hasAnswer = true; + var sdh = this.getSessionDescriptionHandler(); + if (!sdh.hasDescription(offer.contentType)) { + return Promise.reject(new Exceptions_1.Exceptions.UnsupportedSessionDescriptionContentTypeError()); + } + return sdh + .setDescription(offer.content, options.sessionDescriptionHandlerOptions, options.modifiers) + .then(function () { return sdh.getDescription(options.sessionDescriptionHandlerOptions, options.modifiers); }) + .then(function (bodyObj) { return messages_1.fromBodyObj(bodyObj); }); + }; + InviteServerContext.prototype.getSessionDescriptionHandler = function () { + // Create our session description handler if not already done so... + var sdh = this.sessionDescriptionHandler = this.setupSessionDescriptionHandler(); + // FIXME: Ported - this can get emitted multiple times even when only created once... don't we care? + this.emit("SessionDescriptionHandler-created", this.sessionDescriptionHandler); + // Return. + return sdh; + }; + return InviteServerContext; +}(Session)); +exports.InviteServerContext = InviteServerContext; +// tslint:disable-next-line:max-classes-per-file +var InviteClientContext = /** @class */ (function (_super) { + __extends(InviteClientContext, _super); + function InviteClientContext(ua, target, options, modifiers) { + if (options === void 0) { options = {}; } + if (modifiers === void 0) { modifiers = []; } + var _this = this; + if (!ua.configuration.sessionDescriptionHandlerFactory) { + ua.logger.warn("Can't build ISC without SDH Factory"); + throw new Error("ICC Constructor Failed"); + } + options.params = options.params || {}; + var anonymous = options.anonymous || false; + var fromTag = Utils_1.Utils.newTag(); + options.params.fromTag = fromTag; + /* Do not add ;ob in initial forming dialog requests if the registration over + * the current connection got a GRUU URI. + */ + var contact = ua.contact.toString({ + anonymous: anonymous, + outbound: anonymous ? !ua.contact.tempGruu : !ua.contact.pubGruu + }); + var extraHeaders = (options.extraHeaders || []).slice(); + if (anonymous && ua.configuration.uri) { + options.params.from_displayName = "Anonymous"; + options.params.from_uri = "sip:anonymous@anonymous.invalid"; + extraHeaders.push("P-Preferred-Identity: " + ua.configuration.uri.toString()); + extraHeaders.push("Privacy: id"); + } + extraHeaders.push("Contact: " + contact); + // this is UA.C.ALLOWED_METHODS, removed to get around circular dependency + extraHeaders.push("Allow: " + [ + "ACK", + "CANCEL", + "INVITE", + "MESSAGE", + "BYE", + "OPTIONS", + "INFO", + "NOTIFY", + "REFER" + ].toString()); + if (ua.configuration.rel100 === Constants_1.C.supported.REQUIRED) { + extraHeaders.push("Require: 100rel"); + } + if (ua.configuration.replaces === Constants_1.C.supported.REQUIRED) { + extraHeaders.push("Require: replaces"); + } + options.extraHeaders = extraHeaders; + _this = _super.call(this, ua.configuration.sessionDescriptionHandlerFactory) || this; + ClientContext_1.ClientContext.initializer(_this, ua, Constants_1.C.INVITE, target, options); + _this.earlyMediaSessionDescriptionHandlers = new Map(); + _this.type = Enums_1.TypeStrings.InviteClientContext; + _this.passedOptions = options; // Save for later to use with refer + _this.sessionDescriptionHandlerOptions = options.sessionDescriptionHandlerOptions || {}; + _this.modifiers = modifiers; + _this.inviteWithoutSdp = options.inviteWithoutSdp || false; + // Set anonymous property + _this.anonymous = options.anonymous || false; + // Custom data to be sent either in INVITE or in ACK + _this.renderbody = options.renderbody || undefined; + _this.rendertype = options.rendertype || "text/plain"; + // Session parameter initialization + _this.fromTag = fromTag; + _this.contact = contact; + // Check Session Status + if (_this.status !== Enums_1.SessionStatus.STATUS_NULL) { + throw new Exceptions_1.Exceptions.InvalidStateError(_this.status); + } + // OutgoingSession specific parameters + _this.isCanceled = false; + _this.received100 = false; + _this.method = Constants_1.C.INVITE; + _this.logger = ua.getLogger("sip.inviteclientcontext"); + ua.applicants[_this.toString()] = _this; + _this.id = _this.request.callId + _this.fromTag; + _this.onInfo = options.onInfo; + _this.errorListener = _this.onTransportError.bind(_this); + if (ua.transport) { + ua.transport.on("transportError", _this.errorListener); + } + return _this; + } + InviteClientContext.prototype.receiveResponse = function (response) { + throw new Error("Unimplemented."); + }; + // hack for getting around ClientContext interface + InviteClientContext.prototype.send = function () { + this.sendInvite(); + return this; + }; + InviteClientContext.prototype.invite = function () { + var _this = this; + // Save the session into the ua sessions collection. + // Note: placing in constructor breaks call to request.cancel on close... User does not need this anyway + this.ua.sessions[this.id] = this; + // This should allow the function to return so that listeners can be set up for these events + Promise.resolve().then(function () { + // FIXME: There is a race condition where cancel (or terminate) can be called synchronously after invite. + if (_this.isCanceled || _this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { + return; + } + if (_this.inviteWithoutSdp) { + // just send an invite with no sdp... + _this.request.body = _this.renderbody; + _this.status = Enums_1.SessionStatus.STATUS_INVITE_SENT; + _this.send(); + } + else { + // Initialize Media Session + _this.sessionDescriptionHandler = _this.sessionDescriptionHandlerFactory(_this, _this.ua.configuration.sessionDescriptionHandlerFactoryOptions || {}); + _this.emit("SessionDescriptionHandler-created", _this.sessionDescriptionHandler); + _this.sessionDescriptionHandler.getDescription(_this.sessionDescriptionHandlerOptions, _this.modifiers) + .then(function (description) { + // FIXME: There is a race condition where cancel (or terminate) can be called (a)synchronously after invite. + if (_this.isCanceled || _this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { + return; + } + _this.hasOffer = true; + _this.request.body = description; + _this.status = Enums_1.SessionStatus.STATUS_INVITE_SENT; + _this.send(); + }, function (err) { + if (err.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { + _this.logger.log(err.message); + if (err.error) { + _this.logger.log(err.error); + } + } + if (_this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { + return; + } + _this.failed(undefined, Constants_1.C.causes.WEBRTC_ERROR); + _this.terminated(undefined, Constants_1.C.causes.WEBRTC_ERROR); + }); + } + }); + return this; + }; + InviteClientContext.prototype.cancel = function (options) { + if (options === void 0) { options = {}; } + // Check Session Status + if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED || this.status === Enums_1.SessionStatus.STATUS_CONFIRMED) { + throw new Exceptions_1.Exceptions.InvalidStateError(this.status); + } + if (this.isCanceled) { + throw new Exceptions_1.Exceptions.InvalidStateError(Enums_1.SessionStatus.STATUS_CANCELED); + } + this.isCanceled = true; + this.logger.log("Canceling session"); + var cancelReason = Utils_1.Utils.getCancelReason(options.statusCode, options.reasonPhrase); + options.extraHeaders = (options.extraHeaders || []).slice(); + if (this.outgoingInviteRequest) { + this.logger.warn("Canceling session before it was created"); + this.outgoingInviteRequest.cancel(cancelReason, options); + } + return this.canceled(); + }; + InviteClientContext.prototype.terminate = function (options) { + if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { + return this; + } + if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK || this.status === Enums_1.SessionStatus.STATUS_CONFIRMED) { + this.bye(options); + } + else { + this.cancel(options); + } + return this; + }; + /** + * 13.2.1 Creating the Initial INVITE + * + * Since the initial INVITE represents a request outside of a dialog, + * its construction follows the procedures of Section 8.1.1. Additional + * processing is required for the specific case of INVITE. + * + * An Allow header field (Section 20.5) SHOULD be present in the INVITE. + * It indicates what methods can be invoked within a dialog, on the UA + * sending the INVITE, for the duration of the dialog. For example, a + * UA capable of receiving INFO requests within a dialog [34] SHOULD + * include an Allow header field listing the INFO method. + * + * A Supported header field (Section 20.37) SHOULD be present in the + * INVITE. It enumerates all the extensions understood by the UAC. + * + * An Accept (Section 20.1) header field MAY be present in the INVITE. + * It indicates which Content-Types are acceptable to the UA, in both + * the response received by it, and in any subsequent requests sent to + * it within dialogs established by the INVITE. The Accept header field + * is especially useful for indicating support of various session + * description formats. + * + * The UAC MAY add an Expires header field (Section 20.19) to limit the + * validity of the invitation. If the time indicated in the Expires + * header field is reached and no final answer for the INVITE has been + * received, the UAC core SHOULD generate a CANCEL request for the + * INVITE, as per Section 9. + * + * A UAC MAY also find it useful to add, among others, Subject (Section + * 20.36), Organization (Section 20.25) and User-Agent (Section 20.41) + * header fields. They all contain information related to the INVITE. + * + * The UAC MAY choose to add a message body to the INVITE. Section + * 8.1.1.10 deals with how to construct the header fields -- Content- + * Type among others -- needed to describe the message body. + * + * https://tools.ietf.org/html/rfc3261#section-13.2.1 + */ + InviteClientContext.prototype.sendInvite = function () { + // There are special rules for message bodies that contain a session + // description - their corresponding Content-Disposition is "session". + // SIP uses an offer/answer model where one UA sends a session + // description, called the offer, which contains a proposed description + // of the session. The offer indicates the desired communications means + // (audio, video, games), parameters of those means (such as codec + // types) and addresses for receiving media from the answerer. The + // other UA responds with another session description, called the + // answer, which indicates which communications means are accepted, the + // parameters that apply to those means, and addresses for receiving + // media from the offerer. An offer/answer exchange is within the + // context of a dialog, so that if a SIP INVITE results in multiple + // dialogs, each is a separate offer/answer exchange. The offer/answer + // model defines restrictions on when offers and answers can be made + // (for example, you cannot make a new offer while one is in progress). + // This results in restrictions on where the offers and answers can + // appear in SIP messages. In this specification, offers and answers + // can only appear in INVITE requests and responses, and ACK. The usage + // of offers and answers is further restricted. For the initial INVITE + // transaction, the rules are: + // + // o The initial offer MUST be in either an INVITE or, if not there, + // in the first reliable non-failure message from the UAS back to + // the UAC. In this specification, that is the final 2xx + // response. + // + // o If the initial offer is in an INVITE, the answer MUST be in a + // reliable non-failure message from UAS back to UAC which is + // correlated to that INVITE. For this specification, that is + // only the final 2xx response to that INVITE. That same exact + // answer MAY also be placed in any provisional responses sent + // prior to the answer. The UAC MUST treat the first session + // description it receives as the answer, and MUST ignore any + // session descriptions in subsequent responses to the initial + // INVITE. + // + // o If the initial offer is in the first reliable non-failure + // message from the UAS back to UAC, the answer MUST be in the + // acknowledgement for that message (in this specification, ACK + // for a 2xx response). + // + // o After having sent or received an answer to the first offer, the + // UAC MAY generate subsequent offers in requests based on rules + // specified for that method, but only if it has received answers + // to any previous offers, and has not sent any offers to which it + // hasn't gotten an answer. + // + // o Once the UAS has sent or received an answer to the initial + // offer, it MUST NOT generate subsequent offers in any responses + // to the initial INVITE. This means that a UAS based on this + // specification alone can never generate subsequent offers until + // completion of the initial transaction. + // + // https://tools.ietf.org/html/rfc3261#section-13.2.1 + var _this = this; + // 5 The Offer/Answer Model and PRACK + // + // RFC 3261 describes guidelines for the sets of messages in which + // offers and answers [3] can appear. Based on those guidelines, this + // extension provides additional opportunities for offer/answer + // exchanges. + // If the INVITE contained an offer, the UAS MAY generate an answer in a + // reliable provisional response (assuming these are supported by the + // UAC). That results in the establishment of the session before + // completion of the call. Similarly, if a reliable provisional + // response is the first reliable message sent back to the UAC, and the + // INVITE did not contain an offer, one MUST appear in that reliable + // provisional response. + // If the UAC receives a reliable provisional response with an offer + // (this would occur if the UAC sent an INVITE without an offer, in + // which case the first reliable provisional response will contain the + // offer), it MUST generate an answer in the PRACK. If the UAC receives + // a reliable provisional response with an answer, it MAY generate an + // additional offer in the PRACK. If the UAS receives a PRACK with an + // offer, it MUST place the answer in the 2xx to the PRACK. + // Once an answer has been sent or received, the UA SHOULD establish the + // session based on the parameters of the offer and answer, even if the + // original INVITE itself has not been responded to. + // If the UAS had placed a session description in any reliable + // provisional response that is unacknowledged when the INVITE is + // accepted, the UAS MUST delay sending the 2xx until the provisional + // response is acknowledged. Otherwise, the reliability of the 1xx + // cannot be guaranteed, and reliability is needed for proper operation + // of the offer/answer exchange. + // All user agents that support this extension MUST support all + // offer/answer exchanges that are possible based on the rules in + // Section 13.2 of RFC 3261, based on the existence of INVITE and PRACK + // as requests, and 2xx and reliable 1xx as non-failure reliable + // responses. + // + // https://tools.ietf.org/html/rfc3262#section-5 + //// + // The Offer/Answer Model Implementation + // + // The offer/answer model is straight forward, but one MUST READ the specifications... + // + // 13.2.1 Creating the Initial INVITE (paragraph 8 in particular) + // https://tools.ietf.org/html/rfc3261#section-13.2.1 + // + // 5 The Offer/Answer Model and PRACK + // https://tools.ietf.org/html/rfc3262#section-5 + // + // Session Initiation Protocol (SIP) Usage of the Offer/Answer Model + // https://tools.ietf.org/html/rfc6337 + // + // *** IMPORTANT IMPLEMENTATION CHOICES *** + // + // TLDR... + // + // 1) Only one offer/answer exchange permitted during initial INVITE. + // 2) No "early media" if the initial offer is in an INVITE. + // + // + // 1) Initial Offer/Answer Restriction. + // + // Our implementation replaces the following bullet point... + // + // o After having sent or received an answer to the first offer, the + // UAC MAY generate subsequent offers in requests based on rules + // specified for that method, but only if it has received answers + // to any previous offers, and has not sent any offers to which it + // hasn't gotten an answer. + // https://tools.ietf.org/html/rfc3261#section-13.2.1 + // + // ...with... + // + // o After having sent or received an answer to the first offer, the + // UAC MUST NOT generate subsequent offers in requests based on rules + // specified for that method. + // + // ...which in combination with this bullet point... + // + // o Once the UAS has sent or received an answer to the initial + // offer, it MUST NOT generate subsequent offers in any responses + // to the initial INVITE. This means that a UAS based on this + // specification alone can never generate subsequent offers until + // completion of the initial transaction. + // https://tools.ietf.org/html/rfc3261#section-13.2.1 + // + // ...ensures that EXACTLY ONE offer/answer exchange will occur + // during an initial out of dialog INVITE request made by our UAC. + // + // + // 2) Early Media Restriction. + // + // While our implementation adheres to the following bullet point... + // + // o If the initial offer is in an INVITE, the answer MUST be in a + // reliable non-failure message from UAS back to UAC which is + // correlated to that INVITE. For this specification, that is + // only the final 2xx response to that INVITE. That same exact + // answer MAY also be placed in any provisional responses sent + // prior to the answer. The UAC MUST treat the first session + // description it receives as the answer, and MUST ignore any + // session descriptions in subsequent responses to the initial + // INVITE. + // https://tools.ietf.org/html/rfc3261#section-13.2.1 + // + // We have made the following implementation decision with regard to early media... + // + // o If the initial offer is in the INVITE, the answer from the + // UAS back to the UAC will establish a media session only + // only after the final 2xx response to that INVITE is received. + // + // The reason for this decision is rooted in a restriction currently + // inherent in WebRTC. Specifically, while a SIP INVITE request with an + // initial offer may fork resulting in more than one provisional answer, + // there is currently no easy/good way to to "fork" an offer generated + // by a peer connection. In particular, a WebRTC offer currently may only + // be matched with one answer and we have no good way to know which + // "provisional answer" is going to be the "final answer". So we have + // decided to punt and not create any "early media" sessions in this case. + // + // The upshot is that if you want "early media", you must not put the + // initial offer in the INVITE. Instead, force the UAS to provide the + // initial offer by sending an INVITE without an offer. In the WebRTC + // case this allows us to create a unique peer connection with a unique + // answer for every provisional offer with "early media" on all of them. + //// + //// + // ROADMAP: The Offer/Answer Model Implementation + // + // The "no early media if offer in INVITE" implementation is not a + // welcome one. The masses want it. The want it and they want it + // to work for WebRTC (so they want to have their cake and eat too). + // + // So while we currently cannot make the offer in INVITE+forking+webrtc + // case work, we decided to do the following... + // + // 1) modify SDH Factory to provide an initial offer without giving us the SDH, and then... + // 2) stick that offer in the initial INVITE, and when 183 with initial answer is received... + // 3) ask SDH Factory if it supports "earlyRemoteAnswer" + // a) if true, ask SDH Factory to createSDH(localOffer).then((sdh) => sdh.setDescription(remoteAnswer) + // b) if false, defer getting a SDH until 2xx response is received + // + // Our supplied WebRTC SDH will default to behavior 3b which works in forking environment (without) + // early media if initial offer is in the INVITE). We will, however, provide an "inviteWillNotFork" + // option which if set to "true" will have our supplied WebRTC SDH behave in the 3a manner. + // That will result in + // - early media working with initial offer in the INVITE, and... + // - if the INVITE forks, the session terminating with an ERROR that reads like + // "You set 'inviteWillNotFork' to true but the INVITE forked. You can't eat your cake, and have it too." + // - furthermore, we accept that users will report that error to us as "bug" regardless + // + // So, SDH Factory is going to end up with a new interface along the lines of... + // + // interface SessionDescriptionHandlerFactory { + // makeLocalOffer(): Promise; + // makeSessionDescriptionHandler( + // initialOffer: ContentTypeAndBody, offerType: "local" | "remote" + // ): Promise; + // supportsEarlyRemoteAnswer: boolean; + // supportsContentType(contentType: string): boolean; + // getDescription(description: ContentTypeAndBody): Promise + // setDescription(description: ContentTypeAndBody): Promise + // } + // + // We should be able to get rid of all the hasOffer/hasAnswer tracking code and otherwise code + // it up to the same interaction with the SDH Factory and SDH regardless of signaling scenario. + //// + // Send the INVITE request. + this.outgoingInviteRequest = this.ua.userAgentCore.invite(this.request, { + onAccept: function (inviteResponse) { return _this.onAccept(inviteResponse); }, + onProgress: function (inviteResponse) { return _this.onProgress(inviteResponse); }, + onRedirect: function (inviteResponse) { return _this.onRedirect(inviteResponse); }, + onReject: function (inviteResponse) { return _this.onReject(inviteResponse); }, + onTrying: function (inviteResponse) { return _this.onTrying(inviteResponse); } + }); + }; + InviteClientContext.prototype.ackAndBye = function (inviteResponse, session, statusCode, reasonPhrase) { + if (!this.ua.userAgentCore) { + throw new Error("Method requires user agent core."); + } + var extraHeaders = []; + if (statusCode) { + extraHeaders.push("Reason: " + Utils_1.Utils.getReasonHeaderValue(statusCode, reasonPhrase)); + } + var outgoingAckRequest = inviteResponse.ack(); + this.emit("ack", outgoingAckRequest.message); + var outgoingByeRequest = session.bye(undefined, { extraHeaders: extraHeaders }); + this.emit("bye", outgoingByeRequest.message); + }; + InviteClientContext.prototype.disposeEarlyMedia = function () { + if (!this.earlyMediaSessionDescriptionHandlers) { + throw new Error("Early media session description handlers undefined."); + } + this.earlyMediaSessionDescriptionHandlers.forEach(function (sessionDescriptionHandler) { + sessionDescriptionHandler.close(); + }); + }; + /** + * Handle final response to initial INVITE. + * @param inviteResponse 2xx response. + */ + InviteClientContext.prototype.onAccept = function (inviteResponse) { + var _this = this; + if (!this.earlyMediaSessionDescriptionHandlers) { + throw new Error("Early media session description handlers undefined."); + } + var response = inviteResponse.message; + var session = inviteResponse.session; + // Our transaction layer is "non-standard" in that it will only + // pass us a 2xx response once per branch, so there is no need to + // worry about dealing with 2xx retransmissions. However, we can + // and do still get 2xx responses for multiple branches (when an + // INVITE is forked) which may create multiple confirmed dialogs. + // Herein we are acking and sending a bye to any confirmed dialogs + // which arrive beyond the first one. This is the desired behavior + // for most applications (but certainly not all). + // If we already received a confirmed dialog, ack & bye this session. + if (this.session) { + this.ackAndBye(inviteResponse, session); + return; + } + // If the user requested cancellation, ack & bye this session. + if (this.isCanceled) { + this.ackAndBye(inviteResponse, session); + this.emit("bye", this.request); // FIXME: Ported this odd second "bye" emit + return; + } + // Ported behavior. + if (response.hasHeader("P-Asserted-Identity")) { + this.assertedIdentity = Grammar_1.Grammar.nameAddrHeaderParse(response.getHeader("P-Asserted-Identity")); + } + // We have a confirmed dialog. + this.session = session; + this.session.delegate = { + onAck: function (ackRequest) { return _this.onAck(ackRequest); }, + onBye: function (byeRequest) { return _this.receiveRequest(byeRequest); }, + onInfo: function (infoRequest) { return _this.receiveRequest(infoRequest); }, + onInvite: function (inviteRequest) { return _this.receiveRequest(inviteRequest); }, + onNotify: function (notifyRequest) { return _this.receiveRequest(notifyRequest); }, + onPrack: function (prackRequest) { return _this.receiveRequest(prackRequest); }, + onRefer: function (referRequest) { return _this.receiveRequest(referRequest); } + }; + switch (session.signalingState) { + case session_1.SignalingState.Initial: + // INVITE without Offer, so MUST have Offer at this point, so invalid state. + this.ackAndBye(inviteResponse, session, 400, "Missing session description"); + this.failed(response, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); + break; + case session_1.SignalingState.HaveLocalOffer: + // INVITE with Offer, so MUST have Answer at this point, so invalid state. + this.ackAndBye(inviteResponse, session, 400, "Missing session description"); + this.failed(response, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); + break; + case session_1.SignalingState.HaveRemoteOffer: + // INVITE without Offer, received offer in 2xx, so MUST send Answer in ACK. + var sdh_1 = this.sessionDescriptionHandlerFactory(this, this.ua.configuration.sessionDescriptionHandlerFactoryOptions || {}); + this.sessionDescriptionHandler = sdh_1; + this.emit("SessionDescriptionHandler-created", this.sessionDescriptionHandler); + if (!sdh_1.hasDescription(response.getHeader("Content-Type") || "")) { + this.ackAndBye(inviteResponse, session, 400, "Missing session description"); + this.failed(response, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); + break; + } + this.hasOffer = true; + sdh_1 + .setDescription(response.body, this.sessionDescriptionHandlerOptions, this.modifiers) + .then(function () { return sdh_1.getDescription(_this.sessionDescriptionHandlerOptions, _this.modifiers); }) + .then(function (description) { + if (_this.isCanceled || _this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { + return; + } + _this.status = Enums_1.SessionStatus.STATUS_CONFIRMED; + _this.hasAnswer = true; + var body = { + contentDisposition: "session", contentType: description.contentType, content: description.body + }; + var ackRequest = inviteResponse.ack({ body: body }); + _this.emit("ack", ackRequest.message); + _this.accepted(response); + }) + .catch(function (e) { + if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { + _this.logger.warn("invalid description"); + _this.logger.warn(e.toString()); + // TODO: This message is inconsistent + _this.ackAndBye(inviteResponse, session, 488, "Invalid session description"); + _this.failed(response, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); + } + else { + throw e; + } + }); + break; + case session_1.SignalingState.Stable: + // This session has completed an initial offer/answer exchange... + var options_1; + if (this.renderbody && this.rendertype) { + options_1 = { body: { contentDisposition: "render", contentType: this.rendertype, content: this.renderbody } }; + } + // If INVITE with Offer and we have been waiting till now to apply the answer. + if (this.hasOffer && !this.hasAnswer) { + if (!this.sessionDescriptionHandler) { + throw new Error("Session description handler undefined."); + } + var answer = session.answer; + if (!answer) { + throw new Error("Answer is undefined."); + } + this.sessionDescriptionHandler + .setDescription(answer.content, this.sessionDescriptionHandlerOptions, this.modifiers) + .then(function () { + _this.hasAnswer = true; + _this.status = Enums_1.SessionStatus.STATUS_CONFIRMED; + var ackRequest = inviteResponse.ack(options_1); + _this.emit("ack", ackRequest.message); + _this.accepted(response); + }) + .catch(function (error) { + _this.logger.error(error); + _this.ackAndBye(inviteResponse, session, 488, "Not Acceptable Here"); + _this.failed(response, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); + // FIME: DON'T EAT UNHANDLED ERRORS! + }); + } + else { + // Otherwise INVITE with or without Offer and we have already completed the initial exchange. + this.sessionDescriptionHandler = this.earlyMediaSessionDescriptionHandlers.get(session.id); + if (!this.sessionDescriptionHandler) { + throw new Error("Session description handler undefined."); + } + this.earlyMediaSessionDescriptionHandlers.delete(session.id); + this.hasOffer = true; + this.hasAnswer = true; + this.status = Enums_1.SessionStatus.STATUS_CONFIRMED; + var ackRequest = inviteResponse.ack(); + this.emit("ack", ackRequest.message); + this.accepted(response); + } + break; + case session_1.SignalingState.Closed: + // Dialog has terminated. + break; + default: + throw new Error("Unknown session signaling state."); + } + this.disposeEarlyMedia(); + }; + /** + * Handle provisional response to initial INVITE. + * @param inviteResponse 1xx response. + */ + InviteClientContext.prototype.onProgress = function (inviteResponse) { + var _this = this; + // Ported - User requested cancellation. + if (this.isCanceled) { + return; + } + if (!this.outgoingInviteRequest) { + throw new Error("Outgoing INVITE request undefined."); + } + if (!this.earlyMediaSessionDescriptionHandlers) { + throw new Error("Early media session description handlers undefined."); + } + var response = inviteResponse.message; + var session = inviteResponse.session; + // Ported - Set status. + this.status = Enums_1.SessionStatus.STATUS_1XX_RECEIVED; + // Ported - Set assertedIdentity. + if (response.hasHeader("P-Asserted-Identity")) { + this.assertedIdentity = Grammar_1.Grammar.nameAddrHeaderParse(response.getHeader("P-Asserted-Identity")); + } + // The provisional response MUST establish a dialog if one is not yet created. + // https://tools.ietf.org/html/rfc3262#section-4 + if (!session) { + // A response with a to tag MUST create a session (should never get here). + throw new Error("Session undefined."); + } + // If a provisional response is received for an initial request, and + // that response contains a Require header field containing the option + // tag 100rel, the response is to be sent reliably. If the response is + // a 100 (Trying) (as opposed to 101 to 199), this option tag MUST be + // ignored, and the procedures below MUST NOT be used. + // https://tools.ietf.org/html/rfc3262#section-4 + var requireHeader = response.getHeader("require"); + var rseqHeader = response.getHeader("rseq"); + var rseq = requireHeader && requireHeader.includes("100rel") && rseqHeader ? Number(rseqHeader) : undefined; + var responseReliable = !!rseq; + var extraHeaders = []; + if (responseReliable) { + extraHeaders.push("RAck: " + response.getHeader("rseq") + " " + response.getHeader("cseq")); + } + // INVITE without Offer and session still has no offer (and no answer). + if (session.signalingState === session_1.SignalingState.Initial) { + // Similarly, if a reliable provisional + // response is the first reliable message sent back to the UAC, and the + // INVITE did not contain an offer, one MUST appear in that reliable + // provisional response. + // https://tools.ietf.org/html/rfc3262#section-5 + if (responseReliable) { + this.logger.warn("First reliable provisional response received MUST contain an offer when INVITE does not contain an offer."); + // FIXME: Known popular UA's currently end up here... + inviteResponse.prack({ extraHeaders: extraHeaders }); + } + this.emit("progress", response); + return; + } + // INVITE with Offer and session only has that initial local offer. + if (session.signalingState === session_1.SignalingState.HaveLocalOffer) { + if (responseReliable) { + inviteResponse.prack({ extraHeaders: extraHeaders }); + } + this.emit("progress", response); + return; + } + // INVITE without Offer and received initial offer in provisional response + if (session.signalingState === session_1.SignalingState.HaveRemoteOffer) { + // The initial offer MUST be in either an INVITE or, if not there, + // in the first reliable non-failure message from the UAS back to + // the UAC. + // https://tools.ietf.org/html/rfc3261#section-13.2.1 + // According to Section 13.2.1 of [RFC3261], 'The first reliable + // non-failure message' must have an offer if there is no offer in the + // INVITE request. This means that the User Agent (UA) that receives + // the INVITE request without an offer must include an offer in the + // first reliable response with 100rel extension. If no reliable + // provisional response has been sent, the User Agent Server (UAS) must + // include an offer when sending 2xx response. + // https://tools.ietf.org/html/rfc6337#section-2.2 + if (!responseReliable) { + this.logger.warn("Non-reliable provisional response MUST NOT contain an initial offer, discarding response."); + return; + } + // If the initial offer is in the first reliable non-failure + // message from the UAS back to UAC, the answer MUST be in the + // acknowledgement for that message + var sdh_2 = this.sessionDescriptionHandlerFactory(this, this.ua.configuration.sessionDescriptionHandlerFactoryOptions || {}); + this.emit("SessionDescriptionHandler-created", sdh_2); + this.earlyMediaSessionDescriptionHandlers.set(session.id, sdh_2); + sdh_2 + .setDescription(response.body, this.sessionDescriptionHandlerOptions, this.modifiers) + .then(function () { return sdh_2.getDescription(_this.sessionDescriptionHandlerOptions, _this.modifiers); }) + .then(function (description) { + var body = { + contentDisposition: "session", contentType: description.contentType, content: description.body + }; + inviteResponse.prack({ extraHeaders: extraHeaders, body: body }); + _this.status = Enums_1.SessionStatus.STATUS_EARLY_MEDIA; + _this.emit("progress", response); + }) + .catch(function (error) { + if (_this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { + return; + } + _this.failed(undefined, Constants_1.C.causes.WEBRTC_ERROR); + _this.terminated(undefined, Constants_1.C.causes.WEBRTC_ERROR); + }); + return; + } + // This session has completed an initial offer/answer exchange, so... + // - INVITE with SDP and this provisional response MAY be reliable + // - INVITE without SDP and this provisional response MAY be reliable + if (session.signalingState === session_1.SignalingState.Stable) { + if (responseReliable) { + inviteResponse.prack({ extraHeaders: extraHeaders }); + } + // Note: As documented, no early media if offer was in INVITE, so nothing to be done. + // FIXME: TODO: Add a flag/hack to allow early media in this case. There are people + // in non-forking environments (think straight to FreeSWITCH) who want + // early media on a 183. Not sure how to actually make it work, basically + // something like... + if (false) {} + this.emit("progress", response); + return; + } + }; + /** + * Handle final response to initial INVITE. + * @param inviteResponse 3xx response. + */ + InviteClientContext.prototype.onRedirect = function (inviteResponse) { + this.disposeEarlyMedia(); + var response = inviteResponse.message; + var statusCode = response.statusCode; + var cause = Utils_1.Utils.sipErrorCause(statusCode || 0); + this.rejected(response, cause); + this.failed(response, cause); + this.terminated(response, cause); + }; + /** + * Handle final response to initial INVITE. + * @param inviteResponse 4xx, 5xx, or 6xx response. + */ + InviteClientContext.prototype.onReject = function (inviteResponse) { + this.disposeEarlyMedia(); + var response = inviteResponse.message; + var statusCode = response.statusCode; + var cause = Utils_1.Utils.sipErrorCause(statusCode || 0); + this.rejected(response, cause); + this.failed(response, cause); + this.terminated(response, cause); + }; + /** + * Handle final response to initial INVITE. + * @param inviteResponse 100 response. + */ + InviteClientContext.prototype.onTrying = function (inviteResponse) { + this.received100 = true; + this.emit("progress", inviteResponse.message); + }; + return InviteClientContext; +}(Session)); +exports.InviteClientContext = InviteClientContext; + + +/***/ }), +/* 68 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +function __export(m) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; +} +Object.defineProperty(exports, "__esModule", { value: true }); +__export(__webpack_require__(69)); + + +/***/ }), +/* 69 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +/** + * Session state. + * https://tools.ietf.org/html/rfc3261#section-13 + */ +var SessionState; +(function (SessionState) { + SessionState["Initial"] = "Initial"; + SessionState["Early"] = "Early"; + SessionState["AckWait"] = "AckWait"; + SessionState["Confirmed"] = "Confirmed"; + SessionState["Terminated"] = "Terminated"; +})(SessionState = exports.SessionState || (exports.SessionState = {})); +/** + * Offer/Answer State + * + * Offer Answer RFC Ini Est Early + * ------------------------------------------------------------------- + * 1. INVITE Req. 2xx INVITE Resp. RFC 3261 Y Y N + * 2. 2xx INVITE Resp. ACK Req. RFC 3261 Y Y N + * 3. INVITE Req. 1xx-rel INVITE Resp. RFC 3262 Y Y N + * 4. 1xx-rel INVITE Resp. PRACK Req. RFC 3262 Y Y N + * 5. PRACK Req. 200 PRACK Resp. RFC 3262 N Y Y + * 6. UPDATE Req. 2xx UPDATE Resp. RFC 3311 N Y Y + * + * Table 1: Summary of SIP Usage of the Offer/Answer Model + * https://tools.ietf.org/html/rfc6337#section-2.2 + */ +var SignalingState; +(function (SignalingState) { + SignalingState["Initial"] = "Initial"; + SignalingState["HaveLocalOffer"] = "HaveLocalOffer"; + SignalingState["HaveRemoteOffer"] = "HaveRemoteOffer"; + SignalingState["Stable"] = "Stable"; + SignalingState["Closed"] = "Closed"; +})(SignalingState = exports.SignalingState || (exports.SignalingState = {})); + + +/***/ }), +/* 70 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var events_1 = __webpack_require__(2); +var Constants_1 = __webpack_require__(3); +var messages_1 = __webpack_require__(63); +var Enums_1 = __webpack_require__(5); +var Exceptions_1 = __webpack_require__(47); +var Utils_1 = __webpack_require__(11); +/** + * @class DTMF + * @param {SIP.Session} session + */ +var DTMF = /** @class */ (function (_super) { + __extends(DTMF, _super); + function DTMF(session, tone, options) { + if (options === void 0) { options = {}; } + var _this = _super.call(this) || this; + _this.C = { + MIN_DURATION: 70, + MAX_DURATION: 6000, + DEFAULT_DURATION: 100, + MIN_INTER_TONE_GAP: 50, + DEFAULT_INTER_TONE_GAP: 500 + }; + _this.type = Enums_1.TypeStrings.DTMF; + if (tone === undefined) { + throw new TypeError("Not enough arguments"); + } + _this.logger = session.ua.getLogger("sip.invitecontext.dtmf", session.id); + _this.owner = session; + // Check tone type + if (typeof tone === "string") { + tone = tone.toUpperCase(); + } + else if (typeof tone === "number") { + tone = tone.toString(); + } + else { + throw new TypeError("Invalid tone: " + tone); + } + // Check tone value + if (!tone.match(/^[0-9A-D#*]$/)) { + throw new TypeError("Invalid tone: " + tone); + } + else { + _this.tone = tone; + } + var duration = options.duration; + var interToneGap = options.interToneGap; + // Check duration + if (duration && !Utils_1.Utils.isDecimal(duration)) { + throw new TypeError("Invalid tone duration: " + duration); + } + else if (!duration) { + duration = _this.C.DEFAULT_DURATION; + } + else if (duration < _this.C.MIN_DURATION) { + _this.logger.warn("'duration' value is lower than the minimum allowed, setting it to " + + _this.C.MIN_DURATION + " milliseconds"); + duration = _this.C.MIN_DURATION; + } + else if (duration > _this.C.MAX_DURATION) { + _this.logger.warn("'duration' value is greater than the maximum allowed, setting it to " + + _this.C.MAX_DURATION + " milliseconds"); + duration = _this.C.MAX_DURATION; + } + else { + duration = Math.abs(duration); + } + _this.duration = duration; + // Check interToneGap + if (interToneGap && !Utils_1.Utils.isDecimal(interToneGap)) { + throw new TypeError("Invalid interToneGap: " + interToneGap); + } + else if (!interToneGap) { + interToneGap = _this.C.DEFAULT_INTER_TONE_GAP; + } + else if (interToneGap < _this.C.MIN_INTER_TONE_GAP) { + _this.logger.warn("'interToneGap' value is lower than the minimum allowed, setting it to " + + _this.C.MIN_INTER_TONE_GAP + " milliseconds"); + interToneGap = _this.C.MIN_INTER_TONE_GAP; + } + else { + interToneGap = Math.abs(interToneGap); + } + _this.interToneGap = interToneGap; + return _this; + } + DTMF.prototype.send = function (options) { + if (options === void 0) { options = {}; } + // Check RTCSession Status + if (this.owner.status !== Enums_1.SessionStatus.STATUS_CONFIRMED && + this.owner.status !== Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK) { + throw new Exceptions_1.Exceptions.InvalidStateError(this.owner.status); + } + // Get DTMF options + var extraHeaders = options.extraHeaders ? options.extraHeaders.slice() : []; + var body = { + contentType: "application/dtmf-relay", + body: "Signal= " + this.tone + "\r\nDuration= " + this.duration + }; + if (this.owner.session) { + var request = this.owner.session.info(undefined, { + extraHeaders: extraHeaders, + body: messages_1.fromBodyObj(body) + }); + this.owner.emit("dtmf", request.message, this); + return; + } + }; + DTMF.prototype.init_incoming = function (request) { + request.accept(); + if (!this.tone || !this.duration) { + this.logger.warn("invalid INFO DTMF received, discarded"); + } + else { + this.owner.emit("dtmf", request.message, this); + } + }; + DTMF.prototype.receiveResponse = function (response) { + var statusCode = response && response.statusCode ? response.statusCode : 0; + switch (true) { + case /^1[0-9]{2}$/.test(statusCode.toString()): + // Ignore provisional responses. + break; + case /^2[0-9]{2}$/.test(statusCode.toString()): + this.emit("succeeded", { + originator: "remote", + response: response + }); + break; + default: + var cause = Utils_1.Utils.sipErrorCause(statusCode); + this.emit("failed", response, cause); + break; + } + }; + DTMF.prototype.onRequestTimeout = function () { + this.emit("failed", undefined, Constants_1.C.causes.REQUEST_TIMEOUT); + this.owner.onRequestTimeout(); + }; + DTMF.prototype.onTransportError = function () { + this.emit("failed", undefined, Constants_1.C.causes.CONNECTION_ERROR); + this.owner.onTransportError(); + }; + DTMF.prototype.onDialogError = function (response) { + this.emit("failed", response, Constants_1.C.causes.DIALOG_ERROR); + this.owner.onDialogError(response); + }; + return DTMF; +}(events_1.EventEmitter)); +exports.DTMF = DTMF; + + +/***/ }), +/* 71 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var events_1 = __webpack_require__(2); +var Constants_1 = __webpack_require__(3); +var messages_1 = __webpack_require__(63); +var subscription_1 = __webpack_require__(72); +var allowed_methods_1 = __webpack_require__(74); +var Enums_1 = __webpack_require__(5); +var Utils_1 = __webpack_require__(11); +/** + * While this class is named `Subscription`, it is closer to + * an implementation of a "subscriber" as defined in RFC 6665 + * "SIP-Specific Event Notifications". + * https://tools.ietf.org/html/rfc6665 + * @class Class creating a SIP Subscriber. + */ +var Subscription = /** @class */ (function (_super) { + __extends(Subscription, _super); + /** + * Constructor. + * @param ua User agent. + * @param target Subscription target. + * @param event Subscription event. + * @param options Options bucket. + */ + function Subscription(ua, target, event, options) { + if (options === void 0) { options = {}; } + var _this = _super.call(this) || this; + _this.data = {}; + _this.method = Constants_1.C.SUBSCRIBE; + _this.body = undefined; + // ClientContext interface + _this.type = Enums_1.TypeStrings.Subscription; + _this.ua = ua; + _this.logger = ua.getLogger("sip.subscription"); + if (options.body) { + _this.body = { + body: options.body, + contentType: options.contentType ? options.contentType : "application/sdp" + }; + } + // Target URI + var uri = ua.normalizeTarget(target); + if (!uri) { + throw new TypeError("Invalid target: " + target); + } + _this.uri = uri; + // Subscription event + _this.event = event; + // Subscription expires + if (options.expires === undefined) { + _this.expires = 3600; + } + else if (typeof options.expires !== "number") { // pre-typescript type guard + ua.logger.warn("Option \"expires\" must be a number. Using default of 3600."); + _this.expires = 3600; + } + else { + _this.expires = options.expires; + } + // Subscription extra headers + _this.extraHeaders = (options.extraHeaders || []).slice(); + // Subscription context. + _this.context = _this.initContext(); + _this.disposed = false; + // ClientContext interface + _this.request = _this.context.message; + if (!_this.request.from) { + throw new Error("From undefined."); + } + if (!_this.request.to) { + throw new Error("From undefined."); + } + _this.localIdentity = _this.request.from; + _this.remoteIdentity = _this.request.to; + return _this; + } + /** + * Destructor. + */ + Subscription.prototype.dispose = function () { + if (this.disposed) { + return; + } + if (this.retryAfterTimer) { + clearTimeout(this.retryAfterTimer); + this.retryAfterTimer = undefined; + } + this.context.dispose(); + this.disposed = true; + }; + Subscription.prototype.on = function (name, callback) { + return _super.prototype.on.call(this, name, callback); + }; + Subscription.prototype.emit = function (event) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + return _super.prototype.emit.apply(this, [event].concat(args)); + }; + /** + * Gracefully terminate. + */ + Subscription.prototype.close = function () { + if (this.disposed) { + return; + } + this.dispose(); + switch (this.context.state) { + case subscription_1.SubscriptionState.Initial: + this.onTerminated(); + break; + case subscription_1.SubscriptionState.NotifyWait: + this.onTerminated(); + break; + case subscription_1.SubscriptionState.Pending: + this.unsubscribe(); + break; + case subscription_1.SubscriptionState.Active: + this.unsubscribe(); + break; + case subscription_1.SubscriptionState.Terminated: + this.onTerminated(); + break; + default: + break; + } + }; + /** + * Send a re-SUBSCRIBE request if there is an "active" subscription. + */ + Subscription.prototype.refresh = function () { + var _this = this; + switch (this.context.state) { + case subscription_1.SubscriptionState.Initial: + break; + case subscription_1.SubscriptionState.NotifyWait: + break; + case subscription_1.SubscriptionState.Pending: + break; + case subscription_1.SubscriptionState.Active: + if (this.subscription) { + var request = this.subscription.refresh(); + request.delegate = { + onAccept: (function (response) { return _this.onAccepted(response); }), + onRedirect: (function (response) { return _this.onFailed(response); }), + onReject: (function (response) { return _this.onFailed(response); }), + }; + } + break; + case subscription_1.SubscriptionState.Terminated: + break; + default: + break; + } + }; + /** + * Send an initial SUBSCRIBE request if no subscription. + * Send a re-SUBSCRIBE request if there is an "active" subscription. + */ + Subscription.prototype.subscribe = function () { + var _this = this; + switch (this.context.state) { + case subscription_1.SubscriptionState.Initial: + this.context.subscribe().then(function (result) { + if (result.success) { + if (result.success.subscription) { + _this.subscription = result.success.subscription; + _this.subscription.delegate = { + onNotify: function (request) { return _this.onNotify(request); }, + onRefresh: function (request) { return _this.onRefresh(request); }, + onTerminated: function () { return _this.close(); } + }; + } + _this.onNotify(result.success.request); + } + else if (result.failure) { + _this.onFailed(result.failure.response); + } + }); + break; + case subscription_1.SubscriptionState.NotifyWait: + break; + case subscription_1.SubscriptionState.Pending: + break; + case subscription_1.SubscriptionState.Active: + this.refresh(); + break; + case subscription_1.SubscriptionState.Terminated: + break; + default: + break; + } + return this; + }; + /** + * Send a re-SUBSCRIBE request if there is a "pending" or "active" subscription. + */ + Subscription.prototype.unsubscribe = function () { + this.dispose(); + switch (this.context.state) { + case subscription_1.SubscriptionState.Initial: + break; + case subscription_1.SubscriptionState.NotifyWait: + break; + case subscription_1.SubscriptionState.Pending: + if (this.subscription) { + this.subscription.unsubscribe(); + // responses intentionally ignored + } + break; + case subscription_1.SubscriptionState.Active: + if (this.subscription) { + this.subscription.unsubscribe(); + // responses intentionally ignored + } + break; + case subscription_1.SubscriptionState.Terminated: + break; + default: + break; + } + this.onTerminated(); + }; + Subscription.prototype.onAccepted = function (response) { + var statusCode = response.message.statusCode ? response.message.statusCode : 0; + var cause = Utils_1.Utils.getReasonPhrase(statusCode); + this.emit("accepted", response.message, cause); + }; + Subscription.prototype.onFailed = function (response) { + this.close(); + if (response) { + var statusCode = response.message.statusCode ? response.message.statusCode : 0; + var cause = Utils_1.Utils.getReasonPhrase(statusCode); + this.emit("failed", response.message, cause); + this.emit("rejected", response.message, cause); + } + }; + Subscription.prototype.onNotify = function (request) { + var _this = this; + request.accept(); // Send 200 response. + this.emit("notify", { request: request.message }); + // If we've set state to done, no further processing should take place + // and we are only interested in cleaning up after the appropriate NOTIFY. + if (this.disposed) { + return; + } + // If the "Subscription-State" value is "terminated", the subscriber + // MUST consider the subscription terminated. The "expires" parameter + // has no semantics for "terminated" -- notifiers SHOULD NOT include an + // "expires" parameter on a "Subscription-State" header field with a + // value of "terminated", and subscribers MUST ignore any such + // parameter, if present. If a reason code is present, the client + // should behave as described below. If no reason code or an unknown + // reason code is present, the client MAY attempt to re-subscribe at any + // time (unless a "retry-after" parameter is present, in which case the + // client SHOULD NOT attempt re-subscription until after the number of + // seconds specified by the "retry-after" parameter). The reason codes + // defined by this document are: + // https://tools.ietf.org/html/rfc6665#section-4.1.3 + var subscriptionState = request.message.parseHeader("Subscription-State"); + if (subscriptionState && subscriptionState.state) { + switch (subscriptionState.state) { + case "terminated": + if (subscriptionState.reason) { + this.logger.log("Terminated subscription with reason " + subscriptionState.reason); + switch (subscriptionState.reason) { + case "deactivated": + case "timeout": + this.initContext(); + this.subscribe(); + return; + case "probation": + case "giveup": + this.initContext(); + if (subscriptionState.params && subscriptionState.params["retry-after"]) { + this.retryAfterTimer = setTimeout(function () { return _this.subscribe(); }, subscriptionState.params["retry-after"]); + } + else { + this.subscribe(); + } + return; + case "rejected": + case "noresource": + case "invariant": + break; + } + } + this.close(); + break; + default: + break; + } + } + }; + Subscription.prototype.onRefresh = function (request) { + var _this = this; + request.delegate = { + onAccept: function (response) { return _this.onAccepted(response); } + }; + }; + Subscription.prototype.onTerminated = function () { + this.emit("terminated"); + }; + Subscription.prototype.initContext = function () { + var _this = this; + var options = { + extraHeaders: this.extraHeaders, + body: this.body ? messages_1.fromBodyObj(this.body) : undefined + }; + this.context = new SubscribeClientContext(this.ua.userAgentCore, this.uri, this.event, this.expires, options); + this.context.delegate = { + onAccept: (function (response) { return _this.onAccepted(response); }) + }; + return this.context; + }; + return Subscription; +}(events_1.EventEmitter)); +exports.Subscription = Subscription; +// tslint:disable-next-line:max-classes-per-file +var SubscribeClientContext = /** @class */ (function () { + function SubscribeClientContext(core, target, event, expires, options, delegate) { + this.core = core; + this.target = target; + this.event = event; + this.expires = expires; + this.subscribed = false; + this.logger = core.loggerFactory.getLogger("sip.subscription"); + this.delegate = delegate; + var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); + var extraHeaders = (options && options.extraHeaders || []).slice(); + extraHeaders.push(allowHeader); + extraHeaders.push("Event: " + this.event); + extraHeaders.push("Expires: " + this.expires); + extraHeaders.push("Contact: " + this.core.configuration.contact.toString()); + var body = options && options.body ? messages_1.toBodyObj(options.body) : undefined; + this.message = this.core.configuration.outgoingRequestMessageFactory(Constants_1.C.SUBSCRIBE, this.target, {}, extraHeaders, body); + } + /** Destructor. */ + SubscribeClientContext.prototype.dispose = function () { + if (this.subscription) { + this.subscription.dispose(); + } + if (this.request) { + this.request.waitNotifyStop(); + this.request.dispose(); + } + }; + Object.defineProperty(SubscribeClientContext.prototype, "state", { + /** Subscription state. */ + get: function () { + if (this.subscription) { + return this.subscription.subscriptionState; + } + else if (this.subscribed) { + return subscription_1.SubscriptionState.NotifyWait; + } + else { + return subscription_1.SubscriptionState.Initial; + } + }, + enumerable: true, + configurable: true + }); + /** + * Establish subscription. + * @param options Options bucket. + */ + SubscribeClientContext.prototype.subscribe = function () { + var _this = this; + if (this.subscribed) { + return Promise.reject(new Error("Not in initial state. Did you call subscribe more than once?")); + } + this.subscribed = true; + return new Promise(function (resolve, reject) { + if (!_this.message) { + throw new Error("Message undefined."); + } + _this.request = _this.core.subscribe(_this.message, { + // This SUBSCRIBE request will be confirmed with a final response. + // 200-class responses indicate that the subscription has been accepted + // and that a NOTIFY request will be sent immediately. + // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 + onAccept: function (response) { + if (_this.delegate && _this.delegate.onAccept) { + _this.delegate.onAccept(response); + } + }, + // Due to the potential for out-of-order messages, packet loss, and + // forking, the subscriber MUST be prepared to receive NOTIFY requests + // before the SUBSCRIBE transaction has completed. + // https://tools.ietf.org/html/rfc6665#section-4.1.2.4 + onNotify: function (requestWithSubscription) { + _this.subscription = requestWithSubscription.subscription; + if (_this.subscription) { + _this.subscription.autoRefresh = true; + } + resolve({ success: requestWithSubscription }); + }, + // If this Timer N expires prior to the receipt of a NOTIFY request, + // the subscriber considers the subscription failed, and cleans up + // any state associated with the subscription attempt. + // https://tools.ietf.org/html/rfc6665#section-4.1.2.4 + onNotifyTimeout: function () { + resolve({ failure: {} }); + }, + // This SUBSCRIBE request will be confirmed with a final response. + // Non-200-class final responses indicate that no subscription or new + // dialog usage has been created, and no subsequent NOTIFY request will + // be sent. + // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 + onRedirect: function (response) { + resolve({ failure: { response: response } }); + }, + // This SUBSCRIBE request will be confirmed with a final response. + // Non-200-class final responses indicate that no subscription or new + // dialog usage has been created, and no subsequent NOTIFY request will + // be sent. + // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 + onReject: function (response) { + resolve({ failure: { response: response } }); + } + }); + }); + }; + return SubscribeClientContext; +}()); + + +/***/ }), +/* 72 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +function __export(m) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; +} +Object.defineProperty(exports, "__esModule", { value: true }); +__export(__webpack_require__(73)); + + +/***/ }), +/* 73 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +/** + * Subscription state. + * https://tools.ietf.org/html/rfc6665#section-4.1.2 + */ +var SubscriptionState; +(function (SubscriptionState) { + SubscriptionState["Initial"] = "Initial"; + SubscriptionState["NotifyWait"] = "NotifyWait"; + SubscriptionState["Pending"] = "Pending"; + SubscriptionState["Active"] = "Active"; + SubscriptionState["Terminated"] = "Terminated"; +})(SubscriptionState = exports.SubscriptionState || (exports.SubscriptionState = {})); + + +/***/ }), +/* 74 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +var Constants_1 = __webpack_require__(3); +/** + * FIXME: TODO: Should be configurable/variable. + */ +exports.AllowedMethods = [ + Constants_1.C.ACK, + Constants_1.C.BYE, + Constants_1.C.CANCEL, + Constants_1.C.INFO, + Constants_1.C.INVITE, + Constants_1.C.MESSAGE, + Constants_1.C.NOTIFY, + Constants_1.C.OPTIONS, + Constants_1.C.PRACK, + Constants_1.C.REFER, + Constants_1.C.SUBSCRIBE +]; + + +/***/ }), +/* 75 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var events_1 = __webpack_require__(2); +var Enums_1 = __webpack_require__(5); +/* Transport + * @class Abstract transport layer parent class + * @param {Logger} logger + * @param {Object} [options] + */ +var Transport = /** @class */ (function (_super) { + __extends(Transport, _super); + function Transport(logger, options) { + var _this = _super.call(this) || this; + _this.type = Enums_1.TypeStrings.Transport; + _this.logger = logger; + return _this; + } + /** + * Returns the promise designated by the child layer then emits a connected event. + * Automatically emits an event upon resolution, unless overrideEvent is set. If you + * override the event in this fashion, you should emit it in your implementation of connectPromise + * @param {Object} [options] + * @returns {Promise} + */ + Transport.prototype.connect = function (options) { + var _this = this; + if (options === void 0) { options = {}; } + return this.connectPromise(options).then(function (data) { + if (!data.overrideEvent) { + _this.emit("connected"); + } + }); + }; + /** + * Sends a message then emits a 'messageSent' event. Automatically emits an + * event upon resolution, unless data.overrideEvent is set. If you override + * the event in this fashion, you should emit it in your implementation of sendPromise + * @param {String} msg + * @param {Object} options + * @returns {Promise} + */ + Transport.prototype.send = function (msg, options) { + var _this = this; + if (options === void 0) { options = {}; } + return this.sendPromise(msg).then(function (data) { + if (!data.overrideEvent) { + _this.emit("messageSent", data.msg); + } + }); + }; + /** + * Returns the promise designated by the child layer then emits a + * disconnected event. Automatically emits an event upon resolution, + * unless overrideEvent is set. If you override the event in this fashion, + * you should emit it in your implementation of disconnectPromise + * @param {Object} [options] + * @returns {Promise} + */ + Transport.prototype.disconnect = function (options) { + var _this = this; + if (options === void 0) { options = {}; } + return this.disconnectPromise(options).then(function (data) { + if (!data.overrideEvent) { + _this.emit("disconnected"); + } + }); + }; + Transport.prototype.afterConnected = function (callback) { + if (this.isConnected()) { + callback(); + } + else { + this.once("connected", callback); + } + }; + /** + * Returns a promise which resolves once the UA is connected. DEPRECATION WARNING: just use afterConnected() + * @returns {Promise} + */ + Transport.prototype.waitForConnected = function () { + var _this = this; + // tslint:disable-next-line:no-console + console.warn("DEPRECATION WARNING Transport.waitForConnected(): use afterConnected() instead"); + return new Promise(function (resolve) { + _this.afterConnected(resolve); + }); + }; + return Transport; +}(events_1.EventEmitter)); +exports.Transport = Transport; + + +/***/ }), +/* 76 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(global) { +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var events_1 = __webpack_require__(2); +var ClientContext_1 = __webpack_require__(1); +var Constants_1 = __webpack_require__(3); +var user_agent_core_1 = __webpack_require__(78); +var DigestAuthentication_1 = __webpack_require__(12); +var Enums_1 = __webpack_require__(5); +var Exceptions_1 = __webpack_require__(47); +var Grammar_1 = __webpack_require__(7); +var LoggerFactory_1 = __webpack_require__(48); +var Parser_1 = __webpack_require__(49); +var PublishContext_1 = __webpack_require__(50); +var ReferContext_1 = __webpack_require__(51); +var RegisterContext_1 = __webpack_require__(66); +var ServerContext_1 = __webpack_require__(62); +var Session_1 = __webpack_require__(67); +var SIPMessage_1 = __webpack_require__(6); +var Subscription_1 = __webpack_require__(71); +var URI_1 = __webpack_require__(10); +var Utils_1 = __webpack_require__(11); +var SessionDescriptionHandler_1 = __webpack_require__(111); +var Transport_1 = __webpack_require__(114); +var environment = global.window || global; +/** + * @class Class creating a SIP User Agent. + * @param {function returning SIP.sessionDescriptionHandler} [configuration.sessionDescriptionHandlerFactory] + * A function will be invoked by each of the UA's Sessions to build the sessionDescriptionHandler for that Session. + * If no (or a falsy) value is provided, each Session will use a default (WebRTC) sessionDescriptionHandler. + */ +var UA = /** @class */ (function (_super) { + __extends(UA, _super); + function UA(configuration) { + var _this = _super.call(this) || this; + _this.type = Enums_1.TypeStrings.UA; + _this.log = new LoggerFactory_1.LoggerFactory(); + _this.logger = _this.getLogger("sip.ua"); + _this.configuration = {}; + // User actions outside any session/dialog (MESSAGE) + _this.applicants = {}; + _this.data = {}; + _this.sessions = {}; + _this.publishers = {}; + _this.status = Enums_1.UAStatus.STATUS_INIT; + /** + * Load configuration + * + * @throws {SIP.Exceptions.ConfigurationError} + * @throws {TypeError} + */ + if (configuration === undefined) { + configuration = {}; + } + else if (typeof configuration === "string" || configuration instanceof String) { + configuration = { + uri: configuration + }; + } + // Apply log configuration if present + if (configuration.log) { + if (configuration.log.hasOwnProperty("builtinEnabled")) { + _this.log.builtinEnabled = configuration.log.builtinEnabled; + } + if (configuration.log.hasOwnProperty("connector")) { + _this.log.connector = configuration.log.connector; + } + if (configuration.log.hasOwnProperty("level")) { + var level = configuration.log.level; + // const normalized: Levels = typeof level === "string" ? Levels[level] : level; + var normalized = void 0; + switch (level) { + case "error": + normalized = LoggerFactory_1.Levels.error; + break; + case "warn": + normalized = LoggerFactory_1.Levels.warn; + break; + case "log": + normalized = LoggerFactory_1.Levels.log; + break; + case "debug": + normalized = LoggerFactory_1.Levels.debug; + break; + default: + break; + } + // avoid setting level when invalid, use default level instead + if (normalized === undefined) { + _this.logger.error("Invalid \"level\" parameter value: " + JSON.stringify(level)); + } + else { + _this.log.level = normalized; + } + } + } + try { + _this.loadConfig(configuration); + } + catch (e) { + _this.status = Enums_1.UAStatus.STATUS_NOT_READY; + _this.error = UA.C.CONFIGURATION_ERROR; + throw e; + } + var userAgentCoreConfiguration = user_agent_core_1.makeUserAgentCoreConfigurationFromUA(_this); + // The Replaces header contains information used to match an existing + // SIP dialog (call-id, to-tag, and from-tag). Upon receiving an INVITE + // with a Replaces header, the User Agent (UA) attempts to match this + // information with a confirmed or early dialog. + // https://tools.ietf.org/html/rfc3891#section-3 + var handleInviteWithReplacesHeader = function (context, request) { + if (_this.configuration.replaces !== Constants_1.C.supported.UNSUPPORTED) { + var replaces = request.parseHeader("replaces"); + if (replaces) { + var targetSession = _this.sessions[replaces.call_id + replaces.replaces_from_tag] || + _this.sessions[replaces.call_id + replaces.replaces_to_tag] || + undefined; + if (!targetSession) { + _this.userAgentCore.replyStateless(request, { statusCode: 481 }); + return; + } + if (targetSession.status === Enums_1.SessionStatus.STATUS_TERMINATED) { + _this.userAgentCore.replyStateless(request, { statusCode: 603 }); + return; + } + var targetDialogId = replaces.call_id + replaces.replaces_to_tag + replaces.replaces_from_tag; + var targetDialog = _this.userAgentCore.dialogs.get(targetDialogId); + if (!targetDialog) { + _this.userAgentCore.replyStateless(request, { statusCode: 481 }); + return; + } + if (!targetDialog.early && replaces.early_only) { + _this.userAgentCore.replyStateless(request, { statusCode: 486 }); + return; + } + context.replacee = targetSession; + } + } + }; + var userAgentCoreDelegate = { + onInvite: function (incomingInviteRequest) { + // FIXME: Ported - 100 Trying send should be configurable. + // Only required if TU will not respond in 200ms. + // https://tools.ietf.org/html/rfc3261#section-17.2.1 + incomingInviteRequest.trying(); + incomingInviteRequest.delegate = { + onCancel: function (cancel) { + context.onCancel(cancel); + }, + onTransportError: function (error) { + context.onTransportError(); + } + }; + var context = new Session_1.InviteServerContext(_this, incomingInviteRequest); + // Ported - handling of out of dialog INVITE with Replaces. + handleInviteWithReplacesHeader(context, incomingInviteRequest.message); + // Ported - make the first call to progress automatically. + if (context.autoSendAnInitialProvisionalResponse) { + context.progress(); + } + _this.emit("invite", context); + }, + onMessage: function (incomingMessageRequest) { + // Ported - handling of out of dialog MESSAGE. + var serverContext = new ServerContext_1.ServerContext(_this, incomingMessageRequest); + serverContext.body = incomingMessageRequest.message.body; + serverContext.contentType = incomingMessageRequest.message.getHeader("Content-Type") || "text/plain"; + incomingMessageRequest.accept(); + _this.emit("message", serverContext); // TODO: Review. Why is a "ServerContext" emitted? What use it is? + }, + onNotify: function (incomingNotifyRequest) { + // DEPRECATED: Out of dialog NOTIFY is an obsolete usage. + // Ported - handling of out of dialog NOTIFY. + if (_this.configuration.allowLegacyNotifications && _this.listeners("notify").length > 0) { + incomingNotifyRequest.accept(); + _this.emit("notify", { request: incomingNotifyRequest.message }); + } + else { + incomingNotifyRequest.reject({ statusCode: 481 }); + } + }, + onRefer: function (incomingReferRequest) { + // Ported - handling of out of dialog REFER. + _this.logger.log("Received an out of dialog refer"); + if (!_this.configuration.allowOutOfDialogRefers) { + incomingReferRequest.reject({ statusCode: 405 }); + } + _this.logger.log("Allow out of dialog refers is enabled on the UA"); + var referContext = new ReferContext_1.ReferServerContext(_this, incomingReferRequest); + if (_this.listeners("outOfDialogReferRequested").length) { + _this.emit("outOfDialogReferRequested", referContext); + } + else { + _this.logger.log("No outOfDialogReferRequest listeners, automatically accepting and following the out of dialog refer"); + referContext.accept({ followRefer: true }); + } + }, + onSubscribe: function (incomingSubscribeRequest) { + _this.emit("subscribe", incomingSubscribeRequest); + }, + }; + _this.userAgentCore = new user_agent_core_1.UserAgentCore(userAgentCoreConfiguration, userAgentCoreDelegate); + // Initialize registerContext + _this.registerContext = new RegisterContext_1.RegisterContext(_this, configuration.registerOptions); + _this.registerContext.on("failed", _this.emit.bind(_this, "registrationFailed")); + _this.registerContext.on("registered", _this.emit.bind(_this, "registered")); + _this.registerContext.on("unregistered", _this.emit.bind(_this, "unregistered")); + if (_this.configuration.autostart) { + _this.start(); + } + return _this; + } + // ================= + // High Level API + // ================= + UA.prototype.register = function (options) { + if (options === void 0) { options = {}; } + if (options.register) { + this.configuration.register = true; + } + this.registerContext.register(options); + return this; + }; + /** + * Unregister. + * + * @param {Boolean} [all] unregister all user bindings. + * + */ + UA.prototype.unregister = function (options) { + var _this = this; + this.configuration.register = false; + if (this.transport) { + this.transport.afterConnected(function () { + _this.registerContext.unregister(options); + }); + } + return this; + }; + UA.prototype.isRegistered = function () { + return this.registerContext.registered; + }; + /** + * Make an outgoing call. + * + * @param {String} target + * @param {Object} views + * @param {Object} [options.media] gets passed to SIP.sessionDescriptionHandler.getDescription as mediaHint + * + * @throws {TypeError} + * + */ + UA.prototype.invite = function (target, options, modifiers) { + var _this = this; + var context = new Session_1.InviteClientContext(this, target, options, modifiers); + // Delay sending actual invite until the next 'tick' if we are already + // connected, so that API consumers can register to events fired by the + // the session. + if (this.transport) { + this.transport.afterConnected(function () { + context.invite(); + _this.emit("inviteSent", context); + }); + } + return context; + }; + UA.prototype.subscribe = function (target, event, options) { + var sub = new Subscription_1.Subscription(this, target, event, options); + if (this.transport) { + this.transport.afterConnected(function () { return sub.subscribe(); }); + } + return sub; + }; + /** + * Send PUBLISH Event State Publication (RFC3903) + * + * @param {String} target + * @param {String} event + * @param {String} body + * @param {Object} [options] + * + * @throws {SIP.Exceptions.MethodParameterError} + */ + UA.prototype.publish = function (target, event, body, options) { + var pub = new PublishContext_1.PublishContext(this, target, event, options); + if (this.transport) { + this.transport.afterConnected(function () { + pub.publish(body); + }); + } + return pub; + }; + /** + * Send a message. + * + * @param {String} target + * @param {String} body + * @param {Object} [options] + * + * @throws {TypeError} + */ + UA.prototype.message = function (target, body, options) { + if (options === void 0) { options = {}; } + if (body === undefined) { + throw new TypeError("Not enough arguments"); + } + // There is no Message module, so it is okay that the UA handles defaults here. + options.contentType = options.contentType || "text/plain"; + options.body = body; + return this.request(Constants_1.C.MESSAGE, target, options); + }; + UA.prototype.request = function (method, target, options) { + var req = new ClientContext_1.ClientContext(this, method, target, options); + if (this.transport) { + this.transport.afterConnected(function () { return req.send(); }); + } + return req; + }; + /** + * Gracefully close. + */ + UA.prototype.stop = function () { + this.logger.log("user requested closure..."); + if (this.status === Enums_1.UAStatus.STATUS_USER_CLOSED) { + this.logger.warn("UA already closed"); + return this; + } + // Close registerContext + this.logger.log("closing registerContext"); + this.registerContext.close(); + // Run _terminate_ on every Session + for (var session in this.sessions) { + if (this.sessions[session]) { + this.logger.log("closing session " + session); + this.sessions[session].terminate(); + } + } + // Run _close_ on every Publisher + for (var publisher in this.publishers) { + if (this.publishers[publisher]) { + this.logger.log("unpublish " + publisher); + this.publishers[publisher].close(); + } + } + // Run _close_ on every applicant + for (var applicant in this.applicants) { + if (this.applicants[applicant]) { + this.applicants[applicant].close(); + } + } + this.status = Enums_1.UAStatus.STATUS_USER_CLOSED; + if (typeof environment.removeEventListener === "function") { + // Google Chrome Packaged Apps don't allow 'unload' listeners: + // unload is not available in packaged apps + if (!(global.chrome && global.chrome.app && global.chrome.app.runtime)) { + environment.removeEventListener("unload", this.environListener); + } + } + return this; + }; + /** + * Connect to the WS server if status = STATUS_INIT. + * Resume UA after being closed. + * + */ + UA.prototype.start = function () { + var _this = this; + this.logger.log("user requested startup..."); + if (this.status === Enums_1.UAStatus.STATUS_INIT) { + this.status = Enums_1.UAStatus.STATUS_STARTING; + if (!this.configuration.transportConstructor) { + throw new Exceptions_1.Exceptions.TransportError("Transport constructor not set"); + } + this.transport = new this.configuration.transportConstructor(this.getLogger("sip.transport"), this.configuration.transportOptions); + this.setTransportListeners(); + this.emit("transportCreated", this.transport); + this.transport.connect(); + } + else if (this.status === Enums_1.UAStatus.STATUS_USER_CLOSED) { + this.logger.log("resuming"); + this.status = Enums_1.UAStatus.STATUS_READY; + if (this.transport) { + this.transport.connect(); + } + } + else if (this.status === Enums_1.UAStatus.STATUS_STARTING) { + this.logger.log("UA is in STARTING status, not opening new connection"); + } + else if (this.status === Enums_1.UAStatus.STATUS_READY) { + this.logger.log("UA is in READY status, not resuming"); + } + else { + this.logger.error("Connection is down. Auto-Recovery system is trying to connect"); + } + if (this.configuration.autostop && typeof environment.addEventListener === "function") { + // Google Chrome Packaged Apps don't allow 'unload' listeners: + // unload is not available in packaged apps + if (!(global.chrome && global.chrome.app && global.chrome.app.runtime)) { + this.environListener = this.stop; + environment.addEventListener("unload", function () { return _this.environListener(); }); + } + } + return this; + }; + /** + * Normalize a string into a valid SIP request URI + * + * @param {String} target + * + * @returns {SIP.URI|undefined} + */ + UA.prototype.normalizeTarget = function (target) { + return Utils_1.Utils.normalizeTarget(target, this.configuration.hostportParams); + }; + UA.prototype.getLogger = function (category, label) { + return this.log.getLogger(category, label); + }; + UA.prototype.getLoggerFactory = function () { + return this.log; + }; + /** + * Get the session to which the request belongs to, if any. + * @param {SIP.IncomingRequest} request. + * @returns {SIP.OutgoingSession|SIP.IncomingSession|undefined} + */ + UA.prototype.findSession = function (request) { + return this.sessions[request.callId + request.fromTag] || + this.sessions[request.callId + request.toTag] || + undefined; + }; + UA.prototype.on = function (name, callback) { return _super.prototype.on.call(this, name, callback); }; + // ============================== + // Event Handlers + // ============================== + UA.prototype.onTransportError = function () { + if (this.status === Enums_1.UAStatus.STATUS_USER_CLOSED) { + return; + } + if (!this.error || this.error !== UA.C.NETWORK_ERROR) { + this.status = Enums_1.UAStatus.STATUS_NOT_READY; + this.error = UA.C.NETWORK_ERROR; + } + }; + /** + * Helper function. Sets transport listeners + */ + UA.prototype.setTransportListeners = function () { + var _this = this; + if (this.transport) { + this.transport.on("connected", function () { return _this.onTransportConnected(); }); + this.transport.on("message", function (message) { return _this.onTransportReceiveMsg(message); }); + this.transport.on("transportError", function () { return _this.onTransportError(); }); + } + }; + /** + * Transport connection event. + * @event + * @param {SIP.Transport} transport. + */ + UA.prototype.onTransportConnected = function () { + var _this = this; + if (this.configuration.register) { + // In an effor to maintain behavior from when we "initialized" an + // authentication factory, this is in a Promise.then + Promise.resolve().then(function () { return _this.registerContext.register(); }); + } + }; + /** + * Handle SIP message received from the transport. + * @param messageString The message. + */ + UA.prototype.onTransportReceiveMsg = function (messageString) { + var _this = this; + var message = Parser_1.Parser.parseMessage(messageString, this); + if (!message) { + this.logger.warn("UA failed to parse incoming SIP message - discarding."); + return; + } + if (this.status === Enums_1.UAStatus.STATUS_USER_CLOSED && message instanceof SIPMessage_1.IncomingRequest) { + this.logger.warn("UA received message when status = USER_CLOSED - aborting"); + return; + } + // A valid SIP request formulated by a UAC MUST, at a minimum, contain + // the following header fields: To, From, CSeq, Call-ID, Max-Forwards, + // and Via; all of these header fields are mandatory in all SIP + // requests. + // https://tools.ietf.org/html/rfc3261#section-8.1.1 + var hasMinimumHeaders = function () { + var mandatoryHeaders = ["from", "to", "call_id", "cseq", "via"]; + for (var _i = 0, mandatoryHeaders_1 = mandatoryHeaders; _i < mandatoryHeaders_1.length; _i++) { + var header = mandatoryHeaders_1[_i]; + if (!message.hasHeader(header)) { + _this.logger.warn("Missing mandatory header field : " + header + "."); + return false; + } + } + return true; + }; + // Request Checks + if (message instanceof SIPMessage_1.IncomingRequest) { + // This is port of SanityCheck.minimumHeaders(). + if (!hasMinimumHeaders()) { + this.logger.warn("Request missing mandatory header field. Dropping."); + return; + } + // FIXME: This is non-standard and should be a configruable behavior (desirable regardless). + // Custom SIP.js check to reject request from ourself (this instance of SIP.js). + // This is port of SanityCheck.rfc3261_16_3_4(). + if (!message.toTag && message.callId.substr(0, 5) === this.configuration.sipjsId) { + this.userAgentCore.replyStateless(message, { statusCode: 482 }); + return; + } + // FIXME: This should be Transport check before we get here (Section 18). + // Custom SIP.js check to reject requests if body length wrong. + // This is port of SanityCheck.rfc3261_18_3_request(). + var len = Utils_1.Utils.str_utf8_length(message.body); + var contentLength = message.getHeader("content-length"); + if (contentLength && len < Number(contentLength)) { + this.userAgentCore.replyStateless(message, { statusCode: 400 }); + return; + } + } + // Reponse Checks + if (message instanceof SIPMessage_1.IncomingResponse) { + // This is port of SanityCheck.minimumHeaders(). + if (!hasMinimumHeaders()) { + this.logger.warn("Response missing mandatory header field. Dropping."); + return; + } + // Custom SIP.js check to drop responses if multiple Via headers. + // This is port of SanityCheck.rfc3261_8_1_3_3(). + if (message.getHeaders("via").length > 1) { + this.logger.warn("More than one Via header field present in the response. Dropping."); + return; + } + // FIXME: This should be Transport check before we get here (Section 18). + // Custom SIP.js check to drop responses if bad Via header. + // This is port of SanityCheck.rfc3261_18_1_2(). + if (message.via.host !== this.configuration.viaHost || message.via.port !== undefined) { + this.logger.warn("Via sent-by in the response does not match UA Via host value. Dropping."); + return; + } + // FIXME: This should be Transport check before we get here (Section 18). + // Custom SIP.js check to reject requests if body length wrong. + // This is port of SanityCheck.rfc3261_18_3_response(). + var len = Utils_1.Utils.str_utf8_length(message.body); + var contentLength = message.getHeader("content-length"); + if (contentLength && len < Number(contentLength)) { + this.logger.warn("Message body length is lower than the value in Content-Length header field. Dropping."); + return; + } + } + // Handle Request + if (message instanceof SIPMessage_1.IncomingRequest) { + this.userAgentCore.receiveIncomingRequestFromTransport(message); + return; + } + // Handle Response + if (message instanceof SIPMessage_1.IncomingResponse) { + this.userAgentCore.receiveIncomingResponseFromTransport(message); + return; + } + throw new Error("Invalid message type."); + }; + // ================= + // Utils + // ================= + UA.prototype.checkAuthenticationFactory = function (authenticationFactory) { + if (!(authenticationFactory instanceof Function)) { + return; + } + if (!authenticationFactory.initialize) { + authenticationFactory.initialize = function () { + return Promise.resolve(); + }; + } + return authenticationFactory; + }; + /** + * Configuration load. + * returns {void} + */ + UA.prototype.loadConfig = function (configuration) { + var _this = this; + // Settings and default values + var settings = { + /* Host address + * Value to be set in Via sent_by and host part of Contact FQDN + */ + viaHost: Utils_1.Utils.createRandomToken(12) + ".invalid", + uri: new URI_1.URI("sip", "anonymous." + Utils_1.Utils.createRandomToken(6), "anonymous.invalid", undefined, undefined), + // Custom Configuration Settings + custom: {}, + // Display name + displayName: "", + // Password + password: undefined, + register: true, + // Registration parameters + registerOptions: {}, + // Transport related parameters + transportConstructor: Transport_1.Transport, + transportOptions: {}, + // string to be inserted into User-Agent request header + userAgentString: Constants_1.C.USER_AGENT, + // Session parameters + noAnswerTimeout: 60, + // Hacks + hackViaTcp: false, + hackIpInContact: false, + hackWssInTransport: false, + hackAllowUnregisteredOptionTags: false, + // Session Description Handler Options + sessionDescriptionHandlerFactoryOptions: { + constraints: {}, + peerConnectionOptions: {} + }, + extraSupported: [], + contactName: Utils_1.Utils.createRandomToken(8), + contactTransport: "ws", + forceRport: false, + // autostarting + autostart: true, + autostop: true, + // Reliable Provisional Responses + rel100: Constants_1.C.supported.UNSUPPORTED, + // DTMF type: 'info' or 'rtp' (RFC 4733) + // RTP Payload Spec: https://tools.ietf.org/html/rfc4733 + // WebRTC Audio Spec: https://tools.ietf.org/html/rfc7874 + dtmfType: Constants_1.C.dtmfType.INFO, + // Replaces header (RFC 3891) + // http://tools.ietf.org/html/rfc3891 + replaces: Constants_1.C.supported.UNSUPPORTED, + sessionDescriptionHandlerFactory: SessionDescriptionHandler_1.SessionDescriptionHandler.defaultFactory, + authenticationFactory: this.checkAuthenticationFactory(function (ua) { + return new DigestAuthentication_1.DigestAuthentication(ua); + }), + allowLegacyNotifications: false, + allowOutOfDialogRefers: false, + experimentalFeatures: false + }; + var configCheck = this.getConfigurationCheck(); + // Check Mandatory parameters + for (var parameter in configCheck.mandatory) { + if (!configuration.hasOwnProperty(parameter)) { + throw new Exceptions_1.Exceptions.ConfigurationError(parameter); + } + else { + var value = configuration[parameter]; + var checkedValue = configCheck.mandatory[parameter](value); + if (checkedValue !== undefined) { + settings[parameter] = checkedValue; + } + else { + throw new Exceptions_1.Exceptions.ConfigurationError(parameter, value); + } + } + } + // Check Optional parameters + for (var parameter in configCheck.optional) { + if (configuration.hasOwnProperty(parameter)) { + var value = configuration[parameter]; + // If the parameter value is an empty array, but shouldn't be, apply its default value. + // If the parameter value is null, empty string, or undefined then apply its default value. + // If it's a number with NaN value then also apply its default value. + // NOTE: JS does not allow "value === NaN", the following does the work: + if ((value instanceof Array && value.length === 0) || + (value === null || value === "" || value === undefined) || + (typeof (value) === "number" && isNaN(value))) { + continue; + } + var checkedValue = configCheck.optional[parameter](value); + if (checkedValue !== undefined) { + settings[parameter] = checkedValue; + } + else { + throw new Exceptions_1.Exceptions.ConfigurationError(parameter, value); + } + } + } + // Post Configuration Process + // Allow passing 0 number as displayName. + if (settings.displayName === 0) { + settings.displayName = "0"; + } + // sipjsId instance parameter. Static random tag of length 5 + settings.sipjsId = Utils_1.Utils.createRandomToken(5); + // String containing settings.uri without scheme and user. + var hostportParams = settings.uri.clone(); + hostportParams.user = undefined; + settings.hostportParams = hostportParams.toRaw().replace(/^sip:/i, ""); + /* Check whether authorizationUser is explicitly defined. + * Take 'settings.uri.user' value if not. + */ + if (!settings.authorizationUser) { + settings.authorizationUser = settings.uri.user; + } + // User noAnswerTimeout + settings.noAnswerTimeout = settings.noAnswerTimeout * 1000; + // Via Host + if (settings.hackIpInContact) { + if (typeof settings.hackIpInContact === "boolean") { + var from = 1; + var to = 254; + var octet = Math.floor(Math.random() * (to - from + 1) + from); + // random Test-Net IP (http://tools.ietf.org/html/rfc5735) + settings.viaHost = "192.0.2." + octet; + } + else if (typeof settings.hackIpInContact === "string") { + settings.viaHost = settings.hackIpInContact; + } + } + // Contact transport parameter + if (settings.hackWssInTransport) { + settings.contactTransport = "wss"; + } + this.contact = { + pubGruu: undefined, + tempGruu: undefined, + uri: new URI_1.URI("sip", settings.contactName, settings.viaHost, undefined, { transport: settings.contactTransport }), + toString: function (options) { + if (options === void 0) { options = {}; } + var anonymous = options.anonymous || false; + var outbound = options.outbound || false; + var contact = "<"; + if (anonymous) { + contact += (_this.contact.tempGruu || + ("sip:anonymous@anonymous.invalid;transport=" + settings.contactTransport)).toString(); + } + else { + contact += (_this.contact.pubGruu || _this.contact.uri).toString(); + } + if (outbound) { + contact += ";ob"; + } + contact += ">"; + return contact; + } + }; + var skeleton = {}; + // Fill the value of the configuration_skeleton + for (var parameter in settings) { + if (settings.hasOwnProperty(parameter)) { + skeleton[parameter] = settings[parameter]; + } + } + Object.assign(this.configuration, skeleton); + this.logger.log("configuration parameters after validation:"); + for (var parameter in settings) { + if (settings.hasOwnProperty(parameter)) { + switch (parameter) { + case "uri": + case "sessionDescriptionHandlerFactory": + this.logger.log("· " + parameter + ": " + settings[parameter]); + break; + case "password": + this.logger.log("· " + parameter + ": " + "NOT SHOWN"); + break; + case "transportConstructor": + this.logger.log("· " + parameter + ": " + settings[parameter].name); + break; + default: + this.logger.log("· " + parameter + ": " + JSON.stringify(settings[parameter])); + } + } + } + return; + }; + /** + * Configuration checker. + * @return {Boolean} + */ + UA.prototype.getConfigurationCheck = function () { + return { + mandatory: {}, + optional: { + uri: function (uri) { + if (!(/^sip:/i).test(uri)) { + uri = Constants_1.C.SIP + ":" + uri; + } + var parsed = Grammar_1.Grammar.URIParse(uri); + if (!parsed || !parsed.user) { + return; + } + else { + return parsed; + } + }, + transportConstructor: function (transportConstructor) { + if (transportConstructor instanceof Function) { + return transportConstructor; + } + }, + transportOptions: function (transportOptions) { + if (typeof transportOptions === "object") { + return transportOptions; + } + }, + authorizationUser: function (authorizationUser) { + if (Grammar_1.Grammar.parse('"' + authorizationUser + '"', "quoted_string") === -1) { + return; + } + else { + return authorizationUser; + } + }, + displayName: function (displayName) { + if (Grammar_1.Grammar.parse('"' + displayName + '"', "displayName") === -1) { + return; + } + else { + return displayName; + } + }, + dtmfType: function (dtmfType) { + switch (dtmfType) { + case Constants_1.C.dtmfType.RTP: + return Constants_1.C.dtmfType.RTP; + case Constants_1.C.dtmfType.INFO: + // Fall through + default: + return Constants_1.C.dtmfType.INFO; + } + }, + hackViaTcp: function (hackViaTcp) { + if (typeof hackViaTcp === "boolean") { + return hackViaTcp; + } + }, + hackIpInContact: function (hackIpInContact) { + if (typeof hackIpInContact === "boolean") { + return hackIpInContact; + } + else if (typeof hackIpInContact === "string" && Grammar_1.Grammar.parse(hackIpInContact, "host") !== -1) { + return hackIpInContact; + } + }, + hackWssInTransport: function (hackWssInTransport) { + if (typeof hackWssInTransport === "boolean") { + return hackWssInTransport; + } + }, + hackAllowUnregisteredOptionTags: function (hackAllowUnregisteredOptionTags) { + if (typeof hackAllowUnregisteredOptionTags === "boolean") { + return hackAllowUnregisteredOptionTags; + } + }, + contactTransport: function (contactTransport) { + if (typeof contactTransport === "string") { + return contactTransport; + } + }, + extraSupported: function (optionTags) { + if (!(optionTags instanceof Array)) { + return; + } + for (var _i = 0, optionTags_1 = optionTags; _i < optionTags_1.length; _i++) { + var tag = optionTags_1[_i]; + if (typeof tag !== "string") { + return; + } + } + return optionTags; + }, + forceRport: function (forceRport) { + if (typeof forceRport === "boolean") { + return forceRport; + } + }, + noAnswerTimeout: function (noAnswerTimeout) { + if (Utils_1.Utils.isDecimal(noAnswerTimeout)) { + var value = Number(noAnswerTimeout); + if (value > 0) { + return value; + } + } + }, + password: function (password) { + return String(password); + }, + rel100: function (rel100) { + if (rel100 === Constants_1.C.supported.REQUIRED) { + return Constants_1.C.supported.REQUIRED; + } + else if (rel100 === Constants_1.C.supported.SUPPORTED) { + return Constants_1.C.supported.SUPPORTED; + } + else { + return Constants_1.C.supported.UNSUPPORTED; + } + }, + replaces: function (replaces) { + if (replaces === Constants_1.C.supported.REQUIRED) { + return Constants_1.C.supported.REQUIRED; + } + else if (replaces === Constants_1.C.supported.SUPPORTED) { + return Constants_1.C.supported.SUPPORTED; + } + else { + return Constants_1.C.supported.UNSUPPORTED; + } + }, + register: function (register) { + if (typeof register === "boolean") { + return register; + } + }, + registerOptions: function (registerOptions) { + if (typeof registerOptions === "object") { + return registerOptions; + } + }, + userAgentString: function (userAgentString) { + if (typeof userAgentString === "string") { + return userAgentString; + } + }, + autostart: function (autostart) { + if (typeof autostart === "boolean") { + return autostart; + } + }, + autostop: function (autostop) { + if (typeof autostop === "boolean") { + return autostop; + } + }, + sessionDescriptionHandlerFactory: function (sessionDescriptionHandlerFactory) { + if (sessionDescriptionHandlerFactory instanceof Function) { + return sessionDescriptionHandlerFactory; + } + }, + sessionDescriptionHandlerFactoryOptions: function (options) { + if (typeof options === "object") { + return options; + } + }, + authenticationFactory: this.checkAuthenticationFactory, + allowLegacyNotifications: function (allowLegacyNotifications) { + if (typeof allowLegacyNotifications === "boolean") { + return allowLegacyNotifications; + } + }, + custom: function (custom) { + if (typeof custom === "object") { + return custom; + } + }, + contactName: function (contactName) { + if (typeof contactName === "string") { + return contactName; + } + }, + experimentalFeatures: function (experimentalFeatures) { + if (typeof experimentalFeatures === "boolean") { + return experimentalFeatures; + } + }, + } + }; + }; + UA.C = { + // UA status codes + STATUS_INIT: 0, + STATUS_STARTING: 1, + STATUS_READY: 2, + STATUS_USER_CLOSED: 3, + STATUS_NOT_READY: 4, + // UA error codes + CONFIGURATION_ERROR: 1, + NETWORK_ERROR: 2, + ALLOWED_METHODS: [ + "ACK", + "CANCEL", + "INVITE", + "MESSAGE", + "BYE", + "OPTIONS", + "INFO", + "NOTIFY", + "REFER" + ], + ACCEPTED_BODY_TYPES: [ + "application/sdp", + "application/dtmf-relay" + ], + MAX_FORWARDS: 70, + TAG_LENGTH: 10 + }; + return UA; +}(events_1.EventEmitter)); +exports.UA = UA; +(function (UA) { + var DtmfType; + (function (DtmfType) { + DtmfType["RTP"] = "rtp"; + DtmfType["INFO"] = "info"; + })(DtmfType = UA.DtmfType || (UA.DtmfType = {})); +})(UA = exports.UA || (exports.UA = {})); +exports.UA = UA; + +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(77))) + +/***/ }), +/* 77 */ +/***/ (function(module, exports) { + +var g; + +// This works in non-strict mode +g = (function() { + return this; +})(); + +try { + // This works if eval is allowed (see CSP) + g = g || new Function("return this")(); +} catch (e) { + // This works if the window reference is available + if (typeof window === "object") g = window; +} + +// g can still be undefined, but nothing to do about it... +// We return undefined, instead of nothing here, so it's +// easier to handle this case. if(!global) { ...} + +module.exports = g; + + +/***/ }), +/* 78 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +function __export(m) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; +} +Object.defineProperty(exports, "__esModule", { value: true }); +__export(__webpack_require__(79)); +__export(__webpack_require__(110)); + + +/***/ }), +/* 79 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +var Constants_1 = __webpack_require__(3); +var messages_1 = __webpack_require__(63); +var transactions_1 = __webpack_require__(52); +var user_agents_1 = __webpack_require__(80); +var allowed_methods_1 = __webpack_require__(74); +/** + * This is ported from UA.C.ACCEPTED_BODY_TYPES. + * FIXME: TODO: Should be configurable/variable. + */ +var acceptedBodyTypes = [ + "application/sdp", + "application/dtmf-relay" +]; +/** + * Core: Core designates the functions specific to a particular type + * of SIP entity, i.e., specific to either a stateful or stateless + * proxy, a user agent or registrar. All cores, except those for + * the stateless proxy, are transaction users. + * https://tools.ietf.org/html/rfc3261#section-6 + * + * UAC Core: The set of processing functions required of a UAC that + * reside above the transaction and transport layers. + * https://tools.ietf.org/html/rfc3261#section-6 + * + * UAS Core: The set of processing functions required at a UAS that + * resides above the transaction and transport layers. + * https://tools.ietf.org/html/rfc3261#section-6 + */ +var UserAgentCore = /** @class */ (function () { + /** + * Constructor. + * @param configuration Configuration. + * @param delegate Delegate. + */ + function UserAgentCore(configuration, delegate) { + if (delegate === void 0) { delegate = {}; } + /** UACs. */ + this.userAgentClients = new Map(); + /** UASs. */ + this.userAgentServers = new Map(); + this.configuration = configuration; + this.delegate = delegate; + this.dialogs = new Map(); + this.subscribers = new Map(); + this.logger = configuration.loggerFactory.getLogger("sip.user-agent-core"); + } + /** Destructor. */ + UserAgentCore.prototype.dispose = function () { + this.dialogs.forEach(function (dialog) { return dialog.dispose(); }); + this.dialogs.clear(); + this.subscribers.forEach(function (subscriber) { return subscriber.dispose(); }); + this.subscribers.clear(); + this.userAgentClients.forEach(function (uac) { return uac.dispose(); }); + this.userAgentClients.clear(); + this.userAgentServers.forEach(function (uac) { return uac.dispose(); }); + this.userAgentServers.clear(); + }; + Object.defineProperty(UserAgentCore.prototype, "loggerFactory", { + /** Logger factory. */ + get: function () { + return this.configuration.loggerFactory; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(UserAgentCore.prototype, "transport", { + /** Transport. */ + get: function () { + var transport = this.configuration.transportAccessor(); + if (!transport) { + throw new Error("Transport undefined."); + } + return transport; + }, + enumerable: true, + configurable: true + }); + /** + * Send INVITE. + * @param request Outgoing request. + * @param delegate Request delegate. + */ + UserAgentCore.prototype.invite = function (request, delegate) { + return new user_agents_1.InviteUserAgentClient(this, request, delegate); + }; + /** + * Send MESSAGE. + * @param request Outgoing request. + * @param delegate Request delegate. + */ + UserAgentCore.prototype.message = function (request, delegate) { + return new user_agents_1.MessageUserAgentClient(this, request, delegate); + }; + /** + * Send PUBLISH. + * @param request Outgoing request. + * @param delegate Request delegate. + */ + UserAgentCore.prototype.publish = function (request, delegate) { + return new user_agents_1.PublishUserAgentClient(this, request, delegate); + }; + /** + * Send REGISTER. + * @param request Outgoing request. + * @param delegate Request delegate. + */ + UserAgentCore.prototype.register = function (request, delegate) { + return new user_agents_1.RegisterUserAgentClient(this, request, delegate); + }; + /** + * Send SUBSCRIBE. + * @param request Outgoing request. + * @param delegate Request delegate. + */ + UserAgentCore.prototype.subscribe = function (request, delegate) { + return new user_agents_1.SubscribeUserAgentClient(this, request, delegate); + }; + /** + * Send a request. + * @param request Outgoing request. + * @param delegate Request delegate. + */ + UserAgentCore.prototype.request = function (request, delegate) { + return new user_agents_1.UserAgentClient(transactions_1.NonInviteClientTransaction, this, request, delegate); + }; + /** + * Handle an incoming request message from the transport. + * @param message Incoming request message from transport layer. + */ + UserAgentCore.prototype.receiveIncomingRequestFromTransport = function (message) { + this.receiveRequestFromTransport(message); + }; + /** + * Handle an incoming response message from the transport. + * @param message Incoming response message from transport layer. + */ + UserAgentCore.prototype.receiveIncomingResponseFromTransport = function (message) { + this.receiveResponseFromTransport(message); + }; + /** + * A stateless UAS is a UAS that does not maintain transaction state. + * It replies to requests normally, but discards any state that would + * ordinarily be retained by a UAS after a response has been sent. If a + * stateless UAS receives a retransmission of a request, it regenerates + * the response and re-sends it, just as if it were replying to the first + * instance of the request. A UAS cannot be stateless unless the request + * processing for that method would always result in the same response + * if the requests are identical. This rules out stateless registrars, + * for example. Stateless UASs do not use a transaction layer; they + * receive requests directly from the transport layer and send responses + * directly to the transport layer. + * https://tools.ietf.org/html/rfc3261#section-8.2.7 + * @param message Incoming request message to reply to. + * @param statusCode Status code to reply with. + */ + UserAgentCore.prototype.replyStateless = function (message, options) { + var userAgent = this.configuration.userAgentHeaderFieldValue; + options = __assign({}, options, { userAgent: userAgent }); + var response = messages_1.constructOutgoingResponse(message, options); + this.transport.send(response.message); + return response; + }; + /** + * In Section 18.2.1, replace the last paragraph with: + * + * Next, the server transport attempts to match the request to a + * server transaction. It does so using the matching rules described + * in Section 17.2.3. If a matching server transaction is found, the + * request is passed to that transaction for processing. If no match + * is found, the request is passed to the core, which may decide to + * construct a new server transaction for that request. + * https://tools.ietf.org/html/rfc6026#section-8.10 + * @param message Incoming request message from transport layer. + */ + UserAgentCore.prototype.receiveRequestFromTransport = function (message) { + // When a request is received from the network by the server, it has to + // be matched to an existing transaction. This is accomplished in the + // following manner. + // + // The branch parameter in the topmost Via header field of the request + // is examined. If it is present and begins with the magic cookie + // "z9hG4bK", the request was generated by a client transaction + // compliant to this specification. Therefore, the branch parameter + // will be unique across all transactions sent by that client. The + // request matches a transaction if: + // + // 1. the branch parameter in the request is equal to the one in the + // top Via header field of the request that created the + // transaction, and + // + // 2. the sent-by value in the top Via of the request is equal to the + // one in the request that created the transaction, and + // + // 3. the method of the request matches the one that created the + // transaction, except for ACK, where the method of the request + // that created the transaction is INVITE. + // + // This matching rule applies to both INVITE and non-INVITE transactions + // alike. + // + // The sent-by value is used as part of the matching process because + // there could be accidental or malicious duplication of branch + // parameters from different clients. + // https://tools.ietf.org/html/rfc3261#section-17.2.3 + var transactionId = message.viaBranch; // FIXME: Currently only using rule 1... + var uas = this.userAgentServers.get(transactionId); + // When receiving an ACK that matches an existing INVITE server + // transaction and that does not contain a branch parameter containing + // the magic cookie defined in RFC 3261, the matching transaction MUST + // be checked to see if it is in the "Accepted" state. If it is, then + // the ACK must be passed directly to the transaction user instead of + // being absorbed by the transaction state machine. This is necessary + // as requests from RFC 2543 clients will not include a unique branch + // parameter, and the mechanisms for calculating the transaction ID from + // such a request will be the same for both INVITE and ACKs. + // https://tools.ietf.org/html/rfc6026#section-6 + // Any ACKs received from the network while in the "Accepted" state MUST be + // passed directly to the TU and not absorbed. + // https://tools.ietf.org/html/rfc6026#section-7.1 + if (message.method === Constants_1.C.ACK) { + if (uas && uas.transaction.state === transactions_1.TransactionState.Accepted) { + if (uas instanceof user_agents_1.InviteUserAgentServer) { + // These are ACKs matching an INVITE server transaction. + // These should never happen with RFC 3261 compliant user agents + // (would be a broken ACK to negative final response or something) + // but is apparently how RFC 2543 user agents do things. + // We are not currently supporting this case. + // NOTE: Not backwards compatible with RFC 2543 (no support for strict-routing). + this.logger.warn("Discarding out of dialog ACK after 2xx response sent on transaction " + transactionId + "."); + return; + } + } + } + // The CANCEL method requests that the TU at the server side cancel a + // pending transaction. The TU determines the transaction to be + // cancelled by taking the CANCEL request, and then assuming that the + // request method is anything but CANCEL or ACK and applying the + // transaction matching procedures of Section 17.2.3. The matching + // transaction is the one to be cancelled. + // https://tools.ietf.org/html/rfc3261#section-9.2 + if (message.method === Constants_1.C.CANCEL) { + if (uas) { + // Regardless of the method of the original request, as long as the + // CANCEL matched an existing transaction, the UAS answers the CANCEL + // request itself with a 200 (OK) response. + // https://tools.ietf.org/html/rfc3261#section-9.2 + this.replyStateless(message, { statusCode: 200 }); + // If the transaction for the original request still exists, the behavior + // of the UAS on receiving a CANCEL request depends on whether it has already + // sent a final response for the original request. If it has, the CANCEL + // request has no effect on the processing of the original request, no + // effect on any session state, and no effect on the responses generated + // for the original request. If the UAS has not issued a final response + // for the original request, its behavior depends on the method of the + // original request. If the original request was an INVITE, the UAS + // SHOULD immediately respond to the INVITE with a 487 (Request + // Terminated). + // https://tools.ietf.org/html/rfc3261#section-9.2 + if (uas.transaction instanceof transactions_1.InviteServerTransaction && + uas.transaction.state === transactions_1.TransactionState.Proceeding) { + if (uas instanceof user_agents_1.InviteUserAgentServer) { + uas.receiveCancel(message); + } + // A CANCEL request has no impact on the processing of + // transactions with any other method defined in this specification. + // https://tools.ietf.org/html/rfc3261#section-9.2 + } + } + else { + // If the UAS did not find a matching transaction for the CANCEL + // according to the procedure above, it SHOULD respond to the CANCEL + // with a 481 (Call Leg/Transaction Does Not Exist). + // https://tools.ietf.org/html/rfc3261#section-9.2 + this.replyStateless(message, { statusCode: 481 }); + } + return; + } + // If a matching server transaction is found, the request is passed to that + // transaction for processing. + // https://tools.ietf.org/html/rfc6026#section-8.10 + if (uas) { + uas.transaction.receiveRequest(message); + return; + } + // If no match is found, the request is passed to the core, which may decide to + // construct a new server transaction for that request. + // https://tools.ietf.org/html/rfc6026#section-8.10 + this.receiveRequest(message); + return; + }; + /** + * UAC and UAS procedures depend strongly on two factors. First, based + * on whether the request or response is inside or outside of a dialog, + * and second, based on the method of a request. Dialogs are discussed + * thoroughly in Section 12; they represent a peer-to-peer relationship + * between user agents and are established by specific SIP methods, such + * as INVITE. + * @param message Incoming request message. + */ + UserAgentCore.prototype.receiveRequest = function (message) { + // 8.2 UAS Behavior + // UASs SHOULD process the requests in the order of the steps that + // follow in this section (that is, starting with authentication, then + // inspecting the method, the header fields, and so on throughout the + // remainder of this section). + // https://tools.ietf.org/html/rfc3261#section-8.2 + // 8.2.1 Method Inspection + // Once a request is authenticated (or authentication is skipped), the + // UAS MUST inspect the method of the request. If the UAS recognizes + // but does not support the method of a request, it MUST generate a 405 + // (Method Not Allowed) response. Procedures for generating responses + // are described in Section 8.2.6. The UAS MUST also add an Allow + // header field to the 405 (Method Not Allowed) response. The Allow + // header field MUST list the set of methods supported by the UAS + // generating the message. + // https://tools.ietf.org/html/rfc3261#section-8.2.1 + if (!allowed_methods_1.AllowedMethods.includes(message.method)) { + var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); + this.replyStateless(message, { + statusCode: 405, + extraHeaders: [allowHeader] + }); + return; + } + // 8.2.2 Header Inspection + // https://tools.ietf.org/html/rfc3261#section-8.2.2 + if (!message.ruri) { // FIXME: A request message should always have an ruri + throw new Error("Request-URI undefined."); + } + // 8.2.2.1 To and Request-URI + // If the Request-URI uses a scheme not supported by the UAS, it SHOULD + // reject the request with a 416 (Unsupported URI Scheme) response. + // https://tools.ietf.org/html/rfc3261#section-8.2.2.1 + if (message.ruri.scheme !== Constants_1.C.SIP) { + this.replyStateless(message, { statusCode: 416 }); + return; + } + // 8.2.2.1 To and Request-URI + // If the Request-URI does not identify an address that the + // UAS is willing to accept requests for, it SHOULD reject + // the request with a 404 (Not Found) response. + // https://tools.ietf.org/html/rfc3261#section-8.2.2.1 + var ruri = message.ruri; + var ruriMatches = function (uri) { + return !!uri && uri.user === ruri.user; + }; + if (!ruriMatches(this.configuration.aor) && + !(ruriMatches(this.configuration.contact.uri) || + ruriMatches(this.configuration.contact.pubGruu) || + ruriMatches(this.configuration.contact.tempGruu))) { + this.logger.warn("Request-URI does not point to us."); + if (message.method !== Constants_1.C.ACK) { + this.replyStateless(message, { statusCode: 404 }); + } + return; + } + // 8.2.2.1 To and Request-URI + // Other potential sources of received Request-URIs include + // the Contact header fields of requests and responses sent by the UA + // that establish or refresh dialogs. + // https://tools.ietf.org/html/rfc3261#section-8.2.2.1 + if (message.method === Constants_1.C.INVITE) { + if (!message.hasHeader("Contact")) { + this.replyStateless(message, { + statusCode: 400, + reasonPhrase: "Missing Contact Header" + }); + return; + } + } + // 8.2.2.2 Merged Requests + // If the request has no tag in the To header field, the UAS core MUST + // check the request against ongoing transactions. If the From tag, + // Call-ID, and CSeq exactly match those associated with an ongoing + // transaction, but the request does not match that transaction (based + // on the matching rules in Section 17.2.3), the UAS core SHOULD + // generate a 482 (Loop Detected) response and pass it to the server + // transaction. + // + // The same request has arrived at the UAS more than once, following + // different paths, most likely due to forking. The UAS processes + // the first such request received and responds with a 482 (Loop + // Detected) to the rest of them. + // https://tools.ietf.org/html/rfc3261#section-8.2.2.2 + if (!message.toTag) { + var transactionId = message.viaBranch; + if (!this.userAgentServers.has(transactionId)) { + var mergedRequest = Array.from(this.userAgentServers.values()) + .some(function (uas) { + return uas.transaction.request.fromTag === message.fromTag && + uas.transaction.request.callId === message.callId && + uas.transaction.request.cseq === message.cseq; + }); + if (mergedRequest) { + this.replyStateless(message, { statusCode: 482 }); + return; + } + } + } + // 8.2.2.3 Require + // https://tools.ietf.org/html/rfc3261#section-8.2.2.3 + // TODO + // 8.2.3 Content Processing + // https://tools.ietf.org/html/rfc3261#section-8.2.3 + // TODO + // 8.2.4 Applying Extensions + // https://tools.ietf.org/html/rfc3261#section-8.2.4 + // TODO + // 8.2.5 Processing the Request + // Assuming all of the checks in the previous subsections are passed, + // the UAS processing becomes method-specific. + // https://tools.ietf.org/html/rfc3261#section-8.2.5 + // The UAS will receive the request from the transaction layer. If the + // request has a tag in the To header field, the UAS core computes the + // dialog identifier corresponding to the request and compares it with + // existing dialogs. If there is a match, this is a mid-dialog request. + // In that case, the UAS first applies the same processing rules for + // requests outside of a dialog, discussed in Section 8.2. + // https://tools.ietf.org/html/rfc3261#section-12.2.2 + if (message.toTag) { + this.receiveInsideDialogRequest(message); + } + else { + this.receiveOutsideDialogRequest(message); + } + return; + }; + /** + * Once a dialog has been established between two UAs, either of them + * MAY initiate new transactions as needed within the dialog. The UA + * sending the request will take the UAC role for the transaction. The + * UA receiving the request will take the UAS role. Note that these may + * be different roles than the UAs held during the transaction that + * established the dialog. + * https://tools.ietf.org/html/rfc3261#section-12.2 + * @param message Incoming request message. + */ + UserAgentCore.prototype.receiveInsideDialogRequest = function (message) { + // NOTIFY requests are matched to such SUBSCRIBE requests if they + // contain the same "Call-ID", a "To" header field "tag" parameter that + // matches the "From" header field "tag" parameter of the SUBSCRIBE + // request, and the same "Event" header field. Rules for comparisons of + // the "Event" header fields are described in Section 8.2.1. + // https://tools.ietf.org/html/rfc6665#section-4.4.1 + if (message.method === Constants_1.C.NOTIFY) { + var event_1 = message.parseHeader("Event"); + if (!event_1 || !event_1.event) { + this.replyStateless(message, { statusCode: 489 }); + return; + } + // FIXME: Subscriber id should also matching on event id. + var subscriberId = message.callId + message.toTag + event_1.event; + var subscriber = this.subscribers.get(subscriberId); + if (subscriber) { + var uas = new user_agents_1.NotifyUserAgentServer(this, message); + subscriber.onNotify(uas); + return; + } + } + // Requests sent within a dialog, as any other requests, are atomic. If + // a particular request is accepted by the UAS, all the state changes + // associated with it are performed. If the request is rejected, none + // of the state changes are performed. + // + // Note that some requests, such as INVITEs, affect several pieces of + // state. + // + // The UAS will receive the request from the transaction layer. If the + // request has a tag in the To header field, the UAS core computes the + // dialog identifier corresponding to the request and compares it with + // existing dialogs. If there is a match, this is a mid-dialog request. + // https://tools.ietf.org/html/rfc3261#section-12.2.2 + var dialogId = message.callId + message.toTag + message.fromTag; + var dialog = this.dialogs.get(dialogId); + if (dialog) { + // [Sip-implementors] Reg. SIP reinvite, UPDATE and OPTIONS + // You got the question right. + // + // And you got the right answer too. :-) + // + // Thanks, + // Paul + // + // Robert Sparks wrote: + // > So I've lost track of the question during the musing. + // > + // > I _think_ the fundamental question being asked is this: + // > + // > Is an endpoint required to reject (with a 481) an OPTIONS request that + // > arrives with at to-tag but does not match any existing dialog state. + // > (Assuming some earlier requirement hasn't forced another error code). Or + // > is it OK if it just sends + // > a 200 OK anyhow. + // > + // > My take on the collection of specs is that its _not_ ok for it to send + // > the 200 OK anyhow and that it is required to send + // > the 481. I base this primarily on these sentences from 11.2 in 3261: + // > + // > The response to an OPTIONS is constructed using the standard rules + // > for a SIP response as discussed in Section 8.2.6. The response code + // > chosen MUST be the same that would have been chosen had the request + // > been an INVITE. + // > + // > Did I miss the point of the question? + // > + // > On May 15, 2008, at 12:48 PM, Paul Kyzivat wrote: + // > + // >> [Including Robert in hopes of getting his insight on this.] + // https://lists.cs.columbia.edu/pipermail/sip-implementors/2008-May/019178.html + // + // Requests that do not change in any way the state of a dialog may be + // received within a dialog (for example, an OPTIONS request). They are + // processed as if they had been received outside the dialog. + // https://tools.ietf.org/html/rfc3261#section-12.2.2 + if (message.method === Constants_1.C.OPTIONS) { + var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); + var acceptHeader = "Accept: " + acceptedBodyTypes.toString(); + this.replyStateless(message, { + statusCode: 200, + extraHeaders: [allowHeader, acceptHeader] + }); + return; + } + // Pass the incoming request to the dialog for further handling. + dialog.receiveRequest(message); + return; + } + // The most important behaviors of a stateless UAS are the following: + // ... + // o A stateless UAS MUST ignore ACK requests. + // ... + // https://tools.ietf.org/html/rfc3261#section-8.2.7 + if (message.method === Constants_1.C.ACK) { + // If a final response to an INVITE was sent statelessly, + // the corresponding ACK: + // - will not match an existing transaction + // - may have tag in the To header field + // - not not match any existing dialogs + // Absorb unmatched ACKs. + return; + } + // If the request has a tag in the To header field, but the dialog + // identifier does not match any existing dialogs, the UAS may have + // crashed and restarted, or it may have received a request for a + // different (possibly failed) UAS (the UASs can construct the To tags + // so that a UAS can identify that the tag was for a UAS for which it is + // providing recovery). Another possibility is that the incoming + // request has been simply mis-routed. Based on the To tag, the UAS MAY + // either accept or reject the request. Accepting the request for + // acceptable To tags provides robustness, so that dialogs can persist + // even through crashes. UAs wishing to support this capability must + // take into consideration some issues such as choosing monotonically + // increasing CSeq sequence numbers even across reboots, reconstructing + // the route set, and accepting out-of-range RTP timestamps and sequence + // numbers. + // + // If the UAS wishes to reject the request because it does not wish to + // recreate the dialog, it MUST respond to the request with a 481 + // (Call/Transaction Does Not Exist) status code and pass that to the + // server transaction. + // https://tools.ietf.org/html/rfc3261#section-12.2.2 + this.replyStateless(message, { statusCode: 481 }); + return; + }; + /** + * Assuming all of the checks in the previous subsections are passed, + * the UAS processing becomes method-specific. + * https://tools.ietf.org/html/rfc3261#section-8.2.5 + * @param message Incoming request message. + */ + UserAgentCore.prototype.receiveOutsideDialogRequest = function (message) { + switch (message.method) { + case Constants_1.C.ACK: + // Absorb stray out of dialog ACKs + break; + case Constants_1.C.BYE: + // If the BYE does not match an existing dialog, the UAS core SHOULD + // generate a 481 (Call/Transaction Does Not Exist) response and pass + // that to the server transaction. This rule means that a BYE sent + // without tags by a UAC will be rejected. + // https://tools.ietf.org/html/rfc3261#section-15.1.2 + this.replyStateless(message, { statusCode: 481 }); + break; + case Constants_1.C.CANCEL: + throw new Error("Unexpected out of dialog request method " + message.method + "."); + break; + case Constants_1.C.INFO: + // Use of the INFO method does not constitute a separate dialog usage. + // INFO messages are always part of, and share the fate of, an invite + // dialog usage [RFC5057]. INFO messages cannot be sent as part of + // other dialog usages, or outside an existing dialog. + // https://tools.ietf.org/html/rfc6086#section-1 + this.replyStateless(message, { statusCode: 405 }); // Should never happen + break; + case Constants_1.C.INVITE: + // https://tools.ietf.org/html/rfc3261#section-13.3.1 + { + var uas = new user_agents_1.InviteUserAgentServer(this, message); + this.delegate.onInvite ? + this.delegate.onInvite(uas) : + uas.reject(); + } + break; + case Constants_1.C.MESSAGE: + // MESSAGE requests are discouraged inside a dialog. Implementations + // are restricted from creating a usage for the purpose of carrying a + // sequence of MESSAGE requests (though some implementations use it that + // way, against the standard recommendation). + // https://tools.ietf.org/html/rfc5057#section-5.3 + { + var uas = new user_agents_1.MessageUserAgentServer(this, message); + this.delegate.onMessage ? + this.delegate.onMessage(uas) : + uas.accept(); + } + break; + case Constants_1.C.NOTIFY: + // Obsoleted by: RFC 6665 + // If any non-SUBSCRIBE mechanisms are defined to create subscriptions, + // it is the responsibility of the parties defining those mechanisms to + // ensure that correlation of a NOTIFY message to the corresponding + // subscription is possible. Designers of such mechanisms are also + // warned to make a distinction between sending a NOTIFY message to a + // subscriber who is aware of the subscription, and sending a NOTIFY + // message to an unsuspecting node. The latter behavior is invalid, and + // MUST receive a "481 Subscription does not exist" response (unless + // some other 400- or 500-class error code is more applicable), as + // described in section 3.2.4. In other words, knowledge of a + // subscription must exist in both the subscriber and the notifier to be + // valid, even if installed via a non-SUBSCRIBE mechanism. + // https://tools.ietf.org/html/rfc3265#section-3.2 + // + // NOTIFY requests are sent to inform subscribers of changes in state to + // which the subscriber has a subscription. Subscriptions are created + // using the SUBSCRIBE method. In legacy implementations, it is + // possible that other means of subscription creation have been used. + // However, this specification does not allow the creation of + // subscriptions except through SUBSCRIBE requests and (for backwards- + // compatibility) REFER requests [RFC3515]. + // https://tools.ietf.org/html/rfc6665#section-3.2 + { + var uas = new user_agents_1.NotifyUserAgentServer(this, message); + this.delegate.onNotify ? + this.delegate.onNotify(uas) : + this.replyStateless(message, { statusCode: 405 }); + } + break; + case Constants_1.C.OPTIONS: + // https://tools.ietf.org/html/rfc3261#section-11.2 + { + var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); + var acceptHeader = "Accept: " + acceptedBodyTypes.toString(); + this.replyStateless(message, { + statusCode: 200, + extraHeaders: [allowHeader, acceptHeader] + }); + } + break; + case Constants_1.C.REFER: + // https://tools.ietf.org/html/rfc3515#section-2.4.2 + { + var uas = new user_agents_1.ReferUserAgentServer(this, message); + this.delegate.onRefer ? + this.delegate.onRefer(uas) : + this.replyStateless(message, { statusCode: 405 }); + } + break; + case Constants_1.C.SUBSCRIBE: + // https://tools.ietf.org/html/rfc6665#section-4.2 + { + var uas = new user_agents_1.SubscribeUserAgentServer(this, message); + this.delegate.onSubscribe ? + this.delegate.onSubscribe(uas) : + uas.reject(); + } + break; + default: + throw new Error("Unexpected out of dialog request method " + message.method + "."); + } + return; + }; + /** + * Responses are first processed by the transport layer and then passed + * up to the transaction layer. The transaction layer performs its + * processing and then passes the response up to the TU. The majority + * of response processing in the TU is method specific. However, there + * are some general behaviors independent of the method. + * https://tools.ietf.org/html/rfc3261#section-8.1.3 + * @param message Incoming response message from transport layer. + */ + UserAgentCore.prototype.receiveResponseFromTransport = function (message) { + // 8.1.3.1 Transaction Layer Errors + // https://tools.ietf.org/html/rfc3261#section-8.1.3.1 + // Handled by transaction layer callbacks. + // 8.1.3.2 Unrecognized Responses + // https://tools.ietf.org/html/rfc3261#section-8.1.3.1 + // TODO + // 8.1.3.3 Vias + // https://tools.ietf.org/html/rfc3261#section-8.1.3.3 + if (message.getHeaders("via").length > 1) { + this.logger.warn("More than one Via header field present in the response, dropping"); + return; + } + // 8.1.3.4 Processing 3xx Responses + // https://tools.ietf.org/html/rfc3261#section-8.1.3.4 + // TODO + // 8.1.3.5 Processing 4xx Responses + // https://tools.ietf.org/html/rfc3261#section-8.1.3.5 + // TODO + // When the transport layer in the client receives a response, it has to + // determine which client transaction will handle the response, so that + // the processing of Sections 17.1.1 and 17.1.2 can take place. The + // branch parameter in the top Via header field is used for this + // purpose. A response matches a client transaction under two + // conditions: + // + // 1. If the response has the same value of the branch parameter in + // the top Via header field as the branch parameter in the top + // Via header field of the request that created the transaction. + // + // 2. If the method parameter in the CSeq header field matches the + // method of the request that created the transaction. The + // method is needed since a CANCEL request constitutes a + // different transaction, but shares the same value of the branch + // parameter. + // https://tools.ietf.org/html/rfc3261#section-17.1.3 + var userAgentClientId = message.viaBranch + message.method; + var userAgentClient = this.userAgentClients.get(userAgentClientId); + // The client transport uses the matching procedures of Section + // 17.1.3 to attempt to match the response to an existing + // transaction. If there is a match, the response MUST be passed to + // that transaction. Otherwise, any element other than a stateless + // proxy MUST silently discard the response. + // https://tools.ietf.org/html/rfc6026#section-8.9 + if (userAgentClient) { + userAgentClient.transaction.receiveResponse(message); + } + else { + this.logger.warn("Discarding unmatched " + message.statusCode + " response to " + message.method + " " + userAgentClientId + "."); + } + }; + return UserAgentCore; +}()); +exports.UserAgentCore = UserAgentCore; + + +/***/ }), +/* 80 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +function __export(m) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; +} +Object.defineProperty(exports, "__esModule", { value: true }); +__export(__webpack_require__(81)); +__export(__webpack_require__(83)); +__export(__webpack_require__(85)); +__export(__webpack_require__(86)); +__export(__webpack_require__(87)); +__export(__webpack_require__(102)); +__export(__webpack_require__(103)); +__export(__webpack_require__(104)); +__export(__webpack_require__(92)); +__export(__webpack_require__(93)); +__export(__webpack_require__(105)); +__export(__webpack_require__(94)); +__export(__webpack_require__(95)); +__export(__webpack_require__(96)); +__export(__webpack_require__(97)); +__export(__webpack_require__(101)); +__export(__webpack_require__(106)); +__export(__webpack_require__(98)); +__export(__webpack_require__(99)); +__export(__webpack_require__(107)); +__export(__webpack_require__(108)); +__export(__webpack_require__(109)); +__export(__webpack_require__(82)); +__export(__webpack_require__(84)); + + +/***/ }), +/* 81 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Constants_1 = __webpack_require__(3); +var transactions_1 = __webpack_require__(52); +var user_agent_client_1 = __webpack_require__(82); +var ByeUserAgentClient = /** @class */ (function (_super) { + __extends(ByeUserAgentClient, _super); + function ByeUserAgentClient(dialog, delegate, options) { + var _this = this; + var message = dialog.createOutgoingRequestMessage(Constants_1.C.BYE, options); + _this = _super.call(this, transactions_1.NonInviteClientTransaction, dialog.userAgentCore, message, delegate) || this; + dialog.dispose(); + return _this; + } + return ByeUserAgentClient; +}(user_agent_client_1.UserAgentClient)); +exports.ByeUserAgentClient = ByeUserAgentClient; + + +/***/ }), +/* 82 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +var Constants_1 = __webpack_require__(3); +var SIPMessage_1 = __webpack_require__(6); +var transactions_1 = __webpack_require__(52); +/* + * User Agent Client (UAC): A user agent client is a logical entity + * that creates a new request, and then uses the client + * transaction state machinery to send it. The role of UAC lasts + * only for the duration of that transaction. In other words, if + * a piece of software initiates a request, it acts as a UAC for + * the duration of that transaction. If it receives a request + * later, it assumes the role of a user agent server for the + * processing of that transaction. + * https://tools.ietf.org/html/rfc3261#section-6 + */ +var UserAgentClient = /** @class */ (function () { + function UserAgentClient(transactionConstructor, core, message, delegate) { + this.transactionConstructor = transactionConstructor; + this.core = core; + this.message = message; + this.delegate = delegate; + this.challenged = false; + this.stale = false; + this.logger = this.loggerFactory.getLogger("sip.user-agent-client"); + this.init(); + } + UserAgentClient.prototype.dispose = function () { + this.transaction.dispose(); + }; + Object.defineProperty(UserAgentClient.prototype, "loggerFactory", { + get: function () { + return this.core.loggerFactory; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(UserAgentClient.prototype, "transaction", { + /** The transaction associated with this request. */ + get: function () { + if (!this._transaction) { + throw new Error("Transaction undefined."); + } + return this._transaction; + }, + enumerable: true, + configurable: true + }); + /** + * Since requests other than INVITE are responded to immediately, sending a + * CANCEL for a non-INVITE request would always create a race condition. + * A CANCEL request SHOULD NOT be sent to cancel a request other than INVITE. + * https://tools.ietf.org/html/rfc3261#section-9.1 + * @param options Cancel options bucket. + */ + UserAgentClient.prototype.cancel = function (reason, options) { + var _this = this; + if (options === void 0) { options = {}; } + if (!this.transaction) { + throw new Error("Transaction undefined."); + } + if (!this.message.to) { + throw new Error("To undefined."); + } + if (!this.message.from) { + throw new Error("From undefined."); + } + // The following procedures are used to construct a CANCEL request. The + // Request-URI, Call-ID, To, the numeric part of CSeq, and From header + // fields in the CANCEL request MUST be identical to those in the + // request being cancelled, including tags. A CANCEL constructed by a + // client MUST have only a single Via header field value matching the + // top Via value in the request being cancelled. Using the same values + // for these header fields allows the CANCEL to be matched with the + // request it cancels (Section 9.2 indicates how such matching occurs). + // However, the method part of the CSeq header field MUST have a value + // of CANCEL. This allows it to be identified and processed as a + // transaction in its own right (See Section 17). + // https://tools.ietf.org/html/rfc3261#section-9.1 + var message = new SIPMessage_1.OutgoingRequest(Constants_1.C.CANCEL, this.message.ruri, this.message.ua, { + toUri: this.message.to.uri, + toTag: this.message.toTag, + fromUri: this.message.from.uri, + fromTag: this.message.fromTag, + callId: this.message.callId, + cseq: this.message.cseq + }, options.extraHeaders); + message.callId = this.message.callId; + message.cseq = this.message.cseq; + // TODO: Revisit this. + // The CANCEL needs to use the same branch parameter so that + // it matches the INVITE transaction, but this is a hacky way to do this. + // Or at the very least not well documented. If the the branch parameter + // is set on the outgoing request, the transaction will use it. + // Otherwise the transaction will make a new one. + message.branch = this.message.branch; + if (this.message.headers.Route) { + message.headers.Route = this.message.headers.Route; + } + if (reason) { + message.setHeader("Reason", reason); + } + // If no provisional response has been received, the CANCEL request MUST + // NOT be sent; rather, the client MUST wait for the arrival of a + // provisional response before sending the request. If the original + // request has generated a final response, the CANCEL SHOULD NOT be + // sent, as it is an effective no-op, since CANCEL has no effect on + // requests that have already generated a final response. + // https://tools.ietf.org/html/rfc3261#section-9.1 + if (this.transaction.state === transactions_1.TransactionState.Proceeding) { + var uac = new UserAgentClient(transactions_1.NonInviteClientTransaction, this.core, message); + } + else { + this.transaction.once("stateChanged", function () { + if (_this.transaction && _this.transaction.state === transactions_1.TransactionState.Proceeding) { + var uac = new UserAgentClient(transactions_1.NonInviteClientTransaction, _this.core, message); + } + }); + } + return message; + }; + /** + * If a 401 (Unauthorized) or 407 (Proxy Authentication Required) + * response is received, the UAC SHOULD follow the authorization + * procedures of Section 22.2 and Section 22.3 to retry the request with + * credentials. + * https://tools.ietf.org/html/rfc3261#section-8.1.3.5 + * 22 Usage of HTTP Authentication + * https://tools.ietf.org/html/rfc3261#section-22 + * 22.1 Framework + * https://tools.ietf.org/html/rfc3261#section-22.1 + * 22.2 User-to-User Authentication + * https://tools.ietf.org/html/rfc3261#section-22.2 + * 22.3 Proxy-to-User Authentication + * https://tools.ietf.org/html/rfc3261#section-22.3 + * + * FIXME: This "guard for and retry the request with credentials" + * implementation is not complete and at best minimally passable. + * @param response The incoming response to guard. + * @returns True if the program execution is to continue in the branch in question. + * Otherwise the request is retried with credentials and current request processing must stop. + */ + UserAgentClient.prototype.authenticationGuard = function (message) { + var statusCode = message.statusCode; + if (!statusCode) { + throw new Error("Response status code undefined."); + } + // If a 401 (Unauthorized) or 407 (Proxy Authentication Required) + // response is received, the UAC SHOULD follow the authorization + // procedures of Section 22.2 and Section 22.3 to retry the request with + // credentials. + // https://tools.ietf.org/html/rfc3261#section-8.1.3.5 + if (statusCode !== 401 && statusCode !== 407) { + return true; + } + // Get and parse the appropriate WWW-Authenticate or Proxy-Authenticate header. + var challenge; + var authorizationHeaderName; + if (statusCode === 401) { + challenge = message.parseHeader("www-authenticate"); + authorizationHeaderName = "authorization"; + } + else { + challenge = message.parseHeader("proxy-authenticate"); + authorizationHeaderName = "proxy-authorization"; + } + // Verify it seems a valid challenge. + if (!challenge) { + this.logger.warn(statusCode + " with wrong or missing challenge, cannot authenticate"); + return true; + } + // Avoid infinite authentications. + if (this.challenged && (this.stale || challenge.stale !== true)) { + this.logger.warn(statusCode + " apparently in authentication loop, cannot authenticate"); + return true; + } + // Get credentials. + if (!this.credentials) { + this.credentials = this.core.configuration.authenticationFactory(); + if (!this.credentials) { + this.logger.warn("Unable to obtain credentials, cannot authenticate"); + return true; + } + } + // Verify that the challenge is really valid. + if (!this.credentials.authenticate(this.message, challenge)) { + return true; + } + this.challenged = true; + if (challenge.stale) { + this.stale = true; + } + var cseq = this.message.cseq += 1; + this.message.setHeader("cseq", cseq + " " + this.message.method); + this.message.setHeader(authorizationHeaderName, this.credentials.toString()); + // Calling init (again) will swap out our existing client transaction with a new one. + // FIXME: HACK: An assumption is being made here that there is nothing that needs to + // be cleaned up beyond the client transaction which is being replaced. For example, + // it is assumed that no early dialogs have been created. + this.init(); + return false; + }; + /** + * Receive a response from the transaction layer. + * @param message Incoming response message. + */ + UserAgentClient.prototype.receiveResponse = function (message) { + if (!this.authenticationGuard(message)) { + return; + } + var statusCode = message.statusCode ? message.statusCode.toString() : ""; + if (!statusCode) { + throw new Error("Response status code undefined."); + } + switch (true) { + case /^100$/.test(statusCode): + if (this.delegate && this.delegate.onTrying) { + this.delegate.onTrying({ message: message }); + } + break; + case /^1[0-9]{2}$/.test(statusCode): + if (this.delegate && this.delegate.onProgress) { + this.delegate.onProgress({ message: message }); + } + break; + case /^2[0-9]{2}$/.test(statusCode): + if (this.delegate && this.delegate.onAccept) { + this.delegate.onAccept({ message: message }); + } + break; + case /^3[0-9]{2}$/.test(statusCode): + if (this.delegate && this.delegate.onRedirect) { + this.delegate.onRedirect({ message: message }); + } + break; + case /^[4-6][0-9]{2}$/.test(statusCode): + if (this.delegate && this.delegate.onReject) { + this.delegate.onReject({ message: message }); + } + break; + default: + throw new Error("Invalid status code " + statusCode); + } + }; + UserAgentClient.prototype.init = function () { + var _this = this; + // We are the transaction user. + var user = { + loggerFactory: this.loggerFactory, + onRequestTimeout: function () { return _this.onRequestTimeout(); }, + onStateChange: function (newState) { + if (newState === transactions_1.TransactionState.Terminated) { + // Remove the terminated transaction from the core. + _this.core.userAgentClients.delete(userAgentClientId); + // FIXME: HACK: Our transaction may have been swapped out with a new one + // post authentication (see above), so make sure to only to dispose of + // ourselves if this terminating transaction is our current transaction. + if (transaction === _this._transaction) { + _this.dispose(); + } + } + }, + onTransportError: function (error) { return _this.onTransportError(error); }, + receiveResponse: function (message) { return _this.receiveResponse(message); } + }; + // Create a new transaction with us as the user. + var transaction = new this.transactionConstructor(this.message, this.core.transport, user); + this._transaction = transaction; + // Add the new transaction to the core. + var userAgentClientId = transaction.id + transaction.request.method; + this.core.userAgentClients.set(userAgentClientId, this); + }; + /** + * 8.1.3.1 Transaction Layer Errors + * In some cases, the response returned by the transaction layer will + * not be a SIP message, but rather a transaction layer error. When a + * timeout error is received from the transaction layer, it MUST be + * treated as if a 408 (Request Timeout) status code has been received. + * If a fatal transport error is reported by the transport layer + * (generally, due to fatal ICMP errors in UDP or connection failures in + * TCP), the condition MUST be treated as a 503 (Service Unavailable) + * status code. + * https://tools.ietf.org/html/rfc3261#section-8.1.3.1 + */ + UserAgentClient.prototype.onRequestTimeout = function () { + this.logger.warn("User agent client request timed out. Generating internal 408 Request Timeout."); + var message = this.core.configuration.onRequestTimeoutResponseMessageFactory(); + this.receiveResponse(message); + return; + }; + /** + * 8.1.3.1 Transaction Layer Errors + * In some cases, the response returned by the transaction layer will + * not be a SIP message, but rather a transaction layer error. When a + * timeout error is received from the transaction layer, it MUST be + * treated as if a 408 (Request Timeout) status code has been received. + * If a fatal transport error is reported by the transport layer + * (generally, due to fatal ICMP errors in UDP or connection failures in + * TCP), the condition MUST be treated as a 503 (Service Unavailable) + * status code. + * https://tools.ietf.org/html/rfc3261#section-8.1.3.1 + */ + UserAgentClient.prototype.onTransportError = function (error) { + this.logger.error(error.message); + this.logger.error("User agent client request transport error. Generating internal 503 Service Unavailable."); + var message = this.core.configuration.onTransportErrorResponseMessageFactory(); + this.receiveResponse(message); + }; + return UserAgentClient; +}()); +exports.UserAgentClient = UserAgentClient; + + +/***/ }), +/* 83 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var transactions_1 = __webpack_require__(52); +var user_agent_server_1 = __webpack_require__(84); +var ByeUserAgentServer = /** @class */ (function (_super) { + __extends(ByeUserAgentServer, _super); + function ByeUserAgentServer(dialog, message, delegate) { + return _super.call(this, transactions_1.NonInviteServerTransaction, dialog.userAgentCore, message, delegate) || this; + } + return ByeUserAgentServer; +}(user_agent_server_1.UserAgentServer)); +exports.ByeUserAgentServer = ByeUserAgentServer; + + +/***/ }), +/* 84 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +var Exceptions_1 = __webpack_require__(47); +var Utils_1 = __webpack_require__(11); +var messages_1 = __webpack_require__(63); +var transactions_1 = __webpack_require__(52); +/** + * User Agent Server (UAS): A user agent server is a logical entity + * that generates a response to a SIP request. The response + * accepts, rejects, or redirects the request. This role lasts + * only for the duration of that transaction. In other words, if + * a piece of software responds to a request, it acts as a UAS for + * the duration of that transaction. If it generates a request + * later, it assumes the role of a user agent client for the + * processing of that transaction. + * https://tools.ietf.org/html/rfc3261#section-6 + */ +var UserAgentServer = /** @class */ (function () { + function UserAgentServer(transactionConstructor, core, message, delegate) { + this.transactionConstructor = transactionConstructor; + this.core = core; + this.message = message; + this.delegate = delegate; + this.logger = this.loggerFactory.getLogger("sip.user-agent-server"); + this.toTag = message.toTag ? message.toTag : Utils_1.Utils.newTag(); + this.init(); + } + UserAgentServer.prototype.dispose = function () { + this.transaction.dispose(); + }; + Object.defineProperty(UserAgentServer.prototype, "loggerFactory", { + get: function () { + return this.core.loggerFactory; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(UserAgentServer.prototype, "transaction", { + /** The transaction associated with this request. */ + get: function () { + if (!this._transaction) { + throw new Error("Transaction undefined."); + } + return this._transaction; + }, + enumerable: true, + configurable: true + }); + UserAgentServer.prototype.accept = function (options) { + if (options === void 0) { options = { statusCode: 200 }; } + if (!this.acceptable) { + throw new Exceptions_1.Exceptions.TransactionStateError(this.message.method + " not acceptable in state " + this.transaction.state + "."); + } + var statusCode = options.statusCode; + if (statusCode < 200 || statusCode > 299) { + throw new TypeError("Invalid statusCode: " + statusCode); + } + var response = this.reply(options); + return response; + }; + UserAgentServer.prototype.progress = function (options) { + if (options === void 0) { options = { statusCode: 180 }; } + if (!this.progressable) { + throw new Exceptions_1.Exceptions.TransactionStateError(this.message.method + " not progressable in state " + this.transaction.state + "."); + } + var statusCode = options.statusCode; + if (statusCode < 101 || statusCode > 199) { + throw new TypeError("Invalid statusCode: " + statusCode); + } + var response = this.reply(options); + return response; + }; + UserAgentServer.prototype.redirect = function (contacts, options) { + if (options === void 0) { options = { statusCode: 302 }; } + if (!this.redirectable) { + throw new Exceptions_1.Exceptions.TransactionStateError(this.message.method + " not redirectable in state " + this.transaction.state + "."); + } + var statusCode = options.statusCode; + if (statusCode < 300 || statusCode > 399) { + throw new TypeError("Invalid statusCode: " + statusCode); + } + var contactHeaders = new Array(); + contacts.forEach(function (contact) { return contactHeaders.push("Contact: " + contact.toString()); }); + options.extraHeaders = (options.extraHeaders || []).concat(contactHeaders); + var response = this.reply(options); + return response; + }; + UserAgentServer.prototype.reject = function (options) { + if (options === void 0) { options = { statusCode: 480 }; } + if (!this.rejectable) { + throw new Exceptions_1.Exceptions.TransactionStateError(this.message.method + " not rejectable in state " + this.transaction.state + "."); + } + var statusCode = options.statusCode; + if (statusCode < 400 || statusCode > 699) { + throw new TypeError("Invalid statusCode: " + statusCode); + } + var response = this.reply(options); + return response; + }; + UserAgentServer.prototype.trying = function (options) { + if (!this.tryingable) { + throw new Exceptions_1.Exceptions.TransactionStateError(this.message.method + " not tryingable in state " + this.transaction.state + "."); + } + var response = this.reply({ statusCode: 100 }); + return response; + }; + /** + * If the UAS did not find a matching transaction for the CANCEL + * according to the procedure above, it SHOULD respond to the CANCEL + * with a 481 (Call Leg/Transaction Does Not Exist). If the transaction + * for the original request still exists, the behavior of the UAS on + * receiving a CANCEL request depends on whether it has already sent a + * final response for the original request. If it has, the CANCEL + * request has no effect on the processing of the original request, no + * effect on any session state, and no effect on the responses generated + * for the original request. If the UAS has not issued a final response + * for the original request, its behavior depends on the method of the + * original request. If the original request was an INVITE, the UAS + * SHOULD immediately respond to the INVITE with a 487 (Request + * Terminated). A CANCEL request has no impact on the processing of + * transactions with any other method defined in this specification. + * https://tools.ietf.org/html/rfc3261#section-9.2 + * @param request Incoming CANCEL request. + */ + UserAgentServer.prototype.receiveCancel = function (message) { + // Note: Currently CANCEL is being handled as a special case. + // No UAS is created to handle the CANCEL and the response to + // it CANCEL is being handled statelessly by the user agent core. + // As such, there is currently no way to externally impact the + // response to the a CANCEL request. + if (this.delegate && this.delegate.onCancel) { + this.delegate.onCancel(message); + } + }; + Object.defineProperty(UserAgentServer.prototype, "acceptable", { + get: function () { + if (this.transaction instanceof transactions_1.InviteServerTransaction) { + return (this.transaction.state === transactions_1.TransactionState.Proceeding || + this.transaction.state === transactions_1.TransactionState.Accepted); + } + if (this.transaction instanceof transactions_1.NonInviteServerTransaction) { + return (this.transaction.state === transactions_1.TransactionState.Trying || + this.transaction.state === transactions_1.TransactionState.Proceeding); + } + throw new Error("Unknown transaction type."); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(UserAgentServer.prototype, "progressable", { + get: function () { + if (this.transaction instanceof transactions_1.InviteServerTransaction) { + return this.transaction.state === transactions_1.TransactionState.Proceeding; + } + if (this.transaction instanceof transactions_1.NonInviteServerTransaction) { + return false; // https://tools.ietf.org/html/rfc4320#section-4.1 + } + throw new Error("Unknown transaction type."); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(UserAgentServer.prototype, "redirectable", { + get: function () { + if (this.transaction instanceof transactions_1.InviteServerTransaction) { + return this.transaction.state === transactions_1.TransactionState.Proceeding; + } + if (this.transaction instanceof transactions_1.NonInviteServerTransaction) { + return (this.transaction.state === transactions_1.TransactionState.Trying || + this.transaction.state === transactions_1.TransactionState.Proceeding); + } + throw new Error("Unknown transaction type."); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(UserAgentServer.prototype, "rejectable", { + get: function () { + if (this.transaction instanceof transactions_1.InviteServerTransaction) { + return this.transaction.state === transactions_1.TransactionState.Proceeding; + } + if (this.transaction instanceof transactions_1.NonInviteServerTransaction) { + return (this.transaction.state === transactions_1.TransactionState.Trying || + this.transaction.state === transactions_1.TransactionState.Proceeding); + } + throw new Error("Unknown transaction type."); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(UserAgentServer.prototype, "tryingable", { + get: function () { + if (this.transaction instanceof transactions_1.InviteServerTransaction) { + return this.transaction.state === transactions_1.TransactionState.Proceeding; + } + if (this.transaction instanceof transactions_1.NonInviteServerTransaction) { + return this.transaction.state === transactions_1.TransactionState.Trying; + } + throw new Error("Unknown transaction type."); + }, + enumerable: true, + configurable: true + }); + /** + * When a UAS wishes to construct a response to a request, it follows + * the general procedures detailed in the following subsections. + * Additional behaviors specific to the response code in question, which + * are not detailed in this section, may also be required. + * + * Once all procedures associated with the creation of a response have + * been completed, the UAS hands the response back to the server + * transaction from which it received the request. + * https://tools.ietf.org/html/rfc3261#section-8.2.6 + * @param statusCode Status code to reply with. + * @param options Reply options bucket. + */ + UserAgentServer.prototype.reply = function (options) { + if (!options.toTag && options.statusCode !== 100) { + options.toTag = this.toTag; + } + options.userAgent = options.userAgent || this.core.configuration.userAgentHeaderFieldValue; + var response = messages_1.constructOutgoingResponse(this.message, options); + this.transaction.receiveResponse(options.statusCode, response.message); + return response; + }; + UserAgentServer.prototype.init = function () { + var _this = this; + // We are the transaction user. + var user = { + loggerFactory: this.loggerFactory, + onStateChange: function (newState) { + if (newState === transactions_1.TransactionState.Terminated) { + // Remove the terminated transaction from the core. + _this.core.userAgentServers.delete(userAgentServerId); + _this.dispose(); + } + }, + onTransportError: function (error) { + _this.logger.error(error.message); + if (_this.delegate && _this.delegate.onTransportError) { + _this.delegate.onTransportError(error); + } + else { + _this.logger.error("User agent server response transport error."); + } + } + }; + // Create a new transaction with us as the user. + var transaction = new this.transactionConstructor(this.message, this.core.transport, user); + this._transaction = transaction; + // Add the new transaction to the core. + var userAgentServerId = transaction.id; + this.core.userAgentServers.set(transaction.id, this); + }; + return UserAgentServer; +}()); +exports.UserAgentServer = UserAgentServer; + + +/***/ }), +/* 85 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var transactions_1 = __webpack_require__(52); +var user_agent_client_1 = __webpack_require__(82); +var CancelUserAgentClient = /** @class */ (function (_super) { + __extends(CancelUserAgentClient, _super); + function CancelUserAgentClient(core, message, delegate) { + return _super.call(this, transactions_1.NonInviteClientTransaction, core, message, delegate) || this; + } + return CancelUserAgentClient; +}(user_agent_client_1.UserAgentClient)); +exports.CancelUserAgentClient = CancelUserAgentClient; + + +/***/ }), +/* 86 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var transactions_1 = __webpack_require__(52); +var user_agent_server_1 = __webpack_require__(84); +var InfoUserAgentServer = /** @class */ (function (_super) { + __extends(InfoUserAgentServer, _super); + function InfoUserAgentServer(dialog, message, delegate) { + return _super.call(this, transactions_1.NonInviteServerTransaction, dialog.userAgentCore, message, delegate) || this; + } + return InfoUserAgentServer; +}(user_agent_server_1.UserAgentServer)); +exports.InfoUserAgentServer = InfoUserAgentServer; + + +/***/ }), +/* 87 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var dialogs_1 = __webpack_require__(88); +var transactions_1 = __webpack_require__(52); +var user_agent_client_1 = __webpack_require__(82); +/** + * 13 Initiating a Session + * https://tools.ietf.org/html/rfc3261#section-13 + * 13.1 Overview + * https://tools.ietf.org/html/rfc3261#section-13.1 + * 13.2 UAC Processing + * https://tools.ietf.org/html/rfc3261#section-13.2 + */ +var InviteUserAgentClient = /** @class */ (function (_super) { + __extends(InviteUserAgentClient, _super); + function InviteUserAgentClient(core, message, delegate) { + var _this = _super.call(this, transactions_1.InviteClientTransaction, core, message, delegate) || this; + _this.confirmedDialogAcks = new Map(); + _this.confirmedDialogs = new Map(); + _this.earlyDialogs = new Map(); + _this.delegate = delegate; + return _this; + } + InviteUserAgentClient.prototype.dispose = function () { + // The UAC core considers the INVITE transaction completed 64*T1 seconds + // after the reception of the first 2xx response. At this point all the + // early dialogs that have not transitioned to established dialogs are + // terminated. Once the INVITE transaction is considered completed by + // the UAC core, no more new 2xx responses are expected to arrive. + // + // If, after acknowledging any 2xx response to an INVITE, the UAC does + // not want to continue with that dialog, then the UAC MUST terminate + // the dialog by sending a BYE request as described in Section 15. + // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 + this.earlyDialogs.forEach(function (earlyDialog) { return earlyDialog.dispose(); }); + this.earlyDialogs.clear(); + _super.prototype.dispose.call(this); + }; + /** + * Once the INVITE has been passed to the INVITE client transaction, the + * UAC waits for responses for the INVITE. + * https://tools.ietf.org/html/rfc3261#section-13.2.2 + * @param incomingResponse Incoming response to INVITE request. + */ + InviteUserAgentClient.prototype.receiveResponse = function (message) { + var _this = this; + if (!this.authenticationGuard(message)) { + return; + } + var statusCode = message.statusCode ? message.statusCode.toString() : ""; + if (!statusCode) { + throw new Error("Response status code undefined."); + } + switch (true) { + case /^100$/.test(statusCode): + if (this.delegate && this.delegate.onTrying) { + this.delegate.onTrying({ message: message }); + } + return; + case /^1[0-9]{2}$/.test(statusCode): + // Zero, one or multiple provisional responses may arrive before one or + // more final responses are received. Provisional responses for an + // INVITE request can create "early dialogs". If a provisional response + // has a tag in the To field, and if the dialog ID of the response does + // not match an existing dialog, one is constructed using the procedures + // defined in Section 12.1.2. + // + // The early dialog will only be needed if the UAC needs to send a + // request to its peer within the dialog before the initial INVITE + // transaction completes. Header fields present in a provisional + // response are applicable as long as the dialog is in the early state + // (for example, an Allow header field in a provisional response + // contains the methods that can be used in the dialog while this is in + // the early state). + // https://tools.ietf.org/html/rfc3261#section-13.2.2.1 + { + // Provisional without to tag, no dialog to create. + if (!message.toTag) { + this.logger.warn("Non-100 1xx INVITE response received without a to tag, dropping."); + return; + } + // Compute dialog state. + var dialogState = dialogs_1.Dialog.initialDialogStateForUserAgentClient(this.message, message); + // Have existing early dialog or create a new one. + var earlyDialog = this.earlyDialogs.get(dialogState.id); + if (!earlyDialog) { + var transaction = this.transaction; + if (!(transaction instanceof transactions_1.InviteClientTransaction)) { + throw new Error("Transaction not instance of InviteClientTransaction."); + } + earlyDialog = new dialogs_1.SessionDialog(transaction, this.core, dialogState); + this.earlyDialogs.set(earlyDialog.id, earlyDialog); + } + // Guard against out of order reliable provisional responses. + // Note that this is where the rseq tracking is done. + if (!earlyDialog.reliableSequenceGuard(message)) { + this.logger.warn("1xx INVITE reliable response received out of order, dropping."); + return; + } + // Update dialog signaling state if need be. + earlyDialog.signalingStateTransition(message); + // Pass response to delegate. + var session_1 = earlyDialog; + if (this.delegate && this.delegate.onProgress) { + this.delegate.onProgress({ + message: message, + session: session_1, + prack: function (options) { + var outgoingPrackRequest = session_1.prack(undefined, options); + return outgoingPrackRequest; + } + }); + } + } + return; + case /^2[0-9]{2}$/.test(statusCode): + // Multiple 2xx responses may arrive at the UAC for a single INVITE + // request due to a forking proxy. Each response is distinguished by + // the tag parameter in the To header field, and each represents a + // distinct dialog, with a distinct dialog identifier. + // + // If the dialog identifier in the 2xx response matches the dialog + // identifier of an existing dialog, the dialog MUST be transitioned to + // the "confirmed" state, and the route set for the dialog MUST be + // recomputed based on the 2xx response using the procedures of Section + // 12.2.1.2. Otherwise, a new dialog in the "confirmed" state MUST be + // constructed using the procedures of Section 12.1.2. + // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 + { + // Compute dialog state. + var dialogState = dialogs_1.Dialog.initialDialogStateForUserAgentClient(this.message, message); + // NOTE: Currently our transaction layer is caching the 2xx ACKs and + // handling retransmissions of the ACK which is an approach which is + // not to spec. In any event, this block is intended to provide a to + // spec implementation of ACK retransmissions, but it should not be + // hit currently. + var dialog = this.confirmedDialogs.get(dialogState.id); + if (dialog) { + // Once the ACK has been constructed, the procedures of [4] are used to + // determine the destination address, port and transport. However, the + // request is passed to the transport layer directly for transmission, + // rather than a client transaction. This is because the UAC core + // handles retransmissions of the ACK, not the transaction layer. The + // ACK MUST be passed to the client transport every time a + // retransmission of the 2xx final response that triggered the ACK + // arrives. + // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 + var outgoingAckRequest = this.confirmedDialogAcks.get(dialogState.id); + if (outgoingAckRequest) { + var transaction = this.transaction; + if (!(transaction instanceof transactions_1.InviteClientTransaction)) { + throw new Error("Client transaction not instance of InviteClientTransaction."); + } + transaction.ackResponse(outgoingAckRequest.message); + } + else { + // If still waiting for an ACK, drop the retransmission of the 2xx final response. + } + return; + } + // If the dialog identifier in the 2xx response matches the dialog + // identifier of an existing dialog, the dialog MUST be transitioned to + // the "confirmed" state, and the route set for the dialog MUST be + // recomputed based on the 2xx response using the procedures of Section + // 12.2.1.2. Otherwise, a new dialog in the "confirmed" state MUST be + // constructed using the procedures of Section 12.1.2. + // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 + dialog = this.earlyDialogs.get(dialogState.id); + if (dialog) { + dialog.confirm(); + dialog.recomputeRouteSet(message); + this.earlyDialogs.delete(dialog.id); + this.confirmedDialogs.set(dialog.id, dialog); + } + else { + var transaction = this.transaction; + if (!(transaction instanceof transactions_1.InviteClientTransaction)) { + throw new Error("Transaction not instance of InviteClientTransaction."); + } + dialog = new dialogs_1.SessionDialog(transaction, this.core, dialogState); + this.confirmedDialogs.set(dialog.id, dialog); + } + // Update dialog signaling state if need be. + dialog.signalingStateTransition(message); + // Session Initiated! :) + var session_2 = dialog; + // The UAC core MUST generate an ACK request for each 2xx received from + // the transaction layer. The header fields of the ACK are constructed + // in the same way as for any request sent within a dialog (see Section + // 12) with the exception of the CSeq and the header fields related to + // authentication. The sequence number of the CSeq header field MUST be + // the same as the INVITE being acknowledged, but the CSeq method MUST + // be ACK. The ACK MUST contain the same credentials as the INVITE. If + // the 2xx contains an offer (based on the rules above), the ACK MUST + // carry an answer in its body. If the offer in the 2xx response is not + // acceptable, the UAC core MUST generate a valid answer in the ACK and + // then send a BYE immediately. + // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 + if (this.delegate && this.delegate.onAccept) { + this.delegate.onAccept({ + message: message, + session: session_2, + ack: function (options) { + var outgoingAckRequest = session_2.ack(options); + _this.confirmedDialogAcks.set(session_2.id, outgoingAckRequest); + return outgoingAckRequest; + } + }); + } + else { + var outgoingAckRequest = session_2.ack(); + this.confirmedDialogAcks.set(session_2.id, outgoingAckRequest); + } + } + return; + case /^3[0-9]{2}$/.test(statusCode): + // 12.3 Termination of a Dialog + // + // Independent of the method, if a request outside of a dialog generates + // a non-2xx final response, any early dialogs created through + // provisional responses to that request are terminated. The mechanism + // for terminating confirmed dialogs is method specific. In this + // specification, the BYE method terminates a session and the dialog + // associated with it. See Section 15 for details. + // https://tools.ietf.org/html/rfc3261#section-12.3 + // All early dialogs are considered terminated upon reception of the + // non-2xx final response. + // + // After having received the non-2xx final response the UAC core + // considers the INVITE transaction completed. The INVITE client + // transaction handles the generation of ACKs for the response (see + // Section 17). + // https://tools.ietf.org/html/rfc3261#section-13.2.2.3 + this.earlyDialogs.forEach(function (earlyDialog) { return earlyDialog.dispose(); }); + this.earlyDialogs.clear(); + // A 3xx response may contain one or more Contact header field values + // providing new addresses where the callee might be reachable. + // Depending on the status code of the 3xx response (see Section 21.3), + // the UAC MAY choose to try those new addresses. + // https://tools.ietf.org/html/rfc3261#section-13.2.2.2 + if (this.delegate && this.delegate.onRedirect) { + this.delegate.onRedirect({ message: message }); + } + return; + case /^[4-6][0-9]{2}$/.test(statusCode): + // 12.3 Termination of a Dialog + // + // Independent of the method, if a request outside of a dialog generates + // a non-2xx final response, any early dialogs created through + // provisional responses to that request are terminated. The mechanism + // for terminating confirmed dialogs is method specific. In this + // specification, the BYE method terminates a session and the dialog + // associated with it. See Section 15 for details. + // https://tools.ietf.org/html/rfc3261#section-12.3 + // All early dialogs are considered terminated upon reception of the + // non-2xx final response. + // + // After having received the non-2xx final response the UAC core + // considers the INVITE transaction completed. The INVITE client + // transaction handles the generation of ACKs for the response (see + // Section 17). + // https://tools.ietf.org/html/rfc3261#section-13.2.2.3 + this.earlyDialogs.forEach(function (earlyDialog) { return earlyDialog.dispose(); }); + this.earlyDialogs.clear(); + // A single non-2xx final response may be received for the INVITE. 4xx, + // 5xx and 6xx responses may contain a Contact header field value + // indicating the location where additional information about the error + // can be found. Subsequent final responses (which would only arrive + // under error conditions) MUST be ignored. + // https://tools.ietf.org/html/rfc3261#section-13.2.2.3 + if (this.delegate && this.delegate.onReject) { + this.delegate.onReject({ message: message }); + } + return; + default: + throw new Error("Invalid status code " + statusCode); + } + throw new Error("Executing what should be an unreachable code path receiving " + statusCode + " response."); + }; + return InviteUserAgentClient; +}(user_agent_client_1.UserAgentClient)); +exports.InviteUserAgentClient = InviteUserAgentClient; + + +/***/ }), +/* 88 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +function __export(m) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; +} +Object.defineProperty(exports, "__esModule", { value: true }); +__export(__webpack_require__(89)); +__export(__webpack_require__(90)); +__export(__webpack_require__(100)); + + +/***/ }), +/* 89 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +var Constants_1 = __webpack_require__(3); +var NameAddrHeader_1 = __webpack_require__(9); +/** + * A key concept for a user agent is that of a dialog. A dialog + * represents a peer-to-peer SIP relationship between two user agents + * that persists for some time. The dialog facilitates sequencing of + * messages between the user agents and proper routing of requests + * between both of them. The dialog represents a context in which to + * interpret SIP messages. + * https://tools.ietf.org/html/rfc3261#section-12 + */ +var Dialog = /** @class */ (function () { + /** + * Dialog constructor. + * @param core User agent core. + * @param dialogState Initial dialog state. + */ + function Dialog(core, dialogState) { + this.core = core; + this.dialogState = dialogState; + this.core.dialogs.set(this.id, this); + } + /** + * When a UAC receives a response that establishes a dialog, it + * constructs the state of the dialog. This state MUST be maintained + * for the duration of the dialog. + * https://tools.ietf.org/html/rfc3261#section-12.1.2 + * @param outgoingRequestMessage Outgoing request message for dialog. + * @param incomingResponseMessage Incoming response message creating dialog. + */ + Dialog.initialDialogStateForUserAgentClient = function (outgoingRequestMessage, incomingResponseMessage) { + // If the request was sent over TLS, and the Request-URI contained a + // SIPS URI, the "secure" flag is set to TRUE. + // https://tools.ietf.org/html/rfc3261#section-12.1.2 + var secure = false; // FIXME: Currently no support for TLS. + // The route set MUST be set to the list of URIs in the Record-Route + // header field from the response, taken in reverse order and preserving + // all URI parameters. If no Record-Route header field is present in + // the response, the route set MUST be set to the empty set. This route + // set, even if empty, overrides any pre-existing route set for future + // requests in this dialog. The remote target MUST be set to the URI + // from the Contact header field of the response. + // https://tools.ietf.org/html/rfc3261#section-12.1.2 + var routeSet = incomingResponseMessage.getHeaders("record-route").reverse(); + var contact = incomingResponseMessage.parseHeader("contact"); + if (!contact) { // TODO: Review to make sure this will never happen + throw new Error("Contact undefined."); + } + if (!(contact instanceof NameAddrHeader_1.NameAddrHeader)) { + throw new Error("Contact not instance of NameAddrHeader."); + } + var remoteTarget = contact.uri; + // The local sequence number MUST be set to the value of the sequence + // number in the CSeq header field of the request. The remote sequence + // number MUST be empty (it is established when the remote UA sends a + // request within the dialog). The call identifier component of the + // dialog ID MUST be set to the value of the Call-ID in the request. + // The local tag component of the dialog ID MUST be set to the tag in + // the From field in the request, and the remote tag component of the + // dialog ID MUST be set to the tag in the To field of the response. A + // UAC MUST be prepared to receive a response without a tag in the To + // field, in which case the tag is considered to have a value of null. + // + // This is to maintain backwards compatibility with RFC 2543, which + // did not mandate To tags. + // + // https://tools.ietf.org/html/rfc3261#section-12.1.2 + var localSequenceNumber = outgoingRequestMessage.cseq; + var remoteSequenceNumber = undefined; + var callId = outgoingRequestMessage.callId; + var localTag = outgoingRequestMessage.fromTag; + var remoteTag = incomingResponseMessage.toTag; + if (!callId) { // TODO: Review to make sure this will never happen + throw new Error("Call id undefined."); + } + if (!localTag) { // TODO: Review to make sure this will never happen + throw new Error("From tag undefined."); + } + if (!remoteTag) { // TODO: Review to make sure this will never happen + throw new Error("To tag undefined."); // FIXME: No backwards compatibility with RFC 2543 + } + // The remote URI MUST be set to the URI in the To field, and the local + // URI MUST be set to the URI in the From field. + // https://tools.ietf.org/html/rfc3261#section-12.1.2 + if (!outgoingRequestMessage.from) { // TODO: Review to make sure this will never happen + throw new Error("From undefined."); + } + if (!outgoingRequestMessage.to) { // TODO: Review to make sure this will never happen + throw new Error("To undefined."); + } + var localURI = outgoingRequestMessage.from.uri; + var remoteURI = outgoingRequestMessage.to.uri; + // A dialog can also be in the "early" state, which occurs when it is + // created with a provisional response, and then transition to the + // "confirmed" state when a 2xx final response arrives. + // https://tools.ietf.org/html/rfc3261#section-12 + if (!incomingResponseMessage.statusCode) { + throw new Error("Incoming response status code undefined."); + } + var early = incomingResponseMessage.statusCode < 200 ? true : false; + var dialogState = { + id: callId + localTag + remoteTag, + early: early, + callId: callId, + localTag: localTag, + remoteTag: remoteTag, + localSequenceNumber: localSequenceNumber, + remoteSequenceNumber: remoteSequenceNumber, + localURI: localURI, + remoteURI: remoteURI, + remoteTarget: remoteTarget, + routeSet: routeSet, + secure: secure + }; + return dialogState; + }; + /** + * The UAS then constructs the state of the dialog. This state MUST be + * maintained for the duration of the dialog. + * https://tools.ietf.org/html/rfc3261#section-12.1.1 + * @param incomingRequestMessage Incoming request message creating dialog. + * @param toTag Tag in the To field in the response to the incoming request. + */ + Dialog.initialDialogStateForUserAgentServer = function (incomingRequestMessage, toTag, early) { + if (early === void 0) { early = false; } + // If the request arrived over TLS, and the Request-URI contained a SIPS + // URI, the "secure" flag is set to TRUE. + // https://tools.ietf.org/html/rfc3261#section-12.1.1 + var secure = false; // FIXME: Currently no support for TLS. + // The route set MUST be set to the list of URIs in the Record-Route + // header field from the request, taken in order and preserving all URI + // parameters. If no Record-Route header field is present in the + // request, the route set MUST be set to the empty set. This route set, + // even if empty, overrides any pre-existing route set for future + // requests in this dialog. The remote target MUST be set to the URI + // from the Contact header field of the request. + // https://tools.ietf.org/html/rfc3261#section-12.1.1 + var routeSet = incomingRequestMessage.getHeaders("record-route"); + var contact = incomingRequestMessage.parseHeader("contact"); + if (!contact) { // TODO: Review to make sure this will never happen + throw new Error("Contact undefined."); + } + if (!(contact instanceof NameAddrHeader_1.NameAddrHeader)) { + throw new Error("Contact not instance of NameAddrHeader."); + } + var remoteTarget = contact.uri; + // The remote sequence number MUST be set to the value of the sequence + // number in the CSeq header field of the request. The local sequence + // number MUST be empty. The call identifier component of the dialog ID + // MUST be set to the value of the Call-ID in the request. The local + // tag component of the dialog ID MUST be set to the tag in the To field + // in the response to the request (which always includes a tag), and the + // remote tag component of the dialog ID MUST be set to the tag from the + // From field in the request. A UAS MUST be prepared to receive a + // request without a tag in the From field, in which case the tag is + // considered to have a value of null. + // + // This is to maintain backwards compatibility with RFC 2543, which + // did not mandate From tags. + // + // https://tools.ietf.org/html/rfc3261#section-12.1.1 + var remoteSequenceNumber = incomingRequestMessage.cseq; + var localSequenceNumber = undefined; + var callId = incomingRequestMessage.callId; + var localTag = toTag; + var remoteTag = incomingRequestMessage.fromTag; + // The remote URI MUST be set to the URI in the From field, and the + // local URI MUST be set to the URI in the To field. + // https://tools.ietf.org/html/rfc3261#section-12.1.1 + var remoteURI = incomingRequestMessage.from.uri; + var localURI = incomingRequestMessage.to.uri; + var dialogState = { + id: callId + localTag + remoteTag, + early: early, + callId: callId, + localTag: localTag, + remoteTag: remoteTag, + localSequenceNumber: localSequenceNumber, + remoteSequenceNumber: remoteSequenceNumber, + localURI: localURI, + remoteURI: remoteURI, + remoteTarget: remoteTarget, + routeSet: routeSet, + secure: secure + }; + return dialogState; + }; + /** Destructor. */ + Dialog.prototype.dispose = function () { + this.core.dialogs.delete(this.id); + }; + Object.defineProperty(Dialog.prototype, "id", { + /** + * A dialog is identified at each UA with a dialog ID, which consists of + * a Call-ID value, a local tag and a remote tag. The dialog ID at each + * UA involved in the dialog is not the same. Specifically, the local + * tag at one UA is identical to the remote tag at the peer UA. The + * tags are opaque tokens that facilitate the generation of unique + * dialog IDs. + * https://tools.ietf.org/html/rfc3261#section-12 + */ + get: function () { + return this.dialogState.id; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Dialog.prototype, "early", { + /** + * A dialog can also be in the "early" state, which occurs when it is + * created with a provisional response, and then it transition to the + * "confirmed" state when a 2xx final response received or is sent. + * + * Note: RFC 3261 is concise on when a dialog is "confirmed", but it + * can be a point of confusion if an INVITE dialog is "confirmed" after + * a 2xx is sent or after receiving the ACK for the 2xx response. + * With careful reading it can be inferred a dialog is always is + * "confirmed" when the 2xx is sent (regardless of type of dialog). + * However a INVITE dialog does have additional considerations + * when it is confirmed but an ACK has not yet been received (in + * particular with regard to a callee sending BYE requests). + */ + get: function () { + return this.dialogState.early; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Dialog.prototype, "callId", { + /** Call identifier component of the dialog id. */ + get: function () { + return this.dialogState.callId; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Dialog.prototype, "localTag", { + /** Local tag component of the dialog id. */ + get: function () { + return this.dialogState.localTag; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Dialog.prototype, "remoteTag", { + /** Remote tag component of the dialog id. */ + get: function () { + return this.dialogState.remoteTag; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Dialog.prototype, "localSequenceNumber", { + /** Local sequence number (used to order requests from the UA to its peer). */ + get: function () { + return this.dialogState.localSequenceNumber; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Dialog.prototype, "remoteSequenceNumber", { + /** Remote sequence number (used to order requests from its peer to the UA). */ + get: function () { + return this.dialogState.remoteSequenceNumber; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Dialog.prototype, "localURI", { + /** Local URI. */ + get: function () { + return this.dialogState.localURI; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Dialog.prototype, "remoteURI", { + /** Remote URI. */ + get: function () { + return this.dialogState.remoteURI; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Dialog.prototype, "remoteTarget", { + /** Remote target. */ + get: function () { + return this.dialogState.remoteTarget; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Dialog.prototype, "routeSet", { + /** + * Route set, which is an ordered list of URIs. The route set is the + * list of servers that need to be traversed to send a request to the peer. + */ + get: function () { + return this.dialogState.routeSet; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Dialog.prototype, "secure", { + /** + * If the request was sent over TLS, and the Request-URI contained + * a SIPS URI, the "secure" flag is set to true. *NOT IMPLEMENTED* + */ + get: function () { + return this.dialogState.secure; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Dialog.prototype, "userAgentCore", { + /** The user agent core servicing this dialog. */ + get: function () { + return this.core; + }, + enumerable: true, + configurable: true + }); + /** Confirm the dialog. Only matters if dialog is currently early. */ + Dialog.prototype.confirm = function () { + this.dialogState.early = false; + }; + /** + * Requests sent within a dialog, as any other requests, are atomic. If + * a particular request is accepted by the UAS, all the state changes + * associated with it are performed. If the request is rejected, none + * of the state changes are performed. + * + * Note that some requests, such as INVITEs, affect several pieces of + * state. + * + * https://tools.ietf.org/html/rfc3261#section-12.2.2 + * @param message Incoming request message within this dialog. + */ + Dialog.prototype.receiveRequest = function (message) { + // ACK guard. + // By convention, the handling of ACKs is the responsibility + // the particular dialog implementation. For example, see SessionDialog. + // Furthermore, ACKs have same sequence number as the associated INVITE. + if (message.method === Constants_1.C.ACK) { + return; + } + // If the remote sequence number was not empty, but the sequence number + // of the request is lower than the remote sequence number, the request + // is out of order and MUST be rejected with a 500 (Server Internal + // Error) response. If the remote sequence number was not empty, and + // the sequence number of the request is greater than the remote + // sequence number, the request is in order. It is possible for the + // CSeq sequence number to be higher than the remote sequence number by + // more than one. This is not an error condition, and a UAS SHOULD be + // prepared to receive and process requests with CSeq values more than + // one higher than the previous received request. The UAS MUST then set + // the remote sequence number to the value of the sequence number in the + // CSeq header field value in the request. + // + // If a proxy challenges a request generated by the UAC, the UAC has + // to resubmit the request with credentials. The resubmitted request + // will have a new CSeq number. The UAS will never see the first + // request, and thus, it will notice a gap in the CSeq number space. + // Such a gap does not represent any error condition. + // + // https://tools.ietf.org/html/rfc3261#section-12.2.2 + if (this.remoteSequenceNumber) { + if (message.cseq <= this.remoteSequenceNumber) { + throw new Error("Out of sequence in dialog request. Did you forget to call sequenceGuard()?"); + } + this.dialogState.remoteSequenceNumber = message.cseq; + } + // If the remote sequence number is empty, it MUST be set to the value + // of the sequence number in the CSeq header field value in the request. + // https://tools.ietf.org/html/rfc3261#section-12.2.2 + if (!this.remoteSequenceNumber) { + this.dialogState.remoteSequenceNumber = message.cseq; + } + // When a UAS receives a target refresh request, it MUST replace the + // dialog's remote target URI with the URI from the Contact header field + // in that request, if present. + // https://tools.ietf.org/html/rfc3261#section-12.2.2 + // Note: "target refresh request" processing delegated to sub-class. + }; + /** + * If the dialog identifier in the 2xx response matches the dialog + * identifier of an existing dialog, the dialog MUST be transitioned to + * the "confirmed" state, and the route set for the dialog MUST be + * recomputed based on the 2xx response using the procedures of Section + * 12.2.1.2. Otherwise, a new dialog in the "confirmed" state MUST be + * constructed using the procedures of Section 12.1.2. + * + * Note that the only piece of state that is recomputed is the route + * set. Other pieces of state such as the highest sequence numbers + * (remote and local) sent within the dialog are not recomputed. The + * route set only is recomputed for backwards compatibility. RFC + * 2543 did not mandate mirroring of the Record-Route header field in + * a 1xx, only 2xx. However, we cannot update the entire state of + * the dialog, since mid-dialog requests may have been sent within + * the early dialog, modifying the sequence numbers, for example. + * + * https://tools.ietf.org/html/rfc3261#section-13.2.2.4 + */ + Dialog.prototype.recomputeRouteSet = function (message) { + this.dialogState.routeSet = message.getHeaders("record-route").reverse(); + }; + /** + * A request within a dialog is constructed by using many of the + * components of the state stored as part of the dialog. + * https://tools.ietf.org/html/rfc3261#section-12.2.1.1 + * @param method Outgoing request method. + */ + Dialog.prototype.createOutgoingRequestMessage = function (method, options) { + // The URI in the To field of the request MUST be set to the remote URI + // from the dialog state. The tag in the To header field of the request + // MUST be set to the remote tag of the dialog ID. The From URI of the + // request MUST be set to the local URI from the dialog state. The tag + // in the From header field of the request MUST be set to the local tag + // of the dialog ID. If the value of the remote or local tags is null, + // the tag parameter MUST be omitted from the To or From header fields, + // respectively. + // + // Usage of the URI from the To and From fields in the original + // request within subsequent requests is done for backwards + // compatibility with RFC 2543, which used the URI for dialog + // identification. In this specification, only the tags are used for + // dialog identification. It is expected that mandatory reflection + // of the original To and From URI in mid-dialog requests will be + // deprecated in a subsequent revision of this specification. + // https://tools.ietf.org/html/rfc3261#section-12.2.1.1 + var toUri = this.remoteURI; + var toTag = this.remoteTag; + var fromUri = this.localURI; + var fromTag = this.localTag; + // The Call-ID of the request MUST be set to the Call-ID of the dialog. + // Requests within a dialog MUST contain strictly monotonically + // increasing and contiguous CSeq sequence numbers (increasing-by-one) + // in each direction (excepting ACK and CANCEL of course, whose numbers + // equal the requests being acknowledged or cancelled). Therefore, if + // the local sequence number is not empty, the value of the local + // sequence number MUST be incremented by one, and this value MUST be + // placed into the CSeq header field. If the local sequence number is + // empty, an initial value MUST be chosen using the guidelines of + // Section 8.1.1.5. The method field in the CSeq header field value + // MUST match the method of the request. + // https://tools.ietf.org/html/rfc3261#section-12.2.1.1 + var callId = this.callId; + var cseq; + if (options && options.cseq) { + cseq = options.cseq; + } + else if (!this.dialogState.localSequenceNumber) { + cseq = this.dialogState.localSequenceNumber = 1; // https://tools.ietf.org/html/rfc3261#section-8.1.1.5 + } + else { + cseq = this.dialogState.localSequenceNumber += 1; + } + // The UAC uses the remote target and route set to build the Request-URI + // and Route header field of the request. + // + // If the route set is empty, the UAC MUST place the remote target URI + // into the Request-URI. The UAC MUST NOT add a Route header field to + // the request. + // + // If the route set is not empty, and the first URI in the route set + // contains the lr parameter (see Section 19.1.1), the UAC MUST place + // the remote target URI into the Request-URI and MUST include a Route + // header field containing the route set values in order, including all + // parameters. + // + // If the route set is not empty, and its first URI does not contain the + // lr parameter, the UAC MUST place the first URI from the route set + // into the Request-URI, stripping any parameters that are not allowed + // in a Request-URI. The UAC MUST add a Route header field containing + // the remainder of the route set values in order, including all + // parameters. The UAC MUST then place the remote target URI into the + // Route header field as the last value. + // https://tools.ietf.org/html/rfc3261#section-12.2.1.1 + // The lr parameter, when present, indicates that the element + // responsible for this resource implements the routing mechanisms + // specified in this document. This parameter will be used in the + // URIs proxies place into Record-Route header field values, and + // may appear in the URIs in a pre-existing route set. + // + // This parameter is used to achieve backwards compatibility with + // systems implementing the strict-routing mechanisms of RFC 2543 + // and the rfc2543bis drafts up to bis-05. An element preparing + // to send a request based on a URI not containing this parameter + // can assume the receiving element implements strict-routing and + // reformat the message to preserve the information in the + // Request-URI. + // https://tools.ietf.org/html/rfc3261#section-19.1.1 + // NOTE: Not backwards compatible with RFC 2543 (no support for strict-routing). + var ruri = this.remoteTarget; + var routeSet = this.routeSet; + var extraHeaders = options && options.extraHeaders; + var body = options && options.body ? + { contentType: options.body.contentType, body: options.body.content } : + undefined; + // The relative order of header fields with different field names is not + // significant. However, it is RECOMMENDED that header fields which are + // needed for proxy processing (Via, Route, Record-Route, Proxy-Require, + // Max-Forwards, and Proxy-Authorization, for example) appear towards + // the top of the message to facilitate rapid parsing. + // https://tools.ietf.org/html/rfc3261#section-7.3.1 + var message = this.core.configuration.outgoingRequestMessageFactory(method, ruri, { + callId: callId, + cseq: cseq, + fromUri: fromUri, + fromTag: fromTag, + toUri: toUri, + toTag: toTag, + routeSet: routeSet + }, extraHeaders, body); + return message; + }; + /** + * If the remote sequence number was not empty, but the sequence number + * of the request is lower than the remote sequence number, the request + * is out of order and MUST be rejected with a 500 (Server Internal + * Error) response. + * https://tools.ietf.org/html/rfc3261#section-12.2.2 + * @param request Incoming request to guard. + * @returns True if the program execution is to continue in the branch in question. + * Otherwise a 500 Server Internal Error was stateless sent and request processing must stop. + */ + Dialog.prototype.sequenceGuard = function (message) { + // ACK guard. + // By convention, handling of unexpected ACKs is responsibility + // the particular dialog implementation. For example, see SessionDialog. + // Furthermore, we cannot reply to an "out of sequence" ACK. + if (message.method === Constants_1.C.ACK) { + return true; + } + // Note: We are rejecting on "less than or equal to" the remote + // sequence number (excepting ACK whose numbers equal the requests + // being acknowledged or cancelled), which is the correct thing to + // do in our case. The only time a request with the same sequence number + // will show up here if is a) it is a very late retransmission of a + // request we already handled or b) it is a different request with the + // same sequence number which would be violation of the standard. + // Request retransmissions are absorbed by the transaction layer, + // so any request with a duplicate sequence number getting here + // would have to be a retransmission after the transaction terminated + // or a broken request (with unique via branch value). + // Requests within a dialog MUST contain strictly monotonically + // increasing and contiguous CSeq sequence numbers (increasing-by-one) + // in each direction (excepting ACK and CANCEL of course, whose numbers + // equal the requests being acknowledged or cancelled). Therefore, if + // the local sequence number is not empty, the value of the local + // sequence number MUST be incremented by one, and this value MUST be + // placed into the CSeq header field. + // https://tools.ietf.org/html/rfc3261#section-12.2.1.1 + if (this.remoteSequenceNumber && message.cseq <= this.remoteSequenceNumber) { + this.core.replyStateless(message, { statusCode: 500 }); + return false; + } + return true; + }; + return Dialog; +}()); +exports.Dialog = Dialog; + + +/***/ }), +/* 90 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Constants_1 = __webpack_require__(3); +var NameAddrHeader_1 = __webpack_require__(9); +var SIPMessage_1 = __webpack_require__(6); +var Timers_1 = __webpack_require__(56); +var messages_1 = __webpack_require__(63); +var session_1 = __webpack_require__(68); +var transactions_1 = __webpack_require__(52); +var bye_user_agent_client_1 = __webpack_require__(81); +var bye_user_agent_server_1 = __webpack_require__(83); +var info_user_agent_client_1 = __webpack_require__(91); +var info_user_agent_server_1 = __webpack_require__(86); +var notify_user_agent_client_1 = __webpack_require__(92); +var notify_user_agent_server_1 = __webpack_require__(93); +var prack_user_agent_client_1 = __webpack_require__(94); +var prack_user_agent_server_1 = __webpack_require__(95); +var re_invite_user_agent_client_1 = __webpack_require__(96); +var re_invite_user_agent_server_1 = __webpack_require__(97); +var refer_user_agent_client_1 = __webpack_require__(98); +var refer_user_agent_server_1 = __webpack_require__(99); +var dialog_1 = __webpack_require__(89); +var SessionDialog = /** @class */ (function (_super) { + __extends(SessionDialog, _super); + function SessionDialog(initialTransaction, core, state, delegate) { + var _this = _super.call(this, core, state) || this; + _this.initialTransaction = initialTransaction; + /** The state of the offer/answer exchange. */ + _this._signalingState = session_1.SignalingState.Initial; + /** True if waiting for an ACK to the initial transaction 2xx (UAS only). */ + _this.ackWait = false; + _this.delegate = delegate; + if (initialTransaction instanceof transactions_1.InviteServerTransaction) { + // If we're created by an invite server transaction, we're + // going to be waiting for an ACK if are to be confirmed. + _this.ackWait = true; + } + // If we're confirmed upon creation start the retransmitting whatever + // the 2xx final response was that confirmed us into existence. + if (!_this.early) { + _this.start2xxRetransmissionTimer(); + } + _this.signalingStateTransition(initialTransaction.request); + _this.logger = core.loggerFactory.getLogger("sip.invite-dialog"); + _this.logger.log("INVITE dialog " + _this.id + " constructed"); + return _this; + } + SessionDialog.prototype.dispose = function () { + _super.prototype.dispose.call(this); + this._signalingState = session_1.SignalingState.Closed; + this._offer = undefined; + this._answer = undefined; + if (this.invite2xxTimer) { + clearTimeout(this.invite2xxTimer); + this.invite2xxTimer = undefined; + } + // The UAS MUST still respond to any pending requests received for that + // dialog. It is RECOMMENDED that a 487 (Request Terminated) response + // be generated to those pending requests. + // https://tools.ietf.org/html/rfc3261#section-15.1.2 + // TODO: + // this.userAgentServers.forEach((uas) => uas.reply(487)); + this.logger.log("INVITE dialog " + this.id + " destroyed"); + }; + Object.defineProperty(SessionDialog.prototype, "sessionState", { + // FIXME: Need real state machine + get: function () { + if (this.early) { + return session_1.SessionState.Early; + } + else if (this.ackWait) { + return session_1.SessionState.AckWait; + } + else if (this._signalingState === session_1.SignalingState.Closed) { + return session_1.SessionState.Terminated; + } + else { + return session_1.SessionState.Confirmed; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SessionDialog.prototype, "signalingState", { + /** The state of the offer/answer exchange. */ + get: function () { + return this._signalingState; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SessionDialog.prototype, "offer", { + /** The current offer. Undefined unless signaling state HaveLocalOffer, HaveRemoteOffer, of Stable. */ + get: function () { + return this._offer; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SessionDialog.prototype, "answer", { + /** The current answer. Undefined unless signaling state Stable. */ + get: function () { + return this._answer; + }, + enumerable: true, + configurable: true + }); + /** Confirm the dialog. Only matters if dialog is currently early. */ + SessionDialog.prototype.confirm = function () { + // When we're confirmed start the retransmitting whatever + // the 2xx final response that may have confirmed us. + if (this.early) { + this.start2xxRetransmissionTimer(); + } + _super.prototype.confirm.call(this); + }; + /** Re-confirm the dialog. Only matters if handling re-INVITE request. */ + SessionDialog.prototype.reConfirm = function () { + // When we're confirmed start the retransmitting whatever + // the 2xx final response that may have confirmed us. + if (this.reinviteUserAgentServer) { + this.startReInvite2xxRetransmissionTimer(); + } + }; + /** + * The UAC core MUST generate an ACK request for each 2xx received from + * the transaction layer. The header fields of the ACK are constructed + * in the same way as for any request sent within a dialog (see Section + * 12) with the exception of the CSeq and the header fields related to + * authentication. The sequence number of the CSeq header field MUST be + * the same as the INVITE being acknowledged, but the CSeq method MUST + * be ACK. The ACK MUST contain the same credentials as the INVITE. If + * the 2xx contains an offer (based on the rules above), the ACK MUST + * carry an answer in its body. If the offer in the 2xx response is not + * acceptable, the UAC core MUST generate a valid answer in the ACK and + * then send a BYE immediately. + * https://tools.ietf.org/html/rfc3261#section-13.2.2.4 + * @param options ACK options bucket. + */ + SessionDialog.prototype.ack = function (options) { + if (options === void 0) { options = {}; } + this.logger.log("INVITE dialog " + this.id + " sending ACK request"); + var transaction; + if (this.reinviteUserAgentClient) { + // We're sending ACK for a re-INVITE + if (!(this.reinviteUserAgentClient.transaction instanceof transactions_1.InviteClientTransaction)) { + throw new Error("Transaction not instance of InviteClientTransaction."); + } + transaction = this.reinviteUserAgentClient.transaction; + this.reinviteUserAgentClient = undefined; + } + else { + // We're sending ACK for the initial INVITE + if (!(this.initialTransaction instanceof transactions_1.InviteClientTransaction)) { + throw new Error("Initial transaction not instance of InviteClientTransaction."); + } + transaction = this.initialTransaction; + } + options.cseq = transaction.request.cseq; // ACK cseq is INVITE cseq + var message = this.createOutgoingRequestMessage(Constants_1.C.ACK, options); + transaction.ackResponse(message); // See InviteClientTransaction for details. + this.signalingStateTransition(message); + return { message: message }; + }; + /** + * Terminating a Session + * + * This section describes the procedures for terminating a session + * established by SIP. The state of the session and the state of the + * dialog are very closely related. When a session is initiated with an + * INVITE, each 1xx or 2xx response from a distinct UAS creates a + * dialog, and if that response completes the offer/answer exchange, it + * also creates a session. As a result, each session is "associated" + * with a single dialog - the one which resulted in its creation. If an + * initial INVITE generates a non-2xx final response, that terminates + * all sessions (if any) and all dialogs (if any) that were created + * through responses to the request. By virtue of completing the + * transaction, a non-2xx final response also prevents further sessions + * from being created as a result of the INVITE. The BYE request is + * used to terminate a specific session or attempted session. In this + * case, the specific session is the one with the peer UA on the other + * side of the dialog. When a BYE is received on a dialog, any session + * associated with that dialog SHOULD terminate. A UA MUST NOT send a + * BYE outside of a dialog. The caller's UA MAY send a BYE for either + * confirmed or early dialogs, and the callee's UA MAY send a BYE on + * confirmed dialogs, but MUST NOT send a BYE on early dialogs. + * + * However, the callee's UA MUST NOT send a BYE on a confirmed dialog + * until it has received an ACK for its 2xx response or until the server + * transaction times out. If no SIP extensions have defined other + * application layer states associated with the dialog, the BYE also + * terminates the dialog. + * + * https://tools.ietf.org/html/rfc3261#section-15 + * FIXME: Make these proper Exceptions... + * @param options BYE options bucket. + * @throws {Error} If callee's UA attempts a BYE on an early dialog. + * @throws {Error} If callee's UA attempts a BYE on a confirmed dialog + * while it's waiting on the ACK for its 2xx response. + */ + SessionDialog.prototype.bye = function (delegate, options) { + this.logger.log("INVITE dialog " + this.id + " sending BYE request"); + // The caller's UA MAY send a BYE for either + // confirmed or early dialogs, and the callee's UA MAY send a BYE on + // confirmed dialogs, but MUST NOT send a BYE on early dialogs. + // + // However, the callee's UA MUST NOT send a BYE on a confirmed dialog + // until it has received an ACK for its 2xx response or until the server + // transaction times out. + // https://tools.ietf.org/html/rfc3261#section-15 + if (this.initialTransaction instanceof transactions_1.InviteServerTransaction) { + if (this.early) { + // FIXME: TODO: This should throw a proper exception. + throw new Error("UAS MUST NOT send a BYE on early dialogs."); + } + if (this.ackWait && this.initialTransaction.state !== transactions_1.TransactionState.Terminated) { + // FIXME: TODO: This should throw a proper exception. + throw new Error("UAS MUST NOT send a BYE on a confirmed dialog " + + "until it has received an ACK for its 2xx response " + + "or until the server transaction times out."); + } + } + // A BYE request is constructed as would any other request within a + // dialog, as described in Section 12. + // + // Once the BYE is constructed, the UAC core creates a new non-INVITE + // client transaction, and passes it the BYE request. The UAC MUST + // consider the session terminated (and therefore stop sending or + // listening for media) as soon as the BYE request is passed to the + // client transaction. If the response for the BYE is a 481 + // (Call/Transaction Does Not Exist) or a 408 (Request Timeout) or no + // response at all is received for the BYE (that is, a timeout is + // returned by the client transaction), the UAC MUST consider the + // session and the dialog terminated. + // https://tools.ietf.org/html/rfc3261#section-15.1.1 + return new bye_user_agent_client_1.ByeUserAgentClient(this, delegate, options); + }; + /** + * An INFO request can be associated with an Info Package (see + * Section 5), or associated with a legacy INFO usage (see Section 2). + * + * The construction of the INFO request is the same as any other + * non-target refresh request within an existing invite dialog usage as + * described in Section 12.2 of RFC 3261. + * https://tools.ietf.org/html/rfc6086#section-4.2.1 + * @param options Options bucket. + */ + SessionDialog.prototype.info = function (delegate, options) { + this.logger.log("INVITE dialog " + this.id + " sending INFO request"); + if (this.early) { + // FIXME: TODO: This should throw a proper exception. + throw new Error("Dialog not confirmed."); + } + return new info_user_agent_client_1.InfoUserAgentClient(this, delegate, options); + }; + /** + * Modifying an Existing Session + * + * A successful INVITE request (see Section 13) establishes both a + * dialog between two user agents and a session using the offer-answer + * model. Section 12 explains how to modify an existing dialog using a + * target refresh request (for example, changing the remote target URI + * of the dialog). This section describes how to modify the actual + * session. This modification can involve changing addresses or ports, + * adding a media stream, deleting a media stream, and so on. This is + * accomplished by sending a new INVITE request within the same dialog + * that established the session. An INVITE request sent within an + * existing dialog is known as a re-INVITE. + * + * Note that a single re-INVITE can modify the dialog and the + * parameters of the session at the same time. + * + * Either the caller or callee can modify an existing session. + * https://tools.ietf.org/html/rfc3261#section-14 + * @param options Options bucket + */ + SessionDialog.prototype.invite = function (delegate, options) { + this.logger.log("INVITE dialog " + this.id + " sending INVITE request"); + if (this.early) { + // FIXME: TODO: This should throw a proper exception. + throw new Error("Dialog not confirmed."); + } + // Note that a UAC MUST NOT initiate a new INVITE transaction within a + // dialog while another INVITE transaction is in progress in either + // direction. + // + // 1. If there is an ongoing INVITE client transaction, the TU MUST + // wait until the transaction reaches the completed or terminated + // state before initiating the new INVITE. + // + // 2. If there is an ongoing INVITE server transaction, the TU MUST + // wait until the transaction reaches the confirmed or terminated + // state before initiating the new INVITE. + // + // However, a UA MAY initiate a regular transaction while an INVITE + // transaction is in progress. A UA MAY also initiate an INVITE + // transaction while a regular transaction is in progress. + // https://tools.ietf.org/html/rfc3261#section-14.1 + if (this.reinviteUserAgentClient) { + // FIXME: TODO: This should throw a proper exception. + throw new Error("There is an ongoing re-INVITE client transaction."); + } + if (this.reinviteUserAgentServer) { + // FIXME: TODO: This should throw a proper exception. + throw new Error("There is an ongoing re-INVITE server transaction."); + } + return new re_invite_user_agent_client_1.ReInviteUserAgentClient(this, delegate, options); + }; + /** + * The NOTIFY mechanism defined in [2] MUST be used to inform the agent + * sending the REFER of the status of the reference. + * https://tools.ietf.org/html/rfc3515#section-2.4.4 + * @param options Options bucket. + */ + SessionDialog.prototype.notify = function (delegate, options) { + this.logger.log("INVITE dialog " + this.id + " sending NOTIFY request"); + if (this.early) { + // FIXME: TODO: This should throw a proper exception. + throw new Error("Dialog not confirmed."); + } + return new notify_user_agent_client_1.NotifyUserAgentClient(this, delegate, options); + }; + /** + * Assuming the response is to be transmitted reliably, the UAC MUST + * create a new request with method PRACK. This request is sent within + * the dialog associated with the provisional response (indeed, the + * provisional response may have created the dialog). PRACK requests + * MAY contain bodies, which are interpreted according to their type and + * disposition. + * https://tools.ietf.org/html/rfc3262#section-4 + * @param options Options bucket. + */ + SessionDialog.prototype.prack = function (delegate, options) { + this.logger.log("INVITE dialog " + this.id + " sending PRACK request"); + return new prack_user_agent_client_1.PrackUserAgentClient(this, delegate, options); + }; + /** + * REFER is a SIP request and is constructed as defined in [1]. A REFER + * request MUST contain exactly one Refer-To header field value. + * https://tools.ietf.org/html/rfc3515#section-2.4.1 + * @param options Options bucket. + */ + SessionDialog.prototype.refer = function (delegate, options) { + this.logger.log("INVITE dialog " + this.id + " sending REFER request"); + if (this.early) { + // FIXME: TODO: This should throw a proper exception. + throw new Error("Dialog not confirmed."); + } + // FIXME: TODO: Validate Refer-To header field value. + return new refer_user_agent_client_1.ReferUserAgentClient(this, delegate, options); + }; + /** + * Requests sent within a dialog, as any other requests, are atomic. If + * a particular request is accepted by the UAS, all the state changes + * associated with it are performed. If the request is rejected, none + * of the state changes are performed. + * https://tools.ietf.org/html/rfc3261#section-12.2.2 + * @param message Incoming request message within this dialog. + */ + SessionDialog.prototype.receiveRequest = function (message) { + this.logger.log("INVITE dialog " + this.id + " received " + message.method + " request"); + // Response retransmissions cease when an ACK request for the + // response is received. This is independent of whatever transport + // protocols are used to send the response. + // https://tools.ietf.org/html/rfc6026#section-8.1 + if (message.method === Constants_1.C.ACK) { + // If ackWait is true, then this is the ACK to the initial INVITE, + // otherwise this is an ACK to an in dialog INVITE. In either case, + // guard to make sure the sequence number of the ACK matches the INVITE. + if (this.ackWait) { + if (this.initialTransaction instanceof transactions_1.InviteClientTransaction) { + this.logger.warn("INVITE dialog " + this.id + " received unexpected " + message.method + " request, dropping."); + return; + } + if (this.initialTransaction.request.cseq !== message.cseq) { + this.logger.warn("INVITE dialog " + this.id + " received unexpected " + message.method + " request, dropping."); + return; + } + this.ackWait = false; + } + else { + if (!this.reinviteUserAgentServer) { + this.logger.warn("INVITE dialog " + this.id + " received unexpected " + message.method + " request, dropping."); + return; + } + if (this.reinviteUserAgentServer.transaction.request.cseq !== message.cseq) { + this.logger.warn("INVITE dialog " + this.id + " received unexpected " + message.method + " request, dropping."); + return; + } + this.reinviteUserAgentServer = undefined; + } + this.signalingStateTransition(message); + if (this.delegate && this.delegate.onAck) { + this.delegate.onAck({ message: message }); + } + return; + } + // Request within a dialog out of sequence guard. + // https://tools.ietf.org/html/rfc3261#section-12.2.2 + if (!this.sequenceGuard(message)) { + this.logger.log("INVITE dialog " + this.id + " rejected out of order " + message.method + " request."); + return; + } + if (message.method === Constants_1.C.INVITE) { + // A UAS that receives a second INVITE before it sends the final + // response to a first INVITE with a lower CSeq sequence number on the + // same dialog MUST return a 500 (Server Internal Error) response to the + // second INVITE and MUST include a Retry-After header field with a + // randomly chosen value of between 0 and 10 seconds. + // https://tools.ietf.org/html/rfc3261#section-14.2 + if (this.reinviteUserAgentServer) { + // https://tools.ietf.org/html/rfc3261#section-20.33 + var retryAfter = Math.floor((Math.random() * 10)) + 1; + var extraHeaders = ["Retry-After: " + retryAfter]; + this.core.replyStateless(message, { statusCode: 500, extraHeaders: extraHeaders }); + return; + } + // A UAS that receives an INVITE on a dialog while an INVITE it had sent + // on that dialog is in progress MUST return a 491 (Request Pending) + // response to the received INVITE. + // https://tools.ietf.org/html/rfc3261#section-14.2 + if (this.reinviteUserAgentClient) { + this.core.replyStateless(message, { statusCode: 491 }); + return; + } + } + // Request within a dialog common processing. + // https://tools.ietf.org/html/rfc3261#section-12.2.2 + _super.prototype.receiveRequest.call(this, message); + // Requests within a dialog MAY contain Record-Route and Contact header + // fields. However, these requests do not cause the dialog's route set + // to be modified, although they may modify the remote target URI. + // Specifically, requests that are not target refresh requests do not + // modify the dialog's remote target URI, and requests that are target + // refresh requests do. For dialogs that have been established with an + // INVITE, the only target refresh request defined is re-INVITE (see + // Section 14). Other extensions may define different target refresh + // requests for dialogs established in other ways. + // + // Note that an ACK is NOT a target refresh request. + // + // Target refresh requests only update the dialog's remote target URI, + // and not the route set formed from the Record-Route. Updating the + // latter would introduce severe backwards compatibility problems with + // RFC 2543-compliant systems. + // https://tools.ietf.org/html/rfc3261#section-15 + if (message.method === Constants_1.C.INVITE) { + // FIXME: parser needs to be typed... + var contact = message.parseHeader("contact"); + if (!contact) { // TODO: Review to make sure this will never happen + throw new Error("Contact undefined."); + } + if (!(contact instanceof NameAddrHeader_1.NameAddrHeader)) { + throw new Error("Contact not instance of NameAddrHeader."); + } + this.dialogState.remoteTarget = contact.uri; + } + // Switch on method and then delegate. + switch (message.method) { + case Constants_1.C.BYE: + // A UAS core receiving a BYE request for an existing dialog MUST follow + // the procedures of Section 12.2.2 to process the request. Once done, + // the UAS SHOULD terminate the session (and therefore stop sending and + // listening for media). The only case where it can elect not to are + // multicast sessions, where participation is possible even if the other + // participant in the dialog has terminated its involvement in the + // session. Whether or not it ends its participation on the session, + // the UAS core MUST generate a 2xx response to the BYE, and MUST pass + // that to the server transaction for transmission. + // + // The UAS MUST still respond to any pending requests received for that + // dialog. It is RECOMMENDED that a 487 (Request Terminated) response + // be generated to those pending requests. + // https://tools.ietf.org/html/rfc3261#section-15.1.2 + { + var uas = new bye_user_agent_server_1.ByeUserAgentServer(this, message); + this.delegate && this.delegate.onBye ? + this.delegate.onBye(uas) : + uas.accept(); + this.dispose(); + } + break; + case Constants_1.C.INFO: + // If a UA receives an INFO request associated with an Info Package that + // the UA has not indicated willingness to receive, the UA MUST send a + // 469 (Bad Info Package) response (see Section 11.6), which contains a + // Recv-Info header field with Info Packages for which the UA is willing + // to receive INFO requests. + { + var uas = new info_user_agent_server_1.InfoUserAgentServer(this, message); + this.delegate && this.delegate.onInfo ? + this.delegate.onInfo(uas) : + uas.reject({ + statusCode: 469, + extraHeaders: ["Recv-Info :"] + }); + } + break; + case Constants_1.C.INVITE: + // If the new session description is not acceptable, the UAS can reject + // it by returning a 488 (Not Acceptable Here) response for the re- + // INVITE. This response SHOULD include a Warning header field. + // https://tools.ietf.org/html/rfc3261#section-14.2 + { + var uas = new re_invite_user_agent_server_1.ReInviteUserAgentServer(this, message); + this.delegate && this.delegate.onInvite ? + this.delegate.onInvite(uas) : + uas.reject({ statusCode: 488 }); // TODO: Warning header field. + } + break; + case Constants_1.C.NOTIFY: + // https://tools.ietf.org/html/rfc3515#section-2.4.4 + { + var uas = new notify_user_agent_server_1.NotifyUserAgentServer(this, message); + this.delegate && this.delegate.onNotify ? + this.delegate.onNotify(uas) : + uas.accept(); + } + break; + case Constants_1.C.PRACK: + // https://tools.ietf.org/html/rfc3262#section-4 + { + var uas = new prack_user_agent_server_1.PrackUserAgentServer(this, message); + this.delegate && this.delegate.onPrack ? + this.delegate.onPrack(uas) : + uas.accept(); + } + break; + case Constants_1.C.REFER: + // https://tools.ietf.org/html/rfc3515#section-2.4.2 + { + var uas = new refer_user_agent_server_1.ReferUserAgentServer(this, message); + this.delegate && this.delegate.onRefer ? + this.delegate.onRefer(uas) : + uas.reject(); + } + break; + default: + { + this.logger.log("INVITE dialog " + this.id + " received unimplemented " + message.method + " request"); + this.core.replyStateless(message, { statusCode: 501 }); + } + break; + } + }; + SessionDialog.prototype.reliableSequenceGuard = function (message) { + var statusCode = message.statusCode; + if (!statusCode) { + throw new Error("Status code undefined"); + } + if (statusCode > 100 && statusCode < 200) { + // If a provisional response is received for an initial request, and + // that response contains a Require header field containing the option + // tag 100rel, the response is to be sent reliably. If the response is + // a 100 (Trying) (as opposed to 101 to 199), this option tag MUST be + // ignored, and the procedures below MUST NOT be used. + // https://tools.ietf.org/html/rfc3262#section-4 + var requireHeader = message.getHeader("require"); + var rseqHeader = message.getHeader("rseq"); + var rseq = requireHeader && requireHeader.includes("100rel") && rseqHeader ? Number(rseqHeader) : undefined; + if (rseq) { + // Handling of subsequent reliable provisional responses for the same + // initial request follows the same rules as above, with the following + // difference: reliable provisional responses are guaranteed to be in + // order. As a result, if the UAC receives another reliable provisional + // response to the same request, and its RSeq value is not one higher + // than the value of the sequence number, that response MUST NOT be + // acknowledged with a PRACK, and MUST NOT be processed further by the + // UAC. An implementation MAY discard the response, or MAY cache the + // response in the hopes of receiving the missing responses. + // https://tools.ietf.org/html/rfc3262#section-4 + if (this.rseq && this.rseq + 1 !== rseq) { + return false; + } + // Once a reliable provisional response is received, retransmissions of + // that response MUST be discarded. A response is a retransmission when + // its dialog ID, CSeq, and RSeq match the original response. The UAC + // MUST maintain a sequence number that indicates the most recently + // received in-order reliable provisional response for the initial + // request. This sequence number MUST be maintained until a final + // response is received for the initial request. Its value MUST be + // initialized to the RSeq header field in the first reliable + // provisional response received for the initial request. + // https://tools.ietf.org/html/rfc3262#section-4 + if (!this.rseq) { + this.rseq = rseq; + } + } + } + return true; + }; + /** + * Update the signaling state of the dialog. + * @param message The message to base the update off of. + */ + SessionDialog.prototype.signalingStateTransition = function (message) { + var body = messages_1.getBody(message); + // No body, no session. No, woman, no cry. + if (!body || body.contentDisposition !== "session") { + return; + } + // We're in UAS role, receiving incoming request with session description + if (message instanceof SIPMessage_1.IncomingRequest) { + switch (this._signalingState) { + case session_1.SignalingState.Initial: + case session_1.SignalingState.Stable: + this._signalingState = session_1.SignalingState.HaveRemoteOffer; + this._offer = body; + this._answer = undefined; + break; + case session_1.SignalingState.HaveLocalOffer: + this._signalingState = session_1.SignalingState.Stable; + this._answer = body; + break; + case session_1.SignalingState.HaveRemoteOffer: + // You cannot make a new offer while one is in progress. + // https://tools.ietf.org/html/rfc3261#section-13.2.1 + // FIXME: What to do here? + break; + case session_1.SignalingState.Closed: + break; + default: + throw new Error("Unexpected signaling state."); + } + } + // We're in UAC role, receiving incoming response with session description + if (message instanceof SIPMessage_1.IncomingResponse) { + switch (this._signalingState) { + case session_1.SignalingState.Initial: + case session_1.SignalingState.Stable: + this._signalingState = session_1.SignalingState.HaveRemoteOffer; + this._offer = body; + this._answer = undefined; + break; + case session_1.SignalingState.HaveLocalOffer: + this._signalingState = session_1.SignalingState.Stable; + this._answer = body; + break; + case session_1.SignalingState.HaveRemoteOffer: + // You cannot make a new offer while one is in progress. + // https://tools.ietf.org/html/rfc3261#section-13.2.1 + // FIXME: What to do here? + break; + case session_1.SignalingState.Closed: + break; + default: + throw new Error("Unexpected signaling state."); + } + } + // We're in UAC role, sending outgoing request with session description + if (message instanceof SIPMessage_1.OutgoingRequest) { + switch (this._signalingState) { + case session_1.SignalingState.Initial: + case session_1.SignalingState.Stable: + this._signalingState = session_1.SignalingState.HaveLocalOffer; + this._offer = body; + this._answer = undefined; + break; + case session_1.SignalingState.HaveLocalOffer: + // You cannot make a new offer while one is in progress. + // https://tools.ietf.org/html/rfc3261#section-13.2.1 + // FIXME: What to do here? + break; + case session_1.SignalingState.HaveRemoteOffer: + this._signalingState = session_1.SignalingState.Stable; + this._answer = body; + break; + case session_1.SignalingState.Closed: + break; + default: + throw new Error("Unexpected signaling state."); + } + } + // We're in UAS role, sending outgoing response with session description + if (messages_1.isBody(message)) { + switch (this._signalingState) { + case session_1.SignalingState.Initial: + case session_1.SignalingState.Stable: + this._signalingState = session_1.SignalingState.HaveLocalOffer; + this._offer = body; + this._answer = undefined; + break; + case session_1.SignalingState.HaveLocalOffer: + // You cannot make a new offer while one is in progress. + // https://tools.ietf.org/html/rfc3261#section-13.2.1 + // FIXME: What to do here? + break; + case session_1.SignalingState.HaveRemoteOffer: + this._signalingState = session_1.SignalingState.Stable; + this._answer = body; + break; + case session_1.SignalingState.Closed: + break; + default: + throw new Error("Unexpected signaling state."); + } + } + }; + SessionDialog.prototype.start2xxRetransmissionTimer = function () { + var _this = this; + if (this.initialTransaction instanceof transactions_1.InviteServerTransaction) { + var transaction_1 = this.initialTransaction; + // Once the response has been constructed, it is passed to the INVITE + // server transaction. In order to ensure reliable end-to-end + // transport of the response, it is necessary to periodically pass + // the response directly to the transport until the ACK arrives. The + // 2xx response is passed to the transport with an interval that + // starts at T1 seconds and doubles for each retransmission until it + // reaches T2 seconds (T1 and T2 are defined in Section 17). + // Response retransmissions cease when an ACK request for the + // response is received. This is independent of whatever transport + // protocols are used to send the response. + // https://tools.ietf.org/html/rfc6026#section-8.1 + var timeout_1 = Timers_1.Timers.T1; + var retransmission_1 = function () { + if (!_this.ackWait) { + _this.invite2xxTimer = undefined; + return; + } + _this.logger.log("No ACK for 2xx response received, attempting retransmission"); + transaction_1.retransmitAcceptedResponse(); + timeout_1 = Math.min(timeout_1 * 2, Timers_1.Timers.T2); + _this.invite2xxTimer = setTimeout(retransmission_1, timeout_1); + }; + this.invite2xxTimer = setTimeout(retransmission_1, timeout_1); + // If the server retransmits the 2xx response for 64*T1 seconds without + // receiving an ACK, the dialog is confirmed, but the session SHOULD be + // terminated. This is accomplished with a BYE, as described in Section 15. + // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 + var stateChanged_1 = function () { + if (transaction_1.state === transactions_1.TransactionState.Terminated) { + transaction_1.removeListener("stateChanged", stateChanged_1); + if (_this.invite2xxTimer) { + clearTimeout(_this.invite2xxTimer); + _this.invite2xxTimer = undefined; + } + if (_this.ackWait) { + if (_this.delegate && _this.delegate.onAckTimeout) { + _this.delegate.onAckTimeout(); + } + else { + _this.bye(); + } + } + } + }; + transaction_1.addListener("stateChanged", stateChanged_1); + } + }; + // FIXME: Refactor + SessionDialog.prototype.startReInvite2xxRetransmissionTimer = function () { + var _this = this; + if (this.reinviteUserAgentServer && this.reinviteUserAgentServer.transaction instanceof transactions_1.InviteServerTransaction) { + var transaction_2 = this.reinviteUserAgentServer.transaction; + // Once the response has been constructed, it is passed to the INVITE + // server transaction. In order to ensure reliable end-to-end + // transport of the response, it is necessary to periodically pass + // the response directly to the transport until the ACK arrives. The + // 2xx response is passed to the transport with an interval that + // starts at T1 seconds and doubles for each retransmission until it + // reaches T2 seconds (T1 and T2 are defined in Section 17). + // Response retransmissions cease when an ACK request for the + // response is received. This is independent of whatever transport + // protocols are used to send the response. + // https://tools.ietf.org/html/rfc6026#section-8.1 + var timeout_2 = Timers_1.Timers.T1; + var retransmission_2 = function () { + if (!_this.reinviteUserAgentServer) { + _this.invite2xxTimer = undefined; + return; + } + _this.logger.log("No ACK for 2xx response received, attempting retransmission"); + transaction_2.retransmitAcceptedResponse(); + timeout_2 = Math.min(timeout_2 * 2, Timers_1.Timers.T2); + _this.invite2xxTimer = setTimeout(retransmission_2, timeout_2); + }; + this.invite2xxTimer = setTimeout(retransmission_2, timeout_2); + // If the server retransmits the 2xx response for 64*T1 seconds without + // receiving an ACK, the dialog is confirmed, but the session SHOULD be + // terminated. This is accomplished with a BYE, as described in Section 15. + // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 + var stateChanged_2 = function () { + if (transaction_2.state === transactions_1.TransactionState.Terminated) { + transaction_2.removeListener("stateChanged", stateChanged_2); + if (_this.invite2xxTimer) { + clearTimeout(_this.invite2xxTimer); + _this.invite2xxTimer = undefined; + } + if (_this.reinviteUserAgentServer) { + // FIXME: TODO: What to do here + } + } + }; + transaction_2.addListener("stateChanged", stateChanged_2); + } + }; + return SessionDialog; +}(dialog_1.Dialog)); +exports.SessionDialog = SessionDialog; + + +/***/ }), +/* 91 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Constants_1 = __webpack_require__(3); +var transactions_1 = __webpack_require__(52); +var user_agent_client_1 = __webpack_require__(82); +var InfoUserAgentClient = /** @class */ (function (_super) { + __extends(InfoUserAgentClient, _super); + function InfoUserAgentClient(dialog, delegate, options) { + var _this = this; + var message = dialog.createOutgoingRequestMessage(Constants_1.C.INFO, options); + _this = _super.call(this, transactions_1.NonInviteClientTransaction, dialog.userAgentCore, message, delegate) || this; + return _this; + } + return InfoUserAgentClient; +}(user_agent_client_1.UserAgentClient)); +exports.InfoUserAgentClient = InfoUserAgentClient; + + +/***/ }), +/* 92 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Constants_1 = __webpack_require__(3); +var transactions_1 = __webpack_require__(52); +var user_agent_client_1 = __webpack_require__(82); +var NotifyUserAgentClient = /** @class */ (function (_super) { + __extends(NotifyUserAgentClient, _super); + function NotifyUserAgentClient(dialog, delegate, options) { + var _this = this; + var message = dialog.createOutgoingRequestMessage(Constants_1.C.NOTIFY, options); + _this = _super.call(this, transactions_1.NonInviteClientTransaction, dialog.userAgentCore, message, delegate) || this; + return _this; + } + return NotifyUserAgentClient; +}(user_agent_client_1.UserAgentClient)); +exports.NotifyUserAgentClient = NotifyUserAgentClient; + + +/***/ }), +/* 93 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var transactions_1 = __webpack_require__(52); +var user_agent_server_1 = __webpack_require__(84); +var NotifyUserAgentServer = /** @class */ (function (_super) { + __extends(NotifyUserAgentServer, _super); + /** + * NOTIFY UAS constructor. + * @param dialogOrCore Dialog for in dialog NOTIFY, UserAgentCore for out of dialog NOTIFY (deprecated). + * @param message Incoming NOTIFY request message. + */ + function NotifyUserAgentServer(dialogOrCore, message, delegate) { + var _this = this; + var userAgentCore = instanceOfDialog(dialogOrCore) ? + dialogOrCore.userAgentCore : + dialogOrCore; + _this = _super.call(this, transactions_1.NonInviteServerTransaction, userAgentCore, message, delegate) || this; + return _this; + } + return NotifyUserAgentServer; +}(user_agent_server_1.UserAgentServer)); +exports.NotifyUserAgentServer = NotifyUserAgentServer; +function instanceOfDialog(object) { + return object.userAgentCore !== undefined; +} + + +/***/ }), +/* 94 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Constants_1 = __webpack_require__(3); +var transactions_1 = __webpack_require__(52); +var user_agent_client_1 = __webpack_require__(82); +var PrackUserAgentClient = /** @class */ (function (_super) { + __extends(PrackUserAgentClient, _super); + function PrackUserAgentClient(dialog, delegate, options) { + var _this = this; + var message = dialog.createOutgoingRequestMessage(Constants_1.C.PRACK, options); + _this = _super.call(this, transactions_1.NonInviteClientTransaction, dialog.userAgentCore, message, delegate) || this; + dialog.signalingStateTransition(message); + return _this; + } + return PrackUserAgentClient; +}(user_agent_client_1.UserAgentClient)); +exports.PrackUserAgentClient = PrackUserAgentClient; + + +/***/ }), +/* 95 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var transactions_1 = __webpack_require__(52); +var user_agent_server_1 = __webpack_require__(84); +var PrackUserAgentServer = /** @class */ (function (_super) { + __extends(PrackUserAgentServer, _super); + function PrackUserAgentServer(dialog, message, delegate) { + var _this = _super.call(this, transactions_1.NonInviteServerTransaction, dialog.userAgentCore, message, delegate) || this; + // Update dialog signaling state with offer/answer in body + dialog.signalingStateTransition(message); + _this.dialog = dialog; + return _this; + } + /** + * Update the dialog signaling state on a 2xx response. + * @param options Options bucket. + */ + PrackUserAgentServer.prototype.accept = function (options) { + if (options === void 0) { options = { statusCode: 200 }; } + if (options.body) { + // Update dialog signaling state with offer/answer in body + this.dialog.signalingStateTransition(options.body); + } + return _super.prototype.accept.call(this, options); + }; + return PrackUserAgentServer; +}(user_agent_server_1.UserAgentServer)); +exports.PrackUserAgentServer = PrackUserAgentServer; + + +/***/ }), +/* 96 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Constants_1 = __webpack_require__(3); +var transactions_1 = __webpack_require__(52); +var user_agent_client_1 = __webpack_require__(82); +/** + * 14 Modifying an Existing Session + * https://tools.ietf.org/html/rfc3261#section-14 + * 14.1 UAC Behavior + * https://tools.ietf.org/html/rfc3261#section-14.1 + */ +var ReInviteUserAgentClient = /** @class */ (function (_super) { + __extends(ReInviteUserAgentClient, _super); + function ReInviteUserAgentClient(dialog, delegate, options) { + var _this = this; + var message = dialog.createOutgoingRequestMessage(Constants_1.C.INVITE, options); + _this = _super.call(this, transactions_1.InviteClientTransaction, dialog.userAgentCore, message, delegate) || this; + _this.delegate = delegate; + dialog.signalingStateTransition(message); + // FIXME: TODO: next line obviously needs to be improved... + dialog.reinviteUserAgentClient = _this; // let the dialog know re-invite request sent + _this.dialog = dialog; + return _this; + } + ReInviteUserAgentClient.prototype.receiveResponse = function (message) { + var _this = this; + var statusCode = message.statusCode ? message.statusCode.toString() : ""; + if (!statusCode) { + throw new Error("Response status code undefined."); + } + switch (true) { + case /^100$/.test(statusCode): + if (this.delegate && this.delegate.onTrying) { + this.delegate.onTrying({ message: message }); + } + break; + case /^1[0-9]{2}$/.test(statusCode): + if (this.delegate && this.delegate.onProgress) { + this.delegate.onProgress({ + message: message, + session: this.dialog, + prack: function (options) { + throw new Error("Unimplemented."); + } + }); + } + break; + case /^2[0-9]{2}$/.test(statusCode): + // Update dialog signaling state with offer/answer in body + this.dialog.signalingStateTransition(message); + if (this.delegate && this.delegate.onAccept) { + this.delegate.onAccept({ + message: message, + session: this.dialog, + ack: function (options) { + var outgoingAckRequest = _this.dialog.ack(options); + return outgoingAckRequest; + } + }); + } + break; + case /^3[0-9]{2}$/.test(statusCode): + if (this.delegate && this.delegate.onRedirect) { + this.delegate.onRedirect({ message: message }); + } + break; + case /^[4-6][0-9]{2}$/.test(statusCode): + if (this.delegate && this.delegate.onReject) { + this.delegate.onReject({ message: message }); + } + else { + // If a UA receives a non-2xx final response to a re-INVITE, the session + // parameters MUST remain unchanged, as if no re-INVITE had been issued. + // Note that, as stated in Section 12.2.1.2, if the non-2xx final + // response is a 481 (Call/Transaction Does Not Exist), or a 408 + // (Request Timeout), or no response at all is received for the re- + // INVITE (that is, a timeout is returned by the INVITE client + // transaction), the UAC will terminate the dialog. + // + // If a UAC receives a 491 response to a re-INVITE, it SHOULD start a + // timer with a value T chosen as follows: + // + // 1. If the UAC is the owner of the Call-ID of the dialog ID + // (meaning it generated the value), T has a randomly chosen value + // between 2.1 and 4 seconds in units of 10 ms. + // + // 2. If the UAC is not the owner of the Call-ID of the dialog ID, T + // has a randomly chosen value of between 0 and 2 seconds in units + // of 10 ms. + // + // When the timer fires, the UAC SHOULD attempt the re-INVITE once more, + // if it still desires for that session modification to take place. For + // example, if the call was already hung up with a BYE, the re-INVITE + // would not take place. + // https://tools.ietf.org/html/rfc3261#section-14.1 + // FIXME: TODO: The above. + } + break; + default: + throw new Error("Invalid status code " + statusCode); + } + }; + return ReInviteUserAgentClient; +}(user_agent_client_1.UserAgentClient)); +exports.ReInviteUserAgentClient = ReInviteUserAgentClient; + + +/***/ }), +/* 97 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +var transactions_1 = __webpack_require__(52); +var user_agent_server_1 = __webpack_require__(84); +/** + * 14 Modifying an Existing Session + * https://tools.ietf.org/html/rfc3261#section-14 + * 14.2 UAS Behavior + * https://tools.ietf.org/html/rfc3261#section-14.2 + */ +var ReInviteUserAgentServer = /** @class */ (function (_super) { + __extends(ReInviteUserAgentServer, _super); + function ReInviteUserAgentServer(dialog, message, delegate) { + var _this = _super.call(this, transactions_1.InviteServerTransaction, dialog.userAgentCore, message, delegate) || this; + dialog.reinviteUserAgentServer = _this; + _this.dialog = dialog; + return _this; + } + /** + * Update the dialog signaling state on a 2xx response. + * @param options Options bucket. + */ + ReInviteUserAgentServer.prototype.accept = function (options) { + if (options === void 0) { options = { statusCode: 200 }; } + // FIXME: The next two lines SHOULD go away, but I suppose it's technically harmless... + // These are here because some versions of SIP.js prior to 0.13.8 set the route set + // of all in dialog ACKs based on the Record-Route headers in the associated 2xx + // response. While this worked for dialog forming 2xx responses, it was technically + // broken for re-INVITE ACKS as it only worked if the UAS populated the Record-Route + // headers in the re-INVITE 2xx response (which is not required and a waste of bandwidth + // as the should be ignored if present in re-INVITE ACKS) and the UAS populated + // the Record-Route headers with the correct values (would be weird not too, but...). + // Anyway, for now the technically useless Record-Route headers are being added + // to maintain "backwards compatibility" with the older broken versions of SIP.js. + options.extraHeaders = options.extraHeaders || []; + options.extraHeaders = options.extraHeaders.concat(this.dialog.routeSet.map(function (route) { return "Record-Route: " + route; })); + // Send and return the response + var response = _super.prototype.accept.call(this, options); + var session = this.dialog; + var result = __assign({}, response, { session: session }); + if (options.body) { + // Update dialog signaling state with offer/answer in body + this.dialog.signalingStateTransition(options.body); + } + // Update dialog + this.dialog.reConfirm(); + return result; + }; + /** + * Update the dialog signaling state on a 1xx response. + * @param options Progress options bucket. + */ + ReInviteUserAgentServer.prototype.progress = function (options) { + if (options === void 0) { options = { statusCode: 180 }; } + // Send and return the response + var response = _super.prototype.progress.call(this, options); + var session = this.dialog; + var result = __assign({}, response, { session: session }); + // Update dialog signaling state + if (options.body) { + this.dialog.signalingStateTransition(options.body); + } + return result; + }; + return ReInviteUserAgentServer; +}(user_agent_server_1.UserAgentServer)); +exports.ReInviteUserAgentServer = ReInviteUserAgentServer; + + +/***/ }), +/* 98 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Constants_1 = __webpack_require__(3); +var transactions_1 = __webpack_require__(52); +var user_agent_client_1 = __webpack_require__(82); +var ReferUserAgentClient = /** @class */ (function (_super) { + __extends(ReferUserAgentClient, _super); + function ReferUserAgentClient(dialog, delegate, options) { + var _this = this; + var message = dialog.createOutgoingRequestMessage(Constants_1.C.REFER, options); + _this = _super.call(this, transactions_1.NonInviteClientTransaction, dialog.userAgentCore, message, delegate) || this; + return _this; + } + return ReferUserAgentClient; +}(user_agent_client_1.UserAgentClient)); +exports.ReferUserAgentClient = ReferUserAgentClient; + + +/***/ }), +/* 99 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var transactions_1 = __webpack_require__(52); +var user_agent_server_1 = __webpack_require__(84); +var ReferUserAgentServer = /** @class */ (function (_super) { + __extends(ReferUserAgentServer, _super); + /** + * REFER UAS constructor. + * @param dialogOrCore Dialog for in dialog REFER, UserAgentCore for out of dialog REFER. + * @param message Incoming REFER request message. + */ + function ReferUserAgentServer(dialogOrCore, message, delegate) { + var _this = this; + var userAgentCore = instanceOfSessionDialog(dialogOrCore) ? + dialogOrCore.userAgentCore : + dialogOrCore; + _this = _super.call(this, transactions_1.NonInviteServerTransaction, userAgentCore, message, delegate) || this; + return _this; + } + return ReferUserAgentServer; +}(user_agent_server_1.UserAgentServer)); +exports.ReferUserAgentServer = ReferUserAgentServer; +function instanceOfSessionDialog(object) { + return object.userAgentCore !== undefined; +} + + +/***/ }), +/* 100 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Constants_1 = __webpack_require__(3); +var NameAddrHeader_1 = __webpack_require__(9); +var Timers_1 = __webpack_require__(56); +var subscription_1 = __webpack_require__(72); +var allowed_methods_1 = __webpack_require__(74); +var notify_user_agent_server_1 = __webpack_require__(93); +var re_subscribe_user_agent_client_1 = __webpack_require__(101); +var dialog_1 = __webpack_require__(89); +/** + * SIP-Specific Event Notification + * + * Abstract + * + * This document describes an extension to the Session Initiation + * Protocol (SIP) defined by RFC 3261. The purpose of this extension is + * to provide an extensible framework by which SIP nodes can request + * notification from remote nodes indicating that certain events have + * occurred. + * + * Note that the event notification mechanisms defined herein are NOT + * intended to be a general-purpose infrastructure for all classes of + * event subscription and notification. + * + * This document represents a backwards-compatible improvement on the + * original mechanism described by RFC 3265, taking into account several + * years of implementation experience. Accordingly, this document + * obsoletes RFC 3265. This document also updates RFC 4660 slightly to + * accommodate some small changes to the mechanism that were discussed + * in that document. + * + * https://tools.ietf.org/html/rfc6665 + */ +var SubscriptionDialog = /** @class */ (function (_super) { + __extends(SubscriptionDialog, _super); + function SubscriptionDialog(subscriptionEvent, subscriptionExpires, subscriptionState, core, state, delegate) { + var _this = _super.call(this, core, state) || this; + _this.delegate = delegate; + _this._autoRefresh = false; + _this._subscriptionEvent = subscriptionEvent; + _this._subscriptionExpires = subscriptionExpires; + _this._subscriptionExpiresInitial = subscriptionExpires; + _this._subscriptionExpiresLastSet = Math.floor(Date.now() / 1000); + _this._subscriptionRefresh = undefined; + _this._subscriptionRefreshLastSet = undefined; + _this._subscriptionState = subscriptionState; + _this.logger = core.loggerFactory.getLogger("sip.subscribe-dialog"); + _this.logger.log("SUBSCRIBE dialog " + _this.id + " constructed"); + return _this; + } + /** + * When a UAC receives a response that establishes a dialog, it + * constructs the state of the dialog. This state MUST be maintained + * for the duration of the dialog. + * https://tools.ietf.org/html/rfc3261#section-12.1.2 + * @param outgoingRequestMessage Outgoing request message for dialog. + * @param incomingResponseMessage Incoming response message creating dialog. + */ + SubscriptionDialog.initialDialogStateForSubscription = function (outgoingSubscribeRequestMessage, incomingNotifyRequestMessage) { + // If the request was sent over TLS, and the Request-URI contained a + // SIPS URI, the "secure" flag is set to TRUE. + // https://tools.ietf.org/html/rfc3261#section-12.1.2 + var secure = false; // FIXME: Currently no support for TLS. + // The route set MUST be set to the list of URIs in the Record-Route + // header field from the response, taken in reverse order and preserving + // all URI parameters. If no Record-Route header field is present in + // the response, the route set MUST be set to the empty set. This route + // set, even if empty, overrides any pre-existing route set for future + // requests in this dialog. The remote target MUST be set to the URI + // from the Contact header field of the response. + // https://tools.ietf.org/html/rfc3261#section-12.1.2 + var routeSet = incomingNotifyRequestMessage.getHeaders("record-route"); + var contact = incomingNotifyRequestMessage.parseHeader("contact"); + if (!contact) { // TODO: Review to make sure this will never happen + throw new Error("Contact undefined."); + } + if (!(contact instanceof NameAddrHeader_1.NameAddrHeader)) { + throw new Error("Contact not instance of NameAddrHeader."); + } + var remoteTarget = contact.uri; + // The local sequence number MUST be set to the value of the sequence + // number in the CSeq header field of the request. The remote sequence + // number MUST be empty (it is established when the remote UA sends a + // request within the dialog). The call identifier component of the + // dialog ID MUST be set to the value of the Call-ID in the request. + // The local tag component of the dialog ID MUST be set to the tag in + // the From field in the request, and the remote tag component of the + // dialog ID MUST be set to the tag in the To field of the response. A + // UAC MUST be prepared to receive a response without a tag in the To + // field, in which case the tag is considered to have a value of null. + // + // This is to maintain backwards compatibility with RFC 2543, which + // did not mandate To tags. + // + // https://tools.ietf.org/html/rfc3261#section-12.1.2 + var localSequenceNumber = outgoingSubscribeRequestMessage.cseq; + var remoteSequenceNumber = undefined; + var callId = outgoingSubscribeRequestMessage.callId; + var localTag = outgoingSubscribeRequestMessage.fromTag; + var remoteTag = incomingNotifyRequestMessage.fromTag; + if (!callId) { // TODO: Review to make sure this will never happen + throw new Error("Call id undefined."); + } + if (!localTag) { // TODO: Review to make sure this will never happen + throw new Error("From tag undefined."); + } + if (!remoteTag) { // TODO: Review to make sure this will never happen + throw new Error("To tag undefined."); // FIXME: No backwards compatibility with RFC 2543 + } + // The remote URI MUST be set to the URI in the To field, and the local + // URI MUST be set to the URI in the From field. + // https://tools.ietf.org/html/rfc3261#section-12.1.2 + if (!outgoingSubscribeRequestMessage.from) { // TODO: Review to make sure this will never happen + throw new Error("From undefined."); + } + if (!outgoingSubscribeRequestMessage.to) { // TODO: Review to make sure this will never happen + throw new Error("To undefined."); + } + var localURI = outgoingSubscribeRequestMessage.from.uri; + var remoteURI = outgoingSubscribeRequestMessage.to.uri; + // A dialog can also be in the "early" state, which occurs when it is + // created with a provisional response, and then transition to the + // "confirmed" state when a 2xx final response arrives. + // https://tools.ietf.org/html/rfc3261#section-12 + var early = false; + var dialogState = { + id: callId + localTag + remoteTag, + early: early, + callId: callId, + localTag: localTag, + remoteTag: remoteTag, + localSequenceNumber: localSequenceNumber, + remoteSequenceNumber: remoteSequenceNumber, + localURI: localURI, + remoteURI: remoteURI, + remoteTarget: remoteTarget, + routeSet: routeSet, + secure: secure + }; + return dialogState; + }; + SubscriptionDialog.prototype.dispose = function () { + _super.prototype.dispose.call(this); + if (this.N) { + clearTimeout(this.N); + this.N = undefined; + } + this.refreshTimerClear(); + this.logger.log("SUBSCRIBE dialog " + this.id + " destroyed"); + }; + Object.defineProperty(SubscriptionDialog.prototype, "autoRefresh", { + get: function () { + return this._autoRefresh; + }, + set: function (autoRefresh) { + this._autoRefresh = true; + this.refreshTimerSet(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SubscriptionDialog.prototype, "subscriptionEvent", { + get: function () { + return this._subscriptionEvent; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SubscriptionDialog.prototype, "subscriptionExpires", { + /** Number of seconds until subscription expires. */ + get: function () { + var secondsSinceLastSet = Math.floor(Date.now() / 1000) - this._subscriptionExpiresLastSet; + var secondsUntilExpires = this._subscriptionExpires - secondsSinceLastSet; + return Math.max(secondsUntilExpires, 0); + }, + set: function (expires) { + if (expires < 0) { + throw new Error("Expires must be greater than or equal to zero."); + } + this._subscriptionExpires = expires; + this._subscriptionExpiresLastSet = Math.floor(Date.now() / 1000); + if (this.autoRefresh) { + var refresh = this.subscriptionRefresh; + if (refresh === undefined || refresh >= expires) { + this.refreshTimerSet(); + } + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SubscriptionDialog.prototype, "subscriptionExpiresInitial", { + get: function () { + return this._subscriptionExpiresInitial; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SubscriptionDialog.prototype, "subscriptionRefresh", { + /** Number of seconds until subscription auto refresh. */ + get: function () { + if (this._subscriptionRefresh === undefined || this._subscriptionRefreshLastSet === undefined) { + return undefined; + } + var secondsSinceLastSet = Math.floor(Date.now() / 1000) - this._subscriptionRefreshLastSet; + var secondsUntilExpires = this._subscriptionRefresh - secondsSinceLastSet; + return Math.max(secondsUntilExpires, 0); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SubscriptionDialog.prototype, "subscriptionState", { + get: function () { + return this._subscriptionState; + }, + enumerable: true, + configurable: true + }); + /** + * Receive in dialog request message from transport. + * @param message The incoming request message. + */ + SubscriptionDialog.prototype.receiveRequest = function (message) { + this.logger.log("SUBSCRIBE dialog " + this.id + " received " + message.method + " request"); + // Request within a dialog out of sequence guard. + // https://tools.ietf.org/html/rfc3261#section-12.2.2 + if (!this.sequenceGuard(message)) { + this.logger.log("SUBSCRIBE dialog " + this.id + " rejected out of order " + message.method + " request."); + return; + } + // Request within a dialog common processing. + // https://tools.ietf.org/html/rfc3261#section-12.2.2 + _super.prototype.receiveRequest.call(this, message); + // Switch on method and then delegate. + switch (message.method) { + case Constants_1.C.NOTIFY: + this.onNotify(message); + break; + default: + this.logger.log("SUBSCRIBE dialog " + this.id + " received unimplemented " + message.method + " request"); + this.core.replyStateless(message, { statusCode: 501 }); + break; + } + }; + /** + * 4.1.2.2. Refreshing of Subscriptions + * https://tools.ietf.org/html/rfc6665#section-4.1.2.2 + */ + SubscriptionDialog.prototype.refresh = function () { + var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); + var options = {}; + options.extraHeaders = (options.extraHeaders || []).slice(); + options.extraHeaders.push(allowHeader); + options.extraHeaders.push("Event: " + this.subscriptionEvent); + options.extraHeaders.push("Expires: " + this.subscriptionExpiresInitial); + options.extraHeaders.push("Contact: " + this.core.configuration.contact.toString()); + return this.subscribe(undefined, options); + }; + /** + * 4.1.2.2. Refreshing of Subscriptions + * https://tools.ietf.org/html/rfc6665#section-4.1.2.2 + * @param delegate Delegate to handle responses. + * @param options Options bucket. + */ + SubscriptionDialog.prototype.subscribe = function (delegate, options) { + var _this = this; + if (options === void 0) { options = {}; } + if (this.subscriptionState !== subscription_1.SubscriptionState.Pending && this.subscriptionState !== subscription_1.SubscriptionState.Active) { + // FIXME: This needs to be a proper exception + throw new Error("Invalid state " + this.subscriptionState + ". May only re-subscribe while in state \"pending\" or \"active\"."); + } + this.logger.log("SUBSCRIBE dialog " + this.id + " sending SUBSCRIBE request"); + var uac = new re_subscribe_user_agent_client_1.ReSubscribeUserAgentClient(this, delegate, options); + // When refreshing a subscription, a subscriber starts Timer N, set to + // 64*T1, when it sends the SUBSCRIBE request. + // https://tools.ietf.org/html/rfc6665#section-4.1.2.2 + this.N = setTimeout(function () { return _this.timer_N(); }, Timers_1.Timers.TIMER_N); + return uac; + }; + /** + * 4.4.1. Dialog Creation and Termination + * A subscription is destroyed after a notifier sends a NOTIFY request + * with a "Subscription-State" of "terminated", or in certain error + * situations described elsewhere in this document. + * https://tools.ietf.org/html/rfc6665#section-4.4.1 + */ + SubscriptionDialog.prototype.terminate = function () { + this.stateTransition(subscription_1.SubscriptionState.Terminated); + this.onTerminated(); + }; + /** + * 4.1.2.3. Unsubscribing + * https://tools.ietf.org/html/rfc6665#section-4.1.2.3 + */ + SubscriptionDialog.prototype.unsubscribe = function () { + var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); + var options = {}; + options.extraHeaders = (options.extraHeaders || []).slice(); + options.extraHeaders.push(allowHeader); + options.extraHeaders.push("Event: " + this.subscriptionEvent); + options.extraHeaders.push("Expires: 0"); + options.extraHeaders.push("Contact: " + this.core.configuration.contact.toString()); + return this.subscribe(undefined, options); + }; + /** + * Handle in dialog NOTIFY requests. + * This does not include the first NOTIFY which created the dialog. + * @param message The incoming NOTIFY request message. + */ + SubscriptionDialog.prototype.onNotify = function (message) { + // If, for some reason, the event package designated in the "Event" + // header field of the NOTIFY request is not supported, the subscriber + // will respond with a 489 (Bad Event) response. + // https://tools.ietf.org/html/rfc6665#section-4.1.3 + var event = message.parseHeader("Event").event; + if (!event || event !== this.subscriptionEvent) { + this.core.replyStateless(message, { statusCode: 489 }); + return; + } + // In the state diagram, "Re-subscription times out" means that an + // attempt to refresh or update the subscription using a new SUBSCRIBE + // request does not result in a NOTIFY request before the corresponding + // Timer N expires. + // https://tools.ietf.org/html/rfc6665#section-4.1.2 + if (this.N) { + clearTimeout(this.N); + this.N = undefined; + } + // NOTIFY requests MUST contain "Subscription-State" header fields that + // indicate the status of the subscription. + // https://tools.ietf.org/html/rfc6665#section-4.1.3 + var subscriptionState = message.parseHeader("Subscription-State"); + if (!subscriptionState || !subscriptionState.state) { + this.core.replyStateless(message, { statusCode: 489 }); + return; + } + var state = subscriptionState.state; + var expires = subscriptionState.expires ? Math.max(subscriptionState.expires, 0) : undefined; + // Update our state and expiration. + switch (state) { + case "pending": + this.stateTransition(subscription_1.SubscriptionState.Pending, expires); + break; + case "active": + this.stateTransition(subscription_1.SubscriptionState.Active, expires); + break; + case "terminated": + this.stateTransition(subscription_1.SubscriptionState.Terminated, expires); + break; + default: + this.logger.warn("Unrecognized subscription state."); + break; + } + // Delegate remainder of NOTIFY handling. + var uas = new notify_user_agent_server_1.NotifyUserAgentServer(this, message); + if (this.delegate && this.delegate.onNotify) { + this.delegate.onNotify(uas); + } + else { + uas.accept(); + } + }; + SubscriptionDialog.prototype.onRefresh = function (request) { + if (this.delegate && this.delegate.onRefresh) { + this.delegate.onRefresh(request); + } + }; + SubscriptionDialog.prototype.onTerminated = function () { + if (this.delegate && this.delegate.onTerminated) { + this.delegate.onTerminated(); + } + }; + SubscriptionDialog.prototype.refreshTimerClear = function () { + if (this.refreshTimer) { + clearTimeout(this.refreshTimer); + this.refreshTimer = undefined; + } + }; + SubscriptionDialog.prototype.refreshTimerSet = function () { + var _this = this; + this.refreshTimerClear(); + if (this.autoRefresh && this.subscriptionExpires > 0) { + var refresh = this.subscriptionExpires * 900; + this._subscriptionRefresh = Math.floor(refresh / 1000); + this._subscriptionRefreshLastSet = Math.floor(Date.now() / 1000); + this.refreshTimer = setTimeout(function () { + _this.refreshTimer = undefined; + _this._subscriptionRefresh = undefined; + _this._subscriptionRefreshLastSet = undefined; + _this.onRefresh(_this.refresh()); + }, refresh); + } + }; + SubscriptionDialog.prototype.stateTransition = function (newState, newExpires) { + var _this = this; + // Assert valid state transitions. + var invalidStateTransition = function () { + _this.logger.warn("Invalid subscription state transition from " + _this.subscriptionState + " to " + newState); + }; + switch (newState) { + case subscription_1.SubscriptionState.Initial: + invalidStateTransition(); + return; + case subscription_1.SubscriptionState.NotifyWait: + invalidStateTransition(); + return; + case subscription_1.SubscriptionState.Pending: + if (this.subscriptionState !== subscription_1.SubscriptionState.NotifyWait && + this.subscriptionState !== subscription_1.SubscriptionState.Pending) { + invalidStateTransition(); + return; + } + break; + case subscription_1.SubscriptionState.Active: + if (this.subscriptionState !== subscription_1.SubscriptionState.NotifyWait && + this.subscriptionState !== subscription_1.SubscriptionState.Pending && + this.subscriptionState !== subscription_1.SubscriptionState.Active) { + invalidStateTransition(); + return; + } + break; + case subscription_1.SubscriptionState.Terminated: + if (this.subscriptionState !== subscription_1.SubscriptionState.NotifyWait && + this.subscriptionState !== subscription_1.SubscriptionState.Pending && + this.subscriptionState !== subscription_1.SubscriptionState.Active) { + invalidStateTransition(); + return; + } + break; + default: + invalidStateTransition(); + return; + } + // If the "Subscription-State" value is "pending", the subscription has + // been received by the notifier, but there is insufficient policy + // information to grant or deny the subscription yet. If the header + // field also contains an "expires" parameter, the subscriber SHOULD + // take it as the authoritative subscription duration and adjust + // accordingly. No further action is necessary on the part of the + // subscriber. The "retry-after" and "reason" parameters have no + // semantics for "pending". + // https://tools.ietf.org/html/rfc6665#section-4.1.3 + if (newState === subscription_1.SubscriptionState.Pending) { + if (newExpires) { + this.subscriptionExpires = newExpires; + } + } + // If the "Subscription-State" header field value is "active", it means + // that the subscription has been accepted and (in general) has been + // authorized. If the header field also contains an "expires" + // parameter, the subscriber SHOULD take it as the authoritative + // subscription duration and adjust accordingly. The "retry-after" and + // "reason" parameters have no semantics for "active". + // https://tools.ietf.org/html/rfc6665#section-4.1.3 + if (newState === subscription_1.SubscriptionState.Active) { + if (newExpires) { + this.subscriptionExpires = newExpires; + } + } + // If the "Subscription-State" value is "terminated", the subscriber + // MUST consider the subscription terminated. The "expires" parameter + // has no semantics for "terminated" -- notifiers SHOULD NOT include an + // "expires" parameter on a "Subscription-State" header field with a + // value of "terminated", and subscribers MUST ignore any such + // parameter, if present. + if (newState === subscription_1.SubscriptionState.Terminated) { + this.dispose(); + } + this._subscriptionState = newState; + }; + /** + * When refreshing a subscription, a subscriber starts Timer N, set to + * 64*T1, when it sends the SUBSCRIBE request. If this Timer N expires + * prior to the receipt of a NOTIFY request, the subscriber considers + * the subscription terminated. If the subscriber receives a success + * response to the SUBSCRIBE request that indicates that no NOTIFY + * request will be generated -- such as the 204 response defined for use + * with the optional extension described in [RFC5839] -- then it MUST + * cancel Timer N. + * https://tools.ietf.org/html/rfc6665#section-4.1.2.2 + */ + SubscriptionDialog.prototype.timer_N = function () { + if (this.subscriptionState !== subscription_1.SubscriptionState.Terminated) { + this.stateTransition(subscription_1.SubscriptionState.Terminated); + this.onTerminated(); + } + }; + return SubscriptionDialog; +}(dialog_1.Dialog)); +exports.SubscriptionDialog = SubscriptionDialog; + + +/***/ }), +/* 101 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Constants_1 = __webpack_require__(3); +var transactions_1 = __webpack_require__(52); +var user_agent_client_1 = __webpack_require__(82); +var ReSubscribeUserAgentClient = /** @class */ (function (_super) { + __extends(ReSubscribeUserAgentClient, _super); + function ReSubscribeUserAgentClient(dialog, delegate, options) { + var _this = this; + var message = dialog.createOutgoingRequestMessage(Constants_1.C.SUBSCRIBE, options); + _this = _super.call(this, transactions_1.NonInviteClientTransaction, dialog.userAgentCore, message, delegate) || this; + _this.dialog = dialog; + return _this; + } + ReSubscribeUserAgentClient.prototype.waitNotifyStop = function () { + // TODO: Placeholder. Not utilized currently. + return; + }; + /** + * Receive a response from the transaction layer. + * @param message Incoming response message. + */ + ReSubscribeUserAgentClient.prototype.receiveResponse = function (message) { + if (message.statusCode && message.statusCode >= 200 && message.statusCode < 300) { + // The "Expires" header field in a 200-class response to SUBSCRIBE + // request indicates the actual duration for which the subscription will + // remain active (unless refreshed). The received value might be + // smaller than the value indicated in the SUBSCRIBE request but cannot + // be larger; see Section 4.2.1 for details. + // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 + var expires = message.getHeader("Expires"); + if (!expires) { + this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE"); + } + else { + var subscriptionExpiresReceived = Number(expires); + if (this.dialog.subscriptionExpires > subscriptionExpiresReceived) { + this.dialog.subscriptionExpires = subscriptionExpiresReceived; + } + } + } + if (message.statusCode && message.statusCode >= 400 && message.statusCode < 700) { + // If a SUBSCRIBE request to refresh a subscription receives a 404, 405, + // 410, 416, 480-485, 489, 501, or 604 response, the subscriber MUST + // consider the subscription terminated. (See [RFC5057] for further + // details and notes about the effect of error codes on dialogs and + // usages within dialog, such as subscriptions). If the subscriber + // wishes to re-subscribe to the state, he does so by composing an + // unrelated initial SUBSCRIBE request with a freshly generated Call-ID + // and a new, unique "From" tag (see Section 4.1.2.1). + // https://tools.ietf.org/html/rfc6665#section-4.1.2.2 + var errorCodes = [404, 405, 410, 416, 480, 481, 482, 483, 484, 485, 489, 501, 604]; + if (errorCodes.includes(message.statusCode)) { + this.dialog.terminate(); + } + // If a SUBSCRIBE request to refresh a subscription fails with any error + // code other than those listed above, the original subscription is + // still considered valid for the duration of the most recently known + // "Expires" value as negotiated by the most recent successful SUBSCRIBE + // transaction, or as communicated by a NOTIFY request in its + // "Subscription-State" header field "expires" parameter. + // https://tools.ietf.org/html/rfc6665#section-4.1.2.2 + } + _super.prototype.receiveResponse.call(this, message); + }; + return ReSubscribeUserAgentClient; +}(user_agent_client_1.UserAgentClient)); +exports.ReSubscribeUserAgentClient = ReSubscribeUserAgentClient; + + +/***/ }), +/* 102 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +var Exceptions_1 = __webpack_require__(47); +var dialogs_1 = __webpack_require__(88); +var session_1 = __webpack_require__(68); +var transactions_1 = __webpack_require__(52); +var allowed_methods_1 = __webpack_require__(74); +var user_agent_server_1 = __webpack_require__(84); +/** + * 13 Initiating a Session + * https://tools.ietf.org/html/rfc3261#section-13 + * 13.1 Overview + * https://tools.ietf.org/html/rfc3261#section-13.1 + * 13.3 UAS Processing + * https://tools.ietf.org/html/rfc3261#section-13.3 + */ +var InviteUserAgentServer = /** @class */ (function (_super) { + __extends(InviteUserAgentServer, _super); + function InviteUserAgentServer(core, message, delegate) { + var _this = _super.call(this, transactions_1.InviteServerTransaction, core, message, delegate) || this; + _this.core = core; + return _this; + } + InviteUserAgentServer.prototype.dispose = function () { + if (this.earlyDialog) { + this.earlyDialog.dispose(); + } + _super.prototype.dispose.call(this); + }; + /** + * 13.3.1.4 The INVITE is Accepted + * The UAS core generates a 2xx response. This response establishes a + * dialog, and therefore follows the procedures of Section 12.1.1 in + * addition to those of Section 8.2.6. + * https://tools.ietf.org/html/rfc3261#section-13.3.1.4 + * @param options Accept options bucket. + */ + InviteUserAgentServer.prototype.accept = function (options) { + if (options === void 0) { options = { statusCode: 200 }; } + if (!this.acceptable) { + throw new Exceptions_1.Exceptions.TransactionStateError(this.message.method + " not acceptable in state " + this.transaction.state + "."); + } + // This response establishes a dialog... + // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 + if (!this.confirmedDialog) { + if (this.earlyDialog) { + this.earlyDialog.confirm(); + this.confirmedDialog = this.earlyDialog; + this.earlyDialog = undefined; + } + else { + var transaction = this.transaction; + if (!(transaction instanceof transactions_1.InviteServerTransaction)) { + throw new Error("Transaction not instance of InviteClientTransaction."); + } + var state = dialogs_1.Dialog.initialDialogStateForUserAgentServer(this.message, this.toTag); + this.confirmedDialog = new dialogs_1.SessionDialog(transaction, this.core, state); + } + } + // When a UAS responds to a request with a response that establishes a + // dialog (such as a 2xx to INVITE), the UAS MUST copy all Record-Route + // header field values from the request into the response (including the + // URIs, URI parameters, and any Record-Route header field parameters, + // whether they are known or unknown to the UAS) and MUST maintain the + // order of those values. The UAS MUST add a Contact header field to + // the response. The Contact header field contains an address where the + // UAS would like to be contacted for subsequent requests in the dialog + // (which includes the ACK for a 2xx response in the case of an INVITE). + // Generally, the host portion of this URI is the IP address or FQDN of + // the host. The URI provided in the Contact header field MUST be a SIP + // or SIPS URI. If the request that initiated the dialog contained a + // SIPS URI in the Request-URI or in the top Record-Route header field + // value, if there was any, or the Contact header field if there was no + // Record-Route header field, the Contact header field in the response + // MUST be a SIPS URI. The URI SHOULD have global scope (that is, the + // same URI can be used in messages outside this dialog). The same way, + // the scope of the URI in the Contact header field of the INVITE is not + // limited to this dialog either. It can therefore be used in messages + // to the UAC even outside this dialog. + // https://tools.ietf.org/html/rfc3261#section-12.1.1 + var recordRouteHeader = this.message + .getHeaders("record-route") + .map(function (header) { return "Record-Route: " + header; }); + var contactHeader = "Contact: " + this.core.configuration.contact.toString(); + // A 2xx response to an INVITE SHOULD contain the Allow header field and + // the Supported header field, and MAY contain the Accept header field. + // Including these header fields allows the UAC to determine the + // features and extensions supported by the UAS for the duration of the + // call, without probing. + // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 + // FIXME: TODO: This should not be hard coded. + var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); + // FIXME: TODO: Supported header (see reply()) + // FIXME: TODO: Accept header + // If the INVITE request contained an offer, and the UAS had not yet + // sent an answer, the 2xx MUST contain an answer. If the INVITE did + // not contain an offer, the 2xx MUST contain an offer if the UAS had + // not yet sent an offer. + // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 + if (!options.body) { + if (this.confirmedDialog.signalingState === session_1.SignalingState.Initial || + this.confirmedDialog.signalingState === session_1.SignalingState.HaveRemoteOffer) { + throw new Error("Response must have a body."); + } + } + // FIXME: TODO: Guard offer/answer + options.statusCode = options.statusCode || 200; + options.extraHeaders = options.extraHeaders || []; + options.extraHeaders = options.extraHeaders.concat(recordRouteHeader); + options.extraHeaders.push(allowHeader); + options.extraHeaders.push(contactHeader); + var response = _super.prototype.accept.call(this, options); + var session = this.confirmedDialog; + var result = __assign({}, response, { session: session }); + // Update dialog signaling state + if (options.body) { + this.confirmedDialog.signalingStateTransition(options.body); + } + return result; + }; + /** + * 13.3.1.1 Progress + * If the UAS is not able to answer the invitation immediately, it can + * choose to indicate some kind of progress to the UAC (for example, an + * indication that a phone is ringing). This is accomplished with a + * provisional response between 101 and 199. These provisional + * responses establish early dialogs and therefore follow the procedures + * of Section 12.1.1 in addition to those of Section 8.2.6. A UAS MAY + * send as many provisional responses as it likes. Each of these MUST + * indicate the same dialog ID. However, these will not be delivered + * reliably. + * + * If the UAS desires an extended period of time to answer the INVITE, + * it will need to ask for an "extension" in order to prevent proxies + * from canceling the transaction. A proxy has the option of canceling + * a transaction when there is a gap of 3 minutes between responses in a + * transaction. To prevent cancellation, the UAS MUST send a non-100 + * provisional response at every minute, to handle the possibility of + * lost provisional responses. + * https://tools.ietf.org/html/rfc3261#section-13.3.1.1 + * @param options Progress options bucket. + */ + InviteUserAgentServer.prototype.progress = function (options) { + if (options === void 0) { options = { statusCode: 180 }; } + if (!this.progressable) { + throw new Exceptions_1.Exceptions.TransactionStateError(this.message.method + " not progressable in state " + this.transaction.state + "."); + } + // This response establishes a dialog... + // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 + if (!this.earlyDialog) { + var transaction = this.transaction; + if (!(transaction instanceof transactions_1.InviteServerTransaction)) { + throw new Error("Transaction not instance of InviteClientTransaction."); + } + var state = dialogs_1.Dialog.initialDialogStateForUserAgentServer(this.message, this.toTag, true); + this.earlyDialog = new dialogs_1.SessionDialog(transaction, this.core, state); + } + // When a UAS responds to a request with a response that establishes a + // dialog (such as a 2xx to INVITE), the UAS MUST copy all Record-Route + // header field values from the request into the response (including the + // URIs, URI parameters, and any Record-Route header field parameters, + // whether they are known or unknown to the UAS) and MUST maintain the + // order of those values. The UAS MUST add a Contact header field to + // the response. The Contact header field contains an address where the + // UAS would like to be contacted for subsequent requests in the dialog + // (which includes the ACK for a 2xx response in the case of an INVITE). + // Generally, the host portion of this URI is the IP address or FQDN of + // the host. The URI provided in the Contact header field MUST be a SIP + // or SIPS URI. If the request that initiated the dialog contained a + // SIPS URI in the Request-URI or in the top Record-Route header field + // value, if there was any, or the Contact header field if there was no + // Record-Route header field, the Contact header field in the response + // MUST be a SIPS URI. The URI SHOULD have global scope (that is, the + // same URI can be used in messages outside this dialog). The same way, + // the scope of the URI in the Contact header field of the INVITE is not + // limited to this dialog either. It can therefore be used in messages + // to the UAC even outside this dialog. + // https://tools.ietf.org/html/rfc3261#section-12.1.1 + var recordRouteHeader = this.message + .getHeaders("record-route") + .map(function (header) { return "Record-Route: " + header; }); + var contactHeader = "Contact: " + this.core.configuration.contact; + options.extraHeaders = options.extraHeaders || []; + options.extraHeaders = options.extraHeaders.concat(recordRouteHeader); + options.extraHeaders.push(contactHeader); + var response = _super.prototype.progress.call(this, options); + var session = this.earlyDialog; + var result = __assign({}, response, { session: session }); + // Update dialog signaling state + if (options.body) { + this.earlyDialog.signalingStateTransition(options.body); + } + return result; + }; + /** + * 13.3.1.2 The INVITE is Redirected + * If the UAS decides to redirect the call, a 3xx response is sent. A + * 300 (Multiple Choices), 301 (Moved Permanently) or 302 (Moved + * Temporarily) response SHOULD contain a Contact header field + * containing one or more URIs of new addresses to be tried. The + * response is passed to the INVITE server transaction, which will deal + * with its retransmissions. + * https://tools.ietf.org/html/rfc3261#section-13.3.1.2 + * @param options Reject options bucket. + */ + InviteUserAgentServer.prototype.redirect = function (contacts, options) { + if (options === void 0) { options = { statusCode: 302 }; } + return _super.prototype.redirect.call(this, contacts, options); + }; + /** + * 13.3.1.3 The INVITE is Rejected + * A common scenario occurs when the callee is currently not willing or + * able to take additional calls at this end system. A 486 (Busy Here) + * SHOULD be returned in such a scenario. + * https://tools.ietf.org/html/rfc3261#section-13.3.1.3 + * @param options Reject options bucket. + */ + InviteUserAgentServer.prototype.reject = function (options) { + if (options === void 0) { options = { statusCode: 486 }; } + return _super.prototype.reject.call(this, options); + }; + return InviteUserAgentServer; +}(user_agent_server_1.UserAgentServer)); +exports.InviteUserAgentServer = InviteUserAgentServer; + + +/***/ }), +/* 103 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var transactions_1 = __webpack_require__(52); +var user_agent_client_1 = __webpack_require__(82); +var MessageUserAgentClient = /** @class */ (function (_super) { + __extends(MessageUserAgentClient, _super); + function MessageUserAgentClient(core, message, delegate) { + return _super.call(this, transactions_1.NonInviteClientTransaction, core, message, delegate) || this; + } + return MessageUserAgentClient; +}(user_agent_client_1.UserAgentClient)); +exports.MessageUserAgentClient = MessageUserAgentClient; + + +/***/ }), +/* 104 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var transactions_1 = __webpack_require__(52); +var user_agent_server_1 = __webpack_require__(84); +var MessageUserAgentServer = /** @class */ (function (_super) { + __extends(MessageUserAgentServer, _super); + function MessageUserAgentServer(core, message, delegate) { + var _this = _super.call(this, transactions_1.NonInviteServerTransaction, core, message, delegate) || this; + _this.core = core; + return _this; + } + return MessageUserAgentServer; +}(user_agent_server_1.UserAgentServer)); +exports.MessageUserAgentServer = MessageUserAgentServer; + + +/***/ }), +/* 105 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var transactions_1 = __webpack_require__(52); +var user_agent_client_1 = __webpack_require__(82); +var PublishUserAgentClient = /** @class */ (function (_super) { + __extends(PublishUserAgentClient, _super); + function PublishUserAgentClient(core, message, delegate) { + return _super.call(this, transactions_1.NonInviteClientTransaction, core, message, delegate) || this; + } + return PublishUserAgentClient; +}(user_agent_client_1.UserAgentClient)); +exports.PublishUserAgentClient = PublishUserAgentClient; + + +/***/ }), +/* 106 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var transactions_1 = __webpack_require__(52); +var user_agent_server_1 = __webpack_require__(84); +var ReSubscribeUserAgentServer = /** @class */ (function (_super) { + __extends(ReSubscribeUserAgentServer, _super); + function ReSubscribeUserAgentServer(dialog, message, delegate) { + return _super.call(this, transactions_1.NonInviteServerTransaction, dialog.userAgentCore, message, delegate) || this; + } + return ReSubscribeUserAgentServer; +}(user_agent_server_1.UserAgentServer)); +exports.ReSubscribeUserAgentServer = ReSubscribeUserAgentServer; + + +/***/ }), +/* 107 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var transactions_1 = __webpack_require__(52); +var user_agent_client_1 = __webpack_require__(82); +var RegisterUserAgentClient = /** @class */ (function (_super) { + __extends(RegisterUserAgentClient, _super); + function RegisterUserAgentClient(core, message, delegate) { + return _super.call(this, transactions_1.NonInviteClientTransaction, core, message, delegate) || this; + } + return RegisterUserAgentClient; +}(user_agent_client_1.UserAgentClient)); +exports.RegisterUserAgentClient = RegisterUserAgentClient; + + +/***/ }), +/* 108 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Timers_1 = __webpack_require__(56); +var subscription_dialog_1 = __webpack_require__(100); +var subscription_1 = __webpack_require__(72); +var transactions_1 = __webpack_require__(52); +var user_agent_client_1 = __webpack_require__(82); +/** + * 4.1. Subscriber Behavior + * https://tools.ietf.org/html/rfc6665#section-4.1 + * + * User agent client for installation of a single subscription per SUBSCRIBE request. + * TODO: Support for installation of multiple subscriptions on forked SUBSCRIBE reqeuests. + */ +var SubscribeUserAgentClient = /** @class */ (function (_super) { + __extends(SubscribeUserAgentClient, _super); + function SubscribeUserAgentClient(core, message, delegate) { + var _this = this; + // Get event from request message. + var event = message.getHeader("Event"); + if (!event) { + throw new Error("Event undefined"); + } + // Get expires from reqeust message. + var expires = message.getHeader("Expires"); + if (!expires) { + throw new Error("Expires undefined"); + } + _this = _super.call(this, transactions_1.NonInviteClientTransaction, core, message, delegate) || this; + _this.delegate = delegate; + // FIXME: Subscriber id should also be matching on event id. + _this.subscriberId = message.callId + message.fromTag + event; + _this.subscriptionExpiresRequested = _this.subscriptionExpires = Number(expires); + _this.subscriptionEvent = event; + _this.subscriptionState = subscription_1.SubscriptionState.NotifyWait; + // Start waiting for a NOTIFY we can use to create a subscription. + _this.waitNotifyStart(); + return _this; + } + /** + * Destructor. + * Note that Timer N may live on waiting for an initial NOTIFY and + * the delegate may still receive that NOTIFY. If you don't want + * that behavior then either clear the delegate so the delegate + * doesn't get called (a 200 will be sent in response to the NOTIFY) + * or call `waitNotifyStop` which will clear Timer N and remove this + * UAC from the core (a 481 will be sent in response to the NOTIFY). + */ + SubscribeUserAgentClient.prototype.dispose = function () { + _super.prototype.dispose.call(this); + }; + /** + * Handle out of dialog NOTIFY assoicated with SUBSCRIBE request. + * This is the first NOTIFY received after the SUBSCRIBE request. + * @param uas User agent server handling the subscription creating NOTIFY. + */ + SubscribeUserAgentClient.prototype.onNotify = function (uas) { + // NOTIFY requests are matched to such SUBSCRIBE requests if they + // contain the same "Call-ID", a "To" header field "tag" parameter that + // matches the "From" header field "tag" parameter of the SUBSCRIBE + // request, and the same "Event" header field. Rules for comparisons of + // the "Event" header fields are described in Section 8.2.1. + // https://tools.ietf.org/html/rfc6665#section-4.4.1 + var event = uas.message.parseHeader("Event").event; + if (!event || event !== this.subscriptionEvent) { + this.logger.warn("Failed to parse event."); + uas.reject({ statusCode: 489 }); + return; + } + // NOTIFY requests MUST contain "Subscription-State" header fields that + // indicate the status of the subscription. + // https://tools.ietf.org/html/rfc6665#section-4.1.3 + var subscriptionState = uas.message.parseHeader("Subscription-State"); + if (!subscriptionState || !subscriptionState.state) { + this.logger.warn("Failed to parse subscription state."); + uas.reject({ statusCode: 489 }); + return; + } + // Validate subscription state. + var state = subscriptionState.state; + switch (state) { + case "pending": + break; + case "active": + break; + case "terminated": + break; + default: + this.logger.warn("Invalid subscription state " + state); + uas.reject({ statusCode: 489 }); + return; + } + // Dialogs usages are created upon completion of a NOTIFY transaction + // for a new subscription, unless the NOTIFY request contains a + // "Subscription-State" of "terminated." + // https://tools.ietf.org/html/rfc6665#section-4.4.1 + if (state !== "terminated") { + // The Contact header field MUST be present and contain exactly one SIP + // or SIPS URI in any request that can result in the establishment of a + // dialog. + // https://tools.ietf.org/html/rfc3261#section-8.1.1.8 + var contact = uas.message.parseHeader("contact"); + if (!contact) { + this.logger.warn("Failed to parse contact."); + uas.reject({ statusCode: 489 }); + return; + } + } + // In accordance with the rules for proxying non-INVITE requests as + // defined in [RFC3261], successful SUBSCRIBE requests will receive only + // one 200-class response; however, due to forking, the subscription may + // have been accepted by multiple nodes. The subscriber MUST therefore + // be prepared to receive NOTIFY requests with "From:" tags that differ + // from the "To:" tag received in the SUBSCRIBE 200-class response. + // + // If multiple NOTIFY requests are received in different dialogs in + // response to a single SUBSCRIBE request, each dialog represents a + // different destination to which the SUBSCRIBE request was forked. + // Subscriber handling in such situations varies by event package; see + // Section 5.4.9 for details. + // https://tools.ietf.org/html/rfc6665#section-4.1.4 + // Each event package MUST specify whether forked SUBSCRIBE requests are + // allowed to install multiple subscriptions. + // + // If such behavior is not allowed, the first potential dialog- + // establishing message will create a dialog. All subsequent NOTIFY + // requests that correspond to the SUBSCRIBE request (i.e., have + // matching "To", "From", "Call-ID", and "Event" header fields, as well + // as "From" header field "tag" parameter and "Event" header field "id" + // parameter) but that do not match the dialog would be rejected with a + // 481 response. Note that the 200-class response to the SUBSCRIBE + // request can arrive after a matching NOTIFY request has been received; + // such responses might not correlate to the same dialog established by + // the NOTIFY request. Except as required to complete the SUBSCRIBE + // transaction, such non-matching 200-class responses are ignored. + // + // If installing of multiple subscriptions by way of a single forked + // SUBSCRIBE request is allowed, the subscriber establishes a new dialog + // towards each notifier by returning a 200-class response to each + // NOTIFY request. Each dialog is then handled as its own entity and is + // refreshed independently of the other dialogs. + // + // In the case that multiple subscriptions are allowed, the event + // package MUST specify whether merging of the notifications to form a + // single state is required, and how such merging is to be performed. + // Note that it is possible that some event packages may be defined in + // such a way that each dialog is tied to a mutually exclusive state + // that is unaffected by the other dialogs; this MUST be clearly stated + // if it is the case. + // https://tools.ietf.org/html/rfc6665#section-5.4.9 + // *** NOTE: This implementation is only for event packages which + // do not allow forked requests to install muliple subscriptions. + // As such and in accordance with the specificaiton, we stop waiting + // and any future NOTIFY requests will be rejected with a 481. + if (this.dialog) { + throw new Error("Dialog already created. This implementation only supports install of single subscriptions."); + } + this.waitNotifyStop(); + // Update expires. + this.subscriptionExpires = + subscriptionState.expires ? + Math.min(this.subscriptionExpires, Math.max(subscriptionState.expires, 0)) : + this.subscriptionExpires; + // Update subscriptoin state. + switch (state) { + case "pending": + this.subscriptionState = subscription_1.SubscriptionState.Pending; + break; + case "active": + this.subscriptionState = subscription_1.SubscriptionState.Active; + break; + case "terminated": + this.subscriptionState = subscription_1.SubscriptionState.Terminated; + break; + default: + throw new Error("Unrecognized state " + state + "."); + } + // Dialogs usages are created upon completion of a NOTIFY transaction + // for a new subscription, unless the NOTIFY request contains a + // "Subscription-State" of "terminated." + // https://tools.ietf.org/html/rfc6665#section-4.4.1 + if (this.subscriptionState !== subscription_1.SubscriptionState.Terminated) { + // Because the dialog usage is established by the NOTIFY request, the + // route set at the subscriber is taken from the NOTIFY request itself, + // as opposed to the route set present in the 200-class response to the + // SUBSCRIBE request. + // https://tools.ietf.org/html/rfc6665#section-4.4.1 + var dialogState = subscription_dialog_1.SubscriptionDialog.initialDialogStateForSubscription(this.message, uas.message); + // Subscription Initiated! :) + this.dialog = new subscription_dialog_1.SubscriptionDialog(this.subscriptionEvent, this.subscriptionExpires, this.subscriptionState, this.core, dialogState); + } + // Delegate. + if (this.delegate && this.delegate.onNotify) { + var request = uas; + var subscription = this.dialog; + this.delegate.onNotify({ request: request, subscription: subscription }); + } + else { + uas.accept(); + } + }; + SubscribeUserAgentClient.prototype.waitNotifyStart = function () { + var _this = this; + if (!this.N) { + // Add ourselves to the core's subscriber map. + // This allows the core to route out of dialog NOTIFY messages to us. + this.core.subscribers.set(this.subscriberId, this); + this.N = setTimeout(function () { return _this.timer_N(); }, Timers_1.Timers.TIMER_N); + } + }; + SubscribeUserAgentClient.prototype.waitNotifyStop = function () { + if (this.N) { + // Remove ourselves to the core's subscriber map. + // Any future out of dialog NOTIFY messages will be rejected with a 481. + this.core.subscribers.delete(this.subscriberId); + clearTimeout(this.N); + this.N = undefined; + } + }; + /** + * Receive a response from the transaction layer. + * @param message Incoming response message. + */ + SubscribeUserAgentClient.prototype.receiveResponse = function (message) { + if (!this.authenticationGuard(message)) { + return; + } + if (message.statusCode && message.statusCode >= 200 && message.statusCode < 300) { + // The "Expires" header field in a 200-class response to SUBSCRIBE + // request indicates the actual duration for which the subscription will + // remain active (unless refreshed). The received value might be + // smaller than the value indicated in the SUBSCRIBE request but cannot + // be larger; see Section 4.2.1 for details. + // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 + // The "Expires" values present in SUBSCRIBE 200-class responses behave + // in the same way as they do in REGISTER responses: the server MAY + // shorten the interval but MUST NOT lengthen it. + // + // If the duration specified in a SUBSCRIBE request is unacceptably + // short, the notifier may be able to send a 423 response, as + // described earlier in this section. + // + // 200-class responses to SUBSCRIBE requests will not generally contain + // any useful information beyond subscription duration; their primary + // purpose is to serve as a reliability mechanism. State information + // will be communicated via a subsequent NOTIFY request from the + // notifier. + // https://tools.ietf.org/html/rfc6665#section-4.2.1.1 + var expires = message.getHeader("Expires"); + if (!expires) { + this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE"); + } + else { + var subscriptionExpiresReceived = Number(expires); + if (subscriptionExpiresReceived > this.subscriptionExpiresRequested) { + this.logger.warn("Expires header in a 200-class response to SUBSCRIBE with a higher value than the one in the request"); + } + if (subscriptionExpiresReceived < this.subscriptionExpires) { + this.subscriptionExpires = subscriptionExpiresReceived; + } + } + // If a NOTIFY arrived before 200-class response a dialog may have been created. + // Updated the dialogs expiration only if this indicates earlier expiration. + if (this.dialog) { + if (this.dialog.subscriptionExpires > this.subscriptionExpires) { + this.dialog.subscriptionExpires = this.subscriptionExpires; + } + } + } + if (message.statusCode && message.statusCode >= 300 && message.statusCode < 700) { + this.waitNotifyStop(); // No NOTIFY will be sent after a negative final response. + } + _super.prototype.receiveResponse.call(this, message); + }; + /** + * To ensure that subscribers do not wait indefinitely for a + * subscription to be established, a subscriber starts a Timer N, set to + * 64*T1, when it sends a SUBSCRIBE request. If this Timer N expires + * prior to the receipt of a NOTIFY request, the subscriber considers + * the subscription failed, and cleans up any state associated with the + * subscription attempt. + * https://tools.ietf.org/html/rfc6665#section-4.1.2.4 + */ + SubscribeUserAgentClient.prototype.timer_N = function () { + this.logger.warn("Timer N expired for SUBSCRIBE user agent client. Timed out waiting for NOTIFY."); + this.waitNotifyStop(); + if (this.delegate && this.delegate.onNotifyTimeout) { + this.delegate.onNotifyTimeout(); + } + }; + return SubscribeUserAgentClient; +}(user_agent_client_1.UserAgentClient)); +exports.SubscribeUserAgentClient = SubscribeUserAgentClient; + + +/***/ }), +/* 109 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var transactions_1 = __webpack_require__(52); +var user_agent_server_1 = __webpack_require__(84); +var SubscribeUserAgentServer = /** @class */ (function (_super) { + __extends(SubscribeUserAgentServer, _super); + function SubscribeUserAgentServer(core, message, delegate) { + var _this = _super.call(this, transactions_1.NonInviteServerTransaction, core, message, delegate) || this; + _this.core = core; + return _this; + } + return SubscribeUserAgentServer; +}(user_agent_server_1.UserAgentServer)); +exports.SubscribeUserAgentServer = SubscribeUserAgentServer; + + +/***/ }), +/* 110 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +var SIPMessage_1 = __webpack_require__(6); +var URI_1 = __webpack_require__(10); +/** + * Factory function to generate configuration give a UA. + * @param ua UA + */ +function makeUserAgentCoreConfigurationFromUA(ua) { + // FIXME: Configuration URI is a bad mix of types currently. It also needs to exist. + if (!(ua.configuration.uri instanceof URI_1.URI)) { + throw new Error("Configuration URI not instance of URI."); + } + var configuration = { + aor: ua.configuration.uri, + contact: ua.contact, + loggerFactory: ua.getLoggerFactory(), + userAgentHeaderFieldValue: ua.configuration.userAgentString, + authenticationFactory: function () { + if (ua.configuration.authenticationFactory) { + return ua.configuration.authenticationFactory(ua); + } + return undefined; + }, + onRequestTimeoutResponseMessageFactory: function () { + var message = new SIPMessage_1.IncomingResponse(ua); + message.statusCode = 408; + message.reasonPhrase = "Request Timeout"; + return message; + }, + onTransportErrorResponseMessageFactory: function () { + var message = new SIPMessage_1.IncomingResponse(ua); + message.statusCode = 503; + message.reasonPhrase = "Service Unavailable"; + return message; + }, + outgoingRequestMessageFactory: function (method, ruri, params, extraHeaders, body) { return new SIPMessage_1.OutgoingRequest(method, ruri, ua, params, extraHeaders, body); }, + transportAccessor: function () { return ua.transport; } + }; + return configuration; +} +exports.makeUserAgentCoreConfigurationFromUA = makeUserAgentCoreConfigurationFromUA; + + +/***/ }), +/* 111 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(global) { +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var events_1 = __webpack_require__(2); +var Enums_1 = __webpack_require__(5); +var Exceptions_1 = __webpack_require__(47); +var Utils_1 = __webpack_require__(11); +var Modifiers = __webpack_require__(112); +var SessionDescriptionHandlerObserver_1 = __webpack_require__(113); +/* SessionDescriptionHandler + * @class PeerConnection helper Class. + * @param {SIP.Session} session + * @param {Object} [options] + */ +var SessionDescriptionHandler = /** @class */ (function (_super) { + __extends(SessionDescriptionHandler, _super); + function SessionDescriptionHandler(logger, observer, options) { + var _this = _super.call(this) || this; + _this.type = Enums_1.TypeStrings.SessionDescriptionHandler; + // TODO: Validate the options + _this.options = options || {}; + _this.logger = logger; + _this.observer = observer; + _this.dtmfSender = undefined; + _this.shouldAcquireMedia = true; + _this.CONTENT_TYPE = "application/sdp"; + _this.C = { + DIRECTION: { + NULL: null, + SENDRECV: "sendrecv", + SENDONLY: "sendonly", + RECVONLY: "recvonly", + INACTIVE: "inactive" + } + }; + _this.logger.log("SessionDescriptionHandlerOptions: " + JSON.stringify(_this.options)); + _this.direction = _this.C.DIRECTION.NULL; + _this.modifiers = _this.options.modifiers || []; + if (!Array.isArray(_this.modifiers)) { + _this.modifiers = [_this.modifiers]; + } + var environment = global.window || global; + _this.WebRTC = { + MediaStream: environment.MediaStream, + getUserMedia: environment.navigator.mediaDevices.getUserMedia.bind(environment.navigator.mediaDevices), + RTCPeerConnection: environment.RTCPeerConnection + }; + _this.iceGatheringTimeout = false; + _this.initPeerConnection(_this.options.peerConnectionOptions); + _this.constraints = _this.checkAndDefaultConstraints(_this.options.constraints); + return _this; + } + /** + * @param {SIP.Session} session + * @param {Object} [options] + */ + SessionDescriptionHandler.defaultFactory = function (session, options) { + var logger = session.ua.getLogger("sip.invitecontext.sessionDescriptionHandler", session.id); + var observer = new SessionDescriptionHandlerObserver_1.SessionDescriptionHandlerObserver(session, options); + return new SessionDescriptionHandler(logger, observer, options); + }; + // Functions the sesssion can use + /** + * Destructor + */ + SessionDescriptionHandler.prototype.close = function () { + this.logger.log("closing PeerConnection"); + // have to check signalingState since this.close() gets called multiple times + if (this.peerConnection && this.peerConnection.signalingState !== "closed") { + if (this.peerConnection.getSenders) { + this.peerConnection.getSenders().forEach(function (sender) { + if (sender.track) { + sender.track.stop(); + } + }); + } + else { + this.logger.warn("Using getLocalStreams which is deprecated"); + this.peerConnection.getLocalStreams().forEach(function (stream) { + stream.getTracks().forEach(function (track) { + track.stop(); + }); + }); + } + if (this.peerConnection.getReceivers) { + this.peerConnection.getReceivers().forEach(function (receiver) { + if (receiver.track) { + receiver.track.stop(); + } + }); + } + else { + this.logger.warn("Using getRemoteStreams which is deprecated"); + this.peerConnection.getRemoteStreams().forEach(function (stream) { + stream.getTracks().forEach(function (track) { + track.stop(); + }); + }); + } + this.resetIceGatheringComplete(); + this.peerConnection.close(); + } + }; + /** + * Gets the local description from the underlying media implementation + * @param {Object} [options] Options object to be used by getDescription + * @param {MediaStreamConstraints} [options.constraints] MediaStreamConstraints + * https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamConstraints + * @param {Object} [options.peerConnectionOptions] If this is set it will recreate the peer + * connection with the new options + * @param {Array} [modifiers] Array with one time use description modifiers + * @returns {Promise} Promise that resolves with the local description to be used for the session + */ + SessionDescriptionHandler.prototype.getDescription = function (options, modifiers) { + var _this = this; + if (options === void 0) { options = {}; } + if (modifiers === void 0) { modifiers = []; } + if (options.peerConnectionOptions) { + this.initPeerConnection(options.peerConnectionOptions); + } + // Merge passed constraints with saved constraints and save + var newConstraints = Object.assign({}, this.constraints, options.constraints); + newConstraints = this.checkAndDefaultConstraints(newConstraints); + if (JSON.stringify(newConstraints) !== JSON.stringify(this.constraints)) { + this.constraints = newConstraints; + this.shouldAcquireMedia = true; + } + if (!Array.isArray(modifiers)) { + modifiers = [modifiers]; + } + modifiers = modifiers.concat(this.modifiers); + return Promise.resolve().then(function () { + if (_this.shouldAcquireMedia) { + return _this.acquire(_this.constraints).then(function () { + _this.shouldAcquireMedia = false; + }); + } + }).then(function () { return _this.createOfferOrAnswer(options.RTCOfferOptions, modifiers); }) + .then(function (description) { + if (description.sdp === undefined) { + throw new Exceptions_1.Exceptions.SessionDescriptionHandlerError("getDescription", undefined, "SDP undefined"); + } + _this.emit("getDescription", description); + return { + body: description.sdp, + contentType: _this.CONTENT_TYPE + }; + }); + }; + /** + * Check if the Session Description Handler can handle the Content-Type described by a SIP Message + * @param {String} contentType The content type that is in the SIP Message + * @returns {boolean} + */ + SessionDescriptionHandler.prototype.hasDescription = function (contentType) { + return contentType === this.CONTENT_TYPE; + }; + /** + * The modifier that should be used when the session would like to place the call on hold + * @param {String} [sdp] The description that will be modified + * @returns {Promise} Promise that resolves with modified SDP + */ + SessionDescriptionHandler.prototype.holdModifier = function (description) { + if (!description.sdp) { + return Promise.resolve(description); + } + if (!(/a=(sendrecv|sendonly|recvonly|inactive)/).test(description.sdp)) { + description.sdp = description.sdp.replace(/(m=[^\r]*\r\n)/g, "$1a=sendonly\r\n"); + } + else { + description.sdp = description.sdp.replace(/a=sendrecv\r\n/g, "a=sendonly\r\n"); + description.sdp = description.sdp.replace(/a=recvonly\r\n/g, "a=inactive\r\n"); + } + return Promise.resolve(description); + }; + /** + * Set the remote description to the underlying media implementation + * @param {String} sessionDescription The description provided by a SIP message to be set on the media implementation + * @param {Object} [options] Options object to be used by getDescription + * @param {MediaStreamConstraints} [options.constraints] MediaStreamConstraints + * https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamConstraints + * @param {Object} [options.peerConnectionOptions] If this is set it will recreate the peer + * connection with the new options + * @param {Array} [modifiers] Array with one time use description modifiers + * @returns {Promise} Promise that resolves once the description is set + */ + SessionDescriptionHandler.prototype.setDescription = function (sessionDescription, options, modifiers) { + var _this = this; + if (options === void 0) { options = {}; } + if (modifiers === void 0) { modifiers = []; } + if (options.peerConnectionOptions) { + this.initPeerConnection(options.peerConnectionOptions); + } + if (!Array.isArray(modifiers)) { + modifiers = [modifiers]; + } + modifiers = modifiers.concat(this.modifiers); + var description = { + type: this.hasOffer("local") ? "answer" : "offer", + sdp: sessionDescription + }; + return Promise.resolve().then(function () { + // Media should be acquired in getDescription unless we need to do it sooner for some reason (FF61+) + if (_this.shouldAcquireMedia && _this.options.alwaysAcquireMediaFirst) { + return _this.acquire(_this.constraints).then(function () { + _this.shouldAcquireMedia = false; + }); + } + }).then(function () { return Utils_1.Utils.reducePromises(modifiers, description); }) + .catch(function (e) { + if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { + throw e; + } + var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("setDescription", e, "The modifiers did not resolve successfully"); + _this.logger.error(error.message); + _this.emit("peerConnection-setRemoteDescriptionFailed", error); + throw error; + }).then(function (modifiedDescription) { + _this.emit("setDescription", modifiedDescription); + return _this.peerConnection.setRemoteDescription(modifiedDescription); + }).catch(function (e) { + if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { + throw e; + } + // Check the original SDP for video, and ensure that we have want to do audio fallback + if ((/^m=video.+$/gm).test(sessionDescription) && !options.disableAudioFallback) { + // Do not try to audio fallback again + options.disableAudioFallback = true; + // Remove video first, then do the other modifiers + return _this.setDescription(sessionDescription, options, [Modifiers.stripVideo].concat(modifiers)); + } + var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("setDescription", e); + if (error.error) { + _this.logger.error(error.error); + } + _this.emit("peerConnection-setRemoteDescriptionFailed", error); + throw error; + }).then(function () { + if (_this.peerConnection.getReceivers) { + _this.emit("setRemoteDescription", _this.peerConnection.getReceivers()); + } + else { + _this.emit("setRemoteDescription", _this.peerConnection.getRemoteStreams()); + } + _this.emit("confirmed", _this); + }); + }; + /** + * Send DTMF via RTP (RFC 4733) + * @param {String} tones A string containing DTMF digits + * @param {Object} [options] Options object to be used by sendDtmf + * @returns {boolean} true if DTMF send is successful, false otherwise + */ + SessionDescriptionHandler.prototype.sendDtmf = function (tones, options) { + if (options === void 0) { options = {}; } + if (!this.dtmfSender && this.hasBrowserGetSenderSupport()) { + var senders = this.peerConnection.getSenders(); + if (senders.length > 0) { + this.dtmfSender = senders[0].dtmf; + } + } + if (!this.dtmfSender && this.hasBrowserTrackSupport()) { + var streams = this.peerConnection.getLocalStreams(); + if (streams.length > 0) { + var audioTracks = streams[0].getAudioTracks(); + if (audioTracks.length > 0) { + this.dtmfSender = this.peerConnection.createDTMFSender(audioTracks[0]); + } + } + } + if (!this.dtmfSender) { + return false; + } + try { + this.dtmfSender.insertDTMF(tones, options.duration, options.interToneGap); + } + catch (e) { + if (e.type === "InvalidStateError" || e.type === "InvalidCharacterError") { + this.logger.error(e); + return false; + } + else { + throw e; + } + } + this.logger.log("DTMF sent via RTP: " + tones.toString()); + return true; + }; + /** + * Get the direction of the session description + * @returns {String} direction of the description + */ + SessionDescriptionHandler.prototype.getDirection = function () { + return this.direction; + }; + SessionDescriptionHandler.prototype.on = function (name, callback) { return _super.prototype.on.call(this, name, callback); }; + // Internal functions + SessionDescriptionHandler.prototype.createOfferOrAnswer = function (RTCOfferOptions, modifiers) { + var _this = this; + if (RTCOfferOptions === void 0) { RTCOfferOptions = {}; } + if (modifiers === void 0) { modifiers = []; } + var methodName = this.hasOffer("remote") ? "createAnswer" : "createOffer"; + var pc = this.peerConnection; + this.logger.log(methodName); + var method = this.hasOffer("remote") ? pc.createAnswer : pc.createOffer; + return method(RTCOfferOptions).catch(function (e) { + if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { + throw e; + } + var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("createOfferOrAnswer", e, "peerConnection-" + methodName + "Failed"); + _this.emit("peerConnection-" + methodName + "Failed", error); + throw error; + }).then(function (sdp) { + return Utils_1.Utils.reducePromises(modifiers, _this.createRTCSessionDescriptionInit(sdp)); + }).then(function (sdp) { + _this.resetIceGatheringComplete(); + _this.logger.log("Setting local sdp."); + _this.logger.log("sdp is " + sdp.sdp || false); + return pc.setLocalDescription(sdp); + }).catch(function (e) { + if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { + throw e; + } + var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("createOfferOrAnswer", e, "peerConnection-SetLocalDescriptionFailed"); + _this.emit("peerConnection-SetLocalDescriptionFailed", error); + throw error; + }).then(function () { return _this.waitForIceGatheringComplete(); }) + .then(function () { + var localDescription = _this.createRTCSessionDescriptionInit(_this.peerConnection.localDescription); + return Utils_1.Utils.reducePromises(modifiers, localDescription); + }).then(function (localDescription) { + _this.setDirection(localDescription.sdp || ""); + return localDescription; + }).catch(function (e) { + if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { + throw e; + } + var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("createOfferOrAnswer", e); + _this.logger.error(error.toString()); + throw error; + }); + }; + // Creates an RTCSessionDescriptionInit from an RTCSessionDescription + SessionDescriptionHandler.prototype.createRTCSessionDescriptionInit = function (RTCSessionDescription) { + return { + type: RTCSessionDescription.type, + sdp: RTCSessionDescription.sdp + }; + }; + SessionDescriptionHandler.prototype.addDefaultIceCheckingTimeout = function (peerConnectionOptions) { + if (peerConnectionOptions.iceCheckingTimeout === undefined) { + peerConnectionOptions.iceCheckingTimeout = 5000; + } + return peerConnectionOptions; + }; + SessionDescriptionHandler.prototype.addDefaultIceServers = function (rtcConfiguration) { + if (!rtcConfiguration.iceServers) { + rtcConfiguration.iceServers = [{ urls: "stun:stun.l.google.com:19302" }]; + } + return rtcConfiguration; + }; + SessionDescriptionHandler.prototype.checkAndDefaultConstraints = function (constraints) { + var defaultConstraints = { audio: true, video: !this.options.alwaysAcquireMediaFirst }; + constraints = constraints || defaultConstraints; + // Empty object check + if (Object.keys(constraints).length === 0 && constraints.constructor === Object) { + return defaultConstraints; + } + return constraints; + }; + SessionDescriptionHandler.prototype.hasBrowserTrackSupport = function () { + return Boolean(this.peerConnection.addTrack); + }; + SessionDescriptionHandler.prototype.hasBrowserGetSenderSupport = function () { + return Boolean(this.peerConnection.getSenders); + }; + SessionDescriptionHandler.prototype.initPeerConnection = function (options) { + var _this = this; + if (options === void 0) { options = {}; } + options = this.addDefaultIceCheckingTimeout(options); + options.rtcConfiguration = options.rtcConfiguration || {}; + options.rtcConfiguration = this.addDefaultIceServers(options.rtcConfiguration); + this.logger.log("initPeerConnection"); + if (this.peerConnection) { + this.logger.log("Already have a peer connection for this session. Tearing down."); + this.resetIceGatheringComplete(); + this.peerConnection.close(); + } + this.peerConnection = new this.WebRTC.RTCPeerConnection(options.rtcConfiguration); + this.logger.log("New peer connection created"); + if ("ontrack" in this.peerConnection) { + this.peerConnection.addEventListener("track", function (e) { + _this.logger.log("track added"); + _this.observer.trackAdded(); + _this.emit("addTrack", e); + }); + } + else { + this.logger.warn("Using onaddstream which is deprecated"); + this.peerConnection.onaddstream = function (e) { + _this.logger.log("stream added"); + _this.emit("addStream", e); + }; + } + this.peerConnection.onicecandidate = function (e) { + _this.emit("iceCandidate", e); + if (e.candidate) { + _this.logger.log("ICE candidate received: " + + (e.candidate.candidate === null ? null : e.candidate.candidate.trim())); + } + else if (e.candidate === null) { + // indicates the end of candidate gathering + _this.logger.log("ICE candidate gathering complete"); + _this.triggerIceGatheringComplete(); + } + }; + this.peerConnection.onicegatheringstatechange = function () { + _this.logger.log("RTCIceGatheringState changed: " + _this.peerConnection.iceGatheringState); + switch (_this.peerConnection.iceGatheringState) { + case "gathering": + _this.emit("iceGathering", _this); + if (!_this.iceGatheringTimer && options.iceCheckingTimeout) { + _this.iceGatheringTimeout = false; + _this.iceGatheringTimer = setTimeout(function () { + _this.logger.log("RTCIceChecking Timeout Triggered after " + options.iceCheckingTimeout + " milliseconds"); + _this.iceGatheringTimeout = true; + _this.triggerIceGatheringComplete(); + }, options.iceCheckingTimeout); + } + break; + case "complete": + _this.triggerIceGatheringComplete(); + break; + } + }; + this.peerConnection.oniceconnectionstatechange = function () { + var stateEvent; + switch (_this.peerConnection.iceConnectionState) { + case "new": + stateEvent = "iceConnection"; + break; + case "checking": + stateEvent = "iceConnectionChecking"; + break; + case "connected": + stateEvent = "iceConnectionConnected"; + break; + case "completed": + stateEvent = "iceConnectionCompleted"; + break; + case "failed": + stateEvent = "iceConnectionFailed"; + break; + case "disconnected": + stateEvent = "iceConnectionDisconnected"; + break; + case "closed": + stateEvent = "iceConnectionClosed"; + break; + default: + _this.logger.warn("Unknown iceConnection state: " + _this.peerConnection.iceConnectionState); + return; + } + _this.logger.log("ICE Connection State changed to " + stateEvent); + _this.emit(stateEvent, _this); + }; + }; + SessionDescriptionHandler.prototype.acquire = function (constraints) { + var _this = this; + // Default audio & video to true + constraints = this.checkAndDefaultConstraints(constraints); + return new Promise(function (resolve, reject) { + /* + * Make the call asynchronous, so that ICCs have a chance + * to define callbacks to `userMediaRequest` + */ + _this.logger.log("acquiring local media"); + _this.emit("userMediaRequest", constraints); + if (constraints.audio || constraints.video) { + _this.WebRTC.getUserMedia(constraints).then(function (streams) { + _this.observer.trackAdded(); + _this.emit("userMedia", streams); + resolve(streams); + }).catch(function (e) { + _this.emit("userMediaFailed", e); + reject(e); + }); + } + else { + // Local streams were explicitly excluded. + resolve([]); + } + }).catch(function (e) { + if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { + throw e; + } + var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("acquire", e, "unable to acquire streams"); + _this.logger.error(error.message); + if (error.error) { + _this.logger.error(error.error); + } + throw error; + }).then(function (streams) { + _this.logger.log("acquired local media streams"); + try { + // Remove old tracks + if (_this.peerConnection.removeTrack) { + _this.peerConnection.getSenders().forEach(function (sender) { + _this.peerConnection.removeTrack(sender); + }); + } + return streams; + } + catch (e) { + return Promise.reject(e); + } + }).catch(function (e) { + if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { + throw e; + } + var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("acquire", e, "error removing streams"); + _this.logger.error(error.message); + if (error.error) { + _this.logger.error(error.error); + } + throw error; + }).then(function (streams) { + try { + streams = [].concat(streams); + streams.forEach(function (stream) { + if (_this.peerConnection.addTrack) { + stream.getTracks().forEach(function (track) { + _this.peerConnection.addTrack(track, stream); + }); + } + else { + // Chrome 59 does not support addTrack + _this.peerConnection.addStream(stream); + } + }); + } + catch (e) { + return Promise.reject(e); + } + return Promise.resolve(); + }).catch(function (e) { + if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { + throw e; + } + var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("acquire", e, "error adding stream"); + _this.logger.error(error.message); + if (error.error) { + _this.logger.error(error.error); + } + throw error; + }); + }; + SessionDescriptionHandler.prototype.hasOffer = function (where) { + var offerState = "have-" + where + "-offer"; + return this.peerConnection.signalingState === offerState; + }; + // ICE gathering state handling + SessionDescriptionHandler.prototype.isIceGatheringComplete = function () { + return this.peerConnection.iceGatheringState === "complete" || this.iceGatheringTimeout; + }; + SessionDescriptionHandler.prototype.resetIceGatheringComplete = function () { + this.iceGatheringTimeout = false; + this.logger.log("resetIceGatheringComplete"); + if (this.iceGatheringTimer) { + clearTimeout(this.iceGatheringTimer); + this.iceGatheringTimer = undefined; + } + if (this.iceGatheringDeferred) { + this.iceGatheringDeferred.reject(); + this.iceGatheringDeferred = undefined; + } + }; + SessionDescriptionHandler.prototype.setDirection = function (sdp) { + var match = sdp.match(/a=(sendrecv|sendonly|recvonly|inactive)/); + if (match === null) { + this.direction = this.C.DIRECTION.NULL; + this.observer.directionChanged(); + return; + } + var direction = match[1]; + switch (direction) { + case this.C.DIRECTION.SENDRECV: + case this.C.DIRECTION.SENDONLY: + case this.C.DIRECTION.RECVONLY: + case this.C.DIRECTION.INACTIVE: + this.direction = direction; + break; + default: + this.direction = this.C.DIRECTION.NULL; + break; + } + this.observer.directionChanged(); + }; + SessionDescriptionHandler.prototype.triggerIceGatheringComplete = function () { + if (this.isIceGatheringComplete()) { + this.emit("iceGatheringComplete", this); + if (this.iceGatheringTimer) { + clearTimeout(this.iceGatheringTimer); + this.iceGatheringTimer = undefined; + } + if (this.iceGatheringDeferred) { + this.iceGatheringDeferred.resolve(); + this.iceGatheringDeferred = undefined; + } + } + }; + SessionDescriptionHandler.prototype.waitForIceGatheringComplete = function () { + this.logger.log("waitForIceGatheringComplete"); + if (this.isIceGatheringComplete()) { + this.logger.log("ICE is already complete. Return resolved."); + return Promise.resolve(); + } + else if (!this.iceGatheringDeferred) { + this.iceGatheringDeferred = Utils_1.Utils.defer(); + } + this.logger.log("ICE is not complete. Returning promise"); + return this.iceGatheringDeferred ? this.iceGatheringDeferred.promise : Promise.resolve(); + }; + return SessionDescriptionHandler; +}(events_1.EventEmitter)); +exports.SessionDescriptionHandler = SessionDescriptionHandler; + +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(77))) + +/***/ }), +/* 112 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +var stripPayload = function (sdp, payload) { + var mediaDescs = []; + var lines = sdp.split(/\r\n/); + var currentMediaDesc; + for (var i = 0; i < lines.length;) { + var line = lines[i]; + if (/^m=(?:audio|video)/.test(line)) { + currentMediaDesc = { + index: i, + stripped: [] + }; + mediaDescs.push(currentMediaDesc); + } + else if (currentMediaDesc) { + var rtpmap = /^a=rtpmap:(\d+) ([^/]+)\//.exec(line); + if (rtpmap && payload === rtpmap[2]) { + lines.splice(i, 1); + currentMediaDesc.stripped.push(rtpmap[1]); + continue; // Don't increment 'i' + } + } + i++; + } + for (var _i = 0, mediaDescs_1 = mediaDescs; _i < mediaDescs_1.length; _i++) { + var mediaDesc = mediaDescs_1[_i]; + var mline = lines[mediaDesc.index].split(" "); + // Ignore the first 3 parameters of the mline. The codec information is after that + for (var j = 3; j < mline.length;) { + if (mediaDesc.stripped.indexOf(mline[j]) !== -1) { + mline.splice(j, 1); + continue; + } + j++; + } + lines[mediaDesc.index] = mline.join(" "); + } + return lines.join("\r\n"); +}; +var stripMediaDescription = function (sdp, description) { + var descriptionRegExp = new RegExp("m=" + description + ".*$", "gm"); + var groupRegExp = new RegExp("^a=group:.*$", "gm"); + if (descriptionRegExp.test(sdp)) { + var midLineToRemove_1; + sdp = sdp.split(/^m=/gm).filter(function (section) { + if (section.substr(0, description.length) === description) { + midLineToRemove_1 = section.match(/^a=mid:.*$/gm); + if (midLineToRemove_1) { + var step = midLineToRemove_1[0].match(/:.+$/g); + if (step) { + midLineToRemove_1 = step[0].substr(1); + } + } + return false; + } + return true; + }).join("m="); + var groupLine = sdp.match(groupRegExp); + if (groupLine && groupLine.length === 1) { + var groupLinePortion = groupLine[0]; + var groupRegExpReplace = new RegExp("\ *" + midLineToRemove_1 + "[^\ ]*", "g"); + groupLinePortion = groupLinePortion.replace(groupRegExpReplace, ""); + sdp = sdp.split(groupRegExp).join(groupLinePortion); + } + } + return sdp; +}; +function stripTcpCandidates(description) { + description.sdp = (description.sdp || "").replace(/^a=candidate:\d+ \d+ tcp .*?\r\n/img, ""); + return Promise.resolve(description); +} +exports.stripTcpCandidates = stripTcpCandidates; +function stripTelephoneEvent(description) { + description.sdp = stripPayload(description.sdp || "", "telephone-event"); + return Promise.resolve(description); +} +exports.stripTelephoneEvent = stripTelephoneEvent; +function cleanJitsiSdpImageattr(description) { + description.sdp = (description.sdp || "").replace(/^(a=imageattr:.*?)(x|y)=\[0-/gm, "$1$2=[1:"); + return Promise.resolve(description); +} +exports.cleanJitsiSdpImageattr = cleanJitsiSdpImageattr; +function stripG722(description) { + description.sdp = stripPayload(description.sdp || "", "G722"); + return Promise.resolve(description); +} +exports.stripG722 = stripG722; +function stripRtpPayload(payload) { + return function (description) { + description.sdp = stripPayload(description.sdp || "", payload); + return Promise.resolve(description); + }; +} +exports.stripRtpPayload = stripRtpPayload; +function stripVideo(description) { + description.sdp = stripMediaDescription(description.sdp || "", "video"); + return Promise.resolve(description); +} +exports.stripVideo = stripVideo; +function addMidLines(description) { + var sdp = description.sdp || ""; + if (sdp.search(/^a=mid.*$/gm) === -1) { + var mlines_1 = sdp.match(/^m=.*$/gm); + var sdpArray_1 = sdp.split(/^m=.*$/gm); + if (mlines_1) { + mlines_1.forEach(function (elem, idx) { + mlines_1[idx] = elem + "\na=mid:" + idx; + }); + } + sdpArray_1.forEach(function (elem, idx) { + if (mlines_1 && mlines_1[idx]) { + sdpArray_1[idx] = elem + mlines_1[idx]; + } + }); + sdp = sdpArray_1.join(""); + description.sdp = sdp; + } + return Promise.resolve(description); +} +exports.addMidLines = addMidLines; + + +/***/ }), +/* 113 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +var Enums_1 = __webpack_require__(5); +/* SessionDescriptionHandlerObserver + * @class SessionDescriptionHandler Observer Class. + * @param {SIP.Session} session + * @param {Object} [options] + */ +var SessionDescriptionHandlerObserver = /** @class */ (function () { + function SessionDescriptionHandlerObserver(session, options) { + this.type = Enums_1.TypeStrings.SessionDescriptionHandlerObserver; + this.session = session; + this.options = options; + } + SessionDescriptionHandlerObserver.prototype.trackAdded = function () { + this.session.emit("trackAdded"); + }; + SessionDescriptionHandlerObserver.prototype.directionChanged = function () { + this.session.emit("directionChanged"); + }; + return SessionDescriptionHandlerObserver; +}()); +exports.SessionDescriptionHandlerObserver = SessionDescriptionHandlerObserver; + + +/***/ }), +/* 114 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(global) { +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Enums_1 = __webpack_require__(5); +var Exceptions_1 = __webpack_require__(47); +var Grammar_1 = __webpack_require__(7); +var Transport_1 = __webpack_require__(75); +var Utils_1 = __webpack_require__(11); +var TransportStatus; +(function (TransportStatus) { + TransportStatus[TransportStatus["STATUS_CONNECTING"] = 0] = "STATUS_CONNECTING"; + TransportStatus[TransportStatus["STATUS_OPEN"] = 1] = "STATUS_OPEN"; + TransportStatus[TransportStatus["STATUS_CLOSING"] = 2] = "STATUS_CLOSING"; + TransportStatus[TransportStatus["STATUS_CLOSED"] = 3] = "STATUS_CLOSED"; +})(TransportStatus = exports.TransportStatus || (exports.TransportStatus = {})); +/** + * Compute an amount of time in seconds to wait before sending another + * keep-alive. + * @returns {Number} + */ +var computeKeepAliveTimeout = function (upperBound) { + var lowerBound = upperBound * 0.8; + return 1000 * (Math.random() * (upperBound - lowerBound) + lowerBound); +}; +/** + * @class Transport + * @param {Object} options + */ +var Transport = /** @class */ (function (_super) { + __extends(Transport, _super); + function Transport(logger, options) { + if (options === void 0) { options = {}; } + var _this = _super.call(this, logger, options) || this; + _this.WebSocket = (global.window || global).WebSocket; + _this.type = Enums_1.TypeStrings.Transport; + _this.reconnectionAttempts = 0; + _this.status = TransportStatus.STATUS_CONNECTING; + _this.configuration = _this.loadConfig(options); + _this.server = _this.configuration.wsServers[0]; + return _this; + } + /** + * @returns {Boolean} + */ + Transport.prototype.isConnected = function () { + return this.status === TransportStatus.STATUS_OPEN; + }; + /** + * Send a message. + * @param {SIP.OutgoingRequest|String} msg + * @param {Object} [options] + * @returns {Promise} + */ + Transport.prototype.sendPromise = function (msg, options) { + if (options === void 0) { options = {}; } + if (!this.statusAssert(TransportStatus.STATUS_OPEN, options.force)) { + this.onError("unable to send message - WebSocket not open"); + return Promise.reject(); + } + var message = msg.toString(); + if (this.ws) { + if (this.configuration.traceSip === true) { + this.logger.log("sending WebSocket message:\n\n" + message + "\n"); + } + this.ws.send(message); + return Promise.resolve({ msg: message }); + } + else { + this.onError("unable to send message - WebSocket does not exist"); + return Promise.reject(); + } + }; + /** + * Disconnect socket. + */ + Transport.prototype.disconnectPromise = function (options) { + var _this = this; + if (options === void 0) { options = {}; } + if (this.disconnectionPromise) { // Already disconnecting. Just return this. + return this.disconnectionPromise; + } + options.code = options.code || 1000; + if (!this.statusTransition(TransportStatus.STATUS_CLOSING, options.force)) { + if (this.status === TransportStatus.STATUS_CLOSED) { // Websocket is already closed + return Promise.resolve({ overrideEvent: true }); + } + else if (this.connectionPromise) { // Websocket is connecting, cannot move to disconneting yet + return this.connectionPromise.then(function () { return Promise.reject("The websocket did not disconnect"); }) + .catch(function () { return Promise.resolve({ overrideEvent: true }); }); + } + else { + // Cannot move to disconnecting, but not in connecting state. + return Promise.reject("The websocket did not disconnect"); + } + } + this.emit("disconnecting"); + this.disconnectionPromise = new Promise(function (resolve, reject) { + _this.disconnectDeferredResolve = resolve; + if (_this.reconnectTimer) { + clearTimeout(_this.reconnectTimer); + _this.reconnectTimer = undefined; + } + if (_this.ws) { + _this.stopSendingKeepAlives(); + _this.logger.log("closing WebSocket " + _this.server.wsUri); + _this.ws.close(options.code, options.reason); + } + else { + reject("Attempted to disconnect but the websocket doesn't exist"); + } + }); + return this.disconnectionPromise; + }; + /** + * Connect socket. + */ + Transport.prototype.connectPromise = function (options) { + var _this = this; + if (options === void 0) { options = {}; } + if (this.status === TransportStatus.STATUS_CLOSING && !options.force) { + return Promise.reject("WebSocket " + this.server.wsUri + " is closing"); + } + if (this.connectionPromise) { + return this.connectionPromise; + } + this.server = this.server || this.getNextWsServer(options.force); + this.connectionPromise = new Promise(function (resolve, reject) { + if ((_this.status === TransportStatus.STATUS_OPEN || _this.status === TransportStatus.STATUS_CLOSING) + && !options.force) { + _this.logger.warn("WebSocket " + _this.server.wsUri + " is already connected"); + reject("Failed status check - attempted to open a connection but already open/closing"); + return; + } + _this.connectDeferredResolve = resolve; + _this.status = TransportStatus.STATUS_CONNECTING; + _this.emit("connecting"); + _this.logger.log("connecting to WebSocket " + _this.server.wsUri); + _this.disposeWs(); + try { + _this.ws = new WebSocket(_this.server.wsUri, "sip"); + } + catch (e) { + _this.ws = null; + _this.status = TransportStatus.STATUS_CLOSED; // force status to closed in error case + _this.onError("error connecting to WebSocket " + _this.server.wsUri + ":" + e); + reject("Failed to create a websocket"); + return; + } + if (!_this.ws) { + reject("Unexpected instance websocket not set"); + return; + } + _this.connectionTimeout = setTimeout(function () { + _this.statusTransition(TransportStatus.STATUS_CLOSED); + _this.logger.warn("took too long to connect - exceeded time set in configuration.connectionTimeout: " + + _this.configuration.connectionTimeout + "s"); + _this.emit("disconnected", { code: 1000 }); + _this.connectionPromise = undefined; + reject("Connection timeout"); + }, _this.configuration.connectionTimeout * 1000); + _this.boundOnOpen = _this.onOpen.bind(_this); + _this.boundOnMessage = _this.onMessage.bind(_this); + _this.boundOnClose = _this.onClose.bind(_this); + _this.boundOnError = _this.onWebsocketError.bind(_this); + _this.ws.addEventListener("open", _this.boundOnOpen); + _this.ws.addEventListener("message", _this.boundOnMessage); + _this.ws.addEventListener("close", _this.boundOnClose); + _this.ws.addEventListener("error", _this.boundOnError); + }); + return this.connectionPromise; + }; + /** + * @event + * @param {event} e + */ + Transport.prototype.onMessage = function (e) { + var data = e.data; + var finishedData; + // CRLF Keep Alive response from server. Clear our keep alive timeout. + if (/^(\r\n)+$/.test(data)) { + this.clearKeepAliveTimeout(); + if (this.configuration.traceSip === true) { + this.logger.log("received WebSocket message with CRLF Keep Alive response"); + } + return; + } + else if (!data) { + this.logger.warn("received empty message, message discarded"); + return; + } + else if (typeof data !== "string") { // WebSocket binary message. + try { + // the UInt8Data was here prior to types, and doesn't check + finishedData = String.fromCharCode.apply(null, new Uint8Array(data)); + } + catch (err) { + this.logger.warn("received WebSocket binary message failed to be converted into string, message discarded"); + return; + } + if (this.configuration.traceSip === true) { + this.logger.log("received WebSocket binary message:\n\n" + data + "\n"); + } + } + else { // WebSocket text message. + if (this.configuration.traceSip === true) { + this.logger.log("received WebSocket text message:\n\n" + data + "\n"); + } + finishedData = data; + } + this.emit("message", finishedData); + }; + // Transport Event Handlers + /** + * @event + * @param {event} e + */ + Transport.prototype.onOpen = function () { + if (this.status === TransportStatus.STATUS_CLOSED) { // Indicated that the transport thinks the ws is dead already + var ws = this.ws; + this.disposeWs(); + ws.close(1000); + return; + } + this.status = TransportStatus.STATUS_OPEN; // quietly force status to open + this.emit("connected"); + if (this.connectionTimeout) { + clearTimeout(this.connectionTimeout); + this.connectionTimeout = undefined; + } + this.logger.log("WebSocket " + this.server.wsUri + " connected"); + // Clear reconnectTimer since we are not disconnected + if (this.reconnectTimer !== undefined) { + clearTimeout(this.reconnectTimer); + this.reconnectTimer = undefined; + } + // Reset reconnectionAttempts + this.reconnectionAttempts = 0; + // Reset disconnection promise so we can disconnect from a fresh state + this.disconnectionPromise = undefined; + this.disconnectDeferredResolve = undefined; + // Start sending keep-alives + this.startSendingKeepAlives(); + if (this.connectDeferredResolve) { + this.connectDeferredResolve({ overrideEvent: true }); + } + else { + this.logger.warn("Unexpected websocket.onOpen with no connectDeferredResolve"); + } + }; + /** + * @event + * @param {event} e + */ + Transport.prototype.onClose = function (e) { + this.logger.log("WebSocket disconnected (code: " + e.code + (e.reason ? "| reason: " + e.reason : "") + ")"); + if (this.status !== TransportStatus.STATUS_CLOSING) { + this.logger.warn("WebSocket closed without SIP.js requesting it"); + this.emit("transportError"); + } + this.stopSendingKeepAlives(); + // Clean up connection variables so we can connect again from a fresh state + if (this.connectionTimeout) { + clearTimeout(this.connectionTimeout); + } + this.connectionTimeout = undefined; + this.connectionPromise = undefined; + this.connectDeferredResolve = undefined; + // Check whether the user requested to close. + if (this.disconnectDeferredResolve) { + this.disconnectDeferredResolve({ overrideEvent: true }); + this.statusTransition(TransportStatus.STATUS_CLOSED); + this.disconnectDeferredResolve = undefined; + return; + } + this.status = TransportStatus.STATUS_CLOSED; // quietly force status to closed + this.emit("disconnected", { code: e.code, reason: e.reason }); + this.reconnect(); + }; + /** + * Removes event listeners and clears the instance ws + */ + Transport.prototype.disposeWs = function () { + if (this.ws) { + this.ws.removeEventListener("open", this.boundOnOpen); + this.ws.removeEventListener("message", this.boundOnMessage); + this.ws.removeEventListener("close", this.boundOnClose); + this.ws.removeEventListener("error", this.boundOnError); + this.ws = undefined; + } + }; + /** + * @event + * @param {string} e + */ + Transport.prototype.onError = function (e) { + this.logger.warn("Transport error: " + e); + this.emit("transportError"); + }; + /** + * @event + * @private + */ + Transport.prototype.onWebsocketError = function () { + this.onError("The Websocket had an error"); + }; + /** + * Reconnection attempt logic. + */ + Transport.prototype.reconnect = function () { + var _this = this; + if (this.reconnectionAttempts > 0) { + this.logger.log("Reconnection attempt " + this.reconnectionAttempts + " failed"); + } + if (this.noAvailableServers()) { + this.logger.warn("attempted to get next ws server but there are no available ws servers left"); + this.logger.warn("no available ws servers left - going to closed state"); + this.status = TransportStatus.STATUS_CLOSED; + this.emit("closed"); + this.resetServerErrorStatus(); + return; + } + if (this.isConnected()) { + this.logger.warn("attempted to reconnect while connected - forcing disconnect"); + this.disconnect({ force: true }); + } + this.reconnectionAttempts += 1; + if (this.reconnectionAttempts > this.configuration.maxReconnectionAttempts) { + this.logger.warn("maximum reconnection attempts for WebSocket " + this.server.wsUri); + this.logger.log("transport " + this.server.wsUri + " failed | connection state set to 'error'"); + this.server.isError = true; + this.emit("transportError"); + if (!this.noAvailableServers()) { + this.server = this.getNextWsServer(); + } + // When there are no available servers, the reconnect function ends on the next recursive call + // after checking for no available servers again. + this.reconnectionAttempts = 0; + this.reconnect(); + } + else { + this.logger.log("trying to reconnect to WebSocket " + + this.server.wsUri + " (reconnection attempt " + this.reconnectionAttempts + ")"); + this.reconnectTimer = setTimeout(function () { + _this.connect(); + _this.reconnectTimer = undefined; + }, (this.reconnectionAttempts === 1) ? 0 : this.configuration.reconnectionTimeout * 1000); + } + }; + /** + * Resets the error state of all servers in the configuration + */ + Transport.prototype.resetServerErrorStatus = function () { + for (var _i = 0, _a = this.configuration.wsServers; _i < _a.length; _i++) { + var websocket = _a[_i]; + websocket.isError = false; + } + }; + /** + * Retrieve the next server to which connect. + * @param {Boolean} force allows bypass of server error status checking + * @returns {Object} WsServer + */ + Transport.prototype.getNextWsServer = function (force) { + if (force === void 0) { force = false; } + if (this.noAvailableServers()) { + this.logger.warn("attempted to get next ws server but there are no available ws servers left"); + throw new Error("Attempted to get next ws server, but there are no available ws servers left."); + } + // Order servers by weight + var candidates = []; + for (var _i = 0, _a = this.configuration.wsServers; _i < _a.length; _i++) { + var wsServer = _a[_i]; + if (wsServer.isError && !force) { + continue; + } + else if (candidates.length === 0) { + candidates.push(wsServer); + } + else if (wsServer.weight > candidates[0].weight) { + candidates = [wsServer]; + } + else if (wsServer.weight === candidates[0].weight) { + candidates.push(wsServer); + } + } + var idx = Math.floor(Math.random() * candidates.length); + return candidates[idx]; + }; + /** + * Checks all configuration servers, returns true if all of them have isError: true and false otherwise + * @returns {Boolean} + */ + Transport.prototype.noAvailableServers = function () { + for (var _i = 0, _a = this.configuration.wsServers; _i < _a.length; _i++) { + var server = _a[_i]; + if (!server.isError) { + return false; + } + } + return true; + }; + // ============================== + // KeepAlive Stuff + // ============================== + /** + * Send a keep-alive (a double-CRLF sequence). + * @returns {Boolean} + */ + Transport.prototype.sendKeepAlive = function () { + var _this = this; + if (this.keepAliveDebounceTimeout) { + // We already have an outstanding keep alive, do not send another. + return; + } + this.keepAliveDebounceTimeout = setTimeout(function () { + _this.emit("keepAliveDebounceTimeout"); + _this.clearKeepAliveTimeout(); + }, this.configuration.keepAliveDebounce * 1000); + return this.send("\r\n\r\n"); + }; + Transport.prototype.clearKeepAliveTimeout = function () { + if (this.keepAliveDebounceTimeout) { + clearTimeout(this.keepAliveDebounceTimeout); + } + this.keepAliveDebounceTimeout = undefined; + }; + /** + * Start sending keep-alives. + */ + Transport.prototype.startSendingKeepAlives = function () { + var _this = this; + if (this.configuration.keepAliveInterval && !this.keepAliveInterval) { + this.keepAliveInterval = setInterval(function () { + _this.sendKeepAlive(); + _this.startSendingKeepAlives(); + }, computeKeepAliveTimeout(this.configuration.keepAliveInterval)); + } + }; + /** + * Stop sending keep-alives. + */ + Transport.prototype.stopSendingKeepAlives = function () { + if (this.keepAliveInterval) { + clearInterval(this.keepAliveInterval); + } + if (this.keepAliveDebounceTimeout) { + clearTimeout(this.keepAliveDebounceTimeout); + } + this.keepAliveInterval = undefined; + this.keepAliveDebounceTimeout = undefined; + }; + // ============================== + // Status Stuff + // ============================== + /** + * Checks given status against instance current status. Returns true if they match + * @param {Number} status + * @param {Boolean} [force] + * @returns {Boolean} + */ + Transport.prototype.statusAssert = function (status, force) { + if (status === this.status) { + return true; + } + else { + if (force) { + this.logger.warn("Attempted to assert " + + Object.keys(TransportStatus)[this.status] + " as " + + Object.keys(TransportStatus)[status] + "- continuing with option: 'force'"); + return true; + } + else { + this.logger.warn("Tried to assert " + + Object.keys(TransportStatus)[status] + " but is currently " + + Object.keys(TransportStatus)[this.status]); + return false; + } + } + }; + /** + * Transitions the status. Checks for legal transition via assertion beforehand + * @param {Number} status + * @param {Boolean} [force] + * @returns {Boolean} + */ + Transport.prototype.statusTransition = function (status, force) { + if (force === void 0) { force = false; } + this.logger.log("Attempting to transition status from " + + Object.keys(TransportStatus)[this.status] + " to " + + Object.keys(TransportStatus)[status]); + if ((status === TransportStatus.STATUS_CONNECTING && this.statusAssert(TransportStatus.STATUS_CLOSED, force)) || + (status === TransportStatus.STATUS_OPEN && this.statusAssert(TransportStatus.STATUS_CONNECTING, force)) || + (status === TransportStatus.STATUS_CLOSING && this.statusAssert(TransportStatus.STATUS_OPEN, force)) || + (status === TransportStatus.STATUS_CLOSED)) { + this.status = status; + return true; + } + else { + this.logger.warn("Status transition failed - result: no-op - reason:" + + " either gave an nonexistent status or attempted illegal transition"); + return false; + } + }; + // ============================== + // Configuration Handling + // ============================== + /** + * Configuration load. + * returns {Configuration} + */ + Transport.prototype.loadConfig = function (configuration) { + var settings = { + wsServers: [{ + scheme: "WSS", + sipUri: "", + weight: 0, + wsUri: "wss://edge.sip.onsip.com", + isError: false + }], + connectionTimeout: 5, + maxReconnectionAttempts: 3, + reconnectionTimeout: 4, + keepAliveInterval: 0, + keepAliveDebounce: 10, + // Logging + traceSip: false + }; + var configCheck = this.getConfigurationCheck(); + // Check Mandatory parameters + for (var parameter in configCheck.mandatory) { + if (!configuration.hasOwnProperty(parameter)) { + throw new Exceptions_1.Exceptions.ConfigurationError(parameter); + } + else { + var value = configuration[parameter]; + var checkedValue = configCheck.mandatory[parameter](value); + if (checkedValue !== undefined) { + settings[parameter] = checkedValue; + } + else { + throw new Exceptions_1.Exceptions.ConfigurationError(parameter, value); + } + } + } + // Check Optional parameters + for (var parameter in configCheck.optional) { + if (configuration.hasOwnProperty(parameter)) { + var value = configuration[parameter]; + // If the parameter value is an empty array, but shouldn't be, apply its default value. + // If the parameter value is null, empty string, or undefined then apply its default value. + // If it's a number with NaN value then also apply its default value. + // NOTE: JS does not allow "value === NaN", the following does the work: + if ((value instanceof Array && value.length === 0) || + (value === null || value === "" || value === undefined) || + (typeof (value) === "number" && isNaN(value))) { + continue; + } + var checkedValue = configCheck.optional[parameter](value); + if (checkedValue !== undefined) { + settings[parameter] = checkedValue; + } + else { + throw new Exceptions_1.Exceptions.ConfigurationError(parameter, value); + } + } + } + var skeleton = {}; // Fill the value of the configuration_skeleton + for (var parameter in settings) { + if (settings.hasOwnProperty(parameter)) { + skeleton[parameter] = { + value: settings[parameter], + }; + } + } + var returnConfiguration = Object.defineProperties({}, skeleton); + this.logger.log("configuration parameters after validation:"); + for (var parameter in settings) { + if (settings.hasOwnProperty(parameter)) { + this.logger.log("· " + parameter + ": " + JSON.stringify(settings[parameter])); + } + } + return returnConfiguration; + }; + /** + * Configuration checker. + * @return {Boolean} + */ + Transport.prototype.getConfigurationCheck = function () { + return { + mandatory: {}, + optional: { + // Note: this function used to call 'this.logger.error' but calling 'this' with anything here is invalid + wsServers: function (wsServers) { + /* Allow defining wsServers parameter as: + * String: "host" + * Array of Strings: ["host1", "host2"] + * Array of Objects: [{wsUri:"host1", weight:1}, {wsUri:"host2", weight:0}] + * Array of Objects and Strings: [{wsUri:"host1"}, "host2"] + */ + if (typeof wsServers === "string") { + wsServers = [{ wsUri: wsServers }]; + } + else if (wsServers instanceof Array) { + for (var idx = 0; idx < wsServers.length; idx++) { + if (typeof wsServers[idx] === "string") { + wsServers[idx] = { wsUri: wsServers[idx] }; + } + } + } + else { + return; + } + if (wsServers.length === 0) { + return false; + } + for (var _i = 0, wsServers_1 = wsServers; _i < wsServers_1.length; _i++) { + var wsServer = wsServers_1[_i]; + if (!wsServer.wsUri) { + return; + } + if (wsServer.weight && !Number(wsServer.weight)) { + return; + } + var url = Grammar_1.Grammar.parse(wsServer.wsUri, "absoluteURI"); + if (url === -1) { + return; + } + else if (["wss", "ws", "udp"].indexOf(url.scheme) < 0) { + return; + } + else { + wsServer.sipUri = ""; + if (!wsServer.weight) { + wsServer.weight = 0; + } + wsServer.isError = false; + wsServer.scheme = url.scheme.toUpperCase(); + } + } + return wsServers; + }, + keepAliveInterval: function (keepAliveInterval) { + if (Utils_1.Utils.isDecimal(keepAliveInterval)) { + var value = Number(keepAliveInterval); + if (value > 0) { + return value; + } + } + }, + keepAliveDebounce: function (keepAliveDebounce) { + if (Utils_1.Utils.isDecimal(keepAliveDebounce)) { + var value = Number(keepAliveDebounce); + if (value > 0) { + return value; + } + } + }, + traceSip: function (traceSip) { + if (typeof traceSip === "boolean") { + return traceSip; + } + }, + connectionTimeout: function (connectionTimeout) { + if (Utils_1.Utils.isDecimal(connectionTimeout)) { + var value = Number(connectionTimeout); + if (value > 0) { + return value; + } + } + }, + maxReconnectionAttempts: function (maxReconnectionAttempts) { + if (Utils_1.Utils.isDecimal(maxReconnectionAttempts)) { + var value = Number(maxReconnectionAttempts); + if (value >= 0) { + return value; + } + } + }, + reconnectionTimeout: function (reconnectionTimeout) { + if (Utils_1.Utils.isDecimal(reconnectionTimeout)) { + var value = Number(reconnectionTimeout); + if (value > 0) { + return value; + } + } + } + } + }; + }; + Transport.C = TransportStatus; + return Transport; +}(Transport_1.Transport)); +exports.Transport = Transport; + +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(77))) + +/***/ }), +/* 115 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +var Modifiers = __webpack_require__(112); +exports.Modifiers = Modifiers; +var Simple_1 = __webpack_require__(116); +exports.Simple = Simple_1.Simple; +var SessionDescriptionHandler_1 = __webpack_require__(111); +exports.SessionDescriptionHandler = SessionDescriptionHandler_1.SessionDescriptionHandler; +var Transport_1 = __webpack_require__(114); +exports.Transport = Transport_1.Transport; + + +/***/ }), +/* 116 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(global) { +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var events_1 = __webpack_require__(2); +var UA_1 = __webpack_require__(76); +var Modifiers = __webpack_require__(112); +/* Simple + * @class Simple + */ +var SimpleStatus; +(function (SimpleStatus) { + SimpleStatus[SimpleStatus["STATUS_NULL"] = 0] = "STATUS_NULL"; + SimpleStatus[SimpleStatus["STATUS_NEW"] = 1] = "STATUS_NEW"; + SimpleStatus[SimpleStatus["STATUS_CONNECTING"] = 2] = "STATUS_CONNECTING"; + SimpleStatus[SimpleStatus["STATUS_CONNECTED"] = 3] = "STATUS_CONNECTED"; + SimpleStatus[SimpleStatus["STATUS_COMPLETED"] = 4] = "STATUS_COMPLETED"; +})(SimpleStatus = exports.SimpleStatus || (exports.SimpleStatus = {})); +var Simple = /** @class */ (function (_super) { + __extends(Simple, _super); + function Simple(options) { + var _this = _super.call(this) || this; + /* + * { + * media: { + * remote: { + * audio: , + * video: + * }, + * local: { + * video: + * } + * }, + * ua: { + * + * } + * } + */ + if (options.media.remote.video) { + _this.video = true; + } + else { + _this.video = false; + } + if (options.media.remote.audio) { + _this.audio = true; + } + else { + _this.audio = false; + } + if (!_this.audio && !_this.video) { + // Need to do at least audio or video + // Error + throw new Error("At least one remote audio or video element is required for Simple."); + } + _this.options = options; + // https://stackoverflow.com/questions/7944460/detect-safari-browser + var browserUa = global.navigator.userAgent.toLowerCase(); + var isSafari = false; + var isFirefox = false; + if (browserUa.indexOf("safari") > -1 && browserUa.indexOf("chrome") < 0) { + isSafari = true; + } + else if (browserUa.indexOf("firefox") > -1 && browserUa.indexOf("chrome") < 0) { + isFirefox = true; + } + var sessionDescriptionHandlerFactoryOptions = {}; + if (isSafari) { + sessionDescriptionHandlerFactoryOptions.modifiers = [Modifiers.stripG722]; + } + if (isFirefox) { + sessionDescriptionHandlerFactoryOptions.alwaysAcquireMediaFirst = true; + } + if (!_this.options.ua.uri) { + _this.anonymous = true; + } + else { + _this.anonymous = false; + } + _this.ua = new UA_1.UA({ + // User Configurable Options + uri: _this.options.ua.uri, + authorizationUser: _this.options.ua.authorizationUser, + password: _this.options.ua.password, + displayName: _this.options.ua.displayName, + // Undocumented "Advanced" Options + userAgentString: _this.options.ua.userAgentString, + // Fixed Options + register: true, + sessionDescriptionHandlerFactoryOptions: sessionDescriptionHandlerFactoryOptions, + transportOptions: { + traceSip: _this.options.ua.traceSip, + wsServers: _this.options.ua.wsServers + } + }); + _this.state = SimpleStatus.STATUS_NULL; + _this.logger = _this.ua.getLogger("sip.simple"); + _this.ua.on("registered", function () { + _this.emit("registered", _this.ua); + }); + _this.ua.on("unregistered", function () { + _this.emit("unregistered", _this.ua); + }); + _this.ua.on("registrationFailed", function () { + _this.emit("unregistered", _this.ua); + }); + _this.ua.on("invite", function (session) { + // If there is already an active session reject the incoming session + if (_this.state !== SimpleStatus.STATUS_NULL && _this.state !== SimpleStatus.STATUS_COMPLETED) { + _this.logger.warn("Rejecting incoming call. Simple only supports 1 call at a time"); + session.reject(); + return; + } + _this.session = session; + _this.setupSession(); + _this.emit("ringing", _this.session); + }); + _this.ua.on("message", function (message) { + _this.emit("message", message); + }); + return _this; + } + Simple.prototype.call = function (destination) { + if (!this.ua || !this.checkRegistration()) { + this.logger.warn("A registered UA is required for calling"); + return; + } + if (this.state !== SimpleStatus.STATUS_NULL && this.state !== SimpleStatus.STATUS_COMPLETED) { + this.logger.warn("Cannot make more than a single call with Simple"); + return; + } + // Safari hack, because you cannot call .play() from a non user action + if (this.options.media.remote.audio) { + this.options.media.remote.audio.autoplay = true; + } + if (this.options.media.remote.video) { + this.options.media.remote.video.autoplay = true; + } + if (this.options.media.local && this.options.media.local.video) { + this.options.media.local.video.autoplay = true; + this.options.media.local.video.volume = 0; + } + this.session = this.ua.invite(destination, { + sessionDescriptionHandlerOptions: { + constraints: { + audio: this.audio, + video: this.video + } + } + }); + this.setupSession(); + return this.session; + }; + Simple.prototype.answer = function () { + if (this.state !== SimpleStatus.STATUS_NEW && this.state !== SimpleStatus.STATUS_CONNECTING) { + this.logger.warn("No call to answer"); + return; + } + // Safari hack, because you cannot call .play() from a non user action + if (this.options.media.remote.audio) { + this.options.media.remote.audio.autoplay = true; + } + if (this.options.media.remote.video) { + this.options.media.remote.video.autoplay = true; + } + return this.session.accept({ + sessionDescriptionHandlerOptions: { + constraints: { + audio: this.audio, + video: this.video + } + } + }); + // emit call is active + }; + Simple.prototype.reject = function () { + if (this.state !== SimpleStatus.STATUS_NEW && this.state !== SimpleStatus.STATUS_CONNECTING) { + this.logger.warn("Call is already answered"); + return; + } + return this.session.reject(); + }; + Simple.prototype.hangup = function () { + if (this.state !== SimpleStatus.STATUS_CONNECTED && + this.state !== SimpleStatus.STATUS_CONNECTING && + this.state !== SimpleStatus.STATUS_NEW) { + this.logger.warn("No active call to hang up on"); + return; + } + if (this.state !== SimpleStatus.STATUS_CONNECTED) { + return this.session.cancel(); + } + else if (this.session) { + return this.session.bye(); + } + }; + Simple.prototype.hold = function () { + if (this.state !== SimpleStatus.STATUS_CONNECTED || !this.session || this.session.localHold) { + this.logger.warn("Cannot put call on hold"); + return; + } + this.mute(); + this.logger.log("Placing session on hold"); + return this.session.hold(); + }; + Simple.prototype.unhold = function () { + if (this.state !== SimpleStatus.STATUS_CONNECTED || !this.session || !this.session.localHold) { + this.logger.warn("Cannot unhold a call that is not on hold"); + return; + } + this.unmute(); + this.logger.log("Placing call off hold"); + return this.session.unhold(); + }; + Simple.prototype.mute = function () { + if (this.state !== SimpleStatus.STATUS_CONNECTED) { + this.logger.warn("An acitve call is required to mute audio"); + return; + } + this.logger.log("Muting Audio"); + this.toggleMute(true); + this.emit("mute", this); + }; + Simple.prototype.unmute = function () { + if (this.state !== SimpleStatus.STATUS_CONNECTED) { + this.logger.warn("An active call is required to unmute audio"); + return; + } + this.logger.log("Unmuting Audio"); + this.toggleMute(false); + this.emit("unmute", this); + }; + Simple.prototype.sendDTMF = function (tone) { + if (this.state !== SimpleStatus.STATUS_CONNECTED || !this.session) { + this.logger.warn("An active call is required to send a DTMF tone"); + return; + } + this.logger.log("Sending DTMF tone: " + tone); + this.session.dtmf(tone); + }; + Simple.prototype.message = function (destination, message) { + if (!this.ua || !this.checkRegistration()) { + this.logger.warn("A registered UA is required to send a message"); + return; + } + if (!destination || !message) { + this.logger.warn("A destination and message are required to send a message"); + return; + } + this.ua.message(destination, message); + }; + // Private Helpers + Simple.prototype.checkRegistration = function () { + return (this.anonymous || (this.ua && this.ua.isRegistered())); + }; + Simple.prototype.setupRemoteMedia = function () { + var _this = this; + if (!this.session) { + this.logger.warn("No session to set remote media on"); + return; + } + // If there is a video track, it will attach the video and audio to the same element + var pc = this.session.sessionDescriptionHandler.peerConnection; + var remoteStream; + if (pc.getReceivers) { + remoteStream = new global.window.MediaStream(); + pc.getReceivers().forEach(function (receiver) { + var track = receiver.track; + if (track) { + remoteStream.addTrack(track); + } + }); + } + else { + remoteStream = pc.getRemoteStreams()[0]; + } + if (this.video) { + this.options.media.remote.video.srcObject = remoteStream; + this.options.media.remote.video.play().catch(function () { + _this.logger.log("play was rejected"); + }); + } + else if (this.audio) { + this.options.media.remote.audio.srcObject = remoteStream; + this.options.media.remote.audio.play().catch(function () { + _this.logger.log("play was rejected"); + }); + } + }; + Simple.prototype.setupLocalMedia = function () { + if (!this.session) { + this.logger.warn("No session to set local media on"); + return; + } + if (this.video && this.options.media.local && this.options.media.local.video) { + var pc = this.session.sessionDescriptionHandler.peerConnection; + var localStream_1; + if (pc.getSenders) { + localStream_1 = new global.window.MediaStream(); + pc.getSenders().forEach(function (sender) { + var track = sender.track; + if (track && track.kind === "video") { + localStream_1.addTrack(track); + } + }); + } + else { + localStream_1 = pc.getLocalStreams()[0]; + } + this.options.media.local.video.srcObject = localStream_1; + this.options.media.local.video.volume = 0; + this.options.media.local.video.play(); + } + }; + Simple.prototype.cleanupMedia = function () { + if (this.video) { + this.options.media.remote.video.srcObject = null; + this.options.media.remote.video.pause(); + if (this.options.media.local && this.options.media.local.video) { + this.options.media.local.video.srcObject = null; + this.options.media.local.video.pause(); + } + } + if (this.audio) { + this.options.media.remote.audio.srcObject = null; + this.options.media.remote.audio.pause(); + } + }; + Simple.prototype.setupSession = function () { + var _this = this; + if (!this.session) { + this.logger.warn("No session to set up"); + return; + } + this.state = SimpleStatus.STATUS_NEW; + this.emit("new", this.session); + this.session.on("progress", function () { return _this.onProgress(); }); + this.session.on("accepted", function () { return _this.onAccepted(); }); + this.session.on("rejected", function () { return _this.onEnded(); }); + this.session.on("failed", function () { return _this.onFailed(); }); + this.session.on("terminated", function () { return _this.onEnded(); }); + }; + Simple.prototype.destroyMedia = function () { + if (this.session && this.session.sessionDescriptionHandler) { + this.session.sessionDescriptionHandler.close(); + } + }; + Simple.prototype.toggleMute = function (mute) { + if (!this.session) { + this.logger.warn("No session to toggle mute"); + return; + } + var pc = this.session.sessionDescriptionHandler.peerConnection; + if (pc.getSenders) { + pc.getSenders().forEach(function (sender) { + if (sender.track) { + sender.track.enabled = !mute; + } + }); + } + else { + pc.getLocalStreams().forEach(function (stream) { + stream.getAudioTracks().forEach(function (track) { + track.enabled = !mute; + }); + stream.getVideoTracks().forEach(function (track) { + track.enabled = !mute; + }); + }); + } + }; + Simple.prototype.onAccepted = function () { + var _this = this; + if (!this.session) { + this.logger.warn("No session for accepting"); + return; + } + this.state = SimpleStatus.STATUS_CONNECTED; + this.emit("connected", this.session); + this.setupLocalMedia(); + this.setupRemoteMedia(); + if (this.session.sessionDescriptionHandler) { + this.session.sessionDescriptionHandler.on("addTrack", function () { + _this.logger.log("A track has been added, triggering new remoteMedia setup"); + _this.setupRemoteMedia(); + }); + this.session.sessionDescriptionHandler.on("addStream", function () { + _this.logger.log("A stream has been added, trigger new remoteMedia setup"); + _this.setupRemoteMedia(); + }); + } + this.session.on("dtmf", function (request, dtmf) { + _this.emit("dtmf", dtmf.tone); + }); + this.session.on("bye", function () { return _this.onEnded(); }); + }; + Simple.prototype.onProgress = function () { + this.state = SimpleStatus.STATUS_CONNECTING; + this.emit("connecting", this.session); + }; + Simple.prototype.onFailed = function () { + this.onEnded(); + }; + Simple.prototype.onEnded = function () { + this.state = SimpleStatus.STATUS_COMPLETED; + this.emit("ended", this.session); + this.cleanupMedia(); + }; + Simple.C = SimpleStatus; + return Simple; +}(events_1.EventEmitter)); +exports.Simple = Simple; + +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(77))) + +/***/ }) +/******/ ]); +}); \ No newline at end of file diff --git a/dist/sip.min.js b/dist/sip.min.js new file mode 100644 index 000000000..52669b285 --- /dev/null +++ b/dist/sip.min.js @@ -0,0 +1 @@ +!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.SIP=t():e.SIP=t()}(this,function(){return function(e){var t={};function r(n){if(t[n])return t[n].exports;var i=t[n]={i:n,l:!1,exports:{}};return e[n].call(i.exports,i,i.exports,r),i.l=!0,i.exports}return r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var i in e)r.d(n,i,function(t){return e[t]}.bind(null,i));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=64)}([function(e,t,r){var n;e.exports=(n=n||function(e,t){var r=Object.create||function(){function e(){}return function(t){var r;return e.prototype=t,r=new e,e.prototype=null,r}}(),n={},i=n.lib={},o=i.Base={extend:function(e){var t=r(this);return e&&t.mixIn(e),t.hasOwnProperty("init")&&this.init!==t.init||(t.init=function(){t.$super.init.apply(this,arguments)}),t.init.prototype=t,t.$super=this,t},create:function(){var e=this.extend();return e.init.apply(e,arguments),e},init:function(){},mixIn:function(e){for(var t in e)e.hasOwnProperty(t)&&(this[t]=e[t]);e.hasOwnProperty("toString")&&(this.toString=e.toString)},clone:function(){return this.init.prototype.extend(this)}},s=i.WordArray=o.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=null!=t?t:4*e.length},toString:function(e){return(e||c).stringify(this)},concat:function(e){var t=this.words,r=e.words,n=this.sigBytes,i=e.sigBytes;if(this.clamp(),n%4)for(var o=0;o>>2]>>>24-o%4*8&255;t[n+o>>>2]|=s<<24-(n+o)%4*8}else for(var o=0;o>>2]=r[o>>>2];return this.sigBytes+=i,this},clamp:function(){var t=this.words,r=this.sigBytes;t[r>>>2]&=4294967295<<32-r%4*8,t.length=e.ceil(r/4)},clone:function(){var e=o.clone.call(this);return e.words=this.words.slice(0),e},random:function(t){for(var r,n=[],i=function(t){var t=t,r=987654321,n=4294967295;return function(){var i=((r=36969*(65535&r)+(r>>16)&n)<<16)+(t=18e3*(65535&t)+(t>>16)&n)&n;return i/=4294967296,(i+=.5)*(e.random()>.5?1:-1)}},o=0;o>>2]>>>24-i%4*8&255;n.push((o>>>4).toString(16)),n.push((15&o).toString(16))}return n.join("")},parse:function(e){for(var t=e.length,r=[],n=0;n>>3]|=parseInt(e.substr(n,2),16)<<24-n%8*4;return new s.init(r,t/2)}},u=a.Latin1={stringify:function(e){for(var t=e.words,r=e.sigBytes,n=[],i=0;i>>2]>>>24-i%4*8&255;n.push(String.fromCharCode(o))}return n.join("")},parse:function(e){for(var t=e.length,r=[],n=0;n>>2]|=(255&e.charCodeAt(n))<<24-n%4*8;return new s.init(r,t)}},d=a.Utf8={stringify:function(e){try{return decodeURIComponent(escape(u.stringify(e)))}catch(e){throw new Error("Malformed UTF-8 data")}},parse:function(e){return u.parse(unescape(encodeURIComponent(e)))}},h=i.BufferedBlockAlgorithm=o.extend({reset:function(){this._data=new s.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=d.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var r=this._data,n=r.words,i=r.sigBytes,o=this.blockSize,a=4*o,c=i/a,u=(c=t?e.ceil(c):e.max((0|c)-this._minBufferSize,0))*o,d=e.min(4*u,i);if(u){for(var h=0;h>>2];e.sigBytes-=t}},m=(r.BlockCipher=h.extend({cfg:h.cfg.extend({mode:f,padding:v}),reset:function(){h.reset.call(this);var e=this.cfg,t=e.iv,r=e.mode;if(this._xformMode==this._ENC_XFORM_MODE)var n=r.createEncryptor;else{var n=r.createDecryptor;this._minBufferSize=1}this._mode&&this._mode.__creator==n?this._mode.init(this,t&&t.words):(this._mode=n.call(r,this,t&&t.words),this._mode.__creator=n)},_doProcessBlock:function(e,t){this._mode.processBlock(e,t)},_doFinalize:function(){var e=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE){e.pad(this._data,this.blockSize);var t=this._process(!0)}else{var t=this._process(!0);e.unpad(t)}return t},blockSize:4}),r.CipherParams=i.extend({init:function(e){this.mixIn(e)},toString:function(e){return(e||this.formatter).stringify(this)}})),y=t.format={},S=y.OpenSSL={stringify:function(e){var t=e.ciphertext,r=e.salt;if(r)var n=o.create([1398893684,1701076831]).concat(r).concat(t);else var n=t;return n.toString(c)},parse:function(e){var t=c.parse(e),r=t.words;if(1398893684==r[0]&&1701076831==r[1]){var n=o.create(r.slice(2,4));r.splice(0,4),t.sigBytes-=16}return m.create({ciphertext:t,salt:n})}},T=r.SerializableCipher=i.extend({cfg:i.extend({format:S}),encrypt:function(e,t,r,n){n=this.cfg.extend(n);var i=e.createEncryptor(r,n),o=i.finalize(t),s=i.cfg;return m.create({ciphertext:o,key:r,iv:s.iv,algorithm:e,mode:s.mode,padding:s.padding,blockSize:e.blockSize,formatter:n.format})},decrypt:function(e,t,r,n){n=this.cfg.extend(n),t=this._parse(t,n.format);var i=e.createDecryptor(r,n).finalize(t.ciphertext);return i},_parse:function(e,t){return"string"==typeof e?t.parse(e,this):e}}),C=t.kdf={},b=C.OpenSSL={execute:function(e,t,r,n){n||(n=o.random(8));var i=d.create({keySize:t+r}).compute(e,n),s=o.create(i.words.slice(t),4*r);return i.sigBytes=4*t,m.create({key:i,iv:s,salt:n})}},_=r.PasswordBasedCipher=T.extend({cfg:T.cfg.extend({kdf:b}),encrypt:function(e,t,r,n){var i=(n=this.cfg.extend(n)).kdf.execute(r,e.keySize,e.ivSize);n.iv=i.iv;var o=T.encrypt.call(this,e,t,i.key,n);return o.mixIn(i),o},decrypt:function(e,t,r,n){n=this.cfg.extend(n),t=this._parse(t,n.format);var i=n.kdf.execute(r,e.keySize,e.ivSize,t.salt);n.iv=i.iv;var o=T.decrypt.call(this,e,t,i.key,n);return o}})}()))},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(2),i=r(3),o=r(11);!function(e){e.defer=function(){var e={};return e.promise=new Promise(function(t,r){e.resolve=t,e.reject=r}),e},e.reducePromises=function(e,t){return e.reduce(function(e,t){return e=e.then(t)},Promise.resolve(t))},e.str_utf8_length=function(e){return encodeURIComponent(e).replace(/%[A-F\d]{2}/g,"U").length},e.generateFakeSDP=function(e){if(e){var t=e.indexOf("o="),r=e.indexOf("\r\n",t);return"v=0\r\n"+e.slice(t,r)+"\r\ns=-\r\nt=0 0\r\nc=IN IP4 0.0.0.0"}},e.isDecimal=function(e){var t=parseInt(e,10);return!isNaN(t)&&parseFloat(e)===t},e.createRandomToken=function(e,t){void 0===t&&(t=32);for(var r="",n=0;n699)throw new TypeError("Invalid statusCode: "+t);if(t)return e.getReasonHeaderValue(t,r)},e.buildStatusLine=function(t,r){if(!t||t<100||t>699)throw new TypeError("Invalid statusCode: "+t);if(r&&"string"!=typeof r&&!(r instanceof String))throw new TypeError("Invalid reason: "+r);return"SIP/2.0 "+t+" "+(r=e.getReasonPhrase(t,r))+"\r\n"}}(t.Utils||(t.Utils={}))},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(2),i=r(8),o=r(1),s=function(){function e(e,t,r,n){this.transactionConstructor=e,this.core=t,this.message=r,this.delegate=n,this.challenged=!1,this.stale=!1,this.logger=this.loggerFactory.getLogger("sip.user-agent-client"),this.init()}return e.prototype.dispose=function(){this.transaction.dispose()},Object.defineProperty(e.prototype,"loggerFactory",{get:function(){return this.core.loggerFactory},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"transaction",{get:function(){if(!this._transaction)throw new Error("Transaction undefined.");return this._transaction},enumerable:!0,configurable:!0}),e.prototype.cancel=function(t,r){var s=this;if(void 0===r&&(r={}),!this.transaction)throw new Error("Transaction undefined.");if(!this.message.to)throw new Error("To undefined.");if(!this.message.from)throw new Error("From undefined.");var a=new i.OutgoingRequest(n.C.CANCEL,this.message.ruri,this.message.ua,{toUri:this.message.to.uri,toTag:this.message.toTag,fromUri:this.message.from.uri,fromTag:this.message.fromTag,callId:this.message.callId,cseq:this.message.cseq},r.extraHeaders);if(a.callId=this.message.callId,a.cseq=this.message.cseq,a.branch=this.message.branch,this.message.headers.Route&&(a.headers.Route=this.message.headers.Route),t&&a.setHeader("Reason",t),this.transaction.state===o.TransactionState.Proceeding)new e(o.NonInviteClientTransaction,this.core,a);else this.transaction.once("stateChanged",function(){if(s.transaction&&s.transaction.state===o.TransactionState.Proceeding)new e(o.NonInviteClientTransaction,s.core,a)});return a},e.prototype.authenticationGuard=function(e){var t,r,n=e.statusCode;if(!n)throw new Error("Response status code undefined.");if(401!==n&&407!==n)return!0;if(401===n?(t=e.parseHeader("www-authenticate"),r="authorization"):(t=e.parseHeader("proxy-authenticate"),r="proxy-authorization"),!t)return this.logger.warn(n+" with wrong or missing challenge, cannot authenticate"),!0;if(this.challenged&&(this.stale||!0!==t.stale))return this.logger.warn(n+" apparently in authentication loop, cannot authenticate"),!0;if(!this.credentials&&(this.credentials=this.core.configuration.authenticationFactory(),!this.credentials))return this.logger.warn("Unable to obtain credentials, cannot authenticate"),!0;if(!this.credentials.authenticate(this.message,t))return!0;this.challenged=!0,t.stale&&(this.stale=!0);var i=this.message.cseq+=1;return this.message.setHeader("cseq",i+" "+this.message.method),this.message.setHeader(r,this.credentials.toString()),this.init(),!1},e.prototype.receiveResponse=function(e){if(this.authenticationGuard(e)){var t=e.statusCode?e.statusCode.toString():"";if(!t)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(t):this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e});break;case/^1[0-9]{2}$/.test(t):this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e});break;case/^2[0-9]{2}$/.test(t):this.delegate&&this.delegate.onAccept&&this.delegate.onAccept({message:e});break;case/^3[0-9]{2}$/.test(t):this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e});break;case/^[4-6][0-9]{2}$/.test(t):this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e});break;default:throw new Error("Invalid status code "+t)}}},e.prototype.init=function(){var e=this,t={loggerFactory:this.loggerFactory,onRequestTimeout:function(){return e.onRequestTimeout()},onStateChange:function(t){t===o.TransactionState.Terminated&&(e.core.userAgentClients.delete(n),r===e._transaction&&e.dispose())},onTransportError:function(t){return e.onTransportError(t)},receiveResponse:function(t){return e.receiveResponse(t)}},r=new this.transactionConstructor(this.message,this.core.transport,t);this._transaction=r;var n=r.id+r.request.method;this.core.userAgentClients.set(n,this)},e.prototype.onRequestTimeout=function(){this.logger.warn("User agent client request timed out. Generating internal 408 Request Timeout.");var e=this.core.configuration.onRequestTimeoutResponseMessageFactory();this.receiveResponse(e)},e.prototype.onTransportError=function(e){this.logger.error(e.message),this.logger.error("User agent client request transport error. Generating internal 503 Service Unavailable.");var t=this.core.configuration.onTransportErrorResponseMessageFactory();this.receiveResponse(t)},e}();t.UserAgentClient=s},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(3),s=function(e){function t(t){var r=this.constructor,n=e.call(this,t)||this;return Object.setPrototypeOf(n,r.prototype),n}return i(t,e),t}(Error);t.Exception=s,function(e){var t=function(e){function t(t){return e.call(this,t||"Transaction state error.")||this}return i(t,e),t}(s);e.TransactionStateError=t;var r=function(e){function t(){return e.call(this,"The session description handler has closed.")||this}return i(t,e),t}(s);e.ClosedSessionDescriptionHandlerError=r;var n=function(e){function t(){return e.call(this,"The session has terminated.")||this}return i(t,e),t}(s);e.TerminatedSessionError=n;var o=function(e){function t(t){return e.call(this,t||"Unspecified transport error.")||this}return i(t,e),t}(s);e.TransportError=o;var a=function(e){function t(t){return e.call(this,t||"Unsupported session description content type.")||this}return i(t,e),t}(s);e.UnsupportedSessionDescriptionContentTypeError=a}(t.Exceptions||(t.Exceptions={}));var a=function(e){function t(t,r,n){var i=e.call(this,n)||this;return i.code=t,i.name=r,i.message=n,i}return i(t,e),t}(s);!function(e){var t=function(e){function t(t,r){var n=e.call(this,1,"CONFIGURATION_ERROR",r?"Invalid value "+JSON.stringify(r)+" for parameter '"+t+"'":"Missing parameter: "+t)||this;return n.type=o.TypeStrings.ConfigurationError,n.parameter=t,n.value=r,n}return i(t,e),t}(a);e.ConfigurationError=t;var r=function(e){function t(t){var r=e.call(this,2,"INVALID_STATE_ERROR","Invalid status: "+t)||this;return r.type=o.TypeStrings.InvalidStateError,r.status=t,r}return i(t,e),t}(a);e.InvalidStateError=r;var n=function(e){function t(t){var r=e.call(this,3,"NOT_SUPPORTED_ERROR",t)||this;return r.type=o.TypeStrings.NotSupportedError,r}return i(t,e),t}(a);e.NotSupportedError=n;var s=function(e){function t(t){var r=e.call(this,5,"RENEGOTIATION_ERROR",t)||this;return r.type=o.TypeStrings.RenegotiationError,r}return i(t,e),t}(a);e.RenegotiationError=s;var c=function(e){function t(t,r,n){var i=e.call(this,6,"METHOD_PARAMETER_ERROR",n?"Invalid value "+JSON.stringify(n)+" for parameter '"+r+"'":"Missing parameter: "+r)||this;return i.type=o.TypeStrings.MethodParameterError,i.method=t,i.parameter=r,i.value=n,i}return i(t,e),t}(a);e.MethodParameterError=c;var u=function(e){function t(t,r,n){var i=e.call(this,8,"SESSION_DESCRIPTION_HANDLER_ERROR",n||"Error with Session Description Handler")||this;return i.type=o.TypeStrings.SessionDescriptionHandlerError,i.method=t,i.error=r,i}return i(t,e),t}(a);e.SessionDescriptionHandlerError=u}(t.Exceptions||(t.Exceptions={}))},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(2),s=r(3),a=r(11),c=r(5);t.getSupportedHeader=function(e){var t=[];e.method===o.C.REGISTER?t.push("path","gruu"):e.method===o.C.INVITE&&(e.ua.contact.pubGruu||e.ua.contact.tempGruu)&&t.push("gruu"),e.ua.configuration.rel100===o.C.supported.SUPPORTED&&t.push("100rel"),e.ua.configuration.replaces===o.C.supported.SUPPORTED&&t.push("replaces"),t.push("outbound"),t=t.concat(e.ua.configuration.extraSupported||[]);var r=e.ua.configuration.hackAllowUnregisteredOptionTags||!1,n={};return"Supported: "+(t=t.filter(function(e){var t=o.C.OPTION_TAGS[e],i=!n[e];return n[e]=!0,(t||r)&&i})).join(", ")+"\r\n"};var u=function(){function e(e,t,r,n,i,o){void 0===n&&(n={}),this.type=s.TypeStrings.OutgoingRequest,this.ua=r,this.headers={},this.method=e,this.ruri=t,this.body=o,this.extraHeaders=(i||[]).slice(),n.routeSet?this.setHeader("route",n.routeSet):r.configuration.usePreloadedRoute&&r.transport&&this.setHeader("route",r.transport.server.sipUri),this.setHeader("via",""),this.setHeader("max-forwards","70");var u=n.toUri||t;this.toTag=n.toTag;var d=n.toDisplayName||0===n.toDisplayName?'"'+n.toDisplayName+'" ':"";d+="<"+(u.type===s.TypeStrings.URI?u.toRaw():u)+">",d+=this.toTag?";tag="+this.toTag:"",this.to=a.Grammar.nameAddrHeaderParse(d),this.setHeader("to",d);var h,p=n.fromUri||r.configuration.uri||"";this.fromTag=n.fromTag||c.Utils.newTag(),h=n.fromDisplayName||0===n.fromDisplayName?'"'+n.fromDisplayName+'" ':r.configuration.displayName?'"'+r.configuration.displayName+'" ':"",h+="<"+(p.type===s.TypeStrings.URI?p.toRaw():p)+">;tag=",h+=this.fromTag,this.from=a.Grammar.nameAddrHeaderParse(h),this.setHeader("from",h),this.callId=n.callId||r.configuration.sipjsId+c.Utils.createRandomToken(15),this.setHeader("call-id",this.callId),this.cseq=n.cseq||Math.floor(1e4*Math.random()),this.setHeader("cseq",this.cseq+" "+e)}return e.prototype.getHeader=function(e){var t=this.headers[c.Utils.headerize(e)];if(t){if(t[0])return t[0]}else for(var r=new RegExp("^\\s*"+e+"\\s*:","i"),n=0,i=this.extraHeaders;n=this.headers[e].length)){var r=this.headers[e][t],n=r.raw;if(r.parsed)return r.parsed;var i=a.Grammar.parse(n,e.replace(/-/g,"_"));return-1===i?void this.headers[e].splice(t,1):(r.parsed=i,i)}},e.prototype.s=function(e,t){return void 0===t&&(t=0),this.parseHeader(e,t)},e.prototype.setHeader=function(e,t){this.headers[c.Utils.headerize(e)]=[{raw:t}]},e.prototype.toString=function(){return this.data},e}();t.IncomingMessage=d;var h=function(e){function t(t){var r=e.call(this)||this;return r.ua=t,r.type=s.TypeStrings.IncomingRequest,r}return i(t,e),t}(d);t.IncomingRequest=h;var p=function(e){function t(t){var r=e.call(this)||this;return r.ua=t,r.type=s.TypeStrings.IncomingResponse,r.headers={},r}return i(t,e),t}(d);t.IncomingResponse=p},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(7),i=r(5),o=r(14),s=r(1),a=function(){function e(e,t,r,n){this.transactionConstructor=e,this.core=t,this.message=r,this.delegate=n,this.logger=this.loggerFactory.getLogger("sip.user-agent-server"),this.toTag=r.toTag?r.toTag:i.Utils.newTag(),this.init()}return e.prototype.dispose=function(){this.transaction.dispose()},Object.defineProperty(e.prototype,"loggerFactory",{get:function(){return this.core.loggerFactory},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"transaction",{get:function(){if(!this._transaction)throw new Error("Transaction undefined.");return this._transaction},enumerable:!0,configurable:!0}),e.prototype.accept=function(e){if(void 0===e&&(e={statusCode:200}),!this.acceptable)throw new n.Exceptions.TransactionStateError(this.message.method+" not acceptable in state "+this.transaction.state+".");var t=e.statusCode;if(t<200||t>299)throw new TypeError("Invalid statusCode: "+t);return this.reply(e)},e.prototype.progress=function(e){if(void 0===e&&(e={statusCode:180}),!this.progressable)throw new n.Exceptions.TransactionStateError(this.message.method+" not progressable in state "+this.transaction.state+".");var t=e.statusCode;if(t<101||t>199)throw new TypeError("Invalid statusCode: "+t);return this.reply(e)},e.prototype.redirect=function(e,t){if(void 0===t&&(t={statusCode:302}),!this.redirectable)throw new n.Exceptions.TransactionStateError(this.message.method+" not redirectable in state "+this.transaction.state+".");var r=t.statusCode;if(r<300||r>399)throw new TypeError("Invalid statusCode: "+r);var i=new Array;return e.forEach(function(e){return i.push("Contact: "+e.toString())}),t.extraHeaders=(t.extraHeaders||[]).concat(i),this.reply(t)},e.prototype.reject=function(e){if(void 0===e&&(e={statusCode:480}),!this.rejectable)throw new n.Exceptions.TransactionStateError(this.message.method+" not rejectable in state "+this.transaction.state+".");var t=e.statusCode;if(t<400||t>699)throw new TypeError("Invalid statusCode: "+t);return this.reply(e)},e.prototype.trying=function(e){if(!this.tryingable)throw new n.Exceptions.TransactionStateError(this.message.method+" not tryingable in state "+this.transaction.state+".");return this.reply({statusCode:100})},e.prototype.receiveCancel=function(e){this.delegate&&this.delegate.onCancel&&this.delegate.onCancel(e)},Object.defineProperty(e.prototype,"acceptable",{get:function(){if(this.transaction instanceof s.InviteServerTransaction)return this.transaction.state===s.TransactionState.Proceeding||this.transaction.state===s.TransactionState.Accepted;if(this.transaction instanceof s.NonInviteServerTransaction)return this.transaction.state===s.TransactionState.Trying||this.transaction.state===s.TransactionState.Proceeding;throw new Error("Unknown transaction type.")},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"progressable",{get:function(){if(this.transaction instanceof s.InviteServerTransaction)return this.transaction.state===s.TransactionState.Proceeding;if(this.transaction instanceof s.NonInviteServerTransaction)return!1;throw new Error("Unknown transaction type.")},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"redirectable",{get:function(){if(this.transaction instanceof s.InviteServerTransaction)return this.transaction.state===s.TransactionState.Proceeding;if(this.transaction instanceof s.NonInviteServerTransaction)return this.transaction.state===s.TransactionState.Trying||this.transaction.state===s.TransactionState.Proceeding;throw new Error("Unknown transaction type.")},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"rejectable",{get:function(){if(this.transaction instanceof s.InviteServerTransaction)return this.transaction.state===s.TransactionState.Proceeding;if(this.transaction instanceof s.NonInviteServerTransaction)return this.transaction.state===s.TransactionState.Trying||this.transaction.state===s.TransactionState.Proceeding;throw new Error("Unknown transaction type.")},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"tryingable",{get:function(){if(this.transaction instanceof s.InviteServerTransaction)return this.transaction.state===s.TransactionState.Proceeding;if(this.transaction instanceof s.NonInviteServerTransaction)return this.transaction.state===s.TransactionState.Trying;throw new Error("Unknown transaction type.")},enumerable:!0,configurable:!0}),e.prototype.reply=function(e){e.toTag||100===e.statusCode||(e.toTag=this.toTag),e.userAgent=e.userAgent||this.core.configuration.userAgentHeaderFieldValue;var t=o.constructOutgoingResponse(this.message,e);return this.transaction.receiveResponse(e.statusCode,t.message),t},e.prototype.init=function(){var e=this,t={loggerFactory:this.loggerFactory,onStateChange:function(t){t===s.TransactionState.Terminated&&(e.core.userAgentServers.delete(n),e.dispose())},onTransportError:function(t){e.logger.error(t.message),e.delegate&&e.delegate.onTransportError?e.delegate.onTransportError(t):e.logger.error("User agent server response transport error.")}},r=new this.transactionConstructor(this.message,this.core.transport,t);this._transaction=r;var n=r.id;this.core.userAgentServers.set(r.id,this)},e}();t.UserAgentServer=a},function(e,t,r){"use strict";var n,i="object"==typeof Reflect?Reflect:null,o=i&&"function"==typeof i.apply?i.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)};n=i&&"function"==typeof i.ownKeys?i.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var s=Number.isNaN||function(e){return e!=e};function a(){a.init.call(this)}e.exports=a,a.EventEmitter=a,a.prototype._events=void 0,a.prototype._eventsCount=0,a.prototype._maxListeners=void 0;var c=10;function u(e){return void 0===e._maxListeners?a.defaultMaxListeners:e._maxListeners}function d(e,t,r,n){var i,o,s,a;if("function"!=typeof r)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof r);if(void 0===(o=e._events)?(o=e._events=Object.create(null),e._eventsCount=0):(void 0!==o.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),o=e._events),s=o[t]),void 0===s)s=o[t]=r,++e._eventsCount;else if("function"==typeof s?s=o[t]=n?[r,s]:[s,r]:n?s.unshift(r):s.push(r),(i=u(e))>0&&s.length>i&&!s.warned){s.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=s.length,a=c,console&&console.warn&&console.warn(a)}return e}function h(e,t,r){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},i=function(){for(var e=[],t=0;t0&&(s=t[0]),s instanceof Error)throw s;var a=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw a.context=s,a}var c=i[e];if(void 0===c)return!1;if("function"==typeof c)o(c,this,t);else{var u=c.length,d=f(c,u);for(r=0;r=0;o--)if(r[o]===t||r[o].listener===t){s=r[o].listener,i=o;break}if(i<0)return this;0===i?r.shift():function(e,t){for(;t+1=0;n--)this.removeListener(e,t[n]);return this},a.prototype.listeners=function(e){return p(this,e,!0)},a.prototype.rawListeners=function(e){return p(this,e,!1)},a.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):l.call(e,t)},a.prototype.listenerCount=l,a.prototype.eventNames=function(){return this._eventsCount>0?n(this._events):[]}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(65);!function(e){e.parse=function(e,t){var r={startRule:t};try{n.parse(e,r)}catch(e){r.data=-1}return r.data},e.nameAddrHeaderParse=function(t){var r=e.parse(t,"Name_Addr_Header");return-1!==r?r:void 0},e.URIParse=function(t){var r=e.parse(t,"SIP_URI");return-1!==r?r:void 0}}(t.Grammar||(t.Grammar={}))},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=500;t.Timers={T1:n,T2:4e3,T4:5e3,TIMER_B:32e3,TIMER_D:0,TIMER_F:32e3,TIMER_H:32e3,TIMER_I:0,TIMER_J:0,TIMER_K:0,TIMER_L:32e3,TIMER_M:32e3,TIMER_N:32e3,PROVISIONAL_RESPONSE_INTERVAL:6e4}},function(e,t,r){var n,i,o,s,a,c,u,d;e.exports=(n=r(0),r(25),r(26),o=(i=n).lib,s=o.Base,a=o.WordArray,c=i.algo,u=c.MD5,d=c.EvpKDF=s.extend({cfg:s.extend({keySize:4,hasher:u,iterations:1}),init:function(e){this.cfg=this.cfg.extend(e)},compute:function(e,t){for(var r=this.cfg,n=r.hasher.create(),i=a.create(),o=i.words,s=r.keySize,c=r.iterations;o.length>>2]>>>24-o%4*8&255)<<16|(t[o+1>>>2]>>>24-(o+1)%4*8&255)<<8|t[o+2>>>2]>>>24-(o+2)%4*8&255,a=0;a<4&&o+.75*a>>6*(3-a)&63));var c=n.charAt(64);if(c)for(;i.length%4;)i.push(c);return i.join("")},parse:function(e){var t=e.length,r=this._map,n=this._reverseMap;if(!n){n=this._reverseMap=[];for(var i=0;i>>6-s%4*2;n[i>>>2]|=(a|c)<<24-i%4*8,i++}return o.create(n,i)}(e,t,n)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="},n.enc.Base64)},function(e,t,r){var n;e.exports=(n=r(0),function(e){var t=n,r=t.lib,i=r.WordArray,o=r.Hasher,s=t.algo,a=[];!function(){for(var t=0;t<64;t++)a[t]=4294967296*e.abs(e.sin(t+1))|0}();var c=s.MD5=o.extend({_doReset:function(){this._hash=new i.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(e,t){for(var r=0;r<16;r++){var n=t+r,i=e[n];e[n]=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8)}var o=this._hash.words,s=e[t+0],c=e[t+1],l=e[t+2],f=e[t+3],g=e[t+4],v=e[t+5],m=e[t+6],y=e[t+7],S=e[t+8],T=e[t+9],C=e[t+10],b=e[t+11],_=e[t+12],A=e[t+13],w=e[t+14],E=e[t+15],R=o[0],I=o[1],O=o[2],x=o[3];R=u(R,I,O,x,s,7,a[0]),x=u(x,R,I,O,c,12,a[1]),O=u(O,x,R,I,l,17,a[2]),I=u(I,O,x,R,f,22,a[3]),R=u(R,I,O,x,g,7,a[4]),x=u(x,R,I,O,v,12,a[5]),O=u(O,x,R,I,m,17,a[6]),I=u(I,O,x,R,y,22,a[7]),R=u(R,I,O,x,S,7,a[8]),x=u(x,R,I,O,T,12,a[9]),O=u(O,x,R,I,C,17,a[10]),I=u(I,O,x,R,b,22,a[11]),R=u(R,I,O,x,_,7,a[12]),x=u(x,R,I,O,A,12,a[13]),O=u(O,x,R,I,w,17,a[14]),R=d(R,I=u(I,O,x,R,E,22,a[15]),O,x,c,5,a[16]),x=d(x,R,I,O,m,9,a[17]),O=d(O,x,R,I,b,14,a[18]),I=d(I,O,x,R,s,20,a[19]),R=d(R,I,O,x,v,5,a[20]),x=d(x,R,I,O,C,9,a[21]),O=d(O,x,R,I,E,14,a[22]),I=d(I,O,x,R,g,20,a[23]),R=d(R,I,O,x,T,5,a[24]),x=d(x,R,I,O,w,9,a[25]),O=d(O,x,R,I,f,14,a[26]),I=d(I,O,x,R,S,20,a[27]),R=d(R,I,O,x,A,5,a[28]),x=d(x,R,I,O,l,9,a[29]),O=d(O,x,R,I,y,14,a[30]),R=h(R,I=d(I,O,x,R,_,20,a[31]),O,x,v,4,a[32]),x=h(x,R,I,O,S,11,a[33]),O=h(O,x,R,I,b,16,a[34]),I=h(I,O,x,R,w,23,a[35]),R=h(R,I,O,x,c,4,a[36]),x=h(x,R,I,O,g,11,a[37]),O=h(O,x,R,I,y,16,a[38]),I=h(I,O,x,R,C,23,a[39]),R=h(R,I,O,x,A,4,a[40]),x=h(x,R,I,O,s,11,a[41]),O=h(O,x,R,I,f,16,a[42]),I=h(I,O,x,R,m,23,a[43]),R=h(R,I,O,x,T,4,a[44]),x=h(x,R,I,O,_,11,a[45]),O=h(O,x,R,I,E,16,a[46]),R=p(R,I=h(I,O,x,R,l,23,a[47]),O,x,s,6,a[48]),x=p(x,R,I,O,y,10,a[49]),O=p(O,x,R,I,w,15,a[50]),I=p(I,O,x,R,v,21,a[51]),R=p(R,I,O,x,_,6,a[52]),x=p(x,R,I,O,f,10,a[53]),O=p(O,x,R,I,C,15,a[54]),I=p(I,O,x,R,c,21,a[55]),R=p(R,I,O,x,S,6,a[56]),x=p(x,R,I,O,E,10,a[57]),O=p(O,x,R,I,m,15,a[58]),I=p(I,O,x,R,A,21,a[59]),R=p(R,I,O,x,g,6,a[60]),x=p(x,R,I,O,b,10,a[61]),O=p(O,x,R,I,l,15,a[62]),I=p(I,O,x,R,T,21,a[63]),o[0]=o[0]+R|0,o[1]=o[1]+I|0,o[2]=o[2]+O|0,o[3]=o[3]+x|0},_doFinalize:function(){var t=this._data,r=t.words,n=8*this._nDataBytes,i=8*t.sigBytes;r[i>>>5]|=128<<24-i%32;var o=e.floor(n/4294967296),s=n;r[15+(i+64>>>9<<4)]=16711935&(o<<8|o>>>24)|4278255360&(o<<24|o>>>8),r[14+(i+64>>>9<<4)]=16711935&(s<<8|s>>>24)|4278255360&(s<<24|s>>>8),t.sigBytes=4*(r.length+1),this._process();for(var a=this._hash,c=a.words,u=0;u<4;u++){var d=c[u];c[u]=16711935&(d<<8|d>>>24)|4278255360&(d<<24|d>>>8)}return a},clone:function(){var e=o.clone.call(this);return e._hash=this._hash.clone(),e}});function u(e,t,r,n,i,o,s){var a=e+(t&r|~t&n)+i+s;return(a<>>32-o)+t}function d(e,t,r,n,i,o,s){var a=e+(t&n|r&~n)+i+s;return(a<>>32-o)+t}function h(e,t,r,n,i,o,s){var a=e+(t^r^n)+i+s;return(a<>>32-o)+t}function p(e,t,r,n,i,o,s){var a=e+(r^(t|~n))+i+s;return(a<>>32-o)+t}t.MD5=o._createHelper(c),t.HmacMD5=o._createHmacHelper(c)}(Math),n.MD5)},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(3),s=function(e){function t(t,r,n){var i=e.call(this,n)||this;if(i.type=o.TypeStrings.NameAddrHeader,!t||t.type!==o.TypeStrings.URI)throw new TypeError('missing or invalid "uri" parameter');return i.uri=t,i._displayName=r,i}return i(t,e),Object.defineProperty(t.prototype,"friendlyName",{get:function(){return this.displayName||this.uri.aor},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"displayName",{get:function(){return this._displayName},set:function(e){this._displayName=e},enumerable:!0,configurable:!0}),t.prototype.clone=function(){return new t(this.uri.clone(),this._displayName,JSON.parse(JSON.stringify(this.parameters)))},t.prototype.toString=function(){var e=this.displayName||"0"===this.displayName?'"'+this.displayName+'" ':"";for(var t in e+="<"+this.uri.toString()+">",this.parameters)this.parameters.hasOwnProperty(t)&&(e+=";"+t,null!==this.parameters[t]&&(e+="="+this.parameters[t]));return e},t}(r(19).Parameters);t.NameAddrHeader=s},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(2),s=r(3),a=function(){function e(e){for(var t in this.parameters={},this.type=s.TypeStrings.Parameters,e)e.hasOwnProperty(t)&&this.setParam(t,e[t])}return e.prototype.setParam=function(e,t){e&&(this.parameters[e.toLowerCase()]=null==t?null:t.toString())},e.prototype.getParam=function(e){if(e)return this.parameters[e.toLowerCase()]},e.prototype.hasParam=function(e){return!!e&&!!this.parameters.hasOwnProperty(e.toLowerCase())},e.prototype.deleteParam=function(e){if(e=e.toLowerCase(),this.parameters.hasOwnProperty(e)){var t=this.parameters[e];return delete this.parameters[e],t}},e.prototype.clearParams=function(){this.parameters={}},e}();t.Parameters=a;var c=function(e){function t(t,r,n,i,a,c){var u=e.call(this,a)||this;if(u.headers={},u.type=s.TypeStrings.URI,!n)throw new TypeError('missing or invalid "host" parameter');for(var d in t=t||o.C.SIP,c)c.hasOwnProperty(d)&&u.setHeader(d,c[d]);return u.raw={scheme:t,user:r,host:n,port:i},u.normal={scheme:t.toLowerCase(),user:r,host:n.toLowerCase(),port:i},u}return i(t,e),Object.defineProperty(t.prototype,"_normal",{get:function(){return this.normal},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"_raw",{get:function(){return this.raw},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"scheme",{get:function(){return this.normal.scheme},set:function(e){this.raw.scheme=e,this.normal.scheme=e.toLowerCase()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"user",{get:function(){return this.normal.user},set:function(e){this.normal.user=this.raw.user=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"host",{get:function(){return this.normal.host},set:function(e){this.raw.host=e,this.normal.host=e.toLowerCase()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"aor",{get:function(){return this.normal.user+"@"+this.normal.host},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"port",{get:function(){return this.normal.port},set:function(e){this.normal.port=this.raw.port=e},enumerable:!0,configurable:!0}),t.prototype.setHeader=function(e,t){this.headers[this.headerize(e)]=t instanceof Array?t:[t]},t.prototype.getHeader=function(e){if(e)return this.headers[this.headerize(e)]},t.prototype.hasHeader=function(e){return!!e&&!!this.headers.hasOwnProperty(this.headerize(e))},t.prototype.deleteHeader=function(e){if(e=this.headerize(e),this.headers.hasOwnProperty(e)){var t=this.headers[e];return delete this.headers[e],t}},t.prototype.clearHeaders=function(){this.headers={}},t.prototype.clone=function(){return new t(this._raw.scheme,this._raw.user||"",this._raw.host,this._raw.port,JSON.parse(JSON.stringify(this.parameters)),JSON.parse(JSON.stringify(this.headers)))},t.prototype.toRaw=function(){return this._toString(this._raw)},t.prototype.toString=function(){return this._toString(this._normal)},t.prototype._toString=function(e){var t=e.scheme+":";for(var r in e.scheme.toLowerCase().match("^sips?$")||(t+="//"),e.user&&(t+=this.escapeUser(e.user)+"@"),t+=e.host,(e.port||0===e.port)&&(t+=":"+e.port),this.parameters)this.parameters.hasOwnProperty(r)&&(t+=";"+r,null!==this.parameters[r]&&(t+="="+this.parameters[r]));var n=[];for(var i in this.headers)if(this.headers.hasOwnProperty(i))for(var o in this.headers[i])this.headers[i].hasOwnProperty(o)&&n.push(i+"="+this.headers[i][o]);return n.length>0&&(t+="?"+n.join("&")),t},t.prototype.escapeUser=function(e){return encodeURIComponent(decodeURIComponent(e)).replace(/%3A/gi,":").replace(/%2B/gi,"+").replace(/%3F/gi,"?").replace(/%2F/gi,"/")},t.prototype.headerize=function(e){for(var t={"Call-Id":"Call-ID",Cseq:"CSeq","Min-Se":"Min-SE",Rack:"RAck",Rseq:"RSeq","Www-Authenticate":"WWW-Authenticate"},r=e.toLowerCase().replace(/_/g,"-").split("-"),n=r.length,i="",o=0;oi)throw new TypeError("Invalid statusCode: "+r);var h,p={statusCode:r,reasonPhrase:o,extraHeaders:s,body:c},l=r.toString();switch(!0){case/^100$/.test(l):h=this.incomingRequest.trying(p).message;break;case/^1[0-9]{2}$/.test(l):h=this.incomingRequest.progress(p).message;break;case/^2[0-9]{2}$/.test(l):h=this.incomingRequest.accept(p).message;break;case/^3[0-9]{2}$/.test(l):h=this.incomingRequest.redirect([],p).message;break;case/^[4-6][0-9]{2}$/.test(l):h=this.incomingRequest.reject(p).message;break;default:throw new Error("Invalid status code "+r)}return u.forEach(function(e){t.emit(e,h,o)}),this},t.prototype.onRequestTimeout=function(){this.emit("failed",void 0,s.C.causes.REQUEST_TIMEOUT)},t.prototype.onTransportError=function(){this.emit("failed",void 0,s.C.causes.CONNECTION_ERROR)},t}(o.EventEmitter);t.ServerContext=h},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(2);t.AllowedMethods=[n.C.ACK,n.C.BYE,n.C.CANCEL,n.C.INFO,n.C.INVITE,n.C.MESSAGE,n.C.NOTIFY,n.C.OPTIONS,n.C.PRACK,n.C.REFER,n.C.SUBSCRIBE]},function(e,t){var r;r=function(){return this}();try{r=r||new Function("return this")()}catch(e){"object"==typeof window&&(r=window)}e.exports=r},function(e,t,r){var n,i,o,s,a,c,u,d;e.exports=(n=r(0),o=(i=n).lib,s=o.WordArray,a=o.Hasher,c=i.algo,u=[],d=c.SHA1=a.extend({_doReset:function(){this._hash=new s.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(e,t){for(var r=this._hash.words,n=r[0],i=r[1],o=r[2],s=r[3],a=r[4],c=0;c<80;c++){if(c<16)u[c]=0|e[t+c];else{var d=u[c-3]^u[c-8]^u[c-14]^u[c-16];u[c]=d<<1|d>>>31}var h=(n<<5|n>>>27)+a+u[c];h+=c<20?1518500249+(i&o|~i&s):c<40?1859775393+(i^o^s):c<60?(i&o|i&s|o&s)-1894007588:(i^o^s)-899497514,a=s,s=o,o=i<<30|i>>>2,i=n,n=h}r[0]=r[0]+n|0,r[1]=r[1]+i|0,r[2]=r[2]+o|0,r[3]=r[3]+s|0,r[4]=r[4]+a|0},_doFinalize:function(){var e=this._data,t=e.words,r=8*this._nDataBytes,n=8*e.sigBytes;return t[n>>>5]|=128<<24-n%32,t[14+(n+64>>>9<<4)]=Math.floor(r/4294967296),t[15+(n+64>>>9<<4)]=r,e.sigBytes=4*t.length,this._process(),this._hash},clone:function(){var e=a.clone.call(this);return e._hash=this._hash.clone(),e}}),i.SHA1=a._createHelper(d),i.HmacSHA1=a._createHmacHelper(d),n.SHA1)},function(e,t,r){var n,i,o,s,a,c,u;e.exports=(n=r(0),o=(i=n).lib,s=o.Base,a=i.enc,c=a.Utf8,u=i.algo,void(u.HMAC=s.extend({init:function(e,t){e=this._hasher=new e.init,"string"==typeof t&&(t=c.parse(t));var r=e.blockSize,n=4*r;t.sigBytes>n&&(t=e.finalize(t)),t.clamp();for(var i=this._oKey=t.clone(),o=this._iKey=t.clone(),s=i.words,a=o.words,u=0;u"),o.extraHeaders.push("Contact: "+r.contact),o.extraHeaders.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),o.extraHeaders.push("Refer-To: "+o.target),o.errorListener=o.onTransportError.bind(o),t.transport&&t.transport.on("transportError",o.errorListener),o}return i(t,e),t.prototype.refer=function(e){var t=this;void 0===e&&(e={});var r=(this.extraHeaders||[]).slice();return e.extraHeaders&&r.concat(e.extraHeaders),this.applicant.sendRequest(s.C.REFER,{extraHeaders:this.extraHeaders,receiveResponse:function(r){var n=r&&r.statusCode?r.statusCode.toString():"";/^1[0-9]{2}$/.test(n)?t.emit("referRequestProgress",t):/^2[0-9]{2}$/.test(n)?t.emit("referRequestAccepted",t):/^[4-6][0-9]{2}$/.test(n)&&t.emit("referRequestRejected",t),e.receiveResponse&&e.receiveResponse(r)}}),this},t.prototype.receiveNotify=function(e){var t=e.message.hasHeader("Content-Type")?e.message.getHeader("Content-Type"):void 0;if(t&&-1!==t.search(/^message\/sipfrag/)){var r=d.Grammar.parse(e.message.body,"sipfrag");if(-1===r)return void e.reject({statusCode:489,reasonPhrase:"Bad Event"});switch(!0){case/^1[0-9]{2}$/.test(r.status_code):this.emit("referProgress",this);break;case/^2[0-9]{2}$/.test(r.status_code):this.emit("referAccepted",this),!this.options.activeAfterTransfer&&this.applicant.terminate&&this.applicant.terminate();break;default:this.emit("referRejected",this)}return e.accept(),void this.emit("notify",e.message)}e.reject({statusCode:489,reasonPhrase:"Bad Event"})},t.prototype.initReferTo=function(e){var t;if("string"==typeof e){var r=d.Grammar.parse(e,"Refer_To");t=r&&r.uri?r.uri:e;var n=this.ua.normalizeTarget(e);if(!n)throw new TypeError("Invalid target: "+e);t=n}else{if(!e.session)throw new Error("Session undefined.");var i=e.remoteIdentity.friendlyName,o=e.session.remoteTarget.toString(),s=e.session.callId,a=e.session.remoteTag,c=e.session.localTag;t='"'+i+'" <'+o+"?Replaces="+encodeURIComponent(s+";to-tag="+a+";from-tag="+c)+">"}return t},t}(o.ClientContext);t.ReferClientContext=l;var f=function(e){function t(t,r,n){var i=e.call(this,t,r)||this;return i.session=n,i.type=c.TypeStrings.ReferServerContext,i.ua=t,i.status=c.SessionStatus.STATUS_INVITE_RECEIVED,i.fromTag=i.request.fromTag,i.id=i.request.callId+i.fromTag,i.contact=i.ua.contact.toString(),i.logger=t.getLogger("sip.referservercontext",i.id),i.cseq=Math.floor(1e4*Math.random()),i.callId=i.request.callId,i.fromUri=i.request.to.uri,i.fromTag=i.request.to.parameters.tag,i.remoteTarget=i.request.headers.Contact[0].parsed.uri,i.toUri=i.request.from.uri,i.toTag=i.request.fromTag,i.routeSet=i.request.getHeaders("record-route"),i.request.hasHeader("refer-to")?(i.referTo=i.request.parseHeader("refer-to"),i.referredSession=i.ua.findSession(i.request),i.request.hasHeader("referred-by")&&(i.referredBy=i.request.getHeader("referred-by")),i.referTo.uri.hasHeader("replaces")&&(i.replaces=i.referTo.uri.getHeader("replaces")),i.errorListener=i.onTransportError.bind(i),t.transport&&t.transport.on("transportError",i.errorListener),i.status=c.SessionStatus.STATUS_WAITING_FOR_ANSWER,i):(i.logger.warn("Invalid REFER packet. A refer-to header is required. Rejecting refer."),i.reject(),i)}return i(t,e),t.prototype.progress=function(){if(this.status!==c.SessionStatus.STATUS_WAITING_FOR_ANSWER)throw new u.Exceptions.InvalidStateError(this.status);this.incomingRequest.trying()},t.prototype.reject=function(t){if(void 0===t&&(t={}),this.status===c.SessionStatus.STATUS_TERMINATED)throw new u.Exceptions.InvalidStateError(this.status);this.logger.log("Rejecting refer"),this.status=c.SessionStatus.STATUS_TERMINATED,e.prototype.reject.call(this,t),this.emit("referRequestRejected",this)},t.prototype.accept=function(e,t){var r=this;if(void 0===e&&(e={}),this.status!==c.SessionStatus.STATUS_WAITING_FOR_ANSWER)throw new u.Exceptions.InvalidStateError(this.status);if(this.status=c.SessionStatus.STATUS_ANSWERED,this.incomingRequest.accept({statusCode:202,reasonPhrase:"Accepted"}),this.emit("referRequestAccepted",this),e.followRefer){this.logger.log("Accepted refer, attempting to automatically follow it");var n=this.referTo.uri;if(!n.scheme||!n.scheme.match("^sips?$"))return this.logger.error("SIP.js can only automatically follow SIP refer target"),void this.reject();var i=e.inviteOptions||{},o=(i.extraHeaders||[]).slice();if(this.replaces&&o.push("Replaces: "+decodeURIComponent(this.replaces)),this.referredBy&&o.push("Referred-By: "+this.referredBy),i.extraHeaders=o,n.clearHeaders(),this.targetSession=this.ua.invite(n.toString(),i,t),this.emit("referInviteSent",this),this.targetSession){this.targetSession.once("progress",function(e){var t=e.statusCode||100,n=e.reasonPhrase;r.sendNotify(("SIP/2.0 "+t+" "+n).trim()),r.emit("referProgress",r),r.referredSession&&r.referredSession.emit("referProgress",r)}),this.targetSession.once("accepted",function(){r.logger.log("Successfully followed the refer"),r.sendNotify("SIP/2.0 200 OK"),r.emit("referAccepted",r),r.referredSession&&r.referredSession.emit("referAccepted",r)});var s=function(e){if(r.status!==c.SessionStatus.STATUS_TERMINATED){if(r.logger.log("Refer was not successful. Resuming session"),e&&429===e.statusCode)return r.logger.log("Alerting referrer that identity is required."),void r.sendNotify("SIP/2.0 429 Provide Referrer Identity");r.sendNotify("SIP/2.0 603 Declined"),r.status=c.SessionStatus.STATUS_TERMINATED,r.emit("referRejected",r),r.referredSession&&r.referredSession.emit("referRejected")}};this.targetSession.once("rejected",s),this.targetSession.once("failed",s)}}else this.logger.log("Accepted refer, but did not automatically follow it"),this.sendNotify("SIP/2.0 200 OK"),this.emit("referAccepted",this),this.referredSession&&this.referredSession.emit("referAccepted",this)},t.prototype.sendNotify=function(e){if(this.status!==c.SessionStatus.STATUS_ANSWERED)throw new u.Exceptions.InvalidStateError(this.status);if(-1===d.Grammar.parse(e,"sipfrag"))throw new Error("sipfrag body is required to send notify for refer");if(this.session)this.session.notify(void 0,{extraHeaders:["Event: refer","Subscription-State: terminated"],body:{contentDisposition:"render",contentType:"message/sipfrag",content:e}});else{var t=new p.OutgoingRequest(s.C.NOTIFY,this.remoteTarget,this.ua,{cseq:this.cseq+=1,callId:this.callId,fromUri:this.fromUri,fromTag:this.fromTag,toUri:this.toUri,toTag:this.toTag,routeSet:this.routeSet},["Event: refer","Subscription-State: terminated","Content-Type: message/sipfrag"],e),r=this.ua.transport;if(!r)throw new Error("Transport undefined.");var n={loggerFactory:this.ua.getLoggerFactory()};new a.NonInviteClientTransaction(t,r,n)}},t.prototype.on=function(t,r){return e.prototype.on.call(this,t,r)},t}(h.ServerContext);t.ReferServerContext=f},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=function(e){function t(r,n,i,o,s){var a=e.call(this,n,i,t.makeId(r),o,s)||this;return a._request=r,a.user=i,r.setViaHeader(a.id,n),a}return i(t,e),t.makeId=function(e){if("CANCEL"===e.method){if(!e.branch)throw new Error("Outgoing CANCEL request without a branch.");return e.branch}return"z9hG4bK"+Math.floor(1e7*Math.random())},Object.defineProperty(t.prototype,"request",{get:function(){return this._request},enumerable:!0,configurable:!0}),t.prototype.onRequestTimeout=function(){this.user.onRequestTimeout&&this.user.onRequestTimeout()},t}(r(29).Transaction);t.ClientTransaction=o},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(10),s=r(7),a=function(e){function t(t,r,n,i,o){var s=e.call(this)||this;return s._transport=t,s._user=r,s._id=n,s._state=i,s.logger=r.loggerFactory.getLogger(o,n),s.logger.debug("Constructing "+s.typeToString()+" with id "+s.id+"."),s}return i(t,e),t.prototype.dispose=function(){this.logger.debug("Destroyed "+this.typeToString()+" with id "+this.id+".")},Object.defineProperty(t.prototype,"id",{get:function(){return this._id},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"kind",{get:function(){throw new Error("Invalid kind.")},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"state",{get:function(){return this._state},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"transport",{get:function(){return this._transport},enumerable:!0,configurable:!0}),t.prototype.on=function(t,r){return e.prototype.on.call(this,t,r)},t.prototype.logTransportError=function(e,t){this.logger.error(e.message),this.logger.error("Transport error occurred in "+this.typeToString()+" with id "+this.id+"."),this.logger.error(t)},t.prototype.send=function(e){var t=this;return this.transport.send(e).catch(function(e){var r;if(!(e instanceof s.Exceptions.TransportError))throw r=e&&"string"==typeof e.message?new s.Exceptions.TransportError(e.message):new s.Exceptions.TransportError,t.onTransportError(r),r;t.onTransportError(e)})},t.prototype.setState=function(e){this.logger.debug('State change to "'+e+'" on '+this.typeToString()+" with id "+this.id+"."),this._state=e,this._user.onStateChange&&this._user.onStateChange(e),this.emit("stateChanged")},t.prototype.typeToString=function(){return"UnknownType"},t}(o.EventEmitter);t.Transaction=a},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=function(e){function t(t,r,n,i,o){var s=e.call(this,r,n,t.viaBranch,i,o)||this;return s._request=t,s.user=n,s}return i(t,e),Object.defineProperty(t.prototype,"request",{get:function(){return this._request},enumerable:!0,configurable:!0}),t}(r(29).Transaction);t.ServerTransaction=o},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e){for(var r in e)t.hasOwnProperty(r)||(t[r]=e[r])}(r(95))},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e){for(var r in e)t.hasOwnProperty(r)||(t[r]=e[r])}(r(97))},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(2),i=r(18),o=function(){function e(e,t){this.core=e,this.dialogState=t,this.core.dialogs.set(this.id,this)}return e.initialDialogStateForUserAgentClient=function(e,t){var r=t.getHeaders("record-route").reverse(),n=t.parseHeader("contact");if(!n)throw new Error("Contact undefined.");if(!(n instanceof i.NameAddrHeader))throw new Error("Contact not instance of NameAddrHeader.");var o=n.uri,s=e.cseq,a=e.callId,c=e.fromTag,u=t.toTag;if(!a)throw new Error("Call id undefined.");if(!c)throw new Error("From tag undefined.");if(!u)throw new Error("To tag undefined.");if(!e.from)throw new Error("From undefined.");if(!e.to)throw new Error("To undefined.");var d=e.from.uri,h=e.to.uri;if(!t.statusCode)throw new Error("Incoming response status code undefined.");return{id:a+c+u,early:t.statusCode<200,callId:a,localTag:c,remoteTag:u,localSequenceNumber:s,remoteSequenceNumber:void 0,localURI:d,remoteURI:h,remoteTarget:o,routeSet:r,secure:!1}},e.initialDialogStateForUserAgentServer=function(e,t,r){void 0===r&&(r=!1);var n=e.getHeaders("record-route"),o=e.parseHeader("contact");if(!o)throw new Error("Contact undefined.");if(!(o instanceof i.NameAddrHeader))throw new Error("Contact not instance of NameAddrHeader.");var s=o.uri,a=e.cseq,c=e.callId,u=t,d=e.fromTag,h=e.from.uri;return{id:c+u+d,early:r,callId:c,localTag:u,remoteTag:d,localSequenceNumber:void 0,remoteSequenceNumber:a,localURI:e.to.uri,remoteURI:h,remoteTarget:s,routeSet:n,secure:!1}},e.prototype.dispose=function(){this.core.dialogs.delete(this.id)},Object.defineProperty(e.prototype,"id",{get:function(){return this.dialogState.id},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"early",{get:function(){return this.dialogState.early},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"callId",{get:function(){return this.dialogState.callId},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"localTag",{get:function(){return this.dialogState.localTag},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"remoteTag",{get:function(){return this.dialogState.remoteTag},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"localSequenceNumber",{get:function(){return this.dialogState.localSequenceNumber},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"remoteSequenceNumber",{get:function(){return this.dialogState.remoteSequenceNumber},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"localURI",{get:function(){return this.dialogState.localURI},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"remoteURI",{get:function(){return this.dialogState.remoteURI},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"remoteTarget",{get:function(){return this.dialogState.remoteTarget},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"routeSet",{get:function(){return this.dialogState.routeSet},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"secure",{get:function(){return this.dialogState.secure},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"userAgentCore",{get:function(){return this.core},enumerable:!0,configurable:!0}),e.prototype.confirm=function(){this.dialogState.early=!1},e.prototype.receiveRequest=function(e){if(e.method!==n.C.ACK){if(this.remoteSequenceNumber){if(e.cseq<=this.remoteSequenceNumber)throw new Error("Out of sequence in dialog request. Did you forget to call sequenceGuard()?");this.dialogState.remoteSequenceNumber=e.cseq}this.remoteSequenceNumber||(this.dialogState.remoteSequenceNumber=e.cseq)}},e.prototype.recomputeRouteSet=function(e){this.dialogState.routeSet=e.getHeaders("record-route").reverse()},e.prototype.createOutgoingRequestMessage=function(e,t){var r,n=this.remoteURI,i=this.remoteTag,o=this.localURI,s=this.localTag,a=this.callId;r=t&&t.cseq?t.cseq:this.dialogState.localSequenceNumber?this.dialogState.localSequenceNumber+=1:this.dialogState.localSequenceNumber=1;var c=this.remoteTarget,u=this.routeSet,d=t&&t.extraHeaders,h=t&&t.body?{contentType:t.body.contentType,body:t.body.content}:void 0;return this.core.configuration.outgoingRequestMessageFactory(e,c,{callId:a,cseq:r,fromUri:o,fromTag:s,toUri:n,toTag:i,routeSet:u},d,h)},e.prototype.sequenceGuard=function(e){return e.method===n.C.ACK||(!(this.remoteSequenceNumber&&e.cseq<=this.remoteSequenceNumber)||(this.core.replyStateless(e,{statusCode:500}),!1))},e}();t.Dialog=o},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(1),s=function(e){function t(t,r,n){var i=void 0!==t.userAgentCore?t.userAgentCore:t;return e.call(this,o.NonInviteServerTransaction,i,r,n)||this}return i(t,e),t}(r(9).UserAgentServer);t.NotifyUserAgentServer=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=function(e,t){for(var r,n=[],i=e.split(/\r\n/),o=0;o (https://sipjs.com/aboutus/)",contributors:[{url:"https://github.com/onsip/SIP.js/blob/master/THANKS.md"}],repository:{type:"git",url:"https://github.com/onsip/SIP.js.git"},keywords:["sip","webrtc","library","websocket","javascript","typescript"],dependencies:{"crypto-js":"^3.1.9-1"},devDependencies:{"@types/crypto-js":"^3.1.43","@types/jasmine":"^3.3.11","@types/node":"^12.0.2","circular-dependency-plugin":"^5.0.2","jasmine-core":"^3.4.0",karma:"^4.1.0","karma-chrome-launcher":"^2.2.0","karma-cli":"^2.0.0","karma-jasmine":"^2.0.1","karma-jasmine-html-reporter":"^1.4.2","karma-mocha-reporter":"^2.2.5","karma-sourcemap-loader":"^0.3.7","karma-webpack":"^3.0.5",pegjs:"^0.10.0","ts-loader":"^6.0.1","ts-pegjs":"0.2.3",tslint:"^5.16.0",typescript:"^3.4.5",webpack:"^4.32.0","webpack-cli":"^3.3.2"},engines:{node:">=8.0"},scripts:{prebuild:"tslint -p tsconfig-base.json -c tslint.json","generate-grammar":"node build/grammarGenerator.js","build-reg-bundle":"webpack --progress --config build/webpack.config.js --env.buildType reg","build-min-bundle":"webpack --progress --config build/webpack.config.js --env.buildType min","build-bundles":"npm run build-reg-bundle && npm run build-min-bundle","build-lib":"tsc -p src","build-test":"tsc -p test","copy-dist-files":"cp dist/sip.js dist/sip-$npm_package_version.js && cp dist/sip.min.js dist/sip-$npm_package_version.min.js",build:"npm run generate-grammar && npm run build-lib && npm run build-reg-bundle && npm run build-min-bundle && npm run copy-dist-files",browserTest:"npm run build-test && sleep 2 && open http://0.0.0.0:9876/debug.html & karma start --reporters kjhtml --no-single-run",commandLineTest:"npm run build-test && karma start --reporters mocha --browsers ChromeHeadless --single-run",buildAndTest:"npm run build && npm run commandLineTest",buildAndBrowserTest:"npm run build && npm run browserTest"}}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(66),i=r(3),o=r(5),s=function(){function e(e){this.type=i.TypeStrings.DigestAuthentication,this.logger=e.getLogger("sipjs.digestauthentication"),this.username=e.configuration.authorizationUser,this.password=e.configuration.password,this.nc=0,this.ncHex="00000000"}return e.prototype.authenticate=function(e,t,r){if(this.algorithm=t.algorithm,this.realm=t.realm,this.nonce=t.nonce,this.opaque=t.opaque,this.stale=t.stale,this.algorithm){if("MD5"!==this.algorithm)return this.logger.warn("challenge with Digest algorithm different than 'MD5', authentication aborted"),!1}else this.algorithm="MD5";if(!this.realm)return this.logger.warn("challenge without Digest realm, authentication aborted"),!1;if(!this.nonce)return this.logger.warn("challenge without Digest nonce, authentication aborted"),!1;if(t.qop)if(t.qop.indexOf("auth")>-1)this.qop="auth";else{if(!(t.qop.indexOf("auth-int")>-1))return this.logger.warn("challenge without Digest qop different than 'auth' or 'auth-int', authentication aborted"),!1;this.qop="auth-int"}else this.qop=void 0;return this.method=e.method,this.uri=e.ruri,this.cnonce=o.Utils.createRandomToken(12),this.nc+=1,this.updateNcHex(),4294967296===this.nc&&(this.nc=1,this.ncHex="00000001"),this.calculateResponse(r),!0},e.prototype.toString=function(){var e=[];if(!this.response)throw new Error("response field does not exist, cannot generate Authorization header");return e.push("algorithm="+this.algorithm),e.push('username="'+this.username+'"'),e.push('realm="'+this.realm+'"'),e.push('nonce="'+this.nonce+'"'),e.push('uri="'+this.uri+'"'),e.push('response="'+this.response+'"'),this.opaque&&e.push('opaque="'+this.opaque+'"'),this.qop&&(e.push("qop="+this.qop),e.push('cnonce="'+this.cnonce+'"'),e.push("nc="+this.ncHex)),"Digest "+e.join(", ")},e.prototype.updateNcHex=function(){var e=Number(this.nc).toString(16);this.ncHex="00000000".substr(0,8-e.length)+e},e.prototype.calculateResponse=function(e){var t,r=n.MD5(this.username+":"+this.realm+":"+this.password);"auth"===this.qop?(t=n.MD5(this.method+":"+this.uri),this.response=n.MD5(r+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth:"+t)):"auth-int"===this.qop?(t=n.MD5(this.method+":"+this.uri+":"+n.MD5(e||"")),this.response=n.MD5(r+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth-int:"+t)):void 0===this.qop&&(t=n.MD5(this.method+":"+this.uri),this.response=n.MD5(r+":"+this.nonce+":"+t))},e}();t.DigestAuthentication=s},function(e,t,r){var n;e.exports=(n=r(0),function(e){var t=n,r=t.lib,i=r.WordArray,o=r.Hasher,s=t.algo,a=[],c=[];!function(){function t(t){for(var r=e.sqrt(t),n=2;n<=r;n++)if(!(t%n))return!1;return!0}function r(e){return 4294967296*(e-(0|e))|0}for(var n=2,i=0;i<64;)t(n)&&(i<8&&(a[i]=r(e.pow(n,.5))),c[i]=r(e.pow(n,1/3)),i++),n++}();var u=[],d=s.SHA256=o.extend({_doReset:function(){this._hash=new i.init(a.slice(0))},_doProcessBlock:function(e,t){for(var r=this._hash.words,n=r[0],i=r[1],o=r[2],s=r[3],a=r[4],d=r[5],h=r[6],p=r[7],l=0;l<64;l++){if(l<16)u[l]=0|e[t+l];else{var f=u[l-15],g=(f<<25|f>>>7)^(f<<14|f>>>18)^f>>>3,v=u[l-2],m=(v<<15|v>>>17)^(v<<13|v>>>19)^v>>>10;u[l]=g+u[l-7]+m+u[l-16]}var y=n&i^n&o^i&o,S=(n<<30|n>>>2)^(n<<19|n>>>13)^(n<<10|n>>>22),T=p+((a<<26|a>>>6)^(a<<21|a>>>11)^(a<<7|a>>>25))+(a&d^~a&h)+c[l]+u[l];p=h,h=d,d=a,a=s+T|0,s=o,o=i,i=n,n=T+(S+y)|0}r[0]=r[0]+n|0,r[1]=r[1]+i|0,r[2]=r[2]+o|0,r[3]=r[3]+s|0,r[4]=r[4]+a|0,r[5]=r[5]+d|0,r[6]=r[6]+h|0,r[7]=r[7]+p|0},_doFinalize:function(){var t=this._data,r=t.words,n=8*this._nDataBytes,i=8*t.sigBytes;return r[i>>>5]|=128<<24-i%32,r[14+(i+64>>>9<<4)]=e.floor(n/4294967296),r[15+(i+64>>>9<<4)]=n,t.sigBytes=4*r.length,this._process(),this._hash},clone:function(){var e=o.clone.call(this);return e._hash=this._hash.clone(),e}});t.SHA256=o._createHelper(d),t.HmacSHA256=o._createHmacHelper(d)}(Math),n.SHA256)},function(e,t,r){var n;e.exports=(n=r(0),r(21),function(){var e=n,t=e.lib.Hasher,r=e.x64,i=r.Word,o=r.WordArray,s=e.algo;function a(){return i.create.apply(i,arguments)}var c=[a(1116352408,3609767458),a(1899447441,602891725),a(3049323471,3964484399),a(3921009573,2173295548),a(961987163,4081628472),a(1508970993,3053834265),a(2453635748,2937671579),a(2870763221,3664609560),a(3624381080,2734883394),a(310598401,1164996542),a(607225278,1323610764),a(1426881987,3590304994),a(1925078388,4068182383),a(2162078206,991336113),a(2614888103,633803317),a(3248222580,3479774868),a(3835390401,2666613458),a(4022224774,944711139),a(264347078,2341262773),a(604807628,2007800933),a(770255983,1495990901),a(1249150122,1856431235),a(1555081692,3175218132),a(1996064986,2198950837),a(2554220882,3999719339),a(2821834349,766784016),a(2952996808,2566594879),a(3210313671,3203337956),a(3336571891,1034457026),a(3584528711,2466948901),a(113926993,3758326383),a(338241895,168717936),a(666307205,1188179964),a(773529912,1546045734),a(1294757372,1522805485),a(1396182291,2643833823),a(1695183700,2343527390),a(1986661051,1014477480),a(2177026350,1206759142),a(2456956037,344077627),a(2730485921,1290863460),a(2820302411,3158454273),a(3259730800,3505952657),a(3345764771,106217008),a(3516065817,3606008344),a(3600352804,1432725776),a(4094571909,1467031594),a(275423344,851169720),a(430227734,3100823752),a(506948616,1363258195),a(659060556,3750685593),a(883997877,3785050280),a(958139571,3318307427),a(1322822218,3812723403),a(1537002063,2003034995),a(1747873779,3602036899),a(1955562222,1575990012),a(2024104815,1125592928),a(2227730452,2716904306),a(2361852424,442776044),a(2428436474,593698344),a(2756734187,3733110249),a(3204031479,2999351573),a(3329325298,3815920427),a(3391569614,3928383900),a(3515267271,566280711),a(3940187606,3454069534),a(4118630271,4000239992),a(116418474,1914138554),a(174292421,2731055270),a(289380356,3203993006),a(460393269,320620315),a(685471733,587496836),a(852142971,1086792851),a(1017036298,365543100),a(1126000580,2618297676),a(1288033470,3409855158),a(1501505948,4234509866),a(1607167915,987167468),a(1816402316,1246189591)],u=[];!function(){for(var e=0;e<80;e++)u[e]=a()}();var d=s.SHA512=t.extend({_doReset:function(){this._hash=new o.init([new i.init(1779033703,4089235720),new i.init(3144134277,2227873595),new i.init(1013904242,4271175723),new i.init(2773480762,1595750129),new i.init(1359893119,2917565137),new i.init(2600822924,725511199),new i.init(528734635,4215389547),new i.init(1541459225,327033209)])},_doProcessBlock:function(e,t){for(var r=this._hash.words,n=r[0],i=r[1],o=r[2],s=r[3],a=r[4],d=r[5],h=r[6],p=r[7],l=n.high,f=n.low,g=i.high,v=i.low,m=o.high,y=o.low,S=s.high,T=s.low,C=a.high,b=a.low,_=d.high,A=d.low,w=h.high,E=h.low,R=p.high,I=p.low,O=l,x=f,P=g,N=v,D=m,U=y,H=S,k=T,M=C,q=b,j=_,L=A,F=w,B=E,G=R,W=I,z=0;z<80;z++){var K=u[z];if(z<16)var V=K.high=0|e[t+2*z],Y=K.low=0|e[t+2*z+1];else{var $=u[z-15],X=$.high,J=$.low,Q=(X>>>1|J<<31)^(X>>>8|J<<24)^X>>>7,Z=(J>>>1|X<<31)^(J>>>8|X<<24)^(J>>>7|X<<25),ee=u[z-2],te=ee.high,re=ee.low,ne=(te>>>19|re<<13)^(te<<3|re>>>29)^te>>>6,ie=(re>>>19|te<<13)^(re<<3|te>>>29)^(re>>>6|te<<26),oe=u[z-7],se=oe.high,ae=oe.low,ce=u[z-16],ue=ce.high,de=ce.low;V=(V=(V=Q+se+((Y=Z+ae)>>>0>>0?1:0))+ne+((Y+=ie)>>>0>>0?1:0))+ue+((Y+=de)>>>0>>0?1:0),K.high=V,K.low=Y}var he,pe=M&j^~M&F,le=q&L^~q&B,fe=O&P^O&D^P&D,ge=x&N^x&U^N&U,ve=(O>>>28|x<<4)^(O<<30|x>>>2)^(O<<25|x>>>7),me=(x>>>28|O<<4)^(x<<30|O>>>2)^(x<<25|O>>>7),ye=(M>>>14|q<<18)^(M>>>18|q<<14)^(M<<23|q>>>9),Se=(q>>>14|M<<18)^(q>>>18|M<<14)^(q<<23|M>>>9),Te=c[z],Ce=Te.high,be=Te.low,_e=G+ye+((he=W+Se)>>>0>>0?1:0),Ae=me+ge;G=F,W=B,F=j,B=L,j=M,L=q,M=H+(_e=(_e=(_e=_e+pe+((he+=le)>>>0>>0?1:0))+Ce+((he+=be)>>>0>>0?1:0))+V+((he+=Y)>>>0>>0?1:0))+((q=k+he|0)>>>0>>0?1:0)|0,H=D,k=U,D=P,U=N,P=O,N=x,O=_e+(ve+fe+(Ae>>>0>>0?1:0))+((x=he+Ae|0)>>>0>>0?1:0)|0}f=n.low=f+x,n.high=l+O+(f>>>0>>0?1:0),v=i.low=v+N,i.high=g+P+(v>>>0>>0?1:0),y=o.low=y+U,o.high=m+D+(y>>>0>>0?1:0),T=s.low=T+k,s.high=S+H+(T>>>0>>0?1:0),b=a.low=b+q,a.high=C+M+(b>>>0>>0?1:0),A=d.low=A+L,d.high=_+j+(A>>>0>>0?1:0),E=h.low=E+B,h.high=w+F+(E>>>0>>0?1:0),I=p.low=I+W,p.high=R+G+(I>>>0>>0?1:0)},_doFinalize:function(){var e=this._data,t=e.words,r=8*this._nDataBytes,n=8*e.sigBytes;return t[n>>>5]|=128<<24-n%32,t[30+(n+128>>>10<<5)]=Math.floor(r/4294967296),t[31+(n+128>>>10<<5)]=r,e.sigBytes=4*t.length,this._process(),this._hash.toX32()},clone:function(){var e=t.clone.call(this);return e._hash=this._hash.clone(),e},blockSize:32});e.SHA512=t._createHelper(d),e.HmacSHA512=t._createHmacHelper(d)}(),n.SHA512)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n,i=r(3);!function(e){e[e.error=0]="error",e[e.warn=1]="warn",e[e.log=2]="log",e[e.debug=3]="debug"}(n=t.Levels||(t.Levels={}));var o=function(){function e(){this.builtinEnabled=!0,this._level=n.log,this.loggers={},this.type=i.TypeStrings.LoggerFactory,this.logger=this.getLogger("sip:loggerfactory")}return Object.defineProperty(e.prototype,"level",{get:function(){return this._level},set:function(e){e>=0&&e<=3?this._level=e:e>3?this._level=3:n.hasOwnProperty(e)?this._level=e:this.logger.error("invalid 'level' parameter value: "+JSON.stringify(e))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"connector",{get:function(){return this._connector},set:function(e){e?"function"==typeof e?this._connector=e:this.logger.error("invalid 'connector' parameter value: "+JSON.stringify(e)):this._connector=void 0},enumerable:!0,configurable:!0}),e.prototype.getLogger=function(e,t){if(t&&3===this.level)return new s(this,e,t);if(this.loggers[e])return this.loggers[e];var r=new s(this,e);return this.loggers[e]=r,r},e.prototype.genericLog=function(e,t,r,i){this.level>=e&&this.builtinEnabled&&this.print(e,t,r,i),this.connector&&this.connector(n[e],t,r,i)},e.prototype.print=function(e,t,r,i){if("string"==typeof i){var o=[new Date,t];r&&o.push(r),i=o.concat(i).join(" | ")}switch(e){case n.error:console.error(i);break;case n.warn:console.warn(i);break;case n.log:console.log(i);break;case n.debug:console.debug(i)}},e}();t.LoggerFactory=o;var s=function(){function e(e,t,r){this.type=i.TypeStrings.Logger,this.logger=e,this.category=t,this.label=r}return e.prototype.error=function(e){this.genericLog(n.error,e)},e.prototype.warn=function(e){this.genericLog(n.warn,e)},e.prototype.log=function(e){this.genericLog(n.log,e)},e.prototype.debug=function(e){this.genericLog(n.debug,e)},e.prototype.genericLog=function(e,t){this.logger.genericLog(e,this.category,this.label,t)},e}();t.Logger=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(3),i=r(11),o=r(8);!function(e){function t(e,t){var r=t,n=0,i=0;if(e.substring(r,r+2).match(/(^\r\n)/))return-2;for(;0===n;){if(-1===(i=e.indexOf("\r\n",r)))return i;!e.substring(i+2,i+4).match(/(^\r\n)/)&&e.charAt(i+2).match(/(^\s+)/)?r=i+2:n=i}return n}function r(e,t,r,o){var s,a=t.indexOf(":",r),c=t.substring(r,a).trim(),u=t.substring(a+1,o).trim();switch(c.toLowerCase()){case"via":case"v":e.addHeader("via",u),1===e.getHeaders("via").length?(s=e.parseHeader("Via"))&&(e.via=s,e.viaBranch=s.branch):s=0;break;case"from":case"f":e.setHeader("from",u),(s=e.parseHeader("from"))&&(e.from=s,e.fromTag=s.getParam("tag"));break;case"to":case"t":e.setHeader("to",u),(s=e.parseHeader("to"))&&(e.to=s,e.toTag=s.getParam("tag"));break;case"record-route":if(-1===(s=i.Grammar.parse(u,"Record_Route"))){s=void 0;break}for(var d in s)s[d]&&(e.addHeader("record-route",u.substring(s[d].position,s[d].offset)),e.headers["Record-Route"][e.getHeaders("record-route").length-1].parsed=s[d].parsed);break;case"call-id":case"i":e.setHeader("call-id",u),(s=e.parseHeader("call-id"))&&(e.callId=u);break;case"contact":case"m":if(-1===(s=i.Grammar.parse(u,"Contact"))){s=void 0;break}if(!(s instanceof Array)){s=void 0;break}s.forEach(function(t){e.addHeader("contact",u.substring(t.position,t.offset)),e.headers.Contact[e.getHeaders("contact").length-1].parsed=t.parsed});break;case"content-length":case"l":e.setHeader("content-length",u),s=e.parseHeader("content-length");break;case"content-type":case"c":e.setHeader("content-type",u),s=e.parseHeader("content-type");break;case"cseq":e.setHeader("cseq",u),(s=e.parseHeader("cseq"))&&(e.cseq=s.value),e.type===n.TypeStrings.IncomingResponse&&(e.method=s.method);break;case"max-forwards":e.setHeader("max-forwards",u),s=e.parseHeader("max-forwards");break;case"www-authenticate":e.setHeader("www-authenticate",u),s=e.parseHeader("www-authenticate");break;case"proxy-authenticate":e.setHeader("proxy-authenticate",u),s=e.parseHeader("proxy-authenticate");break;case"refer-to":case"r":e.setHeader("refer-to",u),(s=e.parseHeader("refer-to"))&&(e.referTo=s);break;default:e.setHeader(c,u),s=0}return void 0!==s||{error:"error parsing header '"+c+"'"}}e.getHeader=t,e.parseHeader=r,e.parseMessage=function(e,n){var s=0,a=e.indexOf("\r\n"),c=n.getLogger("sip.parser");if(-1!==a){var u,d=e.substring(0,a),h=i.Grammar.parse(d,"Request_Response");if(-1!==h){var p;for(h.status_code?((u=new o.IncomingResponse(n)).statusCode=h.status_code,u.reasonPhrase=h.reason_phrase):((u=new o.IncomingRequest(n)).method=h.method,u.ruri=h.uri),u.data=e,s=a+2;;){if(-2===(a=t(e,s))){p=s+2;break}if(-1===a)return void c.error("malformed message");if(!0!==r(u,e,s,a))return void c.error(h.error);s=a+2}return u.hasHeader("content-length")?u.body=e.substr(p,Number(u.getHeader("content-length"))):u.body=e.substring(p),u}c.warn('error parsing first line of SIP message: "'+d+'"')}else c.warn("no CRLF found, not a SIP message, discarded")}}(t.Parser||(t.Parser={}))},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(15),s=r(2),a=r(3),c=r(7),u=r(8),d=r(5),h=function(e){function t(t,r,n,i){void 0===i&&(i={});var o=this;if(i.extraHeaders=(i.extraHeaders||[]).slice(),i.contentType=i.contentType||"text/plain","number"!=typeof i.expires||i.expires%1!=0?i.expires=3600:i.expires=Number(i.expires),"boolean"!=typeof i.unpublishOnClose&&(i.unpublishOnClose=!0),null==r||""===r)throw new c.Exceptions.MethodParameterError("Publish","Target",r);if(void 0===(r=t.normalizeTarget(r)))throw new c.Exceptions.MethodParameterError("Publish","Target",r);if((o=e.call(this,t,s.C.PUBLISH,r,i)||this).type=a.TypeStrings.PublishContext,o.options=i,o.target=r,null==n||""===n)throw new c.Exceptions.MethodParameterError("Publish","Event",n);return o.event=n,o.logger=t.getLogger("sip.publish"),o.pubRequestExpires=o.options.expires,t.on("transportCreated",function(e){e.on("transportError",function(){return o.onTransportError()})}),o}return i(t,e),t.prototype.publish=function(e){this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.options.body=e,this.pubRequestBody=this.options.body,0===this.pubRequestExpires&&(this.pubRequestExpires=this.options.expires,this.pubRequestEtag=void 0),this.ua.publishers[this.target.toString()+":"+this.event]||(this.ua.publishers[this.target.toString()+":"+this.event]=this),this.sendPublishRequest()},t.prototype.unpublish=function(){this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.pubRequestBody=void 0,this.pubRequestExpires=0,void 0!==this.pubRequestEtag&&this.sendPublishRequest()},t.prototype.close=function(){this.options.unpublishOnClose?this.unpublish():(this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.pubRequestBody=void 0,this.pubRequestExpires=0,this.pubRequestEtag=void 0),this.ua.publishers[this.target.toString()+":"+this.event]&&delete this.ua.publishers[this.target.toString()+":"+this.event]},t.prototype.onRequestTimeout=function(){e.prototype.onRequestTimeout.call(this),this.emit("unpublished",void 0,s.C.causes.REQUEST_TIMEOUT)},t.prototype.onTransportError=function(){e.prototype.onTransportError.call(this),this.emit("unpublished",void 0,s.C.causes.CONNECTION_ERROR)},t.prototype.receiveResponse=function(e){var t=this,r=e.statusCode||0,n=d.Utils.getReasonPhrase(r);switch(!0){case/^1[0-9]{2}$/.test(r.toString()):this.emit("progress",e,n);break;case/^2[0-9]{2}$/.test(r.toString()):if(e.hasHeader("SIP-ETag")?this.pubRequestEtag=e.getHeader("SIP-ETag"):this.logger.warn("SIP-ETag header missing in a 200-class response to PUBLISH"),e.hasHeader("Expires")){var i=Number(e.getHeader("Expires"));"number"==typeof i&&i>=0&&i<=this.pubRequestExpires?this.pubRequestExpires=i:this.logger.warn("Bad Expires header in a 200-class response to PUBLISH")}else this.logger.warn("Expires header missing in a 200-class response to PUBLISH");0!==this.pubRequestExpires?(this.publishRefreshTimer=setTimeout(function(){return t.refreshRequest()},900*this.pubRequestExpires),this.emit("published",e,n)):this.emit("unpublished",e,n);break;case/^412$/.test(r.toString()):void 0!==this.pubRequestEtag&&0!==this.pubRequestExpires?(this.logger.warn("412 response to PUBLISH, recovering"),this.pubRequestEtag=void 0,this.emit("progress",e,n),this.publish(this.options.body)):(this.logger.warn("412 response to PUBLISH, recovery failed"),this.pubRequestExpires=0,this.emit("failed",e,n),this.emit("unpublished",e,n));break;case/^423$/.test(r.toString()):if(0!==this.pubRequestExpires&&e.hasHeader("Min-Expires")){var o=Number(e.getHeader("Min-Expires"));"number"==typeof o||o>this.pubRequestExpires?(this.logger.warn("423 code in response to PUBLISH, adjusting the Expires value and trying to recover"),this.pubRequestExpires=o,this.emit("progress",e,n),this.publish(this.options.body)):(this.logger.warn("Bad 423 response Min-Expires header received for PUBLISH"),this.pubRequestExpires=0,this.emit("failed",e,n),this.emit("unpublished",e,n))}else this.logger.warn("423 response to PUBLISH, recovery failed"),this.pubRequestExpires=0,this.emit("failed",e,n),this.emit("unpublished",e,n);break;default:this.pubRequestExpires=0,this.emit("failed",e,n),this.emit("unpublished",e,n)}0===this.pubRequestExpires&&(this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.pubRequestBody=void 0,this.pubRequestEtag=void 0)},t.prototype.send=function(){var e=this;return this.ua.userAgentCore.publish(this.request,{onAccept:function(t){return e.receiveResponse(t.message)},onProgress:function(t){return e.receiveResponse(t.message)},onRedirect:function(t){return e.receiveResponse(t.message)},onReject:function(t){return e.receiveResponse(t.message)},onTrying:function(t){return e.receiveResponse(t.message)}}),this},t.prototype.refreshRequest=function(){if(this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.pubRequestBody=void 0,void 0===this.pubRequestEtag)throw new c.Exceptions.MethodParameterError("Publish","Body",void 0);if(0===this.pubRequestExpires)throw new c.Exceptions.MethodParameterError("Publish","Expire",this.pubRequestExpires);this.sendPublishRequest()},t.prototype.sendPublishRequest=function(){var e=Object.create(this.options||Object.prototype);e.extraHeaders=(this.options.extraHeaders||[]).slice(),e.extraHeaders.push("Event: "+this.event),e.extraHeaders.push("Expires: "+this.pubRequestExpires),void 0!==this.pubRequestEtag&&e.extraHeaders.push("SIP-If-Match: "+this.pubRequestEtag),this.request=new u.OutgoingRequest(s.C.PUBLISH,this.target,this.ua,this.options.params,e.extraHeaders),void 0!==this.pubRequestBody&&(this.request.body={body:this.pubRequestBody,contentType:this.options.contentType}),this.send()},t}(o.ClientContext);t.PublishContext=h},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(12),s=r(28),a=r(20),c=function(e){function t(t,r,n){var i=e.call(this,t,r,n,a.TransactionState.Calling,"sip.transaction.ict")||this;return i.ackRetransmissionCache=new Map,i.B=setTimeout(function(){return i.timer_B()},o.Timers.TIMER_B),i.send(t.toString()).catch(function(e){i.logTransportError(e,"Failed to send initial outgoing request.")}),i}return i(t,e),t.prototype.dispose=function(){this.B&&(clearTimeout(this.B),this.B=void 0),this.D&&(clearTimeout(this.D),this.D=void 0),this.M&&(clearTimeout(this.M),this.M=void 0),e.prototype.dispose.call(this)},Object.defineProperty(t.prototype,"kind",{get:function(){return"ict"},enumerable:!0,configurable:!0}),t.prototype.ackResponse=function(e){var t=this,r=e.toTag;if(!r)throw new Error("To tag undefined.");var n="z9hG4bK"+Math.floor(1e7*Math.random());e.setViaHeader(n,this.transport),this.ackRetransmissionCache.set(r,e),this.send(e.toString()).catch(function(e){t.logTransportError(e,"Failed to send ACK to 2xx response.")})},t.prototype.receiveResponse=function(e){var t=this,r=e.statusCode;if(!r||r<100||r>699)throw new Error("Invalid status code "+r);switch(this.state){case a.TransactionState.Calling:if(r>=100&&r<=199)return this.stateTransition(a.TransactionState.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(r>=200&&r<=299)return this.ackRetransmissionCache.set(e.toTag,void 0),this.stateTransition(a.TransactionState.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(r>=300&&r<=699)return this.stateTransition(a.TransactionState.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case a.TransactionState.Proceeding:if(r>=100&&r<=199)return void(this.user.receiveResponse&&this.user.receiveResponse(e));if(r>=200&&r<=299)return this.ackRetransmissionCache.set(e.toTag,void 0),this.stateTransition(a.TransactionState.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(r>=300&&r<=699)return this.stateTransition(a.TransactionState.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case a.TransactionState.Accepted:if(r>=200&&r<=299){if(!this.ackRetransmissionCache.has(e.toTag))return this.ackRetransmissionCache.set(e.toTag,void 0),void(this.user.receiveResponse&&this.user.receiveResponse(e));var n=this.ackRetransmissionCache.get(e.toTag);return n?void this.send(n.toString()).catch(function(e){t.logTransportError(e,"Failed to send retransmission of ACK to 2xx response.")}):void 0}break;case a.TransactionState.Completed:if(r>=300&&r<=699)return void this.ack(e);break;case a.TransactionState.Terminated:break;default:throw new Error("Invalid state "+this.state)}var i="Received unexpected "+r+" response while in state "+this.state+".";this.logger.warn(i)},t.prototype.onTransportError=function(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(a.TransactionState.Terminated,!0)},t.prototype.typeToString=function(){return"INVITE client transaction"},t.prototype.ack=function(e){var t=this,r=this.request.ruri,n=this.request.callId,i=this.request.cseq,o=this.request.getHeader("from"),s=e.getHeader("to"),a=this.request.getHeader("via"),c=this.request.getHeader("route");if(!o)throw new Error("From undefined.");if(!s)throw new Error("To undefined.");if(!a)throw new Error("Via undefined.");var u="ACK "+r+" SIP/2.0\r\n";c&&(u+="Route: "+c+"\r\n"),u+="Via: "+a+"\r\n",u+="To: "+s+"\r\n",u+="From: "+o+"\r\n",u+="Call-ID: "+n+"\r\n",u+="CSeq: "+i+" ACK\r\n",u+="Max-Forwards: 70\r\n",u+="Content-Length: 0\r\n\r\n",this.send(u).catch(function(e){t.logTransportError(e,"Failed to send ACK to non-2xx response.")})},t.prototype.stateTransition=function(e,t){var r=this;void 0===t&&(t=!1);var n=function(){throw new Error("Invalid state transition from "+r.state+" to "+e)};switch(e){case a.TransactionState.Calling:n();break;case a.TransactionState.Proceeding:this.state!==a.TransactionState.Calling&&n();break;case a.TransactionState.Accepted:case a.TransactionState.Completed:this.state!==a.TransactionState.Calling&&this.state!==a.TransactionState.Proceeding&&n();break;case a.TransactionState.Terminated:this.state!==a.TransactionState.Calling&&this.state!==a.TransactionState.Accepted&&this.state!==a.TransactionState.Completed&&(t||n());break;default:n()}this.B&&(clearTimeout(this.B),this.B=void 0),a.TransactionState.Proceeding,e===a.TransactionState.Completed&&(this.D=setTimeout(function(){return r.timer_D()},o.Timers.TIMER_D)),e===a.TransactionState.Accepted&&(this.M=setTimeout(function(){return r.timer_M()},o.Timers.TIMER_M)),e===a.TransactionState.Terminated&&this.dispose(),this.setState(e)},t.prototype.timer_A=function(){},t.prototype.timer_B=function(){this.logger.debug("Timer B expired for INVITE client transaction "+this.id+"."),this.state===a.TransactionState.Calling&&(this.onRequestTimeout(),this.stateTransition(a.TransactionState.Terminated))},t.prototype.timer_D=function(){this.logger.debug("Timer D expired for INVITE client transaction "+this.id+"."),this.state===a.TransactionState.Completed&&this.stateTransition(a.TransactionState.Terminated)},t.prototype.timer_M=function(){this.logger.debug("Timer M expired for INVITE client transaction "+this.id+"."),this.state===a.TransactionState.Accepted&&this.stateTransition(a.TransactionState.Terminated)},t}(s.ClientTransaction);t.InviteClientTransaction=c},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}),o=this&&this.__assign||function(){return(o=Object.assign||function(e){for(var t,r=1,n=arguments.length;r=0)return t}},extraContactHeaderParams:function(e){if(e instanceof Array)return e.filter(function(e){return"string"==typeof e})},instanceId:function(e){if("string"==typeof e)return/^uuid:/i.test(e)&&(e=e.substr(5)),-1===d.Grammar.parse(e,"uuid")?void 0:e},params:function(e){if("object"==typeof e)return e},regId:function(e){if(h.Utils.isDecimal(e)){var t=Number(e);if(t>=0)return t}},registrar:function(e){if("string"==typeof e){/^sip:/i.test(e)||(e=a.C.SIP+":"+e);var t=d.Grammar.URIParse(e);return t?t.user?void 0:t:void 0}}}};for(var n in r.mandatory){if(!e.hasOwnProperty(n))throw new u.Exceptions.ConfigurationError(n);var i=e[n];if(void 0===(o=r.mandatory[n](i)))throw new u.Exceptions.ConfigurationError(n,i);t[n]=o}for(var n in r.optional)if(e.hasOwnProperty(n)){var o;if((i=e[n])instanceof Array&&0===i.length)continue;if(null===i||""===i||void 0===i||"number"==typeof i&&isNaN(i))continue;if(void 0===(o=r.optional[n](i)))throw new u.Exceptions.ConfigurationError(n,i);t[n]=o}return t}var l=function(e){function t(t,r){void 0===r&&(r={});var n=this,i=p(r);if(i.regId&&!i.instanceId?i.instanceId=h.Utils.newUUID():!i.regId&&i.instanceId&&(i.regId=1),i.params.toUri=i.params.toUri||t.configuration.uri,i.params.toDisplayName=i.params.toDisplayName||t.configuration.displayName,i.params.callId=i.params.callId||h.Utils.createRandomToken(22),i.params.cseq=i.params.cseq||Math.floor(1e4*Math.random()),!i.registrar){var o={};"object"==typeof t.configuration.uri?(o=t.configuration.uri.clone()).user=void 0:o=t.configuration.uri,i.registrar=o}for(var s in(n=e.call(this,t,a.C.REGISTER,i.registrar,i)||this).type=c.TypeStrings.RegisterContext,n.options=i,n.logger=t.getLogger("sip.registercontext"),n.logger.log("configuration parameters for RegisterContext after validation:"),i)i.hasOwnProperty(s)&&n.logger.log("\xb7 "+s+": "+JSON.stringify(i[s]));return n.expires=i.expires,n.contact=t.contact.toString(),n.registered=!1,t.on("transportCreated",function(e){e.on("disconnected",function(){return n.onTransportDisconnected()})}),n}return i(t,e),t.prototype.register=function(e){var t=this;void 0===e&&(e={}),this.options=o({},this.options,e);var r=(this.options.extraHeaders||[]).slice();r.push("Contact: "+this.generateContactHeader(this.expires)),r.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),this.closeHeaders=this.options.closeWithHeaders?(this.options.extraHeaders||[]).slice():[],this.receiveResponse=function(e){if(e.cseq===t.request.cseq){void 0!==t.registrationTimer&&(clearTimeout(t.registrationTimer),t.registrationTimer=void 0);var r=(e.statusCode||0).toString();switch(!0){case/^1[0-9]{2}$/.test(r):t.emit("progress",e);break;case/^2[0-9]{2}$/.test(r):t.emit("accepted",e);var n=void 0;e.hasHeader("expires")&&(n=Number(e.getHeader("expires"))),void 0!==t.registrationExpiredTimer&&(clearTimeout(t.registrationExpiredTimer),t.registrationExpiredTimer=void 0);var i=e.getHeaders("contact").length;if(!i){t.logger.warn("no Contact header in response to REGISTER, response ignored");break}for(var o=void 0;i--;){if((o=e.parseHeader("contact",i)).uri.user===t.ua.contact.uri.user){n=o.getParam("expires");break}o=void 0}if(!o){t.logger.warn("no Contact header pointing to us, response ignored");break}void 0===n&&(n=t.expires),t.registrationTimer=setTimeout(function(){t.registrationTimer=void 0,t.register(t.options)},1e3*n-3e3),t.registrationExpiredTimer=setTimeout(function(){t.logger.warn("registration expired"),t.registered&&t.unregistered(void 0,a.C.causes.EXPIRES)},1e3*n),o.hasParam("temp-gruu")&&(t.ua.contact.tempGruu=d.Grammar.URIParse(o.getParam("temp-gruu").replace(/"/g,""))),o.hasParam("pub-gruu")&&(t.ua.contact.pubGruu=d.Grammar.URIParse(o.getParam("pub-gruu").replace(/"/g,""))),t.registered=!0,t.emit("registered",e||void 0);break;case/^423$/.test(r):e.hasHeader("min-expires")?(t.expires=Number(e.getHeader("min-expires")),t.register(t.options)):(t.logger.warn("423 response received for REGISTER without Min-Expires"),t.registrationFailure(e,a.C.causes.SIP_FAILURE_CODE));break;default:t.registrationFailure(e,h.Utils.sipErrorCause(e.statusCode||0))}}},this.onRequestTimeout=function(){t.registrationFailure(void 0,a.C.causes.REQUEST_TIMEOUT)},this.onTransportError=function(){t.registrationFailure(void 0,a.C.causes.CONNECTION_ERROR)},this.request.cseq++,this.request.setHeader("cseq",this.request.cseq+" REGISTER"),this.request.extraHeaders=r,this.send()},t.prototype.close=function(){var e={all:!1,extraHeaders:this.closeHeaders};this.registeredBefore=this.registered,this.registered&&this.unregister(e)},t.prototype.unregister=function(e){var t=this;void 0===e&&(e={}),this.registered||e.all||this.logger.warn("Already unregistered, but sending an unregister anyways.");var r=(e.extraHeaders||[]).slice();this.registered=!1,void 0!==this.registrationTimer&&(clearTimeout(this.registrationTimer),this.registrationTimer=void 0),e.all?(r.push("Contact: *"),r.push("Expires: 0")):r.push("Contact: "+this.generateContactHeader(0)),this.receiveResponse=function(e){var r=e&&e.statusCode?e.statusCode.toString():"";switch(!0){case/^1[0-9]{2}$/.test(r):t.emit("progress",e);break;case/^2[0-9]{2}$/.test(r):t.emit("accepted",e),void 0!==t.registrationExpiredTimer&&(clearTimeout(t.registrationExpiredTimer),t.registrationExpiredTimer=void 0),t.unregistered(e);break;default:t.unregistered(e,h.Utils.sipErrorCause(e.statusCode||0))}},this.onRequestTimeout=function(){},this.request.cseq++,this.request.setHeader("cseq",this.request.cseq+" REGISTER"),this.request.extraHeaders=r,this.send()},t.prototype.unregistered=function(e,t){this.registered=!1,this.emit("unregistered",e||void 0,t||void 0)},t.prototype.send=function(){var e=this;return this.ua.userAgentCore.register(this.request,{onAccept:function(t){return e.receiveResponse(t.message)},onProgress:function(t){return e.receiveResponse(t.message)},onRedirect:function(t){return e.receiveResponse(t.message)},onReject:function(t){return e.receiveResponse(t.message)},onTrying:function(t){return e.receiveResponse(t.message)}}),this},t.prototype.registrationFailure=function(e,t){this.emit("failed",e||void 0,t||void 0)},t.prototype.onTransportDisconnected=function(){this.registeredBefore=this.registered,void 0!==this.registrationTimer&&(clearTimeout(this.registrationTimer),this.registrationTimer=void 0),void 0!==this.registrationExpiredTimer&&(clearTimeout(this.registrationExpiredTimer),this.registrationExpiredTimer=void 0),this.registered&&this.unregistered(void 0,a.C.causes.CONNECTION_ERROR)},t.prototype.generateContactHeader=function(e){void 0===e&&(e=0);var t=this.contact;return this.options.regId&&this.options.instanceId&&(t+=";reg-id="+this.options.regId,t+=';+sip.instance=""'),this.options.extraContactHeaderParams&&this.options.extraContactHeaderParams.forEach(function(e){t+=";"+e}),t+=";expires="+e},t}(s.ClientContext);t.RegisterContext=l},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(10),s=r(15),a=r(2),c=r(14),u=r(31),d=r(3),h=r(7),p=r(11),l=r(27),f=r(22),g=r(96),v=r(12),m=r(5),y=function(e){function t(r){var n=e.call(this)||this;if(n.data={},n.type=d.TypeStrings.Session,!r)throw new h.Exceptions.SessionDescriptionHandlerError("A session description handler is required for the session to function");return n.status=t.C.STATUS_NULL,n.pendingReinvite=!1,n.sessionDescriptionHandlerFactory=r,n.hasOffer=!1,n.hasAnswer=!1,n.timers={ackTimer:void 0,expiresTimer:void 0,invite2xxTimer:void 0,userNoAnswerTimer:void 0,rel1xxTimer:void 0,prackTimer:void 0},n.startTime=void 0,n.endTime=void 0,n.tones=void 0,n.localHold=!1,n.earlySdp=void 0,n.rel100=a.C.supported.UNSUPPORTED,n}return i(t,e),t.prototype.dtmf=function(e,t){var r=this;if(void 0===t&&(t={}),this.status!==d.SessionStatus.STATUS_CONFIRMED&&this.status!==d.SessionStatus.STATUS_WAITING_FOR_ACK)throw new h.Exceptions.InvalidStateError(this.status);if(!e||!e.toString().match(/^[0-9A-D#*,]+$/i))throw new TypeError("Invalid tones: "+e);var n=function(){if(r.status!==d.SessionStatus.STATUS_TERMINATED&&r.tones&&0!==r.tones.length){var e,i=r.tones.shift();","===i.tone?e=2e3:(i.on("failed",function(){r.tones=void 0}),i.send(t),e=i.duration+i.interToneGap),setTimeout(n,e)}else r.tones=void 0};e=e.toString();var i=this.ua.configuration.dtmfType;this.sessionDescriptionHandler&&i===a.C.dtmfType.RTP&&(this.sessionDescriptionHandler.sendDtmf(e,t)||(this.logger.warn("Attempt to use dtmfType 'RTP' has failed, falling back to INFO packet method"),i=a.C.dtmfType.INFO));if(i===a.C.dtmfType.INFO){for(var o=[],s=e.split("");s.length>0;)o.push(new g.DTMF(this,s.shift(),t));if(this.tones)return this.tones=this.tones.concat(o),this;this.tones=o,n()}return this},t.prototype.bye=function(e){if(void 0===e&&(e={}),this.status===d.SessionStatus.STATUS_TERMINATED)return this.logger.error("Error: Attempted to send BYE in a terminated session."),this;this.logger.log("terminating Session");var t=e.statusCode;if(t&&(t<200||t>=700))throw new TypeError("Invalid statusCode: "+t);return e.receiveResponse=function(){},this.sendRequest(a.C.BYE,e).terminated()},t.prototype.refer=function(e,t){if(void 0===t&&(t={}),this.status!==d.SessionStatus.STATUS_CONFIRMED)throw new h.Exceptions.InvalidStateError(this.status);return this.referContext=new l.ReferClientContext(this.ua,this,e,t),this.emit("referRequested",this.referContext),this.referContext.refer(t),this.referContext},t.prototype.sendRequest=function(e,t){if(void 0===t&&(t={}),!this.session)throw new Error("Session undefined.");var r;t.body&&(t.body=c.fromBodyObj(t.body));var n,i=t.receiveResponse;i&&(r={onAccept:function(e){return i(e.message)},onProgress:function(e){return i(e.message)},onRedirect:function(e){return i(e.message)},onReject:function(e){return i(e.message)},onTrying:function(e){return i(e.message)}});var o=t;switch(e){case a.C.BYE:n=this.session.bye(r,o);break;case a.C.INVITE:n=this.session.invite(r,o);break;case a.C.REFER:n=this.session.refer(r,o);break;default:throw new Error("Unexpected "+e+". Method not implemented by user agent core.")}return this.emit(e.toLowerCase(),n.message),this},t.prototype.close=function(){if(this.status===d.SessionStatus.STATUS_TERMINATED)return this;for(var e in this.logger.log("closing INVITE session "+this.id),this.sessionDescriptionHandler&&this.sessionDescriptionHandler.close(),this.timers)this.timers[e]&&clearTimeout(this.timers[e]);return this.status=d.SessionStatus.STATUS_TERMINATED,this.ua.transport&&this.ua.transport.removeListener("transportError",this.errorListener),delete this.ua.sessions[this.id],this},t.prototype.hold=function(e,t){if(void 0===e&&(e={}),void 0===t&&(t=[]),this.status!==d.SessionStatus.STATUS_WAITING_FOR_ACK&&this.status!==d.SessionStatus.STATUS_CONFIRMED)throw new h.Exceptions.InvalidStateError(this.status);this.localHold?this.logger.log("Session is already on hold, cannot put it on hold again"):(e.modifiers=t,this.sessionDescriptionHandler&&e.modifiers.push(this.sessionDescriptionHandler.holdModifier),this.localHold=!0,this.sendReinvite(e))},t.prototype.unhold=function(e,t){if(void 0===e&&(e={}),void 0===t&&(t=[]),this.status!==d.SessionStatus.STATUS_WAITING_FOR_ACK&&this.status!==d.SessionStatus.STATUS_CONFIRMED)throw new h.Exceptions.InvalidStateError(this.status);this.localHold?(e.modifiers=t,this.localHold=!1,this.sendReinvite(e)):this.logger.log("Session is not on hold, cannot unhold it")},t.prototype.reinvite=function(e,t){return void 0===e&&(e={}),void 0===t&&(t=[]),e.modifiers=t,this.sendReinvite(e)},t.prototype.terminate=function(e){return this},t.prototype.onTransportError=function(){this.status!==d.SessionStatus.STATUS_CONFIRMED&&this.status!==d.SessionStatus.STATUS_TERMINATED&&this.failed(void 0,a.C.causes.CONNECTION_ERROR)},t.prototype.onRequestTimeout=function(){this.status===d.SessionStatus.STATUS_CONFIRMED?this.terminated(void 0,a.C.causes.REQUEST_TIMEOUT):this.status!==d.SessionStatus.STATUS_TERMINATED&&(this.failed(void 0,a.C.causes.REQUEST_TIMEOUT),this.terminated(void 0,a.C.causes.REQUEST_TIMEOUT))},t.prototype.onDialogError=function(e){this.status===d.SessionStatus.STATUS_CONFIRMED?this.terminated(e,a.C.causes.DIALOG_ERROR):this.status!==d.SessionStatus.STATUS_TERMINATED&&(this.failed(e,a.C.causes.DIALOG_ERROR),this.terminated(e,a.C.causes.DIALOG_ERROR))},t.prototype.on=function(t,r){return e.prototype.on.call(this,t,r)},t.prototype.onAck=function(e){var t=this,r=function(){clearTimeout(t.timers.ackTimer),clearTimeout(t.timers.invite2xxTimer),t.status=d.SessionStatus.STATUS_CONFIRMED;var r=e.message.getHeader("Content-Disposition");r&&"render"===r.type&&(t.renderbody=e.message.body,t.rendertype=e.message.getHeader("Content-Type")),t.emit("confirmed",e.message)};this.status===d.SessionStatus.STATUS_WAITING_FOR_ACK&&(this.sessionDescriptionHandler&&this.sessionDescriptionHandler.hasDescription(e.message.getHeader("Content-Type")||"")?(this.hasAnswer=!0,this.sessionDescriptionHandler.setDescription(e.message.body,this.sessionDescriptionHandlerOptions,this.modifiers).catch(function(r){throw t.logger.warn(r),t.terminate({statusCode:"488",reasonPhrase:"Bad Media Description"}),t.failed(e.message,a.C.causes.BAD_MEDIA_DESCRIPTION),t.terminated(e.message,a.C.causes.BAD_MEDIA_DESCRIPTION),r}).then(function(){return r()})):r())},t.prototype.receiveRequest=function(e){switch(e.message.method){case a.C.BYE:e.accept(),this.status===d.SessionStatus.STATUS_CONFIRMED&&(this.emit("bye",e.message),this.terminated(e.message,a.C.BYE));break;case a.C.INVITE:this.status===d.SessionStatus.STATUS_CONFIRMED&&(this.logger.log("re-INVITE received"),this.receiveReinvite(e));break;case a.C.INFO:if(this.status===d.SessionStatus.STATUS_CONFIRMED||this.status===d.SessionStatus.STATUS_WAITING_FOR_ACK){if(this.onInfo)return this.onInfo(e.message);var t=e.message.getHeader("content-type");if(t)if(t.match(/^application\/dtmf-relay/i)){if(e.message.body){var r=e.message.body.split("\r\n",2);if(2===r.length){var n=void 0,i=void 0,o=/^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/;o.test(r[0])&&(n=r[0].replace(o,"$2"));var s=/^(Duration\s?=\s?)([0-9]{1,4})(\s)?.*/;s.test(r[1])&&(i=parseInt(r[1].replace(s,"$2"),10)),n&&i&&new g.DTMF(this,n,{duration:i}).init_incoming(e)}}}else e.reject({statusCode:415,extraHeaders:["Accept: application/dtmf-relay"]})}break;case a.C.REFER:if(this.status===d.SessionStatus.STATUS_CONFIRMED)if(this.logger.log("REFER received"),this.referContext=new l.ReferServerContext(this.ua,e,this.session),this.listeners("referRequested").length)this.emit("referRequested",this.referContext);else{this.logger.log("No referRequested listeners, automatically accepting and following the refer");var c={followRefer:!0};this.passedOptions&&(c.inviteOptions=this.passedOptions),this.referContext.accept(c,this.modifiers)}break;case a.C.NOTIFY:if(this.referContext&&this.referContext.type===d.TypeStrings.ReferClientContext&&e.message.hasHeader("event")&&/^refer(;.*)?$/.test(e.message.getHeader("event")))return void this.referContext.receiveNotify(e);e.accept(),this.emit("notify",e.message)}},t.prototype.receiveReinvite=function(e){var t,r=this;if(this.emit("reinvite",this,e.message),e.message.hasHeader("P-Asserted-Identity")&&(this.assertedIdentity=p.Grammar.nameAddrHeaderParse(e.message.getHeader("P-Asserted-Identity"))),this.sessionDescriptionHandler){if("0"!==e.message.getHeader("Content-Length")||e.message.getHeader("Content-Type")){if(!this.sessionDescriptionHandler.hasDescription(e.message.getHeader("Content-Type")||""))return e.reject({statusCode:415}),void this.emit("reinviteFailed",this);t=this.sessionDescriptionHandler.setDescription(e.message.body,this.sessionDescriptionHandlerOptions,this.modifiers).then(this.sessionDescriptionHandler.getDescription.bind(this.sessionDescriptionHandler,this.sessionDescriptionHandlerOptions,this.modifiers))}else t=this.sessionDescriptionHandler.getDescription(this.sessionDescriptionHandlerOptions,this.modifiers);t.catch(function(t){var n;throw t.type===d.TypeStrings.SessionDescriptionHandlerError?n=500:t.type===d.TypeStrings.RenegotiationError?(r.emit("renegotiationError",t),r.logger.warn(t.toString()),n=488):(r.logger.error(t),n=488),e.reject({statusCode:n}),r.emit("reinviteFailed",r),t}).then(function(t){var n=["Contact: "+r.contact];e.accept({statusCode:200,extraHeaders:n,body:c.fromBodyObj(t)}),r.status=d.SessionStatus.STATUS_WAITING_FOR_ACK,r.emit("reinviteAccepted",r)})}else this.logger.warn("No SessionDescriptionHandler to reinvite")},t.prototype.sendReinvite=function(e){var t=this;if(void 0===e&&(e={}),this.pendingReinvite)this.logger.warn("Reinvite in progress. Please wait until complete, then try again.");else if(this.sessionDescriptionHandler){this.pendingReinvite=!0,e.modifiers=e.modifiers||[];var r=(e.extraHeaders||[]).slice();r.push("Contact: "+this.contact),r.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),this.sessionDescriptionHandler.getDescription(e.sessionDescriptionHandlerOptions,e.modifiers).then(function(e){if(!t.session)throw new Error("Session undefined.");var n={onAccept:function(e){if(t.status!==d.SessionStatus.STATUS_TERMINATED)if(t.pendingReinvite){if(t.status=d.SessionStatus.STATUS_CONFIRMED,t.emit("ack",e.ack()),t.pendingReinvite=!1,clearTimeout(t.timers.invite2xxTimer),!t.sessionDescriptionHandler||!t.sessionDescriptionHandler.hasDescription(e.message.getHeader("Content-Type")||""))return t.logger.error("2XX response received to re-invite but did not have a description"),t.emit("reinviteFailed",t),void t.emit("renegotiationError",new h.Exceptions.RenegotiationError("2XX response received to re-invite but did not have a description"));t.sessionDescriptionHandler.setDescription(e.message.body,t.sessionDescriptionHandlerOptions,t.modifiers).catch(function(e){throw t.logger.error("Could not set the description in 2XX response"),t.logger.error(e),t.emit("reinviteFailed",t),t.emit("renegotiationError",e),t.sendRequest(a.C.BYE,{extraHeaders:["Reason: "+m.Utils.getReasonHeaderValue(488,"Not Acceptable Here")]}),t.terminated(void 0,a.C.causes.INCOMPATIBLE_SDP),e}).then(function(){t.emit("reinviteAccepted",t)})}else t.logger.error("Received reinvite response, but have no pending reinvite");else t.logger.error("Received reinvite response, but in STATUS_TERMINATED")},onProgress:function(e){},onRedirect:function(e){t.pendingReinvite=!1,t.logger.log("Received a non 1XX or 2XX response to a re-invite"),t.emit("reinviteFailed",t),t.emit("renegotiationError",new h.Exceptions.RenegotiationError("Invalid response to a re-invite"))},onReject:function(e){t.pendingReinvite=!1,t.logger.log("Received a non 1XX or 2XX response to a re-invite"),t.emit("reinviteFailed",t),t.emit("renegotiationError",new h.Exceptions.RenegotiationError("Invalid response to a re-invite"))},onTrying:function(e){}},i={extraHeaders:r,body:c.fromBodyObj(e)};t.session.invite(n,i)}).catch(function(e){if(e.type===d.TypeStrings.RenegotiationError)throw t.pendingReinvite=!1,t.emit("renegotiationError",e),t.logger.warn("Renegotiation Error"),t.logger.warn(e.toString()),e;throw t.logger.error("sessionDescriptionHandler error"),t.logger.error(e),e})}else this.logger.warn("No SessionDescriptionHandler, can't reinvite..")},t.prototype.failed=function(e,t){return this.status===d.SessionStatus.STATUS_TERMINATED?this:(this.emit("failed",e,t),this)},t.prototype.rejected=function(e,t){return this.emit("rejected",e,t),this},t.prototype.canceled=function(){return this.sessionDescriptionHandler&&this.sessionDescriptionHandler.close(),this.emit("cancel"),this},t.prototype.accepted=function(e,t){return e instanceof String||(t=m.Utils.getReasonPhrase(e&&e.statusCode||0,t)),this.startTime=new Date,this.replacee&&(this.replacee.emit("replaced",this),this.replacee.terminate()),this.emit("accepted",e,t),this},t.prototype.terminated=function(e,t){return this.status===d.SessionStatus.STATUS_TERMINATED?this:(this.endTime=new Date,this.close(),this.emit("terminated",e,t),this)},t.prototype.connecting=function(e){return this.emit("connecting",{request:e}),this},t.C=d.SessionStatus,t}(o.EventEmitter);t.Session=y;var S=function(e){function t(t,r){var n=this;if(!t.configuration.sessionDescriptionHandlerFactory)throw t.logger.warn("Can't build ISC without SDH Factory"),new Error("ISC Constructor Failed");(n=e.call(this,t.configuration.sessionDescriptionHandlerFactory)||this)._canceled=!1,n.rseq=Math.floor(1e4*Math.random()),n.incomingRequest=r;var i=r.message;f.ServerContext.initializer(n,t,r),n.type=d.TypeStrings.InviteServerContext;var o=i.parseHeader("Content-Disposition");o&&"render"===o.type&&(n.renderbody=i.body,n.rendertype=i.getHeader("Content-Type")),n.status=d.SessionStatus.STATUS_INVITE_RECEIVED,n.fromTag=i.fromTag,n.id=i.callId+n.fromTag,n.request=i,n.contact=n.ua.contact.toString(),n.logger=t.getLogger("sip.inviteservercontext",n.id),n.ua.sessions[n.id]=n;var s=function(e,t){i.hasHeader(e)&&i.getHeader(e).toLowerCase().indexOf("100rel")>=0&&(n.rel100=t)};if(s("require",a.C.supported.REQUIRED),s("supported",a.C.supported.SUPPORTED),n.request.toTag=r.toTag,n.status=d.SessionStatus.STATUS_WAITING_FOR_ANSWER,n.timers.userNoAnswerTimer=setTimeout(function(){r.reject({statusCode:408}),n.failed(i,a.C.causes.NO_ANSWER),n.terminated(i,a.C.causes.NO_ANSWER)},n.ua.configuration.noAnswerTimeout||60),i.hasHeader("expires")){var c=1e3*Number(i.getHeader("expires")||0);n.timers.expiresTimer=setTimeout(function(){n.status===d.SessionStatus.STATUS_WAITING_FOR_ANSWER&&(r.reject({statusCode:487}),n.failed(i,a.C.causes.EXPIRES),n.terminated(i,a.C.causes.EXPIRES))},c)}return n.errorListener=n.onTransportError.bind(n),t.transport&&t.transport.on("transportError",n.errorListener),n}return i(t,e),Object.defineProperty(t.prototype,"autoSendAnInitialProvisionalResponse",{get:function(){return this.rel100!==a.C.supported.REQUIRED},enumerable:!0,configurable:!0}),t.prototype.reply=function(e){return void 0===e&&(e={}),this},t.prototype.reject=function(e){var t=this;if(void 0===e&&(e={}),this.status===d.SessionStatus.STATUS_TERMINATED)throw new h.Exceptions.InvalidStateError(this.status);this.logger.log("rejecting RTCSession");var r=e.statusCode||480,n=m.Utils.getReasonPhrase(r,e.reasonPhrase),i=e.extraHeaders||[];if(r<300||r>699)throw new TypeError("Invalid statusCode: "+r);var o=e.body?c.fromBodyLegacy(e.body):void 0,s=r<400?this.incomingRequest.redirect([],{statusCode:r,reasonPhrase:n,extraHeaders:i,body:o}):this.incomingRequest.reject({statusCode:r,reasonPhrase:n,extraHeaders:i,body:o});return["rejected","failed"].forEach(function(e){t.emit(e,s.message,n)}),this.terminated()},t.prototype.accept=function(e){var t=this;return void 0===e&&(e={}),this._accept(e).then(function(e){var r=e.message,n=e.session;n.delegate={onAck:function(e){return t.onAck(e)},onAckTimeout:function(){return t.onAckTimeout()},onBye:function(e){return t.receiveRequest(e)},onInfo:function(e){return t.receiveRequest(e)},onInvite:function(e){return t.receiveRequest(e)},onNotify:function(e){return t.receiveRequest(e)},onPrack:function(e){return t.receiveRequest(e)},onRefer:function(e){return t.receiveRequest(e)}},t.session=n,t.status=d.SessionStatus.STATUS_WAITING_FOR_ACK,t.accepted(r,m.Utils.getReasonPhrase(200))}).catch(function(e){if(t.onContextError(e),!t._canceled)throw e}),this},t.prototype.progress=function(e){var t=this;void 0===e&&(e={});var r=e.statusCode||180;if(r<100||r>199)throw new TypeError("Invalid statusCode: "+r);if(this.status===d.SessionStatus.STATUS_TERMINATED)return this.logger.warn("Unexpected call for progress while terminated, ignoring"),this;if(this.status===d.SessionStatus.STATUS_ANSWERED)return this.logger.warn("Unexpected call for progress while answered, ignoring"),this;if(this.status===d.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK)return this.logger.warn("Unexpected call for progress while answered (waiting for prack), ignoring"),this;if(this.status===d.SessionStatus.STATUS_WAITING_FOR_PRACK)return this.logger.warn("Unexpected call for progress while waiting for prack, ignoring"),this;if(100===e.statusCode){try{this.incomingRequest.trying()}catch(e){if(this.onContextError(e),!this._canceled)throw e}return this}return this.rel100===a.C.supported.REQUIRED||this.rel100===a.C.supported.SUPPORTED&&e.rel100||this.rel100===a.C.supported.SUPPORTED&&this.ua.configuration.rel100===a.C.supported.REQUIRED?(this._reliableProgressWaitForPrack(e).catch(function(e){if(t.onContextError(e),!t._canceled)throw e}),this):(this._progress(e).catch(function(e){if(t.onContextError(e),!t._canceled)throw e}),this)},t.prototype.terminate=function(e){var t=this;if(void 0===e&&(e={}),!this.session)return this.reject(e),this;switch(this.session.sessionState){case u.SessionState.Initial:case u.SessionState.Early:return this.reject(e),this;case u.SessionState.AckWait:return this.session.delegate={onAck:function(){t.sendRequest(a.C.BYE,e)},onAckTimeout:function(){t.sendRequest(a.C.BYE,e)}},this.emit("bye",this.request),this.terminated(),this;case u.SessionState.Confirmed:return this.bye(e),this;case u.SessionState.Terminated:default:return this}},t.prototype.onCancel=function(e){this.status!==d.SessionStatus.STATUS_WAITING_FOR_ANSWER&&this.status!==d.SessionStatus.STATUS_WAITING_FOR_PRACK&&this.status!==d.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK&&this.status!==d.SessionStatus.STATUS_EARLY_MEDIA&&this.status!==d.SessionStatus.STATUS_ANSWERED||(this.status=d.SessionStatus.STATUS_CANCELED,this.incomingRequest.reject({statusCode:487}),this.canceled(),this.rejected(e,a.C.causes.CANCELED),this.failed(e,a.C.causes.CANCELED),this.terminated(e,a.C.causes.CANCELED))},t.prototype.receiveRequest=function(t){var r=this;switch(t.message.method){case a.C.PRACK:this.status===d.SessionStatus.STATUS_WAITING_FOR_PRACK||this.status===d.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK?this.hasAnswer?(clearTimeout(this.timers.rel1xxTimer),clearTimeout(this.timers.prackTimer),t.accept(),this.status===d.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK&&(this.status=d.SessionStatus.STATUS_EARLY_MEDIA,this.accept()),this.status=d.SessionStatus.STATUS_EARLY_MEDIA):(this.sessionDescriptionHandler=this.setupSessionDescriptionHandler(),this.emit("SessionDescriptionHandler-created",this.sessionDescriptionHandler),this.sessionDescriptionHandler.hasDescription(t.message.getHeader("Content-Type")||"")?(this.hasAnswer=!0,this.sessionDescriptionHandler.setDescription(t.message.body,this.sessionDescriptionHandlerOptions,this.modifiers).then(function(){clearTimeout(r.timers.rel1xxTimer),clearTimeout(r.timers.prackTimer),t.accept(),r.status===d.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK&&(r.status=d.SessionStatus.STATUS_EARLY_MEDIA,r.accept()),r.status=d.SessionStatus.STATUS_EARLY_MEDIA},function(e){r.logger.warn(e),r.terminate({statusCode:"488",reasonPhrase:"Bad Media Description"}),r.failed(t.message,a.C.causes.BAD_MEDIA_DESCRIPTION),r.terminated(t.message,a.C.causes.BAD_MEDIA_DESCRIPTION)})):(this.terminate({statusCode:"488",reasonPhrase:"Bad Media Description"}),this.failed(t.message,a.C.causes.BAD_MEDIA_DESCRIPTION),this.terminated(t.message,a.C.causes.BAD_MEDIA_DESCRIPTION))):this.status===d.SessionStatus.STATUS_EARLY_MEDIA&&t.accept();break;default:e.prototype.receiveRequest.call(this,t)}},t.prototype.setupSessionDescriptionHandler=function(){return this.sessionDescriptionHandler?this.sessionDescriptionHandler:this.sessionDescriptionHandlerFactory(this,this.ua.configuration.sessionDescriptionHandlerFactoryOptions)},t.prototype.generateResponseOfferAnswer=function(e){if(!this.session){var t=c.getBody(this.incomingRequest.message);return t&&"session"===t.contentDisposition?this.setOfferAndGetAnswer(t,e):this.getOffer(e)}switch(this.session.signalingState){case u.SignalingState.Initial:return this.getOffer(e);case u.SignalingState.Stable:case u.SignalingState.HaveLocalOffer:return Promise.resolve(void 0);case u.SignalingState.HaveRemoteOffer:if(!this.session.offer)throw new Error("Session offer undefined");return this.setOfferAndGetAnswer(this.session.offer,e);case u.SignalingState.Closed:default:throw new Error("Invalid signaling state "+this.session.signalingState+".")}},t.prototype.handlePrackOfferAnswer=function(e,t){if(!this.session)throw new Error("Session undefined.");var r=c.getBody(e.message);if(!r||"session"!==r.contentDisposition)return Promise.resolve(void 0);switch(this.session.signalingState){case u.SignalingState.Initial:throw new Error("Invalid signaling state "+this.session.signalingState+".");case u.SignalingState.Stable:return this.setAnswer(r,t).then(function(){});case u.SignalingState.HaveLocalOffer:throw new Error("Invalid signaling state "+this.session.signalingState+".");case u.SignalingState.HaveRemoteOffer:return this.setOfferAndGetAnswer(r,t);case u.SignalingState.Closed:default:throw new Error("Invalid signaling state "+this.session.signalingState+".")}},t.prototype.canceled=function(){return this._canceled=!0,e.prototype.canceled.call(this)},t.prototype.terminated=function(t,r){return this.prackNeverArrived(),e.prototype.terminated.call(this,t,r)},t.prototype._accept=function(e){var t=this;return void 0===e&&(e={}),this.onInfo=e.onInfo,this.status===d.SessionStatus.STATUS_WAITING_FOR_PRACK?(this.status=d.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK,this.waitForArrivalOfPrack().then(function(){t.status=d.SessionStatus.STATUS_ANSWERED,clearTimeout(t.timers.userNoAnswerTimer)}).then(function(){return t.generateResponseOfferAnswer(e)}).then(function(e){return t.incomingRequest.accept({statusCode:200,body:e})})):this.status!==d.SessionStatus.STATUS_WAITING_FOR_ANSWER?Promise.reject(new h.Exceptions.InvalidStateError(this.status)):(this.status=d.SessionStatus.STATUS_ANSWERED,this.status=d.SessionStatus.STATUS_ANSWERED,clearTimeout(this.timers.userNoAnswerTimer),this.generateResponseOfferAnswer(e).then(function(e){return t.incomingRequest.accept({statusCode:200,body:e})}))},t.prototype._progress=function(e){void 0===e&&(e={});var t=e.statusCode||180,r=e.reasonPhrase,n=(e.extraHeaders||[]).slice(),i=e.body?c.fromBodyLegacy(e.body):void 0;try{var o=this.incomingRequest.progress({statusCode:t,reasonPhrase:r,extraHeaders:n,body:i});return this.emit("progress",o.message,r),this.session=o.session,Promise.resolve(o)}catch(e){return Promise.reject(e)}},t.prototype._reliableProgress=function(e){var t=this;void 0===e&&(e={});var r=e.statusCode||183,n=e.reasonPhrase,i=(e.extraHeaders||[]).slice();return i.push("Require: 100rel"),i.push("RSeq: "+Math.floor(1e4*Math.random())),this.generateResponseOfferAnswer(e).then(function(e){return t.incomingRequest.progress({statusCode:r,reasonPhrase:n,extraHeaders:i,body:e})}).then(function(e){return t.emit("progress",e.message,n),t.session=e.session,e})},t.prototype._reliableProgressWaitForPrack=function(e){var t=this;void 0===e&&(e={});var r,n=e.statusCode||183,i=e.reasonPhrase,o=(e.extraHeaders||[]).slice();return o.push("Require: 100rel"),o.push("RSeq: "+this.rseq++),this.status=d.SessionStatus.STATUS_WAITING_FOR_PRACK,new Promise(function(s,c){var u=!0;return t.generateResponseOfferAnswer(e).then(function(e){return r=e,t.incomingRequest.progress({statusCode:n,reasonPhrase:i,extraHeaders:o,body:r})}).then(function(p){var l,f;t.emit("progress",p.message,i),t.session=p.session,p.session.delegate={onPrack:function(r){l=r,clearTimeout(g),clearTimeout(S),u&&(u=!1,t.handlePrackOfferAnswer(l,e).then(function(e){try{f=l.accept({statusCode:200,body:e}),t.status===d.SessionStatus.STATUS_WAITING_FOR_PRACK&&(t.status=d.SessionStatus.STATUS_WAITING_FOR_ANSWER),t.prackArrived(),s({prackRequest:l,prackResponse:f,progressResponse:p})}catch(e){c(e)}}))}};var g=setTimeout(function(){if(u){u=!1,t.logger.warn("No PRACK received, rejecting INVITE."),clearTimeout(S);try{t.incomingRequest.reject({statusCode:504}),t.terminated(void 0,a.C.causes.NO_PRACK),c(new h.Exceptions.TerminatedSessionError)}catch(e){c(e)}}},64*v.Timers.T1),m=function(){try{t.incomingRequest.progress({statusCode:n,reasonPhrase:i,extraHeaders:o,body:r})}catch(e){return u=!1,void c(e)}S=setTimeout(m,y*=2)},y=v.Timers.T1,S=setTimeout(m,y)})})},t.prototype.onAckTimeout=function(){if(this.status===d.SessionStatus.STATUS_WAITING_FOR_ACK){if(this.logger.log("no ACK received for an extended period of time, terminating the call"),!this.session)throw new Error("Session undefined.");this.session.bye(),this.terminated(void 0,a.C.causes.NO_ACK)}},t.prototype.onContextError=function(e){var t=480;e instanceof h.Exception?e instanceof h.Exceptions.SessionDescriptionHandlerError?(this.logger.error(e.message),e.error&&this.logger.error(e.error)):e instanceof h.Exceptions.TerminatedSessionError?this.logger.warn("Incoming session terminated while waiting for PRACK."):e instanceof h.Exceptions.UnsupportedSessionDescriptionContentTypeError?t=415:e instanceof h.Exception&&this.logger.error(e.message):e instanceof Error?this.logger.error(e.message):(this.logger.error("An error occurred in the session description handler."),this.logger.error(e));try{this.incomingRequest.reject({statusCode:t}),this.failed(this.incomingRequest.message,e.message),this.terminated(this.incomingRequest.message,e.message)}catch(e){return}},t.prototype.prackArrived=function(){this.waitingForPrackResolve&&this.waitingForPrackResolve(),this.waitingForPrackPromise=void 0,this.waitingForPrackResolve=void 0,this.waitingForPrackReject=void 0},t.prototype.prackNeverArrived=function(){this.waitingForPrackReject&&this.waitingForPrackReject(new h.Exceptions.TerminatedSessionError),this.waitingForPrackPromise=void 0,this.waitingForPrackResolve=void 0,this.waitingForPrackReject=void 0},t.prototype.waitForArrivalOfPrack=function(){var e=this;if(this.waitingForPrackPromise)throw new Error("Already waiting for PRACK");return this.waitingForPrackPromise=new Promise(function(t,r){e.waitingForPrackResolve=t,e.waitingForPrackReject=r}),this.waitingForPrackPromise},t.prototype.getOffer=function(e){return this.hasOffer=!0,this.getSessionDescriptionHandler().getDescription(e.sessionDescriptionHandlerOptions,e.modifiers).then(function(e){return c.fromBodyObj(e)})},t.prototype.setAnswer=function(e,t){this.hasAnswer=!0;var r=this.getSessionDescriptionHandler();return r.hasDescription(e.contentType)?r.setDescription(e.content,t.sessionDescriptionHandlerOptions,t.modifiers):Promise.reject(new h.Exceptions.UnsupportedSessionDescriptionContentTypeError)},t.prototype.setOfferAndGetAnswer=function(e,t){this.hasOffer=!0,this.hasAnswer=!0;var r=this.getSessionDescriptionHandler();return r.hasDescription(e.contentType)?r.setDescription(e.content,t.sessionDescriptionHandlerOptions,t.modifiers).then(function(){return r.getDescription(t.sessionDescriptionHandlerOptions,t.modifiers)}).then(function(e){return c.fromBodyObj(e)}):Promise.reject(new h.Exceptions.UnsupportedSessionDescriptionContentTypeError)},t.prototype.getSessionDescriptionHandler=function(){var e=this.sessionDescriptionHandler=this.setupSessionDescriptionHandler();return this.emit("SessionDescriptionHandler-created",this.sessionDescriptionHandler),e},t}(y);t.InviteServerContext=S;var T=function(e){function t(t,r,n,i){void 0===n&&(n={}),void 0===i&&(i=[]);var o=this;if(!t.configuration.sessionDescriptionHandlerFactory)throw t.logger.warn("Can't build ISC without SDH Factory"),new Error("ICC Constructor Failed");n.params=n.params||{};var c=n.anonymous||!1,u=m.Utils.newTag();n.params.fromTag=u;var p=t.contact.toString({anonymous:c,outbound:c?!t.contact.tempGruu:!t.contact.pubGruu}),l=(n.extraHeaders||[]).slice();if(c&&t.configuration.uri&&(n.params.from_displayName="Anonymous",n.params.from_uri="sip:anonymous@anonymous.invalid",l.push("P-Preferred-Identity: "+t.configuration.uri.toString()),l.push("Privacy: id")),l.push("Contact: "+p),l.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),t.configuration.rel100===a.C.supported.REQUIRED&&l.push("Require: 100rel"),t.configuration.replaces===a.C.supported.REQUIRED&&l.push("Require: replaces"),n.extraHeaders=l,o=e.call(this,t.configuration.sessionDescriptionHandlerFactory)||this,s.ClientContext.initializer(o,t,a.C.INVITE,r,n),o.earlyMediaSessionDescriptionHandlers=new Map,o.type=d.TypeStrings.InviteClientContext,o.passedOptions=n,o.sessionDescriptionHandlerOptions=n.sessionDescriptionHandlerOptions||{},o.modifiers=i,o.inviteWithoutSdp=n.inviteWithoutSdp||!1,o.anonymous=n.anonymous||!1,o.renderbody=n.renderbody||void 0,o.rendertype=n.rendertype||"text/plain",o.fromTag=u,o.contact=p,o.status!==d.SessionStatus.STATUS_NULL)throw new h.Exceptions.InvalidStateError(o.status);return o.isCanceled=!1,o.received100=!1,o.method=a.C.INVITE,o.logger=t.getLogger("sip.inviteclientcontext"),t.applicants[o.toString()]=o,o.id=o.request.callId+o.fromTag,o.onInfo=n.onInfo,o.errorListener=o.onTransportError.bind(o),t.transport&&t.transport.on("transportError",o.errorListener),o}return i(t,e),t.prototype.receiveResponse=function(e){throw new Error("Unimplemented.")},t.prototype.send=function(){return this.sendInvite(),this},t.prototype.invite=function(){var e=this;return this.ua.sessions[this.id]=this,Promise.resolve().then(function(){e.isCanceled||e.status===d.SessionStatus.STATUS_TERMINATED||(e.inviteWithoutSdp?(e.request.body=e.renderbody,e.status=d.SessionStatus.STATUS_INVITE_SENT,e.send()):(e.sessionDescriptionHandler=e.sessionDescriptionHandlerFactory(e,e.ua.configuration.sessionDescriptionHandlerFactoryOptions||{}),e.emit("SessionDescriptionHandler-created",e.sessionDescriptionHandler),e.sessionDescriptionHandler.getDescription(e.sessionDescriptionHandlerOptions,e.modifiers).then(function(t){e.isCanceled||e.status===d.SessionStatus.STATUS_TERMINATED||(e.hasOffer=!0,e.request.body=t,e.status=d.SessionStatus.STATUS_INVITE_SENT,e.send())},function(t){t.type===d.TypeStrings.SessionDescriptionHandlerError&&(e.logger.log(t.message),t.error&&e.logger.log(t.error)),e.status!==d.SessionStatus.STATUS_TERMINATED&&(e.failed(void 0,a.C.causes.WEBRTC_ERROR),e.terminated(void 0,a.C.causes.WEBRTC_ERROR))})))}),this},t.prototype.cancel=function(e){if(void 0===e&&(e={}),this.status===d.SessionStatus.STATUS_TERMINATED||this.status===d.SessionStatus.STATUS_CONFIRMED)throw new h.Exceptions.InvalidStateError(this.status);if(this.isCanceled)throw new h.Exceptions.InvalidStateError(d.SessionStatus.STATUS_CANCELED);this.isCanceled=!0,this.logger.log("Canceling session");var t=m.Utils.getCancelReason(e.statusCode,e.reasonPhrase);return e.extraHeaders=(e.extraHeaders||[]).slice(),this.outgoingInviteRequest&&(this.logger.warn("Canceling session before it was created"),this.outgoingInviteRequest.cancel(t,e)),this.canceled()},t.prototype.terminate=function(e){return this.status===d.SessionStatus.STATUS_TERMINATED?this:(this.status===d.SessionStatus.STATUS_WAITING_FOR_ACK||this.status===d.SessionStatus.STATUS_CONFIRMED?this.bye(e):this.cancel(e),this)},t.prototype.sendInvite=function(){var e=this;this.outgoingInviteRequest=this.ua.userAgentCore.invite(this.request,{onAccept:function(t){return e.onAccept(t)},onProgress:function(t){return e.onProgress(t)},onRedirect:function(t){return e.onRedirect(t)},onReject:function(t){return e.onReject(t)},onTrying:function(t){return e.onTrying(t)}})},t.prototype.ackAndBye=function(e,t,r,n){if(!this.ua.userAgentCore)throw new Error("Method requires user agent core.");var i=[];r&&i.push("Reason: "+m.Utils.getReasonHeaderValue(r,n));var o=e.ack();this.emit("ack",o.message);var s=t.bye(void 0,{extraHeaders:i});this.emit("bye",s.message)},t.prototype.disposeEarlyMedia=function(){if(!this.earlyMediaSessionDescriptionHandlers)throw new Error("Early media session description handlers undefined.");this.earlyMediaSessionDescriptionHandlers.forEach(function(e){e.close()})},t.prototype.onAccept=function(e){var t=this;if(!this.earlyMediaSessionDescriptionHandlers)throw new Error("Early media session description handlers undefined.");var r=e.message,n=e.session;if(this.session)this.ackAndBye(e,n);else{if(this.isCanceled)return this.ackAndBye(e,n),void this.emit("bye",this.request);switch(r.hasHeader("P-Asserted-Identity")&&(this.assertedIdentity=p.Grammar.nameAddrHeaderParse(r.getHeader("P-Asserted-Identity"))),this.session=n,this.session.delegate={onAck:function(e){return t.onAck(e)},onBye:function(e){return t.receiveRequest(e)},onInfo:function(e){return t.receiveRequest(e)},onInvite:function(e){return t.receiveRequest(e)},onNotify:function(e){return t.receiveRequest(e)},onPrack:function(e){return t.receiveRequest(e)},onRefer:function(e){return t.receiveRequest(e)}},n.signalingState){case u.SignalingState.Initial:case u.SignalingState.HaveLocalOffer:this.ackAndBye(e,n,400,"Missing session description"),this.failed(r,a.C.causes.BAD_MEDIA_DESCRIPTION);break;case u.SignalingState.HaveRemoteOffer:var i=this.sessionDescriptionHandlerFactory(this,this.ua.configuration.sessionDescriptionHandlerFactoryOptions||{});if(this.sessionDescriptionHandler=i,this.emit("SessionDescriptionHandler-created",this.sessionDescriptionHandler),!i.hasDescription(r.getHeader("Content-Type")||"")){this.ackAndBye(e,n,400,"Missing session description"),this.failed(r,a.C.causes.BAD_MEDIA_DESCRIPTION);break}this.hasOffer=!0,i.setDescription(r.body,this.sessionDescriptionHandlerOptions,this.modifiers).then(function(){return i.getDescription(t.sessionDescriptionHandlerOptions,t.modifiers)}).then(function(n){if(!t.isCanceled&&t.status!==d.SessionStatus.STATUS_TERMINATED){t.status=d.SessionStatus.STATUS_CONFIRMED,t.hasAnswer=!0;var i={contentDisposition:"session",contentType:n.contentType,content:n.body},o=e.ack({body:i});t.emit("ack",o.message),t.accepted(r)}}).catch(function(i){if(i.type!==d.TypeStrings.SessionDescriptionHandlerError)throw i;t.logger.warn("invalid description"),t.logger.warn(i.toString()),t.ackAndBye(e,n,488,"Invalid session description"),t.failed(r,a.C.causes.BAD_MEDIA_DESCRIPTION)});break;case u.SignalingState.Stable:var o;if(this.renderbody&&this.rendertype&&(o={body:{contentDisposition:"render",contentType:this.rendertype,content:this.renderbody}}),this.hasOffer&&!this.hasAnswer){if(!this.sessionDescriptionHandler)throw new Error("Session description handler undefined.");var s=n.answer;if(!s)throw new Error("Answer is undefined.");this.sessionDescriptionHandler.setDescription(s.content,this.sessionDescriptionHandlerOptions,this.modifiers).then(function(){t.hasAnswer=!0,t.status=d.SessionStatus.STATUS_CONFIRMED;var n=e.ack(o);t.emit("ack",n.message),t.accepted(r)}).catch(function(i){t.logger.error(i),t.ackAndBye(e,n,488,"Not Acceptable Here"),t.failed(r,a.C.causes.BAD_MEDIA_DESCRIPTION)})}else{if(this.sessionDescriptionHandler=this.earlyMediaSessionDescriptionHandlers.get(n.id),!this.sessionDescriptionHandler)throw new Error("Session description handler undefined.");this.earlyMediaSessionDescriptionHandlers.delete(n.id),this.hasOffer=!0,this.hasAnswer=!0,this.status=d.SessionStatus.STATUS_CONFIRMED;var c=e.ack();this.emit("ack",c.message),this.accepted(r)}break;case u.SignalingState.Closed:break;default:throw new Error("Unknown session signaling state.")}this.disposeEarlyMedia()}},t.prototype.onProgress=function(e){var t=this;if(!this.isCanceled){if(!this.outgoingInviteRequest)throw new Error("Outgoing INVITE request undefined.");if(!this.earlyMediaSessionDescriptionHandlers)throw new Error("Early media session description handlers undefined.");var r=e.message,n=e.session;if(this.status=d.SessionStatus.STATUS_1XX_RECEIVED,r.hasHeader("P-Asserted-Identity")&&(this.assertedIdentity=p.Grammar.nameAddrHeaderParse(r.getHeader("P-Asserted-Identity"))),!n)throw new Error("Session undefined.");var i=r.getHeader("require"),o=r.getHeader("rseq"),s=!!(i&&i.includes("100rel")&&o?Number(o):void 0),c=[];if(s&&c.push("RAck: "+r.getHeader("rseq")+" "+r.getHeader("cseq")),n.signalingState===u.SignalingState.Initial)return s&&(this.logger.warn("First reliable provisional response received MUST contain an offer when INVITE does not contain an offer."),e.prack({extraHeaders:c})),void this.emit("progress",r);if(n.signalingState===u.SignalingState.HaveLocalOffer)return s&&e.prack({extraHeaders:c}),void this.emit("progress",r);if(n.signalingState===u.SignalingState.HaveRemoteOffer){if(!s)return void this.logger.warn("Non-reliable provisional response MUST NOT contain an initial offer, discarding response.");var h=this.sessionDescriptionHandlerFactory(this,this.ua.configuration.sessionDescriptionHandlerFactoryOptions||{});return this.emit("SessionDescriptionHandler-created",h),this.earlyMediaSessionDescriptionHandlers.set(n.id,h),void h.setDescription(r.body,this.sessionDescriptionHandlerOptions,this.modifiers).then(function(){return h.getDescription(t.sessionDescriptionHandlerOptions,t.modifiers)}).then(function(n){var i={contentDisposition:"session",contentType:n.contentType,content:n.body};e.prack({extraHeaders:c,body:i}),t.status=d.SessionStatus.STATUS_EARLY_MEDIA,t.emit("progress",r)}).catch(function(e){t.status!==d.SessionStatus.STATUS_TERMINATED&&(t.failed(void 0,a.C.causes.WEBRTC_ERROR),t.terminated(void 0,a.C.causes.WEBRTC_ERROR))})}return n.signalingState===u.SignalingState.Stable?(s&&e.prack({extraHeaders:c}),void this.emit("progress",r)):void 0}},t.prototype.onRedirect=function(e){this.disposeEarlyMedia();var t=e.message,r=t.statusCode,n=m.Utils.sipErrorCause(r||0);this.rejected(t,n),this.failed(t,n),this.terminated(t,n)},t.prototype.onReject=function(e){this.disposeEarlyMedia();var t=e.message,r=t.statusCode,n=m.Utils.sipErrorCause(r||0);this.rejected(t,n),this.failed(t,n),this.terminated(t,n)},t.prototype.onTrying=function(e){this.received100=!0,this.emit("progress",e.message)},t}(y);t.InviteClientContext=T},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(10),s=r(2),a=r(14),c=r(32),u=r(23),d=r(3),h=r(5),p=function(e){function t(t,r,n,i){void 0===i&&(i={});var o=e.call(this)||this;o.data={},o.method=s.C.SUBSCRIBE,o.body=void 0,o.type=d.TypeStrings.Subscription,o.ua=t,o.logger=t.getLogger("sip.subscription"),i.body&&(o.body={body:i.body,contentType:i.contentType?i.contentType:"application/sdp"});var a=t.normalizeTarget(r);if(!a)throw new TypeError("Invalid target: "+r);if(o.uri=a,o.event=n,void 0===i.expires?o.expires=3600:"number"!=typeof i.expires?(t.logger.warn('Option "expires" must be a number. Using default of 3600.'),o.expires=3600):o.expires=i.expires,o.extraHeaders=(i.extraHeaders||[]).slice(),o.context=o.initContext(),o.disposed=!1,o.request=o.context.message,!o.request.from)throw new Error("From undefined.");if(!o.request.to)throw new Error("From undefined.");return o.localIdentity=o.request.from,o.remoteIdentity=o.request.to,o}return i(t,e),t.prototype.dispose=function(){this.disposed||(this.retryAfterTimer&&(clearTimeout(this.retryAfterTimer),this.retryAfterTimer=void 0),this.context.dispose(),this.disposed=!0)},t.prototype.on=function(t,r){return e.prototype.on.call(this,t,r)},t.prototype.emit=function(t){for(var r=[],n=1;n0?(e.accept(),n.emit("notify",{request:e.message})):e.reject({statusCode:481})},onRefer:function(e){n.logger.log("Received an out of dialog refer"),n.configuration.allowOutOfDialogRefers||e.reject({statusCode:405}),n.logger.log("Allow out of dialog refers is enabled on the UA");var t=new v.ReferServerContext(n,e);n.listeners("outOfDialogReferRequested").length?n.emit("outOfDialogReferRequested",t):(n.logger.log("No outOfDialogReferRequest listeners, automatically accepting and following the out of dialog refer"),t.accept({followRefer:!0}))},onSubscribe:function(e){n.emit("subscribe",e)}};return n.userAgentCore=new c.UserAgentCore(s,u),n.registerContext=new m.RegisterContext(n,e.registerOptions),n.registerContext.on("failed",n.emit.bind(n,"registrationFailed")),n.registerContext.on("registered",n.emit.bind(n,"registered")),n.registerContext.on("unregistered",n.emit.bind(n,"unregistered")),n.configuration.autostart&&n.start(),n}return i(r,t),r.prototype.register=function(e){return void 0===e&&(e={}),e.register&&(this.configuration.register=!0),this.registerContext.register(e),this},r.prototype.unregister=function(e){var t=this;return this.configuration.register=!1,this.transport&&this.transport.afterConnected(function(){t.registerContext.unregister(e)}),this},r.prototype.isRegistered=function(){return this.registerContext.registered},r.prototype.invite=function(e,t,r){var n=this,i=new S.InviteClientContext(this,e,t,r);return this.transport&&this.transport.afterConnected(function(){i.invite(),n.emit("inviteSent",i)}),i},r.prototype.subscribe=function(e,t,r){var n=new C.Subscription(this,e,t,r);return this.transport&&this.transport.afterConnected(function(){return n.subscribe()}),n},r.prototype.publish=function(e,t,r,n){var i=new g.PublishContext(this,e,t,n);return this.transport&&this.transport.afterConnected(function(){i.publish(r)}),i},r.prototype.message=function(e,t,r){if(void 0===r&&(r={}),void 0===t)throw new TypeError("Not enough arguments");return r.contentType=r.contentType||"text/plain",r.body=t,this.request(a.C.MESSAGE,e,r)},r.prototype.request=function(e,t,r){var n=new s.ClientContext(this,e,t,r);return this.transport&&this.transport.afterConnected(function(){return n.send()}),n},r.prototype.stop=function(){if(this.logger.log("user requested closure..."),this.status===d.UAStatus.STATUS_USER_CLOSED)return this.logger.warn("UA already closed"),this;for(var t in this.logger.log("closing registerContext"),this.registerContext.close(),this.sessions)this.sessions[t]&&(this.logger.log("closing session "+t),this.sessions[t].terminate());for(var r in this.publishers)this.publishers[r]&&(this.logger.log("unpublish "+r),this.publishers[r].close());for(var n in this.applicants)this.applicants[n]&&this.applicants[n].close();return this.status=d.UAStatus.STATUS_USER_CLOSED,"function"==typeof E.removeEventListener&&(e.chrome&&e.chrome.app&&e.chrome.app.runtime||E.removeEventListener("unload",this.environListener)),this},r.prototype.start=function(){var t=this;if(this.logger.log("user requested startup..."),this.status===d.UAStatus.STATUS_INIT){if(this.status=d.UAStatus.STATUS_STARTING,!this.configuration.transportConstructor)throw new h.Exceptions.TransportError("Transport constructor not set");this.transport=new this.configuration.transportConstructor(this.getLogger("sip.transport"),this.configuration.transportOptions),this.setTransportListeners(),this.emit("transportCreated",this.transport),this.transport.connect()}else this.status===d.UAStatus.STATUS_USER_CLOSED?(this.logger.log("resuming"),this.status=d.UAStatus.STATUS_READY,this.transport&&this.transport.connect()):this.status===d.UAStatus.STATUS_STARTING?this.logger.log("UA is in STARTING status, not opening new connection"):this.status===d.UAStatus.STATUS_READY?this.logger.log("UA is in READY status, not resuming"):this.logger.error("Connection is down. Auto-Recovery system is trying to connect");return this.configuration.autostop&&"function"==typeof E.addEventListener&&(e.chrome&&e.chrome.app&&e.chrome.app.runtime||(this.environListener=this.stop,E.addEventListener("unload",function(){return t.environListener()}))),this},r.prototype.normalizeTarget=function(e){return _.Utils.normalizeTarget(e,this.configuration.hostportParams)},r.prototype.getLogger=function(e,t){return this.log.getLogger(e,t)},r.prototype.getLoggerFactory=function(){return this.log},r.prototype.findSession=function(e){return this.sessions[e.callId+e.fromTag]||this.sessions[e.callId+e.toTag]||void 0},r.prototype.on=function(e,r){return t.prototype.on.call(this,e,r)},r.prototype.onTransportError=function(){this.status!==d.UAStatus.STATUS_USER_CLOSED&&(this.error&&this.error===r.C.NETWORK_ERROR||(this.status=d.UAStatus.STATUS_NOT_READY,this.error=r.C.NETWORK_ERROR))},r.prototype.setTransportListeners=function(){var e=this;this.transport&&(this.transport.on("connected",function(){return e.onTransportConnected()}),this.transport.on("message",function(t){return e.onTransportReceiveMsg(t)}),this.transport.on("transportError",function(){return e.onTransportError()}))},r.prototype.onTransportConnected=function(){var e=this;this.configuration.register&&Promise.resolve().then(function(){return e.registerContext.register()})},r.prototype.onTransportReceiveMsg=function(e){var t=this,r=f.Parser.parseMessage(e,this);if(r)if(this.status===d.UAStatus.STATUS_USER_CLOSED&&r instanceof T.IncomingRequest)this.logger.warn("UA received message when status = USER_CLOSED - aborting");else{var n=function(){for(var e=0,n=["from","to","call_id","cseq","via"];e1)return void this.logger.warn("More than one Via header field present in the response. Dropping.");if(r.via.host!==this.configuration.viaHost||void 0!==r.via.port)return void this.logger.warn("Via sent-by in the response does not match UA Via host value. Dropping.");var o;i=_.Utils.str_utf8_length(r.body);if((o=r.getHeader("content-length"))&&i"}};var p={};for(var i in r)r.hasOwnProperty(i)&&(p[i]=r[i]);for(var i in Object.assign(this.configuration,p),this.logger.log("configuration parameters after validation:"),r)if(r.hasOwnProperty(i))switch(i){case"uri":case"sessionDescriptionHandlerFactory":this.logger.log("\xb7 "+i+": "+r[i]);break;case"password":this.logger.log("\xb7 "+i+": NOT SHOWN");break;case"transportConstructor":this.logger.log("\xb7 "+i+": "+r[i].name);break;default:this.logger.log("\xb7 "+i+": "+JSON.stringify(r[i]))}},r.prototype.getConfigurationCheck=function(){return{mandatory:{},optional:{uri:function(e){/^sip:/i.test(e)||(e=a.C.SIP+":"+e);var t=p.Grammar.URIParse(e);return t&&t.user?t:void 0},transportConstructor:function(e){if(e instanceof Function)return e},transportOptions:function(e){if("object"==typeof e)return e},authorizationUser:function(e){return-1===p.Grammar.parse('"'+e+'"',"quoted_string")?void 0:e},displayName:function(e){return-1===p.Grammar.parse('"'+e+'"',"displayName")?void 0:e},dtmfType:function(e){switch(e){case a.C.dtmfType.RTP:return a.C.dtmfType.RTP;case a.C.dtmfType.INFO:default:return a.C.dtmfType.INFO}},hackViaTcp:function(e){if("boolean"==typeof e)return e},hackIpInContact:function(e){return"boolean"==typeof e?e:"string"==typeof e&&-1!==p.Grammar.parse(e,"host")?e:void 0},hackWssInTransport:function(e){if("boolean"==typeof e)return e},hackAllowUnregisteredOptionTags:function(e){if("boolean"==typeof e)return e},contactTransport:function(e){if("string"==typeof e)return e},extraSupported:function(e){if(e instanceof Array){for(var t=0,r=e;t0)return t}},password:function(e){return String(e)},rel100:function(e){return e===a.C.supported.REQUIRED?a.C.supported.REQUIRED:e===a.C.supported.SUPPORTED?a.C.supported.SUPPORTED:a.C.supported.UNSUPPORTED},replaces:function(e){return e===a.C.supported.REQUIRED?a.C.supported.REQUIRED:e===a.C.supported.SUPPORTED?a.C.supported.SUPPORTED:a.C.supported.UNSUPPORTED},register:function(e){if("boolean"==typeof e)return e},registerOptions:function(e){if("object"==typeof e)return e},userAgentString:function(e){if("string"==typeof e)return e},autostart:function(e){if("boolean"==typeof e)return e},autostop:function(e){if("boolean"==typeof e)return e},sessionDescriptionHandlerFactory:function(e){if(e instanceof Function)return e},sessionDescriptionHandlerFactoryOptions:function(e){if("object"==typeof e)return e},authenticationFactory:this.checkAuthenticationFactory,allowLegacyNotifications:function(e){if("boolean"==typeof e)return e},custom:function(e){if("object"==typeof e)return e},contactName:function(e){if("string"==typeof e)return e},experimentalFeatures:function(e){if("boolean"==typeof e)return e}}}},r.C={STATUS_INIT:0,STATUS_STARTING:1,STATUS_READY:2,STATUS_USER_CLOSED:3,STATUS_NOT_READY:4,CONFIGURATION_ERROR:1,NETWORK_ERROR:2,ALLOWED_METHODS:["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"],ACCEPTED_BODY_TYPES:["application/sdp","application/dtmf-relay"],MAX_FORWARDS:70,TAG_LENGTH:10},r}(o.EventEmitter);t.UA=R,function(e){!function(e){e.RTP="rtp",e.INFO="info"}(e.DtmfType||(e.DtmfType={}))}(R=t.UA||(t.UA={})),t.UA=R}).call(this,r(24))},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(2),s=r(1),a=function(e){function t(t,r,n){var i,a=t.createOutgoingRequestMessage(o.C.BYE,n);return i=e.call(this,s.NonInviteClientTransaction,t.userAgentCore,a,r)||this,t.dispose(),i}return i(t,e),t}(r(6).UserAgentClient);t.ByeUserAgentClient=a},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(1),s=function(e){function t(t,r,n){return e.call(this,o.NonInviteServerTransaction,t.userAgentCore,r,n)||this}return i(t,e),t}(r(9).UserAgentServer);t.ByeUserAgentServer=s},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(1),s=function(e){function t(t,r,n){return e.call(this,o.NonInviteServerTransaction,t.userAgentCore,r,n)||this}return i(t,e),t}(r(9).UserAgentServer);t.InfoUserAgentServer=s},function(e,t,r){"use strict";function n(e){for(var r in e)t.hasOwnProperty(r)||(t[r]=e[r])}Object.defineProperty(t,"__esModule",{value:!0}),n(r(33)),n(r(103)),n(r(60))},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(2),s=r(1),a=function(e){function t(t,r,n){var i=t.createOutgoingRequestMessage(o.C.NOTIFY,n);return e.call(this,s.NonInviteClientTransaction,t.userAgentCore,i,r)||this}return i(t,e),t}(r(6).UserAgentClient);t.NotifyUserAgentClient=a},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(2),s=r(1),a=function(e){function t(t,r,n){var i,a=t.createOutgoingRequestMessage(o.C.PRACK,n);return i=e.call(this,s.NonInviteClientTransaction,t.userAgentCore,a,r)||this,t.signalingStateTransition(a),i}return i(t,e),t}(r(6).UserAgentClient);t.PrackUserAgentClient=a},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(1),s=function(e){function t(t,r,n){var i=e.call(this,o.NonInviteServerTransaction,t.userAgentCore,r,n)||this;return t.signalingStateTransition(r),i.dialog=t,i}return i(t,e),t.prototype.accept=function(t){return void 0===t&&(t={statusCode:200}),t.body&&this.dialog.signalingStateTransition(t.body),e.prototype.accept.call(this,t)},t}(r(9).UserAgentServer);t.PrackUserAgentServer=s},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(2),s=r(1),a=function(e){function t(t,r,n){var i=this,a=t.createOutgoingRequestMessage(o.C.INVITE,n);return(i=e.call(this,s.InviteClientTransaction,t.userAgentCore,a,r)||this).delegate=r,t.signalingStateTransition(a),t.reinviteUserAgentClient=i,i.dialog=t,i}return i(t,e),t.prototype.receiveResponse=function(e){var t=this,r=e.statusCode?e.statusCode.toString():"";if(!r)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(r):this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e});break;case/^1[0-9]{2}$/.test(r):this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e,session:this.dialog,prack:function(e){throw new Error("Unimplemented.")}});break;case/^2[0-9]{2}$/.test(r):this.dialog.signalingStateTransition(e),this.delegate&&this.delegate.onAccept&&this.delegate.onAccept({message:e,session:this.dialog,ack:function(e){return t.dialog.ack(e)}});break;case/^3[0-9]{2}$/.test(r):this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e});break;case/^[4-6][0-9]{2}$/.test(r):this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e});break;default:throw new Error("Invalid status code "+r)}},t}(r(6).UserAgentClient);t.ReInviteUserAgentClient=a},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}),o=this&&this.__assign||function(){return(o=Object.assign||function(e){for(var t,r=1,n=arguments.length;r=e)&&this.refreshTimerSet()}},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"subscriptionExpiresInitial",{get:function(){return this._subscriptionExpiresInitial},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"subscriptionRefresh",{get:function(){if(void 0!==this._subscriptionRefresh&&void 0!==this._subscriptionRefreshLastSet){var e=Math.floor(Date.now()/1e3)-this._subscriptionRefreshLastSet,t=this._subscriptionRefresh-e;return Math.max(t,0)}},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"subscriptionState",{get:function(){return this._subscriptionState},enumerable:!0,configurable:!0}),t.prototype.receiveRequest=function(t){if(this.logger.log("SUBSCRIBE dialog "+this.id+" received "+t.method+" request"),this.sequenceGuard(t))switch(e.prototype.receiveRequest.call(this,t),t.method){case o.C.NOTIFY:this.onNotify(t);break;default:this.logger.log("SUBSCRIBE dialog "+this.id+" received unimplemented "+t.method+" request"),this.core.replyStateless(t,{statusCode:501})}else this.logger.log("SUBSCRIBE dialog "+this.id+" rejected out of order "+t.method+" request.")},t.prototype.refresh=function(){var e="Allow: "+u.AllowedMethods.toString(),t={};return t.extraHeaders=(t.extraHeaders||[]).slice(),t.extraHeaders.push(e),t.extraHeaders.push("Event: "+this.subscriptionEvent),t.extraHeaders.push("Expires: "+this.subscriptionExpiresInitial),t.extraHeaders.push("Contact: "+this.core.configuration.contact.toString()),this.subscribe(void 0,t)},t.prototype.subscribe=function(e,t){var r=this;if(void 0===t&&(t={}),this.subscriptionState!==c.SubscriptionState.Pending&&this.subscriptionState!==c.SubscriptionState.Active)throw new Error("Invalid state "+this.subscriptionState+'. May only re-subscribe while in state "pending" or "active".');this.logger.log("SUBSCRIBE dialog "+this.id+" sending SUBSCRIBE request");var n=new h.ReSubscribeUserAgentClient(this,e,t);return this.N=setTimeout(function(){return r.timer_N()},a.Timers.TIMER_N),n},t.prototype.terminate=function(){this.stateTransition(c.SubscriptionState.Terminated),this.onTerminated()},t.prototype.unsubscribe=function(){var e="Allow: "+u.AllowedMethods.toString(),t={};return t.extraHeaders=(t.extraHeaders||[]).slice(),t.extraHeaders.push(e),t.extraHeaders.push("Event: "+this.subscriptionEvent),t.extraHeaders.push("Expires: 0"),t.extraHeaders.push("Contact: "+this.core.configuration.contact.toString()),this.subscribe(void 0,t)},t.prototype.onNotify=function(e){var t=e.parseHeader("Event").event;if(t&&t===this.subscriptionEvent){this.N&&(clearTimeout(this.N),this.N=void 0);var r=e.parseHeader("Subscription-State");if(r&&r.state){var n=r.state,i=r.expires?Math.max(r.expires,0):void 0;switch(n){case"pending":this.stateTransition(c.SubscriptionState.Pending,i);break;case"active":this.stateTransition(c.SubscriptionState.Active,i);break;case"terminated":this.stateTransition(c.SubscriptionState.Terminated,i);break;default:this.logger.warn("Unrecognized subscription state.")}var o=new d.NotifyUserAgentServer(this,e);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(o):o.accept()}else this.core.replyStateless(e,{statusCode:489})}else this.core.replyStateless(e,{statusCode:489})},t.prototype.onRefresh=function(e){this.delegate&&this.delegate.onRefresh&&this.delegate.onRefresh(e)},t.prototype.onTerminated=function(){this.delegate&&this.delegate.onTerminated&&this.delegate.onTerminated()},t.prototype.refreshTimerClear=function(){this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=void 0)},t.prototype.refreshTimerSet=function(){var e=this;if(this.refreshTimerClear(),this.autoRefresh&&this.subscriptionExpires>0){var t=900*this.subscriptionExpires;this._subscriptionRefresh=Math.floor(t/1e3),this._subscriptionRefreshLastSet=Math.floor(Date.now()/1e3),this.refreshTimer=setTimeout(function(){e.refreshTimer=void 0,e._subscriptionRefresh=void 0,e._subscriptionRefreshLastSet=void 0,e.onRefresh(e.refresh())},t)}},t.prototype.stateTransition=function(e,t){var r=this,n=function(){r.logger.warn("Invalid subscription state transition from "+r.subscriptionState+" to "+e)};switch(e){case c.SubscriptionState.Initial:case c.SubscriptionState.NotifyWait:return void n();case c.SubscriptionState.Pending:if(this.subscriptionState!==c.SubscriptionState.NotifyWait&&this.subscriptionState!==c.SubscriptionState.Pending)return void n();break;case c.SubscriptionState.Active:case c.SubscriptionState.Terminated:if(this.subscriptionState!==c.SubscriptionState.NotifyWait&&this.subscriptionState!==c.SubscriptionState.Pending&&this.subscriptionState!==c.SubscriptionState.Active)return void n();break;default:return void n()}e===c.SubscriptionState.Pending&&t&&(this.subscriptionExpires=t),e===c.SubscriptionState.Active&&t&&(this.subscriptionExpires=t),e===c.SubscriptionState.Terminated&&this.dispose(),this._subscriptionState=e},t.prototype.timer_N=function(){this.subscriptionState!==c.SubscriptionState.Terminated&&(this.stateTransition(c.SubscriptionState.Terminated),this.onTerminated())},t}(r(33).Dialog);t.SubscriptionDialog=p},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(2),s=r(1),a=function(e){function t(t,r,n){var i=this,a=t.createOutgoingRequestMessage(o.C.SUBSCRIBE,n);return(i=e.call(this,s.NonInviteClientTransaction,t.userAgentCore,a,r)||this).dialog=t,i}return i(t,e),t.prototype.waitNotifyStop=function(){},t.prototype.receiveResponse=function(t){if(t.statusCode&&t.statusCode>=200&&t.statusCode<300){var r=t.getHeader("Expires");if(r){var n=Number(r);this.dialog.subscriptionExpires>n&&(this.dialog.subscriptionExpires=n)}else this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE")}if(t.statusCode&&t.statusCode>=400&&t.statusCode<700){[404,405,410,416,480,481,482,483,484,485,489,501,604].includes(t.statusCode)&&this.dialog.terminate()}e.prototype.receiveResponse.call(this,t)},t}(r(6).UserAgentClient);t.ReSubscribeUserAgentClient=a},function(e,t,r){"use strict";(function(e){var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(10),s=r(3),a=r(7),c=r(5),u=r(35),d=r(114),h=function(t){function r(r,n,i){var o=t.call(this)||this;o.type=s.TypeStrings.SessionDescriptionHandler,o.options=i||{},o.logger=r,o.observer=n,o.dtmfSender=void 0,o.shouldAcquireMedia=!0,o.CONTENT_TYPE="application/sdp",o.C={DIRECTION:{NULL:null,SENDRECV:"sendrecv",SENDONLY:"sendonly",RECVONLY:"recvonly",INACTIVE:"inactive"}},o.logger.log("SessionDescriptionHandlerOptions: "+JSON.stringify(o.options)),o.direction=o.C.DIRECTION.NULL,o.modifiers=o.options.modifiers||[],Array.isArray(o.modifiers)||(o.modifiers=[o.modifiers]);var a=e.window||e;return o.WebRTC={MediaStream:a.MediaStream,getUserMedia:a.navigator.mediaDevices.getUserMedia.bind(a.navigator.mediaDevices),RTCPeerConnection:a.RTCPeerConnection},o.iceGatheringTimeout=!1,o.initPeerConnection(o.options.peerConnectionOptions),o.constraints=o.checkAndDefaultConstraints(o.options.constraints),o}return i(r,t),r.defaultFactory=function(e,t){return new r(e.ua.getLogger("sip.invitecontext.sessionDescriptionHandler",e.id),new d.SessionDescriptionHandlerObserver(e,t),t)},r.prototype.close=function(){this.logger.log("closing PeerConnection"),this.peerConnection&&"closed"!==this.peerConnection.signalingState&&(this.peerConnection.getSenders?this.peerConnection.getSenders().forEach(function(e){e.track&&e.track.stop()}):(this.logger.warn("Using getLocalStreams which is deprecated"),this.peerConnection.getLocalStreams().forEach(function(e){e.getTracks().forEach(function(e){e.stop()})})),this.peerConnection.getReceivers?this.peerConnection.getReceivers().forEach(function(e){e.track&&e.track.stop()}):(this.logger.warn("Using getRemoteStreams which is deprecated"),this.peerConnection.getRemoteStreams().forEach(function(e){e.getTracks().forEach(function(e){e.stop()})})),this.resetIceGatheringComplete(),this.peerConnection.close())},r.prototype.getDescription=function(e,t){var r=this;void 0===e&&(e={}),void 0===t&&(t=[]),e.peerConnectionOptions&&this.initPeerConnection(e.peerConnectionOptions);var n=Object.assign({},this.constraints,e.constraints);return n=this.checkAndDefaultConstraints(n),JSON.stringify(n)!==JSON.stringify(this.constraints)&&(this.constraints=n,this.shouldAcquireMedia=!0),Array.isArray(t)||(t=[t]),t=t.concat(this.modifiers),Promise.resolve().then(function(){if(r.shouldAcquireMedia)return r.acquire(r.constraints).then(function(){r.shouldAcquireMedia=!1})}).then(function(){return r.createOfferOrAnswer(e.RTCOfferOptions,t)}).then(function(e){if(void 0===e.sdp)throw new a.Exceptions.SessionDescriptionHandlerError("getDescription",void 0,"SDP undefined");return r.emit("getDescription",e),{body:e.sdp,contentType:r.CONTENT_TYPE}})},r.prototype.hasDescription=function(e){return e===this.CONTENT_TYPE},r.prototype.holdModifier=function(e){return e.sdp?(/a=(sendrecv|sendonly|recvonly|inactive)/.test(e.sdp)?(e.sdp=e.sdp.replace(/a=sendrecv\r\n/g,"a=sendonly\r\n"),e.sdp=e.sdp.replace(/a=recvonly\r\n/g,"a=inactive\r\n")):e.sdp=e.sdp.replace(/(m=[^\r]*\r\n)/g,"$1a=sendonly\r\n"),Promise.resolve(e)):Promise.resolve(e)},r.prototype.setDescription=function(e,t,r){var n=this;void 0===t&&(t={}),void 0===r&&(r=[]),t.peerConnectionOptions&&this.initPeerConnection(t.peerConnectionOptions),Array.isArray(r)||(r=[r]),r=r.concat(this.modifiers);var i={type:this.hasOffer("local")?"answer":"offer",sdp:e};return Promise.resolve().then(function(){if(n.shouldAcquireMedia&&n.options.alwaysAcquireMediaFirst)return n.acquire(n.constraints).then(function(){n.shouldAcquireMedia=!1})}).then(function(){return c.Utils.reducePromises(r,i)}).catch(function(e){if(e.type===s.TypeStrings.SessionDescriptionHandlerError)throw e;var t=new a.Exceptions.SessionDescriptionHandlerError("setDescription",e,"The modifiers did not resolve successfully");throw n.logger.error(t.message),n.emit("peerConnection-setRemoteDescriptionFailed",t),t}).then(function(e){return n.emit("setDescription",e),n.peerConnection.setRemoteDescription(e)}).catch(function(i){if(i.type===s.TypeStrings.SessionDescriptionHandlerError)throw i;if(/^m=video.+$/gm.test(e)&&!t.disableAudioFallback)return t.disableAudioFallback=!0,n.setDescription(e,t,[u.stripVideo].concat(r));var o=new a.Exceptions.SessionDescriptionHandlerError("setDescription",i);throw o.error&&n.logger.error(o.error),n.emit("peerConnection-setRemoteDescriptionFailed",o),o}).then(function(){n.peerConnection.getReceivers?n.emit("setRemoteDescription",n.peerConnection.getReceivers()):n.emit("setRemoteDescription",n.peerConnection.getRemoteStreams()),n.emit("confirmed",n)})},r.prototype.sendDtmf=function(e,t){if(void 0===t&&(t={}),!this.dtmfSender&&this.hasBrowserGetSenderSupport()){var r=this.peerConnection.getSenders();r.length>0&&(this.dtmfSender=r[0].dtmf)}if(!this.dtmfSender&&this.hasBrowserTrackSupport()){var n=this.peerConnection.getLocalStreams();if(n.length>0){var i=n[0].getAudioTracks();i.length>0&&(this.dtmfSender=this.peerConnection.createDTMFSender(i[0]))}}if(!this.dtmfSender)return!1;try{this.dtmfSender.insertDTMF(e,t.duration,t.interToneGap)}catch(e){if("InvalidStateError"===e.type||"InvalidCharacterError"===e.type)return this.logger.error(e),!1;throw e}return this.logger.log("DTMF sent via RTP: "+e.toString()),!0},r.prototype.getDirection=function(){return this.direction},r.prototype.on=function(e,r){return t.prototype.on.call(this,e,r)},r.prototype.createOfferOrAnswer=function(e,t){var r=this;void 0===e&&(e={}),void 0===t&&(t=[]);var n=this.hasOffer("remote")?"createAnswer":"createOffer",i=this.peerConnection;return this.logger.log(n),(this.hasOffer("remote")?i.createAnswer:i.createOffer)(e).catch(function(e){if(e.type===s.TypeStrings.SessionDescriptionHandlerError)throw e;var t=new a.Exceptions.SessionDescriptionHandlerError("createOfferOrAnswer",e,"peerConnection-"+n+"Failed");throw r.emit("peerConnection-"+n+"Failed",t),t}).then(function(e){return c.Utils.reducePromises(t,r.createRTCSessionDescriptionInit(e))}).then(function(e){return r.resetIceGatheringComplete(),r.logger.log("Setting local sdp."),r.logger.log("sdp is "+e.sdp||!1),i.setLocalDescription(e)}).catch(function(e){if(e.type===s.TypeStrings.SessionDescriptionHandlerError)throw e;var t=new a.Exceptions.SessionDescriptionHandlerError("createOfferOrAnswer",e,"peerConnection-SetLocalDescriptionFailed");throw r.emit("peerConnection-SetLocalDescriptionFailed",t),t}).then(function(){return r.waitForIceGatheringComplete()}).then(function(){var e=r.createRTCSessionDescriptionInit(r.peerConnection.localDescription);return c.Utils.reducePromises(t,e)}).then(function(e){return r.setDirection(e.sdp||""),e}).catch(function(e){if(e.type===s.TypeStrings.SessionDescriptionHandlerError)throw e;var t=new a.Exceptions.SessionDescriptionHandlerError("createOfferOrAnswer",e);throw r.logger.error(t.toString()),t})},r.prototype.createRTCSessionDescriptionInit=function(e){return{type:e.type,sdp:e.sdp}},r.prototype.addDefaultIceCheckingTimeout=function(e){return void 0===e.iceCheckingTimeout&&(e.iceCheckingTimeout=5e3),e},r.prototype.addDefaultIceServers=function(e){return e.iceServers||(e.iceServers=[{urls:"stun:stun.l.google.com:19302"}]),e},r.prototype.checkAndDefaultConstraints=function(e){var t={audio:!0,video:!this.options.alwaysAcquireMediaFirst};return e=e||t,0===Object.keys(e).length&&e.constructor===Object?t:e},r.prototype.hasBrowserTrackSupport=function(){return Boolean(this.peerConnection.addTrack)},r.prototype.hasBrowserGetSenderSupport=function(){return Boolean(this.peerConnection.getSenders)},r.prototype.initPeerConnection=function(e){var t=this;void 0===e&&(e={}),(e=this.addDefaultIceCheckingTimeout(e)).rtcConfiguration=e.rtcConfiguration||{},e.rtcConfiguration=this.addDefaultIceServers(e.rtcConfiguration),this.logger.log("initPeerConnection"),this.peerConnection&&(this.logger.log("Already have a peer connection for this session. Tearing down."),this.resetIceGatheringComplete(),this.peerConnection.close()),this.peerConnection=new this.WebRTC.RTCPeerConnection(e.rtcConfiguration),this.logger.log("New peer connection created"),"ontrack"in this.peerConnection?this.peerConnection.addEventListener("track",function(e){t.logger.log("track added"),t.observer.trackAdded(),t.emit("addTrack",e)}):(this.logger.warn("Using onaddstream which is deprecated"),this.peerConnection.onaddstream=function(e){t.logger.log("stream added"),t.emit("addStream",e)}),this.peerConnection.onicecandidate=function(e){t.emit("iceCandidate",e),e.candidate?t.logger.log("ICE candidate received: "+(null===e.candidate.candidate?null:e.candidate.candidate.trim())):null===e.candidate&&(t.logger.log("ICE candidate gathering complete"),t.triggerIceGatheringComplete())},this.peerConnection.onicegatheringstatechange=function(){switch(t.logger.log("RTCIceGatheringState changed: "+t.peerConnection.iceGatheringState),t.peerConnection.iceGatheringState){case"gathering":t.emit("iceGathering",t),!t.iceGatheringTimer&&e.iceCheckingTimeout&&(t.iceGatheringTimeout=!1,t.iceGatheringTimer=setTimeout(function(){t.logger.log("RTCIceChecking Timeout Triggered after "+e.iceCheckingTimeout+" milliseconds"),t.iceGatheringTimeout=!0,t.triggerIceGatheringComplete()},e.iceCheckingTimeout));break;case"complete":t.triggerIceGatheringComplete()}},this.peerConnection.oniceconnectionstatechange=function(){var e;switch(t.peerConnection.iceConnectionState){case"new":e="iceConnection";break;case"checking":e="iceConnectionChecking";break;case"connected":e="iceConnectionConnected";break;case"completed":e="iceConnectionCompleted";break;case"failed":e="iceConnectionFailed";break;case"disconnected":e="iceConnectionDisconnected";break;case"closed":e="iceConnectionClosed";break;default:return void t.logger.warn("Unknown iceConnection state: "+t.peerConnection.iceConnectionState)}t.logger.log("ICE Connection State changed to "+e),t.emit(e,t)}},r.prototype.acquire=function(e){var t=this;return e=this.checkAndDefaultConstraints(e),new Promise(function(r,n){t.logger.log("acquiring local media"),t.emit("userMediaRequest",e),e.audio||e.video?t.WebRTC.getUserMedia(e).then(function(e){t.observer.trackAdded(),t.emit("userMedia",e),r(e)}).catch(function(e){t.emit("userMediaFailed",e),n(e)}):r([])}).catch(function(e){if(e.type===s.TypeStrings.SessionDescriptionHandlerError)throw e;var r=new a.Exceptions.SessionDescriptionHandlerError("acquire",e,"unable to acquire streams");throw t.logger.error(r.message),r.error&&t.logger.error(r.error),r}).then(function(e){t.logger.log("acquired local media streams");try{return t.peerConnection.removeTrack&&t.peerConnection.getSenders().forEach(function(e){t.peerConnection.removeTrack(e)}),e}catch(e){return Promise.reject(e)}}).catch(function(e){if(e.type===s.TypeStrings.SessionDescriptionHandlerError)throw e;var r=new a.Exceptions.SessionDescriptionHandlerError("acquire",e,"error removing streams");throw t.logger.error(r.message),r.error&&t.logger.error(r.error),r}).then(function(e){try{(e=[].concat(e)).forEach(function(e){t.peerConnection.addTrack?e.getTracks().forEach(function(r){t.peerConnection.addTrack(r,e)}):t.peerConnection.addStream(e)})}catch(e){return Promise.reject(e)}return Promise.resolve()}).catch(function(e){if(e.type===s.TypeStrings.SessionDescriptionHandlerError)throw e;var r=new a.Exceptions.SessionDescriptionHandlerError("acquire",e,"error adding stream");throw t.logger.error(r.message),r.error&&t.logger.error(r.error),r})},r.prototype.hasOffer=function(e){var t="have-"+e+"-offer";return this.peerConnection.signalingState===t},r.prototype.isIceGatheringComplete=function(){return"complete"===this.peerConnection.iceGatheringState||this.iceGatheringTimeout},r.prototype.resetIceGatheringComplete=function(){this.iceGatheringTimeout=!1,this.logger.log("resetIceGatheringComplete"),this.iceGatheringTimer&&(clearTimeout(this.iceGatheringTimer),this.iceGatheringTimer=void 0),this.iceGatheringDeferred&&(this.iceGatheringDeferred.reject(),this.iceGatheringDeferred=void 0)},r.prototype.setDirection=function(e){var t=e.match(/a=(sendrecv|sendonly|recvonly|inactive)/);if(null===t)return this.direction=this.C.DIRECTION.NULL,void this.observer.directionChanged();var r=t[1];switch(r){case this.C.DIRECTION.SENDRECV:case this.C.DIRECTION.SENDONLY:case this.C.DIRECTION.RECVONLY:case this.C.DIRECTION.INACTIVE:this.direction=r;break;default:this.direction=this.C.DIRECTION.NULL}this.observer.directionChanged()},r.prototype.triggerIceGatheringComplete=function(){this.isIceGatheringComplete()&&(this.emit("iceGatheringComplete",this),this.iceGatheringTimer&&(clearTimeout(this.iceGatheringTimer),this.iceGatheringTimer=void 0),this.iceGatheringDeferred&&(this.iceGatheringDeferred.resolve(),this.iceGatheringDeferred=void 0))},r.prototype.waitForIceGatheringComplete=function(){return this.logger.log("waitForIceGatheringComplete"),this.isIceGatheringComplete()?(this.logger.log("ICE is already complete. Return resolved."),Promise.resolve()):(this.iceGatheringDeferred||(this.iceGatheringDeferred=c.Utils.defer()),this.logger.log("ICE is not complete. Returning promise"),this.iceGatheringDeferred?this.iceGatheringDeferred.promise:Promise.resolve())},r}(o.EventEmitter);t.SessionDescriptionHandler=h}).call(this,r(24))},function(e,t,r){"use strict";(function(e){var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o,s=r(3),a=r(7),c=r(11),u=r(47),d=r(5);!function(e){e[e.STATUS_CONNECTING=0]="STATUS_CONNECTING",e[e.STATUS_OPEN=1]="STATUS_OPEN",e[e.STATUS_CLOSING=2]="STATUS_CLOSING",e[e.STATUS_CLOSED=3]="STATUS_CLOSED"}(o=t.TransportStatus||(t.TransportStatus={}));var h=function(t){function r(r,n){void 0===n&&(n={});var i=t.call(this,r,n)||this;return i.WebSocket=(e.window||e).WebSocket,i.type=s.TypeStrings.Transport,i.reconnectionAttempts=0,i.status=o.STATUS_CONNECTING,i.configuration=i.loadConfig(n),i.server=i.configuration.wsServers[0],i}return i(r,t),r.prototype.isConnected=function(){return this.status===o.STATUS_OPEN},r.prototype.sendPromise=function(e,t){if(void 0===t&&(t={}),!this.statusAssert(o.STATUS_OPEN,t.force))return this.onError("unable to send message - WebSocket not open"),Promise.reject();var r=e.toString();return this.ws?(!0===this.configuration.traceSip&&this.logger.log("sending WebSocket message:\n\n"+r+"\n"),this.ws.send(r),Promise.resolve({msg:r})):(this.onError("unable to send message - WebSocket does not exist"),Promise.reject())},r.prototype.disconnectPromise=function(e){var t=this;return void 0===e&&(e={}),this.disconnectionPromise?this.disconnectionPromise:(e.code=e.code||1e3,this.statusTransition(o.STATUS_CLOSING,e.force)?(this.emit("disconnecting"),this.disconnectionPromise=new Promise(function(r,n){t.disconnectDeferredResolve=r,t.reconnectTimer&&(clearTimeout(t.reconnectTimer),t.reconnectTimer=void 0),t.ws?(t.stopSendingKeepAlives(),t.logger.log("closing WebSocket "+t.server.wsUri),t.ws.close(e.code,e.reason)):n("Attempted to disconnect but the websocket doesn't exist")}),this.disconnectionPromise):this.status===o.STATUS_CLOSED?Promise.resolve({overrideEvent:!0}):this.connectionPromise?this.connectionPromise.then(function(){return Promise.reject("The websocket did not disconnect")}).catch(function(){return Promise.resolve({overrideEvent:!0})}):Promise.reject("The websocket did not disconnect"))},r.prototype.connectPromise=function(e){var t=this;return void 0===e&&(e={}),this.status!==o.STATUS_CLOSING||e.force?this.connectionPromise?this.connectionPromise:(this.server=this.server||this.getNextWsServer(e.force),this.connectionPromise=new Promise(function(r,n){if((t.status===o.STATUS_OPEN||t.status===o.STATUS_CLOSING)&&!e.force)return t.logger.warn("WebSocket "+t.server.wsUri+" is already connected"),void n("Failed status check - attempted to open a connection but already open/closing");t.connectDeferredResolve=r,t.status=o.STATUS_CONNECTING,t.emit("connecting"),t.logger.log("connecting to WebSocket "+t.server.wsUri),t.disposeWs();try{t.ws=new WebSocket(t.server.wsUri,"sip")}catch(e){return t.ws=null,t.status=o.STATUS_CLOSED,t.onError("error connecting to WebSocket "+t.server.wsUri+":"+e),void n("Failed to create a websocket")}t.ws?(t.connectionTimeout=setTimeout(function(){t.statusTransition(o.STATUS_CLOSED),t.logger.warn("took too long to connect - exceeded time set in configuration.connectionTimeout: "+t.configuration.connectionTimeout+"s"),t.emit("disconnected",{code:1e3}),t.connectionPromise=void 0,n("Connection timeout")},1e3*t.configuration.connectionTimeout),t.boundOnOpen=t.onOpen.bind(t),t.boundOnMessage=t.onMessage.bind(t),t.boundOnClose=t.onClose.bind(t),t.boundOnError=t.onWebsocketError.bind(t),t.ws.addEventListener("open",t.boundOnOpen),t.ws.addEventListener("message",t.boundOnMessage),t.ws.addEventListener("close",t.boundOnClose),t.ws.addEventListener("error",t.boundOnError)):n("Unexpected instance websocket not set")}),this.connectionPromise):Promise.reject("WebSocket "+this.server.wsUri+" is closing")},r.prototype.onMessage=function(e){var t,r=e.data;if(/^(\r\n)+$/.test(r))return this.clearKeepAliveTimeout(),void(!0===this.configuration.traceSip&&this.logger.log("received WebSocket message with CRLF Keep Alive response"));if(r){if("string"!=typeof r){try{t=String.fromCharCode.apply(null,new Uint8Array(r))}catch(e){return void this.logger.warn("received WebSocket binary message failed to be converted into string, message discarded")}!0===this.configuration.traceSip&&this.logger.log("received WebSocket binary message:\n\n"+r+"\n")}else!0===this.configuration.traceSip&&this.logger.log("received WebSocket text message:\n\n"+r+"\n"),t=r;this.emit("message",t)}else this.logger.warn("received empty message, message discarded")},r.prototype.onOpen=function(){if(this.status===o.STATUS_CLOSED){var e=this.ws;return this.disposeWs(),void e.close(1e3)}this.status=o.STATUS_OPEN,this.emit("connected"),this.connectionTimeout&&(clearTimeout(this.connectionTimeout),this.connectionTimeout=void 0),this.logger.log("WebSocket "+this.server.wsUri+" connected"),void 0!==this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.reconnectionAttempts=0,this.disconnectionPromise=void 0,this.disconnectDeferredResolve=void 0,this.startSendingKeepAlives(),this.connectDeferredResolve?this.connectDeferredResolve({overrideEvent:!0}):this.logger.warn("Unexpected websocket.onOpen with no connectDeferredResolve")},r.prototype.onClose=function(e){if(this.logger.log("WebSocket disconnected (code: "+e.code+(e.reason?"| reason: "+e.reason:"")+")"),this.status!==o.STATUS_CLOSING&&(this.logger.warn("WebSocket closed without SIP.js requesting it"),this.emit("transportError")),this.stopSendingKeepAlives(),this.connectionTimeout&&clearTimeout(this.connectionTimeout),this.connectionTimeout=void 0,this.connectionPromise=void 0,this.connectDeferredResolve=void 0,this.disconnectDeferredResolve)return this.disconnectDeferredResolve({overrideEvent:!0}),this.statusTransition(o.STATUS_CLOSED),void(this.disconnectDeferredResolve=void 0);this.status=o.STATUS_CLOSED,this.emit("disconnected",{code:e.code,reason:e.reason}),this.reconnect()},r.prototype.disposeWs=function(){this.ws&&(this.ws.removeEventListener("open",this.boundOnOpen),this.ws.removeEventListener("message",this.boundOnMessage),this.ws.removeEventListener("close",this.boundOnClose),this.ws.removeEventListener("error",this.boundOnError),this.ws=void 0)},r.prototype.onError=function(e){this.logger.warn("Transport error: "+e),this.emit("transportError")},r.prototype.onWebsocketError=function(){this.onError("The Websocket had an error")},r.prototype.reconnect=function(){var e=this;if(this.reconnectionAttempts>0&&this.logger.log("Reconnection attempt "+this.reconnectionAttempts+" failed"),this.noAvailableServers())return this.logger.warn("attempted to get next ws server but there are no available ws servers left"),this.logger.warn("no available ws servers left - going to closed state"),this.status=o.STATUS_CLOSED,this.emit("closed"),void this.resetServerErrorStatus();this.isConnected()&&(this.logger.warn("attempted to reconnect while connected - forcing disconnect"),this.disconnect({force:!0})),this.reconnectionAttempts+=1,this.reconnectionAttempts>this.configuration.maxReconnectionAttempts?(this.logger.warn("maximum reconnection attempts for WebSocket "+this.server.wsUri),this.logger.log("transport "+this.server.wsUri+" failed | connection state set to 'error'"),this.server.isError=!0,this.emit("transportError"),this.noAvailableServers()||(this.server=this.getNextWsServer()),this.reconnectionAttempts=0,this.reconnect()):(this.logger.log("trying to reconnect to WebSocket "+this.server.wsUri+" (reconnection attempt "+this.reconnectionAttempts+")"),this.reconnectTimer=setTimeout(function(){e.connect(),e.reconnectTimer=void 0},1===this.reconnectionAttempts?0:1e3*this.configuration.reconnectionTimeout))},r.prototype.resetServerErrorStatus=function(){for(var e=0,t=this.configuration.wsServers;et[0].weight?t=[i]:i.weight===t[0].weight&&t.push(i))}return t[Math.floor(Math.random()*t.length)]},r.prototype.noAvailableServers=function(){for(var e=0,t=this.configuration.wsServers;e",weight:0,wsUri:"wss://edge.sip.onsip.com",isError:!1}],connectionTimeout:5,maxReconnectionAttempts:3,reconnectionTimeout:4,keepAliveInterval:0,keepAliveDebounce:10,traceSip:!1},r=this.getConfigurationCheck();for(var n in r.mandatory){if(!e.hasOwnProperty(n))throw new a.Exceptions.ConfigurationError(n);var i=e[n];if(void 0===(o=r.mandatory[n](i)))throw new a.Exceptions.ConfigurationError(n,i);t[n]=o}for(var n in r.optional)if(e.hasOwnProperty(n)){var o;if((i=e[n])instanceof Array&&0===i.length||null===i||""===i||void 0===i||"number"==typeof i&&isNaN(i))continue;if(void 0===(o=r.optional[n](i)))throw new a.Exceptions.ConfigurationError(n,i);t[n]=o}var s={};for(var n in t)t.hasOwnProperty(n)&&(s[n]={value:t[n]});var c=Object.defineProperties({},s);for(var n in this.logger.log("configuration parameters after validation:"),t)t.hasOwnProperty(n)&&this.logger.log("\xb7 "+n+": "+JSON.stringify(t[n]));return c},r.prototype.getConfigurationCheck=function(){return{mandatory:{},optional:{wsServers:function(e){if("string"==typeof e)e=[{wsUri:e}];else{if(!(e instanceof Array))return;for(var t=0;t",i.weight||(i.weight=0),i.isError=!1,i.scheme=o.scheme.toUpperCase()}return e},keepAliveInterval:function(e){if(d.Utils.isDecimal(e)){var t=Number(e);if(t>0)return t}},keepAliveDebounce:function(e){if(d.Utils.isDecimal(e)){var t=Number(e);if(t>0)return t}},traceSip:function(e){if("boolean"==typeof e)return e},connectionTimeout:function(e){if(d.Utils.isDecimal(e)){var t=Number(e);if(t>0)return t}},maxReconnectionAttempts:function(e){if(d.Utils.isDecimal(e)){var t=Number(e);if(t>=0)return t}},reconnectionTimeout:function(e){if(d.Utils.isDecimal(e)){var t=Number(e);if(t>0)return t}}}}},r.C=o,r}(u.Transport);t.Transport=h}).call(this,r(24))},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(15);t.ClientContext=n.ClientContext;var i=r(2);t.C=i.C;var o=r(37);t.DigestAuthentication=o.DigestAuthentication;var s=r(3);t.DialogStatus=s.DialogStatus,t.SessionStatus=s.SessionStatus,t.TypeStrings=s.TypeStrings,t.UAStatus=s.UAStatus;var a=r(7);t.Exceptions=a.Exceptions;var c=r(11);t.Grammar=c.Grammar;var u=r(40);t.LoggerFactory=u.LoggerFactory;var d=r(18);t.NameAddrHeader=d.NameAddrHeader;var h=r(41);t.Parser=h.Parser;var p=r(42);t.PublishContext=p.PublishContext;var l=r(27);t.ReferClientContext=l.ReferClientContext,t.ReferServerContext=l.ReferServerContext;var f=r(44);t.RegisterContext=f.RegisterContext;var g=r(22);t.ServerContext=g.ServerContext;var v=r(45);t.InviteClientContext=v.InviteClientContext,t.InviteServerContext=v.InviteServerContext,t.Session=v.Session;var m=r(8);t.IncomingRequest=m.IncomingRequest,t.IncomingResponse=m.IncomingResponse,t.OutgoingRequest=m.OutgoingRequest;var y=r(46);t.Subscription=y.Subscription;var S=r(12);t.Timers=S.Timers;var T=r(1),C={InviteClientTransaction:T.InviteClientTransaction,InviteServerTransaction:T.InviteServerTransaction,NonInviteClientTransaction:T.NonInviteClientTransaction,NonInviteServerTransaction:T.NonInviteServerTransaction};t.Transactions=C;var b=r(47);t.Transport=b.Transport;var _=r(48);t.UA=_.UA;var A=r(19);t.URI=A.URI;var w=r(5);t.Utils=w.Utils;var E=r(115);t.Web=E;var R=r(36),I=R.title;t.name=I;var O=R.version;t.version=O},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(18),s=r(19),a=function(e){function t(r,n,i,o){var s=e.call(this)||this;return s.message=r,s.expected=n,s.found=i,s.location=o,s.name="SyntaxError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(s,t),s}return i(t,e),t.buildMessage=function(e,t){function r(e){return e.charCodeAt(0).toString(16).toUpperCase()}function n(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,function(e){return"\\x0"+r(e)}).replace(/[\x10-\x1F\x7F-\x9F]/g,function(e){return"\\x"+r(e)})}function i(e){return e.replace(/\\/g,"\\\\").replace(/\]/g,"\\]").replace(/\^/g,"\\^").replace(/-/g,"\\-").replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,function(e){return"\\x0"+r(e)}).replace(/[\x10-\x1F\x7F-\x9F]/g,function(e){return"\\x"+r(e)})}function o(e){switch(e.type){case"literal":return'"'+n(e.text)+'"';case"class":var t=e.parts.map(function(e){return Array.isArray(e)?i(e[0])+"-"+i(e[1]):i(e)});return"["+(e.inverted?"^":"")+t+"]";case"any":return"any character";case"end":return"end of input";case"other":return e.description}}return"Expected "+function(e){var t,r,n=e.map(o);if(n.sort(),n.length>0){for(t=1,r=1;t",Ae=ws(">",!1),we="\\",Ee=ws("\\",!1),Re="[",Ie=ws("[",!1),Oe="]",xe=ws("]",!1),Pe="{",Ne=ws("{",!1),De="}",Ue=ws("}",!1),He=function(){return"*"},ke=function(){return"/"},Me=function(){return"="},qe=function(){return">"},je=function(){return"<"},Le=function(){return","},Fe=function(){return";"},Be=function(){return":"},Ge=function(){return'"'},We=(Es([["!","'"]],!1,!1),Es([["*","["]],!1,!1),/^[\]-~]/),ze=Es([["]","~"]],!1,!1),Ke=function(e){return e},Ve=/^[#-[]/,Ye=Es([["#","["]],!1,!1),$e=/^[\0-\t]/,Xe=Es([["\0","\t"]],!1,!1),Je=/^[\x0B-\f]/,Qe=Es([["\v","\f"]],!1,!1),Ze=/^[\x0E-\x7F]/,et=Es([["\x0e","\x7f"]],!1,!1),tt=function(){(t=t||{data:{}}).data.uri=new s.URI(t.data.scheme,t.data.user,t.data.host,t.data.port),delete t.data.scheme,delete t.data.user,delete t.data.host,delete t.data.host_type,delete t.data.port},rt=function(){(t=t||{data:{}}).data.uri=new s.URI(t.data.scheme,t.data.user,t.data.host,t.data.port,t.data.uri_params,t.data.uri_headers),delete t.data.scheme,delete t.data.user,delete t.data.host,delete t.data.host_type,delete t.data.port,delete t.data.uri_params,"SIP_URI"===t.startRule&&(t.data=t.data.uri)},nt="sips",it=ws("sips",!0),ot="sip",st=ws("sip",!0),at=function(e){(t=t||{data:{}}).data.scheme=e},ct=function(){(t=t||{data:{}}).data.user=decodeURIComponent(_s().slice(0,-1))},ut=function(){(t=t||{data:{}}).data.password=_s()},dt=function(){return(t=t||{data:{}}).data.host=_s(),t.data.host},ht=function(){return(t=t||{data:{}}).data.host_type="domain",_s()},pt=/^[a-zA-Z0-9_\-]/,lt=Es([["a","z"],["A","Z"],["0","9"],"_","-"],!1,!1),ft=/^[a-zA-Z0-9\-]/,gt=Es([["a","z"],["A","Z"],["0","9"],"-"],!1,!1),vt=function(){return(t=t||{data:{}}).data.host_type="IPv6",_s()},mt="::",yt=ws("::",!1),St=function(){return(t=t||{data:{}}).data.host_type="IPv6",_s()},Tt=function(){return(t=t||{data:{}}).data.host_type="IPv4",_s()},Ct="25",bt=ws("25",!1),_t=/^[0-5]/,At=Es([["0","5"]],!1,!1),wt="2",Et=ws("2",!1),Rt=/^[0-4]/,It=Es([["0","4"]],!1,!1),Ot="1",xt=ws("1",!1),Pt=/^[1-9]/,Nt=Es([["1","9"]],!1,!1),Dt=function(e){return t=t||{data:{}},e=parseInt(e.join("")),t.data.port=e,e},Ut="transport=",Ht=ws("transport=",!0),kt="udp",Mt=ws("udp",!0),qt="tcp",jt=ws("tcp",!0),Lt="sctp",Ft=ws("sctp",!0),Bt="tls",Gt=ws("tls",!0),Wt=function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.transport=e.toLowerCase()},zt="user=",Kt=ws("user=",!0),Vt="phone",Yt=ws("phone",!0),$t="ip",Xt=ws("ip",!0),Jt=function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.user=e.toLowerCase()},Qt="method=",Zt=ws("method=",!0),er=function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.method=e},tr="ttl=",rr=ws("ttl=",!0),nr=function(e){(t=t||{data:{}}).data.params||(t.data.params={}),t.data.params.ttl=e},ir="maddr=",or=ws("maddr=",!0),sr=function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.maddr=e},ar="lr",cr=ws("lr",!0),ur=function(){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.lr=void 0},dr=function(e,r){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),r=null===r?void 0:r[1],t.data.uri_params[e.toLowerCase()]=r},hr=function(e,r){e=e.join("").toLowerCase(),r=r.join(""),(t=t||{data:{}}).data.uri_headers||(t.data.uri_headers={}),t.data.uri_headers[e]?t.data.uri_headers[e].push(r):t.data.uri_headers[e]=[r]},pr=function(){"Refer_To"===(t=t||{data:{}}).startRule&&(t.data.uri=new s.URI(t.data.scheme,t.data.user,t.data.host,t.data.port,t.data.uri_params,t.data.uri_headers),delete t.data.scheme,delete t.data.user,delete t.data.host,delete t.data.host_type,delete t.data.port,delete t.data.uri_params)},lr="//",fr=ws("//",!1),gr=function(){(t=t||{data:{}}).data.scheme=_s()},vr=ws("SIP",!0),mr=function(){(t=t||{data:{}}).data.sip_version=_s()},yr="INVITE",Sr=ws("INVITE",!1),Tr="ACK",Cr=ws("ACK",!1),br=(ws("VXACH",!1),"OPTIONS"),_r=ws("OPTIONS",!1),Ar="BYE",wr=ws("BYE",!1),Er="CANCEL",Rr=ws("CANCEL",!1),Ir="REGISTER",Or=ws("REGISTER",!1),xr="SUBSCRIBE",Pr=ws("SUBSCRIBE",!1),Nr="NOTIFY",Dr=ws("NOTIFY",!1),Ur="REFER",Hr=ws("REFER",!1),kr="PUBLISH",Mr=ws("PUBLISH",!1),qr=function(){return(t=t||{data:{}}).data.method=_s(),t.data.method},jr=function(e){(t=t||{data:{}}).data.status_code=parseInt(e.join(""))},Lr=function(){(t=t||{data:{}}).data.reason_phrase=_s()},Fr=function(){(t=t||{data:{}}).data=_s()},Br=function(){var e,r;for(r=(t=t||{data:{}}).data.multi_header.length,e=0;eTs&&(Ts=ms,Cs=[]),Cs.push(e))}function xs(e,t,r){return new a(a.buildMessage(e,t),e,t,r)}function Ps(){var t;return e.substr(ms,2)===u?(t=u,ms+=2):(t=n,0===bs&&Os(d)),t}function Ns(){var t;return h.test(e.charAt(ms))?(t=e.charAt(ms),ms++):(t=n,0===bs&&Os(p)),t}function Ds(){var t;return l.test(e.charAt(ms))?(t=e.charAt(ms),ms++):(t=n,0===bs&&Os(f)),t}function Us(){var t;return g.test(e.charAt(ms))?(t=e.charAt(ms),ms++):(t=n,0===bs&&Os(v)),t}function Hs(){var e;return(e=qs())===n&&(e=js()),e}function ks(){var t;return m.test(e.charAt(ms))?(t=e.charAt(ms),ms++):(t=n,0===bs&&Os(y)),t}function Ms(){var t;return S.test(e.charAt(ms))?(t=e.charAt(ms),ms++):(t=n,0===bs&&Os(T)),t}function qs(){var t;return 32===e.charCodeAt(ms)?(t=C,ms++):(t=n,0===bs&&Os(b)),t}function js(){var t;return 9===e.charCodeAt(ms)?(t=_,ms++):(t=n,0===bs&&Os(A)),t}function Ls(){var t;return w.test(e.charAt(ms))?(t=e.charAt(ms),ms++):(t=n,0===bs&&Os(E)),t}function Fs(){var t;return 59===e.charCodeAt(ms)?(t=R,ms++):(t=n,0===bs&&Os(I)),t===n&&(47===e.charCodeAt(ms)?(t=O,ms++):(t=n,0===bs&&Os(x)),t===n&&(63===e.charCodeAt(ms)?(t=P,ms++):(t=n,0===bs&&Os(N)),t===n&&(58===e.charCodeAt(ms)?(t=D,ms++):(t=n,0===bs&&Os(U)),t===n&&(64===e.charCodeAt(ms)?(t=H,ms++):(t=n,0===bs&&Os(k)),t===n&&(38===e.charCodeAt(ms)?(t=M,ms++):(t=n,0===bs&&Os(q)),t===n&&(61===e.charCodeAt(ms)?(t=j,ms++):(t=n,0===bs&&Os(L)),t===n&&(43===e.charCodeAt(ms)?(t=F,ms++):(t=n,0===bs&&Os(B)),t===n&&(36===e.charCodeAt(ms)?(t=G,ms++):(t=n,0===bs&&Os(W)),t===n&&(44===e.charCodeAt(ms)?(t=z,ms++):(t=n,0===bs&&Os(K))))))))))),t}function Bs(){var e;return(e=Ls())===n&&(e=Gs()),e}function Gs(){var t;return 45===e.charCodeAt(ms)?(t=V,ms++):(t=n,0===bs&&Os(Y)),t===n&&(95===e.charCodeAt(ms)?(t=$,ms++):(t=n,0===bs&&Os(X)),t===n&&(46===e.charCodeAt(ms)?(t=J,ms++):(t=n,0===bs&&Os(Q)),t===n&&(33===e.charCodeAt(ms)?(t=Z,ms++):(t=n,0===bs&&Os(ee)),t===n&&(126===e.charCodeAt(ms)?(t=te,ms++):(t=n,0===bs&&Os(re)),t===n&&(42===e.charCodeAt(ms)?(t=ne,ms++):(t=n,0===bs&&Os(ie)),t===n&&(39===e.charCodeAt(ms)?(t=oe,ms++):(t=n,0===bs&&Os(se)),t===n&&(40===e.charCodeAt(ms)?(t=ae,ms++):(t=n,0===bs&&Os(ce)),t===n&&(41===e.charCodeAt(ms)?(t=ue,ms++):(t=n,0===bs&&Os(de)))))))))),t}function Ws(){var t,r,i,o,s;return t=ms,r=ms,37===e.charCodeAt(ms)?(i=he,ms++):(i=n,0===bs&&Os(pe)),i!==n&&(o=Us())!==n&&(s=Us())!==n?r=i=[i,o,s]:(ms=r,r=n),t=r!==n?e.substring(t,ms):r}function zs(){var e,t,r,i;for(e=ms,t=ms,r=[],i=Hs();i!==n;)r.push(i),i=Hs();if(r!==n&&(i=Ps())!==n?t=r=[r,i]:(ms=t,t=n),t===n&&(t=null),t!==n){if(r=[],(i=Hs())!==n)for(;i!==n;)r.push(i),i=Hs();else r=n;r!==n?(ys=e,e=t=le()):(ms=e,e=n)}else ms=e,e=n;return e}function Ks(){var e;return(e=zs())===n&&(e=null),e}function Vs(){var t,r,i;for(t=ms,r=[],(i=qs())===n&&(i=js());i!==n;)r.push(i),(i=qs())===n&&(i=js());return r!==n?(58===e.charCodeAt(ms)?(i=D,ms++):(i=n,0===bs&&Os(U)),i!==n&&Ks()!==n?(ys=t,t=r=fe()):(ms=t,t=n)):(ms=t,t=n),t}function Ys(){var t;return ge.test(e.charAt(ms))?(t=e.charAt(ms),ms++):(t=n,0===bs&&Os(ve)),t}function $s(){var t;return me.test(e.charAt(ms))?(t=e.charAt(ms),ms++):(t=n,0===bs&&Os(ye)),t}function Xs(){var t,r,i;if(t=ms,r=[],(i=Ls())===n&&(45===e.charCodeAt(ms)?(i=V,ms++):(i=n,0===bs&&Os(Y)),i===n&&(46===e.charCodeAt(ms)?(i=J,ms++):(i=n,0===bs&&Os(Q)),i===n&&(33===e.charCodeAt(ms)?(i=Z,ms++):(i=n,0===bs&&Os(ee)),i===n&&(37===e.charCodeAt(ms)?(i=he,ms++):(i=n,0===bs&&Os(pe)),i===n&&(42===e.charCodeAt(ms)?(i=ne,ms++):(i=n,0===bs&&Os(ie)),i===n&&(95===e.charCodeAt(ms)?(i=$,ms++):(i=n,0===bs&&Os(X)),i===n&&(43===e.charCodeAt(ms)?(i=F,ms++):(i=n,0===bs&&Os(B)),i===n&&(96===e.charCodeAt(ms)?(i=Se,ms++):(i=n,0===bs&&Os(Te)),i===n&&(39===e.charCodeAt(ms)?(i=oe,ms++):(i=n,0===bs&&Os(se)),i===n&&(126===e.charCodeAt(ms)?(i=te,ms++):(i=n,0===bs&&Os(re)))))))))))),i!==n)for(;i!==n;)r.push(i),(i=Ls())===n&&(45===e.charCodeAt(ms)?(i=V,ms++):(i=n,0===bs&&Os(Y)),i===n&&(46===e.charCodeAt(ms)?(i=J,ms++):(i=n,0===bs&&Os(Q)),i===n&&(33===e.charCodeAt(ms)?(i=Z,ms++):(i=n,0===bs&&Os(ee)),i===n&&(37===e.charCodeAt(ms)?(i=he,ms++):(i=n,0===bs&&Os(pe)),i===n&&(42===e.charCodeAt(ms)?(i=ne,ms++):(i=n,0===bs&&Os(ie)),i===n&&(95===e.charCodeAt(ms)?(i=$,ms++):(i=n,0===bs&&Os(X)),i===n&&(43===e.charCodeAt(ms)?(i=F,ms++):(i=n,0===bs&&Os(B)),i===n&&(96===e.charCodeAt(ms)?(i=Se,ms++):(i=n,0===bs&&Os(Te)),i===n&&(39===e.charCodeAt(ms)?(i=oe,ms++):(i=n,0===bs&&Os(se)),i===n&&(126===e.charCodeAt(ms)?(i=te,ms++):(i=n,0===bs&&Os(re))))))))))));else r=n;return t=r!==n?e.substring(t,ms):r}function Js(){var t,r,i;if(t=ms,r=[],(i=Ls())===n&&(45===e.charCodeAt(ms)?(i=V,ms++):(i=n,0===bs&&Os(Y)),i===n&&(33===e.charCodeAt(ms)?(i=Z,ms++):(i=n,0===bs&&Os(ee)),i===n&&(37===e.charCodeAt(ms)?(i=he,ms++):(i=n,0===bs&&Os(pe)),i===n&&(42===e.charCodeAt(ms)?(i=ne,ms++):(i=n,0===bs&&Os(ie)),i===n&&(95===e.charCodeAt(ms)?(i=$,ms++):(i=n,0===bs&&Os(X)),i===n&&(43===e.charCodeAt(ms)?(i=F,ms++):(i=n,0===bs&&Os(B)),i===n&&(96===e.charCodeAt(ms)?(i=Se,ms++):(i=n,0===bs&&Os(Te)),i===n&&(39===e.charCodeAt(ms)?(i=oe,ms++):(i=n,0===bs&&Os(se)),i===n&&(126===e.charCodeAt(ms)?(i=te,ms++):(i=n,0===bs&&Os(re))))))))))),i!==n)for(;i!==n;)r.push(i),(i=Ls())===n&&(45===e.charCodeAt(ms)?(i=V,ms++):(i=n,0===bs&&Os(Y)),i===n&&(33===e.charCodeAt(ms)?(i=Z,ms++):(i=n,0===bs&&Os(ee)),i===n&&(37===e.charCodeAt(ms)?(i=he,ms++):(i=n,0===bs&&Os(pe)),i===n&&(42===e.charCodeAt(ms)?(i=ne,ms++):(i=n,0===bs&&Os(ie)),i===n&&(95===e.charCodeAt(ms)?(i=$,ms++):(i=n,0===bs&&Os(X)),i===n&&(43===e.charCodeAt(ms)?(i=F,ms++):(i=n,0===bs&&Os(B)),i===n&&(96===e.charCodeAt(ms)?(i=Se,ms++):(i=n,0===bs&&Os(Te)),i===n&&(39===e.charCodeAt(ms)?(i=oe,ms++):(i=n,0===bs&&Os(se)),i===n&&(126===e.charCodeAt(ms)?(i=te,ms++):(i=n,0===bs&&Os(re)))))))))));else r=n;return t=r!==n?e.substring(t,ms):r}function Qs(){var t,r,i;if(t=ms,r=[],(i=Ls())===n&&(45===e.charCodeAt(ms)?(i=V,ms++):(i=n,0===bs&&Os(Y)),i===n&&(46===e.charCodeAt(ms)?(i=J,ms++):(i=n,0===bs&&Os(Q)),i===n&&(33===e.charCodeAt(ms)?(i=Z,ms++):(i=n,0===bs&&Os(ee)),i===n&&(37===e.charCodeAt(ms)?(i=he,ms++):(i=n,0===bs&&Os(pe)),i===n&&(42===e.charCodeAt(ms)?(i=ne,ms++):(i=n,0===bs&&Os(ie)),i===n&&(95===e.charCodeAt(ms)?(i=$,ms++):(i=n,0===bs&&Os(X)),i===n&&(43===e.charCodeAt(ms)?(i=F,ms++):(i=n,0===bs&&Os(B)),i===n&&(96===e.charCodeAt(ms)?(i=Se,ms++):(i=n,0===bs&&Os(Te)),i===n&&(39===e.charCodeAt(ms)?(i=oe,ms++):(i=n,0===bs&&Os(se)),i===n&&(126===e.charCodeAt(ms)?(i=te,ms++):(i=n,0===bs&&Os(re)),i===n&&(40===e.charCodeAt(ms)?(i=ae,ms++):(i=n,0===bs&&Os(ce)),i===n&&(41===e.charCodeAt(ms)?(i=ue,ms++):(i=n,0===bs&&Os(de)),i===n&&(60===e.charCodeAt(ms)?(i=Ce,ms++):(i=n,0===bs&&Os(be)),i===n&&(62===e.charCodeAt(ms)?(i=_e,ms++):(i=n,0===bs&&Os(Ae)),i===n&&(58===e.charCodeAt(ms)?(i=D,ms++):(i=n,0===bs&&Os(U)),i===n&&(92===e.charCodeAt(ms)?(i=we,ms++):(i=n,0===bs&&Os(Ee)),i===n&&(i=Ms())===n&&(47===e.charCodeAt(ms)?(i=O,ms++):(i=n,0===bs&&Os(x)),i===n&&(91===e.charCodeAt(ms)?(i=Re,ms++):(i=n,0===bs&&Os(Ie)),i===n&&(93===e.charCodeAt(ms)?(i=Oe,ms++):(i=n,0===bs&&Os(xe)),i===n&&(63===e.charCodeAt(ms)?(i=P,ms++):(i=n,0===bs&&Os(N)),i===n&&(123===e.charCodeAt(ms)?(i=Pe,ms++):(i=n,0===bs&&Os(Ne)),i===n&&(125===e.charCodeAt(ms)?(i=De,ms++):(i=n,0===bs&&Os(Ue)))))))))))))))))))))))),i!==n)for(;i!==n;)r.push(i),(i=Ls())===n&&(45===e.charCodeAt(ms)?(i=V,ms++):(i=n,0===bs&&Os(Y)),i===n&&(46===e.charCodeAt(ms)?(i=J,ms++):(i=n,0===bs&&Os(Q)),i===n&&(33===e.charCodeAt(ms)?(i=Z,ms++):(i=n,0===bs&&Os(ee)),i===n&&(37===e.charCodeAt(ms)?(i=he,ms++):(i=n,0===bs&&Os(pe)),i===n&&(42===e.charCodeAt(ms)?(i=ne,ms++):(i=n,0===bs&&Os(ie)),i===n&&(95===e.charCodeAt(ms)?(i=$,ms++):(i=n,0===bs&&Os(X)),i===n&&(43===e.charCodeAt(ms)?(i=F,ms++):(i=n,0===bs&&Os(B)),i===n&&(96===e.charCodeAt(ms)?(i=Se,ms++):(i=n,0===bs&&Os(Te)),i===n&&(39===e.charCodeAt(ms)?(i=oe,ms++):(i=n,0===bs&&Os(se)),i===n&&(126===e.charCodeAt(ms)?(i=te,ms++):(i=n,0===bs&&Os(re)),i===n&&(40===e.charCodeAt(ms)?(i=ae,ms++):(i=n,0===bs&&Os(ce)),i===n&&(41===e.charCodeAt(ms)?(i=ue,ms++):(i=n,0===bs&&Os(de)),i===n&&(60===e.charCodeAt(ms)?(i=Ce,ms++):(i=n,0===bs&&Os(be)),i===n&&(62===e.charCodeAt(ms)?(i=_e,ms++):(i=n,0===bs&&Os(Ae)),i===n&&(58===e.charCodeAt(ms)?(i=D,ms++):(i=n,0===bs&&Os(U)),i===n&&(92===e.charCodeAt(ms)?(i=we,ms++):(i=n,0===bs&&Os(Ee)),i===n&&(i=Ms())===n&&(47===e.charCodeAt(ms)?(i=O,ms++):(i=n,0===bs&&Os(x)),i===n&&(91===e.charCodeAt(ms)?(i=Re,ms++):(i=n,0===bs&&Os(Ie)),i===n&&(93===e.charCodeAt(ms)?(i=Oe,ms++):(i=n,0===bs&&Os(xe)),i===n&&(63===e.charCodeAt(ms)?(i=P,ms++):(i=n,0===bs&&Os(N)),i===n&&(123===e.charCodeAt(ms)?(i=Pe,ms++):(i=n,0===bs&&Os(Ne)),i===n&&(125===e.charCodeAt(ms)?(i=De,ms++):(i=n,0===bs&&Os(Ue))))))))))))))))))))))));else r=n;return t=r!==n?e.substring(t,ms):r}function Zs(){var t,r;return t=ms,Ks()!==n?(47===e.charCodeAt(ms)?(r=O,ms++):(r=n,0===bs&&Os(x)),r!==n&&Ks()!==n?(ys=t,t=ke()):(ms=t,t=n)):(ms=t,t=n),t}function ea(){var t,r;return t=ms,Ks()!==n?(61===e.charCodeAt(ms)?(r=j,ms++):(r=n,0===bs&&Os(L)),r!==n&&Ks()!==n?(ys=t,t=Me()):(ms=t,t=n)):(ms=t,t=n),t}function ta(){var t,r;return t=ms,62===e.charCodeAt(ms)?(r=_e,ms++):(r=n,0===bs&&Os(Ae)),r!==n&&Ks()!==n?(ys=t,t=r=qe()):(ms=t,t=n),t}function ra(){var t,r;return t=ms,Ks()!==n?(60===e.charCodeAt(ms)?(r=Ce,ms++):(r=n,0===bs&&Os(be)),r!==n?(ys=t,t=je()):(ms=t,t=n)):(ms=t,t=n),t}function na(){var t,r;return t=ms,Ks()!==n?(44===e.charCodeAt(ms)?(r=z,ms++):(r=n,0===bs&&Os(K)),r!==n&&Ks()!==n?(ys=t,t=Le()):(ms=t,t=n)):(ms=t,t=n),t}function ia(){var t,r;return t=ms,Ks()!==n?(59===e.charCodeAt(ms)?(r=R,ms++):(r=n,0===bs&&Os(I)),r!==n&&Ks()!==n?(ys=t,t=Fe()):(ms=t,t=n)):(ms=t,t=n),t}function oa(){var e;return e=ms,Ks()!==n&&Ms()!==n?(ys=e,e=Ge()):(ms=e,e=n),e}function sa(){var e;return e=ms,Ms()!==n&&Ks()!==n?(ys=e,e=Ge()):(ms=e,e=n),e}function aa(){var t,r,i,o,s,a;if(t=ms,r=ms,(i=Ks())!==n)if((o=Ms())!==n){for(s=[],(a=ua())===n&&(a=da());a!==n;)s.push(a),(a=ua())===n&&(a=da());s!==n&&(a=Ms())!==n?r=i=[i,o,s,a]:(ms=r,r=n)}else ms=r,r=n;else ms=r,r=n;return t=r!==n?e.substring(t,ms):r}function ca(){var t,r,i,o;if(t=ms,Ks()!==n)if(Ms()!==n){for(r=ms,i=[],(o=ua())===n&&(o=da());o!==n;)i.push(o),(o=ua())===n&&(o=da());(r=i!==n?e.substring(r,ms):i)!==n&&(i=Ms())!==n?(ys=t,t=Ke(r)):(ms=t,t=n)}else ms=t,t=n;else ms=t,t=n;return t}function ua(){var t;return(t=zs())===n&&(33===e.charCodeAt(ms)?(t=Z,ms++):(t=n,0===bs&&Os(ee)),t===n&&(Ve.test(e.charAt(ms))?(t=e.charAt(ms),ms++):(t=n,0===bs&&Os(Ye)),t===n&&(We.test(e.charAt(ms))?(t=e.charAt(ms),ms++):(t=n,0===bs&&Os(ze)),t===n&&(t=Ys())))),t}function da(){var t,r,i;return t=ms,92===e.charCodeAt(ms)?(r=we,ms++):(r=n,0===bs&&Os(Ee)),r!==n?($e.test(e.charAt(ms))?(i=e.charAt(ms),ms++):(i=n,0===bs&&Os(Xe)),i===n&&(Je.test(e.charAt(ms))?(i=e.charAt(ms),ms++):(i=n,0===bs&&Os(Qe)),i===n&&(Ze.test(e.charAt(ms))?(i=e.charAt(ms),ms++):(i=n,0===bs&&Os(et)))),i!==n?t=r=[r,i]:(ms=t,t=n)):(ms=t,t=n),t}function ha(){var t,r,i;return t=ms,la()!==n?(58===e.charCodeAt(ms)?(r=D,ms++):(r=n,0===bs&&Os(U)),r!==n?((i=fa())===n&&(i=null),i!==n&&va()!==n?(ys=t,t=tt()):(ms=t,t=n)):(ms=t,t=n)):(ms=t,t=n),t}function pa(){var t,r,i,o;return t=ms,la()!==n?(58===e.charCodeAt(ms)?(r=D,ms++):(r=n,0===bs&&Os(U)),r!==n?((i=fa())===n&&(i=null),i!==n&&va()!==n&&function(){var t,r,i,o;for(t=[],r=ms,59===e.charCodeAt(ms)?(i=R,ms++):(i=n,0===bs&&Os(I)),i!==n&&(o=Ra())!==n?r=i=[i,o]:(ms=r,r=n);r!==n;)t.push(r),r=ms,59===e.charCodeAt(ms)?(i=R,ms++):(i=n,0===bs&&Os(I)),i!==n&&(o=Ra())!==n?r=i=[i,o]:(ms=r,r=n);return t}()!==n?((o=function(){var t,r,i,o,s,a,c;if(t=ms,63===e.charCodeAt(ms)?(r=P,ms++):(r=n,0===bs&&Os(N)),r!==n)if((i=Oa())!==n){for(o=[],s=ms,38===e.charCodeAt(ms)?(a=M,ms++):(a=n,0===bs&&Os(q)),a!==n&&(c=Oa())!==n?s=a=[a,c]:(ms=s,s=n);s!==n;)o.push(s),s=ms,38===e.charCodeAt(ms)?(a=M,ms++):(a=n,0===bs&&Os(q)),a!==n&&(c=Oa())!==n?s=a=[a,c]:(ms=s,s=n);o!==n?t=r=[r,i,o]:(ms=t,t=n)}else ms=t,t=n;else ms=t,t=n;return t}())===n&&(o=null),o!==n?(ys=t,t=rt()):(ms=t,t=n)):(ms=t,t=n)):(ms=t,t=n)):(ms=t,t=n),t}function la(){var t,r;return t=ms,e.substr(ms,4).toLowerCase()===nt?(r=e.substr(ms,4),ms+=4):(r=n,0===bs&&Os(it)),r===n&&(e.substr(ms,3).toLowerCase()===ot?(r=e.substr(ms,3),ms+=3):(r=n,0===bs&&Os(st))),r!==n&&(ys=t,r=at(r)),t=r}function fa(){var t,r,i,o;return t=ms,function(){var e,t;if(e=[],(t=Bs())===n&&(t=Ws())===n&&(t=ga()),t!==n)for(;t!==n;)e.push(t),(t=Bs())===n&&(t=Ws())===n&&(t=ga());else e=n;return e}()!==n?(r=ms,58===e.charCodeAt(ms)?(i=D,ms++):(i=n,0===bs&&Os(U)),i!==n&&(o=function(){var t,r,i;for(t=ms,r=[],(i=Bs())===n&&(i=Ws())===n&&(38===e.charCodeAt(ms)?(i=M,ms++):(i=n,0===bs&&Os(q)),i===n&&(61===e.charCodeAt(ms)?(i=j,ms++):(i=n,0===bs&&Os(L)),i===n&&(43===e.charCodeAt(ms)?(i=F,ms++):(i=n,0===bs&&Os(B)),i===n&&(36===e.charCodeAt(ms)?(i=G,ms++):(i=n,0===bs&&Os(W)),i===n&&(44===e.charCodeAt(ms)?(i=z,ms++):(i=n,0===bs&&Os(K)))))));i!==n;)r.push(i),(i=Bs())===n&&(i=Ws())===n&&(38===e.charCodeAt(ms)?(i=M,ms++):(i=n,0===bs&&Os(q)),i===n&&(61===e.charCodeAt(ms)?(i=j,ms++):(i=n,0===bs&&Os(L)),i===n&&(43===e.charCodeAt(ms)?(i=F,ms++):(i=n,0===bs&&Os(B)),i===n&&(36===e.charCodeAt(ms)?(i=G,ms++):(i=n,0===bs&&Os(W)),i===n&&(44===e.charCodeAt(ms)?(i=z,ms++):(i=n,0===bs&&Os(K)))))));return r!==n&&(ys=t,r=ut()),t=r}())!==n?r=i=[i,o]:(ms=r,r=n),r===n&&(r=null),r!==n?(64===e.charCodeAt(ms)?(i=H,ms++):(i=n,0===bs&&Os(k)),i!==n?(ys=t,t=ct()):(ms=t,t=n)):(ms=t,t=n)):(ms=t,t=n),t}function ga(){var t;return 38===e.charCodeAt(ms)?(t=M,ms++):(t=n,0===bs&&Os(q)),t===n&&(61===e.charCodeAt(ms)?(t=j,ms++):(t=n,0===bs&&Os(L)),t===n&&(43===e.charCodeAt(ms)?(t=F,ms++):(t=n,0===bs&&Os(B)),t===n&&(36===e.charCodeAt(ms)?(t=G,ms++):(t=n,0===bs&&Os(W)),t===n&&(44===e.charCodeAt(ms)?(t=z,ms++):(t=n,0===bs&&Os(K)),t===n&&(59===e.charCodeAt(ms)?(t=R,ms++):(t=n,0===bs&&Os(I)),t===n&&(63===e.charCodeAt(ms)?(t=P,ms++):(t=n,0===bs&&Os(N)),t===n&&(47===e.charCodeAt(ms)?(t=O,ms++):(t=n,0===bs&&Os(x))))))))),t}function va(){var t,r,i,o,s;return t=ms,(r=ma())!==n?(i=ms,58===e.charCodeAt(ms)?(o=D,ms++):(o=n,0===bs&&Os(U)),o!==n&&(s=Ea())!==n?i=o=[o,s]:(ms=i,i=n),i===n&&(i=null),i!==n?t=r=[r,i]:(ms=t,t=n)):(ms=t,t=n),t}function ma(){var e,t;return e=ms,(t=ya())===n&&(t=Aa())===n&&(t=Ta()),t!==n&&(ys=e,t=dt()),e=t}function ya(){var t,r,i,o,s;for(t=ms,r=[],i=ms,(o=Sa())!==n?(46===e.charCodeAt(ms)?(s=J,ms++):(s=n,0===bs&&Os(Q)),s!==n?i=o=[o,s]:(ms=i,i=n)):(ms=i,i=n);i!==n;)r.push(i),i=ms,(o=Sa())!==n?(46===e.charCodeAt(ms)?(s=J,ms++):(s=n,0===bs&&Os(Q)),s!==n?i=o=[o,s]:(ms=i,i=n)):(ms=i,i=n);return r!==n&&(i=function(){var t,r,i,o;if(t=ms,l.test(e.charAt(ms))?(r=e.charAt(ms),ms++):(r=n,0===bs&&Os(f)),r!==n){for(i=[],ft.test(e.charAt(ms))?(o=e.charAt(ms),ms++):(o=n,0===bs&&Os(gt));o!==n;)i.push(o),ft.test(e.charAt(ms))?(o=e.charAt(ms),ms++):(o=n,0===bs&&Os(gt));i!==n?t=r=[r,i]:(ms=t,t=n)}else ms=t,t=n;return t}())!==n?(46===e.charCodeAt(ms)?(o=J,ms++):(o=n,0===bs&&Os(Q)),o===n&&(o=null),o!==n?(ys=t,t=r=ht()):(ms=t,t=n)):(ms=t,t=n),t}function Sa(){var t,r;if(t=[],pt.test(e.charAt(ms))?(r=e.charAt(ms),ms++):(r=n,0===bs&&Os(lt)),r!==n)for(;r!==n;)t.push(r),pt.test(e.charAt(ms))?(r=e.charAt(ms),ms++):(r=n,0===bs&&Os(lt));else t=n;return t}function Ta(){var t,r,i;return t=ms,91===e.charCodeAt(ms)?(r=Re,ms++):(r=n,0===bs&&Os(Ie)),r!==n&&Ca()!==n?(93===e.charCodeAt(ms)?(i=Oe,ms++):(i=n,0===bs&&Os(xe)),i!==n?(ys=t,t=r=vt()):(ms=t,t=n)):(ms=t,t=n),t}function Ca(){var t,r,i,o,s,a,c,u,d,h,p,l,f,g,v;return t=ms,r=ms,(i=ba())!==n?(58===e.charCodeAt(ms)?(o=D,ms++):(o=n,0===bs&&Os(U)),o!==n&&(s=ba())!==n?(58===e.charCodeAt(ms)?(a=D,ms++):(a=n,0===bs&&Os(U)),a!==n&&(c=ba())!==n?(58===e.charCodeAt(ms)?(u=D,ms++):(u=n,0===bs&&Os(U)),u!==n&&(d=ba())!==n?(58===e.charCodeAt(ms)?(h=D,ms++):(h=n,0===bs&&Os(U)),h!==n&&(p=ba())!==n?(58===e.charCodeAt(ms)?(l=D,ms++):(l=n,0===bs&&Os(U)),l!==n&&(f=ba())!==n?(58===e.charCodeAt(ms)?(g=D,ms++):(g=n,0===bs&&Os(U)),g!==n&&(v=_a())!==n?r=i=[i,o,s,a,c,u,d,h,p,l,f,g,v]:(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n),r===n&&(r=ms,e.substr(ms,2)===mt?(i=mt,ms+=2):(i=n,0===bs&&Os(yt)),i!==n&&(o=ba())!==n?(58===e.charCodeAt(ms)?(s=D,ms++):(s=n,0===bs&&Os(U)),s!==n&&(a=ba())!==n?(58===e.charCodeAt(ms)?(c=D,ms++):(c=n,0===bs&&Os(U)),c!==n&&(u=ba())!==n?(58===e.charCodeAt(ms)?(d=D,ms++):(d=n,0===bs&&Os(U)),d!==n&&(h=ba())!==n?(58===e.charCodeAt(ms)?(p=D,ms++):(p=n,0===bs&&Os(U)),p!==n&&(l=ba())!==n?(58===e.charCodeAt(ms)?(f=D,ms++):(f=n,0===bs&&Os(U)),f!==n&&(g=_a())!==n?r=i=[i,o,s,a,c,u,d,h,p,l,f,g]:(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n),r===n&&(r=ms,e.substr(ms,2)===mt?(i=mt,ms+=2):(i=n,0===bs&&Os(yt)),i!==n&&(o=ba())!==n?(58===e.charCodeAt(ms)?(s=D,ms++):(s=n,0===bs&&Os(U)),s!==n&&(a=ba())!==n?(58===e.charCodeAt(ms)?(c=D,ms++):(c=n,0===bs&&Os(U)),c!==n&&(u=ba())!==n?(58===e.charCodeAt(ms)?(d=D,ms++):(d=n,0===bs&&Os(U)),d!==n&&(h=ba())!==n?(58===e.charCodeAt(ms)?(p=D,ms++):(p=n,0===bs&&Os(U)),p!==n&&(l=_a())!==n?r=i=[i,o,s,a,c,u,d,h,p,l]:(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n),r===n&&(r=ms,e.substr(ms,2)===mt?(i=mt,ms+=2):(i=n,0===bs&&Os(yt)),i!==n&&(o=ba())!==n?(58===e.charCodeAt(ms)?(s=D,ms++):(s=n,0===bs&&Os(U)),s!==n&&(a=ba())!==n?(58===e.charCodeAt(ms)?(c=D,ms++):(c=n,0===bs&&Os(U)),c!==n&&(u=ba())!==n?(58===e.charCodeAt(ms)?(d=D,ms++):(d=n,0===bs&&Os(U)),d!==n&&(h=_a())!==n?r=i=[i,o,s,a,c,u,d,h]:(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n),r===n&&(r=ms,e.substr(ms,2)===mt?(i=mt,ms+=2):(i=n,0===bs&&Os(yt)),i!==n&&(o=ba())!==n?(58===e.charCodeAt(ms)?(s=D,ms++):(s=n,0===bs&&Os(U)),s!==n&&(a=ba())!==n?(58===e.charCodeAt(ms)?(c=D,ms++):(c=n,0===bs&&Os(U)),c!==n&&(u=_a())!==n?r=i=[i,o,s,a,c,u]:(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n),r===n&&(r=ms,e.substr(ms,2)===mt?(i=mt,ms+=2):(i=n,0===bs&&Os(yt)),i!==n&&(o=ba())!==n?(58===e.charCodeAt(ms)?(s=D,ms++):(s=n,0===bs&&Os(U)),s!==n&&(a=_a())!==n?r=i=[i,o,s,a]:(ms=r,r=n)):(ms=r,r=n),r===n&&(r=ms,e.substr(ms,2)===mt?(i=mt,ms+=2):(i=n,0===bs&&Os(yt)),i!==n&&(o=_a())!==n?r=i=[i,o]:(ms=r,r=n),r===n&&(r=ms,e.substr(ms,2)===mt?(i=mt,ms+=2):(i=n,0===bs&&Os(yt)),i!==n&&(o=ba())!==n?r=i=[i,o]:(ms=r,r=n),r===n&&(r=ms,(i=ba())!==n?(e.substr(ms,2)===mt?(o=mt,ms+=2):(o=n,0===bs&&Os(yt)),o!==n&&(s=ba())!==n?(58===e.charCodeAt(ms)?(a=D,ms++):(a=n,0===bs&&Os(U)),a!==n&&(c=ba())!==n?(58===e.charCodeAt(ms)?(u=D,ms++):(u=n,0===bs&&Os(U)),u!==n&&(d=ba())!==n?(58===e.charCodeAt(ms)?(h=D,ms++):(h=n,0===bs&&Os(U)),h!==n&&(p=ba())!==n?(58===e.charCodeAt(ms)?(l=D,ms++):(l=n,0===bs&&Os(U)),l!==n&&(f=_a())!==n?r=i=[i,o,s,a,c,u,d,h,p,l,f]:(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n),r===n&&(r=ms,(i=ba())!==n?(o=ms,58===e.charCodeAt(ms)?(s=D,ms++):(s=n,0===bs&&Os(U)),s!==n&&(a=ba())!==n?o=s=[s,a]:(ms=o,o=n),o===n&&(o=null),o!==n?(e.substr(ms,2)===mt?(s=mt,ms+=2):(s=n,0===bs&&Os(yt)),s!==n&&(a=ba())!==n?(58===e.charCodeAt(ms)?(c=D,ms++):(c=n,0===bs&&Os(U)),c!==n&&(u=ba())!==n?(58===e.charCodeAt(ms)?(d=D,ms++):(d=n,0===bs&&Os(U)),d!==n&&(h=ba())!==n?(58===e.charCodeAt(ms)?(p=D,ms++):(p=n,0===bs&&Os(U)),p!==n&&(l=_a())!==n?r=i=[i,o,s,a,c,u,d,h,p,l]:(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n),r===n&&(r=ms,(i=ba())!==n?(o=ms,58===e.charCodeAt(ms)?(s=D,ms++):(s=n,0===bs&&Os(U)),s!==n&&(a=ba())!==n?o=s=[s,a]:(ms=o,o=n),o===n&&(o=null),o!==n?(s=ms,58===e.charCodeAt(ms)?(a=D,ms++):(a=n,0===bs&&Os(U)),a!==n&&(c=ba())!==n?s=a=[a,c]:(ms=s,s=n),s===n&&(s=null),s!==n?(e.substr(ms,2)===mt?(a=mt,ms+=2):(a=n,0===bs&&Os(yt)),a!==n&&(c=ba())!==n?(58===e.charCodeAt(ms)?(u=D,ms++):(u=n,0===bs&&Os(U)),u!==n&&(d=ba())!==n?(58===e.charCodeAt(ms)?(h=D,ms++):(h=n,0===bs&&Os(U)),h!==n&&(p=_a())!==n?r=i=[i,o,s,a,c,u,d,h,p]:(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n),r===n&&(r=ms,(i=ba())!==n?(o=ms,58===e.charCodeAt(ms)?(s=D,ms++):(s=n,0===bs&&Os(U)),s!==n&&(a=ba())!==n?o=s=[s,a]:(ms=o,o=n),o===n&&(o=null),o!==n?(s=ms,58===e.charCodeAt(ms)?(a=D,ms++):(a=n,0===bs&&Os(U)),a!==n&&(c=ba())!==n?s=a=[a,c]:(ms=s,s=n),s===n&&(s=null),s!==n?(a=ms,58===e.charCodeAt(ms)?(c=D,ms++):(c=n,0===bs&&Os(U)),c!==n&&(u=ba())!==n?a=c=[c,u]:(ms=a,a=n),a===n&&(a=null),a!==n?(e.substr(ms,2)===mt?(c=mt,ms+=2):(c=n,0===bs&&Os(yt)),c!==n&&(u=ba())!==n?(58===e.charCodeAt(ms)?(d=D,ms++):(d=n,0===bs&&Os(U)),d!==n&&(h=_a())!==n?r=i=[i,o,s,a,c,u,d,h]:(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n),r===n&&(r=ms,(i=ba())!==n?(o=ms,58===e.charCodeAt(ms)?(s=D,ms++):(s=n,0===bs&&Os(U)),s!==n&&(a=ba())!==n?o=s=[s,a]:(ms=o,o=n),o===n&&(o=null),o!==n?(s=ms,58===e.charCodeAt(ms)?(a=D,ms++):(a=n,0===bs&&Os(U)),a!==n&&(c=ba())!==n?s=a=[a,c]:(ms=s,s=n),s===n&&(s=null),s!==n?(a=ms,58===e.charCodeAt(ms)?(c=D,ms++):(c=n,0===bs&&Os(U)),c!==n&&(u=ba())!==n?a=c=[c,u]:(ms=a,a=n),a===n&&(a=null),a!==n?(c=ms,58===e.charCodeAt(ms)?(u=D,ms++):(u=n,0===bs&&Os(U)),u!==n&&(d=ba())!==n?c=u=[u,d]:(ms=c,c=n),c===n&&(c=null),c!==n?(e.substr(ms,2)===mt?(u=mt,ms+=2):(u=n,0===bs&&Os(yt)),u!==n&&(d=_a())!==n?r=i=[i,o,s,a,c,u,d]:(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n),r===n&&(r=ms,(i=ba())!==n?(o=ms,58===e.charCodeAt(ms)?(s=D,ms++):(s=n,0===bs&&Os(U)),s!==n&&(a=ba())!==n?o=s=[s,a]:(ms=o,o=n),o===n&&(o=null),o!==n?(s=ms,58===e.charCodeAt(ms)?(a=D,ms++):(a=n,0===bs&&Os(U)),a!==n&&(c=ba())!==n?s=a=[a,c]:(ms=s,s=n),s===n&&(s=null),s!==n?(a=ms,58===e.charCodeAt(ms)?(c=D,ms++):(c=n,0===bs&&Os(U)),c!==n&&(u=ba())!==n?a=c=[c,u]:(ms=a,a=n),a===n&&(a=null),a!==n?(c=ms,58===e.charCodeAt(ms)?(u=D,ms++):(u=n,0===bs&&Os(U)),u!==n&&(d=ba())!==n?c=u=[u,d]:(ms=c,c=n),c===n&&(c=null),c!==n?(u=ms,58===e.charCodeAt(ms)?(d=D,ms++):(d=n,0===bs&&Os(U)),d!==n&&(h=ba())!==n?u=d=[d,h]:(ms=u,u=n),u===n&&(u=null),u!==n?(e.substr(ms,2)===mt?(d=mt,ms+=2):(d=n,0===bs&&Os(yt)),d!==n&&(h=ba())!==n?r=i=[i,o,s,a,c,u,d,h]:(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n),r===n&&(r=ms,(i=ba())!==n?(o=ms,58===e.charCodeAt(ms)?(s=D,ms++):(s=n,0===bs&&Os(U)),s!==n&&(a=ba())!==n?o=s=[s,a]:(ms=o,o=n),o===n&&(o=null),o!==n?(s=ms,58===e.charCodeAt(ms)?(a=D,ms++):(a=n,0===bs&&Os(U)),a!==n&&(c=ba())!==n?s=a=[a,c]:(ms=s,s=n),s===n&&(s=null),s!==n?(a=ms,58===e.charCodeAt(ms)?(c=D,ms++):(c=n,0===bs&&Os(U)),c!==n&&(u=ba())!==n?a=c=[c,u]:(ms=a,a=n),a===n&&(a=null),a!==n?(c=ms,58===e.charCodeAt(ms)?(u=D,ms++):(u=n,0===bs&&Os(U)),u!==n&&(d=ba())!==n?c=u=[u,d]:(ms=c,c=n),c===n&&(c=null),c!==n?(u=ms,58===e.charCodeAt(ms)?(d=D,ms++):(d=n,0===bs&&Os(U)),d!==n&&(h=ba())!==n?u=d=[d,h]:(ms=u,u=n),u===n&&(u=null),u!==n?(d=ms,58===e.charCodeAt(ms)?(h=D,ms++):(h=n,0===bs&&Os(U)),h!==n&&(p=ba())!==n?d=h=[h,p]:(ms=d,d=n),d===n&&(d=null),d!==n?(e.substr(ms,2)===mt?(h=mt,ms+=2):(h=n,0===bs&&Os(yt)),h!==n?r=i=[i,o,s,a,c,u,d,h]:(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n)):(ms=r,r=n))))))))))))))),r!==n&&(ys=t,r=St()),t=r}function ba(){var e,t,r,i,o;return e=ms,(t=Us())!==n?((r=Us())===n&&(r=null),r!==n?((i=Us())===n&&(i=null),i!==n?((o=Us())===n&&(o=null),o!==n?e=t=[t,r,i,o]:(ms=e,e=n)):(ms=e,e=n)):(ms=e,e=n)):(ms=e,e=n),e}function _a(){var t,r,i,o;return t=ms,(r=ba())!==n?(58===e.charCodeAt(ms)?(i=D,ms++):(i=n,0===bs&&Os(U)),i!==n&&(o=ba())!==n?t=r=[r,i,o]:(ms=t,t=n)):(ms=t,t=n),t===n&&(t=Aa()),t}function Aa(){var t,r,i,o;return t=ms,wa()!==n?(46===e.charCodeAt(ms)?(r=J,ms++):(r=n,0===bs&&Os(Q)),r!==n&&wa()!==n?(46===e.charCodeAt(ms)?(i=J,ms++):(i=n,0===bs&&Os(Q)),i!==n&&wa()!==n?(46===e.charCodeAt(ms)?(o=J,ms++):(o=n,0===bs&&Os(Q)),o!==n&&wa()!==n?(ys=t,t=Tt()):(ms=t,t=n)):(ms=t,t=n)):(ms=t,t=n)):(ms=t,t=n),t}function wa(){var t,r,i,o;return t=ms,e.substr(ms,2)===Ct?(r=Ct,ms+=2):(r=n,0===bs&&Os(bt)),r!==n?(_t.test(e.charAt(ms))?(i=e.charAt(ms),ms++):(i=n,0===bs&&Os(At)),i!==n?t=r=[r,i]:(ms=t,t=n)):(ms=t,t=n),t===n&&(t=ms,50===e.charCodeAt(ms)?(r=wt,ms++):(r=n,0===bs&&Os(Et)),r!==n?(Rt.test(e.charAt(ms))?(i=e.charAt(ms),ms++):(i=n,0===bs&&Os(It)),i!==n&&(o=Ns())!==n?t=r=[r,i,o]:(ms=t,t=n)):(ms=t,t=n),t===n&&(t=ms,49===e.charCodeAt(ms)?(r=Ot,ms++):(r=n,0===bs&&Os(xt)),r!==n&&(i=Ns())!==n&&(o=Ns())!==n?t=r=[r,i,o]:(ms=t,t=n),t===n&&(t=ms,Pt.test(e.charAt(ms))?(r=e.charAt(ms),ms++):(r=n,0===bs&&Os(Nt)),r!==n&&(i=Ns())!==n?t=r=[r,i]:(ms=t,t=n),t===n&&(t=Ns())))),t}function Ea(){var e,t,r,i,o,s,a;return e=ms,t=ms,(r=Ns())===n&&(r=null),r!==n?((i=Ns())===n&&(i=null),i!==n?((o=Ns())===n&&(o=null),o!==n?((s=Ns())===n&&(s=null),s!==n?((a=Ns())===n&&(a=null),a!==n?t=r=[r,i,o,s,a]:(ms=t,t=n)):(ms=t,t=n)):(ms=t,t=n)):(ms=t,t=n)):(ms=t,t=n),t!==n&&(ys=e,t=Dt(t)),e=t}function Ra(){var t;return(t=function(){var t,r,i;return t=ms,e.substr(ms,10).toLowerCase()===Ut?(r=e.substr(ms,10),ms+=10):(r=n,0===bs&&Os(Ht)),r!==n?(e.substr(ms,3).toLowerCase()===kt?(i=e.substr(ms,3),ms+=3):(i=n,0===bs&&Os(Mt)),i===n&&(e.substr(ms,3).toLowerCase()===qt?(i=e.substr(ms,3),ms+=3):(i=n,0===bs&&Os(jt)),i===n&&(e.substr(ms,4).toLowerCase()===Lt?(i=e.substr(ms,4),ms+=4):(i=n,0===bs&&Os(Ft)),i===n&&(e.substr(ms,3).toLowerCase()===Bt?(i=e.substr(ms,3),ms+=3):(i=n,0===bs&&Os(Gt)),i===n&&(i=Xs())))),i!==n?(ys=t,r=Wt(i),t=r):(ms=t,t=n)):(ms=t,t=n),t}())===n&&(t=function(){var t,r,i;return t=ms,e.substr(ms,5).toLowerCase()===zt?(r=e.substr(ms,5),ms+=5):(r=n,0===bs&&Os(Kt)),r!==n?(e.substr(ms,5).toLowerCase()===Vt?(i=e.substr(ms,5),ms+=5):(i=n,0===bs&&Os(Yt)),i===n&&(e.substr(ms,2).toLowerCase()===$t?(i=e.substr(ms,2),ms+=2):(i=n,0===bs&&Os(Xt)),i===n&&(i=Xs())),i!==n?(ys=t,r=Jt(i),t=r):(ms=t,t=n)):(ms=t,t=n),t}())===n&&(t=function(){var t,r,i;return t=ms,e.substr(ms,7).toLowerCase()===Qt?(r=e.substr(ms,7),ms+=7):(r=n,0===bs&&Os(Zt)),r!==n&&(i=La())!==n?(ys=t,r=er(i),t=r):(ms=t,t=n),t}())===n&&(t=function(){var t,r,i;return t=ms,e.substr(ms,4).toLowerCase()===tr?(r=e.substr(ms,4),ms+=4):(r=n,0===bs&&Os(rr)),r!==n&&(i=lc())!==n?(ys=t,r=nr(i),t=r):(ms=t,t=n),t}())===n&&(t=function(){var t,r,i;return t=ms,e.substr(ms,6).toLowerCase()===ir?(r=e.substr(ms,6),ms+=6):(r=n,0===bs&&Os(or)),r!==n&&(i=ma())!==n?(ys=t,r=sr(i),t=r):(ms=t,t=n),t}())===n&&(t=function(){var t,r,i,o,s;return t=ms,e.substr(ms,2).toLowerCase()===ar?(r=e.substr(ms,2),ms+=2):(r=n,0===bs&&Os(cr)),r!==n?(i=ms,61===e.charCodeAt(ms)?(o=j,ms++):(o=n,0===bs&&Os(L)),o!==n&&(s=Xs())!==n?i=o=[o,s]:(ms=i,i=n),i===n&&(i=null),i!==n?(ys=t,r=ur(),t=r):(ms=t,t=n)):(ms=t,t=n),t}())===n&&(t=function(){var t,r,i,o,s;return t=ms,(r=function(){var t,r,i;if(t=ms,r=[],(i=Ia())!==n)for(;i!==n;)r.push(i),i=Ia();else r=n;return t=r!==n?e.substring(t,ms):r}())!==n?(i=ms,61===e.charCodeAt(ms)?(o=j,ms++):(o=n,0===bs&&Os(L)),o!==n&&(s=function(){var t,r,i;if(t=ms,r=[],(i=Ia())!==n)for(;i!==n;)r.push(i),i=Ia();else r=n;return t=r!==n?e.substring(t,ms):r}())!==n?i=o=[o,s]:(ms=i,i=n),i===n&&(i=null),i!==n?(ys=t,r=dr(r,i),t=r):(ms=t,t=n)):(ms=t,t=n),t}()),t}function Ia(){var t;return(t=function(){var t;return 91===e.charCodeAt(ms)?(t=Re,ms++):(t=n,0===bs&&Os(Ie)),t===n&&(93===e.charCodeAt(ms)?(t=Oe,ms++):(t=n,0===bs&&Os(xe)),t===n&&(47===e.charCodeAt(ms)?(t=O,ms++):(t=n,0===bs&&Os(x)),t===n&&(58===e.charCodeAt(ms)?(t=D,ms++):(t=n,0===bs&&Os(U)),t===n&&(38===e.charCodeAt(ms)?(t=M,ms++):(t=n,0===bs&&Os(q)),t===n&&(43===e.charCodeAt(ms)?(t=F,ms++):(t=n,0===bs&&Os(B)),t===n&&(36===e.charCodeAt(ms)?(t=G,ms++):(t=n,0===bs&&Os(W)))))))),t}())===n&&(t=Bs())===n&&(t=Ws()),t}function Oa(){var t,r,i,o;return t=ms,(r=function(){var e,t;if(e=[],(t=xa())===n&&(t=Bs())===n&&(t=Ws()),t!==n)for(;t!==n;)e.push(t),(t=xa())===n&&(t=Bs())===n&&(t=Ws());else e=n;return e}())!==n?(61===e.charCodeAt(ms)?(i=j,ms++):(i=n,0===bs&&Os(L)),i!==n&&(o=function(){var e,t;for(e=[],(t=xa())===n&&(t=Bs())===n&&(t=Ws());t!==n;)e.push(t),(t=xa())===n&&(t=Bs())===n&&(t=Ws());return e}())!==n?(ys=t,t=r=hr(r,o)):(ms=t,t=n)):(ms=t,t=n),t}function xa(){var t;return 91===e.charCodeAt(ms)?(t=Re,ms++):(t=n,0===bs&&Os(Ie)),t===n&&(93===e.charCodeAt(ms)?(t=Oe,ms++):(t=n,0===bs&&Os(xe)),t===n&&(47===e.charCodeAt(ms)?(t=O,ms++):(t=n,0===bs&&Os(x)),t===n&&(63===e.charCodeAt(ms)?(t=P,ms++):(t=n,0===bs&&Os(N)),t===n&&(58===e.charCodeAt(ms)?(t=D,ms++):(t=n,0===bs&&Os(U)),t===n&&(43===e.charCodeAt(ms)?(t=F,ms++):(t=n,0===bs&&Os(B)),t===n&&(36===e.charCodeAt(ms)?(t=G,ms++):(t=n,0===bs&&Os(W)))))))),t}function Pa(){var e;return(e=function(){var e,t,r,i,o,s;return e=ms,(t=ja())!==n&&(r=qs())!==n&&(i=function(){var e,t;return e=ms,(t=function(){var e,t,r,i;return e=ms,(t=Ns())!==n&&(r=Ns())!==n&&(i=Ns())!==n?e=t=[t,r,i]:(ms=e,e=n),e}())!==n&&(ys=e,t=jr(t)),e=t}())!==n&&(o=qs())!==n&&(s=function(){var e,t,r;for(e=ms,t=[],(r=Fs())===n&&(r=Bs())===n&&(r=Ws())===n&&(r=Ys())===n&&(r=$s())===n&&(r=qs())===n&&(r=js());r!==n;)t.push(r),(r=Fs())===n&&(r=Bs())===n&&(r=Ws())===n&&(r=Ys())===n&&(r=$s())===n&&(r=qs())===n&&(r=js());return t!==n&&(ys=e,t=Lr()),e=t}())!==n?e=t=[t,r,i,o,s]:(ms=e,e=n),e}())===n&&(e=function(){var e,t,r,i,o,s;return e=ms,(t=La())!==n&&(r=qs())!==n&&(i=function(){var e;return(e=pa())===n&&(e=Na()),e}())!==n&&(o=qs())!==n&&(s=ja())!==n?e=t=[t,r,i,o,s]:(ms=e,e=n),e}()),e}function Na(){var t,r,i;return t=ms,function(){var t,r,i,o,s;if(t=ms,r=ms,(i=Ds())!==n){for(o=[],(s=Ds())===n&&(s=Ns())===n&&(43===e.charCodeAt(ms)?(s=F,ms++):(s=n,0===bs&&Os(B)),s===n&&(45===e.charCodeAt(ms)?(s=V,ms++):(s=n,0===bs&&Os(Y)),s===n&&(46===e.charCodeAt(ms)?(s=J,ms++):(s=n,0===bs&&Os(Q)))));s!==n;)o.push(s),(s=Ds())===n&&(s=Ns())===n&&(43===e.charCodeAt(ms)?(s=F,ms++):(s=n,0===bs&&Os(B)),s===n&&(45===e.charCodeAt(ms)?(s=V,ms++):(s=n,0===bs&&Os(Y)),s===n&&(46===e.charCodeAt(ms)?(s=J,ms++):(s=n,0===bs&&Os(Q)))));o!==n?r=i=[i,o]:(ms=r,r=n)}else ms=r,r=n;return r!==n&&(ys=t,r=gr()),t=r}()!==n?(58===e.charCodeAt(ms)?(r=D,ms++):(r=n,0===bs&&Os(U)),r!==n?((i=function(){var t,r,i,o,s;return t=ms,(r=function(){var t,r,i,o;return t=ms,e.substr(ms,2)===lr?(r=lr,ms+=2):(r=n,0===bs&&Os(fr)),r!==n&&(i=function(){var t;return(t=function(){var t,r,i,o;return t=ms,r=ms,(i=fa())!==n?(64===e.charCodeAt(ms)?(o=H,ms++):(o=n,0===bs&&Os(k)),o!==n?r=i=[i,o]:(ms=r,r=n)):(ms=r,r=n),r===n&&(r=null),r!==n&&(i=va())!==n?t=r=[r,i]:(ms=t,t=n),t===n&&(t=null),t}())===n&&(t=qa()),t}())!==n?((o=Da())===n&&(o=null),o!==n?t=r=[r,i,o]:(ms=t,t=n)):(ms=t,t=n),t}())===n&&(r=Da()),r!==n?(i=ms,63===e.charCodeAt(ms)?(o=P,ms++):(o=n,0===bs&&Os(N)),o!==n&&(s=function(){var e,t;for(e=[],t=Ua();t!==n;)e.push(t),t=Ua();return e}())!==n?i=o=[o,s]:(ms=i,i=n),i===n&&(i=null),i!==n?t=r=[r,i]:(ms=t,t=n)):(ms=t,t=n),t}())===n&&(i=function(){var t,r,i,o;if(t=ms,(r=function(){var t;return(t=Bs())===n&&(t=Ws())===n&&(59===e.charCodeAt(ms)?(t=R,ms++):(t=n,0===bs&&Os(I)),t===n&&(63===e.charCodeAt(ms)?(t=P,ms++):(t=n,0===bs&&Os(N)),t===n&&(58===e.charCodeAt(ms)?(t=D,ms++):(t=n,0===bs&&Os(U)),t===n&&(64===e.charCodeAt(ms)?(t=H,ms++):(t=n,0===bs&&Os(k)),t===n&&(38===e.charCodeAt(ms)?(t=M,ms++):(t=n,0===bs&&Os(q)),t===n&&(61===e.charCodeAt(ms)?(t=j,ms++):(t=n,0===bs&&Os(L)),t===n&&(43===e.charCodeAt(ms)?(t=F,ms++):(t=n,0===bs&&Os(B)),t===n&&(36===e.charCodeAt(ms)?(t=G,ms++):(t=n,0===bs&&Os(W)),t===n&&(44===e.charCodeAt(ms)?(t=z,ms++):(t=n,0===bs&&Os(K))))))))))),t}())!==n){for(i=[],o=Ua();o!==n;)i.push(o),o=Ua();i!==n?t=r=[r,i]:(ms=t,t=n)}else ms=t,t=n;return t}()),i!==n?(ys=t,t=pr()):(ms=t,t=n)):(ms=t,t=n)):(ms=t,t=n),t}function Da(){var t,r,i;return t=ms,47===e.charCodeAt(ms)?(r=O,ms++):(r=n,0===bs&&Os(x)),r!==n&&(i=function(){var t,r,i,o,s,a;if(t=ms,(r=Ha())!==n){for(i=[],o=ms,47===e.charCodeAt(ms)?(s=O,ms++):(s=n,0===bs&&Os(x)),s!==n&&(a=Ha())!==n?o=s=[s,a]:(ms=o,o=n);o!==n;)i.push(o),o=ms,47===e.charCodeAt(ms)?(s=O,ms++):(s=n,0===bs&&Os(x)),s!==n&&(a=Ha())!==n?o=s=[s,a]:(ms=o,o=n);i!==n?t=r=[r,i]:(ms=t,t=n)}else ms=t,t=n;return t}())!==n?t=r=[r,i]:(ms=t,t=n),t}function Ua(){var e;return(e=Fs())===n&&(e=Bs())===n&&(e=Ws()),e}function Ha(){var t,r,i,o,s,a;for(t=ms,r=[],i=Ma();i!==n;)r.push(i),i=Ma();if(r!==n){for(i=[],o=ms,59===e.charCodeAt(ms)?(s=R,ms++):(s=n,0===bs&&Os(I)),s!==n&&(a=ka())!==n?o=s=[s,a]:(ms=o,o=n);o!==n;)i.push(o),o=ms,59===e.charCodeAt(ms)?(s=R,ms++):(s=n,0===bs&&Os(I)),s!==n&&(a=ka())!==n?o=s=[s,a]:(ms=o,o=n);i!==n?t=r=[r,i]:(ms=t,t=n)}else ms=t,t=n;return t}function ka(){var e,t;for(e=[],t=Ma();t!==n;)e.push(t),t=Ma();return e}function Ma(){var t;return(t=Bs())===n&&(t=Ws())===n&&(58===e.charCodeAt(ms)?(t=D,ms++):(t=n,0===bs&&Os(U)),t===n&&(64===e.charCodeAt(ms)?(t=H,ms++):(t=n,0===bs&&Os(k)),t===n&&(38===e.charCodeAt(ms)?(t=M,ms++):(t=n,0===bs&&Os(q)),t===n&&(61===e.charCodeAt(ms)?(t=j,ms++):(t=n,0===bs&&Os(L)),t===n&&(43===e.charCodeAt(ms)?(t=F,ms++):(t=n,0===bs&&Os(B)),t===n&&(36===e.charCodeAt(ms)?(t=G,ms++):(t=n,0===bs&&Os(W)),t===n&&(44===e.charCodeAt(ms)?(t=z,ms++):(t=n,0===bs&&Os(K))))))))),t}function qa(){var t,r;if(t=[],(r=Bs())===n&&(r=Ws())===n&&(36===e.charCodeAt(ms)?(r=G,ms++):(r=n,0===bs&&Os(W)),r===n&&(44===e.charCodeAt(ms)?(r=z,ms++):(r=n,0===bs&&Os(K)),r===n&&(59===e.charCodeAt(ms)?(r=R,ms++):(r=n,0===bs&&Os(I)),r===n&&(58===e.charCodeAt(ms)?(r=D,ms++):(r=n,0===bs&&Os(U)),r===n&&(64===e.charCodeAt(ms)?(r=H,ms++):(r=n,0===bs&&Os(k)),r===n&&(38===e.charCodeAt(ms)?(r=M,ms++):(r=n,0===bs&&Os(q)),r===n&&(61===e.charCodeAt(ms)?(r=j,ms++):(r=n,0===bs&&Os(L)),r===n&&(43===e.charCodeAt(ms)?(r=F,ms++):(r=n,0===bs&&Os(B)))))))))),r!==n)for(;r!==n;)t.push(r),(r=Bs())===n&&(r=Ws())===n&&(36===e.charCodeAt(ms)?(r=G,ms++):(r=n,0===bs&&Os(W)),r===n&&(44===e.charCodeAt(ms)?(r=z,ms++):(r=n,0===bs&&Os(K)),r===n&&(59===e.charCodeAt(ms)?(r=R,ms++):(r=n,0===bs&&Os(I)),r===n&&(58===e.charCodeAt(ms)?(r=D,ms++):(r=n,0===bs&&Os(U)),r===n&&(64===e.charCodeAt(ms)?(r=H,ms++):(r=n,0===bs&&Os(k)),r===n&&(38===e.charCodeAt(ms)?(r=M,ms++):(r=n,0===bs&&Os(q)),r===n&&(61===e.charCodeAt(ms)?(r=j,ms++):(r=n,0===bs&&Os(L)),r===n&&(43===e.charCodeAt(ms)?(r=F,ms++):(r=n,0===bs&&Os(B))))))))));else t=n;return t}function ja(){var t,r,i,o,s,a,c;if(t=ms,e.substr(ms,3).toLowerCase()===ot?(r=e.substr(ms,3),ms+=3):(r=n,0===bs&&Os(vr)),r!==n)if(47===e.charCodeAt(ms)?(i=O,ms++):(i=n,0===bs&&Os(x)),i!==n){if(o=[],(s=Ns())!==n)for(;s!==n;)o.push(s),s=Ns();else o=n;if(o!==n)if(46===e.charCodeAt(ms)?(s=J,ms++):(s=n,0===bs&&Os(Q)),s!==n){if(a=[],(c=Ns())!==n)for(;c!==n;)a.push(c),c=Ns();else a=n;a!==n?(ys=t,t=r=mr()):(ms=t,t=n)}else ms=t,t=n;else ms=t,t=n}else ms=t,t=n;else ms=t,t=n;return t}function La(){var t,r;return t=ms,(r=function(){var t;return e.substr(ms,6)===yr?(t=yr,ms+=6):(t=n,0===bs&&Os(Sr)),t}())===n&&(r=function(){var t;return e.substr(ms,3)===Tr?(t=Tr,ms+=3):(t=n,0===bs&&Os(Cr)),t}())===n&&(r=function(){var t;return e.substr(ms,7)===br?(t=br,ms+=7):(t=n,0===bs&&Os(_r)),t}())===n&&(r=function(){var t;return e.substr(ms,3)===Ar?(t=Ar,ms+=3):(t=n,0===bs&&Os(wr)),t}())===n&&(r=function(){var t;return e.substr(ms,6)===Er?(t=Er,ms+=6):(t=n,0===bs&&Os(Rr)),t}())===n&&(r=function(){var t;return e.substr(ms,8)===Ir?(t=Ir,ms+=8):(t=n,0===bs&&Os(Or)),t}())===n&&(r=function(){var t;return e.substr(ms,9)===xr?(t=xr,ms+=9):(t=n,0===bs&&Os(Pr)),t}())===n&&(r=function(){var t;return e.substr(ms,7)===kr?(t=kr,ms+=7):(t=n,0===bs&&Os(Mr)),t}())===n&&(r=function(){var t;return e.substr(ms,6)===Nr?(t=Nr,ms+=6):(t=n,0===bs&&Os(Dr)),t}())===n&&(r=function(){var t;return e.substr(ms,5)===Ur?(t=Ur,ms+=5):(t=n,0===bs&&Os(Hr)),t}())===n&&(r=Xs()),r!==n&&(ys=t,r=qr()),t=r}function Fa(){var t,r,i,o;return t=ms,Qs()!==n?(r=ms,64===e.charCodeAt(ms)?(i=H,ms++):(i=n,0===bs&&Os(k)),i!==n&&(o=Qs())!==n?r=i=[i,o]:(ms=r,r=n),r===n&&(r=null),r!==n?(ys=t,t=Fr()):(ms=t,t=n)):(ms=t,t=n),t}function Ba(){var t,r,i,o,s,a,c;if(t=ms,(r=function(){var t,r;return t=ms,Ks()!==n?(42===e.charCodeAt(ms)?(r=ne,ms++):(r=n,0===bs&&Os(ie)),r!==n&&Ks()!==n?(ys=t,t=He()):(ms=t,t=n)):(ms=t,t=n),t}())===n)if(r=ms,(i=Ga())!==n){for(o=[],s=ms,(a=na())!==n&&(c=Ga())!==n?s=a=[a,c]:(ms=s,s=n);s!==n;)o.push(s),s=ms,(a=na())!==n&&(c=Ga())!==n?s=a=[a,c]:(ms=s,s=n);o!==n?r=i=[i,o]:(ms=r,r=n)}else ms=r,r=n;return r!==n&&(ys=t,r=Br()),t=r}function Ga(){var e,t,r,i,o,s;if(e=ms,(t=ha())===n&&(t=Wa()),t!==n){for(r=[],i=ms,(o=ia())!==n&&(s=Ka())!==n?i=o=[o,s]:(ms=i,i=n);i!==n;)r.push(i),i=ms,(o=ia())!==n&&(s=Ka())!==n?i=o=[o,s]:(ms=i,i=n);r!==n?(ys=e,e=t=Gr()):(ms=e,e=n)}else ms=e,e=n;return e}function Wa(){var e,t,r,i,o;return e=ms,(t=za())===n&&(t=null),t!==n&&(r=ra())!==n&&(i=pa())!==n&&(o=ta())!==n?e=t=[t,r,i,o]:(ms=e,e=n),e}function za(){var e,t,r,i,o,s,a;if(e=ms,t=ms,(r=Xs())!==n){for(i=[],o=ms,(s=zs())!==n&&(a=Xs())!==n?o=s=[s,a]:(ms=o,o=n);o!==n;)i.push(o),o=ms,(s=zs())!==n&&(a=Xs())!==n?o=s=[s,a]:(ms=o,o=n);i!==n?t=r=[r,i]:(ms=t,t=n)}else ms=t,t=n;return t===n&&(t=aa()),t!==n&&(ys=e,t=Wr(t)),e=t}function Ka(){var t;return(t=function(){var t,r,i;return t=ms,e.substr(ms,1).toLowerCase()===zr?(r=e.charAt(ms),ms++):(r=n,0===bs&&Os(Kr)),r!==n&&ea()!==n&&(i=function(){var t,r,i,o,s,a,c;return t=ms,48===e.charCodeAt(ms)?(r=Qr,ms++):(r=n,0===bs&&Os(Zr)),r!==n?(i=ms,46===e.charCodeAt(ms)?(o=J,ms++):(o=n,0===bs&&Os(Q)),o!==n?((s=Ns())===n&&(s=null),s!==n?((a=Ns())===n&&(a=null),a!==n?((c=Ns())===n&&(c=null),c!==n?i=o=[o,s,a,c]:(ms=i,i=n)):(ms=i,i=n)):(ms=i,i=n)):(ms=i,i=n),i===n&&(i=null),i!==n?(ys=t,r=en(),t=r):(ms=t,t=n)):(ms=t,t=n),t}())!==n?(ys=t,r=Vr(i),t=r):(ms=t,t=n),t}())===n&&(t=function(){var t,r,i;return t=ms,e.substr(ms,7).toLowerCase()===Yr?(r=e.substr(ms,7),ms+=7):(r=n,0===bs&&Os($r)),r!==n&&ea()!==n&&(i=Va())!==n?(ys=t,r=Xr(i),t=r):(ms=t,t=n),t}())===n&&(t=Ya()),t}function Va(){var e,t,r;if(e=ms,t=[],(r=Ns())!==n)for(;r!==n;)t.push(r),r=Ns();else t=n;return t!==n&&(ys=e,t=Jr(t)),e=t}function Ya(){var e,t,r,i,o;return e=ms,(t=Xs())!==n?(r=ms,(i=ea())!==n&&(o=function(){var e;return(e=Xs())===n&&(e=ma())===n&&(e=aa()),e}())!==n?r=i=[i,o]:(ms=r,r=n),r===n&&(r=null),r!==n?(ys=e,e=t=tn(t,r)):(ms=e,e=n)):(ms=e,e=n),e}function $a(){var t;return(t=function(){var t,r,i,o;return t=ms,e.substr(ms,8).toLowerCase()===pn?(r=e.substr(ms,8),ms+=8):(r=n,0===bs&&Os(ln)),r!==n&&(i=ea())!==n?(e.substr(ms,8).toLowerCase()===fn?(o=e.substr(ms,8),ms+=8):(o=n,0===bs&&Os(gn)),o===n&&(e.substr(ms,8).toLowerCase()===vn?(o=e.substr(ms,8),ms+=8):(o=n,0===bs&&Os(mn)),o===n&&(o=Xs())),o!==n?t=r=[r,i,o]:(ms=t,t=n)):(ms=t,t=n),t}())===n&&(t=Ya()),t}function Xa(){var t;return(t=Xs())===n&&(t=function(){var t,r,i;return t=ms,e.substr(ms,2).toLowerCase()===Un?(r=e.substr(ms,2),ms+=2):(r=n,0===bs&&Os(Hn)),r!==n&&(i=Xs())!==n?t=r=[r,i]:(ms=t,t=n),t}()),t}function Ja(){var e,t,r,i;return e=ms,(t=Xs())!==n&&(r=ea())!==n&&(i=function(){var e;return(e=Xs())===n&&(e=aa()),e}())!==n?e=t=[t,r,i]:(ms=e,e=n),e}function Qa(){var t,r,i,o,s,a,c;if(t=ms,r=ms,(i=Js())!==n){for(o=[],s=ms,46===e.charCodeAt(ms)?(a=J,ms++):(a=n,0===bs&&Os(Q)),a!==n&&(c=Js())!==n?s=a=[a,c]:(ms=s,s=n);s!==n;)o.push(s),s=ms,46===e.charCodeAt(ms)?(a=J,ms++):(a=n,0===bs&&Os(Q)),a!==n&&(c=Js())!==n?s=a=[a,c]:(ms=s,s=n);o!==n?r=i=[i,o]:(ms=r,r=n)}else ms=r,r=n;return t=r!==n?e.substring(t,ms):r}function Za(){var e;return(e=ec())===n&&(e=Ya()),e}function ec(){var t,r,i;return t=ms,e.substr(ms,3).toLowerCase()===jn?(r=e.substr(ms,3),ms+=3):(r=n,0===bs&&Os(Ln)),r!==n&&ea()!==n&&(i=Xs())!==n?(ys=t,t=r=Fn(i)):(ms=t,t=n),t}function tc(){var t,r,i,o,s,a,c,u;if(t=ms,e.substr(ms,6).toLowerCase()===Wn?(r=e.substr(ms,6),ms+=6):(r=n,0===bs&&Os(zn)),r!==n)if((i=zs())!==n)if((o=nc())!==n){for(s=[],a=ms,(c=na())!==n&&(u=nc())!==n?a=c=[c,u]:(ms=a,a=n);a!==n;)s.push(a),a=ms,(c=na())!==n&&(u=nc())!==n?a=c=[c,u]:(ms=a,a=n);s!==n?t=r=[r,i,o,s]:(ms=t,t=n)}else ms=t,t=n;else ms=t,t=n;else ms=t,t=n;return t===n&&(t=function(){var e,t,r,i,o,s,a,c;if(e=ms,(t=Xs())!==n)if((r=zs())!==n)if((i=rc())!==n){for(o=[],s=ms,(a=na())!==n&&(c=rc())!==n?s=a=[a,c]:(ms=s,s=n);s!==n;)o.push(s),s=ms,(a=na())!==n&&(c=rc())!==n?s=a=[a,c]:(ms=s,s=n);o!==n?e=t=[t,r,i,o]:(ms=e,e=n)}else ms=e,e=n;else ms=e,e=n;else ms=e,e=n;return e}()),t}function rc(){var e,t,r,i;return e=ms,(t=Xs())!==n&&(r=ea())!==n?((i=Xs())===n&&(i=aa()),i!==n?e=t=[t,r,i]:(ms=e,e=n)):(ms=e,e=n),e}function nc(){var t;return(t=function(){var t,r,i,o;return t=ms,e.substr(ms,5).toLowerCase()===Kn?(r=e.substr(ms,5),ms+=5):(r=n,0===bs&&Os(Vn)),r!==n&&(i=ea())!==n&&(o=function(){var e,t;return e=ms,(t=ca())!==n&&(ys=e,t=Yn(t)),e=t}())!==n?t=r=[r,i,o]:(ms=t,t=n),t}())===n&&(t=function(){var t,r,i,o,s,a,c,u,d;if(t=ms,e.substr(ms,6).toLowerCase()===$n?(r=e.substr(ms,6),ms+=6):(r=n,0===bs&&Os(Xn)),r!==n)if((i=ea())!==n)if((o=oa())!==n)if((s=ic())!==n){if(a=[],c=ms,u=[],(d=qs())!==n)for(;d!==n;)u.push(d),d=qs();else u=n;for(u!==n&&(d=ic())!==n?c=u=[u,d]:(ms=c,c=n);c!==n;){if(a.push(c),c=ms,u=[],(d=qs())!==n)for(;d!==n;)u.push(d),d=qs();else u=n;u!==n&&(d=ic())!==n?c=u=[u,d]:(ms=c,c=n)}a!==n&&(c=sa())!==n?t=r=[r,i,o,s,a,c]:(ms=t,t=n)}else ms=t,t=n;else ms=t,t=n;else ms=t,t=n;else ms=t,t=n;return t}())===n&&(t=function(){var t,r,i,o;return t=ms,e.substr(ms,5).toLowerCase()===Jn?(r=e.substr(ms,5),ms+=5):(r=n,0===bs&&Os(Qn)),r!==n&&(i=ea())!==n&&(o=function(){var e,t;return e=ms,(t=ca())!==n&&(ys=e,t=Zn(t)),e=t}())!==n?t=r=[r,i,o]:(ms=t,t=n),t}())===n&&(t=function(){var t,r,i;return t=ms,e.substr(ms,6).toLowerCase()===ei?(r=e.substr(ms,6),ms+=6):(r=n,0===bs&&Os(ti)),r!==n&&ea()!==n&&(i=ca())!==n?(ys=t,r=ri(i),t=r):(ms=t,t=n),t}())===n&&(t=function(){var t,r,i,o,s;return t=ms,e.substr(ms,5).toLowerCase()===ni?(r=e.substr(ms,5),ms+=5):(r=n,0===bs&&Os(ii)),r!==n&&(i=ea())!==n?(o=ms,e.substr(ms,4).toLowerCase()===oi?(s=e.substr(ms,4),ms+=4):(s=n,0===bs&&Os(si)),s!==n&&(ys=o,s=ai()),(o=s)===n&&(o=ms,e.substr(ms,5).toLowerCase()===ci?(s=e.substr(ms,5),ms+=5):(s=n,0===bs&&Os(ui)),s!==n&&(ys=o,s=di()),o=s),o!==n?t=r=[r,i,o]:(ms=t,t=n)):(ms=t,t=n),t}())===n&&(t=function(){var t,r,i;return t=ms,e.substr(ms,9).toLowerCase()===hi?(r=e.substr(ms,9),ms+=9):(r=n,0===bs&&Os(pi)),r!==n&&ea()!==n?(e.substr(ms,3).toLowerCase()===li?(i=e.substr(ms,3),ms+=3):(i=n,0===bs&&Os(fi)),i===n&&(e.substr(ms,8).toLowerCase()===gi?(i=e.substr(ms,8),ms+=8):(i=n,0===bs&&Os(vi)),i===n&&(i=Xs())),i!==n?(ys=t,r=mi(i),t=r):(ms=t,t=n)):(ms=t,t=n),t}())===n&&(t=function(){var t,r,i,o,s,a,c,u,d,h;if(t=ms,e.substr(ms,3).toLowerCase()===yi?(r=e.substr(ms,3),ms+=3):(r=n,0===bs&&Os(Si)),r!==n)if((i=ea())!==n)if((o=oa())!==n){if(s=ms,(a=oc())!==n){for(c=[],u=ms,44===e.charCodeAt(ms)?(d=z,ms++):(d=n,0===bs&&Os(K)),d!==n&&(h=oc())!==n?u=d=[d,h]:(ms=u,u=n);u!==n;)c.push(u),u=ms,44===e.charCodeAt(ms)?(d=z,ms++):(d=n,0===bs&&Os(K)),d!==n&&(h=oc())!==n?u=d=[d,h]:(ms=u,u=n);c!==n?s=a=[a,c]:(ms=s,s=n)}else ms=s,s=n;s!==n&&(a=sa())!==n?t=r=[r,i,o,s,a]:(ms=t,t=n)}else ms=t,t=n;else ms=t,t=n;else ms=t,t=n;return t}())===n&&(t=rc()),t}function ic(){var e;return(e=Na())===n&&(e=Da()),e}function oc(){var t,r;return t=ms,e.substr(ms,8).toLowerCase()===Ti?(r=e.substr(ms,8),ms+=8):(r=n,0===bs&&Os(Ci)),r===n&&(e.substr(ms,4).toLowerCase()===bi?(r=e.substr(ms,4),ms+=4):(r=n,0===bs&&Os(_i)),r===n&&(r=Xs())),r!==n&&(ys=t,r=Ai(r)),t=r}function sc(){var e,t,r,i,o;if(e=ms,Wa()!==n){for(t=[],r=ms,(i=ia())!==n&&(o=Ya())!==n?r=i=[i,o]:(ms=r,r=n);r!==n;)t.push(r),r=ms,(i=ia())!==n&&(o=Ya())!==n?r=i=[i,o]:(ms=r,r=n);t!==n?(ys=e,e=Ei()):(ms=e,e=n)}else ms=e,e=n;return e}function ac(){var t,r,i;return t=ms,e.substr(ms,8).toLowerCase()===xi?(r=e.substr(ms,8),ms+=8):(r=n,0===bs&&Os(Pi)),r!==n&&ea()!==n&&(i=Xs())!==n?(ys=t,t=r=Ni(i)):(ms=t,t=n),t===n&&(t=ms,e.substr(ms,6).toLowerCase()===Di?(r=e.substr(ms,6),ms+=6):(r=n,0===bs&&Os(Ui)),r!==n&&ea()!==n&&(i=Xs())!==n?(ys=t,t=r=Hi(i)):(ms=t,t=n),t===n&&(t=ms,e.substr(ms,10).toLowerCase()===ki?(r=e.substr(ms,10),ms+=10):(r=n,0===bs&&Os(Mi)),r!==n&&(ys=t,r=qi()),(t=r)===n&&(t=Ya()))),t}function cc(){var t,r,i;return t=ms,e.substr(ms,6).toLowerCase()===$i?(r=e.substr(ms,6),ms+=6):(r=n,0===bs&&Os(Xi)),r!==n&&ea()!==n&&(i=function(){var t;return e.substr(ms,11).toLowerCase()===ro?(t=e.substr(ms,11),ms+=11):(t=n,0===bs&&Os(no)),t===n&&(e.substr(ms,9).toLowerCase()===io?(t=e.substr(ms,9),ms+=9):(t=n,0===bs&&Os(oo)),t===n&&(e.substr(ms,8).toLowerCase()===so?(t=e.substr(ms,8),ms+=8):(t=n,0===bs&&Os(ao)),t===n&&(e.substr(ms,7).toLowerCase()===co?(t=e.substr(ms,7),ms+=7):(t=n,0===bs&&Os(uo)),t===n&&(e.substr(ms,6).toLowerCase()===ho?(t=e.substr(ms,6),ms+=6):(t=n,0===bs&&Os(po)),t===n&&(e.substr(ms,10).toLowerCase()===lo?(t=e.substr(ms,10),ms+=10):(t=n,0===bs&&Os(fo)),t===n&&(e.substr(ms,9).toLowerCase()===go?(t=e.substr(ms,9),ms+=9):(t=n,0===bs&&Os(vo)),t===n&&(t=Xs()))))))),t}())!==n?(ys=t,t=r=Ji(i)):(ms=t,t=n),t===n&&(t=ms,e.substr(ms,7).toLowerCase()===Yr?(r=e.substr(ms,7),ms+=7):(r=n,0===bs&&Os($r)),r!==n&&ea()!==n&&(i=Va())!==n?(ys=t,t=r=Qi(i)):(ms=t,t=n),t===n&&(t=ms,e.substr(ms,11).toLowerCase()===Zi?(r=e.substr(ms,11),ms+=11):(r=n,0===bs&&Os(eo)),r!==n&&ea()!==n&&(i=Va())!==n?(ys=t,t=r=to(i)):(ms=t,t=n),t===n&&(t=Ya()))),t}function uc(){var e;return(e=ec())===n&&(e=Ya()),e}function dc(){var t,r,i,o,s,a,c,u;if(t=ms,(r=function(){var t,r,i,o,s,a;return t=ms,(r=function(){var t,r;return t=ms,e.substr(ms,3).toLowerCase()===ot?(r=e.substr(ms,3),ms+=3):(r=n,0===bs&&Os(vr)),r===n&&(r=Xs()),r!==n&&(ys=t,r=Uo(r)),t=r}())!==n&&(i=Zs())!==n&&(o=Xs())!==n&&(s=Zs())!==n&&(a=pc())!==n?t=r=[r,i,o,s,a]:(ms=t,t=n),t}())!==n)if((i=zs())!==n)if((o=function(){var t,r,i,o,s;return t=ms,(r=function(){var e,t;return e=ms,(t=ya())===n&&(t=Aa())===n&&(t=Ta()),t!==n&&(ys=e,t=Lo()),e=t}())!==n?(i=ms,(o=function(){var t,r;return t=ms,Ks()!==n?(58===e.charCodeAt(ms)?(r=D,ms++):(r=n,0===bs&&Os(U)),r!==n&&Ks()!==n?(ys=t,t=Be()):(ms=t,t=n)):(ms=t,t=n),t}())!==n&&(s=function(){var e,t,r,i,o,s,a;return e=ms,t=ms,(r=Ns())===n&&(r=null),r!==n?((i=Ns())===n&&(i=null),i!==n?((o=Ns())===n&&(o=null),o!==n?((s=Ns())===n&&(s=null),s!==n?((a=Ns())===n&&(a=null),a!==n?t=r=[r,i,o,s,a]:(ms=t,t=n)):(ms=t,t=n)):(ms=t,t=n)):(ms=t,t=n)):(ms=t,t=n),t!==n&&(ys=e,t=Fo(t)),e=t}())!==n?i=o=[o,s]:(ms=i,i=n),i===n&&(i=null),i!==n?t=r=[r,i]:(ms=t,t=n)):(ms=t,t=n),t}())!==n){for(s=[],a=ms,(c=ia())!==n&&(u=hc())!==n?a=c=[c,u]:(ms=a,a=n);a!==n;)s.push(a),a=ms,(c=ia())!==n&&(u=hc())!==n?a=c=[c,u]:(ms=a,a=n);s!==n?t=r=[r,i,o,s]:(ms=t,t=n)}else ms=t,t=n;else ms=t,t=n;else ms=t,t=n;return t}function hc(){var t;return(t=function(){var t,r,i;return t=ms,e.substr(ms,3).toLowerCase()===So?(r=e.substr(ms,3),ms+=3):(r=n,0===bs&&Os(To)),r!==n&&ea()!==n&&(i=lc())!==n?(ys=t,r=Co(i),t=r):(ms=t,t=n),t}())===n&&(t=function(){var t,r,i;return t=ms,e.substr(ms,5).toLowerCase()===bo?(r=e.substr(ms,5),ms+=5):(r=n,0===bs&&Os(_o)),r!==n&&ea()!==n&&(i=ma())!==n?(ys=t,r=Ao(i),t=r):(ms=t,t=n),t}())===n&&(t=function(){var t,r,i;return t=ms,e.substr(ms,8).toLowerCase()===wo?(r=e.substr(ms,8),ms+=8):(r=n,0===bs&&Os(Eo)),r!==n&&ea()!==n?((i=Aa())===n&&(i=Ca())===n&&(i=Ta()),i!==n?(ys=t,r=Ro(i),t=r):(ms=t,t=n)):(ms=t,t=n),t}())===n&&(t=function(){var t,r,i;return t=ms,e.substr(ms,6).toLowerCase()===Io?(r=e.substr(ms,6),ms+=6):(r=n,0===bs&&Os(Oo)),r!==n&&ea()!==n&&(i=Xs())!==n?(ys=t,r=xo(i),t=r):(ms=t,t=n),t}())===n&&(t=function(){var t,r,i,o;if(t=ms,e.substr(ms,5).toLowerCase()===Po?(r=e.substr(ms,5),ms+=5):(r=n,0===bs&&Os(No)),r!==n)if(ea()!==n){for(i=[],o=Ns();o!==n;)i.push(o),o=Ns();i!==n?(ys=t,r=Do(i),t=r):(ms=t,t=n)}else ms=t,t=n;else ms=t,t=n;return t}())===n&&(t=Ya()),t}function pc(){var t,r;return t=ms,e.substr(ms,3).toLowerCase()===kt?(r=e.substr(ms,3),ms+=3):(r=n,0===bs&&Os(Ho)),r===n&&(e.substr(ms,3).toLowerCase()===qt?(r=e.substr(ms,3),ms+=3):(r=n,0===bs&&Os(ko)),r===n&&(e.substr(ms,3).toLowerCase()===Bt?(r=e.substr(ms,3),ms+=3):(r=n,0===bs&&Os(Mo)),r===n&&(e.substr(ms,4).toLowerCase()===Lt?(r=e.substr(ms,4),ms+=4):(r=n,0===bs&&Os(qo)),r===n&&(r=Xs())))),r!==n&&(ys=t,r=jo(r)),t=r}function lc(){var e,t,r,i,o;return e=ms,t=ms,(r=Ns())!==n?((i=Ns())===n&&(i=null),i!==n?((o=Ns())===n&&(o=null),o!==n?t=r=[r,i,o]:(ms=t,t=n)):(ms=t,t=n)):(ms=t,t=n),t!==n&&(ys=e,t=Bo(t)),e=t}function fc(){var t;return(t=function(){var t,r,i;return t=ms,e.substr(ms,9)===Wo?(r=Wo,ms+=9):(r=n,0===bs&&Os(zo)),r!==n&&ea()!==n?(e.substr(ms,3)===Ko?(i=Ko,ms+=3):(i=n,0===bs&&Os(Vo)),i===n&&(e.substr(ms,3)===Yo?(i=Yo,ms+=3):(i=n,0===bs&&Os($o))),i!==n?(ys=t,r=Xo(i),t=r):(ms=t,t=n)):(ms=t,t=n),t}())===n&&(t=Ya()),t}function gc(){var t,r,i,o,s;return t=ms,(r=function(){var e,t;return e=ms,(t=Aa())===n&&(t=Ta())===n&&(t=qa()),t!==n&&(ys=e,t=ns(t)),e=t}())!==n?(i=ms,58===e.charCodeAt(ms)?(o=D,ms++):(o=n,0===bs&&Os(U)),o!==n&&(s=Ea())!==n?i=o=[o,s]:(ms=i,i=n),i===n&&(i=null),i!==n?t=r=[r,i]:(ms=t,t=n)):(ms=t,t=n),t}function vc(){var e,t,r,i,o;return e=ms,(t=Us())!==n&&(r=Us())!==n&&(i=Us())!==n&&(o=Us())!==n?e=t=[t,r,i,o]:(ms=e,e=n),e}function mc(){var t,r,i,o;return t=ms,e.substr(ms,3)===gs?(r=gs,ms+=3):(r=n,0===bs&&Os(vs)),r!==n&&(i=ea())!==n&&(o=function(){var t,r,i,o,s,a;return t=ms,(r=oa())!==n&&(i=Gs())!==n?(64===e.charCodeAt(ms)?(o=H,ms++):(o=n,0===bs&&Os(k)),o!==n?((s=Gs())===n&&(s=ma()),s!==n&&(a=sa())!==n?t=r=[r,i,o,s,a]:(ms=t,t=n)):(ms=t,t=n)):(ms=t,t=n),t}())!==n?t=r=[r,i,o]:(ms=t,t=n),t}if(t.data={},(r=c())!==n&&ms===e.length)return r;throw r!==n&&ms>>2]|=e[i]<<24-i%4*8;t.call(this,n,r)}else t.apply(this,arguments)}).prototype=e}}(),n.lib.WordArray)},function(e,t,r){var n;e.exports=(n=r(0),function(){var e=n,t=e.lib.WordArray,r=e.enc;function i(e){return e<<8&4278255360|e>>>8&16711935}r.Utf16=r.Utf16BE={stringify:function(e){for(var t=e.words,r=e.sigBytes,n=[],i=0;i>>2]>>>16-i%4*8&65535;n.push(String.fromCharCode(o))}return n.join("")},parse:function(e){for(var r=e.length,n=[],i=0;i>>1]|=e.charCodeAt(i)<<16-i%2*16;return t.create(n,2*r)}},r.Utf16LE={stringify:function(e){for(var t=e.words,r=e.sigBytes,n=[],o=0;o>>2]>>>16-o%4*8&65535);n.push(String.fromCharCode(s))}return n.join("")},parse:function(e){for(var r=e.length,n=[],o=0;o>>1]|=i(e.charCodeAt(o)<<16-o%2*16);return t.create(n,2*r)}}}(),n.enc.Utf16)},function(e,t,r){var n,i,o,s,a,c;e.exports=(n=r(0),r(38),o=(i=n).lib.WordArray,s=i.algo,a=s.SHA256,c=s.SHA224=a.extend({_doReset:function(){this._hash=new o.init([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428])},_doFinalize:function(){var e=a._doFinalize.call(this);return e.sigBytes-=4,e}}),i.SHA224=a._createHelper(c),i.HmacSHA224=a._createHmacHelper(c),n.SHA224)},function(e,t,r){var n,i,o,s,a,c,u,d;e.exports=(n=r(0),r(21),r(39),o=(i=n).x64,s=o.Word,a=o.WordArray,c=i.algo,u=c.SHA512,d=c.SHA384=u.extend({_doReset:function(){this._hash=new a.init([new s.init(3418070365,3238371032),new s.init(1654270250,914150663),new s.init(2438529370,812702999),new s.init(355462360,4144912697),new s.init(1731405415,4290775857),new s.init(2394180231,1750603025),new s.init(3675008525,1694076839),new s.init(1203062813,3204075428)])},_doFinalize:function(){var e=u._doFinalize.call(this);return e.sigBytes-=16,e}}),i.SHA384=u._createHelper(d),i.HmacSHA384=u._createHmacHelper(d),n.SHA384)},function(e,t,r){var n;e.exports=(n=r(0),r(21),function(e){var t=n,r=t.lib,i=r.WordArray,o=r.Hasher,s=t.x64.Word,a=t.algo,c=[],u=[],d=[];!function(){for(var e=1,t=0,r=0;r<24;r++){c[e+5*t]=(r+1)*(r+2)/2%64;var n=(2*e+3*t)%5;e=t%5,t=n}for(e=0;e<5;e++)for(t=0;t<5;t++)u[e+5*t]=t+(2*e+3*t)%5*5;for(var i=1,o=0;o<24;o++){for(var a=0,h=0,p=0;p<7;p++){if(1&i){var l=(1<>>24)|4278255360&(o<<24|o>>>8),s=16711935&(s<<8|s>>>24)|4278255360&(s<<24|s>>>8),(I=r[i]).high^=s,I.low^=o}for(var a=0;a<24;a++){for(var p=0;p<5;p++){for(var l=0,f=0,g=0;g<5;g++)l^=(I=r[p+5*g]).high,f^=I.low;var v=h[p];v.high=l,v.low=f}for(p=0;p<5;p++){var m=h[(p+4)%5],y=h[(p+1)%5],S=y.high,T=y.low;for(l=m.high^(S<<1|T>>>31),f=m.low^(T<<1|S>>>31),g=0;g<5;g++)(I=r[p+5*g]).high^=l,I.low^=f}for(var C=1;C<25;C++){var b=(I=r[C]).high,_=I.low,A=c[C];A<32?(l=b<>>32-A,f=_<>>32-A):(l=_<>>64-A,f=b<>>64-A);var w=h[u[C]];w.high=l,w.low=f}var E=h[0],R=r[0];for(E.high=R.high,E.low=R.low,p=0;p<5;p++)for(g=0;g<5;g++){var I=r[C=p+5*g],O=h[C],x=h[(p+1)%5+5*g],P=h[(p+2)%5+5*g];I.high=O.high^~x.high&P.high,I.low=O.low^~x.low&P.low}I=r[0];var N=d[a];I.high^=N.high,I.low^=N.low}},_doFinalize:function(){var t=this._data,r=t.words,n=(this._nDataBytes,8*t.sigBytes),o=32*this.blockSize;r[n>>>5]|=1<<24-n%32,r[(e.ceil((n+1)/o)*o>>>5)-1]|=128,t.sigBytes=4*r.length,this._process();for(var s=this._state,a=this.cfg.outputLength/8,c=a/8,u=[],d=0;d>>24)|4278255360&(p<<24|p>>>8),l=16711935&(l<<8|l>>>24)|4278255360&(l<<24|l>>>8),u.push(l),u.push(p)}return new i.init(u,a)},clone:function(){for(var e=o.clone.call(this),t=e._state=this._state.slice(0),r=0;r<25;r++)t[r]=t[r].clone();return e}});t.SHA3=o._createHelper(p),t.HmacSHA3=o._createHmacHelper(p)}(Math),n.SHA3)},function(e,t,r){var n;e.exports=(n=r(0),function(e){var t=n,r=t.lib,i=r.WordArray,o=r.Hasher,s=t.algo,a=i.create([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13]),c=i.create([5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11]),u=i.create([11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6]),d=i.create([8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]),h=i.create([0,1518500249,1859775393,2400959708,2840853838]),p=i.create([1352829926,1548603684,1836072691,2053994217,0]),l=s.RIPEMD160=o.extend({_doReset:function(){this._hash=i.create([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(e,t){for(var r=0;r<16;r++){var n=t+r,i=e[n];e[n]=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8)}var o,s,l,T,C,b,_,A,w,E,R,I=this._hash.words,O=h.words,x=p.words,P=a.words,N=c.words,D=u.words,U=d.words;for(b=o=I[0],_=s=I[1],A=l=I[2],w=T=I[3],E=C=I[4],r=0;r<80;r+=1)R=o+e[t+P[r]]|0,R+=r<16?f(s,l,T)+O[0]:r<32?g(s,l,T)+O[1]:r<48?v(s,l,T)+O[2]:r<64?m(s,l,T)+O[3]:y(s,l,T)+O[4],R=(R=S(R|=0,D[r]))+C|0,o=C,C=T,T=S(l,10),l=s,s=R,R=b+e[t+N[r]]|0,R+=r<16?y(_,A,w)+x[0]:r<32?m(_,A,w)+x[1]:r<48?v(_,A,w)+x[2]:r<64?g(_,A,w)+x[3]:f(_,A,w)+x[4],R=(R=S(R|=0,U[r]))+E|0,b=E,E=w,w=S(A,10),A=_,_=R;R=I[1]+l+w|0,I[1]=I[2]+T+E|0,I[2]=I[3]+C+b|0,I[3]=I[4]+o+_|0,I[4]=I[0]+s+A|0,I[0]=R},_doFinalize:function(){var e=this._data,t=e.words,r=8*this._nDataBytes,n=8*e.sigBytes;t[n>>>5]|=128<<24-n%32,t[14+(n+64>>>9<<4)]=16711935&(r<<8|r>>>24)|4278255360&(r<<24|r>>>8),e.sigBytes=4*(t.length+1),this._process();for(var i=this._hash,o=i.words,s=0;s<5;s++){var a=o[s];o[s]=16711935&(a<<8|a>>>24)|4278255360&(a<<24|a>>>8)}return i},clone:function(){var e=o.clone.call(this);return e._hash=this._hash.clone(),e}});function f(e,t,r){return e^t^r}function g(e,t,r){return e&t|~e&r}function v(e,t,r){return(e|~t)^r}function m(e,t,r){return e&r|t&~r}function y(e,t,r){return e^(t|~r)}function S(e,t){return e<>>32-t}t.RIPEMD160=o._createHelper(l),t.HmacRIPEMD160=o._createHmacHelper(l)}(Math),n.RIPEMD160)},function(e,t,r){var n,i,o,s,a,c,u,d,h;e.exports=(n=r(0),r(25),r(26),o=(i=n).lib,s=o.Base,a=o.WordArray,c=i.algo,u=c.SHA1,d=c.HMAC,h=c.PBKDF2=s.extend({cfg:s.extend({keySize:4,hasher:u,iterations:1}),init:function(e){this.cfg=this.cfg.extend(e)},compute:function(e,t){for(var r=this.cfg,n=d.create(r.hasher,e),i=a.create(),o=a.create([1]),s=i.words,c=o.words,u=r.keySize,h=r.iterations;s.length>24&255)){var t=e>>16&255,r=e>>8&255,n=255&e;255===t?(t=0,255===r?(r=0,255===n?n=0:++n):++r):++t,e=0,e+=t<<16,e+=r<<8,e+=n}else e+=1<<24;return e}var r=e.Encryptor=e.extend({processBlock:function(e,r){var n=this._cipher,i=n.blockSize,o=this._iv,s=this._counter;o&&(s=this._counter=o.slice(0),this._iv=void 0),function(e){0===(e[0]=t(e[0]))&&(e[1]=t(e[1]))}(s);var a=s.slice(0);n.encryptBlock(a,0);for(var c=0;c>>2]|=i<<24-o%4*8,e.sigBytes+=i},unpad:function(e){var t=255&e.words[e.sigBytes-1>>>2];e.sigBytes-=t}},n.pad.Ansix923)},function(e,t,r){var n;e.exports=(n=r(0),r(4),n.pad.Iso10126={pad:function(e,t){var r=4*t,i=r-e.sigBytes%r;e.concat(n.lib.WordArray.random(i-1)).concat(n.lib.WordArray.create([i<<24],1))},unpad:function(e){var t=255&e.words[e.sigBytes-1>>>2];e.sigBytes-=t}},n.pad.Iso10126)},function(e,t,r){var n;e.exports=(n=r(0),r(4),n.pad.Iso97971={pad:function(e,t){e.concat(n.lib.WordArray.create([2147483648],1)),n.pad.ZeroPadding.pad(e,t)},unpad:function(e){n.pad.ZeroPadding.unpad(e),e.sigBytes--}},n.pad.Iso97971)},function(e,t,r){var n;e.exports=(n=r(0),r(4),n.pad.ZeroPadding={pad:function(e,t){var r=4*t;e.clamp(),e.sigBytes+=r-(e.sigBytes%r||r)},unpad:function(e){for(var t=e.words,r=e.sigBytes-1;!(t[r>>>2]>>>24-r%4*8&255);)r--;e.sigBytes=r+1}},n.pad.ZeroPadding)},function(e,t,r){var n;e.exports=(n=r(0),r(4),n.pad.NoPadding={pad:function(){},unpad:function(){}},n.pad.NoPadding)},function(e,t,r){var n,i,o,s;e.exports=(n=r(0),r(4),o=(i=n).lib.CipherParams,s=i.enc.Hex,i.format.Hex={stringify:function(e){return e.ciphertext.toString(s)},parse:function(e){var t=s.parse(e);return o.create({ciphertext:t})}},n.format.Hex)},function(e,t,r){var n;e.exports=(n=r(0),r(16),r(17),r(13),r(4),function(){var e=n,t=e.lib.BlockCipher,r=e.algo,i=[],o=[],s=[],a=[],c=[],u=[],d=[],h=[],p=[],l=[];!function(){for(var e=[],t=0;t<256;t++)e[t]=t<128?t<<1:t<<1^283;var r=0,n=0;for(t=0;t<256;t++){var f=n^n<<1^n<<2^n<<3^n<<4;f=f>>>8^255&f^99,i[r]=f,o[f]=r;var g=e[r],v=e[g],m=e[v],y=257*e[f]^16843008*f;s[r]=y<<24|y>>>8,a[r]=y<<16|y>>>16,c[r]=y<<8|y>>>24,u[r]=y,y=16843009*m^65537*v^257*g^16843008*r,d[f]=y<<24|y>>>8,h[f]=y<<16|y>>>16,p[f]=y<<8|y>>>24,l[f]=y,r?(r=g^e[e[e[m^g]]],n^=e[e[n]]):r=n=1}}();var f=[0,1,2,4,8,16,32,64,128,27,54],g=r.AES=t.extend({_doReset:function(){if(!this._nRounds||this._keyPriorReset!==this._key){for(var e=this._keyPriorReset=this._key,t=e.words,r=e.sigBytes/4,n=4*((this._nRounds=r+6)+1),o=this._keySchedule=[],s=0;s6&&s%r==4&&(a=i[a>>>24]<<24|i[a>>>16&255]<<16|i[a>>>8&255]<<8|i[255&a]):(a=i[(a=a<<8|a>>>24)>>>24]<<24|i[a>>>16&255]<<16|i[a>>>8&255]<<8|i[255&a],a^=f[s/r|0]<<24),o[s]=o[s-r]^a}for(var c=this._invKeySchedule=[],u=0;u>>24]]^h[i[a>>>16&255]]^p[i[a>>>8&255]]^l[i[255&a]]}},encryptBlock:function(e,t){this._doCryptBlock(e,t,this._keySchedule,s,a,c,u,i)},decryptBlock:function(e,t){var r=e[t+1];e[t+1]=e[t+3],e[t+3]=r,this._doCryptBlock(e,t,this._invKeySchedule,d,h,p,l,o),r=e[t+1],e[t+1]=e[t+3],e[t+3]=r},_doCryptBlock:function(e,t,r,n,i,o,s,a){for(var c=this._nRounds,u=e[t]^r[0],d=e[t+1]^r[1],h=e[t+2]^r[2],p=e[t+3]^r[3],l=4,f=1;f>>24]^i[d>>>16&255]^o[h>>>8&255]^s[255&p]^r[l++],v=n[d>>>24]^i[h>>>16&255]^o[p>>>8&255]^s[255&u]^r[l++],m=n[h>>>24]^i[p>>>16&255]^o[u>>>8&255]^s[255&d]^r[l++],y=n[p>>>24]^i[u>>>16&255]^o[d>>>8&255]^s[255&h]^r[l++];u=g,d=v,h=m,p=y}g=(a[u>>>24]<<24|a[d>>>16&255]<<16|a[h>>>8&255]<<8|a[255&p])^r[l++],v=(a[d>>>24]<<24|a[h>>>16&255]<<16|a[p>>>8&255]<<8|a[255&u])^r[l++],m=(a[h>>>24]<<24|a[p>>>16&255]<<16|a[u>>>8&255]<<8|a[255&d])^r[l++],y=(a[p>>>24]<<24|a[u>>>16&255]<<16|a[d>>>8&255]<<8|a[255&h])^r[l++],e[t]=g,e[t+1]=v,e[t+2]=m,e[t+3]=y},keySize:8});e.AES=t._createHelper(g)}(),n.AES)},function(e,t,r){var n;e.exports=(n=r(0),r(16),r(17),r(13),r(4),function(){var e=n,t=e.lib,r=t.WordArray,i=t.BlockCipher,o=e.algo,s=[57,49,41,33,25,17,9,1,58,50,42,34,26,18,10,2,59,51,43,35,27,19,11,3,60,52,44,36,63,55,47,39,31,23,15,7,62,54,46,38,30,22,14,6,61,53,45,37,29,21,13,5,28,20,12,4],a=[14,17,11,24,1,5,3,28,15,6,21,10,23,19,12,4,26,8,16,7,27,20,13,2,41,52,31,37,47,55,30,40,51,45,33,48,44,49,39,56,34,53,46,42,50,36,29,32],c=[1,2,4,6,8,10,12,14,15,17,19,21,23,25,27,28],u=[{0:8421888,268435456:32768,536870912:8421378,805306368:2,1073741824:512,1342177280:8421890,1610612736:8389122,1879048192:8388608,2147483648:514,2415919104:8389120,2684354560:33280,2952790016:8421376,3221225472:32770,3489660928:8388610,3758096384:0,4026531840:33282,134217728:0,402653184:8421890,671088640:33282,939524096:32768,1207959552:8421888,1476395008:512,1744830464:8421378,2013265920:2,2281701376:8389120,2550136832:33280,2818572288:8421376,3087007744:8389122,3355443200:8388610,3623878656:32770,3892314112:514,4160749568:8388608,1:32768,268435457:2,536870913:8421888,805306369:8388608,1073741825:8421378,1342177281:33280,1610612737:512,1879048193:8389122,2147483649:8421890,2415919105:8421376,2684354561:8388610,2952790017:33282,3221225473:514,3489660929:8389120,3758096385:32770,4026531841:0,134217729:8421890,402653185:8421376,671088641:8388608,939524097:512,1207959553:32768,1476395009:8388610,1744830465:2,2013265921:33282,2281701377:32770,2550136833:8389122,2818572289:514,3087007745:8421888,3355443201:8389120,3623878657:0,3892314113:33280,4160749569:8421378},{0:1074282512,16777216:16384,33554432:524288,50331648:1074266128,67108864:1073741840,83886080:1074282496,100663296:1073758208,117440512:16,134217728:540672,150994944:1073758224,167772160:1073741824,184549376:540688,201326592:524304,218103808:0,234881024:16400,251658240:1074266112,8388608:1073758208,25165824:540688,41943040:16,58720256:1073758224,75497472:1074282512,92274688:1073741824,109051904:524288,125829120:1074266128,142606336:524304,159383552:0,176160768:16384,192937984:1074266112,209715200:1073741840,226492416:540672,243269632:1074282496,260046848:16400,268435456:0,285212672:1074266128,301989888:1073758224,318767104:1074282496,335544320:1074266112,352321536:16,369098752:540688,385875968:16384,402653184:16400,419430400:524288,436207616:524304,452984832:1073741840,469762048:540672,486539264:1073758208,503316480:1073741824,520093696:1074282512,276824064:540688,293601280:524288,310378496:1074266112,327155712:16384,343932928:1073758208,360710144:1074282512,377487360:16,394264576:1073741824,411041792:1074282496,427819008:1073741840,444596224:1073758224,461373440:524304,478150656:0,494927872:16400,511705088:1074266128,528482304:540672},{0:260,1048576:0,2097152:67109120,3145728:65796,4194304:65540,5242880:67108868,6291456:67174660,7340032:67174400,8388608:67108864,9437184:67174656,10485760:65792,11534336:67174404,12582912:67109124,13631488:65536,14680064:4,15728640:256,524288:67174656,1572864:67174404,2621440:0,3670016:67109120,4718592:67108868,5767168:65536,6815744:65540,7864320:260,8912896:4,9961472:256,11010048:67174400,12058624:65796,13107200:65792,14155776:67109124,15204352:67174660,16252928:67108864,16777216:67174656,17825792:65540,18874368:65536,19922944:67109120,20971520:256,22020096:67174660,23068672:67108868,24117248:0,25165824:67109124,26214400:67108864,27262976:4,28311552:65792,29360128:67174400,30408704:260,31457280:65796,32505856:67174404,17301504:67108864,18350080:260,19398656:67174656,20447232:0,21495808:65540,22544384:67109120,23592960:256,24641536:67174404,25690112:65536,26738688:67174660,27787264:65796,28835840:67108868,29884416:67109124,30932992:67174400,31981568:4,33030144:65792},{0:2151682048,65536:2147487808,131072:4198464,196608:2151677952,262144:0,327680:4198400,393216:2147483712,458752:4194368,524288:2147483648,589824:4194304,655360:64,720896:2147487744,786432:2151678016,851968:4160,917504:4096,983040:2151682112,32768:2147487808,98304:64,163840:2151678016,229376:2147487744,294912:4198400,360448:2151682112,425984:0,491520:2151677952,557056:4096,622592:2151682048,688128:4194304,753664:4160,819200:2147483648,884736:4194368,950272:4198464,1015808:2147483712,1048576:4194368,1114112:4198400,1179648:2147483712,1245184:0,1310720:4160,1376256:2151678016,1441792:2151682048,1507328:2147487808,1572864:2151682112,1638400:2147483648,1703936:2151677952,1769472:4198464,1835008:2147487744,1900544:4194304,1966080:64,2031616:4096,1081344:2151677952,1146880:2151682112,1212416:0,1277952:4198400,1343488:4194368,1409024:2147483648,1474560:2147487808,1540096:64,1605632:2147483712,1671168:4096,1736704:2147487744,1802240:2151678016,1867776:4160,1933312:2151682048,1998848:4194304,2064384:4198464},{0:128,4096:17039360,8192:262144,12288:536870912,16384:537133184,20480:16777344,24576:553648256,28672:262272,32768:16777216,36864:537133056,40960:536871040,45056:553910400,49152:553910272,53248:0,57344:17039488,61440:553648128,2048:17039488,6144:553648256,10240:128,14336:17039360,18432:262144,22528:537133184,26624:553910272,30720:536870912,34816:537133056,38912:0,43008:553910400,47104:16777344,51200:536871040,55296:553648128,59392:16777216,63488:262272,65536:262144,69632:128,73728:536870912,77824:553648256,81920:16777344,86016:553910272,90112:537133184,94208:16777216,98304:553910400,102400:553648128,106496:17039360,110592:537133056,114688:262272,118784:536871040,122880:0,126976:17039488,67584:553648256,71680:16777216,75776:17039360,79872:537133184,83968:536870912,88064:17039488,92160:128,96256:553910272,100352:262272,104448:553910400,108544:0,112640:553648128,116736:16777344,120832:262144,124928:537133056,129024:536871040},{0:268435464,256:8192,512:270532608,768:270540808,1024:268443648,1280:2097152,1536:2097160,1792:268435456,2048:0,2304:268443656,2560:2105344,2816:8,3072:270532616,3328:2105352,3584:8200,3840:270540800,128:270532608,384:270540808,640:8,896:2097152,1152:2105352,1408:268435464,1664:268443648,1920:8200,2176:2097160,2432:8192,2688:268443656,2944:270532616,3200:0,3456:270540800,3712:2105344,3968:268435456,4096:268443648,4352:270532616,4608:270540808,4864:8200,5120:2097152,5376:268435456,5632:268435464,5888:2105344,6144:2105352,6400:0,6656:8,6912:270532608,7168:8192,7424:268443656,7680:270540800,7936:2097160,4224:8,4480:2105344,4736:2097152,4992:268435464,5248:268443648,5504:8200,5760:270540808,6016:270532608,6272:270540800,6528:270532616,6784:8192,7040:2105352,7296:2097160,7552:0,7808:268435456,8064:268443656},{0:1048576,16:33555457,32:1024,48:1049601,64:34604033,80:0,96:1,112:34603009,128:33555456,144:1048577,160:33554433,176:34604032,192:34603008,208:1025,224:1049600,240:33554432,8:34603009,24:0,40:33555457,56:34604032,72:1048576,88:33554433,104:33554432,120:1025,136:1049601,152:33555456,168:34603008,184:1048577,200:1024,216:34604033,232:1,248:1049600,256:33554432,272:1048576,288:33555457,304:34603009,320:1048577,336:33555456,352:34604032,368:1049601,384:1025,400:34604033,416:1049600,432:1,448:0,464:34603008,480:33554433,496:1024,264:1049600,280:33555457,296:34603009,312:1,328:33554432,344:1048576,360:1025,376:34604032,392:33554433,408:34603008,424:0,440:34604033,456:1049601,472:1024,488:33555456,504:1048577},{0:134219808,1:131072,2:134217728,3:32,4:131104,5:134350880,6:134350848,7:2048,8:134348800,9:134219776,10:133120,11:134348832,12:2080,13:0,14:134217760,15:133152,2147483648:2048,2147483649:134350880,2147483650:134219808,2147483651:134217728,2147483652:134348800,2147483653:133120,2147483654:133152,2147483655:32,2147483656:134217760,2147483657:2080,2147483658:131104,2147483659:134350848,2147483660:0,2147483661:134348832,2147483662:134219776,2147483663:131072,16:133152,17:134350848,18:32,19:2048,20:134219776,21:134217760,22:134348832,23:131072,24:0,25:131104,26:134348800,27:134219808,28:134350880,29:133120,30:2080,31:134217728,2147483664:131072,2147483665:2048,2147483666:134348832,2147483667:133152,2147483668:32,2147483669:134348800,2147483670:134217728,2147483671:134219808,2147483672:134350880,2147483673:134217760,2147483674:134219776,2147483675:0,2147483676:133120,2147483677:2080,2147483678:131104,2147483679:134350848}],d=[4160749569,528482304,33030144,2064384,129024,8064,504,2147483679],h=o.DES=i.extend({_doReset:function(){for(var e=this._key.words,t=[],r=0;r<56;r++){var n=s[r]-1;t[r]=e[n>>>5]>>>31-n%32&1}for(var i=this._subKeys=[],o=0;o<16;o++){var u=i[o]=[],d=c[o];for(r=0;r<24;r++)u[r/6|0]|=t[(a[r]-1+d)%28]<<31-r%6,u[4+(r/6|0)]|=t[28+(a[r+24]-1+d)%28]<<31-r%6;for(u[0]=u[0]<<1|u[0]>>>31,r=1;r<7;r++)u[r]=u[r]>>>4*(r-1)+3;u[7]=u[7]<<5|u[7]>>>27}var h=this._invSubKeys=[];for(r=0;r<16;r++)h[r]=i[15-r]},encryptBlock:function(e,t){this._doCryptBlock(e,t,this._subKeys)},decryptBlock:function(e,t){this._doCryptBlock(e,t,this._invSubKeys)},_doCryptBlock:function(e,t,r){this._lBlock=e[t],this._rBlock=e[t+1],p.call(this,4,252645135),p.call(this,16,65535),l.call(this,2,858993459),l.call(this,8,16711935),p.call(this,1,1431655765);for(var n=0;n<16;n++){for(var i=r[n],o=this._lBlock,s=this._rBlock,a=0,c=0;c<8;c++)a|=u[c][((s^i[c])&d[c])>>>0];this._lBlock=s,this._rBlock=o^a}var h=this._lBlock;this._lBlock=this._rBlock,this._rBlock=h,p.call(this,1,1431655765),l.call(this,8,16711935),l.call(this,2,858993459),p.call(this,16,65535),p.call(this,4,252645135),e[t]=this._lBlock,e[t+1]=this._rBlock},keySize:2,ivSize:2,blockSize:2});function p(e,t){var r=(this._lBlock>>>e^this._rBlock)&t;this._rBlock^=r,this._lBlock^=r<>>e^this._lBlock)&t;this._lBlock^=r,this._rBlock^=r<>>2]>>>24-s%4*8&255;o=(o+n[i]+a)%256;var c=n[i];n[i]=n[o],n[o]=c}this._i=this._j=0},_doProcessBlock:function(e,t){e[t]^=o.call(this)},keySize:8,ivSize:0});function o(){for(var e=this._S,t=this._i,r=this._j,n=0,i=0;i<4;i++){r=(r+e[t=(t+1)%256])%256;var o=e[t];e[t]=e[r],e[r]=o,n|=e[(e[t]+e[r])%256]<<24-8*i}return this._i=t,this._j=r,n}e.RC4=t._createHelper(i);var s=r.RC4Drop=i.extend({cfg:i.cfg.extend({drop:192}),_doReset:function(){i._doReset.call(this);for(var e=this.cfg.drop;e>0;e--)o.call(this)}});e.RC4Drop=t._createHelper(s)}(),n.RC4)},function(e,t,r){var n;e.exports=(n=r(0),r(16),r(17),r(13),r(4),function(){var e=n,t=e.lib.StreamCipher,r=e.algo,i=[],o=[],s=[],a=r.Rabbit=t.extend({_doReset:function(){for(var e=this._key.words,t=this.cfg.iv,r=0;r<4;r++)e[r]=16711935&(e[r]<<8|e[r]>>>24)|4278255360&(e[r]<<24|e[r]>>>8);var n=this._X=[e[0],e[3]<<16|e[2]>>>16,e[1],e[0]<<16|e[3]>>>16,e[2],e[1]<<16|e[0]>>>16,e[3],e[2]<<16|e[1]>>>16],i=this._C=[e[2]<<16|e[2]>>>16,4294901760&e[0]|65535&e[1],e[3]<<16|e[3]>>>16,4294901760&e[1]|65535&e[2],e[0]<<16|e[0]>>>16,4294901760&e[2]|65535&e[3],e[1]<<16|e[1]>>>16,4294901760&e[3]|65535&e[0]];for(this._b=0,r=0;r<4;r++)c.call(this);for(r=0;r<8;r++)i[r]^=n[r+4&7];if(t){var o=t.words,s=o[0],a=o[1],u=16711935&(s<<8|s>>>24)|4278255360&(s<<24|s>>>8),d=16711935&(a<<8|a>>>24)|4278255360&(a<<24|a>>>8),h=u>>>16|4294901760&d,p=d<<16|65535&u;for(i[0]^=u,i[1]^=h,i[2]^=d,i[3]^=p,i[4]^=u,i[5]^=h,i[6]^=d,i[7]^=p,r=0;r<4;r++)c.call(this)}},_doProcessBlock:function(e,t){var r=this._X;c.call(this),i[0]=r[0]^r[5]>>>16^r[3]<<16,i[1]=r[2]^r[7]>>>16^r[5]<<16,i[2]=r[4]^r[1]>>>16^r[7]<<16,i[3]=r[6]^r[3]>>>16^r[1]<<16;for(var n=0;n<4;n++)i[n]=16711935&(i[n]<<8|i[n]>>>24)|4278255360&(i[n]<<24|i[n]>>>8),e[t+n]^=i[n]},blockSize:4,ivSize:2});function c(){for(var e=this._X,t=this._C,r=0;r<8;r++)o[r]=t[r];for(t[0]=t[0]+1295307597+this._b|0,t[1]=t[1]+3545052371+(t[0]>>>0>>0?1:0)|0,t[2]=t[2]+886263092+(t[1]>>>0>>0?1:0)|0,t[3]=t[3]+1295307597+(t[2]>>>0>>0?1:0)|0,t[4]=t[4]+3545052371+(t[3]>>>0>>0?1:0)|0,t[5]=t[5]+886263092+(t[4]>>>0>>0?1:0)|0,t[6]=t[6]+1295307597+(t[5]>>>0>>0?1:0)|0,t[7]=t[7]+3545052371+(t[6]>>>0>>0?1:0)|0,this._b=t[7]>>>0>>0?1:0,r=0;r<8;r++){var n=e[r]+t[r],i=65535&n,a=n>>>16,c=((i*i>>>17)+i*a>>>15)+a*a,u=((4294901760&n)*n|0)+((65535&n)*n|0);s[r]=c^u}e[0]=s[0]+(s[7]<<16|s[7]>>>16)+(s[6]<<16|s[6]>>>16)|0,e[1]=s[1]+(s[0]<<8|s[0]>>>24)+s[7]|0,e[2]=s[2]+(s[1]<<16|s[1]>>>16)+(s[0]<<16|s[0]>>>16)|0,e[3]=s[3]+(s[2]<<8|s[2]>>>24)+s[1]|0,e[4]=s[4]+(s[3]<<16|s[3]>>>16)+(s[2]<<16|s[2]>>>16)|0,e[5]=s[5]+(s[4]<<8|s[4]>>>24)+s[3]|0,e[6]=s[6]+(s[5]<<16|s[5]>>>16)+(s[4]<<16|s[4]>>>16)|0,e[7]=s[7]+(s[6]<<8|s[6]>>>24)+s[5]|0}e.Rabbit=t._createHelper(a)}(),n.Rabbit)},function(e,t,r){var n;e.exports=(n=r(0),r(16),r(17),r(13),r(4),function(){var e=n,t=e.lib.StreamCipher,r=e.algo,i=[],o=[],s=[],a=r.RabbitLegacy=t.extend({_doReset:function(){var e=this._key.words,t=this.cfg.iv,r=this._X=[e[0],e[3]<<16|e[2]>>>16,e[1],e[0]<<16|e[3]>>>16,e[2],e[1]<<16|e[0]>>>16,e[3],e[2]<<16|e[1]>>>16],n=this._C=[e[2]<<16|e[2]>>>16,4294901760&e[0]|65535&e[1],e[3]<<16|e[3]>>>16,4294901760&e[1]|65535&e[2],e[0]<<16|e[0]>>>16,4294901760&e[2]|65535&e[3],e[1]<<16|e[1]>>>16,4294901760&e[3]|65535&e[0]];this._b=0;for(var i=0;i<4;i++)c.call(this);for(i=0;i<8;i++)n[i]^=r[i+4&7];if(t){var o=t.words,s=o[0],a=o[1],u=16711935&(s<<8|s>>>24)|4278255360&(s<<24|s>>>8),d=16711935&(a<<8|a>>>24)|4278255360&(a<<24|a>>>8),h=u>>>16|4294901760&d,p=d<<16|65535&u;for(n[0]^=u,n[1]^=h,n[2]^=d,n[3]^=p,n[4]^=u,n[5]^=h,n[6]^=d,n[7]^=p,i=0;i<4;i++)c.call(this)}},_doProcessBlock:function(e,t){var r=this._X;c.call(this),i[0]=r[0]^r[5]>>>16^r[3]<<16,i[1]=r[2]^r[7]>>>16^r[5]<<16,i[2]=r[4]^r[1]>>>16^r[7]<<16,i[3]=r[6]^r[3]>>>16^r[1]<<16;for(var n=0;n<4;n++)i[n]=16711935&(i[n]<<8|i[n]>>>24)|4278255360&(i[n]<<24|i[n]>>>8),e[t+n]^=i[n]},blockSize:4,ivSize:2});function c(){for(var e=this._X,t=this._C,r=0;r<8;r++)o[r]=t[r];for(t[0]=t[0]+1295307597+this._b|0,t[1]=t[1]+3545052371+(t[0]>>>0>>0?1:0)|0,t[2]=t[2]+886263092+(t[1]>>>0>>0?1:0)|0,t[3]=t[3]+1295307597+(t[2]>>>0>>0?1:0)|0,t[4]=t[4]+3545052371+(t[3]>>>0>>0?1:0)|0,t[5]=t[5]+886263092+(t[4]>>>0>>0?1:0)|0,t[6]=t[6]+1295307597+(t[5]>>>0>>0?1:0)|0,t[7]=t[7]+3545052371+(t[6]>>>0>>0?1:0)|0,this._b=t[7]>>>0>>0?1:0,r=0;r<8;r++){var n=e[r]+t[r],i=65535&n,a=n>>>16,c=((i*i>>>17)+i*a>>>15)+a*a,u=((4294901760&n)*n|0)+((65535&n)*n|0);s[r]=c^u}e[0]=s[0]+(s[7]<<16|s[7]>>>16)+(s[6]<<16|s[6]>>>16)|0,e[1]=s[1]+(s[0]<<8|s[0]>>>24)+s[7]|0,e[2]=s[2]+(s[1]<<16|s[1]>>>16)+(s[0]<<16|s[0]>>>16)|0,e[3]=s[3]+(s[2]<<8|s[2]>>>24)+s[1]|0,e[4]=s[4]+(s[3]<<16|s[3]>>>16)+(s[2]<<16|s[2]>>>16)|0,e[5]=s[5]+(s[4]<<8|s[4]>>>24)+s[3]|0,e[6]=s[6]+(s[5]<<16|s[5]>>>16)+(s[4]<<16|s[4]>>>16)|0,e[7]=s[7]+(s[6]<<8|s[6]>>>24)+s[5]|0}e.RabbitLegacy=t._createHelper(a)}(),n.RabbitLegacy)},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(2),s=r(12),a=r(30),c=r(20),u=function(e){function t(t,r,n){return e.call(this,t,r,n,c.TransactionState.Proceeding,"sip.transaction.ist")||this}return i(t,e),t.prototype.dispose=function(){this.stopProgressExtensionTimer(),this.H&&(clearTimeout(this.H),this.H=void 0),this.I&&(clearTimeout(this.I),this.I=void 0),this.L&&(clearTimeout(this.L),this.L=void 0),e.prototype.dispose.call(this)},Object.defineProperty(t.prototype,"kind",{get:function(){return"ist"},enumerable:!0,configurable:!0}),t.prototype.receiveRequest=function(e){var t=this;switch(this.state){case c.TransactionState.Proceeding:if(e.method===o.C.INVITE)return void(this.lastProvisionalResponse&&this.send(this.lastProvisionalResponse).catch(function(e){t.logTransportError(e,"Failed to send retransmission of provisional response.")}));break;case c.TransactionState.Accepted:if(e.method===o.C.INVITE)return;break;case c.TransactionState.Completed:if(e.method===o.C.INVITE){if(!this.lastFinalResponse)throw new Error("Last final response undefined.");return void this.send(this.lastFinalResponse).catch(function(e){t.logTransportError(e,"Failed to send retransmission of final response.")})}if(e.method===o.C.ACK)return void this.stateTransition(c.TransactionState.Confirmed);break;case c.TransactionState.Confirmed:case c.TransactionState.Terminated:if(e.method===o.C.INVITE||e.method===o.C.ACK)return;break;default:throw new Error("Invalid state "+this.state)}var r="INVITE server transaction received unexpected "+e.method+" request while in state "+this.state+".";this.logger.warn(r)},t.prototype.receiveResponse=function(e,t){var r=this;if(e<100||e>699)throw new Error("Invalid status code "+e);switch(this.state){case c.TransactionState.Proceeding:if(e>=100&&e<=199)return this.lastProvisionalResponse=t,e>100&&this.startProgressExtensionTimer(),void this.send(t).catch(function(e){r.logTransportError(e,"Failed to send 1xx response.")});if(e>=200&&e<=299)return this.lastFinalResponse=t,this.stateTransition(c.TransactionState.Accepted),void this.send(t).catch(function(e){r.logTransportError(e,"Failed to send 2xx response.")});if(e>=300&&e<=699)return this.lastFinalResponse=t,this.stateTransition(c.TransactionState.Completed),void this.send(t).catch(function(e){r.logTransportError(e,"Failed to send non-2xx final response.")});break;case c.TransactionState.Accepted:if(e>=200&&e<=299)return void this.send(t).catch(function(e){r.logTransportError(e,"Failed to send 2xx response.")});break;case c.TransactionState.Completed:case c.TransactionState.Confirmed:case c.TransactionState.Terminated:break;default:throw new Error("Invalid state "+this.state)}var n="INVITE server transaction received unexpected "+e+" response from TU while in state "+this.state+".";throw this.logger.error(n),new Error(n)},t.prototype.retransmitAcceptedResponse=function(){var e=this;this.state===c.TransactionState.Accepted&&this.lastFinalResponse&&this.send(this.lastFinalResponse).catch(function(t){e.logTransportError(t,"Failed to send 2xx response.")})},t.prototype.onTransportError=function(e){this.user.onTransportError&&this.user.onTransportError(e)},t.prototype.typeToString=function(){return"INVITE server transaction"},t.prototype.stateTransition=function(e){var t=this,r=function(){throw new Error("Invalid state transition from "+t.state+" to "+e)};switch(e){case c.TransactionState.Proceeding:r();break;case c.TransactionState.Accepted:case c.TransactionState.Completed:this.state!==c.TransactionState.Proceeding&&r();break;case c.TransactionState.Confirmed:this.state!==c.TransactionState.Completed&&r();break;case c.TransactionState.Terminated:this.state!==c.TransactionState.Accepted&&this.state!==c.TransactionState.Completed&&this.state!==c.TransactionState.Confirmed&&r();break;default:r()}this.stopProgressExtensionTimer(),e===c.TransactionState.Accepted&&(this.L=setTimeout(function(){return t.timer_L()},s.Timers.TIMER_L)),e===c.TransactionState.Completed&&(this.H=setTimeout(function(){return t.timer_H()},s.Timers.TIMER_H)),e===c.TransactionState.Confirmed&&(this.I=setTimeout(function(){return t.timer_I()},s.Timers.TIMER_I)),e===c.TransactionState.Terminated&&this.dispose(),this.setState(e)},t.prototype.startProgressExtensionTimer=function(){var e=this;void 0===this.progressExtensionTimer&&(this.progressExtensionTimer=setInterval(function(){if(e.logger.debug("Progress extension timer expired for INVITE server transaction "+e.id+"."),!e.lastProvisionalResponse)throw new Error("Last provisional response undefined.");e.send(e.lastProvisionalResponse).catch(function(t){e.logTransportError(t,"Failed to send retransmission of provisional response.")})},s.Timers.PROVISIONAL_RESPONSE_INTERVAL))},t.prototype.stopProgressExtensionTimer=function(){void 0!==this.progressExtensionTimer&&(clearInterval(this.progressExtensionTimer),this.progressExtensionTimer=void 0)},t.prototype.timer_G=function(){},t.prototype.timer_H=function(){this.logger.debug("Timer H expired for INVITE server transaction "+this.id+"."),this.state===c.TransactionState.Completed&&(this.logger.warn("ACK to negative final response was never received, terminating transaction."),this.stateTransition(c.TransactionState.Terminated))},t.prototype.timer_I=function(){this.logger.debug("Timer I expired for INVITE server transaction "+this.id+"."),this.stateTransition(c.TransactionState.Terminated)},t.prototype.timer_L=function(){this.logger.debug("Timer L expired for INVITE server transaction "+this.id+"."),this.state===c.TransactionState.Accepted&&this.stateTransition(c.TransactionState.Terminated)},t}(a.ServerTransaction);t.InviteServerTransaction=u},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(12),s=r(28),a=r(20),c=function(e){function t(t,r,n){var i=e.call(this,t,r,n,a.TransactionState.Trying,"sip.transaction.nict")||this;return i.F=setTimeout(function(){return i.timer_F()},o.Timers.TIMER_F),i.send(t.toString()).catch(function(e){i.logTransportError(e,"Failed to send initial outgoing request.")}),i}return i(t,e),t.prototype.dispose=function(){this.F&&(clearTimeout(this.F),this.F=void 0),this.K&&(clearTimeout(this.K),this.K=void 0),e.prototype.dispose.call(this)},Object.defineProperty(t.prototype,"kind",{get:function(){return"nict"},enumerable:!0,configurable:!0}),t.prototype.receiveResponse=function(e){var t=e.statusCode;if(!t||t<100||t>699)throw new Error("Invalid status code "+t);switch(this.state){case a.TransactionState.Trying:if(t>=100&&t<=199)return this.stateTransition(a.TransactionState.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=699)return this.stateTransition(a.TransactionState.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case a.TransactionState.Proceeding:if(t>=100&&t<=199&&this.user.receiveResponse)return this.user.receiveResponse(e);if(t>=200&&t<=699)return this.stateTransition(a.TransactionState.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));case a.TransactionState.Completed:case a.TransactionState.Terminated:return;default:throw new Error("Invalid state "+this.state)}var r="Non-INVITE client transaction received unexpected "+t+" response while in state "+this.state+".";this.logger.warn(r)},t.prototype.onTransportError=function(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(a.TransactionState.Terminated,!0)},t.prototype.typeToString=function(){return"non-INVITE client transaction"},t.prototype.stateTransition=function(e,t){var r=this;void 0===t&&(t=!1);var n=function(){throw new Error("Invalid state transition from "+r.state+" to "+e)};switch(e){case a.TransactionState.Trying:n();break;case a.TransactionState.Proceeding:this.state!==a.TransactionState.Trying&&n();break;case a.TransactionState.Completed:this.state!==a.TransactionState.Trying&&this.state!==a.TransactionState.Proceeding&&n();break;case a.TransactionState.Terminated:this.state!==a.TransactionState.Trying&&this.state!==a.TransactionState.Proceeding&&this.state!==a.TransactionState.Completed&&(t||n());break;default:n()}e===a.TransactionState.Completed&&(this.F&&(clearTimeout(this.F),this.F=void 0),this.K=setTimeout(function(){return r.timer_K()},o.Timers.TIMER_K)),e===a.TransactionState.Terminated&&this.dispose(),this.setState(e)},t.prototype.timer_F=function(){this.logger.debug("Timer F expired for non-INVITE client transaction "+this.id+"."),this.state!==a.TransactionState.Trying&&this.state!==a.TransactionState.Proceeding||(this.onRequestTimeout(),this.stateTransition(a.TransactionState.Terminated))},t.prototype.timer_K=function(){this.state===a.TransactionState.Completed&&this.stateTransition(a.TransactionState.Terminated)},t}(s.ClientTransaction);t.NonInviteClientTransaction=c},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(12),s=r(30),a=r(20),c=function(e){function t(t,r,n){return e.call(this,t,r,n,a.TransactionState.Trying,"sip.transaction.nist")||this}return i(t,e),t.prototype.dispose=function(){this.J&&(clearTimeout(this.J),this.J=void 0),e.prototype.dispose.call(this)},Object.defineProperty(t.prototype,"kind",{get:function(){return"nist"},enumerable:!0,configurable:!0}),t.prototype.receiveRequest=function(e){var t=this;switch(this.state){case a.TransactionState.Trying:break;case a.TransactionState.Proceeding:if(!this.lastResponse)throw new Error("Last response undefined.");this.send(this.lastResponse).catch(function(e){t.logTransportError(e,"Failed to send retransmission of provisional response.")});break;case a.TransactionState.Completed:if(!this.lastResponse)throw new Error("Last response undefined.");this.send(this.lastResponse).catch(function(e){t.logTransportError(e,"Failed to send retransmission of final response.")});break;case a.TransactionState.Terminated:break;default:throw new Error("Invalid state "+this.state)}},t.prototype.receiveResponse=function(e,t){var r=this;if(e<100||e>699)throw new Error("Invalid status code "+e);if(e>100&&e<=199)throw new Error("Provisional response other than 100 not allowed.");switch(this.state){case a.TransactionState.Trying:if(this.lastResponse=t,e>=100&&e<200)return this.stateTransition(a.TransactionState.Proceeding),void this.send(t).catch(function(e){r.logTransportError(e,"Failed to send provisional response.")});if(e>=200&&e<=699)return this.stateTransition(a.TransactionState.Completed),void this.send(t).catch(function(e){r.logTransportError(e,"Failed to send final response.")});break;case a.TransactionState.Proceeding:if(this.lastResponse=t,e>=200&&e<=699)return this.stateTransition(a.TransactionState.Completed),void this.send(t).catch(function(e){r.logTransportError(e,"Failed to send final response.")});break;case a.TransactionState.Completed:return;case a.TransactionState.Terminated:break;default:throw new Error("Invalid state "+this.state)}var n="Non-INVITE server transaction received unexpected "+e+" response from TU while in state "+this.state+".";throw this.logger.error(n),new Error(n)},t.prototype.onTransportError=function(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(a.TransactionState.Terminated,!0)},t.prototype.typeToString=function(){return"non-INVITE server transaction"},t.prototype.stateTransition=function(e,t){var r=this;void 0===t&&(t=!1);var n=function(){throw new Error("Invalid state transition from "+r.state+" to "+e)};switch(e){case a.TransactionState.Trying:n();break;case a.TransactionState.Proceeding:this.state!==a.TransactionState.Trying&&n();break;case a.TransactionState.Completed:this.state!==a.TransactionState.Trying&&this.state!==a.TransactionState.Proceeding&&n();break;case a.TransactionState.Terminated:this.state!==a.TransactionState.Proceeding&&this.state!==a.TransactionState.Completed&&(t||n());break;default:n()}e===a.TransactionState.Completed&&(this.J=setTimeout(function(){return r.timer_J()},o.Timers.TIMER_J)),e===a.TransactionState.Terminated&&this.dispose(),this.setState(e)},t.prototype.timer_J=function(){this.logger.debug("Timer J expired for NON-INVITE server transaction "+this.id+"."),this.state===a.TransactionState.Completed&&this.stateTransition(a.TransactionState.Terminated)},t}(s.ServerTransaction);t.NonInviteServerTransaction=c},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(8);function i(e){return!(!e||"string"!=typeof e.content||"string"!=typeof e.contentType||void 0!==e.contentDisposition)||"string"==typeof e.contentDisposition}function o(e){return"application/sdp"===e?"session":"render"}t.fromBodyObj=function(e){var t=e.body,r=e.contentType;return{contentDisposition:o(r),contentType:r,content:t}},t.fromBodyLegacy=function(e){var t="string"==typeof e?e:e.body,r="string"==typeof e?"application/sdp":e.contentType;return{contentDisposition:o(r),contentType:r,content:t}},t.getBody=function(e){var t,r,s,a;if(e instanceof n.IncomingRequest&&e.body&&(t=(a=e.parseHeader("Content-Disposition"))?a.type:void 0,r=e.parseHeader("Content-Type"),s=e.body),e instanceof n.IncomingResponse&&e.body&&(t=(a=e.parseHeader("Content-Disposition"))?a.type:void 0,r=e.parseHeader("Content-Type"),s=e.body),e instanceof n.OutgoingRequest&&e.body)if(t=e.getHeader("Content-Disposition"),r=e.getHeader("Content-Type"),"string"==typeof e.body){if(!r)throw new Error("Header content type header does not equal body content type.");s=e.body}else{if(r&&r!==e.body.contentType)throw new Error("Header content type header does not equal body content type.");r=e.body.contentType,s=e.body.body}if(i(e)&&(t=e.contentDisposition,r=e.contentType,s=e.content),s){if(r&&!t&&(t=o(r)),!t)throw new Error("Content disposition undefined.");if(!r)throw new Error("Content type undefined.");return{contentDisposition:t,contentType:r,content:s}}},t.isBody=i,t.toBodyObj=function(e){return{body:e.content,contentType:e.contentType}}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(8),i=r(5);t.constructOutgoingResponse=function(e,t){var r="\r\n",o=i.Utils.buildStatusLine(t.statusCode,t.reasonPhrase);t.statusCode>=100&&t.statusCode,t.statusCode;var s="From: "+e.getHeader("From")+r,a="Call-ID: "+e.callId+r,c="CSeq: "+e.cseq+" "+e.method+r,u=e.getHeaders("via").reduce(function(e,t){return e+"Via: "+t+r},""),d="To: "+e.getHeader("to");if(t.statusCode>100&&!e.parseHeader("to").hasParam("tag")){var h=t.toTag;h||(h=i.Utils.newTag()),d+=";tag="+h}d+=r;var p=n.getSupportedHeader(e),l="";t.userAgent&&(l="User-Agent: "+t.userAgent+r);var f="";return t.extraHeaders&&(f=t.extraHeaders.reduce(function(e,t){return e+t.trim()+r},"")),o+=u,o+=s,o+=d,o+=c,o+=a,o+=p,o+=l,o+=f,t.body?(o+="Content-Type: "+t.body.contentType+r,o+="Content-Length: "+i.Utils.str_utf8_length(t.body.content)+r+r,o+=t.body.content):o+="Content-Length: 0\r\n\r\n",{message:o}}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e){e.Initial="Initial",e.Early="Early",e.AckWait="AckWait",e.Confirmed="Confirmed",e.Terminated="Terminated"}(t.SessionState||(t.SessionState={})),function(e){e.Initial="Initial",e.HaveLocalOffer="HaveLocalOffer",e.HaveRemoteOffer="HaveRemoteOffer",e.Stable="Stable",e.Closed="Closed"}(t.SignalingState||(t.SignalingState={}))},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(10),s=r(2),a=r(14),c=r(3),u=r(7),d=r(5),h=function(e){function t(t,r,n){void 0===n&&(n={});var i=e.call(this)||this;if(i.C={MIN_DURATION:70,MAX_DURATION:6e3,DEFAULT_DURATION:100,MIN_INTER_TONE_GAP:50,DEFAULT_INTER_TONE_GAP:500},i.type=c.TypeStrings.DTMF,void 0===r)throw new TypeError("Not enough arguments");if(i.logger=t.ua.getLogger("sip.invitecontext.dtmf",t.id),i.owner=t,"string"==typeof r)r=r.toUpperCase();else{if("number"!=typeof r)throw new TypeError("Invalid tone: "+r);r=r.toString()}if(!r.match(/^[0-9A-D#*]$/))throw new TypeError("Invalid tone: "+r);i.tone=r;var o=n.duration,s=n.interToneGap;if(o&&!d.Utils.isDecimal(o))throw new TypeError("Invalid tone duration: "+o);if(o?oi.C.MAX_DURATION?(i.logger.warn("'duration' value is greater than the maximum allowed, setting it to "+i.C.MAX_DURATION+" milliseconds"),o=i.C.MAX_DURATION):o=Math.abs(o):o=i.C.DEFAULT_DURATION,i.duration=o,s&&!d.Utils.isDecimal(s))throw new TypeError("Invalid interToneGap: "+s);return s?s1)this.logger.warn("More than one Via header field present in the response, dropping");else{var t=e.viaBranch+e.method,r=this.userAgentClients.get(t);r?r.transaction.receiveResponse(e):this.logger.warn("Discarding unmatched "+e.statusCode+" response to "+e.method+" "+t+".")}},e}();t.UserAgentCore=d},function(e,t,r){"use strict";function n(e){for(var r in e)t.hasOwnProperty(r)||(t[r]=e[r])}Object.defineProperty(t,"__esModule",{value:!0}),n(r(49)),n(r(50)),n(r(101)),n(r(51)),n(r(102)),n(r(105)),n(r(106)),n(r(107)),n(r(53)),n(r(34)),n(r(108)),n(r(54)),n(r(55)),n(r(56)),n(r(57)),n(r(61)),n(r(109)),n(r(58)),n(r(59)),n(r(110)),n(r(111)),n(r(112)),n(r(6)),n(r(9))},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(1),s=function(e){function t(t,r,n){return e.call(this,o.NonInviteClientTransaction,t,r,n)||this}return i(t,e),t}(r(6).UserAgentClient);t.CancelUserAgentClient=s},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(52),s=r(1),a=function(e){function t(t,r,n){var i=e.call(this,s.InviteClientTransaction,t,r,n)||this;return i.confirmedDialogAcks=new Map,i.confirmedDialogs=new Map,i.earlyDialogs=new Map,i.delegate=n,i}return i(t,e),t.prototype.dispose=function(){this.earlyDialogs.forEach(function(e){return e.dispose()}),this.earlyDialogs.clear(),e.prototype.dispose.call(this)},t.prototype.receiveResponse=function(e){var t=this;if(this.authenticationGuard(e)){var r=e.statusCode?e.statusCode.toString():"";if(!r)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(r):return void(this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e}));case/^1[0-9]{2}$/.test(r):if(!e.toTag)return void this.logger.warn("Non-100 1xx INVITE response received without a to tag, dropping.");var n=o.Dialog.initialDialogStateForUserAgentClient(this.message,e),i=this.earlyDialogs.get(n.id);if(!i){if(!((u=this.transaction)instanceof s.InviteClientTransaction))throw new Error("Transaction not instance of InviteClientTransaction.");i=new o.SessionDialog(u,this.core,n),this.earlyDialogs.set(i.id,i)}if(!i.reliableSequenceGuard(e))return void this.logger.warn("1xx INVITE reliable response received out of order, dropping.");i.signalingStateTransition(e);var a=i;return void(this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e,session:a,prack:function(e){return a.prack(void 0,e)}}));case/^2[0-9]{2}$/.test(r):n=o.Dialog.initialDialogStateForUserAgentClient(this.message,e);var c=this.confirmedDialogs.get(n.id);if(c){if(h=this.confirmedDialogAcks.get(n.id)){if(!((u=this.transaction)instanceof s.InviteClientTransaction))throw new Error("Client transaction not instance of InviteClientTransaction.");u.ackResponse(h.message)}return}if(c=this.earlyDialogs.get(n.id))c.confirm(),c.recomputeRouteSet(e),this.earlyDialogs.delete(c.id),this.confirmedDialogs.set(c.id,c);else{var u;if(!((u=this.transaction)instanceof s.InviteClientTransaction))throw new Error("Transaction not instance of InviteClientTransaction.");c=new o.SessionDialog(u,this.core,n),this.confirmedDialogs.set(c.id,c)}c.signalingStateTransition(e);var d=c;if(this.delegate&&this.delegate.onAccept)this.delegate.onAccept({message:e,session:d,ack:function(e){var r=d.ack(e);return t.confirmedDialogAcks.set(d.id,r),r}});else{var h=d.ack();this.confirmedDialogAcks.set(d.id,h)}return;case/^3[0-9]{2}$/.test(r):return this.earlyDialogs.forEach(function(e){return e.dispose()}),this.earlyDialogs.clear(),void(this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e}));case/^[4-6][0-9]{2}$/.test(r):return this.earlyDialogs.forEach(function(e){return e.dispose()}),this.earlyDialogs.clear(),void(this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e}));default:throw new Error("Invalid status code "+r)}throw new Error("Executing what should be an unreachable code path receiving "+r+" response.")}},t}(r(6).UserAgentClient);t.InviteUserAgentClient=a},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(2),s=r(18),a=r(8),c=r(12),u=r(14),d=r(31),h=r(1),p=r(49),l=r(50),f=r(104),g=r(51),v=r(53),m=r(34),y=r(54),S=r(55),T=r(56),C=r(57),b=r(58),_=r(59),A=function(e){function t(t,r,n,i){var o=e.call(this,r,n)||this;return o.initialTransaction=t,o._signalingState=d.SignalingState.Initial,o.ackWait=!1,o.delegate=i,t instanceof h.InviteServerTransaction&&(o.ackWait=!0),o.early||o.start2xxRetransmissionTimer(),o.signalingStateTransition(t.request),o.logger=r.loggerFactory.getLogger("sip.invite-dialog"),o.logger.log("INVITE dialog "+o.id+" constructed"),o}return i(t,e),t.prototype.dispose=function(){e.prototype.dispose.call(this),this._signalingState=d.SignalingState.Closed,this._offer=void 0,this._answer=void 0,this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.logger.log("INVITE dialog "+this.id+" destroyed")},Object.defineProperty(t.prototype,"sessionState",{get:function(){return this.early?d.SessionState.Early:this.ackWait?d.SessionState.AckWait:this._signalingState===d.SignalingState.Closed?d.SessionState.Terminated:d.SessionState.Confirmed},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"signalingState",{get:function(){return this._signalingState},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"offer",{get:function(){return this._offer},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"answer",{get:function(){return this._answer},enumerable:!0,configurable:!0}),t.prototype.confirm=function(){this.early&&this.start2xxRetransmissionTimer(),e.prototype.confirm.call(this)},t.prototype.reConfirm=function(){this.reinviteUserAgentServer&&this.startReInvite2xxRetransmissionTimer()},t.prototype.ack=function(e){var t;if(void 0===e&&(e={}),this.logger.log("INVITE dialog "+this.id+" sending ACK request"),this.reinviteUserAgentClient){if(!(this.reinviteUserAgentClient.transaction instanceof h.InviteClientTransaction))throw new Error("Transaction not instance of InviteClientTransaction.");t=this.reinviteUserAgentClient.transaction,this.reinviteUserAgentClient=void 0}else{if(!(this.initialTransaction instanceof h.InviteClientTransaction))throw new Error("Initial transaction not instance of InviteClientTransaction.");t=this.initialTransaction}e.cseq=t.request.cseq;var r=this.createOutgoingRequestMessage(o.C.ACK,e);return t.ackResponse(r),this.signalingStateTransition(r),{message:r}},t.prototype.bye=function(e,t){if(this.logger.log("INVITE dialog "+this.id+" sending BYE request"),this.initialTransaction instanceof h.InviteServerTransaction){if(this.early)throw new Error("UAS MUST NOT send a BYE on early dialogs.");if(this.ackWait&&this.initialTransaction.state!==h.TransactionState.Terminated)throw new Error("UAS MUST NOT send a BYE on a confirmed dialog until it has received an ACK for its 2xx response or until the server transaction times out.")}return new p.ByeUserAgentClient(this,e,t)},t.prototype.info=function(e,t){if(this.logger.log("INVITE dialog "+this.id+" sending INFO request"),this.early)throw new Error("Dialog not confirmed.");return new f.InfoUserAgentClient(this,e,t)},t.prototype.invite=function(e,t){if(this.logger.log("INVITE dialog "+this.id+" sending INVITE request"),this.early)throw new Error("Dialog not confirmed.");if(this.reinviteUserAgentClient)throw new Error("There is an ongoing re-INVITE client transaction.");if(this.reinviteUserAgentServer)throw new Error("There is an ongoing re-INVITE server transaction.");return new T.ReInviteUserAgentClient(this,e,t)},t.prototype.notify=function(e,t){if(this.logger.log("INVITE dialog "+this.id+" sending NOTIFY request"),this.early)throw new Error("Dialog not confirmed.");return new v.NotifyUserAgentClient(this,e,t)},t.prototype.prack=function(e,t){return this.logger.log("INVITE dialog "+this.id+" sending PRACK request"),new y.PrackUserAgentClient(this,e,t)},t.prototype.refer=function(e,t){if(this.logger.log("INVITE dialog "+this.id+" sending REFER request"),this.early)throw new Error("Dialog not confirmed.");return new b.ReferUserAgentClient(this,e,t)},t.prototype.receiveRequest=function(t){if(this.logger.log("INVITE dialog "+this.id+" received "+t.method+" request"),t.method===o.C.ACK){if(this.ackWait){if(this.initialTransaction instanceof h.InviteClientTransaction)return void this.logger.warn("INVITE dialog "+this.id+" received unexpected "+t.method+" request, dropping.");if(this.initialTransaction.request.cseq!==t.cseq)return void this.logger.warn("INVITE dialog "+this.id+" received unexpected "+t.method+" request, dropping.");this.ackWait=!1}else{if(!this.reinviteUserAgentServer)return void this.logger.warn("INVITE dialog "+this.id+" received unexpected "+t.method+" request, dropping.");if(this.reinviteUserAgentServer.transaction.request.cseq!==t.cseq)return void this.logger.warn("INVITE dialog "+this.id+" received unexpected "+t.method+" request, dropping.");this.reinviteUserAgentServer=void 0}return this.signalingStateTransition(t),void(this.delegate&&this.delegate.onAck&&this.delegate.onAck({message:t}))}if(this.sequenceGuard(t)){if(t.method===o.C.INVITE){if(this.reinviteUserAgentServer){var r=["Retry-After: "+(Math.floor(10*Math.random())+1)];return void this.core.replyStateless(t,{statusCode:500,extraHeaders:r})}if(this.reinviteUserAgentClient)return void this.core.replyStateless(t,{statusCode:491})}if(e.prototype.receiveRequest.call(this,t),t.method===o.C.INVITE){var n=t.parseHeader("contact");if(!n)throw new Error("Contact undefined.");if(!(n instanceof s.NameAddrHeader))throw new Error("Contact not instance of NameAddrHeader.");this.dialogState.remoteTarget=n.uri}switch(t.method){case o.C.BYE:var i=new l.ByeUserAgentServer(this,t);this.delegate&&this.delegate.onBye?this.delegate.onBye(i):i.accept(),this.dispose();break;case o.C.INFO:i=new g.InfoUserAgentServer(this,t);this.delegate&&this.delegate.onInfo?this.delegate.onInfo(i):i.reject({statusCode:469,extraHeaders:["Recv-Info :"]});break;case o.C.INVITE:i=new C.ReInviteUserAgentServer(this,t);this.delegate&&this.delegate.onInvite?this.delegate.onInvite(i):i.reject({statusCode:488});break;case o.C.NOTIFY:i=new m.NotifyUserAgentServer(this,t);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(i):i.accept();break;case o.C.PRACK:i=new S.PrackUserAgentServer(this,t);this.delegate&&this.delegate.onPrack?this.delegate.onPrack(i):i.accept();break;case o.C.REFER:i=new _.ReferUserAgentServer(this,t);this.delegate&&this.delegate.onRefer?this.delegate.onRefer(i):i.reject();break;default:this.logger.log("INVITE dialog "+this.id+" received unimplemented "+t.method+" request"),this.core.replyStateless(t,{statusCode:501})}}else this.logger.log("INVITE dialog "+this.id+" rejected out of order "+t.method+" request.")},t.prototype.reliableSequenceGuard=function(e){var t=e.statusCode;if(!t)throw new Error("Status code undefined");if(t>100&&t<200){var r=e.getHeader("require"),n=e.getHeader("rseq"),i=r&&r.includes("100rel")&&n?Number(n):void 0;if(i){if(this.rseq&&this.rseq+1!==i)return!1;this.rseq||(this.rseq=i)}}return!0},t.prototype.signalingStateTransition=function(e){var t=u.getBody(e);if(t&&"session"===t.contentDisposition){if(e instanceof a.IncomingRequest)switch(this._signalingState){case d.SignalingState.Initial:case d.SignalingState.Stable:this._signalingState=d.SignalingState.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case d.SignalingState.HaveLocalOffer:this._signalingState=d.SignalingState.Stable,this._answer=t;break;case d.SignalingState.HaveRemoteOffer:case d.SignalingState.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof a.IncomingResponse)switch(this._signalingState){case d.SignalingState.Initial:case d.SignalingState.Stable:this._signalingState=d.SignalingState.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case d.SignalingState.HaveLocalOffer:this._signalingState=d.SignalingState.Stable,this._answer=t;break;case d.SignalingState.HaveRemoteOffer:case d.SignalingState.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof a.OutgoingRequest)switch(this._signalingState){case d.SignalingState.Initial:case d.SignalingState.Stable:this._signalingState=d.SignalingState.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case d.SignalingState.HaveLocalOffer:break;case d.SignalingState.HaveRemoteOffer:this._signalingState=d.SignalingState.Stable,this._answer=t;break;case d.SignalingState.Closed:break;default:throw new Error("Unexpected signaling state.")}if(u.isBody(e))switch(this._signalingState){case d.SignalingState.Initial:case d.SignalingState.Stable:this._signalingState=d.SignalingState.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case d.SignalingState.HaveLocalOffer:break;case d.SignalingState.HaveRemoteOffer:this._signalingState=d.SignalingState.Stable,this._answer=t;break;case d.SignalingState.Closed:break;default:throw new Error("Unexpected signaling state.")}}},t.prototype.start2xxRetransmissionTimer=function(){var e=this;if(this.initialTransaction instanceof h.InviteServerTransaction){var t=this.initialTransaction,r=c.Timers.T1,n=function(){e.ackWait?(e.logger.log("No ACK for 2xx response received, attempting retransmission"),t.retransmitAcceptedResponse(),r=Math.min(2*r,c.Timers.T2),e.invite2xxTimer=setTimeout(n,r)):e.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(n,r);var i=function(){t.state===h.TransactionState.Terminated&&(t.removeListener("stateChanged",i),e.invite2xxTimer&&(clearTimeout(e.invite2xxTimer),e.invite2xxTimer=void 0),e.ackWait&&(e.delegate&&e.delegate.onAckTimeout?e.delegate.onAckTimeout():e.bye()))};t.addListener("stateChanged",i)}},t.prototype.startReInvite2xxRetransmissionTimer=function(){var e=this;if(this.reinviteUserAgentServer&&this.reinviteUserAgentServer.transaction instanceof h.InviteServerTransaction){var t=this.reinviteUserAgentServer.transaction,r=c.Timers.T1,n=function(){e.reinviteUserAgentServer?(e.logger.log("No ACK for 2xx response received, attempting retransmission"),t.retransmitAcceptedResponse(),r=Math.min(2*r,c.Timers.T2),e.invite2xxTimer=setTimeout(n,r)):e.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(n,r);var i=function(){t.state===h.TransactionState.Terminated&&(t.removeListener("stateChanged",i),e.invite2xxTimer&&(clearTimeout(e.invite2xxTimer),e.invite2xxTimer=void 0),e.reinviteUserAgentServer)};t.addListener("stateChanged",i)}},t}(r(33).Dialog);t.SessionDialog=A},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(2),s=r(1),a=function(e){function t(t,r,n){var i=t.createOutgoingRequestMessage(o.C.INFO,n);return e.call(this,s.NonInviteClientTransaction,t.userAgentCore,i,r)||this}return i(t,e),t}(r(6).UserAgentClient);t.InfoUserAgentClient=a},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}),o=this&&this.__assign||function(){return(o=Object.assign||function(e){for(var t,r=1,n=arguments.length;r=200&&t.statusCode<300){var r=t.getHeader("Expires");if(r){var n=Number(r);n>this.subscriptionExpiresRequested&&this.logger.warn("Expires header in a 200-class response to SUBSCRIBE with a higher value than the one in the request"),nthis.subscriptionExpires&&(this.dialog.subscriptionExpires=this.subscriptionExpires)}t.statusCode&&t.statusCode>=300&&t.statusCode<700&&this.waitNotifyStop(),e.prototype.receiveResponse.call(this,t)}},t.prototype.timer_N=function(){this.logger.warn("Timer N expired for SUBSCRIBE user agent client. Timed out waiting for NOTIFY."),this.waitNotifyStop(),this.delegate&&this.delegate.onNotifyTimeout&&this.delegate.onNotifyTimeout()},t}(r(6).UserAgentClient);t.SubscribeUserAgentClient=u},function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o=r(1),s=function(e){function t(t,r,n){var i=e.call(this,o.NonInviteServerTransaction,t,r,n)||this;return i.core=t,i}return i(t,e),t}(r(9).UserAgentServer);t.SubscribeUserAgentServer=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(8),i=r(19);t.makeUserAgentCoreConfigurationFromUA=function(e){if(!(e.configuration.uri instanceof i.URI))throw new Error("Configuration URI not instance of URI.");return{aor:e.configuration.uri,contact:e.contact,loggerFactory:e.getLoggerFactory(),userAgentHeaderFieldValue:e.configuration.userAgentString,authenticationFactory:function(){if(e.configuration.authenticationFactory)return e.configuration.authenticationFactory(e)},onRequestTimeoutResponseMessageFactory:function(){var t=new n.IncomingResponse(e);return t.statusCode=408,t.reasonPhrase="Request Timeout",t},onTransportErrorResponseMessageFactory:function(){var t=new n.IncomingResponse(e);return t.statusCode=503,t.reasonPhrase="Service Unavailable",t},outgoingRequestMessageFactory:function(t,r,i,o,s){return new n.OutgoingRequest(t,r,e,i,o,s)},transportAccessor:function(){return e.transport}}}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(3),i=function(){function e(e,t){this.type=n.TypeStrings.SessionDescriptionHandlerObserver,this.session=e,this.options=t}return e.prototype.trackAdded=function(){this.session.emit("trackAdded")},e.prototype.directionChanged=function(){this.session.emit("directionChanged")},e}();t.SessionDescriptionHandlerObserver=i},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(35);t.Modifiers=n;var i=r(116);t.Simple=i.Simple;var o=r(62);t.SessionDescriptionHandler=o.SessionDescriptionHandler;var s=r(63);t.Transport=s.Transport},function(e,t,r){"use strict";(function(e){var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var o,s=r(10),a=r(48),c=r(35);!function(e){e[e.STATUS_NULL=0]="STATUS_NULL",e[e.STATUS_NEW=1]="STATUS_NEW",e[e.STATUS_CONNECTING=2]="STATUS_CONNECTING",e[e.STATUS_CONNECTED=3]="STATUS_CONNECTED",e[e.STATUS_COMPLETED=4]="STATUS_COMPLETED"}(o=t.SimpleStatus||(t.SimpleStatus={}));var u=function(t){function r(r){var n=t.call(this)||this;if(r.media.remote.video?n.video=!0:n.video=!1,r.media.remote.audio?n.audio=!0:n.audio=!1,!n.audio&&!n.video)throw new Error("At least one remote audio or video element is required for Simple.");n.options=r;var i=e.navigator.userAgent.toLowerCase(),s=!1,u=!1;i.indexOf("safari")>-1&&i.indexOf("chrome")<0?s=!0:i.indexOf("firefox")>-1&&i.indexOf("chrome")<0&&(u=!0);var d={};return s&&(d.modifiers=[c.stripG722]),u&&(d.alwaysAcquireMediaFirst=!0),n.options.ua.uri?n.anonymous=!1:n.anonymous=!0,n.ua=new a.UA({uri:n.options.ua.uri,authorizationUser:n.options.ua.authorizationUser,password:n.options.ua.password,displayName:n.options.ua.displayName,userAgentString:n.options.ua.userAgentString,register:!0,sessionDescriptionHandlerFactoryOptions:d,transportOptions:{traceSip:n.options.ua.traceSip,wsServers:n.options.ua.wsServers}}),n.state=o.STATUS_NULL,n.logger=n.ua.getLogger("sip.simple"),n.ua.on("registered",function(){n.emit("registered",n.ua)}),n.ua.on("unregistered",function(){n.emit("unregistered",n.ua)}),n.ua.on("registrationFailed",function(){n.emit("unregistered",n.ua)}),n.ua.on("invite",function(e){if(n.state!==o.STATUS_NULL&&n.state!==o.STATUS_COMPLETED)return n.logger.warn("Rejecting incoming call. Simple only supports 1 call at a time"),void e.reject();n.session=e,n.setupSession(),n.emit("ringing",n.session)}),n.ua.on("message",function(e){n.emit("message",e)}),n}return i(r,t),r.prototype.call=function(e){if(this.ua&&this.checkRegistration()){if(this.state===o.STATUS_NULL||this.state===o.STATUS_COMPLETED)return this.options.media.remote.audio&&(this.options.media.remote.audio.autoplay=!0),this.options.media.remote.video&&(this.options.media.remote.video.autoplay=!0),this.options.media.local&&this.options.media.local.video&&(this.options.media.local.video.autoplay=!0,this.options.media.local.video.volume=0),this.session=this.ua.invite(e,{sessionDescriptionHandlerOptions:{constraints:{audio:this.audio,video:this.video}}}),this.setupSession(),this.session;this.logger.warn("Cannot make more than a single call with Simple")}else this.logger.warn("A registered UA is required for calling")},r.prototype.answer=function(){if(this.state===o.STATUS_NEW||this.state===o.STATUS_CONNECTING)return this.options.media.remote.audio&&(this.options.media.remote.audio.autoplay=!0),this.options.media.remote.video&&(this.options.media.remote.video.autoplay=!0),this.session.accept({sessionDescriptionHandlerOptions:{constraints:{audio:this.audio,video:this.video}}});this.logger.warn("No call to answer")},r.prototype.reject=function(){if(this.state===o.STATUS_NEW||this.state===o.STATUS_CONNECTING)return this.session.reject();this.logger.warn("Call is already answered")},r.prototype.hangup=function(){if(this.state===o.STATUS_CONNECTED||this.state===o.STATUS_CONNECTING||this.state===o.STATUS_NEW)return this.state!==o.STATUS_CONNECTED?this.session.cancel():this.session?this.session.bye():void 0;this.logger.warn("No active call to hang up on")},r.prototype.hold=function(){if(this.state===o.STATUS_CONNECTED&&this.session&&!this.session.localHold)return this.mute(),this.logger.log("Placing session on hold"),this.session.hold();this.logger.warn("Cannot put call on hold")},r.prototype.unhold=function(){if(this.state===o.STATUS_CONNECTED&&this.session&&this.session.localHold)return this.unmute(),this.logger.log("Placing call off hold"),this.session.unhold();this.logger.warn("Cannot unhold a call that is not on hold")},r.prototype.mute=function(){this.state===o.STATUS_CONNECTED?(this.logger.log("Muting Audio"),this.toggleMute(!0),this.emit("mute",this)):this.logger.warn("An acitve call is required to mute audio")},r.prototype.unmute=function(){this.state===o.STATUS_CONNECTED?(this.logger.log("Unmuting Audio"),this.toggleMute(!1),this.emit("unmute",this)):this.logger.warn("An active call is required to unmute audio")},r.prototype.sendDTMF=function(e){this.state===o.STATUS_CONNECTED&&this.session?(this.logger.log("Sending DTMF tone: "+e),this.session.dtmf(e)):this.logger.warn("An active call is required to send a DTMF tone")},r.prototype.message=function(e,t){this.ua&&this.checkRegistration()?e&&t?this.ua.message(e,t):this.logger.warn("A destination and message are required to send a message"):this.logger.warn("A registered UA is required to send a message")},r.prototype.checkRegistration=function(){return this.anonymous||this.ua&&this.ua.isRegistered()},r.prototype.setupRemoteMedia=function(){var t=this;if(this.session){var r,n=this.session.sessionDescriptionHandler.peerConnection;n.getReceivers?(r=new e.window.MediaStream,n.getReceivers().forEach(function(e){var t=e.track;t&&r.addTrack(t)})):r=n.getRemoteStreams()[0],this.video?(this.options.media.remote.video.srcObject=r,this.options.media.remote.video.play().catch(function(){t.logger.log("play was rejected")})):this.audio&&(this.options.media.remote.audio.srcObject=r,this.options.media.remote.audio.play().catch(function(){t.logger.log("play was rejected")}))}else this.logger.warn("No session to set remote media on")},r.prototype.setupLocalMedia=function(){if(this.session){if(this.video&&this.options.media.local&&this.options.media.local.video){var t,r=this.session.sessionDescriptionHandler.peerConnection;r.getSenders?(t=new e.window.MediaStream,r.getSenders().forEach(function(e){var r=e.track;r&&"video"===r.kind&&t.addTrack(r)})):t=r.getLocalStreams()[0],this.options.media.local.video.srcObject=t,this.options.media.local.video.volume=0,this.options.media.local.video.play()}}else this.logger.warn("No session to set local media on")},r.prototype.cleanupMedia=function(){this.video&&(this.options.media.remote.video.srcObject=null,this.options.media.remote.video.pause(),this.options.media.local&&this.options.media.local.video&&(this.options.media.local.video.srcObject=null,this.options.media.local.video.pause())),this.audio&&(this.options.media.remote.audio.srcObject=null,this.options.media.remote.audio.pause())},r.prototype.setupSession=function(){var e=this;this.session?(this.state=o.STATUS_NEW,this.emit("new",this.session),this.session.on("progress",function(){return e.onProgress()}),this.session.on("accepted",function(){return e.onAccepted()}),this.session.on("rejected",function(){return e.onEnded()}),this.session.on("failed",function(){return e.onFailed()}),this.session.on("terminated",function(){return e.onEnded()})):this.logger.warn("No session to set up")},r.prototype.destroyMedia=function(){this.session&&this.session.sessionDescriptionHandler&&this.session.sessionDescriptionHandler.close()},r.prototype.toggleMute=function(e){if(this.session){var t=this.session.sessionDescriptionHandler.peerConnection;t.getSenders?t.getSenders().forEach(function(t){t.track&&(t.track.enabled=!e)}):t.getLocalStreams().forEach(function(t){t.getAudioTracks().forEach(function(t){t.enabled=!e}),t.getVideoTracks().forEach(function(t){t.enabled=!e})})}else this.logger.warn("No session to toggle mute")},r.prototype.onAccepted=function(){var e=this;this.session?(this.state=o.STATUS_CONNECTED,this.emit("connected",this.session),this.setupLocalMedia(),this.setupRemoteMedia(),this.session.sessionDescriptionHandler&&(this.session.sessionDescriptionHandler.on("addTrack",function(){e.logger.log("A track has been added, triggering new remoteMedia setup"),e.setupRemoteMedia()}),this.session.sessionDescriptionHandler.on("addStream",function(){e.logger.log("A stream has been added, trigger new remoteMedia setup"),e.setupRemoteMedia()})),this.session.on("dtmf",function(t,r){e.emit("dtmf",r.tone)}),this.session.on("bye",function(){return e.onEnded()})):this.logger.warn("No session for accepting")},r.prototype.onProgress=function(){this.state=o.STATUS_CONNECTING,this.emit("connecting",this.session)},r.prototype.onFailed=function(){this.onEnded()},r.prototype.onEnded=function(){this.state=o.STATUS_COMPLETED,this.emit("ended",this.session),this.cleanupMedia()},r.C=o,r}(s.EventEmitter);t.Simple=u}).call(this,r(24))}])}); \ No newline at end of file diff --git a/lib/ClientContext.d.ts b/lib/ClientContext.d.ts new file mode 100644 index 000000000..854fb9bea --- /dev/null +++ b/lib/ClientContext.d.ts @@ -0,0 +1,26 @@ +/// +import { EventEmitter } from "events"; +import { TypeStrings } from "./Enums"; +import { Logger } from "./LoggerFactory"; +import { NameAddrHeader } from "./NameAddrHeader"; +import { BodyObj } from "./session-description-handler"; +import { IncomingResponse, OutgoingRequest } from "./SIPMessage"; +import { UA } from "./UA"; +import { URI } from "./URI"; +export declare class ClientContext extends EventEmitter { + static initializer(objToConstruct: ClientContext, ua: UA, method: string, originalTarget: string | URI, options?: any): void; + type: TypeStrings; + data: any; + ua: UA; + logger: Logger; + request: OutgoingRequest; + method: string; + body: BodyObj | undefined; + localIdentity: NameAddrHeader; + remoteIdentity: NameAddrHeader; + constructor(ua: UA, method: string, target: string | URI, options?: any); + send(): this; + receiveResponse(response: IncomingResponse): void; + onRequestTimeout(): void; + onTransportError(): void; +} diff --git a/lib/ClientContext.js b/lib/ClientContext.js new file mode 100644 index 000000000..853caccf6 --- /dev/null +++ b/lib/ClientContext.js @@ -0,0 +1,111 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var events_1 = require("events"); +var Constants_1 = require("./Constants"); +var Enums_1 = require("./Enums"); +var SIPMessage_1 = require("./SIPMessage"); +var Utils_1 = require("./Utils"); +var ClientContext = /** @class */ (function (_super) { + __extends(ClientContext, _super); + function ClientContext(ua, method, target, options) { + var _this = _super.call(this) || this; + _this.data = {}; + ClientContext.initializer(_this, ua, method, target, options); + return _this; + } + ClientContext.initializer = function (objToConstruct, ua, method, originalTarget, options) { + objToConstruct.type = Enums_1.TypeStrings.ClientContext; + // Validate arguments + if (originalTarget === undefined) { + throw new TypeError("Not enough arguments"); + } + objToConstruct.ua = ua; + objToConstruct.logger = ua.getLogger("sip.clientcontext"); + objToConstruct.method = method; + var target = ua.normalizeTarget(originalTarget); + if (!target) { + throw new TypeError("Invalid target: " + originalTarget); + } + /* Options + * - extraHeaders + * - params + * - contentType + * - body + */ + options = Object.create(options || Object.prototype); + options.extraHeaders = (options.extraHeaders || []).slice(); + // Build the request + objToConstruct.request = new SIPMessage_1.OutgoingRequest(objToConstruct.method, target, objToConstruct.ua, options.params, options.extraHeaders); + if (options.body) { + var body = options.body; + var contentType = options.contentType ? options.contentType : "application/sdp"; + var bodyObj = { + body: body, + contentType: contentType + }; + objToConstruct.body = bodyObj; + objToConstruct.request.body = bodyObj; + } + /* Set other properties from the request */ + if (objToConstruct.request.from) { + objToConstruct.localIdentity = objToConstruct.request.from; + } + if (objToConstruct.request.to) { + objToConstruct.remoteIdentity = objToConstruct.request.to; + } + }; + ClientContext.prototype.send = function () { + var _this = this; + this.ua.userAgentCore.request(this.request, { + onAccept: function (response) { return _this.receiveResponse(response.message); }, + onProgress: function (response) { return _this.receiveResponse(response.message); }, + onRedirect: function (response) { return _this.receiveResponse(response.message); }, + onReject: function (response) { return _this.receiveResponse(response.message); }, + onTrying: function (response) { return _this.receiveResponse(response.message); } + }); + return this; + }; + ClientContext.prototype.receiveResponse = function (response) { + var statusCode = response.statusCode || 0; + var cause = Utils_1.Utils.getReasonPhrase(statusCode); + switch (true) { + case /^1[0-9]{2}$/.test(statusCode.toString()): + this.emit("progress", response, cause); + break; + case /^2[0-9]{2}$/.test(statusCode.toString()): + if (this.ua.applicants[this.toString()]) { + delete this.ua.applicants[this.toString()]; + } + this.emit("accepted", response, cause); + break; + default: + if (this.ua.applicants[this.toString()]) { + delete this.ua.applicants[this.toString()]; + } + this.emit("rejected", response, cause); + this.emit("failed", response, cause); + break; + } + }; + ClientContext.prototype.onRequestTimeout = function () { + this.emit("failed", undefined, Constants_1.C.causes.REQUEST_TIMEOUT); + }; + ClientContext.prototype.onTransportError = function () { + this.emit("failed", undefined, Constants_1.C.causes.CONNECTION_ERROR); + }; + return ClientContext; +}(events_1.EventEmitter)); +exports.ClientContext = ClientContext; diff --git a/lib/Constants.d.ts b/lib/Constants.d.ts new file mode 100644 index 000000000..63b1c5938 --- /dev/null +++ b/lib/Constants.d.ts @@ -0,0 +1,62 @@ +export declare namespace C { + const USER_AGENT: string; + const SIP = "sip"; + const SIPS = "sips"; + enum causes { + CONNECTION_ERROR = "Connection Error", + INTERNAL_ERROR = "Internal Error", + REQUEST_TIMEOUT = "Request Timeout", + SIP_FAILURE_CODE = "SIP Failure Code", + ADDRESS_INCOMPLETE = "Address Incomplete", + AUTHENTICATION_ERROR = "Authentication Error", + BUSY = "Busy", + DIALOG_ERROR = "Dialog Error", + INCOMPATIBLE_SDP = "Incompatible SDP", + NOT_FOUND = "Not Found", + REDIRECTED = "Redirected", + REJECTED = "Rejected", + UNAVAILABLE = "Unavailable", + BAD_MEDIA_DESCRIPTION = "Bad Media Description", + CANCELED = "Canceled", + EXPIRES = "Expires", + NO_ACK = "No ACK", + NO_ANSWER = "No Answer", + NO_PRACK = "No PRACK", + RTP_TIMEOUT = "RTP Timeout", + USER_DENIED_MEDIA_ACCESS = "User Denied Media Access", + WEBRTC_ERROR = "WebRTC Error", + WEBRTC_NOT_SUPPORTED = "WebRTC Not Supported" + } + enum supported { + REQUIRED = "required", + SUPPORTED = "supported", + UNSUPPORTED = "none" + } + const SIP_ERROR_CAUSES: { + [name: string]: Array; + }; + const ACK = "ACK"; + const BYE = "BYE"; + const CANCEL = "CANCEL"; + const INFO = "INFO"; + const INVITE = "INVITE"; + const MESSAGE = "MESSAGE"; + const NOTIFY = "NOTIFY"; + const OPTIONS = "OPTIONS"; + const REGISTER = "REGISTER"; + const UPDATE = "UPDATE"; + const SUBSCRIBE = "SUBSCRIBE"; + const PUBLISH = "PUBLISH"; + const REFER = "REFER"; + const PRACK = "PRACK"; + const REASON_PHRASE: { + [code: number]: string; + }; + const OPTION_TAGS: { + [option: string]: boolean; + }; + enum dtmfType { + INFO = "info", + RTP = "rtp" + } +} diff --git a/lib/Constants.js b/lib/Constants.js new file mode 100644 index 000000000..08f9e5c7c --- /dev/null +++ b/lib/Constants.js @@ -0,0 +1,192 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +// tslint:disable-next-line:no-var-requires +var pkg = require("../package.json"); +var C; +(function (C) { + C.USER_AGENT = pkg.title + "/" + pkg.version; + // SIP scheme + C.SIP = "sip"; + C.SIPS = "sips"; + // End and Failure causes + var causes; + (function (causes) { + // Generic error causes + causes["CONNECTION_ERROR"] = "Connection Error"; + causes["INTERNAL_ERROR"] = "Internal Error"; + causes["REQUEST_TIMEOUT"] = "Request Timeout"; + causes["SIP_FAILURE_CODE"] = "SIP Failure Code"; + // SIP error causes + causes["ADDRESS_INCOMPLETE"] = "Address Incomplete"; + causes["AUTHENTICATION_ERROR"] = "Authentication Error"; + causes["BUSY"] = "Busy"; + causes["DIALOG_ERROR"] = "Dialog Error"; + causes["INCOMPATIBLE_SDP"] = "Incompatible SDP"; + causes["NOT_FOUND"] = "Not Found"; + causes["REDIRECTED"] = "Redirected"; + causes["REJECTED"] = "Rejected"; + causes["UNAVAILABLE"] = "Unavailable"; + // Session error causes + causes["BAD_MEDIA_DESCRIPTION"] = "Bad Media Description"; + causes["CANCELED"] = "Canceled"; + causes["EXPIRES"] = "Expires"; + causes["NO_ACK"] = "No ACK"; + causes["NO_ANSWER"] = "No Answer"; + causes["NO_PRACK"] = "No PRACK"; + causes["RTP_TIMEOUT"] = "RTP Timeout"; + causes["USER_DENIED_MEDIA_ACCESS"] = "User Denied Media Access"; + causes["WEBRTC_ERROR"] = "WebRTC Error"; + causes["WEBRTC_NOT_SUPPORTED"] = "WebRTC Not Supported"; + })(causes = C.causes || (C.causes = {})); + var supported; + (function (supported) { + supported["REQUIRED"] = "required"; + supported["SUPPORTED"] = "supported"; + supported["UNSUPPORTED"] = "none"; + })(supported = C.supported || (C.supported = {})); + C.SIP_ERROR_CAUSES = { + ADDRESS_INCOMPLETE: [484], + AUTHENTICATION_ERROR: [401, 407], + BUSY: [486, 600], + INCOMPATIBLE_SDP: [488, 606], + NOT_FOUND: [404, 604], + REDIRECTED: [300, 301, 302, 305, 380], + REJECTED: [403, 603], + UNAVAILABLE: [480, 410, 408, 430] + }; + // SIP Methods + C.ACK = "ACK"; + C.BYE = "BYE"; + C.CANCEL = "CANCEL"; + C.INFO = "INFO"; + C.INVITE = "INVITE"; + C.MESSAGE = "MESSAGE"; + C.NOTIFY = "NOTIFY"; + C.OPTIONS = "OPTIONS"; + C.REGISTER = "REGISTER"; + C.UPDATE = "UPDATE"; + C.SUBSCRIBE = "SUBSCRIBE"; + C.PUBLISH = "PUBLISH"; + C.REFER = "REFER"; + C.PRACK = "PRACK"; + /* SIP Response Reasons + * DOC: http://www.iana.org/assignments/sip-parameters + * Copied from https://github.com/versatica/OverSIP/blob/master/lib/oversip/sip/constants.rb#L7 + */ + C.REASON_PHRASE = { + 100: "Trying", + 180: "Ringing", + 181: "Call Is Being Forwarded", + 182: "Queued", + 183: "Session Progress", + 199: "Early Dialog Terminated", + 200: "OK", + 202: "Accepted", + 204: "No Notification", + 300: "Multiple Choices", + 301: "Moved Permanently", + 302: "Moved Temporarily", + 305: "Use Proxy", + 380: "Alternative Service", + 400: "Bad Request", + 401: "Unauthorized", + 402: "Payment Required", + 403: "Forbidden", + 404: "Not Found", + 405: "Method Not Allowed", + 406: "Not Acceptable", + 407: "Proxy Authentication Required", + 408: "Request Timeout", + 410: "Gone", + 412: "Conditional Request Failed", + 413: "Request Entity Too Large", + 414: "Request-URI Too Long", + 415: "Unsupported Media Type", + 416: "Unsupported URI Scheme", + 417: "Unknown Resource-Priority", + 420: "Bad Extension", + 421: "Extension Required", + 422: "Session Interval Too Small", + 423: "Interval Too Brief", + 428: "Use Identity Header", + 429: "Provide Referrer Identity", + 430: "Flow Failed", + 433: "Anonymity Disallowed", + 436: "Bad Identity-Info", + 437: "Unsupported Certificate", + 438: "Invalid Identity Header", + 439: "First Hop Lacks Outbound Support", + 440: "Max-Breadth Exceeded", + 469: "Bad Info Package", + 470: "Consent Needed", + 478: "Unresolvable Destination", + 480: "Temporarily Unavailable", + 481: "Call/Transaction Does Not Exist", + 482: "Loop Detected", + 483: "Too Many Hops", + 484: "Address Incomplete", + 485: "Ambiguous", + 486: "Busy Here", + 487: "Request Terminated", + 488: "Not Acceptable Here", + 489: "Bad Event", + 491: "Request Pending", + 493: "Undecipherable", + 494: "Security Agreement Required", + 500: "Internal Server Error", + 501: "Not Implemented", + 502: "Bad Gateway", + 503: "Service Unavailable", + 504: "Server Time-out", + 505: "Version Not Supported", + 513: "Message Too Large", + 580: "Precondition Failure", + 600: "Busy Everywhere", + 603: "Decline", + 604: "Does Not Exist Anywhere", + 606: "Not Acceptable" + }; + /* SIP Option Tags + * DOC: http://www.iana.org/assignments/sip-parameters/sip-parameters.xhtml#sip-parameters-4 + */ + C.OPTION_TAGS = { + "100rel": true, + "199": true, + "answermode": true, + "early-session": true, + "eventlist": true, + "explicitsub": true, + "from-change": true, + "geolocation-http": true, + "geolocation-sip": true, + "gin": true, + "gruu": true, + "histinfo": true, + "ice": true, + "join": true, + "multiple-refer": true, + "norefersub": true, + "nosub": true, + "outbound": true, + "path": true, + "policy": true, + "precondition": true, + "pref": true, + "privacy": true, + "recipient-list-invite": true, + "recipient-list-message": true, + "recipient-list-subscribe": true, + "replaces": true, + "resource-priority": true, + "sdp-anat": true, + "sec-agree": true, + "tdialog": true, + "timer": true, + "uui": true // RFC 7433 + }; + var dtmfType; + (function (dtmfType) { + dtmfType["INFO"] = "info"; + dtmfType["RTP"] = "rtp"; + })(dtmfType = C.dtmfType || (C.dtmfType = {})); +})(C = exports.C || (exports.C = {})); diff --git a/lib/Contexts/client-context.d.ts b/lib/Contexts/client-context.d.ts new file mode 100644 index 000000000..b016b7458 --- /dev/null +++ b/lib/Contexts/client-context.d.ts @@ -0,0 +1,11 @@ +import { ClientContext as ClientContextBase } from "../ClientContext"; +import { IncomingResponse as IncomingResponseMessage } from "../SIPMessage"; +import { UA } from "../UA"; +import { URI } from "../URI"; +export declare class ClientContext extends ClientContextBase { + constructor(ua: UA, method: string, target: string | URI, options?: any); + onRequestTimeout(): void; + onTransportError(): void; + receiveResponse(message: IncomingResponseMessage): void; + send(): this; +} diff --git a/lib/Contexts/client-context.js b/lib/Contexts/client-context.js new file mode 100644 index 000000000..bc2c85b60 --- /dev/null +++ b/lib/Contexts/client-context.js @@ -0,0 +1,52 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var ClientContext_1 = require("../ClientContext"); +var ClientContext = /** @class */ (function (_super) { + __extends(ClientContext, _super); + // Override ClientContext + function ClientContext(ua, method, target, options) { + return _super.call(this, ua, method, target, options) || this; + } + // Override ClientContext + ClientContext.prototype.onRequestTimeout = function () { + throw new Error("Method not utilized by user agent core."); + }; + // Override ClientContext + ClientContext.prototype.onTransportError = function () { + throw new Error("Method not utilized by user agent core."); + }; + // Override ClientContext + ClientContext.prototype.receiveResponse = function (message) { + _super.prototype.receiveResponse.call(this, message); + }; + // Override ClientContext + ClientContext.prototype.send = function () { + var _this = this; + if (!this.ua.userAgentCore) { + throw new Error("User agent core undefined."); + } + var outgoingRequest = this.ua.userAgentCore.request(this.request, { + onAccept: function (response) { return _this.receiveResponse(response.message); }, + onProgress: function (response) { return _this.receiveResponse(response.message); }, + onRedirect: function (response) { return _this.receiveResponse(response.message); }, + onReject: function (response) { return _this.receiveResponse(response.message); }, + onTrying: function (response) { return _this.receiveResponse(response.message); } + }); + return this; + }; + return ClientContext; +}(ClientContext_1.ClientContext)); +exports.ClientContext = ClientContext; diff --git a/lib/Contexts/invite-client-context.d.ts b/lib/Contexts/invite-client-context.d.ts new file mode 100644 index 000000000..a8e30af61 --- /dev/null +++ b/lib/Contexts/invite-client-context.d.ts @@ -0,0 +1,116 @@ +import { InviteClientContext as InviteClientContextBase } from "../Session"; +import { IncomingRequest as IncomingRequestMessage, IncomingResponse as IncomingResponseMessage } from "../SIPMessage"; +import { UA } from "../UA"; +import { URI } from "../URI"; +export declare class InviteClientContext extends InviteClientContextBase { + private earlyMediaSessionDescriptionHandlers; + private outgoingInviteRequest; + constructor(ua: UA, target: string | URI, options?: any, modifiers?: any); + acceptAndTerminate(message: IncomingResponseMessage, statusCode?: number, reasonPhrase?: string): this; + createDialog(message: IncomingRequestMessage | IncomingResponseMessage, type: "UAS" | "UAC", early?: boolean): boolean; + /** + * Sends in dialog request. + * @param method Request method. + * @param options Options bucket. + */ + sendRequest(method: string, options?: any): this; + setInvite2xxTimer(message: IncomingRequestMessage, body?: { + body: string; + contentType: string; + }): void; + setACKTimer(): void; + receiveInviteResponse(message: IncomingResponseMessage): void; + receiveNonInviteResponse(message: IncomingResponseMessage): void; + receiveResponse(message: IncomingResponseMessage): void; + /** + * Cancel an unaccepted outgoing INVITE request. + * @param options Options bucket. FIXME: This options bucket needs to be typed. + */ + cancel(options?: any): this; + /** + * Create an outgoing INVITE request and send it to the target. + */ + invite(): this; + /** + * This public function here in the service of a hack in a parent class. It should be protected. + * It will, hopefully, go away altogether at somepoint. Meanwhile, please do not call it. + */ + send(): this; + /** + * Cancel an unaccepted outgoing INVITE request or send BYE if established session. + * @param options Options bucket. FIXME: This options bucket needs to be typed. + */ + terminate(options?: any): this; + /** + * Incoming request handler. + * @param message Incoming request. + */ + receiveRequest(message: IncomingRequestMessage): void; + /** + * 13.2.1 Creating the Initial INVITE + * + * Since the initial INVITE represents a request outside of a dialog, + * its construction follows the procedures of Section 8.1.1. Additional + * processing is required for the specific case of INVITE. + * + * An Allow header field (Section 20.5) SHOULD be present in the INVITE. + * It indicates what methods can be invoked within a dialog, on the UA + * sending the INVITE, for the duration of the dialog. For example, a + * UA capable of receiving INFO requests within a dialog [34] SHOULD + * include an Allow header field listing the INFO method. + * + * A Supported header field (Section 20.37) SHOULD be present in the + * INVITE. It enumerates all the extensions understood by the UAC. + * + * An Accept (Section 20.1) header field MAY be present in the INVITE. + * It indicates which Content-Types are acceptable to the UA, in both + * the response received by it, and in any subsequent requests sent to + * it within dialogs established by the INVITE. The Accept header field + * is especially useful for indicating support of various session + * description formats. + * + * The UAC MAY add an Expires header field (Section 20.19) to limit the + * validity of the invitation. If the time indicated in the Expires + * header field is reached and no final answer for the INVITE has been + * received, the UAC core SHOULD generate a CANCEL request for the + * INVITE, as per Section 9. + * + * A UAC MAY also find it useful to add, among others, Subject (Section + * 20.36), Organization (Section 20.25) and User-Agent (Section 20.41) + * header fields. They all contain information related to the INVITE. + * + * The UAC MAY choose to add a message body to the INVITE. Section + * 8.1.1.10 deals with how to construct the header fields -- Content- + * Type among others -- needed to describe the message body. + * + * https://tools.ietf.org/html/rfc3261#section-13.2.1 + */ + private sendInvite; + private ackAndBye; + private disposeEarlyMedia; + /** + * Handle final response to initial INVITE. + * @param inviteResponse 2xx response. + */ + private onAccept; + /** + * Handle provisional response to initial INVITE. + * @param inviteResponse 1xx response. + */ + private onProgress; + /** + * Handle final response to initial INVITE. + * @param inviteResponse 3xx response. + */ + private onRedirect; + /** + * Handle final response to initial INVITE. + * @param inviteResponse 4xx, 5xx, or 6xx response. + */ + private onReject; + /** + * Handle final response to initial INVITE. + * @param inviteResponse 100 response. + */ + private onTrying; +} diff --git a/lib/Contexts/invite-client-context.js b/lib/Contexts/invite-client-context.js new file mode 100644 index 000000000..95fab1332 --- /dev/null +++ b/lib/Contexts/invite-client-context.js @@ -0,0 +1,781 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var messages_1 = require("../Core/messages"); +var session_1 = require("../Core/session"); +var Constants_1 = require("../Constants"); +var Enums_1 = require("../Enums"); +var Grammar_1 = require("../Grammar"); +var Session_1 = require("../Session"); +var Utils_1 = require("../Utils"); +var InviteClientContext = /** @class */ (function (_super) { + __extends(InviteClientContext, _super); + function InviteClientContext(ua, target, options, modifiers) { + if (options === void 0) { options = {}; } + if (modifiers === void 0) { modifiers = []; } + var _this = _super.call(this, ua, target, options, modifiers) || this; + _this.earlyMediaSessionDescriptionHandlers = new Map(); + return _this; + } + //// + // BEGIN Session Overrides - roadmap is to remove all of these, but for now... + // + // Override Session member we want to make sure we are not using. + InviteClientContext.prototype.acceptAndTerminate = function (message, statusCode, reasonPhrase) { + throw new Error("Method not utilized by user agent core."); + }; + // Override Session member we want to make sure we are not using. + InviteClientContext.prototype.createDialog = function (message, type, early) { + if (early === void 0) { early = false; } + throw new Error("Method not utilized by user agent core."); + }; + /** + * Sends in dialog request. + * @param method Request method. + * @param options Options bucket. + */ + InviteClientContext.prototype.sendRequest = function (method, options) { + if (options === void 0) { options = {}; } + if (!this.session) { + throw new Error("Session undefined."); + } + // Convert any "body" option to a Body. + if (options.body) { + options.body = messages_1.fromBodyObj(options.body); + } + // Convert any "receiveResponse" callback option passed to an OutgoingRequestDelegate. + var delegate; + var callback = options.receiveResponse; + if (callback) { + delegate = { + onAccept: function (response) { return callback(response.message); }, + onProgress: function (response) { return callback(response.message); }, + onRedirect: function (response) { return callback(response.message); }, + onReject: function (response) { return callback(response.message); }, + onTrying: function (response) { return callback(response.message); } + }; + } + var request; + var requestOptions = options; + switch (method) { + case Constants_1.C.BYE: + request = this.session.bye(delegate, requestOptions); + break; + case Constants_1.C.INVITE: + request = this.session.invite(delegate, requestOptions); + break; + case Constants_1.C.REFER: + request = this.session.refer(delegate, requestOptions); + break; + default: + throw new Error("Unexpected " + method + ". Method not implemented by user agent core."); + } + // Ported - Emit the request event + this.emit(method.toLowerCase(), request.message); + return this; + }; + // Override Session member we want to make sure we are not using. + InviteClientContext.prototype.setInvite2xxTimer = function (message, body) { + throw new Error("Method not utilized by user agent core."); + }; + // Override Session member we want to make sure we are not using. + InviteClientContext.prototype.setACKTimer = function () { + // throw new Error("Method not utilized by user agent core."); + // FIXME: TODO: This gets called by receiveReinvite(). + // Just prevent it from doing anything for now until we stop calling that. + return; + }; + // END Session Overrides + ////// + // Override InviteClientContextBase member we want to make sure we are not using. + InviteClientContext.prototype.receiveInviteResponse = function (message) { + throw new Error("Method not utilized by user agent core."); + }; + // Override InviteClientContextBase member we want to make sure we are not using. + InviteClientContext.prototype.receiveNonInviteResponse = function (message) { + throw new Error("Method not utilized by user agent core."); + }; + // Override InviteClientContextBase member we want to make sure we are not using. + InviteClientContext.prototype.receiveResponse = function (message) { + throw new Error("Method not utilized by user agent core."); + }; + /** + * Cancel an unaccepted outgoing INVITE request. + * @param options Options bucket. FIXME: This options bucket needs to be typed. + */ + InviteClientContext.prototype.cancel = function (options) { + if (options === void 0) { options = {}; } + return _super.prototype.cancel.call(this, options); + }; + /** + * Create an outgoing INVITE request and send it to the target. + */ + InviteClientContext.prototype.invite = function () { + if (this.outgoingInviteRequest) { + throw new Error("Outgoing invite request already defined. Did you call invite() more than once?"); + } + return _super.prototype.invite.call(this); + }; + /** + * This public function here in the service of a hack in a parent class. It should be protected. + * It will, hopefully, go away altogether at somepoint. Meanwhile, please do not call it. + */ + InviteClientContext.prototype.send = function () { + this.sendInvite(); + return this; + }; + /** + * Cancel an unaccepted outgoing INVITE request or send BYE if established session. + * @param options Options bucket. FIXME: This options bucket needs to be typed. + */ + InviteClientContext.prototype.terminate = function (options) { + if (!this.outgoingInviteRequest) { + throw new Error("Outgoing invite request undefined. Did you call terminate() without calling invite() first?"); + } + return _super.prototype.terminate.call(this, options); + }; + /** + * Incoming request handler. + * @param message Incoming request. + */ + InviteClientContext.prototype.receiveRequest = function (message) { + this.logger.log("INVITE client context received " + message.method + "."); + _super.prototype.receiveRequest.call(this, message); + }; + /** + * 13.2.1 Creating the Initial INVITE + * + * Since the initial INVITE represents a request outside of a dialog, + * its construction follows the procedures of Section 8.1.1. Additional + * processing is required for the specific case of INVITE. + * + * An Allow header field (Section 20.5) SHOULD be present in the INVITE. + * It indicates what methods can be invoked within a dialog, on the UA + * sending the INVITE, for the duration of the dialog. For example, a + * UA capable of receiving INFO requests within a dialog [34] SHOULD + * include an Allow header field listing the INFO method. + * + * A Supported header field (Section 20.37) SHOULD be present in the + * INVITE. It enumerates all the extensions understood by the UAC. + * + * An Accept (Section 20.1) header field MAY be present in the INVITE. + * It indicates which Content-Types are acceptable to the UA, in both + * the response received by it, and in any subsequent requests sent to + * it within dialogs established by the INVITE. The Accept header field + * is especially useful for indicating support of various session + * description formats. + * + * The UAC MAY add an Expires header field (Section 20.19) to limit the + * validity of the invitation. If the time indicated in the Expires + * header field is reached and no final answer for the INVITE has been + * received, the UAC core SHOULD generate a CANCEL request for the + * INVITE, as per Section 9. + * + * A UAC MAY also find it useful to add, among others, Subject (Section + * 20.36), Organization (Section 20.25) and User-Agent (Section 20.41) + * header fields. They all contain information related to the INVITE. + * + * The UAC MAY choose to add a message body to the INVITE. Section + * 8.1.1.10 deals with how to construct the header fields -- Content- + * Type among others -- needed to describe the message body. + * + * https://tools.ietf.org/html/rfc3261#section-13.2.1 + */ + InviteClientContext.prototype.sendInvite = function () { + // There are special rules for message bodies that contain a session + // description - their corresponding Content-Disposition is "session". + // SIP uses an offer/answer model where one UA sends a session + // description, called the offer, which contains a proposed description + // of the session. The offer indicates the desired communications means + // (audio, video, games), parameters of those means (such as codec + // types) and addresses for receiving media from the answerer. The + // other UA responds with another session description, called the + // answer, which indicates which communications means are accepted, the + // parameters that apply to those means, and addresses for receiving + // media from the offerer. An offer/answer exchange is within the + // context of a dialog, so that if a SIP INVITE results in multiple + // dialogs, each is a separate offer/answer exchange. The offer/answer + // model defines restrictions on when offers and answers can be made + // (for example, you cannot make a new offer while one is in progress). + // This results in restrictions on where the offers and answers can + // appear in SIP messages. In this specification, offers and answers + // can only appear in INVITE requests and responses, and ACK. The usage + // of offers and answers is further restricted. For the initial INVITE + // transaction, the rules are: + // + // o The initial offer MUST be in either an INVITE or, if not there, + // in the first reliable non-failure message from the UAS back to + // the UAC. In this specification, that is the final 2xx + // response. + // + // o If the initial offer is in an INVITE, the answer MUST be in a + // reliable non-failure message from UAS back to UAC which is + // correlated to that INVITE. For this specification, that is + // only the final 2xx response to that INVITE. That same exact + // answer MAY also be placed in any provisional responses sent + // prior to the answer. The UAC MUST treat the first session + // description it receives as the answer, and MUST ignore any + // session descriptions in subsequent responses to the initial + // INVITE. + // + // o If the initial offer is in the first reliable non-failure + // message from the UAS back to UAC, the answer MUST be in the + // acknowledgement for that message (in this specification, ACK + // for a 2xx response). + // + // o After having sent or received an answer to the first offer, the + // UAC MAY generate subsequent offers in requests based on rules + // specified for that method, but only if it has received answers + // to any previous offers, and has not sent any offers to which it + // hasn't gotten an answer. + // + // o Once the UAS has sent or received an answer to the initial + // offer, it MUST NOT generate subsequent offers in any responses + // to the initial INVITE. This means that a UAS based on this + // specification alone can never generate subsequent offers until + // completion of the initial transaction. + // + // https://tools.ietf.org/html/rfc3261#section-13.2.1 + var _this = this; + // 5 The Offer/Answer Model and PRACK + // + // RFC 3261 describes guidelines for the sets of messages in which + // offers and answers [3] can appear. Based on those guidelines, this + // extension provides additional opportunities for offer/answer + // exchanges. + // If the INVITE contained an offer, the UAS MAY generate an answer in a + // reliable provisional response (assuming these are supported by the + // UAC). That results in the establishment of the session before + // completion of the call. Similarly, if a reliable provisional + // response is the first reliable message sent back to the UAC, and the + // INVITE did not contain an offer, one MUST appear in that reliable + // provisional response. + // If the UAC receives a reliable provisional response with an offer + // (this would occur if the UAC sent an INVITE without an offer, in + // which case the first reliable provisional response will contain the + // offer), it MUST generate an answer in the PRACK. If the UAC receives + // a reliable provisional response with an answer, it MAY generate an + // additional offer in the PRACK. If the UAS receives a PRACK with an + // offer, it MUST place the answer in the 2xx to the PRACK. + // Once an answer has been sent or received, the UA SHOULD establish the + // session based on the parameters of the offer and answer, even if the + // original INVITE itself has not been responded to. + // If the UAS had placed a session description in any reliable + // provisional response that is unacknowledged when the INVITE is + // accepted, the UAS MUST delay sending the 2xx until the provisional + // response is acknowledged. Otherwise, the reliability of the 1xx + // cannot be guaranteed, and reliability is needed for proper operation + // of the offer/answer exchange. + // All user agents that support this extension MUST support all + // offer/answer exchanges that are possible based on the rules in + // Section 13.2 of RFC 3261, based on the existence of INVITE and PRACK + // as requests, and 2xx and reliable 1xx as non-failure reliable + // responses. + // + // https://tools.ietf.org/html/rfc3262#section-5 + //// + // The Offer/Answer Model Implementation + // + // The offer/answer model is straight forward, but one MUST READ the specifications... + // + // 13.2.1 Creating the Initial INVITE (paragraph 8 in particular) + // https://tools.ietf.org/html/rfc3261#section-13.2.1 + // + // 5 The Offer/Answer Model and PRACK + // https://tools.ietf.org/html/rfc3262#section-5 + // + // Session Initiation Protocol (SIP) Usage of the Offer/Answer Model + // https://tools.ietf.org/html/rfc6337 + // + // *** IMPORTANT IMPLEMENTATION CHOICES *** + // + // TLDR... + // + // 1) Only one offer/answer exchange permitted during initial INVITE. + // 2) No "early media" if the initial offer is in an INVITE. + // + // + // 1) Initial Offer/Answer Restriction. + // + // Our implementation replaces the following bullet point... + // + // o After having sent or received an answer to the first offer, the + // UAC MAY generate subsequent offers in requests based on rules + // specified for that method, but only if it has received answers + // to any previous offers, and has not sent any offers to which it + // hasn't gotten an answer. + // https://tools.ietf.org/html/rfc3261#section-13.2.1 + // + // ...with... + // + // o After having sent or received an answer to the first offer, the + // UAC MUST NOT generate subsequent offers in requests based on rules + // specified for that method. + // + // ...which in combination with this bullet point... + // + // o Once the UAS has sent or received an answer to the initial + // offer, it MUST NOT generate subsequent offers in any responses + // to the initial INVITE. This means that a UAS based on this + // specification alone can never generate subsequent offers until + // completion of the initial transaction. + // https://tools.ietf.org/html/rfc3261#section-13.2.1 + // + // ...ensures that EXACTLY ONE offer/answer exchange will occur + // during an initial out of dialog INVITE request made by our UAC. + // + // + // 2) Early Media Restriction. + // + // While our implementation adheres to the following bullet point... + // + // o If the initial offer is in an INVITE, the answer MUST be in a + // reliable non-failure message from UAS back to UAC which is + // correlated to that INVITE. For this specification, that is + // only the final 2xx response to that INVITE. That same exact + // answer MAY also be placed in any provisional responses sent + // prior to the answer. The UAC MUST treat the first session + // description it receives as the answer, and MUST ignore any + // session descriptions in subsequent responses to the initial + // INVITE. + // https://tools.ietf.org/html/rfc3261#section-13.2.1 + // + // We have made the following implementation decision with regard to early media... + // + // o If the initial offer is in the INVITE, the answer from the + // UAS back to the UAC will establish a media session only + // only after the final 2xx response to that INVITE is received. + // + // The reason for this decision is rooted in a restriction currently + // inherent in WebRTC. Specifically, while a SIP INVITE request with an + // initial offer may fork resulting in more than one provisional answer, + // there is currently no easy/good way to to "fork" an offer generated + // by a peer connection. In particular, a WebRTC offer currently may only + // be matched with one answer and we have no good way to know which + // "provisional answer" is going to be the "final answer". So we have + // decided to punt and not create any "early media" sessions in this case. + // + // The upshot is that if you want "early media", you must not put the + // initial offer in the INVITE. Instead, force the UAS to provide the + // initial offer by sending an INVITE without an offer. In the WebRTC + // case this allows us to create a unique peer connection with a unique + // answer for every provisional offer with "early media" on all of them. + //// + //// + // ROADMAP: The Offer/Answer Model Implementation + // + // The "no early media if offer in INVITE" implementation is not a + // welcome one. The masses want it. The want it and they want it + // to work for WebRTC (so they want to have their cake and eat too). + // + // So while we currently cannot make the offer in INVITE+forking+webrtc + // case work, we decided to do the following... + // + // 1) modify SDH Factory to provide an initial offer without giving us the SDH, and then... + // 2) stick that offer in the initial INVITE, and when 183 with initial answer is received... + // 3) ask SDH Factory if it supports "earlyRemoteAnswer" + // a) if true, ask SDH Factory to createSDH(localOffer).then((sdh) => sdh.setDescription(remoteAnswer) + // b) if false, defer getting a SDH until 2xx response is received + // + // Our supplied WebRTC SDH will default to behavior 3b which works in forking environment (without) + // early media if initial offer is in the INVITE). We will, however, provide an "inviteWillNotFork" + // option which if set to "true" will have our supplied WebRTC SDH behave in the 3a manner. + // That will result in + // - early media working with initial offer in the INVITE, and... + // - if the INVITE forks, the session terminating with an ERROR that reads like + // "You set 'inviteWillNotFork' to true but the INVITE forked. You can't eat your cake, and have it too." + // - furthermore, we accept that users will report that error to us as "bug" regardless + // + // So, SDH Factory is going to end up with a new interface along the lines of... + // + // interface SessionDescriptionHandlerFactory { + // makeLocalOffer(): Promise; + // makeSessionDescriptionHandler( + // initialOffer: ContentTypeAndBody, offerType: "local" | "remote" + // ): Promise; + // supportsEarlyRemoteAnswer: boolean; + // supportsContentType(contentType: string): boolean; + // getDescription(description: ContentTypeAndBody): Promise + // setDescription(description: ContentTypeAndBody): Promise + // } + // + // We should be able to get rid of all the hasOffer/hasAnswer tracking code and otherwise code + // it up to the same interaction with the SDH Factory and SDH regardless of signaling scenario. + //// + if (!this.ua.userAgentCore) { + throw new Error("User agent core undefined."); + } + // Send the INVITE request. + this.outgoingInviteRequest = this.ua.userAgentCore.invite(this.request, { + onAccept: function (inviteResponse) { return _this.onAccept(inviteResponse); }, + onProgress: function (inviteResponse) { return _this.onProgress(inviteResponse); }, + onRedirect: function (inviteResponse) { return _this.onRedirect(inviteResponse); }, + onReject: function (inviteResponse) { return _this.onReject(inviteResponse); }, + onTrying: function (inviteResponse) { return _this.onTrying(inviteResponse); } + }); + }; + InviteClientContext.prototype.ackAndBye = function (inviteResponse, session, statusCode, reasonPhrase) { + if (!this.ua.userAgentCore) { + throw new Error("Method requires user agent core."); + } + var extraHeaders = []; + if (statusCode) { + extraHeaders.push("Reason: " + Utils_1.Utils.getReasonHeaderValue(statusCode, reasonPhrase)); + } + var outgoingAckRequest = inviteResponse.ack(); + this.emit("ack", outgoingAckRequest.message); + var outgoingByeRequest = session.bye(undefined, { extraHeaders: extraHeaders }); + this.emit("bye", outgoingByeRequest.message); + }; + InviteClientContext.prototype.disposeEarlyMedia = function () { + if (!this.earlyMediaSessionDescriptionHandlers) { + throw new Error("Early media session description handlers undefined."); + } + this.earlyMediaSessionDescriptionHandlers.forEach(function (sessionDescriptionHandler) { + sessionDescriptionHandler.close(); + }); + }; + /** + * Handle final response to initial INVITE. + * @param inviteResponse 2xx response. + */ + InviteClientContext.prototype.onAccept = function (inviteResponse) { + var _this = this; + if (!this.earlyMediaSessionDescriptionHandlers) { + throw new Error("Early media session description handlers undefined."); + } + var response = inviteResponse.message; + var session = inviteResponse.session; + // Our transaction layer is "non-standard" in that it will only + // pass us a 2xx response once per branch, so there is no need to + // worry about dealing with 2xx retransmissions. However, we can + // and do still get 2xx responses for multiple branches (when an + // INVITE is forked) which may create multiple confirmed dialogs. + // Herein we are acking and sending a bye to any confirmed dialogs + // which arrive beyond the first one. This is the desired behavior + // for most applications (but certainly not all). + // If we already received a confirmed dialog, ack & bye this session. + if (this.session) { + this.ackAndBye(inviteResponse, session); + return; + } + // If the user requested cancellation, ack & bye this session. + if (this.isCanceled) { + this.ackAndBye(inviteResponse, session); + this.emit("bye", this.request); // FIXME: Ported this odd second "bye" emit + return; + } + // Ported behavior. + if (response.hasHeader("P-Asserted-Identity")) { + this.assertedIdentity = Grammar_1.Grammar.nameAddrHeaderParse(response.getHeader("P-Asserted-Identity")); + } + // We have a confirmed dialog. + this.session = session; + this.session.delegate = { + onAck: function (ackRequest) { return _this.receiveRequest(ackRequest.message); }, + onBye: function (byeRequest) { return _this.receiveRequest(byeRequest.message); }, + onInfo: function (infoRequest) { return _this.receiveRequest(infoRequest.message); }, + onInvite: function (inviteRequest) { return _this.receiveRequest(inviteRequest.message); }, + onNotify: function (notifyRequest) { return _this.receiveRequest(notifyRequest.message); }, + onPrack: function (prackRequest) { return _this.receiveRequest(prackRequest.message); }, + onRefer: function (referRequest) { return _this.receiveRequest(referRequest.message); } + }; + switch (session.signalingState) { + case session_1.SignalingState.Initial: + // INVITE without Offer, so MUST have Offer at this point, so invalid state. + this.ackAndBye(inviteResponse, session, 400, "Missing session description"); + this.failed(response, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); + break; + case session_1.SignalingState.HaveLocalOffer: + // INVITE with Offer, so MUST have Answer at this point, so invalid state. + this.ackAndBye(inviteResponse, session, 400, "Missing session description"); + this.failed(response, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); + break; + case session_1.SignalingState.HaveRemoteOffer: + // INVITE without Offer, received offer in 2xx, so MUST send Answer in ACK. + var sdh_1 = this.sessionDescriptionHandlerFactory(this, this.ua.configuration.sessionDescriptionHandlerFactoryOptions || {}); + this.sessionDescriptionHandler = sdh_1; + this.emit("SessionDescriptionHandler-created", this.sessionDescriptionHandler); + if (!sdh_1.hasDescription(response.getHeader("Content-Type") || "")) { + this.ackAndBye(inviteResponse, session, 400, "Missing session description"); + this.failed(response, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); + break; + } + this.hasOffer = true; + sdh_1 + .setDescription(response.body, this.sessionDescriptionHandlerOptions, this.modifiers) + .then(function () { return sdh_1.getDescription(_this.sessionDescriptionHandlerOptions, _this.modifiers); }) + .then(function (description) { + if (_this.isCanceled || _this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { + return; + } + _this.status = Enums_1.SessionStatus.STATUS_CONFIRMED; + _this.hasAnswer = true; + var body = { + contentDisposition: "session", contentType: description.contentType, content: description.body + }; + var ackRequest = inviteResponse.ack({ body: body }); + _this.emit("ack", ackRequest.message); + _this.accepted(response); + }) + .catch(function (e) { + if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { + _this.logger.warn("invalid description"); + _this.logger.warn(e.toString()); + // TODO: This message is inconsistent + _this.acceptAndTerminate(response, 488, "Invalid session description"); + _this.failed(response, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); + } + else { + throw e; + } + }); + break; + case session_1.SignalingState.Stable: + // This session has completed an initial offer/answer exchange... + var options_1; + if (this.renderbody && this.rendertype) { + options_1 = { body: { contentDisposition: "render", contentType: this.rendertype, content: this.renderbody } }; + } + // If INVITE with Offer and we have been waiting till now to apply the answer. + if (this.hasOffer && !this.hasAnswer) { + if (!this.sessionDescriptionHandler) { + throw new Error("Session description handler undefined."); + } + var answer = session.answer; + if (!answer) { + throw new Error("Answer is undefined."); + } + this.sessionDescriptionHandler + .setDescription(answer.content, this.sessionDescriptionHandlerOptions, this.modifiers) + .then(function () { + _this.hasAnswer = true; + _this.status = Enums_1.SessionStatus.STATUS_CONFIRMED; + var ackRequest = inviteResponse.ack(options_1); + _this.emit("ack", ackRequest.message); + _this.accepted(response); + }) + .catch(function (error) { + _this.logger.error(error); + _this.ackAndBye(inviteResponse, session, 488, "Not Acceptable Here"); + _this.failed(response, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); + // FIME: DON'T EAT UNHANDLED ERRORS! + }); + } + else { + // Otherwise INVITE with or without Offer and we have already completed the initial exchange. + this.sessionDescriptionHandler = this.earlyMediaSessionDescriptionHandlers.get(session.id); + if (!this.sessionDescriptionHandler) { + throw new Error("Session description handler undefined."); + } + this.earlyMediaSessionDescriptionHandlers.delete(session.id); + this.hasOffer = true; + this.hasAnswer = true; + this.status = Enums_1.SessionStatus.STATUS_CONFIRMED; + var ackRequest = inviteResponse.ack(); + this.emit("ack", ackRequest.message); + this.accepted(response); + } + break; + case session_1.SignalingState.Closed: + // Dialog has terminated. + break; + default: + throw new Error("Unknown session signaling state."); + } + this.disposeEarlyMedia(); + }; + /** + * Handle provisional response to initial INVITE. + * @param inviteResponse 1xx response. + */ + InviteClientContext.prototype.onProgress = function (inviteResponse) { + var _this = this; + if (!this.outgoingInviteRequest) { + throw new Error("Outgoing INVITE request undefined."); + } + if (!this.earlyMediaSessionDescriptionHandlers) { + throw new Error("Early media session description handlers undefined."); + } + var response = inviteResponse.message; + var session = inviteResponse.session; + // Ported - User requested cancellation. + if (this.isCanceled) { + this.outgoingInviteRequest.cancel(this.cancelReason); + this.canceled(); + return; + } + // Ported - Set status. + this.status = Enums_1.SessionStatus.STATUS_1XX_RECEIVED; + // Ported - Set assertedIdentity. + if (response.hasHeader("P-Asserted-Identity")) { + this.assertedIdentity = Grammar_1.Grammar.nameAddrHeaderParse(response.getHeader("P-Asserted-Identity")); + } + // The provisional response MUST establish a dialog if one is not yet created. + // https://tools.ietf.org/html/rfc3262#section-4 + if (!session) { + // A response with a to tag MUST create a session (should never get here). + throw new Error("Session undefined."); + } + // If a provisional response is received for an initial request, and + // that response contains a Require header field containing the option + // tag 100rel, the response is to be sent reliably. If the response is + // a 100 (Trying) (as opposed to 101 to 199), this option tag MUST be + // ignored, and the procedures below MUST NOT be used. + // https://tools.ietf.org/html/rfc3262#section-4 + var requireHeader = response.getHeader("require"); + var rseqHeader = response.getHeader("rseq"); + var rseq = requireHeader && requireHeader.includes("100rel") && rseqHeader ? Number(rseqHeader) : undefined; + var responseReliable = !!rseq; + var extraHeaders = []; + if (responseReliable) { + extraHeaders.push("RAck: " + response.getHeader("rseq") + " " + response.getHeader("cseq")); + } + // INVITE without Offer and session still has no offer (and no answer). + if (session.signalingState === session_1.SignalingState.Initial) { + // Similarly, if a reliable provisional + // response is the first reliable message sent back to the UAC, and the + // INVITE did not contain an offer, one MUST appear in that reliable + // provisional response. + // https://tools.ietf.org/html/rfc3262#section-5 + if (responseReliable) { + this.logger.warn("First reliable provisional response received MUST contain an offer when INVITE does not contain an offer."); + // FIXME: Known popular UA's currently end up here... + inviteResponse.prack({ extraHeaders: extraHeaders }); + } + this.emit("progress", response); + return; + } + // INVITE with Offer and session only has that initial local offer. + if (session.signalingState === session_1.SignalingState.HaveLocalOffer) { + if (responseReliable) { + inviteResponse.prack({ extraHeaders: extraHeaders }); + } + this.emit("progress", response); + return; + } + // INVITE without Offer and received initial offer in provisional response + if (session.signalingState === session_1.SignalingState.HaveRemoteOffer) { + // The initial offer MUST be in either an INVITE or, if not there, + // in the first reliable non-failure message from the UAS back to + // the UAC. + // https://tools.ietf.org/html/rfc3261#section-13.2.1 + // According to Section 13.2.1 of [RFC3261], 'The first reliable + // non-failure message' must have an offer if there is no offer in the + // INVITE request. This means that the User Agent (UA) that receives + // the INVITE request without an offer must include an offer in the + // first reliable response with 100rel extension. If no reliable + // provisional response has been sent, the User Agent Server (UAS) must + // include an offer when sending 2xx response. + // https://tools.ietf.org/html/rfc6337#section-2.2 + if (!responseReliable) { + this.logger.warn("Non-reliable provisional response MUST NOT contain an initial offer, discarding response."); + return; + } + // If the initial offer is in the first reliable non-failure + // message from the UAS back to UAC, the answer MUST be in the + // acknowledgement for that message + var sdh_2 = this.sessionDescriptionHandlerFactory(this, this.ua.configuration.sessionDescriptionHandlerFactoryOptions || {}); + this.emit("SessionDescriptionHandler-created", sdh_2); + this.earlyMediaSessionDescriptionHandlers.set(session.id, sdh_2); + sdh_2 + .setDescription(response.body, this.sessionDescriptionHandlerOptions, this.modifiers) + .then(function () { return sdh_2.getDescription(_this.sessionDescriptionHandlerOptions, _this.modifiers); }) + .then(function (description) { + var body = { + contentDisposition: "session", contentType: description.contentType, content: description.body + }; + inviteResponse.prack({ extraHeaders: extraHeaders, body: body }); + _this.status = Enums_1.SessionStatus.STATUS_EARLY_MEDIA; + _this.emit("progress", response); + }) + .catch(function (error) { + if (_this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { + return; + } + _this.failed(undefined, Constants_1.C.causes.WEBRTC_ERROR); + _this.terminated(undefined, Constants_1.C.causes.WEBRTC_ERROR); + }); + return; + } + // This session has completed an initial offer/answer exchange, so... + // - INVITE with SDP and this provisional response MAY be reliable + // - INVITE without SDP and this provisional response MAY be reliable + if (session.signalingState === session_1.SignalingState.Stable) { + if (responseReliable) { + inviteResponse.prack({ extraHeaders: extraHeaders }); + } + // Note: As documented, no early media if offer was in INVITE, so nothing to be done. + // FIXME: TODO: Add a flag/hack to allow early media in this case. There are people + // in non-forking environments (think straight to FreeSWITCH) who want + // early media on a 183. Not sure how to actually make it work, basically + // something like... + if (0 /* flag */ && this.hasOffer && !this.hasAnswer && this.sessionDescriptionHandler) { + this.hasAnswer = true; + this.status = Enums_1.SessionStatus.STATUS_EARLY_MEDIA; + this.sessionDescriptionHandler + .setDescription(response.body, this.sessionDescriptionHandlerOptions, this.modifiers) + .then(function () { + _this.status = Enums_1.SessionStatus.STATUS_EARLY_MEDIA; + }) + .catch(function (error) { + if (_this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { + return; + } + _this.failed(undefined, Constants_1.C.causes.WEBRTC_ERROR); + _this.terminated(undefined, Constants_1.C.causes.WEBRTC_ERROR); + }); + } + this.emit("progress", response); + return; + } + }; + /** + * Handle final response to initial INVITE. + * @param inviteResponse 3xx response. + */ + InviteClientContext.prototype.onRedirect = function (inviteResponse) { + this.disposeEarlyMedia(); + var response = inviteResponse.message; + var statusCode = response.statusCode; + var cause = Utils_1.Utils.sipErrorCause(statusCode || 0); + this.rejected(response, cause); + this.failed(response, cause); + this.terminated(response, cause); + }; + /** + * Handle final response to initial INVITE. + * @param inviteResponse 4xx, 5xx, or 6xx response. + */ + InviteClientContext.prototype.onReject = function (inviteResponse) { + this.disposeEarlyMedia(); + var response = inviteResponse.message; + var statusCode = response.statusCode; + var cause = Utils_1.Utils.sipErrorCause(statusCode || 0); + this.rejected(response, cause); + this.failed(response, cause); + this.terminated(response, cause); + }; + /** + * Handle final response to initial INVITE. + * @param inviteResponse 100 response. + */ + InviteClientContext.prototype.onTrying = function (inviteResponse) { + this.received100 = true; + this.emit("progress", inviteResponse.message); + }; + return InviteClientContext; +}(Session_1.InviteClientContext)); +exports.InviteClientContext = InviteClientContext; diff --git a/lib/Contexts/invite-server-context.d.ts b/lib/Contexts/invite-server-context.d.ts new file mode 100644 index 000000000..9221ceb38 --- /dev/null +++ b/lib/Contexts/invite-server-context.d.ts @@ -0,0 +1,130 @@ +import { Body, IncomingInviteRequest, IncomingPrackRequest } from "../Core/messages"; +import { InviteServerContext as InviteServerContextBase } from "../Session"; +import { SessionDescriptionHandlerModifiers, SessionDescriptionHandlerOptions } from "../session-description-handler"; +import { IncomingRequest as IncomingRequestMessage, IncomingResponse as IncomingResponseMessage } from "../SIPMessage"; +import { UA } from "../UA"; +export declare class InviteServerContext extends InviteServerContextBase { + private incomingInviteRequest; + /** + * FIXME: TODO: + * Used to squelch throwing of errors due to async race condition. + * We have an internal race between calling `accept()` and handling + * an incoming CANCEL request. As there is no good way currently to + * delegate the handling of this async errors to the caller of + * `accept()`, we are squelching the throwing ALL errors when + * they occur after receiving a CANCEL to catch the ONE we know + * is a "normal" exceptional condition. While this is a completely + * reasonable appraoch, the decision should be left up to the library user. + */ + private _canceled; + private waitingForPrackPromise; + private waitingForPrackResolve; + private waitingForPrackReject; + constructor(ua: UA, incomingInviteRequest: IncomingInviteRequest); + acceptAndTerminate(message: IncomingResponseMessage, statusCode?: number, reasonPhrase?: string): this; + createDialog(message: IncomingRequestMessage | IncomingResponseMessage, type: "UAS" | "UAC", early?: boolean): boolean; + /** + * Sends in dialog request. + * @param method Request method. + * @param options Options bucket. + */ + sendRequest(method: string, options?: any): this; + setInvite2xxTimer(message: IncomingRequestMessage, body?: { + body: string; + contentType: string; + }): void; + setACKTimer(): void; + /** + * Accept the incoming INVITE request to start a Session. + * Replies to the INVITE request with a 200 Ok response. + * @param options Options bucket. + */ + accept(options?: InviteServerContextBase.Options): this; + /** + * Report progress to the the caller. + * Replies to the INVITE request with a 1xx provisional response. + * @param options Options bucket. + */ + progress(options?: InviteServerContextBase.Options): this; + /** + * Reject an unaccepted incoming INVITE request. + * @param options Options bucket. + */ + reject(options?: InviteServerContextBase.Options): this; + /** + * Reject an unaccepted incoming INVITE request or send BYE if established session. + * @param options Options bucket. FIXME: This options bucket needs to be typed. + */ + terminate(options?: any): this; + protected generateResponseOfferAnswer(options: { + sessionDescriptionHandlerOptions?: SessionDescriptionHandlerOptions; + modifiers?: SessionDescriptionHandlerModifiers; + }): Promise; + protected handlePrackOfferAnswer(request: IncomingPrackRequest, options: { + sessionDescriptionHandlerOptions?: SessionDescriptionHandlerOptions; + modifiers?: SessionDescriptionHandlerModifiers; + }): Promise; + /** + * Called when session canceled. + */ + protected canceled(): this; + /** + * Called when session terminated. + * Using it here just for the PRACK timeout. + */ + protected terminated(message?: IncomingResponseMessage | IncomingRequestMessage, cause?: string): this; + /** + * A version of `accept` which resolves a session when the 200 Ok response is sent. + * @param options Options bucket. + * @throws {ClosedSessionDescriptionHandlerError} The session description handler closed before method completed. + * @throws {TransactionStateError} The transaction state does not allow for `accept()` to be called. + * Note that the transaction state can change while this call is in progress. + */ + private _accept; + /** + * A version of `progress` which resolves when the provisional response is sent. + * @param options Options bucket. + * @throws {ClosedSessionDescriptionHandlerError} The session description handler closed before method completed. + * @throws {TransactionStateError} The transaction state does not allow for `progress()` to be called. + * Note that the transaction state can change while this call is in progress. + */ + private _progress; + /** + * A version of `progress` which resolves when the reliable provisional response is sent. + * @param options Options bucket. + * @throws {ClosedSessionDescriptionHandlerError} The session description handler closed before method completed. + * @throws {TransactionStateError} The transaction state does not allow for `progress()` to be called. + * Note that the transaction state can change while this call is in progress. + */ + private _reliableProgress; + /** + * A version of `progress` which resolves when the reliable provisional response is acknowledged. + * @param options Options bucket. + * @throws {ClosedSessionDescriptionHandlerError} The session description handler closed before method completed. + * @throws {TransactionStateError} The transaction state does not allow for `progress()` to be called. + * Note that the transaction state can change while this call is in progress. + */ + private _reliableProgressWaitForPrack; + /** + * Callback for when ACK for a 2xx response is never received. + * @param session Session the ACK never arrived for + */ + private onAckTimeout; + /** + * FIXME: TODO: The current library interface presents async methods without a + * proper async error handling mechanism. Arguably a promise based interface + * would be an improvement over the pattern of returning `this`. The approach has + * been generally along the lines of log a error and terminate. + */ + private onContextError; + private prackArrived; + private prackNeverArrived; + /** + * @throws {Exceptions.TerminatedSessionError} The session terminated before being accepted (i.e. cancel arrived). + */ + private waitForArrivalOfPrack; + private getOffer; + private setAnswer; + private setOfferAndGetAnswer; + private getSessionDescriptionHandler; +} diff --git a/lib/Contexts/invite-server-context.js b/lib/Contexts/invite-server-context.js new file mode 100644 index 000000000..a3cfd7866 --- /dev/null +++ b/lib/Contexts/invite-server-context.js @@ -0,0 +1,693 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var messages_1 = require("../Core/messages"); +var session_1 = require("../Core/session"); +var Constants_1 = require("../Constants"); +var Enums_1 = require("../Enums"); +var Exceptions_1 = require("../Exceptions"); +var Session_1 = require("../Session"); +var Timers_1 = require("../Timers"); +var Utils_1 = require("../Utils"); +var InviteServerContext = /** @class */ (function (_super) { + __extends(InviteServerContext, _super); + function InviteServerContext(ua, incomingInviteRequest) { + var _this = _super.call(this, ua, incomingInviteRequest.message) || this; + _this.incomingInviteRequest = incomingInviteRequest; + /** + * FIXME: TODO: + * Used to squelch throwing of errors due to async race condition. + * We have an internal race between calling `accept()` and handling + * an incoming CANCEL request. As there is no good way currently to + * delegate the handling of this async errors to the caller of + * `accept()`, we are squelching the throwing ALL errors when + * they occur after receiving a CANCEL to catch the ONE we know + * is a "normal" exceptional condition. While this is a completely + * reasonable appraoch, the decision should be left up to the library user. + */ + _this._canceled = false; + // Set the toTag on the incoming request to the toTag which + // will be used in the response to the incoming request!!! + // FIXME: HACK: This is a hack to port an existing behavior. + // The behavior being ported appears to be a hack itself, + // so this is a hack to port a hack. At least one test spec + // relies on it (which is yet another hack). See the parent + // constructor for where this is done originally. + _this.request.toTag = incomingInviteRequest.toTag; + return _this; + } + //// + // BEGIN Session Overrides - roadmap is to remove all of these, but for now... + // + // Override Session member we want to make sure we are not using. + InviteServerContext.prototype.acceptAndTerminate = function (message, statusCode, reasonPhrase) { + throw new Error("Method not utilized by user agent core."); + }; + // Override Session member we want to make sure we are not using. + InviteServerContext.prototype.createDialog = function (message, type, early) { + if (early === void 0) { early = false; } + throw new Error("Method not utilized by user agent core."); + }; + /** + * Sends in dialog request. + * @param method Request method. + * @param options Options bucket. + */ + InviteServerContext.prototype.sendRequest = function (method, options) { + if (options === void 0) { options = {}; } + if (!this.session) { + throw new Error("Session undefined."); + } + // Convert any "body" option to a Body. + if (options.body) { + options.body = messages_1.fromBodyObj(options.body); + } + // Convert any "receiveResponse" callback option passed to an OutgoingRequestDelegate. + var delegate; + var callback = options.receiveResponse; + if (callback) { + delegate = { + onAccept: function (response) { return callback(response.message); }, + onProgress: function (response) { return callback(response.message); }, + onRedirect: function (response) { return callback(response.message); }, + onReject: function (response) { return callback(response.message); }, + onTrying: function (response) { return callback(response.message); } + }; + } + var request; + var requestOptions = options; + switch (method) { + case Constants_1.C.BYE: + request = this.session.bye(delegate, requestOptions); + break; + case Constants_1.C.INVITE: + request = this.session.invite(delegate, requestOptions); + break; + case Constants_1.C.REFER: + request = this.session.refer(delegate, requestOptions); + break; + default: + throw new Error("Unexpected " + method + ". Method not implemented by user agent core."); + } + // Ported - Emit the request event + this.emit(method.toLowerCase(), request.message); + return this; + }; + // Override Session member we want to make sure we are not using. + InviteServerContext.prototype.setInvite2xxTimer = function (message, body) { + throw new Error("Method not utilized by user agent core."); + }; + // Override Session member we want to make sure we are not using. + InviteServerContext.prototype.setACKTimer = function () { + // throw new Error("Method not utilized by user agent core."); + // FIXME: TODO: This gets called by receiveReinvite(). + // Just prevent it from doing anything for now until we stop calling that. + return; + }; + // END Session Overrides + ////// + /** + * Accept the incoming INVITE request to start a Session. + * Replies to the INVITE request with a 200 Ok response. + * @param options Options bucket. + */ + InviteServerContext.prototype.accept = function (options) { + var _this = this; + if (options === void 0) { options = {}; } + this._accept(options) + .then(function (_a) { + var message = _a.message, session = _a.session; + session.delegate = { + onAck: function (ackRequest) { return _this.receiveRequest(ackRequest.message); }, + onAckTimeout: function () { return _this.onAckTimeout(); }, + onBye: function (byeRequest) { return _this.receiveRequest(byeRequest.message); }, + onInfo: function (infoRequest) { return _this.receiveRequest(infoRequest.message); }, + onInvite: function (inviteRequest) { return _this.receiveRequest(inviteRequest.message); }, + onNotify: function (notifyRequest) { return _this.receiveRequest(notifyRequest.message); }, + onPrack: function (prackRequest) { return _this.receiveRequest(prackRequest.message); }, + onRefer: function (referRequest) { return _this.receiveRequest(referRequest.message); } + }; + _this.session = session; + _this.status = Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK; + _this.accepted(message, Utils_1.Utils.getReasonPhrase(200)); + }) + .catch(function (error) { + _this.onContextError(error); + // FIXME: Assuming error due to async race on CANCEL and eating error. + if (!_this._canceled) { + throw error; + } + }); + return this; + }; + /** + * Report progress to the the caller. + * Replies to the INVITE request with a 1xx provisional response. + * @param options Options bucket. + */ + InviteServerContext.prototype.progress = function (options) { + var _this = this; + if (options === void 0) { options = {}; } + // Ported + var statusCode = options.statusCode || 180; + if (statusCode < 100 || statusCode > 199) { + throw new TypeError("Invalid statusCode: " + statusCode); + } + // Ported + if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { + this.logger.warn("Unexpected call for progress while terminated, ignoring"); + return this; + } + // Added + if (this.status === Enums_1.SessionStatus.STATUS_ANSWERED) { + this.logger.warn("Unexpected call for progress while answered, ignoring"); + return this; + } + // Added + if (this.status === Enums_1.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK) { + this.logger.warn("Unexpected call for progress while answered (waiting for prack), ignoring"); + return this; + } + // After the first reliable provisional response for a request has been + // acknowledged, the UAS MAY send additional reliable provisional + // responses. The UAS MUST NOT send a second reliable provisional + // response until the first is acknowledged. After the first, it is + // RECOMMENDED that the UAS not send an additional reliable provisional + // response until the previous is acknowledged. The first reliable + // provisional response receives special treatment because it conveys + // the initial sequence number. If additional reliable provisional + // responses were sent before the first was acknowledged, the UAS could + // not be certain these were received in order. + // https://tools.ietf.org/html/rfc3262#section-3 + if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_PRACK) { + this.logger.warn("Unexpected call for progress while waiting for prack, ignoring"); + return this; + } + // Ported + if (options.statusCode === 100) { + try { + this.incomingInviteRequest.trying(); + } + catch (error) { + this.onContextError(error); + // FIXME: Assuming error due to async race on CANCEL and eating error. + if (!this._canceled) { + throw error; + } + } + return this; + } + // Standard provisional response. + if (!(this.rel100 === Constants_1.C.supported.REQUIRED) && + !(this.rel100 === Constants_1.C.supported.SUPPORTED && options.rel100) && + !(this.rel100 === Constants_1.C.supported.SUPPORTED && this.ua.configuration.rel100 === Constants_1.C.supported.REQUIRED)) { + this._progress(options) + .catch(function (error) { + _this.onContextError(error); + // FIXME: Assuming error due to async race on CANCEL and eating error. + if (!_this._canceled) { + throw error; + } + }); + return this; + } + // Reliable provisional response. + this._reliableProgressWaitForPrack(options) + .catch(function (error) { + _this.onContextError(error); + // FIXME: Assuming error due to async race on CANCEL and eating error. + if (!_this._canceled) { + throw error; + } + }); + return this; + }; + /** + * Reject an unaccepted incoming INVITE request. + * @param options Options bucket. + */ + InviteServerContext.prototype.reject = function (options) { + if (options === void 0) { options = {}; } + return _super.prototype.reject.call(this, options); + }; + /** + * Reject an unaccepted incoming INVITE request or send BYE if established session. + * @param options Options bucket. FIXME: This options bucket needs to be typed. + */ + InviteServerContext.prototype.terminate = function (options) { + // The caller's UA MAY send a BYE for either confirmed or early dialogs, + // and the callee's UA MAY send a BYE on confirmed dialogs, but MUST NOT + // send a BYE on early dialogs. However, the callee's UA MUST NOT send a + // BYE on a confirmed dialog until it has received an ACK for its 2xx + // response or until the server transaction times out. + // https://tools.ietf.org/html/rfc3261#section-15 + var _this = this; + if (options === void 0) { options = {}; } + // We don't yet have a dialog, so reject request. + if (!this.session) { + this.reject(options); + return this; + } + switch (this.session.sessionState) { + case session_1.SessionState.Initial: + this.reject(options); + return this; + case session_1.SessionState.Early: + this.reject(options); + return this; + case session_1.SessionState.AckWait: + this.session.delegate = { + // When ACK shows up, say BYE. + onAck: function () { + _this.bye(); + }, + // Or the server transaction times out before the ACK arrives. + onAckTimeout: function () { + _this.bye(); + } + }; + // Ported + this.emit("bye", this.request); + this.terminated(); + return this; + case session_1.SessionState.Confirmed: + this.bye(options); + return this; + case session_1.SessionState.Terminated: + return this; + default: + return this; + } + }; + InviteServerContext.prototype.generateResponseOfferAnswer = function (options) { + if (!this.session) { + var body = messages_1.getBody(this.incomingInviteRequest.message); + if (!body || body.contentDisposition !== "session") { + return this.getOffer(options); + } + else { + return this.setOfferAndGetAnswer(body, options); + } + } + else { + switch (this.session.signalingState) { + case session_1.SignalingState.Initial: + return this.getOffer(options); + case session_1.SignalingState.Stable: + return Promise.resolve(undefined); + case session_1.SignalingState.HaveLocalOffer: + // o Once the UAS has sent or received an answer to the initial + // offer, it MUST NOT generate subsequent offers in any responses + // to the initial INVITE. This means that a UAS based on this + // specification alone can never generate subsequent offers until + // completion of the initial transaction. + // https://tools.ietf.org/html/rfc3261#section-13.2.1 + return Promise.resolve(undefined); + case session_1.SignalingState.HaveRemoteOffer: + if (!this.session.offer) { + throw new Error("Session offer undefined"); + } + return this.setOfferAndGetAnswer(this.session.offer, options); + case session_1.SignalingState.Closed: + throw new Error("Invalid signaling state " + this.session.signalingState + "."); + default: + throw new Error("Invalid signaling state " + this.session.signalingState + "."); + } + } + }; + InviteServerContext.prototype.handlePrackOfferAnswer = function (request, options) { + if (!this.session) { + throw new Error("Session undefined."); + } + // If the PRACK doesn't have an offer/answer, nothing to be done. + var body = messages_1.getBody(request.message); + if (!body || body.contentDisposition !== "session") { + return Promise.resolve(undefined); + } + // If the UAC receives a reliable provisional response with an offer + // (this would occur if the UAC sent an INVITE without an offer, in + // which case the first reliable provisional response will contain the + // offer), it MUST generate an answer in the PRACK. If the UAC receives + // a reliable provisional response with an answer, it MAY generate an + // additional offer in the PRACK. If the UAS receives a PRACK with an + // offer, it MUST place the answer in the 2xx to the PRACK. + // https://tools.ietf.org/html/rfc3262#section-5 + switch (this.session.signalingState) { + case session_1.SignalingState.Initial: + // State should never be reached as first reliable provisional response must have answer/offer. + throw new Error("Invalid signaling state " + this.session.signalingState + "."); + case session_1.SignalingState.Stable: + // Receved answer. + return this.setAnswer(body, options).then(function () { return undefined; }); + case session_1.SignalingState.HaveLocalOffer: + // State should never be reached as local offer would be answered by this PRACK + throw new Error("Invalid signaling state " + this.session.signalingState + "."); + case session_1.SignalingState.HaveRemoteOffer: + // Receved offer, generate answer. + return this.setOfferAndGetAnswer(body, options); + case session_1.SignalingState.Closed: + throw new Error("Invalid signaling state " + this.session.signalingState + "."); + default: + throw new Error("Invalid signaling state " + this.session.signalingState + "."); + } + }; + /** + * Called when session canceled. + */ + InviteServerContext.prototype.canceled = function () { + this._canceled = true; + return _super.prototype.canceled.call(this); + }; + /** + * Called when session terminated. + * Using it here just for the PRACK timeout. + */ + InviteServerContext.prototype.terminated = function (message, cause) { + this.prackNeverArrived(); + return _super.prototype.terminated.call(this, message, cause); + }; + /** + * A version of `accept` which resolves a session when the 200 Ok response is sent. + * @param options Options bucket. + * @throws {ClosedSessionDescriptionHandlerError} The session description handler closed before method completed. + * @throws {TransactionStateError} The transaction state does not allow for `accept()` to be called. + * Note that the transaction state can change while this call is in progress. + */ + InviteServerContext.prototype._accept = function (options) { + var _this = this; + if (options === void 0) { options = {}; } + // FIXME: Ported - callback for in dialog INFO requests. + // Turns out accept() can be called more than once if we are waiting + // for a PRACK in which case "options" get completely tossed away. + // So this is broken in that case (and potentially other uses of options). + // Tempted to just try to fix it now, but leaving it broken for the moment. + this.onInfo = options.onInfo; + // The UAS MAY send a final response to the initial request before + // having received PRACKs for all unacknowledged reliable provisional + // responses, unless the final response is 2xx and any of the + // unacknowledged reliable provisional responses contained a session + // description. In that case, it MUST NOT send a final response until + // those provisional responses are acknowledged. If the UAS does send a + // final response when reliable responses are still unacknowledged, it + // SHOULD NOT continue to retransmit the unacknowledged reliable + // provisional responses, but it MUST be prepared to process PRACK + // requests for those outstanding responses. A UAS MUST NOT send new + // reliable provisional responses (as opposed to retransmissions of + // unacknowledged ones) after sending a final response to a request. + // https://tools.ietf.org/html/rfc3262#section-3 + if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_PRACK) { + this.status = Enums_1.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK; + return this.waitForArrivalOfPrack() + .then(function () { + _this.status = Enums_1.SessionStatus.STATUS_ANSWERED; + clearTimeout(_this.timers.userNoAnswerTimer); // Ported + }) + .then(function () { return _this.generateResponseOfferAnswer(options); }) + .then(function (body) { return _this.incomingInviteRequest.accept({ statusCode: 200, body: body }); }); + } + // Ported + if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER) { + this.status = Enums_1.SessionStatus.STATUS_ANSWERED; + } + else { + return Promise.reject(new Exceptions_1.Exceptions.InvalidStateError(this.status)); + } + this.status = Enums_1.SessionStatus.STATUS_ANSWERED; + clearTimeout(this.timers.userNoAnswerTimer); // Ported + return this.generateResponseOfferAnswer(options) + .then(function (body) { return _this.incomingInviteRequest.accept({ statusCode: 200, body: body }); }); + }; + /** + * A version of `progress` which resolves when the provisional response is sent. + * @param options Options bucket. + * @throws {ClosedSessionDescriptionHandlerError} The session description handler closed before method completed. + * @throws {TransactionStateError} The transaction state does not allow for `progress()` to be called. + * Note that the transaction state can change while this call is in progress. + */ + InviteServerContext.prototype._progress = function (options) { + if (options === void 0) { options = {}; } + // Ported + var statusCode = options.statusCode || 180; + var reasonPhrase = options.reasonPhrase; + var extraHeaders = (options.extraHeaders || []).slice(); + var body = options.body ? messages_1.fromBodyLegacy(options.body) : undefined; + try { + var progressResponse = this.incomingInviteRequest.progress({ statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }); + this.emit("progress", progressResponse.message, reasonPhrase); // Ported + this.session = progressResponse.session; + return Promise.resolve(progressResponse); + } + catch (error) { + return Promise.reject(error); + } + }; + /** + * A version of `progress` which resolves when the reliable provisional response is sent. + * @param options Options bucket. + * @throws {ClosedSessionDescriptionHandlerError} The session description handler closed before method completed. + * @throws {TransactionStateError} The transaction state does not allow for `progress()` to be called. + * Note that the transaction state can change while this call is in progress. + */ + InviteServerContext.prototype._reliableProgress = function (options) { + var _this = this; + if (options === void 0) { options = {}; } + var statusCode = options.statusCode || 183; + var reasonPhrase = options.reasonPhrase; + var extraHeaders = (options.extraHeaders || []).slice(); + extraHeaders.push("Require: 100rel"); + extraHeaders.push("RSeq: " + Math.floor(Math.random() * 10000)); + // Get an offer/answer and send a reply. + return this.generateResponseOfferAnswer(options) + .then(function (body) { return _this.incomingInviteRequest.progress({ statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }); }) + .then(function (progressResponse) { + _this.emit("progress", progressResponse.message, reasonPhrase); // Ported + _this.session = progressResponse.session; + return progressResponse; + }); + }; + /** + * A version of `progress` which resolves when the reliable provisional response is acknowledged. + * @param options Options bucket. + * @throws {ClosedSessionDescriptionHandlerError} The session description handler closed before method completed. + * @throws {TransactionStateError} The transaction state does not allow for `progress()` to be called. + * Note that the transaction state can change while this call is in progress. + */ + InviteServerContext.prototype._reliableProgressWaitForPrack = function (options) { + var _this = this; + if (options === void 0) { options = {}; } + var statusCode = options.statusCode || 183; + var reasonPhrase = options.reasonPhrase; + var extraHeaders = (options.extraHeaders || []).slice(); + extraHeaders.push("Require: 100rel"); + extraHeaders.push("RSeq: " + Math.floor(Math.random() * 10000)); + var body; + // Ported - set status. + this.status = Enums_1.SessionStatus.STATUS_WAITING_FOR_PRACK; + return new Promise(function (resolve, reject) { + var waitingForPrack = true; + return _this.generateResponseOfferAnswer(options) + .then(function (offerAnswer) { + body = offerAnswer; + return _this.incomingInviteRequest.progress({ statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }); + }) + .then(function (progressResponse) { + _this.emit("progress", progressResponse.message, reasonPhrase); // Ported + _this.session = progressResponse.session; + var prackRequest; + var prackResponse; + progressResponse.session.delegate = { + onPrack: function (request) { + prackRequest = request; + clearTimeout(prackWaitTimeoutTimer); + clearTimeout(rel1xxRetransmissionTimer); + if (!waitingForPrack) { + return; + } + waitingForPrack = false; + _this.handlePrackOfferAnswer(prackRequest, options) + .then(function (prackResponseBody) { + try { + prackResponse = prackRequest.accept({ statusCode: 200, body: prackResponseBody }); + // Ported - set status. + if (_this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_PRACK) { + _this.status = Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER; + } + _this.prackArrived(); + resolve({ prackRequest: prackRequest, prackResponse: prackResponse, progressResponse: progressResponse }); + } + catch (error) { + reject(error); + } + }); + } + }; + // https://tools.ietf.org/html/rfc3262#section-3 + var prackWaitTimeout = function () { + if (!waitingForPrack) { + return; + } + waitingForPrack = false; + _this.logger.warn("No PRACK received, rejecting INVITE."); + clearTimeout(rel1xxRetransmissionTimer); + try { + _this.incomingInviteRequest.reject({ statusCode: 504 }); + _this.terminated(undefined, Constants_1.C.causes.NO_PRACK); + reject(new Exceptions_1.Exceptions.TerminatedSessionError()); + } + catch (error) { + reject(error); + } + }; + var prackWaitTimeoutTimer = setTimeout(prackWaitTimeout, Timers_1.Timers.T1 * 64); + // https://tools.ietf.org/html/rfc3262#section-3 + var rel1xxRetransmission = function () { + try { + _this.incomingInviteRequest.progress({ statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }); + } + catch (error) { + waitingForPrack = false; + reject(error); + return; + } + rel1xxRetransmissionTimer = setTimeout(rel1xxRetransmission, timeout *= 2); + }; + var timeout = Timers_1.Timers.T1; + var rel1xxRetransmissionTimer = setTimeout(rel1xxRetransmission, timeout); + }); + }); + }; + /** + * Callback for when ACK for a 2xx response is never received. + * @param session Session the ACK never arrived for + */ + InviteServerContext.prototype.onAckTimeout = function () { + if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK) { + this.logger.log("no ACK received for an extended period of time, terminating the call"); + if (!this.session) { + throw new Error("Session undefined."); + } + this.session.bye(); + this.terminated(undefined, Constants_1.C.causes.NO_ACK); + } + }; + /** + * FIXME: TODO: The current library interface presents async methods without a + * proper async error handling mechanism. Arguably a promise based interface + * would be an improvement over the pattern of returning `this`. The approach has + * been generally along the lines of log a error and terminate. + */ + InviteServerContext.prototype.onContextError = function (error) { + if (error instanceof Exceptions_1.Exception) { // There might be interest in catching these Exceptions. + if (error instanceof Exceptions_1.Exceptions.SessionDescriptionHandlerError) { + this.logger.error(error.message); + if (error.error) { + this.logger.error(error.error); + } + } + else if (error instanceof Exceptions_1.Exception) { + this.logger.error(error.message); + } + } + else if (error instanceof Exceptions_1.Exceptions.TerminatedSessionError) { + // PRACK never arrived, so we timed out waiting for it. + this.logger.warn("Incoming session terminated while waiting for PRACK."); + } + else if (error instanceof Error) { // Other Errors hould go uncaught. + this.logger.error(error.message); + } + else { + // We don't actually know what a session description handler implementation might throw + // our way, so as a last resort, just assume we are getting an "any" and log it. + this.logger.error("An error occurred in the session description handler."); + this.logger.error(error); + } + try { + this.incomingInviteRequest.reject({ statusCode: 480 }); // "Temporarily Unavailable" + this.failed(this.incomingInviteRequest.message, error.message); + this.terminated(this.incomingInviteRequest.message, error.message); + } + catch (error) { + return; + } + }; + InviteServerContext.prototype.prackArrived = function () { + if (this.waitingForPrackResolve) { + this.waitingForPrackResolve(); + } + this.waitingForPrackPromise = undefined; + this.waitingForPrackResolve = undefined; + this.waitingForPrackReject = undefined; + }; + InviteServerContext.prototype.prackNeverArrived = function () { + if (this.waitingForPrackReject) { + this.waitingForPrackReject(new Exceptions_1.Exceptions.TerminatedSessionError()); + } + this.waitingForPrackPromise = undefined; + this.waitingForPrackResolve = undefined; + this.waitingForPrackReject = undefined; + }; + /** + * @throws {Exceptions.TerminatedSessionError} The session terminated before being accepted (i.e. cancel arrived). + */ + InviteServerContext.prototype.waitForArrivalOfPrack = function () { + var _this = this; + if (this.waitingForPrackPromise) { + throw new Error("Already waiting for PRACK"); + } + this.waitingForPrackPromise = new Promise(function (resolve, reject) { + _this.waitingForPrackResolve = resolve; + _this.waitingForPrackReject = reject; + }); + return this.waitingForPrackPromise; + }; + InviteServerContext.prototype.getOffer = function (options) { + this.hasOffer = true; + var sdh = this.getSessionDescriptionHandler(); + return sdh + .getDescription(options.sessionDescriptionHandlerOptions, options.modifiers) + .then(function (bodyObj) { return messages_1.fromBodyObj(bodyObj); }); + }; + InviteServerContext.prototype.setAnswer = function (answer, options) { + this.hasAnswer = true; + var sdh = this.getSessionDescriptionHandler(); + if (!sdh.hasDescription(answer.contentType)) { + return Promise.reject(new Exceptions_1.Exceptions.UnsupportedSessionDescriptionContentTypeError()); + } + return sdh + .setDescription(answer.content, options.sessionDescriptionHandlerOptions, options.modifiers); + }; + InviteServerContext.prototype.setOfferAndGetAnswer = function (offer, options) { + this.hasOffer = true; + this.hasAnswer = true; + var sdh = this.getSessionDescriptionHandler(); + if (!sdh.hasDescription(offer.contentType)) { + return Promise.reject(new Exceptions_1.Exceptions.UnsupportedSessionDescriptionContentTypeError()); + } + return sdh + .setDescription(offer.content, options.sessionDescriptionHandlerOptions, options.modifiers) + .then(function () { return sdh.getDescription(options.sessionDescriptionHandlerOptions, options.modifiers); }) + .then(function (bodyObj) { return messages_1.fromBodyObj(bodyObj); }); + }; + InviteServerContext.prototype.getSessionDescriptionHandler = function () { + // Create our session description handler if not already done so... + var sdh = this.sessionDescriptionHandler = this.setupSessionDescriptionHandler(); + // FIXME: Ported - this can get emitted multiple times even when only created once... don't we care? + this.emit("SessionDescriptionHandler-created", this.sessionDescriptionHandler); + // Return. + return sdh; + }; + return InviteServerContext; +}(Session_1.InviteServerContext)); +exports.InviteServerContext = InviteServerContext; diff --git a/lib/Contexts/publish-client-context.d.ts b/lib/Contexts/publish-client-context.d.ts new file mode 100644 index 000000000..97dbd41fa --- /dev/null +++ b/lib/Contexts/publish-client-context.d.ts @@ -0,0 +1,14 @@ +import { PublishContext as PublishClientContextBase } from "../PublishContext"; +import { IncomingResponse as IncomingResponseMessage } from "../SIPMessage"; +import { UA } from "../UA"; +import { URI } from "../URI"; +export declare class PublishClientContext extends PublishClientContextBase { + constructor(ua: UA, target: string | URI, event: string, options?: any); + onRequestTimeout(): void; + onTransportError(): void; + receiveResponse(message: IncomingResponseMessage): void; + send(): this; + publish(body: string): void; + unpublish(): void; + close(): void; +} diff --git a/lib/Contexts/publish-client-context.js b/lib/Contexts/publish-client-context.js new file mode 100644 index 000000000..ac19f431b --- /dev/null +++ b/lib/Contexts/publish-client-context.js @@ -0,0 +1,61 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var PublishContext_1 = require("../PublishContext"); +var PublishClientContext = /** @class */ (function (_super) { + __extends(PublishClientContext, _super); + function PublishClientContext(ua, target, event, options) { + if (options === void 0) { options = {}; } + return _super.call(this, ua, target, event, options) || this; + } + // Override ClientContext + PublishClientContext.prototype.onRequestTimeout = function () { + throw new Error("Method not utilized by user agent core."); + }; + // Override ClientContext + PublishClientContext.prototype.onTransportError = function () { + throw new Error("Method not utilized by user agent core."); + }; + // Override ClientContext + PublishClientContext.prototype.receiveResponse = function (message) { + _super.prototype.receiveResponse.call(this, message); + }; + // Override ClientContext + PublishClientContext.prototype.send = function () { + var _this = this; + if (!this.ua.userAgentCore) { + throw new Error("User agent core undefined."); + } + this.ua.userAgentCore.publish(this.request, { + onAccept: function (response) { return _this.receiveResponse(response.message); }, + onProgress: function (response) { return _this.receiveResponse(response.message); }, + onRedirect: function (response) { return _this.receiveResponse(response.message); }, + onReject: function (response) { return _this.receiveResponse(response.message); }, + onTrying: function (response) { return _this.receiveResponse(response.message); } + }); + return this; + }; + PublishClientContext.prototype.publish = function (body) { + return _super.prototype.publish.call(this, body); + }; + PublishClientContext.prototype.unpublish = function () { + return _super.prototype.unpublish.call(this); + }; + PublishClientContext.prototype.close = function () { + return _super.prototype.close.call(this); + }; + return PublishClientContext; +}(PublishContext_1.PublishContext)); +exports.PublishClientContext = PublishClientContext; diff --git a/lib/Contexts/refer-client-context.d.ts b/lib/Contexts/refer-client-context.d.ts new file mode 100644 index 000000000..aa89a15af --- /dev/null +++ b/lib/Contexts/refer-client-context.d.ts @@ -0,0 +1,21 @@ +import { ReferClientContext as ReferClientContextBase } from "../ReferContext"; +import { InviteClientContext, InviteServerContext } from "../Session"; +import { UA } from "../UA"; +import { URI } from "../URI"; +export declare class ReferClientContext extends ReferClientContextBase { + /** + * Sends an in dialog REFER and handles the implicit subscription + * dialog usage created by a REFER. The REFER is sent within the session + * managed by the supplied InviteClientContext or InviteServerContext. + * @param ua UA + * @param context The invite context within which REFER will be sent. + * @param target Target of the REFER. + * @param options Options bucket. + */ + constructor(ua: UA, context: InviteClientContext | InviteServerContext, target: InviteClientContext | InviteServerContext | string, options?: any); + onRequestTimeout(): void; + onTransportError(): void; + receiveResponse(): void; + send(): this; + protected initReferTo(target: InviteClientContext | InviteServerContext | string): string | URI; +} diff --git a/lib/Contexts/refer-client-context.js b/lib/Contexts/refer-client-context.js new file mode 100644 index 000000000..8eff91a01 --- /dev/null +++ b/lib/Contexts/refer-client-context.js @@ -0,0 +1,79 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Grammar_1 = require("../Grammar"); +var ReferContext_1 = require("../ReferContext"); +var ReferClientContext = /** @class */ (function (_super) { + __extends(ReferClientContext, _super); + /** + * Sends an in dialog REFER and handles the implicit subscription + * dialog usage created by a REFER. The REFER is sent within the session + * managed by the supplied InviteClientContext or InviteServerContext. + * @param ua UA + * @param context The invite context within which REFER will be sent. + * @param target Target of the REFER. + * @param options Options bucket. + */ + function ReferClientContext(ua, context, target, options) { + if (options === void 0) { options = {}; } + return _super.call(this, ua, context, target, options) || this; + } + // Override ClientContext + ReferClientContext.prototype.onRequestTimeout = function () { + throw new Error("Method not utilized by user agent core."); + }; + // Override ClientContext + ReferClientContext.prototype.onTransportError = function () { + throw new Error("Method not utilized by user agent core."); + }; + // Override ClientContext + ReferClientContext.prototype.receiveResponse = function () { + throw new Error("Method not utilized by user agent core."); + }; + // Override ClientContext + ReferClientContext.prototype.send = function () { + throw new Error("Method not utilized by user agent core."); + }; + ReferClientContext.prototype.initReferTo = function (target) { + var stringOrURI; + if (typeof target === "string") { + // REFER without Replaces (Blind Transfer) + var targetString = Grammar_1.Grammar.parse(target, "Refer_To"); + stringOrURI = targetString && targetString.uri ? targetString.uri : target; + // Check target validity + var targetUri = this.ua.normalizeTarget(target); + if (!targetUri) { + throw new TypeError("Invalid target: " + target); + } + stringOrURI = targetUri; + } + else { + // REFER with Replaces (Attended Transfer) + if (!target.session) { + throw new Error("Session undefined."); + } + var displayName = target.remoteIdentity.friendlyName; + var remoteTarget = target.session.remoteTarget.toString(); + var callId = target.session.callId; + var remoteTag = target.session.remoteTag; + var localTag = target.session.localTag; + var replaces = encodeURIComponent(callId + ";to-tag=" + remoteTag + ";from-tag=" + localTag); + stringOrURI = "\"" + displayName + "\" <" + remoteTarget + "?Replaces=" + replaces + ">"; + } + return stringOrURI; + }; + return ReferClientContext; +}(ReferContext_1.ReferClientContext)); +exports.ReferClientContext = ReferClientContext; diff --git a/lib/Contexts/refer-server-context.d.ts b/lib/Contexts/refer-server-context.d.ts new file mode 100644 index 000000000..ba71098b0 --- /dev/null +++ b/lib/Contexts/refer-server-context.d.ts @@ -0,0 +1,26 @@ +import { Session } from "../Core/session"; +import { ReferServerContext as ReferServerContextBase } from "../ReferContext"; +import { SessionDescriptionHandlerModifiers } from "../session-description-handler"; +import { IncomingRequest as IncomingRequestMessage } from "../SIPMessage"; +import { UA } from "../UA"; +export declare class ReferServerContext extends ReferServerContextBase { + private session?; + /** + * Receives an in dialog REFER and handles the implicit subscription + * dialog usage created by a REFER. The REFER is received within the + * session provided. + * @param ua UA + * @param context The invite context within which REFER will be sent. + * @param target Target of the REFER. + * @param options Options bucket. + */ + constructor(ua: UA, message: IncomingRequestMessage, session?: Session | undefined); + accept(options: ReferServerContextBase.AcceptOptions, modifiers?: SessionDescriptionHandlerModifiers): void; + progress(): void; + reject(options: ReferServerContextBase.RejectOptions): void; + /** + * Send an in dialog NOTIFY. + * @param body Content of body. + */ + sendNotify(body: string): void; +} diff --git a/lib/Contexts/refer-server-context.js b/lib/Contexts/refer-server-context.js new file mode 100644 index 000000000..5d029d445 --- /dev/null +++ b/lib/Contexts/refer-server-context.js @@ -0,0 +1,109 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var transactions_1 = require("../Core/transactions"); +var Constants_1 = require("../Constants"); +var Enums_1 = require("../Enums"); +var Exceptions_1 = require("../Exceptions"); +var Grammar_1 = require("../Grammar"); +var ReferContext_1 = require("../ReferContext"); +var SIPMessage_1 = require("../SIPMessage"); +var ReferServerContext = /** @class */ (function (_super) { + __extends(ReferServerContext, _super); + /** + * Receives an in dialog REFER and handles the implicit subscription + * dialog usage created by a REFER. The REFER is received within the + * session provided. + * @param ua UA + * @param context The invite context within which REFER will be sent. + * @param target Target of the REFER. + * @param options Options bucket. + */ + function ReferServerContext(ua, message, session) { + var _this = _super.call(this, ua, message) || this; + _this.session = session; + return _this; + } + ReferServerContext.prototype.accept = function (options, modifiers) { + _super.prototype.accept.call(this, options, modifiers); + }; + ReferServerContext.prototype.progress = function () { + _super.prototype.progress.call(this); + }; + ReferServerContext.prototype.reject = function (options) { + _super.prototype.reject.call(this, options); + }; + /** + * Send an in dialog NOTIFY. + * @param body Content of body. + */ + ReferServerContext.prototype.sendNotify = function (body) { + // FIXME: Ported this. Clean it up. Session knows its state. + if (this.status !== Enums_1.SessionStatus.STATUS_ANSWERED) { + throw new Exceptions_1.Exceptions.InvalidStateError(this.status); + } + if (Grammar_1.Grammar.parse(body, "sipfrag") === -1) { + throw new Error("sipfrag body is required to send notify for refer"); + } + // NOTIFY requests sent in same dialog as in dialog REFER. + if (this.session) { + this.session.notify(undefined, { + extraHeaders: [ + "Event: refer", + "Subscription-State: terminated", + ], + body: { + contentDisposition: "render", + contentType: "message/sipfrag", + content: body + } + }); + return; + } + // The implicit subscription created by a REFER is the same as a + // subscription created with a SUBSCRIBE request. The agent issuing the + // REFER can terminate this subscription prematurely by unsubscribing + // using the mechanisms described in [2]. Terminating a subscription, + // either by explicitly unsubscribing or rejecting NOTIFY, is not an + // indication that the referenced request should be withdrawn or + // abandoned. + // https://tools.ietf.org/html/rfc3515#section-2.4.4 + // NOTIFY requests sent in new dialog for out of dialog REFER. + // FIXME: TODO: This should be done in a subscribe dialog to satisfy the above. + var request = new SIPMessage_1.OutgoingRequest(Constants_1.C.NOTIFY, this.remoteTarget, this.ua, { + cseq: this.cseq += 1, + callId: this.callId, + fromUri: this.fromUri, + fromTag: this.fromTag, + toUri: this.toUri, + toTag: this.toTag, + routeSet: this.routeSet + }, [ + "Event: refer", + "Subscription-State: terminated", + "Content-Type: message/sipfrag" + ], body); + var transport = this.ua.transport; + if (!transport) { + throw new Error("Transport undefined."); + } + var user = { + loggerFactory: this.ua.getLoggerFactory() + }; + var nic = new transactions_1.NonInviteClientTransaction(request, transport, user); + }; + return ReferServerContext; +}(ReferContext_1.ReferServerContext)); +exports.ReferServerContext = ReferServerContext; diff --git a/lib/Contexts/subscribe-client-context.d.ts b/lib/Contexts/subscribe-client-context.d.ts new file mode 100644 index 000000000..d8610e68d --- /dev/null +++ b/lib/Contexts/subscribe-client-context.d.ts @@ -0,0 +1,18 @@ +import { IncomingRequest as IncomingRequestMessage, IncomingResponse as IncomingResponseMessage } from "../SIPMessage"; +import { Subscription as SubscribeClientContextBase } from "../Subscription"; +import { UA } from "../UA"; +import { URI } from "../URI"; +export declare class SubscribeClientContext extends SubscribeClientContextBase { + private subscription; + constructor(ua: UA, target: string | URI, event: string, options?: any); + onRequestTimeout(): void; + onTransportError(): void; + receiveResponse(message: IncomingResponseMessage): void; + send(): this; + refresh(): void; + subscribe(): SubscribeClientContextBase; + unsubscribe(): void; + close(): void; + protected sendSubscribeRequest(options?: any): void; + protected createConfirmedDialog(message: IncomingRequestMessage, type: "UAC" | "UAS"): boolean; +} diff --git a/lib/Contexts/subscribe-client-context.js b/lib/Contexts/subscribe-client-context.js new file mode 100644 index 000000000..0f02ffe6d --- /dev/null +++ b/lib/Contexts/subscribe-client-context.js @@ -0,0 +1,78 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Subscription_1 = require("../Subscription"); +var SubscribeClientContext = /** @class */ (function (_super) { + __extends(SubscribeClientContext, _super); + function SubscribeClientContext(ua, target, event, options) { + if (options === void 0) { options = {}; } + return _super.call(this, ua, target, event, options) || this; + } + // Override ClientContext + SubscribeClientContext.prototype.onRequestTimeout = function () { + throw new Error("Method not utilized by user agent core."); + }; + // Override ClientContext + SubscribeClientContext.prototype.onTransportError = function () { + throw new Error("Method not utilized by user agent core."); + }; + // Override ClientContext + SubscribeClientContext.prototype.receiveResponse = function (message) { + _super.prototype.receiveResponse.call(this, message); + }; + // Override ClientContext + SubscribeClientContext.prototype.send = function () { + var _this = this; + if (!this.ua.userAgentCore) { + throw new Error("User agent core undefined."); + } + this.ua.userAgentCore.subscribe(this.request, { + onAccept: function (subscribeResponse) { + _this.subscription = subscribeResponse.subscription; + return _this.receiveResponse(subscribeResponse.message); + }, + onProgress: function (subscribeResponse) { return _this.receiveResponse(subscribeResponse.message); }, + onRedirect: function (subscribeResponse) { return _this.receiveResponse(subscribeResponse.message); }, + onReject: function (subscribeResponse) { return _this.receiveResponse(subscribeResponse.message); }, + onTrying: function (subscribeResponse) { return _this.receiveResponse(subscribeResponse.message); } + }); + return this; + }; + SubscribeClientContext.prototype.refresh = function () { + _super.prototype.refresh.call(this); + }; + SubscribeClientContext.prototype.subscribe = function () { + return _super.prototype.subscribe.call(this); + }; + SubscribeClientContext.prototype.unsubscribe = function () { + _super.prototype.unsubscribe.call(this); + }; + SubscribeClientContext.prototype.close = function () { + return; + }; + SubscribeClientContext.prototype.sendSubscribeRequest = function (options) { + if (options === void 0) { options = {}; } + if (!this.subscription) { + throw new Error("Subscription undefined."); + } + this.subscription.subscribe(options); + }; + // Override SubscribeClientContextBase member we want to make sure we are not using. + SubscribeClientContext.prototype.createConfirmedDialog = function (message, type) { + return true; + }; + return SubscribeClientContext; +}(Subscription_1.Subscription)); +exports.SubscribeClientContext = SubscribeClientContext; diff --git a/lib/Core/dialogs/dialog-state.d.ts b/lib/Core/dialogs/dialog-state.d.ts new file mode 100644 index 000000000..3619fe7af --- /dev/null +++ b/lib/Core/dialogs/dialog-state.d.ts @@ -0,0 +1,31 @@ +import { URI } from "../../URI"; +/** + * A dialog contains certain pieces of state needed for further message + * transmissions within the dialog. This state consists of the dialog + * ID, a local sequence number (used to order requests from the UA to + * its peer), a remote sequence number (used to order requests from its + * peer to the UA), a local URI, a remote URI, remote target, a boolean + * flag called "secure", and a route set, which is an ordered list of + * URIs. The route set is the list of servers that need to be traversed + * to send a request to the peer. A dialog can also be in the "early" + * state, which occurs when it is created with a provisional response, + * and then transition to the "confirmed" state when a 2xx final + * response arrives. For other responses, or if no response arrives at + * all on that dialog, the early dialog terminates. + * + * https://tools.ietf.org/html/rfc3261#section-12 + */ +export interface DialogState { + id: string; + early: boolean; + callId: string; + localTag: string; + remoteTag: string; + localSequenceNumber: number | undefined; + remoteSequenceNumber: number | undefined; + localURI: URI; + remoteURI: URI; + remoteTarget: URI; + routeSet: Array; + secure: boolean; +} diff --git a/lib/Core/dialogs/dialog-state.js b/lib/Core/dialogs/dialog-state.js new file mode 100644 index 000000000..c8ad2e549 --- /dev/null +++ b/lib/Core/dialogs/dialog-state.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/Core/dialogs/dialog.d.ts b/lib/Core/dialogs/dialog.d.ts new file mode 100644 index 000000000..4d5d4a209 --- /dev/null +++ b/lib/Core/dialogs/dialog.d.ts @@ -0,0 +1,153 @@ +import { IncomingRequest as IncomingRequestMessage, IncomingResponse as IncomingResponseMessage, OutgoingRequest as OutgoingRequestMessage } from "../../SIPMessage"; +import { URI } from "../../URI"; +import { Body } from "../messages"; +import { UserAgentCore } from "../user-agent-core"; +import { DialogState } from "./dialog-state"; +/** + * A key concept for a user agent is that of a dialog. A dialog + * represents a peer-to-peer SIP relationship between two user agents + * that persists for some time. The dialog facilitates sequencing of + * messages between the user agents and proper routing of requests + * between both of them. The dialog represents a context in which to + * interpret SIP messages. + * https://tools.ietf.org/html/rfc3261#section-12 + */ +export declare class Dialog { + protected core: UserAgentCore; + protected dialogState: DialogState; + /** + * When a UAC receives a response that establishes a dialog, it + * constructs the state of the dialog. This state MUST be maintained + * for the duration of the dialog. + * https://tools.ietf.org/html/rfc3261#section-12.1.2 + * @param outgoingRequestMessage Outgoing request message for dialog. + * @param incomingResponseMessage Incoming response message creating dialog. + */ + static initialDialogStateForUserAgentClient(outgoingRequestMessage: OutgoingRequestMessage, incomingResponseMessage: IncomingResponseMessage): DialogState; + /** + * The UAS then constructs the state of the dialog. This state MUST be + * maintained for the duration of the dialog. + * https://tools.ietf.org/html/rfc3261#section-12.1.1 + * @param incomingRequestMessage Incoming request message creating dialog. + * @param toTag Tag in the To field in the response to the incoming request. + */ + static initialDialogStateForUserAgentServer(incomingRequestMessage: IncomingRequestMessage, toTag: string, early?: boolean): DialogState; + /** + * Dialog constructor. + * @param core User agent core. + * @param dialogState Initial dialog state. + */ + protected constructor(core: UserAgentCore, dialogState: DialogState); + /** Destructor. */ + dispose(): void; + /** + * A dialog is identified at each UA with a dialog ID, which consists of + * a Call-ID value, a local tag and a remote tag. The dialog ID at each + * UA involved in the dialog is not the same. Specifically, the local + * tag at one UA is identical to the remote tag at the peer UA. The + * tags are opaque tokens that facilitate the generation of unique + * dialog IDs. + * https://tools.ietf.org/html/rfc3261#section-12 + */ + readonly id: string; + /** + * A dialog can also be in the "early" state, which occurs when it is + * created with a provisional response, and then it transition to the + * "confirmed" state when a 2xx final response received or is sent. + * + * Note: RFC 3261 is concise on when a dialog is "confirmed", but it + * can be a point of confusion if an INVITE dialog is "confirmed" after + * a 2xx is sent or after receiving the ACK for the 2xx response. + * With careful reading it can be inferred a dialog is always is + * "confirmed" when the 2xx is sent (regardless of type of dialog). + * However a INVITE dialog does have additional considerations + * when it is confirmed but an ACK has not yet been received (in + * particular with regard to a callee sending BYE requests). + */ + readonly early: boolean; + /** Call identifier component of the dialog id. */ + readonly callId: string; + /** Local tag component of the dialog id. */ + readonly localTag: string; + /** Remote tag component of the dialog id. */ + readonly remoteTag: string; + /** Local sequence number (used to order requests from the UA to its peer). */ + readonly localSequenceNumber: number | undefined; + /** Remote sequence number (used to order requests from its peer to the UA). */ + readonly remoteSequenceNumber: number | undefined; + /** Local URI. */ + readonly localURI: URI; + /** Remote URI. */ + readonly remoteURI: URI; + /** Remote target. */ + readonly remoteTarget: URI; + /** + * Route set, which is an ordered list of URIs. The route set is the + * list of servers that need to be traversed to send a request to the peer. + */ + readonly routeSet: Array; + /** + * If the request was sent over TLS, and the Request-URI contained + * a SIPS URI, the "secure" flag is set to true. *NOT IMPLEMENTED* + */ + readonly secure: boolean; + /** The user agent core servicing this dialog. */ + readonly userAgentCore: UserAgentCore; + /** Confirm the dialog. Only matters if dialog is currently early. */ + confirm(): void; + /** + * Requests sent within a dialog, as any other requests, are atomic. If + * a particular request is accepted by the UAS, all the state changes + * associated with it are performed. If the request is rejected, none + * of the state changes are performed. + * + * Note that some requests, such as INVITEs, affect several pieces of + * state. + * + * https://tools.ietf.org/html/rfc3261#section-12.2.2 + * @param message Incoming request message within this dialog. + */ + receiveRequest(message: IncomingRequestMessage): void; + /** + * If the dialog identifier in the 2xx response matches the dialog + * identifier of an existing dialog, the dialog MUST be transitioned to + * the "confirmed" state, and the route set for the dialog MUST be + * recomputed based on the 2xx response using the procedures of Section + * 12.2.1.2. Otherwise, a new dialog in the "confirmed" state MUST be + * constructed using the procedures of Section 12.1.2. + * + * Note that the only piece of state that is recomputed is the route + * set. Other pieces of state such as the highest sequence numbers + * (remote and local) sent within the dialog are not recomputed. The + * route set only is recomputed for backwards compatibility. RFC + * 2543 did not mandate mirroring of the Record-Route header field in + * a 1xx, only 2xx. However, we cannot update the entire state of + * the dialog, since mid-dialog requests may have been sent within + * the early dialog, modifying the sequence numbers, for example. + * + * https://tools.ietf.org/html/rfc3261#section-13.2.2.4 + */ + recomputeRouteSet(message: IncomingResponseMessage): void; + /** + * A request within a dialog is constructed by using many of the + * components of the state stored as part of the dialog. + * https://tools.ietf.org/html/rfc3261#section-12.2.1.1 + * @param method Outgoing request method. + */ + createOutgoingRequestMessage(method: string, options?: { + cseq?: number; + extraHeaders?: Array; + body?: Body; + }): OutgoingRequestMessage; + /** + * If the remote sequence number was not empty, but the sequence number + * of the request is lower than the remote sequence number, the request + * is out of order and MUST be rejected with a 500 (Server Internal + * Error) response. + * https://tools.ietf.org/html/rfc3261#section-12.2.2 + * @param request Incoming request to guard. + * @returns True if the program execution is to continue in the branch in question. + * Otherwise a 500 Server Internal Error was stateless sent and request processing must stop. + */ + protected sequenceGuard(message: IncomingRequestMessage): boolean; +} diff --git a/lib/Core/dialogs/dialog.js b/lib/Core/dialogs/dialog.js new file mode 100644 index 000000000..056221a88 --- /dev/null +++ b/lib/Core/dialogs/dialog.js @@ -0,0 +1,564 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var Constants_1 = require("../../Constants"); +var NameAddrHeader_1 = require("../../NameAddrHeader"); +/** + * A key concept for a user agent is that of a dialog. A dialog + * represents a peer-to-peer SIP relationship between two user agents + * that persists for some time. The dialog facilitates sequencing of + * messages between the user agents and proper routing of requests + * between both of them. The dialog represents a context in which to + * interpret SIP messages. + * https://tools.ietf.org/html/rfc3261#section-12 + */ +var Dialog = /** @class */ (function () { + /** + * Dialog constructor. + * @param core User agent core. + * @param dialogState Initial dialog state. + */ + function Dialog(core, dialogState) { + this.core = core; + this.dialogState = dialogState; + this.core.dialogs.set(this.id, this); + } + /** + * When a UAC receives a response that establishes a dialog, it + * constructs the state of the dialog. This state MUST be maintained + * for the duration of the dialog. + * https://tools.ietf.org/html/rfc3261#section-12.1.2 + * @param outgoingRequestMessage Outgoing request message for dialog. + * @param incomingResponseMessage Incoming response message creating dialog. + */ + Dialog.initialDialogStateForUserAgentClient = function (outgoingRequestMessage, incomingResponseMessage) { + // If the request was sent over TLS, and the Request-URI contained a + // SIPS URI, the "secure" flag is set to TRUE. + // https://tools.ietf.org/html/rfc3261#section-12.1.2 + var secure = false; // FIXME: Currently no support for TLS. + // The route set MUST be set to the list of URIs in the Record-Route + // header field from the response, taken in reverse order and preserving + // all URI parameters. If no Record-Route header field is present in + // the response, the route set MUST be set to the empty set. This route + // set, even if empty, overrides any pre-existing route set for future + // requests in this dialog. The remote target MUST be set to the URI + // from the Contact header field of the response. + // https://tools.ietf.org/html/rfc3261#section-12.1.2 + var routeSet = incomingResponseMessage.getHeaders("record-route").reverse(); + var contact = incomingResponseMessage.parseHeader("contact"); + if (!contact) { // TODO: Review to make sure this will never happen + throw new Error("Contact undefined."); + } + if (!(contact instanceof NameAddrHeader_1.NameAddrHeader)) { + throw new Error("Contact not instance of NameAddrHeader."); + } + var remoteTarget = contact.uri; + // The local sequence number MUST be set to the value of the sequence + // number in the CSeq header field of the request. The remote sequence + // number MUST be empty (it is established when the remote UA sends a + // request within the dialog). The call identifier component of the + // dialog ID MUST be set to the value of the Call-ID in the request. + // The local tag component of the dialog ID MUST be set to the tag in + // the From field in the request, and the remote tag component of the + // dialog ID MUST be set to the tag in the To field of the response. A + // UAC MUST be prepared to receive a response without a tag in the To + // field, in which case the tag is considered to have a value of null. + // + // This is to maintain backwards compatibility with RFC 2543, which + // did not mandate To tags. + // + // https://tools.ietf.org/html/rfc3261#section-12.1.2 + var localSequenceNumber = outgoingRequestMessage.cseq; + var remoteSequenceNumber = undefined; + var callId = outgoingRequestMessage.callId; + var localTag = outgoingRequestMessage.fromTag; + var remoteTag = incomingResponseMessage.toTag; + if (!callId) { // TODO: Review to make sure this will never happen + throw new Error("Call id undefined."); + } + if (!localTag) { // TODO: Review to make sure this will never happen + throw new Error("From tag undefined."); + } + if (!remoteTag) { // TODO: Review to make sure this will never happen + throw new Error("To tag undefined."); // FIXME: No backwards compatibility with RFC 2543 + } + // The remote URI MUST be set to the URI in the To field, and the local + // URI MUST be set to the URI in the From field. + // https://tools.ietf.org/html/rfc3261#section-12.1.2 + if (!outgoingRequestMessage.from) { // TODO: Review to make sure this will never happen + throw new Error("From undefined."); + } + if (!outgoingRequestMessage.to) { // TODO: Review to make sure this will never happen + throw new Error("To undefined."); + } + var localURI = outgoingRequestMessage.from.uri; + var remoteURI = outgoingRequestMessage.to.uri; + // A dialog can also be in the "early" state, which occurs when it is + // created with a provisional response, and then transition to the + // "confirmed" state when a 2xx final response arrives. + // https://tools.ietf.org/html/rfc3261#section-12 + if (!incomingResponseMessage.statusCode) { + throw new Error("Incoming response status code undefined."); + } + var early = incomingResponseMessage.statusCode < 200 ? true : false; + var dialogState = { + id: callId + localTag + remoteTag, + early: early, + callId: callId, + localTag: localTag, + remoteTag: remoteTag, + localSequenceNumber: localSequenceNumber, + remoteSequenceNumber: remoteSequenceNumber, + localURI: localURI, + remoteURI: remoteURI, + remoteTarget: remoteTarget, + routeSet: routeSet, + secure: secure + }; + return dialogState; + }; + /** + * The UAS then constructs the state of the dialog. This state MUST be + * maintained for the duration of the dialog. + * https://tools.ietf.org/html/rfc3261#section-12.1.1 + * @param incomingRequestMessage Incoming request message creating dialog. + * @param toTag Tag in the To field in the response to the incoming request. + */ + Dialog.initialDialogStateForUserAgentServer = function (incomingRequestMessage, toTag, early) { + if (early === void 0) { early = false; } + // If the request arrived over TLS, and the Request-URI contained a SIPS + // URI, the "secure" flag is set to TRUE. + // https://tools.ietf.org/html/rfc3261#section-12.1.1 + var secure = false; // FIXME: Currently no support for TLS. + // The route set MUST be set to the list of URIs in the Record-Route + // header field from the request, taken in order and preserving all URI + // parameters. If no Record-Route header field is present in the + // request, the route set MUST be set to the empty set. This route set, + // even if empty, overrides any pre-existing route set for future + // requests in this dialog. The remote target MUST be set to the URI + // from the Contact header field of the request. + // https://tools.ietf.org/html/rfc3261#section-12.1.1 + var routeSet = incomingRequestMessage.getHeaders("record-route"); + var contact = incomingRequestMessage.parseHeader("contact"); + if (!contact) { // TODO: Review to make sure this will never happen + throw new Error("Contact undefined."); + } + if (!(contact instanceof NameAddrHeader_1.NameAddrHeader)) { + throw new Error("Contact not instance of NameAddrHeader."); + } + var remoteTarget = contact.uri; + // The remote sequence number MUST be set to the value of the sequence + // number in the CSeq header field of the request. The local sequence + // number MUST be empty. The call identifier component of the dialog ID + // MUST be set to the value of the Call-ID in the request. The local + // tag component of the dialog ID MUST be set to the tag in the To field + // in the response to the request (which always includes a tag), and the + // remote tag component of the dialog ID MUST be set to the tag from the + // From field in the request. A UAS MUST be prepared to receive a + // request without a tag in the From field, in which case the tag is + // considered to have a value of null. + // + // This is to maintain backwards compatibility with RFC 2543, which + // did not mandate From tags. + // + // https://tools.ietf.org/html/rfc3261#section-12.1.1 + var remoteSequenceNumber = incomingRequestMessage.cseq; + var localSequenceNumber = undefined; + var callId = incomingRequestMessage.callId; + var localTag = toTag; + var remoteTag = incomingRequestMessage.fromTag; + // The remote URI MUST be set to the URI in the From field, and the + // local URI MUST be set to the URI in the To field. + // https://tools.ietf.org/html/rfc3261#section-12.1.1 + var remoteURI = incomingRequestMessage.from.uri; + var localURI = incomingRequestMessage.to.uri; + var dialogState = { + id: callId + localTag + remoteTag, + early: early, + callId: callId, + localTag: localTag, + remoteTag: remoteTag, + localSequenceNumber: localSequenceNumber, + remoteSequenceNumber: remoteSequenceNumber, + localURI: localURI, + remoteURI: remoteURI, + remoteTarget: remoteTarget, + routeSet: routeSet, + secure: secure + }; + return dialogState; + }; + /** Destructor. */ + Dialog.prototype.dispose = function () { + this.core.dialogs.delete(this.id); + }; + Object.defineProperty(Dialog.prototype, "id", { + /** + * A dialog is identified at each UA with a dialog ID, which consists of + * a Call-ID value, a local tag and a remote tag. The dialog ID at each + * UA involved in the dialog is not the same. Specifically, the local + * tag at one UA is identical to the remote tag at the peer UA. The + * tags are opaque tokens that facilitate the generation of unique + * dialog IDs. + * https://tools.ietf.org/html/rfc3261#section-12 + */ + get: function () { + return this.dialogState.id; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Dialog.prototype, "early", { + /** + * A dialog can also be in the "early" state, which occurs when it is + * created with a provisional response, and then it transition to the + * "confirmed" state when a 2xx final response received or is sent. + * + * Note: RFC 3261 is concise on when a dialog is "confirmed", but it + * can be a point of confusion if an INVITE dialog is "confirmed" after + * a 2xx is sent or after receiving the ACK for the 2xx response. + * With careful reading it can be inferred a dialog is always is + * "confirmed" when the 2xx is sent (regardless of type of dialog). + * However a INVITE dialog does have additional considerations + * when it is confirmed but an ACK has not yet been received (in + * particular with regard to a callee sending BYE requests). + */ + get: function () { + return this.dialogState.early; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Dialog.prototype, "callId", { + /** Call identifier component of the dialog id. */ + get: function () { + return this.dialogState.callId; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Dialog.prototype, "localTag", { + /** Local tag component of the dialog id. */ + get: function () { + return this.dialogState.localTag; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Dialog.prototype, "remoteTag", { + /** Remote tag component of the dialog id. */ + get: function () { + return this.dialogState.remoteTag; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Dialog.prototype, "localSequenceNumber", { + /** Local sequence number (used to order requests from the UA to its peer). */ + get: function () { + return this.dialogState.localSequenceNumber; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Dialog.prototype, "remoteSequenceNumber", { + /** Remote sequence number (used to order requests from its peer to the UA). */ + get: function () { + return this.dialogState.remoteSequenceNumber; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Dialog.prototype, "localURI", { + /** Local URI. */ + get: function () { + return this.dialogState.localURI; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Dialog.prototype, "remoteURI", { + /** Remote URI. */ + get: function () { + return this.dialogState.remoteURI; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Dialog.prototype, "remoteTarget", { + /** Remote target. */ + get: function () { + return this.dialogState.remoteTarget; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Dialog.prototype, "routeSet", { + /** + * Route set, which is an ordered list of URIs. The route set is the + * list of servers that need to be traversed to send a request to the peer. + */ + get: function () { + return this.dialogState.routeSet; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Dialog.prototype, "secure", { + /** + * If the request was sent over TLS, and the Request-URI contained + * a SIPS URI, the "secure" flag is set to true. *NOT IMPLEMENTED* + */ + get: function () { + return this.dialogState.secure; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Dialog.prototype, "userAgentCore", { + /** The user agent core servicing this dialog. */ + get: function () { + return this.core; + }, + enumerable: true, + configurable: true + }); + /** Confirm the dialog. Only matters if dialog is currently early. */ + Dialog.prototype.confirm = function () { + this.dialogState.early = false; + }; + /** + * Requests sent within a dialog, as any other requests, are atomic. If + * a particular request is accepted by the UAS, all the state changes + * associated with it are performed. If the request is rejected, none + * of the state changes are performed. + * + * Note that some requests, such as INVITEs, affect several pieces of + * state. + * + * https://tools.ietf.org/html/rfc3261#section-12.2.2 + * @param message Incoming request message within this dialog. + */ + Dialog.prototype.receiveRequest = function (message) { + // ACK guard. + // By convention, the handling of ACKs is the responsibility + // the particular dialog implementation. For example, see SessionDialog. + // Furthermore, ACKs have same sequence number as the associated INVITE. + if (message.method === Constants_1.C.ACK) { + return; + } + // If the remote sequence number was not empty, but the sequence number + // of the request is lower than the remote sequence number, the request + // is out of order and MUST be rejected with a 500 (Server Internal + // Error) response. If the remote sequence number was not empty, and + // the sequence number of the request is greater than the remote + // sequence number, the request is in order. It is possible for the + // CSeq sequence number to be higher than the remote sequence number by + // more than one. This is not an error condition, and a UAS SHOULD be + // prepared to receive and process requests with CSeq values more than + // one higher than the previous received request. The UAS MUST then set + // the remote sequence number to the value of the sequence number in the + // CSeq header field value in the request. + // + // If a proxy challenges a request generated by the UAC, the UAC has + // to resubmit the request with credentials. The resubmitted request + // will have a new CSeq number. The UAS will never see the first + // request, and thus, it will notice a gap in the CSeq number space. + // Such a gap does not represent any error condition. + // + // https://tools.ietf.org/html/rfc3261#section-12.2.2 + if (this.remoteSequenceNumber) { + if (message.cseq <= this.remoteSequenceNumber) { + throw new Error("Out of sequence in dialog request. Did you forget to call sequenceGuard()?"); + } + this.dialogState.remoteSequenceNumber = message.cseq; + } + // If the remote sequence number is empty, it MUST be set to the value + // of the sequence number in the CSeq header field value in the request. + // https://tools.ietf.org/html/rfc3261#section-12.2.2 + if (!this.remoteSequenceNumber) { + this.dialogState.remoteSequenceNumber = message.cseq; + } + // When a UAS receives a target refresh request, it MUST replace the + // dialog's remote target URI with the URI from the Contact header field + // in that request, if present. + // https://tools.ietf.org/html/rfc3261#section-12.2.2 + // Note: "target refresh request" processing delegated to sub-class. + }; + /** + * If the dialog identifier in the 2xx response matches the dialog + * identifier of an existing dialog, the dialog MUST be transitioned to + * the "confirmed" state, and the route set for the dialog MUST be + * recomputed based on the 2xx response using the procedures of Section + * 12.2.1.2. Otherwise, a new dialog in the "confirmed" state MUST be + * constructed using the procedures of Section 12.1.2. + * + * Note that the only piece of state that is recomputed is the route + * set. Other pieces of state such as the highest sequence numbers + * (remote and local) sent within the dialog are not recomputed. The + * route set only is recomputed for backwards compatibility. RFC + * 2543 did not mandate mirroring of the Record-Route header field in + * a 1xx, only 2xx. However, we cannot update the entire state of + * the dialog, since mid-dialog requests may have been sent within + * the early dialog, modifying the sequence numbers, for example. + * + * https://tools.ietf.org/html/rfc3261#section-13.2.2.4 + */ + Dialog.prototype.recomputeRouteSet = function (message) { + this.dialogState.routeSet = message.getHeaders("record-route").reverse(); + }; + /** + * A request within a dialog is constructed by using many of the + * components of the state stored as part of the dialog. + * https://tools.ietf.org/html/rfc3261#section-12.2.1.1 + * @param method Outgoing request method. + */ + Dialog.prototype.createOutgoingRequestMessage = function (method, options) { + // The URI in the To field of the request MUST be set to the remote URI + // from the dialog state. The tag in the To header field of the request + // MUST be set to the remote tag of the dialog ID. The From URI of the + // request MUST be set to the local URI from the dialog state. The tag + // in the From header field of the request MUST be set to the local tag + // of the dialog ID. If the value of the remote or local tags is null, + // the tag parameter MUST be omitted from the To or From header fields, + // respectively. + // + // Usage of the URI from the To and From fields in the original + // request within subsequent requests is done for backwards + // compatibility with RFC 2543, which used the URI for dialog + // identification. In this specification, only the tags are used for + // dialog identification. It is expected that mandatory reflection + // of the original To and From URI in mid-dialog requests will be + // deprecated in a subsequent revision of this specification. + // https://tools.ietf.org/html/rfc3261#section-12.2.1.1 + var toUri = this.remoteURI; + var toTag = this.remoteTag; + var fromUri = this.localURI; + var fromTag = this.localTag; + // The Call-ID of the request MUST be set to the Call-ID of the dialog. + // Requests within a dialog MUST contain strictly monotonically + // increasing and contiguous CSeq sequence numbers (increasing-by-one) + // in each direction (excepting ACK and CANCEL of course, whose numbers + // equal the requests being acknowledged or cancelled). Therefore, if + // the local sequence number is not empty, the value of the local + // sequence number MUST be incremented by one, and this value MUST be + // placed into the CSeq header field. If the local sequence number is + // empty, an initial value MUST be chosen using the guidelines of + // Section 8.1.1.5. The method field in the CSeq header field value + // MUST match the method of the request. + // https://tools.ietf.org/html/rfc3261#section-12.2.1.1 + var callId = this.callId; + var cseq; + if (options && options.cseq) { + cseq = options.cseq; + } + else if (!this.dialogState.localSequenceNumber) { + cseq = this.dialogState.localSequenceNumber = 1; // https://tools.ietf.org/html/rfc3261#section-8.1.1.5 + } + else { + cseq = this.dialogState.localSequenceNumber += 1; + } + // The UAC uses the remote target and route set to build the Request-URI + // and Route header field of the request. + // + // If the route set is empty, the UAC MUST place the remote target URI + // into the Request-URI. The UAC MUST NOT add a Route header field to + // the request. + // + // If the route set is not empty, and the first URI in the route set + // contains the lr parameter (see Section 19.1.1), the UAC MUST place + // the remote target URI into the Request-URI and MUST include a Route + // header field containing the route set values in order, including all + // parameters. + // + // If the route set is not empty, and its first URI does not contain the + // lr parameter, the UAC MUST place the first URI from the route set + // into the Request-URI, stripping any parameters that are not allowed + // in a Request-URI. The UAC MUST add a Route header field containing + // the remainder of the route set values in order, including all + // parameters. The UAC MUST then place the remote target URI into the + // Route header field as the last value. + // https://tools.ietf.org/html/rfc3261#section-12.2.1.1 + // The lr parameter, when present, indicates that the element + // responsible for this resource implements the routing mechanisms + // specified in this document. This parameter will be used in the + // URIs proxies place into Record-Route header field values, and + // may appear in the URIs in a pre-existing route set. + // + // This parameter is used to achieve backwards compatibility with + // systems implementing the strict-routing mechanisms of RFC 2543 + // and the rfc2543bis drafts up to bis-05. An element preparing + // to send a request based on a URI not containing this parameter + // can assume the receiving element implements strict-routing and + // reformat the message to preserve the information in the + // Request-URI. + // https://tools.ietf.org/html/rfc3261#section-19.1.1 + // NOTE: Not backwards compatible with RFC 2543 (no support for strict-routing). + var ruri = this.remoteTarget; + var routeSet = this.routeSet; + var extraHeaders = options && options.extraHeaders; + var body = options && options.body ? + { contentType: options.body.contentType, body: options.body.content } : + undefined; + // The relative order of header fields with different field names is not + // significant. However, it is RECOMMENDED that header fields which are + // needed for proxy processing (Via, Route, Record-Route, Proxy-Require, + // Max-Forwards, and Proxy-Authorization, for example) appear towards + // the top of the message to facilitate rapid parsing. + // https://tools.ietf.org/html/rfc3261#section-7.3.1 + var message = this.core.configuration.outgoingRequestMessageFactory(method, ruri, { + callId: callId, + cseq: cseq, + fromUri: fromUri, + fromTag: fromTag, + toUri: toUri, + toTag: toTag, + routeSet: routeSet + }, extraHeaders, body); + return message; + }; + /** + * If the remote sequence number was not empty, but the sequence number + * of the request is lower than the remote sequence number, the request + * is out of order and MUST be rejected with a 500 (Server Internal + * Error) response. + * https://tools.ietf.org/html/rfc3261#section-12.2.2 + * @param request Incoming request to guard. + * @returns True if the program execution is to continue in the branch in question. + * Otherwise a 500 Server Internal Error was stateless sent and request processing must stop. + */ + Dialog.prototype.sequenceGuard = function (message) { + // ACK guard. + // By convention, handling of unexpected ACKs is responsibility + // the particular dialog implementation. For example, see SessionDialog. + // Furthermore, we cannot reply to an "out of sequence" ACK. + if (message.method === Constants_1.C.ACK) { + return true; + } + // Note: We are rejecting on "less than or equal to" the remote + // sequence number (excepting ACK whose numbers equal the requests + // being acknowledged or cancelled), which is the correct thing to + // do in our case. The only time a request with the same sequence number + // will show up here if is a) it is a very late retransmission of a + // request we already handled or b) it is a different request with the + // same sequence number which would be violation of the standard. + // Request retransmissions are absorbed by the transaction layer, + // so any request with a duplicate sequence number getting here + // would have to be a retransmission after the transaction terminated + // or a broken request (with unique via branch value). + // Requests within a dialog MUST contain strictly monotonically + // increasing and contiguous CSeq sequence numbers (increasing-by-one) + // in each direction (excepting ACK and CANCEL of course, whose numbers + // equal the requests being acknowledged or cancelled). Therefore, if + // the local sequence number is not empty, the value of the local + // sequence number MUST be incremented by one, and this value MUST be + // placed into the CSeq header field. + // https://tools.ietf.org/html/rfc3261#section-12.2.1.1 + if (this.remoteSequenceNumber && message.cseq <= this.remoteSequenceNumber) { + this.core.replyStateless(message, { statusCode: 500 }); + return false; + } + return true; + }; + return Dialog; +}()); +exports.Dialog = Dialog; diff --git a/lib/Core/dialogs/index.d.ts b/lib/Core/dialogs/index.d.ts new file mode 100644 index 000000000..7cacf07f2 --- /dev/null +++ b/lib/Core/dialogs/index.d.ts @@ -0,0 +1,4 @@ +export * from "./dialog"; +export * from "./dialog-state"; +export * from "./session-dialog"; +export * from "./subscription-dialog"; diff --git a/lib/Core/dialogs/index.js b/lib/Core/dialogs/index.js new file mode 100644 index 000000000..8c8b3ba1e --- /dev/null +++ b/lib/Core/dialogs/index.js @@ -0,0 +1,8 @@ +"use strict"; +function __export(m) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; +} +Object.defineProperty(exports, "__esModule", { value: true }); +__export(require("./dialog")); +__export(require("./session-dialog")); +__export(require("./subscription-dialog")); diff --git a/lib/Core/dialogs/invite-dialog.d.ts b/lib/Core/dialogs/invite-dialog.d.ts new file mode 100644 index 000000000..b3a525117 --- /dev/null +++ b/lib/Core/dialogs/invite-dialog.d.ts @@ -0,0 +1,170 @@ +import { IncomingRequest as IncomingRequestMessage, IncomingResponse as IncomingResponseMessage, OutgoingRequest as OutgoingRequestMessage } from "../../SIPMessage"; +import { Body, OutgoingAckRequest, OutgoingByeRequest, OutgoingInfoRequest, OutgoingInviteRequest, OutgoingInviteRequestDelegate, OutgoingNotifyRequest, OutgoingPrackRequest, OutgoingReferRequest, OutgoingRequestDelegate, RequestOptions } from "../messages"; +import { Session, SessionDelegate, SessionState, SignalingState } from "../session"; +import { InviteClientTransaction, InviteServerTransaction } from "../transactions"; +import { UserAgentCore } from "../user-agent-core"; +import { ReInviteUserAgentClient } from "../user-agents/re-invite-user-agent-client"; +import { ReInviteUserAgentServer } from "../user-agents/re-invite-user-agent-server"; +import { Dialog } from "./dialog"; +import { DialogState } from "./dialog-state"; +export declare type OutgoingResponseBody = Body; +export declare class InviteDialog extends Dialog implements Session { + private initialTransaction; + delegate: SessionDelegate | undefined; + reinviteUserAgentClient: ReInviteUserAgentClient | undefined; + reinviteUserAgentServer: ReInviteUserAgentServer | undefined; + /** The state of the offer/answer exchange. */ + private _signalingState; + /** The current offer. Undefined unless signaling state HaveLocalOffer, HaveRemoteOffer, of Stable. */ + private _offer; + /** The current answer. Undefined unless signaling state Stable. */ + private _answer; + /** True if waiting for an ACK to the initial transaction 2xx (UAS only). */ + private ackWait; + /** Retransmission timer for 2xx response which confirmed the dialog. */ + private invite2xxTimer; + /** The rseq of the last reliable response. */ + private rseq; + private logger; + constructor(initialTransaction: InviteClientTransaction | InviteServerTransaction, core: UserAgentCore, state: DialogState, delegate?: SessionDelegate); + dispose(): void; + readonly sessionState: SessionState; + /** The state of the offer/answer exchange. */ + readonly signalingState: SignalingState; + /** The current offer. Undefined unless signaling state HaveLocalOffer, HaveRemoteOffer, of Stable. */ + readonly offer: Body | undefined; + /** The current answer. Undefined unless signaling state Stable. */ + readonly answer: Body | undefined; + /** Confirm the dialog. Only matters if dialog is currently early. */ + confirm(): void; + /** Re-confirm the dialog. Only matters if handling re-INVITE request. */ + reConfirm(): void; + /** + * The UAC core MUST generate an ACK request for each 2xx received from + * the transaction layer. The header fields of the ACK are constructed + * in the same way as for any request sent within a dialog (see Section + * 12) with the exception of the CSeq and the header fields related to + * authentication. The sequence number of the CSeq header field MUST be + * the same as the INVITE being acknowledged, but the CSeq method MUST + * be ACK. The ACK MUST contain the same credentials as the INVITE. If + * the 2xx contains an offer (based on the rules above), the ACK MUST + * carry an answer in its body. If the offer in the 2xx response is not + * acceptable, the UAC core MUST generate a valid answer in the ACK and + * then send a BYE immediately. + * https://tools.ietf.org/html/rfc3261#section-13.2.2.4 + * @param options ACK options bucket. + */ + ack(options?: RequestOptions): OutgoingAckRequest; + /** + * Terminating a Session + * + * This section describes the procedures for terminating a session + * established by SIP. The state of the session and the state of the + * dialog are very closely related. When a session is initiated with an + * INVITE, each 1xx or 2xx response from a distinct UAS creates a + * dialog, and if that response completes the offer/answer exchange, it + * also creates a session. As a result, each session is "associated" + * with a single dialog - the one which resulted in its creation. If an + * initial INVITE generates a non-2xx final response, that terminates + * all sessions (if any) and all dialogs (if any) that were created + * through responses to the request. By virtue of completing the + * transaction, a non-2xx final response also prevents further sessions + * from being created as a result of the INVITE. The BYE request is + * used to terminate a specific session or attempted session. In this + * case, the specific session is the one with the peer UA on the other + * side of the dialog. When a BYE is received on a dialog, any session + * associated with that dialog SHOULD terminate. A UA MUST NOT send a + * BYE outside of a dialog. The caller's UA MAY send a BYE for either + * confirmed or early dialogs, and the callee's UA MAY send a BYE on + * confirmed dialogs, but MUST NOT send a BYE on early dialogs. + * + * However, the callee's UA MUST NOT send a BYE on a confirmed dialog + * until it has received an ACK for its 2xx response or until the server + * transaction times out. If no SIP extensions have defined other + * application layer states associated with the dialog, the BYE also + * terminates the dialog. + * + * https://tools.ietf.org/html/rfc3261#section-15 + * FIXME: Make these proper Exceptions... + * @param options BYE options bucket. + * @throws {Error} If callee's UA attempts a BYE on an early dialog. + * @throws {Error} If callee's UA attempts a BYE on a confirmed dialog + * while it's waiting on the ACK for its 2xx response. + */ + bye(delegate?: OutgoingRequestDelegate, options?: RequestOptions): OutgoingByeRequest; + /** + * An INFO request can be associated with an Info Package (see + * Section 5), or associated with a legacy INFO usage (see Section 2). + * + * The construction of the INFO request is the same as any other + * non-target refresh request within an existing invite dialog usage as + * described in Section 12.2 of RFC 3261. + * https://tools.ietf.org/html/rfc6086#section-4.2.1 + * @param options Options bucket. + */ + info(delegate?: OutgoingRequestDelegate, options?: RequestOptions): OutgoingInfoRequest; + /** + * Modifying an Existing Session + * + * A successful INVITE request (see Section 13) establishes both a + * dialog between two user agents and a session using the offer-answer + * model. Section 12 explains how to modify an existing dialog using a + * target refresh request (for example, changing the remote target URI + * of the dialog). This section describes how to modify the actual + * session. This modification can involve changing addresses or ports, + * adding a media stream, deleting a media stream, and so on. This is + * accomplished by sending a new INVITE request within the same dialog + * that established the session. An INVITE request sent within an + * existing dialog is known as a re-INVITE. + * + * Note that a single re-INVITE can modify the dialog and the + * parameters of the session at the same time. + * + * Either the caller or callee can modify an existing session. + * https://tools.ietf.org/html/rfc3261#section-14 + * @param options Options bucket + */ + invite(delegate?: OutgoingInviteRequestDelegate, options?: RequestOptions): OutgoingInviteRequest; + /** + * The NOTIFY mechanism defined in [2] MUST be used to inform the agent + * sending the REFER of the status of the reference. + * https://tools.ietf.org/html/rfc3515#section-2.4.4 + * @param options Options bucket. + */ + notify(delegate?: OutgoingRequestDelegate, options?: RequestOptions): OutgoingNotifyRequest; + /** + * Assuming the response is to be transmitted reliably, the UAC MUST + * create a new request with method PRACK. This request is sent within + * the dialog associated with the provisional response (indeed, the + * provisional response may have created the dialog). PRACK requests + * MAY contain bodies, which are interpreted according to their type and + * disposition. + * https://tools.ietf.org/html/rfc3262#section-4 + * @param options Options bucket. + */ + prack(delegate?: OutgoingRequestDelegate, options?: RequestOptions): OutgoingPrackRequest; + /** + * REFER is a SIP request and is constructed as defined in [1]. A REFER + * request MUST contain exactly one Refer-To header field value. + * https://tools.ietf.org/html/rfc3515#section-2.4.1 + * @param options Options bucket. + */ + refer(delegate?: OutgoingRequestDelegate, options?: RequestOptions): OutgoingReferRequest; + /** + * Requests sent within a dialog, as any other requests, are atomic. If + * a particular request is accepted by the UAS, all the state changes + * associated with it are performed. If the request is rejected, none + * of the state changes are performed. + * https://tools.ietf.org/html/rfc3261#section-12.2.2 + * @param message Incoming request message within this dialog. + */ + receiveRequest(message: IncomingRequestMessage): void; + reliableSequenceGuard(message: IncomingResponseMessage): boolean; + /** + * Update the signaling state of the dialog. + * @param message The message to base the update off of. + */ + signalingStateTransition(message: IncomingRequestMessage | IncomingResponseMessage | OutgoingRequestMessage | OutgoingResponseBody): void; + private start2xxRetransmissionTimer; + private startReInvite2xxRetransmissionTimer; +} diff --git a/lib/Core/dialogs/invite-dialog.js b/lib/Core/dialogs/invite-dialog.js new file mode 100644 index 000000000..9a0d764fc --- /dev/null +++ b/lib/Core/dialogs/invite-dialog.js @@ -0,0 +1,812 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Constants_1 = require("../../Constants"); +var NameAddrHeader_1 = require("../../NameAddrHeader"); +var SIPMessage_1 = require("../../SIPMessage"); +var Timers_1 = require("../../Timers"); +var messages_1 = require("../messages"); +var session_1 = require("../session"); +var transactions_1 = require("../transactions"); +var bye_user_agent_client_1 = require("../user-agents/bye-user-agent-client"); +var bye_user_agent_server_1 = require("../user-agents/bye-user-agent-server"); +var info_user_agent_client_1 = require("../user-agents/info-user-agent-client"); +var info_user_agent_server_1 = require("../user-agents/info-user-agent-server"); +var notify_user_agent_client_1 = require("../user-agents/notify-user-agent-client"); +var notify_user_agent_server_1 = require("../user-agents/notify-user-agent-server"); +var prack_user_agent_client_1 = require("../user-agents/prack-user-agent-client"); +var prack_user_agent_server_1 = require("../user-agents/prack-user-agent-server"); +var re_invite_user_agent_client_1 = require("../user-agents/re-invite-user-agent-client"); +var re_invite_user_agent_server_1 = require("../user-agents/re-invite-user-agent-server"); +var refer_user_agent_client_1 = require("../user-agents/refer-user-agent-client"); +var refer_user_agent_server_1 = require("../user-agents/refer-user-agent-server"); +var dialog_1 = require("./dialog"); +var InviteDialog = /** @class */ (function (_super) { + __extends(InviteDialog, _super); + function InviteDialog(initialTransaction, core, state, delegate) { + var _this = _super.call(this, core, state) || this; + _this.initialTransaction = initialTransaction; + /** The state of the offer/answer exchange. */ + _this._signalingState = session_1.SignalingState.Initial; + /** True if waiting for an ACK to the initial transaction 2xx (UAS only). */ + _this.ackWait = false; + _this.delegate = delegate; + if (initialTransaction instanceof transactions_1.InviteServerTransaction) { + // If we're created by an invite server transaction, we're + // going to be waiting for an ACK if are to be confirmed. + _this.ackWait = true; + } + // If we're confirmed upon creation start the retransmitting whatever + // the 2xx final response was that confirmed us into existence. + if (!_this.early) { + _this.start2xxRetransmissionTimer(); + } + _this.signalingStateTransition(initialTransaction.request); + _this.logger = core.loggerFactory.getLogger("sip.invite-dialog"); + _this.logger.log("INVITE dialog " + _this.id + " constructed"); + return _this; + } + InviteDialog.prototype.dispose = function () { + _super.prototype.dispose.call(this); + this._signalingState = session_1.SignalingState.Closed; + this._offer = undefined; + this._answer = undefined; + if (this.invite2xxTimer) { + clearTimeout(this.invite2xxTimer); + this.invite2xxTimer = undefined; + } + // The UAS MUST still respond to any pending requests received for that + // dialog. It is RECOMMENDED that a 487 (Request Terminated) response + // be generated to those pending requests. + // https://tools.ietf.org/html/rfc3261#section-15.1.2 + // TODO: + // this.userAgentServers.forEach((uas) => uas.reply(487)); + this.logger.log("INVITE dialog " + this.id + " destroyed"); + }; + Object.defineProperty(InviteDialog.prototype, "sessionState", { + // FIXME: Need real state machine + get: function () { + if (this.early) { + return session_1.SessionState.Early; + } + else if (this.ackWait) { + return session_1.SessionState.AckWait; + } + else if (this._signalingState === session_1.SignalingState.Closed) { + return session_1.SessionState.Terminated; + } + else { + return session_1.SessionState.Confirmed; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(InviteDialog.prototype, "signalingState", { + /** The state of the offer/answer exchange. */ + get: function () { + return this._signalingState; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(InviteDialog.prototype, "offer", { + /** The current offer. Undefined unless signaling state HaveLocalOffer, HaveRemoteOffer, of Stable. */ + get: function () { + return this._offer; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(InviteDialog.prototype, "answer", { + /** The current answer. Undefined unless signaling state Stable. */ + get: function () { + return this._answer; + }, + enumerable: true, + configurable: true + }); + /** Confirm the dialog. Only matters if dialog is currently early. */ + InviteDialog.prototype.confirm = function () { + // When we're confirmed start the retransmitting whatever + // the 2xx final response that may have confirmed us. + if (this.early) { + this.start2xxRetransmissionTimer(); + } + _super.prototype.confirm.call(this); + }; + /** Re-confirm the dialog. Only matters if handling re-INVITE request. */ + InviteDialog.prototype.reConfirm = function () { + // When we're confirmed start the retransmitting whatever + // the 2xx final response that may have confirmed us. + if (this.reinviteUserAgentServer) { + this.startReInvite2xxRetransmissionTimer(); + } + }; + /** + * The UAC core MUST generate an ACK request for each 2xx received from + * the transaction layer. The header fields of the ACK are constructed + * in the same way as for any request sent within a dialog (see Section + * 12) with the exception of the CSeq and the header fields related to + * authentication. The sequence number of the CSeq header field MUST be + * the same as the INVITE being acknowledged, but the CSeq method MUST + * be ACK. The ACK MUST contain the same credentials as the INVITE. If + * the 2xx contains an offer (based on the rules above), the ACK MUST + * carry an answer in its body. If the offer in the 2xx response is not + * acceptable, the UAC core MUST generate a valid answer in the ACK and + * then send a BYE immediately. + * https://tools.ietf.org/html/rfc3261#section-13.2.2.4 + * @param options ACK options bucket. + */ + InviteDialog.prototype.ack = function (options) { + if (options === void 0) { options = {}; } + this.logger.log("INVITE dialog " + this.id + " sending ACK request"); + var transaction; + if (this.reinviteUserAgentClient) { + // We're sending ACK for a re-INVITE + if (!(this.reinviteUserAgentClient.transaction instanceof transactions_1.InviteClientTransaction)) { + throw new Error("Transaction not instance of InviteClientTransaction."); + } + transaction = this.reinviteUserAgentClient.transaction; + this.reinviteUserAgentClient = undefined; + } + else { + // We're sending ACK for the initial INVITE + if (!(this.initialTransaction instanceof transactions_1.InviteClientTransaction)) { + throw new Error("Initial transaction not instance of InviteClientTransaction."); + } + transaction = this.initialTransaction; + } + options.cseq = transaction.request.cseq; // ACK cseq is INVITE cseq + var message = this.createOutgoingRequestMessage(Constants_1.C.ACK, options); + transaction.ackResponse(message); // See InviteClientTransaction for details. + this.signalingStateTransition(message); + return { message: message }; + }; + /** + * Terminating a Session + * + * This section describes the procedures for terminating a session + * established by SIP. The state of the session and the state of the + * dialog are very closely related. When a session is initiated with an + * INVITE, each 1xx or 2xx response from a distinct UAS creates a + * dialog, and if that response completes the offer/answer exchange, it + * also creates a session. As a result, each session is "associated" + * with a single dialog - the one which resulted in its creation. If an + * initial INVITE generates a non-2xx final response, that terminates + * all sessions (if any) and all dialogs (if any) that were created + * through responses to the request. By virtue of completing the + * transaction, a non-2xx final response also prevents further sessions + * from being created as a result of the INVITE. The BYE request is + * used to terminate a specific session or attempted session. In this + * case, the specific session is the one with the peer UA on the other + * side of the dialog. When a BYE is received on a dialog, any session + * associated with that dialog SHOULD terminate. A UA MUST NOT send a + * BYE outside of a dialog. The caller's UA MAY send a BYE for either + * confirmed or early dialogs, and the callee's UA MAY send a BYE on + * confirmed dialogs, but MUST NOT send a BYE on early dialogs. + * + * However, the callee's UA MUST NOT send a BYE on a confirmed dialog + * until it has received an ACK for its 2xx response or until the server + * transaction times out. If no SIP extensions have defined other + * application layer states associated with the dialog, the BYE also + * terminates the dialog. + * + * https://tools.ietf.org/html/rfc3261#section-15 + * FIXME: Make these proper Exceptions... + * @param options BYE options bucket. + * @throws {Error} If callee's UA attempts a BYE on an early dialog. + * @throws {Error} If callee's UA attempts a BYE on a confirmed dialog + * while it's waiting on the ACK for its 2xx response. + */ + InviteDialog.prototype.bye = function (delegate, options) { + this.logger.log("INVITE dialog " + this.id + " sending BYE request"); + // The caller's UA MAY send a BYE for either + // confirmed or early dialogs, and the callee's UA MAY send a BYE on + // confirmed dialogs, but MUST NOT send a BYE on early dialogs. + // + // However, the callee's UA MUST NOT send a BYE on a confirmed dialog + // until it has received an ACK for its 2xx response or until the server + // transaction times out. + // https://tools.ietf.org/html/rfc3261#section-15 + if (this.initialTransaction instanceof transactions_1.InviteServerTransaction) { + if (this.early) { + // FIXME: TODO: This should throw a proper exception. + throw new Error("UAS MUST NOT send a BYE on early dialogs."); + } + if (this.ackWait && this.initialTransaction.state !== transactions_1.TransactionState.Terminated) { + // FIXME: TODO: This should throw a proper exception. + throw new Error("UAS MUST NOT send a BYE on a confirmed dialog " + + "until it has received an ACK for its 2xx response " + + "or until the server transaction times out."); + } + } + // A BYE request is constructed as would any other request within a + // dialog, as described in Section 12. + // + // Once the BYE is constructed, the UAC core creates a new non-INVITE + // client transaction, and passes it the BYE request. The UAC MUST + // consider the session terminated (and therefore stop sending or + // listening for media) as soon as the BYE request is passed to the + // client transaction. If the response for the BYE is a 481 + // (Call/Transaction Does Not Exist) or a 408 (Request Timeout) or no + // response at all is received for the BYE (that is, a timeout is + // returned by the client transaction), the UAC MUST consider the + // session and the dialog terminated. + // https://tools.ietf.org/html/rfc3261#section-15.1.1 + return new bye_user_agent_client_1.ByeUserAgentClient(this, delegate, options); + }; + /** + * An INFO request can be associated with an Info Package (see + * Section 5), or associated with a legacy INFO usage (see Section 2). + * + * The construction of the INFO request is the same as any other + * non-target refresh request within an existing invite dialog usage as + * described in Section 12.2 of RFC 3261. + * https://tools.ietf.org/html/rfc6086#section-4.2.1 + * @param options Options bucket. + */ + InviteDialog.prototype.info = function (delegate, options) { + this.logger.log("INVITE dialog " + this.id + " sending INFO request"); + if (this.early) { + // FIXME: TODO: This should throw a proper exception. + throw new Error("Dialog not confirmed."); + } + return new info_user_agent_client_1.InfoUserAgentClient(this, delegate, options); + }; + /** + * Modifying an Existing Session + * + * A successful INVITE request (see Section 13) establishes both a + * dialog between two user agents and a session using the offer-answer + * model. Section 12 explains how to modify an existing dialog using a + * target refresh request (for example, changing the remote target URI + * of the dialog). This section describes how to modify the actual + * session. This modification can involve changing addresses or ports, + * adding a media stream, deleting a media stream, and so on. This is + * accomplished by sending a new INVITE request within the same dialog + * that established the session. An INVITE request sent within an + * existing dialog is known as a re-INVITE. + * + * Note that a single re-INVITE can modify the dialog and the + * parameters of the session at the same time. + * + * Either the caller or callee can modify an existing session. + * https://tools.ietf.org/html/rfc3261#section-14 + * @param options Options bucket + */ + InviteDialog.prototype.invite = function (delegate, options) { + this.logger.log("INVITE dialog " + this.id + " sending INVITE request"); + if (this.early) { + // FIXME: TODO: This should throw a proper exception. + throw new Error("Dialog not confirmed."); + } + // Note that a UAC MUST NOT initiate a new INVITE transaction within a + // dialog while another INVITE transaction is in progress in either + // direction. + // + // 1. If there is an ongoing INVITE client transaction, the TU MUST + // wait until the transaction reaches the completed or terminated + // state before initiating the new INVITE. + // + // 2. If there is an ongoing INVITE server transaction, the TU MUST + // wait until the transaction reaches the confirmed or terminated + // state before initiating the new INVITE. + // + // However, a UA MAY initiate a regular transaction while an INVITE + // transaction is in progress. A UA MAY also initiate an INVITE + // transaction while a regular transaction is in progress. + // https://tools.ietf.org/html/rfc3261#section-14.1 + if (this.reinviteUserAgentClient) { + // FIXME: TODO: This should throw a proper exception. + throw new Error("There is an ongoing re-INVITE client transaction."); + } + if (this.reinviteUserAgentServer) { + // FIXME: TODO: This should throw a proper exception. + throw new Error("There is an ongoing re-INVITE server transaction."); + } + return new re_invite_user_agent_client_1.ReInviteUserAgentClient(this, delegate, options); + }; + /** + * The NOTIFY mechanism defined in [2] MUST be used to inform the agent + * sending the REFER of the status of the reference. + * https://tools.ietf.org/html/rfc3515#section-2.4.4 + * @param options Options bucket. + */ + InviteDialog.prototype.notify = function (delegate, options) { + this.logger.log("INVITE dialog " + this.id + " sending NOTIFY request"); + if (this.early) { + // FIXME: TODO: This should throw a proper exception. + throw new Error("Dialog not confirmed."); + } + return new notify_user_agent_client_1.NotifyUserAgentClient(this, delegate, options); + }; + /** + * Assuming the response is to be transmitted reliably, the UAC MUST + * create a new request with method PRACK. This request is sent within + * the dialog associated with the provisional response (indeed, the + * provisional response may have created the dialog). PRACK requests + * MAY contain bodies, which are interpreted according to their type and + * disposition. + * https://tools.ietf.org/html/rfc3262#section-4 + * @param options Options bucket. + */ + InviteDialog.prototype.prack = function (delegate, options) { + if (options === void 0) { options = {}; } + this.logger.log("INVITE dialog " + this.id + " sending PRACK request"); + return new prack_user_agent_client_1.PrackUserAgentClient(this, delegate, options); + }; + /** + * REFER is a SIP request and is constructed as defined in [1]. A REFER + * request MUST contain exactly one Refer-To header field value. + * https://tools.ietf.org/html/rfc3515#section-2.4.1 + * @param options Options bucket. + */ + InviteDialog.prototype.refer = function (delegate, options) { + if (options === void 0) { options = {}; } + this.logger.log("INVITE dialog " + this.id + " sending REFER request"); + if (this.early) { + // FIXME: TODO: This should throw a proper exception. + throw new Error("Dialog not confirmed."); + } + // FIXME: TODO: Validate Refer-To header field value. + return new refer_user_agent_client_1.ReferUserAgentClient(this, delegate, options); + }; + /** + * Requests sent within a dialog, as any other requests, are atomic. If + * a particular request is accepted by the UAS, all the state changes + * associated with it are performed. If the request is rejected, none + * of the state changes are performed. + * https://tools.ietf.org/html/rfc3261#section-12.2.2 + * @param message Incoming request message within this dialog. + */ + InviteDialog.prototype.receiveRequest = function (message) { + this.logger.log("INVITE dialog " + this.id + " received " + message.method + " request"); + // Response retransmissions cease when an ACK request for the + // response is received. This is independent of whatever transport + // protocols are used to send the response. + // https://tools.ietf.org/html/rfc6026#section-8.1 + if (message.method === Constants_1.C.ACK) { + // If ackWait is true, then this is the ACK to the initial INVITE, + // otherwise this is an ACK to an in dialog INVITE. In either case, + // guard to make sure the sequence number of the ACK matches the INVITE. + if (this.ackWait) { + if (this.initialTransaction instanceof transactions_1.InviteClientTransaction) { + this.logger.warn("INVITE dialog " + this.id + " received unexpected " + message.method + " request, dropping."); + return; + } + if (this.initialTransaction.request.cseq !== message.cseq) { + this.logger.warn("INVITE dialog " + this.id + " received unexpected " + message.method + " request, dropping."); + return; + } + this.ackWait = false; + } + else { + if (!this.reinviteUserAgentServer) { + this.logger.warn("INVITE dialog " + this.id + " received unexpected " + message.method + " request, dropping."); + return; + } + if (this.reinviteUserAgentServer.transaction.request.cseq !== message.cseq) { + this.logger.warn("INVITE dialog " + this.id + " received unexpected " + message.method + " request, dropping."); + return; + } + this.reinviteUserAgentServer = undefined; + } + this.signalingStateTransition(message); + if (this.delegate && this.delegate.onAck) { + this.delegate.onAck({ message: message }); + } + return; + } + // Request within a dialog out of sequence guard. + // https://tools.ietf.org/html/rfc3261#section-12.2.2 + if (!this.sequenceGuard(message)) { + this.logger.log("INVITE dialog " + this.id + " rejected out of order " + message.method + " request."); + return; + } + if (message.method === Constants_1.C.INVITE) { + // A UAS that receives a second INVITE before it sends the final + // response to a first INVITE with a lower CSeq sequence number on the + // same dialog MUST return a 500 (Server Internal Error) response to the + // second INVITE and MUST include a Retry-After header field with a + // randomly chosen value of between 0 and 10 seconds. + // https://tools.ietf.org/html/rfc3261#section-14.2 + if (this.reinviteUserAgentServer) { + // https://tools.ietf.org/html/rfc3261#section-20.33 + var retryAfter = Math.floor((Math.random() * 10)) + 1; + var extraHeaders = ["Retry-After: " + retryAfter]; + this.core.replyStateless(message, { statusCode: 500, extraHeaders: extraHeaders }); + return; + } + // A UAS that receives an INVITE on a dialog while an INVITE it had sent + // on that dialog is in progress MUST return a 491 (Request Pending) + // response to the received INVITE. + // https://tools.ietf.org/html/rfc3261#section-14.2 + if (this.reinviteUserAgentClient) { + this.core.replyStateless(message, { statusCode: 491 }); + return; + } + } + // Request within a dialog common processing. + // https://tools.ietf.org/html/rfc3261#section-12.2.2 + _super.prototype.receiveRequest.call(this, message); + // Requests within a dialog MAY contain Record-Route and Contact header + // fields. However, these requests do not cause the dialog's route set + // to be modified, although they may modify the remote target URI. + // Specifically, requests that are not target refresh requests do not + // modify the dialog's remote target URI, and requests that are target + // refresh requests do. For dialogs that have been established with an + // INVITE, the only target refresh request defined is re-INVITE (see + // Section 14). Other extensions may define different target refresh + // requests for dialogs established in other ways. + // + // Note that an ACK is NOT a target refresh request. + // + // Target refresh requests only update the dialog's remote target URI, + // and not the route set formed from the Record-Route. Updating the + // latter would introduce severe backwards compatibility problems with + // RFC 2543-compliant systems. + // https://tools.ietf.org/html/rfc3261#section-15 + if (message.method === Constants_1.C.INVITE) { + // FIXME: parser needs to be typed... + var contact = message.parseHeader("contact"); + if (!contact) { // TODO: Review to make sure this will never happen + throw new Error("Contact undefined."); + } + if (!(contact instanceof NameAddrHeader_1.NameAddrHeader)) { + throw new Error("Contact not instance of NameAddrHeader."); + } + this.dialogState.remoteTarget = contact.uri; + } + // Switch on method and then delegate. + switch (message.method) { + case Constants_1.C.BYE: + // A UAS core receiving a BYE request for an existing dialog MUST follow + // the procedures of Section 12.2.2 to process the request. Once done, + // the UAS SHOULD terminate the session (and therefore stop sending and + // listening for media). The only case where it can elect not to are + // multicast sessions, where participation is possible even if the other + // participant in the dialog has terminated its involvement in the + // session. Whether or not it ends its participation on the session, + // the UAS core MUST generate a 2xx response to the BYE, and MUST pass + // that to the server transaction for transmission. + // + // The UAS MUST still respond to any pending requests received for that + // dialog. It is RECOMMENDED that a 487 (Request Terminated) response + // be generated to those pending requests. + // https://tools.ietf.org/html/rfc3261#section-15.1.2 + { + var uas = new bye_user_agent_server_1.ByeUserAgentServer(this, message); + this.delegate && this.delegate.onBye ? + this.delegate.onBye(uas) : + uas.accept(); + this.dispose(); + } + break; + case Constants_1.C.INFO: + // If a UA receives an INFO request associated with an Info Package that + // the UA has not indicated willingness to receive, the UA MUST send a + // 469 (Bad Info Package) response (see Section 11.6), which contains a + // Recv-Info header field with Info Packages for which the UA is willing + // to receive INFO requests. + { + var uas = new info_user_agent_server_1.InfoUserAgentServer(this, message); + this.delegate && this.delegate.onInfo ? + this.delegate.onInfo(uas) : + uas.reject({ + statusCode: 469, + extraHeaders: ["Recv-Info :"] + }); + } + break; + case Constants_1.C.INVITE: + // If the new session description is not acceptable, the UAS can reject + // it by returning a 488 (Not Acceptable Here) response for the re- + // INVITE. This response SHOULD include a Warning header field. + // https://tools.ietf.org/html/rfc3261#section-14.2 + { + var uas = new re_invite_user_agent_server_1.ReInviteUserAgentServer(this, message); + this.delegate && this.delegate.onInvite ? + this.delegate.onInvite(uas) : + uas.reject({ statusCode: 488 }); // TODO: Warning header field. + } + break; + case Constants_1.C.NOTIFY: + // https://tools.ietf.org/html/rfc3515#section-2.4.4 + { + var uas = new notify_user_agent_server_1.NotifyUserAgentServer(this, message); + this.delegate && this.delegate.onNotify ? + this.delegate.onNotify(uas) : + uas.accept(); + } + break; + case Constants_1.C.PRACK: + // https://tools.ietf.org/html/rfc3262#section-4 + { + var uas = new prack_user_agent_server_1.PrackUserAgentServer(this, message); + this.delegate && this.delegate.onPrack ? + this.delegate.onPrack(uas) : + uas.accept(); + } + break; + case Constants_1.C.REFER: + // https://tools.ietf.org/html/rfc3515#section-2.4.2 + { + var uas = new refer_user_agent_server_1.ReferUserAgentServer(this, message); + this.delegate && this.delegate.onRefer ? + this.delegate.onRefer(uas) : + uas.reject(); + } + break; + default: + { + this.logger.log("INVITE dialog " + this.id + " received unimplemented " + message.method + " request"); + this.core.replyStateless(message, { statusCode: 501 }); + } + break; + } + }; + InviteDialog.prototype.reliableSequenceGuard = function (message) { + var statusCode = message.statusCode; + if (!statusCode) { + throw new Error("Status code undefined"); + } + if (statusCode > 100 && statusCode < 200) { + // If a provisional response is received for an initial request, and + // that response contains a Require header field containing the option + // tag 100rel, the response is to be sent reliably. If the response is + // a 100 (Trying) (as opposed to 101 to 199), this option tag MUST be + // ignored, and the procedures below MUST NOT be used. + // https://tools.ietf.org/html/rfc3262#section-4 + var requireHeader = message.getHeader("require"); + var rseqHeader = message.getHeader("rseq"); + var rseq = requireHeader && requireHeader.includes("100rel") && rseqHeader ? Number(rseqHeader) : undefined; + // Handling of subsequent reliable provisional responses for the same + // initial request follows the same rules as above, with the following + // difference: reliable provisional responses are guaranteed to be in + // order. As a result, if the UAC receives another reliable provisional + // response to the same request, and its RSeq value is not one higher + // than the value of the sequence number, that response MUST NOT be + // acknowledged with a PRACK, and MUST NOT be processed further by the + // UAC. An implementation MAY discard the response, or MAY cache the + // response in the hopes of receiving the missing responses. + // https://tools.ietf.org/html/rfc3262#section-4 + if (this.rseq && this.rseq + 1 !== rseq) { + return false; + } + // Once a reliable provisional response is received, retransmissions of + // that response MUST be discarded. A response is a retransmission when + // its dialog ID, CSeq, and RSeq match the original response. The UAC + // MUST maintain a sequence number that indicates the most recently + // received in-order reliable provisional response for the initial + // request. This sequence number MUST be maintained until a final + // response is received for the initial request. Its value MUST be + // initialized to the RSeq header field in the first reliable + // provisional response received for the initial request. + // https://tools.ietf.org/html/rfc3262#section-4 + if (!this.rseq) { + this.rseq = rseq; + } + } + return true; + }; + /** + * Update the signaling state of the dialog. + * @param message The message to base the update off of. + */ + InviteDialog.prototype.signalingStateTransition = function (message) { + var body = messages_1.getBody(message); + // No body, no session. No, woman, no cry. + if (!body || body.contentDisposition !== "session") { + return; + } + // We're in UAS role, receiving incoming request with session description + if (message instanceof SIPMessage_1.IncomingRequest) { + switch (this._signalingState) { + case session_1.SignalingState.Initial: + case session_1.SignalingState.Stable: + this._signalingState = session_1.SignalingState.HaveRemoteOffer; + this._offer = body; + this._answer = undefined; + break; + case session_1.SignalingState.HaveLocalOffer: + this._signalingState = session_1.SignalingState.Stable; + this._answer = body; + break; + case session_1.SignalingState.HaveRemoteOffer: + // You cannot make a new offer while one is in progress. + // https://tools.ietf.org/html/rfc3261#section-13.2.1 + // FIXME: What to do here? + break; + case session_1.SignalingState.Closed: + break; + default: + throw new Error("Unexpected signaling state."); + } + } + // We're in UAC role, receiving incoming response with session description + if (message instanceof SIPMessage_1.IncomingResponse) { + switch (this._signalingState) { + case session_1.SignalingState.Initial: + case session_1.SignalingState.Stable: + this._signalingState = session_1.SignalingState.HaveRemoteOffer; + this._offer = body; + this._answer = undefined; + break; + case session_1.SignalingState.HaveLocalOffer: + this._signalingState = session_1.SignalingState.Stable; + this._answer = body; + break; + case session_1.SignalingState.HaveRemoteOffer: + // You cannot make a new offer while one is in progress. + // https://tools.ietf.org/html/rfc3261#section-13.2.1 + // FIXME: What to do here? + break; + case session_1.SignalingState.Closed: + break; + default: + throw new Error("Unexpected signaling state."); + } + } + // We're in UAC role, sending outgoing request with session description + if (message instanceof SIPMessage_1.OutgoingRequest) { + switch (this._signalingState) { + case session_1.SignalingState.Initial: + case session_1.SignalingState.Stable: + this._signalingState = session_1.SignalingState.HaveLocalOffer; + this._offer = body; + this._answer = undefined; + break; + case session_1.SignalingState.HaveLocalOffer: + // You cannot make a new offer while one is in progress. + // https://tools.ietf.org/html/rfc3261#section-13.2.1 + // FIXME: What to do here? + break; + case session_1.SignalingState.HaveRemoteOffer: + this._signalingState = session_1.SignalingState.Stable; + this._answer = body; + break; + case session_1.SignalingState.Closed: + break; + default: + throw new Error("Unexpected signaling state."); + } + } + // We're in UAS role, sending outgoing response with session description + if (messages_1.isBody(message)) { + switch (this._signalingState) { + case session_1.SignalingState.Initial: + case session_1.SignalingState.Stable: + this._signalingState = session_1.SignalingState.HaveLocalOffer; + this._offer = body; + this._answer = undefined; + break; + case session_1.SignalingState.HaveLocalOffer: + // You cannot make a new offer while one is in progress. + // https://tools.ietf.org/html/rfc3261#section-13.2.1 + // FIXME: What to do here? + break; + case session_1.SignalingState.HaveRemoteOffer: + this._signalingState = session_1.SignalingState.Stable; + this._answer = body; + break; + case session_1.SignalingState.Closed: + break; + default: + throw new Error("Unexpected signaling state."); + } + } + }; + InviteDialog.prototype.start2xxRetransmissionTimer = function () { + var _this = this; + if (this.initialTransaction instanceof transactions_1.InviteServerTransaction) { + var transaction_1 = this.initialTransaction; + // Once the response has been constructed, it is passed to the INVITE + // server transaction. In order to ensure reliable end-to-end + // transport of the response, it is necessary to periodically pass + // the response directly to the transport until the ACK arrives. The + // 2xx response is passed to the transport with an interval that + // starts at T1 seconds and doubles for each retransmission until it + // reaches T2 seconds (T1 and T2 are defined in Section 17). + // Response retransmissions cease when an ACK request for the + // response is received. This is independent of whatever transport + // protocols are used to send the response. + // https://tools.ietf.org/html/rfc6026#section-8.1 + var timeout_1 = Timers_1.Timers.T1; + var retransmission_1 = function () { + if (!_this.ackWait) { + _this.invite2xxTimer = undefined; + return; + } + _this.logger.log("No ACK for 2xx response received, attempting retransmission"); + transaction_1.retransmitAcceptedResponse(); + timeout_1 = Math.min(timeout_1 * 2, Timers_1.Timers.T2); + _this.invite2xxTimer = setTimeout(retransmission_1, timeout_1); + }; + this.invite2xxTimer = setTimeout(retransmission_1, timeout_1); + // If the server retransmits the 2xx response for 64*T1 seconds without + // receiving an ACK, the dialog is confirmed, but the session SHOULD be + // terminated. This is accomplished with a BYE, as described in Section 15. + // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 + var stateChanged_1 = function () { + if (transaction_1.state === transactions_1.TransactionState.Terminated) { + transaction_1.removeListener("stateChanged", stateChanged_1); + if (_this.invite2xxTimer) { + clearTimeout(_this.invite2xxTimer); + _this.invite2xxTimer = undefined; + } + if (_this.ackWait) { + if (_this.delegate && _this.delegate.onAckTimeout) { + _this.delegate.onAckTimeout(); + } + else { + _this.bye(); + } + } + } + }; + transaction_1.addListener("stateChanged", stateChanged_1); + } + }; + // FIXME: Refactor + InviteDialog.prototype.startReInvite2xxRetransmissionTimer = function () { + var _this = this; + if (this.reinviteUserAgentServer && this.reinviteUserAgentServer.transaction instanceof transactions_1.InviteServerTransaction) { + var transaction_2 = this.reinviteUserAgentServer.transaction; + // Once the response has been constructed, it is passed to the INVITE + // server transaction. In order to ensure reliable end-to-end + // transport of the response, it is necessary to periodically pass + // the response directly to the transport until the ACK arrives. The + // 2xx response is passed to the transport with an interval that + // starts at T1 seconds and doubles for each retransmission until it + // reaches T2 seconds (T1 and T2 are defined in Section 17). + // Response retransmissions cease when an ACK request for the + // response is received. This is independent of whatever transport + // protocols are used to send the response. + // https://tools.ietf.org/html/rfc6026#section-8.1 + var timeout_2 = Timers_1.Timers.T1; + var retransmission_2 = function () { + if (!_this.reinviteUserAgentServer) { + _this.invite2xxTimer = undefined; + return; + } + _this.logger.log("No ACK for 2xx response received, attempting retransmission"); + transaction_2.retransmitAcceptedResponse(); + timeout_2 = Math.min(timeout_2 * 2, Timers_1.Timers.T2); + _this.invite2xxTimer = setTimeout(retransmission_2, timeout_2); + }; + this.invite2xxTimer = setTimeout(retransmission_2, timeout_2); + // If the server retransmits the 2xx response for 64*T1 seconds without + // receiving an ACK, the dialog is confirmed, but the session SHOULD be + // terminated. This is accomplished with a BYE, as described in Section 15. + // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 + var stateChanged_2 = function () { + if (transaction_2.state === transactions_1.TransactionState.Terminated) { + transaction_2.removeListener("stateChanged", stateChanged_2); + if (_this.invite2xxTimer) { + clearTimeout(_this.invite2xxTimer); + _this.invite2xxTimer = undefined; + } + if (_this.reinviteUserAgentServer) { + // FIXME: TODO: What to do here + } + } + }; + transaction_2.addListener("stateChanged", stateChanged_2); + } + }; + return InviteDialog; +}(dialog_1.Dialog)); +exports.InviteDialog = InviteDialog; diff --git a/lib/Core/dialogs/session-dialog.d.ts b/lib/Core/dialogs/session-dialog.d.ts new file mode 100644 index 000000000..1905d6f4a --- /dev/null +++ b/lib/Core/dialogs/session-dialog.d.ts @@ -0,0 +1,170 @@ +import { IncomingRequest as IncomingRequestMessage, IncomingResponse as IncomingResponseMessage, OutgoingRequest as OutgoingRequestMessage } from "../../SIPMessage"; +import { Body, OutgoingAckRequest, OutgoingByeRequest, OutgoingInfoRequest, OutgoingInviteRequest, OutgoingInviteRequestDelegate, OutgoingNotifyRequest, OutgoingPrackRequest, OutgoingReferRequest, OutgoingRequestDelegate, RequestOptions } from "../messages"; +import { Session, SessionDelegate, SessionState, SignalingState } from "../session"; +import { InviteClientTransaction, InviteServerTransaction } from "../transactions"; +import { UserAgentCore } from "../user-agent-core"; +import { ReInviteUserAgentClient } from "../user-agents/re-invite-user-agent-client"; +import { ReInviteUserAgentServer } from "../user-agents/re-invite-user-agent-server"; +import { Dialog } from "./dialog"; +import { DialogState } from "./dialog-state"; +export declare type OutgoingResponseBody = Body; +export declare class SessionDialog extends Dialog implements Session { + private initialTransaction; + delegate: SessionDelegate | undefined; + reinviteUserAgentClient: ReInviteUserAgentClient | undefined; + reinviteUserAgentServer: ReInviteUserAgentServer | undefined; + /** The state of the offer/answer exchange. */ + private _signalingState; + /** The current offer. Undefined unless signaling state HaveLocalOffer, HaveRemoteOffer, of Stable. */ + private _offer; + /** The current answer. Undefined unless signaling state Stable. */ + private _answer; + /** True if waiting for an ACK to the initial transaction 2xx (UAS only). */ + private ackWait; + /** Retransmission timer for 2xx response which confirmed the dialog. */ + private invite2xxTimer; + /** The rseq of the last reliable response. */ + private rseq; + private logger; + constructor(initialTransaction: InviteClientTransaction | InviteServerTransaction, core: UserAgentCore, state: DialogState, delegate?: SessionDelegate); + dispose(): void; + readonly sessionState: SessionState; + /** The state of the offer/answer exchange. */ + readonly signalingState: SignalingState; + /** The current offer. Undefined unless signaling state HaveLocalOffer, HaveRemoteOffer, of Stable. */ + readonly offer: Body | undefined; + /** The current answer. Undefined unless signaling state Stable. */ + readonly answer: Body | undefined; + /** Confirm the dialog. Only matters if dialog is currently early. */ + confirm(): void; + /** Re-confirm the dialog. Only matters if handling re-INVITE request. */ + reConfirm(): void; + /** + * The UAC core MUST generate an ACK request for each 2xx received from + * the transaction layer. The header fields of the ACK are constructed + * in the same way as for any request sent within a dialog (see Section + * 12) with the exception of the CSeq and the header fields related to + * authentication. The sequence number of the CSeq header field MUST be + * the same as the INVITE being acknowledged, but the CSeq method MUST + * be ACK. The ACK MUST contain the same credentials as the INVITE. If + * the 2xx contains an offer (based on the rules above), the ACK MUST + * carry an answer in its body. If the offer in the 2xx response is not + * acceptable, the UAC core MUST generate a valid answer in the ACK and + * then send a BYE immediately. + * https://tools.ietf.org/html/rfc3261#section-13.2.2.4 + * @param options ACK options bucket. + */ + ack(options?: RequestOptions): OutgoingAckRequest; + /** + * Terminating a Session + * + * This section describes the procedures for terminating a session + * established by SIP. The state of the session and the state of the + * dialog are very closely related. When a session is initiated with an + * INVITE, each 1xx or 2xx response from a distinct UAS creates a + * dialog, and if that response completes the offer/answer exchange, it + * also creates a session. As a result, each session is "associated" + * with a single dialog - the one which resulted in its creation. If an + * initial INVITE generates a non-2xx final response, that terminates + * all sessions (if any) and all dialogs (if any) that were created + * through responses to the request. By virtue of completing the + * transaction, a non-2xx final response also prevents further sessions + * from being created as a result of the INVITE. The BYE request is + * used to terminate a specific session or attempted session. In this + * case, the specific session is the one with the peer UA on the other + * side of the dialog. When a BYE is received on a dialog, any session + * associated with that dialog SHOULD terminate. A UA MUST NOT send a + * BYE outside of a dialog. The caller's UA MAY send a BYE for either + * confirmed or early dialogs, and the callee's UA MAY send a BYE on + * confirmed dialogs, but MUST NOT send a BYE on early dialogs. + * + * However, the callee's UA MUST NOT send a BYE on a confirmed dialog + * until it has received an ACK for its 2xx response or until the server + * transaction times out. If no SIP extensions have defined other + * application layer states associated with the dialog, the BYE also + * terminates the dialog. + * + * https://tools.ietf.org/html/rfc3261#section-15 + * FIXME: Make these proper Exceptions... + * @param options BYE options bucket. + * @throws {Error} If callee's UA attempts a BYE on an early dialog. + * @throws {Error} If callee's UA attempts a BYE on a confirmed dialog + * while it's waiting on the ACK for its 2xx response. + */ + bye(delegate?: OutgoingRequestDelegate, options?: RequestOptions): OutgoingByeRequest; + /** + * An INFO request can be associated with an Info Package (see + * Section 5), or associated with a legacy INFO usage (see Section 2). + * + * The construction of the INFO request is the same as any other + * non-target refresh request within an existing invite dialog usage as + * described in Section 12.2 of RFC 3261. + * https://tools.ietf.org/html/rfc6086#section-4.2.1 + * @param options Options bucket. + */ + info(delegate?: OutgoingRequestDelegate, options?: RequestOptions): OutgoingInfoRequest; + /** + * Modifying an Existing Session + * + * A successful INVITE request (see Section 13) establishes both a + * dialog between two user agents and a session using the offer-answer + * model. Section 12 explains how to modify an existing dialog using a + * target refresh request (for example, changing the remote target URI + * of the dialog). This section describes how to modify the actual + * session. This modification can involve changing addresses or ports, + * adding a media stream, deleting a media stream, and so on. This is + * accomplished by sending a new INVITE request within the same dialog + * that established the session. An INVITE request sent within an + * existing dialog is known as a re-INVITE. + * + * Note that a single re-INVITE can modify the dialog and the + * parameters of the session at the same time. + * + * Either the caller or callee can modify an existing session. + * https://tools.ietf.org/html/rfc3261#section-14 + * @param options Options bucket + */ + invite(delegate?: OutgoingInviteRequestDelegate, options?: RequestOptions): OutgoingInviteRequest; + /** + * The NOTIFY mechanism defined in [2] MUST be used to inform the agent + * sending the REFER of the status of the reference. + * https://tools.ietf.org/html/rfc3515#section-2.4.4 + * @param options Options bucket. + */ + notify(delegate?: OutgoingRequestDelegate, options?: RequestOptions): OutgoingNotifyRequest; + /** + * Assuming the response is to be transmitted reliably, the UAC MUST + * create a new request with method PRACK. This request is sent within + * the dialog associated with the provisional response (indeed, the + * provisional response may have created the dialog). PRACK requests + * MAY contain bodies, which are interpreted according to their type and + * disposition. + * https://tools.ietf.org/html/rfc3262#section-4 + * @param options Options bucket. + */ + prack(delegate?: OutgoingRequestDelegate, options?: RequestOptions): OutgoingPrackRequest; + /** + * REFER is a SIP request and is constructed as defined in [1]. A REFER + * request MUST contain exactly one Refer-To header field value. + * https://tools.ietf.org/html/rfc3515#section-2.4.1 + * @param options Options bucket. + */ + refer(delegate?: OutgoingRequestDelegate, options?: RequestOptions): OutgoingReferRequest; + /** + * Requests sent within a dialog, as any other requests, are atomic. If + * a particular request is accepted by the UAS, all the state changes + * associated with it are performed. If the request is rejected, none + * of the state changes are performed. + * https://tools.ietf.org/html/rfc3261#section-12.2.2 + * @param message Incoming request message within this dialog. + */ + receiveRequest(message: IncomingRequestMessage): void; + reliableSequenceGuard(message: IncomingResponseMessage): boolean; + /** + * Update the signaling state of the dialog. + * @param message The message to base the update off of. + */ + signalingStateTransition(message: IncomingRequestMessage | IncomingResponseMessage | OutgoingRequestMessage | OutgoingResponseBody): void; + private start2xxRetransmissionTimer; + private startReInvite2xxRetransmissionTimer; +} diff --git a/lib/Core/dialogs/session-dialog.js b/lib/Core/dialogs/session-dialog.js new file mode 100644 index 000000000..0f6616ee7 --- /dev/null +++ b/lib/Core/dialogs/session-dialog.js @@ -0,0 +1,812 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Constants_1 = require("../../Constants"); +var NameAddrHeader_1 = require("../../NameAddrHeader"); +var SIPMessage_1 = require("../../SIPMessage"); +var Timers_1 = require("../../Timers"); +var messages_1 = require("../messages"); +var session_1 = require("../session"); +var transactions_1 = require("../transactions"); +var bye_user_agent_client_1 = require("../user-agents/bye-user-agent-client"); +var bye_user_agent_server_1 = require("../user-agents/bye-user-agent-server"); +var info_user_agent_client_1 = require("../user-agents/info-user-agent-client"); +var info_user_agent_server_1 = require("../user-agents/info-user-agent-server"); +var notify_user_agent_client_1 = require("../user-agents/notify-user-agent-client"); +var notify_user_agent_server_1 = require("../user-agents/notify-user-agent-server"); +var prack_user_agent_client_1 = require("../user-agents/prack-user-agent-client"); +var prack_user_agent_server_1 = require("../user-agents/prack-user-agent-server"); +var re_invite_user_agent_client_1 = require("../user-agents/re-invite-user-agent-client"); +var re_invite_user_agent_server_1 = require("../user-agents/re-invite-user-agent-server"); +var refer_user_agent_client_1 = require("../user-agents/refer-user-agent-client"); +var refer_user_agent_server_1 = require("../user-agents/refer-user-agent-server"); +var dialog_1 = require("./dialog"); +var SessionDialog = /** @class */ (function (_super) { + __extends(SessionDialog, _super); + function SessionDialog(initialTransaction, core, state, delegate) { + var _this = _super.call(this, core, state) || this; + _this.initialTransaction = initialTransaction; + /** The state of the offer/answer exchange. */ + _this._signalingState = session_1.SignalingState.Initial; + /** True if waiting for an ACK to the initial transaction 2xx (UAS only). */ + _this.ackWait = false; + _this.delegate = delegate; + if (initialTransaction instanceof transactions_1.InviteServerTransaction) { + // If we're created by an invite server transaction, we're + // going to be waiting for an ACK if are to be confirmed. + _this.ackWait = true; + } + // If we're confirmed upon creation start the retransmitting whatever + // the 2xx final response was that confirmed us into existence. + if (!_this.early) { + _this.start2xxRetransmissionTimer(); + } + _this.signalingStateTransition(initialTransaction.request); + _this.logger = core.loggerFactory.getLogger("sip.invite-dialog"); + _this.logger.log("INVITE dialog " + _this.id + " constructed"); + return _this; + } + SessionDialog.prototype.dispose = function () { + _super.prototype.dispose.call(this); + this._signalingState = session_1.SignalingState.Closed; + this._offer = undefined; + this._answer = undefined; + if (this.invite2xxTimer) { + clearTimeout(this.invite2xxTimer); + this.invite2xxTimer = undefined; + } + // The UAS MUST still respond to any pending requests received for that + // dialog. It is RECOMMENDED that a 487 (Request Terminated) response + // be generated to those pending requests. + // https://tools.ietf.org/html/rfc3261#section-15.1.2 + // TODO: + // this.userAgentServers.forEach((uas) => uas.reply(487)); + this.logger.log("INVITE dialog " + this.id + " destroyed"); + }; + Object.defineProperty(SessionDialog.prototype, "sessionState", { + // FIXME: Need real state machine + get: function () { + if (this.early) { + return session_1.SessionState.Early; + } + else if (this.ackWait) { + return session_1.SessionState.AckWait; + } + else if (this._signalingState === session_1.SignalingState.Closed) { + return session_1.SessionState.Terminated; + } + else { + return session_1.SessionState.Confirmed; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SessionDialog.prototype, "signalingState", { + /** The state of the offer/answer exchange. */ + get: function () { + return this._signalingState; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SessionDialog.prototype, "offer", { + /** The current offer. Undefined unless signaling state HaveLocalOffer, HaveRemoteOffer, of Stable. */ + get: function () { + return this._offer; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SessionDialog.prototype, "answer", { + /** The current answer. Undefined unless signaling state Stable. */ + get: function () { + return this._answer; + }, + enumerable: true, + configurable: true + }); + /** Confirm the dialog. Only matters if dialog is currently early. */ + SessionDialog.prototype.confirm = function () { + // When we're confirmed start the retransmitting whatever + // the 2xx final response that may have confirmed us. + if (this.early) { + this.start2xxRetransmissionTimer(); + } + _super.prototype.confirm.call(this); + }; + /** Re-confirm the dialog. Only matters if handling re-INVITE request. */ + SessionDialog.prototype.reConfirm = function () { + // When we're confirmed start the retransmitting whatever + // the 2xx final response that may have confirmed us. + if (this.reinviteUserAgentServer) { + this.startReInvite2xxRetransmissionTimer(); + } + }; + /** + * The UAC core MUST generate an ACK request for each 2xx received from + * the transaction layer. The header fields of the ACK are constructed + * in the same way as for any request sent within a dialog (see Section + * 12) with the exception of the CSeq and the header fields related to + * authentication. The sequence number of the CSeq header field MUST be + * the same as the INVITE being acknowledged, but the CSeq method MUST + * be ACK. The ACK MUST contain the same credentials as the INVITE. If + * the 2xx contains an offer (based on the rules above), the ACK MUST + * carry an answer in its body. If the offer in the 2xx response is not + * acceptable, the UAC core MUST generate a valid answer in the ACK and + * then send a BYE immediately. + * https://tools.ietf.org/html/rfc3261#section-13.2.2.4 + * @param options ACK options bucket. + */ + SessionDialog.prototype.ack = function (options) { + if (options === void 0) { options = {}; } + this.logger.log("INVITE dialog " + this.id + " sending ACK request"); + var transaction; + if (this.reinviteUserAgentClient) { + // We're sending ACK for a re-INVITE + if (!(this.reinviteUserAgentClient.transaction instanceof transactions_1.InviteClientTransaction)) { + throw new Error("Transaction not instance of InviteClientTransaction."); + } + transaction = this.reinviteUserAgentClient.transaction; + this.reinviteUserAgentClient = undefined; + } + else { + // We're sending ACK for the initial INVITE + if (!(this.initialTransaction instanceof transactions_1.InviteClientTransaction)) { + throw new Error("Initial transaction not instance of InviteClientTransaction."); + } + transaction = this.initialTransaction; + } + options.cseq = transaction.request.cseq; // ACK cseq is INVITE cseq + var message = this.createOutgoingRequestMessage(Constants_1.C.ACK, options); + transaction.ackResponse(message); // See InviteClientTransaction for details. + this.signalingStateTransition(message); + return { message: message }; + }; + /** + * Terminating a Session + * + * This section describes the procedures for terminating a session + * established by SIP. The state of the session and the state of the + * dialog are very closely related. When a session is initiated with an + * INVITE, each 1xx or 2xx response from a distinct UAS creates a + * dialog, and if that response completes the offer/answer exchange, it + * also creates a session. As a result, each session is "associated" + * with a single dialog - the one which resulted in its creation. If an + * initial INVITE generates a non-2xx final response, that terminates + * all sessions (if any) and all dialogs (if any) that were created + * through responses to the request. By virtue of completing the + * transaction, a non-2xx final response also prevents further sessions + * from being created as a result of the INVITE. The BYE request is + * used to terminate a specific session or attempted session. In this + * case, the specific session is the one with the peer UA on the other + * side of the dialog. When a BYE is received on a dialog, any session + * associated with that dialog SHOULD terminate. A UA MUST NOT send a + * BYE outside of a dialog. The caller's UA MAY send a BYE for either + * confirmed or early dialogs, and the callee's UA MAY send a BYE on + * confirmed dialogs, but MUST NOT send a BYE on early dialogs. + * + * However, the callee's UA MUST NOT send a BYE on a confirmed dialog + * until it has received an ACK for its 2xx response or until the server + * transaction times out. If no SIP extensions have defined other + * application layer states associated with the dialog, the BYE also + * terminates the dialog. + * + * https://tools.ietf.org/html/rfc3261#section-15 + * FIXME: Make these proper Exceptions... + * @param options BYE options bucket. + * @throws {Error} If callee's UA attempts a BYE on an early dialog. + * @throws {Error} If callee's UA attempts a BYE on a confirmed dialog + * while it's waiting on the ACK for its 2xx response. + */ + SessionDialog.prototype.bye = function (delegate, options) { + this.logger.log("INVITE dialog " + this.id + " sending BYE request"); + // The caller's UA MAY send a BYE for either + // confirmed or early dialogs, and the callee's UA MAY send a BYE on + // confirmed dialogs, but MUST NOT send a BYE on early dialogs. + // + // However, the callee's UA MUST NOT send a BYE on a confirmed dialog + // until it has received an ACK for its 2xx response or until the server + // transaction times out. + // https://tools.ietf.org/html/rfc3261#section-15 + if (this.initialTransaction instanceof transactions_1.InviteServerTransaction) { + if (this.early) { + // FIXME: TODO: This should throw a proper exception. + throw new Error("UAS MUST NOT send a BYE on early dialogs."); + } + if (this.ackWait && this.initialTransaction.state !== transactions_1.TransactionState.Terminated) { + // FIXME: TODO: This should throw a proper exception. + throw new Error("UAS MUST NOT send a BYE on a confirmed dialog " + + "until it has received an ACK for its 2xx response " + + "or until the server transaction times out."); + } + } + // A BYE request is constructed as would any other request within a + // dialog, as described in Section 12. + // + // Once the BYE is constructed, the UAC core creates a new non-INVITE + // client transaction, and passes it the BYE request. The UAC MUST + // consider the session terminated (and therefore stop sending or + // listening for media) as soon as the BYE request is passed to the + // client transaction. If the response for the BYE is a 481 + // (Call/Transaction Does Not Exist) or a 408 (Request Timeout) or no + // response at all is received for the BYE (that is, a timeout is + // returned by the client transaction), the UAC MUST consider the + // session and the dialog terminated. + // https://tools.ietf.org/html/rfc3261#section-15.1.1 + return new bye_user_agent_client_1.ByeUserAgentClient(this, delegate, options); + }; + /** + * An INFO request can be associated with an Info Package (see + * Section 5), or associated with a legacy INFO usage (see Section 2). + * + * The construction of the INFO request is the same as any other + * non-target refresh request within an existing invite dialog usage as + * described in Section 12.2 of RFC 3261. + * https://tools.ietf.org/html/rfc6086#section-4.2.1 + * @param options Options bucket. + */ + SessionDialog.prototype.info = function (delegate, options) { + this.logger.log("INVITE dialog " + this.id + " sending INFO request"); + if (this.early) { + // FIXME: TODO: This should throw a proper exception. + throw new Error("Dialog not confirmed."); + } + return new info_user_agent_client_1.InfoUserAgentClient(this, delegate, options); + }; + /** + * Modifying an Existing Session + * + * A successful INVITE request (see Section 13) establishes both a + * dialog between two user agents and a session using the offer-answer + * model. Section 12 explains how to modify an existing dialog using a + * target refresh request (for example, changing the remote target URI + * of the dialog). This section describes how to modify the actual + * session. This modification can involve changing addresses or ports, + * adding a media stream, deleting a media stream, and so on. This is + * accomplished by sending a new INVITE request within the same dialog + * that established the session. An INVITE request sent within an + * existing dialog is known as a re-INVITE. + * + * Note that a single re-INVITE can modify the dialog and the + * parameters of the session at the same time. + * + * Either the caller or callee can modify an existing session. + * https://tools.ietf.org/html/rfc3261#section-14 + * @param options Options bucket + */ + SessionDialog.prototype.invite = function (delegate, options) { + this.logger.log("INVITE dialog " + this.id + " sending INVITE request"); + if (this.early) { + // FIXME: TODO: This should throw a proper exception. + throw new Error("Dialog not confirmed."); + } + // Note that a UAC MUST NOT initiate a new INVITE transaction within a + // dialog while another INVITE transaction is in progress in either + // direction. + // + // 1. If there is an ongoing INVITE client transaction, the TU MUST + // wait until the transaction reaches the completed or terminated + // state before initiating the new INVITE. + // + // 2. If there is an ongoing INVITE server transaction, the TU MUST + // wait until the transaction reaches the confirmed or terminated + // state before initiating the new INVITE. + // + // However, a UA MAY initiate a regular transaction while an INVITE + // transaction is in progress. A UA MAY also initiate an INVITE + // transaction while a regular transaction is in progress. + // https://tools.ietf.org/html/rfc3261#section-14.1 + if (this.reinviteUserAgentClient) { + // FIXME: TODO: This should throw a proper exception. + throw new Error("There is an ongoing re-INVITE client transaction."); + } + if (this.reinviteUserAgentServer) { + // FIXME: TODO: This should throw a proper exception. + throw new Error("There is an ongoing re-INVITE server transaction."); + } + return new re_invite_user_agent_client_1.ReInviteUserAgentClient(this, delegate, options); + }; + /** + * The NOTIFY mechanism defined in [2] MUST be used to inform the agent + * sending the REFER of the status of the reference. + * https://tools.ietf.org/html/rfc3515#section-2.4.4 + * @param options Options bucket. + */ + SessionDialog.prototype.notify = function (delegate, options) { + this.logger.log("INVITE dialog " + this.id + " sending NOTIFY request"); + if (this.early) { + // FIXME: TODO: This should throw a proper exception. + throw new Error("Dialog not confirmed."); + } + return new notify_user_agent_client_1.NotifyUserAgentClient(this, delegate, options); + }; + /** + * Assuming the response is to be transmitted reliably, the UAC MUST + * create a new request with method PRACK. This request is sent within + * the dialog associated with the provisional response (indeed, the + * provisional response may have created the dialog). PRACK requests + * MAY contain bodies, which are interpreted according to their type and + * disposition. + * https://tools.ietf.org/html/rfc3262#section-4 + * @param options Options bucket. + */ + SessionDialog.prototype.prack = function (delegate, options) { + this.logger.log("INVITE dialog " + this.id + " sending PRACK request"); + return new prack_user_agent_client_1.PrackUserAgentClient(this, delegate, options); + }; + /** + * REFER is a SIP request and is constructed as defined in [1]. A REFER + * request MUST contain exactly one Refer-To header field value. + * https://tools.ietf.org/html/rfc3515#section-2.4.1 + * @param options Options bucket. + */ + SessionDialog.prototype.refer = function (delegate, options) { + this.logger.log("INVITE dialog " + this.id + " sending REFER request"); + if (this.early) { + // FIXME: TODO: This should throw a proper exception. + throw new Error("Dialog not confirmed."); + } + // FIXME: TODO: Validate Refer-To header field value. + return new refer_user_agent_client_1.ReferUserAgentClient(this, delegate, options); + }; + /** + * Requests sent within a dialog, as any other requests, are atomic. If + * a particular request is accepted by the UAS, all the state changes + * associated with it are performed. If the request is rejected, none + * of the state changes are performed. + * https://tools.ietf.org/html/rfc3261#section-12.2.2 + * @param message Incoming request message within this dialog. + */ + SessionDialog.prototype.receiveRequest = function (message) { + this.logger.log("INVITE dialog " + this.id + " received " + message.method + " request"); + // Response retransmissions cease when an ACK request for the + // response is received. This is independent of whatever transport + // protocols are used to send the response. + // https://tools.ietf.org/html/rfc6026#section-8.1 + if (message.method === Constants_1.C.ACK) { + // If ackWait is true, then this is the ACK to the initial INVITE, + // otherwise this is an ACK to an in dialog INVITE. In either case, + // guard to make sure the sequence number of the ACK matches the INVITE. + if (this.ackWait) { + if (this.initialTransaction instanceof transactions_1.InviteClientTransaction) { + this.logger.warn("INVITE dialog " + this.id + " received unexpected " + message.method + " request, dropping."); + return; + } + if (this.initialTransaction.request.cseq !== message.cseq) { + this.logger.warn("INVITE dialog " + this.id + " received unexpected " + message.method + " request, dropping."); + return; + } + this.ackWait = false; + } + else { + if (!this.reinviteUserAgentServer) { + this.logger.warn("INVITE dialog " + this.id + " received unexpected " + message.method + " request, dropping."); + return; + } + if (this.reinviteUserAgentServer.transaction.request.cseq !== message.cseq) { + this.logger.warn("INVITE dialog " + this.id + " received unexpected " + message.method + " request, dropping."); + return; + } + this.reinviteUserAgentServer = undefined; + } + this.signalingStateTransition(message); + if (this.delegate && this.delegate.onAck) { + this.delegate.onAck({ message: message }); + } + return; + } + // Request within a dialog out of sequence guard. + // https://tools.ietf.org/html/rfc3261#section-12.2.2 + if (!this.sequenceGuard(message)) { + this.logger.log("INVITE dialog " + this.id + " rejected out of order " + message.method + " request."); + return; + } + if (message.method === Constants_1.C.INVITE) { + // A UAS that receives a second INVITE before it sends the final + // response to a first INVITE with a lower CSeq sequence number on the + // same dialog MUST return a 500 (Server Internal Error) response to the + // second INVITE and MUST include a Retry-After header field with a + // randomly chosen value of between 0 and 10 seconds. + // https://tools.ietf.org/html/rfc3261#section-14.2 + if (this.reinviteUserAgentServer) { + // https://tools.ietf.org/html/rfc3261#section-20.33 + var retryAfter = Math.floor((Math.random() * 10)) + 1; + var extraHeaders = ["Retry-After: " + retryAfter]; + this.core.replyStateless(message, { statusCode: 500, extraHeaders: extraHeaders }); + return; + } + // A UAS that receives an INVITE on a dialog while an INVITE it had sent + // on that dialog is in progress MUST return a 491 (Request Pending) + // response to the received INVITE. + // https://tools.ietf.org/html/rfc3261#section-14.2 + if (this.reinviteUserAgentClient) { + this.core.replyStateless(message, { statusCode: 491 }); + return; + } + } + // Request within a dialog common processing. + // https://tools.ietf.org/html/rfc3261#section-12.2.2 + _super.prototype.receiveRequest.call(this, message); + // Requests within a dialog MAY contain Record-Route and Contact header + // fields. However, these requests do not cause the dialog's route set + // to be modified, although they may modify the remote target URI. + // Specifically, requests that are not target refresh requests do not + // modify the dialog's remote target URI, and requests that are target + // refresh requests do. For dialogs that have been established with an + // INVITE, the only target refresh request defined is re-INVITE (see + // Section 14). Other extensions may define different target refresh + // requests for dialogs established in other ways. + // + // Note that an ACK is NOT a target refresh request. + // + // Target refresh requests only update the dialog's remote target URI, + // and not the route set formed from the Record-Route. Updating the + // latter would introduce severe backwards compatibility problems with + // RFC 2543-compliant systems. + // https://tools.ietf.org/html/rfc3261#section-15 + if (message.method === Constants_1.C.INVITE) { + // FIXME: parser needs to be typed... + var contact = message.parseHeader("contact"); + if (!contact) { // TODO: Review to make sure this will never happen + throw new Error("Contact undefined."); + } + if (!(contact instanceof NameAddrHeader_1.NameAddrHeader)) { + throw new Error("Contact not instance of NameAddrHeader."); + } + this.dialogState.remoteTarget = contact.uri; + } + // Switch on method and then delegate. + switch (message.method) { + case Constants_1.C.BYE: + // A UAS core receiving a BYE request for an existing dialog MUST follow + // the procedures of Section 12.2.2 to process the request. Once done, + // the UAS SHOULD terminate the session (and therefore stop sending and + // listening for media). The only case where it can elect not to are + // multicast sessions, where participation is possible even if the other + // participant in the dialog has terminated its involvement in the + // session. Whether or not it ends its participation on the session, + // the UAS core MUST generate a 2xx response to the BYE, and MUST pass + // that to the server transaction for transmission. + // + // The UAS MUST still respond to any pending requests received for that + // dialog. It is RECOMMENDED that a 487 (Request Terminated) response + // be generated to those pending requests. + // https://tools.ietf.org/html/rfc3261#section-15.1.2 + { + var uas = new bye_user_agent_server_1.ByeUserAgentServer(this, message); + this.delegate && this.delegate.onBye ? + this.delegate.onBye(uas) : + uas.accept(); + this.dispose(); + } + break; + case Constants_1.C.INFO: + // If a UA receives an INFO request associated with an Info Package that + // the UA has not indicated willingness to receive, the UA MUST send a + // 469 (Bad Info Package) response (see Section 11.6), which contains a + // Recv-Info header field with Info Packages for which the UA is willing + // to receive INFO requests. + { + var uas = new info_user_agent_server_1.InfoUserAgentServer(this, message); + this.delegate && this.delegate.onInfo ? + this.delegate.onInfo(uas) : + uas.reject({ + statusCode: 469, + extraHeaders: ["Recv-Info :"] + }); + } + break; + case Constants_1.C.INVITE: + // If the new session description is not acceptable, the UAS can reject + // it by returning a 488 (Not Acceptable Here) response for the re- + // INVITE. This response SHOULD include a Warning header field. + // https://tools.ietf.org/html/rfc3261#section-14.2 + { + var uas = new re_invite_user_agent_server_1.ReInviteUserAgentServer(this, message); + this.delegate && this.delegate.onInvite ? + this.delegate.onInvite(uas) : + uas.reject({ statusCode: 488 }); // TODO: Warning header field. + } + break; + case Constants_1.C.NOTIFY: + // https://tools.ietf.org/html/rfc3515#section-2.4.4 + { + var uas = new notify_user_agent_server_1.NotifyUserAgentServer(this, message); + this.delegate && this.delegate.onNotify ? + this.delegate.onNotify(uas) : + uas.accept(); + } + break; + case Constants_1.C.PRACK: + // https://tools.ietf.org/html/rfc3262#section-4 + { + var uas = new prack_user_agent_server_1.PrackUserAgentServer(this, message); + this.delegate && this.delegate.onPrack ? + this.delegate.onPrack(uas) : + uas.accept(); + } + break; + case Constants_1.C.REFER: + // https://tools.ietf.org/html/rfc3515#section-2.4.2 + { + var uas = new refer_user_agent_server_1.ReferUserAgentServer(this, message); + this.delegate && this.delegate.onRefer ? + this.delegate.onRefer(uas) : + uas.reject(); + } + break; + default: + { + this.logger.log("INVITE dialog " + this.id + " received unimplemented " + message.method + " request"); + this.core.replyStateless(message, { statusCode: 501 }); + } + break; + } + }; + SessionDialog.prototype.reliableSequenceGuard = function (message) { + var statusCode = message.statusCode; + if (!statusCode) { + throw new Error("Status code undefined"); + } + if (statusCode > 100 && statusCode < 200) { + // If a provisional response is received for an initial request, and + // that response contains a Require header field containing the option + // tag 100rel, the response is to be sent reliably. If the response is + // a 100 (Trying) (as opposed to 101 to 199), this option tag MUST be + // ignored, and the procedures below MUST NOT be used. + // https://tools.ietf.org/html/rfc3262#section-4 + var requireHeader = message.getHeader("require"); + var rseqHeader = message.getHeader("rseq"); + var rseq = requireHeader && requireHeader.includes("100rel") && rseqHeader ? Number(rseqHeader) : undefined; + if (rseq) { + // Handling of subsequent reliable provisional responses for the same + // initial request follows the same rules as above, with the following + // difference: reliable provisional responses are guaranteed to be in + // order. As a result, if the UAC receives another reliable provisional + // response to the same request, and its RSeq value is not one higher + // than the value of the sequence number, that response MUST NOT be + // acknowledged with a PRACK, and MUST NOT be processed further by the + // UAC. An implementation MAY discard the response, or MAY cache the + // response in the hopes of receiving the missing responses. + // https://tools.ietf.org/html/rfc3262#section-4 + if (this.rseq && this.rseq + 1 !== rseq) { + return false; + } + // Once a reliable provisional response is received, retransmissions of + // that response MUST be discarded. A response is a retransmission when + // its dialog ID, CSeq, and RSeq match the original response. The UAC + // MUST maintain a sequence number that indicates the most recently + // received in-order reliable provisional response for the initial + // request. This sequence number MUST be maintained until a final + // response is received for the initial request. Its value MUST be + // initialized to the RSeq header field in the first reliable + // provisional response received for the initial request. + // https://tools.ietf.org/html/rfc3262#section-4 + if (!this.rseq) { + this.rseq = rseq; + } + } + } + return true; + }; + /** + * Update the signaling state of the dialog. + * @param message The message to base the update off of. + */ + SessionDialog.prototype.signalingStateTransition = function (message) { + var body = messages_1.getBody(message); + // No body, no session. No, woman, no cry. + if (!body || body.contentDisposition !== "session") { + return; + } + // We're in UAS role, receiving incoming request with session description + if (message instanceof SIPMessage_1.IncomingRequest) { + switch (this._signalingState) { + case session_1.SignalingState.Initial: + case session_1.SignalingState.Stable: + this._signalingState = session_1.SignalingState.HaveRemoteOffer; + this._offer = body; + this._answer = undefined; + break; + case session_1.SignalingState.HaveLocalOffer: + this._signalingState = session_1.SignalingState.Stable; + this._answer = body; + break; + case session_1.SignalingState.HaveRemoteOffer: + // You cannot make a new offer while one is in progress. + // https://tools.ietf.org/html/rfc3261#section-13.2.1 + // FIXME: What to do here? + break; + case session_1.SignalingState.Closed: + break; + default: + throw new Error("Unexpected signaling state."); + } + } + // We're in UAC role, receiving incoming response with session description + if (message instanceof SIPMessage_1.IncomingResponse) { + switch (this._signalingState) { + case session_1.SignalingState.Initial: + case session_1.SignalingState.Stable: + this._signalingState = session_1.SignalingState.HaveRemoteOffer; + this._offer = body; + this._answer = undefined; + break; + case session_1.SignalingState.HaveLocalOffer: + this._signalingState = session_1.SignalingState.Stable; + this._answer = body; + break; + case session_1.SignalingState.HaveRemoteOffer: + // You cannot make a new offer while one is in progress. + // https://tools.ietf.org/html/rfc3261#section-13.2.1 + // FIXME: What to do here? + break; + case session_1.SignalingState.Closed: + break; + default: + throw new Error("Unexpected signaling state."); + } + } + // We're in UAC role, sending outgoing request with session description + if (message instanceof SIPMessage_1.OutgoingRequest) { + switch (this._signalingState) { + case session_1.SignalingState.Initial: + case session_1.SignalingState.Stable: + this._signalingState = session_1.SignalingState.HaveLocalOffer; + this._offer = body; + this._answer = undefined; + break; + case session_1.SignalingState.HaveLocalOffer: + // You cannot make a new offer while one is in progress. + // https://tools.ietf.org/html/rfc3261#section-13.2.1 + // FIXME: What to do here? + break; + case session_1.SignalingState.HaveRemoteOffer: + this._signalingState = session_1.SignalingState.Stable; + this._answer = body; + break; + case session_1.SignalingState.Closed: + break; + default: + throw new Error("Unexpected signaling state."); + } + } + // We're in UAS role, sending outgoing response with session description + if (messages_1.isBody(message)) { + switch (this._signalingState) { + case session_1.SignalingState.Initial: + case session_1.SignalingState.Stable: + this._signalingState = session_1.SignalingState.HaveLocalOffer; + this._offer = body; + this._answer = undefined; + break; + case session_1.SignalingState.HaveLocalOffer: + // You cannot make a new offer while one is in progress. + // https://tools.ietf.org/html/rfc3261#section-13.2.1 + // FIXME: What to do here? + break; + case session_1.SignalingState.HaveRemoteOffer: + this._signalingState = session_1.SignalingState.Stable; + this._answer = body; + break; + case session_1.SignalingState.Closed: + break; + default: + throw new Error("Unexpected signaling state."); + } + } + }; + SessionDialog.prototype.start2xxRetransmissionTimer = function () { + var _this = this; + if (this.initialTransaction instanceof transactions_1.InviteServerTransaction) { + var transaction_1 = this.initialTransaction; + // Once the response has been constructed, it is passed to the INVITE + // server transaction. In order to ensure reliable end-to-end + // transport of the response, it is necessary to periodically pass + // the response directly to the transport until the ACK arrives. The + // 2xx response is passed to the transport with an interval that + // starts at T1 seconds and doubles for each retransmission until it + // reaches T2 seconds (T1 and T2 are defined in Section 17). + // Response retransmissions cease when an ACK request for the + // response is received. This is independent of whatever transport + // protocols are used to send the response. + // https://tools.ietf.org/html/rfc6026#section-8.1 + var timeout_1 = Timers_1.Timers.T1; + var retransmission_1 = function () { + if (!_this.ackWait) { + _this.invite2xxTimer = undefined; + return; + } + _this.logger.log("No ACK for 2xx response received, attempting retransmission"); + transaction_1.retransmitAcceptedResponse(); + timeout_1 = Math.min(timeout_1 * 2, Timers_1.Timers.T2); + _this.invite2xxTimer = setTimeout(retransmission_1, timeout_1); + }; + this.invite2xxTimer = setTimeout(retransmission_1, timeout_1); + // If the server retransmits the 2xx response for 64*T1 seconds without + // receiving an ACK, the dialog is confirmed, but the session SHOULD be + // terminated. This is accomplished with a BYE, as described in Section 15. + // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 + var stateChanged_1 = function () { + if (transaction_1.state === transactions_1.TransactionState.Terminated) { + transaction_1.removeListener("stateChanged", stateChanged_1); + if (_this.invite2xxTimer) { + clearTimeout(_this.invite2xxTimer); + _this.invite2xxTimer = undefined; + } + if (_this.ackWait) { + if (_this.delegate && _this.delegate.onAckTimeout) { + _this.delegate.onAckTimeout(); + } + else { + _this.bye(); + } + } + } + }; + transaction_1.addListener("stateChanged", stateChanged_1); + } + }; + // FIXME: Refactor + SessionDialog.prototype.startReInvite2xxRetransmissionTimer = function () { + var _this = this; + if (this.reinviteUserAgentServer && this.reinviteUserAgentServer.transaction instanceof transactions_1.InviteServerTransaction) { + var transaction_2 = this.reinviteUserAgentServer.transaction; + // Once the response has been constructed, it is passed to the INVITE + // server transaction. In order to ensure reliable end-to-end + // transport of the response, it is necessary to periodically pass + // the response directly to the transport until the ACK arrives. The + // 2xx response is passed to the transport with an interval that + // starts at T1 seconds and doubles for each retransmission until it + // reaches T2 seconds (T1 and T2 are defined in Section 17). + // Response retransmissions cease when an ACK request for the + // response is received. This is independent of whatever transport + // protocols are used to send the response. + // https://tools.ietf.org/html/rfc6026#section-8.1 + var timeout_2 = Timers_1.Timers.T1; + var retransmission_2 = function () { + if (!_this.reinviteUserAgentServer) { + _this.invite2xxTimer = undefined; + return; + } + _this.logger.log("No ACK for 2xx response received, attempting retransmission"); + transaction_2.retransmitAcceptedResponse(); + timeout_2 = Math.min(timeout_2 * 2, Timers_1.Timers.T2); + _this.invite2xxTimer = setTimeout(retransmission_2, timeout_2); + }; + this.invite2xxTimer = setTimeout(retransmission_2, timeout_2); + // If the server retransmits the 2xx response for 64*T1 seconds without + // receiving an ACK, the dialog is confirmed, but the session SHOULD be + // terminated. This is accomplished with a BYE, as described in Section 15. + // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 + var stateChanged_2 = function () { + if (transaction_2.state === transactions_1.TransactionState.Terminated) { + transaction_2.removeListener("stateChanged", stateChanged_2); + if (_this.invite2xxTimer) { + clearTimeout(_this.invite2xxTimer); + _this.invite2xxTimer = undefined; + } + if (_this.reinviteUserAgentServer) { + // FIXME: TODO: What to do here + } + } + }; + transaction_2.addListener("stateChanged", stateChanged_2); + } + }; + return SessionDialog; +}(dialog_1.Dialog)); +exports.SessionDialog = SessionDialog; diff --git a/lib/Core/dialogs/subscribe-dialog.d.ts b/lib/Core/dialogs/subscribe-dialog.d.ts new file mode 100644 index 000000000..b85eea6b8 --- /dev/null +++ b/lib/Core/dialogs/subscribe-dialog.d.ts @@ -0,0 +1,39 @@ +import { IncomingRequest as IncomingRequestMessage } from "../../SIPMessage"; +import { OutgoingSubscribeRequest, OutgoingSubscribeRequestDelegate, RequestOptions } from "../messages"; +import { Subscription, SubscriptionDelegate, SubscriptionState } from "../subscription"; +import { UserAgentCore } from "../user-agent-core"; +import { Dialog } from "./dialog"; +import { DialogState } from "./dialog-state"; +/** + * SIP-Specific Event Notification + * + * Abstract + * + * This document describes an extension to the Session Initiation + * Protocol (SIP) defined by RFC 3261. The purpose of this extension is + * to provide an extensible framework by which SIP nodes can request + * notification from remote nodes indicating that certain events have + * occurred. + * + * Note that the event notification mechanisms defined herein are NOT + * intended to be a general-purpose infrastructure for all classes of + * event subscription and notification. + * + * This document represents a backwards-compatible improvement on the + * original mechanism described by RFC 3265, taking into account several + * years of implementation experience. Accordingly, this document + * obsoletes RFC 3265. This document also updates RFC 4660 slightly to + * accommodate some small changes to the mechanism that were discussed + * in that document. + * + * https://tools.ietf.org/html/rfc6665 + */ +export declare class SubscribeDialog extends Dialog implements Subscription { + delegate: SubscriptionDelegate | undefined; + private logger; + constructor(core: UserAgentCore, state: DialogState, delegate?: SubscriptionDelegate); + dispose(): void; + readonly subscriptionState: SubscriptionState; + receiveRequest(message: IncomingRequestMessage): void; + subscribe(delegate?: OutgoingSubscribeRequestDelegate, options?: RequestOptions): OutgoingSubscribeRequest; +} diff --git a/lib/Core/dialogs/subscribe-dialog.js b/lib/Core/dialogs/subscribe-dialog.js new file mode 100644 index 000000000..a81109d46 --- /dev/null +++ b/lib/Core/dialogs/subscribe-dialog.js @@ -0,0 +1,105 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Constants_1 = require("../../Constants"); +var subscription_1 = require("../subscription"); +var notify_user_agent_server_1 = require("../user-agents/notify-user-agent-server"); +var re_subscribe_user_agent_client_1 = require("../user-agents/re-subscribe-user-agent-client"); +var dialog_1 = require("./dialog"); +/** + * SIP-Specific Event Notification + * + * Abstract + * + * This document describes an extension to the Session Initiation + * Protocol (SIP) defined by RFC 3261. The purpose of this extension is + * to provide an extensible framework by which SIP nodes can request + * notification from remote nodes indicating that certain events have + * occurred. + * + * Note that the event notification mechanisms defined herein are NOT + * intended to be a general-purpose infrastructure for all classes of + * event subscription and notification. + * + * This document represents a backwards-compatible improvement on the + * original mechanism described by RFC 3265, taking into account several + * years of implementation experience. Accordingly, this document + * obsoletes RFC 3265. This document also updates RFC 4660 slightly to + * accommodate some small changes to the mechanism that were discussed + * in that document. + * + * https://tools.ietf.org/html/rfc6665 + */ +var SubscribeDialog = /** @class */ (function (_super) { + __extends(SubscribeDialog, _super); + function SubscribeDialog(core, state, delegate) { + var _this = _super.call(this, core, state) || this; + _this.delegate = delegate; + _this.logger = core.loggerFactory.getLogger("sip.subscribe-dialog"); + _this.logger.log("SUBSCRIBE dialog " + _this.id + " constructed"); + return _this; + } + SubscribeDialog.prototype.dispose = function () { + _super.prototype.dispose.call(this); + this.logger.log("SUBSCRIBE dialog " + this.id + " destroyed"); + }; + Object.defineProperty(SubscribeDialog.prototype, "subscriptionState", { + // FIXME: TODO: + get: function () { + return subscription_1.SubscriptionState.Initial; + }, + enumerable: true, + configurable: true + }); + SubscribeDialog.prototype.receiveRequest = function (message) { + this.logger.log("SUBSCRIBE dialog " + this.id + " received " + message.method + " request"); + // Request within a dialog out of sequence guard. + // https://tools.ietf.org/html/rfc3261#section-12.2.2 + if (!this.sequenceGuard(message)) { + this.logger.log("SUBSCRIBE dialog " + this.id + " rejected out of order " + message.method + " request."); + return; + } + // Request within a dialog common processing. + // https://tools.ietf.org/html/rfc3261#section-12.2.2 + _super.prototype.receiveRequest.call(this, message); + // Switch on method and then delegate. + switch (message.method) { + case Constants_1.C.NOTIFY: + { + var uas = new notify_user_agent_server_1.NotifyUserAgentServer(this, message); + if (this.delegate && this.delegate.onNotify) { + this.delegate.onNotify(uas); + } + else { + uas.accept(); + } + } + break; + default: + { + this.logger.log("SUBSCRIBE dialog " + this.id + " received unimplemented " + message.method + " request"); + this.core.replyStateless(message, { statusCode: 501 }); + } + break; + } + }; + SubscribeDialog.prototype.subscribe = function (delegate, options) { + this.logger.log("SUBSCRIBE dialog " + this.id + " sending SUBSCRIBE request"); + var uac = new re_subscribe_user_agent_client_1.ReSubscribeUserAgentClient(this, delegate, options); + return uac; + }; + return SubscribeDialog; +}(dialog_1.Dialog)); +exports.SubscribeDialog = SubscribeDialog; diff --git a/lib/Core/dialogs/subscription-dialog.d.ts b/lib/Core/dialogs/subscription-dialog.d.ts new file mode 100644 index 000000000..4eadff8ff --- /dev/null +++ b/lib/Core/dialogs/subscription-dialog.d.ts @@ -0,0 +1,116 @@ +import { IncomingRequest as IncomingRequestMessage, OutgoingRequest as OutgoingRequestMessage } from "../../SIPMessage"; +import { OutgoingSubscribeRequest, OutgoingSubscribeRequestDelegate, RequestOptions } from "../messages"; +import { Subscription, SubscriptionDelegate, SubscriptionState } from "../subscription"; +import { UserAgentCore } from "../user-agent-core/user-agent-core"; +import { Dialog } from "./dialog"; +import { DialogState } from "./dialog-state"; +/** + * SIP-Specific Event Notification + * + * Abstract + * + * This document describes an extension to the Session Initiation + * Protocol (SIP) defined by RFC 3261. The purpose of this extension is + * to provide an extensible framework by which SIP nodes can request + * notification from remote nodes indicating that certain events have + * occurred. + * + * Note that the event notification mechanisms defined herein are NOT + * intended to be a general-purpose infrastructure for all classes of + * event subscription and notification. + * + * This document represents a backwards-compatible improvement on the + * original mechanism described by RFC 3265, taking into account several + * years of implementation experience. Accordingly, this document + * obsoletes RFC 3265. This document also updates RFC 4660 slightly to + * accommodate some small changes to the mechanism that were discussed + * in that document. + * + * https://tools.ietf.org/html/rfc6665 + */ +export declare class SubscriptionDialog extends Dialog implements Subscription { + /** + * When a UAC receives a response that establishes a dialog, it + * constructs the state of the dialog. This state MUST be maintained + * for the duration of the dialog. + * https://tools.ietf.org/html/rfc3261#section-12.1.2 + * @param outgoingRequestMessage Outgoing request message for dialog. + * @param incomingResponseMessage Incoming response message creating dialog. + */ + static initialDialogStateForSubscription(outgoingSubscribeRequestMessage: OutgoingRequestMessage, incomingNotifyRequestMessage: IncomingRequestMessage): DialogState; + delegate: SubscriptionDelegate | undefined; + private _autoRefresh; + private _subscriptionEvent; + private _subscriptionExpires; + private _subscriptionExpiresInitial; + private _subscriptionExpiresLastSet; + private _subscriptionRefresh; + private _subscriptionRefreshLastSet; + private _subscriptionState; + private logger; + private N; + private refreshTimer; + constructor(subscriptionEvent: string, subscriptionExpires: number, subscriptionState: SubscriptionState, core: UserAgentCore, state: DialogState, delegate?: SubscriptionDelegate); + dispose(): void; + autoRefresh: boolean; + readonly subscriptionEvent: string; + /** Number of seconds until subscription expires. */ + subscriptionExpires: number; + readonly subscriptionExpiresInitial: number; + /** Number of seconds until subscription auto refresh. */ + readonly subscriptionRefresh: number | undefined; + readonly subscriptionState: SubscriptionState; + /** + * Receive in dialog request message from transport. + * @param message The incoming request message. + */ + receiveRequest(message: IncomingRequestMessage): void; + /** + * 4.1.2.2. Refreshing of Subscriptions + * https://tools.ietf.org/html/rfc6665#section-4.1.2.2 + */ + refresh(): OutgoingSubscribeRequest; + /** + * 4.1.2.2. Refreshing of Subscriptions + * https://tools.ietf.org/html/rfc6665#section-4.1.2.2 + * @param delegate Delegate to handle responses. + * @param options Options bucket. + */ + subscribe(delegate?: OutgoingSubscribeRequestDelegate, options?: RequestOptions): OutgoingSubscribeRequest; + /** + * 4.4.1. Dialog Creation and Termination + * A subscription is destroyed after a notifier sends a NOTIFY request + * with a "Subscription-State" of "terminated", or in certain error + * situations described elsewhere in this document. + * https://tools.ietf.org/html/rfc6665#section-4.4.1 + */ + terminate(): void; + /** + * 4.1.2.3. Unsubscribing + * https://tools.ietf.org/html/rfc6665#section-4.1.2.3 + */ + unsubscribe(): OutgoingSubscribeRequest; + /** + * Handle in dialog NOTIFY requests. + * This does not include the first NOTIFY which created the dialog. + * @param message The incoming NOTIFY request message. + */ + private onNotify; + private onRefresh; + private onTerminated; + private refreshTimerClear; + private refreshTimerSet; + private stateTransition; + /** + * When refreshing a subscription, a subscriber starts Timer N, set to + * 64*T1, when it sends the SUBSCRIBE request. If this Timer N expires + * prior to the receipt of a NOTIFY request, the subscriber considers + * the subscription terminated. If the subscriber receives a success + * response to the SUBSCRIBE request that indicates that no NOTIFY + * request will be generated -- such as the 204 response defined for use + * with the optional extension described in [RFC5839] -- then it MUST + * cancel Timer N. + * https://tools.ietf.org/html/rfc6665#section-4.1.2.2 + */ + private timer_N; +} diff --git a/lib/Core/dialogs/subscription-dialog.js b/lib/Core/dialogs/subscription-dialog.js new file mode 100644 index 000000000..87071f03a --- /dev/null +++ b/lib/Core/dialogs/subscription-dialog.js @@ -0,0 +1,504 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Constants_1 = require("../../Constants"); +var NameAddrHeader_1 = require("../../NameAddrHeader"); +var Timers_1 = require("../../Timers"); +var subscription_1 = require("../subscription"); +var allowed_methods_1 = require("../user-agent-core/allowed-methods"); +var notify_user_agent_server_1 = require("../user-agents/notify-user-agent-server"); +var re_subscribe_user_agent_client_1 = require("../user-agents/re-subscribe-user-agent-client"); +var dialog_1 = require("./dialog"); +/** + * SIP-Specific Event Notification + * + * Abstract + * + * This document describes an extension to the Session Initiation + * Protocol (SIP) defined by RFC 3261. The purpose of this extension is + * to provide an extensible framework by which SIP nodes can request + * notification from remote nodes indicating that certain events have + * occurred. + * + * Note that the event notification mechanisms defined herein are NOT + * intended to be a general-purpose infrastructure for all classes of + * event subscription and notification. + * + * This document represents a backwards-compatible improvement on the + * original mechanism described by RFC 3265, taking into account several + * years of implementation experience. Accordingly, this document + * obsoletes RFC 3265. This document also updates RFC 4660 slightly to + * accommodate some small changes to the mechanism that were discussed + * in that document. + * + * https://tools.ietf.org/html/rfc6665 + */ +var SubscriptionDialog = /** @class */ (function (_super) { + __extends(SubscriptionDialog, _super); + function SubscriptionDialog(subscriptionEvent, subscriptionExpires, subscriptionState, core, state, delegate) { + var _this = _super.call(this, core, state) || this; + _this.delegate = delegate; + _this._autoRefresh = false; + _this._subscriptionEvent = subscriptionEvent; + _this._subscriptionExpires = subscriptionExpires; + _this._subscriptionExpiresInitial = subscriptionExpires; + _this._subscriptionExpiresLastSet = Math.floor(Date.now() / 1000); + _this._subscriptionRefresh = undefined; + _this._subscriptionRefreshLastSet = undefined; + _this._subscriptionState = subscriptionState; + _this.logger = core.loggerFactory.getLogger("sip.subscribe-dialog"); + _this.logger.log("SUBSCRIBE dialog " + _this.id + " constructed"); + return _this; + } + /** + * When a UAC receives a response that establishes a dialog, it + * constructs the state of the dialog. This state MUST be maintained + * for the duration of the dialog. + * https://tools.ietf.org/html/rfc3261#section-12.1.2 + * @param outgoingRequestMessage Outgoing request message for dialog. + * @param incomingResponseMessage Incoming response message creating dialog. + */ + SubscriptionDialog.initialDialogStateForSubscription = function (outgoingSubscribeRequestMessage, incomingNotifyRequestMessage) { + // If the request was sent over TLS, and the Request-URI contained a + // SIPS URI, the "secure" flag is set to TRUE. + // https://tools.ietf.org/html/rfc3261#section-12.1.2 + var secure = false; // FIXME: Currently no support for TLS. + // The route set MUST be set to the list of URIs in the Record-Route + // header field from the response, taken in reverse order and preserving + // all URI parameters. If no Record-Route header field is present in + // the response, the route set MUST be set to the empty set. This route + // set, even if empty, overrides any pre-existing route set for future + // requests in this dialog. The remote target MUST be set to the URI + // from the Contact header field of the response. + // https://tools.ietf.org/html/rfc3261#section-12.1.2 + var routeSet = incomingNotifyRequestMessage.getHeaders("record-route"); + var contact = incomingNotifyRequestMessage.parseHeader("contact"); + if (!contact) { // TODO: Review to make sure this will never happen + throw new Error("Contact undefined."); + } + if (!(contact instanceof NameAddrHeader_1.NameAddrHeader)) { + throw new Error("Contact not instance of NameAddrHeader."); + } + var remoteTarget = contact.uri; + // The local sequence number MUST be set to the value of the sequence + // number in the CSeq header field of the request. The remote sequence + // number MUST be empty (it is established when the remote UA sends a + // request within the dialog). The call identifier component of the + // dialog ID MUST be set to the value of the Call-ID in the request. + // The local tag component of the dialog ID MUST be set to the tag in + // the From field in the request, and the remote tag component of the + // dialog ID MUST be set to the tag in the To field of the response. A + // UAC MUST be prepared to receive a response without a tag in the To + // field, in which case the tag is considered to have a value of null. + // + // This is to maintain backwards compatibility with RFC 2543, which + // did not mandate To tags. + // + // https://tools.ietf.org/html/rfc3261#section-12.1.2 + var localSequenceNumber = outgoingSubscribeRequestMessage.cseq; + var remoteSequenceNumber = undefined; + var callId = outgoingSubscribeRequestMessage.callId; + var localTag = outgoingSubscribeRequestMessage.fromTag; + var remoteTag = incomingNotifyRequestMessage.fromTag; + if (!callId) { // TODO: Review to make sure this will never happen + throw new Error("Call id undefined."); + } + if (!localTag) { // TODO: Review to make sure this will never happen + throw new Error("From tag undefined."); + } + if (!remoteTag) { // TODO: Review to make sure this will never happen + throw new Error("To tag undefined."); // FIXME: No backwards compatibility with RFC 2543 + } + // The remote URI MUST be set to the URI in the To field, and the local + // URI MUST be set to the URI in the From field. + // https://tools.ietf.org/html/rfc3261#section-12.1.2 + if (!outgoingSubscribeRequestMessage.from) { // TODO: Review to make sure this will never happen + throw new Error("From undefined."); + } + if (!outgoingSubscribeRequestMessage.to) { // TODO: Review to make sure this will never happen + throw new Error("To undefined."); + } + var localURI = outgoingSubscribeRequestMessage.from.uri; + var remoteURI = outgoingSubscribeRequestMessage.to.uri; + // A dialog can also be in the "early" state, which occurs when it is + // created with a provisional response, and then transition to the + // "confirmed" state when a 2xx final response arrives. + // https://tools.ietf.org/html/rfc3261#section-12 + var early = false; + var dialogState = { + id: callId + localTag + remoteTag, + early: early, + callId: callId, + localTag: localTag, + remoteTag: remoteTag, + localSequenceNumber: localSequenceNumber, + remoteSequenceNumber: remoteSequenceNumber, + localURI: localURI, + remoteURI: remoteURI, + remoteTarget: remoteTarget, + routeSet: routeSet, + secure: secure + }; + return dialogState; + }; + SubscriptionDialog.prototype.dispose = function () { + _super.prototype.dispose.call(this); + if (this.N) { + clearTimeout(this.N); + this.N = undefined; + } + this.refreshTimerClear(); + this.logger.log("SUBSCRIBE dialog " + this.id + " destroyed"); + }; + Object.defineProperty(SubscriptionDialog.prototype, "autoRefresh", { + get: function () { + return this._autoRefresh; + }, + set: function (autoRefresh) { + this._autoRefresh = true; + this.refreshTimerSet(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SubscriptionDialog.prototype, "subscriptionEvent", { + get: function () { + return this._subscriptionEvent; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SubscriptionDialog.prototype, "subscriptionExpires", { + /** Number of seconds until subscription expires. */ + get: function () { + var secondsSinceLastSet = Math.floor(Date.now() / 1000) - this._subscriptionExpiresLastSet; + var secondsUntilExpires = this._subscriptionExpires - secondsSinceLastSet; + return Math.max(secondsUntilExpires, 0); + }, + set: function (expires) { + if (expires < 0) { + throw new Error("Expires must be greater than or equal to zero."); + } + this._subscriptionExpires = expires; + this._subscriptionExpiresLastSet = Math.floor(Date.now() / 1000); + if (this.autoRefresh) { + var refresh = this.subscriptionRefresh; + if (refresh === undefined || refresh >= expires) { + this.refreshTimerSet(); + } + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SubscriptionDialog.prototype, "subscriptionExpiresInitial", { + get: function () { + return this._subscriptionExpiresInitial; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SubscriptionDialog.prototype, "subscriptionRefresh", { + /** Number of seconds until subscription auto refresh. */ + get: function () { + if (this._subscriptionRefresh === undefined || this._subscriptionRefreshLastSet === undefined) { + return undefined; + } + var secondsSinceLastSet = Math.floor(Date.now() / 1000) - this._subscriptionRefreshLastSet; + var secondsUntilExpires = this._subscriptionRefresh - secondsSinceLastSet; + return Math.max(secondsUntilExpires, 0); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SubscriptionDialog.prototype, "subscriptionState", { + get: function () { + return this._subscriptionState; + }, + enumerable: true, + configurable: true + }); + /** + * Receive in dialog request message from transport. + * @param message The incoming request message. + */ + SubscriptionDialog.prototype.receiveRequest = function (message) { + this.logger.log("SUBSCRIBE dialog " + this.id + " received " + message.method + " request"); + // Request within a dialog out of sequence guard. + // https://tools.ietf.org/html/rfc3261#section-12.2.2 + if (!this.sequenceGuard(message)) { + this.logger.log("SUBSCRIBE dialog " + this.id + " rejected out of order " + message.method + " request."); + return; + } + // Request within a dialog common processing. + // https://tools.ietf.org/html/rfc3261#section-12.2.2 + _super.prototype.receiveRequest.call(this, message); + // Switch on method and then delegate. + switch (message.method) { + case Constants_1.C.NOTIFY: + this.onNotify(message); + break; + default: + this.logger.log("SUBSCRIBE dialog " + this.id + " received unimplemented " + message.method + " request"); + this.core.replyStateless(message, { statusCode: 501 }); + break; + } + }; + /** + * 4.1.2.2. Refreshing of Subscriptions + * https://tools.ietf.org/html/rfc6665#section-4.1.2.2 + */ + SubscriptionDialog.prototype.refresh = function () { + var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); + var options = {}; + options.extraHeaders = (options.extraHeaders || []).slice(); + options.extraHeaders.push(allowHeader); + options.extraHeaders.push("Event: " + this.subscriptionEvent); + options.extraHeaders.push("Expires: " + this.subscriptionExpiresInitial); + options.extraHeaders.push("Contact: " + this.core.configuration.contact.toString()); + return this.subscribe(undefined, options); + }; + /** + * 4.1.2.2. Refreshing of Subscriptions + * https://tools.ietf.org/html/rfc6665#section-4.1.2.2 + * @param delegate Delegate to handle responses. + * @param options Options bucket. + */ + SubscriptionDialog.prototype.subscribe = function (delegate, options) { + var _this = this; + if (options === void 0) { options = {}; } + if (this.subscriptionState !== subscription_1.SubscriptionState.Pending && this.subscriptionState !== subscription_1.SubscriptionState.Active) { + // FIXME: This needs to be a proper exception + throw new Error("Invalid state " + this.subscriptionState + ". May only re-subscribe while in state \"pending\" or \"active\"."); + } + this.logger.log("SUBSCRIBE dialog " + this.id + " sending SUBSCRIBE request"); + var uac = new re_subscribe_user_agent_client_1.ReSubscribeUserAgentClient(this, delegate, options); + // When refreshing a subscription, a subscriber starts Timer N, set to + // 64*T1, when it sends the SUBSCRIBE request. + // https://tools.ietf.org/html/rfc6665#section-4.1.2.2 + this.N = setTimeout(function () { return _this.timer_N(); }, Timers_1.Timers.TIMER_N); + return uac; + }; + /** + * 4.4.1. Dialog Creation and Termination + * A subscription is destroyed after a notifier sends a NOTIFY request + * with a "Subscription-State" of "terminated", or in certain error + * situations described elsewhere in this document. + * https://tools.ietf.org/html/rfc6665#section-4.4.1 + */ + SubscriptionDialog.prototype.terminate = function () { + this.stateTransition(subscription_1.SubscriptionState.Terminated); + this.onTerminated(); + }; + /** + * 4.1.2.3. Unsubscribing + * https://tools.ietf.org/html/rfc6665#section-4.1.2.3 + */ + SubscriptionDialog.prototype.unsubscribe = function () { + var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); + var options = {}; + options.extraHeaders = (options.extraHeaders || []).slice(); + options.extraHeaders.push(allowHeader); + options.extraHeaders.push("Event: " + this.subscriptionEvent); + options.extraHeaders.push("Expires: 0"); + options.extraHeaders.push("Contact: " + this.core.configuration.contact.toString()); + return this.subscribe(undefined, options); + }; + /** + * Handle in dialog NOTIFY requests. + * This does not include the first NOTIFY which created the dialog. + * @param message The incoming NOTIFY request message. + */ + SubscriptionDialog.prototype.onNotify = function (message) { + // If, for some reason, the event package designated in the "Event" + // header field of the NOTIFY request is not supported, the subscriber + // will respond with a 489 (Bad Event) response. + // https://tools.ietf.org/html/rfc6665#section-4.1.3 + var event = message.parseHeader("Event").event; + if (!event || event !== this.subscriptionEvent) { + this.core.replyStateless(message, { statusCode: 489 }); + return; + } + // In the state diagram, "Re-subscription times out" means that an + // attempt to refresh or update the subscription using a new SUBSCRIBE + // request does not result in a NOTIFY request before the corresponding + // Timer N expires. + // https://tools.ietf.org/html/rfc6665#section-4.1.2 + if (this.N) { + clearTimeout(this.N); + this.N = undefined; + } + // NOTIFY requests MUST contain "Subscription-State" header fields that + // indicate the status of the subscription. + // https://tools.ietf.org/html/rfc6665#section-4.1.3 + var subscriptionState = message.parseHeader("Subscription-State"); + if (!subscriptionState || !subscriptionState.state) { + this.core.replyStateless(message, { statusCode: 489 }); + return; + } + var state = subscriptionState.state; + var expires = subscriptionState.expires ? Math.max(subscriptionState.expires, 0) : undefined; + // Update our state and expiration. + switch (state) { + case "pending": + this.stateTransition(subscription_1.SubscriptionState.Pending, expires); + break; + case "active": + this.stateTransition(subscription_1.SubscriptionState.Active, expires); + break; + case "terminated": + this.stateTransition(subscription_1.SubscriptionState.Terminated, expires); + break; + default: + this.logger.warn("Unrecognized subscription state."); + break; + } + // Delegate remainder of NOTIFY handling. + var uas = new notify_user_agent_server_1.NotifyUserAgentServer(this, message); + if (this.delegate && this.delegate.onNotify) { + this.delegate.onNotify(uas); + } + else { + uas.accept(); + } + }; + SubscriptionDialog.prototype.onRefresh = function (request) { + if (this.delegate && this.delegate.onRefresh) { + this.delegate.onRefresh(request); + } + }; + SubscriptionDialog.prototype.onTerminated = function () { + if (this.delegate && this.delegate.onTerminated) { + this.delegate.onTerminated(); + } + }; + SubscriptionDialog.prototype.refreshTimerClear = function () { + if (this.refreshTimer) { + clearTimeout(this.refreshTimer); + this.refreshTimer = undefined; + } + }; + SubscriptionDialog.prototype.refreshTimerSet = function () { + var _this = this; + this.refreshTimerClear(); + if (this.autoRefresh && this.subscriptionExpires > 0) { + var refresh = this.subscriptionExpires * 900; + this._subscriptionRefresh = Math.floor(refresh / 1000); + this._subscriptionRefreshLastSet = Math.floor(Date.now() / 1000); + this.refreshTimer = setTimeout(function () { + _this.refreshTimer = undefined; + _this._subscriptionRefresh = undefined; + _this._subscriptionRefreshLastSet = undefined; + _this.onRefresh(_this.refresh()); + }, refresh); + } + }; + SubscriptionDialog.prototype.stateTransition = function (newState, newExpires) { + var _this = this; + // Assert valid state transitions. + var invalidStateTransition = function () { + _this.logger.warn("Invalid subscription state transition from " + _this.subscriptionState + " to " + newState); + }; + switch (newState) { + case subscription_1.SubscriptionState.Initial: + invalidStateTransition(); + return; + case subscription_1.SubscriptionState.NotifyWait: + invalidStateTransition(); + return; + case subscription_1.SubscriptionState.Pending: + if (this.subscriptionState !== subscription_1.SubscriptionState.NotifyWait && + this.subscriptionState !== subscription_1.SubscriptionState.Pending) { + invalidStateTransition(); + return; + } + break; + case subscription_1.SubscriptionState.Active: + if (this.subscriptionState !== subscription_1.SubscriptionState.NotifyWait && + this.subscriptionState !== subscription_1.SubscriptionState.Pending && + this.subscriptionState !== subscription_1.SubscriptionState.Active) { + invalidStateTransition(); + return; + } + break; + case subscription_1.SubscriptionState.Terminated: + if (this.subscriptionState !== subscription_1.SubscriptionState.NotifyWait && + this.subscriptionState !== subscription_1.SubscriptionState.Pending && + this.subscriptionState !== subscription_1.SubscriptionState.Active) { + invalidStateTransition(); + return; + } + break; + default: + invalidStateTransition(); + return; + } + // If the "Subscription-State" value is "pending", the subscription has + // been received by the notifier, but there is insufficient policy + // information to grant or deny the subscription yet. If the header + // field also contains an "expires" parameter, the subscriber SHOULD + // take it as the authoritative subscription duration and adjust + // accordingly. No further action is necessary on the part of the + // subscriber. The "retry-after" and "reason" parameters have no + // semantics for "pending". + // https://tools.ietf.org/html/rfc6665#section-4.1.3 + if (newState === subscription_1.SubscriptionState.Pending) { + if (newExpires) { + this.subscriptionExpires = newExpires; + } + } + // If the "Subscription-State" header field value is "active", it means + // that the subscription has been accepted and (in general) has been + // authorized. If the header field also contains an "expires" + // parameter, the subscriber SHOULD take it as the authoritative + // subscription duration and adjust accordingly. The "retry-after" and + // "reason" parameters have no semantics for "active". + // https://tools.ietf.org/html/rfc6665#section-4.1.3 + if (newState === subscription_1.SubscriptionState.Active) { + if (newExpires) { + this.subscriptionExpires = newExpires; + } + } + // If the "Subscription-State" value is "terminated", the subscriber + // MUST consider the subscription terminated. The "expires" parameter + // has no semantics for "terminated" -- notifiers SHOULD NOT include an + // "expires" parameter on a "Subscription-State" header field with a + // value of "terminated", and subscribers MUST ignore any such + // parameter, if present. + if (newState === subscription_1.SubscriptionState.Terminated) { + this.dispose(); + } + this._subscriptionState = newState; + }; + /** + * When refreshing a subscription, a subscriber starts Timer N, set to + * 64*T1, when it sends the SUBSCRIBE request. If this Timer N expires + * prior to the receipt of a NOTIFY request, the subscriber considers + * the subscription terminated. If the subscriber receives a success + * response to the SUBSCRIBE request that indicates that no NOTIFY + * request will be generated -- such as the 204 response defined for use + * with the optional extension described in [RFC5839] -- then it MUST + * cancel Timer N. + * https://tools.ietf.org/html/rfc6665#section-4.1.2.2 + */ + SubscriptionDialog.prototype.timer_N = function () { + if (this.subscriptionState !== subscription_1.SubscriptionState.Terminated) { + this.stateTransition(subscription_1.SubscriptionState.Terminated); + this.onTerminated(); + } + }; + return SubscriptionDialog; +}(dialog_1.Dialog)); +exports.SubscriptionDialog = SubscriptionDialog; diff --git a/lib/Core/messages/body.d.ts b/lib/Core/messages/body.d.ts new file mode 100644 index 000000000..965c89f57 --- /dev/null +++ b/lib/Core/messages/body.d.ts @@ -0,0 +1,70 @@ +import { BodyObj } from "../../session-description-handler"; +import { IncomingRequest as IncomingRequestMessage, IncomingResponse as IncomingResponseMessage, OutgoingRequest as OutgoingRequestMessage } from "../../SIPMessage"; +/** + * SIP Message Body. + * https://tools.ietf.org/html/rfc3261#section-7.4 + */ +export interface Body { + /** + * If the Content-Disposition header field is missing, bodies of + * Content-Type application/sdp imply the disposition "session", while + * other content types imply "render". + * https://tools.ietf.org/html/rfc3261#section-13.2.1 + * For backward-compatibility, if the Content-Disposition header field + * is missing, the server SHOULD assume bodies of Content-Type + * application/sdp are the disposition "session", while other content + * types are "render". + * https://tools.ietf.org/html/rfc3261#section-20.11 + */ + contentDisposition: string; + /** + * The Content-Type header field indicates the media type of the + * message-body sent to the recipient. The Content-Type header field + * MUST be present if the body is not empty. If the body is empty, + * and a Content-Type header field is present, it indicates that the body + * of the specific type has zero length (for example, an empty audio file). + * https://tools.ietf.org/html/rfc3261#section-20.15 + */ + contentType: string; + /** + * Requests, including new requests defined in extensions to this + * specification, MAY contain message bodies unless otherwise noted. + * The interpretation of the body depends on the request method. + * For response messages, the request method and the response status + * code determine the type and interpretation of any message body. All + * responses MAY include a body. + * https://tools.ietf.org/html/rfc3261#section-7.4 + */ + content: string; +} +/** + * Create a Body given a BodyObj. + * @param bodyObj Body Object + */ +export declare function fromBodyObj(bodyObj: BodyObj): Body; +/** + * Create a Body given a BodyObj. + * @param bodyObj Body Object + */ +export declare function fromBodyLegacy(bodyLegacy: string | { + body: string; + contentType: string; +}): Body; +/** Outgoing response body */ +export declare type OutgoingResponseBody = Body; +/** + * Given a message, get a normalized body. + * The content disposition is inferred if not set. + * @param message The message. + */ +export declare function getBody(message: IncomingRequestMessage | IncomingResponseMessage | OutgoingRequestMessage | OutgoingResponseBody): Body | undefined; +/** + * User-Defined Type Guard for Body. + * @param body Body to check. + */ +export declare function isBody(body: any): body is Body; +/** + * Create a BodyObj given a Body. + * @param bodyObj Body Object + */ +export declare function toBodyObj(body: Body): BodyObj; diff --git a/lib/Core/messages/body.js b/lib/Core/messages/body.js new file mode 100644 index 000000000..396022824 --- /dev/null +++ b/lib/Core/messages/body.js @@ -0,0 +1,139 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var SIPMessage_1 = require("../../SIPMessage"); +/** + * Create a Body given a BodyObj. + * @param bodyObj Body Object + */ +function fromBodyObj(bodyObj) { + var content = bodyObj.body; + var contentType = bodyObj.contentType; + var contentDisposition = contentTypeToContentDisposition(contentType); + var body = { contentDisposition: contentDisposition, contentType: contentType, content: content }; + return body; +} +exports.fromBodyObj = fromBodyObj; +/** + * Create a Body given a BodyObj. + * @param bodyObj Body Object + */ +function fromBodyLegacy(bodyLegacy) { + var content = (typeof bodyLegacy === "string") ? bodyLegacy : bodyLegacy.body; + var contentType = (typeof bodyLegacy === "string") ? "application/sdp" : bodyLegacy.contentType; + var contentDisposition = contentTypeToContentDisposition(contentType); + var body = { contentDisposition: contentDisposition, contentType: contentType, content: content }; + return body; +} +exports.fromBodyLegacy = fromBodyLegacy; +/** + * Given a message, get a normalized body. + * The content disposition is inferred if not set. + * @param message The message. + */ +function getBody(message) { + var contentDisposition; + var contentType; + var content; + // We're in UAS role, receiving incoming request + if (message instanceof SIPMessage_1.IncomingRequest) { + if (message.body) { + // FIXME: Parsing needs typing + var parse = message.parseHeader("Content-Disposition"); + contentDisposition = parse ? parse.type : undefined; + contentType = message.parseHeader("Content-Type"); + content = message.body; + } + } + // We're in UAC role, receiving incoming response + if (message instanceof SIPMessage_1.IncomingResponse) { + if (message.body) { + // FIXME: Parsing needs typing + var parse = message.parseHeader("Content-Disposition"); + contentDisposition = parse ? parse.type : undefined; + contentType = message.parseHeader("Content-Type"); + content = message.body; + } + } + // We're in UAC role, sending outgoing request + if (message instanceof SIPMessage_1.OutgoingRequest) { + if (message.body) { + contentDisposition = message.getHeader("Content-Disposition"); + contentType = message.getHeader("Content-Type"); + if (typeof message.body === "string") { + // FIXME: OutgoingRequest should not allow a "string" body without a "Content-Type" header. + if (!contentType) { + throw new Error("Header content type header does not equal body content type."); + } + content = message.body; + } + else { + // FIXME: OutgoingRequest should not allow the "Content-Type" header not to match th body content type + if (contentType && contentType !== message.body.contentType) { + throw new Error("Header content type header does not equal body content type."); + } + contentType = message.body.contentType; + content = message.body.body; + } + } + } + // We're in UAS role, sending outgoing response + if (isBody(message)) { + contentDisposition = message.contentDisposition; + contentType = message.contentType; + content = message.content; + } + // No content, no body. + if (!content) { + return undefined; + } + if (contentType && !contentDisposition) { + contentDisposition = contentTypeToContentDisposition(contentType); + } + if (!contentDisposition) { + throw new Error("Content disposition undefined."); + } + if (!contentType) { + throw new Error("Content type undefined."); + } + return { + contentDisposition: contentDisposition, + contentType: contentType, + content: content + }; +} +exports.getBody = getBody; +/** + * User-Defined Type Guard for Body. + * @param body Body to check. + */ +function isBody(body) { + return body && + typeof body.content === "string" && + typeof body.contentType === "string" && + body.contentDisposition === undefined ? true : typeof body.contentDisposition === "string"; +} +exports.isBody = isBody; +/** + * Create a BodyObj given a Body. + * @param bodyObj Body Object + */ +function toBodyObj(body) { + var bodyObj = { + body: body.content, + contentType: body.contentType + }; + return bodyObj; +} +exports.toBodyObj = toBodyObj; +// If the Content-Disposition header field is missing, bodies of +// Content-Type application/sdp imply the disposition "session", while +// other content types imply "render". +// https://tools.ietf.org/html/rfc3261#section-13.2.1 +function contentTypeToContentDisposition(contentType) { + if (contentType === "application/sdp") { + return "session"; + } + else { + return "render"; + } +} diff --git a/lib/Core/messages/incoming-request.d.ts b/lib/Core/messages/incoming-request.d.ts new file mode 100644 index 000000000..205e117c4 --- /dev/null +++ b/lib/Core/messages/incoming-request.d.ts @@ -0,0 +1,62 @@ +import { Exceptions } from "../../Exceptions"; +import { IncomingRequest as IncomingRequestMessage } from "../../SIPMessage"; +import { URI } from "../../URI"; +import { OutgoingResponse, ResponseOptions } from "./outgoing-response"; +/** + * A SIP message sent from a remote client to a local server, + * for the purpose of invoking a particular operation. + * https://tools.ietf.org/html/rfc3261#section-7.1 + */ +export interface IncomingRequest { + /** Delegate providing custom handling of this incoming request. */ + delegate?: IncomingRequestDelegate; + /** The incoming message. */ + readonly message: IncomingRequestMessage; + /** + * Send a 2xx positive final response to this request. Defaults to 200. + * @param options Response options bucket. + */ + accept(options?: ResponseOptions): OutgoingResponse; + /** + * Send a 1xx provisional response to this request. Defaults to 180. Excludes 100. + * Note that per RFC 4320, this method may only be used to respond to INVITE requests. + * @param options Response options bucket. + */ + progress(options?: ResponseOptions): OutgoingResponse; + /** + * Send a 3xx negative final response to this request. Defaults to 302. + * @param contacts Contacts to redirect the UAC to. + * @param options Response options bucket. + */ + redirect(contacts: Array, options?: ResponseOptions): OutgoingResponse; + /** + * Send a 4xx, 5xx, or 6xx negative final response to this request. Defaults to 480. + * @param options Response options bucket. + */ + reject(options?: ResponseOptions): OutgoingResponse; + /** + * Send a 100 outgoing response to this request. + * @param options Response options bucket. + */ + trying(options?: ResponseOptions): OutgoingResponse; +} +/** Delegate providing custom handling of incoming requests. */ +export interface IncomingRequestDelegate { + /** + * Receive CANCEL request. + * https://tools.ietf.org/html/rfc3261#section-9.2 + * Note: Currently CANCEL is being handled as a special case. + * No UAS is created to handle the CANCEL and the response to + * it CANCEL is being handled statelessly by the user agent core. + * As such, there is currently no way to externally impact the + * response to the a CANCEL request and thus the method here is + * receiving a "message" (as apposed to a "uas"). + * @param message Incoming CANCEL request message. + */ + onCancel?(message: IncomingRequestMessage): void; + /** + * A transport error occurred attempted to send a response. + * @param error Transport error. + */ + onTransportError?(error: Exceptions.TransportError): void; +} diff --git a/lib/Core/messages/incoming-request.js b/lib/Core/messages/incoming-request.js new file mode 100644 index 000000000..c8ad2e549 --- /dev/null +++ b/lib/Core/messages/incoming-request.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/Core/messages/incoming-response.d.ts b/lib/Core/messages/incoming-response.d.ts new file mode 100644 index 000000000..da56af701 --- /dev/null +++ b/lib/Core/messages/incoming-response.d.ts @@ -0,0 +1,11 @@ +import { IncomingResponse as IncomingResponseMessage } from "../../SIPMessage"; +/** + * A SIP message sent from a remote server to a local client, + * for indicating the status of a request sent from the + * client to the server. + * https://tools.ietf.org/html/rfc3261#section-7.2 + */ +export interface IncomingResponse { + /** The incoming message. */ + readonly message: IncomingResponseMessage; +} diff --git a/lib/Core/messages/incoming-response.js b/lib/Core/messages/incoming-response.js new file mode 100644 index 000000000..c8ad2e549 --- /dev/null +++ b/lib/Core/messages/incoming-response.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/Core/messages/index.d.ts b/lib/Core/messages/index.d.ts new file mode 100644 index 000000000..8fe81f3f1 --- /dev/null +++ b/lib/Core/messages/index.d.ts @@ -0,0 +1,6 @@ +export * from "./methods"; +export * from "./body"; +export * from "./incoming-request"; +export * from "./incoming-response"; +export * from "./outgoing-request"; +export * from "./outgoing-response"; diff --git a/lib/Core/messages/index.js b/lib/Core/messages/index.js new file mode 100644 index 000000000..1b76ef610 --- /dev/null +++ b/lib/Core/messages/index.js @@ -0,0 +1,7 @@ +"use strict"; +function __export(m) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; +} +Object.defineProperty(exports, "__esModule", { value: true }); +__export(require("./body")); +__export(require("./outgoing-response")); diff --git a/lib/Core/messages/methods/ack.d.ts b/lib/Core/messages/methods/ack.d.ts new file mode 100644 index 000000000..e2b633d15 --- /dev/null +++ b/lib/Core/messages/methods/ack.d.ts @@ -0,0 +1,11 @@ +import { IncomingRequest as IncomingRequestMessage, OutgoingRequest as OutgoingRequestMessage } from "../../../SIPMessage"; +/** ACK message sent from remote client to local server. */ +export interface IncomingAckRequest { + /** The incoming message. */ + readonly message: IncomingRequestMessage; +} +/** ACK message sent from local client to remote server. */ +export interface OutgoingAckRequest { + /** The outgoing message. */ + readonly message: OutgoingRequestMessage; +} diff --git a/lib/Core/messages/methods/ack.js b/lib/Core/messages/methods/ack.js new file mode 100644 index 000000000..c8ad2e549 --- /dev/null +++ b/lib/Core/messages/methods/ack.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/Core/messages/methods/bye.d.ts b/lib/Core/messages/methods/bye.d.ts new file mode 100644 index 000000000..bac866b66 --- /dev/null +++ b/lib/Core/messages/methods/bye.d.ts @@ -0,0 +1,9 @@ +import { IncomingRequest } from "../incoming-request"; +import { IncomingResponse } from "../incoming-response"; +import { OutgoingRequest } from "../outgoing-request"; +export interface IncomingByeRequest extends IncomingRequest { +} +export interface IncomingByeResponse extends IncomingResponse { +} +export interface OutgoingByeRequest extends OutgoingRequest { +} diff --git a/lib/Core/messages/methods/bye.js b/lib/Core/messages/methods/bye.js new file mode 100644 index 000000000..c8ad2e549 --- /dev/null +++ b/lib/Core/messages/methods/bye.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/Core/messages/methods/cancel.d.ts b/lib/Core/messages/methods/cancel.d.ts new file mode 100644 index 000000000..d7965a204 --- /dev/null +++ b/lib/Core/messages/methods/cancel.d.ts @@ -0,0 +1,9 @@ +import { IncomingRequest } from "../incoming-request"; +import { IncomingResponse } from "../incoming-response"; +import { OutgoingRequest } from "../outgoing-request"; +export interface IncomingCancelRequest extends IncomingRequest { +} +export interface IncomingCancelResponse extends IncomingResponse { +} +export interface OutgoingCancelRequest extends OutgoingRequest { +} diff --git a/lib/Core/messages/methods/cancel.js b/lib/Core/messages/methods/cancel.js new file mode 100644 index 000000000..c8ad2e549 --- /dev/null +++ b/lib/Core/messages/methods/cancel.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/Core/messages/methods/index.d.ts b/lib/Core/messages/methods/index.d.ts new file mode 100644 index 000000000..0f8cf428c --- /dev/null +++ b/lib/Core/messages/methods/index.d.ts @@ -0,0 +1,12 @@ +export * from "./ack"; +export * from "./bye"; +export * from "./cancel"; +export * from "./info"; +export * from "./invite"; +export * from "./message"; +export * from "./notify"; +export * from "./prack"; +export * from "./publish"; +export * from "./register"; +export * from "./refer"; +export * from "./subscribe"; diff --git a/lib/Core/messages/methods/index.js b/lib/Core/messages/methods/index.js new file mode 100644 index 000000000..c8ad2e549 --- /dev/null +++ b/lib/Core/messages/methods/index.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/Core/messages/methods/info.d.ts b/lib/Core/messages/methods/info.d.ts new file mode 100644 index 000000000..0aed392b7 --- /dev/null +++ b/lib/Core/messages/methods/info.d.ts @@ -0,0 +1,9 @@ +import { IncomingRequest } from "../incoming-request"; +import { IncomingResponse } from "../incoming-response"; +import { OutgoingRequest } from "../outgoing-request"; +export interface IncomingInfoRequest extends IncomingRequest { +} +export interface IncomingInfoResponse extends IncomingResponse { +} +export interface OutgoingInfoRequest extends OutgoingRequest { +} diff --git a/lib/Core/messages/methods/info.js b/lib/Core/messages/methods/info.js new file mode 100644 index 000000000..c8ad2e549 --- /dev/null +++ b/lib/Core/messages/methods/info.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/Core/messages/methods/invite.d.ts b/lib/Core/messages/methods/invite.d.ts new file mode 100644 index 000000000..e57ec0f6d --- /dev/null +++ b/lib/Core/messages/methods/invite.d.ts @@ -0,0 +1,70 @@ +import { Session } from "../../session"; +import { IncomingRequest } from "../incoming-request"; +import { IncomingResponse } from "../incoming-response"; +import { OutgoingRequest, OutgoingRequestDelegate, RequestOptions } from "../outgoing-request"; +import { OutgoingResponse, ResponseOptions } from "../outgoing-response"; +import { OutgoingAckRequest } from "./ack"; +import { OutgoingPrackRequest } from "./prack"; +/** INVITE message sent from remote client to local server. */ +export interface IncomingInviteRequest extends IncomingRequest { + /** + * Send a 2xx positive final response to this request. Defaults to 200. + * @param options Response options bucket. + * @returns Outgoing response and a confirmed Session. + */ + accept(options?: ResponseOptions): OutgoingResponseWithSession; + /** + * Send a 1xx provisional response to this request. Defaults to 180. Excludes 100. + * @param options Response options bucket. + * @returns Outgoing response and an early Session. + */ + progress(options?: ResponseOptions): OutgoingResponseWithSession; +} +/** Response received when accepting an incoming INVITE request. */ +export interface OutgoingResponseWithSession extends OutgoingResponse { + /** Session associated with incoming request acceptance. */ + readonly session: Session; +} +/** Response received when progressing an incoming INVITE request. */ +export interface OutgoingResponseWithSession extends OutgoingResponse { + /** Session associated with incoming request progress. If out of dialog request, an early dialog. */ + readonly session: Session; +} +/** INVITE message sent from local client to remote server. */ +export interface OutgoingInviteRequest extends OutgoingRequest { + /** Delegate providing custom handling of this outgoing INVITE request. */ + delegate?: OutgoingInviteRequestDelegate; +} +/** Delegate providing custom handling of outgoing INVITE requests. */ +export interface OutgoingInviteRequestDelegate extends OutgoingRequestDelegate { + /** + * Received a 2xx positive final response to this request. + * @param response Incoming response (including a confirmed Session). + */ + onAccept?(response: AckableIncomingResponseWithSession): void; + /** + * Received a 1xx provisional response to this request. Excluding 100 responses. + * @param response Incoming response (including an early Session). + */ + onProgress?(response: PrackableIncomingResponseWithSession): void; +} +/** Response received when an outgoing INVITE request is accepted. */ +export interface AckableIncomingResponseWithSession extends IncomingResponse { + /** Session associated with outgoing request acceptance. */ + readonly session: Session; + /** + * Send an ACK to acknowledge this response. + * @param options Request options bucket. + */ + ack(options?: RequestOptions): OutgoingAckRequest; +} +/** Response received when an outgoing INVITE request is progressed. */ +export interface PrackableIncomingResponseWithSession extends IncomingResponse { + /** Session associated with outgoing request progress. If out of dialog request, an early dialog. */ + readonly session: Session; + /** + * Send an PRACK to acknowledge this response. + * @param options Request options bucket. + */ + prack(options?: RequestOptions): OutgoingPrackRequest; +} diff --git a/lib/Core/messages/methods/invite.js b/lib/Core/messages/methods/invite.js new file mode 100644 index 000000000..c8ad2e549 --- /dev/null +++ b/lib/Core/messages/methods/invite.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/Core/messages/methods/message.d.ts b/lib/Core/messages/methods/message.d.ts new file mode 100644 index 000000000..5965fd57f --- /dev/null +++ b/lib/Core/messages/methods/message.d.ts @@ -0,0 +1,9 @@ +import { IncomingRequest } from "../incoming-request"; +import { IncomingResponse } from "../incoming-response"; +import { OutgoingRequest } from "../outgoing-request"; +export interface IncomingMessageRequest extends IncomingRequest { +} +export interface IncomingMessageResponse extends IncomingResponse { +} +export interface OutgoingMessageRequest extends OutgoingRequest { +} diff --git a/lib/Core/messages/methods/message.js b/lib/Core/messages/methods/message.js new file mode 100644 index 000000000..c8ad2e549 --- /dev/null +++ b/lib/Core/messages/methods/message.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/Core/messages/methods/notify.d.ts b/lib/Core/messages/methods/notify.d.ts new file mode 100644 index 000000000..cd25b4980 --- /dev/null +++ b/lib/Core/messages/methods/notify.d.ts @@ -0,0 +1,9 @@ +import { IncomingRequest } from "../incoming-request"; +import { IncomingResponse } from "../incoming-response"; +import { OutgoingRequest } from "../outgoing-request"; +export interface IncomingNotifyRequest extends IncomingRequest { +} +export interface IncomingNotifyResponse extends IncomingResponse { +} +export interface OutgoingNotifyRequest extends OutgoingRequest { +} diff --git a/lib/Core/messages/methods/notify.js b/lib/Core/messages/methods/notify.js new file mode 100644 index 000000000..c8ad2e549 --- /dev/null +++ b/lib/Core/messages/methods/notify.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/Core/messages/methods/prack.d.ts b/lib/Core/messages/methods/prack.d.ts new file mode 100644 index 000000000..e87dbb190 --- /dev/null +++ b/lib/Core/messages/methods/prack.d.ts @@ -0,0 +1,9 @@ +import { IncomingRequest } from "../incoming-request"; +import { IncomingResponse } from "../incoming-response"; +import { OutgoingRequest } from "../outgoing-request"; +export interface IncomingPrackRequest extends IncomingRequest { +} +export interface IncomingPrackResponse extends IncomingResponse { +} +export interface OutgoingPrackRequest extends OutgoingRequest { +} diff --git a/lib/Core/messages/methods/prack.js b/lib/Core/messages/methods/prack.js new file mode 100644 index 000000000..c8ad2e549 --- /dev/null +++ b/lib/Core/messages/methods/prack.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/Core/messages/methods/publish.d.ts b/lib/Core/messages/methods/publish.d.ts new file mode 100644 index 000000000..9a115746b --- /dev/null +++ b/lib/Core/messages/methods/publish.d.ts @@ -0,0 +1,9 @@ +import { IncomingRequest } from "../incoming-request"; +import { IncomingResponse } from "../incoming-response"; +import { OutgoingRequest } from "../outgoing-request"; +export interface IncomingPublishRequest extends IncomingRequest { +} +export interface IncomingPublishResponse extends IncomingResponse { +} +export interface OutgoingPublishRequest extends OutgoingRequest { +} diff --git a/lib/Core/messages/methods/publish.js b/lib/Core/messages/methods/publish.js new file mode 100644 index 000000000..c8ad2e549 --- /dev/null +++ b/lib/Core/messages/methods/publish.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/Core/messages/methods/refer.d.ts b/lib/Core/messages/methods/refer.d.ts new file mode 100644 index 000000000..51ad80664 --- /dev/null +++ b/lib/Core/messages/methods/refer.d.ts @@ -0,0 +1,9 @@ +import { IncomingRequest } from "../incoming-request"; +import { IncomingResponse } from "../incoming-response"; +import { OutgoingRequest } from "../outgoing-request"; +export interface IncomingReferRequest extends IncomingRequest { +} +export interface IncomingReferResponse extends IncomingResponse { +} +export interface OutgoingReferRequest extends OutgoingRequest { +} diff --git a/lib/Core/messages/methods/refer.js b/lib/Core/messages/methods/refer.js new file mode 100644 index 000000000..c8ad2e549 --- /dev/null +++ b/lib/Core/messages/methods/refer.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/Core/messages/methods/register.d.ts b/lib/Core/messages/methods/register.d.ts new file mode 100644 index 000000000..5f2cf6924 --- /dev/null +++ b/lib/Core/messages/methods/register.d.ts @@ -0,0 +1,9 @@ +import { IncomingRequest } from "../incoming-request"; +import { IncomingResponse } from "../incoming-response"; +import { OutgoingRequest } from "../outgoing-request"; +export interface IncomingRegisterRequest extends IncomingRequest { +} +export interface IncomingRegisterResponse extends IncomingResponse { +} +export interface OutgoingRegisterRequest extends OutgoingRequest { +} diff --git a/lib/Core/messages/methods/register.js b/lib/Core/messages/methods/register.js new file mode 100644 index 000000000..c8ad2e549 --- /dev/null +++ b/lib/Core/messages/methods/register.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/Core/messages/methods/subscribe.d.ts b/lib/Core/messages/methods/subscribe.d.ts new file mode 100644 index 000000000..410ecfe3c --- /dev/null +++ b/lib/Core/messages/methods/subscribe.d.ts @@ -0,0 +1,36 @@ +import { Subscription } from "../../subscription"; +import { IncomingRequest } from "../incoming-request"; +import { IncomingResponse } from "../incoming-response"; +import { OutgoingRequest, OutgoingRequestDelegate } from "../outgoing-request"; +import { IncomingNotifyRequest } from "./notify"; +export interface IncomingSubscribeRequest extends IncomingRequest { +} +export interface IncomingSubscribeResponse extends IncomingResponse { +} +/** SUBSCRIBE message sent from local client to remote server. */ +export interface OutgoingSubscribeRequest extends OutgoingRequest { + /** Delegate providing custom handling of this outgoing SUBSCRIBE request. */ + delegate?: OutgoingSubscribeRequestDelegate; + /** Stop waiting for an inital subscription creating NOTIFY. */ + waitNotifyStop(): void; +} +/** Delegate providing custom handling of outgoing SUBSCRIBE requests. */ +export interface OutgoingSubscribeRequestDelegate extends OutgoingRequestDelegate { + /** + * Received the initial subscription creating NOTIFY in response to this request. + * Called for out of dialog SUBSCRIBE requests only (not called for re-SUBSCRIBE requests). + * @param request Incoming NOTIFY request (including a Subscription). + */ + onNotify?(request: IncomingRequestWithSubscription): void; + /** + * Timed out waiting to receive the initial subscription creating NOTIFY in response to this request. + * Called for out of dialog SUBSCRIBE requests only (not called for re-SUBSCRIBE requests). + */ + onNotifyTimeout?(): void; +} +export interface IncomingRequestWithSubscription { + /** The NOTIFY request which established the subscription. */ + readonly request: IncomingNotifyRequest; + /** If subscription state is not "terminated", then the subscription. Otherwise undefined. */ + readonly subscription?: Subscription; +} diff --git a/lib/Core/messages/methods/subscribe.js b/lib/Core/messages/methods/subscribe.js new file mode 100644 index 000000000..c8ad2e549 --- /dev/null +++ b/lib/Core/messages/methods/subscribe.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/Core/messages/outgoing-request.d.ts b/lib/Core/messages/outgoing-request.d.ts new file mode 100644 index 000000000..aabc6406c --- /dev/null +++ b/lib/Core/messages/outgoing-request.d.ts @@ -0,0 +1,59 @@ +import { OutgoingRequest as OutgoingRequestMessage } from "../../SIPMessage"; +import { Body } from "./body"; +import { IncomingResponse } from "./incoming-response"; +/** + * A SIP message sent from a local client to a remote server, + * for the purpose of invoking a particular operation. + * https://tools.ietf.org/html/rfc3261#section-7.1 + */ +export interface OutgoingRequest { + /** Delegate providing custom handling of this outgoing request. */ + delegate?: OutgoingRequestDelegate; + /** The outgoing message. */ + readonly message: OutgoingRequestMessage; + /** + * Destroy request. + */ + dispose(): void; + /** + * Sends a CANCEL message targeting this request to the UAS. + * @param reason Reason for canceling request. + * @param options Request options bucket. + */ + cancel(reason?: string, options?: RequestOptions): void; +} +/** Delegate providing custom handling of outgoing requests. */ +export interface OutgoingRequestDelegate { + /** + * Received a 2xx positive final response to this request. + * @param response Incoming response. + */ + onAccept?(response: IncomingResponse): void; + /** + * Received a 1xx provisional response to this request. Excluding 100 responses. + * @param response Incoming response. + */ + onProgress?(response: IncomingResponse): void; + /** + * Received a 3xx negative final response to this request. + * @param response Incoming response. + */ + onRedirect?(response: IncomingResponse): void; + /** + * Received a 4xx, 5xx, or 6xx negative final response to this request. + * @param response Incoming response. + */ + onReject?(response: IncomingResponse): void; + /** + * Received a 100 provisional response. + * @param response Incoming response. + */ + onTrying?(response: IncomingResponse): void; +} +/** Request options bucket. */ +export interface RequestOptions { + /** Extra headers to include in the message. */ + extraHeaders?: Array; + /** Body to include in the message. */ + body?: Body; +} diff --git a/lib/Core/messages/outgoing-request.js b/lib/Core/messages/outgoing-request.js new file mode 100644 index 000000000..c8ad2e549 --- /dev/null +++ b/lib/Core/messages/outgoing-request.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/Core/messages/outgoing-response.d.ts b/lib/Core/messages/outgoing-response.d.ts new file mode 100644 index 000000000..edad1ec08 --- /dev/null +++ b/lib/Core/messages/outgoing-response.d.ts @@ -0,0 +1,35 @@ +import { IncomingRequest as IncomingRequestMessage } from "../../SIPMessage"; +import { Body } from "./body"; +/** + * A SIP message sent from a local server to a remote client, + * for indicating the status of a request sent from the + * client to the server. + * https://tools.ietf.org/html/rfc3261#section-7.2 + */ +export interface OutgoingResponse { + /** The outgoing message. */ + readonly message: string; +} +/** Response options bucket. */ +export interface ResponseOptions { + /** Status code of the response. */ + statusCode: number; + /** Reason phrase of the response. */ + reasonPhrase?: string; + /** To tag of the response. If not provided, one is generated. */ + toTag?: string; + /** User agent string for User-Agent header. */ + userAgent?: string; + /** Extra headers to include in the message. */ + extraHeaders?: Array; + /** Body to include in the message. */ + body?: Body; +} +/** + * When a UAS wishes to construct a response to a request, it follows + * the general procedures detailed in the following subsections. + * Additional behaviors specific to the response code in question, which + * are not detailed in this section, may also be required. + * https://tools.ietf.org/html/rfc3261#section-8.2.6 + */ +export declare function constructOutgoingResponse(message: IncomingRequestMessage, options: ResponseOptions): OutgoingResponse; diff --git a/lib/Core/messages/outgoing-response.js b/lib/Core/messages/outgoing-response.js new file mode 100644 index 000000000..1152cb587 --- /dev/null +++ b/lib/Core/messages/outgoing-response.js @@ -0,0 +1,122 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var SIPMessage_1 = require("../../SIPMessage"); +var Utils_1 = require("../../Utils"); +/** + * When a UAS wishes to construct a response to a request, it follows + * the general procedures detailed in the following subsections. + * Additional behaviors specific to the response code in question, which + * are not detailed in this section, may also be required. + * https://tools.ietf.org/html/rfc3261#section-8.2.6 + */ +function constructOutgoingResponse(message, options) { + var CRLF = "\r\n"; + // SIP responses are distinguished from requests by having a Status-Line + // as their start-line. A Status-Line consists of the protocol version + // followed by a numeric Status-Code and its associated textual phrase, + // with each element separated by a single SP character. + // https://tools.ietf.org/html/rfc3261#section-7.2 + var response = Utils_1.Utils.buildStatusLine(options.statusCode, options.reasonPhrase); + // One largely non-method-specific guideline for the generation of + // responses is that UASs SHOULD NOT issue a provisional response for a + // non-INVITE request. Rather, UASs SHOULD generate a final response to + // a non-INVITE request as soon as possible. + // https://tools.ietf.org/html/rfc3261#section-8.2.6.1 + if (options.statusCode >= 100 && options.statusCode < 200) { + // TODO + } + // When a 100 (Trying) response is generated, any Timestamp header field + // present in the request MUST be copied into this 100 (Trying) + // response. If there is a delay in generating the response, the UAS + // SHOULD add a delay value into the Timestamp value in the response. + // This value MUST contain the difference between the time of sending of + // the response and receipt of the request, measured in seconds. + // https://tools.ietf.org/html/rfc3261#section-8.2.6.1 + if (options.statusCode === 100) { + // TODO + } + // The From field of the response MUST equal the From header field of + // the request. The Call-ID header field of the response MUST equal the + // Call-ID header field of the request. The CSeq header field of the + // response MUST equal the CSeq field of the request. The Via header + // field values in the response MUST equal the Via header field values + // in the request and MUST maintain the same ordering. + // https://tools.ietf.org/html/rfc3261#section-8.2.6.2 + var fromHeader = "From: " + message.getHeader("From") + CRLF; + var callIdHeader = "Call-ID: " + message.callId + CRLF; + var cSeqHeader = "CSeq: " + message.cseq + " " + message.method + CRLF; + var viaHeaders = message.getHeaders("via").reduce(function (previous, current) { + return previous + "Via: " + current + CRLF; + }, ""); + // If a request contained a To tag in the request, the To header field + // in the response MUST equal that of the request. However, if the To + // header field in the request did not contain a tag, the URI in the To + // header field in the response MUST equal the URI in the To header + // field; additionally, the UAS MUST add a tag to the To header field in + // the response (with the exception of the 100 (Trying) response, in + // which a tag MAY be present). This serves to identify the UAS that is + // responding, possibly resulting in a component of a dialog ID. The + // same tag MUST be used for all responses to that request, both final + // and provisional (again excepting the 100 (Trying)). + // https://tools.ietf.org/html/rfc3261#section-8.2.6.2 + var toHeader = "To: " + message.getHeader("to"); + if (options.statusCode > 100 && !message.parseHeader("to").hasParam("tag")) { + var toTag = options.toTag; + if (!toTag) { + // Stateless UAS Behavior... + // o To header tags MUST be generated for responses in a stateless + // manner - in a manner that will generate the same tag for the + // same request consistently. For information on tag construction + // see Section 19.3. + // https://tools.ietf.org/html/rfc3261#section-8.2.7 + toTag = Utils_1.Utils.newTag(); // FIXME: Utils.newTag() currently generates random tags + } + toHeader += ";tag=" + toTag; + } + toHeader += CRLF; + // FIXME: TODO: needs review... moved to InviteUserAgentServer (as it is specific to that) + // let recordRouteHeaders = ""; + // if (request.method === C.INVITE && statusCode > 100 && statusCode <= 200) { + // recordRouteHeaders = request.getHeaders("record-route").reduce((previous, current) => { + // return previous + "Record-Route: " + current + CRLF; + // }, ""); + // } + // FIXME: TODO: needs review... + var supportedHeader = SIPMessage_1.getSupportedHeader(message); + // FIXME: TODO: needs review... + var userAgentHeader = ""; + if (options.userAgent) { + userAgentHeader = "User-Agent: " + options.userAgent + CRLF; + } + var extensionHeaders = ""; + if (options.extraHeaders) { + extensionHeaders = options.extraHeaders.reduce(function (previous, current) { + return previous + current.trim() + CRLF; + }, ""); + } + // The relative order of header fields with different field names is not + // significant. However, it is RECOMMENDED that header fields which are + // needed for proxy processing (Via, Route, Record-Route, Proxy-Require, + // Max-Forwards, and Proxy-Authorization, for example) appear towards + // the top of the message to facilitate rapid parsing. + // https://tools.ietf.org/html/rfc3261#section-7.3.1 + // response += recordRouteHeaders; + response += viaHeaders; + response += fromHeader; + response += toHeader; + response += cSeqHeader; + response += callIdHeader; + response += supportedHeader; + response += userAgentHeader; + response += extensionHeaders; + if (options.body) { + response += "Content-Type: " + options.body.contentType + CRLF; + response += "Content-Length: " + Utils_1.Utils.str_utf8_length(options.body.content) + CRLF + CRLF; + response += options.body.content; + } + else { + response += "Content-Length: " + 0 + CRLF + CRLF; + } + return { message: response }; +} +exports.constructOutgoingResponse = constructOutgoingResponse; diff --git a/lib/Core/session/index.d.ts b/lib/Core/session/index.d.ts new file mode 100644 index 000000000..765f8ba7f --- /dev/null +++ b/lib/Core/session/index.d.ts @@ -0,0 +1,2 @@ +export * from "./session"; +export * from "./session-delegate"; diff --git a/lib/Core/session/index.js b/lib/Core/session/index.js new file mode 100644 index 000000000..331a62e14 --- /dev/null +++ b/lib/Core/session/index.js @@ -0,0 +1,6 @@ +"use strict"; +function __export(m) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; +} +Object.defineProperty(exports, "__esModule", { value: true }); +__export(require("./session")); diff --git a/lib/Core/session/session-delegate.d.ts b/lib/Core/session/session-delegate.d.ts new file mode 100644 index 000000000..8ba981c8e --- /dev/null +++ b/lib/Core/session/session-delegate.d.ts @@ -0,0 +1,49 @@ +import { IncomingAckRequest, IncomingByeRequest, IncomingInfoRequest, IncomingInviteRequest, IncomingNotifyRequest, IncomingPrackRequest, IncomingReferRequest } from "../messages"; +export interface SessionDelegate { + /** + * Receive ACK request. + * @param request Incoming ACK request. + */ + onAck?(request: IncomingAckRequest): void; + /** + * Timeout waiting for ACK request. + * If no handler is provided the Session will terminated with a BYE. + * https://tools.ietf.org/html/rfc3261#section-13.3.1.4 + */ + onAckTimeout?(): void; + /** + * Receive BYE request. + * https://tools.ietf.org/html/rfc3261#section-15.1.2 + * @param request Incoming BYE request. + */ + onBye?(request: IncomingByeRequest): void; + /** + * Receive INFO request. + * @param request Incoming INFO request. + */ + onInfo?(request: IncomingInfoRequest): void; + /** + * Receive re-INVITE request. + * https://tools.ietf.org/html/rfc3261#section-14.2 + * @param request Incoming INVITE request. + */ + onInvite?(request: IncomingInviteRequest): void; + /** + * Receive NOTIFY request. + * https://tools.ietf.org/html/rfc6665#section-4.1.3 + * @param request Incoming NOTIFY request. + */ + onNotify?(request: IncomingNotifyRequest): void; + /** + * Receive PRACK request. + * https://tools.ietf.org/html/rfc3262#section-3 + * @param request Incoming PRACK request. + */ + onPrack?(request: IncomingPrackRequest): void; + /** + * Receive REFER request. + * https://tools.ietf.org/html/rfc3515#section-2.4.2 + * @param request Incoming REFER request. + */ + onRefer?(request: IncomingReferRequest): void; +} diff --git a/lib/Core/session/session-delegate.js b/lib/Core/session/session-delegate.js new file mode 100644 index 000000000..c8ad2e549 --- /dev/null +++ b/lib/Core/session/session-delegate.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/Core/session/session.d.ts b/lib/Core/session/session.d.ts new file mode 100644 index 000000000..2389e9afe --- /dev/null +++ b/lib/Core/session/session.d.ts @@ -0,0 +1,132 @@ +import { URI } from "../../URI"; +import { Body, OutgoingByeRequest, OutgoingInfoRequest, OutgoingInviteRequest, OutgoingInviteRequestDelegate, OutgoingNotifyRequest, OutgoingPrackRequest, OutgoingReferRequest, OutgoingRequestDelegate, RequestOptions } from "../messages"; +import { SessionDelegate } from "./session-delegate"; +/** + * https://tools.ietf.org/html/rfc3261#section-13 + */ +export interface Session { + /** Session delegate. */ + delegate: SessionDelegate | undefined; + /** The session id. Equal to callId + localTag + remoteTag. */ + readonly id: string; + /** Call Id. */ + readonly callId: string; + /** Local Tag. */ + readonly localTag: string; + /** Local URI. */ + readonly localURI: URI; + /** Remote Tag. */ + readonly remoteTag: string; + /** Remote Target. */ + readonly remoteTarget: URI; + /** Remote URI. */ + readonly remoteURI: URI; + /** Session state. */ + readonly sessionState: SessionState; + /** Current state of the offer/answer exchange. */ + readonly signalingState: SignalingState; + /** The current answer if signalingState is stable. Otherwise undefined. */ + readonly answer: Body | undefined; + /** The current offer if signalingState is not initial or closed. Otherwise undefined. */ + readonly offer: Body | undefined; + /** + * Destroy session. + */ + dispose(): void; + /** + * Send a BYE request. + * Terminating a session. + * https://tools.ietf.org/html/rfc3261#section-15 + * @param delegate Request delegate. + * @param options Options bucket. + * @returns A promise which resolves when a 2xx response to the BYE is received. + * @throws {RequestFailedReason} If a non-2xx final response to the BYE is received. + */ + bye(delegate?: OutgoingRequestDelegate, options?: RequestOptions): OutgoingByeRequest; + /** + * Send an INFO request. + * Exchange information during a session. + * https://tools.ietf.org/html/rfc6086#section-4.2.1 + * @param delegate Request delegate. + * @param options Options bucket. + * @returns A promise which resolves when a 2xx response to the BYE is received. + * @throws {RequestFailedReason} If a non-2xx final response to the BYE is received. + */ + info(delegate?: OutgoingRequestDelegate, options?: RequestOptions): OutgoingInfoRequest; + /** + * Send re-INVITE request. + * Modifying a session. + * https://tools.ietf.org/html/rfc3261#section-14.1 + * @param delegate Request delegate. + * @param options Options bucket. + * @returns A promise which resolves when a 2xx response to the INVITE is received. + * @throws {PendingRequestError} If there is a re-invite "pending". + * @throws {RequestFailedReason} If a non-2xx final response to the INVITE is received. + */ + invite(delegate?: OutgoingInviteRequestDelegate, options?: RequestOptions): OutgoingInviteRequest; + /** + * Send NOTIFY request. + * Inform referrer of transfer progress. + * The use of this is limited to the implicit creation of subscription by REFER (historical). + * Otherwise, notifiers MUST NOT create subscriptions except upon receipt of a SUBSCRIBE request. + * https://tools.ietf.org/html/rfc3515#section-3.7 + * @param delegate Request delegate. + * @param options Options bucket. + * @returns A promise which resolves when a 2xx response to the NOTIFY is received. + * @throws {RequestFailedReason} If a non-2xx final response to the NOTIFY is received. + */ + notify(delegate?: OutgoingRequestDelegate, options?: RequestOptions): OutgoingNotifyRequest; + /** + * Send PRACK request. + * Acknowledge a reliable provisional response. + * https://tools.ietf.org/html/rfc3262#section-4 + * @param delegate Request delegate. + * @param options Options bucket. + * @returns A promise which resolves when a 2xx response to the PRACK is received. + * @throws {RequestFailedReason} If a non-2xx final response to the PRACK is received. + */ + prack(delegate?: OutgoingRequestDelegate, options?: RequestOptions): OutgoingPrackRequest; + /** + * Send REFER request (in dialog). + * Transfer a session. + * https://tools.ietf.org/html/rfc3515#section-2.4.1 + * @param delegate Request delegate. + * @param options Options bucket. + * @returns A promise which resolves when a 2xx response to the REFER is received. + * @throws {RequestFailedReason} If a non-2xx final response to the REFER is received. + */ + refer(delegate?: OutgoingRequestDelegate, options?: RequestOptions): OutgoingReferRequest; +} +/** + * Session state. + * https://tools.ietf.org/html/rfc3261#section-13 + */ +export declare enum SessionState { + Initial = "Initial", + Early = "Early", + AckWait = "AckWait", + Confirmed = "Confirmed", + Terminated = "Terminated" +} +/** + * Offer/Answer State + * + * Offer Answer RFC Ini Est Early + * ------------------------------------------------------------------- + * 1. INVITE Req. 2xx INVITE Resp. RFC 3261 Y Y N + * 2. 2xx INVITE Resp. ACK Req. RFC 3261 Y Y N + * 3. INVITE Req. 1xx-rel INVITE Resp. RFC 3262 Y Y N + * 4. 1xx-rel INVITE Resp. PRACK Req. RFC 3262 Y Y N + * 5. PRACK Req. 200 PRACK Resp. RFC 3262 N Y Y + * 6. UPDATE Req. 2xx UPDATE Resp. RFC 3311 N Y Y + * + * Table 1: Summary of SIP Usage of the Offer/Answer Model + * https://tools.ietf.org/html/rfc6337#section-2.2 + */ +export declare enum SignalingState { + Initial = "Initial", + HaveLocalOffer = "HaveLocalOffer", + HaveRemoteOffer = "HaveRemoteOffer", + Stable = "Stable", + Closed = "Closed" +} diff --git a/lib/Core/session/session.js b/lib/Core/session/session.js new file mode 100644 index 000000000..87293f7c8 --- /dev/null +++ b/lib/Core/session/session.js @@ -0,0 +1,37 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +/** + * Session state. + * https://tools.ietf.org/html/rfc3261#section-13 + */ +var SessionState; +(function (SessionState) { + SessionState["Initial"] = "Initial"; + SessionState["Early"] = "Early"; + SessionState["AckWait"] = "AckWait"; + SessionState["Confirmed"] = "Confirmed"; + SessionState["Terminated"] = "Terminated"; +})(SessionState = exports.SessionState || (exports.SessionState = {})); +/** + * Offer/Answer State + * + * Offer Answer RFC Ini Est Early + * ------------------------------------------------------------------- + * 1. INVITE Req. 2xx INVITE Resp. RFC 3261 Y Y N + * 2. 2xx INVITE Resp. ACK Req. RFC 3261 Y Y N + * 3. INVITE Req. 1xx-rel INVITE Resp. RFC 3262 Y Y N + * 4. 1xx-rel INVITE Resp. PRACK Req. RFC 3262 Y Y N + * 5. PRACK Req. 200 PRACK Resp. RFC 3262 N Y Y + * 6. UPDATE Req. 2xx UPDATE Resp. RFC 3311 N Y Y + * + * Table 1: Summary of SIP Usage of the Offer/Answer Model + * https://tools.ietf.org/html/rfc6337#section-2.2 + */ +var SignalingState; +(function (SignalingState) { + SignalingState["Initial"] = "Initial"; + SignalingState["HaveLocalOffer"] = "HaveLocalOffer"; + SignalingState["HaveRemoteOffer"] = "HaveRemoteOffer"; + SignalingState["Stable"] = "Stable"; + SignalingState["Closed"] = "Closed"; +})(SignalingState = exports.SignalingState || (exports.SignalingState = {})); diff --git a/lib/Core/subscription/index.d.ts b/lib/Core/subscription/index.d.ts new file mode 100644 index 000000000..28f539cf8 --- /dev/null +++ b/lib/Core/subscription/index.d.ts @@ -0,0 +1,2 @@ +export * from "./subscription"; +export * from "./subscription-delegate"; diff --git a/lib/Core/subscription/index.js b/lib/Core/subscription/index.js new file mode 100644 index 000000000..e138f9122 --- /dev/null +++ b/lib/Core/subscription/index.js @@ -0,0 +1,6 @@ +"use strict"; +function __export(m) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; +} +Object.defineProperty(exports, "__esModule", { value: true }); +__export(require("./subscription")); diff --git a/lib/Core/subscription/subscription-delegate.d.ts b/lib/Core/subscription/subscription-delegate.d.ts new file mode 100644 index 000000000..24f8bda83 --- /dev/null +++ b/lib/Core/subscription/subscription-delegate.d.ts @@ -0,0 +1,23 @@ +import { IncomingNotifyRequest, OutgoingSubscribeRequest } from "../messages"; +export interface SubscriptionDelegate { + /** + * Receive NOTIFY request. This includes in dialog NOTIFY requests only. + * Thus the first NOTIFY (the subscription creating NOTIFY) will not be provided. + * https://tools.ietf.org/html/rfc6665#section-4.1.3 + * @param request Incoming NOTIFY request. + */ + onNotify?(request: IncomingNotifyRequest): void; + /** + * Sent a SUBSCRIBE request. This includes "auto refresh" in dialog SUBSCRIBE requests only. + * Thus SUBSCRIBE requests triggered by calls to `refresh()` or `subscribe()` will not be provided. + * Thus the first SUBSCRIBE (the subscription creating SUBSCRIBE) will not be provided. + * @param request Outgoing SUBSCRIBE request. + */ + onRefresh?(request: OutgoingSubscribeRequest): void; + /** + * Subscription termination. This includes non-NOTIFY termination causes only. + * Thus this will not be called if a NOTIFY is the cause of termination. + * https://tools.ietf.org/html/rfc6665#section-4.4.1 + */ + onTerminated?(): void; +} diff --git a/lib/Core/subscription/subscription-delegate.js b/lib/Core/subscription/subscription-delegate.js new file mode 100644 index 000000000..c8ad2e549 --- /dev/null +++ b/lib/Core/subscription/subscription-delegate.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/Core/subscription/subscription.d.ts b/lib/Core/subscription/subscription.d.ts new file mode 100644 index 000000000..f137a6585 --- /dev/null +++ b/lib/Core/subscription/subscription.d.ts @@ -0,0 +1,50 @@ +import { OutgoingSubscribeRequest, OutgoingSubscribeRequestDelegate, RequestOptions } from "../messages"; +import { SubscriptionDelegate } from "./subscription-delegate"; +/** + * https://tools.ietf.org/html/rfc6665 + */ +export interface Subscription { + /** Subscription delegate. */ + delegate: SubscriptionDelegate | undefined; + /** The subscription id. */ + readonly id: string; + /** Subscription expires. Number of seconds until the subscription expires. */ + readonly subscriptionExpires: number; + /** Subscription state. */ + readonly subscriptionState: SubscriptionState; + /** If true, refresh subscription prior to expiration. Default is false. */ + autoRefresh: boolean; + /** + * Destroy subscription. + */ + dispose(): void; + /** + * Send re-SUBSCRIBE request. + * Refreshing a subscription and unsubscribing. + * https://tools.ietf.org/html/rfc6665#section-4.1.2.2 + * @param delegate Request delegate. + * @param options Options bucket + */ + subscribe(delegate?: OutgoingSubscribeRequestDelegate, options?: RequestOptions): OutgoingSubscribeRequest; + /** + * 4.1.2.2. Refreshing of Subscriptions + * https://tools.ietf.org/html/rfc6665#section-4.1.2.2 + */ + refresh(): OutgoingSubscribeRequest; + /** + * 4.1.2.3. Unsubscribing + * https://tools.ietf.org/html/rfc6665#section-4.1.2.3 + */ + unsubscribe(): OutgoingSubscribeRequest; +} +/** + * Subscription state. + * https://tools.ietf.org/html/rfc6665#section-4.1.2 + */ +export declare enum SubscriptionState { + Initial = "Initial", + NotifyWait = "NotifyWait", + Pending = "Pending", + Active = "Active", + Terminated = "Terminated" +} diff --git a/lib/Core/subscription/subscription.js b/lib/Core/subscription/subscription.js new file mode 100644 index 000000000..df01e3fa3 --- /dev/null +++ b/lib/Core/subscription/subscription.js @@ -0,0 +1,14 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +/** + * Subscription state. + * https://tools.ietf.org/html/rfc6665#section-4.1.2 + */ +var SubscriptionState; +(function (SubscriptionState) { + SubscriptionState["Initial"] = "Initial"; + SubscriptionState["NotifyWait"] = "NotifyWait"; + SubscriptionState["Pending"] = "Pending"; + SubscriptionState["Active"] = "Active"; + SubscriptionState["Terminated"] = "Terminated"; +})(SubscriptionState = exports.SubscriptionState || (exports.SubscriptionState = {})); diff --git a/lib/Core/transactions/client-transaction.d.ts b/lib/Core/transactions/client-transaction.d.ts new file mode 100644 index 000000000..b8bf966ff --- /dev/null +++ b/lib/Core/transactions/client-transaction.d.ts @@ -0,0 +1,44 @@ +import { IncomingResponse, OutgoingRequest } from "../../SIPMessage"; +import { Transport } from "../../Transport"; +import { Transaction } from "./transaction"; +import { TransactionState } from "./transaction-state"; +import { ClientTransactionUser } from "./transaction-user"; +/** + * Client Transaction + * + * The client transaction provides its functionality through the + * maintenance of a state machine. + * + * The TU communicates with the client transaction through a simple + * interface. When the TU wishes to initiate a new transaction, it + * creates a client transaction and passes it the SIP request to send + * and an IP address, port, and transport to which to send it. The + * client transaction begins execution of its state machine. Valid + * responses are passed up to the TU from the client transaction. + * https://tools.ietf.org/html/rfc3261#section-17.1 + */ +export declare abstract class ClientTransaction extends Transaction { + private _request; + protected user: ClientTransactionUser; + private static makeId; + protected constructor(_request: OutgoingRequest, transport: Transport, user: ClientTransactionUser, state: TransactionState, loggerCategory: string); + /** The outgoing request the transaction handling. */ + readonly request: OutgoingRequest; + /** + * Receive incoming responses from the transport which match this transaction. + * Responses will be delivered to the transaction user as necessary. + * @param response The incoming response. + */ + abstract receiveResponse(response: IncomingResponse): void; + /** + * A 408 to non-INVITE will always arrive too late to be useful ([3]), + * The client already has full knowledge of the timeout. The only + * information this message would convey is whether or not the server + * believed the transaction timed out. However, with the current design + * of the NIT, a client cannot do anything with this knowledge. Thus, + * the 408 is simply wasting network resources and contributes to the + * response bombardment illustrated in [3]. + * https://tools.ietf.org/html/rfc4320#section-4.1 + */ + protected onRequestTimeout(): void; +} diff --git a/lib/Core/transactions/client-transaction.js b/lib/Core/transactions/client-transaction.js new file mode 100644 index 000000000..594f03bd3 --- /dev/null +++ b/lib/Core/transactions/client-transaction.js @@ -0,0 +1,82 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var transaction_1 = require("./transaction"); +/** + * Client Transaction + * + * The client transaction provides its functionality through the + * maintenance of a state machine. + * + * The TU communicates with the client transaction through a simple + * interface. When the TU wishes to initiate a new transaction, it + * creates a client transaction and passes it the SIP request to send + * and an IP address, port, and transport to which to send it. The + * client transaction begins execution of its state machine. Valid + * responses are passed up to the TU from the client transaction. + * https://tools.ietf.org/html/rfc3261#section-17.1 + */ +var ClientTransaction = /** @class */ (function (_super) { + __extends(ClientTransaction, _super); + function ClientTransaction(_request, transport, user, state, loggerCategory) { + var _this = _super.call(this, transport, user, ClientTransaction.makeId(_request), state, loggerCategory) || this; + _this._request = _request; + _this.user = user; + // The Via header field indicates the transport used for the transaction + // and identifies the location where the response is to be sent. A Via + // header field value is added only after the transport that will be + // used to reach the next hop has been selected (which may involve the + // usage of the procedures in [4]). + // https://tools.ietf.org/html/rfc3261#section-8.1.1.7 + _request.setViaHeader(_this.id, transport); + return _this; + } + ClientTransaction.makeId = function (request) { + if (request.method === "CANCEL") { + if (!request.branch) { + throw new Error("Outgoing CANCEL request without a branch."); + } + return request.branch; + } + else { + return "z9hG4bK" + Math.floor(Math.random() * 10000000); + } + }; + Object.defineProperty(ClientTransaction.prototype, "request", { + /** The outgoing request the transaction handling. */ + get: function () { + return this._request; + }, + enumerable: true, + configurable: true + }); + /** + * A 408 to non-INVITE will always arrive too late to be useful ([3]), + * The client already has full knowledge of the timeout. The only + * information this message would convey is whether or not the server + * believed the transaction timed out. However, with the current design + * of the NIT, a client cannot do anything with this knowledge. Thus, + * the 408 is simply wasting network resources and contributes to the + * response bombardment illustrated in [3]. + * https://tools.ietf.org/html/rfc4320#section-4.1 + */ + ClientTransaction.prototype.onRequestTimeout = function () { + if (this.user.onRequestTimeout) { + this.user.onRequestTimeout(); + } + }; + return ClientTransaction; +}(transaction_1.Transaction)); +exports.ClientTransaction = ClientTransaction; diff --git a/lib/Core/transactions/index.d.ts b/lib/Core/transactions/index.d.ts new file mode 100644 index 000000000..c4f66d3f7 --- /dev/null +++ b/lib/Core/transactions/index.d.ts @@ -0,0 +1,10 @@ +export * from "./client-transaction"; +export * from "./invite-client-transaction"; +export * from "./invite-server-transaction"; +export * from "./non-invite-client-transaction"; +export * from "./non-invite-server-transaction"; +export * from "./invite-client-transaction"; +export * from "./server-transaction"; +export * from "./transaction-state"; +export * from "./transaction-user"; +export * from "./transaction"; diff --git a/lib/Core/transactions/index.js b/lib/Core/transactions/index.js new file mode 100644 index 000000000..b5343743a --- /dev/null +++ b/lib/Core/transactions/index.js @@ -0,0 +1,14 @@ +"use strict"; +function __export(m) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; +} +Object.defineProperty(exports, "__esModule", { value: true }); +__export(require("./client-transaction")); +__export(require("./invite-client-transaction")); +__export(require("./invite-server-transaction")); +__export(require("./non-invite-client-transaction")); +__export(require("./non-invite-server-transaction")); +__export(require("./invite-client-transaction")); +__export(require("./server-transaction")); +__export(require("./transaction-state")); +__export(require("./transaction")); diff --git a/lib/Core/transactions/invite-client-transaction.d.ts b/lib/Core/transactions/invite-client-transaction.d.ts new file mode 100644 index 000000000..b5a0f6312 --- /dev/null +++ b/lib/Core/transactions/invite-client-transaction.d.ts @@ -0,0 +1,115 @@ +import { Exceptions } from "../../Exceptions"; +import { IncomingResponse, OutgoingRequest } from "../../SIPMessage"; +import { Transport } from "../../Transport"; +import { ClientTransaction } from "./client-transaction"; +import { ClientTransactionUser } from "./transaction-user"; +/** + * INVITE Client Transaction + * + * The INVITE transaction consists of a three-way handshake. The client + * transaction sends an INVITE, the server transaction sends responses, + * and the client transaction sends an ACK. + * https://tools.ietf.org/html/rfc3261#section-17.1.1 + */ +export declare class InviteClientTransaction extends ClientTransaction { + private B; + private D; + private M; + /** + * Map of 2xx to-tag => ACK. + * If value is not undefined, value is the ACK which was sent. + * If key exists but value is undefined, a 2xx was received but the ACK not yet sent. + * Otherwise, a 2xx was not (yet) received for this transaction. + */ + private ackRetransmissionCache; + /** + * Constructor. + * Upon construction, the outgoing request's Via header is updated by calling `setViaHeader`. + * Then `toString` is called on the outgoing request and the message is sent via the transport. + * After construction the transaction will be in the "calling" state and the transaction id + * will equal the branch parameter set in the Via header of the outgoing request. + * https://tools.ietf.org/html/rfc3261#section-17.1.1 + * @param request The outgoing INVITE request. + * @param transport The transport. + * @param user The transaction user. + */ + constructor(request: OutgoingRequest, transport: Transport, user: ClientTransactionUser); + /** + * Destructor. + */ + dispose(): void; + /** Transaction kind. Deprecated. */ + readonly kind: string; + /** + * ACK a 2xx final response. + * + * The transaction includes the ACK only if the final response was not a 2xx response (the + * transaction will generate and send the ACK to the transport automagically). If the + * final response was a 2xx, the ACK is not considered part of the transaction (the + * transaction user needs to generate and send the ACK). + * + * This library is not strictly RFC compliant with regard to ACK handling for 2xx final + * responses. Specifically, retransmissions of ACKs to a 2xx final responses is handled + * by the transaction layer (instead of the UAC core). The "standard" approach is for + * the UAC core to receive all 2xx responses and manage sending ACK retransmissions to + * the transport directly. Herein the transaction layer manages sending ACKs to 2xx responses + * and any retransmissions of those ACKs as needed. + * + * @param ack The outgoing ACK request. + */ + ackResponse(ack: OutgoingRequest): void; + /** + * Handler for incoming responses from the transport which match this transaction. + * @param response The incoming response. + */ + receiveResponse(response: IncomingResponse): void; + /** + * The client transaction SHOULD inform the TU that a transport failure + * has occurred, and the client transaction SHOULD transition directly + * to the "Terminated" state. The TU will handle the failover + * mechanisms described in [4]. + * https://tools.ietf.org/html/rfc3261#section-17.1.4 + * @param error The error. + */ + protected onTransportError(error: Exceptions.TransportError): void; + /** For logging. */ + protected typeToString(): string; + private ack; + /** + * Execute a state transition. + * @param newState New state. + */ + private stateTransition; + /** + * When timer A fires, the client transaction MUST retransmit the + * request by passing it to the transport layer, and MUST reset the + * timer with a value of 2*T1. + * When timer A fires 2*T1 seconds later, the request MUST be + * retransmitted again (assuming the client transaction is still in this + * state). This process MUST continue so that the request is + * retransmitted with intervals that double after each transmission. + * These retransmissions SHOULD only be done while the client + * transaction is in the "Calling" state. + * https://tools.ietf.org/html/rfc3261#section-17.1.1.2 + */ + private timer_A; + /** + * If the client transaction is still in the "Calling" state when timer + * B fires, the client transaction SHOULD inform the TU that a timeout + * has occurred. The client transaction MUST NOT generate an ACK. + * https://tools.ietf.org/html/rfc3261#section-17.1.1.2 + */ + private timer_B; + /** + * If Timer D fires while the client transaction is in the "Completed" state, + * the client transaction MUST move to the "Terminated" state. + * https://tools.ietf.org/html/rfc6026#section-8.4 + */ + private timer_D; + /** + * If Timer M fires while the client transaction is in the "Accepted" + * state, the client transaction MUST move to the "Terminated" state. + * https://tools.ietf.org/html/rfc6026#section-8.4 + */ + private timer_M; +} diff --git a/lib/Core/transactions/invite-client-transaction.js b/lib/Core/transactions/invite-client-transaction.js new file mode 100644 index 000000000..a12bd7e21 --- /dev/null +++ b/lib/Core/transactions/invite-client-transaction.js @@ -0,0 +1,495 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Timers_1 = require("../../Timers"); +var client_transaction_1 = require("./client-transaction"); +var transaction_state_1 = require("./transaction-state"); +/** + * INVITE Client Transaction + * + * The INVITE transaction consists of a three-way handshake. The client + * transaction sends an INVITE, the server transaction sends responses, + * and the client transaction sends an ACK. + * https://tools.ietf.org/html/rfc3261#section-17.1.1 + */ +var InviteClientTransaction = /** @class */ (function (_super) { + __extends(InviteClientTransaction, _super); + /** + * Constructor. + * Upon construction, the outgoing request's Via header is updated by calling `setViaHeader`. + * Then `toString` is called on the outgoing request and the message is sent via the transport. + * After construction the transaction will be in the "calling" state and the transaction id + * will equal the branch parameter set in the Via header of the outgoing request. + * https://tools.ietf.org/html/rfc3261#section-17.1.1 + * @param request The outgoing INVITE request. + * @param transport The transport. + * @param user The transaction user. + */ + function InviteClientTransaction(request, transport, user) { + var _this = _super.call(this, request, transport, user, transaction_state_1.TransactionState.Calling, "sip.transaction.ict") || this; + /** + * Map of 2xx to-tag => ACK. + * If value is not undefined, value is the ACK which was sent. + * If key exists but value is undefined, a 2xx was received but the ACK not yet sent. + * Otherwise, a 2xx was not (yet) received for this transaction. + */ + _this.ackRetransmissionCache = new Map(); + // FIXME: Timer A for unreliable transport not implemented + // + // If an unreliable transport is being used, the client transaction + // MUST start timer A with a value of T1. If a reliable transport is being used, + // the client transaction SHOULD NOT start timer A (Timer A controls request retransmissions). + // For any transport, the client transaction MUST start timer B with a value + // of 64*T1 seconds (Timer B controls transaction timeouts). + // https://tools.ietf.org/html/rfc3261#section-17.1.1.2 + // + // While not spelled out in the RFC, Timer B is the maximum amount of time that a sender + // will wait for an INVITE message to be acknowledged (a SIP response message is received). + // So Timer B should be cleared when the transaction state proceeds from "Calling". + _this.B = setTimeout(function () { return _this.timer_B(); }, Timers_1.Timers.TIMER_B); + _this.send(request.toString()).catch(function (error) { + _this.logTransportError(error, "Failed to send initial outgoing request."); + }); + return _this; + } + /** + * Destructor. + */ + InviteClientTransaction.prototype.dispose = function () { + if (this.B) { + clearTimeout(this.B); + this.B = undefined; + } + if (this.D) { + clearTimeout(this.D); + this.D = undefined; + } + if (this.M) { + clearTimeout(this.M); + this.M = undefined; + } + _super.prototype.dispose.call(this); + }; + Object.defineProperty(InviteClientTransaction.prototype, "kind", { + /** Transaction kind. Deprecated. */ + get: function () { + return "ict"; + }, + enumerable: true, + configurable: true + }); + /** + * ACK a 2xx final response. + * + * The transaction includes the ACK only if the final response was not a 2xx response (the + * transaction will generate and send the ACK to the transport automagically). If the + * final response was a 2xx, the ACK is not considered part of the transaction (the + * transaction user needs to generate and send the ACK). + * + * This library is not strictly RFC compliant with regard to ACK handling for 2xx final + * responses. Specifically, retransmissions of ACKs to a 2xx final responses is handled + * by the transaction layer (instead of the UAC core). The "standard" approach is for + * the UAC core to receive all 2xx responses and manage sending ACK retransmissions to + * the transport directly. Herein the transaction layer manages sending ACKs to 2xx responses + * and any retransmissions of those ACKs as needed. + * + * @param ack The outgoing ACK request. + */ + InviteClientTransaction.prototype.ackResponse = function (ack) { + var _this = this; + var toTag = ack.toTag; + if (!toTag) { + throw new Error("To tag undefined."); + } + var id = "z9hG4bK" + Math.floor(Math.random() * 10000000); + ack.setViaHeader(id, this.transport); + this.ackRetransmissionCache.set(toTag, ack); // Add to ACK retransmission cache + this.send(ack.toString()).catch(function (error) { + _this.logTransportError(error, "Failed to send ACK to 2xx response."); + }); + }; + /** + * Handler for incoming responses from the transport which match this transaction. + * @param response The incoming response. + */ + InviteClientTransaction.prototype.receiveResponse = function (response) { + var _this = this; + var statusCode = response.statusCode; + if (!statusCode || statusCode < 100 || statusCode > 699) { + throw new Error("Invalid status code " + statusCode); + } + switch (this.state) { + case transaction_state_1.TransactionState.Calling: + // If the client transaction receives a provisional response while in + // the "Calling" state, it transitions to the "Proceeding" state. In the + // "Proceeding" state, the client transaction SHOULD NOT retransmit the + // request any longer. Furthermore, the provisional response MUST be + // passed to the TU. Any further provisional responses MUST be passed + // up to the TU while in the "Proceeding" state. + // https://tools.ietf.org/html/rfc3261#section-17.1.1.2 + if (statusCode >= 100 && statusCode <= 199) { + this.stateTransition(transaction_state_1.TransactionState.Proceeding); + if (this.user.receiveResponse) { + this.user.receiveResponse(response); + } + return; + } + // When a 2xx response is received while in either the "Calling" or + // "Proceeding" states, the client transaction MUST transition to + // the "Accepted" state... The 2xx response MUST be passed up to the TU. + // The client transaction MUST NOT generate an ACK to the 2xx response -- its + // handling is delegated to the TU. A UAC core will send an ACK to + // the 2xx response using a new transaction. + // https://tools.ietf.org/html/rfc6026#section-8.4 + if (statusCode >= 200 && statusCode <= 299) { + this.ackRetransmissionCache.set(response.toTag, undefined); // Prime the ACK cache + this.stateTransition(transaction_state_1.TransactionState.Accepted); + if (this.user.receiveResponse) { + this.user.receiveResponse(response); + } + return; + } + // When in either the "Calling" or "Proceeding" states, reception of + // a response with status code from 300-699 MUST cause the client + // transaction to transition to "Completed". The client transaction + // MUST pass the received response up to the TU, and the client + // transaction MUST generate an ACK request, even if the transport is + // reliable (guidelines for constructing the ACK from the response + // are given in Section 17.1.1.3), and then pass the ACK to the + // transport layer for transmission. The ACK MUST be sent to the + // same address, port, and transport to which the original request was sent. + // https://tools.ietf.org/html/rfc6026#section-8.4 + if (statusCode >= 300 && statusCode <= 699) { + this.stateTransition(transaction_state_1.TransactionState.Completed); + this.ack(response); + if (this.user.receiveResponse) { + this.user.receiveResponse(response); + } + return; + } + break; + case transaction_state_1.TransactionState.Proceeding: + // In the "Proceeding" state, the client transaction SHOULD NOT retransmit the + // request any longer. Furthermore, the provisional response MUST be + // passed to the TU. Any further provisional responses MUST be passed + // up to the TU while in the "Proceeding" state. + // https://tools.ietf.org/html/rfc3261#section-17.1.1.2 + if (statusCode >= 100 && statusCode <= 199) { + if (this.user.receiveResponse) { + this.user.receiveResponse(response); + } + return; + } + // When a 2xx response is received while in either the "Calling" or "Proceeding" states, + // the client transaction MUST transition to the "Accepted" state... + // The 2xx response MUST be passed up to the TU. The client + // transaction MUST NOT generate an ACK to the 2xx response -- its + // handling is delegated to the TU. A UAC core will send an ACK to + // the 2xx response using a new transaction. + // https://tools.ietf.org/html/rfc6026#section-8.4 + if (statusCode >= 200 && statusCode <= 299) { + this.ackRetransmissionCache.set(response.toTag, undefined); // Prime the ACK cache + this.stateTransition(transaction_state_1.TransactionState.Accepted); + if (this.user.receiveResponse) { + this.user.receiveResponse(response); + } + return; + } + // When in either the "Calling" or "Proceeding" states, reception of + // a response with status code from 300-699 MUST cause the client + // transaction to transition to "Completed". The client transaction + // MUST pass the received response up to the TU, and the client + // transaction MUST generate an ACK request, even if the transport is + // reliable (guidelines for constructing the ACK from the response + // are given in Section 17.1.1.3), and then pass the ACK to the + // transport layer for transmission. The ACK MUST be sent to the + // same address, port, and transport to which the original request was sent. + // https://tools.ietf.org/html/rfc6026#section-8.4 + if (statusCode >= 300 && statusCode <= 699) { + this.stateTransition(transaction_state_1.TransactionState.Completed); + this.ack(response); + if (this.user.receiveResponse) { + this.user.receiveResponse(response); + } + return; + } + break; + case transaction_state_1.TransactionState.Accepted: + // The purpose of the "Accepted" state is to allow the client + // transaction to continue to exist to receive, and pass to the TU, + // any retransmissions of the 2xx response and any additional 2xx + // responses from other branches of the INVITE if it forked + // downstream. Timer M reflects the amount of time that the + // transaction user will wait for such messages. + // + // Any 2xx responses that match this client transaction and that are + // received while in the "Accepted" state MUST be passed up to the + // TU. The client transaction MUST NOT generate an ACK to the 2xx + // response. The client transaction takes no further action. + // https://tools.ietf.org/html/rfc6026#section-8.4 + if (statusCode >= 200 && statusCode <= 299) { + // NOTE: This implementation herein is intentionally not RFC compliant. + // While the first 2xx response for a given branch is passed up to the TU, + // retransmissions of 2xx responses are absorbed and the ACK associated + // with the original response is resent. This approach is taken because + // our current transaction users are not currently in a good position to + // deal with 2xx retransmission. This SHOULD NOT cause any compliance issues - ;) + // + // If we don't have a cache hit, pass the response to the TU. + if (!this.ackRetransmissionCache.has(response.toTag)) { + this.ackRetransmissionCache.set(response.toTag, undefined); // Prime the ACK cache + if (this.user.receiveResponse) { + this.user.receiveResponse(response); + } + return; + } + // If we have a cache hit, try pulling the ACK from cache and retransmitting it. + var ack = this.ackRetransmissionCache.get(response.toTag); + if (ack) { + this.send(ack.toString()).catch(function (error) { + _this.logTransportError(error, "Failed to send retransmission of ACK to 2xx response."); + }); + return; + } + // If an ACK was not found in cache then we have received a retransmitted 2xx + // response before the TU responded to the original response (we don't have an ACK yet). + // So discard this response under the assumption that the TU will eventually + // get us a ACK for the original response. + return; + } + break; + case transaction_state_1.TransactionState.Completed: + // Any retransmissions of a response with status code 300-699 that + // are received while in the "Completed" state MUST cause the ACK to + // be re-passed to the transport layer for retransmission, but the + // newly received response MUST NOT be passed up to the TU. + // https://tools.ietf.org/html/rfc6026#section-8.4 + if (statusCode >= 300 && statusCode <= 699) { + this.ack(response); + return; + } + break; + case transaction_state_1.TransactionState.Terminated: + break; + default: + throw new Error("Invalid state " + this.state); + } + // Any response received that does not match an existing client + // transaction state machine is simply dropped. (Implementations are, + // of course, free to log or do other implementation-specific things + // with such responses, but the implementer should be sure to consider + // the impact of large numbers of malicious stray responses.) + // https://tools.ietf.org/html/rfc6026#section-7.2 + var message = "Received unexpected " + statusCode + " response while in state " + this.state + "."; + this.logger.warn(message); + return; + }; + /** + * The client transaction SHOULD inform the TU that a transport failure + * has occurred, and the client transaction SHOULD transition directly + * to the "Terminated" state. The TU will handle the failover + * mechanisms described in [4]. + * https://tools.ietf.org/html/rfc3261#section-17.1.4 + * @param error The error. + */ + InviteClientTransaction.prototype.onTransportError = function (error) { + if (this.user.onTransportError) { + this.user.onTransportError(error); + } + this.stateTransition(transaction_state_1.TransactionState.Terminated, true); + }; + /** For logging. */ + InviteClientTransaction.prototype.typeToString = function () { + return "INVITE client transaction"; + }; + InviteClientTransaction.prototype.ack = function (response) { + var _this = this; + // The ACK request constructed by the client transaction MUST contain + // values for the Call-ID, From, and Request-URI that are equal to the + // values of those header fields in the request passed to the transport + // by the client transaction (call this the "original request"). The To + // header field in the ACK MUST equal the To header field in the + // response being acknowledged, and therefore will usually differ from + // the To header field in the original request by the addition of the + // tag parameter. The ACK MUST contain a single Via header field, and + // this MUST be equal to the top Via header field of the original + // request. The CSeq header field in the ACK MUST contain the same + // value for the sequence number as was present in the original request, + // but the method parameter MUST be equal to "ACK". + // + // If the INVITE request whose response is being acknowledged had Route + // header fields, those header fields MUST appear in the ACK. This is + // to ensure that the ACK can be routed properly through any downstream + // stateless proxies. + // https://tools.ietf.org/html/rfc3261#section-17.1.1.3 + var ruri = this.request.ruri; + var callId = this.request.callId; + var cseq = this.request.cseq; + var from = this.request.getHeader("from"); + var to = response.getHeader("to"); + var via = this.request.getHeader("via"); + var route = this.request.getHeader("route"); + if (!from) { + throw new Error("From undefined."); + } + if (!to) { + throw new Error("To undefined."); + } + if (!via) { + throw new Error("Via undefined."); + } + var ack = "ACK " + ruri + " SIP/2.0\r\n"; + if (route) { + ack += "Route: " + route + "\r\n"; + } + ack += "Via: " + via + "\r\n"; + ack += "To: " + to + "\r\n"; + ack += "From: " + from + "\r\n"; + ack += "Call-ID: " + callId + "\r\n"; + ack += "CSeq: " + cseq + " ACK\r\n"; + ack += "Max-Forwards: 70\r\n"; + ack += "Content-Length: 0\r\n\r\n"; + // TOOO: "User-Agent" header + this.send(ack).catch(function (error) { + _this.logTransportError(error, "Failed to send ACK to non-2xx response."); + }); + return; + }; + /** + * Execute a state transition. + * @param newState New state. + */ + InviteClientTransaction.prototype.stateTransition = function (newState, dueToTransportError) { + var _this = this; + if (dueToTransportError === void 0) { dueToTransportError = false; } + // Assert valid state transitions. + var invalidStateTransition = function () { + throw new Error("Invalid state transition from " + _this.state + " to " + newState); + }; + switch (newState) { + case transaction_state_1.TransactionState.Calling: + invalidStateTransition(); + break; + case transaction_state_1.TransactionState.Proceeding: + if (this.state !== transaction_state_1.TransactionState.Calling) { + invalidStateTransition(); + } + break; + case transaction_state_1.TransactionState.Accepted: + case transaction_state_1.TransactionState.Completed: + if (this.state !== transaction_state_1.TransactionState.Calling && + this.state !== transaction_state_1.TransactionState.Proceeding) { + invalidStateTransition(); + } + break; + case transaction_state_1.TransactionState.Terminated: + if (this.state !== transaction_state_1.TransactionState.Calling && + this.state !== transaction_state_1.TransactionState.Accepted && + this.state !== transaction_state_1.TransactionState.Completed) { + if (!dueToTransportError) { + invalidStateTransition(); + } + } + break; + default: + invalidStateTransition(); + } + // While not spelled out in the RFC, Timer B is the maximum amount of time that a sender + // will wait for an INVITE message to be acknowledged (a SIP response message is received). + // So Timer B should be cleared when the transaction state proceeds from "Calling". + if (this.B) { + clearTimeout(this.B); + this.B = undefined; + } + if (newState === transaction_state_1.TransactionState.Proceeding) { + // Timers have no effect on "Proceeding" state. + // In the "Proceeding" state, the client transaction + // SHOULD NOT retransmit the request any longer. + // https://tools.ietf.org/html/rfc3261#section-17.1.1.2 + } + // The client transaction MUST start Timer D when it enters the "Completed" state + // for any reason, with a value of at least 32 seconds for unreliable transports, + // and a value of zero seconds for reliable transports. + // https://tools.ietf.org/html/rfc6026#section-8.4 + if (newState === transaction_state_1.TransactionState.Completed) { + this.D = setTimeout(function () { return _this.timer_D(); }, Timers_1.Timers.TIMER_D); + } + // The client transaction MUST transition to the "Accepted" state, + // and Timer M MUST be started with a value of 64*T1. + // https://tools.ietf.org/html/rfc6026#section-8.4 + if (newState === transaction_state_1.TransactionState.Accepted) { + this.M = setTimeout(function () { return _this.timer_M(); }, Timers_1.Timers.TIMER_M); + } + // Once the transaction is in the "Terminated" state, it MUST be destroyed immediately. + // https://tools.ietf.org/html/rfc6026#section-8.7 + if (newState === transaction_state_1.TransactionState.Terminated) { + this.dispose(); + } + // Update state. + this.setState(newState); + }; + /** + * When timer A fires, the client transaction MUST retransmit the + * request by passing it to the transport layer, and MUST reset the + * timer with a value of 2*T1. + * When timer A fires 2*T1 seconds later, the request MUST be + * retransmitted again (assuming the client transaction is still in this + * state). This process MUST continue so that the request is + * retransmitted with intervals that double after each transmission. + * These retransmissions SHOULD only be done while the client + * transaction is in the "Calling" state. + * https://tools.ietf.org/html/rfc3261#section-17.1.1.2 + */ + InviteClientTransaction.prototype.timer_A = function () { + // TODO + }; + /** + * If the client transaction is still in the "Calling" state when timer + * B fires, the client transaction SHOULD inform the TU that a timeout + * has occurred. The client transaction MUST NOT generate an ACK. + * https://tools.ietf.org/html/rfc3261#section-17.1.1.2 + */ + InviteClientTransaction.prototype.timer_B = function () { + this.logger.debug("Timer B expired for INVITE client transaction " + this.id + "."); + if (this.state === transaction_state_1.TransactionState.Calling) { + this.onRequestTimeout(); + this.stateTransition(transaction_state_1.TransactionState.Terminated); + } + }; + /** + * If Timer D fires while the client transaction is in the "Completed" state, + * the client transaction MUST move to the "Terminated" state. + * https://tools.ietf.org/html/rfc6026#section-8.4 + */ + InviteClientTransaction.prototype.timer_D = function () { + this.logger.debug("Timer D expired for INVITE client transaction " + this.id + "."); + if (this.state === transaction_state_1.TransactionState.Completed) { + this.stateTransition(transaction_state_1.TransactionState.Terminated); + } + }; + /** + * If Timer M fires while the client transaction is in the "Accepted" + * state, the client transaction MUST move to the "Terminated" state. + * https://tools.ietf.org/html/rfc6026#section-8.4 + */ + InviteClientTransaction.prototype.timer_M = function () { + this.logger.debug("Timer M expired for INVITE client transaction " + this.id + "."); + if (this.state === transaction_state_1.TransactionState.Accepted) { + this.stateTransition(transaction_state_1.TransactionState.Terminated); + } + }; + return InviteClientTransaction; +}(client_transaction_1.ClientTransaction)); +exports.InviteClientTransaction = InviteClientTransaction; diff --git a/lib/Core/transactions/invite-server-transaction.d.ts b/lib/Core/transactions/invite-server-transaction.d.ts new file mode 100644 index 000000000..fe5ef1601 --- /dev/null +++ b/lib/Core/transactions/invite-server-transaction.d.ts @@ -0,0 +1,125 @@ +import { IncomingRequest } from "../../SIPMessage"; +import { Transport } from "../../Transport"; +import { ServerTransaction } from "./server-transaction"; +import { ServerTransactionUser } from "./transaction-user"; +/** + * INVITE Server Transaction + * https://tools.ietf.org/html/rfc3261#section-17.2.1 + */ +export declare class InviteServerTransaction extends ServerTransaction { + private lastFinalResponse; + private lastProvisionalResponse; + private H; + private I; + private L; + /** + * FIXME: This should not be here. It should be in the UAS. + * + * If the UAS desires an extended period of time to answer the INVITE, + * it will need to ask for an "extension" in order to prevent proxies + * from canceling the transaction. A proxy has the option of canceling + * a transaction when there is a gap of 3 minutes between responses in a + * transaction. To prevent cancellation, the UAS MUST send a non-100 + * provisional response at every minute, to handle the possibility of + * lost provisional responses. + * + * An INVITE transaction can go on for extended durations when the + * user is placed on hold, or when interworking with PSTN systems + * which allow communications to take place without answering the + * call. The latter is common in Interactive Voice Response (IVR) + * systems. + * https://tools.ietf.org/html/rfc3261#section-13.3.1.1 + */ + private progressExtensionTimer; + /** + * Constructor. + * Upon construction, a "100 Trying" reply will be immediately sent. + * After construction the transaction will be in the "proceeding" state and the transaction + * `id` will equal the branch parameter set in the Via header of the incoming request. + * https://tools.ietf.org/html/rfc3261#section-17.2.1 + * @param request Incoming INVITE request from the transport. + * @param transport The transport. + * @param user The transaction user. + */ + constructor(request: IncomingRequest, transport: Transport, user: ServerTransactionUser); + /** + * Destructor. + */ + dispose(): void; + /** Transaction kind. Deprecated. */ + readonly kind: string; + /** + * Receive requests from transport matching this transaction. + * @param request Request matching this transaction. + */ + receiveRequest(request: IncomingRequest): void; + /** + * Receive responses from TU for this transaction. + * @param statusCode Status code of response. + * @param response Response. + */ + receiveResponse(statusCode: number, response: string): void; + /** + * Retransmit the last 2xx response. This is a noop if not in the "accepted" state. + */ + retransmitAcceptedResponse(): void; + /** + * First, the procedures in [4] are followed, which attempt to deliver the response to a backup. + * If those should all fail, based on the definition of failure in [4], the server transaction SHOULD + * inform the TU that a failure has occurred, and MUST remain in the current state. + * https://tools.ietf.org/html/rfc6026#section-8.8 + */ + protected onTransportError(error: Error): void; + /** For logging. */ + protected typeToString(): string; + /** + * Execute a state transition. + * @param newState New state. + */ + private stateTransition; + /** + * FIXME: UAS Provisional Retransmission Timer. See RFC 3261 Section 13.3.1.1 + * This is in the wrong place. This is not a transaction level thing. It's a UAS level thing. + */ + private startProgressExtensionTimer; + /** + * FIXME: UAS Provisional Retransmission Timer id. See RFC 3261 Section 13.3.1.1 + * This is in the wrong place. This is not a transaction level thing. It's a UAS level thing. + */ + private stopProgressExtensionTimer; + /** + * While in the "Proceeding" state, if the TU passes a response with status code + * from 300 to 699 to the server transaction, the response MUST be passed to the + * transport layer for transmission, and the state machine MUST enter the "Completed" state. + * For unreliable transports, timer G is set to fire in T1 seconds, and is not set to fire for + * reliable transports. If timer G fires, the response is passed to the transport layer once + * more for retransmission, and timer G is set to fire in MIN(2*T1, T2) seconds. From then on, + * when timer G fires, the response is passed to the transport again for transmission, and + * timer G is reset with a value that doubles, unless that value exceeds T2, in which case + * it is reset with the value of T2. + * https://tools.ietf.org/html/rfc3261#section-17.2.1 + */ + private timer_G; + /** + * If timer H fires while in the "Completed" state, it implies that the ACK was never received. + * In this case, the server transaction MUST transition to the "Terminated" state, and MUST + * indicate to the TU that a transaction failure has occurred. + * https://tools.ietf.org/html/rfc3261#section-17.2.1 + */ + private timer_H; + /** + * Once timer I fires, the server MUST transition to the "Terminated" state. + * https://tools.ietf.org/html/rfc3261#section-17.2.1 + */ + private timer_I; + /** + * When Timer L fires and the state machine is in the "Accepted" state, the machine MUST + * transition to the "Terminated" state. Once the transaction is in the "Terminated" state, + * it MUST be destroyed immediately. Timer L reflects the amount of time the server + * transaction could receive 2xx responses for retransmission from the + * TU while it is waiting to receive an ACK. + * https://tools.ietf.org/html/rfc6026#section-7.1 + * https://tools.ietf.org/html/rfc6026#section-8.7 + */ + private timer_L; +} diff --git a/lib/Core/transactions/invite-server-transaction.js b/lib/Core/transactions/invite-server-transaction.js new file mode 100644 index 000000000..cc2e9fbca --- /dev/null +++ b/lib/Core/transactions/invite-server-transaction.js @@ -0,0 +1,401 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Constants_1 = require("../../Constants"); +var Timers_1 = require("../../Timers"); +var server_transaction_1 = require("./server-transaction"); +var transaction_state_1 = require("./transaction-state"); +/** + * INVITE Server Transaction + * https://tools.ietf.org/html/rfc3261#section-17.2.1 + */ +var InviteServerTransaction = /** @class */ (function (_super) { + __extends(InviteServerTransaction, _super); + /** + * Constructor. + * Upon construction, a "100 Trying" reply will be immediately sent. + * After construction the transaction will be in the "proceeding" state and the transaction + * `id` will equal the branch parameter set in the Via header of the incoming request. + * https://tools.ietf.org/html/rfc3261#section-17.2.1 + * @param request Incoming INVITE request from the transport. + * @param transport The transport. + * @param user The transaction user. + */ + function InviteServerTransaction(request, transport, user) { + return _super.call(this, request, transport, user, transaction_state_1.TransactionState.Proceeding, "sip.transaction.ist") || this; + } + /** + * Destructor. + */ + InviteServerTransaction.prototype.dispose = function () { + this.stopProgressExtensionTimer(); + if (this.H) { + clearTimeout(this.H); + this.H = undefined; + } + if (this.I) { + clearTimeout(this.I); + this.I = undefined; + } + if (this.L) { + clearTimeout(this.L); + this.L = undefined; + } + _super.prototype.dispose.call(this); + }; + Object.defineProperty(InviteServerTransaction.prototype, "kind", { + /** Transaction kind. Deprecated. */ + get: function () { + return "ist"; + }, + enumerable: true, + configurable: true + }); + /** + * Receive requests from transport matching this transaction. + * @param request Request matching this transaction. + */ + InviteServerTransaction.prototype.receiveRequest = function (request) { + var _this = this; + switch (this.state) { + case transaction_state_1.TransactionState.Proceeding: + // If a request retransmission is received while in the "Proceeding" state, the most + // recent provisional response that was received from the TU MUST be passed to the + // transport layer for retransmission. + // https://tools.ietf.org/html/rfc3261#section-17.2.1 + if (request.method === Constants_1.C.INVITE) { + if (this.lastProvisionalResponse) { + this.send(this.lastProvisionalResponse).catch(function (error) { + _this.logTransportError(error, "Failed to send retransmission of provisional response."); + }); + } + return; + } + break; + case transaction_state_1.TransactionState.Accepted: + // While in the "Accepted" state, any retransmissions of the INVITE + // received will match this transaction state machine and will be + // absorbed by the machine without changing its state. These + // retransmissions are not passed onto the TU. + // https://tools.ietf.org/html/rfc6026#section-7.1 + if (request.method === Constants_1.C.INVITE) { + return; + } + break; + case transaction_state_1.TransactionState.Completed: + // Furthermore, while in the "Completed" state, if a request retransmission is + // received, the server SHOULD pass the response to the transport for retransmission. + // https://tools.ietf.org/html/rfc3261#section-17.2.1 + if (request.method === Constants_1.C.INVITE) { + if (!this.lastFinalResponse) { + throw new Error("Last final response undefined."); + } + this.send(this.lastFinalResponse).catch(function (error) { + _this.logTransportError(error, "Failed to send retransmission of final response."); + }); + return; + } + // If an ACK is received while the server transaction is in the "Completed" state, + // the server transaction MUST transition to the "Confirmed" state. + // https://tools.ietf.org/html/rfc3261#section-17.2.1 + if (request.method === Constants_1.C.ACK) { + this.stateTransition(transaction_state_1.TransactionState.Confirmed); + return; + } + break; + case transaction_state_1.TransactionState.Confirmed: + // The purpose of the "Confirmed" state is to absorb any additional ACK messages that arrive, + // triggered from retransmissions of the final response. + // https://tools.ietf.org/html/rfc3261#section-17.2.1 + if (request.method === Constants_1.C.INVITE || request.method === Constants_1.C.ACK) { + return; + } + break; + case transaction_state_1.TransactionState.Terminated: + // For good measure absorb any additional messages that arrive (should not happen). + if (request.method === Constants_1.C.INVITE || request.method === Constants_1.C.ACK) { + return; + } + break; + default: + throw new Error("Invalid state " + this.state); + } + var message = "INVITE server transaction received unexpected " + request.method + " request while in state " + this.state + "."; + this.logger.warn(message); + return; + }; + /** + * Receive responses from TU for this transaction. + * @param statusCode Status code of response. + * @param response Response. + */ + InviteServerTransaction.prototype.receiveResponse = function (statusCode, response) { + var _this = this; + if (statusCode < 100 || statusCode > 699) { + throw new Error("Invalid status code " + statusCode); + } + switch (this.state) { + case transaction_state_1.TransactionState.Proceeding: + // The TU passes any number of provisional responses to the server + // transaction. So long as the server transaction is in the + // "Proceeding" state, each of these MUST be passed to the transport + // layer for transmission. They are not sent reliably by the + // transaction layer (they are not retransmitted by it) and do not cause + // a change in the state of the server transaction. + // https://tools.ietf.org/html/rfc3261#section-17.2.1 + if (statusCode >= 100 && statusCode <= 199) { + this.lastProvisionalResponse = response; + // Start the progress extension timer only for a non-100 provisional response. + if (statusCode > 100) { + this.startProgressExtensionTimer(); // FIXME: remove + } + this.send(response).catch(function (error) { + _this.logTransportError(error, "Failed to send 1xx response."); + }); + return; + } + // If, while in the "Proceeding" state, the TU passes a 2xx response + // to the server transaction, the server transaction MUST pass this + // response to the transport layer for transmission. It is not + // retransmitted by the server transaction; retransmissions of 2xx + // responses are handled by the TU. The server transaction MUST then + // transition to the "Accepted" state. + // https://tools.ietf.org/html/rfc6026#section-8.5 + if (statusCode >= 200 && statusCode <= 299) { + this.lastFinalResponse = response; + this.stateTransition(transaction_state_1.TransactionState.Accepted); + this.send(response).catch(function (error) { + _this.logTransportError(error, "Failed to send 2xx response."); + }); + return; + } + // While in the "Proceeding" state, if the TU passes a response with + // status code from 300 to 699 to the server transaction, the response + // MUST be passed to the transport layer for transmission, and the state + // machine MUST enter the "Completed" state. + // https://tools.ietf.org/html/rfc3261#section-17.2.1 + if (statusCode >= 300 && statusCode <= 699) { + this.lastFinalResponse = response; + this.stateTransition(transaction_state_1.TransactionState.Completed); + this.send(response).catch(function (error) { + _this.logTransportError(error, "Failed to send non-2xx final response."); + }); + return; + } + break; + case transaction_state_1.TransactionState.Accepted: + // While in the "Accepted" state, if the TU passes a 2xx response, + // the server transaction MUST pass the response to the transport layer for transmission. + // https://tools.ietf.org/html/rfc6026#section-8.7 + if (statusCode >= 200 && statusCode <= 299) { + this.send(response).catch(function (error) { + _this.logTransportError(error, "Failed to send 2xx response."); + }); + return; + } + break; + case transaction_state_1.TransactionState.Completed: + break; + case transaction_state_1.TransactionState.Confirmed: + break; + case transaction_state_1.TransactionState.Terminated: + break; + default: + throw new Error("Invalid state " + this.state); + } + var message = "INVITE server transaction received unexpected " + statusCode + " response from TU while in state " + this.state + "."; + this.logger.error(message); + throw new Error(message); + }; + /** + * Retransmit the last 2xx response. This is a noop if not in the "accepted" state. + */ + InviteServerTransaction.prototype.retransmitAcceptedResponse = function () { + var _this = this; + if (this.state === transaction_state_1.TransactionState.Accepted && this.lastFinalResponse) { + this.send(this.lastFinalResponse).catch(function (error) { + _this.logTransportError(error, "Failed to send 2xx response."); + }); + } + }; + /** + * First, the procedures in [4] are followed, which attempt to deliver the response to a backup. + * If those should all fail, based on the definition of failure in [4], the server transaction SHOULD + * inform the TU that a failure has occurred, and MUST remain in the current state. + * https://tools.ietf.org/html/rfc6026#section-8.8 + */ + InviteServerTransaction.prototype.onTransportError = function (error) { + if (this.user.onTransportError) { + this.user.onTransportError(error); + } + }; + /** For logging. */ + InviteServerTransaction.prototype.typeToString = function () { + return "INVITE server transaction"; + }; + /** + * Execute a state transition. + * @param newState New state. + */ + InviteServerTransaction.prototype.stateTransition = function (newState) { + var _this = this; + // Assert valid state transitions. + var invalidStateTransition = function () { + throw new Error("Invalid state transition from " + _this.state + " to " + newState); + }; + switch (newState) { + case transaction_state_1.TransactionState.Proceeding: + invalidStateTransition(); + break; + case transaction_state_1.TransactionState.Accepted: + case transaction_state_1.TransactionState.Completed: + if (this.state !== transaction_state_1.TransactionState.Proceeding) { + invalidStateTransition(); + } + break; + case transaction_state_1.TransactionState.Confirmed: + if (this.state !== transaction_state_1.TransactionState.Completed) { + invalidStateTransition(); + } + break; + case transaction_state_1.TransactionState.Terminated: + if (this.state !== transaction_state_1.TransactionState.Accepted && + this.state !== transaction_state_1.TransactionState.Completed && + this.state !== transaction_state_1.TransactionState.Confirmed) { + invalidStateTransition(); + } + break; + default: + invalidStateTransition(); + } + // On any state transition, stop resending provisonal responses + this.stopProgressExtensionTimer(); + // The purpose of the "Accepted" state is to absorb retransmissions of an accepted INVITE request. + // Any such retransmissions are absorbed entirely within the server transaction. + // They are not passed up to the TU since any downstream UAS cores that accepted the request have + // taken responsibility for reliability and will already retransmit their 2xx responses if necessary. + // https://tools.ietf.org/html/rfc6026#section-8.7 + if (newState === transaction_state_1.TransactionState.Accepted) { + this.L = setTimeout(function () { return _this.timer_L(); }, Timers_1.Timers.TIMER_L); + } + // When the "Completed" state is entered, timer H MUST be set to fire in 64*T1 seconds for all transports. + // Timer H determines when the server transaction abandons retransmitting the response. + // If an ACK is received while the server transaction is in the "Completed" state, + // the server transaction MUST transition to the "Confirmed" state. + // https://tools.ietf.org/html/rfc3261#section-17.2.1 + if (newState === transaction_state_1.TransactionState.Completed) { + // FIXME: Missing timer G for unreliable transports. + this.H = setTimeout(function () { return _this.timer_H(); }, Timers_1.Timers.TIMER_H); + } + // The purpose of the "Confirmed" state is to absorb any additional ACK messages that arrive, + // triggered from retransmissions of the final response. When this state is entered, timer I + // is set to fire in T4 seconds for unreliable transports, and zero seconds for reliable + // transports. Once timer I fires, the server MUST transition to the "Terminated" state. + // https://tools.ietf.org/html/rfc3261#section-17.2.1 + if (newState === transaction_state_1.TransactionState.Confirmed) { + // FIXME: This timer is not getting set correctly for unreliable transports. + this.I = setTimeout(function () { return _this.timer_I(); }, Timers_1.Timers.TIMER_I); + } + // Once the transaction is in the "Terminated" state, it MUST be destroyed immediately. + // https://tools.ietf.org/html/rfc6026#section-8.7 + if (newState === transaction_state_1.TransactionState.Terminated) { + this.dispose(); + } + // Update state. + this.setState(newState); + }; + /** + * FIXME: UAS Provisional Retransmission Timer. See RFC 3261 Section 13.3.1.1 + * This is in the wrong place. This is not a transaction level thing. It's a UAS level thing. + */ + InviteServerTransaction.prototype.startProgressExtensionTimer = function () { + var _this = this; + // Start the progress extension timer only for the first non-100 provisional response. + if (this.progressExtensionTimer === undefined) { + this.progressExtensionTimer = setInterval(function () { + _this.logger.debug("Progress extension timer expired for INVITE server transaction " + _this.id + "."); + if (!_this.lastProvisionalResponse) { + throw new Error("Last provisional response undefined."); + } + _this.send(_this.lastProvisionalResponse).catch(function (error) { + _this.logTransportError(error, "Failed to send retransmission of provisional response."); + }); + }, Timers_1.Timers.PROVISIONAL_RESPONSE_INTERVAL); + } + }; + /** + * FIXME: UAS Provisional Retransmission Timer id. See RFC 3261 Section 13.3.1.1 + * This is in the wrong place. This is not a transaction level thing. It's a UAS level thing. + */ + InviteServerTransaction.prototype.stopProgressExtensionTimer = function () { + if (this.progressExtensionTimer !== undefined) { + clearInterval(this.progressExtensionTimer); + this.progressExtensionTimer = undefined; + } + }; + /** + * While in the "Proceeding" state, if the TU passes a response with status code + * from 300 to 699 to the server transaction, the response MUST be passed to the + * transport layer for transmission, and the state machine MUST enter the "Completed" state. + * For unreliable transports, timer G is set to fire in T1 seconds, and is not set to fire for + * reliable transports. If timer G fires, the response is passed to the transport layer once + * more for retransmission, and timer G is set to fire in MIN(2*T1, T2) seconds. From then on, + * when timer G fires, the response is passed to the transport again for transmission, and + * timer G is reset with a value that doubles, unless that value exceeds T2, in which case + * it is reset with the value of T2. + * https://tools.ietf.org/html/rfc3261#section-17.2.1 + */ + InviteServerTransaction.prototype.timer_G = function () { + // TODO + }; + /** + * If timer H fires while in the "Completed" state, it implies that the ACK was never received. + * In this case, the server transaction MUST transition to the "Terminated" state, and MUST + * indicate to the TU that a transaction failure has occurred. + * https://tools.ietf.org/html/rfc3261#section-17.2.1 + */ + InviteServerTransaction.prototype.timer_H = function () { + this.logger.debug("Timer H expired for INVITE server transaction " + this.id + "."); + if (this.state === transaction_state_1.TransactionState.Completed) { + this.logger.warn("ACK to negative final response was never received, terminating transaction."); + this.stateTransition(transaction_state_1.TransactionState.Terminated); + } + }; + /** + * Once timer I fires, the server MUST transition to the "Terminated" state. + * https://tools.ietf.org/html/rfc3261#section-17.2.1 + */ + InviteServerTransaction.prototype.timer_I = function () { + this.logger.debug("Timer I expired for INVITE server transaction " + this.id + "."); + this.stateTransition(transaction_state_1.TransactionState.Terminated); + }; + /** + * When Timer L fires and the state machine is in the "Accepted" state, the machine MUST + * transition to the "Terminated" state. Once the transaction is in the "Terminated" state, + * it MUST be destroyed immediately. Timer L reflects the amount of time the server + * transaction could receive 2xx responses for retransmission from the + * TU while it is waiting to receive an ACK. + * https://tools.ietf.org/html/rfc6026#section-7.1 + * https://tools.ietf.org/html/rfc6026#section-8.7 + */ + InviteServerTransaction.prototype.timer_L = function () { + this.logger.debug("Timer L expired for INVITE server transaction " + this.id + "."); + if (this.state === transaction_state_1.TransactionState.Accepted) { + this.stateTransition(transaction_state_1.TransactionState.Terminated); + } + }; + return InviteServerTransaction; +}(server_transaction_1.ServerTransaction)); +exports.InviteServerTransaction = InviteServerTransaction; diff --git a/lib/Core/transactions/non-invite-client-transaction.d.ts b/lib/Core/transactions/non-invite-client-transaction.d.ts new file mode 100644 index 000000000..6c19399ce --- /dev/null +++ b/lib/Core/transactions/non-invite-client-transaction.d.ts @@ -0,0 +1,68 @@ +import { IncomingResponse, OutgoingRequest } from "../../SIPMessage"; +import { Transport } from "../../Transport"; +import { ClientTransaction } from "./client-transaction"; +import { ClientTransactionUser } from "./transaction-user"; +/** + * Non-INVITE Client Transaction + * + * Non-INVITE transactions do not make use of ACK. + * They are simple request-response interactions. + * https://tools.ietf.org/html/rfc3261#section-17.1.2 + */ +export declare class NonInviteClientTransaction extends ClientTransaction { + private F; + private K; + /** + * Constructor + * Upon construction, the outgoing request's Via header is updated by calling `setViaHeader`. + * Then `toString` is called on the outgoing request and the message is sent via the transport. + * After construction the transaction will be in the "calling" state and the transaction id + * will equal the branch parameter set in the Via header of the outgoing request. + * https://tools.ietf.org/html/rfc3261#section-17.1.2 + * @param request The outgoing Non-INVITE request. + * @param transport The transport. + * @param user The transaction user. + */ + constructor(request: OutgoingRequest, transport: Transport, user: ClientTransactionUser); + /** + * Destructor. + */ + dispose(): void; + /** Transaction kind. Deprecated. */ + readonly kind: string; + /** + * Handler for incoming responses from the transport which match this transaction. + * @param response The incoming response. + */ + receiveResponse(response: IncomingResponse): void; + /** + * The client transaction SHOULD inform the TU that a transport failure has occurred, + * and the client transaction SHOULD transition directly to the "Terminated" state. + * The TU will handle the failover mechanisms described in [4]. + * https://tools.ietf.org/html/rfc3261#section-17.1.4 + * @param error Trasnsport error + */ + protected onTransportError(error: Error): void; + /** For logging. */ + protected typeToString(): string; + /** + * Execute a state transition. + * @param newState New state. + */ + private stateTransition; + /** + * If Timer F fires while the client transaction is still in the + * "Trying" state, the client transaction SHOULD inform the TU about the + * timeout, and then it SHOULD enter the "Terminated" state. + * If timer F fires while in the "Proceeding" state, the TU MUST be informed of + * a timeout, and the client transaction MUST transition to the terminated state. + * https://tools.ietf.org/html/rfc3261#section-17.1.2.2 + */ + private timer_F; + /** + * If Timer K fires while in this (COMPLETED) state, the client transaction + * MUST transition to the "Terminated" state. + * https://tools.ietf.org/html/rfc3261#section-17.1.2.2 + */ + private timer_K; +} diff --git a/lib/Core/transactions/non-invite-client-transaction.js b/lib/Core/transactions/non-invite-client-transaction.js new file mode 100644 index 000000000..731af40a4 --- /dev/null +++ b/lib/Core/transactions/non-invite-client-transaction.js @@ -0,0 +1,257 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Timers_1 = require("../../Timers"); +var client_transaction_1 = require("./client-transaction"); +var transaction_state_1 = require("./transaction-state"); +/** + * Non-INVITE Client Transaction + * + * Non-INVITE transactions do not make use of ACK. + * They are simple request-response interactions. + * https://tools.ietf.org/html/rfc3261#section-17.1.2 + */ +var NonInviteClientTransaction = /** @class */ (function (_super) { + __extends(NonInviteClientTransaction, _super); + /** + * Constructor + * Upon construction, the outgoing request's Via header is updated by calling `setViaHeader`. + * Then `toString` is called on the outgoing request and the message is sent via the transport. + * After construction the transaction will be in the "calling" state and the transaction id + * will equal the branch parameter set in the Via header of the outgoing request. + * https://tools.ietf.org/html/rfc3261#section-17.1.2 + * @param request The outgoing Non-INVITE request. + * @param transport The transport. + * @param user The transaction user. + */ + function NonInviteClientTransaction(request, transport, user) { + var _this = _super.call(this, request, transport, user, transaction_state_1.TransactionState.Trying, "sip.transaction.nict") || this; + // FIXME: Timer E for unreliable transports not implemented. + // + // The "Trying" state is entered when the TU initiates a new client + // transaction with a request. When entering this state, the client + // transaction SHOULD set timer F to fire in 64*T1 seconds. The request + // MUST be passed to the transport layer for transmission. + // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 + _this.F = setTimeout(function () { return _this.timer_F(); }, Timers_1.Timers.TIMER_F); + _this.send(request.toString()).catch(function (error) { + _this.logTransportError(error, "Failed to send initial outgoing request."); + }); + return _this; + } + /** + * Destructor. + */ + NonInviteClientTransaction.prototype.dispose = function () { + if (this.F) { + clearTimeout(this.F); + this.F = undefined; + } + if (this.K) { + clearTimeout(this.K); + this.K = undefined; + } + _super.prototype.dispose.call(this); + }; + Object.defineProperty(NonInviteClientTransaction.prototype, "kind", { + /** Transaction kind. Deprecated. */ + get: function () { + return "nict"; + }, + enumerable: true, + configurable: true + }); + /** + * Handler for incoming responses from the transport which match this transaction. + * @param response The incoming response. + */ + NonInviteClientTransaction.prototype.receiveResponse = function (response) { + var statusCode = response.statusCode; + if (!statusCode || statusCode < 100 || statusCode > 699) { + throw new Error("Invalid status code " + statusCode); + } + switch (this.state) { + case transaction_state_1.TransactionState.Trying: + // If a provisional response is received while in the "Trying" state, the + // response MUST be passed to the TU, and then the client transaction + // SHOULD move to the "Proceeding" state. + // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 + if (statusCode >= 100 && statusCode <= 199) { + this.stateTransition(transaction_state_1.TransactionState.Proceeding); + if (this.user.receiveResponse) { + this.user.receiveResponse(response); + } + return; + } + // If a final response (status codes 200-699) is received while in the + // "Trying" state, the response MUST be passed to the TU, and the + // client transaction MUST transition to the "Completed" state. + // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 + if (statusCode >= 200 && statusCode <= 699) { + this.stateTransition(transaction_state_1.TransactionState.Completed); + if (statusCode === 408) { + this.onRequestTimeout(); + return; + } + if (this.user.receiveResponse) { + this.user.receiveResponse(response); + } + return; + } + break; + case transaction_state_1.TransactionState.Proceeding: + // If a provisional response is received while in the "Proceeding" state, + // the response MUST be passed to the TU. (From Figure 6) + // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 + if (statusCode >= 100 && statusCode <= 199) { + if (this.user.receiveResponse) { + return this.user.receiveResponse(response); + } + } + // If a final response (status codes 200-699) is received while in the + // "Proceeding" state, the response MUST be passed to the TU, and the + // client transaction MUST transition to the "Completed" state. + // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 + if (statusCode >= 200 && statusCode <= 699) { + this.stateTransition(transaction_state_1.TransactionState.Completed); + if (statusCode === 408) { + this.onRequestTimeout(); + return; + } + if (this.user.receiveResponse) { + this.user.receiveResponse(response); + } + return; + } + case transaction_state_1.TransactionState.Completed: + // The "Completed" state exists to buffer any additional response + // retransmissions that may be received (which is why the client + // transaction remains there only for unreliable transports). + // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 + return; + case transaction_state_1.TransactionState.Terminated: + // For good measure just absorb additional response retransmissions. + return; + default: + throw new Error("Invalid state " + this.state); + } + var message = "Non-INVITE client transaction received unexpected " + statusCode + " response while in state " + this.state + "."; + this.logger.warn(message); + return; + }; + /** + * The client transaction SHOULD inform the TU that a transport failure has occurred, + * and the client transaction SHOULD transition directly to the "Terminated" state. + * The TU will handle the failover mechanisms described in [4]. + * https://tools.ietf.org/html/rfc3261#section-17.1.4 + * @param error Trasnsport error + */ + NonInviteClientTransaction.prototype.onTransportError = function (error) { + if (this.user.onTransportError) { + this.user.onTransportError(error); + } + this.stateTransition(transaction_state_1.TransactionState.Terminated, true); + }; + /** For logging. */ + NonInviteClientTransaction.prototype.typeToString = function () { + return "non-INVITE client transaction"; + }; + /** + * Execute a state transition. + * @param newState New state. + */ + NonInviteClientTransaction.prototype.stateTransition = function (newState, dueToTransportError) { + var _this = this; + if (dueToTransportError === void 0) { dueToTransportError = false; } + // Assert valid state transitions. + var invalidStateTransition = function () { + throw new Error("Invalid state transition from " + _this.state + " to " + newState); + }; + switch (newState) { + case transaction_state_1.TransactionState.Trying: + invalidStateTransition(); + break; + case transaction_state_1.TransactionState.Proceeding: + if (this.state !== transaction_state_1.TransactionState.Trying) { + invalidStateTransition(); + } + break; + case transaction_state_1.TransactionState.Completed: + if (this.state !== transaction_state_1.TransactionState.Trying && + this.state !== transaction_state_1.TransactionState.Proceeding) { + invalidStateTransition(); + } + break; + case transaction_state_1.TransactionState.Terminated: + if (this.state !== transaction_state_1.TransactionState.Trying && + this.state !== transaction_state_1.TransactionState.Proceeding && + this.state !== transaction_state_1.TransactionState.Completed) { + if (!dueToTransportError) { + invalidStateTransition(); + } + } + break; + default: + invalidStateTransition(); + } + // Once the client transaction enters the "Completed" state, it MUST set + // Timer K to fire in T4 seconds for unreliable transports, and zero + // seconds for reliable transports The "Completed" state exists to + // buffer any additional response retransmissions that may be received + // (which is why the client transaction remains there only for unreliable transports). + // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 + if (newState === transaction_state_1.TransactionState.Completed) { + if (this.F) { + clearTimeout(this.F); + this.F = undefined; + } + this.K = setTimeout(function () { return _this.timer_K(); }, Timers_1.Timers.TIMER_K); + } + // Once the transaction is in the terminated state, it MUST be destroyed immediately. + // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 + if (newState === transaction_state_1.TransactionState.Terminated) { + this.dispose(); + } + // Update state. + this.setState(newState); + }; + /** + * If Timer F fires while the client transaction is still in the + * "Trying" state, the client transaction SHOULD inform the TU about the + * timeout, and then it SHOULD enter the "Terminated" state. + * If timer F fires while in the "Proceeding" state, the TU MUST be informed of + * a timeout, and the client transaction MUST transition to the terminated state. + * https://tools.ietf.org/html/rfc3261#section-17.1.2.2 + */ + NonInviteClientTransaction.prototype.timer_F = function () { + this.logger.debug("Timer F expired for non-INVITE client transaction " + this.id + "."); + if (this.state === transaction_state_1.TransactionState.Trying || this.state === transaction_state_1.TransactionState.Proceeding) { + this.onRequestTimeout(); + this.stateTransition(transaction_state_1.TransactionState.Terminated); + } + }; + /** + * If Timer K fires while in this (COMPLETED) state, the client transaction + * MUST transition to the "Terminated" state. + * https://tools.ietf.org/html/rfc3261#section-17.1.2.2 + */ + NonInviteClientTransaction.prototype.timer_K = function () { + if (this.state === transaction_state_1.TransactionState.Completed) { + this.stateTransition(transaction_state_1.TransactionState.Terminated); + } + }; + return NonInviteClientTransaction; +}(client_transaction_1.ClientTransaction)); +exports.NonInviteClientTransaction = NonInviteClientTransaction; diff --git a/lib/Core/transactions/non-invite-server-transaction.d.ts b/lib/Core/transactions/non-invite-server-transaction.d.ts new file mode 100644 index 000000000..597d94807 --- /dev/null +++ b/lib/Core/transactions/non-invite-server-transaction.d.ts @@ -0,0 +1,55 @@ +import { IncomingRequest } from "../../SIPMessage"; +import { Transport } from "../../Transport"; +import { ServerTransaction } from "./server-transaction"; +import { ServerTransactionUser } from "./transaction-user"; +/** + * Non-INVITE Server Transaction + * https://tools.ietf.org/html/rfc3261#section-17.2.2 + */ +export declare class NonInviteServerTransaction extends ServerTransaction { + private lastResponse; + private J; + /** + * Constructor. + * After construction the transaction will be in the "trying": state and the transaction + * `id` will equal the branch parameter set in the Via header of the incoming request. + * https://tools.ietf.org/html/rfc3261#section-17.2.2 + * @param request Incoming Non-INVITE request from the transport. + * @param transport The transport. + * @param user The transaction user. + */ + constructor(request: IncomingRequest, transport: Transport, user: ServerTransactionUser); + /** + * Destructor. + */ + dispose(): void; + /** Transaction kind. Deprecated. */ + readonly kind: string; + /** + * Receive requests from transport matching this transaction. + * @param request Request matching this transaction. + */ + receiveRequest(request: IncomingRequest): void; + /** + * Receive responses from TU for this transaction. + * @param statusCode Status code of repsonse. 101-199 not allowed per RFC 4320. + * @param response Response to send. + */ + receiveResponse(statusCode: number, response: string): void; + /** + * First, the procedures in [4] are followed, which attempt to deliver the response to a backup. + * If those should all fail, based on the definition of failure in [4], the server transaction SHOULD + * inform the TU that a failure has occurred, and SHOULD transition to the terminated state. + * https://tools.ietf.org/html/rfc3261#section-17.2.4 + */ + protected onTransportError(error: Error): void; + /** For logging. */ + protected typeToString(): string; + private stateTransition; + /** + * The server transaction remains in this state until Timer J fires, + * at which point it MUST transition to the "Terminated" state. + * https://tools.ietf.org/html/rfc3261#section-17.2.2 + */ + private timer_J; +} diff --git a/lib/Core/transactions/non-invite-server-transaction.js b/lib/Core/transactions/non-invite-server-transaction.js new file mode 100644 index 000000000..7face9b1c --- /dev/null +++ b/lib/Core/transactions/non-invite-server-transaction.js @@ -0,0 +1,241 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Timers_1 = require("../../Timers"); +var server_transaction_1 = require("./server-transaction"); +var transaction_state_1 = require("./transaction-state"); +/** + * Non-INVITE Server Transaction + * https://tools.ietf.org/html/rfc3261#section-17.2.2 + */ +var NonInviteServerTransaction = /** @class */ (function (_super) { + __extends(NonInviteServerTransaction, _super); + /** + * Constructor. + * After construction the transaction will be in the "trying": state and the transaction + * `id` will equal the branch parameter set in the Via header of the incoming request. + * https://tools.ietf.org/html/rfc3261#section-17.2.2 + * @param request Incoming Non-INVITE request from the transport. + * @param transport The transport. + * @param user The transaction user. + */ + function NonInviteServerTransaction(request, transport, user) { + return _super.call(this, request, transport, user, transaction_state_1.TransactionState.Trying, "sip.transaction.nist") || this; + } + /** + * Destructor. + */ + NonInviteServerTransaction.prototype.dispose = function () { + if (this.J) { + clearTimeout(this.J); + this.J = undefined; + } + _super.prototype.dispose.call(this); + }; + Object.defineProperty(NonInviteServerTransaction.prototype, "kind", { + /** Transaction kind. Deprecated. */ + get: function () { + return "nist"; + }, + enumerable: true, + configurable: true + }); + /** + * Receive requests from transport matching this transaction. + * @param request Request matching this transaction. + */ + NonInviteServerTransaction.prototype.receiveRequest = function (request) { + var _this = this; + switch (this.state) { + case transaction_state_1.TransactionState.Trying: + // Once in the "Trying" state, any further request retransmissions are discarded. + // https://tools.ietf.org/html/rfc3261#section-17.2.2 + break; + case transaction_state_1.TransactionState.Proceeding: + // If a retransmission of the request is received while in the "Proceeding" state, + // the most recently sent provisional response MUST be passed to the transport layer for retransmission. + // https://tools.ietf.org/html/rfc3261#section-17.2.2 + if (!this.lastResponse) { + throw new Error("Last response undefined."); + } + this.send(this.lastResponse).catch(function (error) { + _this.logTransportError(error, "Failed to send retransmission of provisional response."); + }); + break; + case transaction_state_1.TransactionState.Completed: + // While in the "Completed" state, the server transaction MUST pass the final response to the transport + // layer for retransmission whenever a retransmission of the request is received. Any other final responses + // passed by the TU to the server transaction MUST be discarded while in the "Completed" state. + // https://tools.ietf.org/html/rfc3261#section-17.2.2 + if (!this.lastResponse) { + throw new Error("Last response undefined."); + } + this.send(this.lastResponse).catch(function (error) { + _this.logTransportError(error, "Failed to send retransmission of final response."); + }); + break; + case transaction_state_1.TransactionState.Terminated: + break; + default: + throw new Error("Invalid state " + this.state); + } + }; + /** + * Receive responses from TU for this transaction. + * @param statusCode Status code of repsonse. 101-199 not allowed per RFC 4320. + * @param response Response to send. + */ + NonInviteServerTransaction.prototype.receiveResponse = function (statusCode, response) { + var _this = this; + if (statusCode < 100 || statusCode > 699) { + throw new Error("Invalid status code " + statusCode); + } + // An SIP element MUST NOT send any provisional response with a + // Status-Code other than 100 to a non-INVITE request. + // An SIP element MUST NOT respond to a non-INVITE request with a + // Status-Code of 100 over any unreliable transport, such as UDP, + // before the amount of time it takes a client transaction's Timer E to be reset to T2. + // An SIP element MAY respond to a non-INVITE request with a + // Status-Code of 100 over a reliable transport at any time. + // https://tools.ietf.org/html/rfc4320#section-4.1 + if (statusCode > 100 && statusCode <= 199) { + throw new Error("Provisional response other than 100 not allowed."); + } + switch (this.state) { + case transaction_state_1.TransactionState.Trying: + // While in the "Trying" state, if the TU passes a provisional response + // to the server transaction, the server transaction MUST enter the "Proceeding" state. + // The response MUST be passed to the transport layer for transmission. + // https://tools.ietf.org/html/rfc3261#section-17.2.2 + this.lastResponse = response; + if (statusCode >= 100 && statusCode < 200) { + this.stateTransition(transaction_state_1.TransactionState.Proceeding); + this.send(response).catch(function (error) { + _this.logTransportError(error, "Failed to send provisional response."); + }); + return; + } + if (statusCode >= 200 && statusCode <= 699) { + this.stateTransition(transaction_state_1.TransactionState.Completed); + this.send(response).catch(function (error) { + _this.logTransportError(error, "Failed to send final response."); + }); + return; + } + break; + case transaction_state_1.TransactionState.Proceeding: + // Any further provisional responses that are received from the TU while + // in the "Proceeding" state MUST be passed to the transport layer for transmission. + // If the TU passes a final response (status codes 200-699) to the server while in + // the "Proceeding" state, the transaction MUST enter the "Completed" state, and + // the response MUST be passed to the transport layer for transmission. + // https://tools.ietf.org/html/rfc3261#section-17.2.2 + this.lastResponse = response; + if (statusCode >= 200 && statusCode <= 699) { + this.stateTransition(transaction_state_1.TransactionState.Completed); + this.send(response).catch(function (error) { + _this.logTransportError(error, "Failed to send final response."); + }); + return; + } + break; + case transaction_state_1.TransactionState.Completed: + // Any other final responses passed by the TU to the server + // transaction MUST be discarded while in the "Completed" state. + // https://tools.ietf.org/html/rfc3261#section-17.2.2 + return; + case transaction_state_1.TransactionState.Terminated: + break; + default: + throw new Error("Invalid state " + this.state); + } + var message = "Non-INVITE server transaction received unexpected " + statusCode + " response from TU while in state " + this.state + "."; + this.logger.error(message); + throw new Error(message); + }; + /** + * First, the procedures in [4] are followed, which attempt to deliver the response to a backup. + * If those should all fail, based on the definition of failure in [4], the server transaction SHOULD + * inform the TU that a failure has occurred, and SHOULD transition to the terminated state. + * https://tools.ietf.org/html/rfc3261#section-17.2.4 + */ + NonInviteServerTransaction.prototype.onTransportError = function (error) { + if (this.user.onTransportError) { + this.user.onTransportError(error); + } + this.stateTransition(transaction_state_1.TransactionState.Terminated, true); + }; + /** For logging. */ + NonInviteServerTransaction.prototype.typeToString = function () { + return "non-INVITE server transaction"; + }; + NonInviteServerTransaction.prototype.stateTransition = function (newState, dueToTransportError) { + var _this = this; + if (dueToTransportError === void 0) { dueToTransportError = false; } + // Assert valid state transitions. + var invalidStateTransition = function () { + throw new Error("Invalid state transition from " + _this.state + " to " + newState); + }; + switch (newState) { + case transaction_state_1.TransactionState.Trying: + invalidStateTransition(); + break; + case transaction_state_1.TransactionState.Proceeding: + if (this.state !== transaction_state_1.TransactionState.Trying) { + invalidStateTransition(); + } + break; + case transaction_state_1.TransactionState.Completed: + if (this.state !== transaction_state_1.TransactionState.Trying && this.state !== transaction_state_1.TransactionState.Proceeding) { + invalidStateTransition(); + } + break; + case transaction_state_1.TransactionState.Terminated: + if (this.state !== transaction_state_1.TransactionState.Proceeding && this.state !== transaction_state_1.TransactionState.Completed) { + if (!dueToTransportError) { + invalidStateTransition(); + } + } + break; + default: + invalidStateTransition(); + } + // When the server transaction enters the "Completed" state, it MUST set Timer J to fire + // in 64*T1 seconds for unreliable transports, and zero seconds for reliable transports. + // https://tools.ietf.org/html/rfc3261#section-17.2.2 + if (newState === transaction_state_1.TransactionState.Completed) { + this.J = setTimeout(function () { return _this.timer_J(); }, Timers_1.Timers.TIMER_J); + } + // The server transaction MUST be destroyed the instant it enters the "Terminated" state. + // https://tools.ietf.org/html/rfc3261#section-17.2.2 + if (newState === transaction_state_1.TransactionState.Terminated) { + this.dispose(); + } + this.setState(newState); + }; + /** + * The server transaction remains in this state until Timer J fires, + * at which point it MUST transition to the "Terminated" state. + * https://tools.ietf.org/html/rfc3261#section-17.2.2 + */ + NonInviteServerTransaction.prototype.timer_J = function () { + this.logger.debug("Timer J expired for NON-INVITE server transaction " + this.id + "."); + if (this.state === transaction_state_1.TransactionState.Completed) { + this.stateTransition(transaction_state_1.TransactionState.Terminated); + } + }; + return NonInviteServerTransaction; +}(server_transaction_1.ServerTransaction)); +exports.NonInviteServerTransaction = NonInviteServerTransaction; diff --git a/lib/Core/transactions/server-transaction.d.ts b/lib/Core/transactions/server-transaction.d.ts new file mode 100644 index 000000000..3d0f29d3e --- /dev/null +++ b/lib/Core/transactions/server-transaction.d.ts @@ -0,0 +1,33 @@ +import { IncomingRequest } from "../../SIPMessage"; +import { Transport } from "../../Transport"; +import { Transaction } from "./transaction"; +import { TransactionState } from "./transaction-state"; +import { ServerTransactionUser } from "./transaction-user"; +/** + * Server Transaction + * The server transaction is responsible for the delivery of requests to + * the TU and the reliable transmission of responses. It accomplishes + * this through a state machine. Server transactions are created by the + * core when a request is received, and transaction handling is desired + * for that request (this is not always the case). + * https://tools.ietf.org/html/rfc3261#section-17.2 + */ +export declare abstract class ServerTransaction extends Transaction { + private _request; + protected user: ServerTransactionUser; + protected constructor(_request: IncomingRequest, transport: Transport, user: ServerTransactionUser, state: TransactionState, loggerCategory: string); + /** The incoming request the transaction handling. */ + readonly request: IncomingRequest; + /** + * Receive incoming requests from the transport which match this transaction. + * @param request The incoming request. + */ + abstract receiveRequest(request: IncomingRequest): void; + /** + * Receive outgoing responses to this request from the transaction user. + * Responses will be delivered to the transport as necessary. + * @param statusCode Response status code. + * @param response Response. + */ + abstract receiveResponse(statusCode: number, response: string): void; +} diff --git a/lib/Core/transactions/server-transaction.js b/lib/Core/transactions/server-transaction.js new file mode 100644 index 000000000..7983e720c --- /dev/null +++ b/lib/Core/transactions/server-transaction.js @@ -0,0 +1,44 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var transaction_1 = require("./transaction"); +/** + * Server Transaction + * The server transaction is responsible for the delivery of requests to + * the TU and the reliable transmission of responses. It accomplishes + * this through a state machine. Server transactions are created by the + * core when a request is received, and transaction handling is desired + * for that request (this is not always the case). + * https://tools.ietf.org/html/rfc3261#section-17.2 + */ +var ServerTransaction = /** @class */ (function (_super) { + __extends(ServerTransaction, _super); + function ServerTransaction(_request, transport, user, state, loggerCategory) { + var _this = _super.call(this, transport, user, _request.viaBranch, state, loggerCategory) || this; + _this._request = _request; + _this.user = user; + return _this; + } + Object.defineProperty(ServerTransaction.prototype, "request", { + /** The incoming request the transaction handling. */ + get: function () { + return this._request; + }, + enumerable: true, + configurable: true + }); + return ServerTransaction; +}(transaction_1.Transaction)); +exports.ServerTransaction = ServerTransaction; diff --git a/lib/Core/transactions/transaction-state.d.ts b/lib/Core/transactions/transaction-state.d.ts new file mode 100644 index 000000000..b4e366429 --- /dev/null +++ b/lib/Core/transactions/transaction-state.d.ts @@ -0,0 +1,10 @@ +/** Transaction state. */ +export declare enum TransactionState { + Accepted = "Accepted", + Calling = "Calling", + Completed = "Completed", + Confirmed = "Confirmed", + Proceeding = "Proceeding", + Terminated = "Terminated", + Trying = "Trying" +} diff --git a/lib/Core/transactions/transaction-state.js b/lib/Core/transactions/transaction-state.js new file mode 100644 index 000000000..3f88d67ed --- /dev/null +++ b/lib/Core/transactions/transaction-state.js @@ -0,0 +1,13 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +/** Transaction state. */ +var TransactionState; +(function (TransactionState) { + TransactionState["Accepted"] = "Accepted"; + TransactionState["Calling"] = "Calling"; + TransactionState["Completed"] = "Completed"; + TransactionState["Confirmed"] = "Confirmed"; + TransactionState["Proceeding"] = "Proceeding"; + TransactionState["Terminated"] = "Terminated"; + TransactionState["Trying"] = "Trying"; +})(TransactionState = exports.TransactionState || (exports.TransactionState = {})); diff --git a/lib/Core/transactions/transaction-user.d.ts b/lib/Core/transactions/transaction-user.d.ts new file mode 100644 index 000000000..74836d6bf --- /dev/null +++ b/lib/Core/transactions/transaction-user.d.ts @@ -0,0 +1,68 @@ +import { Exceptions } from "../../Exceptions"; +import { LoggerFactory } from "../../LoggerFactory"; +import { IncomingResponse } from "../../SIPMessage"; +import { TransactionState } from "./transaction-state"; +/** + * Transaction User (TU) Interface + * The layer of protocol processing that resides above the transaction layer. + * Transaction users include the UAC core, UAS core, and proxy core. + * https://tools.ietf.org/html/rfc3261#section-5 + * https://tools.ietf.org/html/rfc3261#section-6 + */ +export interface TransactionUser { + /** + * Logger factory. + */ + loggerFactory: LoggerFactory; + /** + * Callback for notification of transaction state changes. + * + * Not called when transaction is constructed, so there is + * no notification of entering the initial transaction state. + * Otherwise, called once for each transaction state change. + * State changes adhere to the following RFCs. + * https://tools.ietf.org/html/rfc3261#section-17 + * https://tools.ietf.org/html/rfc6026 + */ + onStateChange?: (newState: TransactionState) => void; + /** + * Callback for notification of a transport error. + * + * If a fatal transport error is reported by the transport layer + * (generally, due to fatal ICMP errors in UDP or connection failures in + * TCP), the condition MUST be treated as a 503 (Service Unavailable) + * status code. + * https://tools.ietf.org/html/rfc3261#section-8.1.3.1 + * https://tools.ietf.org/html/rfc3261#section-17.1.4 + * https://tools.ietf.org/html/rfc3261#section-17.2.4 + * https://tools.ietf.org/html/rfc6026 + */ + onTransportError?: (error: Exceptions.TransportError) => void; +} +/** + * UAC core Transaction User inteface. + */ +export interface ClientTransactionUser extends TransactionUser { + /** + * Callback for request timeout error. + * + * When a timeout error is received from the transaction layer, it MUST be + * treated as if a 408 (Request Timeout) status code has been received. + * https://tools.ietf.org/html/rfc3261#section-8.1.3.1 + * TU MUST be informed of a timeout. + * https://tools.ietf.org/html/rfc3261#section-17.1.2.2 + */ + onRequestTimeout?: () => void; + /** + * Callback for delegation of valid response handling. + * + * Valid responses are passed up to the TU from the client transaction. + * https://tools.ietf.org/html/rfc3261#section-17.1 + */ + receiveResponse?: (response: IncomingResponse) => void; +} +/** + * UAS core Transaction User interface. + */ +export interface ServerTransactionUser extends TransactionUser { +} diff --git a/lib/Core/transactions/transaction-user.js b/lib/Core/transactions/transaction-user.js new file mode 100644 index 000000000..c8ad2e549 --- /dev/null +++ b/lib/Core/transactions/transaction-user.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/Core/transactions/transaction.d.ts b/lib/Core/transactions/transaction.d.ts new file mode 100644 index 000000000..ae30e73bf --- /dev/null +++ b/lib/Core/transactions/transaction.d.ts @@ -0,0 +1,60 @@ +/// +import { EventEmitter } from "events"; +import { Exceptions } from "../../Exceptions"; +import { Logger } from "../../LoggerFactory"; +import { Transport } from "../../Transport"; +import { TransactionState } from "./transaction-state"; +import { TransactionUser } from "./transaction-user"; +/** + * Transaction + * + * SIP is a transactional protocol: interactions between components take + * place in a series of independent message exchanges. Specifically, a + * SIP transaction consists of a single request and any responses to + * that request, which include zero or more provisional responses and + * one or more final responses. In the case of a transaction where the + * request was an INVITE (known as an INVITE transaction), the + * transaction also includes the ACK only if the final response was not + * a 2xx response. If the response was a 2xx, the ACK is not considered + * part of the transaction. + * https://tools.ietf.org/html/rfc3261#section-17 + */ +export declare abstract class Transaction extends EventEmitter { + private _transport; + private _user; + private _id; + private _state; + protected logger: Logger; + protected constructor(_transport: Transport, _user: TransactionUser, _id: string, _state: TransactionState, loggerCategory: string); + /** + * Destructor. + * Once the transaction is in the "terminated" state, it is destroyed + * immediately and there is no need to call `dispose`. However, if a + * transaction needs to be ended prematurely, the transaction user may + * do so by calling this method (for example, perhaps the UA is shutting down). + * No state transition will occur upon calling this method, all outstanding + * transmission timers will be cancelled, and use of the transaction after + * calling `dispose` is undefined. + */ + dispose(): void; + /** Transaction id. */ + readonly id: string; + /** Transaction kind. Deprecated. */ + readonly kind: string; + /** Transaction state. */ + readonly state: TransactionState; + /** Transaction transport. */ + readonly transport: Transport; + /** Subscribe to 'stateChanged' event. */ + on(name: "stateChanged", callback: () => void): this; + protected logTransportError(error: Exceptions.TransportError, message: string): void; + protected abstract onTransportError(error: Exceptions.TransportError): void; + /** + * Pass message to transport for transmission. If transport fails, + * the transaction user is notified by callback to onTransportError(). + * @throws {TransportError} If transport fails. + */ + protected send(message: string): Promise; + protected setState(state: TransactionState): void; + protected typeToString(): string; +} diff --git a/lib/Core/transactions/transaction.js b/lib/Core/transactions/transaction.js new file mode 100644 index 000000000..ea18a1686 --- /dev/null +++ b/lib/Core/transactions/transaction.js @@ -0,0 +1,134 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var events_1 = require("events"); +var Exceptions_1 = require("../../Exceptions"); +/** + * Transaction + * + * SIP is a transactional protocol: interactions between components take + * place in a series of independent message exchanges. Specifically, a + * SIP transaction consists of a single request and any responses to + * that request, which include zero or more provisional responses and + * one or more final responses. In the case of a transaction where the + * request was an INVITE (known as an INVITE transaction), the + * transaction also includes the ACK only if the final response was not + * a 2xx response. If the response was a 2xx, the ACK is not considered + * part of the transaction. + * https://tools.ietf.org/html/rfc3261#section-17 + */ +var Transaction = /** @class */ (function (_super) { + __extends(Transaction, _super); + function Transaction(_transport, _user, _id, _state, loggerCategory) { + var _this = _super.call(this) || this; + _this._transport = _transport; + _this._user = _user; + _this._id = _id; + _this._state = _state; + _this.logger = _user.loggerFactory.getLogger(loggerCategory, _id); + _this.logger.debug("Constructing " + _this.typeToString() + " with id " + _this.id + "."); + return _this; + } + /** + * Destructor. + * Once the transaction is in the "terminated" state, it is destroyed + * immediately and there is no need to call `dispose`. However, if a + * transaction needs to be ended prematurely, the transaction user may + * do so by calling this method (for example, perhaps the UA is shutting down). + * No state transition will occur upon calling this method, all outstanding + * transmission timers will be cancelled, and use of the transaction after + * calling `dispose` is undefined. + */ + Transaction.prototype.dispose = function () { + this.logger.debug("Destroyed " + this.typeToString() + " with id " + this.id + "."); + }; + Object.defineProperty(Transaction.prototype, "id", { + /** Transaction id. */ + get: function () { + return this._id; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Transaction.prototype, "kind", { + /** Transaction kind. Deprecated. */ + get: function () { + throw new Error("Invalid kind."); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Transaction.prototype, "state", { + /** Transaction state. */ + get: function () { + return this._state; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Transaction.prototype, "transport", { + /** Transaction transport. */ + get: function () { + return this._transport; + }, + enumerable: true, + configurable: true + }); + Transaction.prototype.on = function (name, callback) { return _super.prototype.on.call(this, name, callback); }; + Transaction.prototype.logTransportError = function (error, message) { + this.logger.error(error.message); + this.logger.error("Transport error occurred in " + this.typeToString() + " with id " + this.id + "."); + this.logger.error(message); + }; + /** + * Pass message to transport for transmission. If transport fails, + * the transaction user is notified by callback to onTransportError(). + * @throws {TransportError} If transport fails. + */ + Transaction.prototype.send = function (message) { + var _this = this; + return this.transport.send(message).catch(function (error) { + // FIXME: Transport is not, yet, typed and it is not clear + // yet what send() may or may not send our way. So for now, + // make sure we convert it to a TransportError if need be. + if (error instanceof Exceptions_1.Exceptions.TransportError) { + _this.onTransportError(error); + return; + } + var transportError; + if (error && typeof error.message === "string") { + transportError = new Exceptions_1.Exceptions.TransportError(error.message); + } + else { + transportError = new Exceptions_1.Exceptions.TransportError(); + } + _this.onTransportError(transportError); + throw transportError; + }); + }; + Transaction.prototype.setState = function (state) { + this.logger.debug("State change to \"" + state + "\" on " + this.typeToString() + " with id " + this.id + "."); + this._state = state; + if (this._user.onStateChange) { + this._user.onStateChange(state); + } + this.emit("stateChanged"); + }; + Transaction.prototype.typeToString = function () { + return "UnknownType"; + }; + return Transaction; +}(events_1.EventEmitter)); +exports.Transaction = Transaction; diff --git a/lib/Core/user-agent-core/allowed-methods.d.ts b/lib/Core/user-agent-core/allowed-methods.d.ts new file mode 100644 index 000000000..c0f99a550 --- /dev/null +++ b/lib/Core/user-agent-core/allowed-methods.d.ts @@ -0,0 +1,4 @@ +/** + * FIXME: TODO: Should be configurable/variable. + */ +export declare const AllowedMethods: string[]; diff --git a/lib/Core/user-agent-core/allowed-methods.js b/lib/Core/user-agent-core/allowed-methods.js new file mode 100644 index 000000000..e824e4586 --- /dev/null +++ b/lib/Core/user-agent-core/allowed-methods.js @@ -0,0 +1,19 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var Constants_1 = require("../../Constants"); +/** + * FIXME: TODO: Should be configurable/variable. + */ +exports.AllowedMethods = [ + Constants_1.C.ACK, + Constants_1.C.BYE, + Constants_1.C.CANCEL, + Constants_1.C.INFO, + Constants_1.C.INVITE, + Constants_1.C.MESSAGE, + Constants_1.C.NOTIFY, + Constants_1.C.OPTIONS, + Constants_1.C.PRACK, + Constants_1.C.REFER, + Constants_1.C.SUBSCRIBE +]; diff --git a/lib/Core/user-agent-core/index.d.ts b/lib/Core/user-agent-core/index.d.ts new file mode 100644 index 000000000..189fc40b8 --- /dev/null +++ b/lib/Core/user-agent-core/index.d.ts @@ -0,0 +1,3 @@ +export * from "./user-agent-core"; +export * from "./user-agent-core-configuration"; +export * from "./user-agent-core-delegate"; diff --git a/lib/Core/user-agent-core/index.js b/lib/Core/user-agent-core/index.js new file mode 100644 index 000000000..097aa809f --- /dev/null +++ b/lib/Core/user-agent-core/index.js @@ -0,0 +1,7 @@ +"use strict"; +function __export(m) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; +} +Object.defineProperty(exports, "__esModule", { value: true }); +__export(require("./user-agent-core")); +__export(require("./user-agent-core-configuration")); diff --git a/lib/Core/user-agent-core/user-agent-core-configuration.d.ts b/lib/Core/user-agent-core/user-agent-core-configuration.d.ts new file mode 100644 index 000000000..6929822af --- /dev/null +++ b/lib/Core/user-agent-core/user-agent-core-configuration.d.ts @@ -0,0 +1,102 @@ +import { DigestAuthentication } from "../../DigestAuthentication"; +import { LoggerFactory } from "../../LoggerFactory"; +import { IncomingResponse as IncomingResponseMessage, OutgoingRequest as OutgoingRequestMessage } from "../../SIPMessage"; +import { Transport } from "../../Transport"; +import { UA } from "../../UA"; +import { URI } from "../../URI"; +/** + * This is ported from UA.contact. + * FIXME: TODO: This is not a great rep for Contact + * and is used in a kinda hacky way herein. + */ +interface Contact { + pubGruu: URI | undefined; + tempGruu: URI | undefined; + uri: URI; + toString: (options?: any) => string; +} +/** + * User agent core configuration. + */ +export interface UserAgentCoreConfiguration { + /** + * Address-of-Record (AOR). + * https://tools.ietf.org/html/rfc3261#section-6 + */ + aor: URI; + /** + * Contact. + * https://tools.ietf.org/html/rfc3261#section-8.1.1.8 + */ + contact: Contact; + /** + * Logger factory. + */ + loggerFactory: LoggerFactory; + /** + * User-Agent header field value. + * https://tools.ietf.org/html/rfc3261#section-20.41 + */ + userAgentHeaderFieldValue: string | undefined; + /** + * DEPRECATED + * Authentication factory function. + */ + authenticationFactory(): DigestAuthentication | undefined; + /** + * DEPRECATED: This is a hack to get around `IncomingResponseMessage` + * requiring a `UA` for construction. Hopefully that will go away soon. + * Meanwhile, this method is here to avoid leaking `UA` further than it + * needs to be. Please remove this when no longer needed here. + * + * Returns a "fake" 408 (Request Timeout) response. + */ + onRequestTimeoutResponseMessageFactory(): IncomingResponseMessage; + /** + * DEPRECATED: This is a hack to get around `IncomingResponseMessage` + * requiring a `UA` for construction. Hopefully that will go away soon. + * Meanwhile, this method is here to avoid leaking `UA` further than it + * needs to be. Please remove this when no longer needed here. + * + * Returns a "fake" 503 (Service Unavailable) response. + */ + onTransportErrorResponseMessageFactory(): IncomingResponseMessage; + /** + * DEPRECATED: This is a hack to get around `OutgoingRequestMessage` + * requiring a `UA` for construction. Hopefully that will go away soon. + * Meanwhile, this method is here to avoid leaking `UA` further than it + * needs to be. Please remove this when no longer needed here. + * It's simply a cover function for OutgoingRequestMessage constructor + * + * Outgoing request message factory function. + * @param method Method. + * @param ruri Request-URI. + * @param params Various parameters. + * @param extraHeaders Extra headers to add. + * @param body Message body. + */ + outgoingRequestMessageFactory(method: string, ruri: string | URI, params: { + callId?: string; + cseq?: number; + toTag?: string; + toUri?: URI; + fromDisplayName?: string; + fromTag?: string; + fromUri?: URI; + routeSet?: string[]; + }, extraHeaders?: Array, body?: string | { + body: string; + contentType: string; + }): OutgoingRequestMessage; + /** + * DEPRECATED: This is a hack to get around `Transport` + * requiring the `UA` to start for construction. + */ + transportAccessor(): Transport | undefined; +} +/** + * Factory function to generate configuration give a UA. + * @param ua UA + */ +export declare function makeUserAgentCoreConfigurationFromUA(ua: UA): UserAgentCoreConfiguration; +export {}; diff --git a/lib/Core/user-agent-core/user-agent-core-configuration.js b/lib/Core/user-agent-core/user-agent-core-configuration.js new file mode 100644 index 000000000..1f710959b --- /dev/null +++ b/lib/Core/user-agent-core/user-agent-core-configuration.js @@ -0,0 +1,42 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var SIPMessage_1 = require("../../SIPMessage"); +var URI_1 = require("../../URI"); +/** + * Factory function to generate configuration give a UA. + * @param ua UA + */ +function makeUserAgentCoreConfigurationFromUA(ua) { + // FIXME: Configuration URI is a bad mix of types currently. It also needs to exist. + if (!(ua.configuration.uri instanceof URI_1.URI)) { + throw new Error("Configuration URI not instance of URI."); + } + var configuration = { + aor: ua.configuration.uri, + contact: ua.contact, + loggerFactory: ua.getLoggerFactory(), + userAgentHeaderFieldValue: ua.configuration.userAgentString, + authenticationFactory: function () { + if (ua.configuration.authenticationFactory) { + return ua.configuration.authenticationFactory(ua); + } + return undefined; + }, + onRequestTimeoutResponseMessageFactory: function () { + var message = new SIPMessage_1.IncomingResponse(ua); + message.statusCode = 408; + message.reasonPhrase = "Request Timeout"; + return message; + }, + onTransportErrorResponseMessageFactory: function () { + var message = new SIPMessage_1.IncomingResponse(ua); + message.statusCode = 503; + message.reasonPhrase = "Service Unavailable"; + return message; + }, + outgoingRequestMessageFactory: function (method, ruri, params, extraHeaders, body) { return new SIPMessage_1.OutgoingRequest(method, ruri, ua, params, extraHeaders, body); }, + transportAccessor: function () { return ua.transport; } + }; + return configuration; +} +exports.makeUserAgentCoreConfigurationFromUA = makeUserAgentCoreConfigurationFromUA; diff --git a/lib/Core/user-agent-core/user-agent-core-delegate.d.ts b/lib/Core/user-agent-core/user-agent-core-delegate.d.ts new file mode 100644 index 000000000..a8400fc2b --- /dev/null +++ b/lib/Core/user-agent-core/user-agent-core-delegate.d.ts @@ -0,0 +1,31 @@ +import { IncomingInviteRequest, IncomingMessageRequest, IncomingNotifyRequest, IncomingReferRequest, IncomingSubscribeRequest } from "../messages"; +/** + * User agent core delegate. + */ +export interface UserAgentCoreDelegate { + /** + * Receive INVITE request. + * @param request Incoming INVITE request. + */ + onInvite?(request: IncomingInviteRequest): void; + /** + * Receive MESSAGE request. + * @param request Incoming MESSAGE request. + */ + onMessage?(request: IncomingMessageRequest): void; + /** + * DEPRECATED. Receive NOTIFY request. + * @param message Incoming NOTIFY request. + */ + onNotify?(request: IncomingNotifyRequest): void; + /** + * Receive REFER request. + * @param request Incoming REFER request. + */ + onRefer?(request: IncomingReferRequest): void; + /** + * Receive SUBSCRIBE request. + * @param request Incoming SUBSCRIBE request. + */ + onSubscribe?(request: IncomingSubscribeRequest): void; +} diff --git a/lib/Core/user-agent-core/user-agent-core-delegate.js b/lib/Core/user-agent-core/user-agent-core-delegate.js new file mode 100644 index 000000000..c8ad2e549 --- /dev/null +++ b/lib/Core/user-agent-core/user-agent-core-delegate.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/Core/user-agent-core/user-agent-core.d.ts b/lib/Core/user-agent-core/user-agent-core.d.ts new file mode 100644 index 000000000..303972029 --- /dev/null +++ b/lib/Core/user-agent-core/user-agent-core.d.ts @@ -0,0 +1,164 @@ +import { LoggerFactory } from "../../LoggerFactory"; +import { IncomingRequest as IncomingRequestMessage, IncomingResponse as IncomingResponseMessage, OutgoingRequest as OutgoingRequestMessage } from "../../SIPMessage"; +import { Transport } from "../../Transport"; +import { Dialog } from ".././dialogs"; +import { OutgoingInviteRequest, OutgoingInviteRequestDelegate, OutgoingMessageRequest, OutgoingPublishRequest, OutgoingRegisterRequest, OutgoingRequest, OutgoingRequestDelegate, OutgoingResponse, OutgoingSubscribeRequest, OutgoingSubscribeRequestDelegate, ResponseOptions } from "../messages"; +import { SubscribeUserAgentClient, UserAgentClient, UserAgentServer } from "../user-agents"; +import { UserAgentCoreConfiguration } from "./user-agent-core-configuration"; +import { UserAgentCoreDelegate } from "./user-agent-core-delegate"; +/** + * Core: Core designates the functions specific to a particular type + * of SIP entity, i.e., specific to either a stateful or stateless + * proxy, a user agent or registrar. All cores, except those for + * the stateless proxy, are transaction users. + * https://tools.ietf.org/html/rfc3261#section-6 + * + * UAC Core: The set of processing functions required of a UAC that + * reside above the transaction and transport layers. + * https://tools.ietf.org/html/rfc3261#section-6 + * + * UAS Core: The set of processing functions required at a UAS that + * resides above the transaction and transport layers. + * https://tools.ietf.org/html/rfc3261#section-6 + */ +export declare class UserAgentCore { + /** Configuration. */ + configuration: UserAgentCoreConfiguration; + /** Delegate. */ + delegate: UserAgentCoreDelegate; + /** Dialogs. */ + dialogs: Map; + /** Subscribers. */ + subscribers: Map; + /** UACs. */ + userAgentClients: Map; + /** UASs. */ + userAgentServers: Map; + private logger; + /** + * Constructor. + * @param configuration Configuration. + * @param delegate Delegate. + */ + constructor(configuration: UserAgentCoreConfiguration, delegate?: UserAgentCoreDelegate); + /** Destructor. */ + dispose(): void; + /** Logger factory. */ + readonly loggerFactory: LoggerFactory; + /** Transport. */ + readonly transport: Transport; + /** + * Send INVITE. + * @param request Outgoing request. + * @param delegate Request delegate. + */ + invite(request: OutgoingRequestMessage, delegate?: OutgoingInviteRequestDelegate): OutgoingInviteRequest; + /** + * Send MESSAGE. + * @param request Outgoing request. + * @param delegate Request delegate. + */ + message(request: OutgoingRequestMessage, delegate?: OutgoingRequestDelegate): OutgoingMessageRequest; + /** + * Send PUBLISH. + * @param request Outgoing request. + * @param delegate Request delegate. + */ + publish(request: OutgoingRequestMessage, delegate?: OutgoingRequestDelegate): OutgoingPublishRequest; + /** + * Send REGISTER. + * @param request Outgoing request. + * @param delegate Request delegate. + */ + register(request: OutgoingRequestMessage, delegate?: OutgoingRequestDelegate): OutgoingRegisterRequest; + /** + * Send SUBSCRIBE. + * @param request Outgoing request. + * @param delegate Request delegate. + */ + subscribe(request: OutgoingRequestMessage, delegate?: OutgoingSubscribeRequestDelegate): OutgoingSubscribeRequest; + /** + * Send a request. + * @param request Outgoing request. + * @param delegate Request delegate. + */ + request(request: OutgoingRequestMessage, delegate?: OutgoingRequestDelegate): OutgoingRequest; + /** + * Handle an incoming request message from the transport. + * @param message Incoming request message from transport layer. + */ + receiveIncomingRequestFromTransport(message: IncomingRequestMessage): void; + /** + * Handle an incoming response message from the transport. + * @param message Incoming response message from transport layer. + */ + receiveIncomingResponseFromTransport(message: IncomingResponseMessage): void; + /** + * A stateless UAS is a UAS that does not maintain transaction state. + * It replies to requests normally, but discards any state that would + * ordinarily be retained by a UAS after a response has been sent. If a + * stateless UAS receives a retransmission of a request, it regenerates + * the response and re-sends it, just as if it were replying to the first + * instance of the request. A UAS cannot be stateless unless the request + * processing for that method would always result in the same response + * if the requests are identical. This rules out stateless registrars, + * for example. Stateless UASs do not use a transaction layer; they + * receive requests directly from the transport layer and send responses + * directly to the transport layer. + * https://tools.ietf.org/html/rfc3261#section-8.2.7 + * @param message Incoming request message to reply to. + * @param statusCode Status code to reply with. + */ + replyStateless(message: IncomingRequestMessage, options: ResponseOptions): OutgoingResponse; + /** + * In Section 18.2.1, replace the last paragraph with: + * + * Next, the server transport attempts to match the request to a + * server transaction. It does so using the matching rules described + * in Section 17.2.3. If a matching server transaction is found, the + * request is passed to that transaction for processing. If no match + * is found, the request is passed to the core, which may decide to + * construct a new server transaction for that request. + * https://tools.ietf.org/html/rfc6026#section-8.10 + * @param message Incoming request message from transport layer. + */ + private receiveRequestFromTransport; + /** + * UAC and UAS procedures depend strongly on two factors. First, based + * on whether the request or response is inside or outside of a dialog, + * and second, based on the method of a request. Dialogs are discussed + * thoroughly in Section 12; they represent a peer-to-peer relationship + * between user agents and are established by specific SIP methods, such + * as INVITE. + * @param message Incoming request message. + */ + private receiveRequest; + /** + * Once a dialog has been established between two UAs, either of them + * MAY initiate new transactions as needed within the dialog. The UA + * sending the request will take the UAC role for the transaction. The + * UA receiving the request will take the UAS role. Note that these may + * be different roles than the UAs held during the transaction that + * established the dialog. + * https://tools.ietf.org/html/rfc3261#section-12.2 + * @param message Incoming request message. + */ + private receiveInsideDialogRequest; + /** + * Assuming all of the checks in the previous subsections are passed, + * the UAS processing becomes method-specific. + * https://tools.ietf.org/html/rfc3261#section-8.2.5 + * @param message Incoming request message. + */ + private receiveOutsideDialogRequest; + /** + * Responses are first processed by the transport layer and then passed + * up to the transaction layer. The transaction layer performs its + * processing and then passes the response up to the TU. The majority + * of response processing in the TU is method specific. However, there + * are some general behaviors independent of the method. + * https://tools.ietf.org/html/rfc3261#section-8.1.3 + * @param message Incoming response message from transport layer. + */ + private receiveResponseFromTransport; +} diff --git a/lib/Core/user-agent-core/user-agent-core.js b/lib/Core/user-agent-core/user-agent-core.js new file mode 100644 index 000000000..3285ad0e9 --- /dev/null +++ b/lib/Core/user-agent-core/user-agent-core.js @@ -0,0 +1,757 @@ +"use strict"; +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +var Constants_1 = require("../../Constants"); +var messages_1 = require("../messages"); +var transactions_1 = require("../transactions"); +var user_agents_1 = require("../user-agents"); +var allowed_methods_1 = require("./allowed-methods"); +/** + * This is ported from UA.C.ACCEPTED_BODY_TYPES. + * FIXME: TODO: Should be configurable/variable. + */ +var acceptedBodyTypes = [ + "application/sdp", + "application/dtmf-relay" +]; +/** + * Core: Core designates the functions specific to a particular type + * of SIP entity, i.e., specific to either a stateful or stateless + * proxy, a user agent or registrar. All cores, except those for + * the stateless proxy, are transaction users. + * https://tools.ietf.org/html/rfc3261#section-6 + * + * UAC Core: The set of processing functions required of a UAC that + * reside above the transaction and transport layers. + * https://tools.ietf.org/html/rfc3261#section-6 + * + * UAS Core: The set of processing functions required at a UAS that + * resides above the transaction and transport layers. + * https://tools.ietf.org/html/rfc3261#section-6 + */ +var UserAgentCore = /** @class */ (function () { + /** + * Constructor. + * @param configuration Configuration. + * @param delegate Delegate. + */ + function UserAgentCore(configuration, delegate) { + if (delegate === void 0) { delegate = {}; } + /** UACs. */ + this.userAgentClients = new Map(); + /** UASs. */ + this.userAgentServers = new Map(); + this.configuration = configuration; + this.delegate = delegate; + this.dialogs = new Map(); + this.subscribers = new Map(); + this.logger = configuration.loggerFactory.getLogger("sip.user-agent-core"); + } + /** Destructor. */ + UserAgentCore.prototype.dispose = function () { + this.dialogs.forEach(function (dialog) { return dialog.dispose(); }); + this.dialogs.clear(); + this.subscribers.forEach(function (subscriber) { return subscriber.dispose(); }); + this.subscribers.clear(); + this.userAgentClients.forEach(function (uac) { return uac.dispose(); }); + this.userAgentClients.clear(); + this.userAgentServers.forEach(function (uac) { return uac.dispose(); }); + this.userAgentServers.clear(); + }; + Object.defineProperty(UserAgentCore.prototype, "loggerFactory", { + /** Logger factory. */ + get: function () { + return this.configuration.loggerFactory; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(UserAgentCore.prototype, "transport", { + /** Transport. */ + get: function () { + var transport = this.configuration.transportAccessor(); + if (!transport) { + throw new Error("Transport undefined."); + } + return transport; + }, + enumerable: true, + configurable: true + }); + /** + * Send INVITE. + * @param request Outgoing request. + * @param delegate Request delegate. + */ + UserAgentCore.prototype.invite = function (request, delegate) { + return new user_agents_1.InviteUserAgentClient(this, request, delegate); + }; + /** + * Send MESSAGE. + * @param request Outgoing request. + * @param delegate Request delegate. + */ + UserAgentCore.prototype.message = function (request, delegate) { + return new user_agents_1.MessageUserAgentClient(this, request, delegate); + }; + /** + * Send PUBLISH. + * @param request Outgoing request. + * @param delegate Request delegate. + */ + UserAgentCore.prototype.publish = function (request, delegate) { + return new user_agents_1.PublishUserAgentClient(this, request, delegate); + }; + /** + * Send REGISTER. + * @param request Outgoing request. + * @param delegate Request delegate. + */ + UserAgentCore.prototype.register = function (request, delegate) { + return new user_agents_1.RegisterUserAgentClient(this, request, delegate); + }; + /** + * Send SUBSCRIBE. + * @param request Outgoing request. + * @param delegate Request delegate. + */ + UserAgentCore.prototype.subscribe = function (request, delegate) { + return new user_agents_1.SubscribeUserAgentClient(this, request, delegate); + }; + /** + * Send a request. + * @param request Outgoing request. + * @param delegate Request delegate. + */ + UserAgentCore.prototype.request = function (request, delegate) { + return new user_agents_1.UserAgentClient(transactions_1.NonInviteClientTransaction, this, request, delegate); + }; + /** + * Handle an incoming request message from the transport. + * @param message Incoming request message from transport layer. + */ + UserAgentCore.prototype.receiveIncomingRequestFromTransport = function (message) { + this.receiveRequestFromTransport(message); + }; + /** + * Handle an incoming response message from the transport. + * @param message Incoming response message from transport layer. + */ + UserAgentCore.prototype.receiveIncomingResponseFromTransport = function (message) { + this.receiveResponseFromTransport(message); + }; + /** + * A stateless UAS is a UAS that does not maintain transaction state. + * It replies to requests normally, but discards any state that would + * ordinarily be retained by a UAS after a response has been sent. If a + * stateless UAS receives a retransmission of a request, it regenerates + * the response and re-sends it, just as if it were replying to the first + * instance of the request. A UAS cannot be stateless unless the request + * processing for that method would always result in the same response + * if the requests are identical. This rules out stateless registrars, + * for example. Stateless UASs do not use a transaction layer; they + * receive requests directly from the transport layer and send responses + * directly to the transport layer. + * https://tools.ietf.org/html/rfc3261#section-8.2.7 + * @param message Incoming request message to reply to. + * @param statusCode Status code to reply with. + */ + UserAgentCore.prototype.replyStateless = function (message, options) { + var userAgent = this.configuration.userAgentHeaderFieldValue; + options = __assign({}, options, { userAgent: userAgent }); + var response = messages_1.constructOutgoingResponse(message, options); + this.transport.send(response.message); + return response; + }; + /** + * In Section 18.2.1, replace the last paragraph with: + * + * Next, the server transport attempts to match the request to a + * server transaction. It does so using the matching rules described + * in Section 17.2.3. If a matching server transaction is found, the + * request is passed to that transaction for processing. If no match + * is found, the request is passed to the core, which may decide to + * construct a new server transaction for that request. + * https://tools.ietf.org/html/rfc6026#section-8.10 + * @param message Incoming request message from transport layer. + */ + UserAgentCore.prototype.receiveRequestFromTransport = function (message) { + // When a request is received from the network by the server, it has to + // be matched to an existing transaction. This is accomplished in the + // following manner. + // + // The branch parameter in the topmost Via header field of the request + // is examined. If it is present and begins with the magic cookie + // "z9hG4bK", the request was generated by a client transaction + // compliant to this specification. Therefore, the branch parameter + // will be unique across all transactions sent by that client. The + // request matches a transaction if: + // + // 1. the branch parameter in the request is equal to the one in the + // top Via header field of the request that created the + // transaction, and + // + // 2. the sent-by value in the top Via of the request is equal to the + // one in the request that created the transaction, and + // + // 3. the method of the request matches the one that created the + // transaction, except for ACK, where the method of the request + // that created the transaction is INVITE. + // + // This matching rule applies to both INVITE and non-INVITE transactions + // alike. + // + // The sent-by value is used as part of the matching process because + // there could be accidental or malicious duplication of branch + // parameters from different clients. + // https://tools.ietf.org/html/rfc3261#section-17.2.3 + var transactionId = message.viaBranch; // FIXME: Currently only using rule 1... + var uas = this.userAgentServers.get(transactionId); + // When receiving an ACK that matches an existing INVITE server + // transaction and that does not contain a branch parameter containing + // the magic cookie defined in RFC 3261, the matching transaction MUST + // be checked to see if it is in the "Accepted" state. If it is, then + // the ACK must be passed directly to the transaction user instead of + // being absorbed by the transaction state machine. This is necessary + // as requests from RFC 2543 clients will not include a unique branch + // parameter, and the mechanisms for calculating the transaction ID from + // such a request will be the same for both INVITE and ACKs. + // https://tools.ietf.org/html/rfc6026#section-6 + // Any ACKs received from the network while in the "Accepted" state MUST be + // passed directly to the TU and not absorbed. + // https://tools.ietf.org/html/rfc6026#section-7.1 + if (message.method === Constants_1.C.ACK) { + if (uas && uas.transaction.state === transactions_1.TransactionState.Accepted) { + if (uas instanceof user_agents_1.InviteUserAgentServer) { + // These are ACKs matching an INVITE server transaction. + // These should never happen with RFC 3261 compliant user agents + // (would be a broken ACK to negative final response or something) + // but is apparently how RFC 2543 user agents do things. + // We are not currently supporting this case. + // NOTE: Not backwards compatible with RFC 2543 (no support for strict-routing). + this.logger.warn("Discarding out of dialog ACK after 2xx response sent on transaction " + transactionId + "."); + return; + } + } + } + // The CANCEL method requests that the TU at the server side cancel a + // pending transaction. The TU determines the transaction to be + // cancelled by taking the CANCEL request, and then assuming that the + // request method is anything but CANCEL or ACK and applying the + // transaction matching procedures of Section 17.2.3. The matching + // transaction is the one to be cancelled. + // https://tools.ietf.org/html/rfc3261#section-9.2 + if (message.method === Constants_1.C.CANCEL) { + if (uas) { + // Regardless of the method of the original request, as long as the + // CANCEL matched an existing transaction, the UAS answers the CANCEL + // request itself with a 200 (OK) response. + // https://tools.ietf.org/html/rfc3261#section-9.2 + this.replyStateless(message, { statusCode: 200 }); + // If the transaction for the original request still exists, the behavior + // of the UAS on receiving a CANCEL request depends on whether it has already + // sent a final response for the original request. If it has, the CANCEL + // request has no effect on the processing of the original request, no + // effect on any session state, and no effect on the responses generated + // for the original request. If the UAS has not issued a final response + // for the original request, its behavior depends on the method of the + // original request. If the original request was an INVITE, the UAS + // SHOULD immediately respond to the INVITE with a 487 (Request + // Terminated). + // https://tools.ietf.org/html/rfc3261#section-9.2 + if (uas.transaction instanceof transactions_1.InviteServerTransaction && + uas.transaction.state === transactions_1.TransactionState.Proceeding) { + if (uas instanceof user_agents_1.InviteUserAgentServer) { + uas.receiveCancel(message); + } + // A CANCEL request has no impact on the processing of + // transactions with any other method defined in this specification. + // https://tools.ietf.org/html/rfc3261#section-9.2 + } + } + else { + // If the UAS did not find a matching transaction for the CANCEL + // according to the procedure above, it SHOULD respond to the CANCEL + // with a 481 (Call Leg/Transaction Does Not Exist). + // https://tools.ietf.org/html/rfc3261#section-9.2 + this.replyStateless(message, { statusCode: 481 }); + } + return; + } + // If a matching server transaction is found, the request is passed to that + // transaction for processing. + // https://tools.ietf.org/html/rfc6026#section-8.10 + if (uas) { + uas.transaction.receiveRequest(message); + return; + } + // If no match is found, the request is passed to the core, which may decide to + // construct a new server transaction for that request. + // https://tools.ietf.org/html/rfc6026#section-8.10 + this.receiveRequest(message); + return; + }; + /** + * UAC and UAS procedures depend strongly on two factors. First, based + * on whether the request or response is inside or outside of a dialog, + * and second, based on the method of a request. Dialogs are discussed + * thoroughly in Section 12; they represent a peer-to-peer relationship + * between user agents and are established by specific SIP methods, such + * as INVITE. + * @param message Incoming request message. + */ + UserAgentCore.prototype.receiveRequest = function (message) { + // 8.2 UAS Behavior + // UASs SHOULD process the requests in the order of the steps that + // follow in this section (that is, starting with authentication, then + // inspecting the method, the header fields, and so on throughout the + // remainder of this section). + // https://tools.ietf.org/html/rfc3261#section-8.2 + // 8.2.1 Method Inspection + // Once a request is authenticated (or authentication is skipped), the + // UAS MUST inspect the method of the request. If the UAS recognizes + // but does not support the method of a request, it MUST generate a 405 + // (Method Not Allowed) response. Procedures for generating responses + // are described in Section 8.2.6. The UAS MUST also add an Allow + // header field to the 405 (Method Not Allowed) response. The Allow + // header field MUST list the set of methods supported by the UAS + // generating the message. + // https://tools.ietf.org/html/rfc3261#section-8.2.1 + if (!allowed_methods_1.AllowedMethods.includes(message.method)) { + var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); + this.replyStateless(message, { + statusCode: 405, + extraHeaders: [allowHeader] + }); + return; + } + // 8.2.2 Header Inspection + // https://tools.ietf.org/html/rfc3261#section-8.2.2 + if (!message.ruri) { // FIXME: A request message should always have an ruri + throw new Error("Request-URI undefined."); + } + // 8.2.2.1 To and Request-URI + // If the Request-URI uses a scheme not supported by the UAS, it SHOULD + // reject the request with a 416 (Unsupported URI Scheme) response. + // https://tools.ietf.org/html/rfc3261#section-8.2.2.1 + if (message.ruri.scheme !== Constants_1.C.SIP) { + this.replyStateless(message, { statusCode: 416 }); + return; + } + // 8.2.2.1 To and Request-URI + // If the Request-URI does not identify an address that the + // UAS is willing to accept requests for, it SHOULD reject + // the request with a 404 (Not Found) response. + // https://tools.ietf.org/html/rfc3261#section-8.2.2.1 + var ruri = message.ruri; + var ruriMatches = function (uri) { + return !!uri && uri.user === ruri.user; + }; + if (!ruriMatches(this.configuration.aor) && + !(ruriMatches(this.configuration.contact.uri) || + ruriMatches(this.configuration.contact.pubGruu) || + ruriMatches(this.configuration.contact.tempGruu))) { + this.logger.warn("Request-URI does not point to us."); + if (message.method !== Constants_1.C.ACK) { + this.replyStateless(message, { statusCode: 404 }); + } + return; + } + // 8.2.2.1 To and Request-URI + // Other potential sources of received Request-URIs include + // the Contact header fields of requests and responses sent by the UA + // that establish or refresh dialogs. + // https://tools.ietf.org/html/rfc3261#section-8.2.2.1 + if (message.method === Constants_1.C.INVITE) { + if (!message.hasHeader("Contact")) { + this.replyStateless(message, { + statusCode: 400, + reasonPhrase: "Missing Contact Header" + }); + return; + } + } + // 8.2.2.2 Merged Requests + // If the request has no tag in the To header field, the UAS core MUST + // check the request against ongoing transactions. If the From tag, + // Call-ID, and CSeq exactly match those associated with an ongoing + // transaction, but the request does not match that transaction (based + // on the matching rules in Section 17.2.3), the UAS core SHOULD + // generate a 482 (Loop Detected) response and pass it to the server + // transaction. + // + // The same request has arrived at the UAS more than once, following + // different paths, most likely due to forking. The UAS processes + // the first such request received and responds with a 482 (Loop + // Detected) to the rest of them. + // https://tools.ietf.org/html/rfc3261#section-8.2.2.2 + if (!message.toTag) { + var transactionId = message.viaBranch; + if (!this.userAgentServers.has(transactionId)) { + var mergedRequest = Array.from(this.userAgentServers.values()) + .some(function (uas) { + return uas.transaction.request.fromTag === message.fromTag && + uas.transaction.request.callId === message.callId && + uas.transaction.request.cseq === message.cseq; + }); + if (mergedRequest) { + this.replyStateless(message, { statusCode: 482 }); + return; + } + } + } + // 8.2.2.3 Require + // https://tools.ietf.org/html/rfc3261#section-8.2.2.3 + // TODO + // 8.2.3 Content Processing + // https://tools.ietf.org/html/rfc3261#section-8.2.3 + // TODO + // 8.2.4 Applying Extensions + // https://tools.ietf.org/html/rfc3261#section-8.2.4 + // TODO + // 8.2.5 Processing the Request + // Assuming all of the checks in the previous subsections are passed, + // the UAS processing becomes method-specific. + // https://tools.ietf.org/html/rfc3261#section-8.2.5 + // The UAS will receive the request from the transaction layer. If the + // request has a tag in the To header field, the UAS core computes the + // dialog identifier corresponding to the request and compares it with + // existing dialogs. If there is a match, this is a mid-dialog request. + // In that case, the UAS first applies the same processing rules for + // requests outside of a dialog, discussed in Section 8.2. + // https://tools.ietf.org/html/rfc3261#section-12.2.2 + if (message.toTag) { + this.receiveInsideDialogRequest(message); + } + else { + this.receiveOutsideDialogRequest(message); + } + return; + }; + /** + * Once a dialog has been established between two UAs, either of them + * MAY initiate new transactions as needed within the dialog. The UA + * sending the request will take the UAC role for the transaction. The + * UA receiving the request will take the UAS role. Note that these may + * be different roles than the UAs held during the transaction that + * established the dialog. + * https://tools.ietf.org/html/rfc3261#section-12.2 + * @param message Incoming request message. + */ + UserAgentCore.prototype.receiveInsideDialogRequest = function (message) { + // NOTIFY requests are matched to such SUBSCRIBE requests if they + // contain the same "Call-ID", a "To" header field "tag" parameter that + // matches the "From" header field "tag" parameter of the SUBSCRIBE + // request, and the same "Event" header field. Rules for comparisons of + // the "Event" header fields are described in Section 8.2.1. + // https://tools.ietf.org/html/rfc6665#section-4.4.1 + if (message.method === Constants_1.C.NOTIFY) { + var event_1 = message.parseHeader("Event"); + if (!event_1 || !event_1.event) { + this.replyStateless(message, { statusCode: 489 }); + return; + } + // FIXME: Subscriber id should also matching on event id. + var subscriberId = message.callId + message.toTag + event_1.event; + var subscriber = this.subscribers.get(subscriberId); + if (subscriber) { + var uas = new user_agents_1.NotifyUserAgentServer(this, message); + subscriber.onNotify(uas); + return; + } + } + // Requests sent within a dialog, as any other requests, are atomic. If + // a particular request is accepted by the UAS, all the state changes + // associated with it are performed. If the request is rejected, none + // of the state changes are performed. + // + // Note that some requests, such as INVITEs, affect several pieces of + // state. + // + // The UAS will receive the request from the transaction layer. If the + // request has a tag in the To header field, the UAS core computes the + // dialog identifier corresponding to the request and compares it with + // existing dialogs. If there is a match, this is a mid-dialog request. + // https://tools.ietf.org/html/rfc3261#section-12.2.2 + var dialogId = message.callId + message.toTag + message.fromTag; + var dialog = this.dialogs.get(dialogId); + if (dialog) { + // [Sip-implementors] Reg. SIP reinvite, UPDATE and OPTIONS + // You got the question right. + // + // And you got the right answer too. :-) + // + // Thanks, + // Paul + // + // Robert Sparks wrote: + // > So I've lost track of the question during the musing. + // > + // > I _think_ the fundamental question being asked is this: + // > + // > Is an endpoint required to reject (with a 481) an OPTIONS request that + // > arrives with at to-tag but does not match any existing dialog state. + // > (Assuming some earlier requirement hasn't forced another error code). Or + // > is it OK if it just sends + // > a 200 OK anyhow. + // > + // > My take on the collection of specs is that its _not_ ok for it to send + // > the 200 OK anyhow and that it is required to send + // > the 481. I base this primarily on these sentences from 11.2 in 3261: + // > + // > The response to an OPTIONS is constructed using the standard rules + // > for a SIP response as discussed in Section 8.2.6. The response code + // > chosen MUST be the same that would have been chosen had the request + // > been an INVITE. + // > + // > Did I miss the point of the question? + // > + // > On May 15, 2008, at 12:48 PM, Paul Kyzivat wrote: + // > + // >> [Including Robert in hopes of getting his insight on this.] + // https://lists.cs.columbia.edu/pipermail/sip-implementors/2008-May/019178.html + // + // Requests that do not change in any way the state of a dialog may be + // received within a dialog (for example, an OPTIONS request). They are + // processed as if they had been received outside the dialog. + // https://tools.ietf.org/html/rfc3261#section-12.2.2 + if (message.method === Constants_1.C.OPTIONS) { + var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); + var acceptHeader = "Accept: " + acceptedBodyTypes.toString(); + this.replyStateless(message, { + statusCode: 200, + extraHeaders: [allowHeader, acceptHeader] + }); + return; + } + // Pass the incoming request to the dialog for further handling. + dialog.receiveRequest(message); + return; + } + // The most important behaviors of a stateless UAS are the following: + // ... + // o A stateless UAS MUST ignore ACK requests. + // ... + // https://tools.ietf.org/html/rfc3261#section-8.2.7 + if (message.method === Constants_1.C.ACK) { + // If a final response to an INVITE was sent statelessly, + // the corresponding ACK: + // - will not match an existing transaction + // - may have tag in the To header field + // - not not match any existing dialogs + // Absorb unmatched ACKs. + return; + } + // If the request has a tag in the To header field, but the dialog + // identifier does not match any existing dialogs, the UAS may have + // crashed and restarted, or it may have received a request for a + // different (possibly failed) UAS (the UASs can construct the To tags + // so that a UAS can identify that the tag was for a UAS for which it is + // providing recovery). Another possibility is that the incoming + // request has been simply mis-routed. Based on the To tag, the UAS MAY + // either accept or reject the request. Accepting the request for + // acceptable To tags provides robustness, so that dialogs can persist + // even through crashes. UAs wishing to support this capability must + // take into consideration some issues such as choosing monotonically + // increasing CSeq sequence numbers even across reboots, reconstructing + // the route set, and accepting out-of-range RTP timestamps and sequence + // numbers. + // + // If the UAS wishes to reject the request because it does not wish to + // recreate the dialog, it MUST respond to the request with a 481 + // (Call/Transaction Does Not Exist) status code and pass that to the + // server transaction. + // https://tools.ietf.org/html/rfc3261#section-12.2.2 + this.replyStateless(message, { statusCode: 481 }); + return; + }; + /** + * Assuming all of the checks in the previous subsections are passed, + * the UAS processing becomes method-specific. + * https://tools.ietf.org/html/rfc3261#section-8.2.5 + * @param message Incoming request message. + */ + UserAgentCore.prototype.receiveOutsideDialogRequest = function (message) { + switch (message.method) { + case Constants_1.C.ACK: + // Absorb stray out of dialog ACKs + break; + case Constants_1.C.BYE: + // If the BYE does not match an existing dialog, the UAS core SHOULD + // generate a 481 (Call/Transaction Does Not Exist) response and pass + // that to the server transaction. This rule means that a BYE sent + // without tags by a UAC will be rejected. + // https://tools.ietf.org/html/rfc3261#section-15.1.2 + this.replyStateless(message, { statusCode: 481 }); + break; + case Constants_1.C.CANCEL: + throw new Error("Unexpected out of dialog request method " + message.method + "."); + break; + case Constants_1.C.INFO: + // Use of the INFO method does not constitute a separate dialog usage. + // INFO messages are always part of, and share the fate of, an invite + // dialog usage [RFC5057]. INFO messages cannot be sent as part of + // other dialog usages, or outside an existing dialog. + // https://tools.ietf.org/html/rfc6086#section-1 + this.replyStateless(message, { statusCode: 405 }); // Should never happen + break; + case Constants_1.C.INVITE: + // https://tools.ietf.org/html/rfc3261#section-13.3.1 + { + var uas = new user_agents_1.InviteUserAgentServer(this, message); + this.delegate.onInvite ? + this.delegate.onInvite(uas) : + uas.reject(); + } + break; + case Constants_1.C.MESSAGE: + // MESSAGE requests are discouraged inside a dialog. Implementations + // are restricted from creating a usage for the purpose of carrying a + // sequence of MESSAGE requests (though some implementations use it that + // way, against the standard recommendation). + // https://tools.ietf.org/html/rfc5057#section-5.3 + { + var uas = new user_agents_1.MessageUserAgentServer(this, message); + this.delegate.onMessage ? + this.delegate.onMessage(uas) : + uas.accept(); + } + break; + case Constants_1.C.NOTIFY: + // Obsoleted by: RFC 6665 + // If any non-SUBSCRIBE mechanisms are defined to create subscriptions, + // it is the responsibility of the parties defining those mechanisms to + // ensure that correlation of a NOTIFY message to the corresponding + // subscription is possible. Designers of such mechanisms are also + // warned to make a distinction between sending a NOTIFY message to a + // subscriber who is aware of the subscription, and sending a NOTIFY + // message to an unsuspecting node. The latter behavior is invalid, and + // MUST receive a "481 Subscription does not exist" response (unless + // some other 400- or 500-class error code is more applicable), as + // described in section 3.2.4. In other words, knowledge of a + // subscription must exist in both the subscriber and the notifier to be + // valid, even if installed via a non-SUBSCRIBE mechanism. + // https://tools.ietf.org/html/rfc3265#section-3.2 + // + // NOTIFY requests are sent to inform subscribers of changes in state to + // which the subscriber has a subscription. Subscriptions are created + // using the SUBSCRIBE method. In legacy implementations, it is + // possible that other means of subscription creation have been used. + // However, this specification does not allow the creation of + // subscriptions except through SUBSCRIBE requests and (for backwards- + // compatibility) REFER requests [RFC3515]. + // https://tools.ietf.org/html/rfc6665#section-3.2 + { + var uas = new user_agents_1.NotifyUserAgentServer(this, message); + this.delegate.onNotify ? + this.delegate.onNotify(uas) : + this.replyStateless(message, { statusCode: 405 }); + } + break; + case Constants_1.C.OPTIONS: + // https://tools.ietf.org/html/rfc3261#section-11.2 + { + var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); + var acceptHeader = "Accept: " + acceptedBodyTypes.toString(); + this.replyStateless(message, { + statusCode: 200, + extraHeaders: [allowHeader, acceptHeader] + }); + } + break; + case Constants_1.C.REFER: + // https://tools.ietf.org/html/rfc3515#section-2.4.2 + { + var uas = new user_agents_1.ReferUserAgentServer(this, message); + this.delegate.onRefer ? + this.delegate.onRefer(uas) : + this.replyStateless(message, { statusCode: 405 }); + } + break; + case Constants_1.C.SUBSCRIBE: + // https://tools.ietf.org/html/rfc6665#section-4.2 + { + var uas = new user_agents_1.SubscribeUserAgentServer(this, message); + this.delegate.onSubscribe ? + this.delegate.onSubscribe(uas) : + uas.reject(); + } + break; + default: + throw new Error("Unexpected out of dialog request method " + message.method + "."); + } + return; + }; + /** + * Responses are first processed by the transport layer and then passed + * up to the transaction layer. The transaction layer performs its + * processing and then passes the response up to the TU. The majority + * of response processing in the TU is method specific. However, there + * are some general behaviors independent of the method. + * https://tools.ietf.org/html/rfc3261#section-8.1.3 + * @param message Incoming response message from transport layer. + */ + UserAgentCore.prototype.receiveResponseFromTransport = function (message) { + // 8.1.3.1 Transaction Layer Errors + // https://tools.ietf.org/html/rfc3261#section-8.1.3.1 + // Handled by transaction layer callbacks. + // 8.1.3.2 Unrecognized Responses + // https://tools.ietf.org/html/rfc3261#section-8.1.3.1 + // TODO + // 8.1.3.3 Vias + // https://tools.ietf.org/html/rfc3261#section-8.1.3.3 + if (message.getHeaders("via").length > 1) { + this.logger.warn("More than one Via header field present in the response, dropping"); + return; + } + // 8.1.3.4 Processing 3xx Responses + // https://tools.ietf.org/html/rfc3261#section-8.1.3.4 + // TODO + // 8.1.3.5 Processing 4xx Responses + // https://tools.ietf.org/html/rfc3261#section-8.1.3.5 + // TODO + // When the transport layer in the client receives a response, it has to + // determine which client transaction will handle the response, so that + // the processing of Sections 17.1.1 and 17.1.2 can take place. The + // branch parameter in the top Via header field is used for this + // purpose. A response matches a client transaction under two + // conditions: + // + // 1. If the response has the same value of the branch parameter in + // the top Via header field as the branch parameter in the top + // Via header field of the request that created the transaction. + // + // 2. If the method parameter in the CSeq header field matches the + // method of the request that created the transaction. The + // method is needed since a CANCEL request constitutes a + // different transaction, but shares the same value of the branch + // parameter. + // https://tools.ietf.org/html/rfc3261#section-17.1.3 + var userAgentClientId = message.viaBranch + message.method; + var userAgentClient = this.userAgentClients.get(userAgentClientId); + // The client transport uses the matching procedures of Section + // 17.1.3 to attempt to match the response to an existing + // transaction. If there is a match, the response MUST be passed to + // that transaction. Otherwise, any element other than a stateless + // proxy MUST silently discard the response. + // https://tools.ietf.org/html/rfc6026#section-8.9 + if (userAgentClient) { + userAgentClient.transaction.receiveResponse(message); + } + else { + this.logger.warn("Discarding unmatched " + message.statusCode + " response to " + message.method + " " + userAgentClientId + "."); + } + }; + return UserAgentCore; +}()); +exports.UserAgentCore = UserAgentCore; diff --git a/lib/Core/user-agents/bye-user-agent-client.d.ts b/lib/Core/user-agents/bye-user-agent-client.d.ts new file mode 100644 index 000000000..32682e220 --- /dev/null +++ b/lib/Core/user-agents/bye-user-agent-client.d.ts @@ -0,0 +1,6 @@ +import { SessionDialog } from "../dialogs"; +import { OutgoingByeRequest, OutgoingRequestDelegate, RequestOptions } from "../messages"; +import { UserAgentClient } from "./user-agent-client"; +export declare class ByeUserAgentClient extends UserAgentClient implements OutgoingByeRequest { + constructor(dialog: SessionDialog, delegate?: OutgoingRequestDelegate, options?: RequestOptions); +} diff --git a/lib/Core/user-agents/bye-user-agent-client.js b/lib/Core/user-agents/bye-user-agent-client.js new file mode 100644 index 000000000..4e97defa6 --- /dev/null +++ b/lib/Core/user-agents/bye-user-agent-client.js @@ -0,0 +1,30 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Constants_1 = require("../../Constants"); +var transactions_1 = require("../transactions"); +var user_agent_client_1 = require("./user-agent-client"); +var ByeUserAgentClient = /** @class */ (function (_super) { + __extends(ByeUserAgentClient, _super); + function ByeUserAgentClient(dialog, delegate, options) { + var _this = this; + var message = dialog.createOutgoingRequestMessage(Constants_1.C.BYE, options); + _this = _super.call(this, transactions_1.NonInviteClientTransaction, dialog.userAgentCore, message, delegate) || this; + dialog.dispose(); + return _this; + } + return ByeUserAgentClient; +}(user_agent_client_1.UserAgentClient)); +exports.ByeUserAgentClient = ByeUserAgentClient; diff --git a/lib/Core/user-agents/bye-user-agent-server.d.ts b/lib/Core/user-agents/bye-user-agent-server.d.ts new file mode 100644 index 000000000..173851211 --- /dev/null +++ b/lib/Core/user-agents/bye-user-agent-server.d.ts @@ -0,0 +1,7 @@ +import { IncomingRequest as IncomingRequestMessage } from "../../SIPMessage"; +import { SessionDialog } from "../dialogs"; +import { IncomingByeRequest, IncomingRequestDelegate } from "../messages"; +import { UserAgentServer } from "./user-agent-server"; +export declare class ByeUserAgentServer extends UserAgentServer implements IncomingByeRequest { + constructor(dialog: SessionDialog, message: IncomingRequestMessage, delegate?: IncomingRequestDelegate); +} diff --git a/lib/Core/user-agents/bye-user-agent-server.js b/lib/Core/user-agents/bye-user-agent-server.js new file mode 100644 index 000000000..622210dd9 --- /dev/null +++ b/lib/Core/user-agents/bye-user-agent-server.js @@ -0,0 +1,25 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var transactions_1 = require("../transactions"); +var user_agent_server_1 = require("./user-agent-server"); +var ByeUserAgentServer = /** @class */ (function (_super) { + __extends(ByeUserAgentServer, _super); + function ByeUserAgentServer(dialog, message, delegate) { + return _super.call(this, transactions_1.NonInviteServerTransaction, dialog.userAgentCore, message, delegate) || this; + } + return ByeUserAgentServer; +}(user_agent_server_1.UserAgentServer)); +exports.ByeUserAgentServer = ByeUserAgentServer; diff --git a/lib/Core/user-agents/cancel-user-agent-client.d.ts b/lib/Core/user-agents/cancel-user-agent-client.d.ts new file mode 100644 index 000000000..b7bfb4e9b --- /dev/null +++ b/lib/Core/user-agents/cancel-user-agent-client.d.ts @@ -0,0 +1,7 @@ +import { OutgoingRequest as OutgoingRequestMessage } from "../../SIPMessage"; +import { OutgoingCancelRequest, OutgoingRequestDelegate } from "../messages"; +import { UserAgentCore } from "../user-agent-core"; +import { UserAgentClient } from "./user-agent-client"; +export declare class CancelUserAgentClient extends UserAgentClient implements OutgoingCancelRequest { + constructor(core: UserAgentCore, message: OutgoingRequestMessage, delegate?: OutgoingRequestDelegate); +} diff --git a/lib/Core/user-agents/cancel-user-agent-client.js b/lib/Core/user-agents/cancel-user-agent-client.js new file mode 100644 index 000000000..a19f48696 --- /dev/null +++ b/lib/Core/user-agents/cancel-user-agent-client.js @@ -0,0 +1,25 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var transactions_1 = require("../transactions"); +var user_agent_client_1 = require("./user-agent-client"); +var CancelUserAgentClient = /** @class */ (function (_super) { + __extends(CancelUserAgentClient, _super); + function CancelUserAgentClient(core, message, delegate) { + return _super.call(this, transactions_1.NonInviteClientTransaction, core, message, delegate) || this; + } + return CancelUserAgentClient; +}(user_agent_client_1.UserAgentClient)); +exports.CancelUserAgentClient = CancelUserAgentClient; diff --git a/lib/Core/user-agents/index.d.ts b/lib/Core/user-agents/index.d.ts new file mode 100644 index 000000000..1e66f345e --- /dev/null +++ b/lib/Core/user-agents/index.d.ts @@ -0,0 +1,24 @@ +export * from "./bye-user-agent-client"; +export * from "./bye-user-agent-server"; +export * from "./cancel-user-agent-client"; +export * from "./info-user-agent-server"; +export * from "./invite-user-agent-client"; +export * from "./invite-user-agent-server"; +export * from "./message-user-agent-client"; +export * from "./message-user-agent-server"; +export * from "./notify-user-agent-client"; +export * from "./notify-user-agent-server"; +export * from "./publish-user-agent-client"; +export * from "./prack-user-agent-client"; +export * from "./prack-user-agent-server"; +export * from "./re-invite-user-agent-client"; +export * from "./re-invite-user-agent-server"; +export * from "./re-subscribe-user-agent-client"; +export * from "./re-subscribe-user-agent-server"; +export * from "./refer-user-agent-client"; +export * from "./refer-user-agent-server"; +export * from "./register-user-agent-client"; +export * from "./subscribe-user-agent-client"; +export * from "./subscribe-user-agent-server"; +export * from "./user-agent-client"; +export * from "./user-agent-server"; diff --git a/lib/Core/user-agents/index.js b/lib/Core/user-agents/index.js new file mode 100644 index 000000000..faccb5355 --- /dev/null +++ b/lib/Core/user-agents/index.js @@ -0,0 +1,29 @@ +"use strict"; +function __export(m) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; +} +Object.defineProperty(exports, "__esModule", { value: true }); +__export(require("./bye-user-agent-client")); +__export(require("./bye-user-agent-server")); +__export(require("./cancel-user-agent-client")); +__export(require("./info-user-agent-server")); +__export(require("./invite-user-agent-client")); +__export(require("./invite-user-agent-server")); +__export(require("./message-user-agent-client")); +__export(require("./message-user-agent-server")); +__export(require("./notify-user-agent-client")); +__export(require("./notify-user-agent-server")); +__export(require("./publish-user-agent-client")); +__export(require("./prack-user-agent-client")); +__export(require("./prack-user-agent-server")); +__export(require("./re-invite-user-agent-client")); +__export(require("./re-invite-user-agent-server")); +__export(require("./re-subscribe-user-agent-client")); +__export(require("./re-subscribe-user-agent-server")); +__export(require("./refer-user-agent-client")); +__export(require("./refer-user-agent-server")); +__export(require("./register-user-agent-client")); +__export(require("./subscribe-user-agent-client")); +__export(require("./subscribe-user-agent-server")); +__export(require("./user-agent-client")); +__export(require("./user-agent-server")); diff --git a/lib/Core/user-agents/info-user-agent-client.d.ts b/lib/Core/user-agents/info-user-agent-client.d.ts new file mode 100644 index 000000000..54d04ce12 --- /dev/null +++ b/lib/Core/user-agents/info-user-agent-client.d.ts @@ -0,0 +1,6 @@ +import { SessionDialog } from "../dialogs"; +import { OutgoingInfoRequest, OutgoingRequestDelegate, RequestOptions } from "../messages"; +import { UserAgentClient } from "./user-agent-client"; +export declare class InfoUserAgentClient extends UserAgentClient implements OutgoingInfoRequest { + constructor(dialog: SessionDialog, delegate?: OutgoingRequestDelegate, options?: RequestOptions); +} diff --git a/lib/Core/user-agents/info-user-agent-client.js b/lib/Core/user-agents/info-user-agent-client.js new file mode 100644 index 000000000..475913ecf --- /dev/null +++ b/lib/Core/user-agents/info-user-agent-client.js @@ -0,0 +1,29 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Constants_1 = require("../../Constants"); +var transactions_1 = require("../transactions"); +var user_agent_client_1 = require("./user-agent-client"); +var InfoUserAgentClient = /** @class */ (function (_super) { + __extends(InfoUserAgentClient, _super); + function InfoUserAgentClient(dialog, delegate, options) { + var _this = this; + var message = dialog.createOutgoingRequestMessage(Constants_1.C.INFO, options); + _this = _super.call(this, transactions_1.NonInviteClientTransaction, dialog.userAgentCore, message, delegate) || this; + return _this; + } + return InfoUserAgentClient; +}(user_agent_client_1.UserAgentClient)); +exports.InfoUserAgentClient = InfoUserAgentClient; diff --git a/lib/Core/user-agents/info-user-agent-server.d.ts b/lib/Core/user-agents/info-user-agent-server.d.ts new file mode 100644 index 000000000..beb749467 --- /dev/null +++ b/lib/Core/user-agents/info-user-agent-server.d.ts @@ -0,0 +1,7 @@ +import { IncomingRequest as IncomingRequestMessage } from "../../SIPMessage"; +import { SessionDialog } from "../dialogs"; +import { IncomingInfoRequest, IncomingRequestDelegate } from "../messages"; +import { UserAgentServer } from "./user-agent-server"; +export declare class InfoUserAgentServer extends UserAgentServer implements IncomingInfoRequest { + constructor(dialog: SessionDialog, message: IncomingRequestMessage, delegate?: IncomingRequestDelegate); +} diff --git a/lib/Core/user-agents/info-user-agent-server.js b/lib/Core/user-agents/info-user-agent-server.js new file mode 100644 index 000000000..d53e211ef --- /dev/null +++ b/lib/Core/user-agents/info-user-agent-server.js @@ -0,0 +1,25 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var transactions_1 = require("../transactions"); +var user_agent_server_1 = require("./user-agent-server"); +var InfoUserAgentServer = /** @class */ (function (_super) { + __extends(InfoUserAgentServer, _super); + function InfoUserAgentServer(dialog, message, delegate) { + return _super.call(this, transactions_1.NonInviteServerTransaction, dialog.userAgentCore, message, delegate) || this; + } + return InfoUserAgentServer; +}(user_agent_server_1.UserAgentServer)); +exports.InfoUserAgentServer = InfoUserAgentServer; diff --git a/lib/Core/user-agents/invite-user-agent-client.d.ts b/lib/Core/user-agents/invite-user-agent-client.d.ts new file mode 100644 index 000000000..463dc4fb6 --- /dev/null +++ b/lib/Core/user-agents/invite-user-agent-client.d.ts @@ -0,0 +1,27 @@ +import { IncomingResponse as IncomingResponseMessage, OutgoingRequest as OutgoingRequestMessage } from "../../SIPMessage"; +import { OutgoingInviteRequest, OutgoingInviteRequestDelegate } from "../messages"; +import { UserAgentCore } from "../user-agent-core"; +import { UserAgentClient } from "./user-agent-client"; +/** + * 13 Initiating a Session + * https://tools.ietf.org/html/rfc3261#section-13 + * 13.1 Overview + * https://tools.ietf.org/html/rfc3261#section-13.1 + * 13.2 UAC Processing + * https://tools.ietf.org/html/rfc3261#section-13.2 + */ +export declare class InviteUserAgentClient extends UserAgentClient implements OutgoingInviteRequest { + delegate: OutgoingInviteRequestDelegate | undefined; + private confirmedDialogAcks; + private confirmedDialogs; + private earlyDialogs; + constructor(core: UserAgentCore, message: OutgoingRequestMessage, delegate?: OutgoingInviteRequestDelegate); + dispose(): void; + /** + * Once the INVITE has been passed to the INVITE client transaction, the + * UAC waits for responses for the INVITE. + * https://tools.ietf.org/html/rfc3261#section-13.2.2 + * @param incomingResponse Incoming response to INVITE request. + */ + protected receiveResponse(message: IncomingResponseMessage): void; +} diff --git a/lib/Core/user-agents/invite-user-agent-client.js b/lib/Core/user-agents/invite-user-agent-client.js new file mode 100644 index 000000000..6d95d157e --- /dev/null +++ b/lib/Core/user-agents/invite-user-agent-client.js @@ -0,0 +1,295 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var dialogs_1 = require("../dialogs"); +var transactions_1 = require("../transactions"); +var user_agent_client_1 = require("./user-agent-client"); +/** + * 13 Initiating a Session + * https://tools.ietf.org/html/rfc3261#section-13 + * 13.1 Overview + * https://tools.ietf.org/html/rfc3261#section-13.1 + * 13.2 UAC Processing + * https://tools.ietf.org/html/rfc3261#section-13.2 + */ +var InviteUserAgentClient = /** @class */ (function (_super) { + __extends(InviteUserAgentClient, _super); + function InviteUserAgentClient(core, message, delegate) { + var _this = _super.call(this, transactions_1.InviteClientTransaction, core, message, delegate) || this; + _this.confirmedDialogAcks = new Map(); + _this.confirmedDialogs = new Map(); + _this.earlyDialogs = new Map(); + _this.delegate = delegate; + return _this; + } + InviteUserAgentClient.prototype.dispose = function () { + // The UAC core considers the INVITE transaction completed 64*T1 seconds + // after the reception of the first 2xx response. At this point all the + // early dialogs that have not transitioned to established dialogs are + // terminated. Once the INVITE transaction is considered completed by + // the UAC core, no more new 2xx responses are expected to arrive. + // + // If, after acknowledging any 2xx response to an INVITE, the UAC does + // not want to continue with that dialog, then the UAC MUST terminate + // the dialog by sending a BYE request as described in Section 15. + // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 + this.earlyDialogs.forEach(function (earlyDialog) { return earlyDialog.dispose(); }); + this.earlyDialogs.clear(); + _super.prototype.dispose.call(this); + }; + /** + * Once the INVITE has been passed to the INVITE client transaction, the + * UAC waits for responses for the INVITE. + * https://tools.ietf.org/html/rfc3261#section-13.2.2 + * @param incomingResponse Incoming response to INVITE request. + */ + InviteUserAgentClient.prototype.receiveResponse = function (message) { + var _this = this; + if (!this.authenticationGuard(message)) { + return; + } + var statusCode = message.statusCode ? message.statusCode.toString() : ""; + if (!statusCode) { + throw new Error("Response status code undefined."); + } + switch (true) { + case /^100$/.test(statusCode): + if (this.delegate && this.delegate.onTrying) { + this.delegate.onTrying({ message: message }); + } + return; + case /^1[0-9]{2}$/.test(statusCode): + // Zero, one or multiple provisional responses may arrive before one or + // more final responses are received. Provisional responses for an + // INVITE request can create "early dialogs". If a provisional response + // has a tag in the To field, and if the dialog ID of the response does + // not match an existing dialog, one is constructed using the procedures + // defined in Section 12.1.2. + // + // The early dialog will only be needed if the UAC needs to send a + // request to its peer within the dialog before the initial INVITE + // transaction completes. Header fields present in a provisional + // response are applicable as long as the dialog is in the early state + // (for example, an Allow header field in a provisional response + // contains the methods that can be used in the dialog while this is in + // the early state). + // https://tools.ietf.org/html/rfc3261#section-13.2.2.1 + { + // Provisional without to tag, no dialog to create. + if (!message.toTag) { + this.logger.warn("Non-100 1xx INVITE response received without a to tag, dropping."); + return; + } + // Compute dialog state. + var dialogState = dialogs_1.Dialog.initialDialogStateForUserAgentClient(this.message, message); + // Have existing early dialog or create a new one. + var earlyDialog = this.earlyDialogs.get(dialogState.id); + if (!earlyDialog) { + var transaction = this.transaction; + if (!(transaction instanceof transactions_1.InviteClientTransaction)) { + throw new Error("Transaction not instance of InviteClientTransaction."); + } + earlyDialog = new dialogs_1.SessionDialog(transaction, this.core, dialogState); + this.earlyDialogs.set(earlyDialog.id, earlyDialog); + } + // Guard against out of order reliable provisional responses. + // Note that this is where the rseq tracking is done. + if (!earlyDialog.reliableSequenceGuard(message)) { + this.logger.warn("1xx INVITE reliable response received out of order, dropping."); + return; + } + // Update dialog signaling state if need be. + earlyDialog.signalingStateTransition(message); + // Pass response to delegate. + var session_1 = earlyDialog; + if (this.delegate && this.delegate.onProgress) { + this.delegate.onProgress({ + message: message, + session: session_1, + prack: function (options) { + var outgoingPrackRequest = session_1.prack(undefined, options); + return outgoingPrackRequest; + } + }); + } + } + return; + case /^2[0-9]{2}$/.test(statusCode): + // Multiple 2xx responses may arrive at the UAC for a single INVITE + // request due to a forking proxy. Each response is distinguished by + // the tag parameter in the To header field, and each represents a + // distinct dialog, with a distinct dialog identifier. + // + // If the dialog identifier in the 2xx response matches the dialog + // identifier of an existing dialog, the dialog MUST be transitioned to + // the "confirmed" state, and the route set for the dialog MUST be + // recomputed based on the 2xx response using the procedures of Section + // 12.2.1.2. Otherwise, a new dialog in the "confirmed" state MUST be + // constructed using the procedures of Section 12.1.2. + // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 + { + // Compute dialog state. + var dialogState = dialogs_1.Dialog.initialDialogStateForUserAgentClient(this.message, message); + // NOTE: Currently our transaction layer is caching the 2xx ACKs and + // handling retransmissions of the ACK which is an approach which is + // not to spec. In any event, this block is intended to provide a to + // spec implementation of ACK retransmissions, but it should not be + // hit currently. + var dialog = this.confirmedDialogs.get(dialogState.id); + if (dialog) { + // Once the ACK has been constructed, the procedures of [4] are used to + // determine the destination address, port and transport. However, the + // request is passed to the transport layer directly for transmission, + // rather than a client transaction. This is because the UAC core + // handles retransmissions of the ACK, not the transaction layer. The + // ACK MUST be passed to the client transport every time a + // retransmission of the 2xx final response that triggered the ACK + // arrives. + // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 + var outgoingAckRequest = this.confirmedDialogAcks.get(dialogState.id); + if (outgoingAckRequest) { + var transaction = this.transaction; + if (!(transaction instanceof transactions_1.InviteClientTransaction)) { + throw new Error("Client transaction not instance of InviteClientTransaction."); + } + transaction.ackResponse(outgoingAckRequest.message); + } + else { + // If still waiting for an ACK, drop the retransmission of the 2xx final response. + } + return; + } + // If the dialog identifier in the 2xx response matches the dialog + // identifier of an existing dialog, the dialog MUST be transitioned to + // the "confirmed" state, and the route set for the dialog MUST be + // recomputed based on the 2xx response using the procedures of Section + // 12.2.1.2. Otherwise, a new dialog in the "confirmed" state MUST be + // constructed using the procedures of Section 12.1.2. + // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 + dialog = this.earlyDialogs.get(dialogState.id); + if (dialog) { + dialog.confirm(); + dialog.recomputeRouteSet(message); + this.earlyDialogs.delete(dialog.id); + this.confirmedDialogs.set(dialog.id, dialog); + } + else { + var transaction = this.transaction; + if (!(transaction instanceof transactions_1.InviteClientTransaction)) { + throw new Error("Transaction not instance of InviteClientTransaction."); + } + dialog = new dialogs_1.SessionDialog(transaction, this.core, dialogState); + this.confirmedDialogs.set(dialog.id, dialog); + } + // Update dialog signaling state if need be. + dialog.signalingStateTransition(message); + // Session Initiated! :) + var session_2 = dialog; + // The UAC core MUST generate an ACK request for each 2xx received from + // the transaction layer. The header fields of the ACK are constructed + // in the same way as for any request sent within a dialog (see Section + // 12) with the exception of the CSeq and the header fields related to + // authentication. The sequence number of the CSeq header field MUST be + // the same as the INVITE being acknowledged, but the CSeq method MUST + // be ACK. The ACK MUST contain the same credentials as the INVITE. If + // the 2xx contains an offer (based on the rules above), the ACK MUST + // carry an answer in its body. If the offer in the 2xx response is not + // acceptable, the UAC core MUST generate a valid answer in the ACK and + // then send a BYE immediately. + // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 + if (this.delegate && this.delegate.onAccept) { + this.delegate.onAccept({ + message: message, + session: session_2, + ack: function (options) { + var outgoingAckRequest = session_2.ack(options); + _this.confirmedDialogAcks.set(session_2.id, outgoingAckRequest); + return outgoingAckRequest; + } + }); + } + else { + var outgoingAckRequest = session_2.ack(); + this.confirmedDialogAcks.set(session_2.id, outgoingAckRequest); + } + } + return; + case /^3[0-9]{2}$/.test(statusCode): + // 12.3 Termination of a Dialog + // + // Independent of the method, if a request outside of a dialog generates + // a non-2xx final response, any early dialogs created through + // provisional responses to that request are terminated. The mechanism + // for terminating confirmed dialogs is method specific. In this + // specification, the BYE method terminates a session and the dialog + // associated with it. See Section 15 for details. + // https://tools.ietf.org/html/rfc3261#section-12.3 + // All early dialogs are considered terminated upon reception of the + // non-2xx final response. + // + // After having received the non-2xx final response the UAC core + // considers the INVITE transaction completed. The INVITE client + // transaction handles the generation of ACKs for the response (see + // Section 17). + // https://tools.ietf.org/html/rfc3261#section-13.2.2.3 + this.earlyDialogs.forEach(function (earlyDialog) { return earlyDialog.dispose(); }); + this.earlyDialogs.clear(); + // A 3xx response may contain one or more Contact header field values + // providing new addresses where the callee might be reachable. + // Depending on the status code of the 3xx response (see Section 21.3), + // the UAC MAY choose to try those new addresses. + // https://tools.ietf.org/html/rfc3261#section-13.2.2.2 + if (this.delegate && this.delegate.onRedirect) { + this.delegate.onRedirect({ message: message }); + } + return; + case /^[4-6][0-9]{2}$/.test(statusCode): + // 12.3 Termination of a Dialog + // + // Independent of the method, if a request outside of a dialog generates + // a non-2xx final response, any early dialogs created through + // provisional responses to that request are terminated. The mechanism + // for terminating confirmed dialogs is method specific. In this + // specification, the BYE method terminates a session and the dialog + // associated with it. See Section 15 for details. + // https://tools.ietf.org/html/rfc3261#section-12.3 + // All early dialogs are considered terminated upon reception of the + // non-2xx final response. + // + // After having received the non-2xx final response the UAC core + // considers the INVITE transaction completed. The INVITE client + // transaction handles the generation of ACKs for the response (see + // Section 17). + // https://tools.ietf.org/html/rfc3261#section-13.2.2.3 + this.earlyDialogs.forEach(function (earlyDialog) { return earlyDialog.dispose(); }); + this.earlyDialogs.clear(); + // A single non-2xx final response may be received for the INVITE. 4xx, + // 5xx and 6xx responses may contain a Contact header field value + // indicating the location where additional information about the error + // can be found. Subsequent final responses (which would only arrive + // under error conditions) MUST be ignored. + // https://tools.ietf.org/html/rfc3261#section-13.2.2.3 + if (this.delegate && this.delegate.onReject) { + this.delegate.onReject({ message: message }); + } + return; + default: + throw new Error("Invalid status code " + statusCode); + } + throw new Error("Executing what should be an unreachable code path receiving " + statusCode + " response."); + }; + return InviteUserAgentClient; +}(user_agent_client_1.UserAgentClient)); +exports.InviteUserAgentClient = InviteUserAgentClient; diff --git a/lib/Core/user-agents/invite-user-agent-server.d.ts b/lib/Core/user-agents/invite-user-agent-server.d.ts new file mode 100644 index 000000000..0c1186da7 --- /dev/null +++ b/lib/Core/user-agents/invite-user-agent-server.d.ts @@ -0,0 +1,75 @@ +import { IncomingRequest as IncomingRequestMessage } from "../../SIPMessage"; +import { URI } from "../../URI"; +import { IncomingInviteRequest, IncomingRequestDelegate, OutgoingResponse, OutgoingResponseWithSession, ResponseOptions } from "../messages"; +import { UserAgentCore } from "../user-agent-core"; +import { UserAgentServer } from "./user-agent-server"; +/** + * 13 Initiating a Session + * https://tools.ietf.org/html/rfc3261#section-13 + * 13.1 Overview + * https://tools.ietf.org/html/rfc3261#section-13.1 + * 13.3 UAS Processing + * https://tools.ietf.org/html/rfc3261#section-13.3 + */ +export declare class InviteUserAgentServer extends UserAgentServer implements IncomingInviteRequest { + protected core: UserAgentCore; + /** The confirmed dialog, if any. */ + private confirmedDialog; + /** The early dialog, if any. */ + private earlyDialog; + constructor(core: UserAgentCore, message: IncomingRequestMessage, delegate?: IncomingRequestDelegate); + dispose(): void; + /** + * 13.3.1.4 The INVITE is Accepted + * The UAS core generates a 2xx response. This response establishes a + * dialog, and therefore follows the procedures of Section 12.1.1 in + * addition to those of Section 8.2.6. + * https://tools.ietf.org/html/rfc3261#section-13.3.1.4 + * @param options Accept options bucket. + */ + accept(options?: ResponseOptions): OutgoingResponseWithSession; + /** + * 13.3.1.1 Progress + * If the UAS is not able to answer the invitation immediately, it can + * choose to indicate some kind of progress to the UAC (for example, an + * indication that a phone is ringing). This is accomplished with a + * provisional response between 101 and 199. These provisional + * responses establish early dialogs and therefore follow the procedures + * of Section 12.1.1 in addition to those of Section 8.2.6. A UAS MAY + * send as many provisional responses as it likes. Each of these MUST + * indicate the same dialog ID. However, these will not be delivered + * reliably. + * + * If the UAS desires an extended period of time to answer the INVITE, + * it will need to ask for an "extension" in order to prevent proxies + * from canceling the transaction. A proxy has the option of canceling + * a transaction when there is a gap of 3 minutes between responses in a + * transaction. To prevent cancellation, the UAS MUST send a non-100 + * provisional response at every minute, to handle the possibility of + * lost provisional responses. + * https://tools.ietf.org/html/rfc3261#section-13.3.1.1 + * @param options Progress options bucket. + */ + progress(options?: ResponseOptions): OutgoingResponseWithSession; + /** + * 13.3.1.2 The INVITE is Redirected + * If the UAS decides to redirect the call, a 3xx response is sent. A + * 300 (Multiple Choices), 301 (Moved Permanently) or 302 (Moved + * Temporarily) response SHOULD contain a Contact header field + * containing one or more URIs of new addresses to be tried. The + * response is passed to the INVITE server transaction, which will deal + * with its retransmissions. + * https://tools.ietf.org/html/rfc3261#section-13.3.1.2 + * @param options Reject options bucket. + */ + redirect(contacts: Array, options?: ResponseOptions): OutgoingResponse; + /** + * 13.3.1.3 The INVITE is Rejected + * A common scenario occurs when the callee is currently not willing or + * able to take additional calls at this end system. A 486 (Busy Here) + * SHOULD be returned in such a scenario. + * https://tools.ietf.org/html/rfc3261#section-13.3.1.3 + * @param options Reject options bucket. + */ + reject(options?: ResponseOptions): OutgoingResponse; +} diff --git a/lib/Core/user-agents/invite-user-agent-server.js b/lib/Core/user-agents/invite-user-agent-server.js new file mode 100644 index 000000000..885b2e3e3 --- /dev/null +++ b/lib/Core/user-agents/invite-user-agent-server.js @@ -0,0 +1,248 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +var Exceptions_1 = require("../../Exceptions"); +var dialogs_1 = require("../dialogs"); +var session_1 = require("../session"); +var transactions_1 = require("../transactions"); +var allowed_methods_1 = require("../user-agent-core/allowed-methods"); +var user_agent_server_1 = require("./user-agent-server"); +/** + * 13 Initiating a Session + * https://tools.ietf.org/html/rfc3261#section-13 + * 13.1 Overview + * https://tools.ietf.org/html/rfc3261#section-13.1 + * 13.3 UAS Processing + * https://tools.ietf.org/html/rfc3261#section-13.3 + */ +var InviteUserAgentServer = /** @class */ (function (_super) { + __extends(InviteUserAgentServer, _super); + function InviteUserAgentServer(core, message, delegate) { + var _this = _super.call(this, transactions_1.InviteServerTransaction, core, message, delegate) || this; + _this.core = core; + return _this; + } + InviteUserAgentServer.prototype.dispose = function () { + if (this.earlyDialog) { + this.earlyDialog.dispose(); + } + _super.prototype.dispose.call(this); + }; + /** + * 13.3.1.4 The INVITE is Accepted + * The UAS core generates a 2xx response. This response establishes a + * dialog, and therefore follows the procedures of Section 12.1.1 in + * addition to those of Section 8.2.6. + * https://tools.ietf.org/html/rfc3261#section-13.3.1.4 + * @param options Accept options bucket. + */ + InviteUserAgentServer.prototype.accept = function (options) { + if (options === void 0) { options = { statusCode: 200 }; } + if (!this.acceptable) { + throw new Exceptions_1.Exceptions.TransactionStateError(this.message.method + " not acceptable in state " + this.transaction.state + "."); + } + // This response establishes a dialog... + // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 + if (!this.confirmedDialog) { + if (this.earlyDialog) { + this.earlyDialog.confirm(); + this.confirmedDialog = this.earlyDialog; + this.earlyDialog = undefined; + } + else { + var transaction = this.transaction; + if (!(transaction instanceof transactions_1.InviteServerTransaction)) { + throw new Error("Transaction not instance of InviteClientTransaction."); + } + var state = dialogs_1.Dialog.initialDialogStateForUserAgentServer(this.message, this.toTag); + this.confirmedDialog = new dialogs_1.SessionDialog(transaction, this.core, state); + } + } + // When a UAS responds to a request with a response that establishes a + // dialog (such as a 2xx to INVITE), the UAS MUST copy all Record-Route + // header field values from the request into the response (including the + // URIs, URI parameters, and any Record-Route header field parameters, + // whether they are known or unknown to the UAS) and MUST maintain the + // order of those values. The UAS MUST add a Contact header field to + // the response. The Contact header field contains an address where the + // UAS would like to be contacted for subsequent requests in the dialog + // (which includes the ACK for a 2xx response in the case of an INVITE). + // Generally, the host portion of this URI is the IP address or FQDN of + // the host. The URI provided in the Contact header field MUST be a SIP + // or SIPS URI. If the request that initiated the dialog contained a + // SIPS URI in the Request-URI or in the top Record-Route header field + // value, if there was any, or the Contact header field if there was no + // Record-Route header field, the Contact header field in the response + // MUST be a SIPS URI. The URI SHOULD have global scope (that is, the + // same URI can be used in messages outside this dialog). The same way, + // the scope of the URI in the Contact header field of the INVITE is not + // limited to this dialog either. It can therefore be used in messages + // to the UAC even outside this dialog. + // https://tools.ietf.org/html/rfc3261#section-12.1.1 + var recordRouteHeader = this.message + .getHeaders("record-route") + .map(function (header) { return "Record-Route: " + header; }); + var contactHeader = "Contact: " + this.core.configuration.contact.toString(); + // A 2xx response to an INVITE SHOULD contain the Allow header field and + // the Supported header field, and MAY contain the Accept header field. + // Including these header fields allows the UAC to determine the + // features and extensions supported by the UAS for the duration of the + // call, without probing. + // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 + // FIXME: TODO: This should not be hard coded. + var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); + // FIXME: TODO: Supported header (see reply()) + // FIXME: TODO: Accept header + // If the INVITE request contained an offer, and the UAS had not yet + // sent an answer, the 2xx MUST contain an answer. If the INVITE did + // not contain an offer, the 2xx MUST contain an offer if the UAS had + // not yet sent an offer. + // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 + if (!options.body) { + if (this.confirmedDialog.signalingState === session_1.SignalingState.Initial || + this.confirmedDialog.signalingState === session_1.SignalingState.HaveRemoteOffer) { + throw new Error("Response must have a body."); + } + } + // FIXME: TODO: Guard offer/answer + options.statusCode = options.statusCode || 200; + options.extraHeaders = options.extraHeaders || []; + options.extraHeaders = options.extraHeaders.concat(recordRouteHeader); + options.extraHeaders.push(allowHeader); + options.extraHeaders.push(contactHeader); + var response = _super.prototype.accept.call(this, options); + var session = this.confirmedDialog; + var result = __assign({}, response, { session: session }); + // Update dialog signaling state + if (options.body) { + this.confirmedDialog.signalingStateTransition(options.body); + } + return result; + }; + /** + * 13.3.1.1 Progress + * If the UAS is not able to answer the invitation immediately, it can + * choose to indicate some kind of progress to the UAC (for example, an + * indication that a phone is ringing). This is accomplished with a + * provisional response between 101 and 199. These provisional + * responses establish early dialogs and therefore follow the procedures + * of Section 12.1.1 in addition to those of Section 8.2.6. A UAS MAY + * send as many provisional responses as it likes. Each of these MUST + * indicate the same dialog ID. However, these will not be delivered + * reliably. + * + * If the UAS desires an extended period of time to answer the INVITE, + * it will need to ask for an "extension" in order to prevent proxies + * from canceling the transaction. A proxy has the option of canceling + * a transaction when there is a gap of 3 minutes between responses in a + * transaction. To prevent cancellation, the UAS MUST send a non-100 + * provisional response at every minute, to handle the possibility of + * lost provisional responses. + * https://tools.ietf.org/html/rfc3261#section-13.3.1.1 + * @param options Progress options bucket. + */ + InviteUserAgentServer.prototype.progress = function (options) { + if (options === void 0) { options = { statusCode: 180 }; } + if (!this.progressable) { + throw new Exceptions_1.Exceptions.TransactionStateError(this.message.method + " not progressable in state " + this.transaction.state + "."); + } + // This response establishes a dialog... + // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 + if (!this.earlyDialog) { + var transaction = this.transaction; + if (!(transaction instanceof transactions_1.InviteServerTransaction)) { + throw new Error("Transaction not instance of InviteClientTransaction."); + } + var state = dialogs_1.Dialog.initialDialogStateForUserAgentServer(this.message, this.toTag, true); + this.earlyDialog = new dialogs_1.SessionDialog(transaction, this.core, state); + } + // When a UAS responds to a request with a response that establishes a + // dialog (such as a 2xx to INVITE), the UAS MUST copy all Record-Route + // header field values from the request into the response (including the + // URIs, URI parameters, and any Record-Route header field parameters, + // whether they are known or unknown to the UAS) and MUST maintain the + // order of those values. The UAS MUST add a Contact header field to + // the response. The Contact header field contains an address where the + // UAS would like to be contacted for subsequent requests in the dialog + // (which includes the ACK for a 2xx response in the case of an INVITE). + // Generally, the host portion of this URI is the IP address or FQDN of + // the host. The URI provided in the Contact header field MUST be a SIP + // or SIPS URI. If the request that initiated the dialog contained a + // SIPS URI in the Request-URI or in the top Record-Route header field + // value, if there was any, or the Contact header field if there was no + // Record-Route header field, the Contact header field in the response + // MUST be a SIPS URI. The URI SHOULD have global scope (that is, the + // same URI can be used in messages outside this dialog). The same way, + // the scope of the URI in the Contact header field of the INVITE is not + // limited to this dialog either. It can therefore be used in messages + // to the UAC even outside this dialog. + // https://tools.ietf.org/html/rfc3261#section-12.1.1 + var recordRouteHeader = this.message + .getHeaders("record-route") + .map(function (header) { return "Record-Route: " + header; }); + var contactHeader = "Contact: " + this.core.configuration.contact; + options.extraHeaders = options.extraHeaders || []; + options.extraHeaders = options.extraHeaders.concat(recordRouteHeader); + options.extraHeaders.push(contactHeader); + var response = _super.prototype.progress.call(this, options); + var session = this.earlyDialog; + var result = __assign({}, response, { session: session }); + // Update dialog signaling state + if (options.body) { + this.earlyDialog.signalingStateTransition(options.body); + } + return result; + }; + /** + * 13.3.1.2 The INVITE is Redirected + * If the UAS decides to redirect the call, a 3xx response is sent. A + * 300 (Multiple Choices), 301 (Moved Permanently) or 302 (Moved + * Temporarily) response SHOULD contain a Contact header field + * containing one or more URIs of new addresses to be tried. The + * response is passed to the INVITE server transaction, which will deal + * with its retransmissions. + * https://tools.ietf.org/html/rfc3261#section-13.3.1.2 + * @param options Reject options bucket. + */ + InviteUserAgentServer.prototype.redirect = function (contacts, options) { + if (options === void 0) { options = { statusCode: 302 }; } + return _super.prototype.redirect.call(this, contacts, options); + }; + /** + * 13.3.1.3 The INVITE is Rejected + * A common scenario occurs when the callee is currently not willing or + * able to take additional calls at this end system. A 486 (Busy Here) + * SHOULD be returned in such a scenario. + * https://tools.ietf.org/html/rfc3261#section-13.3.1.3 + * @param options Reject options bucket. + */ + InviteUserAgentServer.prototype.reject = function (options) { + if (options === void 0) { options = { statusCode: 486 }; } + return _super.prototype.reject.call(this, options); + }; + return InviteUserAgentServer; +}(user_agent_server_1.UserAgentServer)); +exports.InviteUserAgentServer = InviteUserAgentServer; diff --git a/lib/Core/user-agents/message-user-agent-client.d.ts b/lib/Core/user-agents/message-user-agent-client.d.ts new file mode 100644 index 000000000..b2484e052 --- /dev/null +++ b/lib/Core/user-agents/message-user-agent-client.d.ts @@ -0,0 +1,7 @@ +import { OutgoingRequest as OutgoingRequestMessage } from "../../SIPMessage"; +import { OutgoingMessageRequest, OutgoingRequestDelegate } from "../messages"; +import { UserAgentCore } from "../user-agent-core"; +import { UserAgentClient } from "./user-agent-client"; +export declare class MessageUserAgentClient extends UserAgentClient implements OutgoingMessageRequest { + constructor(core: UserAgentCore, message: OutgoingRequestMessage, delegate?: OutgoingRequestDelegate); +} diff --git a/lib/Core/user-agents/message-user-agent-client.js b/lib/Core/user-agents/message-user-agent-client.js new file mode 100644 index 000000000..b9c835bfc --- /dev/null +++ b/lib/Core/user-agents/message-user-agent-client.js @@ -0,0 +1,25 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var transactions_1 = require("../transactions"); +var user_agent_client_1 = require("./user-agent-client"); +var MessageUserAgentClient = /** @class */ (function (_super) { + __extends(MessageUserAgentClient, _super); + function MessageUserAgentClient(core, message, delegate) { + return _super.call(this, transactions_1.NonInviteClientTransaction, core, message, delegate) || this; + } + return MessageUserAgentClient; +}(user_agent_client_1.UserAgentClient)); +exports.MessageUserAgentClient = MessageUserAgentClient; diff --git a/lib/Core/user-agents/message-user-agent-server.d.ts b/lib/Core/user-agents/message-user-agent-server.d.ts new file mode 100644 index 000000000..f7f56499f --- /dev/null +++ b/lib/Core/user-agents/message-user-agent-server.d.ts @@ -0,0 +1,8 @@ +import { IncomingRequest as IncomingRequestMessage } from "../../SIPMessage"; +import { IncomingMessageRequest, IncomingRequestDelegate } from "../messages"; +import { UserAgentCore } from "../user-agent-core"; +import { UserAgentServer } from "./user-agent-server"; +export declare class MessageUserAgentServer extends UserAgentServer implements IncomingMessageRequest { + protected core: UserAgentCore; + constructor(core: UserAgentCore, message: IncomingRequestMessage, delegate?: IncomingRequestDelegate); +} diff --git a/lib/Core/user-agents/message-user-agent-server.js b/lib/Core/user-agents/message-user-agent-server.js new file mode 100644 index 000000000..545cc19fd --- /dev/null +++ b/lib/Core/user-agents/message-user-agent-server.js @@ -0,0 +1,27 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var transactions_1 = require("../transactions"); +var user_agent_server_1 = require("./user-agent-server"); +var MessageUserAgentServer = /** @class */ (function (_super) { + __extends(MessageUserAgentServer, _super); + function MessageUserAgentServer(core, message, delegate) { + var _this = _super.call(this, transactions_1.NonInviteServerTransaction, core, message, delegate) || this; + _this.core = core; + return _this; + } + return MessageUserAgentServer; +}(user_agent_server_1.UserAgentServer)); +exports.MessageUserAgentServer = MessageUserAgentServer; diff --git a/lib/Core/user-agents/notify-user-agent-client.d.ts b/lib/Core/user-agents/notify-user-agent-client.d.ts new file mode 100644 index 000000000..ddab646bb --- /dev/null +++ b/lib/Core/user-agents/notify-user-agent-client.d.ts @@ -0,0 +1,6 @@ +import { SessionDialog } from "../dialogs"; +import { OutgoingNotifyRequest, OutgoingRequestDelegate, RequestOptions } from "../messages"; +import { UserAgentClient } from "./user-agent-client"; +export declare class NotifyUserAgentClient extends UserAgentClient implements OutgoingNotifyRequest { + constructor(dialog: SessionDialog, delegate?: OutgoingRequestDelegate, options?: RequestOptions); +} diff --git a/lib/Core/user-agents/notify-user-agent-client.js b/lib/Core/user-agents/notify-user-agent-client.js new file mode 100644 index 000000000..dc3b2e7de --- /dev/null +++ b/lib/Core/user-agents/notify-user-agent-client.js @@ -0,0 +1,29 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Constants_1 = require("../../Constants"); +var transactions_1 = require("../transactions"); +var user_agent_client_1 = require("./user-agent-client"); +var NotifyUserAgentClient = /** @class */ (function (_super) { + __extends(NotifyUserAgentClient, _super); + function NotifyUserAgentClient(dialog, delegate, options) { + var _this = this; + var message = dialog.createOutgoingRequestMessage(Constants_1.C.NOTIFY, options); + _this = _super.call(this, transactions_1.NonInviteClientTransaction, dialog.userAgentCore, message, delegate) || this; + return _this; + } + return NotifyUserAgentClient; +}(user_agent_client_1.UserAgentClient)); +exports.NotifyUserAgentClient = NotifyUserAgentClient; diff --git a/lib/Core/user-agents/notify-user-agent-server.d.ts b/lib/Core/user-agents/notify-user-agent-server.d.ts new file mode 100644 index 000000000..1c01feb46 --- /dev/null +++ b/lib/Core/user-agents/notify-user-agent-server.d.ts @@ -0,0 +1,13 @@ +import { IncomingRequest as IncomingRequestMessage } from "../../SIPMessage"; +import { Dialog } from "../dialogs"; +import { IncomingNotifyRequest, IncomingRequestDelegate } from "../messages"; +import { UserAgentCore } from "../user-agent-core"; +import { UserAgentServer } from "./user-agent-server"; +export declare class NotifyUserAgentServer extends UserAgentServer implements IncomingNotifyRequest { + /** + * NOTIFY UAS constructor. + * @param dialogOrCore Dialog for in dialog NOTIFY, UserAgentCore for out of dialog NOTIFY (deprecated). + * @param message Incoming NOTIFY request message. + */ + constructor(dialogOrCore: Dialog | UserAgentCore, message: IncomingRequestMessage, delegate?: IncomingRequestDelegate); +} diff --git a/lib/Core/user-agents/notify-user-agent-server.js b/lib/Core/user-agents/notify-user-agent-server.js new file mode 100644 index 000000000..315b6ec70 --- /dev/null +++ b/lib/Core/user-agents/notify-user-agent-server.js @@ -0,0 +1,38 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var transactions_1 = require("../transactions"); +var user_agent_server_1 = require("./user-agent-server"); +var NotifyUserAgentServer = /** @class */ (function (_super) { + __extends(NotifyUserAgentServer, _super); + /** + * NOTIFY UAS constructor. + * @param dialogOrCore Dialog for in dialog NOTIFY, UserAgentCore for out of dialog NOTIFY (deprecated). + * @param message Incoming NOTIFY request message. + */ + function NotifyUserAgentServer(dialogOrCore, message, delegate) { + var _this = this; + var userAgentCore = instanceOfDialog(dialogOrCore) ? + dialogOrCore.userAgentCore : + dialogOrCore; + _this = _super.call(this, transactions_1.NonInviteServerTransaction, userAgentCore, message, delegate) || this; + return _this; + } + return NotifyUserAgentServer; +}(user_agent_server_1.UserAgentServer)); +exports.NotifyUserAgentServer = NotifyUserAgentServer; +function instanceOfDialog(object) { + return object.userAgentCore !== undefined; +} diff --git a/lib/Core/user-agents/prack-user-agent-client.d.ts b/lib/Core/user-agents/prack-user-agent-client.d.ts new file mode 100644 index 000000000..0f4a0f6bc --- /dev/null +++ b/lib/Core/user-agents/prack-user-agent-client.d.ts @@ -0,0 +1,6 @@ +import { SessionDialog } from "../dialogs"; +import { OutgoingPrackRequest, OutgoingRequestDelegate, RequestOptions } from "../messages"; +import { UserAgentClient } from "./user-agent-client"; +export declare class PrackUserAgentClient extends UserAgentClient implements OutgoingPrackRequest { + constructor(dialog: SessionDialog, delegate?: OutgoingRequestDelegate, options?: RequestOptions); +} diff --git a/lib/Core/user-agents/prack-user-agent-client.js b/lib/Core/user-agents/prack-user-agent-client.js new file mode 100644 index 000000000..e25fced02 --- /dev/null +++ b/lib/Core/user-agents/prack-user-agent-client.js @@ -0,0 +1,30 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Constants_1 = require("../../Constants"); +var transactions_1 = require("../transactions"); +var user_agent_client_1 = require("./user-agent-client"); +var PrackUserAgentClient = /** @class */ (function (_super) { + __extends(PrackUserAgentClient, _super); + function PrackUserAgentClient(dialog, delegate, options) { + var _this = this; + var message = dialog.createOutgoingRequestMessage(Constants_1.C.PRACK, options); + _this = _super.call(this, transactions_1.NonInviteClientTransaction, dialog.userAgentCore, message, delegate) || this; + dialog.signalingStateTransition(message); + return _this; + } + return PrackUserAgentClient; +}(user_agent_client_1.UserAgentClient)); +exports.PrackUserAgentClient = PrackUserAgentClient; diff --git a/lib/Core/user-agents/prack-user-agent-server.d.ts b/lib/Core/user-agents/prack-user-agent-server.d.ts new file mode 100644 index 000000000..b162f75f9 --- /dev/null +++ b/lib/Core/user-agents/prack-user-agent-server.d.ts @@ -0,0 +1,13 @@ +import { IncomingRequest as IncomingRequestMessage } from "../../SIPMessage"; +import { SessionDialog } from "../dialogs"; +import { IncomingPrackRequest, IncomingRequestDelegate, OutgoingResponse, ResponseOptions } from "../messages"; +import { UserAgentServer } from "./user-agent-server"; +export declare class PrackUserAgentServer extends UserAgentServer implements IncomingPrackRequest { + private dialog; + constructor(dialog: SessionDialog, message: IncomingRequestMessage, delegate?: IncomingRequestDelegate); + /** + * Update the dialog signaling state on a 2xx response. + * @param options Options bucket. + */ + accept(options?: ResponseOptions): OutgoingResponse; +} diff --git a/lib/Core/user-agents/prack-user-agent-server.js b/lib/Core/user-agents/prack-user-agent-server.js new file mode 100644 index 000000000..767eb330b --- /dev/null +++ b/lib/Core/user-agents/prack-user-agent-server.js @@ -0,0 +1,41 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var transactions_1 = require("../transactions"); +var user_agent_server_1 = require("./user-agent-server"); +var PrackUserAgentServer = /** @class */ (function (_super) { + __extends(PrackUserAgentServer, _super); + function PrackUserAgentServer(dialog, message, delegate) { + var _this = _super.call(this, transactions_1.NonInviteServerTransaction, dialog.userAgentCore, message, delegate) || this; + // Update dialog signaling state with offer/answer in body + dialog.signalingStateTransition(message); + _this.dialog = dialog; + return _this; + } + /** + * Update the dialog signaling state on a 2xx response. + * @param options Options bucket. + */ + PrackUserAgentServer.prototype.accept = function (options) { + if (options === void 0) { options = { statusCode: 200 }; } + if (options.body) { + // Update dialog signaling state with offer/answer in body + this.dialog.signalingStateTransition(options.body); + } + return _super.prototype.accept.call(this, options); + }; + return PrackUserAgentServer; +}(user_agent_server_1.UserAgentServer)); +exports.PrackUserAgentServer = PrackUserAgentServer; diff --git a/lib/Core/user-agents/publish-user-agent-client.d.ts b/lib/Core/user-agents/publish-user-agent-client.d.ts new file mode 100644 index 000000000..74e068bfe --- /dev/null +++ b/lib/Core/user-agents/publish-user-agent-client.d.ts @@ -0,0 +1,7 @@ +import { OutgoingRequest as OutgoingRequestMessage } from "../../SIPMessage"; +import { OutgoingPublishRequest, OutgoingRequestDelegate } from "../messages"; +import { UserAgentCore } from "../user-agent-core"; +import { UserAgentClient } from "./user-agent-client"; +export declare class PublishUserAgentClient extends UserAgentClient implements OutgoingPublishRequest { + constructor(core: UserAgentCore, message: OutgoingRequestMessage, delegate?: OutgoingRequestDelegate); +} diff --git a/lib/Core/user-agents/publish-user-agent-client.js b/lib/Core/user-agents/publish-user-agent-client.js new file mode 100644 index 000000000..cf7c3c43b --- /dev/null +++ b/lib/Core/user-agents/publish-user-agent-client.js @@ -0,0 +1,25 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var transactions_1 = require("../transactions"); +var user_agent_client_1 = require("./user-agent-client"); +var PublishUserAgentClient = /** @class */ (function (_super) { + __extends(PublishUserAgentClient, _super); + function PublishUserAgentClient(core, message, delegate) { + return _super.call(this, transactions_1.NonInviteClientTransaction, core, message, delegate) || this; + } + return PublishUserAgentClient; +}(user_agent_client_1.UserAgentClient)); +exports.PublishUserAgentClient = PublishUserAgentClient; diff --git a/lib/Core/user-agents/re-invite-user-agent-client.d.ts b/lib/Core/user-agents/re-invite-user-agent-client.d.ts new file mode 100644 index 000000000..7e256bdb4 --- /dev/null +++ b/lib/Core/user-agents/re-invite-user-agent-client.d.ts @@ -0,0 +1,16 @@ +import { IncomingResponse as IncomingResponseMessage } from "../../SIPMessage"; +import { SessionDialog } from "../dialogs"; +import { OutgoingInviteRequest, OutgoingInviteRequestDelegate, RequestOptions } from "../messages"; +import { UserAgentClient } from "./user-agent-client"; +/** + * 14 Modifying an Existing Session + * https://tools.ietf.org/html/rfc3261#section-14 + * 14.1 UAC Behavior + * https://tools.ietf.org/html/rfc3261#section-14.1 + */ +export declare class ReInviteUserAgentClient extends UserAgentClient implements OutgoingInviteRequest { + delegate: OutgoingInviteRequestDelegate | undefined; + private dialog; + constructor(dialog: SessionDialog, delegate?: OutgoingInviteRequestDelegate, options?: RequestOptions); + protected receiveResponse(message: IncomingResponseMessage): void; +} diff --git a/lib/Core/user-agents/re-invite-user-agent-client.js b/lib/Core/user-agents/re-invite-user-agent-client.js new file mode 100644 index 000000000..a5ae7627a --- /dev/null +++ b/lib/Core/user-agents/re-invite-user-agent-client.js @@ -0,0 +1,118 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Constants_1 = require("../../Constants"); +var transactions_1 = require("../transactions"); +var user_agent_client_1 = require("./user-agent-client"); +/** + * 14 Modifying an Existing Session + * https://tools.ietf.org/html/rfc3261#section-14 + * 14.1 UAC Behavior + * https://tools.ietf.org/html/rfc3261#section-14.1 + */ +var ReInviteUserAgentClient = /** @class */ (function (_super) { + __extends(ReInviteUserAgentClient, _super); + function ReInviteUserAgentClient(dialog, delegate, options) { + var _this = this; + var message = dialog.createOutgoingRequestMessage(Constants_1.C.INVITE, options); + _this = _super.call(this, transactions_1.InviteClientTransaction, dialog.userAgentCore, message, delegate) || this; + _this.delegate = delegate; + dialog.signalingStateTransition(message); + // FIXME: TODO: next line obviously needs to be improved... + dialog.reinviteUserAgentClient = _this; // let the dialog know re-invite request sent + _this.dialog = dialog; + return _this; + } + ReInviteUserAgentClient.prototype.receiveResponse = function (message) { + var _this = this; + var statusCode = message.statusCode ? message.statusCode.toString() : ""; + if (!statusCode) { + throw new Error("Response status code undefined."); + } + switch (true) { + case /^100$/.test(statusCode): + if (this.delegate && this.delegate.onTrying) { + this.delegate.onTrying({ message: message }); + } + break; + case /^1[0-9]{2}$/.test(statusCode): + if (this.delegate && this.delegate.onProgress) { + this.delegate.onProgress({ + message: message, + session: this.dialog, + prack: function (options) { + throw new Error("Unimplemented."); + } + }); + } + break; + case /^2[0-9]{2}$/.test(statusCode): + // Update dialog signaling state with offer/answer in body + this.dialog.signalingStateTransition(message); + if (this.delegate && this.delegate.onAccept) { + this.delegate.onAccept({ + message: message, + session: this.dialog, + ack: function (options) { + var outgoingAckRequest = _this.dialog.ack(options); + return outgoingAckRequest; + } + }); + } + break; + case /^3[0-9]{2}$/.test(statusCode): + if (this.delegate && this.delegate.onRedirect) { + this.delegate.onRedirect({ message: message }); + } + break; + case /^[4-6][0-9]{2}$/.test(statusCode): + if (this.delegate && this.delegate.onReject) { + this.delegate.onReject({ message: message }); + } + else { + // If a UA receives a non-2xx final response to a re-INVITE, the session + // parameters MUST remain unchanged, as if no re-INVITE had been issued. + // Note that, as stated in Section 12.2.1.2, if the non-2xx final + // response is a 481 (Call/Transaction Does Not Exist), or a 408 + // (Request Timeout), or no response at all is received for the re- + // INVITE (that is, a timeout is returned by the INVITE client + // transaction), the UAC will terminate the dialog. + // + // If a UAC receives a 491 response to a re-INVITE, it SHOULD start a + // timer with a value T chosen as follows: + // + // 1. If the UAC is the owner of the Call-ID of the dialog ID + // (meaning it generated the value), T has a randomly chosen value + // between 2.1 and 4 seconds in units of 10 ms. + // + // 2. If the UAC is not the owner of the Call-ID of the dialog ID, T + // has a randomly chosen value of between 0 and 2 seconds in units + // of 10 ms. + // + // When the timer fires, the UAC SHOULD attempt the re-INVITE once more, + // if it still desires for that session modification to take place. For + // example, if the call was already hung up with a BYE, the re-INVITE + // would not take place. + // https://tools.ietf.org/html/rfc3261#section-14.1 + // FIXME: TODO: The above. + } + break; + default: + throw new Error("Invalid status code " + statusCode); + } + }; + return ReInviteUserAgentClient; +}(user_agent_client_1.UserAgentClient)); +exports.ReInviteUserAgentClient = ReInviteUserAgentClient; diff --git a/lib/Core/user-agents/re-invite-user-agent-server.d.ts b/lib/Core/user-agents/re-invite-user-agent-server.d.ts new file mode 100644 index 000000000..a88fd84d3 --- /dev/null +++ b/lib/Core/user-agents/re-invite-user-agent-server.d.ts @@ -0,0 +1,24 @@ +import { IncomingRequest as IncomingRequestMessage } from "../../SIPMessage"; +import { SessionDialog } from "../dialogs"; +import { IncomingInviteRequest, IncomingRequestDelegate, OutgoingResponseWithSession, ResponseOptions } from "../messages"; +import { UserAgentServer } from "./user-agent-server"; +/** + * 14 Modifying an Existing Session + * https://tools.ietf.org/html/rfc3261#section-14 + * 14.2 UAS Behavior + * https://tools.ietf.org/html/rfc3261#section-14.2 + */ +export declare class ReInviteUserAgentServer extends UserAgentServer implements IncomingInviteRequest { + private dialog; + constructor(dialog: SessionDialog, message: IncomingRequestMessage, delegate?: IncomingRequestDelegate); + /** + * Update the dialog signaling state on a 2xx response. + * @param options Options bucket. + */ + accept(options?: ResponseOptions): OutgoingResponseWithSession; + /** + * Update the dialog signaling state on a 1xx response. + * @param options Progress options bucket. + */ + progress(options?: ResponseOptions): OutgoingResponseWithSession; +} diff --git a/lib/Core/user-agents/re-invite-user-agent-server.js b/lib/Core/user-agents/re-invite-user-agent-server.js new file mode 100644 index 000000000..8f70ffd6e --- /dev/null +++ b/lib/Core/user-agents/re-invite-user-agent-server.js @@ -0,0 +1,91 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +var transactions_1 = require("../transactions"); +var user_agent_server_1 = require("./user-agent-server"); +/** + * 14 Modifying an Existing Session + * https://tools.ietf.org/html/rfc3261#section-14 + * 14.2 UAS Behavior + * https://tools.ietf.org/html/rfc3261#section-14.2 + */ +var ReInviteUserAgentServer = /** @class */ (function (_super) { + __extends(ReInviteUserAgentServer, _super); + function ReInviteUserAgentServer(dialog, message, delegate) { + var _this = _super.call(this, transactions_1.InviteServerTransaction, dialog.userAgentCore, message, delegate) || this; + dialog.reinviteUserAgentServer = _this; + _this.dialog = dialog; + return _this; + } + /** + * Update the dialog signaling state on a 2xx response. + * @param options Options bucket. + */ + ReInviteUserAgentServer.prototype.accept = function (options) { + if (options === void 0) { options = { statusCode: 200 }; } + // FIXME: The next two lines SHOULD go away, but I suppose it's technically harmless... + // These are here because some versions of SIP.js prior to 0.13.8 set the route set + // of all in dialog ACKs based on the Record-Route headers in the associated 2xx + // response. While this worked for dialog forming 2xx responses, it was technically + // broken for re-INVITE ACKS as it only worked if the UAS populated the Record-Route + // headers in the re-INVITE 2xx response (which is not required and a waste of bandwidth + // as the should be ignored if present in re-INVITE ACKS) and the UAS populated + // the Record-Route headers with the correct values (would be weird not too, but...). + // Anyway, for now the technically useless Record-Route headers are being added + // to maintain "backwards compatibility" with the older broken versions of SIP.js. + options.extraHeaders = options.extraHeaders || []; + options.extraHeaders = options.extraHeaders.concat(this.dialog.routeSet.map(function (route) { return "Record-Route: " + route; })); + // Send and return the response + var response = _super.prototype.accept.call(this, options); + var session = this.dialog; + var result = __assign({}, response, { session: session }); + if (options.body) { + // Update dialog signaling state with offer/answer in body + this.dialog.signalingStateTransition(options.body); + } + // Update dialog + this.dialog.reConfirm(); + return result; + }; + /** + * Update the dialog signaling state on a 1xx response. + * @param options Progress options bucket. + */ + ReInviteUserAgentServer.prototype.progress = function (options) { + if (options === void 0) { options = { statusCode: 180 }; } + // Send and return the response + var response = _super.prototype.progress.call(this, options); + var session = this.dialog; + var result = __assign({}, response, { session: session }); + // Update dialog signaling state + if (options.body) { + this.dialog.signalingStateTransition(options.body); + } + return result; + }; + return ReInviteUserAgentServer; +}(user_agent_server_1.UserAgentServer)); +exports.ReInviteUserAgentServer = ReInviteUserAgentServer; diff --git a/lib/Core/user-agents/re-subscribe-user-agent-client.d.ts b/lib/Core/user-agents/re-subscribe-user-agent-client.d.ts new file mode 100644 index 000000000..91ef6555c --- /dev/null +++ b/lib/Core/user-agents/re-subscribe-user-agent-client.d.ts @@ -0,0 +1,14 @@ +import { IncomingResponse as IncomingResponseMessage } from "../../SIPMessage"; +import { SubscriptionDialog } from "../dialogs"; +import { OutgoingRequestDelegate, OutgoingSubscribeRequest, RequestOptions } from "../messages"; +import { UserAgentClient } from "./user-agent-client"; +export declare class ReSubscribeUserAgentClient extends UserAgentClient implements OutgoingSubscribeRequest { + private dialog; + constructor(dialog: SubscriptionDialog, delegate?: OutgoingRequestDelegate, options?: RequestOptions); + waitNotifyStop(): void; + /** + * Receive a response from the transaction layer. + * @param message Incoming response message. + */ + protected receiveResponse(message: IncomingResponseMessage): void; +} diff --git a/lib/Core/user-agents/re-subscribe-user-agent-client.js b/lib/Core/user-agents/re-subscribe-user-agent-client.js new file mode 100644 index 000000000..4910051f2 --- /dev/null +++ b/lib/Core/user-agents/re-subscribe-user-agent-client.js @@ -0,0 +1,81 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Constants_1 = require("../../Constants"); +var transactions_1 = require("../transactions"); +var user_agent_client_1 = require("./user-agent-client"); +var ReSubscribeUserAgentClient = /** @class */ (function (_super) { + __extends(ReSubscribeUserAgentClient, _super); + function ReSubscribeUserAgentClient(dialog, delegate, options) { + var _this = this; + var message = dialog.createOutgoingRequestMessage(Constants_1.C.SUBSCRIBE, options); + _this = _super.call(this, transactions_1.NonInviteClientTransaction, dialog.userAgentCore, message, delegate) || this; + _this.dialog = dialog; + return _this; + } + ReSubscribeUserAgentClient.prototype.waitNotifyStop = function () { + // TODO: Placeholder. Not utilized currently. + return; + }; + /** + * Receive a response from the transaction layer. + * @param message Incoming response message. + */ + ReSubscribeUserAgentClient.prototype.receiveResponse = function (message) { + if (message.statusCode && message.statusCode >= 200 && message.statusCode < 300) { + // The "Expires" header field in a 200-class response to SUBSCRIBE + // request indicates the actual duration for which the subscription will + // remain active (unless refreshed). The received value might be + // smaller than the value indicated in the SUBSCRIBE request but cannot + // be larger; see Section 4.2.1 for details. + // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 + var expires = message.getHeader("Expires"); + if (!expires) { + this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE"); + } + else { + var subscriptionExpiresReceived = Number(expires); + if (this.dialog.subscriptionExpires > subscriptionExpiresReceived) { + this.dialog.subscriptionExpires = subscriptionExpiresReceived; + } + } + } + if (message.statusCode && message.statusCode >= 400 && message.statusCode < 700) { + // If a SUBSCRIBE request to refresh a subscription receives a 404, 405, + // 410, 416, 480-485, 489, 501, or 604 response, the subscriber MUST + // consider the subscription terminated. (See [RFC5057] for further + // details and notes about the effect of error codes on dialogs and + // usages within dialog, such as subscriptions). If the subscriber + // wishes to re-subscribe to the state, he does so by composing an + // unrelated initial SUBSCRIBE request with a freshly generated Call-ID + // and a new, unique "From" tag (see Section 4.1.2.1). + // https://tools.ietf.org/html/rfc6665#section-4.1.2.2 + var errorCodes = [404, 405, 410, 416, 480, 481, 482, 483, 484, 485, 489, 501, 604]; + if (errorCodes.includes(message.statusCode)) { + this.dialog.terminate(); + } + // If a SUBSCRIBE request to refresh a subscription fails with any error + // code other than those listed above, the original subscription is + // still considered valid for the duration of the most recently known + // "Expires" value as negotiated by the most recent successful SUBSCRIBE + // transaction, or as communicated by a NOTIFY request in its + // "Subscription-State" header field "expires" parameter. + // https://tools.ietf.org/html/rfc6665#section-4.1.2.2 + } + _super.prototype.receiveResponse.call(this, message); + }; + return ReSubscribeUserAgentClient; +}(user_agent_client_1.UserAgentClient)); +exports.ReSubscribeUserAgentClient = ReSubscribeUserAgentClient; diff --git a/lib/Core/user-agents/re-subscribe-user-agent-server.d.ts b/lib/Core/user-agents/re-subscribe-user-agent-server.d.ts new file mode 100644 index 000000000..5a980b5e5 --- /dev/null +++ b/lib/Core/user-agents/re-subscribe-user-agent-server.d.ts @@ -0,0 +1,7 @@ +import { IncomingRequest as IncomingRequestMessage } from "../../SIPMessage"; +import { Dialog } from "../dialogs"; +import { IncomingRequestDelegate, IncomingSubscribeRequest } from "../messages"; +import { UserAgentServer } from "./user-agent-server"; +export declare class ReSubscribeUserAgentServer extends UserAgentServer implements IncomingSubscribeRequest { + constructor(dialog: Dialog, message: IncomingRequestMessage, delegate?: IncomingRequestDelegate); +} diff --git a/lib/Core/user-agents/re-subscribe-user-agent-server.js b/lib/Core/user-agents/re-subscribe-user-agent-server.js new file mode 100644 index 000000000..bb42d6151 --- /dev/null +++ b/lib/Core/user-agents/re-subscribe-user-agent-server.js @@ -0,0 +1,25 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var transactions_1 = require("../transactions"); +var user_agent_server_1 = require("./user-agent-server"); +var ReSubscribeUserAgentServer = /** @class */ (function (_super) { + __extends(ReSubscribeUserAgentServer, _super); + function ReSubscribeUserAgentServer(dialog, message, delegate) { + return _super.call(this, transactions_1.NonInviteServerTransaction, dialog.userAgentCore, message, delegate) || this; + } + return ReSubscribeUserAgentServer; +}(user_agent_server_1.UserAgentServer)); +exports.ReSubscribeUserAgentServer = ReSubscribeUserAgentServer; diff --git a/lib/Core/user-agents/refer-user-agent-client.d.ts b/lib/Core/user-agents/refer-user-agent-client.d.ts new file mode 100644 index 000000000..ffda0b191 --- /dev/null +++ b/lib/Core/user-agents/refer-user-agent-client.d.ts @@ -0,0 +1,6 @@ +import { SessionDialog } from "../dialogs"; +import { OutgoingReferRequest, OutgoingRequestDelegate, RequestOptions } from "../messages"; +import { UserAgentClient } from "./user-agent-client"; +export declare class ReferUserAgentClient extends UserAgentClient implements OutgoingReferRequest { + constructor(dialog: SessionDialog, delegate?: OutgoingRequestDelegate, options?: RequestOptions); +} diff --git a/lib/Core/user-agents/refer-user-agent-client.js b/lib/Core/user-agents/refer-user-agent-client.js new file mode 100644 index 000000000..930ce737a --- /dev/null +++ b/lib/Core/user-agents/refer-user-agent-client.js @@ -0,0 +1,29 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Constants_1 = require("../../Constants"); +var transactions_1 = require("../transactions"); +var user_agent_client_1 = require("./user-agent-client"); +var ReferUserAgentClient = /** @class */ (function (_super) { + __extends(ReferUserAgentClient, _super); + function ReferUserAgentClient(dialog, delegate, options) { + var _this = this; + var message = dialog.createOutgoingRequestMessage(Constants_1.C.REFER, options); + _this = _super.call(this, transactions_1.NonInviteClientTransaction, dialog.userAgentCore, message, delegate) || this; + return _this; + } + return ReferUserAgentClient; +}(user_agent_client_1.UserAgentClient)); +exports.ReferUserAgentClient = ReferUserAgentClient; diff --git a/lib/Core/user-agents/refer-user-agent-server.d.ts b/lib/Core/user-agents/refer-user-agent-server.d.ts new file mode 100644 index 000000000..4e871fad6 --- /dev/null +++ b/lib/Core/user-agents/refer-user-agent-server.d.ts @@ -0,0 +1,13 @@ +import { IncomingRequest as IncomingRequestMessage } from "../../SIPMessage"; +import { SessionDialog } from "../dialogs"; +import { IncomingReferRequest, IncomingRequestDelegate } from "../messages"; +import { UserAgentCore } from "../user-agent-core"; +import { UserAgentServer } from "./user-agent-server"; +export declare class ReferUserAgentServer extends UserAgentServer implements IncomingReferRequest { + /** + * REFER UAS constructor. + * @param dialogOrCore Dialog for in dialog REFER, UserAgentCore for out of dialog REFER. + * @param message Incoming REFER request message. + */ + constructor(dialogOrCore: SessionDialog | UserAgentCore, message: IncomingRequestMessage, delegate?: IncomingRequestDelegate); +} diff --git a/lib/Core/user-agents/refer-user-agent-server.js b/lib/Core/user-agents/refer-user-agent-server.js new file mode 100644 index 000000000..d87f5f093 --- /dev/null +++ b/lib/Core/user-agents/refer-user-agent-server.js @@ -0,0 +1,38 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var transactions_1 = require("../transactions"); +var user_agent_server_1 = require("./user-agent-server"); +var ReferUserAgentServer = /** @class */ (function (_super) { + __extends(ReferUserAgentServer, _super); + /** + * REFER UAS constructor. + * @param dialogOrCore Dialog for in dialog REFER, UserAgentCore for out of dialog REFER. + * @param message Incoming REFER request message. + */ + function ReferUserAgentServer(dialogOrCore, message, delegate) { + var _this = this; + var userAgentCore = instanceOfSessionDialog(dialogOrCore) ? + dialogOrCore.userAgentCore : + dialogOrCore; + _this = _super.call(this, transactions_1.NonInviteServerTransaction, userAgentCore, message, delegate) || this; + return _this; + } + return ReferUserAgentServer; +}(user_agent_server_1.UserAgentServer)); +exports.ReferUserAgentServer = ReferUserAgentServer; +function instanceOfSessionDialog(object) { + return object.userAgentCore !== undefined; +} diff --git a/lib/Core/user-agents/register-user-agent-client.d.ts b/lib/Core/user-agents/register-user-agent-client.d.ts new file mode 100644 index 000000000..0270233e8 --- /dev/null +++ b/lib/Core/user-agents/register-user-agent-client.d.ts @@ -0,0 +1,7 @@ +import { OutgoingRequest as OutgoingRequestMessage } from "../../SIPMessage"; +import { OutgoingRegisterRequest, OutgoingRequestDelegate } from "../messages"; +import { UserAgentCore } from "../user-agent-core"; +import { UserAgentClient } from "./user-agent-client"; +export declare class RegisterUserAgentClient extends UserAgentClient implements OutgoingRegisterRequest { + constructor(core: UserAgentCore, message: OutgoingRequestMessage, delegate?: OutgoingRequestDelegate); +} diff --git a/lib/Core/user-agents/register-user-agent-client.js b/lib/Core/user-agents/register-user-agent-client.js new file mode 100644 index 000000000..9558d2b71 --- /dev/null +++ b/lib/Core/user-agents/register-user-agent-client.js @@ -0,0 +1,25 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var transactions_1 = require("../transactions"); +var user_agent_client_1 = require("./user-agent-client"); +var RegisterUserAgentClient = /** @class */ (function (_super) { + __extends(RegisterUserAgentClient, _super); + function RegisterUserAgentClient(core, message, delegate) { + return _super.call(this, transactions_1.NonInviteClientTransaction, core, message, delegate) || this; + } + return RegisterUserAgentClient; +}(user_agent_client_1.UserAgentClient)); +exports.RegisterUserAgentClient = RegisterUserAgentClient; diff --git a/lib/Core/user-agents/subscribe-user-agent-client.d.ts b/lib/Core/user-agents/subscribe-user-agent-client.d.ts new file mode 100644 index 000000000..8dd0728fe --- /dev/null +++ b/lib/Core/user-agents/subscribe-user-agent-client.d.ts @@ -0,0 +1,63 @@ +import { IncomingResponse as IncomingResponseMessage, OutgoingRequest as OutgoingRequestMessage } from "../../SIPMessage"; +import { OutgoingSubscribeRequest, OutgoingSubscribeRequestDelegate } from "../messages"; +import { UserAgentCore } from "../user-agent-core"; +import { NotifyUserAgentServer } from "./notify-user-agent-server"; +import { UserAgentClient } from "./user-agent-client"; +/** + * 4.1. Subscriber Behavior + * https://tools.ietf.org/html/rfc6665#section-4.1 + * + * User agent client for installation of a single subscription per SUBSCRIBE request. + * TODO: Support for installation of multiple subscriptions on forked SUBSCRIBE reqeuests. + */ +export declare class SubscribeUserAgentClient extends UserAgentClient implements OutgoingSubscribeRequest { + delegate: OutgoingSubscribeRequestDelegate | undefined; + /** Dialog created upon receiving the first NOTIFY. */ + private dialog; + /** Identifier of this user agent client. */ + private subscriberId; + /** When the subscription expires. Starts as requested expires and updated on 200 and NOTIFY. */ + private subscriptionExpires; + /** The requested expires for the subscription. */ + private subscriptionExpiresRequested; + /** Subscription event being targeted. */ + private subscriptionEvent; + /** Subscription state. */ + private subscriptionState; + /** Timer N Id. */ + private N; + constructor(core: UserAgentCore, message: OutgoingRequestMessage, delegate?: OutgoingSubscribeRequestDelegate); + /** + * Destructor. + * Note that Timer N may live on waiting for an initial NOTIFY and + * the delegate may still receive that NOTIFY. If you don't want + * that behavior then either clear the delegate so the delegate + * doesn't get called (a 200 will be sent in response to the NOTIFY) + * or call `waitNotifyStop` which will clear Timer N and remove this + * UAC from the core (a 481 will be sent in response to the NOTIFY). + */ + dispose(): void; + /** + * Handle out of dialog NOTIFY assoicated with SUBSCRIBE request. + * This is the first NOTIFY received after the SUBSCRIBE request. + * @param uas User agent server handling the subscription creating NOTIFY. + */ + onNotify(uas: NotifyUserAgentServer): void; + waitNotifyStart(): void; + waitNotifyStop(): void; + /** + * Receive a response from the transaction layer. + * @param message Incoming response message. + */ + protected receiveResponse(message: IncomingResponseMessage): void; + /** + * To ensure that subscribers do not wait indefinitely for a + * subscription to be established, a subscriber starts a Timer N, set to + * 64*T1, when it sends a SUBSCRIBE request. If this Timer N expires + * prior to the receipt of a NOTIFY request, the subscriber considers + * the subscription failed, and cleans up any state associated with the + * subscription attempt. + * https://tools.ietf.org/html/rfc6665#section-4.1.2.4 + */ + private timer_N; +} diff --git a/lib/Core/user-agents/subscribe-user-agent-client.js b/lib/Core/user-agents/subscribe-user-agent-client.js new file mode 100644 index 000000000..9ba1ce5d4 --- /dev/null +++ b/lib/Core/user-agents/subscribe-user-agent-client.js @@ -0,0 +1,306 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Timers_1 = require("../../Timers"); +var subscription_dialog_1 = require("../dialogs/subscription-dialog"); +var subscription_1 = require("../subscription"); +var transactions_1 = require("../transactions"); +var user_agent_client_1 = require("./user-agent-client"); +/** + * 4.1. Subscriber Behavior + * https://tools.ietf.org/html/rfc6665#section-4.1 + * + * User agent client for installation of a single subscription per SUBSCRIBE request. + * TODO: Support for installation of multiple subscriptions on forked SUBSCRIBE reqeuests. + */ +var SubscribeUserAgentClient = /** @class */ (function (_super) { + __extends(SubscribeUserAgentClient, _super); + function SubscribeUserAgentClient(core, message, delegate) { + var _this = this; + // Get event from request message. + var event = message.getHeader("Event"); + if (!event) { + throw new Error("Event undefined"); + } + // Get expires from reqeust message. + var expires = message.getHeader("Expires"); + if (!expires) { + throw new Error("Expires undefined"); + } + _this = _super.call(this, transactions_1.NonInviteClientTransaction, core, message, delegate) || this; + _this.delegate = delegate; + // FIXME: Subscriber id should also be matching on event id. + _this.subscriberId = message.callId + message.fromTag + event; + _this.subscriptionExpiresRequested = _this.subscriptionExpires = Number(expires); + _this.subscriptionEvent = event; + _this.subscriptionState = subscription_1.SubscriptionState.NotifyWait; + // Start waiting for a NOTIFY we can use to create a subscription. + _this.waitNotifyStart(); + return _this; + } + /** + * Destructor. + * Note that Timer N may live on waiting for an initial NOTIFY and + * the delegate may still receive that NOTIFY. If you don't want + * that behavior then either clear the delegate so the delegate + * doesn't get called (a 200 will be sent in response to the NOTIFY) + * or call `waitNotifyStop` which will clear Timer N and remove this + * UAC from the core (a 481 will be sent in response to the NOTIFY). + */ + SubscribeUserAgentClient.prototype.dispose = function () { + _super.prototype.dispose.call(this); + }; + /** + * Handle out of dialog NOTIFY assoicated with SUBSCRIBE request. + * This is the first NOTIFY received after the SUBSCRIBE request. + * @param uas User agent server handling the subscription creating NOTIFY. + */ + SubscribeUserAgentClient.prototype.onNotify = function (uas) { + // NOTIFY requests are matched to such SUBSCRIBE requests if they + // contain the same "Call-ID", a "To" header field "tag" parameter that + // matches the "From" header field "tag" parameter of the SUBSCRIBE + // request, and the same "Event" header field. Rules for comparisons of + // the "Event" header fields are described in Section 8.2.1. + // https://tools.ietf.org/html/rfc6665#section-4.4.1 + var event = uas.message.parseHeader("Event").event; + if (!event || event !== this.subscriptionEvent) { + this.logger.warn("Failed to parse event."); + uas.reject({ statusCode: 489 }); + return; + } + // NOTIFY requests MUST contain "Subscription-State" header fields that + // indicate the status of the subscription. + // https://tools.ietf.org/html/rfc6665#section-4.1.3 + var subscriptionState = uas.message.parseHeader("Subscription-State"); + if (!subscriptionState || !subscriptionState.state) { + this.logger.warn("Failed to parse subscription state."); + uas.reject({ statusCode: 489 }); + return; + } + // Validate subscription state. + var state = subscriptionState.state; + switch (state) { + case "pending": + break; + case "active": + break; + case "terminated": + break; + default: + this.logger.warn("Invalid subscription state " + state); + uas.reject({ statusCode: 489 }); + return; + } + // Dialogs usages are created upon completion of a NOTIFY transaction + // for a new subscription, unless the NOTIFY request contains a + // "Subscription-State" of "terminated." + // https://tools.ietf.org/html/rfc6665#section-4.4.1 + if (state !== "terminated") { + // The Contact header field MUST be present and contain exactly one SIP + // or SIPS URI in any request that can result in the establishment of a + // dialog. + // https://tools.ietf.org/html/rfc3261#section-8.1.1.8 + var contact = uas.message.parseHeader("contact"); + if (!contact) { + this.logger.warn("Failed to parse contact."); + uas.reject({ statusCode: 489 }); + return; + } + } + // In accordance with the rules for proxying non-INVITE requests as + // defined in [RFC3261], successful SUBSCRIBE requests will receive only + // one 200-class response; however, due to forking, the subscription may + // have been accepted by multiple nodes. The subscriber MUST therefore + // be prepared to receive NOTIFY requests with "From:" tags that differ + // from the "To:" tag received in the SUBSCRIBE 200-class response. + // + // If multiple NOTIFY requests are received in different dialogs in + // response to a single SUBSCRIBE request, each dialog represents a + // different destination to which the SUBSCRIBE request was forked. + // Subscriber handling in such situations varies by event package; see + // Section 5.4.9 for details. + // https://tools.ietf.org/html/rfc6665#section-4.1.4 + // Each event package MUST specify whether forked SUBSCRIBE requests are + // allowed to install multiple subscriptions. + // + // If such behavior is not allowed, the first potential dialog- + // establishing message will create a dialog. All subsequent NOTIFY + // requests that correspond to the SUBSCRIBE request (i.e., have + // matching "To", "From", "Call-ID", and "Event" header fields, as well + // as "From" header field "tag" parameter and "Event" header field "id" + // parameter) but that do not match the dialog would be rejected with a + // 481 response. Note that the 200-class response to the SUBSCRIBE + // request can arrive after a matching NOTIFY request has been received; + // such responses might not correlate to the same dialog established by + // the NOTIFY request. Except as required to complete the SUBSCRIBE + // transaction, such non-matching 200-class responses are ignored. + // + // If installing of multiple subscriptions by way of a single forked + // SUBSCRIBE request is allowed, the subscriber establishes a new dialog + // towards each notifier by returning a 200-class response to each + // NOTIFY request. Each dialog is then handled as its own entity and is + // refreshed independently of the other dialogs. + // + // In the case that multiple subscriptions are allowed, the event + // package MUST specify whether merging of the notifications to form a + // single state is required, and how such merging is to be performed. + // Note that it is possible that some event packages may be defined in + // such a way that each dialog is tied to a mutually exclusive state + // that is unaffected by the other dialogs; this MUST be clearly stated + // if it is the case. + // https://tools.ietf.org/html/rfc6665#section-5.4.9 + // *** NOTE: This implementation is only for event packages which + // do not allow forked requests to install muliple subscriptions. + // As such and in accordance with the specificaiton, we stop waiting + // and any future NOTIFY requests will be rejected with a 481. + if (this.dialog) { + throw new Error("Dialog already created. This implementation only supports install of single subscriptions."); + } + this.waitNotifyStop(); + // Update expires. + this.subscriptionExpires = + subscriptionState.expires ? + Math.min(this.subscriptionExpires, Math.max(subscriptionState.expires, 0)) : + this.subscriptionExpires; + // Update subscriptoin state. + switch (state) { + case "pending": + this.subscriptionState = subscription_1.SubscriptionState.Pending; + break; + case "active": + this.subscriptionState = subscription_1.SubscriptionState.Active; + break; + case "terminated": + this.subscriptionState = subscription_1.SubscriptionState.Terminated; + break; + default: + throw new Error("Unrecognized state " + state + "."); + } + // Dialogs usages are created upon completion of a NOTIFY transaction + // for a new subscription, unless the NOTIFY request contains a + // "Subscription-State" of "terminated." + // https://tools.ietf.org/html/rfc6665#section-4.4.1 + if (this.subscriptionState !== subscription_1.SubscriptionState.Terminated) { + // Because the dialog usage is established by the NOTIFY request, the + // route set at the subscriber is taken from the NOTIFY request itself, + // as opposed to the route set present in the 200-class response to the + // SUBSCRIBE request. + // https://tools.ietf.org/html/rfc6665#section-4.4.1 + var dialogState = subscription_dialog_1.SubscriptionDialog.initialDialogStateForSubscription(this.message, uas.message); + // Subscription Initiated! :) + this.dialog = new subscription_dialog_1.SubscriptionDialog(this.subscriptionEvent, this.subscriptionExpires, this.subscriptionState, this.core, dialogState); + } + // Delegate. + if (this.delegate && this.delegate.onNotify) { + var request = uas; + var subscription = this.dialog; + this.delegate.onNotify({ request: request, subscription: subscription }); + } + else { + uas.accept(); + } + }; + SubscribeUserAgentClient.prototype.waitNotifyStart = function () { + var _this = this; + if (!this.N) { + // Add ourselves to the core's subscriber map. + // This allows the core to route out of dialog NOTIFY messages to us. + this.core.subscribers.set(this.subscriberId, this); + this.N = setTimeout(function () { return _this.timer_N(); }, Timers_1.Timers.TIMER_N); + } + }; + SubscribeUserAgentClient.prototype.waitNotifyStop = function () { + if (this.N) { + // Remove ourselves to the core's subscriber map. + // Any future out of dialog NOTIFY messages will be rejected with a 481. + this.core.subscribers.delete(this.subscriberId); + clearTimeout(this.N); + this.N = undefined; + } + }; + /** + * Receive a response from the transaction layer. + * @param message Incoming response message. + */ + SubscribeUserAgentClient.prototype.receiveResponse = function (message) { + if (!this.authenticationGuard(message)) { + return; + } + if (message.statusCode && message.statusCode >= 200 && message.statusCode < 300) { + // The "Expires" header field in a 200-class response to SUBSCRIBE + // request indicates the actual duration for which the subscription will + // remain active (unless refreshed). The received value might be + // smaller than the value indicated in the SUBSCRIBE request but cannot + // be larger; see Section 4.2.1 for details. + // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 + // The "Expires" values present in SUBSCRIBE 200-class responses behave + // in the same way as they do in REGISTER responses: the server MAY + // shorten the interval but MUST NOT lengthen it. + // + // If the duration specified in a SUBSCRIBE request is unacceptably + // short, the notifier may be able to send a 423 response, as + // described earlier in this section. + // + // 200-class responses to SUBSCRIBE requests will not generally contain + // any useful information beyond subscription duration; their primary + // purpose is to serve as a reliability mechanism. State information + // will be communicated via a subsequent NOTIFY request from the + // notifier. + // https://tools.ietf.org/html/rfc6665#section-4.2.1.1 + var expires = message.getHeader("Expires"); + if (!expires) { + this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE"); + } + else { + var subscriptionExpiresReceived = Number(expires); + if (subscriptionExpiresReceived > this.subscriptionExpiresRequested) { + this.logger.warn("Expires header in a 200-class response to SUBSCRIBE with a higher value than the one in the request"); + } + if (subscriptionExpiresReceived < this.subscriptionExpires) { + this.subscriptionExpires = subscriptionExpiresReceived; + } + } + // If a NOTIFY arrived before 200-class response a dialog may have been created. + // Updated the dialogs expiration only if this indicates earlier expiration. + if (this.dialog) { + if (this.dialog.subscriptionExpires > this.subscriptionExpires) { + this.dialog.subscriptionExpires = this.subscriptionExpires; + } + } + } + if (message.statusCode && message.statusCode >= 300 && message.statusCode < 700) { + this.waitNotifyStop(); // No NOTIFY will be sent after a negative final response. + } + _super.prototype.receiveResponse.call(this, message); + }; + /** + * To ensure that subscribers do not wait indefinitely for a + * subscription to be established, a subscriber starts a Timer N, set to + * 64*T1, when it sends a SUBSCRIBE request. If this Timer N expires + * prior to the receipt of a NOTIFY request, the subscriber considers + * the subscription failed, and cleans up any state associated with the + * subscription attempt. + * https://tools.ietf.org/html/rfc6665#section-4.1.2.4 + */ + SubscribeUserAgentClient.prototype.timer_N = function () { + this.logger.warn("Timer N expired for SUBSCRIBE user agent client. Timed out waiting for NOTIFY."); + this.waitNotifyStop(); + if (this.delegate && this.delegate.onNotifyTimeout) { + this.delegate.onNotifyTimeout(); + } + }; + return SubscribeUserAgentClient; +}(user_agent_client_1.UserAgentClient)); +exports.SubscribeUserAgentClient = SubscribeUserAgentClient; diff --git a/lib/Core/user-agents/subscribe-user-agent-server.d.ts b/lib/Core/user-agents/subscribe-user-agent-server.d.ts new file mode 100644 index 000000000..d2bee2e6f --- /dev/null +++ b/lib/Core/user-agents/subscribe-user-agent-server.d.ts @@ -0,0 +1,8 @@ +import { IncomingRequest as IncomingRequestMessage } from "../../SIPMessage"; +import { IncomingRequestDelegate, IncomingSubscribeRequest } from "../messages"; +import { UserAgentCore } from "../user-agent-core"; +import { UserAgentServer } from "./user-agent-server"; +export declare class SubscribeUserAgentServer extends UserAgentServer implements IncomingSubscribeRequest { + protected core: UserAgentCore; + constructor(core: UserAgentCore, message: IncomingRequestMessage, delegate?: IncomingRequestDelegate); +} diff --git a/lib/Core/user-agents/subscribe-user-agent-server.js b/lib/Core/user-agents/subscribe-user-agent-server.js new file mode 100644 index 000000000..822cd1127 --- /dev/null +++ b/lib/Core/user-agents/subscribe-user-agent-server.js @@ -0,0 +1,27 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var transactions_1 = require("../transactions"); +var user_agent_server_1 = require("./user-agent-server"); +var SubscribeUserAgentServer = /** @class */ (function (_super) { + __extends(SubscribeUserAgentServer, _super); + function SubscribeUserAgentServer(core, message, delegate) { + var _this = _super.call(this, transactions_1.NonInviteServerTransaction, core, message, delegate) || this; + _this.core = core; + return _this; + } + return SubscribeUserAgentServer; +}(user_agent_server_1.UserAgentServer)); +exports.SubscribeUserAgentServer = SubscribeUserAgentServer; diff --git a/lib/Core/user-agents/user-agent-client.d.ts b/lib/Core/user-agents/user-agent-client.d.ts new file mode 100644 index 000000000..903cd3274 --- /dev/null +++ b/lib/Core/user-agents/user-agent-client.d.ts @@ -0,0 +1,86 @@ +import { Logger, LoggerFactory } from "../../LoggerFactory"; +import { IncomingResponse as IncomingResponseMessage, OutgoingRequest as OutgoingRequestMessage } from "../../SIPMessage"; +import { Transport } from "../../Transport"; +import { OutgoingRequest, OutgoingRequestDelegate, RequestOptions } from "../messages"; +import { ClientTransaction, ClientTransactionUser } from "../transactions"; +import { UserAgentCore } from "../user-agent-core"; +declare type ClientTransactionConstructor = new (message: OutgoingRequestMessage, transport: Transport, user: ClientTransactionUser) => ClientTransaction; +export declare class UserAgentClient implements OutgoingRequest { + private transactionConstructor; + protected core: UserAgentCore; + message: OutgoingRequestMessage; + delegate?: OutgoingRequestDelegate | undefined; + protected logger: Logger; + private _transaction; + private credentials; + private challenged; + private stale; + constructor(transactionConstructor: ClientTransactionConstructor, core: UserAgentCore, message: OutgoingRequestMessage, delegate?: OutgoingRequestDelegate | undefined); + dispose(): void; + readonly loggerFactory: LoggerFactory; + /** The transaction associated with this request. */ + readonly transaction: ClientTransaction; + /** + * Since requests other than INVITE are responded to immediately, sending a + * CANCEL for a non-INVITE request would always create a race condition. + * A CANCEL request SHOULD NOT be sent to cancel a request other than INVITE. + * https://tools.ietf.org/html/rfc3261#section-9.1 + * @param options Cancel options bucket. + */ + cancel(reason?: string, options?: RequestOptions): OutgoingRequestMessage; + /** + * If a 401 (Unauthorized) or 407 (Proxy Authentication Required) + * response is received, the UAC SHOULD follow the authorization + * procedures of Section 22.2 and Section 22.3 to retry the request with + * credentials. + * https://tools.ietf.org/html/rfc3261#section-8.1.3.5 + * 22 Usage of HTTP Authentication + * https://tools.ietf.org/html/rfc3261#section-22 + * 22.1 Framework + * https://tools.ietf.org/html/rfc3261#section-22.1 + * 22.2 User-to-User Authentication + * https://tools.ietf.org/html/rfc3261#section-22.2 + * 22.3 Proxy-to-User Authentication + * https://tools.ietf.org/html/rfc3261#section-22.3 + * + * FIXME: This "guard for and retry the request with credentials" + * implementation is not complete and at best minimally passable. + * @param response The incoming response to guard. + * @returns True if the program execution is to continue in the branch in question. + * Otherwise the request is retried with credentials and current request processing must stop. + */ + protected authenticationGuard(message: IncomingResponseMessage): boolean; + /** + * Receive a response from the transaction layer. + * @param message Incoming response message. + */ + protected receiveResponse(message: IncomingResponseMessage): void; + private init; + /** + * 8.1.3.1 Transaction Layer Errors + * In some cases, the response returned by the transaction layer will + * not be a SIP message, but rather a transaction layer error. When a + * timeout error is received from the transaction layer, it MUST be + * treated as if a 408 (Request Timeout) status code has been received. + * If a fatal transport error is reported by the transport layer + * (generally, due to fatal ICMP errors in UDP or connection failures in + * TCP), the condition MUST be treated as a 503 (Service Unavailable) + * status code. + * https://tools.ietf.org/html/rfc3261#section-8.1.3.1 + */ + private onRequestTimeout; + /** + * 8.1.3.1 Transaction Layer Errors + * In some cases, the response returned by the transaction layer will + * not be a SIP message, but rather a transaction layer error. When a + * timeout error is received from the transaction layer, it MUST be + * treated as if a 408 (Request Timeout) status code has been received. + * If a fatal transport error is reported by the transport layer + * (generally, due to fatal ICMP errors in UDP or connection failures in + * TCP), the condition MUST be treated as a 503 (Service Unavailable) + * status code. + * https://tools.ietf.org/html/rfc3261#section-8.1.3.1 + */ + private onTransportError; +} +export {}; diff --git a/lib/Core/user-agents/user-agent-client.js b/lib/Core/user-agents/user-agent-client.js new file mode 100644 index 000000000..06478b669 --- /dev/null +++ b/lib/Core/user-agents/user-agent-client.js @@ -0,0 +1,311 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var Constants_1 = require("../../Constants"); +var SIPMessage_1 = require("../../SIPMessage"); +var transactions_1 = require("../transactions"); +/* + * User Agent Client (UAC): A user agent client is a logical entity + * that creates a new request, and then uses the client + * transaction state machinery to send it. The role of UAC lasts + * only for the duration of that transaction. In other words, if + * a piece of software initiates a request, it acts as a UAC for + * the duration of that transaction. If it receives a request + * later, it assumes the role of a user agent server for the + * processing of that transaction. + * https://tools.ietf.org/html/rfc3261#section-6 + */ +var UserAgentClient = /** @class */ (function () { + function UserAgentClient(transactionConstructor, core, message, delegate) { + this.transactionConstructor = transactionConstructor; + this.core = core; + this.message = message; + this.delegate = delegate; + this.challenged = false; + this.stale = false; + this.logger = this.loggerFactory.getLogger("sip.user-agent-client"); + this.init(); + } + UserAgentClient.prototype.dispose = function () { + this.transaction.dispose(); + }; + Object.defineProperty(UserAgentClient.prototype, "loggerFactory", { + get: function () { + return this.core.loggerFactory; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(UserAgentClient.prototype, "transaction", { + /** The transaction associated with this request. */ + get: function () { + if (!this._transaction) { + throw new Error("Transaction undefined."); + } + return this._transaction; + }, + enumerable: true, + configurable: true + }); + /** + * Since requests other than INVITE are responded to immediately, sending a + * CANCEL for a non-INVITE request would always create a race condition. + * A CANCEL request SHOULD NOT be sent to cancel a request other than INVITE. + * https://tools.ietf.org/html/rfc3261#section-9.1 + * @param options Cancel options bucket. + */ + UserAgentClient.prototype.cancel = function (reason, options) { + var _this = this; + if (options === void 0) { options = {}; } + if (!this.transaction) { + throw new Error("Transaction undefined."); + } + if (!this.message.to) { + throw new Error("To undefined."); + } + if (!this.message.from) { + throw new Error("From undefined."); + } + // The following procedures are used to construct a CANCEL request. The + // Request-URI, Call-ID, To, the numeric part of CSeq, and From header + // fields in the CANCEL request MUST be identical to those in the + // request being cancelled, including tags. A CANCEL constructed by a + // client MUST have only a single Via header field value matching the + // top Via value in the request being cancelled. Using the same values + // for these header fields allows the CANCEL to be matched with the + // request it cancels (Section 9.2 indicates how such matching occurs). + // However, the method part of the CSeq header field MUST have a value + // of CANCEL. This allows it to be identified and processed as a + // transaction in its own right (See Section 17). + // https://tools.ietf.org/html/rfc3261#section-9.1 + var message = new SIPMessage_1.OutgoingRequest(Constants_1.C.CANCEL, this.message.ruri, this.message.ua, { + toUri: this.message.to.uri, + toTag: this.message.toTag, + fromUri: this.message.from.uri, + fromTag: this.message.fromTag, + callId: this.message.callId, + cseq: this.message.cseq + }, options.extraHeaders); + message.callId = this.message.callId; + message.cseq = this.message.cseq; + // TODO: Revisit this. + // The CANCEL needs to use the same branch parameter so that + // it matches the INVITE transaction, but this is a hacky way to do this. + // Or at the very least not well documented. If the the branch parameter + // is set on the outgoing request, the transaction will use it. + // Otherwise the transaction will make a new one. + message.branch = this.message.branch; + if (this.message.headers.Route) { + message.headers.Route = this.message.headers.Route; + } + if (reason) { + message.setHeader("Reason", reason); + } + // If no provisional response has been received, the CANCEL request MUST + // NOT be sent; rather, the client MUST wait for the arrival of a + // provisional response before sending the request. If the original + // request has generated a final response, the CANCEL SHOULD NOT be + // sent, as it is an effective no-op, since CANCEL has no effect on + // requests that have already generated a final response. + // https://tools.ietf.org/html/rfc3261#section-9.1 + if (this.transaction.state === transactions_1.TransactionState.Proceeding) { + var uac = new UserAgentClient(transactions_1.NonInviteClientTransaction, this.core, message); + } + else { + this.transaction.once("stateChanged", function () { + if (_this.transaction && _this.transaction.state === transactions_1.TransactionState.Proceeding) { + var uac = new UserAgentClient(transactions_1.NonInviteClientTransaction, _this.core, message); + } + }); + } + return message; + }; + /** + * If a 401 (Unauthorized) or 407 (Proxy Authentication Required) + * response is received, the UAC SHOULD follow the authorization + * procedures of Section 22.2 and Section 22.3 to retry the request with + * credentials. + * https://tools.ietf.org/html/rfc3261#section-8.1.3.5 + * 22 Usage of HTTP Authentication + * https://tools.ietf.org/html/rfc3261#section-22 + * 22.1 Framework + * https://tools.ietf.org/html/rfc3261#section-22.1 + * 22.2 User-to-User Authentication + * https://tools.ietf.org/html/rfc3261#section-22.2 + * 22.3 Proxy-to-User Authentication + * https://tools.ietf.org/html/rfc3261#section-22.3 + * + * FIXME: This "guard for and retry the request with credentials" + * implementation is not complete and at best minimally passable. + * @param response The incoming response to guard. + * @returns True if the program execution is to continue in the branch in question. + * Otherwise the request is retried with credentials and current request processing must stop. + */ + UserAgentClient.prototype.authenticationGuard = function (message) { + var statusCode = message.statusCode; + if (!statusCode) { + throw new Error("Response status code undefined."); + } + // If a 401 (Unauthorized) or 407 (Proxy Authentication Required) + // response is received, the UAC SHOULD follow the authorization + // procedures of Section 22.2 and Section 22.3 to retry the request with + // credentials. + // https://tools.ietf.org/html/rfc3261#section-8.1.3.5 + if (statusCode !== 401 && statusCode !== 407) { + return true; + } + // Get and parse the appropriate WWW-Authenticate or Proxy-Authenticate header. + var challenge; + var authorizationHeaderName; + if (statusCode === 401) { + challenge = message.parseHeader("www-authenticate"); + authorizationHeaderName = "authorization"; + } + else { + challenge = message.parseHeader("proxy-authenticate"); + authorizationHeaderName = "proxy-authorization"; + } + // Verify it seems a valid challenge. + if (!challenge) { + this.logger.warn(statusCode + " with wrong or missing challenge, cannot authenticate"); + return true; + } + // Avoid infinite authentications. + if (this.challenged && (this.stale || challenge.stale !== true)) { + this.logger.warn(statusCode + " apparently in authentication loop, cannot authenticate"); + return true; + } + // Get credentials. + if (!this.credentials) { + this.credentials = this.core.configuration.authenticationFactory(); + if (!this.credentials) { + this.logger.warn("Unable to obtain credentials, cannot authenticate"); + return true; + } + } + // Verify that the challenge is really valid. + if (!this.credentials.authenticate(this.message, challenge)) { + return true; + } + this.challenged = true; + if (challenge.stale) { + this.stale = true; + } + var cseq = this.message.cseq += 1; + this.message.setHeader("cseq", cseq + " " + this.message.method); + this.message.setHeader(authorizationHeaderName, this.credentials.toString()); + // Calling init (again) will swap out our existing client transaction with a new one. + // FIXME: HACK: An assumption is being made here that there is nothing that needs to + // be cleaned up beyond the client transaction which is being replaced. For example, + // it is assumed that no early dialogs have been created. + this.init(); + return false; + }; + /** + * Receive a response from the transaction layer. + * @param message Incoming response message. + */ + UserAgentClient.prototype.receiveResponse = function (message) { + if (!this.authenticationGuard(message)) { + return; + } + var statusCode = message.statusCode ? message.statusCode.toString() : ""; + if (!statusCode) { + throw new Error("Response status code undefined."); + } + switch (true) { + case /^100$/.test(statusCode): + if (this.delegate && this.delegate.onTrying) { + this.delegate.onTrying({ message: message }); + } + break; + case /^1[0-9]{2}$/.test(statusCode): + if (this.delegate && this.delegate.onProgress) { + this.delegate.onProgress({ message: message }); + } + break; + case /^2[0-9]{2}$/.test(statusCode): + if (this.delegate && this.delegate.onAccept) { + this.delegate.onAccept({ message: message }); + } + break; + case /^3[0-9]{2}$/.test(statusCode): + if (this.delegate && this.delegate.onRedirect) { + this.delegate.onRedirect({ message: message }); + } + break; + case /^[4-6][0-9]{2}$/.test(statusCode): + if (this.delegate && this.delegate.onReject) { + this.delegate.onReject({ message: message }); + } + break; + default: + throw new Error("Invalid status code " + statusCode); + } + }; + UserAgentClient.prototype.init = function () { + var _this = this; + // We are the transaction user. + var user = { + loggerFactory: this.loggerFactory, + onRequestTimeout: function () { return _this.onRequestTimeout(); }, + onStateChange: function (newState) { + if (newState === transactions_1.TransactionState.Terminated) { + // Remove the terminated transaction from the core. + _this.core.userAgentClients.delete(userAgentClientId); + // FIXME: HACK: Our transaction may have been swapped out with a new one + // post authentication (see above), so make sure to only to dispose of + // ourselves if this terminating transaction is our current transaction. + if (transaction === _this._transaction) { + _this.dispose(); + } + } + }, + onTransportError: function (error) { return _this.onTransportError(error); }, + receiveResponse: function (message) { return _this.receiveResponse(message); } + }; + // Create a new transaction with us as the user. + var transaction = new this.transactionConstructor(this.message, this.core.transport, user); + this._transaction = transaction; + // Add the new transaction to the core. + var userAgentClientId = transaction.id + transaction.request.method; + this.core.userAgentClients.set(userAgentClientId, this); + }; + /** + * 8.1.3.1 Transaction Layer Errors + * In some cases, the response returned by the transaction layer will + * not be a SIP message, but rather a transaction layer error. When a + * timeout error is received from the transaction layer, it MUST be + * treated as if a 408 (Request Timeout) status code has been received. + * If a fatal transport error is reported by the transport layer + * (generally, due to fatal ICMP errors in UDP or connection failures in + * TCP), the condition MUST be treated as a 503 (Service Unavailable) + * status code. + * https://tools.ietf.org/html/rfc3261#section-8.1.3.1 + */ + UserAgentClient.prototype.onRequestTimeout = function () { + this.logger.warn("User agent client request timed out. Generating internal 408 Request Timeout."); + var message = this.core.configuration.onRequestTimeoutResponseMessageFactory(); + this.receiveResponse(message); + return; + }; + /** + * 8.1.3.1 Transaction Layer Errors + * In some cases, the response returned by the transaction layer will + * not be a SIP message, but rather a transaction layer error. When a + * timeout error is received from the transaction layer, it MUST be + * treated as if a 408 (Request Timeout) status code has been received. + * If a fatal transport error is reported by the transport layer + * (generally, due to fatal ICMP errors in UDP or connection failures in + * TCP), the condition MUST be treated as a 503 (Service Unavailable) + * status code. + * https://tools.ietf.org/html/rfc3261#section-8.1.3.1 + */ + UserAgentClient.prototype.onTransportError = function (error) { + this.logger.error(error.message); + this.logger.error("User agent client request transport error. Generating internal 503 Service Unavailable."); + var message = this.core.configuration.onTransportErrorResponseMessageFactory(); + this.receiveResponse(message); + }; + return UserAgentClient; +}()); +exports.UserAgentClient = UserAgentClient; diff --git a/lib/Core/user-agents/user-agent-server.d.ts b/lib/Core/user-agents/user-agent-server.d.ts new file mode 100644 index 000000000..595f7d934 --- /dev/null +++ b/lib/Core/user-agents/user-agent-server.d.ts @@ -0,0 +1,78 @@ +import { Logger, LoggerFactory } from "../../LoggerFactory"; +import { IncomingRequest as IncomingRequestMessage } from "../../SIPMessage"; +import { Transport } from "../../Transport"; +import { URI } from "../../URI"; +import { IncomingRequest, IncomingRequestDelegate, OutgoingResponse, ResponseOptions } from "../messages"; +import { ServerTransaction, ServerTransactionUser } from "../transactions"; +import { UserAgentCore } from "../user-agent-core"; +declare type ServerTransactionConstructor = new (message: IncomingRequestMessage, transport: Transport, user: ServerTransactionUser) => ServerTransaction; +/** + * User Agent Server (UAS): A user agent server is a logical entity + * that generates a response to a SIP request. The response + * accepts, rejects, or redirects the request. This role lasts + * only for the duration of that transaction. In other words, if + * a piece of software responds to a request, it acts as a UAS for + * the duration of that transaction. If it generates a request + * later, it assumes the role of a user agent client for the + * processing of that transaction. + * https://tools.ietf.org/html/rfc3261#section-6 + */ +export declare class UserAgentServer implements IncomingRequest { + private transactionConstructor; + protected core: UserAgentCore; + message: IncomingRequestMessage; + delegate?: IncomingRequestDelegate | undefined; + protected logger: Logger; + protected toTag: string; + private _transaction; + constructor(transactionConstructor: ServerTransactionConstructor, core: UserAgentCore, message: IncomingRequestMessage, delegate?: IncomingRequestDelegate | undefined); + dispose(): void; + readonly loggerFactory: LoggerFactory; + /** The transaction associated with this request. */ + readonly transaction: ServerTransaction; + accept(options?: ResponseOptions): OutgoingResponse; + progress(options?: ResponseOptions): OutgoingResponse; + redirect(contacts: Array, options?: ResponseOptions): OutgoingResponse; + reject(options?: ResponseOptions): OutgoingResponse; + trying(options?: ResponseOptions): OutgoingResponse; + /** + * If the UAS did not find a matching transaction for the CANCEL + * according to the procedure above, it SHOULD respond to the CANCEL + * with a 481 (Call Leg/Transaction Does Not Exist). If the transaction + * for the original request still exists, the behavior of the UAS on + * receiving a CANCEL request depends on whether it has already sent a + * final response for the original request. If it has, the CANCEL + * request has no effect on the processing of the original request, no + * effect on any session state, and no effect on the responses generated + * for the original request. If the UAS has not issued a final response + * for the original request, its behavior depends on the method of the + * original request. If the original request was an INVITE, the UAS + * SHOULD immediately respond to the INVITE with a 487 (Request + * Terminated). A CANCEL request has no impact on the processing of + * transactions with any other method defined in this specification. + * https://tools.ietf.org/html/rfc3261#section-9.2 + * @param request Incoming CANCEL request. + */ + receiveCancel(message: IncomingRequestMessage): void; + protected readonly acceptable: boolean; + protected readonly progressable: boolean; + protected readonly redirectable: boolean; + protected readonly rejectable: boolean; + protected readonly tryingable: boolean; + /** + * When a UAS wishes to construct a response to a request, it follows + * the general procedures detailed in the following subsections. + * Additional behaviors specific to the response code in question, which + * are not detailed in this section, may also be required. + * + * Once all procedures associated with the creation of a response have + * been completed, the UAS hands the response back to the server + * transaction from which it received the request. + * https://tools.ietf.org/html/rfc3261#section-8.2.6 + * @param statusCode Status code to reply with. + * @param options Reply options bucket. + */ + private reply; + private init; +} +export {}; diff --git a/lib/Core/user-agents/user-agent-server.js b/lib/Core/user-agents/user-agent-server.js new file mode 100644 index 000000000..227c3d7e3 --- /dev/null +++ b/lib/Core/user-agents/user-agent-server.js @@ -0,0 +1,257 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var Exceptions_1 = require("../../Exceptions"); +var Utils_1 = require("../../Utils"); +var messages_1 = require("../messages"); +var transactions_1 = require("../transactions"); +/** + * User Agent Server (UAS): A user agent server is a logical entity + * that generates a response to a SIP request. The response + * accepts, rejects, or redirects the request. This role lasts + * only for the duration of that transaction. In other words, if + * a piece of software responds to a request, it acts as a UAS for + * the duration of that transaction. If it generates a request + * later, it assumes the role of a user agent client for the + * processing of that transaction. + * https://tools.ietf.org/html/rfc3261#section-6 + */ +var UserAgentServer = /** @class */ (function () { + function UserAgentServer(transactionConstructor, core, message, delegate) { + this.transactionConstructor = transactionConstructor; + this.core = core; + this.message = message; + this.delegate = delegate; + this.logger = this.loggerFactory.getLogger("sip.user-agent-server"); + this.toTag = message.toTag ? message.toTag : Utils_1.Utils.newTag(); + this.init(); + } + UserAgentServer.prototype.dispose = function () { + this.transaction.dispose(); + }; + Object.defineProperty(UserAgentServer.prototype, "loggerFactory", { + get: function () { + return this.core.loggerFactory; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(UserAgentServer.prototype, "transaction", { + /** The transaction associated with this request. */ + get: function () { + if (!this._transaction) { + throw new Error("Transaction undefined."); + } + return this._transaction; + }, + enumerable: true, + configurable: true + }); + UserAgentServer.prototype.accept = function (options) { + if (options === void 0) { options = { statusCode: 200 }; } + if (!this.acceptable) { + throw new Exceptions_1.Exceptions.TransactionStateError(this.message.method + " not acceptable in state " + this.transaction.state + "."); + } + var statusCode = options.statusCode; + if (statusCode < 200 || statusCode > 299) { + throw new TypeError("Invalid statusCode: " + statusCode); + } + var response = this.reply(options); + return response; + }; + UserAgentServer.prototype.progress = function (options) { + if (options === void 0) { options = { statusCode: 180 }; } + if (!this.progressable) { + throw new Exceptions_1.Exceptions.TransactionStateError(this.message.method + " not progressable in state " + this.transaction.state + "."); + } + var statusCode = options.statusCode; + if (statusCode < 101 || statusCode > 199) { + throw new TypeError("Invalid statusCode: " + statusCode); + } + var response = this.reply(options); + return response; + }; + UserAgentServer.prototype.redirect = function (contacts, options) { + if (options === void 0) { options = { statusCode: 302 }; } + if (!this.redirectable) { + throw new Exceptions_1.Exceptions.TransactionStateError(this.message.method + " not redirectable in state " + this.transaction.state + "."); + } + var statusCode = options.statusCode; + if (statusCode < 300 || statusCode > 399) { + throw new TypeError("Invalid statusCode: " + statusCode); + } + var contactHeaders = new Array(); + contacts.forEach(function (contact) { return contactHeaders.push("Contact: " + contact.toString()); }); + options.extraHeaders = (options.extraHeaders || []).concat(contactHeaders); + var response = this.reply(options); + return response; + }; + UserAgentServer.prototype.reject = function (options) { + if (options === void 0) { options = { statusCode: 480 }; } + if (!this.rejectable) { + throw new Exceptions_1.Exceptions.TransactionStateError(this.message.method + " not rejectable in state " + this.transaction.state + "."); + } + var statusCode = options.statusCode; + if (statusCode < 400 || statusCode > 699) { + throw new TypeError("Invalid statusCode: " + statusCode); + } + var response = this.reply(options); + return response; + }; + UserAgentServer.prototype.trying = function (options) { + if (!this.tryingable) { + throw new Exceptions_1.Exceptions.TransactionStateError(this.message.method + " not tryingable in state " + this.transaction.state + "."); + } + var response = this.reply({ statusCode: 100 }); + return response; + }; + /** + * If the UAS did not find a matching transaction for the CANCEL + * according to the procedure above, it SHOULD respond to the CANCEL + * with a 481 (Call Leg/Transaction Does Not Exist). If the transaction + * for the original request still exists, the behavior of the UAS on + * receiving a CANCEL request depends on whether it has already sent a + * final response for the original request. If it has, the CANCEL + * request has no effect on the processing of the original request, no + * effect on any session state, and no effect on the responses generated + * for the original request. If the UAS has not issued a final response + * for the original request, its behavior depends on the method of the + * original request. If the original request was an INVITE, the UAS + * SHOULD immediately respond to the INVITE with a 487 (Request + * Terminated). A CANCEL request has no impact on the processing of + * transactions with any other method defined in this specification. + * https://tools.ietf.org/html/rfc3261#section-9.2 + * @param request Incoming CANCEL request. + */ + UserAgentServer.prototype.receiveCancel = function (message) { + // Note: Currently CANCEL is being handled as a special case. + // No UAS is created to handle the CANCEL and the response to + // it CANCEL is being handled statelessly by the user agent core. + // As such, there is currently no way to externally impact the + // response to the a CANCEL request. + if (this.delegate && this.delegate.onCancel) { + this.delegate.onCancel(message); + } + }; + Object.defineProperty(UserAgentServer.prototype, "acceptable", { + get: function () { + if (this.transaction instanceof transactions_1.InviteServerTransaction) { + return (this.transaction.state === transactions_1.TransactionState.Proceeding || + this.transaction.state === transactions_1.TransactionState.Accepted); + } + if (this.transaction instanceof transactions_1.NonInviteServerTransaction) { + return (this.transaction.state === transactions_1.TransactionState.Trying || + this.transaction.state === transactions_1.TransactionState.Proceeding); + } + throw new Error("Unknown transaction type."); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(UserAgentServer.prototype, "progressable", { + get: function () { + if (this.transaction instanceof transactions_1.InviteServerTransaction) { + return this.transaction.state === transactions_1.TransactionState.Proceeding; + } + if (this.transaction instanceof transactions_1.NonInviteServerTransaction) { + return false; // https://tools.ietf.org/html/rfc4320#section-4.1 + } + throw new Error("Unknown transaction type."); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(UserAgentServer.prototype, "redirectable", { + get: function () { + if (this.transaction instanceof transactions_1.InviteServerTransaction) { + return this.transaction.state === transactions_1.TransactionState.Proceeding; + } + if (this.transaction instanceof transactions_1.NonInviteServerTransaction) { + return (this.transaction.state === transactions_1.TransactionState.Trying || + this.transaction.state === transactions_1.TransactionState.Proceeding); + } + throw new Error("Unknown transaction type."); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(UserAgentServer.prototype, "rejectable", { + get: function () { + if (this.transaction instanceof transactions_1.InviteServerTransaction) { + return this.transaction.state === transactions_1.TransactionState.Proceeding; + } + if (this.transaction instanceof transactions_1.NonInviteServerTransaction) { + return (this.transaction.state === transactions_1.TransactionState.Trying || + this.transaction.state === transactions_1.TransactionState.Proceeding); + } + throw new Error("Unknown transaction type."); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(UserAgentServer.prototype, "tryingable", { + get: function () { + if (this.transaction instanceof transactions_1.InviteServerTransaction) { + return this.transaction.state === transactions_1.TransactionState.Proceeding; + } + if (this.transaction instanceof transactions_1.NonInviteServerTransaction) { + return this.transaction.state === transactions_1.TransactionState.Trying; + } + throw new Error("Unknown transaction type."); + }, + enumerable: true, + configurable: true + }); + /** + * When a UAS wishes to construct a response to a request, it follows + * the general procedures detailed in the following subsections. + * Additional behaviors specific to the response code in question, which + * are not detailed in this section, may also be required. + * + * Once all procedures associated with the creation of a response have + * been completed, the UAS hands the response back to the server + * transaction from which it received the request. + * https://tools.ietf.org/html/rfc3261#section-8.2.6 + * @param statusCode Status code to reply with. + * @param options Reply options bucket. + */ + UserAgentServer.prototype.reply = function (options) { + if (!options.toTag && options.statusCode !== 100) { + options.toTag = this.toTag; + } + options.userAgent = options.userAgent || this.core.configuration.userAgentHeaderFieldValue; + var response = messages_1.constructOutgoingResponse(this.message, options); + this.transaction.receiveResponse(options.statusCode, response.message); + return response; + }; + UserAgentServer.prototype.init = function () { + var _this = this; + // We are the transaction user. + var user = { + loggerFactory: this.loggerFactory, + onStateChange: function (newState) { + if (newState === transactions_1.TransactionState.Terminated) { + // Remove the terminated transaction from the core. + _this.core.userAgentServers.delete(userAgentServerId); + _this.dispose(); + } + }, + onTransportError: function (error) { + _this.logger.error(error.message); + if (_this.delegate && _this.delegate.onTransportError) { + _this.delegate.onTransportError(error); + } + else { + _this.logger.error("User agent server response transport error."); + } + } + }; + // Create a new transaction with us as the user. + var transaction = new this.transactionConstructor(this.message, this.core.transport, user); + this._transaction = transaction; + // Add the new transaction to the core. + var userAgentServerId = transaction.id; + this.core.userAgentServers.set(transaction.id, this); + }; + return UserAgentServer; +}()); +exports.UserAgentServer = UserAgentServer; diff --git a/lib/DigestAuthentication.d.ts b/lib/DigestAuthentication.d.ts new file mode 100644 index 000000000..0245ea243 --- /dev/null +++ b/lib/DigestAuthentication.d.ts @@ -0,0 +1,50 @@ +import { TypeStrings } from "./Enums"; +import { OutgoingRequest } from "./SIPMessage"; +import { UA } from "./UA"; +/** + * SIP Digest Authentication. + * @function Digest Authentication + * @param {SIP.UA} ua + */ +export declare class DigestAuthentication { + type: TypeStrings; + stale: boolean | undefined; + private logger; + private username; + private password; + private cnonce; + private nc; + private ncHex; + private response; + private algorithm; + private realm; + private nonce; + private opaque; + private qop; + private method; + private uri; + constructor(ua: UA); + /** + * Performs Digest authentication given a SIP request and the challenge + * received in a response to that request. + * Returns true if credentials were successfully generated, false otherwise. + * + * @param {SIP.OutgoingRequest} request + * @param {Object} challenge + */ + authenticate(request: OutgoingRequest, challenge: any, body?: string): boolean; + /** + * Return the Proxy-Authorization or WWW-Authorization header value. + */ + toString(): string; + /** + * Generate the 'nc' value as required by Digest in this.ncHex by reading this.nc. + * @private + */ + private updateNcHex; + /** + * Generate Digest 'response' value. + * @private + */ + private calculateResponse; +} diff --git a/lib/DigestAuthentication.js b/lib/DigestAuthentication.js new file mode 100644 index 000000000..9cbfaba5b --- /dev/null +++ b/lib/DigestAuthentication.js @@ -0,0 +1,145 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var crypto_js_1 = require("crypto-js"); +var Enums_1 = require("./Enums"); +var Utils_1 = require("./Utils"); +/** + * SIP Digest Authentication. + * @function Digest Authentication + * @param {SIP.UA} ua + */ +var DigestAuthentication = /** @class */ (function () { + function DigestAuthentication(ua) { + this.type = Enums_1.TypeStrings.DigestAuthentication; + this.logger = ua.getLogger("sipjs.digestauthentication"); + this.username = ua.configuration.authorizationUser; + this.password = ua.configuration.password; + this.nc = 0; + this.ncHex = "00000000"; + } + /** + * Performs Digest authentication given a SIP request and the challenge + * received in a response to that request. + * Returns true if credentials were successfully generated, false otherwise. + * + * @param {SIP.OutgoingRequest} request + * @param {Object} challenge + */ + DigestAuthentication.prototype.authenticate = function (request, challenge, body) { + // Inspect and validate the challenge. + this.algorithm = challenge.algorithm; + this.realm = challenge.realm; + this.nonce = challenge.nonce; + this.opaque = challenge.opaque; + this.stale = challenge.stale; + if (this.algorithm) { + if (this.algorithm !== "MD5") { + this.logger.warn("challenge with Digest algorithm different than 'MD5', authentication aborted"); + return false; + } + } + else { + this.algorithm = "MD5"; + } + if (!this.realm) { + this.logger.warn("challenge without Digest realm, authentication aborted"); + return false; + } + if (!this.nonce) { + this.logger.warn("challenge without Digest nonce, authentication aborted"); + return false; + } + // 'qop' can contain a list of values (Array). Let's choose just one. + if (challenge.qop) { + if (challenge.qop.indexOf("auth") > -1) { + this.qop = "auth"; + } + else if (challenge.qop.indexOf("auth-int") > -1) { + this.qop = "auth-int"; + } + else { + // Otherwise 'qop' is present but does not contain 'auth' or 'auth-int', so abort here. + this.logger.warn("challenge without Digest qop different than 'auth' or 'auth-int', authentication aborted"); + return false; + } + } + else { + this.qop = undefined; + } + // Fill other attributes. + this.method = request.method; + this.uri = request.ruri; + this.cnonce = Utils_1.Utils.createRandomToken(12); + this.nc += 1; + this.updateNcHex(); + // nc-value = 8LHEX. Max value = 'FFFFFFFF'. + if (this.nc === 4294967296) { + this.nc = 1; + this.ncHex = "00000001"; + } + // Calculate the Digest "response" value. + this.calculateResponse(body); + return true; + }; + /** + * Return the Proxy-Authorization or WWW-Authorization header value. + */ + DigestAuthentication.prototype.toString = function () { + var authParams = []; + if (!this.response) { + throw new Error("response field does not exist, cannot generate Authorization header"); + } + authParams.push("algorithm=" + this.algorithm); + authParams.push('username="' + this.username + '"'); + authParams.push('realm="' + this.realm + '"'); + authParams.push('nonce="' + this.nonce + '"'); + authParams.push('uri="' + this.uri + '"'); + authParams.push('response="' + this.response + '"'); + if (this.opaque) { + authParams.push('opaque="' + this.opaque + '"'); + } + if (this.qop) { + authParams.push("qop=" + this.qop); + authParams.push('cnonce="' + this.cnonce + '"'); + authParams.push("nc=" + this.ncHex); + } + return "Digest " + authParams.join(", "); + }; + /** + * Generate the 'nc' value as required by Digest in this.ncHex by reading this.nc. + * @private + */ + DigestAuthentication.prototype.updateNcHex = function () { + var hex = Number(this.nc).toString(16); + this.ncHex = "00000000".substr(0, 8 - hex.length) + hex; + }; + /** + * Generate Digest 'response' value. + * @private + */ + DigestAuthentication.prototype.calculateResponse = function (body) { + var ha2; + // HA1 = MD5(A1) = MD5(username:realm:password) + var ha1 = crypto_js_1.MD5(this.username + ":" + this.realm + ":" + this.password); + if (this.qop === "auth") { + // HA2 = MD5(A2) = MD5(method:digestURI) + ha2 = crypto_js_1.MD5(this.method + ":" + this.uri); + // response = MD5(HA1:nonce:nonceCount:credentialsNonce:qop:HA2) + this.response = crypto_js_1.MD5(ha1 + ":" + this.nonce + ":" + this.ncHex + ":" + this.cnonce + ":auth:" + ha2); + } + else if (this.qop === "auth-int") { + // HA2 = MD5(A2) = MD5(method:digestURI:MD5(entityBody)) + ha2 = crypto_js_1.MD5(this.method + ":" + this.uri + ":" + crypto_js_1.MD5(body ? body : "")); + // response = MD5(HA1:nonce:nonceCount:credentialsNonce:qop:HA2) + this.response = crypto_js_1.MD5(ha1 + ":" + this.nonce + ":" + this.ncHex + ":" + this.cnonce + ":auth-int:" + ha2); + } + else if (this.qop === undefined) { + // HA2 = MD5(A2) = MD5(method:digestURI) + ha2 = crypto_js_1.MD5(this.method + ":" + this.uri); + // response = MD5(HA1:nonce:HA2) + this.response = crypto_js_1.MD5(ha1 + ":" + this.nonce + ":" + ha2); + } + }; + return DigestAuthentication; +}()); +exports.DigestAuthentication = DigestAuthentication; diff --git a/lib/Enums.d.ts b/lib/Enums.d.ts new file mode 100644 index 000000000..a55b876e1 --- /dev/null +++ b/lib/Enums.d.ts @@ -0,0 +1,61 @@ +export declare enum DialogStatus { + STATUS_EARLY = 1, + STATUS_CONFIRMED = 2 +} +export declare enum SessionStatus { + STATUS_NULL = 0, + STATUS_INVITE_SENT = 1, + STATUS_1XX_RECEIVED = 2, + STATUS_INVITE_RECEIVED = 3, + STATUS_WAITING_FOR_ANSWER = 4, + STATUS_ANSWERED = 5, + STATUS_WAITING_FOR_PRACK = 6, + STATUS_WAITING_FOR_ACK = 7, + STATUS_CANCELED = 8, + STATUS_TERMINATED = 9, + STATUS_ANSWERED_WAITING_FOR_PRACK = 10, + STATUS_EARLY_MEDIA = 11, + STATUS_CONFIRMED = 12 +} +export declare enum TypeStrings { + ClientContext = 0, + ConfigurationError = 1, + Dialog = 2, + DigestAuthentication = 3, + DTMF = 4, + IncomingMessage = 5, + IncomingRequest = 6, + IncomingResponse = 7, + InvalidStateError = 8, + InviteClientContext = 9, + InviteServerContext = 10, + Logger = 11, + LoggerFactory = 12, + MethodParameterError = 13, + NameAddrHeader = 14, + NotSupportedError = 15, + OutgoingRequest = 16, + Parameters = 17, + PublishContext = 18, + ReferClientContext = 19, + ReferServerContext = 20, + RegisterContext = 21, + RenegotiationError = 22, + RequestSender = 23, + ServerContext = 24, + Session = 25, + SessionDescriptionHandler = 26, + SessionDescriptionHandlerError = 27, + SessionDescriptionHandlerObserver = 28, + Subscription = 29, + Transport = 30, + UA = 31, + URI = 32 +} +export declare enum UAStatus { + STATUS_INIT = 0, + STATUS_STARTING = 1, + STATUS_READY = 2, + STATUS_USER_CLOSED = 3, + STATUS_NOT_READY = 4 +} diff --git a/lib/Enums.js b/lib/Enums.js new file mode 100644 index 000000000..920136fd0 --- /dev/null +++ b/lib/Enums.js @@ -0,0 +1,71 @@ +"use strict"; +// enums can't really be declared, so they are set here. +// pulled out of individual files to avoid circular dependencies +Object.defineProperty(exports, "__esModule", { value: true }); +var DialogStatus; +(function (DialogStatus) { + DialogStatus[DialogStatus["STATUS_EARLY"] = 1] = "STATUS_EARLY"; + DialogStatus[DialogStatus["STATUS_CONFIRMED"] = 2] = "STATUS_CONFIRMED"; +})(DialogStatus = exports.DialogStatus || (exports.DialogStatus = {})); +var SessionStatus; +(function (SessionStatus) { + // Session states + SessionStatus[SessionStatus["STATUS_NULL"] = 0] = "STATUS_NULL"; + SessionStatus[SessionStatus["STATUS_INVITE_SENT"] = 1] = "STATUS_INVITE_SENT"; + SessionStatus[SessionStatus["STATUS_1XX_RECEIVED"] = 2] = "STATUS_1XX_RECEIVED"; + SessionStatus[SessionStatus["STATUS_INVITE_RECEIVED"] = 3] = "STATUS_INVITE_RECEIVED"; + SessionStatus[SessionStatus["STATUS_WAITING_FOR_ANSWER"] = 4] = "STATUS_WAITING_FOR_ANSWER"; + SessionStatus[SessionStatus["STATUS_ANSWERED"] = 5] = "STATUS_ANSWERED"; + SessionStatus[SessionStatus["STATUS_WAITING_FOR_PRACK"] = 6] = "STATUS_WAITING_FOR_PRACK"; + SessionStatus[SessionStatus["STATUS_WAITING_FOR_ACK"] = 7] = "STATUS_WAITING_FOR_ACK"; + SessionStatus[SessionStatus["STATUS_CANCELED"] = 8] = "STATUS_CANCELED"; + SessionStatus[SessionStatus["STATUS_TERMINATED"] = 9] = "STATUS_TERMINATED"; + SessionStatus[SessionStatus["STATUS_ANSWERED_WAITING_FOR_PRACK"] = 10] = "STATUS_ANSWERED_WAITING_FOR_PRACK"; + SessionStatus[SessionStatus["STATUS_EARLY_MEDIA"] = 11] = "STATUS_EARLY_MEDIA"; + SessionStatus[SessionStatus["STATUS_CONFIRMED"] = 12] = "STATUS_CONFIRMED"; +})(SessionStatus = exports.SessionStatus || (exports.SessionStatus = {})); +var TypeStrings; +(function (TypeStrings) { + TypeStrings[TypeStrings["ClientContext"] = 0] = "ClientContext"; + TypeStrings[TypeStrings["ConfigurationError"] = 1] = "ConfigurationError"; + TypeStrings[TypeStrings["Dialog"] = 2] = "Dialog"; + TypeStrings[TypeStrings["DigestAuthentication"] = 3] = "DigestAuthentication"; + TypeStrings[TypeStrings["DTMF"] = 4] = "DTMF"; + TypeStrings[TypeStrings["IncomingMessage"] = 5] = "IncomingMessage"; + TypeStrings[TypeStrings["IncomingRequest"] = 6] = "IncomingRequest"; + TypeStrings[TypeStrings["IncomingResponse"] = 7] = "IncomingResponse"; + TypeStrings[TypeStrings["InvalidStateError"] = 8] = "InvalidStateError"; + TypeStrings[TypeStrings["InviteClientContext"] = 9] = "InviteClientContext"; + TypeStrings[TypeStrings["InviteServerContext"] = 10] = "InviteServerContext"; + TypeStrings[TypeStrings["Logger"] = 11] = "Logger"; + TypeStrings[TypeStrings["LoggerFactory"] = 12] = "LoggerFactory"; + TypeStrings[TypeStrings["MethodParameterError"] = 13] = "MethodParameterError"; + TypeStrings[TypeStrings["NameAddrHeader"] = 14] = "NameAddrHeader"; + TypeStrings[TypeStrings["NotSupportedError"] = 15] = "NotSupportedError"; + TypeStrings[TypeStrings["OutgoingRequest"] = 16] = "OutgoingRequest"; + TypeStrings[TypeStrings["Parameters"] = 17] = "Parameters"; + TypeStrings[TypeStrings["PublishContext"] = 18] = "PublishContext"; + TypeStrings[TypeStrings["ReferClientContext"] = 19] = "ReferClientContext"; + TypeStrings[TypeStrings["ReferServerContext"] = 20] = "ReferServerContext"; + TypeStrings[TypeStrings["RegisterContext"] = 21] = "RegisterContext"; + TypeStrings[TypeStrings["RenegotiationError"] = 22] = "RenegotiationError"; + TypeStrings[TypeStrings["RequestSender"] = 23] = "RequestSender"; + TypeStrings[TypeStrings["ServerContext"] = 24] = "ServerContext"; + TypeStrings[TypeStrings["Session"] = 25] = "Session"; + TypeStrings[TypeStrings["SessionDescriptionHandler"] = 26] = "SessionDescriptionHandler"; + TypeStrings[TypeStrings["SessionDescriptionHandlerError"] = 27] = "SessionDescriptionHandlerError"; + TypeStrings[TypeStrings["SessionDescriptionHandlerObserver"] = 28] = "SessionDescriptionHandlerObserver"; + TypeStrings[TypeStrings["Subscription"] = 29] = "Subscription"; + TypeStrings[TypeStrings["Transport"] = 30] = "Transport"; + TypeStrings[TypeStrings["UA"] = 31] = "UA"; + TypeStrings[TypeStrings["URI"] = 32] = "URI"; +})(TypeStrings = exports.TypeStrings || (exports.TypeStrings = {})); +// UA status codes +var UAStatus; +(function (UAStatus) { + UAStatus[UAStatus["STATUS_INIT"] = 0] = "STATUS_INIT"; + UAStatus[UAStatus["STATUS_STARTING"] = 1] = "STATUS_STARTING"; + UAStatus[UAStatus["STATUS_READY"] = 2] = "STATUS_READY"; + UAStatus[UAStatus["STATUS_USER_CLOSED"] = 3] = "STATUS_USER_CLOSED"; + UAStatus[UAStatus["STATUS_NOT_READY"] = 4] = "STATUS_NOT_READY"; +})(UAStatus = exports.UAStatus || (exports.UAStatus = {})); diff --git a/lib/Exceptions.d.ts b/lib/Exceptions.d.ts new file mode 100644 index 000000000..b3a85862d --- /dev/null +++ b/lib/Exceptions.d.ts @@ -0,0 +1,85 @@ +import { SessionStatus, TypeStrings } from "./Enums"; +/** + * An Exception is considered a condition that a reasonable application may wish to catch. + * An Error indicates serious problems that a reasonable application should not try to catch. + */ +export declare abstract class Exception extends Error { + protected constructor(message?: string); +} +export declare namespace Exceptions { + /** + * Indicates that the operation could not be completed given the current transaction state. + */ + class TransactionStateError extends Exception { + constructor(message?: string); + } + /** + * Indicates the session description handler has closed. + * Occurs when getDescription() or setDescription() are called after close() has been called. + * Occurs when close() is called while getDescription() or setDescription() are in progress. + */ + class ClosedSessionDescriptionHandlerError extends Exception { + constructor(); + } + /** + * Indicates the session terminated before the action completed. + */ + class TerminatedSessionError extends Exception { + constructor(); + } + /** + * Transport error. + */ + class TransportError extends Exception { + constructor(message?: string); + } + /** + * Unsupported session description content type. + */ + class UnsupportedSessionDescriptionContentTypeError extends Exception { + constructor(message?: string); + } +} +/** + * DEPRECATED: The original implementation of exceptions in this library attempted to + * deal with the lack of type checking in JavaScript by adding a "type" attribute + * to objects and using that to discriminate. On top of that it layered allcoated + * "code" numbers and constant "name" strings. All of that is unnecessary when using + * TypeScript, inheriting from Error and properly setting up the prototype chain... + */ +declare abstract class LegacyException extends Exception { + type: TypeStrings; + name: string; + message: string; + code: number; + constructor(code: number, name: string, message: string); +} +export declare namespace Exceptions { + class ConfigurationError extends LegacyException { + parameter: string; + value: any; + constructor(parameter: string, value?: any); + } + class InvalidStateError extends LegacyException { + status: SessionStatus; + constructor(status: SessionStatus); + } + class NotSupportedError extends LegacyException { + constructor(message: string); + } + class RenegotiationError extends LegacyException { + constructor(message: string); + } + class MethodParameterError extends LegacyException { + method: string; + parameter: string; + value: any; + constructor(method: string, parameter: string, value: any); + } + class SessionDescriptionHandlerError extends LegacyException { + error: string | undefined; + method: string; + constructor(method: string, error?: string, message?: string); + } +} +export {}; diff --git a/lib/Exceptions.js b/lib/Exceptions.js new file mode 100644 index 000000000..beebdfa1c --- /dev/null +++ b/lib/Exceptions.js @@ -0,0 +1,185 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Enums_1 = require("./Enums"); +// tslint:disable:max-classes-per-file +/** + * An Exception is considered a condition that a reasonable application may wish to catch. + * An Error indicates serious problems that a reasonable application should not try to catch. + */ +var Exception = /** @class */ (function (_super) { + __extends(Exception, _super); + function Exception(message) { + var _newTarget = this.constructor; + var _this = _super.call(this, message) || this; + Object.setPrototypeOf(_this, _newTarget.prototype); // restore prototype chain + return _this; + } + return Exception; +}(Error)); +exports.Exception = Exception; +var Exceptions; +(function (Exceptions) { + /** + * Indicates that the operation could not be completed given the current transaction state. + */ + var TransactionStateError = /** @class */ (function (_super) { + __extends(TransactionStateError, _super); + function TransactionStateError(message) { + return _super.call(this, message ? message : "Transaction state error.") || this; + } + return TransactionStateError; + }(Exception)); + Exceptions.TransactionStateError = TransactionStateError; + /** + * Indicates the session description handler has closed. + * Occurs when getDescription() or setDescription() are called after close() has been called. + * Occurs when close() is called while getDescription() or setDescription() are in progress. + */ + var ClosedSessionDescriptionHandlerError = /** @class */ (function (_super) { + __extends(ClosedSessionDescriptionHandlerError, _super); + function ClosedSessionDescriptionHandlerError() { + return _super.call(this, "The session description handler has closed.") || this; + } + return ClosedSessionDescriptionHandlerError; + }(Exception)); + Exceptions.ClosedSessionDescriptionHandlerError = ClosedSessionDescriptionHandlerError; + /** + * Indicates the session terminated before the action completed. + */ + var TerminatedSessionError = /** @class */ (function (_super) { + __extends(TerminatedSessionError, _super); + function TerminatedSessionError() { + return _super.call(this, "The session has terminated.") || this; + } + return TerminatedSessionError; + }(Exception)); + Exceptions.TerminatedSessionError = TerminatedSessionError; + /** + * Transport error. + */ + var TransportError = /** @class */ (function (_super) { + __extends(TransportError, _super); + function TransportError(message) { + return _super.call(this, message ? message : "Unspecified transport error.") || this; + } + return TransportError; + }(Exception)); + Exceptions.TransportError = TransportError; + /** + * Unsupported session description content type. + */ + var UnsupportedSessionDescriptionContentTypeError = /** @class */ (function (_super) { + __extends(UnsupportedSessionDescriptionContentTypeError, _super); + function UnsupportedSessionDescriptionContentTypeError(message) { + return _super.call(this, message ? message : "Unsupported session description content type.") || this; + } + return UnsupportedSessionDescriptionContentTypeError; + }(Exception)); + Exceptions.UnsupportedSessionDescriptionContentTypeError = UnsupportedSessionDescriptionContentTypeError; +})(Exceptions = exports.Exceptions || (exports.Exceptions = {})); +/** + * DEPRECATED: The original implementation of exceptions in this library attempted to + * deal with the lack of type checking in JavaScript by adding a "type" attribute + * to objects and using that to discriminate. On top of that it layered allcoated + * "code" numbers and constant "name" strings. All of that is unnecessary when using + * TypeScript, inheriting from Error and properly setting up the prototype chain... + */ +var LegacyException = /** @class */ (function (_super) { + __extends(LegacyException, _super); + function LegacyException(code, name, message) { + var _this = _super.call(this, message) || this; + _this.code = code; + _this.name = name; + _this.message = message; + return _this; + } + return LegacyException; +}(Exception)); +(function (Exceptions) { + var ConfigurationError = /** @class */ (function (_super) { + __extends(ConfigurationError, _super); + function ConfigurationError(parameter, value) { + var _this = _super.call(this, 1, "CONFIGURATION_ERROR", (!value) ? "Missing parameter: " + parameter : + "Invalid value " + JSON.stringify(value) + " for parameter '" + parameter + "'") || this; + _this.type = Enums_1.TypeStrings.ConfigurationError; + _this.parameter = parameter; + _this.value = value; + return _this; + } + return ConfigurationError; + }(LegacyException)); + Exceptions.ConfigurationError = ConfigurationError; + var InvalidStateError = /** @class */ (function (_super) { + __extends(InvalidStateError, _super); + function InvalidStateError(status) { + var _this = _super.call(this, 2, "INVALID_STATE_ERROR", "Invalid status: " + status) || this; + _this.type = Enums_1.TypeStrings.InvalidStateError; + _this.status = status; + return _this; + } + return InvalidStateError; + }(LegacyException)); + Exceptions.InvalidStateError = InvalidStateError; + var NotSupportedError = /** @class */ (function (_super) { + __extends(NotSupportedError, _super); + function NotSupportedError(message) { + var _this = _super.call(this, 3, "NOT_SUPPORTED_ERROR", message) || this; + _this.type = Enums_1.TypeStrings.NotSupportedError; + return _this; + } + return NotSupportedError; + }(LegacyException)); + Exceptions.NotSupportedError = NotSupportedError; + // 4 was GetDescriptionError, which was deprecated and now removed + var RenegotiationError = /** @class */ (function (_super) { + __extends(RenegotiationError, _super); + function RenegotiationError(message) { + var _this = _super.call(this, 5, "RENEGOTIATION_ERROR", message) || this; + _this.type = Enums_1.TypeStrings.RenegotiationError; + return _this; + } + return RenegotiationError; + }(LegacyException)); + Exceptions.RenegotiationError = RenegotiationError; + var MethodParameterError = /** @class */ (function (_super) { + __extends(MethodParameterError, _super); + function MethodParameterError(method, parameter, value) { + var _this = _super.call(this, 6, "METHOD_PARAMETER_ERROR", (!value) ? + "Missing parameter: " + parameter : + "Invalid value " + JSON.stringify(value) + " for parameter '" + parameter + "'") || this; + _this.type = Enums_1.TypeStrings.MethodParameterError; + _this.method = method; + _this.parameter = parameter; + _this.value = value; + return _this; + } + return MethodParameterError; + }(LegacyException)); + Exceptions.MethodParameterError = MethodParameterError; + // 7 was TransportError, which was replaced + var SessionDescriptionHandlerError = /** @class */ (function (_super) { + __extends(SessionDescriptionHandlerError, _super); + function SessionDescriptionHandlerError(method, error, message) { + var _this = _super.call(this, 8, "SESSION_DESCRIPTION_HANDLER_ERROR", message || "Error with Session Description Handler") || this; + _this.type = Enums_1.TypeStrings.SessionDescriptionHandlerError; + _this.method = method; + _this.error = error; + return _this; + } + return SessionDescriptionHandlerError; + }(LegacyException)); + Exceptions.SessionDescriptionHandlerError = SessionDescriptionHandlerError; +})(Exceptions = exports.Exceptions || (exports.Exceptions = {})); diff --git a/lib/Grammar.d.ts b/lib/Grammar.d.ts new file mode 100644 index 000000000..bed8f0b29 --- /dev/null +++ b/lib/Grammar.d.ts @@ -0,0 +1,19 @@ +import { NameAddrHeader } from "./NameAddrHeader"; +import { URI } from "./URI"; +export declare namespace Grammar { + function parse(input: string, startRule: string): any; + /** + * Parse the given string and returns a SIP.NameAddrHeader instance or undefined if + * it is an invalid NameAddrHeader. + * @public + * @param {String} name_addr_header + */ + function nameAddrHeaderParse(nameAddrHeader: string): NameAddrHeader | undefined; + /** + * Parse the given string and returns a SIP.URI instance or undefined if + * it is an invalid URI. + * @public + * @param {String} uri + */ + function URIParse(uri: string): URI | undefined; +} diff --git a/lib/Grammar.js b/lib/Grammar.js new file mode 100644 index 000000000..a90d7abe0 --- /dev/null +++ b/lib/Grammar.js @@ -0,0 +1,39 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var pegGrammar = require("./Grammar/dist/Grammar"); +var Grammar; +(function (Grammar) { + function parse(input, startRule) { + var options = { startRule: startRule }; + try { + pegGrammar.parse(input, options); + } + catch (e) { + options.data = -1; + } + return options.data; + } + Grammar.parse = parse; + /** + * Parse the given string and returns a SIP.NameAddrHeader instance or undefined if + * it is an invalid NameAddrHeader. + * @public + * @param {String} name_addr_header + */ + function nameAddrHeaderParse(nameAddrHeader) { + var parsedNameAddrHeader = Grammar.parse(nameAddrHeader, "Name_Addr_Header"); + return parsedNameAddrHeader !== -1 ? parsedNameAddrHeader : undefined; + } + Grammar.nameAddrHeaderParse = nameAddrHeaderParse; + /** + * Parse the given string and returns a SIP.URI instance or undefined if + * it is an invalid URI. + * @public + * @param {String} uri + */ + function URIParse(uri) { + var parsedUri = Grammar.parse(uri, "SIP_URI"); + return parsedUri !== -1 ? parsedUri : undefined; + } + Grammar.URIParse = URIParse; +})(Grammar = exports.Grammar || (exports.Grammar = {})); diff --git a/lib/Grammar/dist/Grammar.d.ts b/lib/Grammar/dist/Grammar.d.ts new file mode 100644 index 000000000..eb9f72b05 --- /dev/null +++ b/lib/Grammar/dist/Grammar.d.ts @@ -0,0 +1,50 @@ +export interface IFilePosition { + offset: number; + line: number; + column: number; +} +export interface IFileRange { + start: IFilePosition; + end: IFilePosition; +} +export interface ILiteralExpectation { + type: "literal"; + text: string; + ignoreCase: boolean; +} +export interface IClassParts extends Array { +} +export interface IClassExpectation { + type: "class"; + parts: IClassParts; + inverted: boolean; + ignoreCase: boolean; +} +export interface IAnyExpectation { + type: "any"; +} +export interface IEndExpectation { + type: "end"; +} +export interface IOtherExpectation { + type: "other"; + description: string; +} +export declare type Expectation = ILiteralExpectation | IClassExpectation | IAnyExpectation | IEndExpectation | IOtherExpectation; +export declare class SyntaxError extends Error { + static buildMessage(expected: Expectation[], found: string | null): string; + message: string; + expected: Expectation[]; + found: string | null; + location: IFileRange; + name: string; + constructor(message: string, expected: Expectation[], found: string | null, location: IFileRange); +} +export interface IParseOptions { + filename?: string; + startRule?: string; + tracer?: any; + [key: string]: any; +} +export declare type ParseFunction = (input: string, options?: IParseOptions) => any; +export declare const parse: ParseFunction; diff --git a/lib/Grammar/dist/Grammar.js b/lib/Grammar/dist/Grammar.js new file mode 100644 index 000000000..a260258f4 --- /dev/null +++ b/lib/Grammar/dist/Grammar.js @@ -0,0 +1,14299 @@ +"use strict"; +// tslint:disable:interface-name +// tslint:disable: trailing-comma +// tslint:disable: object-literal-sort-keys +// tslint:disable: max-line-length +// tslint:disable: only-arrow-functions +// tslint:disable: one-variable-per-declaration +// tslint:disable: no-consecutive-blank-lines +// tslint:disable: align +// tslint:disable: radix +// tslint:disable: quotemark +// tslint:disable: semicolon +// tslint:disable: object-literal-shorthand +// tslint:disable: variable-name +// tslint:disable: no-var-keyword +// tslint:disable: whitespace +// tslint:disable: curly +// tslint:disable: prefer-const +// tslint:disable: object-literal-key-quotes +// tslint:disable: no-string-literal +// tslint:disable: one-line +// tslint:disable: no-unused-expression +// tslint:disable: space-before-function-paren +// tslint:disable: arrow-return-shorthand +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +// Generated by PEG.js v. 0.10.0 (ts-pegjs plugin v. 0.2.3 ) +// +// https://pegjs.org/ https://github.com/metadevpro/ts-pegjs +var NameAddrHeader_1 = require("../../NameAddrHeader"); +var URI_1 = require("../../URI"); +var SyntaxError = /** @class */ (function (_super) { + __extends(SyntaxError, _super); + function SyntaxError(message, expected, found, location) { + var _this = _super.call(this) || this; + _this.message = message; + _this.expected = expected; + _this.found = found; + _this.location = location; + _this.name = "SyntaxError"; + if (typeof Error.captureStackTrace === "function") { + Error.captureStackTrace(_this, SyntaxError); + } + return _this; + } + SyntaxError.buildMessage = function (expected, found) { + function hex(ch) { + return ch.charCodeAt(0).toString(16).toUpperCase(); + } + function literalEscape(s) { + return s + .replace(/\\/g, "\\\\") + .replace(/"/g, "\\\"") + .replace(/\0/g, "\\0") + .replace(/\t/g, "\\t") + .replace(/\n/g, "\\n") + .replace(/\r/g, "\\r") + .replace(/[\x00-\x0F]/g, function (ch) { return "\\x0" + hex(ch); }) + .replace(/[\x10-\x1F\x7F-\x9F]/g, function (ch) { return "\\x" + hex(ch); }); + } + function classEscape(s) { + return s + .replace(/\\/g, "\\\\") + .replace(/\]/g, "\\]") + .replace(/\^/g, "\\^") + .replace(/-/g, "\\-") + .replace(/\0/g, "\\0") + .replace(/\t/g, "\\t") + .replace(/\n/g, "\\n") + .replace(/\r/g, "\\r") + .replace(/[\x00-\x0F]/g, function (ch) { return "\\x0" + hex(ch); }) + .replace(/[\x10-\x1F\x7F-\x9F]/g, function (ch) { return "\\x" + hex(ch); }); + } + function describeExpectation(expectation) { + switch (expectation.type) { + case "literal": + return "\"" + literalEscape(expectation.text) + "\""; + case "class": + var escapedParts = expectation.parts.map(function (part) { + return Array.isArray(part) + ? classEscape(part[0]) + "-" + classEscape(part[1]) + : classEscape(part); + }); + return "[" + (expectation.inverted ? "^" : "") + escapedParts + "]"; + case "any": + return "any character"; + case "end": + return "end of input"; + case "other": + return expectation.description; + } + } + function describeExpected(expected1) { + var descriptions = expected1.map(describeExpectation); + var i; + var j; + descriptions.sort(); + if (descriptions.length > 0) { + for (i = 1, j = 1; i < descriptions.length; i++) { + if (descriptions[i - 1] !== descriptions[i]) { + descriptions[j] = descriptions[i]; + j++; + } + } + descriptions.length = j; + } + switch (descriptions.length) { + case 1: + return descriptions[0]; + case 2: + return descriptions[0] + " or " + descriptions[1]; + default: + return descriptions.slice(0, -1).join(", ") + + ", or " + + descriptions[descriptions.length - 1]; + } + } + function describeFound(found1) { + return found1 ? "\"" + literalEscape(found1) + "\"" : "end of input"; + } + return "Expected " + describeExpected(expected) + " but " + describeFound(found) + " found."; + }; + return SyntaxError; +}(Error)); +exports.SyntaxError = SyntaxError; +function peg$parse(input, options) { + options = options !== undefined ? options : {}; + var peg$FAILED = {}; + var peg$startRuleFunctions = { Contact: peg$parseContact, Name_Addr_Header: peg$parseName_Addr_Header, Record_Route: peg$parseRecord_Route, Request_Response: peg$parseRequest_Response, SIP_URI: peg$parseSIP_URI, Subscription_State: peg$parseSubscription_State, Supported: peg$parseSupported, Require: peg$parseRequire, Via: peg$parseVia, absoluteURI: peg$parseabsoluteURI, Call_ID: peg$parseCall_ID, Content_Disposition: peg$parseContent_Disposition, Content_Length: peg$parseContent_Length, Content_Type: peg$parseContent_Type, CSeq: peg$parseCSeq, displayName: peg$parsedisplayName, Event: peg$parseEvent, From: peg$parseFrom, host: peg$parsehost, Max_Forwards: peg$parseMax_Forwards, Min_SE: peg$parseMin_SE, Proxy_Authenticate: peg$parseProxy_Authenticate, quoted_string: peg$parsequoted_string, Refer_To: peg$parseRefer_To, Replaces: peg$parseReplaces, Session_Expires: peg$parseSession_Expires, stun_URI: peg$parsestun_URI, To: peg$parseTo, turn_URI: peg$parseturn_URI, uuid: peg$parseuuid, WWW_Authenticate: peg$parseWWW_Authenticate, challenge: peg$parsechallenge, sipfrag: peg$parsesipfrag, Referred_By: peg$parseReferred_By }; + var peg$startRuleFunction = peg$parseContact; + var peg$c0 = "\r\n"; + var peg$c1 = peg$literalExpectation("\r\n", false); + var peg$c2 = /^[0-9]/; + var peg$c3 = peg$classExpectation([["0", "9"]], false, false); + var peg$c4 = /^[a-zA-Z]/; + var peg$c5 = peg$classExpectation([["a", "z"], ["A", "Z"]], false, false); + var peg$c6 = /^[0-9a-fA-F]/; + var peg$c7 = peg$classExpectation([["0", "9"], ["a", "f"], ["A", "F"]], false, false); + var peg$c8 = /^[\0-\xFF]/; + var peg$c9 = peg$classExpectation([["\0", "\xFF"]], false, false); + var peg$c10 = /^["]/; + var peg$c11 = peg$classExpectation(["\""], false, false); + var peg$c12 = " "; + var peg$c13 = peg$literalExpectation(" ", false); + var peg$c14 = "\t"; + var peg$c15 = peg$literalExpectation("\t", false); + var peg$c16 = /^[a-zA-Z0-9]/; + var peg$c17 = peg$classExpectation([["a", "z"], ["A", "Z"], ["0", "9"]], false, false); + var peg$c18 = ";"; + var peg$c19 = peg$literalExpectation(";", false); + var peg$c20 = "/"; + var peg$c21 = peg$literalExpectation("/", false); + var peg$c22 = "?"; + var peg$c23 = peg$literalExpectation("?", false); + var peg$c24 = ":"; + var peg$c25 = peg$literalExpectation(":", false); + var peg$c26 = "@"; + var peg$c27 = peg$literalExpectation("@", false); + var peg$c28 = "&"; + var peg$c29 = peg$literalExpectation("&", false); + var peg$c30 = "="; + var peg$c31 = peg$literalExpectation("=", false); + var peg$c32 = "+"; + var peg$c33 = peg$literalExpectation("+", false); + var peg$c34 = "$"; + var peg$c35 = peg$literalExpectation("$", false); + var peg$c36 = ","; + var peg$c37 = peg$literalExpectation(",", false); + var peg$c38 = "-"; + var peg$c39 = peg$literalExpectation("-", false); + var peg$c40 = "_"; + var peg$c41 = peg$literalExpectation("_", false); + var peg$c42 = "."; + var peg$c43 = peg$literalExpectation(".", false); + var peg$c44 = "!"; + var peg$c45 = peg$literalExpectation("!", false); + var peg$c46 = "~"; + var peg$c47 = peg$literalExpectation("~", false); + var peg$c48 = "*"; + var peg$c49 = peg$literalExpectation("*", false); + var peg$c50 = "'"; + var peg$c51 = peg$literalExpectation("'", false); + var peg$c52 = "("; + var peg$c53 = peg$literalExpectation("(", false); + var peg$c54 = ")"; + var peg$c55 = peg$literalExpectation(")", false); + var peg$c56 = "%"; + var peg$c57 = peg$literalExpectation("%", false); + var peg$c58 = function () { return " "; }; + var peg$c59 = function () { return ':'; }; + var peg$c60 = /^[!-~]/; + var peg$c61 = peg$classExpectation([["!", "~"]], false, false); + var peg$c62 = /^[\x80-\uFFFF]/; + var peg$c63 = peg$classExpectation([["\x80", "\uFFFF"]], false, false); + var peg$c64 = /^[\x80-\xBF]/; + var peg$c65 = peg$classExpectation([["\x80", "\xBF"]], false, false); + var peg$c66 = /^[a-f]/; + var peg$c67 = peg$classExpectation([["a", "f"]], false, false); + var peg$c68 = "`"; + var peg$c69 = peg$literalExpectation("`", false); + var peg$c70 = "<"; + var peg$c71 = peg$literalExpectation("<", false); + var peg$c72 = ">"; + var peg$c73 = peg$literalExpectation(">", false); + var peg$c74 = "\\"; + var peg$c75 = peg$literalExpectation("\\", false); + var peg$c76 = "["; + var peg$c77 = peg$literalExpectation("[", false); + var peg$c78 = "]"; + var peg$c79 = peg$literalExpectation("]", false); + var peg$c80 = "{"; + var peg$c81 = peg$literalExpectation("{", false); + var peg$c82 = "}"; + var peg$c83 = peg$literalExpectation("}", false); + var peg$c84 = function () { return "*"; }; + var peg$c85 = function () { return "/"; }; + var peg$c86 = function () { return "="; }; + var peg$c87 = function () { return "("; }; + var peg$c88 = function () { return ")"; }; + var peg$c89 = function () { return ">"; }; + var peg$c90 = function () { return "<"; }; + var peg$c91 = function () { return ","; }; + var peg$c92 = function () { return ";"; }; + var peg$c93 = function () { return ":"; }; + var peg$c94 = function () { return "\""; }; + var peg$c95 = /^[!-']/; + var peg$c96 = peg$classExpectation([["!", "'"]], false, false); + var peg$c97 = /^[*-[]/; + var peg$c98 = peg$classExpectation([["*", "["]], false, false); + var peg$c99 = /^[\]-~]/; + var peg$c100 = peg$classExpectation([["]", "~"]], false, false); + var peg$c101 = function (contents) { + return contents; + }; + var peg$c102 = /^[#-[]/; + var peg$c103 = peg$classExpectation([["#", "["]], false, false); + var peg$c104 = /^[\0-\t]/; + var peg$c105 = peg$classExpectation([["\0", "\t"]], false, false); + var peg$c106 = /^[\x0B-\f]/; + var peg$c107 = peg$classExpectation([["\x0B", "\f"]], false, false); + var peg$c108 = /^[\x0E-\x7F]/; + var peg$c109 = peg$classExpectation([["\x0E", "\x7F"]], false, false); + var peg$c110 = function () { + options = options || { data: {} }; + options.data.uri = new URI_1.URI(options.data.scheme, options.data.user, options.data.host, options.data.port); + delete options.data.scheme; + delete options.data.user; + delete options.data.host; + delete options.data.host_type; + delete options.data.port; + }; + var peg$c111 = function () { + options = options || { data: {} }; + options.data.uri = new URI_1.URI(options.data.scheme, options.data.user, options.data.host, options.data.port, options.data.uri_params, options.data.uri_headers); + delete options.data.scheme; + delete options.data.user; + delete options.data.host; + delete options.data.host_type; + delete options.data.port; + delete options.data.uri_params; + if (options.startRule === 'SIP_URI') { + options.data = options.data.uri; + } + }; + var peg$c112 = "sips"; + var peg$c113 = peg$literalExpectation("sips", true); + var peg$c114 = "sip"; + var peg$c115 = peg$literalExpectation("sip", true); + var peg$c116 = function (uri_scheme) { + options = options || { data: {} }; + options.data.scheme = uri_scheme; + }; + var peg$c117 = function () { + options = options || { data: {} }; + options.data.user = decodeURIComponent(text().slice(0, -1)); + }; + var peg$c118 = function () { + options = options || { data: {} }; + options.data.password = text(); + }; + var peg$c119 = function () { + options = options || { data: {} }; + options.data.host = text(); + return options.data.host; + }; + var peg$c120 = function () { + options = options || { data: {} }; + options.data.host_type = 'domain'; + return text(); + }; + var peg$c121 = /^[a-zA-Z0-9_\-]/; + var peg$c122 = peg$classExpectation([["a", "z"], ["A", "Z"], ["0", "9"], "_", "-"], false, false); + var peg$c123 = /^[a-zA-Z0-9\-]/; + var peg$c124 = peg$classExpectation([["a", "z"], ["A", "Z"], ["0", "9"], "-"], false, false); + var peg$c125 = function () { + options = options || { data: {} }; + options.data.host_type = 'IPv6'; + return text(); + }; + var peg$c126 = "::"; + var peg$c127 = peg$literalExpectation("::", false); + var peg$c128 = function () { + options = options || { data: {} }; + options.data.host_type = 'IPv6'; + return text(); + }; + var peg$c129 = function () { + options = options || { data: {} }; + options.data.host_type = 'IPv4'; + return text(); + }; + var peg$c130 = "25"; + var peg$c131 = peg$literalExpectation("25", false); + var peg$c132 = /^[0-5]/; + var peg$c133 = peg$classExpectation([["0", "5"]], false, false); + var peg$c134 = "2"; + var peg$c135 = peg$literalExpectation("2", false); + var peg$c136 = /^[0-4]/; + var peg$c137 = peg$classExpectation([["0", "4"]], false, false); + var peg$c138 = "1"; + var peg$c139 = peg$literalExpectation("1", false); + var peg$c140 = /^[1-9]/; + var peg$c141 = peg$classExpectation([["1", "9"]], false, false); + var peg$c142 = function (port) { + options = options || { data: {} }; + port = parseInt(port.join('')); + options.data.port = port; + return port; + }; + var peg$c143 = "transport="; + var peg$c144 = peg$literalExpectation("transport=", true); + var peg$c145 = "udp"; + var peg$c146 = peg$literalExpectation("udp", true); + var peg$c147 = "tcp"; + var peg$c148 = peg$literalExpectation("tcp", true); + var peg$c149 = "sctp"; + var peg$c150 = peg$literalExpectation("sctp", true); + var peg$c151 = "tls"; + var peg$c152 = peg$literalExpectation("tls", true); + var peg$c153 = function (transport) { + options = options || { data: {} }; + if (!options.data.uri_params) + options.data.uri_params = {}; + options.data.uri_params['transport'] = transport.toLowerCase(); + }; + var peg$c154 = "user="; + var peg$c155 = peg$literalExpectation("user=", true); + var peg$c156 = "phone"; + var peg$c157 = peg$literalExpectation("phone", true); + var peg$c158 = "ip"; + var peg$c159 = peg$literalExpectation("ip", true); + var peg$c160 = function (user) { + options = options || { data: {} }; + if (!options.data.uri_params) + options.data.uri_params = {}; + options.data.uri_params['user'] = user.toLowerCase(); + }; + var peg$c161 = "method="; + var peg$c162 = peg$literalExpectation("method=", true); + var peg$c163 = function (method) { + options = options || { data: {} }; + if (!options.data.uri_params) + options.data.uri_params = {}; + options.data.uri_params['method'] = method; + }; + var peg$c164 = "ttl="; + var peg$c165 = peg$literalExpectation("ttl=", true); + var peg$c166 = function (ttl) { + options = options || { data: {} }; + if (!options.data.params) + options.data.params = {}; + options.data.params['ttl'] = ttl; + }; + var peg$c167 = "maddr="; + var peg$c168 = peg$literalExpectation("maddr=", true); + var peg$c169 = function (maddr) { + options = options || { data: {} }; + if (!options.data.uri_params) + options.data.uri_params = {}; + options.data.uri_params['maddr'] = maddr; + }; + var peg$c170 = "lr"; + var peg$c171 = peg$literalExpectation("lr", true); + var peg$c172 = function () { + options = options || { data: {} }; + if (!options.data.uri_params) + options.data.uri_params = {}; + options.data.uri_params['lr'] = undefined; + }; + var peg$c173 = function (param, value) { + options = options || { data: {} }; + if (!options.data.uri_params) + options.data.uri_params = {}; + if (value === null) { + value = undefined; + } + else { + value = value[1]; + } + options.data.uri_params[param.toLowerCase()] = value; + }; + var peg$c174 = function (hname, hvalue) { + hname = hname.join('').toLowerCase(); + hvalue = hvalue.join(''); + options = options || { data: {} }; + if (!options.data.uri_headers) + options.data.uri_headers = {}; + if (!options.data.uri_headers[hname]) { + options.data.uri_headers[hname] = [hvalue]; + } + else { + options.data.uri_headers[hname].push(hvalue); + } + }; + var peg$c175 = function () { + options = options || { data: {} }; + // lots of tests fail if this isn't guarded... + if (options.startRule === 'Refer_To') { + options.data.uri = new URI_1.URI(options.data.scheme, options.data.user, options.data.host, options.data.port, options.data.uri_params, options.data.uri_headers); + delete options.data.scheme; + delete options.data.user; + delete options.data.host; + delete options.data.host_type; + delete options.data.port; + delete options.data.uri_params; + } + }; + var peg$c176 = "//"; + var peg$c177 = peg$literalExpectation("//", false); + var peg$c178 = function () { + options = options || { data: {} }; + options.data.scheme = text(); + }; + var peg$c179 = peg$literalExpectation("SIP", true); + var peg$c180 = function () { + options = options || { data: {} }; + options.data.sip_version = text(); + }; + var peg$c181 = "INVITE"; + var peg$c182 = peg$literalExpectation("INVITE", false); + var peg$c183 = "ACK"; + var peg$c184 = peg$literalExpectation("ACK", false); + var peg$c185 = "VXACH"; + var peg$c186 = peg$literalExpectation("VXACH", false); + var peg$c187 = "OPTIONS"; + var peg$c188 = peg$literalExpectation("OPTIONS", false); + var peg$c189 = "BYE"; + var peg$c190 = peg$literalExpectation("BYE", false); + var peg$c191 = "CANCEL"; + var peg$c192 = peg$literalExpectation("CANCEL", false); + var peg$c193 = "REGISTER"; + var peg$c194 = peg$literalExpectation("REGISTER", false); + var peg$c195 = "SUBSCRIBE"; + var peg$c196 = peg$literalExpectation("SUBSCRIBE", false); + var peg$c197 = "NOTIFY"; + var peg$c198 = peg$literalExpectation("NOTIFY", false); + var peg$c199 = "REFER"; + var peg$c200 = peg$literalExpectation("REFER", false); + var peg$c201 = "PUBLISH"; + var peg$c202 = peg$literalExpectation("PUBLISH", false); + var peg$c203 = function () { + options = options || { data: {} }; + options.data.method = text(); + return options.data.method; + }; + var peg$c204 = function (status_code) { + options = options || { data: {} }; + options.data.status_code = parseInt(status_code.join('')); + }; + var peg$c205 = function () { + options = options || { data: {} }; + options.data.reason_phrase = text(); + }; + var peg$c206 = function () { + options = options || { data: {} }; + options.data = text(); + }; + var peg$c207 = function () { + var idx, length; + options = options || { data: {} }; + length = options.data.multi_header.length; + for (idx = 0; idx < length; idx++) { + if (options.data.multi_header[idx].parsed === null) { + options.data = null; + break; + } + } + if (options.data !== null) { + options.data = options.data.multi_header; + } + else { + options.data = -1; + } + }; + var peg$c208 = function () { + var header; + options = options || { data: {} }; + if (!options.data.multi_header) + options.data.multi_header = []; + try { + header = new NameAddrHeader_1.NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); + delete options.data.uri; + delete options.data.displayName; + delete options.data.params; + } + catch (e) { + header = null; + } + options.data.multi_header.push({ 'position': peg$currPos, + 'offset': location().start.offset, + 'parsed': header + }); + }; + var peg$c209 = function (displayName) { + displayName = text().trim(); + if (displayName[0] === '\"') { + displayName = displayName.substring(1, displayName.length - 1); + } + options = options || { data: {} }; + options.data.displayName = displayName; + }; + var peg$c210 = "q"; + var peg$c211 = peg$literalExpectation("q", true); + var peg$c212 = function (q) { + options = options || { data: {} }; + if (!options.data.params) + options.data.params = {}; + options.data.params['q'] = q; + }; + var peg$c213 = "expires"; + var peg$c214 = peg$literalExpectation("expires", true); + var peg$c215 = function (expires) { + options = options || { data: {} }; + if (!options.data.params) + options.data.params = {}; + options.data.params['expires'] = expires; + }; + var peg$c216 = function (delta_seconds) { + return parseInt(delta_seconds.join('')); + }; + var peg$c217 = "0"; + var peg$c218 = peg$literalExpectation("0", false); + var peg$c219 = function () { + return parseFloat(text()); + }; + var peg$c220 = function (param, value) { + options = options || { data: {} }; + if (!options.data.params) + options.data.params = {}; + if (value === null) { + value = undefined; + } + else { + value = value[1]; + } + options.data.params[param.toLowerCase()] = value; + }; + var peg$c221 = "render"; + var peg$c222 = peg$literalExpectation("render", true); + var peg$c223 = "session"; + var peg$c224 = peg$literalExpectation("session", true); + var peg$c225 = "icon"; + var peg$c226 = peg$literalExpectation("icon", true); + var peg$c227 = "alert"; + var peg$c228 = peg$literalExpectation("alert", true); + var peg$c229 = function () { + options = options || { data: {} }; + if (options.startRule === 'Content_Disposition') { + options.data.type = text().toLowerCase(); + } + }; + var peg$c230 = "handling"; + var peg$c231 = peg$literalExpectation("handling", true); + var peg$c232 = "optional"; + var peg$c233 = peg$literalExpectation("optional", true); + var peg$c234 = "required"; + var peg$c235 = peg$literalExpectation("required", true); + var peg$c236 = function (length) { + options = options || { data: {} }; + options.data = parseInt(length.join('')); + }; + var peg$c237 = function () { + options = options || { data: {} }; + options.data = text(); + }; + var peg$c238 = "text"; + var peg$c239 = peg$literalExpectation("text", true); + var peg$c240 = "image"; + var peg$c241 = peg$literalExpectation("image", true); + var peg$c242 = "audio"; + var peg$c243 = peg$literalExpectation("audio", true); + var peg$c244 = "video"; + var peg$c245 = peg$literalExpectation("video", true); + var peg$c246 = "application"; + var peg$c247 = peg$literalExpectation("application", true); + var peg$c248 = "message"; + var peg$c249 = peg$literalExpectation("message", true); + var peg$c250 = "multipart"; + var peg$c251 = peg$literalExpectation("multipart", true); + var peg$c252 = "x-"; + var peg$c253 = peg$literalExpectation("x-", true); + var peg$c254 = function (cseq_value) { + options = options || { data: {} }; + options.data.value = parseInt(cseq_value.join('')); + }; + var peg$c255 = function (expires) { options = options || { data: {} }; options.data = expires; }; + var peg$c256 = function (event_type) { + options = options || { data: {} }; + options.data.event = event_type.toLowerCase(); + }; + var peg$c257 = function () { + options = options || { data: {} }; + var tag = options.data.tag; + options.data = new NameAddrHeader_1.NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); + if (tag) { + options.data.setParam('tag', tag); + } + }; + var peg$c258 = "tag"; + var peg$c259 = peg$literalExpectation("tag", true); + var peg$c260 = function (tag) { options = options || { data: {} }; options.data.tag = tag; }; + var peg$c261 = function (forwards) { + options = options || { data: {} }; + options.data = parseInt(forwards.join('')); + }; + var peg$c262 = function (min_expires) { options = options || { data: {} }; options.data = min_expires; }; + var peg$c263 = function () { + options = options || { data: {} }; + options.data = new NameAddrHeader_1.NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); + }; + var peg$c264 = "digest"; + var peg$c265 = peg$literalExpectation("Digest", true); + var peg$c266 = "realm"; + var peg$c267 = peg$literalExpectation("realm", true); + var peg$c268 = function (realm) { options = options || { data: {} }; options.data.realm = realm; }; + var peg$c269 = "domain"; + var peg$c270 = peg$literalExpectation("domain", true); + var peg$c271 = "nonce"; + var peg$c272 = peg$literalExpectation("nonce", true); + var peg$c273 = function (nonce) { options = options || { data: {} }; options.data.nonce = nonce; }; + var peg$c274 = "opaque"; + var peg$c275 = peg$literalExpectation("opaque", true); + var peg$c276 = function (opaque) { options = options || { data: {} }; options.data.opaque = opaque; }; + var peg$c277 = "stale"; + var peg$c278 = peg$literalExpectation("stale", true); + var peg$c279 = "true"; + var peg$c280 = peg$literalExpectation("true", true); + var peg$c281 = function () { options = options || { data: {} }; options.data.stale = true; }; + var peg$c282 = "false"; + var peg$c283 = peg$literalExpectation("false", true); + var peg$c284 = function () { options = options || { data: {} }; options.data.stale = false; }; + var peg$c285 = "algorithm"; + var peg$c286 = peg$literalExpectation("algorithm", true); + var peg$c287 = "md5"; + var peg$c288 = peg$literalExpectation("MD5", true); + var peg$c289 = "md5-sess"; + var peg$c290 = peg$literalExpectation("MD5-sess", true); + var peg$c291 = function (algorithm) { + options = options || { data: {} }; + options.data.algorithm = algorithm.toUpperCase(); + }; + var peg$c292 = "qop"; + var peg$c293 = peg$literalExpectation("qop", true); + var peg$c294 = "auth-int"; + var peg$c295 = peg$literalExpectation("auth-int", true); + var peg$c296 = "auth"; + var peg$c297 = peg$literalExpectation("auth", true); + var peg$c298 = function (qop_value) { + options = options || { data: {} }; + options.data.qop || (options.data.qop = []); + options.data.qop.push(qop_value.toLowerCase()); + }; + var peg$c299 = function (rack_value) { + options = options || { data: {} }; + options.data.value = parseInt(rack_value.join('')); + }; + var peg$c300 = function () { + var idx, length; + options = options || { data: {} }; + length = options.data.multi_header.length; + for (idx = 0; idx < length; idx++) { + if (options.data.multi_header[idx].parsed === null) { + options.data = null; + break; + } + } + if (options.data !== null) { + options.data = options.data.multi_header; + } + else { + options.data = -1; + } + }; + var peg$c301 = function () { + var header; + options = options || { data: {} }; + if (!options.data.multi_header) + options.data.multi_header = []; + try { + header = new NameAddrHeader_1.NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); + delete options.data.uri; + delete options.data.displayName; + delete options.data.params; + } + catch (e) { + header = null; + } + options.data.multi_header.push({ 'position': peg$currPos, + 'offset': location().start.offset, + 'parsed': header + }); + }; + var peg$c302 = function () { + options = options || { data: {} }; + options.data = new NameAddrHeader_1.NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); + }; + var peg$c303 = function () { + options = options || { data: {} }; + if (!(options.data.replaces_from_tag && options.data.replaces_to_tag)) { + options.data = -1; + } + }; + var peg$c304 = function () { + options = options || { data: {} }; + options.data = { + call_id: options.data + }; + }; + var peg$c305 = "from-tag"; + var peg$c306 = peg$literalExpectation("from-tag", true); + var peg$c307 = function (from_tag) { + options = options || { data: {} }; + options.data.replaces_from_tag = from_tag; + }; + var peg$c308 = "to-tag"; + var peg$c309 = peg$literalExpectation("to-tag", true); + var peg$c310 = function (to_tag) { + options = options || { data: {} }; + options.data.replaces_to_tag = to_tag; + }; + var peg$c311 = "early-only"; + var peg$c312 = peg$literalExpectation("early-only", true); + var peg$c313 = function () { + options = options || { data: {} }; + options.data.early_only = true; + }; + var peg$c314 = function (head, r) { return r; }; + var peg$c315 = function (head, tail) { return list(head, tail); }; + var peg$c316 = function (value) { + options = options || { data: {} }; + if (options.startRule === 'Require') { + options.data = value || []; + } + }; + var peg$c317 = function (rseq_value) { + options = options || { data: {} }; + options.data.value = parseInt(rseq_value.join('')); + }; + var peg$c318 = "active"; + var peg$c319 = peg$literalExpectation("active", true); + var peg$c320 = "pending"; + var peg$c321 = peg$literalExpectation("pending", true); + var peg$c322 = "terminated"; + var peg$c323 = peg$literalExpectation("terminated", true); + var peg$c324 = function () { + options = options || { data: {} }; + options.data.state = text(); + }; + var peg$c325 = "reason"; + var peg$c326 = peg$literalExpectation("reason", true); + var peg$c327 = function (reason) { + options = options || { data: {} }; + if (typeof reason !== 'undefined') + options.data.reason = reason; + }; + var peg$c328 = function (expires) { + options = options || { data: {} }; + if (typeof expires !== 'undefined') + options.data.expires = expires; + }; + var peg$c329 = "retry_after"; + var peg$c330 = peg$literalExpectation("retry_after", true); + var peg$c331 = function (retry_after) { + options = options || { data: {} }; + if (typeof retry_after !== 'undefined') + options.data.retry_after = retry_after; + }; + var peg$c332 = "deactivated"; + var peg$c333 = peg$literalExpectation("deactivated", true); + var peg$c334 = "probation"; + var peg$c335 = peg$literalExpectation("probation", true); + var peg$c336 = "rejected"; + var peg$c337 = peg$literalExpectation("rejected", true); + var peg$c338 = "timeout"; + var peg$c339 = peg$literalExpectation("timeout", true); + var peg$c340 = "giveup"; + var peg$c341 = peg$literalExpectation("giveup", true); + var peg$c342 = "noresource"; + var peg$c343 = peg$literalExpectation("noresource", true); + var peg$c344 = "invariant"; + var peg$c345 = peg$literalExpectation("invariant", true); + var peg$c346 = function (value) { + options = options || { data: {} }; + if (options.startRule === 'Supported') { + options.data = value || []; + } + }; + var peg$c347 = function () { + options = options || { data: {} }; + var tag = options.data.tag; + options.data = new NameAddrHeader_1.NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); + if (tag) { + options.data.setParam('tag', tag); + } + }; + var peg$c348 = "ttl"; + var peg$c349 = peg$literalExpectation("ttl", true); + var peg$c350 = function (via_ttl_value) { + options = options || { data: {} }; + options.data.ttl = via_ttl_value; + }; + var peg$c351 = "maddr"; + var peg$c352 = peg$literalExpectation("maddr", true); + var peg$c353 = function (via_maddr) { + options = options || { data: {} }; + options.data.maddr = via_maddr; + }; + var peg$c354 = "received"; + var peg$c355 = peg$literalExpectation("received", true); + var peg$c356 = function (via_received) { + options = options || { data: {} }; + options.data.received = via_received; + }; + var peg$c357 = "branch"; + var peg$c358 = peg$literalExpectation("branch", true); + var peg$c359 = function (via_branch) { + options = options || { data: {} }; + options.data.branch = via_branch; + }; + var peg$c360 = "rport"; + var peg$c361 = peg$literalExpectation("rport", true); + var peg$c362 = function (response_port) { + options = options || { data: {} }; + if (typeof response_port !== 'undefined') + options.data.rport = response_port.join(''); + }; + var peg$c363 = function (via_protocol) { + options = options || { data: {} }; + options.data.protocol = via_protocol; + }; + var peg$c364 = peg$literalExpectation("UDP", true); + var peg$c365 = peg$literalExpectation("TCP", true); + var peg$c366 = peg$literalExpectation("TLS", true); + var peg$c367 = peg$literalExpectation("SCTP", true); + var peg$c368 = function (via_transport) { + options = options || { data: {} }; + options.data.transport = via_transport; + }; + var peg$c369 = function () { + options = options || { data: {} }; + options.data.host = text(); + }; + var peg$c370 = function (via_sent_by_port) { + options = options || { data: {} }; + options.data.port = parseInt(via_sent_by_port.join('')); + }; + var peg$c371 = function (ttl) { + return parseInt(ttl.join('')); + }; + var peg$c372 = function (deltaSeconds) { + options = options || { data: {} }; + if (options.startRule === 'Session_Expires') { + options.data.deltaSeconds = deltaSeconds; + } + }; + var peg$c373 = "refresher"; + var peg$c374 = peg$literalExpectation("refresher", false); + var peg$c375 = "uas"; + var peg$c376 = peg$literalExpectation("uas", false); + var peg$c377 = "uac"; + var peg$c378 = peg$literalExpectation("uac", false); + var peg$c379 = function (endpoint) { + options = options || { data: {} }; + if (options.startRule === 'Session_Expires') { + options.data.refresher = endpoint; + } + }; + var peg$c380 = function (deltaSeconds) { + options = options || { data: {} }; + if (options.startRule === 'Min_SE') { + options.data = deltaSeconds; + } + }; + var peg$c381 = "stuns"; + var peg$c382 = peg$literalExpectation("stuns", true); + var peg$c383 = "stun"; + var peg$c384 = peg$literalExpectation("stun", true); + var peg$c385 = function (scheme) { + options = options || { data: {} }; + options.data.scheme = scheme; + }; + var peg$c386 = function (host) { + options = options || { data: {} }; + options.data.host = host; + }; + var peg$c387 = "?transport="; + var peg$c388 = peg$literalExpectation("?transport=", false); + var peg$c389 = "turns"; + var peg$c390 = peg$literalExpectation("turns", true); + var peg$c391 = "turn"; + var peg$c392 = peg$literalExpectation("turn", true); + var peg$c393 = function (transport) { + options = options || { data: {} }; + options.data.transport = transport; + }; + var peg$c394 = function () { + options = options || { data: {} }; + options.data = text(); + }; + var peg$c395 = "Referred-By"; + var peg$c396 = peg$literalExpectation("Referred-By", false); + var peg$c397 = "b"; + var peg$c398 = peg$literalExpectation("b", false); + var peg$c399 = "cid"; + var peg$c400 = peg$literalExpectation("cid", false); + var peg$currPos = 0; + var peg$savedPos = 0; + var peg$posDetailsCache = [{ line: 1, column: 1 }]; + var peg$maxFailPos = 0; + var peg$maxFailExpected = []; + var peg$silentFails = 0; + var peg$result; + if (options.startRule !== undefined) { + if (!(options.startRule in peg$startRuleFunctions)) { + throw new Error("Can't start parsing from rule \"" + options.startRule + "\"."); + } + peg$startRuleFunction = peg$startRuleFunctions[options.startRule]; + } + function text() { + return input.substring(peg$savedPos, peg$currPos); + } + function location() { + return peg$computeLocation(peg$savedPos, peg$currPos); + } + function expected(description, location1) { + location1 = location1 !== undefined + ? location1 + : peg$computeLocation(peg$savedPos, peg$currPos); + throw peg$buildStructuredError([peg$otherExpectation(description)], input.substring(peg$savedPos, peg$currPos), location1); + } + function error(message, location1) { + location1 = location1 !== undefined + ? location1 + : peg$computeLocation(peg$savedPos, peg$currPos); + throw peg$buildSimpleError(message, location1); + } + function peg$literalExpectation(text1, ignoreCase) { + return { type: "literal", text: text1, ignoreCase: ignoreCase }; + } + function peg$classExpectation(parts, inverted, ignoreCase) { + return { type: "class", parts: parts, inverted: inverted, ignoreCase: ignoreCase }; + } + function peg$anyExpectation() { + return { type: "any" }; + } + function peg$endExpectation() { + return { type: "end" }; + } + function peg$otherExpectation(description) { + return { type: "other", description: description }; + } + function peg$computePosDetails(pos) { + var details = peg$posDetailsCache[pos]; + var p; + if (details) { + return details; + } + else { + p = pos - 1; + while (!peg$posDetailsCache[p]) { + p--; + } + details = peg$posDetailsCache[p]; + details = { + line: details.line, + column: details.column + }; + while (p < pos) { + if (input.charCodeAt(p) === 10) { + details.line++; + details.column = 1; + } + else { + details.column++; + } + p++; + } + peg$posDetailsCache[pos] = details; + return details; + } + } + function peg$computeLocation(startPos, endPos) { + var startPosDetails = peg$computePosDetails(startPos); + var endPosDetails = peg$computePosDetails(endPos); + return { + start: { + offset: startPos, + line: startPosDetails.line, + column: startPosDetails.column + }, + end: { + offset: endPos, + line: endPosDetails.line, + column: endPosDetails.column + } + }; + } + function peg$fail(expected1) { + if (peg$currPos < peg$maxFailPos) { + return; + } + if (peg$currPos > peg$maxFailPos) { + peg$maxFailPos = peg$currPos; + peg$maxFailExpected = []; + } + peg$maxFailExpected.push(expected1); + } + function peg$buildSimpleError(message, location1) { + return new SyntaxError(message, [], "", location1); + } + function peg$buildStructuredError(expected1, found, location1) { + return new SyntaxError(SyntaxError.buildMessage(expected1, found), expected1, found, location1); + } + function peg$parseCRLF() { + var s0; + if (input.substr(peg$currPos, 2) === peg$c0) { + s0 = peg$c0; + peg$currPos += 2; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c1); + } + } + return s0; + } + function peg$parseDIGIT() { + var s0; + if (peg$c2.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c3); + } + } + return s0; + } + function peg$parseALPHA() { + var s0; + if (peg$c4.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c5); + } + } + return s0; + } + function peg$parseHEXDIG() { + var s0; + if (peg$c6.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c7); + } + } + return s0; + } + function peg$parseWSP() { + var s0; + s0 = peg$parseSP(); + if (s0 === peg$FAILED) { + s0 = peg$parseHTAB(); + } + return s0; + } + function peg$parseOCTET() { + var s0; + if (peg$c8.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c9); + } + } + return s0; + } + function peg$parseDQUOTE() { + var s0; + if (peg$c10.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c11); + } + } + return s0; + } + function peg$parseSP() { + var s0; + if (input.charCodeAt(peg$currPos) === 32) { + s0 = peg$c12; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c13); + } + } + return s0; + } + function peg$parseHTAB() { + var s0; + if (input.charCodeAt(peg$currPos) === 9) { + s0 = peg$c14; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c15); + } + } + return s0; + } + function peg$parsealphanum() { + var s0; + if (peg$c16.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c17); + } + } + return s0; + } + function peg$parsereserved() { + var s0; + if (input.charCodeAt(peg$currPos) === 59) { + s0 = peg$c18; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c19); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 47) { + s0 = peg$c20; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c21); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 63) { + s0 = peg$c22; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c23); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s0 = peg$c24; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 64) { + s0 = peg$c26; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c27); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 38) { + s0 = peg$c28; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c29); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s0 = peg$c30; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c31); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s0 = peg$c32; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 36) { + s0 = peg$c34; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c35); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s0 = peg$c36; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c37); + } + } + } + } + } + } + } + } + } + } + } + return s0; + } + function peg$parseunreserved() { + var s0; + s0 = peg$parsealphanum(); + if (s0 === peg$FAILED) { + s0 = peg$parsemark(); + } + return s0; + } + function peg$parsemark() { + var s0; + if (input.charCodeAt(peg$currPos) === 45) { + s0 = peg$c38; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c39); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 95) { + s0 = peg$c40; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c41); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s0 = peg$c42; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c43); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 33) { + s0 = peg$c44; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c45); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 126) { + s0 = peg$c46; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c47); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 42) { + s0 = peg$c48; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c49); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 39) { + s0 = peg$c50; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c51); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 40) { + s0 = peg$c52; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c53); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s0 = peg$c54; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c55); + } + } + } + } + } + } + } + } + } + } + return s0; + } + function peg$parseescaped() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + s1 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 37) { + s2 = peg$c56; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c57); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseHEXDIG(); + if (s3 !== peg$FAILED) { + s4 = peg$parseHEXDIG(); + if (s4 !== peg$FAILED) { + s2 = [s2, s3, s4]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s0 = input.substring(s0, peg$currPos); + } + else { + s0 = s1; + } + return s0; + } + function peg$parseLWS() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$currPos; + s2 = []; + s3 = peg$parseWSP(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseWSP(); + } + if (s2 !== peg$FAILED) { + s3 = peg$parseCRLF(); + if (s3 !== peg$FAILED) { + s2 = [s2, s3]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseWSP(); + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseWSP(); + } + } + else { + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c58(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseSWS() { + var s0; + s0 = peg$parseLWS(); + if (s0 === peg$FAILED) { + s0 = null; + } + return s0; + } + function peg$parseHCOLON() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = []; + s2 = peg$parseSP(); + if (s2 === peg$FAILED) { + s2 = peg$parseHTAB(); + } + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseSP(); + if (s2 === peg$FAILED) { + s2 = peg$parseHTAB(); + } + } + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s2 = peg$c24; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseSWS(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c59(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseTEXT_UTF8_TRIM() { + var s0, s1, s2, s3, s4, s5, s6; + s0 = peg$currPos; + s1 = peg$currPos; + s2 = []; + s3 = peg$parseTEXT_UTF8char(); + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseTEXT_UTF8char(); + } + } + else { + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$currPos; + s5 = []; + s6 = peg$parseLWS(); + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parseLWS(); + } + if (s5 !== peg$FAILED) { + s6 = peg$parseTEXT_UTF8char(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$currPos; + s5 = []; + s6 = peg$parseLWS(); + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parseLWS(); + } + if (s5 !== peg$FAILED) { + s6 = peg$parseTEXT_UTF8char(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + if (s3 !== peg$FAILED) { + s2 = [s2, s3]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s0 = input.substring(s0, peg$currPos); + } + else { + s0 = s1; + } + return s0; + } + function peg$parseTEXT_UTF8char() { + var s0; + if (peg$c60.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c61); + } + } + if (s0 === peg$FAILED) { + s0 = peg$parseUTF8_NONASCII(); + } + return s0; + } + function peg$parseUTF8_NONASCII() { + var s0; + if (peg$c62.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c63); + } + } + return s0; + } + function peg$parseUTF8_CONT() { + var s0; + if (peg$c64.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c65); + } + } + return s0; + } + function peg$parseLHEX() { + var s0; + s0 = peg$parseDIGIT(); + if (s0 === peg$FAILED) { + if (peg$c66.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c67); + } + } + } + return s0; + } + function peg$parsetoken() { + var s0, s1, s2; + s0 = peg$currPos; + s1 = []; + s2 = peg$parsealphanum(); + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s2 = peg$c38; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c39); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s2 = peg$c42; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c43); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 33) { + s2 = peg$c44; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c45); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 37) { + s2 = peg$c56; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c57); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 42) { + s2 = peg$c48; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c49); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 95) { + s2 = peg$c40; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c41); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s2 = peg$c32; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 96) { + s2 = peg$c68; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c69); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 39) { + s2 = peg$c50; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c51); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 126) { + s2 = peg$c46; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c47); + } + } + } + } + } + } + } + } + } + } + } + } + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parsealphanum(); + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s2 = peg$c38; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c39); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s2 = peg$c42; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c43); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 33) { + s2 = peg$c44; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c45); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 37) { + s2 = peg$c56; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c57); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 42) { + s2 = peg$c48; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c49); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 95) { + s2 = peg$c40; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c41); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s2 = peg$c32; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 96) { + s2 = peg$c68; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c69); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 39) { + s2 = peg$c50; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c51); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 126) { + s2 = peg$c46; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c47); + } + } + } + } + } + } + } + } + } + } + } + } + } + } + else { + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s0 = input.substring(s0, peg$currPos); + } + else { + s0 = s1; + } + return s0; + } + function peg$parsetoken_nodot() { + var s0, s1, s2; + s0 = peg$currPos; + s1 = []; + s2 = peg$parsealphanum(); + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s2 = peg$c38; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c39); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 33) { + s2 = peg$c44; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c45); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 37) { + s2 = peg$c56; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c57); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 42) { + s2 = peg$c48; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c49); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 95) { + s2 = peg$c40; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c41); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s2 = peg$c32; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 96) { + s2 = peg$c68; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c69); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 39) { + s2 = peg$c50; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c51); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 126) { + s2 = peg$c46; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c47); + } + } + } + } + } + } + } + } + } + } + } + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parsealphanum(); + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s2 = peg$c38; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c39); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 33) { + s2 = peg$c44; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c45); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 37) { + s2 = peg$c56; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c57); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 42) { + s2 = peg$c48; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c49); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 95) { + s2 = peg$c40; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c41); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s2 = peg$c32; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 96) { + s2 = peg$c68; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c69); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 39) { + s2 = peg$c50; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c51); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 126) { + s2 = peg$c46; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c47); + } + } + } + } + } + } + } + } + } + } + } + } + } + else { + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s0 = input.substring(s0, peg$currPos); + } + else { + s0 = s1; + } + return s0; + } + function peg$parseseparators() { + var s0; + if (input.charCodeAt(peg$currPos) === 40) { + s0 = peg$c52; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c53); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s0 = peg$c54; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c55); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 60) { + s0 = peg$c70; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c71); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 62) { + s0 = peg$c72; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c73); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 64) { + s0 = peg$c26; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c27); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s0 = peg$c36; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c37); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 59) { + s0 = peg$c18; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c19); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s0 = peg$c24; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 92) { + s0 = peg$c74; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c75); + } + } + if (s0 === peg$FAILED) { + s0 = peg$parseDQUOTE(); + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 47) { + s0 = peg$c20; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c21); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 91) { + s0 = peg$c76; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c77); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s0 = peg$c78; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c79); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 63) { + s0 = peg$c22; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c23); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s0 = peg$c30; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c31); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 123) { + s0 = peg$c80; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c81); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 125) { + s0 = peg$c82; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c83); + } + } + if (s0 === peg$FAILED) { + s0 = peg$parseSP(); + if (s0 === peg$FAILED) { + s0 = peg$parseHTAB(); + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + return s0; + } + function peg$parseword() { + var s0, s1, s2; + s0 = peg$currPos; + s1 = []; + s2 = peg$parsealphanum(); + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s2 = peg$c38; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c39); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s2 = peg$c42; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c43); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 33) { + s2 = peg$c44; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c45); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 37) { + s2 = peg$c56; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c57); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 42) { + s2 = peg$c48; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c49); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 95) { + s2 = peg$c40; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c41); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s2 = peg$c32; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 96) { + s2 = peg$c68; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c69); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 39) { + s2 = peg$c50; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c51); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 126) { + s2 = peg$c46; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c47); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 40) { + s2 = peg$c52; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c53); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s2 = peg$c54; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c55); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 60) { + s2 = peg$c70; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c71); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 62) { + s2 = peg$c72; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c73); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s2 = peg$c24; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 92) { + s2 = peg$c74; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c75); + } + } + if (s2 === peg$FAILED) { + s2 = peg$parseDQUOTE(); + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 47) { + s2 = peg$c20; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c21); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 91) { + s2 = peg$c76; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c77); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s2 = peg$c78; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c79); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 63) { + s2 = peg$c22; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c23); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 123) { + s2 = peg$c80; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c81); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 125) { + s2 = peg$c82; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c83); + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parsealphanum(); + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s2 = peg$c38; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c39); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s2 = peg$c42; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c43); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 33) { + s2 = peg$c44; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c45); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 37) { + s2 = peg$c56; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c57); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 42) { + s2 = peg$c48; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c49); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 95) { + s2 = peg$c40; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c41); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s2 = peg$c32; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 96) { + s2 = peg$c68; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c69); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 39) { + s2 = peg$c50; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c51); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 126) { + s2 = peg$c46; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c47); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 40) { + s2 = peg$c52; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c53); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s2 = peg$c54; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c55); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 60) { + s2 = peg$c70; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c71); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 62) { + s2 = peg$c72; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c73); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s2 = peg$c24; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 92) { + s2 = peg$c74; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c75); + } + } + if (s2 === peg$FAILED) { + s2 = peg$parseDQUOTE(); + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 47) { + s2 = peg$c20; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c21); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 91) { + s2 = peg$c76; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c77); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s2 = peg$c78; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c79); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 63) { + s2 = peg$c22; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c23); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 123) { + s2 = peg$c80; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c81); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 125) { + s2 = peg$c82; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c83); + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + else { + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s0 = input.substring(s0, peg$currPos); + } + else { + s0 = s1; + } + return s0; + } + function peg$parseSTAR() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parseSWS(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 42) { + s2 = peg$c48; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c49); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseSWS(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c84(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseSLASH() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parseSWS(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 47) { + s2 = peg$c20; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c21); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseSWS(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c85(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseEQUAL() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parseSWS(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s2 = peg$c30; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c31); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseSWS(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c86(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseLPAREN() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parseSWS(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 40) { + s2 = peg$c52; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c53); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseSWS(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c87(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseRPAREN() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parseSWS(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s2 = peg$c54; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c55); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseSWS(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c88(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseRAQUOT() { + var s0, s1, s2; + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 62) { + s1 = peg$c72; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c73); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseSWS(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c89(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseLAQUOT() { + var s0, s1, s2; + s0 = peg$currPos; + s1 = peg$parseSWS(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 60) { + s2 = peg$c70; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c71); + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c90(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseCOMMA() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parseSWS(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s2 = peg$c36; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c37); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseSWS(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c91(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseSEMI() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parseSWS(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 59) { + s2 = peg$c18; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c19); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseSWS(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c92(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseCOLON() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parseSWS(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s2 = peg$c24; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseSWS(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c93(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseLDQUOT() { + var s0, s1, s2; + s0 = peg$currPos; + s1 = peg$parseSWS(); + if (s1 !== peg$FAILED) { + s2 = peg$parseDQUOTE(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c94(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseRDQUOT() { + var s0, s1, s2; + s0 = peg$currPos; + s1 = peg$parseDQUOTE(); + if (s1 !== peg$FAILED) { + s2 = peg$parseSWS(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c94(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsecomment() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parseLPAREN(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parsectext(); + if (s3 === peg$FAILED) { + s3 = peg$parsequoted_pair(); + if (s3 === peg$FAILED) { + s3 = peg$parsecomment(); + } + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parsectext(); + if (s3 === peg$FAILED) { + s3 = peg$parsequoted_pair(); + if (s3 === peg$FAILED) { + s3 = peg$parsecomment(); + } + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseRPAREN(); + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsectext() { + var s0; + if (peg$c95.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c96); + } + } + if (s0 === peg$FAILED) { + if (peg$c97.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c98); + } + } + if (s0 === peg$FAILED) { + if (peg$c99.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c100); + } + } + if (s0 === peg$FAILED) { + s0 = peg$parseUTF8_NONASCII(); + if (s0 === peg$FAILED) { + s0 = peg$parseLWS(); + } + } + } + } + return s0; + } + function peg$parsequoted_string() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$currPos; + s2 = peg$parseSWS(); + if (s2 !== peg$FAILED) { + s3 = peg$parseDQUOTE(); + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$parseqdtext(); + if (s5 === peg$FAILED) { + s5 = peg$parsequoted_pair(); + } + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$parseqdtext(); + if (s5 === peg$FAILED) { + s5 = peg$parsequoted_pair(); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseDQUOTE(); + if (s5 !== peg$FAILED) { + s2 = [s2, s3, s4, s5]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s0 = input.substring(s0, peg$currPos); + } + else { + s0 = s1; + } + return s0; + } + function peg$parsequoted_string_clean() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parseSWS(); + if (s1 !== peg$FAILED) { + s2 = peg$parseDQUOTE(); + if (s2 !== peg$FAILED) { + s3 = peg$currPos; + s4 = []; + s5 = peg$parseqdtext(); + if (s5 === peg$FAILED) { + s5 = peg$parsequoted_pair(); + } + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$parseqdtext(); + if (s5 === peg$FAILED) { + s5 = peg$parsequoted_pair(); + } + } + if (s4 !== peg$FAILED) { + s3 = input.substring(s3, peg$currPos); + } + else { + s3 = s4; + } + if (s3 !== peg$FAILED) { + s4 = peg$parseDQUOTE(); + if (s4 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c101(s3); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseqdtext() { + var s0; + s0 = peg$parseLWS(); + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 33) { + s0 = peg$c44; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c45); + } + } + if (s0 === peg$FAILED) { + if (peg$c102.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c103); + } + } + if (s0 === peg$FAILED) { + if (peg$c99.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c100); + } + } + if (s0 === peg$FAILED) { + s0 = peg$parseUTF8_NONASCII(); + } + } + } + } + return s0; + } + function peg$parsequoted_pair() { + var s0, s1, s2; + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 92) { + s1 = peg$c74; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c75); + } + } + if (s1 !== peg$FAILED) { + if (peg$c104.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c105); + } + } + if (s2 === peg$FAILED) { + if (peg$c106.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c107); + } + } + if (s2 === peg$FAILED) { + if (peg$c108.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c109); + } + } + } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseSIP_URI_noparams() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + s1 = peg$parseuri_scheme(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s2 = peg$c24; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseuserinfo(); + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + s4 = peg$parsehostport(); + if (s4 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c110(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseSIP_URI() { + var s0, s1, s2, s3, s4, s5, s6; + s0 = peg$currPos; + s1 = peg$parseuri_scheme(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s2 = peg$c24; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseuserinfo(); + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + s4 = peg$parsehostport(); + if (s4 !== peg$FAILED) { + s5 = peg$parseuri_parameters(); + if (s5 !== peg$FAILED) { + s6 = peg$parseheaders(); + if (s6 === peg$FAILED) { + s6 = null; + } + if (s6 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c111(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseuri_scheme() { + var s0, s1; + s0 = peg$currPos; + if (input.substr(peg$currPos, 4).toLowerCase() === peg$c112) { + s1 = input.substr(peg$currPos, 4); + peg$currPos += 4; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c113); + } + } + if (s1 === peg$FAILED) { + if (input.substr(peg$currPos, 3).toLowerCase() === peg$c114) { + s1 = input.substr(peg$currPos, 3); + peg$currPos += 3; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c115); + } + } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c116(s1); + } + s0 = s1; + return s0; + } + function peg$parseuserinfo() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + s1 = peg$parseuser(); + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s3 = peg$c24; + peg$currPos++; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s3 !== peg$FAILED) { + s4 = peg$parsepassword(); + if (s4 !== peg$FAILED) { + s3 = [s3, s4]; + s2 = s3; + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 64) { + s3 = peg$c26; + peg$currPos++; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c27); + } + } + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c117(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseuser() { + var s0, s1; + s0 = []; + s1 = peg$parseunreserved(); + if (s1 === peg$FAILED) { + s1 = peg$parseescaped(); + if (s1 === peg$FAILED) { + s1 = peg$parseuser_unreserved(); + } + } + if (s1 !== peg$FAILED) { + while (s1 !== peg$FAILED) { + s0.push(s1); + s1 = peg$parseunreserved(); + if (s1 === peg$FAILED) { + s1 = peg$parseescaped(); + if (s1 === peg$FAILED) { + s1 = peg$parseuser_unreserved(); + } + } + } + } + else { + s0 = peg$FAILED; + } + return s0; + } + function peg$parseuser_unreserved() { + var s0; + if (input.charCodeAt(peg$currPos) === 38) { + s0 = peg$c28; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c29); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s0 = peg$c30; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c31); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s0 = peg$c32; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 36) { + s0 = peg$c34; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c35); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s0 = peg$c36; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c37); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 59) { + s0 = peg$c18; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c19); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 63) { + s0 = peg$c22; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c23); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 47) { + s0 = peg$c20; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c21); + } + } + } + } + } + } + } + } + } + return s0; + } + function peg$parsepassword() { + var s0, s1, s2; + s0 = peg$currPos; + s1 = []; + s2 = peg$parseunreserved(); + if (s2 === peg$FAILED) { + s2 = peg$parseescaped(); + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 38) { + s2 = peg$c28; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c29); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s2 = peg$c30; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c31); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s2 = peg$c32; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 36) { + s2 = peg$c34; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c35); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s2 = peg$c36; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c37); + } + } + } + } + } + } + } + } + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseunreserved(); + if (s2 === peg$FAILED) { + s2 = peg$parseescaped(); + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 38) { + s2 = peg$c28; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c29); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s2 = peg$c30; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c31); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s2 = peg$c32; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 36) { + s2 = peg$c34; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c35); + } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s2 = peg$c36; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c37); + } + } + } + } + } + } + } + } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c118(); + } + s0 = s1; + return s0; + } + function peg$parsehostport() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + s1 = peg$parsehost(); + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s3 = peg$c24; + peg$currPos++; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s3 !== peg$FAILED) { + s4 = peg$parseport(); + if (s4 !== peg$FAILED) { + s3 = [s3, s4]; + s2 = s3; + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsehost() { + var s0, s1; + s0 = peg$currPos; + s1 = peg$parsehostname(); + if (s1 === peg$FAILED) { + s1 = peg$parseIPv4address(); + if (s1 === peg$FAILED) { + s1 = peg$parseIPv6reference(); + } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c119(); + } + s0 = s1; + return s0; + } + function peg$parsehostname() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + s1 = []; + s2 = peg$currPos; + s3 = peg$parsedomainlabel(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c42; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c43); + } + } + if (s4 !== peg$FAILED) { + s3 = [s3, s4]; + s2 = s3; + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$currPos; + s3 = peg$parsedomainlabel(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c42; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c43); + } + } + if (s4 !== peg$FAILED) { + s3 = [s3, s4]; + s2 = s3; + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parsetoplabel(); + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s3 = peg$c42; + peg$currPos++; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c43); + } + } + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c120(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsedomainlabel() { + var s0, s1; + s0 = []; + if (peg$c121.test(input.charAt(peg$currPos))) { + s1 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c122); + } + } + if (s1 !== peg$FAILED) { + while (s1 !== peg$FAILED) { + s0.push(s1); + if (peg$c121.test(input.charAt(peg$currPos))) { + s1 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c122); + } + } + } + } + else { + s0 = peg$FAILED; + } + return s0; + } + function peg$parsetoplabel() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (peg$c4.test(input.charAt(peg$currPos))) { + s1 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c5); + } + } + if (s1 !== peg$FAILED) { + s2 = []; + if (peg$c123.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c124); + } + } + while (s3 !== peg$FAILED) { + s2.push(s3); + if (peg$c123.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c124); + } + } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseIPv6reference() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c76; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c77); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseIPv6address(); + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s3 = peg$c78; + peg$currPos++; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c79); + } + } + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c125(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseIPv6address() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14; + s0 = peg$currPos; + s1 = peg$currPos; + s2 = peg$parseh16(); + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s3 = peg$c24; + peg$currPos++; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s3 !== peg$FAILED) { + s4 = peg$parseh16(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s5 = peg$c24; + peg$currPos++; + } + else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parseh16(); + if (s6 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s7 = peg$c24; + peg$currPos++; + } + else { + s7 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s7 !== peg$FAILED) { + s8 = peg$parseh16(); + if (s8 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s9 = peg$c24; + peg$currPos++; + } + else { + s9 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s9 !== peg$FAILED) { + s10 = peg$parseh16(); + if (s10 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s11 = peg$c24; + peg$currPos++; + } + else { + s11 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s11 !== peg$FAILED) { + s12 = peg$parseh16(); + if (s12 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s13 = peg$c24; + peg$currPos++; + } + else { + s13 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s13 !== peg$FAILED) { + s14 = peg$parsels32(); + if (s14 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c126) { + s2 = peg$c126; + peg$currPos += 2; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c127); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseh16(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s4 = peg$c24; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseh16(); + if (s5 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s6 = peg$c24; + peg$currPos++; + } + else { + s6 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s6 !== peg$FAILED) { + s7 = peg$parseh16(); + if (s7 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s8 = peg$c24; + peg$currPos++; + } + else { + s8 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s8 !== peg$FAILED) { + s9 = peg$parseh16(); + if (s9 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s10 = peg$c24; + peg$currPos++; + } + else { + s10 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s10 !== peg$FAILED) { + s11 = peg$parseh16(); + if (s11 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s12 = peg$c24; + peg$currPos++; + } + else { + s12 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s12 !== peg$FAILED) { + s13 = peg$parsels32(); + if (s13 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c126) { + s2 = peg$c126; + peg$currPos += 2; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c127); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseh16(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s4 = peg$c24; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseh16(); + if (s5 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s6 = peg$c24; + peg$currPos++; + } + else { + s6 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s6 !== peg$FAILED) { + s7 = peg$parseh16(); + if (s7 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s8 = peg$c24; + peg$currPos++; + } + else { + s8 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s8 !== peg$FAILED) { + s9 = peg$parseh16(); + if (s9 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s10 = peg$c24; + peg$currPos++; + } + else { + s10 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s10 !== peg$FAILED) { + s11 = peg$parsels32(); + if (s11 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6, s7, s8, s9, s10, s11]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c126) { + s2 = peg$c126; + peg$currPos += 2; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c127); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseh16(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s4 = peg$c24; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseh16(); + if (s5 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s6 = peg$c24; + peg$currPos++; + } + else { + s6 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s6 !== peg$FAILED) { + s7 = peg$parseh16(); + if (s7 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s8 = peg$c24; + peg$currPos++; + } + else { + s8 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s8 !== peg$FAILED) { + s9 = peg$parsels32(); + if (s9 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6, s7, s8, s9]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c126) { + s2 = peg$c126; + peg$currPos += 2; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c127); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseh16(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s4 = peg$c24; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseh16(); + if (s5 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s6 = peg$c24; + peg$currPos++; + } + else { + s6 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s6 !== peg$FAILED) { + s7 = peg$parsels32(); + if (s7 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6, s7]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c126) { + s2 = peg$c126; + peg$currPos += 2; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c127); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseh16(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s4 = peg$c24; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parsels32(); + if (s5 !== peg$FAILED) { + s2 = [s2, s3, s4, s5]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c126) { + s2 = peg$c126; + peg$currPos += 2; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c127); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parsels32(); + if (s3 !== peg$FAILED) { + s2 = [s2, s3]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c126) { + s2 = peg$c126; + peg$currPos += 2; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c127); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseh16(); + if (s3 !== peg$FAILED) { + s2 = [s2, s3]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = peg$currPos; + s2 = peg$parseh16(); + if (s2 !== peg$FAILED) { + if (input.substr(peg$currPos, 2) === peg$c126) { + s3 = peg$c126; + peg$currPos += 2; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c127); + } + } + if (s3 !== peg$FAILED) { + s4 = peg$parseh16(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s5 = peg$c24; + peg$currPos++; + } + else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parseh16(); + if (s6 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s7 = peg$c24; + peg$currPos++; + } + else { + s7 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s7 !== peg$FAILED) { + s8 = peg$parseh16(); + if (s8 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s9 = peg$c24; + peg$currPos++; + } + else { + s9 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s9 !== peg$FAILED) { + s10 = peg$parseh16(); + if (s10 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s11 = peg$c24; + peg$currPos++; + } + else { + s11 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s11 !== peg$FAILED) { + s12 = peg$parsels32(); + if (s12 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = peg$currPos; + s2 = peg$parseh16(); + if (s2 !== peg$FAILED) { + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s4 = peg$c24; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseh16(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + if (input.substr(peg$currPos, 2) === peg$c126) { + s4 = peg$c126; + peg$currPos += 2; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c127); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseh16(); + if (s5 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s6 = peg$c24; + peg$currPos++; + } + else { + s6 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s6 !== peg$FAILED) { + s7 = peg$parseh16(); + if (s7 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s8 = peg$c24; + peg$currPos++; + } + else { + s8 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s8 !== peg$FAILED) { + s9 = peg$parseh16(); + if (s9 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s10 = peg$c24; + peg$currPos++; + } + else { + s10 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s10 !== peg$FAILED) { + s11 = peg$parsels32(); + if (s11 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6, s7, s8, s9, s10, s11]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = peg$currPos; + s2 = peg$parseh16(); + if (s2 !== peg$FAILED) { + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s4 = peg$c24; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseh16(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + s4 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s5 = peg$c24; + peg$currPos++; + } + else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parseh16(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + if (input.substr(peg$currPos, 2) === peg$c126) { + s5 = peg$c126; + peg$currPos += 2; + } + else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c127); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parseh16(); + if (s6 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s7 = peg$c24; + peg$currPos++; + } + else { + s7 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s7 !== peg$FAILED) { + s8 = peg$parseh16(); + if (s8 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s9 = peg$c24; + peg$currPos++; + } + else { + s9 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s9 !== peg$FAILED) { + s10 = peg$parsels32(); + if (s10 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6, s7, s8, s9, s10]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = peg$currPos; + s2 = peg$parseh16(); + if (s2 !== peg$FAILED) { + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s4 = peg$c24; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseh16(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + s4 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s5 = peg$c24; + peg$currPos++; + } + else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parseh16(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s5 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s6 = peg$c24; + peg$currPos++; + } + else { + s6 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s6 !== peg$FAILED) { + s7 = peg$parseh16(); + if (s7 !== peg$FAILED) { + s6 = [s6, s7]; + s5 = s6; + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + if (s5 === peg$FAILED) { + s5 = null; + } + if (s5 !== peg$FAILED) { + if (input.substr(peg$currPos, 2) === peg$c126) { + s6 = peg$c126; + peg$currPos += 2; + } + else { + s6 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c127); + } + } + if (s6 !== peg$FAILED) { + s7 = peg$parseh16(); + if (s7 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s8 = peg$c24; + peg$currPos++; + } + else { + s8 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s8 !== peg$FAILED) { + s9 = peg$parsels32(); + if (s9 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6, s7, s8, s9]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = peg$currPos; + s2 = peg$parseh16(); + if (s2 !== peg$FAILED) { + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s4 = peg$c24; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseh16(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + s4 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s5 = peg$c24; + peg$currPos++; + } + else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parseh16(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s5 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s6 = peg$c24; + peg$currPos++; + } + else { + s6 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s6 !== peg$FAILED) { + s7 = peg$parseh16(); + if (s7 !== peg$FAILED) { + s6 = [s6, s7]; + s5 = s6; + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + if (s5 === peg$FAILED) { + s5 = null; + } + if (s5 !== peg$FAILED) { + s6 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s7 = peg$c24; + peg$currPos++; + } + else { + s7 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s7 !== peg$FAILED) { + s8 = peg$parseh16(); + if (s8 !== peg$FAILED) { + s7 = [s7, s8]; + s6 = s7; + } + else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } + else { + peg$currPos = s6; + s6 = peg$FAILED; + } + if (s6 === peg$FAILED) { + s6 = null; + } + if (s6 !== peg$FAILED) { + if (input.substr(peg$currPos, 2) === peg$c126) { + s7 = peg$c126; + peg$currPos += 2; + } + else { + s7 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c127); + } + } + if (s7 !== peg$FAILED) { + s8 = peg$parsels32(); + if (s8 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6, s7, s8]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = peg$currPos; + s2 = peg$parseh16(); + if (s2 !== peg$FAILED) { + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s4 = peg$c24; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseh16(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + s4 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s5 = peg$c24; + peg$currPos++; + } + else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parseh16(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s5 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s6 = peg$c24; + peg$currPos++; + } + else { + s6 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s6 !== peg$FAILED) { + s7 = peg$parseh16(); + if (s7 !== peg$FAILED) { + s6 = [s6, s7]; + s5 = s6; + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + if (s5 === peg$FAILED) { + s5 = null; + } + if (s5 !== peg$FAILED) { + s6 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s7 = peg$c24; + peg$currPos++; + } + else { + s7 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s7 !== peg$FAILED) { + s8 = peg$parseh16(); + if (s8 !== peg$FAILED) { + s7 = [s7, s8]; + s6 = s7; + } + else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } + else { + peg$currPos = s6; + s6 = peg$FAILED; + } + if (s6 === peg$FAILED) { + s6 = null; + } + if (s6 !== peg$FAILED) { + s7 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s8 = peg$c24; + peg$currPos++; + } + else { + s8 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s8 !== peg$FAILED) { + s9 = peg$parseh16(); + if (s9 !== peg$FAILED) { + s8 = [s8, s9]; + s7 = s8; + } + else { + peg$currPos = s7; + s7 = peg$FAILED; + } + } + else { + peg$currPos = s7; + s7 = peg$FAILED; + } + if (s7 === peg$FAILED) { + s7 = null; + } + if (s7 !== peg$FAILED) { + if (input.substr(peg$currPos, 2) === peg$c126) { + s8 = peg$c126; + peg$currPos += 2; + } + else { + s8 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c127); + } + } + if (s8 !== peg$FAILED) { + s9 = peg$parseh16(); + if (s9 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6, s7, s8, s9]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = peg$currPos; + s2 = peg$parseh16(); + if (s2 !== peg$FAILED) { + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s4 = peg$c24; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseh16(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + s4 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s5 = peg$c24; + peg$currPos++; + } + else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parseh16(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s5 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s6 = peg$c24; + peg$currPos++; + } + else { + s6 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s6 !== peg$FAILED) { + s7 = peg$parseh16(); + if (s7 !== peg$FAILED) { + s6 = [s6, s7]; + s5 = s6; + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + if (s5 === peg$FAILED) { + s5 = null; + } + if (s5 !== peg$FAILED) { + s6 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s7 = peg$c24; + peg$currPos++; + } + else { + s7 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s7 !== peg$FAILED) { + s8 = peg$parseh16(); + if (s8 !== peg$FAILED) { + s7 = [s7, s8]; + s6 = s7; + } + else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } + else { + peg$currPos = s6; + s6 = peg$FAILED; + } + if (s6 === peg$FAILED) { + s6 = null; + } + if (s6 !== peg$FAILED) { + s7 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s8 = peg$c24; + peg$currPos++; + } + else { + s8 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s8 !== peg$FAILED) { + s9 = peg$parseh16(); + if (s9 !== peg$FAILED) { + s8 = [s8, s9]; + s7 = s8; + } + else { + peg$currPos = s7; + s7 = peg$FAILED; + } + } + else { + peg$currPos = s7; + s7 = peg$FAILED; + } + if (s7 === peg$FAILED) { + s7 = null; + } + if (s7 !== peg$FAILED) { + s8 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s9 = peg$c24; + peg$currPos++; + } + else { + s9 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s9 !== peg$FAILED) { + s10 = peg$parseh16(); + if (s10 !== peg$FAILED) { + s9 = [s9, s10]; + s8 = s9; + } + else { + peg$currPos = s8; + s8 = peg$FAILED; + } + } + else { + peg$currPos = s8; + s8 = peg$FAILED; + } + if (s8 === peg$FAILED) { + s8 = null; + } + if (s8 !== peg$FAILED) { + if (input.substr(peg$currPos, 2) === peg$c126) { + s9 = peg$c126; + peg$currPos += 2; + } + else { + s9 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c127); + } + } + if (s9 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6, s7, s8, s9]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c128(); + } + s0 = s1; + return s0; + } + function peg$parseh16() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + s1 = peg$parseHEXDIG(); + if (s1 !== peg$FAILED) { + s2 = peg$parseHEXDIG(); + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + s3 = peg$parseHEXDIG(); + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + s4 = peg$parseHEXDIG(); + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s1 = [s1, s2, s3, s4]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsels32() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parseh16(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s2 = peg$c24; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseh16(); + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$parseIPv4address(); + } + return s0; + } + function peg$parseIPv4address() { + var s0, s1, s2, s3, s4, s5, s6, s7; + s0 = peg$currPos; + s1 = peg$parsedec_octet(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s2 = peg$c42; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c43); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parsedec_octet(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c42; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c43); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parsedec_octet(); + if (s5 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s6 = peg$c42; + peg$currPos++; + } + else { + s6 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c43); + } + } + if (s6 !== peg$FAILED) { + s7 = peg$parsedec_octet(); + if (s7 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c129(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsedec_octet() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c130) { + s1 = peg$c130; + peg$currPos += 2; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c131); + } + } + if (s1 !== peg$FAILED) { + if (peg$c132.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c133); + } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 50) { + s1 = peg$c134; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c135); + } + } + if (s1 !== peg$FAILED) { + if (peg$c136.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c137); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseDIGIT(); + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 49) { + s1 = peg$c138; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c139); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseDIGIT(); + if (s2 !== peg$FAILED) { + s3 = peg$parseDIGIT(); + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (peg$c140.test(input.charAt(peg$currPos))) { + s1 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c141); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseDIGIT(); + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$parseDIGIT(); + } + } + } + } + return s0; + } + function peg$parseport() { + var s0, s1, s2, s3, s4, s5, s6; + s0 = peg$currPos; + s1 = peg$currPos; + s2 = peg$parseDIGIT(); + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + s3 = peg$parseDIGIT(); + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + s4 = peg$parseDIGIT(); + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s5 = peg$parseDIGIT(); + if (s5 === peg$FAILED) { + s5 = null; + } + if (s5 !== peg$FAILED) { + s6 = peg$parseDIGIT(); + if (s6 === peg$FAILED) { + s6 = null; + } + if (s6 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c142(s1); + } + s0 = s1; + return s0; + } + function peg$parseuri_parameters() { + var s0, s1, s2, s3; + s0 = []; + s1 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 59) { + s2 = peg$c18; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c19); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseuri_parameter(); + if (s3 !== peg$FAILED) { + s2 = [s2, s3]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + while (s1 !== peg$FAILED) { + s0.push(s1); + s1 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 59) { + s2 = peg$c18; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c19); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseuri_parameter(); + if (s3 !== peg$FAILED) { + s2 = [s2, s3]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + return s0; + } + function peg$parseuri_parameter() { + var s0; + s0 = peg$parsetransport_param(); + if (s0 === peg$FAILED) { + s0 = peg$parseuser_param(); + if (s0 === peg$FAILED) { + s0 = peg$parsemethod_param(); + if (s0 === peg$FAILED) { + s0 = peg$parsettl_param(); + if (s0 === peg$FAILED) { + s0 = peg$parsemaddr_param(); + if (s0 === peg$FAILED) { + s0 = peg$parselr_param(); + if (s0 === peg$FAILED) { + s0 = peg$parseother_param(); + } + } + } + } + } + } + return s0; + } + function peg$parsetransport_param() { + var s0, s1, s2; + s0 = peg$currPos; + if (input.substr(peg$currPos, 10).toLowerCase() === peg$c143) { + s1 = input.substr(peg$currPos, 10); + peg$currPos += 10; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c144); + } + } + if (s1 !== peg$FAILED) { + if (input.substr(peg$currPos, 3).toLowerCase() === peg$c145) { + s2 = input.substr(peg$currPos, 3); + peg$currPos += 3; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c146); + } + } + if (s2 === peg$FAILED) { + if (input.substr(peg$currPos, 3).toLowerCase() === peg$c147) { + s2 = input.substr(peg$currPos, 3); + peg$currPos += 3; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c148); + } + } + if (s2 === peg$FAILED) { + if (input.substr(peg$currPos, 4).toLowerCase() === peg$c149) { + s2 = input.substr(peg$currPos, 4); + peg$currPos += 4; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c150); + } + } + if (s2 === peg$FAILED) { + if (input.substr(peg$currPos, 3).toLowerCase() === peg$c151) { + s2 = input.substr(peg$currPos, 3); + peg$currPos += 3; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c152); + } + } + if (s2 === peg$FAILED) { + s2 = peg$parsetoken(); + } + } + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c153(s2); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseuser_param() { + var s0, s1, s2; + s0 = peg$currPos; + if (input.substr(peg$currPos, 5).toLowerCase() === peg$c154) { + s1 = input.substr(peg$currPos, 5); + peg$currPos += 5; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c155); + } + } + if (s1 !== peg$FAILED) { + if (input.substr(peg$currPos, 5).toLowerCase() === peg$c156) { + s2 = input.substr(peg$currPos, 5); + peg$currPos += 5; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c157); + } + } + if (s2 === peg$FAILED) { + if (input.substr(peg$currPos, 2).toLowerCase() === peg$c158) { + s2 = input.substr(peg$currPos, 2); + peg$currPos += 2; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c159); + } + } + if (s2 === peg$FAILED) { + s2 = peg$parsetoken(); + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c160(s2); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsemethod_param() { + var s0, s1, s2; + s0 = peg$currPos; + if (input.substr(peg$currPos, 7).toLowerCase() === peg$c161) { + s1 = input.substr(peg$currPos, 7); + peg$currPos += 7; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c162); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseMethod(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c163(s2); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsettl_param() { + var s0, s1, s2; + s0 = peg$currPos; + if (input.substr(peg$currPos, 4).toLowerCase() === peg$c164) { + s1 = input.substr(peg$currPos, 4); + peg$currPos += 4; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c165); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parsettl(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c166(s2); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsemaddr_param() { + var s0, s1, s2; + s0 = peg$currPos; + if (input.substr(peg$currPos, 6).toLowerCase() === peg$c167) { + s1 = input.substr(peg$currPos, 6); + peg$currPos += 6; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c168); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parsehost(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c169(s2); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parselr_param() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + if (input.substr(peg$currPos, 2).toLowerCase() === peg$c170) { + s1 = input.substr(peg$currPos, 2); + peg$currPos += 2; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c171); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 61) { + s3 = peg$c30; + peg$currPos++; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c31); + } + } + if (s3 !== peg$FAILED) { + s4 = peg$parsetoken(); + if (s4 !== peg$FAILED) { + s3 = [s3, s4]; + s2 = s3; + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c172(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseother_param() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + s1 = peg$parsepname(); + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 61) { + s3 = peg$c30; + peg$currPos++; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c31); + } + } + if (s3 !== peg$FAILED) { + s4 = peg$parsepvalue(); + if (s4 !== peg$FAILED) { + s3 = [s3, s4]; + s2 = s3; + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c173(s1, s2); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsepname() { + var s0, s1, s2; + s0 = peg$currPos; + s1 = []; + s2 = peg$parseparamchar(); + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseparamchar(); + } + } + else { + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s0 = input.substring(s0, peg$currPos); + } + else { + s0 = s1; + } + return s0; + } + function peg$parsepvalue() { + var s0, s1, s2; + s0 = peg$currPos; + s1 = []; + s2 = peg$parseparamchar(); + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseparamchar(); + } + } + else { + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s0 = input.substring(s0, peg$currPos); + } + else { + s0 = s1; + } + return s0; + } + function peg$parseparamchar() { + var s0; + s0 = peg$parseparam_unreserved(); + if (s0 === peg$FAILED) { + s0 = peg$parseunreserved(); + if (s0 === peg$FAILED) { + s0 = peg$parseescaped(); + } + } + return s0; + } + function peg$parseparam_unreserved() { + var s0; + if (input.charCodeAt(peg$currPos) === 91) { + s0 = peg$c76; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c77); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s0 = peg$c78; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c79); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 47) { + s0 = peg$c20; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c21); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s0 = peg$c24; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 38) { + s0 = peg$c28; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c29); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s0 = peg$c32; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 36) { + s0 = peg$c34; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c35); + } + } + } + } + } + } + } + } + return s0; + } + function peg$parseheaders() { + var s0, s1, s2, s3, s4, s5, s6; + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 63) { + s1 = peg$c22; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c23); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseheader(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 38) { + s5 = peg$c28; + peg$currPos++; + } + else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c29); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parseheader(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 38) { + s5 = peg$c28; + peg$currPos++; + } + else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c29); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parseheader(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseheader() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parsehname(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s2 = peg$c30; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c31); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parsehvalue(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c174(s1, s3); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsehname() { + var s0, s1; + s0 = []; + s1 = peg$parsehnv_unreserved(); + if (s1 === peg$FAILED) { + s1 = peg$parseunreserved(); + if (s1 === peg$FAILED) { + s1 = peg$parseescaped(); + } + } + if (s1 !== peg$FAILED) { + while (s1 !== peg$FAILED) { + s0.push(s1); + s1 = peg$parsehnv_unreserved(); + if (s1 === peg$FAILED) { + s1 = peg$parseunreserved(); + if (s1 === peg$FAILED) { + s1 = peg$parseescaped(); + } + } + } + } + else { + s0 = peg$FAILED; + } + return s0; + } + function peg$parsehvalue() { + var s0, s1; + s0 = []; + s1 = peg$parsehnv_unreserved(); + if (s1 === peg$FAILED) { + s1 = peg$parseunreserved(); + if (s1 === peg$FAILED) { + s1 = peg$parseescaped(); + } + } + while (s1 !== peg$FAILED) { + s0.push(s1); + s1 = peg$parsehnv_unreserved(); + if (s1 === peg$FAILED) { + s1 = peg$parseunreserved(); + if (s1 === peg$FAILED) { + s1 = peg$parseescaped(); + } + } + } + return s0; + } + function peg$parsehnv_unreserved() { + var s0; + if (input.charCodeAt(peg$currPos) === 91) { + s0 = peg$c76; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c77); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s0 = peg$c78; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c79); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 47) { + s0 = peg$c20; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c21); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 63) { + s0 = peg$c22; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c23); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s0 = peg$c24; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s0 = peg$c32; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 36) { + s0 = peg$c34; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c35); + } + } + } + } + } + } + } + } + return s0; + } + function peg$parseRequest_Response() { + var s0; + s0 = peg$parseStatus_Line(); + if (s0 === peg$FAILED) { + s0 = peg$parseRequest_Line(); + } + return s0; + } + function peg$parseRequest_Line() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parseMethod(); + if (s1 !== peg$FAILED) { + s2 = peg$parseSP(); + if (s2 !== peg$FAILED) { + s3 = peg$parseRequest_URI(); + if (s3 !== peg$FAILED) { + s4 = peg$parseSP(); + if (s4 !== peg$FAILED) { + s5 = peg$parseSIP_Version(); + if (s5 !== peg$FAILED) { + s1 = [s1, s2, s3, s4, s5]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseRequest_URI() { + var s0; + s0 = peg$parseSIP_URI(); + if (s0 === peg$FAILED) { + s0 = peg$parseabsoluteURI(); + } + return s0; + } + function peg$parseabsoluteURI() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parsescheme(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s2 = peg$c24; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parsehier_part(); + if (s3 === peg$FAILED) { + s3 = peg$parseopaque_part(); + } + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c175(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsehier_part() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + s1 = peg$parsenet_path(); + if (s1 === peg$FAILED) { + s1 = peg$parseabs_path(); + } + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 63) { + s3 = peg$c22; + peg$currPos++; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c23); + } + } + if (s3 !== peg$FAILED) { + s4 = peg$parsequery(); + if (s4 !== peg$FAILED) { + s3 = [s3, s4]; + s2 = s3; + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsenet_path() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c176) { + s1 = peg$c176; + peg$currPos += 2; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c177); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseauthority(); + if (s2 !== peg$FAILED) { + s3 = peg$parseabs_path(); + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseabs_path() { + var s0, s1, s2; + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 47) { + s1 = peg$c20; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c21); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parsepath_segments(); + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseopaque_part() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parseuric_no_slash(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseuric(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseuric(); + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseuric() { + var s0; + s0 = peg$parsereserved(); + if (s0 === peg$FAILED) { + s0 = peg$parseunreserved(); + if (s0 === peg$FAILED) { + s0 = peg$parseescaped(); + } + } + return s0; + } + function peg$parseuric_no_slash() { + var s0; + s0 = peg$parseunreserved(); + if (s0 === peg$FAILED) { + s0 = peg$parseescaped(); + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 59) { + s0 = peg$c18; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c19); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 63) { + s0 = peg$c22; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c23); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s0 = peg$c24; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 64) { + s0 = peg$c26; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c27); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 38) { + s0 = peg$c28; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c29); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s0 = peg$c30; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c31); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s0 = peg$c32; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 36) { + s0 = peg$c34; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c35); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s0 = peg$c36; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c37); + } + } + } + } + } + } + } + } + } + } + } + } + return s0; + } + function peg$parsepath_segments() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parsesegment(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 47) { + s4 = peg$c20; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c21); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parsesegment(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 47) { + s4 = peg$c20; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c21); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parsesegment(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsesegment() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = []; + s2 = peg$parsepchar(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parsepchar(); + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 59) { + s4 = peg$c18; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c19); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseparam(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 59) { + s4 = peg$c18; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c19); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseparam(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseparam() { + var s0, s1; + s0 = []; + s1 = peg$parsepchar(); + while (s1 !== peg$FAILED) { + s0.push(s1); + s1 = peg$parsepchar(); + } + return s0; + } + function peg$parsepchar() { + var s0; + s0 = peg$parseunreserved(); + if (s0 === peg$FAILED) { + s0 = peg$parseescaped(); + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s0 = peg$c24; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 64) { + s0 = peg$c26; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c27); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 38) { + s0 = peg$c28; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c29); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s0 = peg$c30; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c31); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s0 = peg$c32; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 36) { + s0 = peg$c34; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c35); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s0 = peg$c36; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c37); + } + } + } + } + } + } + } + } + } + } + return s0; + } + function peg$parsescheme() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + s1 = peg$currPos; + s2 = peg$parseALPHA(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseALPHA(); + if (s4 === peg$FAILED) { + s4 = peg$parseDIGIT(); + if (s4 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s4 = peg$c32; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + if (s4 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s4 = peg$c38; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c39); + } + } + if (s4 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c42; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c43); + } + } + } + } + } + } + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseALPHA(); + if (s4 === peg$FAILED) { + s4 = peg$parseDIGIT(); + if (s4 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s4 = peg$c32; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + if (s4 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s4 = peg$c38; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c39); + } + } + if (s4 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c42; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c43); + } + } + } + } + } + } + } + if (s3 !== peg$FAILED) { + s2 = [s2, s3]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c178(); + } + s0 = s1; + return s0; + } + function peg$parseauthority() { + var s0; + s0 = peg$parsesrvr(); + if (s0 === peg$FAILED) { + s0 = peg$parsereg_name(); + } + return s0; + } + function peg$parsesrvr() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$currPos; + s2 = peg$parseuserinfo(); + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 64) { + s3 = peg$c26; + peg$currPos++; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c27); + } + } + if (s3 !== peg$FAILED) { + s2 = [s2, s3]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + s2 = peg$parsehostport(); + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = null; + } + return s0; + } + function peg$parsereg_name() { + var s0, s1; + s0 = []; + s1 = peg$parseunreserved(); + if (s1 === peg$FAILED) { + s1 = peg$parseescaped(); + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 36) { + s1 = peg$c34; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c35); + } + } + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s1 = peg$c36; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c37); + } + } + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 59) { + s1 = peg$c18; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c19); + } + } + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s1 = peg$c24; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 64) { + s1 = peg$c26; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c27); + } + } + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 38) { + s1 = peg$c28; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c29); + } + } + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s1 = peg$c30; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c31); + } + } + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s1 = peg$c32; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + } + } + } + } + } + } + } + } + } + if (s1 !== peg$FAILED) { + while (s1 !== peg$FAILED) { + s0.push(s1); + s1 = peg$parseunreserved(); + if (s1 === peg$FAILED) { + s1 = peg$parseescaped(); + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 36) { + s1 = peg$c34; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c35); + } + } + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s1 = peg$c36; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c37); + } + } + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 59) { + s1 = peg$c18; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c19); + } + } + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s1 = peg$c24; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 64) { + s1 = peg$c26; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c27); + } + } + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 38) { + s1 = peg$c28; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c29); + } + } + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s1 = peg$c30; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c31); + } + } + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s1 = peg$c32; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + } + } + } + } + } + } + } + } + } + } + } + else { + s0 = peg$FAILED; + } + return s0; + } + function peg$parsequery() { + var s0, s1; + s0 = []; + s1 = peg$parseuric(); + while (s1 !== peg$FAILED) { + s0.push(s1); + s1 = peg$parseuric(); + } + return s0; + } + function peg$parseSIP_Version() { + var s0, s1, s2, s3, s4, s5, s6; + s0 = peg$currPos; + if (input.substr(peg$currPos, 3).toLowerCase() === peg$c114) { + s1 = input.substr(peg$currPos, 3); + peg$currPos += 3; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c179); + } + } + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 47) { + s2 = peg$c20; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c21); + } + } + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseDIGIT(); + if (s4 !== peg$FAILED) { + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseDIGIT(); + } + } + else { + s3 = peg$FAILED; + } + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c42; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c43); + } + } + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$parseDIGIT(); + if (s6 !== peg$FAILED) { + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parseDIGIT(); + } + } + else { + s5 = peg$FAILED; + } + if (s5 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c180(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseINVITEm() { + var s0; + if (input.substr(peg$currPos, 6) === peg$c181) { + s0 = peg$c181; + peg$currPos += 6; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c182); + } + } + return s0; + } + function peg$parseACKm() { + var s0; + if (input.substr(peg$currPos, 3) === peg$c183) { + s0 = peg$c183; + peg$currPos += 3; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c184); + } + } + return s0; + } + function peg$parsePRACKm() { + var s0; + if (input.substr(peg$currPos, 5) === peg$c185) { + s0 = peg$c185; + peg$currPos += 5; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c186); + } + } + return s0; + } + function peg$parseOPTIONSm() { + var s0; + if (input.substr(peg$currPos, 7) === peg$c187) { + s0 = peg$c187; + peg$currPos += 7; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c188); + } + } + return s0; + } + function peg$parseBYEm() { + var s0; + if (input.substr(peg$currPos, 3) === peg$c189) { + s0 = peg$c189; + peg$currPos += 3; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c190); + } + } + return s0; + } + function peg$parseCANCELm() { + var s0; + if (input.substr(peg$currPos, 6) === peg$c191) { + s0 = peg$c191; + peg$currPos += 6; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c192); + } + } + return s0; + } + function peg$parseREGISTERm() { + var s0; + if (input.substr(peg$currPos, 8) === peg$c193) { + s0 = peg$c193; + peg$currPos += 8; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c194); + } + } + return s0; + } + function peg$parseSUBSCRIBEm() { + var s0; + if (input.substr(peg$currPos, 9) === peg$c195) { + s0 = peg$c195; + peg$currPos += 9; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c196); + } + } + return s0; + } + function peg$parseNOTIFYm() { + var s0; + if (input.substr(peg$currPos, 6) === peg$c197) { + s0 = peg$c197; + peg$currPos += 6; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c198); + } + } + return s0; + } + function peg$parseREFERm() { + var s0; + if (input.substr(peg$currPos, 5) === peg$c199) { + s0 = peg$c199; + peg$currPos += 5; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c200); + } + } + return s0; + } + function peg$parsePUBLISHm() { + var s0; + if (input.substr(peg$currPos, 7) === peg$c201) { + s0 = peg$c201; + peg$currPos += 7; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c202); + } + } + return s0; + } + function peg$parseMethod() { + var s0, s1; + s0 = peg$currPos; + s1 = peg$parseINVITEm(); + if (s1 === peg$FAILED) { + s1 = peg$parseACKm(); + if (s1 === peg$FAILED) { + s1 = peg$parseOPTIONSm(); + if (s1 === peg$FAILED) { + s1 = peg$parseBYEm(); + if (s1 === peg$FAILED) { + s1 = peg$parseCANCELm(); + if (s1 === peg$FAILED) { + s1 = peg$parseREGISTERm(); + if (s1 === peg$FAILED) { + s1 = peg$parseSUBSCRIBEm(); + if (s1 === peg$FAILED) { + s1 = peg$parsePUBLISHm(); + if (s1 === peg$FAILED) { + s1 = peg$parseNOTIFYm(); + if (s1 === peg$FAILED) { + s1 = peg$parseREFERm(); + if (s1 === peg$FAILED) { + s1 = peg$parsetoken(); + } + } + } + } + } + } + } + } + } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c203(); + } + s0 = s1; + return s0; + } + function peg$parseStatus_Line() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parseSIP_Version(); + if (s1 !== peg$FAILED) { + s2 = peg$parseSP(); + if (s2 !== peg$FAILED) { + s3 = peg$parseStatus_Code(); + if (s3 !== peg$FAILED) { + s4 = peg$parseSP(); + if (s4 !== peg$FAILED) { + s5 = peg$parseReason_Phrase(); + if (s5 !== peg$FAILED) { + s1 = [s1, s2, s3, s4, s5]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseStatus_Code() { + var s0, s1; + s0 = peg$currPos; + s1 = peg$parseextension_code(); + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c204(s1); + } + s0 = s1; + return s0; + } + function peg$parseextension_code() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parseDIGIT(); + if (s1 !== peg$FAILED) { + s2 = peg$parseDIGIT(); + if (s2 !== peg$FAILED) { + s3 = peg$parseDIGIT(); + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseReason_Phrase() { + var s0, s1, s2; + s0 = peg$currPos; + s1 = []; + s2 = peg$parsereserved(); + if (s2 === peg$FAILED) { + s2 = peg$parseunreserved(); + if (s2 === peg$FAILED) { + s2 = peg$parseescaped(); + if (s2 === peg$FAILED) { + s2 = peg$parseUTF8_NONASCII(); + if (s2 === peg$FAILED) { + s2 = peg$parseUTF8_CONT(); + if (s2 === peg$FAILED) { + s2 = peg$parseSP(); + if (s2 === peg$FAILED) { + s2 = peg$parseHTAB(); + } + } + } + } + } + } + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parsereserved(); + if (s2 === peg$FAILED) { + s2 = peg$parseunreserved(); + if (s2 === peg$FAILED) { + s2 = peg$parseescaped(); + if (s2 === peg$FAILED) { + s2 = peg$parseUTF8_NONASCII(); + if (s2 === peg$FAILED) { + s2 = peg$parseUTF8_CONT(); + if (s2 === peg$FAILED) { + s2 = peg$parseSP(); + if (s2 === peg$FAILED) { + s2 = peg$parseHTAB(); + } + } + } + } + } + } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c205(); + } + s0 = s1; + return s0; + } + function peg$parseAllow_Events() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parseevent_type(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseCOMMA(); + if (s4 !== peg$FAILED) { + s5 = peg$parseevent_type(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseCOMMA(); + if (s4 !== peg$FAILED) { + s5 = peg$parseevent_type(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseCall_ID() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + s1 = peg$parseword(); + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 64) { + s3 = peg$c26; + peg$currPos++; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c27); + } + } + if (s3 !== peg$FAILED) { + s4 = peg$parseword(); + if (s4 !== peg$FAILED) { + s3 = [s3, s4]; + s2 = s3; + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c206(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseContact() { + var s0, s1, s2, s3, s4, s5, s6; + s0 = peg$currPos; + s1 = peg$parseSTAR(); + if (s1 === peg$FAILED) { + s1 = peg$currPos; + s2 = peg$parsecontact_param(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$currPos; + s5 = peg$parseCOMMA(); + if (s5 !== peg$FAILED) { + s6 = peg$parsecontact_param(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$currPos; + s5 = peg$parseCOMMA(); + if (s5 !== peg$FAILED) { + s6 = peg$parsecontact_param(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + if (s3 !== peg$FAILED) { + s2 = [s2, s3]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c207(); + } + s0 = s1; + return s0; + } + function peg$parsecontact_param() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parseSIP_URI_noparams(); + if (s1 === peg$FAILED) { + s1 = peg$parsename_addr(); + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsecontact_params(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsecontact_params(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c208(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsename_addr() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + s1 = peg$parsedisplayName(); + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + s2 = peg$parseLAQUOT(); + if (s2 !== peg$FAILED) { + s3 = peg$parseSIP_URI(); + if (s3 !== peg$FAILED) { + s4 = peg$parseRAQUOT(); + if (s4 !== peg$FAILED) { + s1 = [s1, s2, s3, s4]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsedisplayName() { + var s0, s1, s2, s3, s4, s5, s6; + s0 = peg$currPos; + s1 = peg$currPos; + s2 = peg$parsetoken(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$currPos; + s5 = peg$parseLWS(); + if (s5 !== peg$FAILED) { + s6 = peg$parsetoken(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$currPos; + s5 = peg$parseLWS(); + if (s5 !== peg$FAILED) { + s6 = peg$parsetoken(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + if (s3 !== peg$FAILED) { + s2 = [s2, s3]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = peg$parsequoted_string(); + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c209(s1); + } + s0 = s1; + return s0; + } + function peg$parsecontact_params() { + var s0; + s0 = peg$parsec_p_q(); + if (s0 === peg$FAILED) { + s0 = peg$parsec_p_expires(); + if (s0 === peg$FAILED) { + s0 = peg$parsegeneric_param(); + } + } + return s0; + } + function peg$parsec_p_q() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.substr(peg$currPos, 1).toLowerCase() === peg$c210) { + s1 = input.charAt(peg$currPos); + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c211); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parseqvalue(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c212(s3); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsec_p_expires() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.substr(peg$currPos, 7).toLowerCase() === peg$c213) { + s1 = input.substr(peg$currPos, 7); + peg$currPos += 7; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c214); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parsedelta_seconds(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c215(s3); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsedelta_seconds() { + var s0, s1, s2; + s0 = peg$currPos; + s1 = []; + s2 = peg$parseDIGIT(); + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseDIGIT(); + } + } + else { + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c216(s1); + } + s0 = s1; + return s0; + } + function peg$parseqvalue() { + var s0, s1, s2, s3, s4, s5, s6; + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 48) { + s1 = peg$c217; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c218); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s3 = peg$c42; + peg$currPos++; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c43); + } + } + if (s3 !== peg$FAILED) { + s4 = peg$parseDIGIT(); + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s5 = peg$parseDIGIT(); + if (s5 === peg$FAILED) { + s5 = null; + } + if (s5 !== peg$FAILED) { + s6 = peg$parseDIGIT(); + if (s6 === peg$FAILED) { + s6 = null; + } + if (s6 !== peg$FAILED) { + s3 = [s3, s4, s5, s6]; + s2 = s3; + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c219(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsegeneric_param() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + s1 = peg$parsetoken(); + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + s3 = peg$parseEQUAL(); + if (s3 !== peg$FAILED) { + s4 = peg$parsegen_value(); + if (s4 !== peg$FAILED) { + s3 = [s3, s4]; + s2 = s3; + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c220(s1, s2); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsegen_value() { + var s0; + s0 = peg$parsetoken(); + if (s0 === peg$FAILED) { + s0 = peg$parsehost(); + if (s0 === peg$FAILED) { + s0 = peg$parsequoted_string(); + } + } + return s0; + } + function peg$parseContent_Disposition() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parsedisp_type(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsedisp_param(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsedisp_param(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsedisp_type() { + var s0, s1; + s0 = peg$currPos; + if (input.substr(peg$currPos, 6).toLowerCase() === peg$c221) { + s1 = input.substr(peg$currPos, 6); + peg$currPos += 6; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c222); + } + } + if (s1 === peg$FAILED) { + if (input.substr(peg$currPos, 7).toLowerCase() === peg$c223) { + s1 = input.substr(peg$currPos, 7); + peg$currPos += 7; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c224); + } + } + if (s1 === peg$FAILED) { + if (input.substr(peg$currPos, 4).toLowerCase() === peg$c225) { + s1 = input.substr(peg$currPos, 4); + peg$currPos += 4; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c226); + } + } + if (s1 === peg$FAILED) { + if (input.substr(peg$currPos, 5).toLowerCase() === peg$c227) { + s1 = input.substr(peg$currPos, 5); + peg$currPos += 5; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c228); + } + } + if (s1 === peg$FAILED) { + s1 = peg$parsetoken(); + } + } + } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c229(); + } + s0 = s1; + return s0; + } + function peg$parsedisp_param() { + var s0; + s0 = peg$parsehandling_param(); + if (s0 === peg$FAILED) { + s0 = peg$parsegeneric_param(); + } + return s0; + } + function peg$parsehandling_param() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.substr(peg$currPos, 8).toLowerCase() === peg$c230) { + s1 = input.substr(peg$currPos, 8); + peg$currPos += 8; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c231); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + if (input.substr(peg$currPos, 8).toLowerCase() === peg$c232) { + s3 = input.substr(peg$currPos, 8); + peg$currPos += 8; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c233); + } + } + if (s3 === peg$FAILED) { + if (input.substr(peg$currPos, 8).toLowerCase() === peg$c234) { + s3 = input.substr(peg$currPos, 8); + peg$currPos += 8; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c235); + } + } + if (s3 === peg$FAILED) { + s3 = peg$parsetoken(); + } + } + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseContent_Encoding() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parsetoken(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseCOMMA(); + if (s4 !== peg$FAILED) { + s5 = peg$parsetoken(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseCOMMA(); + if (s4 !== peg$FAILED) { + s5 = peg$parsetoken(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseContent_Length() { + var s0, s1, s2; + s0 = peg$currPos; + s1 = []; + s2 = peg$parseDIGIT(); + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseDIGIT(); + } + } + else { + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c236(s1); + } + s0 = s1; + return s0; + } + function peg$parseContent_Type() { + var s0, s1; + s0 = peg$currPos; + s1 = peg$parsemedia_type(); + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c237(); + } + s0 = s1; + return s0; + } + function peg$parsemedia_type() { + var s0, s1, s2, s3, s4, s5, s6, s7; + s0 = peg$currPos; + s1 = peg$parsem_type(); + if (s1 !== peg$FAILED) { + s2 = peg$parseSLASH(); + if (s2 !== peg$FAILED) { + s3 = peg$parsem_subtype(); + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$currPos; + s6 = peg$parseSEMI(); + if (s6 !== peg$FAILED) { + s7 = peg$parsem_parameter(); + if (s7 !== peg$FAILED) { + s6 = [s6, s7]; + s5 = s6; + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$currPos; + s6 = peg$parseSEMI(); + if (s6 !== peg$FAILED) { + s7 = peg$parsem_parameter(); + if (s7 !== peg$FAILED) { + s6 = [s6, s7]; + s5 = s6; + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + if (s4 !== peg$FAILED) { + s1 = [s1, s2, s3, s4]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsem_type() { + var s0; + s0 = peg$parsediscrete_type(); + if (s0 === peg$FAILED) { + s0 = peg$parsecomposite_type(); + } + return s0; + } + function peg$parsediscrete_type() { + var s0; + if (input.substr(peg$currPos, 4).toLowerCase() === peg$c238) { + s0 = input.substr(peg$currPos, 4); + peg$currPos += 4; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c239); + } + } + if (s0 === peg$FAILED) { + if (input.substr(peg$currPos, 5).toLowerCase() === peg$c240) { + s0 = input.substr(peg$currPos, 5); + peg$currPos += 5; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c241); + } + } + if (s0 === peg$FAILED) { + if (input.substr(peg$currPos, 5).toLowerCase() === peg$c242) { + s0 = input.substr(peg$currPos, 5); + peg$currPos += 5; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c243); + } + } + if (s0 === peg$FAILED) { + if (input.substr(peg$currPos, 5).toLowerCase() === peg$c244) { + s0 = input.substr(peg$currPos, 5); + peg$currPos += 5; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c245); + } + } + if (s0 === peg$FAILED) { + if (input.substr(peg$currPos, 11).toLowerCase() === peg$c246) { + s0 = input.substr(peg$currPos, 11); + peg$currPos += 11; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c247); + } + } + if (s0 === peg$FAILED) { + s0 = peg$parseextension_token(); + } + } + } + } + } + return s0; + } + function peg$parsecomposite_type() { + var s0; + if (input.substr(peg$currPos, 7).toLowerCase() === peg$c248) { + s0 = input.substr(peg$currPos, 7); + peg$currPos += 7; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c249); + } + } + if (s0 === peg$FAILED) { + if (input.substr(peg$currPos, 9).toLowerCase() === peg$c250) { + s0 = input.substr(peg$currPos, 9); + peg$currPos += 9; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c251); + } + } + if (s0 === peg$FAILED) { + s0 = peg$parseextension_token(); + } + } + return s0; + } + function peg$parseextension_token() { + var s0; + s0 = peg$parsetoken(); + if (s0 === peg$FAILED) { + s0 = peg$parsex_token(); + } + return s0; + } + function peg$parsex_token() { + var s0, s1, s2; + s0 = peg$currPos; + if (input.substr(peg$currPos, 2).toLowerCase() === peg$c252) { + s1 = input.substr(peg$currPos, 2); + peg$currPos += 2; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c253); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parsetoken(); + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsem_subtype() { + var s0; + s0 = peg$parseextension_token(); + if (s0 === peg$FAILED) { + s0 = peg$parsetoken(); + } + return s0; + } + function peg$parsem_parameter() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parsetoken(); + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parsem_value(); + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsem_value() { + var s0; + s0 = peg$parsetoken(); + if (s0 === peg$FAILED) { + s0 = peg$parsequoted_string(); + } + return s0; + } + function peg$parseCSeq() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parseCSeq_value(); + if (s1 !== peg$FAILED) { + s2 = peg$parseLWS(); + if (s2 !== peg$FAILED) { + s3 = peg$parseMethod(); + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseCSeq_value() { + var s0, s1, s2; + s0 = peg$currPos; + s1 = []; + s2 = peg$parseDIGIT(); + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseDIGIT(); + } + } + else { + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c254(s1); + } + s0 = s1; + return s0; + } + function peg$parseExpires() { + var s0, s1; + s0 = peg$currPos; + s1 = peg$parsedelta_seconds(); + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c255(s1); + } + s0 = s1; + return s0; + } + function peg$parseEvent() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parseevent_type(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsegeneric_param(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsegeneric_param(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c256(s1); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseevent_type() { + var s0, s1, s2, s3, s4, s5, s6; + s0 = peg$currPos; + s1 = peg$currPos; + s2 = peg$parsetoken_nodot(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s5 = peg$c42; + peg$currPos++; + } + else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c43); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parsetoken_nodot(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s5 = peg$c42; + peg$currPos++; + } + else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c43); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parsetoken_nodot(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + if (s3 !== peg$FAILED) { + s2 = [s2, s3]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s0 = input.substring(s0, peg$currPos); + } + else { + s0 = s1; + } + return s0; + } + function peg$parseFrom() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parseSIP_URI_noparams(); + if (s1 === peg$FAILED) { + s1 = peg$parsename_addr(); + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsefrom_param(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsefrom_param(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c257(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsefrom_param() { + var s0; + s0 = peg$parsetag_param(); + if (s0 === peg$FAILED) { + s0 = peg$parsegeneric_param(); + } + return s0; + } + function peg$parsetag_param() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.substr(peg$currPos, 3).toLowerCase() === peg$c258) { + s1 = input.substr(peg$currPos, 3); + peg$currPos += 3; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c259); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parsetoken(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c260(s3); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseMax_Forwards() { + var s0, s1, s2; + s0 = peg$currPos; + s1 = []; + s2 = peg$parseDIGIT(); + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseDIGIT(); + } + } + else { + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c261(s1); + } + s0 = s1; + return s0; + } + function peg$parseMin_Expires() { + var s0, s1; + s0 = peg$currPos; + s1 = peg$parsedelta_seconds(); + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c262(s1); + } + s0 = s1; + return s0; + } + function peg$parseName_Addr_Header() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8; + s0 = peg$currPos; + s1 = []; + s2 = peg$parsedisplayName(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parsedisplayName(); + } + if (s1 !== peg$FAILED) { + s2 = peg$parseLAQUOT(); + if (s2 !== peg$FAILED) { + s3 = peg$parseSIP_URI(); + if (s3 !== peg$FAILED) { + s4 = peg$parseRAQUOT(); + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$currPos; + s7 = peg$parseSEMI(); + if (s7 !== peg$FAILED) { + s8 = peg$parsegeneric_param(); + if (s8 !== peg$FAILED) { + s7 = [s7, s8]; + s6 = s7; + } + else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } + else { + peg$currPos = s6; + s6 = peg$FAILED; + } + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$currPos; + s7 = peg$parseSEMI(); + if (s7 !== peg$FAILED) { + s8 = peg$parsegeneric_param(); + if (s8 !== peg$FAILED) { + s7 = [s7, s8]; + s6 = s7; + } + else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } + else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } + if (s5 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c263(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseProxy_Authenticate() { + var s0; + s0 = peg$parsechallenge(); + return s0; + } + function peg$parsechallenge() { + var s0, s1, s2, s3, s4, s5, s6, s7; + s0 = peg$currPos; + if (input.substr(peg$currPos, 6).toLowerCase() === peg$c264) { + s1 = input.substr(peg$currPos, 6); + peg$currPos += 6; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c265); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseLWS(); + if (s2 !== peg$FAILED) { + s3 = peg$parsedigest_cln(); + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$currPos; + s6 = peg$parseCOMMA(); + if (s6 !== peg$FAILED) { + s7 = peg$parsedigest_cln(); + if (s7 !== peg$FAILED) { + s6 = [s6, s7]; + s5 = s6; + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$currPos; + s6 = peg$parseCOMMA(); + if (s6 !== peg$FAILED) { + s7 = peg$parsedigest_cln(); + if (s7 !== peg$FAILED) { + s6 = [s6, s7]; + s5 = s6; + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + if (s4 !== peg$FAILED) { + s1 = [s1, s2, s3, s4]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$parseother_challenge(); + } + return s0; + } + function peg$parseother_challenge() { + var s0, s1, s2, s3, s4, s5, s6, s7; + s0 = peg$currPos; + s1 = peg$parsetoken(); + if (s1 !== peg$FAILED) { + s2 = peg$parseLWS(); + if (s2 !== peg$FAILED) { + s3 = peg$parseauth_param(); + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$currPos; + s6 = peg$parseCOMMA(); + if (s6 !== peg$FAILED) { + s7 = peg$parseauth_param(); + if (s7 !== peg$FAILED) { + s6 = [s6, s7]; + s5 = s6; + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$currPos; + s6 = peg$parseCOMMA(); + if (s6 !== peg$FAILED) { + s7 = peg$parseauth_param(); + if (s7 !== peg$FAILED) { + s6 = [s6, s7]; + s5 = s6; + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + if (s4 !== peg$FAILED) { + s1 = [s1, s2, s3, s4]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseauth_param() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parsetoken(); + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parsetoken(); + if (s3 === peg$FAILED) { + s3 = peg$parsequoted_string(); + } + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsedigest_cln() { + var s0; + s0 = peg$parserealm(); + if (s0 === peg$FAILED) { + s0 = peg$parsedomain(); + if (s0 === peg$FAILED) { + s0 = peg$parsenonce(); + if (s0 === peg$FAILED) { + s0 = peg$parseopaque(); + if (s0 === peg$FAILED) { + s0 = peg$parsestale(); + if (s0 === peg$FAILED) { + s0 = peg$parsealgorithm(); + if (s0 === peg$FAILED) { + s0 = peg$parseqop_options(); + if (s0 === peg$FAILED) { + s0 = peg$parseauth_param(); + } + } + } + } + } + } + } + return s0; + } + function peg$parserealm() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.substr(peg$currPos, 5).toLowerCase() === peg$c266) { + s1 = input.substr(peg$currPos, 5); + peg$currPos += 5; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c267); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parserealm_value(); + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parserealm_value() { + var s0, s1; + s0 = peg$currPos; + s1 = peg$parsequoted_string_clean(); + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c268(s1); + } + s0 = s1; + return s0; + } + function peg$parsedomain() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8; + s0 = peg$currPos; + if (input.substr(peg$currPos, 6).toLowerCase() === peg$c269) { + s1 = input.substr(peg$currPos, 6); + peg$currPos += 6; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c270); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parseLDQUOT(); + if (s3 !== peg$FAILED) { + s4 = peg$parseURI(); + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$currPos; + s7 = []; + s8 = peg$parseSP(); + if (s8 !== peg$FAILED) { + while (s8 !== peg$FAILED) { + s7.push(s8); + s8 = peg$parseSP(); + } + } + else { + s7 = peg$FAILED; + } + if (s7 !== peg$FAILED) { + s8 = peg$parseURI(); + if (s8 !== peg$FAILED) { + s7 = [s7, s8]; + s6 = s7; + } + else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } + else { + peg$currPos = s6; + s6 = peg$FAILED; + } + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$currPos; + s7 = []; + s8 = peg$parseSP(); + if (s8 !== peg$FAILED) { + while (s8 !== peg$FAILED) { + s7.push(s8); + s8 = peg$parseSP(); + } + } + else { + s7 = peg$FAILED; + } + if (s7 !== peg$FAILED) { + s8 = peg$parseURI(); + if (s8 !== peg$FAILED) { + s7 = [s7, s8]; + s6 = s7; + } + else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } + else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parseRDQUOT(); + if (s6 !== peg$FAILED) { + s1 = [s1, s2, s3, s4, s5, s6]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseURI() { + var s0; + s0 = peg$parseabsoluteURI(); + if (s0 === peg$FAILED) { + s0 = peg$parseabs_path(); + } + return s0; + } + function peg$parsenonce() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.substr(peg$currPos, 5).toLowerCase() === peg$c271) { + s1 = input.substr(peg$currPos, 5); + peg$currPos += 5; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c272); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parsenonce_value(); + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsenonce_value() { + var s0, s1; + s0 = peg$currPos; + s1 = peg$parsequoted_string_clean(); + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c273(s1); + } + s0 = s1; + return s0; + } + function peg$parseopaque() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.substr(peg$currPos, 6).toLowerCase() === peg$c274) { + s1 = input.substr(peg$currPos, 6); + peg$currPos += 6; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c275); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parsequoted_string_clean(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c276(s3); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsestale() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + if (input.substr(peg$currPos, 5).toLowerCase() === peg$c277) { + s1 = input.substr(peg$currPos, 5); + peg$currPos += 5; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c278); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$currPos; + if (input.substr(peg$currPos, 4).toLowerCase() === peg$c279) { + s4 = input.substr(peg$currPos, 4); + peg$currPos += 4; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c280); + } + } + if (s4 !== peg$FAILED) { + peg$savedPos = s3; + s4 = peg$c281(); + } + s3 = s4; + if (s3 === peg$FAILED) { + s3 = peg$currPos; + if (input.substr(peg$currPos, 5).toLowerCase() === peg$c282) { + s4 = input.substr(peg$currPos, 5); + peg$currPos += 5; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c283); + } + } + if (s4 !== peg$FAILED) { + peg$savedPos = s3; + s4 = peg$c284(); + } + s3 = s4; + } + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsealgorithm() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.substr(peg$currPos, 9).toLowerCase() === peg$c285) { + s1 = input.substr(peg$currPos, 9); + peg$currPos += 9; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c286); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + if (input.substr(peg$currPos, 3).toLowerCase() === peg$c287) { + s3 = input.substr(peg$currPos, 3); + peg$currPos += 3; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c288); + } + } + if (s3 === peg$FAILED) { + if (input.substr(peg$currPos, 8).toLowerCase() === peg$c289) { + s3 = input.substr(peg$currPos, 8); + peg$currPos += 8; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c290); + } + } + if (s3 === peg$FAILED) { + s3 = peg$parsetoken(); + } + } + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c291(s3); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseqop_options() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9; + s0 = peg$currPos; + if (input.substr(peg$currPos, 3).toLowerCase() === peg$c292) { + s1 = input.substr(peg$currPos, 3); + peg$currPos += 3; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c293); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parseLDQUOT(); + if (s3 !== peg$FAILED) { + s4 = peg$currPos; + s5 = peg$parseqop_value(); + if (s5 !== peg$FAILED) { + s6 = []; + s7 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 44) { + s8 = peg$c36; + peg$currPos++; + } + else { + s8 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c37); + } + } + if (s8 !== peg$FAILED) { + s9 = peg$parseqop_value(); + if (s9 !== peg$FAILED) { + s8 = [s8, s9]; + s7 = s8; + } + else { + peg$currPos = s7; + s7 = peg$FAILED; + } + } + else { + peg$currPos = s7; + s7 = peg$FAILED; + } + while (s7 !== peg$FAILED) { + s6.push(s7); + s7 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 44) { + s8 = peg$c36; + peg$currPos++; + } + else { + s8 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c37); + } + } + if (s8 !== peg$FAILED) { + s9 = peg$parseqop_value(); + if (s9 !== peg$FAILED) { + s8 = [s8, s9]; + s7 = s8; + } + else { + peg$currPos = s7; + s7 = peg$FAILED; + } + } + else { + peg$currPos = s7; + s7 = peg$FAILED; + } + } + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + if (s4 !== peg$FAILED) { + s5 = peg$parseRDQUOT(); + if (s5 !== peg$FAILED) { + s1 = [s1, s2, s3, s4, s5]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseqop_value() { + var s0, s1; + s0 = peg$currPos; + if (input.substr(peg$currPos, 8).toLowerCase() === peg$c294) { + s1 = input.substr(peg$currPos, 8); + peg$currPos += 8; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c295); + } + } + if (s1 === peg$FAILED) { + if (input.substr(peg$currPos, 4).toLowerCase() === peg$c296) { + s1 = input.substr(peg$currPos, 4); + peg$currPos += 4; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c297); + } + } + if (s1 === peg$FAILED) { + s1 = peg$parsetoken(); + } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c298(s1); + } + s0 = s1; + return s0; + } + function peg$parseProxy_Require() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parsetoken(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseCOMMA(); + if (s4 !== peg$FAILED) { + s5 = peg$parsetoken(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseCOMMA(); + if (s4 !== peg$FAILED) { + s5 = peg$parsetoken(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseRAck() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parseRAck_value(); + if (s1 !== peg$FAILED) { + s2 = peg$parseLWS(); + if (s2 !== peg$FAILED) { + s3 = peg$parseRAck_value(); + if (s3 !== peg$FAILED) { + s4 = peg$parseLWS(); + if (s4 !== peg$FAILED) { + s5 = peg$parseMethod(); + if (s5 !== peg$FAILED) { + s1 = [s1, s2, s3, s4, s5]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseRAck_value() { + var s0, s1, s2; + s0 = peg$currPos; + s1 = []; + s2 = peg$parseDIGIT(); + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseDIGIT(); + } + } + else { + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c299(s1); + } + s0 = s1; + return s0; + } + function peg$parseRecord_Route() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parserec_route(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseCOMMA(); + if (s4 !== peg$FAILED) { + s5 = peg$parserec_route(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseCOMMA(); + if (s4 !== peg$FAILED) { + s5 = peg$parserec_route(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c300(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parserec_route() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parsename_addr(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsegeneric_param(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsegeneric_param(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c301(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseRefer_To() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parseSIP_URI_noparams(); + if (s1 === peg$FAILED) { + s1 = peg$parsename_addr(); + if (s1 === peg$FAILED) { + s1 = peg$currPos; + s2 = peg$parseLAQUOT(); + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + s3 = peg$parseabsoluteURI(); + if (s3 !== peg$FAILED) { + s4 = peg$parseRAQUOT(); + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s2 = [s2, s3, s4]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsegeneric_param(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsegeneric_param(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c302(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseReplaces() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parsereplaces_call_id(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsereplaces_params(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsereplaces_params(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c303(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsereplaces_call_id() { + var s0, s1; + s0 = peg$currPos; + s1 = peg$parseCall_ID(); + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c304(); + } + s0 = s1; + return s0; + } + function peg$parsereplaces_params() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.substr(peg$currPos, 8).toLowerCase() === peg$c305) { + s1 = input.substr(peg$currPos, 8); + peg$currPos += 8; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c306); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parsetoken(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c307(s3); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 6).toLowerCase() === peg$c308) { + s1 = input.substr(peg$currPos, 6); + peg$currPos += 6; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c309); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parsetoken(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c310(s3); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 10).toLowerCase() === peg$c311) { + s1 = input.substr(peg$currPos, 10); + peg$currPos += 10; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c312); + } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c313(); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$parsegeneric_param(); + } + } + } + return s0; + } + function peg$parseRequire() { + var s0, s1, s2, s3, s4, s5, s6; + s0 = peg$currPos; + s1 = peg$currPos; + s2 = peg$parsetoken(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$currPos; + s5 = peg$parseCOMMA(); + if (s5 !== peg$FAILED) { + s6 = peg$parsetoken(); + if (s6 !== peg$FAILED) { + peg$savedPos = s4; + s5 = peg$c314(s2, s6); + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$currPos; + s5 = peg$parseCOMMA(); + if (s5 !== peg$FAILED) { + s6 = peg$parsetoken(); + if (s6 !== peg$FAILED) { + peg$savedPos = s4; + s5 = peg$c314(s2, s6); + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + if (s3 !== peg$FAILED) { + peg$savedPos = s1; + s2 = peg$c315(s2, s3); + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c316(s1); + } + s0 = s1; + return s0; + } + function peg$parseRoute() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parseroute_param(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseCOMMA(); + if (s4 !== peg$FAILED) { + s5 = peg$parseroute_param(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseCOMMA(); + if (s4 !== peg$FAILED) { + s5 = peg$parseroute_param(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseroute_param() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parsename_addr(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsegeneric_param(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsegeneric_param(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseRSeq() { + var s0, s1, s2; + s0 = peg$currPos; + s1 = []; + s2 = peg$parseDIGIT(); + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseDIGIT(); + } + } + else { + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c317(s1); + } + s0 = s1; + return s0; + } + function peg$parseSubscription_State() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parsesubstate_value(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsesubexp_params(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsesubexp_params(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsesubstate_value() { + var s0, s1; + s0 = peg$currPos; + if (input.substr(peg$currPos, 6).toLowerCase() === peg$c318) { + s1 = input.substr(peg$currPos, 6); + peg$currPos += 6; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c319); + } + } + if (s1 === peg$FAILED) { + if (input.substr(peg$currPos, 7).toLowerCase() === peg$c320) { + s1 = input.substr(peg$currPos, 7); + peg$currPos += 7; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c321); + } + } + if (s1 === peg$FAILED) { + if (input.substr(peg$currPos, 10).toLowerCase() === peg$c322) { + s1 = input.substr(peg$currPos, 10); + peg$currPos += 10; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c323); + } + } + if (s1 === peg$FAILED) { + s1 = peg$parsetoken(); + } + } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c324(); + } + s0 = s1; + return s0; + } + function peg$parsesubexp_params() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.substr(peg$currPos, 6).toLowerCase() === peg$c325) { + s1 = input.substr(peg$currPos, 6); + peg$currPos += 6; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c326); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parseevent_reason_value(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c327(s3); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 7).toLowerCase() === peg$c213) { + s1 = input.substr(peg$currPos, 7); + peg$currPos += 7; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c214); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parsedelta_seconds(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c328(s3); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 11).toLowerCase() === peg$c329) { + s1 = input.substr(peg$currPos, 11); + peg$currPos += 11; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c330); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parsedelta_seconds(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c331(s3); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$parsegeneric_param(); + } + } + } + return s0; + } + function peg$parseevent_reason_value() { + var s0; + if (input.substr(peg$currPos, 11).toLowerCase() === peg$c332) { + s0 = input.substr(peg$currPos, 11); + peg$currPos += 11; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c333); + } + } + if (s0 === peg$FAILED) { + if (input.substr(peg$currPos, 9).toLowerCase() === peg$c334) { + s0 = input.substr(peg$currPos, 9); + peg$currPos += 9; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c335); + } + } + if (s0 === peg$FAILED) { + if (input.substr(peg$currPos, 8).toLowerCase() === peg$c336) { + s0 = input.substr(peg$currPos, 8); + peg$currPos += 8; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c337); + } + } + if (s0 === peg$FAILED) { + if (input.substr(peg$currPos, 7).toLowerCase() === peg$c338) { + s0 = input.substr(peg$currPos, 7); + peg$currPos += 7; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c339); + } + } + if (s0 === peg$FAILED) { + if (input.substr(peg$currPos, 6).toLowerCase() === peg$c340) { + s0 = input.substr(peg$currPos, 6); + peg$currPos += 6; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c341); + } + } + if (s0 === peg$FAILED) { + if (input.substr(peg$currPos, 10).toLowerCase() === peg$c342) { + s0 = input.substr(peg$currPos, 10); + peg$currPos += 10; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c343); + } + } + if (s0 === peg$FAILED) { + if (input.substr(peg$currPos, 9).toLowerCase() === peg$c344) { + s0 = input.substr(peg$currPos, 9); + peg$currPos += 9; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c345); + } + } + if (s0 === peg$FAILED) { + s0 = peg$parsetoken(); + } + } + } + } + } + } + } + return s0; + } + function peg$parseSubject() { + var s0; + s0 = peg$parseTEXT_UTF8_TRIM(); + if (s0 === peg$FAILED) { + s0 = null; + } + return s0; + } + function peg$parseSupported() { + var s0, s1, s2, s3, s4, s5, s6; + s0 = peg$currPos; + s1 = peg$currPos; + s2 = peg$parsetoken(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$currPos; + s5 = peg$parseCOMMA(); + if (s5 !== peg$FAILED) { + s6 = peg$parsetoken(); + if (s6 !== peg$FAILED) { + peg$savedPos = s4; + s5 = peg$c314(s2, s6); + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$currPos; + s5 = peg$parseCOMMA(); + if (s5 !== peg$FAILED) { + s6 = peg$parsetoken(); + if (s6 !== peg$FAILED) { + peg$savedPos = s4; + s5 = peg$c314(s2, s6); + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + if (s3 !== peg$FAILED) { + peg$savedPos = s1; + s2 = peg$c315(s2, s3); + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c346(s1); + } + s0 = s1; + return s0; + } + function peg$parseTo() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parseSIP_URI_noparams(); + if (s1 === peg$FAILED) { + s1 = peg$parsename_addr(); + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parseto_param(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parseto_param(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c347(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseto_param() { + var s0; + s0 = peg$parsetag_param(); + if (s0 === peg$FAILED) { + s0 = peg$parsegeneric_param(); + } + return s0; + } + function peg$parseVia() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parsevia_parm(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseCOMMA(); + if (s4 !== peg$FAILED) { + s5 = peg$parsevia_parm(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseCOMMA(); + if (s4 !== peg$FAILED) { + s5 = peg$parsevia_parm(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsevia_parm() { + var s0, s1, s2, s3, s4, s5, s6, s7; + s0 = peg$currPos; + s1 = peg$parsesent_protocol(); + if (s1 !== peg$FAILED) { + s2 = peg$parseLWS(); + if (s2 !== peg$FAILED) { + s3 = peg$parsesent_by(); + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$currPos; + s6 = peg$parseSEMI(); + if (s6 !== peg$FAILED) { + s7 = peg$parsevia_params(); + if (s7 !== peg$FAILED) { + s6 = [s6, s7]; + s5 = s6; + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$currPos; + s6 = peg$parseSEMI(); + if (s6 !== peg$FAILED) { + s7 = peg$parsevia_params(); + if (s7 !== peg$FAILED) { + s6 = [s6, s7]; + s5 = s6; + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + if (s4 !== peg$FAILED) { + s1 = [s1, s2, s3, s4]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsevia_params() { + var s0; + s0 = peg$parsevia_ttl(); + if (s0 === peg$FAILED) { + s0 = peg$parsevia_maddr(); + if (s0 === peg$FAILED) { + s0 = peg$parsevia_received(); + if (s0 === peg$FAILED) { + s0 = peg$parsevia_branch(); + if (s0 === peg$FAILED) { + s0 = peg$parseresponse_port(); + if (s0 === peg$FAILED) { + s0 = peg$parsegeneric_param(); + } + } + } + } + } + return s0; + } + function peg$parsevia_ttl() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.substr(peg$currPos, 3).toLowerCase() === peg$c348) { + s1 = input.substr(peg$currPos, 3); + peg$currPos += 3; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c349); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parsettl(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c350(s3); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsevia_maddr() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.substr(peg$currPos, 5).toLowerCase() === peg$c351) { + s1 = input.substr(peg$currPos, 5); + peg$currPos += 5; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c352); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parsehost(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c353(s3); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsevia_received() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.substr(peg$currPos, 8).toLowerCase() === peg$c354) { + s1 = input.substr(peg$currPos, 8); + peg$currPos += 8; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c355); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parseIPv4address(); + if (s3 === peg$FAILED) { + s3 = peg$parseIPv6address(); + if (s3 === peg$FAILED) { + s3 = peg$parseIPv6reference(); + } + } + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c356(s3); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsevia_branch() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.substr(peg$currPos, 6).toLowerCase() === peg$c357) { + s1 = input.substr(peg$currPos, 6); + peg$currPos += 6; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c358); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parsetoken(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c359(s3); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseresponse_port() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + if (input.substr(peg$currPos, 5).toLowerCase() === peg$c360) { + s1 = input.substr(peg$currPos, 5); + peg$currPos += 5; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c361); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseDIGIT(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseDIGIT(); + } + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c362(s3); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsesent_protocol() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parseprotocol_name(); + if (s1 !== peg$FAILED) { + s2 = peg$parseSLASH(); + if (s2 !== peg$FAILED) { + s3 = peg$parsetoken(); + if (s3 !== peg$FAILED) { + s4 = peg$parseSLASH(); + if (s4 !== peg$FAILED) { + s5 = peg$parsetransport(); + if (s5 !== peg$FAILED) { + s1 = [s1, s2, s3, s4, s5]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseprotocol_name() { + var s0, s1; + s0 = peg$currPos; + if (input.substr(peg$currPos, 3).toLowerCase() === peg$c114) { + s1 = input.substr(peg$currPos, 3); + peg$currPos += 3; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c179); + } + } + if (s1 === peg$FAILED) { + s1 = peg$parsetoken(); + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c363(s1); + } + s0 = s1; + return s0; + } + function peg$parsetransport() { + var s0, s1; + s0 = peg$currPos; + if (input.substr(peg$currPos, 3).toLowerCase() === peg$c145) { + s1 = input.substr(peg$currPos, 3); + peg$currPos += 3; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c364); + } + } + if (s1 === peg$FAILED) { + if (input.substr(peg$currPos, 3).toLowerCase() === peg$c147) { + s1 = input.substr(peg$currPos, 3); + peg$currPos += 3; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c365); + } + } + if (s1 === peg$FAILED) { + if (input.substr(peg$currPos, 3).toLowerCase() === peg$c151) { + s1 = input.substr(peg$currPos, 3); + peg$currPos += 3; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c366); + } + } + if (s1 === peg$FAILED) { + if (input.substr(peg$currPos, 4).toLowerCase() === peg$c149) { + s1 = input.substr(peg$currPos, 4); + peg$currPos += 4; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c367); + } + } + if (s1 === peg$FAILED) { + s1 = peg$parsetoken(); + } + } + } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c368(s1); + } + s0 = s1; + return s0; + } + function peg$parsesent_by() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + s1 = peg$parseviaHost(); + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + s3 = peg$parseCOLON(); + if (s3 !== peg$FAILED) { + s4 = peg$parsevia_port(); + if (s4 !== peg$FAILED) { + s3 = [s3, s4]; + s2 = s3; + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseviaHost() { + var s0, s1; + s0 = peg$currPos; + s1 = peg$parsehostname(); + if (s1 === peg$FAILED) { + s1 = peg$parseIPv4address(); + if (s1 === peg$FAILED) { + s1 = peg$parseIPv6reference(); + } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c369(); + } + s0 = s1; + return s0; + } + function peg$parsevia_port() { + var s0, s1, s2, s3, s4, s5, s6; + s0 = peg$currPos; + s1 = peg$currPos; + s2 = peg$parseDIGIT(); + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + s3 = peg$parseDIGIT(); + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + s4 = peg$parseDIGIT(); + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s5 = peg$parseDIGIT(); + if (s5 === peg$FAILED) { + s5 = null; + } + if (s5 !== peg$FAILED) { + s6 = peg$parseDIGIT(); + if (s6 === peg$FAILED) { + s6 = null; + } + if (s6 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c370(s1); + } + s0 = s1; + return s0; + } + function peg$parsettl() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + s1 = peg$currPos; + s2 = peg$parseDIGIT(); + if (s2 !== peg$FAILED) { + s3 = peg$parseDIGIT(); + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + s4 = peg$parseDIGIT(); + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s2 = [s2, s3, s4]; + s1 = s2; + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } + else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c371(s1); + } + s0 = s1; + return s0; + } + function peg$parseWWW_Authenticate() { + var s0; + s0 = peg$parsechallenge(); + return s0; + } + function peg$parseSession_Expires() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parsedelta_seconds(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsese_params(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsese_params(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c372(s1); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsese_params() { + var s0; + s0 = peg$parserefresher_param(); + if (s0 === peg$FAILED) { + s0 = peg$parsegeneric_param(); + } + return s0; + } + function peg$parserefresher_param() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.substr(peg$currPos, 9) === peg$c373) { + s1 = peg$c373; + peg$currPos += 9; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c374); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + if (input.substr(peg$currPos, 3) === peg$c375) { + s3 = peg$c375; + peg$currPos += 3; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c376); + } + } + if (s3 === peg$FAILED) { + if (input.substr(peg$currPos, 3) === peg$c377) { + s3 = peg$c377; + peg$currPos += 3; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c378); + } + } + } + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c379(s3); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseMin_SE() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parsedelta_seconds(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsegeneric_param(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parseSEMI(); + if (s4 !== peg$FAILED) { + s5 = peg$parsegeneric_param(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c380(s1); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseextension_header() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parsetoken(); + if (s1 !== peg$FAILED) { + s2 = peg$parseHCOLON(); + if (s2 !== peg$FAILED) { + s3 = peg$parseheader_value(); + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseheader_value() { + var s0, s1; + s0 = []; + s1 = peg$parseTEXT_UTF8char(); + if (s1 === peg$FAILED) { + s1 = peg$parseUTF8_CONT(); + if (s1 === peg$FAILED) { + s1 = peg$parseLWS(); + } + } + while (s1 !== peg$FAILED) { + s0.push(s1); + s1 = peg$parseTEXT_UTF8char(); + if (s1 === peg$FAILED) { + s1 = peg$parseUTF8_CONT(); + if (s1 === peg$FAILED) { + s1 = peg$parseLWS(); + } + } + } + return s0; + } + function peg$parsemessage_body() { + var s0, s1; + s0 = []; + s1 = peg$parseOCTET(); + while (s1 !== peg$FAILED) { + s0.push(s1); + s1 = peg$parseOCTET(); + } + return s0; + } + function peg$parsestun_URI() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parsestun_scheme(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s2 = peg$c24; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parsestun_host_port(); + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsestun_scheme() { + var s0, s1; + s0 = peg$currPos; + if (input.substr(peg$currPos, 5).toLowerCase() === peg$c381) { + s1 = input.substr(peg$currPos, 5); + peg$currPos += 5; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c382); + } + } + if (s1 === peg$FAILED) { + if (input.substr(peg$currPos, 4).toLowerCase() === peg$c383) { + s1 = input.substr(peg$currPos, 4); + peg$currPos += 4; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c384); + } + } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c385(s1); + } + s0 = s1; + return s0; + } + function peg$parsestun_host_port() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + s1 = peg$parsestun_host(); + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s3 = peg$c24; + peg$currPos++; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s3 !== peg$FAILED) { + s4 = peg$parseport(); + if (s4 !== peg$FAILED) { + s3 = [s3, s4]; + s2 = s3; + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } + else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsestun_host() { + var s0, s1; + s0 = peg$currPos; + s1 = peg$parseIPv4address(); + if (s1 === peg$FAILED) { + s1 = peg$parseIPv6reference(); + if (s1 === peg$FAILED) { + s1 = peg$parsereg_name(); + } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c386(s1); + } + s0 = s1; + return s0; + } + function peg$parsestun_unreserved() { + var s0; + s0 = peg$parseALPHA(); + if (s0 === peg$FAILED) { + s0 = peg$parseDIGIT(); + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s0 = peg$c38; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c39); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s0 = peg$c42; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c43); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 95) { + s0 = peg$c40; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c41); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 126) { + s0 = peg$c46; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c47); + } + } + } + } + } + } + } + return s0; + } + function peg$parsesub_delims() { + var s0; + if (input.charCodeAt(peg$currPos) === 33) { + s0 = peg$c44; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c45); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 36) { + s0 = peg$c34; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c35); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 38) { + s0 = peg$c28; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c29); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 39) { + s0 = peg$c50; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c51); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 40) { + s0 = peg$c52; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c53); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s0 = peg$c54; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c55); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 42) { + s0 = peg$c48; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c49); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s0 = peg$c32; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c33); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s0 = peg$c36; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c37); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 59) { + s0 = peg$c18; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c19); + } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s0 = peg$c30; + peg$currPos++; + } + else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c31); + } + } + } + } + } + } + } + } + } + } + } + } + return s0; + } + function peg$parseturn_URI() { + var s0, s1, s2, s3, s4, s5, s6; + s0 = peg$currPos; + s1 = peg$parseturn_scheme(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s2 = peg$c24; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c25); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parsestun_host_port(); + if (s3 !== peg$FAILED) { + s4 = peg$currPos; + if (input.substr(peg$currPos, 11) === peg$c387) { + s5 = peg$c387; + peg$currPos += 11; + } + else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c388); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parsetransport(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + else { + peg$currPos = s4; + s4 = peg$FAILED; + } + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s1 = [s1, s2, s3, s4]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseturn_scheme() { + var s0, s1; + s0 = peg$currPos; + if (input.substr(peg$currPos, 5).toLowerCase() === peg$c389) { + s1 = input.substr(peg$currPos, 5); + peg$currPos += 5; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c390); + } + } + if (s1 === peg$FAILED) { + if (input.substr(peg$currPos, 4).toLowerCase() === peg$c391) { + s1 = input.substr(peg$currPos, 4); + peg$currPos += 4; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c392); + } + } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c385(s1); + } + s0 = s1; + return s0; + } + function peg$parseturn_transport() { + var s0, s1, s2; + s0 = peg$currPos; + if (input.substr(peg$currPos, 3).toLowerCase() === peg$c145) { + s1 = input.substr(peg$currPos, 3); + peg$currPos += 3; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c146); + } + } + if (s1 === peg$FAILED) { + if (input.substr(peg$currPos, 3).toLowerCase() === peg$c147) { + s1 = input.substr(peg$currPos, 3); + peg$currPos += 3; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c148); + } + } + if (s1 === peg$FAILED) { + s1 = []; + s2 = peg$parseunreserved(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseunreserved(); + } + } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c393(s1); + } + s0 = s1; + return s0; + } + function peg$parseuuid() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9; + s0 = peg$currPos; + s1 = peg$parsehex8(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s2 = peg$c38; + peg$currPos++; + } + else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c39); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parsehex4(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s4 = peg$c38; + peg$currPos++; + } + else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c39); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parsehex4(); + if (s5 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s6 = peg$c38; + peg$currPos++; + } + else { + s6 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c39); + } + } + if (s6 !== peg$FAILED) { + s7 = peg$parsehex4(); + if (s7 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s8 = peg$c38; + peg$currPos++; + } + else { + s8 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c39); + } + } + if (s8 !== peg$FAILED) { + s9 = peg$parsehex12(); + if (s9 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c394(); + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsehex4() { + var s0, s1, s2, s3, s4; + s0 = peg$currPos; + s1 = peg$parseHEXDIG(); + if (s1 !== peg$FAILED) { + s2 = peg$parseHEXDIG(); + if (s2 !== peg$FAILED) { + s3 = peg$parseHEXDIG(); + if (s3 !== peg$FAILED) { + s4 = peg$parseHEXDIG(); + if (s4 !== peg$FAILED) { + s1 = [s1, s2, s3, s4]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsehex8() { + var s0, s1, s2; + s0 = peg$currPos; + s1 = peg$parsehex4(); + if (s1 !== peg$FAILED) { + s2 = peg$parsehex4(); + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsehex12() { + var s0, s1, s2, s3; + s0 = peg$currPos; + s1 = peg$parsehex4(); + if (s1 !== peg$FAILED) { + s2 = peg$parsehex4(); + if (s2 !== peg$FAILED) { + s3 = peg$parsehex4(); + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsesipfrag() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parseRequest_Response(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseheader(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseheader(); + } + if (s2 !== peg$FAILED) { + s3 = peg$currPos; + s4 = peg$parseCRLF(); + if (s4 !== peg$FAILED) { + s5 = peg$parsemessage_body(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + else { + peg$currPos = s3; + s3 = peg$FAILED; + } + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parseReferred_By() { + var s0, s1, s2, s3, s4, s5, s6, s7; + s0 = peg$currPos; + if (input.substr(peg$currPos, 11) === peg$c395) { + s1 = peg$c395; + peg$currPos += 11; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c396); + } + } + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 98) { + s1 = peg$c397; + peg$currPos++; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c398); + } + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseHCOLON(); + if (s2 !== peg$FAILED) { + s3 = peg$parsereferrer_uri(); + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$currPos; + s6 = peg$parseSEMI(); + if (s6 !== peg$FAILED) { + s7 = peg$parsereferredby_id_param(); + if (s7 === peg$FAILED) { + s7 = peg$parsegeneric_param(); + } + if (s7 !== peg$FAILED) { + s6 = [s6, s7]; + s5 = s6; + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$currPos; + s6 = peg$parseSEMI(); + if (s6 !== peg$FAILED) { + s7 = peg$parsereferredby_id_param(); + if (s7 === peg$FAILED) { + s7 = peg$parsegeneric_param(); + } + if (s7 !== peg$FAILED) { + s6 = [s6, s7]; + s5 = s6; + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + if (s4 !== peg$FAILED) { + s1 = [s1, s2, s3, s4]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsereferrer_uri() { + var s0; + s0 = peg$parsename_addr(); + if (s0 === peg$FAILED) { + s0 = peg$parseSIP_URI_noparams(); + } + return s0; + } + function peg$parsereferredby_id_param() { + var s0, s1, s2, s3; + s0 = peg$currPos; + if (input.substr(peg$currPos, 3) === peg$c399) { + s1 = peg$c399; + peg$currPos += 3; + } + else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c400); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseEQUAL(); + if (s2 !== peg$FAILED) { + s3 = peg$parsesip_clean_msg_id(); + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + function peg$parsesip_clean_msg_id() { + var s0, s1, s2, s3, s4, s5; + s0 = peg$currPos; + s1 = peg$parseLDQUOT(); + if (s1 !== peg$FAILED) { + s2 = peg$parsemark(); + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 64) { + s3 = peg$c26; + peg$currPos++; + } + else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { + peg$fail(peg$c27); + } + } + if (s3 !== peg$FAILED) { + s4 = peg$parsemark(); + if (s4 === peg$FAILED) { + s4 = peg$parsehost(); + } + if (s4 !== peg$FAILED) { + s5 = peg$parseRDQUOT(); + if (s5 !== peg$FAILED) { + s1 = [s1, s2, s3, s4, s5]; + s0 = s1; + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + else { + peg$currPos = s0; + s0 = peg$FAILED; + } + return s0; + } + options.data = {}; // Object to which header attributes will be assigned during parsing + function list(head, tail) { + return [head].concat(tail); + } + peg$result = peg$startRuleFunction(); + if (peg$result !== peg$FAILED && peg$currPos === input.length) { + return peg$result; + } + else { + if (peg$result !== peg$FAILED && peg$currPos < input.length) { + peg$fail(peg$endExpectation()); + } + throw peg$buildStructuredError(peg$maxFailExpected, peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null, peg$maxFailPos < input.length + ? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1) + : peg$computeLocation(peg$maxFailPos, peg$maxFailPos)); + } +} +exports.parse = peg$parse; diff --git a/lib/LoggerFactory.d.ts b/lib/LoggerFactory.d.ts new file mode 100644 index 000000000..89f706b5a --- /dev/null +++ b/lib/LoggerFactory.d.ts @@ -0,0 +1,33 @@ +import { TypeStrings } from "./Enums"; +export declare enum Levels { + error = 0, + warn = 1, + log = 2, + debug = 3 +} +export declare class LoggerFactory { + type: TypeStrings; + builtinEnabled: boolean; + private _level; + private _connector; + private loggers; + private logger; + constructor(); + level: Levels; + connector: ((level: string, category: string, label: string | undefined, content: any) => void) | undefined; + getLogger(category: string, label?: string): Logger; + genericLog(levelToLog: Levels, category: string, label: string | undefined, content: any): void; + private print; +} +export declare class Logger { + type: TypeStrings; + private logger; + private category; + private label; + constructor(logger: LoggerFactory, category: string, label?: string); + error(content: string): void; + warn(content: string): void; + log(content: string): void; + debug(content: string): void; + private genericLog; +} diff --git a/lib/LoggerFactory.js b/lib/LoggerFactory.js new file mode 100644 index 000000000..bef540f74 --- /dev/null +++ b/lib/LoggerFactory.js @@ -0,0 +1,129 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var Enums_1 = require("./Enums"); +var Levels; +(function (Levels) { + Levels[Levels["error"] = 0] = "error"; + Levels[Levels["warn"] = 1] = "warn"; + Levels[Levels["log"] = 2] = "log"; + Levels[Levels["debug"] = 3] = "debug"; +})(Levels = exports.Levels || (exports.Levels = {})); +var LoggerFactory = /** @class */ (function () { + function LoggerFactory() { + this.builtinEnabled = true; + // tslint:disable-next-line:variable-name + this._level = Levels.log; + this.loggers = {}; + this.type = Enums_1.TypeStrings.LoggerFactory; + this.logger = this.getLogger("sip:loggerfactory"); + } + Object.defineProperty(LoggerFactory.prototype, "level", { + get: function () { return this._level; }, + set: function (newLevel) { + if (newLevel >= 0 && newLevel <= 3) { + this._level = newLevel; + } + else if (newLevel > 3) { + this._level = 3; + } + else if (Levels.hasOwnProperty(newLevel)) { + this._level = newLevel; + } + else { + this.logger.error("invalid 'level' parameter value: " + JSON.stringify(newLevel)); + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(LoggerFactory.prototype, "connector", { + get: function () { + return this._connector; + }, + set: function (value) { + if (!value) { + this._connector = undefined; + } + else if (typeof value === "function") { + this._connector = value; + } + else { + this.logger.error("invalid 'connector' parameter value: " + JSON.stringify(value)); + } + }, + enumerable: true, + configurable: true + }); + LoggerFactory.prototype.getLogger = function (category, label) { + if (label && this.level === 3) { + return new Logger(this, category, label); + } + else if (this.loggers[category]) { + return this.loggers[category]; + } + else { + var logger = new Logger(this, category); + this.loggers[category] = logger; + return logger; + } + }; + LoggerFactory.prototype.genericLog = function (levelToLog, category, label, content) { + if (this.level >= levelToLog) { + if (this.builtinEnabled) { + this.print(levelToLog, category, label, content); + } + } + if (this.connector) { + this.connector(Levels[levelToLog], category, label, content); + } + }; + LoggerFactory.prototype.print = function (levelToLog, category, label, content) { + if (typeof content === "string") { + var prefix = [new Date(), category]; + if (label) { + prefix.push(label); + } + content = prefix.concat(content).join(" | "); + } + switch (levelToLog) { + case Levels.error: + // tslint:disable-next-line:no-console + console.error(content); + break; + case Levels.warn: + // tslint:disable-next-line:no-console + console.warn(content); + break; + case Levels.log: + // tslint:disable-next-line:no-console + console.log(content); + break; + case Levels.debug: + // tslint:disable-next-line:no-console + console.debug(content); + break; + default: + break; + } + }; + return LoggerFactory; +}()); +exports.LoggerFactory = LoggerFactory; +// tslint:disable-next-line:max-classes-per-file +var Logger = /** @class */ (function () { + function Logger(logger, category, label) { + this.type = Enums_1.TypeStrings.Logger; + this.logger = logger; + this.category = category; + this.label = label; + } + Logger.prototype.error = function (content) { this.genericLog(Levels.error, content); }; + Logger.prototype.warn = function (content) { this.genericLog(Levels.warn, content); }; + Logger.prototype.log = function (content) { this.genericLog(Levels.log, content); }; + Logger.prototype.debug = function (content) { this.genericLog(Levels.debug, content); }; + Logger.prototype.genericLog = function (level, content) { + this.logger.genericLog(level, this.category, this.label, content); + }; + return Logger; +}()); +exports.Logger = Logger; diff --git a/lib/NameAddrHeader.d.ts b/lib/NameAddrHeader.d.ts new file mode 100644 index 000000000..bc3f0e1c3 --- /dev/null +++ b/lib/NameAddrHeader.d.ts @@ -0,0 +1,23 @@ +import { TypeStrings } from "./Enums"; +import { Parameters, URI } from "./URI"; +/** + * @class Class creating a Name Address SIP header. + * + * @param {SIP.URI} uri + * @param {String} [displayName] + * @param {Object} [parameters] + * + */ +export declare class NameAddrHeader extends Parameters { + type: TypeStrings; + uri: URI; + private _displayName; + constructor(uri: URI, displayName: string, parameters: Array<{ + key: string; + value: string; + }>); + readonly friendlyName: string; + displayName: string; + clone(): NameAddrHeader; + toString(): string; +} diff --git a/lib/NameAddrHeader.js b/lib/NameAddrHeader.js new file mode 100644 index 000000000..2db5f76af --- /dev/null +++ b/lib/NameAddrHeader.js @@ -0,0 +1,72 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Enums_1 = require("./Enums"); +var URI_1 = require("./URI"); +/** + * @class Class creating a Name Address SIP header. + * + * @param {SIP.URI} uri + * @param {String} [displayName] + * @param {Object} [parameters] + * + */ +var NameAddrHeader = /** @class */ (function (_super) { + __extends(NameAddrHeader, _super); + function NameAddrHeader(uri, displayName, parameters) { + var _this = _super.call(this, parameters) || this; + _this.type = Enums_1.TypeStrings.NameAddrHeader; + // Checks + if (!uri || !(uri.type === Enums_1.TypeStrings.URI)) { + throw new TypeError('missing or invalid "uri" parameter'); + } + _this.uri = uri; + _this._displayName = displayName; + return _this; + } + Object.defineProperty(NameAddrHeader.prototype, "friendlyName", { + get: function () { + return this.displayName || this.uri.aor; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(NameAddrHeader.prototype, "displayName", { + get: function () { return this._displayName; }, + set: function (value) { + this._displayName = value; + }, + enumerable: true, + configurable: true + }); + NameAddrHeader.prototype.clone = function () { + return new NameAddrHeader(this.uri.clone(), this._displayName, JSON.parse(JSON.stringify(this.parameters))); + }; + NameAddrHeader.prototype.toString = function () { + var body = (this.displayName || this.displayName === "0") ? '"' + this.displayName + '" ' : ""; + body += "<" + this.uri.toString() + ">"; + for (var parameter in this.parameters) { + if (this.parameters.hasOwnProperty(parameter)) { + body += ";" + parameter; + if (this.parameters[parameter] !== null) { + body += "=" + this.parameters[parameter]; + } + } + } + return body; + }; + return NameAddrHeader; +}(URI_1.Parameters)); +exports.NameAddrHeader = NameAddrHeader; diff --git a/lib/Parser.d.ts b/lib/Parser.d.ts new file mode 100644 index 000000000..7debc792a --- /dev/null +++ b/lib/Parser.d.ts @@ -0,0 +1,19 @@ +import { IncomingRequest, IncomingResponse } from "./SIPMessage"; +import { UA } from "./UA"; +/** + * Extract and parse every header of a SIP message. + * @namespace + */ +export declare namespace Parser { + function getHeader(data: any, headerStart: number): number; + function parseHeader(message: IncomingRequest | IncomingResponse, data: any, headerStart: number, headerEnd: number): boolean | { + error: string; + }; + /** Parse SIP Message + * @function + * @param {String} message SIP message. + * @param {Object} logger object. + * @returns {SIP.IncomingRequest|SIP.IncomingResponse|undefined} + */ + function parseMessage(data: string, ua: UA): IncomingRequest | IncomingResponse | undefined; +} diff --git a/lib/Parser.js b/lib/Parser.js new file mode 100644 index 000000000..f3b8ee4a7 --- /dev/null +++ b/lib/Parser.js @@ -0,0 +1,245 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var Enums_1 = require("./Enums"); +var Grammar_1 = require("./Grammar"); +var SIPMessage_1 = require("./SIPMessage"); +// SIP.Parser = Parser; +/** + * Extract and parse every header of a SIP message. + * @namespace + */ +var Parser; +(function (Parser) { + function getHeader(data, headerStart) { + // 'start' position of the header. + var start = headerStart; + // 'end' position of the header. + var end = 0; + // 'partial end' position of the header. + var partialEnd = 0; + // End of message. + if (data.substring(start, start + 2).match(/(^\r\n)/)) { + return -2; + } + while (end === 0) { + // Partial End of Header. + partialEnd = data.indexOf("\r\n", start); + // 'indexOf' returns -1 if the value to be found never occurs. + if (partialEnd === -1) { + return partialEnd; + } + if (!data.substring(partialEnd + 2, partialEnd + 4).match(/(^\r\n)/) && + data.charAt(partialEnd + 2).match(/(^\s+)/)) { + // Not the end of the message. Continue from the next position. + start = partialEnd + 2; + } + else { + end = partialEnd; + } + } + return end; + } + Parser.getHeader = getHeader; + function parseHeader(message, data, headerStart, headerEnd) { + var hcolonIndex = data.indexOf(":", headerStart); + var headerName = data.substring(headerStart, hcolonIndex).trim(); + var headerValue = data.substring(hcolonIndex + 1, headerEnd).trim(); + var parsed; + // If header-field is well-known, parse it. + switch (headerName.toLowerCase()) { + case "via": + case "v": + message.addHeader("via", headerValue); + if (message.getHeaders("via").length === 1) { + parsed = message.parseHeader("Via"); + if (parsed) { + message.via = parsed; + message.viaBranch = parsed.branch; + } + } + else { + parsed = 0; + } + break; + case "from": + case "f": + message.setHeader("from", headerValue); + parsed = message.parseHeader("from"); + if (parsed) { + message.from = parsed; + message.fromTag = parsed.getParam("tag"); + } + break; + case "to": + case "t": + message.setHeader("to", headerValue); + parsed = message.parseHeader("to"); + if (parsed) { + message.to = parsed; + message.toTag = parsed.getParam("tag"); + } + break; + case "record-route": + parsed = Grammar_1.Grammar.parse(headerValue, "Record_Route"); + if (parsed === -1) { + parsed = undefined; + break; + } + for (var header in parsed) { + if (parsed[header]) { + message.addHeader("record-route", headerValue.substring(parsed[header].position, parsed[header].offset)); + message.headers["Record-Route"][message.getHeaders("record-route").length - 1].parsed = + parsed[header].parsed; + } + } + break; + case "call-id": + case "i": + message.setHeader("call-id", headerValue); + parsed = message.parseHeader("call-id"); + if (parsed) { + message.callId = headerValue; + } + break; + case "contact": + case "m": + parsed = Grammar_1.Grammar.parse(headerValue, "Contact"); + if (parsed === -1) { + parsed = undefined; + break; + } + if (!(parsed instanceof Array)) { + parsed = undefined; + break; + } + parsed.forEach(function (header) { + message.addHeader("contact", headerValue.substring(header.position, header.offset)); + message.headers.Contact[message.getHeaders("contact").length - 1].parsed = header.parsed; + }); + break; + case "content-length": + case "l": + message.setHeader("content-length", headerValue); + parsed = message.parseHeader("content-length"); + break; + case "content-type": + case "c": + message.setHeader("content-type", headerValue); + parsed = message.parseHeader("content-type"); + break; + case "cseq": + message.setHeader("cseq", headerValue); + parsed = message.parseHeader("cseq"); + if (parsed) { + message.cseq = parsed.value; + } + if (message.type === Enums_1.TypeStrings.IncomingResponse) { + message.method = parsed.method; + } + break; + case "max-forwards": + message.setHeader("max-forwards", headerValue); + parsed = message.parseHeader("max-forwards"); + break; + case "www-authenticate": + message.setHeader("www-authenticate", headerValue); + parsed = message.parseHeader("www-authenticate"); + break; + case "proxy-authenticate": + message.setHeader("proxy-authenticate", headerValue); + parsed = message.parseHeader("proxy-authenticate"); + break; + case "refer-to": + case "r": + message.setHeader("refer-to", headerValue); + parsed = message.parseHeader("refer-to"); + if (parsed) { + message.referTo = parsed; + } + break; + default: + // Do not parse this header. + message.setHeader(headerName, headerValue); + parsed = 0; + } + if (parsed === undefined) { + return { + error: "error parsing header '" + headerName + "'" + }; + } + else { + return true; + } + } + Parser.parseHeader = parseHeader; + /** Parse SIP Message + * @function + * @param {String} message SIP message. + * @param {Object} logger object. + * @returns {SIP.IncomingRequest|SIP.IncomingResponse|undefined} + */ + function parseMessage(data, ua) { + var headerStart = 0; + var headerEnd = data.indexOf("\r\n"); + var logger = ua.getLogger("sip.parser"); + if (headerEnd === -1) { + logger.warn("no CRLF found, not a SIP message, discarded"); + return; + } + // Parse first line. Check if it is a Request or a Reply. + var firstLine = data.substring(0, headerEnd); + var parsed = Grammar_1.Grammar.parse(firstLine, "Request_Response"); + var message; + if (parsed === -1) { + logger.warn('error parsing first line of SIP message: "' + firstLine + '"'); + return; + } + else if (!parsed.status_code) { + message = new SIPMessage_1.IncomingRequest(ua); + message.method = parsed.method; + message.ruri = parsed.uri; + } + else { + message = new SIPMessage_1.IncomingResponse(ua); + message.statusCode = parsed.status_code; + message.reasonPhrase = parsed.reason_phrase; + } + message.data = data; + headerStart = headerEnd + 2; + /* Loop over every line in data. Detect the end of each header and parse + * it or simply add to the headers collection. + */ + var bodyStart; + while (true) { + headerEnd = getHeader(data, headerStart); + // The SIP message has normally finished. + if (headerEnd === -2) { + bodyStart = headerStart + 2; + break; + } + else if (headerEnd === -1) { + // data.indexOf returned -1 due to a malformed message. + logger.error("malformed message"); + return; + } + var parsedHeader = parseHeader(message, data, headerStart, headerEnd); + if (parsedHeader !== true) { + logger.error(parsed.error); + return; + } + headerStart = headerEnd + 2; + } + /* RFC3261 18.3. + * If there are additional bytes in the transport packet + * beyond the end of the body, they MUST be discarded. + */ + if (message.hasHeader("content-length")) { + message.body = data.substr(bodyStart, Number(message.getHeader("content-length"))); + } + else { + message.body = data.substring(bodyStart); + } + return message; + } + Parser.parseMessage = parseMessage; +})(Parser = exports.Parser || (exports.Parser = {})); diff --git a/lib/PublishContext.d.ts b/lib/PublishContext.d.ts new file mode 100644 index 000000000..fac5ca315 --- /dev/null +++ b/lib/PublishContext.d.ts @@ -0,0 +1,39 @@ +import { ClientContext } from "./ClientContext"; +import { TypeStrings } from "./Enums"; +import { IncomingResponse } from "./SIPMessage"; +import { UA } from "./UA"; +import { URI } from "./URI"; +/** + * SIP Publish (SIP Extension for Event State Publication RFC3903) + * @class Class creating a SIP PublishContext. + */ +export declare class PublishContext extends ClientContext { + type: TypeStrings; + private options; + private event; + private target; + private pubRequestBody; + private pubRequestExpires; + private pubRequestEtag; + private publishRefreshTimer; + constructor(ua: UA, target: string | URI, event: string, options?: any); + /** + * Publish + * @param {string} Event body to publish, optional + */ + publish(body: string): void; + /** + * Unpublish + */ + unpublish(): void; + /** + * Close + */ + close(): void; + onRequestTimeout(): void; + onTransportError(): void; + receiveResponse(response: IncomingResponse): void; + send(): this; + private refreshRequest; + private sendPublishRequest; +} diff --git a/lib/PublishContext.js b/lib/PublishContext.js new file mode 100644 index 000000000..8f00f5d07 --- /dev/null +++ b/lib/PublishContext.js @@ -0,0 +1,277 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var ClientContext_1 = require("./ClientContext"); +var Constants_1 = require("./Constants"); +var Enums_1 = require("./Enums"); +var Exceptions_1 = require("./Exceptions"); +var SIPMessage_1 = require("./SIPMessage"); +var Utils_1 = require("./Utils"); +/** + * SIP Publish (SIP Extension for Event State Publication RFC3903) + * @class Class creating a SIP PublishContext. + */ +var PublishContext = /** @class */ (function (_super) { + __extends(PublishContext, _super); + function PublishContext(ua, target, event, options) { + if (options === void 0) { options = {}; } + var _this = this; + options.extraHeaders = (options.extraHeaders || []).slice(); + options.contentType = (options.contentType || "text/plain"); + if (typeof options.expires !== "number" || (options.expires % 1) !== 0) { + options.expires = 3600; + } + else { + options.expires = Number(options.expires); + } + if (typeof (options.unpublishOnClose) !== "boolean") { + options.unpublishOnClose = true; + } + if (target === undefined || target === null || target === "") { + throw new Exceptions_1.Exceptions.MethodParameterError("Publish", "Target", target); + } + else { + target = ua.normalizeTarget(target); + if (target === undefined) { + throw new Exceptions_1.Exceptions.MethodParameterError("Publish", "Target", target); + } + } + _this = _super.call(this, ua, Constants_1.C.PUBLISH, target, options) || this; + _this.type = Enums_1.TypeStrings.PublishContext; + _this.options = options; + _this.target = target; + if (event === undefined || event === null || event === "") { + throw new Exceptions_1.Exceptions.MethodParameterError("Publish", "Event", event); + } + else { + _this.event = event; + } + _this.logger = ua.getLogger("sip.publish"); + _this.pubRequestExpires = _this.options.expires; + ua.on("transportCreated", function (transport) { + transport.on("transportError", function () { return _this.onTransportError(); }); + }); + return _this; + } + /** + * Publish + * @param {string} Event body to publish, optional + */ + PublishContext.prototype.publish = function (body) { + // Clean up before the run + if (this.publishRefreshTimer) { + clearTimeout(this.publishRefreshTimer); + this.publishRefreshTimer = undefined; + } + // is Inital or Modify request + this.options.body = body; + this.pubRequestBody = this.options.body; + if (this.pubRequestExpires === 0) { + // This is Initial request after unpublish + this.pubRequestExpires = this.options.expires; + this.pubRequestEtag = undefined; + } + if (!(this.ua.publishers[this.target.toString() + ":" + this.event])) { + this.ua.publishers[this.target.toString() + ":" + this.event] = this; + } + this.sendPublishRequest(); + }; + /** + * Unpublish + */ + PublishContext.prototype.unpublish = function () { + // Clean up before the run + if (this.publishRefreshTimer) { + clearTimeout(this.publishRefreshTimer); + this.publishRefreshTimer = undefined; + } + this.pubRequestBody = undefined; + this.pubRequestExpires = 0; + if (this.pubRequestEtag !== undefined) { + this.sendPublishRequest(); + } + }; + /** + * Close + */ + PublishContext.prototype.close = function () { + // Send unpublish, if requested + if (this.options.unpublishOnClose) { + this.unpublish(); + } + else { + if (this.publishRefreshTimer) { + clearTimeout(this.publishRefreshTimer); + this.publishRefreshTimer = undefined; + } + this.pubRequestBody = undefined; + this.pubRequestExpires = 0; + this.pubRequestEtag = undefined; + } + if (this.ua.publishers[this.target.toString() + ":" + this.event]) { + delete this.ua.publishers[this.target.toString() + ":" + this.event]; + } + }; + PublishContext.prototype.onRequestTimeout = function () { + _super.prototype.onRequestTimeout.call(this); + this.emit("unpublished", undefined, Constants_1.C.causes.REQUEST_TIMEOUT); + }; + PublishContext.prototype.onTransportError = function () { + _super.prototype.onTransportError.call(this); + this.emit("unpublished", undefined, Constants_1.C.causes.CONNECTION_ERROR); + }; + PublishContext.prototype.receiveResponse = function (response) { + var _this = this; + var statusCode = response.statusCode || 0; + var cause = Utils_1.Utils.getReasonPhrase(statusCode); + switch (true) { + case /^1[0-9]{2}$/.test(statusCode.toString()): + this.emit("progress", response, cause); + break; + case /^2[0-9]{2}$/.test(statusCode.toString()): + // Set SIP-Etag + if (response.hasHeader("SIP-ETag")) { + this.pubRequestEtag = response.getHeader("SIP-ETag"); + } + else { + this.logger.warn("SIP-ETag header missing in a 200-class response to PUBLISH"); + } + // Update Expire + if (response.hasHeader("Expires")) { + var expires = Number(response.getHeader("Expires")); + if (typeof expires === "number" && expires >= 0 && expires <= this.pubRequestExpires) { + this.pubRequestExpires = expires; + } + else { + this.logger.warn("Bad Expires header in a 200-class response to PUBLISH"); + } + } + else { + this.logger.warn("Expires header missing in a 200-class response to PUBLISH"); + } + if (this.pubRequestExpires !== 0) { + // Schedule refresh + this.publishRefreshTimer = setTimeout(function () { return _this.refreshRequest(); }, this.pubRequestExpires * 900); + this.emit("published", response, cause); + } + else { + this.emit("unpublished", response, cause); + } + break; + case /^412$/.test(statusCode.toString()): + // 412 code means no matching ETag - possibly the PUBLISH expired + // Resubmit as new request, if the current request is not a "remove" + if (this.pubRequestEtag !== undefined && this.pubRequestExpires !== 0) { + this.logger.warn("412 response to PUBLISH, recovering"); + this.pubRequestEtag = undefined; + this.emit("progress", response, cause); + this.publish(this.options.body); + } + else { + this.logger.warn("412 response to PUBLISH, recovery failed"); + this.pubRequestExpires = 0; + this.emit("failed", response, cause); + this.emit("unpublished", response, cause); + } + break; + case /^423$/.test(statusCode.toString()): + // 423 code means we need to adjust the Expires interval up + if (this.pubRequestExpires !== 0 && response.hasHeader("Min-Expires")) { + var minExpires = Number(response.getHeader("Min-Expires")); + if (typeof minExpires === "number" || minExpires > this.pubRequestExpires) { + this.logger.warn("423 code in response to PUBLISH, adjusting the Expires value and trying to recover"); + this.pubRequestExpires = minExpires; + this.emit("progress", response, cause); + this.publish(this.options.body); + } + else { + this.logger.warn("Bad 423 response Min-Expires header received for PUBLISH"); + this.pubRequestExpires = 0; + this.emit("failed", response, cause); + this.emit("unpublished", response, cause); + } + } + else { + this.logger.warn("423 response to PUBLISH, recovery failed"); + this.pubRequestExpires = 0; + this.emit("failed", response, cause); + this.emit("unpublished", response, cause); + } + break; + default: + this.pubRequestExpires = 0; + this.emit("failed", response, cause); + this.emit("unpublished", response, cause); + break; + } + // Do the cleanup + if (this.pubRequestExpires === 0) { + if (this.publishRefreshTimer) { + clearTimeout(this.publishRefreshTimer); + this.publishRefreshTimer = undefined; + } + this.pubRequestBody = undefined; + this.pubRequestEtag = undefined; + } + }; + PublishContext.prototype.send = function () { + var _this = this; + this.ua.userAgentCore.publish(this.request, { + onAccept: function (response) { return _this.receiveResponse(response.message); }, + onProgress: function (response) { return _this.receiveResponse(response.message); }, + onRedirect: function (response) { return _this.receiveResponse(response.message); }, + onReject: function (response) { return _this.receiveResponse(response.message); }, + onTrying: function (response) { return _this.receiveResponse(response.message); } + }); + return this; + }; + PublishContext.prototype.refreshRequest = function () { + // Clean up before the run + if (this.publishRefreshTimer) { + clearTimeout(this.publishRefreshTimer); + this.publishRefreshTimer = undefined; + } + // This is Refresh request + this.pubRequestBody = undefined; + if (this.pubRequestEtag === undefined) { + // Request not valid + throw new Exceptions_1.Exceptions.MethodParameterError("Publish", "Body", undefined); + } + if (this.pubRequestExpires === 0) { + // Request not valid + throw new Exceptions_1.Exceptions.MethodParameterError("Publish", "Expire", this.pubRequestExpires); + } + this.sendPublishRequest(); + }; + PublishContext.prototype.sendPublishRequest = function () { + var reqOptions = Object.create(this.options || Object.prototype); + reqOptions.extraHeaders = (this.options.extraHeaders || []).slice(); + reqOptions.extraHeaders.push("Event: " + this.event); + reqOptions.extraHeaders.push("Expires: " + this.pubRequestExpires); + if (this.pubRequestEtag !== undefined) { + reqOptions.extraHeaders.push("SIP-If-Match: " + this.pubRequestEtag); + } + this.request = new SIPMessage_1.OutgoingRequest(Constants_1.C.PUBLISH, this.target, this.ua, this.options.params, reqOptions.extraHeaders); + if (this.pubRequestBody !== undefined) { + this.request.body = { + body: this.pubRequestBody, + contentType: this.options.contentType + }; + } + this.send(); + }; + return PublishContext; +}(ClientContext_1.ClientContext)); +exports.PublishContext = PublishContext; diff --git a/lib/React/SessionDescriptionHandler.d.ts b/lib/React/SessionDescriptionHandler.d.ts new file mode 100644 index 000000000..7b4c42a15 --- /dev/null +++ b/lib/React/SessionDescriptionHandler.d.ts @@ -0,0 +1,93 @@ +/// +import { EventEmitter } from "events"; +import { TypeStrings } from "../Enums"; +import { Logger } from "../LoggerFactory"; +import { InviteClientContext, InviteServerContext } from "../Session"; +import { BodyObj, SessionDescriptionHandler as SessionDescriptionHandlerDefinition, SessionDescriptionHandlerModifiers } from "../session-description-handler"; +import { SessionDescriptionHandlerObserver } from "./SessionDescriptionHandlerObserver"; +export declare class SessionDescriptionHandler extends EventEmitter implements SessionDescriptionHandlerDefinition { + type: TypeStrings; + private options; + private logger; + private observer; + private dtmfSender; + private shouldAcquireMedia; + private CONTENT_TYPE; + private direction; + private C; + private modifiers; + private WebRTC; + private iceGatheringDeferred; + private iceGatheringTimeout; + private iceGatheringTimer; + private constraints; + private peerConnection; + constructor(logger: Logger, observer: SessionDescriptionHandlerObserver, options: any); + /** + * @param {SIP.Session} session + * @param {Object} [options] + */ + defaultFactory(session: InviteClientContext | InviteServerContext, options: any): SessionDescriptionHandler; + /** + * Destructor + */ + close(): void; + /** + * Gets the local description from the underlying media implementation + * @param {Object} [options] Options object to be used by getDescription + * @param {MediaStreamConstraints} [options.constraints] MediaStreamConstraints + * https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamConstraints + * @param {Object} [options.peerConnectionOptions] If this is set it will recreate the peer + * connection with the new options + * @param {Array} [modifiers] Array with one time use description modifiers + * @returns {Promise} Promise that resolves with the local description to be used for the session + */ + getDescription(options?: any, modifiers?: SessionDescriptionHandlerModifiers): Promise; + /** + * Check if the Session Description Handler can handle the Content-Type described by a SIP Message + * @param {String} contentType The content type that is in the SIP Message + * @returns {boolean} + */ + hasDescription(contentType: string): boolean; + /** + * The modifier that should be used when the session would like to place the call on hold + * @param {String} [sdp] The description that will be modified + * @returns {Promise} Promise that resolves with modified SDP + */ + holdModifier(description: RTCSessionDescriptionInit): Promise; + /** + * Set the remote description to the underlying media implementation + * @param {String} sessionDescription The description provided by a SIP message to be set on the media implementation + * @param {Object} [options] Options object to be used by getDescription + * @param {MediaStreamConstraints} [options.constraints] MediaStreamConstraints + * https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamConstraints + * @param {Object} [options.peerConnectionOptions] If this is set it will recreate the peer + * connection with the new options + * @param {Array} [modifiers] Array with one time use description modifiers + * @returns {Promise} Promise that resolves once the description is set + */ + setDescription(sessionDescription: string, options?: any, modifiers?: SessionDescriptionHandlerModifiers): Promise; + /** + * Send DTMF via RTP (RFC 4733) + * @param {String} tones A string containing DTMF digits + * @param {Object} [options] Options object to be used by sendDtmf + * @returns {boolean} true if DTMF send is successful, false otherwise + */ + sendDtmf(tones: string, options: any): boolean; + getDirection(): string; + private createOfferOrAnswer; + private createRTCSessionDescriptionInit; + private addDefaultIceCheckingTimeout; + private addDefaultIceServers; + private checkAndDefaultConstraints; + private hasBrowserTrackSupport; + private hasBrowserGetSenderSupport; + private initPeerConnection; + private acquire; + private hasOffer; + private isIceGatheringComplete; + private resetIceGatheringComplete; + private setDirection; + private triggerIceGatheringComplete; + private waitForIceGatheringComplete; +} diff --git a/lib/React/SessionDescriptionHandler.js b/lib/React/SessionDescriptionHandler.js new file mode 100644 index 000000000..9cccc9cb6 --- /dev/null +++ b/lib/React/SessionDescriptionHandler.js @@ -0,0 +1,648 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var events_1 = require("events"); +var react_native_webrtc_1 = require("react-native-webrtc"); +var Enums_1 = require("../Enums"); +var Exceptions_1 = require("../Exceptions"); +var Utils_1 = require("../Utils"); +var Modifiers = require("../Web/Modifiers"); +var SessionDescriptionHandlerObserver_1 = require("./SessionDescriptionHandlerObserver"); +/* SessionDescriptionHandler + * @class PeerConnection helper Class. + * @param {SIP.Session} session + * @param {Object} [options] + */ +var SessionDescriptionHandler = /** @class */ (function (_super) { + __extends(SessionDescriptionHandler, _super); + function SessionDescriptionHandler(logger, observer, options) { + var _this = _super.call(this) || this; + _this.type = Enums_1.TypeStrings.SessionDescriptionHandler; + // TODO: Validate the options + _this.options = options || {}; + _this.logger = logger; + _this.observer = observer; + _this.dtmfSender = undefined; + _this.shouldAcquireMedia = true; + _this.CONTENT_TYPE = "application/sdp"; + _this.C = { + DIRECTION: { + NULL: null, + SENDRECV: "sendrecv", + SENDONLY: "sendonly", + RECVONLY: "recvonly", + INACTIVE: "inactive" + } + }; + _this.logger.log("SessionDescriptionHandlerOptions: " + JSON.stringify(_this.options)); + _this.direction = _this.C.DIRECTION.NULL; + _this.modifiers = _this.options.modifiers || []; + if (!Array.isArray(_this.modifiers)) { + _this.modifiers = [_this.modifiers]; + } + _this.WebRTC = { + MediaStream: react_native_webrtc_1.MediaStream, + getUserMedia: react_native_webrtc_1.mediaDevices.getUserMedia, + RTCPeerConnection: react_native_webrtc_1.RTCPeerConnection + }; + _this.iceGatheringTimeout = false; + _this.initPeerConnection(_this.options.peerConnectionOptions); + _this.constraints = _this.checkAndDefaultConstraints(_this.options.constraints); + return _this; + } + /** + * @param {SIP.Session} session + * @param {Object} [options] + */ + SessionDescriptionHandler.prototype.defaultFactory = function (session, options) { + var logger = session.ua.getLogger("sip.invitecontext.sessionDescriptionHandler", session.id); + var observer = new SessionDescriptionHandlerObserver_1.SessionDescriptionHandlerObserver(session, options); + return new SessionDescriptionHandler(logger, observer, options); + }; + // Functions the sesssion can use + /** + * Destructor + */ + SessionDescriptionHandler.prototype.close = function () { + this.logger.log("closing PeerConnection"); + // have to check signalingState since this.close() gets called multiple times + if (this.peerConnection && this.peerConnection.signalingState !== "closed") { + if (this.peerConnection.getSenders) { + this.peerConnection.getSenders().forEach(function (sender) { + if (sender.track) { + sender.track.stop(); + } + }); + } + else { + this.logger.warn("Using getLocalStreams which is deprecated"); + this.peerConnection.getLocalStreams().forEach(function (stream) { + stream.getTracks().forEach(function (track) { + track.stop(); + }); + }); + } + if (this.peerConnection.getReceivers) { + this.peerConnection.getReceivers().forEach(function (receiver) { + if (receiver.track) { + receiver.track.stop(); + } + }); + } + else { + this.logger.warn("Using getRemoteStreams which is deprecated"); + this.peerConnection.getRemoteStreams().forEach(function (stream) { + stream.getTracks().forEach(function (track) { + track.stop(); + }); + }); + } + this.resetIceGatheringComplete(); + this.peerConnection.close(); + } + }; + /** + * Gets the local description from the underlying media implementation + * @param {Object} [options] Options object to be used by getDescription + * @param {MediaStreamConstraints} [options.constraints] MediaStreamConstraints + * https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamConstraints + * @param {Object} [options.peerConnectionOptions] If this is set it will recreate the peer + * connection with the new options + * @param {Array} [modifiers] Array with one time use description modifiers + * @returns {Promise} Promise that resolves with the local description to be used for the session + */ + SessionDescriptionHandler.prototype.getDescription = function (options, modifiers) { + var _this = this; + if (options === void 0) { options = {}; } + if (modifiers === void 0) { modifiers = []; } + if (options.peerConnectionOptions) { + this.initPeerConnection(options.peerConnectionOptions); + } + // Merge passed constraints with saved constraints and save + var newConstraints = Object.assign({}, this.constraints, options.constraints); + newConstraints = this.checkAndDefaultConstraints(newConstraints); + if (JSON.stringify(newConstraints) !== JSON.stringify(this.constraints)) { + this.constraints = newConstraints; + this.shouldAcquireMedia = true; + } + if (!Array.isArray(modifiers)) { + modifiers = [modifiers]; + } + modifiers = modifiers.concat(this.modifiers); + return Promise.resolve().then(function () { + if (_this.shouldAcquireMedia) { + return _this.acquire(_this.constraints).then(function () { + _this.shouldAcquireMedia = false; + }); + } + }).then(function () { return _this.createOfferOrAnswer(options.RTCOfferOptions, modifiers); }) + .then(function (description) { + // Recreate offer containing the ICE Candidates + if (description.type === "offer") { + return _this.peerConnection.createOffer() + .then(function (sdp) { return _this.createRTCSessionDescriptionInit(sdp); }); + } + return description; + }).catch(function (e) { + if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { + throw e; + } + var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("createOffer failed", e); + _this.logger.error(error.toString()); + throw error; + }).then(function (description) { + if (description.sdp === undefined) { + throw new Exceptions_1.Exceptions.SessionDescriptionHandlerError("getDescription", undefined, "SDP undefined"); + } + _this.emit("getDescription", description); + return { + body: description.sdp, + contentType: _this.CONTENT_TYPE + }; + }); + }; + /** + * Check if the Session Description Handler can handle the Content-Type described by a SIP Message + * @param {String} contentType The content type that is in the SIP Message + * @returns {boolean} + */ + SessionDescriptionHandler.prototype.hasDescription = function (contentType) { + return contentType === this.CONTENT_TYPE; + }; + /** + * The modifier that should be used when the session would like to place the call on hold + * @param {String} [sdp] The description that will be modified + * @returns {Promise} Promise that resolves with modified SDP + */ + SessionDescriptionHandler.prototype.holdModifier = function (description) { + if (!description.sdp) { + return Promise.resolve(description); + } + if (!(/a=(sendrecv|sendonly|recvonly|inactive)/).test(description.sdp)) { + description.sdp = description.sdp.replace(/(m=[^\r]*\r\n)/g, "$1a=sendonly\r\n"); + } + else { + description.sdp = description.sdp.replace(/a=sendrecv\r\n/g, "a=sendonly\r\n"); + description.sdp = description.sdp.replace(/a=recvonly\r\n/g, "a=inactive\r\n"); + } + return Promise.resolve(description); + }; + /** + * Set the remote description to the underlying media implementation + * @param {String} sessionDescription The description provided by a SIP message to be set on the media implementation + * @param {Object} [options] Options object to be used by getDescription + * @param {MediaStreamConstraints} [options.constraints] MediaStreamConstraints + * https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamConstraints + * @param {Object} [options.peerConnectionOptions] If this is set it will recreate the peer + * connection with the new options + * @param {Array} [modifiers] Array with one time use description modifiers + * @returns {Promise} Promise that resolves once the description is set + */ + SessionDescriptionHandler.prototype.setDescription = function (sessionDescription, options, modifiers) { + var _this = this; + if (options === void 0) { options = {}; } + if (modifiers === void 0) { modifiers = []; } + options = options || {}; + if (options.peerConnectionOptions) { + this.initPeerConnection(options.peerConnectionOptions); + } + if (!Array.isArray(modifiers)) { + modifiers = [modifiers]; + } + modifiers = modifiers.concat(this.modifiers); + var description = { + type: this.hasOffer("local") ? "answer" : "offer", + sdp: sessionDescription + }; + return Promise.resolve().then(function () { + // Media should be acquired in getDescription unless we need to do it sooner for some reason (FF61+) + if (_this.shouldAcquireMedia && _this.options.alwaysAcquireMediaFirst) { + return _this.acquire(_this.constraints).then(function () { + _this.shouldAcquireMedia = false; + }); + } + }).then(function () { return Utils_1.Utils.reducePromises(modifiers, description); }) + .catch(function (e) { + if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { + throw e; + } + var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("setDescription", e, "The modifiers did not resolve successfully"); + _this.logger.error(error.message); + _this.emit("peerConnection-setRemoteDescriptionFailed", error); + throw error; + }).then(function (modifiedDescription) { + _this.emit("setDescription", modifiedDescription); + return _this.peerConnection.setRemoteDescription(modifiedDescription); + }).catch(function (e) { + if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { + throw e; + } + // Check the original SDP for video, and ensure that we have want to do audio fallback + if ((/^m=video.+$/gm).test(sessionDescription) && !options.disableAudioFallback) { + // Do not try to audio fallback again + options.disableAudioFallback = true; + // Remove video first, then do the other modifiers + return _this.setDescription(sessionDescription, options, [Modifiers.stripVideo].concat(modifiers)); + } + var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("setDescription", e); + if (error.error) { + _this.logger.error(error.error); + } + _this.emit("peerConnection-setRemoteDescriptionFailed", error); + throw error; + }).then(function () { + if (_this.peerConnection.getReceivers) { + _this.emit("setRemoteDescription", _this.peerConnection.getReceivers()); + } + else { + _this.emit("setRemoteDescription", _this.peerConnection.getRemoteStreams()); + } + _this.emit("confirmed", _this); + }); + }; + /** + * Send DTMF via RTP (RFC 4733) + * @param {String} tones A string containing DTMF digits + * @param {Object} [options] Options object to be used by sendDtmf + * @returns {boolean} true if DTMF send is successful, false otherwise + */ + SessionDescriptionHandler.prototype.sendDtmf = function (tones, options) { + if (!this.dtmfSender && this.hasBrowserGetSenderSupport()) { + var senders = this.peerConnection.getSenders(); + if (senders.length > 0) { + this.dtmfSender = senders[0].dtmf; + } + } + if (!this.dtmfSender && this.hasBrowserTrackSupport()) { + var streams = this.peerConnection.getLocalStreams(); + if (streams.length > 0) { + var audioTracks = streams[0].getAudioTracks(); + if (audioTracks.length > 0) { + this.dtmfSender = this.peerConnection.createDTMFSender(audioTracks[0]); + } + } + } + if (!this.dtmfSender) { + return false; + } + try { + this.dtmfSender.insertDTMF(tones, options.duration, options.interToneGap); + } + catch (e) { + if (e.type === "InvalidStateError" || e.type === "InvalidCharacterError") { + this.logger.error(e); + return false; + } + else { + throw e; + } + } + this.logger.log("DTMF sent via RTP: " + tones.toString()); + return true; + }; + SessionDescriptionHandler.prototype.getDirection = function () { + return this.direction; + }; + // Internal functions + SessionDescriptionHandler.prototype.createOfferOrAnswer = function (RTCOfferOptions, modifiers) { + var _this = this; + if (RTCOfferOptions === void 0) { RTCOfferOptions = {}; } + RTCOfferOptions = RTCOfferOptions || {}; + var methodName = this.hasOffer("remote") ? "createAnswer" : "createOffer"; + var pc = this.peerConnection; + this.logger.log(methodName); + return pc[methodName](RTCOfferOptions).catch(function (e) { + if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { + throw e; + } + var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("createOfferOrAnswer", e, "peerConnection-" + methodName + "Failed"); + _this.emit("peerConnection-" + methodName + "Failed", error); + throw error; + }).then(function (sdp) { return Utils_1.Utils.reducePromises(modifiers, _this.createRTCSessionDescriptionInit(sdp)); }) + .then(function (sdp) { + _this.resetIceGatheringComplete(); + _this.logger.log("Setting local sdp."); + _this.logger.log("sdp is " + sdp.sdp || "undefined"); + return pc.setLocalDescription(sdp); + }) + .catch(function (e) { + if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { + throw e; + } + var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("createOfferOrAnswer", e, "peerConnection-SetLocalDescriptionFailed"); + _this.emit("peerConnection-SetLocalDescriptionFailed", error); + throw error; + }).then(function () { return _this.waitForIceGatheringComplete(); }) + .then(function () { + var localDescription = _this.createRTCSessionDescriptionInit(_this.peerConnection.localDescription); + return Utils_1.Utils.reducePromises(modifiers, localDescription); + }).then(function (localDescription) { + _this.setDirection(localDescription.sdp || ""); + return localDescription; + }).catch(function (e) { + if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { + throw e; + } + var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("createOfferOrAnswer", e); + _this.logger.error(error.toString()); + throw error; + }); + }; + // Creates an RTCSessionDescriptionInit from an RTCSessionDescription + SessionDescriptionHandler.prototype.createRTCSessionDescriptionInit = function (RTCSessionDescription) { + return { + type: RTCSessionDescription.type, + sdp: RTCSessionDescription.sdp + }; + }; + SessionDescriptionHandler.prototype.addDefaultIceCheckingTimeout = function (peerConnectionOptions) { + if (peerConnectionOptions.iceCheckingTimeout === undefined) { + peerConnectionOptions.iceCheckingTimeout = 5000; + } + return peerConnectionOptions; + }; + SessionDescriptionHandler.prototype.addDefaultIceServers = function (rtcConfiguration) { + if (!rtcConfiguration.iceServers) { + rtcConfiguration.iceServers = [{ urls: "stun:stun.l.google.com:19302" }]; + } + return rtcConfiguration; + }; + SessionDescriptionHandler.prototype.checkAndDefaultConstraints = function (constraints) { + var defaultConstraints = { audio: true, video: !this.options.alwaysAcquireMediaFirst }; + constraints = constraints || defaultConstraints; + // Empty object check + if (Object.keys(constraints).length === 0 && constraints.constructor === Object) { + return defaultConstraints; + } + return constraints; + }; + SessionDescriptionHandler.prototype.hasBrowserTrackSupport = function () { + return Boolean(this.peerConnection.addTrack); + }; + SessionDescriptionHandler.prototype.hasBrowserGetSenderSupport = function () { + return Boolean(this.peerConnection.getSenders); + }; + SessionDescriptionHandler.prototype.initPeerConnection = function (options) { + var _this = this; + if (options === void 0) { options = {}; } + options = this.addDefaultIceCheckingTimeout(options); + options.rtcConfiguration = options.rtcConfiguration || {}; + options.rtcConfiguration = this.addDefaultIceServers(options.rtcConfiguration); + this.logger.log("initPeerConnection"); + if (this.peerConnection) { + this.logger.log("Already have a peer connection for this session. Tearing down."); + this.resetIceGatheringComplete(); + this.peerConnection.close(); + } + this.peerConnection = new this.WebRTC.RTCPeerConnection(options.rtcConfiguration); + this.logger.log("New peer connection created"); + if ("ontrack" in this.peerConnection) { + this.peerConnection.addEventListener("track", function (e) { + _this.logger.log("track added"); + _this.observer.trackAdded(); + _this.emit("addTrack", e); + }); + } + else { + this.logger.warn("Using onaddstream which is deprecated"); + this.peerConnection.onaddstream = function (e) { + _this.logger.log("stream added"); + _this.emit("addStream", e); + }; + } + this.peerConnection.onicecandidate = function (e) { + _this.emit("iceCandidate", e); + if (e.candidate) { + _this.logger.log("ICE candidate received: " + + (e.candidate.candidate === null ? null : e.candidate.candidate.trim())); + } + else if (e.candidate === null) { + // indicates the end of candidate gathering + _this.logger.log("ICE candidate gathering complete"); + _this.triggerIceGatheringComplete(); + } + }; + this.peerConnection.onicegatheringstatechange = function () { + _this.logger.log("RTCIceGatheringState changed: " + _this.peerConnection.iceGatheringState); + switch (_this.peerConnection.iceGatheringState) { + case "gathering": + _this.emit("iceGathering", _this); + if (!_this.iceGatheringTimer && options.iceCheckingTimeout) { + _this.iceGatheringTimeout = false; + _this.iceGatheringTimer = setTimeout(function () { + _this.logger.log("RTCIceChecking Timeout Triggered after " + options.iceCheckingTimeout + " milliseconds"); + _this.iceGatheringTimeout = true; + _this.triggerIceGatheringComplete(); + }, options.iceCheckingTimeout); + } + break; + case "complete": + _this.triggerIceGatheringComplete(); + break; + } + }; + this.peerConnection.oniceconnectionstatechange = function () { + var stateEvent; + switch (_this.peerConnection.iceConnectionState) { + case "new": + stateEvent = "iceConnection"; + break; + case "checking": + stateEvent = "iceConnectionChecking"; + break; + case "connected": + stateEvent = "iceConnectionConnected"; + break; + case "completed": + stateEvent = "iceConnectionCompleted"; + break; + case "failed": + stateEvent = "iceConnectionFailed"; + break; + case "disconnected": + stateEvent = "iceConnectionDisconnected"; + break; + case "closed": + stateEvent = "iceConnectionClosed"; + break; + default: + _this.logger.warn("Unknown iceConnection state: " + _this.peerConnection.iceConnectionState); + return; + } + _this.logger.log("ICE Connection State changed to " + stateEvent); + _this.emit(stateEvent, _this); + }; + }; + SessionDescriptionHandler.prototype.acquire = function (constraints) { + var _this = this; + // Default audio & video to true + constraints = this.checkAndDefaultConstraints(constraints); + return new Promise(function (resolve, reject) { + /* + * Make the call asynchronous, so that ICCs have a chance + * to define callbacks to `userMediaRequest` + */ + _this.logger.log("acquiring local media"); + _this.emit("userMediaRequest", constraints); + if (constraints.audio || constraints.video) { + _this.WebRTC.getUserMedia(constraints).then(function (streams) { + _this.observer.trackAdded(); + _this.emit("userMedia", streams); + resolve(streams); + }).catch(function (e) { + _this.emit("userMediaFailed", e); + reject(e); + }); + } + else { + // Local streams were explicitly excluded. + resolve([]); + } + }).catch(function (e) { + if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { + throw e; + } + var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("acquire", e, "unable to acquire streams"); + _this.logger.error(error.message); + if (error.error) { + _this.logger.error(error.error); + } + throw error; + }).then(function (streams) { + _this.logger.log("acquired local media streams"); + try { + // Remove old tracks + if (_this.peerConnection.removeTrack) { + _this.peerConnection.getSenders().forEach(function (sender) { + _this.peerConnection.removeTrack(sender); + }); + } + return streams; + } + catch (e) { + return Promise.reject(e); + } + }) + .catch(function (e) { + if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { + throw e; + } + var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("acquire", e, "error removing streams"); + _this.logger.error(error.message); + if (error.error) { + _this.logger.error(error.error); + } + throw error; + }).then(function (streams) { + try { + streams = [].concat(streams); + streams.forEach(function (stream) { + if (_this.peerConnection.addTrack) { + stream.getTracks().forEach(function (track) { + _this.peerConnection.addTrack(track, stream); + }); + } + else { + // Chrome 59 does not support addTrack + _this.peerConnection.addStream(stream); + } + }); + } + catch (e) { + return Promise.reject(e); + } + return Promise.resolve(); + }) + .catch(function (e) { + if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { + throw e; + } + var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("acquire", e, "error adding stream"); + _this.logger.error(error.message); + if (error.error) { + _this.logger.error(error.error); + } + throw error; + }); + }; + SessionDescriptionHandler.prototype.hasOffer = function (where) { + var offerState = "have-" + where + "-offer"; + return this.peerConnection.signalingState === offerState; + }; + // ICE gathering state handling + SessionDescriptionHandler.prototype.isIceGatheringComplete = function () { + return this.peerConnection.iceGatheringState === "complete" || this.iceGatheringTimeout; + }; + SessionDescriptionHandler.prototype.resetIceGatheringComplete = function () { + this.iceGatheringTimeout = false; + this.logger.log("resetIceGatheringComplete"); + if (this.iceGatheringTimer) { + clearTimeout(this.iceGatheringTimer); + this.iceGatheringTimer = undefined; + } + if (this.iceGatheringDeferred) { + this.iceGatheringDeferred.reject(); + this.iceGatheringDeferred = undefined; + } + }; + SessionDescriptionHandler.prototype.setDirection = function (sdp) { + var match = sdp.match(/a=(sendrecv|sendonly|recvonly|inactive)/); + if (match === null) { + this.direction = this.C.DIRECTION.NULL; + this.observer.directionChanged(); + return; + } + var direction = match[1]; + switch (direction) { + case this.C.DIRECTION.SENDRECV: + case this.C.DIRECTION.SENDONLY: + case this.C.DIRECTION.RECVONLY: + case this.C.DIRECTION.INACTIVE: + this.direction = direction; + break; + default: + this.direction = this.C.DIRECTION.NULL; + break; + } + this.observer.directionChanged(); + }; + SessionDescriptionHandler.prototype.triggerIceGatheringComplete = function () { + if (this.isIceGatheringComplete()) { + this.emit("iceGatheringComplete", this); + if (this.iceGatheringTimer) { + clearTimeout(this.iceGatheringTimer); + this.iceGatheringTimer = undefined; + } + if (this.iceGatheringDeferred) { + this.iceGatheringDeferred.resolve(); + this.iceGatheringDeferred = undefined; + } + } + }; + SessionDescriptionHandler.prototype.waitForIceGatheringComplete = function () { + this.logger.log("waitForIceGatheringComplete"); + if (this.isIceGatheringComplete()) { + this.logger.log("ICE is already complete. Return resolved."); + return Promise.resolve(); + } + else if (!this.iceGatheringDeferred) { + this.iceGatheringDeferred = Utils_1.Utils.defer(); + } + this.logger.log("ICE is not complete. Returning promise"); + return this.iceGatheringDeferred ? this.iceGatheringDeferred.promise : Promise.resolve(); + }; + return SessionDescriptionHandler; +}(events_1.EventEmitter)); +exports.SessionDescriptionHandler = SessionDescriptionHandler; diff --git a/lib/React/SessionDescriptionHandlerObserver.d.ts b/lib/React/SessionDescriptionHandlerObserver.d.ts new file mode 100644 index 000000000..24b5b8187 --- /dev/null +++ b/lib/React/SessionDescriptionHandlerObserver.d.ts @@ -0,0 +1,11 @@ +import { TypeStrings } from "../Enums"; +import { InviteClientContext, InviteServerContext } from "../Session"; +import { SessionDescriptionHandlerObserver as SessionDescriptionHandlerObserverDefinition } from "../session-description-handler-observer"; +export declare class SessionDescriptionHandlerObserver implements SessionDescriptionHandlerObserverDefinition { + type: TypeStrings; + private session; + private options; + constructor(session: InviteClientContext | InviteServerContext, options: any); + trackAdded(): void; + directionChanged(): void; +} diff --git a/lib/React/SessionDescriptionHandlerObserver.js b/lib/React/SessionDescriptionHandlerObserver.js new file mode 100644 index 000000000..d410c8968 --- /dev/null +++ b/lib/React/SessionDescriptionHandlerObserver.js @@ -0,0 +1,23 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var Enums_1 = require("../Enums"); +/* SessionDescriptionHandlerObserver + * @class SessionDescriptionHandler Observer Class. + * @param {SIP.Session} session + * @param {Object} [options] + */ +var SessionDescriptionHandlerObserver = /** @class */ (function () { + function SessionDescriptionHandlerObserver(session, options) { + this.type = Enums_1.TypeStrings.SessionDescriptionHandlerObserver; + this.session = session; + this.options = options; + } + SessionDescriptionHandlerObserver.prototype.trackAdded = function () { + this.session.emit("trackAdded"); + }; + SessionDescriptionHandlerObserver.prototype.directionChanged = function () { + this.session.emit("directionChanged"); + }; + return SessionDescriptionHandlerObserver; +}()); +exports.SessionDescriptionHandlerObserver = SessionDescriptionHandlerObserver; diff --git a/lib/ReferContext.d.ts b/lib/ReferContext.d.ts new file mode 100644 index 000000000..790f73b8f --- /dev/null +++ b/lib/ReferContext.d.ts @@ -0,0 +1,59 @@ +import { ClientContext } from "./ClientContext"; +import { IncomingRequest } from "./Core/messages"; +import { Session } from "./Core/session"; +import { SessionStatus, TypeStrings } from "./Enums"; +import { NameAddrHeader } from "./NameAddrHeader"; +import { ServerContext } from "./ServerContext"; +import { InviteClientContext, InviteServerContext } from "./Session"; +import { SessionDescriptionHandlerModifiers } from "./session-description-handler"; +import { UA } from "./UA"; +import { URI } from "./URI"; +export declare namespace ReferServerContext { + interface AcceptOptions { + /** If true, accept REFER request and automatically attempt to follow it. */ + followRefer?: boolean; + /** If followRefer is true, options to following INVITE request. */ + inviteOptions?: InviteClientContext.Options; + } + interface RejectOptions { + } +} +export declare class ReferClientContext extends ClientContext { + type: TypeStrings; + protected extraHeaders: Array; + protected options: any; + protected applicant: InviteClientContext | InviteServerContext; + protected target: URI | string; + private errorListener; + constructor(ua: UA, applicant: InviteClientContext | InviteServerContext, target: InviteClientContext | InviteServerContext | string, options?: any); + refer(options?: any): ReferClientContext; + receiveNotify(request: IncomingRequest): void; + protected initReferTo(target: InviteClientContext | InviteServerContext | string): string | URI; +} +export declare class ReferServerContext extends ServerContext { + private session?; + type: TypeStrings; + referTo: NameAddrHeader; + targetSession: InviteClientContext | InviteServerContext | undefined; + protected status: SessionStatus; + protected fromTag: string; + protected fromUri: URI; + protected toUri: URI; + protected toTag: string; + protected routeSet: Array; + protected remoteTarget: URI; + protected id: string; + protected callId: string; + protected cseq: number; + protected contact: string; + protected referredBy: string | undefined; + protected referredSession: InviteClientContext | InviteServerContext | undefined; + protected replaces: string | undefined; + protected errorListener: (() => void); + constructor(ua: UA, incomingRequest: IncomingRequest, session?: Session | undefined); + progress(): void; + reject(options?: ReferServerContext.RejectOptions): void; + accept(options?: ReferServerContext.AcceptOptions, modifiers?: SessionDescriptionHandlerModifiers): void; + sendNotify(body: string): void; + on(name: "referAccepted" | "referInviteSent" | "referProgress" | "referRejected" | "referRequestAccepted" | "referRequestRejected", callback: (referServerContext: ReferServerContext) => void): this; +} diff --git a/lib/ReferContext.js b/lib/ReferContext.js new file mode 100644 index 000000000..23259c055 --- /dev/null +++ b/lib/ReferContext.js @@ -0,0 +1,359 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var ClientContext_1 = require("./ClientContext"); +var Constants_1 = require("./Constants"); +var transactions_1 = require("./Core/transactions"); +var Enums_1 = require("./Enums"); +var Exceptions_1 = require("./Exceptions"); +var Grammar_1 = require("./Grammar"); +var ServerContext_1 = require("./ServerContext"); +var SIPMessage_1 = require("./SIPMessage"); +// tslint:disable-next-line:max-classes-per-file +var ReferClientContext = /** @class */ (function (_super) { + __extends(ReferClientContext, _super); + function ReferClientContext(ua, applicant, target, options) { + if (options === void 0) { options = {}; } + var _this = this; + if (ua === undefined || applicant === undefined || target === undefined) { + throw new TypeError("Not enough arguments"); + } + _this = _super.call(this, ua, Constants_1.C.REFER, applicant.remoteIdentity.uri.toString(), options) || this; + _this.type = Enums_1.TypeStrings.ReferClientContext; + _this.options = options; + _this.extraHeaders = (_this.options.extraHeaders || []).slice(); + _this.applicant = applicant; + _this.target = _this.initReferTo(target); + if (_this.ua) { + _this.extraHeaders.push("Referred-By: <" + _this.ua.configuration.uri + ">"); + } + // TODO: Check that this is correct isc/icc + _this.extraHeaders.push("Contact: " + applicant.contact); + // this is UA.C.ALLOWED_METHODS, removed to get around circular dependency + _this.extraHeaders.push("Allow: " + [ + "ACK", + "CANCEL", + "INVITE", + "MESSAGE", + "BYE", + "OPTIONS", + "INFO", + "NOTIFY", + "REFER" + ].toString()); + _this.extraHeaders.push("Refer-To: " + _this.target); + _this.errorListener = _this.onTransportError.bind(_this); + if (ua.transport) { + ua.transport.on("transportError", _this.errorListener); + } + return _this; + } + ReferClientContext.prototype.refer = function (options) { + var _this = this; + if (options === void 0) { options = {}; } + var extraHeaders = (this.extraHeaders || []).slice(); + if (options.extraHeaders) { + extraHeaders.concat(options.extraHeaders); + } + this.applicant.sendRequest(Constants_1.C.REFER, { + extraHeaders: this.extraHeaders, + receiveResponse: function (response) { + var statusCode = response && response.statusCode ? response.statusCode.toString() : ""; + if (/^1[0-9]{2}$/.test(statusCode)) { + _this.emit("referRequestProgress", _this); + } + else if (/^2[0-9]{2}$/.test(statusCode)) { + _this.emit("referRequestAccepted", _this); + } + else if (/^[4-6][0-9]{2}$/.test(statusCode)) { + _this.emit("referRequestRejected", _this); + } + if (options.receiveResponse) { + options.receiveResponse(response); + } + } + }); + return this; + }; + ReferClientContext.prototype.receiveNotify = function (request) { + // If we can correctly handle this, then we need to send a 200 OK! + var contentType = request.message.hasHeader("Content-Type") ? + request.message.getHeader("Content-Type") : undefined; + if (contentType && contentType.search(/^message\/sipfrag/) !== -1) { + var messageBody = Grammar_1.Grammar.parse(request.message.body, "sipfrag"); + if (messageBody === -1) { + request.reject({ + statusCode: 489, + reasonPhrase: "Bad Event" + }); + return; + } + switch (true) { + case (/^1[0-9]{2}$/.test(messageBody.status_code)): + this.emit("referProgress", this); + break; + case (/^2[0-9]{2}$/.test(messageBody.status_code)): + this.emit("referAccepted", this); + if (!this.options.activeAfterTransfer && this.applicant.terminate) { + this.applicant.terminate(); + } + break; + default: + this.emit("referRejected", this); + break; + } + request.accept(); + this.emit("notify", request.message); + return; + } + request.reject({ + statusCode: 489, + reasonPhrase: "Bad Event" + }); + }; + ReferClientContext.prototype.initReferTo = function (target) { + var stringOrURI; + if (typeof target === "string") { + // REFER without Replaces (Blind Transfer) + var targetString = Grammar_1.Grammar.parse(target, "Refer_To"); + stringOrURI = targetString && targetString.uri ? targetString.uri : target; + // Check target validity + var targetUri = this.ua.normalizeTarget(target); + if (!targetUri) { + throw new TypeError("Invalid target: " + target); + } + stringOrURI = targetUri; + } + else { + // REFER with Replaces (Attended Transfer) + if (!target.session) { + throw new Error("Session undefined."); + } + var displayName = target.remoteIdentity.friendlyName; + var remoteTarget = target.session.remoteTarget.toString(); + var callId = target.session.callId; + var remoteTag = target.session.remoteTag; + var localTag = target.session.localTag; + var replaces = encodeURIComponent(callId + ";to-tag=" + remoteTag + ";from-tag=" + localTag); + stringOrURI = "\"" + displayName + "\" <" + remoteTarget + "?Replaces=" + replaces + ">"; + } + return stringOrURI; + }; + return ReferClientContext; +}(ClientContext_1.ClientContext)); +exports.ReferClientContext = ReferClientContext; +// tslint:disable-next-line:max-classes-per-file +var ReferServerContext = /** @class */ (function (_super) { + __extends(ReferServerContext, _super); + function ReferServerContext(ua, incomingRequest, session) { + var _this = _super.call(this, ua, incomingRequest) || this; + _this.session = session; + _this.type = Enums_1.TypeStrings.ReferServerContext; + _this.ua = ua; + _this.status = Enums_1.SessionStatus.STATUS_INVITE_RECEIVED; + _this.fromTag = _this.request.fromTag; + _this.id = _this.request.callId + _this.fromTag; + _this.contact = _this.ua.contact.toString(); + _this.logger = ua.getLogger("sip.referservercontext", _this.id); + // Needed to send the NOTIFY's + _this.cseq = Math.floor(Math.random() * 10000); + _this.callId = _this.request.callId; + _this.fromUri = _this.request.to.uri; + _this.fromTag = _this.request.to.parameters.tag; + _this.remoteTarget = _this.request.headers.Contact[0].parsed.uri; + _this.toUri = _this.request.from.uri; + _this.toTag = _this.request.fromTag; + _this.routeSet = _this.request.getHeaders("record-route"); + // RFC 3515 2.4.1 + if (!_this.request.hasHeader("refer-to")) { + _this.logger.warn("Invalid REFER packet. A refer-to header is required. Rejecting refer."); + _this.reject(); + return _this; + } + _this.referTo = _this.request.parseHeader("refer-to"); + // TODO: Must set expiration timer and send 202 if there is no response by then + _this.referredSession = _this.ua.findSession(_this.request); + if (_this.request.hasHeader("referred-by")) { + _this.referredBy = _this.request.getHeader("referred-by"); + } + if (_this.referTo.uri.hasHeader("replaces")) { + _this.replaces = _this.referTo.uri.getHeader("replaces"); + } + _this.errorListener = _this.onTransportError.bind(_this); + if (ua.transport) { + ua.transport.on("transportError", _this.errorListener); + } + _this.status = Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER; + return _this; + } + ReferServerContext.prototype.progress = function () { + if (this.status !== Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER) { + throw new Exceptions_1.Exceptions.InvalidStateError(this.status); + } + this.incomingRequest.trying(); + }; + ReferServerContext.prototype.reject = function (options) { + if (options === void 0) { options = {}; } + if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { + throw new Exceptions_1.Exceptions.InvalidStateError(this.status); + } + this.logger.log("Rejecting refer"); + this.status = Enums_1.SessionStatus.STATUS_TERMINATED; + _super.prototype.reject.call(this, options); + this.emit("referRequestRejected", this); + }; + ReferServerContext.prototype.accept = function (options, modifiers) { + var _this = this; + if (options === void 0) { options = {}; } + if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER) { + this.status = Enums_1.SessionStatus.STATUS_ANSWERED; + } + else { + throw new Exceptions_1.Exceptions.InvalidStateError(this.status); + } + this.incomingRequest.accept({ + statusCode: 202, + reasonPhrase: "Accepted" + }); + this.emit("referRequestAccepted", this); + if (options.followRefer) { + this.logger.log("Accepted refer, attempting to automatically follow it"); + var target = this.referTo.uri; + if (!target.scheme || !target.scheme.match("^sips?$")) { + this.logger.error("SIP.js can only automatically follow SIP refer target"); + this.reject(); + return; + } + var inviteOptions = options.inviteOptions || {}; + var extraHeaders = (inviteOptions.extraHeaders || []).slice(); + if (this.replaces) { + // decodeURIComponent is a holdover from 2c086eb4. Not sure that it is actually necessary + extraHeaders.push("Replaces: " + decodeURIComponent(this.replaces)); + } + if (this.referredBy) { + extraHeaders.push("Referred-By: " + this.referredBy); + } + inviteOptions.extraHeaders = extraHeaders; + target.clearHeaders(); + this.targetSession = this.ua.invite(target.toString(), inviteOptions, modifiers); + this.emit("referInviteSent", this); + if (this.targetSession) { + this.targetSession.once("progress", function (response) { + var statusCode = response.statusCode || 100; + var reasonPhrase = response.reasonPhrase; + _this.sendNotify(("SIP/2.0 " + statusCode + " " + reasonPhrase).trim()); + _this.emit("referProgress", _this); + if (_this.referredSession) { + _this.referredSession.emit("referProgress", _this); + } + }); + this.targetSession.once("accepted", function () { + _this.logger.log("Successfully followed the refer"); + _this.sendNotify("SIP/2.0 200 OK"); + _this.emit("referAccepted", _this); + if (_this.referredSession) { + _this.referredSession.emit("referAccepted", _this); + } + }); + var referFailed = function (response) { + if (_this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { + return; // No throw here because it is possible this gets called multiple times + } + _this.logger.log("Refer was not successful. Resuming session"); + if (response && response.statusCode === 429) { + _this.logger.log("Alerting referrer that identity is required."); + _this.sendNotify("SIP/2.0 429 Provide Referrer Identity"); + return; + } + _this.sendNotify("SIP/2.0 603 Declined"); + // Must change the status after sending the final Notify or it will not send due to check + _this.status = Enums_1.SessionStatus.STATUS_TERMINATED; + _this.emit("referRejected", _this); + if (_this.referredSession) { + _this.referredSession.emit("referRejected"); + } + }; + this.targetSession.once("rejected", referFailed); + this.targetSession.once("failed", referFailed); + } + } + else { + this.logger.log("Accepted refer, but did not automatically follow it"); + this.sendNotify("SIP/2.0 200 OK"); + this.emit("referAccepted", this); + if (this.referredSession) { + this.referredSession.emit("referAccepted", this); + } + } + }; + ReferServerContext.prototype.sendNotify = function (body) { + // FIXME: Ported this. Clean it up. Session knows its state. + if (this.status !== Enums_1.SessionStatus.STATUS_ANSWERED) { + throw new Exceptions_1.Exceptions.InvalidStateError(this.status); + } + if (Grammar_1.Grammar.parse(body, "sipfrag") === -1) { + throw new Error("sipfrag body is required to send notify for refer"); + } + // NOTIFY requests sent in same dialog as in dialog REFER. + if (this.session) { + this.session.notify(undefined, { + extraHeaders: [ + "Event: refer", + "Subscription-State: terminated", + ], + body: { + contentDisposition: "render", + contentType: "message/sipfrag", + content: body + } + }); + return; + } + // The implicit subscription created by a REFER is the same as a + // subscription created with a SUBSCRIBE request. The agent issuing the + // REFER can terminate this subscription prematurely by unsubscribing + // using the mechanisms described in [2]. Terminating a subscription, + // either by explicitly unsubscribing or rejecting NOTIFY, is not an + // indication that the referenced request should be withdrawn or + // abandoned. + // https://tools.ietf.org/html/rfc3515#section-2.4.4 + // NOTIFY requests sent in new dialog for out of dialog REFER. + // FIXME: TODO: This should be done in a subscribe dialog to satisfy the above. + var request = new SIPMessage_1.OutgoingRequest(Constants_1.C.NOTIFY, this.remoteTarget, this.ua, { + cseq: this.cseq += 1, + callId: this.callId, + fromUri: this.fromUri, + fromTag: this.fromTag, + toUri: this.toUri, + toTag: this.toTag, + routeSet: this.routeSet + }, [ + "Event: refer", + "Subscription-State: terminated", + "Content-Type: message/sipfrag" + ], body); + var transport = this.ua.transport; + if (!transport) { + throw new Error("Transport undefined."); + } + var user = { + loggerFactory: this.ua.getLoggerFactory() + }; + var nic = new transactions_1.NonInviteClientTransaction(request, transport, user); + }; + ReferServerContext.prototype.on = function (name, callback) { return _super.prototype.on.call(this, name, callback); }; + return ReferServerContext; +}(ServerContext_1.ServerContext)); +exports.ReferServerContext = ReferServerContext; diff --git a/lib/RegisterContext.d.ts b/lib/RegisterContext.d.ts new file mode 100644 index 000000000..2e3986254 --- /dev/null +++ b/lib/RegisterContext.d.ts @@ -0,0 +1,39 @@ +import { ClientContext } from "./ClientContext"; +import { TypeStrings } from "./Enums"; +import { IncomingResponse } from "./SIPMessage"; +import { UA } from "./UA"; +export declare namespace RegisterContext { + interface RegistrationConfiguration { + expires?: string; + extraContactHeaderParams?: Array; + instanceId?: string; + params?: any; + regId?: number; + registrar?: string; + } +} +export declare class RegisterContext extends ClientContext { + type: TypeStrings; + registered: boolean; + private options; + private expires; + private contact; + private registrationTimer; + private registrationExpiredTimer; + private registeredBefore; + private closeHeaders; + constructor(ua: UA, options?: any); + register(options?: any): void; + close(): void; + unregister(options?: any): void; + unregistered(response?: IncomingResponse, cause?: string): void; + send(): this; + private registrationFailure; + private onTransportDisconnected; + /** + * Helper Function to generate Contact Header + * @private + * returns {String} + */ + private generateContactHeader; +} diff --git a/lib/RegisterContext.js b/lib/RegisterContext.js new file mode 100644 index 000000000..149a07137 --- /dev/null +++ b/lib/RegisterContext.js @@ -0,0 +1,436 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +var ClientContext_1 = require("./ClientContext"); +var Constants_1 = require("./Constants"); +var Enums_1 = require("./Enums"); +var Exceptions_1 = require("./Exceptions"); +var Grammar_1 = require("./Grammar"); +var Utils_1 = require("./Utils"); +/** + * Configuration load. + * @private + * returns {any} + */ +function loadConfig(configuration) { + var settings = { + expires: 600, + extraContactHeaderParams: [], + instanceId: undefined, + params: {}, + regId: undefined, + registrar: undefined, + }; + var configCheck = getConfigurationCheck(); + // Check Mandatory parameters + for (var parameter in configCheck.mandatory) { + if (!configuration.hasOwnProperty(parameter)) { + throw new Exceptions_1.Exceptions.ConfigurationError(parameter); + } + else { + var value = configuration[parameter]; + var checkedValue = configCheck.mandatory[parameter](value); + if (checkedValue !== undefined) { + settings[parameter] = checkedValue; + } + else { + throw new Exceptions_1.Exceptions.ConfigurationError(parameter, value); + } + } + } + // Check Optional parameters + for (var parameter in configCheck.optional) { + if (configuration.hasOwnProperty(parameter)) { + var value = configuration[parameter]; + // If the parameter value is an empty array, but shouldn't be, apply its default value. + if (value instanceof Array && value.length === 0) { + continue; + } + // If the parameter value is null, empty string, or undefined then apply its default value. + // If it's a number with NaN value then also apply its default value. + // NOTE: JS does not allow "value === NaN", the following does the work: + if (value === null || value === "" || value === undefined || + (typeof (value) === "number" && isNaN(value))) { + continue; + } + var checkedValue = configCheck.optional[parameter](value); + if (checkedValue !== undefined) { + settings[parameter] = checkedValue; + } + else { + throw new Exceptions_1.Exceptions.ConfigurationError(parameter, value); + } + } + } + return settings; +} +function getConfigurationCheck() { + return { + mandatory: {}, + optional: { + expires: function (expires) { + if (Utils_1.Utils.isDecimal(expires)) { + var value = Number(expires); + if (value >= 0) { + return value; + } + } + }, + extraContactHeaderParams: function (extraContactHeaderParams) { + if (extraContactHeaderParams instanceof Array) { + return extraContactHeaderParams.filter(function (contactHeaderParam) { return (typeof contactHeaderParam === "string"); }); + } + }, + instanceId: function (instanceId) { + if (typeof instanceId !== "string") { + return; + } + if ((/^uuid:/i.test(instanceId))) { + instanceId = instanceId.substr(5); + } + if (Grammar_1.Grammar.parse(instanceId, "uuid") === -1) { + return; + } + else { + return instanceId; + } + }, + params: function (params) { + if (typeof params === "object") { + return params; + } + }, + regId: function (regId) { + if (Utils_1.Utils.isDecimal(regId)) { + var value = Number(regId); + if (value >= 0) { + return value; + } + } + }, + registrar: function (registrar) { + if (typeof registrar !== "string") { + return; + } + if (!/^sip:/i.test(registrar)) { + registrar = Constants_1.C.SIP + ":" + registrar; + } + var parsed = Grammar_1.Grammar.URIParse(registrar); + if (!parsed) { + return; + } + else if (parsed.user) { + return; + } + else { + return parsed; + } + } + } + }; +} +var RegisterContext = /** @class */ (function (_super) { + __extends(RegisterContext, _super); + function RegisterContext(ua, options) { + if (options === void 0) { options = {}; } + var _this = this; + var settings = loadConfig(options); + if (settings.regId && !settings.instanceId) { + settings.instanceId = Utils_1.Utils.newUUID(); + } + else if (!settings.regId && settings.instanceId) { + settings.regId = 1; + } + settings.params.toUri = settings.params.toUri || ua.configuration.uri; + settings.params.toDisplayName = settings.params.toDisplayName || ua.configuration.displayName; + settings.params.callId = settings.params.callId || Utils_1.Utils.createRandomToken(22); + settings.params.cseq = settings.params.cseq || Math.floor(Math.random() * 10000); + /* If no 'registrarServer' is set use the 'uri' value without user portion. */ + if (!settings.registrar) { + var registrarServer = {}; + if (typeof ua.configuration.uri === "object") { + registrarServer = ua.configuration.uri.clone(); + registrarServer.user = undefined; + } + else { + registrarServer = ua.configuration.uri; + } + settings.registrar = registrarServer; + } + _this = _super.call(this, ua, Constants_1.C.REGISTER, settings.registrar, settings) || this; + _this.type = Enums_1.TypeStrings.RegisterContext; + _this.options = settings; + _this.logger = ua.getLogger("sip.registercontext"); + _this.logger.log("configuration parameters for RegisterContext after validation:"); + for (var parameter in settings) { + if (settings.hasOwnProperty(parameter)) { + _this.logger.log("· " + parameter + ": " + JSON.stringify(settings[parameter])); + } + } + // Registration expires + _this.expires = settings.expires; + // Contact header + _this.contact = ua.contact.toString(); + // Set status + _this.registered = false; + ua.on("transportCreated", function (transport) { + transport.on("disconnected", function () { return _this.onTransportDisconnected(); }); + }); + return _this; + } + RegisterContext.prototype.register = function (options) { + var _this = this; + if (options === void 0) { options = {}; } + // Handle Options + this.options = __assign({}, this.options, options); + var extraHeaders = (this.options.extraHeaders || []).slice(); + extraHeaders.push("Contact: " + this.generateContactHeader(this.expires)); + // this is UA.C.ALLOWED_METHODS, removed to get around circular dependency + extraHeaders.push("Allow: " + [ + "ACK", + "CANCEL", + "INVITE", + "MESSAGE", + "BYE", + "OPTIONS", + "INFO", + "NOTIFY", + "REFER" + ].toString()); + // Save original extraHeaders to be used in .close + this.closeHeaders = this.options.closeWithHeaders ? + (this.options.extraHeaders || []).slice() : []; + this.receiveResponse = function (response) { + // Discard responses to older REGISTER/un-REGISTER requests. + if (response.cseq !== _this.request.cseq) { + return; + } + // Clear registration timer + if (_this.registrationTimer !== undefined) { + clearTimeout(_this.registrationTimer); + _this.registrationTimer = undefined; + } + var statusCode = (response.statusCode || 0).toString(); + switch (true) { + case /^1[0-9]{2}$/.test(statusCode): + _this.emit("progress", response); + break; + case /^2[0-9]{2}$/.test(statusCode): + _this.emit("accepted", response); + var expires = void 0; + if (response.hasHeader("expires")) { + expires = Number(response.getHeader("expires")); + } + if (_this.registrationExpiredTimer !== undefined) { + clearTimeout(_this.registrationExpiredTimer); + _this.registrationExpiredTimer = undefined; + } + // Search the Contact pointing to us and update the expires value accordingly. + var contacts = response.getHeaders("contact").length; + if (!contacts) { + _this.logger.warn("no Contact header in response to REGISTER, response ignored"); + break; + } + var contact = void 0; + while (contacts--) { + contact = response.parseHeader("contact", contacts); + if (contact.uri.user === _this.ua.contact.uri.user) { + expires = contact.getParam("expires"); + break; + } + else { + contact = undefined; + } + } + if (!contact) { + _this.logger.warn("no Contact header pointing to us, response ignored"); + break; + } + if (expires === undefined) { + expires = _this.expires; + } + // Re-Register before the expiration interval has elapsed. + // For that, decrease the expires value. ie: 3 seconds + _this.registrationTimer = setTimeout(function () { + _this.registrationTimer = undefined; + _this.register(_this.options); + }, (expires * 1000) - 3000); + _this.registrationExpiredTimer = setTimeout(function () { + _this.logger.warn("registration expired"); + if (_this.registered) { + _this.unregistered(undefined, Constants_1.C.causes.EXPIRES); + } + }, expires * 1000); + // Save gruu values + if (contact.hasParam("temp-gruu")) { + _this.ua.contact.tempGruu = Grammar_1.Grammar.URIParse(contact.getParam("temp-gruu").replace(/"/g, "")); + } + if (contact.hasParam("pub-gruu")) { + _this.ua.contact.pubGruu = Grammar_1.Grammar.URIParse(contact.getParam("pub-gruu").replace(/"/g, "")); + } + _this.registered = true; + _this.emit("registered", response || undefined); + break; + // Interval too brief RFC3261 10.2.8 + case /^423$/.test(statusCode): + if (response.hasHeader("min-expires")) { + // Increase our registration interval to the suggested minimum + _this.expires = Number(response.getHeader("min-expires")); + // Attempt the registration again immediately + _this.register(_this.options); + } + else { // This response MUST contain a Min-Expires header field + _this.logger.warn("423 response received for REGISTER without Min-Expires"); + _this.registrationFailure(response, Constants_1.C.causes.SIP_FAILURE_CODE); + } + break; + default: + _this.registrationFailure(response, Utils_1.Utils.sipErrorCause(response.statusCode || 0)); + } + }; + this.onRequestTimeout = function () { + _this.registrationFailure(undefined, Constants_1.C.causes.REQUEST_TIMEOUT); + }; + this.onTransportError = function () { + _this.registrationFailure(undefined, Constants_1.C.causes.CONNECTION_ERROR); + }; + this.request.cseq++; + this.request.setHeader("cseq", this.request.cseq + " REGISTER"); + this.request.extraHeaders = extraHeaders; + this.send(); + }; + RegisterContext.prototype.close = function () { + var options = { + all: false, + extraHeaders: this.closeHeaders + }; + this.registeredBefore = this.registered; + if (this.registered) { + this.unregister(options); + } + }; + RegisterContext.prototype.unregister = function (options) { + var _this = this; + if (options === void 0) { options = {}; } + if (!this.registered && !options.all) { + this.logger.warn("Already unregistered, but sending an unregister anyways."); + } + var extraHeaders = (options.extraHeaders || []).slice(); + this.registered = false; + // Clear the registration timer. + if (this.registrationTimer !== undefined) { + clearTimeout(this.registrationTimer); + this.registrationTimer = undefined; + } + if (options.all) { + extraHeaders.push("Contact: *"); + extraHeaders.push("Expires: 0"); + } + else { + extraHeaders.push("Contact: " + this.generateContactHeader(0)); + } + this.receiveResponse = function (response) { + var statusCode = (response && response.statusCode) ? response.statusCode.toString() : ""; + switch (true) { + case /^1[0-9]{2}$/.test(statusCode): + _this.emit("progress", response); + break; + case /^2[0-9]{2}$/.test(statusCode): + _this.emit("accepted", response); + if (_this.registrationExpiredTimer !== undefined) { + clearTimeout(_this.registrationExpiredTimer); + _this.registrationExpiredTimer = undefined; + } + _this.unregistered(response); + break; + default: + _this.unregistered(response, Utils_1.Utils.sipErrorCause(response.statusCode || 0)); + } + }; + this.onRequestTimeout = function () { + // Not actually unregistered... + // this.unregistered(undefined, SIP.C.causes.REQUEST_TIMEOUT); + }; + this.request.cseq++; + this.request.setHeader("cseq", this.request.cseq + " REGISTER"); + this.request.extraHeaders = extraHeaders; + this.send(); + }; + RegisterContext.prototype.unregistered = function (response, cause) { + this.registered = false; + this.emit("unregistered", response || undefined, cause || undefined); + }; + RegisterContext.prototype.send = function () { + var _this = this; + this.ua.userAgentCore.register(this.request, { + onAccept: function (response) { return _this.receiveResponse(response.message); }, + onProgress: function (response) { return _this.receiveResponse(response.message); }, + onRedirect: function (response) { return _this.receiveResponse(response.message); }, + onReject: function (response) { return _this.receiveResponse(response.message); }, + onTrying: function (response) { return _this.receiveResponse(response.message); } + }); + return this; + }; + RegisterContext.prototype.registrationFailure = function (response, cause) { + this.emit("failed", response || undefined, cause || undefined); + }; + RegisterContext.prototype.onTransportDisconnected = function () { + this.registeredBefore = this.registered; + if (this.registrationTimer !== undefined) { + clearTimeout(this.registrationTimer); + this.registrationTimer = undefined; + } + if (this.registrationExpiredTimer !== undefined) { + clearTimeout(this.registrationExpiredTimer); + this.registrationExpiredTimer = undefined; + } + if (this.registered) { + this.unregistered(undefined, Constants_1.C.causes.CONNECTION_ERROR); + } + }; + /** + * Helper Function to generate Contact Header + * @private + * returns {String} + */ + RegisterContext.prototype.generateContactHeader = function (expires) { + if (expires === void 0) { expires = 0; } + var contact = this.contact; + if (this.options.regId && this.options.instanceId) { + contact += ";reg-id=" + this.options.regId; + contact += ';+sip.instance=""'; + } + if (this.options.extraContactHeaderParams) { + this.options.extraContactHeaderParams.forEach(function (header) { + contact += ";" + header; + }); + } + contact += ";expires=" + expires; + return contact; + }; + return RegisterContext; +}(ClientContext_1.ClientContext)); +exports.RegisterContext = RegisterContext; diff --git a/lib/SIPMessage.d.ts b/lib/SIPMessage.d.ts new file mode 100644 index 000000000..5b7266eac --- /dev/null +++ b/lib/SIPMessage.d.ts @@ -0,0 +1,182 @@ +import { TypeStrings } from "./Enums"; +import { NameAddrHeader } from "./NameAddrHeader"; +import { Transport } from "./Transport"; +import { UA } from "./UA"; +import { URI } from "./URI"; +export declare const getSupportedHeader: ((request: OutgoingRequest | IncomingRequest) => string); +/** + * @class Class for outgoing SIP request. + * @param {String} method request method + * @param {String} ruri request uri + * @param {SIP.UA} ua + * @param {Object} params parameters that will have priority over ua.configuration parameters: + *
+ * - cseq, callId, fromTag, fromUri, fromDisplayName, toUri, toTag, routeSet + * @param {Object} [headers] extra headers + * @param {String} [body] + */ +export declare class OutgoingRequest { + type: TypeStrings; + ruri: string | URI; + ua: UA; + headers: { + [name: string]: Array; + }; + method: string; + cseq: number; + body: string | { + body: string; + contentType: string; + } | undefined; + branch: string | undefined; + to: NameAddrHeader | undefined; + toTag: string | undefined; + from: NameAddrHeader | undefined; + fromTag: string; + extraHeaders: Array; + callId: string; + constructor(method: string, ruri: string | URI, ua: UA, params?: any, extraHeaders?: Array, body?: string | { + body: string; + contentType: string; + }); + /** + * Get the value of the given header name at the given position. + * @param {String} name header name + * @returns {String|undefined} Returns the specified header, undefined if header doesn't exist. + */ + getHeader(name: string): string | undefined; + /** + * Get the header/s of the given name. + * @param {String} name header name + * @returns {Array} Array with all the headers of the specified name. + */ + getHeaders(name: string): Array; + /** + * Verify the existence of the given header. + * @param {String} name header name + * @returns {boolean} true if header with given name exists, false otherwise + */ + hasHeader(name: string): boolean; + /** + * Replace the the given header by the given value. + * @param {String} name header name + * @param {String | Array} value header value + */ + setHeader(name: string, value: string | Array): void; + /** + * The Via header field indicates the transport used for the transaction + * and identifies the location where the response is to be sent. A Via + * header field value is added only after the transport that will be + * used to reach the next hop has been selected (which may involve the + * usage of the procedures in [4]). + * + * When the UAC creates a request, it MUST insert a Via into that + * request. The protocol name and protocol version in the header field + * MUST be SIP and 2.0, respectively. The Via header field value MUST + * contain a branch parameter. This parameter is used to identify the + * transaction created by that request. This parameter is used by both + * the client and the server. + * https://tools.ietf.org/html/rfc3261#section-8.1.1.7 + * @param branchParameter The branch parameter. + * @param transport The transport. + */ + setViaHeader(branch: string, transport: Transport): void; + toString(): string; +} +/** + * @class Class for incoming SIP message. + */ +export declare class IncomingMessage { + type: TypeStrings; + viaBranch: string; + method: string; + body: string; + toTag: string; + to: NameAddrHeader; + fromTag: string; + from: NameAddrHeader; + callId: string; + cseq: number; + via: { + host: string; + port: number; + }; + headers: { + [name: string]: Array<{ + parsed?: any; + raw: string; + }>; + }; + referTo: string | undefined; + data: string; + /** + * Insert a header of the given name and value into the last position of the + * header array. + * @param {String} name header name + * @param {String} value header value + */ + addHeader(name: string, value: string): void; + /** + * Get the value of the given header name at the given position. + * @param {String} name header name + * @returns {String|undefined} Returns the specified header, undefined if header doesn't exist. + */ + getHeader(name: string): string | undefined; + /** + * Get the header/s of the given name. + * @param {String} name header name + * @returns {Array} Array with all the headers of the specified name. + */ + getHeaders(name: string): Array; + /** + * Verify the existence of the given header. + * @param {String} name header name + * @returns {boolean} true if header with given name exists, false otherwise + */ + hasHeader(name: string): boolean; + /** + * Parse the given header on the given index. + * @param {String} name header name + * @param {Number} [idx=0] header index + * @returns {Object|undefined} Parsed header object, undefined if the + * header is not present or in case of a parsing error. + */ + parseHeader(name: string, idx?: number): any | undefined; + /** + * Message Header attribute selector. Alias of parseHeader. + * @param {String} name header name + * @param {Number} [idx=0] header index + * @returns {Object|undefined} Parsed header object, undefined if the + * header is not present or in case of a parsing error. + * + * @example + * message.s('via',3).port + */ + s(name: string, idx?: number): any | undefined; + /** + * Replace the value of the given header by the value. + * @param {String} name header name + * @param {String} value header value + */ + setHeader(name: string, value: string): void; + toString(): string; +} +/** + * @class Class for incoming SIP request. + */ +export declare class IncomingRequest extends IncomingMessage { + ua: UA; + type: TypeStrings; + ruri: URI | undefined; + constructor(ua: UA); +} +/** + * @class Class for incoming SIP response. + */ +export declare class IncomingResponse extends IncomingMessage { + ua: UA; + type: TypeStrings; + statusCode: number | undefined; + reasonPhrase: string | undefined; + constructor(ua: UA); +} diff --git a/lib/SIPMessage.js b/lib/SIPMessage.js new file mode 100644 index 000000000..116e75351 --- /dev/null +++ b/lib/SIPMessage.js @@ -0,0 +1,430 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Constants_1 = require("./Constants"); +var Enums_1 = require("./Enums"); +var Grammar_1 = require("./Grammar"); +var Utils_1 = require("./Utils"); +exports.getSupportedHeader = function (request) { + var optionTags = []; + if (request.method === Constants_1.C.REGISTER) { + optionTags.push("path", "gruu"); + } + else if (request.method === Constants_1.C.INVITE && + (request.ua.contact.pubGruu || request.ua.contact.tempGruu)) { + optionTags.push("gruu"); + } + if (request.ua.configuration.rel100 === Constants_1.C.supported.SUPPORTED) { + optionTags.push("100rel"); + } + if (request.ua.configuration.replaces === Constants_1.C.supported.SUPPORTED) { + optionTags.push("replaces"); + } + optionTags.push("outbound"); + optionTags = optionTags.concat(request.ua.configuration.extraSupported || []); + var allowUnregistered = request.ua.configuration.hackAllowUnregisteredOptionTags || false; + var optionTagSet = {}; + optionTags = optionTags.filter(function (optionTag) { + var registered = Constants_1.C.OPTION_TAGS[optionTag]; + var unique = !optionTagSet[optionTag]; + optionTagSet[optionTag] = true; + return (registered || allowUnregistered) && unique; + }); + return "Supported: " + optionTags.join(", ") + "\r\n"; +}; +/** + * @class Class for outgoing SIP request. + * @param {String} method request method + * @param {String} ruri request uri + * @param {SIP.UA} ua + * @param {Object} params parameters that will have priority over ua.configuration parameters: + *
+ * - cseq, callId, fromTag, fromUri, fromDisplayName, toUri, toTag, routeSet + * @param {Object} [headers] extra headers + * @param {String} [body] + */ +var OutgoingRequest = /** @class */ (function () { + function OutgoingRequest(method, ruri, ua, params, extraHeaders, body) { + if (params === void 0) { params = {}; } + this.type = Enums_1.TypeStrings.OutgoingRequest; + this.ua = ua; + this.headers = {}; + this.method = method; + this.ruri = ruri; + this.body = body; + this.extraHeaders = (extraHeaders || []).slice(); + // Fill the Common SIP Request Headers + // Route + if (params.routeSet) { + this.setHeader("route", params.routeSet); + } + else if (ua.configuration.usePreloadedRoute && ua.transport) { + this.setHeader("route", ua.transport.server.sipUri); + } + // Via + // Empty Via header. Will be filled by the client transaction. + this.setHeader("via", ""); + // Max-Forwards + // is a constant on ua.c, removed for circular dependency + this.setHeader("max-forwards", "70"); + // To + var toUri = params.toUri || ruri; + this.toTag = params.toTag; + var to = (params.toDisplayName || params.toDisplayName === 0) ? '"' + params.toDisplayName + '" ' : ""; + to += "<" + (toUri.type === Enums_1.TypeStrings.URI ? toUri.toRaw() : toUri) + ">"; + to += this.toTag ? ";tag=" + this.toTag : ""; + this.to = Grammar_1.Grammar.nameAddrHeaderParse(to); + this.setHeader("to", to); + // From + var fromUri = params.fromUri || ua.configuration.uri || ""; + this.fromTag = params.fromTag || Utils_1.Utils.newTag(); + var from; + if (params.fromDisplayName || params.fromDisplayName === 0) { + from = '"' + params.fromDisplayName + '" '; + } + else if (ua.configuration.displayName) { + from = '"' + ua.configuration.displayName + '" '; + } + else { + from = ""; + } + from += "<" + (fromUri.type === Enums_1.TypeStrings.URI ? fromUri.toRaw() : fromUri) + ">;tag="; + from += this.fromTag; + this.from = Grammar_1.Grammar.nameAddrHeaderParse(from); + this.setHeader("from", from); + // Call-ID + this.callId = params.callId || (ua.configuration.sipjsId + Utils_1.Utils.createRandomToken(15)); + this.setHeader("call-id", this.callId); + // CSeq + // Why not make this a "1" if not provided? See: https://tools.ietf.org/html/rfc3261#section-8.1.1.5 + this.cseq = params.cseq || Math.floor(Math.random() * 10000); + this.setHeader("cseq", this.cseq + " " + method); + } + /** + * Get the value of the given header name at the given position. + * @param {String} name header name + * @returns {String|undefined} Returns the specified header, undefined if header doesn't exist. + */ + OutgoingRequest.prototype.getHeader = function (name) { + var header = this.headers[Utils_1.Utils.headerize(name)]; + if (header) { + if (header[0]) { + return header[0]; + } + } + else { + var regexp = new RegExp("^\\s*" + name + "\\s*:", "i"); + for (var _i = 0, _a = this.extraHeaders; _i < _a.length; _i++) { + var exHeader = _a[_i]; + if (regexp.test(exHeader)) { + return exHeader.substring(exHeader.indexOf(":") + 1).trim(); + } + } + } + return; + }; + /** + * Get the header/s of the given name. + * @param {String} name header name + * @returns {Array} Array with all the headers of the specified name. + */ + OutgoingRequest.prototype.getHeaders = function (name) { + var result = []; + var headerArray = this.headers[Utils_1.Utils.headerize(name)]; + if (headerArray) { + for (var _i = 0, headerArray_1 = headerArray; _i < headerArray_1.length; _i++) { + var headerPart = headerArray_1[_i]; + result.push(headerPart); + } + } + else { + var regexp = new RegExp("^\\s*" + name + "\\s*:", "i"); + for (var _a = 0, _b = this.extraHeaders; _a < _b.length; _a++) { + var exHeader = _b[_a]; + if (regexp.test(exHeader)) { + result.push(exHeader.substring(exHeader.indexOf(":") + 1).trim()); + } + } + } + return result; + }; + /** + * Verify the existence of the given header. + * @param {String} name header name + * @returns {boolean} true if header with given name exists, false otherwise + */ + OutgoingRequest.prototype.hasHeader = function (name) { + if (this.headers[Utils_1.Utils.headerize(name)]) { + return true; + } + else { + var regexp = new RegExp("^\\s*" + name + "\\s*:", "i"); + for (var _i = 0, _a = this.extraHeaders; _i < _a.length; _i++) { + var extraHeader = _a[_i]; + if (regexp.test(extraHeader)) { + return true; + } + } + } + return false; + }; + /** + * Replace the the given header by the given value. + * @param {String} name header name + * @param {String | Array} value header value + */ + OutgoingRequest.prototype.setHeader = function (name, value) { + this.headers[Utils_1.Utils.headerize(name)] = (value instanceof Array) ? value : [value]; + }; + /** + * The Via header field indicates the transport used for the transaction + * and identifies the location where the response is to be sent. A Via + * header field value is added only after the transport that will be + * used to reach the next hop has been selected (which may involve the + * usage of the procedures in [4]). + * + * When the UAC creates a request, it MUST insert a Via into that + * request. The protocol name and protocol version in the header field + * MUST be SIP and 2.0, respectively. The Via header field value MUST + * contain a branch parameter. This parameter is used to identify the + * transaction created by that request. This parameter is used by both + * the client and the server. + * https://tools.ietf.org/html/rfc3261#section-8.1.1.7 + * @param branchParameter The branch parameter. + * @param transport The transport. + */ + OutgoingRequest.prototype.setViaHeader = function (branch, transport) { + // FIXME: Default scheme to "WSS" + // This should go away once transport is typed and we can be sure + // we are getting the something valid from there transport. + var scheme = "WSS"; + // FIXME: Transport's server property is not typed (as of writing this). + if (transport.server && transport.server.scheme) { + scheme = transport.server.scheme; + } + // FIXME: Hack + if (this.ua.configuration.hackViaTcp) { + scheme = "TCP"; + } + var via = "SIP/2.0/" + scheme; + via += " " + this.ua.configuration.viaHost + ";branch=" + branch; + if (this.ua.configuration.forceRport) { + via += ";rport"; + } + this.setHeader("via", via); + this.branch = branch; + }; + OutgoingRequest.prototype.toString = function () { + var msg = ""; + msg += this.method + " " + (this.ruri.type === Enums_1.TypeStrings.URI ? + this.ruri.toRaw() : this.ruri) + " SIP/2.0\r\n"; + for (var header in this.headers) { + if (this.headers[header]) { + for (var _i = 0, _a = this.headers[header]; _i < _a.length; _i++) { + var headerPart = _a[_i]; + msg += header + ": " + headerPart + "\r\n"; + } + } + } + for (var _b = 0, _c = this.extraHeaders; _b < _c.length; _b++) { + var header = _c[_b]; + msg += header.trim() + "\r\n"; + } + msg += exports.getSupportedHeader(this); + msg += "User-Agent: " + this.ua.configuration.userAgentString + "\r\n"; + if (this.body) { + if (typeof this.body === "string") { + msg += "Content-Length: " + Utils_1.Utils.str_utf8_length(this.body) + "\r\n\r\n"; + msg += this.body; + } + else { + if (this.body.body && this.body.contentType) { + msg += "Content-Type: " + this.body.contentType + "\r\n"; + msg += "Content-Length: " + Utils_1.Utils.str_utf8_length(this.body.body) + "\r\n\r\n"; + msg += this.body.body; + } + else { + msg += "Content-Length: " + 0 + "\r\n\r\n"; + } + } + } + else { + msg += "Content-Length: " + 0 + "\r\n\r\n"; + } + return msg; + }; + return OutgoingRequest; +}()); +exports.OutgoingRequest = OutgoingRequest; +/** + * @class Class for incoming SIP message. + */ +// tslint:disable-next-line:max-classes-per-file +var IncomingMessage = /** @class */ (function () { + function IncomingMessage() { + this.type = Enums_1.TypeStrings.IncomingMessage; + this.headers = {}; + } + /** + * Insert a header of the given name and value into the last position of the + * header array. + * @param {String} name header name + * @param {String} value header value + */ + IncomingMessage.prototype.addHeader = function (name, value) { + var header = { raw: value }; + name = Utils_1.Utils.headerize(name); + if (this.headers[name]) { + this.headers[name].push(header); + } + else { + this.headers[name] = [header]; + } + }; + /** + * Get the value of the given header name at the given position. + * @param {String} name header name + * @returns {String|undefined} Returns the specified header, undefined if header doesn't exist. + */ + IncomingMessage.prototype.getHeader = function (name) { + var header = this.headers[Utils_1.Utils.headerize(name)]; + if (header) { + if (header[0]) { + return header[0].raw; + } + } + else { + return; + } + }; + /** + * Get the header/s of the given name. + * @param {String} name header name + * @returns {Array} Array with all the headers of the specified name. + */ + IncomingMessage.prototype.getHeaders = function (name) { + var header = this.headers[Utils_1.Utils.headerize(name)]; + var result = []; + if (!header) { + return []; + } + for (var _i = 0, header_1 = header; _i < header_1.length; _i++) { + var headerPart = header_1[_i]; + result.push(headerPart.raw); + } + return result; + }; + /** + * Verify the existence of the given header. + * @param {String} name header name + * @returns {boolean} true if header with given name exists, false otherwise + */ + IncomingMessage.prototype.hasHeader = function (name) { + return !!this.headers[Utils_1.Utils.headerize(name)]; + }; + /** + * Parse the given header on the given index. + * @param {String} name header name + * @param {Number} [idx=0] header index + * @returns {Object|undefined} Parsed header object, undefined if the + * header is not present or in case of a parsing error. + */ + IncomingMessage.prototype.parseHeader = function (name, idx) { + if (idx === void 0) { idx = 0; } + name = Utils_1.Utils.headerize(name); + if (!this.headers[name]) { + // this.logger.log("header '" + name + "' not present"); + return; + } + else if (idx >= this.headers[name].length) { + // this.logger.log("not so many '" + name + "' headers present"); + return; + } + var header = this.headers[name][idx]; + var value = header.raw; + if (header.parsed) { + return header.parsed; + } + // substitute '-' by '_' for grammar rule matching. + var parsed = Grammar_1.Grammar.parse(value, name.replace(/-/g, "_")); + if (parsed === -1) { + this.headers[name].splice(idx, 1); // delete from headers + // this.logger.warn('error parsing "' + name + '" header field with value "' + value + '"'); + return; + } + else { + header.parsed = parsed; + return parsed; + } + }; + /** + * Message Header attribute selector. Alias of parseHeader. + * @param {String} name header name + * @param {Number} [idx=0] header index + * @returns {Object|undefined} Parsed header object, undefined if the + * header is not present or in case of a parsing error. + * + * @example + * message.s('via',3).port + */ + IncomingMessage.prototype.s = function (name, idx) { + if (idx === void 0) { idx = 0; } + return this.parseHeader(name, idx); + }; + /** + * Replace the value of the given header by the value. + * @param {String} name header name + * @param {String} value header value + */ + IncomingMessage.prototype.setHeader = function (name, value) { + this.headers[Utils_1.Utils.headerize(name)] = [{ raw: value }]; + }; + IncomingMessage.prototype.toString = function () { + return this.data; + }; + return IncomingMessage; +}()); +exports.IncomingMessage = IncomingMessage; +/** + * @class Class for incoming SIP request. + */ +// tslint:disable-next-line:max-classes-per-file +var IncomingRequest = /** @class */ (function (_super) { + __extends(IncomingRequest, _super); + function IncomingRequest(ua) { + var _this = _super.call(this) || this; + _this.ua = ua; + _this.type = Enums_1.TypeStrings.IncomingRequest; + return _this; + } + return IncomingRequest; +}(IncomingMessage)); +exports.IncomingRequest = IncomingRequest; +/** + * @class Class for incoming SIP response. + */ +// tslint:disable-next-line:max-classes-per-file +var IncomingResponse = /** @class */ (function (_super) { + __extends(IncomingResponse, _super); + function IncomingResponse(ua) { + var _this = _super.call(this) || this; + _this.ua = ua; + _this.type = Enums_1.TypeStrings.IncomingResponse; + _this.headers = {}; + return _this; + } + return IncomingResponse; +}(IncomingMessage)); +exports.IncomingResponse = IncomingResponse; diff --git a/lib/ServerContext.d.ts b/lib/ServerContext.d.ts new file mode 100644 index 000000000..dc8e9432d --- /dev/null +++ b/lib/ServerContext.d.ts @@ -0,0 +1,32 @@ +/// +import { EventEmitter } from "events"; +import { IncomingRequest } from "./Core/messages"; +import { InviteServerTransaction, NonInviteServerTransaction } from "./Core/transactions"; +import { TypeStrings } from "./Enums"; +import { Logger } from "./LoggerFactory"; +import { NameAddrHeader } from "./NameAddrHeader"; +import { IncomingRequest as IncomingRequestMessage } from "./SIPMessage"; +import { UA } from "./UA"; +export declare class ServerContext extends EventEmitter { + incomingRequest: IncomingRequest; + static initializer(objectToConstruct: ServerContext, ua: UA, incomingRequest: IncomingRequest): void; + type: TypeStrings; + ua: UA; + logger: Logger; + localIdentity: NameAddrHeader; + remoteIdentity: NameAddrHeader; + method: string; + request: IncomingRequestMessage; + data: any; + transaction: InviteServerTransaction | NonInviteServerTransaction; + body: any; + contentType: string | undefined; + assertedIdentity: NameAddrHeader | undefined; + constructor(ua: UA, incomingRequest: IncomingRequest); + progress(options?: any): any; + accept(options?: any): any; + reject(options?: any): any; + reply(options?: any): any; + onRequestTimeout(): void; + onTransportError(): void; +} diff --git a/lib/ServerContext.js b/lib/ServerContext.js new file mode 100644 index 000000000..a6cedeebf --- /dev/null +++ b/lib/ServerContext.js @@ -0,0 +1,132 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var events_1 = require("events"); +var Constants_1 = require("./Constants"); +var messages_1 = require("./Core/messages"); +var Enums_1 = require("./Enums"); +var Grammar_1 = require("./Grammar"); +var Utils_1 = require("./Utils"); +var ServerContext = /** @class */ (function (_super) { + __extends(ServerContext, _super); + function ServerContext(ua, incomingRequest) { + var _this = _super.call(this) || this; + _this.incomingRequest = incomingRequest; + _this.data = {}; + ServerContext.initializer(_this, ua, incomingRequest); + return _this; + } + // hack to get around our multiple inheritance issues + ServerContext.initializer = function (objectToConstruct, ua, incomingRequest) { + var request = incomingRequest.message; + objectToConstruct.type = Enums_1.TypeStrings.ServerContext; + objectToConstruct.ua = ua; + objectToConstruct.logger = ua.getLogger("sip.servercontext"); + objectToConstruct.request = request; + if (request.body) { + objectToConstruct.body = request.body; + } + if (request.hasHeader("Content-Type")) { + objectToConstruct.contentType = request.getHeader("Content-Type"); + } + objectToConstruct.method = request.method; + objectToConstruct.localIdentity = request.to; + objectToConstruct.remoteIdentity = request.from; + var hasAssertedIdentity = request.hasHeader("P-Asserted-Identity"); + if (hasAssertedIdentity) { + var assertedIdentity = request.getHeader("P-Asserted-Identity"); + if (assertedIdentity) { + objectToConstruct.assertedIdentity = Grammar_1.Grammar.nameAddrHeaderParse(assertedIdentity); + } + } + }; + ServerContext.prototype.progress = function (options) { + if (options === void 0) { options = {}; } + options.statusCode = options.statusCode || 180; + options.minCode = 100; + options.maxCode = 199; + options.events = ["progress"]; + return this.reply(options); + }; + ServerContext.prototype.accept = function (options) { + if (options === void 0) { options = {}; } + options.statusCode = options.statusCode || 200; + options.minCode = 200; + options.maxCode = 299; + options.events = ["accepted"]; + return this.reply(options); + }; + ServerContext.prototype.reject = function (options) { + if (options === void 0) { options = {}; } + options.statusCode = options.statusCode || 480; + options.minCode = 300; + options.maxCode = 699; + options.events = ["rejected", "failed"]; + return this.reply(options); + }; + ServerContext.prototype.reply = function (options) { + var _this = this; + if (options === void 0) { options = {}; } + var statusCode = options.statusCode || 100; + var minCode = options.minCode || 100; + var maxCode = options.maxCode || 699; + var reasonPhrase = Utils_1.Utils.getReasonPhrase(statusCode, options.reasonPhrase); + var extraHeaders = options.extraHeaders || []; + var body = options.body ? messages_1.fromBodyLegacy(options.body) : undefined; + var events = options.events || []; + if (statusCode < minCode || statusCode > maxCode) { + throw new TypeError("Invalid statusCode: " + statusCode); + } + var responseOptions = { + statusCode: statusCode, + reasonPhrase: reasonPhrase, + extraHeaders: extraHeaders, + body: body + }; + var response; + var statusCodeString = statusCode.toString(); + switch (true) { + case /^100$/.test(statusCodeString): + response = this.incomingRequest.trying(responseOptions).message; + break; + case /^1[0-9]{2}$/.test(statusCodeString): + response = this.incomingRequest.progress(responseOptions).message; + break; + case /^2[0-9]{2}$/.test(statusCodeString): + response = this.incomingRequest.accept(responseOptions).message; + break; + case /^3[0-9]{2}$/.test(statusCodeString): + response = this.incomingRequest.redirect([], responseOptions).message; + break; + case /^[4-6][0-9]{2}$/.test(statusCodeString): + response = this.incomingRequest.reject(responseOptions).message; + break; + default: + throw new Error("Invalid status code " + statusCode); + } + events.forEach(function (event) { + _this.emit(event, response, reasonPhrase); + }); + return this; + }; + ServerContext.prototype.onRequestTimeout = function () { + this.emit("failed", undefined, Constants_1.C.causes.REQUEST_TIMEOUT); + }; + ServerContext.prototype.onTransportError = function () { + this.emit("failed", undefined, Constants_1.C.causes.CONNECTION_ERROR); + }; + return ServerContext; +}(events_1.EventEmitter)); +exports.ServerContext = ServerContext; diff --git a/lib/Session.d.ts b/lib/Session.d.ts new file mode 100644 index 000000000..31d59633d --- /dev/null +++ b/lib/Session.d.ts @@ -0,0 +1,358 @@ +/// +import { EventEmitter } from "events"; +import { ClientContext } from "./ClientContext"; +import { C } from "./Constants"; +import { Body, IncomingAckRequest, IncomingInviteRequest, IncomingPrackRequest, IncomingRequest } from "./Core/messages"; +import { Session as SessionCore } from "./Core/session"; +import { InviteServerTransaction, NonInviteServerTransaction } from "./Core/transactions"; +import { SessionStatus, TypeStrings } from "./Enums"; +import { Logger } from "./LoggerFactory"; +import { NameAddrHeader } from "./NameAddrHeader"; +import { ReferClientContext, ReferServerContext } from "./ReferContext"; +import { ServerContext } from "./ServerContext"; +import { SessionDescriptionHandler, SessionDescriptionHandlerModifier, SessionDescriptionHandlerModifiers, SessionDescriptionHandlerOptions } from "./session-description-handler"; +import { SessionDescriptionHandlerFactory } from "./session-description-handler-factory"; +import { DTMF } from "./Session/DTMF"; +import { IncomingRequest as IncomingRequestMessage, IncomingResponse as IncomingResponseMessage, OutgoingRequest as OutgoingRequestMessage } from "./SIPMessage"; +import { UA } from "./UA"; +import { URI } from "./URI"; +export declare namespace Session { + interface DtmfOptions { + extraHeaders?: string[]; + duration?: number; + interToneGap?: number; + } +} +export declare abstract class Session extends EventEmitter { + static readonly C: typeof SessionStatus; + type: TypeStrings; + ua: UA; + logger: Logger; + method: string; + body: any; + status: SessionStatus; + contentType: string; + localIdentity: NameAddrHeader; + remoteIdentity: NameAddrHeader; + data: any; + assertedIdentity: NameAddrHeader | undefined; + id: string; + contact: string | undefined; + replacee: InviteClientContext | InviteServerContext | undefined; + localHold: boolean; + sessionDescriptionHandler: SessionDescriptionHandler | undefined; + startTime: Date | undefined; + endTime: Date | undefined; + session: SessionCore | undefined; + protected sessionDescriptionHandlerFactory: SessionDescriptionHandlerFactory; + protected sessionDescriptionHandlerOptions: any; + protected rel100: string; + protected earlySdp: string | undefined; + protected hasOffer: boolean; + protected hasAnswer: boolean; + protected timers: { + [name: string]: any; + }; + protected fromTag: string | undefined; + protected errorListener: ((...args: Array) => void); + protected renderbody: string | undefined; + protected rendertype: string | undefined; + protected modifiers: Array | undefined; + protected passedOptions: any; + protected onInfo: ((request: IncomingRequestMessage) => void) | undefined; + private tones; + private pendingReinvite; + private referContext; + protected constructor(sessionDescriptionHandlerFactory: SessionDescriptionHandlerFactory); + dtmf(tones: string | number, options?: Session.DtmfOptions): this; + bye(options?: any): this; + refer(target: string | InviteClientContext | InviteServerContext, options?: any): ReferClientContext; + /** + * Sends in dialog request. + * @param method Request method. + * @param options Options bucket. + */ + sendRequest(method: string, options?: any): this; + close(): this; + hold(options?: SessionDescriptionHandlerOptions, modifiers?: SessionDescriptionHandlerModifiers): void; + unhold(options?: SessionDescriptionHandlerOptions, modifiers?: SessionDescriptionHandlerModifiers): void; + reinvite(options?: any, modifiers?: SessionDescriptionHandlerModifiers): void; + terminate(options?: any): this; + onTransportError(): void; + onRequestTimeout(): void; + onDialogError(response: IncomingResponseMessage): void; + on(event: "dtmf", listener: (request: IncomingRequestMessage | OutgoingRequestMessage, dtmf: DTMF) => void): this; + on(event: "progress", listener: (response: string, reasonPhrase?: any) => void): this; + on(event: "referRequested", listener: (context: ReferServerContext) => void): this; + on(event: "referInviteSent" | "referProgress" | "referAccepted" | "referRejected" | "referRequestProgress" | "referRequestAccepted" | "referRequestRejected" | "reinvite" | "reinviteAccepted" | "reinviteFailed" | "replaced", listener: (session: Session) => void): this; + on(event: "SessionDescriptionHandler-created", listener: (sessionDescriptionHandler: SessionDescriptionHandler) => void): this; + on(event: "accepted", listener: (response: any, cause: C.causes) => void): this; + on(event: "ack" | "bye" | "confirmed" | "connecting" | "notify", listener: (request: any) => void): this; + on(event: "dialog", listener: (dialog: any) => void): this; + on(event: "renegotiationError", listener: (error: any) => void): this; + on(event: "failed" | "rejected", listener: (response?: any, cause?: C.causes) => void): this; + on(event: "terminated", listener: (message?: any, cause?: C.causes) => void): this; + on(event: "cancel" | "trackAdded" | "directionChanged", listener: () => void): this; + protected onAck(incomingRequest: IncomingAckRequest): void; + protected receiveRequest(incomingRequest: IncomingRequest): void; + protected receiveReinvite(incomingRequest: IncomingRequest): void; + protected sendReinvite(options?: any): void; + protected failed(response: IncomingResponseMessage | IncomingRequestMessage | undefined, cause: string): this; + protected rejected(response: IncomingResponseMessage | IncomingRequestMessage, cause: string): this; + protected canceled(): this; + protected accepted(response?: IncomingResponseMessage | string, cause?: string): this; + protected terminated(message?: IncomingResponseMessage | IncomingRequestMessage, cause?: string): this; + protected connecting(request: IncomingRequestMessage): this; +} +export declare namespace InviteServerContext { + interface Options { + /** Array of extra headers added to the INVITE. */ + extraHeaders?: Array; + /** Options to pass to SessionDescriptionHandler's getDescription() and setDescription(). */ + sessionDescriptionHandlerOptions?: SessionDescriptionHandlerOptions; + modifiers?: SessionDescriptionHandlerModifiers; + onInfo?: ((request: IncomingRequestMessage) => void); + statusCode?: number; + reasonPhrase?: string; + body?: any; + rel100?: boolean; + } +} +export declare class InviteServerContext extends Session implements ServerContext { + type: TypeStrings; + transaction: InviteServerTransaction | NonInviteServerTransaction; + request: IncomingRequestMessage; + incomingRequest: IncomingInviteRequest; + /** + * FIXME: TODO: + * Used to squelch throwing of errors due to async race condition. + * We have an internal race between calling `accept()` and handling + * an incoming CANCEL request. As there is no good way currently to + * delegate the handling of this async errors to the caller of + * `accept()`, we are squelching the throwing ALL errors when + * they occur after receiving a CANCEL to catch the ONE we know + * is a "normal" exceptional condition. While this is a completely + * reasonable appraoch, the decision should be left up to the library user. + */ + private _canceled; + private rseq; + private waitingForPrackPromise; + private waitingForPrackResolve; + private waitingForPrackReject; + constructor(ua: UA, incomingInviteRequest: IncomingInviteRequest); + /** + * If true, a first provisional response after the 100 Trying + * will be sent automatically. This is false it the UAC required + * reliable provisional responses (100rel in Require header), + * otherwise it is true. The provisional is sent by calling + * `progress()` without any options. + * + * FIXME: TODO: It seems reasonable that the ISC user should + * be able to optionally disable this behavior. As the provisional + * is sent prior to the "invite" event being emitted, it's a known + * issue that the ISC user cannot register listeners or do any other + * setup prior to the call to `progress()`. As an example why this is + * an issue, setting `ua.configuration.rel100` to REQUIRED will result + * in an attempt by `progress()` to send a 183 with SDP produced by + * calling `getDescription()` on a session description handler, but + * the ISC user cannot perform any potentially required session description + * handler initialization (thus preventing the utilization of setting + * `ua.configuration.rel100` to REQUIRED). That begs the question of + * why this behavior is disabled when the UAC requires 100rel but not + * when the UAS requires 100rel? But ignoring that, it's just one example + * of a class of cases where the ISC user needs to do something prior + * to the first call to `progress()` and is unable to do so. + */ + readonly autoSendAnInitialProvisionalResponse: boolean; + reply(options?: any): this; + reject(options?: InviteServerContext.Options): this; + /** + * Accept the incoming INVITE request to start a Session. + * Replies to the INVITE request with a 200 Ok response. + * @param options Options bucket. + */ + accept(options?: InviteServerContext.Options): this; + /** + * Report progress to the the caller. + * Replies to the INVITE request with a 1xx provisional response. + * @param options Options bucket. + */ + progress(options?: InviteServerContext.Options): this; + /** + * Reject an unaccepted incoming INVITE request or send BYE if established session. + * @param options Options bucket. FIXME: This options bucket needs to be typed. + */ + terminate(options?: any): this; + onCancel(message: IncomingRequestMessage): void; + protected receiveRequest(incomingRequest: IncomingRequest): void; + protected setupSessionDescriptionHandler(): SessionDescriptionHandler; + protected generateResponseOfferAnswer(options: { + sessionDescriptionHandlerOptions?: SessionDescriptionHandlerOptions; + modifiers?: SessionDescriptionHandlerModifiers; + }): Promise; + protected handlePrackOfferAnswer(request: IncomingPrackRequest, options: { + sessionDescriptionHandlerOptions?: SessionDescriptionHandlerOptions; + modifiers?: SessionDescriptionHandlerModifiers; + }): Promise; + /** + * Called when session canceled. + */ + protected canceled(): this; + /** + * Called when session terminated. + * Using it here just for the PRACK timeout. + */ + protected terminated(message?: IncomingResponseMessage | IncomingRequestMessage, cause?: string): this; + /** + * A version of `accept` which resolves a session when the 200 Ok response is sent. + * @param options Options bucket. + * @throws {ClosedSessionDescriptionHandlerError} The session description handler closed before method completed. + * @throws {TransactionStateError} The transaction state does not allow for `accept()` to be called. + * Note that the transaction state can change while this call is in progress. + */ + private _accept; + /** + * A version of `progress` which resolves when the provisional response is sent. + * @param options Options bucket. + * @throws {ClosedSessionDescriptionHandlerError} The session description handler closed before method completed. + * @throws {TransactionStateError} The transaction state does not allow for `progress()` to be called. + * Note that the transaction state can change while this call is in progress. + */ + private _progress; + /** + * A version of `progress` which resolves when the reliable provisional response is sent. + * @param options Options bucket. + * @throws {ClosedSessionDescriptionHandlerError} The session description handler closed before method completed. + * @throws {TransactionStateError} The transaction state does not allow for `progress()` to be called. + * Note that the transaction state can change while this call is in progress. + */ + private _reliableProgress; + /** + * A version of `progress` which resolves when the reliable provisional response is acknowledged. + * @param options Options bucket. + * @throws {ClosedSessionDescriptionHandlerError} The session description handler closed before method completed. + * @throws {TransactionStateError} The transaction state does not allow for `progress()` to be called. + * Note that the transaction state can change while this call is in progress. + */ + private _reliableProgressWaitForPrack; + /** + * Callback for when ACK for a 2xx response is never received. + * @param session Session the ACK never arrived for + */ + private onAckTimeout; + /** + * FIXME: TODO: The current library interface presents async methods without a + * proper async error handling mechanism. Arguably a promise based interface + * would be an improvement over the pattern of returning `this`. The approach has + * been generally along the lines of log a error and terminate. + */ + private onContextError; + private prackArrived; + private prackNeverArrived; + /** + * @throws {Exceptions.TerminatedSessionError} The session terminated before being accepted (i.e. cancel arrived). + */ + private waitForArrivalOfPrack; + private getOffer; + private setAnswer; + private setOfferAndGetAnswer; + private getSessionDescriptionHandler; +} +export declare namespace InviteClientContext { + interface Options { + /** Array of extra headers added to the INVITE. */ + extraHeaders?: Array; + /** If true, send INVITE without SDP. */ + inviteWithoutSdp?: boolean; + /** Deprecated */ + params?: { + toUri?: string; + toDisplayName: string; + }; + /** Options to pass to SessionDescriptionHandler's getDescription() and setDescription(). */ + sessionDescriptionHandlerOptions?: SessionDescriptionHandlerOptions; + } +} +export declare class InviteClientContext extends Session implements ClientContext { + type: TypeStrings; + request: OutgoingRequestMessage; + protected anonymous: boolean; + protected inviteWithoutSdp: boolean; + protected isCanceled: boolean; + protected received100: boolean; + private earlyMediaSessionDescriptionHandlers; + private outgoingInviteRequest; + constructor(ua: UA, target: string | URI, options?: any, modifiers?: any); + receiveResponse(response: IncomingResponseMessage): void; + send(): this; + invite(): this; + cancel(options?: any): this; + terminate(options?: any): this; + /** + * 13.2.1 Creating the Initial INVITE + * + * Since the initial INVITE represents a request outside of a dialog, + * its construction follows the procedures of Section 8.1.1. Additional + * processing is required for the specific case of INVITE. + * + * An Allow header field (Section 20.5) SHOULD be present in the INVITE. + * It indicates what methods can be invoked within a dialog, on the UA + * sending the INVITE, for the duration of the dialog. For example, a + * UA capable of receiving INFO requests within a dialog [34] SHOULD + * include an Allow header field listing the INFO method. + * + * A Supported header field (Section 20.37) SHOULD be present in the + * INVITE. It enumerates all the extensions understood by the UAC. + * + * An Accept (Section 20.1) header field MAY be present in the INVITE. + * It indicates which Content-Types are acceptable to the UA, in both + * the response received by it, and in any subsequent requests sent to + * it within dialogs established by the INVITE. The Accept header field + * is especially useful for indicating support of various session + * description formats. + * + * The UAC MAY add an Expires header field (Section 20.19) to limit the + * validity of the invitation. If the time indicated in the Expires + * header field is reached and no final answer for the INVITE has been + * received, the UAC core SHOULD generate a CANCEL request for the + * INVITE, as per Section 9. + * + * A UAC MAY also find it useful to add, among others, Subject (Section + * 20.36), Organization (Section 20.25) and User-Agent (Section 20.41) + * header fields. They all contain information related to the INVITE. + * + * The UAC MAY choose to add a message body to the INVITE. Section + * 8.1.1.10 deals with how to construct the header fields -- Content- + * Type among others -- needed to describe the message body. + * + * https://tools.ietf.org/html/rfc3261#section-13.2.1 + */ + private sendInvite; + private ackAndBye; + private disposeEarlyMedia; + /** + * Handle final response to initial INVITE. + * @param inviteResponse 2xx response. + */ + private onAccept; + /** + * Handle provisional response to initial INVITE. + * @param inviteResponse 1xx response. + */ + private onProgress; + /** + * Handle final response to initial INVITE. + * @param inviteResponse 3xx response. + */ + private onRedirect; + /** + * Handle final response to initial INVITE. + * @param inviteResponse 4xx, 5xx, or 6xx response. + */ + private onReject; + /** + * Handle final response to initial INVITE. + * @param inviteResponse 100 response. + */ + private onTrying; +} diff --git a/lib/Session.js b/lib/Session.js new file mode 100644 index 000000000..f852d27d6 --- /dev/null +++ b/lib/Session.js @@ -0,0 +1,2185 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var events_1 = require("events"); +var ClientContext_1 = require("./ClientContext"); +var Constants_1 = require("./Constants"); +var messages_1 = require("./Core/messages"); +var session_1 = require("./Core/session"); +var Enums_1 = require("./Enums"); +var Exceptions_1 = require("./Exceptions"); +var Grammar_1 = require("./Grammar"); +var ReferContext_1 = require("./ReferContext"); +var ServerContext_1 = require("./ServerContext"); +var DTMF_1 = require("./Session/DTMF"); +var Timers_1 = require("./Timers"); +var Utils_1 = require("./Utils"); +/* + * @param {function returning SIP.sessionDescriptionHandler} [sessionDescriptionHandlerFactory] + * (See the documentation for the sessionDescriptionHandlerFactory argument of the UA constructor.) + */ +var Session = /** @class */ (function (_super) { + __extends(Session, _super); + function Session(sessionDescriptionHandlerFactory) { + var _this = _super.call(this) || this; + _this.data = {}; + _this.type = Enums_1.TypeStrings.Session; + if (!sessionDescriptionHandlerFactory) { + throw new Exceptions_1.Exceptions.SessionDescriptionHandlerError("A session description handler is required for the session to function"); + } + _this.status = Session.C.STATUS_NULL; + _this.pendingReinvite = false; + _this.sessionDescriptionHandlerFactory = sessionDescriptionHandlerFactory; + _this.hasOffer = false; + _this.hasAnswer = false; + // Session Timers + _this.timers = { + ackTimer: undefined, + expiresTimer: undefined, + invite2xxTimer: undefined, + userNoAnswerTimer: undefined, + rel1xxTimer: undefined, + prackTimer: undefined + }; + // Session info + _this.startTime = undefined; + _this.endTime = undefined; + _this.tones = undefined; + // Hold state + _this.localHold = false; + _this.earlySdp = undefined; + _this.rel100 = Constants_1.C.supported.UNSUPPORTED; + return _this; + } + Session.prototype.dtmf = function (tones, options) { + var _this = this; + if (options === void 0) { options = {}; } + // Check Session Status + if (this.status !== Enums_1.SessionStatus.STATUS_CONFIRMED && this.status !== Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK) { + throw new Exceptions_1.Exceptions.InvalidStateError(this.status); + } + // Check tones + if (!tones || !tones.toString().match(/^[0-9A-D#*,]+$/i)) { + throw new TypeError("Invalid tones: " + tones); + } + var sendDTMF = function () { + if (_this.status === Enums_1.SessionStatus.STATUS_TERMINATED || !_this.tones || _this.tones.length === 0) { + // Stop sending DTMF + _this.tones = undefined; + return; + } + var dtmf = _this.tones.shift(); + var timeout; + if (dtmf.tone === ",") { + timeout = 2000; + } + else { + dtmf.on("failed", function () { _this.tones = undefined; }); + dtmf.send(options); + timeout = dtmf.duration + dtmf.interToneGap; + } + // Set timeout for the next tone + setTimeout(sendDTMF, timeout); + }; + tones = tones.toString(); + var dtmfType = this.ua.configuration.dtmfType; + if (this.sessionDescriptionHandler && dtmfType === Constants_1.C.dtmfType.RTP) { + var sent = this.sessionDescriptionHandler.sendDtmf(tones, options); + if (!sent) { + this.logger.warn("Attempt to use dtmfType 'RTP' has failed, falling back to INFO packet method"); + dtmfType = Constants_1.C.dtmfType.INFO; + } + } + if (dtmfType === Constants_1.C.dtmfType.INFO) { + var dtmfs = []; + var tonesArray = tones.split(""); + while (tonesArray.length > 0) { + dtmfs.push(new DTMF_1.DTMF(this, tonesArray.shift(), options)); + } + if (this.tones) { + // Tones are already queued, just add to the queue + this.tones = this.tones.concat(dtmfs); + return this; + } + this.tones = dtmfs; + sendDTMF(); + } + return this; + }; + Session.prototype.bye = function (options) { + if (options === void 0) { options = {}; } + // Check Session Status + if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { + this.logger.error("Error: Attempted to send BYE in a terminated session."); + return this; + } + this.logger.log("terminating Session"); + var statusCode = options.statusCode; + if (statusCode && (statusCode < 200 || statusCode >= 700)) { + throw new TypeError("Invalid statusCode: " + statusCode); + } + options.receiveResponse = function () { }; + return this.sendRequest(Constants_1.C.BYE, options).terminated(); + }; + Session.prototype.refer = function (target, options) { + if (options === void 0) { options = {}; } + // Check Session Status + if (this.status !== Enums_1.SessionStatus.STATUS_CONFIRMED) { + throw new Exceptions_1.Exceptions.InvalidStateError(this.status); + } + this.referContext = new ReferContext_1.ReferClientContext(this.ua, this, target, options); + this.emit("referRequested", this.referContext); + this.referContext.refer(options); + return this.referContext; + }; + /** + * Sends in dialog request. + * @param method Request method. + * @param options Options bucket. + */ + Session.prototype.sendRequest = function (method, options) { + if (options === void 0) { options = {}; } + if (!this.session) { + throw new Error("Session undefined."); + } + // Convert any "body" option to a Body. + if (options.body) { + options.body = messages_1.fromBodyObj(options.body); + } + // Convert any "receiveResponse" callback option passed to an OutgoingRequestDelegate. + var delegate; + var callback = options.receiveResponse; + if (callback) { + delegate = { + onAccept: function (response) { return callback(response.message); }, + onProgress: function (response) { return callback(response.message); }, + onRedirect: function (response) { return callback(response.message); }, + onReject: function (response) { return callback(response.message); }, + onTrying: function (response) { return callback(response.message); } + }; + } + var request; + var requestOptions = options; + switch (method) { + case Constants_1.C.BYE: + request = this.session.bye(delegate, requestOptions); + break; + case Constants_1.C.INVITE: + request = this.session.invite(delegate, requestOptions); + break; + case Constants_1.C.REFER: + request = this.session.refer(delegate, requestOptions); + break; + default: + throw new Error("Unexpected " + method + ". Method not implemented by user agent core."); + } + // Ported - Emit the request event + this.emit(method.toLowerCase(), request.message); + return this; + }; + Session.prototype.close = function () { + if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { + return this; + } + this.logger.log("closing INVITE session " + this.id); + // 1st Step. Terminate media. + if (this.sessionDescriptionHandler) { + this.sessionDescriptionHandler.close(); + } + // 2nd Step. Terminate signaling. + // Clear session timers + for (var timer in this.timers) { + if (this.timers[timer]) { + clearTimeout(this.timers[timer]); + } + } + this.status = Enums_1.SessionStatus.STATUS_TERMINATED; + if (this.ua.transport) { + this.ua.transport.removeListener("transportError", this.errorListener); + } + delete this.ua.sessions[this.id]; + return this; + }; + Session.prototype.hold = function (options, modifiers) { + if (options === void 0) { options = {}; } + if (modifiers === void 0) { modifiers = []; } + if (this.status !== Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK && this.status !== Enums_1.SessionStatus.STATUS_CONFIRMED) { + throw new Exceptions_1.Exceptions.InvalidStateError(this.status); + } + if (this.localHold) { + this.logger.log("Session is already on hold, cannot put it on hold again"); + return; + } + options.modifiers = modifiers; + if (this.sessionDescriptionHandler) { + options.modifiers.push(this.sessionDescriptionHandler.holdModifier); + } + this.localHold = true; + this.sendReinvite(options); + }; + Session.prototype.unhold = function (options, modifiers) { + if (options === void 0) { options = {}; } + if (modifiers === void 0) { modifiers = []; } + if (this.status !== Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK && this.status !== Enums_1.SessionStatus.STATUS_CONFIRMED) { + throw new Exceptions_1.Exceptions.InvalidStateError(this.status); + } + if (!this.localHold) { + this.logger.log("Session is not on hold, cannot unhold it"); + return; + } + options.modifiers = modifiers; + this.localHold = false; + this.sendReinvite(options); + }; + Session.prototype.reinvite = function (options, modifiers) { + if (options === void 0) { options = {}; } + if (modifiers === void 0) { modifiers = []; } + options.modifiers = modifiers; + return this.sendReinvite(options); + }; + Session.prototype.terminate = function (options) { + // here for types and to be overridden + return this; + }; + Session.prototype.onTransportError = function () { + if (this.status !== Enums_1.SessionStatus.STATUS_CONFIRMED && this.status !== Enums_1.SessionStatus.STATUS_TERMINATED) { + this.failed(undefined, Constants_1.C.causes.CONNECTION_ERROR); + } + }; + Session.prototype.onRequestTimeout = function () { + if (this.status === Enums_1.SessionStatus.STATUS_CONFIRMED) { + this.terminated(undefined, Constants_1.C.causes.REQUEST_TIMEOUT); + } + else if (this.status !== Enums_1.SessionStatus.STATUS_TERMINATED) { + this.failed(undefined, Constants_1.C.causes.REQUEST_TIMEOUT); + this.terminated(undefined, Constants_1.C.causes.REQUEST_TIMEOUT); + } + }; + Session.prototype.onDialogError = function (response) { + if (this.status === Enums_1.SessionStatus.STATUS_CONFIRMED) { + this.terminated(response, Constants_1.C.causes.DIALOG_ERROR); + } + else if (this.status !== Enums_1.SessionStatus.STATUS_TERMINATED) { + this.failed(response, Constants_1.C.causes.DIALOG_ERROR); + this.terminated(response, Constants_1.C.causes.DIALOG_ERROR); + } + }; + Session.prototype.on = function (name, callback) { + return _super.prototype.on.call(this, name, callback); + }; + Session.prototype.onAck = function (incomingRequest) { + var _this = this; + var confirmSession = function () { + clearTimeout(_this.timers.ackTimer); + clearTimeout(_this.timers.invite2xxTimer); + _this.status = Enums_1.SessionStatus.STATUS_CONFIRMED; + var contentDisp = incomingRequest.message.getHeader("Content-Disposition"); + if (contentDisp && contentDisp.type === "render") { + _this.renderbody = incomingRequest.message.body; + _this.rendertype = incomingRequest.message.getHeader("Content-Type"); + } + _this.emit("confirmed", incomingRequest.message); + }; + if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK) { + if (this.sessionDescriptionHandler && + this.sessionDescriptionHandler.hasDescription(incomingRequest.message.getHeader("Content-Type") || "")) { + this.hasAnswer = true; + this.sessionDescriptionHandler.setDescription(incomingRequest.message.body, this.sessionDescriptionHandlerOptions, this.modifiers).catch(function (e) { + _this.logger.warn(e); + _this.terminate({ + statusCode: "488", + reasonPhrase: "Bad Media Description" + }); + _this.failed(incomingRequest.message, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); + _this.terminated(incomingRequest.message, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); + throw e; + }).then(function () { return confirmSession(); }); + } + else { + confirmSession(); + } + } + }; + Session.prototype.receiveRequest = function (incomingRequest) { + switch (incomingRequest.message.method) { // TODO: This needs a default case + case Constants_1.C.BYE: + incomingRequest.accept(); + if (this.status === Enums_1.SessionStatus.STATUS_CONFIRMED) { + this.emit("bye", incomingRequest.message); + this.terminated(incomingRequest.message, Constants_1.C.BYE); + } + break; + case Constants_1.C.INVITE: + if (this.status === Enums_1.SessionStatus.STATUS_CONFIRMED) { + this.logger.log("re-INVITE received"); + this.receiveReinvite(incomingRequest); + } + break; + case Constants_1.C.INFO: + if (this.status === Enums_1.SessionStatus.STATUS_CONFIRMED || this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK) { + if (this.onInfo) { + return this.onInfo(incomingRequest.message); + } + var contentType = incomingRequest.message.getHeader("content-type"); + if (contentType) { + if (contentType.match(/^application\/dtmf-relay/i)) { + if (incomingRequest.message.body) { + var body = incomingRequest.message.body.split("\r\n", 2); + if (body.length === 2) { + var tone = void 0; + var duration = void 0; + var regTone = /^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/; + if (regTone.test(body[0])) { + tone = body[0].replace(regTone, "$2"); + } + var regDuration = /^(Duration\s?=\s?)([0-9]{1,4})(\s)?.*/; + if (regDuration.test(body[1])) { + duration = parseInt(body[1].replace(regDuration, "$2"), 10); + } + if (tone && duration) { + new DTMF_1.DTMF(this, tone, { duration: duration }).init_incoming(incomingRequest); + } + } + } + } + else { + incomingRequest.reject({ + statusCode: 415, + extraHeaders: ["Accept: application/dtmf-relay"] + }); + } + } + } + break; + case Constants_1.C.REFER: + if (this.status === Enums_1.SessionStatus.STATUS_CONFIRMED) { + this.logger.log("REFER received"); + this.referContext = new ReferContext_1.ReferServerContext(this.ua, incomingRequest, this.session); + if (this.listeners("referRequested").length) { + this.emit("referRequested", this.referContext); + } + else { + this.logger.log("No referRequested listeners, automatically accepting and following the refer"); + var options = { followRefer: true }; + if (this.passedOptions) { + options.inviteOptions = this.passedOptions; + } + this.referContext.accept(options, this.modifiers); + } + } + break; + case Constants_1.C.NOTIFY: + if (this.referContext && + this.referContext.type === Enums_1.TypeStrings.ReferClientContext && + incomingRequest.message.hasHeader("event") && + /^refer(;.*)?$/.test(incomingRequest.message.getHeader("event"))) { + this.referContext.receiveNotify(incomingRequest); + return; + } + incomingRequest.accept(); + this.emit("notify", incomingRequest.message); + break; + } + }; + // In dialog INVITE Reception + Session.prototype.receiveReinvite = function (incomingRequest) { + // TODO: Should probably check state of the session + var _this = this; + this.emit("reinvite", this, incomingRequest.message); + if (incomingRequest.message.hasHeader("P-Asserted-Identity")) { + this.assertedIdentity = + Grammar_1.Grammar.nameAddrHeaderParse(incomingRequest.message.getHeader("P-Asserted-Identity")); + } + var promise; + if (!this.sessionDescriptionHandler) { + this.logger.warn("No SessionDescriptionHandler to reinvite"); + return; + } + if (incomingRequest.message.getHeader("Content-Length") === "0" && + !incomingRequest.message.getHeader("Content-Type")) { // Invite w/o SDP + promise = this.sessionDescriptionHandler.getDescription(this.sessionDescriptionHandlerOptions, this.modifiers); + } + else if (this.sessionDescriptionHandler.hasDescription(incomingRequest.message.getHeader("Content-Type") || "")) { + // Invite w/ SDP + promise = this.sessionDescriptionHandler.setDescription(incomingRequest.message.body, this.sessionDescriptionHandlerOptions, this.modifiers).then(this.sessionDescriptionHandler.getDescription.bind(this.sessionDescriptionHandler, this.sessionDescriptionHandlerOptions, this.modifiers)); + } + else { // Bad Packet (should never get hit) + incomingRequest.reject({ statusCode: 415 }); + this.emit("reinviteFailed", this); + return; + } + promise.catch(function (e) { + var statusCode; + if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { + statusCode = 500; + } + else if (e.type === Enums_1.TypeStrings.RenegotiationError) { + _this.emit("renegotiationError", e); + _this.logger.warn(e.toString()); + statusCode = 488; + } + else { + _this.logger.error(e); + statusCode = 488; + } + incomingRequest.reject({ statusCode: statusCode }); + _this.emit("reinviteFailed", _this); + // TODO: This could be better + throw e; + }).then(function (description) { + var extraHeaders = ["Contact: " + _this.contact]; + incomingRequest.accept({ + statusCode: 200, + extraHeaders: extraHeaders, + body: messages_1.fromBodyObj(description) + }); + _this.status = Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK; + _this.emit("reinviteAccepted", _this); + }); + }; + Session.prototype.sendReinvite = function (options) { + var _this = this; + if (options === void 0) { options = {}; } + if (this.pendingReinvite) { + this.logger.warn("Reinvite in progress. Please wait until complete, then try again."); + return; + } + if (!this.sessionDescriptionHandler) { + this.logger.warn("No SessionDescriptionHandler, can't reinvite.."); + return; + } + this.pendingReinvite = true; + options.modifiers = options.modifiers || []; + var extraHeaders = (options.extraHeaders || []).slice(); + extraHeaders.push("Contact: " + this.contact); + // this is UA.C.ALLOWED_METHODS, removed to get around circular dependency + extraHeaders.push("Allow: " + [ + "ACK", + "CANCEL", + "INVITE", + "MESSAGE", + "BYE", + "OPTIONS", + "INFO", + "NOTIFY", + "REFER" + ].toString()); + this.sessionDescriptionHandler.getDescription(options.sessionDescriptionHandlerOptions, options.modifiers) + .then(function (description) { + if (!_this.session) { + throw new Error("Session undefined."); + } + var delegate = { + onAccept: function (response) { + if (_this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { + _this.logger.error("Received reinvite response, but in STATUS_TERMINATED"); + // TODO: Do we need to send a SIP response? + return; + } + if (!_this.pendingReinvite) { + _this.logger.error("Received reinvite response, but have no pending reinvite"); + // TODO: Do we need to send a SIP response? + return; + } + // FIXME: Why is this set here? + _this.status = Enums_1.SessionStatus.STATUS_CONFIRMED; + // 17.1.1.1 - For each final response that is received at the client transaction, + // the client transaction sends an ACK, + _this.emit("ack", response.ack()); + _this.pendingReinvite = false; + // TODO: All of these timers should move into the Transaction layer + clearTimeout(_this.timers.invite2xxTimer); + if (!_this.sessionDescriptionHandler || + !_this.sessionDescriptionHandler.hasDescription(response.message.getHeader("Content-Type") || "")) { + _this.logger.error("2XX response received to re-invite but did not have a description"); + _this.emit("reinviteFailed", _this); + _this.emit("renegotiationError", new Exceptions_1.Exceptions.RenegotiationError("2XX response received to re-invite but did not have a description")); + return; + } + _this.sessionDescriptionHandler + .setDescription(response.message.body, _this.sessionDescriptionHandlerOptions, _this.modifiers) + .catch(function (e) { + _this.logger.error("Could not set the description in 2XX response"); + _this.logger.error(e); + _this.emit("reinviteFailed", _this); + _this.emit("renegotiationError", e); + _this.sendRequest(Constants_1.C.BYE, { + extraHeaders: ["Reason: " + Utils_1.Utils.getReasonHeaderValue(488, "Not Acceptable Here")] + }); + _this.terminated(undefined, Constants_1.C.causes.INCOMPATIBLE_SDP); + throw e; + }) + .then(function () { + _this.emit("reinviteAccepted", _this); + }); + }, + onProgress: function (response) { + return; + }, + onRedirect: function (response) { + // FIXME: Does ACK need to be sent? + _this.pendingReinvite = false; + _this.logger.log("Received a non 1XX or 2XX response to a re-invite"); + _this.emit("reinviteFailed", _this); + _this.emit("renegotiationError", new Exceptions_1.Exceptions.RenegotiationError("Invalid response to a re-invite")); + }, + onReject: function (response) { + // FIXME: Does ACK need to be sent? + _this.pendingReinvite = false; + _this.logger.log("Received a non 1XX or 2XX response to a re-invite"); + _this.emit("reinviteFailed", _this); + _this.emit("renegotiationError", new Exceptions_1.Exceptions.RenegotiationError("Invalid response to a re-invite")); + }, + onTrying: function (response) { + return; + } + }; + var requestOptions = { + extraHeaders: extraHeaders, + body: messages_1.fromBodyObj(description) + }; + _this.session.invite(delegate, requestOptions); + }).catch(function (e) { + if (e.type === Enums_1.TypeStrings.RenegotiationError) { + _this.pendingReinvite = false; + _this.emit("renegotiationError", e); + _this.logger.warn("Renegotiation Error"); + _this.logger.warn(e.toString()); + throw e; + } + _this.logger.error("sessionDescriptionHandler error"); + _this.logger.error(e); + throw e; + }); + }; + Session.prototype.failed = function (response, cause) { + if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { + return this; + } + this.emit("failed", response, cause); + return this; + }; + Session.prototype.rejected = function (response, cause) { + this.emit("rejected", response, cause); + return this; + }; + Session.prototype.canceled = function () { + if (this.sessionDescriptionHandler) { + this.sessionDescriptionHandler.close(); + } + this.emit("cancel"); + return this; + }; + Session.prototype.accepted = function (response, cause) { + if (!(response instanceof String)) { + cause = Utils_1.Utils.getReasonPhrase((response && response.statusCode) || 0, cause); + } + this.startTime = new Date(); + if (this.replacee) { + this.replacee.emit("replaced", this); + this.replacee.terminate(); + } + this.emit("accepted", response, cause); + return this; + }; + Session.prototype.terminated = function (message, cause) { + if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { + return this; + } + this.endTime = new Date(); + this.close(); + this.emit("terminated", message, cause); + return this; + }; + Session.prototype.connecting = function (request) { + this.emit("connecting", { request: request }); + return this; + }; + Session.C = Enums_1.SessionStatus; + return Session; +}(events_1.EventEmitter)); +exports.Session = Session; +// tslint:disable-next-line:max-classes-per-file +var InviteServerContext = /** @class */ (function (_super) { + __extends(InviteServerContext, _super); + function InviteServerContext(ua, incomingInviteRequest) { + var _this = this; + if (!ua.configuration.sessionDescriptionHandlerFactory) { + ua.logger.warn("Can't build ISC without SDH Factory"); + throw new Error("ISC Constructor Failed"); + } + _this = _super.call(this, ua.configuration.sessionDescriptionHandlerFactory) || this; + _this._canceled = false; + _this.rseq = Math.floor(Math.random() * 10000); + _this.incomingRequest = incomingInviteRequest; + var request = incomingInviteRequest.message; + ServerContext_1.ServerContext.initializer(_this, ua, incomingInviteRequest); + _this.type = Enums_1.TypeStrings.InviteServerContext; + var contentDisp = request.parseHeader("Content-Disposition"); + if (contentDisp && contentDisp.type === "render") { + _this.renderbody = request.body; + _this.rendertype = request.getHeader("Content-Type"); + } + _this.status = Enums_1.SessionStatus.STATUS_INVITE_RECEIVED; + _this.fromTag = request.fromTag; + _this.id = request.callId + _this.fromTag; + _this.request = request; + _this.contact = _this.ua.contact.toString(); + _this.logger = ua.getLogger("sip.inviteservercontext", _this.id); + // Save the session into the ua sessions collection. + _this.ua.sessions[_this.id] = _this; + // Set 100rel if necessary + var set100rel = function (header, relSetting) { + if (request.hasHeader(header) && request.getHeader(header).toLowerCase().indexOf("100rel") >= 0) { + _this.rel100 = relSetting; + } + }; + set100rel("require", Constants_1.C.supported.REQUIRED); + set100rel("supported", Constants_1.C.supported.SUPPORTED); + // Set the toTag on the incoming request to the toTag which + // will be used in the response to the incoming request!!! + // FIXME: HACK: This is a hack to port an existing behavior. + // The behavior being ported appears to be a hack itself, + // so this is a hack to port a hack. At least one test spec + // relies on it (which is yet another hack). + _this.request.toTag = incomingInviteRequest.toTag; + _this.status = Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER; + // Set userNoAnswerTimer + _this.timers.userNoAnswerTimer = setTimeout(function () { + incomingInviteRequest.reject({ statusCode: 408 }); + _this.failed(request, Constants_1.C.causes.NO_ANSWER); + _this.terminated(request, Constants_1.C.causes.NO_ANSWER); + }, _this.ua.configuration.noAnswerTimeout || 60); + /* Set expiresTimer + * RFC3261 13.3.1 + */ + // Get the Expires header value if exists + if (request.hasHeader("expires")) { + var expires = Number(request.getHeader("expires") || 0) * 1000; + _this.timers.expiresTimer = setTimeout(function () { + if (_this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER) { + incomingInviteRequest.reject({ statusCode: 487 }); + _this.failed(request, Constants_1.C.causes.EXPIRES); + _this.terminated(request, Constants_1.C.causes.EXPIRES); + } + }, expires); + } + _this.errorListener = _this.onTransportError.bind(_this); + if (ua.transport) { + ua.transport.on("transportError", _this.errorListener); + } + return _this; + } + Object.defineProperty(InviteServerContext.prototype, "autoSendAnInitialProvisionalResponse", { + /** + * If true, a first provisional response after the 100 Trying + * will be sent automatically. This is false it the UAC required + * reliable provisional responses (100rel in Require header), + * otherwise it is true. The provisional is sent by calling + * `progress()` without any options. + * + * FIXME: TODO: It seems reasonable that the ISC user should + * be able to optionally disable this behavior. As the provisional + * is sent prior to the "invite" event being emitted, it's a known + * issue that the ISC user cannot register listeners or do any other + * setup prior to the call to `progress()`. As an example why this is + * an issue, setting `ua.configuration.rel100` to REQUIRED will result + * in an attempt by `progress()` to send a 183 with SDP produced by + * calling `getDescription()` on a session description handler, but + * the ISC user cannot perform any potentially required session description + * handler initialization (thus preventing the utilization of setting + * `ua.configuration.rel100` to REQUIRED). That begs the question of + * why this behavior is disabled when the UAC requires 100rel but not + * when the UAS requires 100rel? But ignoring that, it's just one example + * of a class of cases where the ISC user needs to do something prior + * to the first call to `progress()` and is unable to do so. + */ + get: function () { + return this.rel100 === Constants_1.C.supported.REQUIRED ? false : true; + }, + enumerable: true, + configurable: true + }); + // type hack for servercontext interface + InviteServerContext.prototype.reply = function (options) { + if (options === void 0) { options = {}; } + return this; + }; + // typing note: this was the only function using its super in ServerContext + // so the bottom half of this function is copied and paired down from that + InviteServerContext.prototype.reject = function (options) { + var _this = this; + if (options === void 0) { options = {}; } + // Check Session Status + if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { + throw new Exceptions_1.Exceptions.InvalidStateError(this.status); + } + this.logger.log("rejecting RTCSession"); + var statusCode = options.statusCode || 480; + var reasonPhrase = Utils_1.Utils.getReasonPhrase(statusCode, options.reasonPhrase); + var extraHeaders = options.extraHeaders || []; + if (statusCode < 300 || statusCode > 699) { + throw new TypeError("Invalid statusCode: " + statusCode); + } + var body = options.body ? messages_1.fromBodyLegacy(options.body) : undefined; + // FIXME: Need to redirect to someplae + var response = statusCode < 400 ? + this.incomingRequest.redirect([], { statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }) : + this.incomingRequest.reject({ statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }); + (["rejected", "failed"]).forEach(function (event) { + _this.emit(event, response.message, reasonPhrase); + }); + return this.terminated(); + }; + /** + * Accept the incoming INVITE request to start a Session. + * Replies to the INVITE request with a 200 Ok response. + * @param options Options bucket. + */ + InviteServerContext.prototype.accept = function (options) { + var _this = this; + if (options === void 0) { options = {}; } + // FIXME: Need guard against calling more than once. + this._accept(options) + .then(function (_a) { + var message = _a.message, session = _a.session; + session.delegate = { + onAck: function (ackRequest) { return _this.onAck(ackRequest); }, + onAckTimeout: function () { return _this.onAckTimeout(); }, + onBye: function (byeRequest) { return _this.receiveRequest(byeRequest); }, + onInfo: function (infoRequest) { return _this.receiveRequest(infoRequest); }, + onInvite: function (inviteRequest) { return _this.receiveRequest(inviteRequest); }, + onNotify: function (notifyRequest) { return _this.receiveRequest(notifyRequest); }, + onPrack: function (prackRequest) { return _this.receiveRequest(prackRequest); }, + onRefer: function (referRequest) { return _this.receiveRequest(referRequest); } + }; + _this.session = session; + _this.status = Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK; + _this.accepted(message, Utils_1.Utils.getReasonPhrase(200)); + }) + .catch(function (error) { + _this.onContextError(error); + // FIXME: Assuming error due to async race on CANCEL and eating error. + if (!_this._canceled) { + throw error; + } + }); + return this; + }; + /** + * Report progress to the the caller. + * Replies to the INVITE request with a 1xx provisional response. + * @param options Options bucket. + */ + InviteServerContext.prototype.progress = function (options) { + var _this = this; + if (options === void 0) { options = {}; } + // Ported + var statusCode = options.statusCode || 180; + if (statusCode < 100 || statusCode > 199) { + throw new TypeError("Invalid statusCode: " + statusCode); + } + // Ported + if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { + this.logger.warn("Unexpected call for progress while terminated, ignoring"); + return this; + } + // Added + if (this.status === Enums_1.SessionStatus.STATUS_ANSWERED) { + this.logger.warn("Unexpected call for progress while answered, ignoring"); + return this; + } + // Added + if (this.status === Enums_1.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK) { + this.logger.warn("Unexpected call for progress while answered (waiting for prack), ignoring"); + return this; + } + // After the first reliable provisional response for a request has been + // acknowledged, the UAS MAY send additional reliable provisional + // responses. The UAS MUST NOT send a second reliable provisional + // response until the first is acknowledged. After the first, it is + // RECOMMENDED that the UAS not send an additional reliable provisional + // response until the previous is acknowledged. The first reliable + // provisional response receives special treatment because it conveys + // the initial sequence number. If additional reliable provisional + // responses were sent before the first was acknowledged, the UAS could + // not be certain these were received in order. + // https://tools.ietf.org/html/rfc3262#section-3 + if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_PRACK) { + this.logger.warn("Unexpected call for progress while waiting for prack, ignoring"); + return this; + } + // Ported + if (options.statusCode === 100) { + try { + this.incomingRequest.trying(); + } + catch (error) { + this.onContextError(error); + // FIXME: Assuming error due to async race on CANCEL and eating error. + if (!this._canceled) { + throw error; + } + } + return this; + } + // Standard provisional response. + if (!(this.rel100 === Constants_1.C.supported.REQUIRED) && + !(this.rel100 === Constants_1.C.supported.SUPPORTED && options.rel100) && + !(this.rel100 === Constants_1.C.supported.SUPPORTED && this.ua.configuration.rel100 === Constants_1.C.supported.REQUIRED)) { + this._progress(options) + .catch(function (error) { + _this.onContextError(error); + // FIXME: Assuming error due to async race on CANCEL and eating error. + if (!_this._canceled) { + throw error; + } + }); + return this; + } + // Reliable provisional response. + this._reliableProgressWaitForPrack(options) + .catch(function (error) { + _this.onContextError(error); + // FIXME: Assuming error due to async race on CANCEL and eating error. + if (!_this._canceled) { + throw error; + } + }); + return this; + }; + /** + * Reject an unaccepted incoming INVITE request or send BYE if established session. + * @param options Options bucket. FIXME: This options bucket needs to be typed. + */ + InviteServerContext.prototype.terminate = function (options) { + // The caller's UA MAY send a BYE for either confirmed or early dialogs, + // and the callee's UA MAY send a BYE on confirmed dialogs, but MUST NOT + // send a BYE on early dialogs. However, the callee's UA MUST NOT send a + // BYE on a confirmed dialog until it has received an ACK for its 2xx + // response or until the server transaction times out. + // https://tools.ietf.org/html/rfc3261#section-15 + var _this = this; + if (options === void 0) { options = {}; } + // We don't yet have a dialog, so reject request. + if (!this.session) { + this.reject(options); + return this; + } + switch (this.session.sessionState) { + case session_1.SessionState.Initial: + this.reject(options); + return this; + case session_1.SessionState.Early: + this.reject(options); + return this; + case session_1.SessionState.AckWait: + this.session.delegate = { + // When ACK shows up, say BYE. + onAck: function () { + _this.sendRequest(Constants_1.C.BYE, options); + }, + // Or the server transaction times out before the ACK arrives. + onAckTimeout: function () { + _this.sendRequest(Constants_1.C.BYE, options); + } + }; + // Ported + this.emit("bye", this.request); + this.terminated(); + return this; + case session_1.SessionState.Confirmed: + this.bye(options); + return this; + case session_1.SessionState.Terminated: + return this; + default: + return this; + } + }; + InviteServerContext.prototype.onCancel = function (message) { + if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER || + this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_PRACK || + this.status === Enums_1.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK || + this.status === Enums_1.SessionStatus.STATUS_EARLY_MEDIA || + this.status === Enums_1.SessionStatus.STATUS_ANSWERED) { + this.status = Enums_1.SessionStatus.STATUS_CANCELED; + this.incomingRequest.reject({ statusCode: 487 }); + this.canceled(); + this.rejected(message, Constants_1.C.causes.CANCELED); + this.failed(message, Constants_1.C.causes.CANCELED); + this.terminated(message, Constants_1.C.causes.CANCELED); + } + }; + InviteServerContext.prototype.receiveRequest = function (incomingRequest) { + var _this = this; + switch (incomingRequest.message.method) { + case Constants_1.C.PRACK: + if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_PRACK || + this.status === Enums_1.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK) { + if (!this.hasAnswer) { + this.sessionDescriptionHandler = this.setupSessionDescriptionHandler(); + this.emit("SessionDescriptionHandler-created", this.sessionDescriptionHandler); + if (this.sessionDescriptionHandler.hasDescription(incomingRequest.message.getHeader("Content-Type") || "")) { + this.hasAnswer = true; + this.sessionDescriptionHandler.setDescription(incomingRequest.message.body, this.sessionDescriptionHandlerOptions, this.modifiers).then(function () { + clearTimeout(_this.timers.rel1xxTimer); + clearTimeout(_this.timers.prackTimer); + incomingRequest.accept(); + if (_this.status === Enums_1.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK) { + _this.status = Enums_1.SessionStatus.STATUS_EARLY_MEDIA; + _this.accept(); + } + _this.status = Enums_1.SessionStatus.STATUS_EARLY_MEDIA; + }, function (e) { + _this.logger.warn(e); + _this.terminate({ + statusCode: "488", + reasonPhrase: "Bad Media Description" + }); + _this.failed(incomingRequest.message, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); + _this.terminated(incomingRequest.message, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); + }); + } + else { + this.terminate({ + statusCode: "488", + reasonPhrase: "Bad Media Description" + }); + this.failed(incomingRequest.message, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); + this.terminated(incomingRequest.message, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); + } + } + else { + clearTimeout(this.timers.rel1xxTimer); + clearTimeout(this.timers.prackTimer); + incomingRequest.accept(); + if (this.status === Enums_1.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK) { + this.status = Enums_1.SessionStatus.STATUS_EARLY_MEDIA; + this.accept(); + } + this.status = Enums_1.SessionStatus.STATUS_EARLY_MEDIA; + } + } + else if (this.status === Enums_1.SessionStatus.STATUS_EARLY_MEDIA) { + incomingRequest.accept(); + } + break; + default: + _super.prototype.receiveRequest.call(this, incomingRequest); + break; + } + }; + // Internal Function to setup the handler consistently + InviteServerContext.prototype.setupSessionDescriptionHandler = function () { + if (this.sessionDescriptionHandler) { + return this.sessionDescriptionHandler; + } + return this.sessionDescriptionHandlerFactory(this, this.ua.configuration.sessionDescriptionHandlerFactoryOptions); + }; + InviteServerContext.prototype.generateResponseOfferAnswer = function (options) { + if (!this.session) { + var body = messages_1.getBody(this.incomingRequest.message); + if (!body || body.contentDisposition !== "session") { + return this.getOffer(options); + } + else { + return this.setOfferAndGetAnswer(body, options); + } + } + else { + switch (this.session.signalingState) { + case session_1.SignalingState.Initial: + return this.getOffer(options); + case session_1.SignalingState.Stable: + return Promise.resolve(undefined); + case session_1.SignalingState.HaveLocalOffer: + // o Once the UAS has sent or received an answer to the initial + // offer, it MUST NOT generate subsequent offers in any responses + // to the initial INVITE. This means that a UAS based on this + // specification alone can never generate subsequent offers until + // completion of the initial transaction. + // https://tools.ietf.org/html/rfc3261#section-13.2.1 + return Promise.resolve(undefined); + case session_1.SignalingState.HaveRemoteOffer: + if (!this.session.offer) { + throw new Error("Session offer undefined"); + } + return this.setOfferAndGetAnswer(this.session.offer, options); + case session_1.SignalingState.Closed: + throw new Error("Invalid signaling state " + this.session.signalingState + "."); + default: + throw new Error("Invalid signaling state " + this.session.signalingState + "."); + } + } + }; + InviteServerContext.prototype.handlePrackOfferAnswer = function (request, options) { + if (!this.session) { + throw new Error("Session undefined."); + } + // If the PRACK doesn't have an offer/answer, nothing to be done. + var body = messages_1.getBody(request.message); + if (!body || body.contentDisposition !== "session") { + return Promise.resolve(undefined); + } + // If the UAC receives a reliable provisional response with an offer + // (this would occur if the UAC sent an INVITE without an offer, in + // which case the first reliable provisional response will contain the + // offer), it MUST generate an answer in the PRACK. If the UAC receives + // a reliable provisional response with an answer, it MAY generate an + // additional offer in the PRACK. If the UAS receives a PRACK with an + // offer, it MUST place the answer in the 2xx to the PRACK. + // https://tools.ietf.org/html/rfc3262#section-5 + switch (this.session.signalingState) { + case session_1.SignalingState.Initial: + // State should never be reached as first reliable provisional response must have answer/offer. + throw new Error("Invalid signaling state " + this.session.signalingState + "."); + case session_1.SignalingState.Stable: + // Receved answer. + return this.setAnswer(body, options).then(function () { return undefined; }); + case session_1.SignalingState.HaveLocalOffer: + // State should never be reached as local offer would be answered by this PRACK + throw new Error("Invalid signaling state " + this.session.signalingState + "."); + case session_1.SignalingState.HaveRemoteOffer: + // Receved offer, generate answer. + return this.setOfferAndGetAnswer(body, options); + case session_1.SignalingState.Closed: + throw new Error("Invalid signaling state " + this.session.signalingState + "."); + default: + throw new Error("Invalid signaling state " + this.session.signalingState + "."); + } + }; + /** + * Called when session canceled. + */ + InviteServerContext.prototype.canceled = function () { + this._canceled = true; + return _super.prototype.canceled.call(this); + }; + /** + * Called when session terminated. + * Using it here just for the PRACK timeout. + */ + InviteServerContext.prototype.terminated = function (message, cause) { + this.prackNeverArrived(); + return _super.prototype.terminated.call(this, message, cause); + }; + /** + * A version of `accept` which resolves a session when the 200 Ok response is sent. + * @param options Options bucket. + * @throws {ClosedSessionDescriptionHandlerError} The session description handler closed before method completed. + * @throws {TransactionStateError} The transaction state does not allow for `accept()` to be called. + * Note that the transaction state can change while this call is in progress. + */ + InviteServerContext.prototype._accept = function (options) { + var _this = this; + if (options === void 0) { options = {}; } + // FIXME: Ported - callback for in dialog INFO requests. + // Turns out accept() can be called more than once if we are waiting + // for a PRACK in which case "options" get completely tossed away. + // So this is broken in that case (and potentially other uses of options). + // Tempted to just try to fix it now, but leaving it broken for the moment. + this.onInfo = options.onInfo; + // The UAS MAY send a final response to the initial request before + // having received PRACKs for all unacknowledged reliable provisional + // responses, unless the final response is 2xx and any of the + // unacknowledged reliable provisional responses contained a session + // description. In that case, it MUST NOT send a final response until + // those provisional responses are acknowledged. If the UAS does send a + // final response when reliable responses are still unacknowledged, it + // SHOULD NOT continue to retransmit the unacknowledged reliable + // provisional responses, but it MUST be prepared to process PRACK + // requests for those outstanding responses. A UAS MUST NOT send new + // reliable provisional responses (as opposed to retransmissions of + // unacknowledged ones) after sending a final response to a request. + // https://tools.ietf.org/html/rfc3262#section-3 + if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_PRACK) { + this.status = Enums_1.SessionStatus.STATUS_ANSWERED_WAITING_FOR_PRACK; + return this.waitForArrivalOfPrack() + .then(function () { + _this.status = Enums_1.SessionStatus.STATUS_ANSWERED; + clearTimeout(_this.timers.userNoAnswerTimer); // Ported + }) + .then(function () { return _this.generateResponseOfferAnswer(options); }) + .then(function (body) { return _this.incomingRequest.accept({ statusCode: 200, body: body }); }); + } + // Ported + if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER) { + this.status = Enums_1.SessionStatus.STATUS_ANSWERED; + } + else { + return Promise.reject(new Exceptions_1.Exceptions.InvalidStateError(this.status)); + } + this.status = Enums_1.SessionStatus.STATUS_ANSWERED; + clearTimeout(this.timers.userNoAnswerTimer); // Ported + return this.generateResponseOfferAnswer(options) + .then(function (body) { return _this.incomingRequest.accept({ statusCode: 200, body: body }); }); + }; + /** + * A version of `progress` which resolves when the provisional response is sent. + * @param options Options bucket. + * @throws {ClosedSessionDescriptionHandlerError} The session description handler closed before method completed. + * @throws {TransactionStateError} The transaction state does not allow for `progress()` to be called. + * Note that the transaction state can change while this call is in progress. + */ + InviteServerContext.prototype._progress = function (options) { + if (options === void 0) { options = {}; } + // Ported + var statusCode = options.statusCode || 180; + var reasonPhrase = options.reasonPhrase; + var extraHeaders = (options.extraHeaders || []).slice(); + var body = options.body ? messages_1.fromBodyLegacy(options.body) : undefined; + try { + var progressResponse = this.incomingRequest.progress({ statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }); + this.emit("progress", progressResponse.message, reasonPhrase); // Ported + this.session = progressResponse.session; + return Promise.resolve(progressResponse); + } + catch (error) { + return Promise.reject(error); + } + }; + /** + * A version of `progress` which resolves when the reliable provisional response is sent. + * @param options Options bucket. + * @throws {ClosedSessionDescriptionHandlerError} The session description handler closed before method completed. + * @throws {TransactionStateError} The transaction state does not allow for `progress()` to be called. + * Note that the transaction state can change while this call is in progress. + */ + InviteServerContext.prototype._reliableProgress = function (options) { + var _this = this; + if (options === void 0) { options = {}; } + var statusCode = options.statusCode || 183; + var reasonPhrase = options.reasonPhrase; + var extraHeaders = (options.extraHeaders || []).slice(); + extraHeaders.push("Require: 100rel"); + extraHeaders.push("RSeq: " + Math.floor(Math.random() * 10000)); + // Get an offer/answer and send a reply. + return this.generateResponseOfferAnswer(options) + .then(function (body) { return _this.incomingRequest.progress({ statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }); }) + .then(function (progressResponse) { + _this.emit("progress", progressResponse.message, reasonPhrase); // Ported + _this.session = progressResponse.session; + return progressResponse; + }); + }; + /** + * A version of `progress` which resolves when the reliable provisional response is acknowledged. + * @param options Options bucket. + * @throws {ClosedSessionDescriptionHandlerError} The session description handler closed before method completed. + * @throws {TransactionStateError} The transaction state does not allow for `progress()` to be called. + * Note that the transaction state can change while this call is in progress. + */ + InviteServerContext.prototype._reliableProgressWaitForPrack = function (options) { + var _this = this; + if (options === void 0) { options = {}; } + var statusCode = options.statusCode || 183; + var reasonPhrase = options.reasonPhrase; + var extraHeaders = (options.extraHeaders || []).slice(); + extraHeaders.push("Require: 100rel"); + extraHeaders.push("RSeq: " + this.rseq++); + var body; + // Ported - set status. + this.status = Enums_1.SessionStatus.STATUS_WAITING_FOR_PRACK; + return new Promise(function (resolve, reject) { + var waitingForPrack = true; + return _this.generateResponseOfferAnswer(options) + .then(function (offerAnswer) { + body = offerAnswer; + return _this.incomingRequest.progress({ statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }); + }) + .then(function (progressResponse) { + _this.emit("progress", progressResponse.message, reasonPhrase); // Ported + _this.session = progressResponse.session; + var prackRequest; + var prackResponse; + progressResponse.session.delegate = { + onPrack: function (request) { + prackRequest = request; + clearTimeout(prackWaitTimeoutTimer); + clearTimeout(rel1xxRetransmissionTimer); + if (!waitingForPrack) { + return; + } + waitingForPrack = false; + _this.handlePrackOfferAnswer(prackRequest, options) + .then(function (prackResponseBody) { + try { + prackResponse = prackRequest.accept({ statusCode: 200, body: prackResponseBody }); + // Ported - set status. + if (_this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_PRACK) { + _this.status = Enums_1.SessionStatus.STATUS_WAITING_FOR_ANSWER; + } + _this.prackArrived(); + resolve({ prackRequest: prackRequest, prackResponse: prackResponse, progressResponse: progressResponse }); + } + catch (error) { + reject(error); + } + }); + } + }; + // https://tools.ietf.org/html/rfc3262#section-3 + var prackWaitTimeout = function () { + if (!waitingForPrack) { + return; + } + waitingForPrack = false; + _this.logger.warn("No PRACK received, rejecting INVITE."); + clearTimeout(rel1xxRetransmissionTimer); + try { + _this.incomingRequest.reject({ statusCode: 504 }); + _this.terminated(undefined, Constants_1.C.causes.NO_PRACK); + reject(new Exceptions_1.Exceptions.TerminatedSessionError()); + } + catch (error) { + reject(error); + } + }; + var prackWaitTimeoutTimer = setTimeout(prackWaitTimeout, Timers_1.Timers.T1 * 64); + // https://tools.ietf.org/html/rfc3262#section-3 + var rel1xxRetransmission = function () { + try { + _this.incomingRequest.progress({ statusCode: statusCode, reasonPhrase: reasonPhrase, extraHeaders: extraHeaders, body: body }); + } + catch (error) { + waitingForPrack = false; + reject(error); + return; + } + rel1xxRetransmissionTimer = setTimeout(rel1xxRetransmission, timeout *= 2); + }; + var timeout = Timers_1.Timers.T1; + var rel1xxRetransmissionTimer = setTimeout(rel1xxRetransmission, timeout); + }); + }); + }; + /** + * Callback for when ACK for a 2xx response is never received. + * @param session Session the ACK never arrived for + */ + InviteServerContext.prototype.onAckTimeout = function () { + if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK) { + this.logger.log("no ACK received for an extended period of time, terminating the call"); + if (!this.session) { + throw new Error("Session undefined."); + } + this.session.bye(); + this.terminated(undefined, Constants_1.C.causes.NO_ACK); + } + }; + /** + * FIXME: TODO: The current library interface presents async methods without a + * proper async error handling mechanism. Arguably a promise based interface + * would be an improvement over the pattern of returning `this`. The approach has + * been generally along the lines of log a error and terminate. + */ + InviteServerContext.prototype.onContextError = function (error) { + var statusCode = 480; + if (error instanceof Exceptions_1.Exception) { // There might be interest in catching these Exceptions. + if (error instanceof Exceptions_1.Exceptions.SessionDescriptionHandlerError) { + this.logger.error(error.message); + if (error.error) { + this.logger.error(error.error); + } + } + else if (error instanceof Exceptions_1.Exceptions.TerminatedSessionError) { + // PRACK never arrived, so we timed out waiting for it. + this.logger.warn("Incoming session terminated while waiting for PRACK."); + } + else if (error instanceof Exceptions_1.Exceptions.UnsupportedSessionDescriptionContentTypeError) { + statusCode = 415; + } + else if (error instanceof Exceptions_1.Exception) { + this.logger.error(error.message); + } + } + else if (error instanceof Error) { // Other Errors hould go uncaught. + this.logger.error(error.message); + } + else { + // We don't actually know what a session description handler implementation might throw + // our way, so as a last resort, just assume we are getting an "any" and log it. + this.logger.error("An error occurred in the session description handler."); + this.logger.error(error); + } + try { + this.incomingRequest.reject({ statusCode: statusCode }); // "Temporarily Unavailable" + this.failed(this.incomingRequest.message, error.message); + this.terminated(this.incomingRequest.message, error.message); + } + catch (error) { + return; + } + }; + InviteServerContext.prototype.prackArrived = function () { + if (this.waitingForPrackResolve) { + this.waitingForPrackResolve(); + } + this.waitingForPrackPromise = undefined; + this.waitingForPrackResolve = undefined; + this.waitingForPrackReject = undefined; + }; + InviteServerContext.prototype.prackNeverArrived = function () { + if (this.waitingForPrackReject) { + this.waitingForPrackReject(new Exceptions_1.Exceptions.TerminatedSessionError()); + } + this.waitingForPrackPromise = undefined; + this.waitingForPrackResolve = undefined; + this.waitingForPrackReject = undefined; + }; + /** + * @throws {Exceptions.TerminatedSessionError} The session terminated before being accepted (i.e. cancel arrived). + */ + InviteServerContext.prototype.waitForArrivalOfPrack = function () { + var _this = this; + if (this.waitingForPrackPromise) { + throw new Error("Already waiting for PRACK"); + } + this.waitingForPrackPromise = new Promise(function (resolve, reject) { + _this.waitingForPrackResolve = resolve; + _this.waitingForPrackReject = reject; + }); + return this.waitingForPrackPromise; + }; + InviteServerContext.prototype.getOffer = function (options) { + this.hasOffer = true; + var sdh = this.getSessionDescriptionHandler(); + return sdh + .getDescription(options.sessionDescriptionHandlerOptions, options.modifiers) + .then(function (bodyObj) { return messages_1.fromBodyObj(bodyObj); }); + }; + InviteServerContext.prototype.setAnswer = function (answer, options) { + this.hasAnswer = true; + var sdh = this.getSessionDescriptionHandler(); + if (!sdh.hasDescription(answer.contentType)) { + return Promise.reject(new Exceptions_1.Exceptions.UnsupportedSessionDescriptionContentTypeError()); + } + return sdh + .setDescription(answer.content, options.sessionDescriptionHandlerOptions, options.modifiers); + }; + InviteServerContext.prototype.setOfferAndGetAnswer = function (offer, options) { + this.hasOffer = true; + this.hasAnswer = true; + var sdh = this.getSessionDescriptionHandler(); + if (!sdh.hasDescription(offer.contentType)) { + return Promise.reject(new Exceptions_1.Exceptions.UnsupportedSessionDescriptionContentTypeError()); + } + return sdh + .setDescription(offer.content, options.sessionDescriptionHandlerOptions, options.modifiers) + .then(function () { return sdh.getDescription(options.sessionDescriptionHandlerOptions, options.modifiers); }) + .then(function (bodyObj) { return messages_1.fromBodyObj(bodyObj); }); + }; + InviteServerContext.prototype.getSessionDescriptionHandler = function () { + // Create our session description handler if not already done so... + var sdh = this.sessionDescriptionHandler = this.setupSessionDescriptionHandler(); + // FIXME: Ported - this can get emitted multiple times even when only created once... don't we care? + this.emit("SessionDescriptionHandler-created", this.sessionDescriptionHandler); + // Return. + return sdh; + }; + return InviteServerContext; +}(Session)); +exports.InviteServerContext = InviteServerContext; +// tslint:disable-next-line:max-classes-per-file +var InviteClientContext = /** @class */ (function (_super) { + __extends(InviteClientContext, _super); + function InviteClientContext(ua, target, options, modifiers) { + if (options === void 0) { options = {}; } + if (modifiers === void 0) { modifiers = []; } + var _this = this; + if (!ua.configuration.sessionDescriptionHandlerFactory) { + ua.logger.warn("Can't build ISC without SDH Factory"); + throw new Error("ICC Constructor Failed"); + } + options.params = options.params || {}; + var anonymous = options.anonymous || false; + var fromTag = Utils_1.Utils.newTag(); + options.params.fromTag = fromTag; + /* Do not add ;ob in initial forming dialog requests if the registration over + * the current connection got a GRUU URI. + */ + var contact = ua.contact.toString({ + anonymous: anonymous, + outbound: anonymous ? !ua.contact.tempGruu : !ua.contact.pubGruu + }); + var extraHeaders = (options.extraHeaders || []).slice(); + if (anonymous && ua.configuration.uri) { + options.params.from_displayName = "Anonymous"; + options.params.from_uri = "sip:anonymous@anonymous.invalid"; + extraHeaders.push("P-Preferred-Identity: " + ua.configuration.uri.toString()); + extraHeaders.push("Privacy: id"); + } + extraHeaders.push("Contact: " + contact); + // this is UA.C.ALLOWED_METHODS, removed to get around circular dependency + extraHeaders.push("Allow: " + [ + "ACK", + "CANCEL", + "INVITE", + "MESSAGE", + "BYE", + "OPTIONS", + "INFO", + "NOTIFY", + "REFER" + ].toString()); + if (ua.configuration.rel100 === Constants_1.C.supported.REQUIRED) { + extraHeaders.push("Require: 100rel"); + } + if (ua.configuration.replaces === Constants_1.C.supported.REQUIRED) { + extraHeaders.push("Require: replaces"); + } + options.extraHeaders = extraHeaders; + _this = _super.call(this, ua.configuration.sessionDescriptionHandlerFactory) || this; + ClientContext_1.ClientContext.initializer(_this, ua, Constants_1.C.INVITE, target, options); + _this.earlyMediaSessionDescriptionHandlers = new Map(); + _this.type = Enums_1.TypeStrings.InviteClientContext; + _this.passedOptions = options; // Save for later to use with refer + _this.sessionDescriptionHandlerOptions = options.sessionDescriptionHandlerOptions || {}; + _this.modifiers = modifiers; + _this.inviteWithoutSdp = options.inviteWithoutSdp || false; + // Set anonymous property + _this.anonymous = options.anonymous || false; + // Custom data to be sent either in INVITE or in ACK + _this.renderbody = options.renderbody || undefined; + _this.rendertype = options.rendertype || "text/plain"; + // Session parameter initialization + _this.fromTag = fromTag; + _this.contact = contact; + // Check Session Status + if (_this.status !== Enums_1.SessionStatus.STATUS_NULL) { + throw new Exceptions_1.Exceptions.InvalidStateError(_this.status); + } + // OutgoingSession specific parameters + _this.isCanceled = false; + _this.received100 = false; + _this.method = Constants_1.C.INVITE; + _this.logger = ua.getLogger("sip.inviteclientcontext"); + ua.applicants[_this.toString()] = _this; + _this.id = _this.request.callId + _this.fromTag; + _this.onInfo = options.onInfo; + _this.errorListener = _this.onTransportError.bind(_this); + if (ua.transport) { + ua.transport.on("transportError", _this.errorListener); + } + return _this; + } + InviteClientContext.prototype.receiveResponse = function (response) { + throw new Error("Unimplemented."); + }; + // hack for getting around ClientContext interface + InviteClientContext.prototype.send = function () { + this.sendInvite(); + return this; + }; + InviteClientContext.prototype.invite = function () { + var _this = this; + // Save the session into the ua sessions collection. + // Note: placing in constructor breaks call to request.cancel on close... User does not need this anyway + this.ua.sessions[this.id] = this; + // This should allow the function to return so that listeners can be set up for these events + Promise.resolve().then(function () { + // FIXME: There is a race condition where cancel (or terminate) can be called synchronously after invite. + if (_this.isCanceled || _this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { + return; + } + if (_this.inviteWithoutSdp) { + // just send an invite with no sdp... + _this.request.body = _this.renderbody; + _this.status = Enums_1.SessionStatus.STATUS_INVITE_SENT; + _this.send(); + } + else { + // Initialize Media Session + _this.sessionDescriptionHandler = _this.sessionDescriptionHandlerFactory(_this, _this.ua.configuration.sessionDescriptionHandlerFactoryOptions || {}); + _this.emit("SessionDescriptionHandler-created", _this.sessionDescriptionHandler); + _this.sessionDescriptionHandler.getDescription(_this.sessionDescriptionHandlerOptions, _this.modifiers) + .then(function (description) { + // FIXME: There is a race condition where cancel (or terminate) can be called (a)synchronously after invite. + if (_this.isCanceled || _this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { + return; + } + _this.hasOffer = true; + _this.request.body = description; + _this.status = Enums_1.SessionStatus.STATUS_INVITE_SENT; + _this.send(); + }, function (err) { + if (err.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { + _this.logger.log(err.message); + if (err.error) { + _this.logger.log(err.error); + } + } + if (_this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { + return; + } + _this.failed(undefined, Constants_1.C.causes.WEBRTC_ERROR); + _this.terminated(undefined, Constants_1.C.causes.WEBRTC_ERROR); + }); + } + }); + return this; + }; + InviteClientContext.prototype.cancel = function (options) { + if (options === void 0) { options = {}; } + // Check Session Status + if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED || this.status === Enums_1.SessionStatus.STATUS_CONFIRMED) { + throw new Exceptions_1.Exceptions.InvalidStateError(this.status); + } + if (this.isCanceled) { + throw new Exceptions_1.Exceptions.InvalidStateError(Enums_1.SessionStatus.STATUS_CANCELED); + } + this.isCanceled = true; + this.logger.log("Canceling session"); + var cancelReason = Utils_1.Utils.getCancelReason(options.statusCode, options.reasonPhrase); + options.extraHeaders = (options.extraHeaders || []).slice(); + if (this.outgoingInviteRequest) { + this.logger.warn("Canceling session before it was created"); + this.outgoingInviteRequest.cancel(cancelReason, options); + } + return this.canceled(); + }; + InviteClientContext.prototype.terminate = function (options) { + if (this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { + return this; + } + if (this.status === Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK || this.status === Enums_1.SessionStatus.STATUS_CONFIRMED) { + this.bye(options); + } + else { + this.cancel(options); + } + return this; + }; + /** + * 13.2.1 Creating the Initial INVITE + * + * Since the initial INVITE represents a request outside of a dialog, + * its construction follows the procedures of Section 8.1.1. Additional + * processing is required for the specific case of INVITE. + * + * An Allow header field (Section 20.5) SHOULD be present in the INVITE. + * It indicates what methods can be invoked within a dialog, on the UA + * sending the INVITE, for the duration of the dialog. For example, a + * UA capable of receiving INFO requests within a dialog [34] SHOULD + * include an Allow header field listing the INFO method. + * + * A Supported header field (Section 20.37) SHOULD be present in the + * INVITE. It enumerates all the extensions understood by the UAC. + * + * An Accept (Section 20.1) header field MAY be present in the INVITE. + * It indicates which Content-Types are acceptable to the UA, in both + * the response received by it, and in any subsequent requests sent to + * it within dialogs established by the INVITE. The Accept header field + * is especially useful for indicating support of various session + * description formats. + * + * The UAC MAY add an Expires header field (Section 20.19) to limit the + * validity of the invitation. If the time indicated in the Expires + * header field is reached and no final answer for the INVITE has been + * received, the UAC core SHOULD generate a CANCEL request for the + * INVITE, as per Section 9. + * + * A UAC MAY also find it useful to add, among others, Subject (Section + * 20.36), Organization (Section 20.25) and User-Agent (Section 20.41) + * header fields. They all contain information related to the INVITE. + * + * The UAC MAY choose to add a message body to the INVITE. Section + * 8.1.1.10 deals with how to construct the header fields -- Content- + * Type among others -- needed to describe the message body. + * + * https://tools.ietf.org/html/rfc3261#section-13.2.1 + */ + InviteClientContext.prototype.sendInvite = function () { + // There are special rules for message bodies that contain a session + // description - their corresponding Content-Disposition is "session". + // SIP uses an offer/answer model where one UA sends a session + // description, called the offer, which contains a proposed description + // of the session. The offer indicates the desired communications means + // (audio, video, games), parameters of those means (such as codec + // types) and addresses for receiving media from the answerer. The + // other UA responds with another session description, called the + // answer, which indicates which communications means are accepted, the + // parameters that apply to those means, and addresses for receiving + // media from the offerer. An offer/answer exchange is within the + // context of a dialog, so that if a SIP INVITE results in multiple + // dialogs, each is a separate offer/answer exchange. The offer/answer + // model defines restrictions on when offers and answers can be made + // (for example, you cannot make a new offer while one is in progress). + // This results in restrictions on where the offers and answers can + // appear in SIP messages. In this specification, offers and answers + // can only appear in INVITE requests and responses, and ACK. The usage + // of offers and answers is further restricted. For the initial INVITE + // transaction, the rules are: + // + // o The initial offer MUST be in either an INVITE or, if not there, + // in the first reliable non-failure message from the UAS back to + // the UAC. In this specification, that is the final 2xx + // response. + // + // o If the initial offer is in an INVITE, the answer MUST be in a + // reliable non-failure message from UAS back to UAC which is + // correlated to that INVITE. For this specification, that is + // only the final 2xx response to that INVITE. That same exact + // answer MAY also be placed in any provisional responses sent + // prior to the answer. The UAC MUST treat the first session + // description it receives as the answer, and MUST ignore any + // session descriptions in subsequent responses to the initial + // INVITE. + // + // o If the initial offer is in the first reliable non-failure + // message from the UAS back to UAC, the answer MUST be in the + // acknowledgement for that message (in this specification, ACK + // for a 2xx response). + // + // o After having sent or received an answer to the first offer, the + // UAC MAY generate subsequent offers in requests based on rules + // specified for that method, but only if it has received answers + // to any previous offers, and has not sent any offers to which it + // hasn't gotten an answer. + // + // o Once the UAS has sent or received an answer to the initial + // offer, it MUST NOT generate subsequent offers in any responses + // to the initial INVITE. This means that a UAS based on this + // specification alone can never generate subsequent offers until + // completion of the initial transaction. + // + // https://tools.ietf.org/html/rfc3261#section-13.2.1 + var _this = this; + // 5 The Offer/Answer Model and PRACK + // + // RFC 3261 describes guidelines for the sets of messages in which + // offers and answers [3] can appear. Based on those guidelines, this + // extension provides additional opportunities for offer/answer + // exchanges. + // If the INVITE contained an offer, the UAS MAY generate an answer in a + // reliable provisional response (assuming these are supported by the + // UAC). That results in the establishment of the session before + // completion of the call. Similarly, if a reliable provisional + // response is the first reliable message sent back to the UAC, and the + // INVITE did not contain an offer, one MUST appear in that reliable + // provisional response. + // If the UAC receives a reliable provisional response with an offer + // (this would occur if the UAC sent an INVITE without an offer, in + // which case the first reliable provisional response will contain the + // offer), it MUST generate an answer in the PRACK. If the UAC receives + // a reliable provisional response with an answer, it MAY generate an + // additional offer in the PRACK. If the UAS receives a PRACK with an + // offer, it MUST place the answer in the 2xx to the PRACK. + // Once an answer has been sent or received, the UA SHOULD establish the + // session based on the parameters of the offer and answer, even if the + // original INVITE itself has not been responded to. + // If the UAS had placed a session description in any reliable + // provisional response that is unacknowledged when the INVITE is + // accepted, the UAS MUST delay sending the 2xx until the provisional + // response is acknowledged. Otherwise, the reliability of the 1xx + // cannot be guaranteed, and reliability is needed for proper operation + // of the offer/answer exchange. + // All user agents that support this extension MUST support all + // offer/answer exchanges that are possible based on the rules in + // Section 13.2 of RFC 3261, based on the existence of INVITE and PRACK + // as requests, and 2xx and reliable 1xx as non-failure reliable + // responses. + // + // https://tools.ietf.org/html/rfc3262#section-5 + //// + // The Offer/Answer Model Implementation + // + // The offer/answer model is straight forward, but one MUST READ the specifications... + // + // 13.2.1 Creating the Initial INVITE (paragraph 8 in particular) + // https://tools.ietf.org/html/rfc3261#section-13.2.1 + // + // 5 The Offer/Answer Model and PRACK + // https://tools.ietf.org/html/rfc3262#section-5 + // + // Session Initiation Protocol (SIP) Usage of the Offer/Answer Model + // https://tools.ietf.org/html/rfc6337 + // + // *** IMPORTANT IMPLEMENTATION CHOICES *** + // + // TLDR... + // + // 1) Only one offer/answer exchange permitted during initial INVITE. + // 2) No "early media" if the initial offer is in an INVITE. + // + // + // 1) Initial Offer/Answer Restriction. + // + // Our implementation replaces the following bullet point... + // + // o After having sent or received an answer to the first offer, the + // UAC MAY generate subsequent offers in requests based on rules + // specified for that method, but only if it has received answers + // to any previous offers, and has not sent any offers to which it + // hasn't gotten an answer. + // https://tools.ietf.org/html/rfc3261#section-13.2.1 + // + // ...with... + // + // o After having sent or received an answer to the first offer, the + // UAC MUST NOT generate subsequent offers in requests based on rules + // specified for that method. + // + // ...which in combination with this bullet point... + // + // o Once the UAS has sent or received an answer to the initial + // offer, it MUST NOT generate subsequent offers in any responses + // to the initial INVITE. This means that a UAS based on this + // specification alone can never generate subsequent offers until + // completion of the initial transaction. + // https://tools.ietf.org/html/rfc3261#section-13.2.1 + // + // ...ensures that EXACTLY ONE offer/answer exchange will occur + // during an initial out of dialog INVITE request made by our UAC. + // + // + // 2) Early Media Restriction. + // + // While our implementation adheres to the following bullet point... + // + // o If the initial offer is in an INVITE, the answer MUST be in a + // reliable non-failure message from UAS back to UAC which is + // correlated to that INVITE. For this specification, that is + // only the final 2xx response to that INVITE. That same exact + // answer MAY also be placed in any provisional responses sent + // prior to the answer. The UAC MUST treat the first session + // description it receives as the answer, and MUST ignore any + // session descriptions in subsequent responses to the initial + // INVITE. + // https://tools.ietf.org/html/rfc3261#section-13.2.1 + // + // We have made the following implementation decision with regard to early media... + // + // o If the initial offer is in the INVITE, the answer from the + // UAS back to the UAC will establish a media session only + // only after the final 2xx response to that INVITE is received. + // + // The reason for this decision is rooted in a restriction currently + // inherent in WebRTC. Specifically, while a SIP INVITE request with an + // initial offer may fork resulting in more than one provisional answer, + // there is currently no easy/good way to to "fork" an offer generated + // by a peer connection. In particular, a WebRTC offer currently may only + // be matched with one answer and we have no good way to know which + // "provisional answer" is going to be the "final answer". So we have + // decided to punt and not create any "early media" sessions in this case. + // + // The upshot is that if you want "early media", you must not put the + // initial offer in the INVITE. Instead, force the UAS to provide the + // initial offer by sending an INVITE without an offer. In the WebRTC + // case this allows us to create a unique peer connection with a unique + // answer for every provisional offer with "early media" on all of them. + //// + //// + // ROADMAP: The Offer/Answer Model Implementation + // + // The "no early media if offer in INVITE" implementation is not a + // welcome one. The masses want it. The want it and they want it + // to work for WebRTC (so they want to have their cake and eat too). + // + // So while we currently cannot make the offer in INVITE+forking+webrtc + // case work, we decided to do the following... + // + // 1) modify SDH Factory to provide an initial offer without giving us the SDH, and then... + // 2) stick that offer in the initial INVITE, and when 183 with initial answer is received... + // 3) ask SDH Factory if it supports "earlyRemoteAnswer" + // a) if true, ask SDH Factory to createSDH(localOffer).then((sdh) => sdh.setDescription(remoteAnswer) + // b) if false, defer getting a SDH until 2xx response is received + // + // Our supplied WebRTC SDH will default to behavior 3b which works in forking environment (without) + // early media if initial offer is in the INVITE). We will, however, provide an "inviteWillNotFork" + // option which if set to "true" will have our supplied WebRTC SDH behave in the 3a manner. + // That will result in + // - early media working with initial offer in the INVITE, and... + // - if the INVITE forks, the session terminating with an ERROR that reads like + // "You set 'inviteWillNotFork' to true but the INVITE forked. You can't eat your cake, and have it too." + // - furthermore, we accept that users will report that error to us as "bug" regardless + // + // So, SDH Factory is going to end up with a new interface along the lines of... + // + // interface SessionDescriptionHandlerFactory { + // makeLocalOffer(): Promise; + // makeSessionDescriptionHandler( + // initialOffer: ContentTypeAndBody, offerType: "local" | "remote" + // ): Promise; + // supportsEarlyRemoteAnswer: boolean; + // supportsContentType(contentType: string): boolean; + // getDescription(description: ContentTypeAndBody): Promise + // setDescription(description: ContentTypeAndBody): Promise + // } + // + // We should be able to get rid of all the hasOffer/hasAnswer tracking code and otherwise code + // it up to the same interaction with the SDH Factory and SDH regardless of signaling scenario. + //// + // Send the INVITE request. + this.outgoingInviteRequest = this.ua.userAgentCore.invite(this.request, { + onAccept: function (inviteResponse) { return _this.onAccept(inviteResponse); }, + onProgress: function (inviteResponse) { return _this.onProgress(inviteResponse); }, + onRedirect: function (inviteResponse) { return _this.onRedirect(inviteResponse); }, + onReject: function (inviteResponse) { return _this.onReject(inviteResponse); }, + onTrying: function (inviteResponse) { return _this.onTrying(inviteResponse); } + }); + }; + InviteClientContext.prototype.ackAndBye = function (inviteResponse, session, statusCode, reasonPhrase) { + if (!this.ua.userAgentCore) { + throw new Error("Method requires user agent core."); + } + var extraHeaders = []; + if (statusCode) { + extraHeaders.push("Reason: " + Utils_1.Utils.getReasonHeaderValue(statusCode, reasonPhrase)); + } + var outgoingAckRequest = inviteResponse.ack(); + this.emit("ack", outgoingAckRequest.message); + var outgoingByeRequest = session.bye(undefined, { extraHeaders: extraHeaders }); + this.emit("bye", outgoingByeRequest.message); + }; + InviteClientContext.prototype.disposeEarlyMedia = function () { + if (!this.earlyMediaSessionDescriptionHandlers) { + throw new Error("Early media session description handlers undefined."); + } + this.earlyMediaSessionDescriptionHandlers.forEach(function (sessionDescriptionHandler) { + sessionDescriptionHandler.close(); + }); + }; + /** + * Handle final response to initial INVITE. + * @param inviteResponse 2xx response. + */ + InviteClientContext.prototype.onAccept = function (inviteResponse) { + var _this = this; + if (!this.earlyMediaSessionDescriptionHandlers) { + throw new Error("Early media session description handlers undefined."); + } + var response = inviteResponse.message; + var session = inviteResponse.session; + // Our transaction layer is "non-standard" in that it will only + // pass us a 2xx response once per branch, so there is no need to + // worry about dealing with 2xx retransmissions. However, we can + // and do still get 2xx responses for multiple branches (when an + // INVITE is forked) which may create multiple confirmed dialogs. + // Herein we are acking and sending a bye to any confirmed dialogs + // which arrive beyond the first one. This is the desired behavior + // for most applications (but certainly not all). + // If we already received a confirmed dialog, ack & bye this session. + if (this.session) { + this.ackAndBye(inviteResponse, session); + return; + } + // If the user requested cancellation, ack & bye this session. + if (this.isCanceled) { + this.ackAndBye(inviteResponse, session); + this.emit("bye", this.request); // FIXME: Ported this odd second "bye" emit + return; + } + // Ported behavior. + if (response.hasHeader("P-Asserted-Identity")) { + this.assertedIdentity = Grammar_1.Grammar.nameAddrHeaderParse(response.getHeader("P-Asserted-Identity")); + } + // We have a confirmed dialog. + this.session = session; + this.session.delegate = { + onAck: function (ackRequest) { return _this.onAck(ackRequest); }, + onBye: function (byeRequest) { return _this.receiveRequest(byeRequest); }, + onInfo: function (infoRequest) { return _this.receiveRequest(infoRequest); }, + onInvite: function (inviteRequest) { return _this.receiveRequest(inviteRequest); }, + onNotify: function (notifyRequest) { return _this.receiveRequest(notifyRequest); }, + onPrack: function (prackRequest) { return _this.receiveRequest(prackRequest); }, + onRefer: function (referRequest) { return _this.receiveRequest(referRequest); } + }; + switch (session.signalingState) { + case session_1.SignalingState.Initial: + // INVITE without Offer, so MUST have Offer at this point, so invalid state. + this.ackAndBye(inviteResponse, session, 400, "Missing session description"); + this.failed(response, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); + break; + case session_1.SignalingState.HaveLocalOffer: + // INVITE with Offer, so MUST have Answer at this point, so invalid state. + this.ackAndBye(inviteResponse, session, 400, "Missing session description"); + this.failed(response, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); + break; + case session_1.SignalingState.HaveRemoteOffer: + // INVITE without Offer, received offer in 2xx, so MUST send Answer in ACK. + var sdh_1 = this.sessionDescriptionHandlerFactory(this, this.ua.configuration.sessionDescriptionHandlerFactoryOptions || {}); + this.sessionDescriptionHandler = sdh_1; + this.emit("SessionDescriptionHandler-created", this.sessionDescriptionHandler); + if (!sdh_1.hasDescription(response.getHeader("Content-Type") || "")) { + this.ackAndBye(inviteResponse, session, 400, "Missing session description"); + this.failed(response, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); + break; + } + this.hasOffer = true; + sdh_1 + .setDescription(response.body, this.sessionDescriptionHandlerOptions, this.modifiers) + .then(function () { return sdh_1.getDescription(_this.sessionDescriptionHandlerOptions, _this.modifiers); }) + .then(function (description) { + if (_this.isCanceled || _this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { + return; + } + _this.status = Enums_1.SessionStatus.STATUS_CONFIRMED; + _this.hasAnswer = true; + var body = { + contentDisposition: "session", contentType: description.contentType, content: description.body + }; + var ackRequest = inviteResponse.ack({ body: body }); + _this.emit("ack", ackRequest.message); + _this.accepted(response); + }) + .catch(function (e) { + if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { + _this.logger.warn("invalid description"); + _this.logger.warn(e.toString()); + // TODO: This message is inconsistent + _this.ackAndBye(inviteResponse, session, 488, "Invalid session description"); + _this.failed(response, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); + } + else { + throw e; + } + }); + break; + case session_1.SignalingState.Stable: + // This session has completed an initial offer/answer exchange... + var options_1; + if (this.renderbody && this.rendertype) { + options_1 = { body: { contentDisposition: "render", contentType: this.rendertype, content: this.renderbody } }; + } + // If INVITE with Offer and we have been waiting till now to apply the answer. + if (this.hasOffer && !this.hasAnswer) { + if (!this.sessionDescriptionHandler) { + throw new Error("Session description handler undefined."); + } + var answer = session.answer; + if (!answer) { + throw new Error("Answer is undefined."); + } + this.sessionDescriptionHandler + .setDescription(answer.content, this.sessionDescriptionHandlerOptions, this.modifiers) + .then(function () { + _this.hasAnswer = true; + _this.status = Enums_1.SessionStatus.STATUS_CONFIRMED; + var ackRequest = inviteResponse.ack(options_1); + _this.emit("ack", ackRequest.message); + _this.accepted(response); + }) + .catch(function (error) { + _this.logger.error(error); + _this.ackAndBye(inviteResponse, session, 488, "Not Acceptable Here"); + _this.failed(response, Constants_1.C.causes.BAD_MEDIA_DESCRIPTION); + // FIME: DON'T EAT UNHANDLED ERRORS! + }); + } + else { + // Otherwise INVITE with or without Offer and we have already completed the initial exchange. + this.sessionDescriptionHandler = this.earlyMediaSessionDescriptionHandlers.get(session.id); + if (!this.sessionDescriptionHandler) { + throw new Error("Session description handler undefined."); + } + this.earlyMediaSessionDescriptionHandlers.delete(session.id); + this.hasOffer = true; + this.hasAnswer = true; + this.status = Enums_1.SessionStatus.STATUS_CONFIRMED; + var ackRequest = inviteResponse.ack(); + this.emit("ack", ackRequest.message); + this.accepted(response); + } + break; + case session_1.SignalingState.Closed: + // Dialog has terminated. + break; + default: + throw new Error("Unknown session signaling state."); + } + this.disposeEarlyMedia(); + }; + /** + * Handle provisional response to initial INVITE. + * @param inviteResponse 1xx response. + */ + InviteClientContext.prototype.onProgress = function (inviteResponse) { + var _this = this; + // Ported - User requested cancellation. + if (this.isCanceled) { + return; + } + if (!this.outgoingInviteRequest) { + throw new Error("Outgoing INVITE request undefined."); + } + if (!this.earlyMediaSessionDescriptionHandlers) { + throw new Error("Early media session description handlers undefined."); + } + var response = inviteResponse.message; + var session = inviteResponse.session; + // Ported - Set status. + this.status = Enums_1.SessionStatus.STATUS_1XX_RECEIVED; + // Ported - Set assertedIdentity. + if (response.hasHeader("P-Asserted-Identity")) { + this.assertedIdentity = Grammar_1.Grammar.nameAddrHeaderParse(response.getHeader("P-Asserted-Identity")); + } + // The provisional response MUST establish a dialog if one is not yet created. + // https://tools.ietf.org/html/rfc3262#section-4 + if (!session) { + // A response with a to tag MUST create a session (should never get here). + throw new Error("Session undefined."); + } + // If a provisional response is received for an initial request, and + // that response contains a Require header field containing the option + // tag 100rel, the response is to be sent reliably. If the response is + // a 100 (Trying) (as opposed to 101 to 199), this option tag MUST be + // ignored, and the procedures below MUST NOT be used. + // https://tools.ietf.org/html/rfc3262#section-4 + var requireHeader = response.getHeader("require"); + var rseqHeader = response.getHeader("rseq"); + var rseq = requireHeader && requireHeader.includes("100rel") && rseqHeader ? Number(rseqHeader) : undefined; + var responseReliable = !!rseq; + var extraHeaders = []; + if (responseReliable) { + extraHeaders.push("RAck: " + response.getHeader("rseq") + " " + response.getHeader("cseq")); + } + // INVITE without Offer and session still has no offer (and no answer). + if (session.signalingState === session_1.SignalingState.Initial) { + // Similarly, if a reliable provisional + // response is the first reliable message sent back to the UAC, and the + // INVITE did not contain an offer, one MUST appear in that reliable + // provisional response. + // https://tools.ietf.org/html/rfc3262#section-5 + if (responseReliable) { + this.logger.warn("First reliable provisional response received MUST contain an offer when INVITE does not contain an offer."); + // FIXME: Known popular UA's currently end up here... + inviteResponse.prack({ extraHeaders: extraHeaders }); + } + this.emit("progress", response); + return; + } + // INVITE with Offer and session only has that initial local offer. + if (session.signalingState === session_1.SignalingState.HaveLocalOffer) { + if (responseReliable) { + inviteResponse.prack({ extraHeaders: extraHeaders }); + } + this.emit("progress", response); + return; + } + // INVITE without Offer and received initial offer in provisional response + if (session.signalingState === session_1.SignalingState.HaveRemoteOffer) { + // The initial offer MUST be in either an INVITE or, if not there, + // in the first reliable non-failure message from the UAS back to + // the UAC. + // https://tools.ietf.org/html/rfc3261#section-13.2.1 + // According to Section 13.2.1 of [RFC3261], 'The first reliable + // non-failure message' must have an offer if there is no offer in the + // INVITE request. This means that the User Agent (UA) that receives + // the INVITE request without an offer must include an offer in the + // first reliable response with 100rel extension. If no reliable + // provisional response has been sent, the User Agent Server (UAS) must + // include an offer when sending 2xx response. + // https://tools.ietf.org/html/rfc6337#section-2.2 + if (!responseReliable) { + this.logger.warn("Non-reliable provisional response MUST NOT contain an initial offer, discarding response."); + return; + } + // If the initial offer is in the first reliable non-failure + // message from the UAS back to UAC, the answer MUST be in the + // acknowledgement for that message + var sdh_2 = this.sessionDescriptionHandlerFactory(this, this.ua.configuration.sessionDescriptionHandlerFactoryOptions || {}); + this.emit("SessionDescriptionHandler-created", sdh_2); + this.earlyMediaSessionDescriptionHandlers.set(session.id, sdh_2); + sdh_2 + .setDescription(response.body, this.sessionDescriptionHandlerOptions, this.modifiers) + .then(function () { return sdh_2.getDescription(_this.sessionDescriptionHandlerOptions, _this.modifiers); }) + .then(function (description) { + var body = { + contentDisposition: "session", contentType: description.contentType, content: description.body + }; + inviteResponse.prack({ extraHeaders: extraHeaders, body: body }); + _this.status = Enums_1.SessionStatus.STATUS_EARLY_MEDIA; + _this.emit("progress", response); + }) + .catch(function (error) { + if (_this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { + return; + } + _this.failed(undefined, Constants_1.C.causes.WEBRTC_ERROR); + _this.terminated(undefined, Constants_1.C.causes.WEBRTC_ERROR); + }); + return; + } + // This session has completed an initial offer/answer exchange, so... + // - INVITE with SDP and this provisional response MAY be reliable + // - INVITE without SDP and this provisional response MAY be reliable + if (session.signalingState === session_1.SignalingState.Stable) { + if (responseReliable) { + inviteResponse.prack({ extraHeaders: extraHeaders }); + } + // Note: As documented, no early media if offer was in INVITE, so nothing to be done. + // FIXME: TODO: Add a flag/hack to allow early media in this case. There are people + // in non-forking environments (think straight to FreeSWITCH) who want + // early media on a 183. Not sure how to actually make it work, basically + // something like... + if (0 /* flag */ && this.hasOffer && !this.hasAnswer && this.sessionDescriptionHandler) { + this.hasAnswer = true; + this.status = Enums_1.SessionStatus.STATUS_EARLY_MEDIA; + this.sessionDescriptionHandler + .setDescription(response.body, this.sessionDescriptionHandlerOptions, this.modifiers) + .then(function () { + _this.status = Enums_1.SessionStatus.STATUS_EARLY_MEDIA; + }) + .catch(function (error) { + if (_this.status === Enums_1.SessionStatus.STATUS_TERMINATED) { + return; + } + _this.failed(undefined, Constants_1.C.causes.WEBRTC_ERROR); + _this.terminated(undefined, Constants_1.C.causes.WEBRTC_ERROR); + }); + } + this.emit("progress", response); + return; + } + }; + /** + * Handle final response to initial INVITE. + * @param inviteResponse 3xx response. + */ + InviteClientContext.prototype.onRedirect = function (inviteResponse) { + this.disposeEarlyMedia(); + var response = inviteResponse.message; + var statusCode = response.statusCode; + var cause = Utils_1.Utils.sipErrorCause(statusCode || 0); + this.rejected(response, cause); + this.failed(response, cause); + this.terminated(response, cause); + }; + /** + * Handle final response to initial INVITE. + * @param inviteResponse 4xx, 5xx, or 6xx response. + */ + InviteClientContext.prototype.onReject = function (inviteResponse) { + this.disposeEarlyMedia(); + var response = inviteResponse.message; + var statusCode = response.statusCode; + var cause = Utils_1.Utils.sipErrorCause(statusCode || 0); + this.rejected(response, cause); + this.failed(response, cause); + this.terminated(response, cause); + }; + /** + * Handle final response to initial INVITE. + * @param inviteResponse 100 response. + */ + InviteClientContext.prototype.onTrying = function (inviteResponse) { + this.received100 = true; + this.emit("progress", inviteResponse.message); + }; + return InviteClientContext; +}(Session)); +exports.InviteClientContext = InviteClientContext; diff --git a/lib/Session/DTMF.d.ts b/lib/Session/DTMF.d.ts new file mode 100644 index 000000000..96b7599e6 --- /dev/null +++ b/lib/Session/DTMF.d.ts @@ -0,0 +1,26 @@ +/// +import { EventEmitter } from "events"; +import { IncomingRequest } from "../Core/messages"; +import { TypeStrings } from "../Enums"; +import { Session } from "../Session"; +import { IncomingResponse } from "../SIPMessage"; +/** + * @class DTMF + * @param {SIP.Session} session + */ +export declare class DTMF extends EventEmitter { + type: TypeStrings; + tone: string; + duration: number; + interToneGap: number; + private C; + private logger; + private owner; + constructor(session: Session, tone: string | number, options?: any); + send(options?: any): void; + init_incoming(request: IncomingRequest): void; + receiveResponse(response: IncomingResponse): void; + onRequestTimeout(): void; + onTransportError(): void; + onDialogError(response: IncomingResponse): void; +} diff --git a/lib/Session/DTMF.js b/lib/Session/DTMF.js new file mode 100644 index 000000000..a491750d3 --- /dev/null +++ b/lib/Session/DTMF.js @@ -0,0 +1,165 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var events_1 = require("events"); +var Constants_1 = require("../Constants"); +var messages_1 = require("../Core/messages"); +var Enums_1 = require("../Enums"); +var Exceptions_1 = require("../Exceptions"); +var Utils_1 = require("../Utils"); +/** + * @class DTMF + * @param {SIP.Session} session + */ +var DTMF = /** @class */ (function (_super) { + __extends(DTMF, _super); + function DTMF(session, tone, options) { + if (options === void 0) { options = {}; } + var _this = _super.call(this) || this; + _this.C = { + MIN_DURATION: 70, + MAX_DURATION: 6000, + DEFAULT_DURATION: 100, + MIN_INTER_TONE_GAP: 50, + DEFAULT_INTER_TONE_GAP: 500 + }; + _this.type = Enums_1.TypeStrings.DTMF; + if (tone === undefined) { + throw new TypeError("Not enough arguments"); + } + _this.logger = session.ua.getLogger("sip.invitecontext.dtmf", session.id); + _this.owner = session; + // Check tone type + if (typeof tone === "string") { + tone = tone.toUpperCase(); + } + else if (typeof tone === "number") { + tone = tone.toString(); + } + else { + throw new TypeError("Invalid tone: " + tone); + } + // Check tone value + if (!tone.match(/^[0-9A-D#*]$/)) { + throw new TypeError("Invalid tone: " + tone); + } + else { + _this.tone = tone; + } + var duration = options.duration; + var interToneGap = options.interToneGap; + // Check duration + if (duration && !Utils_1.Utils.isDecimal(duration)) { + throw new TypeError("Invalid tone duration: " + duration); + } + else if (!duration) { + duration = _this.C.DEFAULT_DURATION; + } + else if (duration < _this.C.MIN_DURATION) { + _this.logger.warn("'duration' value is lower than the minimum allowed, setting it to " + + _this.C.MIN_DURATION + " milliseconds"); + duration = _this.C.MIN_DURATION; + } + else if (duration > _this.C.MAX_DURATION) { + _this.logger.warn("'duration' value is greater than the maximum allowed, setting it to " + + _this.C.MAX_DURATION + " milliseconds"); + duration = _this.C.MAX_DURATION; + } + else { + duration = Math.abs(duration); + } + _this.duration = duration; + // Check interToneGap + if (interToneGap && !Utils_1.Utils.isDecimal(interToneGap)) { + throw new TypeError("Invalid interToneGap: " + interToneGap); + } + else if (!interToneGap) { + interToneGap = _this.C.DEFAULT_INTER_TONE_GAP; + } + else if (interToneGap < _this.C.MIN_INTER_TONE_GAP) { + _this.logger.warn("'interToneGap' value is lower than the minimum allowed, setting it to " + + _this.C.MIN_INTER_TONE_GAP + " milliseconds"); + interToneGap = _this.C.MIN_INTER_TONE_GAP; + } + else { + interToneGap = Math.abs(interToneGap); + } + _this.interToneGap = interToneGap; + return _this; + } + DTMF.prototype.send = function (options) { + if (options === void 0) { options = {}; } + // Check RTCSession Status + if (this.owner.status !== Enums_1.SessionStatus.STATUS_CONFIRMED && + this.owner.status !== Enums_1.SessionStatus.STATUS_WAITING_FOR_ACK) { + throw new Exceptions_1.Exceptions.InvalidStateError(this.owner.status); + } + // Get DTMF options + var extraHeaders = options.extraHeaders ? options.extraHeaders.slice() : []; + var body = { + contentType: "application/dtmf-relay", + body: "Signal= " + this.tone + "\r\nDuration= " + this.duration + }; + if (this.owner.session) { + var request = this.owner.session.info(undefined, { + extraHeaders: extraHeaders, + body: messages_1.fromBodyObj(body) + }); + this.owner.emit("dtmf", request.message, this); + return; + } + }; + DTMF.prototype.init_incoming = function (request) { + request.accept(); + if (!this.tone || !this.duration) { + this.logger.warn("invalid INFO DTMF received, discarded"); + } + else { + this.owner.emit("dtmf", request.message, this); + } + }; + DTMF.prototype.receiveResponse = function (response) { + var statusCode = response && response.statusCode ? response.statusCode : 0; + switch (true) { + case /^1[0-9]{2}$/.test(statusCode.toString()): + // Ignore provisional responses. + break; + case /^2[0-9]{2}$/.test(statusCode.toString()): + this.emit("succeeded", { + originator: "remote", + response: response + }); + break; + default: + var cause = Utils_1.Utils.sipErrorCause(statusCode); + this.emit("failed", response, cause); + break; + } + }; + DTMF.prototype.onRequestTimeout = function () { + this.emit("failed", undefined, Constants_1.C.causes.REQUEST_TIMEOUT); + this.owner.onRequestTimeout(); + }; + DTMF.prototype.onTransportError = function () { + this.emit("failed", undefined, Constants_1.C.causes.CONNECTION_ERROR); + this.owner.onTransportError(); + }; + DTMF.prototype.onDialogError = function (response) { + this.emit("failed", response, Constants_1.C.causes.DIALOG_ERROR); + this.owner.onDialogError(response); + }; + return DTMF; +}(events_1.EventEmitter)); +exports.DTMF = DTMF; diff --git a/lib/Subscription.d.ts b/lib/Subscription.d.ts new file mode 100644 index 000000000..a670a0848 --- /dev/null +++ b/lib/Subscription.d.ts @@ -0,0 +1,130 @@ +/// +import { EventEmitter } from "events"; +import { ClientContext } from "./ClientContext"; +import { IncomingNotifyRequest, IncomingResponse, OutgoingSubscribeRequest } from "./Core/messages"; +import { TypeStrings } from "./Enums"; +import { Logger } from "./LoggerFactory"; +import { NameAddrHeader } from "./NameAddrHeader"; +import { BodyObj } from "./session-description-handler"; +import { IncomingRequest as IncomingRequestMessage, IncomingResponse as IncomingResponseMessage, OutgoingRequest as OutgoingRequestMessage } from "./SIPMessage"; +import { UA } from "./UA"; +import { URI } from "./URI"; +interface SubscriptionOptions { + expires?: number; + extraHeaders?: Array; + body?: string; + contentType?: string; +} +/** + * While this class is named `Subscription`, it is closer to + * an implementation of a "subscriber" as defined in RFC 6665 + * "SIP-Specific Event Notifications". + * https://tools.ietf.org/html/rfc6665 + * @class Class creating a SIP Subscriber. + */ +export declare class Subscription extends EventEmitter implements ClientContext { + type: TypeStrings; + ua: UA; + logger: Logger; + data: any; + method: string; + body: BodyObj | undefined; + localIdentity: NameAddrHeader; + remoteIdentity: NameAddrHeader; + request: OutgoingRequestMessage; + onRequestTimeout: () => void; + onTransportError: () => void; + receiveResponse: () => void; + send: () => this; + private context; + private disposed; + private event; + private expires; + private extraHeaders; + private retryAfterTimer; + private subscription; + private uri; + /** + * Constructor. + * @param ua User agent. + * @param target Subscription target. + * @param event Subscription event. + * @param options Options bucket. + */ + constructor(ua: UA, target: string | URI, event: string, options?: SubscriptionOptions); + /** + * Destructor. + */ + dispose(): void; + /** + * Registration of event listeners. + * + * The following events are emitted... + * - "accepted" A 200-class final response to a SUBSCRIBE request was received. + * - "failed" A non-200-class final response to a SUBSCRIBE request was received. + * - "rejected" Emitted immediately after a "failed" event (yes, it's redundant). + * - "notify" A NOTIFY request was received. + * - "terminated" The subscription is moving to or has moved to a terminated state. + * + * More than one SUBSCRIBE request may be sent, so "accepted", "failed" and "rejected" + * may be emitted multiple times. However these event will NOT be emitted for SUBSCRIBE + * requests with expires of zero (unsubscribe requests). + * + * Note that a "terminated" event does NOT indicate the subscription is in the "terminated" + * state as described in RFC 6665. Instead, a "terminated" event indicates that this class + * is no longer usable and/or is in the process of becoming no longer usable. + * + * The order the events are emitted in is not deterministic. Some examples... + * - "accepted" may occur multiple times + * - "accepted" may follow "notify" and "notify" may follow "accepted" + * - "terminated" may follow "accepted" and "accepted" may follow "terminated" + * - "terminated" may follow "notify" and "notify" may follow "terminated" + * + * Hint: Experience suggests one workable approach to utilizing these events + * is to make use of "notify" and "terminated" only. That is, call `subscribe()` + * and if a "notify" occurs then you have a subscription. If a "terminated" + * event occurs then either a new subscription failed to be established or an + * established subscription has terminated or is in the process of terminating. + * Note that "notify" events may follow a "terminated" event, but experience + * suggests it is reasonable to discontinue usage of this class after receipt + * of a "terminated" event. The other events are informational, but as they do not + * arrive in a deterministic manner it is difficult to make use of them otherwise. + * + * @param name Event name. + * @param callback Callback. + */ + on(name: "accepted" | "failed" | "rejected", callback: (message: IncomingResponseMessage, cause: string) => void): this; + on(name: "notify", callback: (notification: { + request: IncomingRequestMessage; + }) => void): this; + on(name: "terminated", callback: () => void): this; + emit(event: "accepted" | "failed" | "rejected", message: IncomingResponseMessage, cause: string): boolean; + emit(event: "notify", notification: { + request: IncomingRequestMessage; + }): boolean; + emit(event: "terminated"): boolean; + /** + * Gracefully terminate. + */ + close(): void; + /** + * Send a re-SUBSCRIBE request if there is an "active" subscription. + */ + refresh(): void; + /** + * Send an initial SUBSCRIBE request if no subscription. + * Send a re-SUBSCRIBE request if there is an "active" subscription. + */ + subscribe(): this; + /** + * Send a re-SUBSCRIBE request if there is a "pending" or "active" subscription. + */ + unsubscribe(): void; + protected onAccepted(response: IncomingResponse): void; + protected onFailed(response?: IncomingResponse): void; + protected onNotify(request: IncomingNotifyRequest): void; + protected onRefresh(request: OutgoingSubscribeRequest): void; + protected onTerminated(): void; + private initContext; +} +export {}; diff --git a/lib/Subscription.js b/lib/Subscription.js new file mode 100644 index 000000000..02bee8155 --- /dev/null +++ b/lib/Subscription.js @@ -0,0 +1,441 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var events_1 = require("events"); +var Constants_1 = require("./Constants"); +var messages_1 = require("./Core/messages"); +var subscription_1 = require("./Core/subscription"); +var allowed_methods_1 = require("./Core/user-agent-core/allowed-methods"); +var Enums_1 = require("./Enums"); +var Utils_1 = require("./Utils"); +/** + * While this class is named `Subscription`, it is closer to + * an implementation of a "subscriber" as defined in RFC 6665 + * "SIP-Specific Event Notifications". + * https://tools.ietf.org/html/rfc6665 + * @class Class creating a SIP Subscriber. + */ +var Subscription = /** @class */ (function (_super) { + __extends(Subscription, _super); + /** + * Constructor. + * @param ua User agent. + * @param target Subscription target. + * @param event Subscription event. + * @param options Options bucket. + */ + function Subscription(ua, target, event, options) { + if (options === void 0) { options = {}; } + var _this = _super.call(this) || this; + _this.data = {}; + _this.method = Constants_1.C.SUBSCRIBE; + _this.body = undefined; + // ClientContext interface + _this.type = Enums_1.TypeStrings.Subscription; + _this.ua = ua; + _this.logger = ua.getLogger("sip.subscription"); + if (options.body) { + _this.body = { + body: options.body, + contentType: options.contentType ? options.contentType : "application/sdp" + }; + } + // Target URI + var uri = ua.normalizeTarget(target); + if (!uri) { + throw new TypeError("Invalid target: " + target); + } + _this.uri = uri; + // Subscription event + _this.event = event; + // Subscription expires + if (options.expires === undefined) { + _this.expires = 3600; + } + else if (typeof options.expires !== "number") { // pre-typescript type guard + ua.logger.warn("Option \"expires\" must be a number. Using default of 3600."); + _this.expires = 3600; + } + else { + _this.expires = options.expires; + } + // Subscription extra headers + _this.extraHeaders = (options.extraHeaders || []).slice(); + // Subscription context. + _this.context = _this.initContext(); + _this.disposed = false; + // ClientContext interface + _this.request = _this.context.message; + if (!_this.request.from) { + throw new Error("From undefined."); + } + if (!_this.request.to) { + throw new Error("From undefined."); + } + _this.localIdentity = _this.request.from; + _this.remoteIdentity = _this.request.to; + return _this; + } + /** + * Destructor. + */ + Subscription.prototype.dispose = function () { + if (this.disposed) { + return; + } + if (this.retryAfterTimer) { + clearTimeout(this.retryAfterTimer); + this.retryAfterTimer = undefined; + } + this.context.dispose(); + this.disposed = true; + }; + Subscription.prototype.on = function (name, callback) { + return _super.prototype.on.call(this, name, callback); + }; + Subscription.prototype.emit = function (event) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + return _super.prototype.emit.apply(this, [event].concat(args)); + }; + /** + * Gracefully terminate. + */ + Subscription.prototype.close = function () { + if (this.disposed) { + return; + } + this.dispose(); + switch (this.context.state) { + case subscription_1.SubscriptionState.Initial: + this.onTerminated(); + break; + case subscription_1.SubscriptionState.NotifyWait: + this.onTerminated(); + break; + case subscription_1.SubscriptionState.Pending: + this.unsubscribe(); + break; + case subscription_1.SubscriptionState.Active: + this.unsubscribe(); + break; + case subscription_1.SubscriptionState.Terminated: + this.onTerminated(); + break; + default: + break; + } + }; + /** + * Send a re-SUBSCRIBE request if there is an "active" subscription. + */ + Subscription.prototype.refresh = function () { + var _this = this; + switch (this.context.state) { + case subscription_1.SubscriptionState.Initial: + break; + case subscription_1.SubscriptionState.NotifyWait: + break; + case subscription_1.SubscriptionState.Pending: + break; + case subscription_1.SubscriptionState.Active: + if (this.subscription) { + var request = this.subscription.refresh(); + request.delegate = { + onAccept: (function (response) { return _this.onAccepted(response); }), + onRedirect: (function (response) { return _this.onFailed(response); }), + onReject: (function (response) { return _this.onFailed(response); }), + }; + } + break; + case subscription_1.SubscriptionState.Terminated: + break; + default: + break; + } + }; + /** + * Send an initial SUBSCRIBE request if no subscription. + * Send a re-SUBSCRIBE request if there is an "active" subscription. + */ + Subscription.prototype.subscribe = function () { + var _this = this; + switch (this.context.state) { + case subscription_1.SubscriptionState.Initial: + this.context.subscribe().then(function (result) { + if (result.success) { + if (result.success.subscription) { + _this.subscription = result.success.subscription; + _this.subscription.delegate = { + onNotify: function (request) { return _this.onNotify(request); }, + onRefresh: function (request) { return _this.onRefresh(request); }, + onTerminated: function () { return _this.close(); } + }; + } + _this.onNotify(result.success.request); + } + else if (result.failure) { + _this.onFailed(result.failure.response); + } + }); + break; + case subscription_1.SubscriptionState.NotifyWait: + break; + case subscription_1.SubscriptionState.Pending: + break; + case subscription_1.SubscriptionState.Active: + this.refresh(); + break; + case subscription_1.SubscriptionState.Terminated: + break; + default: + break; + } + return this; + }; + /** + * Send a re-SUBSCRIBE request if there is a "pending" or "active" subscription. + */ + Subscription.prototype.unsubscribe = function () { + this.dispose(); + switch (this.context.state) { + case subscription_1.SubscriptionState.Initial: + break; + case subscription_1.SubscriptionState.NotifyWait: + break; + case subscription_1.SubscriptionState.Pending: + if (this.subscription) { + this.subscription.unsubscribe(); + // responses intentionally ignored + } + break; + case subscription_1.SubscriptionState.Active: + if (this.subscription) { + this.subscription.unsubscribe(); + // responses intentionally ignored + } + break; + case subscription_1.SubscriptionState.Terminated: + break; + default: + break; + } + this.onTerminated(); + }; + Subscription.prototype.onAccepted = function (response) { + var statusCode = response.message.statusCode ? response.message.statusCode : 0; + var cause = Utils_1.Utils.getReasonPhrase(statusCode); + this.emit("accepted", response.message, cause); + }; + Subscription.prototype.onFailed = function (response) { + this.close(); + if (response) { + var statusCode = response.message.statusCode ? response.message.statusCode : 0; + var cause = Utils_1.Utils.getReasonPhrase(statusCode); + this.emit("failed", response.message, cause); + this.emit("rejected", response.message, cause); + } + }; + Subscription.prototype.onNotify = function (request) { + var _this = this; + request.accept(); // Send 200 response. + this.emit("notify", { request: request.message }); + // If we've set state to done, no further processing should take place + // and we are only interested in cleaning up after the appropriate NOTIFY. + if (this.disposed) { + return; + } + // If the "Subscription-State" value is "terminated", the subscriber + // MUST consider the subscription terminated. The "expires" parameter + // has no semantics for "terminated" -- notifiers SHOULD NOT include an + // "expires" parameter on a "Subscription-State" header field with a + // value of "terminated", and subscribers MUST ignore any such + // parameter, if present. If a reason code is present, the client + // should behave as described below. If no reason code or an unknown + // reason code is present, the client MAY attempt to re-subscribe at any + // time (unless a "retry-after" parameter is present, in which case the + // client SHOULD NOT attempt re-subscription until after the number of + // seconds specified by the "retry-after" parameter). The reason codes + // defined by this document are: + // https://tools.ietf.org/html/rfc6665#section-4.1.3 + var subscriptionState = request.message.parseHeader("Subscription-State"); + if (subscriptionState && subscriptionState.state) { + switch (subscriptionState.state) { + case "terminated": + if (subscriptionState.reason) { + this.logger.log("Terminated subscription with reason " + subscriptionState.reason); + switch (subscriptionState.reason) { + case "deactivated": + case "timeout": + this.initContext(); + this.subscribe(); + return; + case "probation": + case "giveup": + this.initContext(); + if (subscriptionState.params && subscriptionState.params["retry-after"]) { + this.retryAfterTimer = setTimeout(function () { return _this.subscribe(); }, subscriptionState.params["retry-after"]); + } + else { + this.subscribe(); + } + return; + case "rejected": + case "noresource": + case "invariant": + break; + } + } + this.close(); + break; + default: + break; + } + } + }; + Subscription.prototype.onRefresh = function (request) { + var _this = this; + request.delegate = { + onAccept: function (response) { return _this.onAccepted(response); } + }; + }; + Subscription.prototype.onTerminated = function () { + this.emit("terminated"); + }; + Subscription.prototype.initContext = function () { + var _this = this; + var options = { + extraHeaders: this.extraHeaders, + body: this.body ? messages_1.fromBodyObj(this.body) : undefined + }; + this.context = new SubscribeClientContext(this.ua.userAgentCore, this.uri, this.event, this.expires, options); + this.context.delegate = { + onAccept: (function (response) { return _this.onAccepted(response); }) + }; + return this.context; + }; + return Subscription; +}(events_1.EventEmitter)); +exports.Subscription = Subscription; +// tslint:disable-next-line:max-classes-per-file +var SubscribeClientContext = /** @class */ (function () { + function SubscribeClientContext(core, target, event, expires, options, delegate) { + this.core = core; + this.target = target; + this.event = event; + this.expires = expires; + this.subscribed = false; + this.logger = core.loggerFactory.getLogger("sip.subscription"); + this.delegate = delegate; + var allowHeader = "Allow: " + allowed_methods_1.AllowedMethods.toString(); + var extraHeaders = (options && options.extraHeaders || []).slice(); + extraHeaders.push(allowHeader); + extraHeaders.push("Event: " + this.event); + extraHeaders.push("Expires: " + this.expires); + extraHeaders.push("Contact: " + this.core.configuration.contact.toString()); + var body = options && options.body ? messages_1.toBodyObj(options.body) : undefined; + this.message = this.core.configuration.outgoingRequestMessageFactory(Constants_1.C.SUBSCRIBE, this.target, {}, extraHeaders, body); + } + /** Destructor. */ + SubscribeClientContext.prototype.dispose = function () { + if (this.subscription) { + this.subscription.dispose(); + } + if (this.request) { + this.request.waitNotifyStop(); + this.request.dispose(); + } + }; + Object.defineProperty(SubscribeClientContext.prototype, "state", { + /** Subscription state. */ + get: function () { + if (this.subscription) { + return this.subscription.subscriptionState; + } + else if (this.subscribed) { + return subscription_1.SubscriptionState.NotifyWait; + } + else { + return subscription_1.SubscriptionState.Initial; + } + }, + enumerable: true, + configurable: true + }); + /** + * Establish subscription. + * @param options Options bucket. + */ + SubscribeClientContext.prototype.subscribe = function () { + var _this = this; + if (this.subscribed) { + return Promise.reject(new Error("Not in initial state. Did you call subscribe more than once?")); + } + this.subscribed = true; + return new Promise(function (resolve, reject) { + if (!_this.message) { + throw new Error("Message undefined."); + } + _this.request = _this.core.subscribe(_this.message, { + // This SUBSCRIBE request will be confirmed with a final response. + // 200-class responses indicate that the subscription has been accepted + // and that a NOTIFY request will be sent immediately. + // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 + onAccept: function (response) { + if (_this.delegate && _this.delegate.onAccept) { + _this.delegate.onAccept(response); + } + }, + // Due to the potential for out-of-order messages, packet loss, and + // forking, the subscriber MUST be prepared to receive NOTIFY requests + // before the SUBSCRIBE transaction has completed. + // https://tools.ietf.org/html/rfc6665#section-4.1.2.4 + onNotify: function (requestWithSubscription) { + _this.subscription = requestWithSubscription.subscription; + if (_this.subscription) { + _this.subscription.autoRefresh = true; + } + resolve({ success: requestWithSubscription }); + }, + // If this Timer N expires prior to the receipt of a NOTIFY request, + // the subscriber considers the subscription failed, and cleans up + // any state associated with the subscription attempt. + // https://tools.ietf.org/html/rfc6665#section-4.1.2.4 + onNotifyTimeout: function () { + resolve({ failure: {} }); + }, + // This SUBSCRIBE request will be confirmed with a final response. + // Non-200-class final responses indicate that no subscription or new + // dialog usage has been created, and no subsequent NOTIFY request will + // be sent. + // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 + onRedirect: function (response) { + resolve({ failure: { response: response } }); + }, + // This SUBSCRIBE request will be confirmed with a final response. + // Non-200-class final responses indicate that no subscription or new + // dialog usage has been created, and no subsequent NOTIFY request will + // be sent. + // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 + onReject: function (response) { + resolve({ failure: { response: response } }); + } + }); + }); + }; + return SubscribeClientContext; +}()); diff --git a/lib/SubscriptionOriginal.d.ts b/lib/SubscriptionOriginal.d.ts new file mode 100644 index 000000000..ffc03499d --- /dev/null +++ b/lib/SubscriptionOriginal.d.ts @@ -0,0 +1,41 @@ +import { ClientContext } from "./ClientContext"; +import { C } from "./Constants"; +import { IncomingRequest } from "./Core/messages"; +import { TypeStrings } from "./Enums"; +import { IncomingRequest as IncomingRequestMessage, IncomingResponse as IncomingResponseMessage } from "./SIPMessage"; +import { UA } from "./UA"; +import { URI } from "./URI"; +/** + * SIP Subscriber (SIP-Specific Event Notifications RFC6665) + * @class Class creating a SIP Subscription. + */ +export declare class SubscriptionOriginal extends ClientContext { + type: TypeStrings; + protected event: string; + protected requestedExpires: number; + protected expires: number; + protected id: string | undefined; + protected state: string; + protected contact: string; + protected extraHeaders: Array; + protected timers: any; + protected errorCodes: Array; + private subscription; + constructor(ua: UA, target: string | URI, event: string, options?: any); + subscribe(): SubscriptionOriginal; + refresh(): void; + receiveResponse(response: IncomingResponseMessage): void; + unsubscribe(): void; + receiveRequest(request: IncomingRequest): void; + close(): void; + onDialogError(response: IncomingResponseMessage): void; + on(name: "accepted", callback: (response: any, cause: C.causes) => void): this; + on(name: "notify", callback: (notification: { + request: IncomingRequestMessage; + }) => void): this; + on(name: "failed" | "rejected" | "terminated", callback: (messageOrResponse?: any, cause?: C.causes) => void): this; + send(): this; + protected timer_fire(): void; + protected failed(response: IncomingResponseMessage, cause?: string): this; + protected matchEvent(request: IncomingRequest): boolean; +} diff --git a/lib/SubscriptionOriginal.js b/lib/SubscriptionOriginal.js new file mode 100644 index 000000000..23f993cee --- /dev/null +++ b/lib/SubscriptionOriginal.js @@ -0,0 +1,348 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var ClientContext_1 = require("./ClientContext"); +var Constants_1 = require("./Constants"); +var messages_1 = require("./Core/messages"); +var subscription_1 = require("./Core/subscription"); +var Enums_1 = require("./Enums"); +var Timers_1 = require("./Timers"); +var Utils_1 = require("./Utils"); +/** + * SIP Subscriber (SIP-Specific Event Notifications RFC6665) + * @class Class creating a SIP Subscription. + */ +var SubscriptionOriginal = /** @class */ (function (_super) { + __extends(SubscriptionOriginal, _super); + function SubscriptionOriginal(ua, target, event, options) { + if (options === void 0) { options = {}; } + var _this = this; + if (!event) { + throw new TypeError("Event necessary to create a subscription."); + } + options.extraHeaders = (options.extraHeaders || []).slice(); + var expires; + if (typeof options.expires !== "number") { + ua.logger.warn("expires must be a number. Using default of 3600."); + expires = 3600; + } + else { + expires = options.expires; + } + options.extraHeaders.push("Event: " + event); + options.extraHeaders.push("Expires: " + expires); + options.extraHeaders.push("Contact: " + ua.contact.toString()); + // was UA.C.ALLOWED_METHODS, removed due to circular dependency + options.extraHeaders.push("Allow: " + [ + "ACK", + "CANCEL", + "INVITE", + "MESSAGE", + "BYE", + "OPTIONS", + "INFO", + "NOTIFY", + "REFER" + ].toString()); + _this = _super.call(this, ua, Constants_1.C.SUBSCRIBE, target, options) || this; + _this.type = Enums_1.TypeStrings.Subscription; + // TODO: check for valid events here probably make a list in SIP.C; or leave it up to app to check? + // The check may need to/should probably occur on the other side, + _this.event = event; + _this.requestedExpires = expires; + _this.state = "init"; + _this.contact = ua.contact.toString(); + _this.extraHeaders = options.extraHeaders; + _this.logger = ua.getLogger("sip.subscription"); + _this.expires = expires; + _this.timers = { N: undefined, subDuration: undefined }; + _this.errorCodes = [404, 405, 410, 416, 480, 481, 482, 483, 484, 485, 489, 501, 604]; + return _this; + } + SubscriptionOriginal.prototype.subscribe = function () { + var _this = this; + // these states point to an existing subscription, no subscribe is necessary + if (this.state === "active") { + this.refresh(); + return this; + } + else if (this.state === "notify_wait") { + return this; + } + clearTimeout(this.timers.subDuration); + clearTimeout(this.timers.N); + this.timers.N = setTimeout(function () { return _this.timer_fire(); }, Timers_1.Timers.TIMER_N); + if (this.request && this.request.from) { + this.ua.earlySubscriptions[this.request.callId + this.request.from.parameters.tag + this.event] = this; + } + this.send(); + this.state = "notify_wait"; + return this; + }; + SubscriptionOriginal.prototype.refresh = function () { + var _this = this; + if (this.state === "terminated" || this.state === "pending" || this.state === "notify_wait") { + return; + } + var extraHeaders = this.extraHeaders; + var body = this.body ? messages_1.fromBodyObj(this.body) : undefined; + if (this.subscription && this.subscription.subscriptionState === subscription_1.SubscriptionState.Active || + this.subscription && this.subscription.subscriptionState === subscription_1.SubscriptionState.Pending) { + this.subscription.subscribe({ + onAccept: function (subscribeResponse) { return _this.receiveResponse(subscribeResponse.message); }, + onProgress: function (subscribeResponse) { return _this.receiveResponse(subscribeResponse.message); }, + onRedirect: function (subscribeResponse) { return _this.receiveResponse(subscribeResponse.message); }, + onReject: function (subscribeResponse) { return _this.receiveResponse(subscribeResponse.message); }, + onTrying: function (subscribeResponse) { return _this.receiveResponse(subscribeResponse.message); } + }, { + extraHeaders: extraHeaders, + body: body + }); + } + }; + SubscriptionOriginal.prototype.receiveResponse = function (response) { + var _this = this; + var statusCode = response.statusCode ? response.statusCode : 0; + var cause = Utils_1.Utils.getReasonPhrase(statusCode); + if ((this.state === "notify_wait" && statusCode >= 300) || + (this.state !== "notify_wait" && this.errorCodes.indexOf(statusCode) !== -1)) { + this.failed(response, undefined); + } + else if (/^2[0-9]{2}$/.test(statusCode.toString())) { + this.emit("accepted", response, cause); + // As we don't support RFC 5839 or other extensions where the NOTIFY is optional, timer N will not be cleared + // clearTimeout(this.timers.N); + var expires = response.getHeader("Expires"); + if (expires && Number(expires) <= this.requestedExpires) { + // Preserve new expires value for subsequent requests + this.expires = Number(expires); + this.timers.subDuration = setTimeout(function () { return _this.refresh(); }, Number(expires) * 900); + } + else { + if (!expires) { + this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE"); + this.failed(response, "Expires Header Missing"); + } + else { + this.logger.warn("Expires header in a 200-class response to" + + " SUBSCRIBE with a higher value than the one in the request"); + this.failed(response, "Invalid Expires Header"); + } + } + } + else if (statusCode > 300) { + this.emit("failed", response, cause); + this.emit("rejected", response, cause); + } + }; + SubscriptionOriginal.prototype.unsubscribe = function () { + var _this = this; + var extraHeaders = []; + this.state = "terminated"; + extraHeaders.push("Event: " + this.event); + extraHeaders.push("Expires: 0"); + extraHeaders.push("Contact: " + this.contact); + // was UA.C.ALLOWED_METHODS, removed due to circular dependency + extraHeaders.push("Allow: " + [ + "ACK", + "CANCEL", + "INVITE", + "MESSAGE", + "BYE", + "OPTIONS", + "INFO", + "NOTIFY", + "REFER" + ].toString()); + var body = this.body ? messages_1.fromBodyObj(this.body) : undefined; + if (this.subscription && this.subscription.subscriptionState === subscription_1.SubscriptionState.Active || + this.subscription && this.subscription.subscriptionState === subscription_1.SubscriptionState.Pending) { + this.subscription.subscribe({ + onAccept: function (subscribeResponse) { return; }, + onProgress: function (subscribeResponse) { return; }, + onRedirect: function (subscribeResponse) { return; }, + onReject: function (subscribeResponse) { return; }, + onTrying: function (subscribeResponse) { return; }, + }, { + extraHeaders: extraHeaders, + body: body + }); + } + clearTimeout(this.timers.subDuration); + clearTimeout(this.timers.N); + this.timers.N = setTimeout(function () { return _this.timer_fire(); }, Timers_1.Timers.TIMER_N); + this.emit("terminated"); + }; + SubscriptionOriginal.prototype.receiveRequest = function (request) { + var _this = this; + var subState; + var setExpiresTimeout = function () { + if (subState.expires) { + clearTimeout(_this.timers.subDuration); + subState.expires = Math.min(_this.expires, Math.max(subState.expires, 0)); + _this.timers.subDuration = setTimeout(function () { return _this.refresh(); }, subState.expires * 900); + } + }; + if (!this.matchEvent(request)) { // checks event and subscription_state headers + request.reject({ statusCode: 489 }); + return; + } + subState = request.message.parseHeader("Subscription-State"); + request.accept(); + clearTimeout(this.timers.N); + this.emit("notify", { request: request.message }); + // if we've set state to terminated, no further processing should take place + // and we are only interested in cleaning up after the appropriate NOTIFY + if (this.state === "terminated") { + if (subState.state === "terminated") { + clearTimeout(this.timers.N); + clearTimeout(this.timers.subDuration); + delete this.ua.subscriptions[this.id || ""]; + } + return; + } + switch (subState.state) { + case "active": + this.state = "active"; + setExpiresTimeout(); + break; + case "pending": + if (this.state === "notify_wait") { + setExpiresTimeout(); + } + this.state = "pending"; + break; + case "terminated": + clearTimeout(this.timers.subDuration); + if (subState.reason) { + this.logger.log("terminating subscription with reason " + subState.reason); + switch (subState.reason) { + case "deactivated": + case "timeout": + this.subscribe(); + return; + case "probation": + case "giveup": + if (subState.params && subState.params["retry-after"]) { + this.timers.subDuration = setTimeout(function () { return _this.subscribe(); }, subState.params["retry-after"]); + } + else { + this.subscribe(); + } + return; + case "rejected": + case "noresource": + case "invariant": + break; + } + } + this.close(); + break; + } + }; + SubscriptionOriginal.prototype.close = function () { + if (this.state === "notify_wait") { + this.state = "terminated"; + clearTimeout(this.timers.N); + clearTimeout(this.timers.subDuration); + this.receiveResponse = function () { }; + if (this.request && this.request.from) { + delete this.ua.earlySubscriptions[this.request.callId + this.request.from.parameters.tag + this.event]; + } + this.emit("terminated"); + } + else if (this.state !== "terminated") { + this.unsubscribe(); + } + }; + SubscriptionOriginal.prototype.onDialogError = function (response) { + this.failed(response, Constants_1.C.causes.DIALOG_ERROR); + }; + SubscriptionOriginal.prototype.on = function (name, callback) { return _super.prototype.on.call(this, name, callback); }; + SubscriptionOriginal.prototype.send = function () { + var _this = this; + if (!this.ua.userAgentCore) { + throw new Error("User agent core undefined."); + } + this.ua.userAgentCore.subscribe(this.request, { + onNotify: function (requestWithSubscription) { + _this.subscription = requestWithSubscription.subscription; + if (_this.subscription) { + _this.subscription.delegate = { + onNotify: function (incomingNotifyRequest) { return _this.receiveRequest(incomingNotifyRequest); } + }; + _this.id = _this.subscription.id; + _this.ua.subscriptions[_this.id] = _this; + } + if (_this.request && _this.request.from) { + delete _this.ua.earlySubscriptions[_this.request.callId + _this.request.from.parameters.tag + _this.event]; + } + _this.receiveRequest(requestWithSubscription.request); + }, + onAccept: function (subscribeResponse) { return _this.receiveResponse(subscribeResponse.message); }, + onProgress: function (subscribeResponse) { return _this.receiveResponse(subscribeResponse.message); }, + onRedirect: function (subscribeResponse) { return _this.receiveResponse(subscribeResponse.message); }, + onReject: function (subscribeResponse) { return _this.receiveResponse(subscribeResponse.message); }, + onTrying: function (subscribeResponse) { return _this.receiveResponse(subscribeResponse.message); } + }); + return this; + }; + SubscriptionOriginal.prototype.timer_fire = function () { + if (this.state === "terminated") { + clearTimeout(this.timers.N); + clearTimeout(this.timers.subDuration); + delete this.ua.subscriptions[this.id || ""]; + } + else if (this.state === "notify_wait" || this.state === "pending") { + this.close(); + } + else { + this.refresh(); + } + }; + SubscriptionOriginal.prototype.failed = function (response, cause) { + this.close(); + this.emit("failed", response, cause); + this.emit("rejected", response, cause); + return this; + }; + SubscriptionOriginal.prototype.matchEvent = function (request) { + // Check mandatory header Event + if (!request.message.hasHeader("Event")) { + this.logger.warn("missing Event header"); + return false; + } + // Check mandatory header Subscription-State + if (!request.message.hasHeader("Subscription-State")) { + this.logger.warn("missing Subscription-State header"); + return false; + } + // Check whether the event in NOTIFY matches the event in SUBSCRIBE + var event = request.message.parseHeader("event").event; + if (this.event !== event) { + this.logger.warn("event match failed"); + request.reject({ + statusCode: 481, + reasonPhrase: "Event Match Failed" + }); + return false; + } + else { + return true; + } + }; + return SubscriptionOriginal; +}(ClientContext_1.ClientContext)); +exports.SubscriptionOriginal = SubscriptionOriginal; diff --git a/lib/Timers.d.ts b/lib/Timers.d.ts new file mode 100644 index 000000000..5d0e2ada5 --- /dev/null +++ b/lib/Timers.d.ts @@ -0,0 +1,16 @@ +export declare const Timers: { + T1: number; + T2: number; + T4: number; + TIMER_B: number; + TIMER_D: number; + TIMER_F: number; + TIMER_H: number; + TIMER_I: number; + TIMER_J: number; + TIMER_K: number; + TIMER_L: number; + TIMER_M: number; + TIMER_N: number; + PROVISIONAL_RESPONSE_INTERVAL: number; +}; diff --git a/lib/Timers.js b/lib/Timers.js new file mode 100644 index 000000000..e363818d7 --- /dev/null +++ b/lib/Timers.js @@ -0,0 +1,21 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var T1 = 500; +var T2 = 4000; +var T4 = 5000; +exports.Timers = { + T1: T1, + T2: T2, + T4: T4, + TIMER_B: 64 * T1, + TIMER_D: 0 * T1, + TIMER_F: 64 * T1, + TIMER_H: 64 * T1, + TIMER_I: 0 * T4, + TIMER_J: 0 * T1, + TIMER_K: 0 * T4, + TIMER_L: 64 * T1, + TIMER_M: 64 * T1, + TIMER_N: 64 * T1, + PROVISIONAL_RESPONSE_INTERVAL: 60000 // See RFC 3261 Section 13.3.1.1 +}; diff --git a/lib/Transport.d.ts b/lib/Transport.d.ts new file mode 100644 index 000000000..41c458aa3 --- /dev/null +++ b/lib/Transport.d.ts @@ -0,0 +1,81 @@ +/// +import { EventEmitter } from "events"; +import { TypeStrings } from "./Enums"; +import { Logger } from "./LoggerFactory"; +export declare abstract class Transport extends EventEmitter { + type: TypeStrings; + server: any; + protected logger: Logger; + constructor(logger: Logger, options: any); + /** + * Returns the promise designated by the child layer then emits a connected event. + * Automatically emits an event upon resolution, unless overrideEvent is set. If you + * override the event in this fashion, you should emit it in your implementation of connectPromise + * @param {Object} [options] + * @returns {Promise} + */ + connect(options?: any): Promise; + /** + * Returns true if the transport is connected + * @returns {Boolean} + */ + abstract isConnected(): boolean; + /** + * Sends a message then emits a 'messageSent' event. Automatically emits an + * event upon resolution, unless data.overrideEvent is set. If you override + * the event in this fashion, you should emit it in your implementation of sendPromise + * @param {String} msg + * @param {Object} options + * @returns {Promise} + */ + send(msg: string, options?: any): Promise; + /** + * Returns the promise designated by the child layer then emits a + * disconnected event. Automatically emits an event upon resolution, + * unless overrideEvent is set. If you override the event in this fashion, + * you should emit it in your implementation of disconnectPromise + * @param {Object} [options] + * @returns {Promise} + */ + disconnect(options?: any): Promise; + afterConnected(callback: () => void): void; + /** + * Returns a promise which resolves once the UA is connected. DEPRECATION WARNING: just use afterConnected() + * @returns {Promise} + */ + waitForConnected(): Promise; + /** + * Called by connect, must return a promise + * promise must resolve to an object. object supports 1 parameter: overrideEvent - Boolean + * @abstract + * @private + * @param {Object} [options] + * @returns {Promise} + */ + protected abstract connectPromise(options: any): Promise; + /** + * Called by send, must return a promise + * promise must resolve to an object. object supports 2 parameters: msg - string (mandatory) + * and overrideEvent - Boolean (optional) + * @abstract + * @private + * @param {String} msg + * @param {Object} [options] + * @returns {Promise} + */ + protected abstract sendPromise(msg: string, options?: any): Promise; + /** + * Called by disconnect, must return a promise + * promise must resolve to an object. object supports 1 parameter: overrideEvent - Boolean + * @abstract + * @private + * @param {Object} [options] + * @returns {Promise} + */ + protected abstract disconnectPromise(options: any): Promise; + /** + * To be called when a message is received + * @param {Event} e + */ + protected abstract onMessage(e: any): void; +} diff --git a/lib/Transport.js b/lib/Transport.js new file mode 100644 index 000000000..7aaef1735 --- /dev/null +++ b/lib/Transport.js @@ -0,0 +1,103 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var events_1 = require("events"); +var Enums_1 = require("./Enums"); +/* Transport + * @class Abstract transport layer parent class + * @param {Logger} logger + * @param {Object} [options] + */ +var Transport = /** @class */ (function (_super) { + __extends(Transport, _super); + function Transport(logger, options) { + var _this = _super.call(this) || this; + _this.type = Enums_1.TypeStrings.Transport; + _this.logger = logger; + return _this; + } + /** + * Returns the promise designated by the child layer then emits a connected event. + * Automatically emits an event upon resolution, unless overrideEvent is set. If you + * override the event in this fashion, you should emit it in your implementation of connectPromise + * @param {Object} [options] + * @returns {Promise} + */ + Transport.prototype.connect = function (options) { + var _this = this; + if (options === void 0) { options = {}; } + return this.connectPromise(options).then(function (data) { + if (!data.overrideEvent) { + _this.emit("connected"); + } + }); + }; + /** + * Sends a message then emits a 'messageSent' event. Automatically emits an + * event upon resolution, unless data.overrideEvent is set. If you override + * the event in this fashion, you should emit it in your implementation of sendPromise + * @param {String} msg + * @param {Object} options + * @returns {Promise} + */ + Transport.prototype.send = function (msg, options) { + var _this = this; + if (options === void 0) { options = {}; } + return this.sendPromise(msg).then(function (data) { + if (!data.overrideEvent) { + _this.emit("messageSent", data.msg); + } + }); + }; + /** + * Returns the promise designated by the child layer then emits a + * disconnected event. Automatically emits an event upon resolution, + * unless overrideEvent is set. If you override the event in this fashion, + * you should emit it in your implementation of disconnectPromise + * @param {Object} [options] + * @returns {Promise} + */ + Transport.prototype.disconnect = function (options) { + var _this = this; + if (options === void 0) { options = {}; } + return this.disconnectPromise(options).then(function (data) { + if (!data.overrideEvent) { + _this.emit("disconnected"); + } + }); + }; + Transport.prototype.afterConnected = function (callback) { + if (this.isConnected()) { + callback(); + } + else { + this.once("connected", callback); + } + }; + /** + * Returns a promise which resolves once the UA is connected. DEPRECATION WARNING: just use afterConnected() + * @returns {Promise} + */ + Transport.prototype.waitForConnected = function () { + var _this = this; + // tslint:disable-next-line:no-console + console.warn("DEPRECATION WARNING Transport.waitForConnected(): use afterConnected() instead"); + return new Promise(function (resolve) { + _this.afterConnected(resolve); + }); + }; + return Transport; +}(events_1.EventEmitter)); +exports.Transport = Transport; diff --git a/lib/UA.d.ts b/lib/UA.d.ts new file mode 100644 index 000000000..e704ef484 --- /dev/null +++ b/lib/UA.d.ts @@ -0,0 +1,225 @@ +/// +import { EventEmitter } from "events"; +import { ClientContext } from "./ClientContext"; +import { C as SIPConstants } from "./Constants"; +import { IncomingSubscribeRequest } from "./Core/messages"; +import { UserAgentCore } from "./Core/user-agent-core"; +import { DigestAuthentication } from "./DigestAuthentication"; +import { TypeStrings, UAStatus } from "./Enums"; +import { Logger, LoggerFactory } from "./LoggerFactory"; +import { PublishContext } from "./PublishContext"; +import { ReferServerContext } from "./ReferContext"; +import { InviteClientContext, InviteServerContext } from "./Session"; +import { SessionDescriptionHandlerModifiers } from "./session-description-handler"; +import { SessionDescriptionHandlerFactory, SessionDescriptionHandlerFactoryOptions } from "./session-description-handler-factory"; +import { IncomingRequest } from "./SIPMessage"; +import { Subscription } from "./Subscription"; +import { Transport } from "./Transport"; +import { URI } from "./URI"; +export declare namespace UA { + interface Options { + uri?: string | URI; + allowLegacyNotifications?: boolean; + allowOutOfDialogRefers?: boolean; + authenticationFactory?: (ua: UA) => DigestAuthentication | any; + authorizationUser?: string; + autostart?: boolean; + autostop?: boolean; + displayName?: string; + dtmfType?: DtmfType; + experimentalFeatures?: boolean; + extraSupported?: Array; + forceRport?: boolean; + hackIpInContact?: boolean; + hackAllowUnregisteredOptionTags?: boolean; + hackViaTcp?: boolean; + hackWssInTransport?: boolean; + hostportParams?: any; + log?: { + builtinEnabled: boolean; + level: string | number; + connector: (level: string, category: string, label: string | undefined, content: any) => void; + }; + noAnswerTimeout?: number; + password?: string; + register?: boolean; + registerOptions?: RegisterOptions; + rel100?: SIPConstants.supported; + replaces?: SIPConstants.supported; + sessionDescriptionHandlerFactory?: SessionDescriptionHandlerFactory; + sessionDescriptionHandlerFactoryOptions?: SessionDescriptionHandlerFactoryOptions; + sipjsId?: string; + transportConstructor?: new (logger: any, options: any) => Transport; + transportOptions?: any; + userAgentString?: string; + usePreloadedRoute?: boolean; + viaHost?: string; + } + interface RegisterOptions { + expires?: number; + extraContactHeaderParams?: Array; + instanceId?: string; + params?: any; + regId?: number; + registrar?: string; + } +} +/** + * @class Class creating a SIP User Agent. + * @param {function returning SIP.sessionDescriptionHandler} [configuration.sessionDescriptionHandlerFactory] + * A function will be invoked by each of the UA's Sessions to build the sessionDescriptionHandler for that Session. + * If no (or a falsy) value is provided, each Session will use a default (WebRTC) sessionDescriptionHandler. + */ +export declare class UA extends EventEmitter { + static readonly C: { + STATUS_INIT: number; + STATUS_STARTING: number; + STATUS_READY: number; + STATUS_USER_CLOSED: number; + STATUS_NOT_READY: number; + CONFIGURATION_ERROR: number; + NETWORK_ERROR: number; + ALLOWED_METHODS: string[]; + ACCEPTED_BODY_TYPES: string[]; + MAX_FORWARDS: number; + TAG_LENGTH: number; + }; + type: TypeStrings; + configuration: UA.Options; + applicants: { + [id: string]: InviteClientContext; + }; + publishers: { + [id: string]: PublishContext; + }; + contact: { + pubGruu: URI | undefined; + tempGruu: URI | undefined; + uri: URI; + toString: (options?: any) => string; + }; + status: UAStatus; + transport: Transport | undefined; + sessions: { + [id: string]: InviteClientContext | InviteServerContext; + }; + data: any; + logger: Logger; + userAgentCore: UserAgentCore; + private log; + private error; + private registerContext; + private environListener; + constructor(configuration?: UA.Options); + register(options?: any): this; + /** + * Unregister. + * + * @param {Boolean} [all] unregister all user bindings. + * + */ + unregister(options?: any): this; + isRegistered(): boolean; + /** + * Make an outgoing call. + * + * @param {String} target + * @param {Object} views + * @param {Object} [options.media] gets passed to SIP.sessionDescriptionHandler.getDescription as mediaHint + * + * @throws {TypeError} + * + */ + invite(target: string | URI, options?: InviteClientContext.Options, modifiers?: SessionDescriptionHandlerModifiers): InviteClientContext; + subscribe(target: string | URI, event: string, options: any): Subscription; + /** + * Send PUBLISH Event State Publication (RFC3903) + * + * @param {String} target + * @param {String} event + * @param {String} body + * @param {Object} [options] + * + * @throws {SIP.Exceptions.MethodParameterError} + */ + publish(target: string | URI, event: string, body: string, options: any): PublishContext; + /** + * Send a message. + * + * @param {String} target + * @param {String} body + * @param {Object} [options] + * + * @throws {TypeError} + */ + message(target: string | URI, body: string, options?: any): ClientContext; + request(method: string, target: string | URI, options?: any): ClientContext; + /** + * Gracefully close. + */ + stop(): this; + /** + * Connect to the WS server if status = STATUS_INIT. + * Resume UA after being closed. + * + */ + start(): this; + /** + * Normalize a string into a valid SIP request URI + * + * @param {String} target + * + * @returns {SIP.URI|undefined} + */ + normalizeTarget(target: string | URI): URI | undefined; + getLogger(category: string, label?: string): Logger; + getLoggerFactory(): LoggerFactory; + /** + * Get the session to which the request belongs to, if any. + * @param {SIP.IncomingRequest} request. + * @returns {SIP.OutgoingSession|SIP.IncomingSession|undefined} + */ + findSession(request: IncomingRequest): InviteClientContext | InviteServerContext | undefined; + on(name: "invite", callback: (session: InviteServerContext) => void): this; + on(name: "inviteSent", callback: (session: InviteClientContext) => void): this; + on(name: "outOfDialogReferRequested", callback: (context: ReferServerContext) => void): this; + on(name: "transportCreated", callback: (transport: Transport) => void): this; + on(name: "message", callback: (message: any) => void): this; + on(name: "notify", callback: (request: any) => void): this; + on(name: "subscribe", callback: (subscribe: IncomingSubscribeRequest) => void): this; + on(name: "registered", callback: (response?: any) => void): this; + on(name: "unregistered" | "registrationFailed", callback: (response?: any, cause?: any) => void): this; + private onTransportError; + /** + * Helper function. Sets transport listeners + */ + private setTransportListeners; + /** + * Transport connection event. + * @event + * @param {SIP.Transport} transport. + */ + private onTransportConnected; + /** + * Handle SIP message received from the transport. + * @param messageString The message. + */ + private onTransportReceiveMsg; + private checkAuthenticationFactory; + /** + * Configuration load. + * returns {void} + */ + private loadConfig; + /** + * Configuration checker. + * @return {Boolean} + */ + private getConfigurationCheck; +} +export declare namespace UA { + enum DtmfType { + RTP = "rtp", + INFO = "info" + } +} diff --git a/lib/UA.js b/lib/UA.js new file mode 100644 index 000000000..6358f7219 --- /dev/null +++ b/lib/UA.js @@ -0,0 +1,1012 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var events_1 = require("events"); +var ClientContext_1 = require("./ClientContext"); +var Constants_1 = require("./Constants"); +var user_agent_core_1 = require("./Core/user-agent-core"); +var DigestAuthentication_1 = require("./DigestAuthentication"); +var Enums_1 = require("./Enums"); +var Exceptions_1 = require("./Exceptions"); +var Grammar_1 = require("./Grammar"); +var LoggerFactory_1 = require("./LoggerFactory"); +var Parser_1 = require("./Parser"); +var PublishContext_1 = require("./PublishContext"); +var ReferContext_1 = require("./ReferContext"); +var RegisterContext_1 = require("./RegisterContext"); +var ServerContext_1 = require("./ServerContext"); +var Session_1 = require("./Session"); +var SIPMessage_1 = require("./SIPMessage"); +var Subscription_1 = require("./Subscription"); +var URI_1 = require("./URI"); +var Utils_1 = require("./Utils"); +var SessionDescriptionHandler_1 = require("./Web/SessionDescriptionHandler"); +var Transport_1 = require("./Web/Transport"); +var environment = global.window || global; +/** + * @class Class creating a SIP User Agent. + * @param {function returning SIP.sessionDescriptionHandler} [configuration.sessionDescriptionHandlerFactory] + * A function will be invoked by each of the UA's Sessions to build the sessionDescriptionHandler for that Session. + * If no (or a falsy) value is provided, each Session will use a default (WebRTC) sessionDescriptionHandler. + */ +var UA = /** @class */ (function (_super) { + __extends(UA, _super); + function UA(configuration) { + var _this = _super.call(this) || this; + _this.type = Enums_1.TypeStrings.UA; + _this.log = new LoggerFactory_1.LoggerFactory(); + _this.logger = _this.getLogger("sip.ua"); + _this.configuration = {}; + // User actions outside any session/dialog (MESSAGE) + _this.applicants = {}; + _this.data = {}; + _this.sessions = {}; + _this.publishers = {}; + _this.status = Enums_1.UAStatus.STATUS_INIT; + /** + * Load configuration + * + * @throws {SIP.Exceptions.ConfigurationError} + * @throws {TypeError} + */ + if (configuration === undefined) { + configuration = {}; + } + else if (typeof configuration === "string" || configuration instanceof String) { + configuration = { + uri: configuration + }; + } + // Apply log configuration if present + if (configuration.log) { + if (configuration.log.hasOwnProperty("builtinEnabled")) { + _this.log.builtinEnabled = configuration.log.builtinEnabled; + } + if (configuration.log.hasOwnProperty("connector")) { + _this.log.connector = configuration.log.connector; + } + if (configuration.log.hasOwnProperty("level")) { + var level = configuration.log.level; + // const normalized: Levels = typeof level === "string" ? Levels[level] : level; + var normalized = void 0; + switch (level) { + case "error": + normalized = LoggerFactory_1.Levels.error; + break; + case "warn": + normalized = LoggerFactory_1.Levels.warn; + break; + case "log": + normalized = LoggerFactory_1.Levels.log; + break; + case "debug": + normalized = LoggerFactory_1.Levels.debug; + break; + default: + break; + } + // avoid setting level when invalid, use default level instead + if (normalized === undefined) { + _this.logger.error("Invalid \"level\" parameter value: " + JSON.stringify(level)); + } + else { + _this.log.level = normalized; + } + } + } + try { + _this.loadConfig(configuration); + } + catch (e) { + _this.status = Enums_1.UAStatus.STATUS_NOT_READY; + _this.error = UA.C.CONFIGURATION_ERROR; + throw e; + } + var userAgentCoreConfiguration = user_agent_core_1.makeUserAgentCoreConfigurationFromUA(_this); + // The Replaces header contains information used to match an existing + // SIP dialog (call-id, to-tag, and from-tag). Upon receiving an INVITE + // with a Replaces header, the User Agent (UA) attempts to match this + // information with a confirmed or early dialog. + // https://tools.ietf.org/html/rfc3891#section-3 + var handleInviteWithReplacesHeader = function (context, request) { + if (_this.configuration.replaces !== Constants_1.C.supported.UNSUPPORTED) { + var replaces = request.parseHeader("replaces"); + if (replaces) { + var targetSession = _this.sessions[replaces.call_id + replaces.replaces_from_tag] || + _this.sessions[replaces.call_id + replaces.replaces_to_tag] || + undefined; + if (!targetSession) { + _this.userAgentCore.replyStateless(request, { statusCode: 481 }); + return; + } + if (targetSession.status === Enums_1.SessionStatus.STATUS_TERMINATED) { + _this.userAgentCore.replyStateless(request, { statusCode: 603 }); + return; + } + var targetDialogId = replaces.call_id + replaces.replaces_to_tag + replaces.replaces_from_tag; + var targetDialog = _this.userAgentCore.dialogs.get(targetDialogId); + if (!targetDialog) { + _this.userAgentCore.replyStateless(request, { statusCode: 481 }); + return; + } + if (!targetDialog.early && replaces.early_only) { + _this.userAgentCore.replyStateless(request, { statusCode: 486 }); + return; + } + context.replacee = targetSession; + } + } + }; + var userAgentCoreDelegate = { + onInvite: function (incomingInviteRequest) { + // FIXME: Ported - 100 Trying send should be configurable. + // Only required if TU will not respond in 200ms. + // https://tools.ietf.org/html/rfc3261#section-17.2.1 + incomingInviteRequest.trying(); + incomingInviteRequest.delegate = { + onCancel: function (cancel) { + context.onCancel(cancel); + }, + onTransportError: function (error) { + context.onTransportError(); + } + }; + var context = new Session_1.InviteServerContext(_this, incomingInviteRequest); + // Ported - handling of out of dialog INVITE with Replaces. + handleInviteWithReplacesHeader(context, incomingInviteRequest.message); + // Ported - make the first call to progress automatically. + if (context.autoSendAnInitialProvisionalResponse) { + context.progress(); + } + _this.emit("invite", context); + }, + onMessage: function (incomingMessageRequest) { + // Ported - handling of out of dialog MESSAGE. + var serverContext = new ServerContext_1.ServerContext(_this, incomingMessageRequest); + serverContext.body = incomingMessageRequest.message.body; + serverContext.contentType = incomingMessageRequest.message.getHeader("Content-Type") || "text/plain"; + incomingMessageRequest.accept(); + _this.emit("message", serverContext); // TODO: Review. Why is a "ServerContext" emitted? What use it is? + }, + onNotify: function (incomingNotifyRequest) { + // DEPRECATED: Out of dialog NOTIFY is an obsolete usage. + // Ported - handling of out of dialog NOTIFY. + if (_this.configuration.allowLegacyNotifications && _this.listeners("notify").length > 0) { + incomingNotifyRequest.accept(); + _this.emit("notify", { request: incomingNotifyRequest.message }); + } + else { + incomingNotifyRequest.reject({ statusCode: 481 }); + } + }, + onRefer: function (incomingReferRequest) { + // Ported - handling of out of dialog REFER. + _this.logger.log("Received an out of dialog refer"); + if (!_this.configuration.allowOutOfDialogRefers) { + incomingReferRequest.reject({ statusCode: 405 }); + } + _this.logger.log("Allow out of dialog refers is enabled on the UA"); + var referContext = new ReferContext_1.ReferServerContext(_this, incomingReferRequest); + if (_this.listeners("outOfDialogReferRequested").length) { + _this.emit("outOfDialogReferRequested", referContext); + } + else { + _this.logger.log("No outOfDialogReferRequest listeners, automatically accepting and following the out of dialog refer"); + referContext.accept({ followRefer: true }); + } + }, + onSubscribe: function (incomingSubscribeRequest) { + _this.emit("subscribe", incomingSubscribeRequest); + }, + }; + _this.userAgentCore = new user_agent_core_1.UserAgentCore(userAgentCoreConfiguration, userAgentCoreDelegate); + // Initialize registerContext + _this.registerContext = new RegisterContext_1.RegisterContext(_this, configuration.registerOptions); + _this.registerContext.on("failed", _this.emit.bind(_this, "registrationFailed")); + _this.registerContext.on("registered", _this.emit.bind(_this, "registered")); + _this.registerContext.on("unregistered", _this.emit.bind(_this, "unregistered")); + if (_this.configuration.autostart) { + _this.start(); + } + return _this; + } + // ================= + // High Level API + // ================= + UA.prototype.register = function (options) { + if (options === void 0) { options = {}; } + if (options.register) { + this.configuration.register = true; + } + this.registerContext.register(options); + return this; + }; + /** + * Unregister. + * + * @param {Boolean} [all] unregister all user bindings. + * + */ + UA.prototype.unregister = function (options) { + var _this = this; + this.configuration.register = false; + if (this.transport) { + this.transport.afterConnected(function () { + _this.registerContext.unregister(options); + }); + } + return this; + }; + UA.prototype.isRegistered = function () { + return this.registerContext.registered; + }; + /** + * Make an outgoing call. + * + * @param {String} target + * @param {Object} views + * @param {Object} [options.media] gets passed to SIP.sessionDescriptionHandler.getDescription as mediaHint + * + * @throws {TypeError} + * + */ + UA.prototype.invite = function (target, options, modifiers) { + var _this = this; + var context = new Session_1.InviteClientContext(this, target, options, modifiers); + // Delay sending actual invite until the next 'tick' if we are already + // connected, so that API consumers can register to events fired by the + // the session. + if (this.transport) { + this.transport.afterConnected(function () { + context.invite(); + _this.emit("inviteSent", context); + }); + } + return context; + }; + UA.prototype.subscribe = function (target, event, options) { + var sub = new Subscription_1.Subscription(this, target, event, options); + if (this.transport) { + this.transport.afterConnected(function () { return sub.subscribe(); }); + } + return sub; + }; + /** + * Send PUBLISH Event State Publication (RFC3903) + * + * @param {String} target + * @param {String} event + * @param {String} body + * @param {Object} [options] + * + * @throws {SIP.Exceptions.MethodParameterError} + */ + UA.prototype.publish = function (target, event, body, options) { + var pub = new PublishContext_1.PublishContext(this, target, event, options); + if (this.transport) { + this.transport.afterConnected(function () { + pub.publish(body); + }); + } + return pub; + }; + /** + * Send a message. + * + * @param {String} target + * @param {String} body + * @param {Object} [options] + * + * @throws {TypeError} + */ + UA.prototype.message = function (target, body, options) { + if (options === void 0) { options = {}; } + if (body === undefined) { + throw new TypeError("Not enough arguments"); + } + // There is no Message module, so it is okay that the UA handles defaults here. + options.contentType = options.contentType || "text/plain"; + options.body = body; + return this.request(Constants_1.C.MESSAGE, target, options); + }; + UA.prototype.request = function (method, target, options) { + var req = new ClientContext_1.ClientContext(this, method, target, options); + if (this.transport) { + this.transport.afterConnected(function () { return req.send(); }); + } + return req; + }; + /** + * Gracefully close. + */ + UA.prototype.stop = function () { + this.logger.log("user requested closure..."); + if (this.status === Enums_1.UAStatus.STATUS_USER_CLOSED) { + this.logger.warn("UA already closed"); + return this; + } + // Close registerContext + this.logger.log("closing registerContext"); + this.registerContext.close(); + // Run _terminate_ on every Session + for (var session in this.sessions) { + if (this.sessions[session]) { + this.logger.log("closing session " + session); + this.sessions[session].terminate(); + } + } + // Run _close_ on every Publisher + for (var publisher in this.publishers) { + if (this.publishers[publisher]) { + this.logger.log("unpublish " + publisher); + this.publishers[publisher].close(); + } + } + // Run _close_ on every applicant + for (var applicant in this.applicants) { + if (this.applicants[applicant]) { + this.applicants[applicant].close(); + } + } + this.status = Enums_1.UAStatus.STATUS_USER_CLOSED; + if (typeof environment.removeEventListener === "function") { + // Google Chrome Packaged Apps don't allow 'unload' listeners: + // unload is not available in packaged apps + if (!(global.chrome && global.chrome.app && global.chrome.app.runtime)) { + environment.removeEventListener("unload", this.environListener); + } + } + return this; + }; + /** + * Connect to the WS server if status = STATUS_INIT. + * Resume UA after being closed. + * + */ + UA.prototype.start = function () { + var _this = this; + this.logger.log("user requested startup..."); + if (this.status === Enums_1.UAStatus.STATUS_INIT) { + this.status = Enums_1.UAStatus.STATUS_STARTING; + if (!this.configuration.transportConstructor) { + throw new Exceptions_1.Exceptions.TransportError("Transport constructor not set"); + } + this.transport = new this.configuration.transportConstructor(this.getLogger("sip.transport"), this.configuration.transportOptions); + this.setTransportListeners(); + this.emit("transportCreated", this.transport); + this.transport.connect(); + } + else if (this.status === Enums_1.UAStatus.STATUS_USER_CLOSED) { + this.logger.log("resuming"); + this.status = Enums_1.UAStatus.STATUS_READY; + if (this.transport) { + this.transport.connect(); + } + } + else if (this.status === Enums_1.UAStatus.STATUS_STARTING) { + this.logger.log("UA is in STARTING status, not opening new connection"); + } + else if (this.status === Enums_1.UAStatus.STATUS_READY) { + this.logger.log("UA is in READY status, not resuming"); + } + else { + this.logger.error("Connection is down. Auto-Recovery system is trying to connect"); + } + if (this.configuration.autostop && typeof environment.addEventListener === "function") { + // Google Chrome Packaged Apps don't allow 'unload' listeners: + // unload is not available in packaged apps + if (!(global.chrome && global.chrome.app && global.chrome.app.runtime)) { + this.environListener = this.stop; + environment.addEventListener("unload", function () { return _this.environListener(); }); + } + } + return this; + }; + /** + * Normalize a string into a valid SIP request URI + * + * @param {String} target + * + * @returns {SIP.URI|undefined} + */ + UA.prototype.normalizeTarget = function (target) { + return Utils_1.Utils.normalizeTarget(target, this.configuration.hostportParams); + }; + UA.prototype.getLogger = function (category, label) { + return this.log.getLogger(category, label); + }; + UA.prototype.getLoggerFactory = function () { + return this.log; + }; + /** + * Get the session to which the request belongs to, if any. + * @param {SIP.IncomingRequest} request. + * @returns {SIP.OutgoingSession|SIP.IncomingSession|undefined} + */ + UA.prototype.findSession = function (request) { + return this.sessions[request.callId + request.fromTag] || + this.sessions[request.callId + request.toTag] || + undefined; + }; + UA.prototype.on = function (name, callback) { return _super.prototype.on.call(this, name, callback); }; + // ============================== + // Event Handlers + // ============================== + UA.prototype.onTransportError = function () { + if (this.status === Enums_1.UAStatus.STATUS_USER_CLOSED) { + return; + } + if (!this.error || this.error !== UA.C.NETWORK_ERROR) { + this.status = Enums_1.UAStatus.STATUS_NOT_READY; + this.error = UA.C.NETWORK_ERROR; + } + }; + /** + * Helper function. Sets transport listeners + */ + UA.prototype.setTransportListeners = function () { + var _this = this; + if (this.transport) { + this.transport.on("connected", function () { return _this.onTransportConnected(); }); + this.transport.on("message", function (message) { return _this.onTransportReceiveMsg(message); }); + this.transport.on("transportError", function () { return _this.onTransportError(); }); + } + }; + /** + * Transport connection event. + * @event + * @param {SIP.Transport} transport. + */ + UA.prototype.onTransportConnected = function () { + var _this = this; + if (this.configuration.register) { + // In an effor to maintain behavior from when we "initialized" an + // authentication factory, this is in a Promise.then + Promise.resolve().then(function () { return _this.registerContext.register(); }); + } + }; + /** + * Handle SIP message received from the transport. + * @param messageString The message. + */ + UA.prototype.onTransportReceiveMsg = function (messageString) { + var _this = this; + var message = Parser_1.Parser.parseMessage(messageString, this); + if (!message) { + this.logger.warn("UA failed to parse incoming SIP message - discarding."); + return; + } + if (this.status === Enums_1.UAStatus.STATUS_USER_CLOSED && message instanceof SIPMessage_1.IncomingRequest) { + this.logger.warn("UA received message when status = USER_CLOSED - aborting"); + return; + } + // A valid SIP request formulated by a UAC MUST, at a minimum, contain + // the following header fields: To, From, CSeq, Call-ID, Max-Forwards, + // and Via; all of these header fields are mandatory in all SIP + // requests. + // https://tools.ietf.org/html/rfc3261#section-8.1.1 + var hasMinimumHeaders = function () { + var mandatoryHeaders = ["from", "to", "call_id", "cseq", "via"]; + for (var _i = 0, mandatoryHeaders_1 = mandatoryHeaders; _i < mandatoryHeaders_1.length; _i++) { + var header = mandatoryHeaders_1[_i]; + if (!message.hasHeader(header)) { + _this.logger.warn("Missing mandatory header field : " + header + "."); + return false; + } + } + return true; + }; + // Request Checks + if (message instanceof SIPMessage_1.IncomingRequest) { + // This is port of SanityCheck.minimumHeaders(). + if (!hasMinimumHeaders()) { + this.logger.warn("Request missing mandatory header field. Dropping."); + return; + } + // FIXME: This is non-standard and should be a configruable behavior (desirable regardless). + // Custom SIP.js check to reject request from ourself (this instance of SIP.js). + // This is port of SanityCheck.rfc3261_16_3_4(). + if (!message.toTag && message.callId.substr(0, 5) === this.configuration.sipjsId) { + this.userAgentCore.replyStateless(message, { statusCode: 482 }); + return; + } + // FIXME: This should be Transport check before we get here (Section 18). + // Custom SIP.js check to reject requests if body length wrong. + // This is port of SanityCheck.rfc3261_18_3_request(). + var len = Utils_1.Utils.str_utf8_length(message.body); + var contentLength = message.getHeader("content-length"); + if (contentLength && len < Number(contentLength)) { + this.userAgentCore.replyStateless(message, { statusCode: 400 }); + return; + } + } + // Reponse Checks + if (message instanceof SIPMessage_1.IncomingResponse) { + // This is port of SanityCheck.minimumHeaders(). + if (!hasMinimumHeaders()) { + this.logger.warn("Response missing mandatory header field. Dropping."); + return; + } + // Custom SIP.js check to drop responses if multiple Via headers. + // This is port of SanityCheck.rfc3261_8_1_3_3(). + if (message.getHeaders("via").length > 1) { + this.logger.warn("More than one Via header field present in the response. Dropping."); + return; + } + // FIXME: This should be Transport check before we get here (Section 18). + // Custom SIP.js check to drop responses if bad Via header. + // This is port of SanityCheck.rfc3261_18_1_2(). + if (message.via.host !== this.configuration.viaHost || message.via.port !== undefined) { + this.logger.warn("Via sent-by in the response does not match UA Via host value. Dropping."); + return; + } + // FIXME: This should be Transport check before we get here (Section 18). + // Custom SIP.js check to reject requests if body length wrong. + // This is port of SanityCheck.rfc3261_18_3_response(). + var len = Utils_1.Utils.str_utf8_length(message.body); + var contentLength = message.getHeader("content-length"); + if (contentLength && len < Number(contentLength)) { + this.logger.warn("Message body length is lower than the value in Content-Length header field. Dropping."); + return; + } + } + // Handle Request + if (message instanceof SIPMessage_1.IncomingRequest) { + this.userAgentCore.receiveIncomingRequestFromTransport(message); + return; + } + // Handle Response + if (message instanceof SIPMessage_1.IncomingResponse) { + this.userAgentCore.receiveIncomingResponseFromTransport(message); + return; + } + throw new Error("Invalid message type."); + }; + // ================= + // Utils + // ================= + UA.prototype.checkAuthenticationFactory = function (authenticationFactory) { + if (!(authenticationFactory instanceof Function)) { + return; + } + if (!authenticationFactory.initialize) { + authenticationFactory.initialize = function () { + return Promise.resolve(); + }; + } + return authenticationFactory; + }; + /** + * Configuration load. + * returns {void} + */ + UA.prototype.loadConfig = function (configuration) { + var _this = this; + // Settings and default values + var settings = { + /* Host address + * Value to be set in Via sent_by and host part of Contact FQDN + */ + viaHost: Utils_1.Utils.createRandomToken(12) + ".invalid", + uri: new URI_1.URI("sip", "anonymous." + Utils_1.Utils.createRandomToken(6), "anonymous.invalid", undefined, undefined), + // Custom Configuration Settings + custom: {}, + // Display name + displayName: "", + // Password + password: undefined, + register: true, + // Registration parameters + registerOptions: {}, + // Transport related parameters + transportConstructor: Transport_1.Transport, + transportOptions: {}, + // string to be inserted into User-Agent request header + userAgentString: Constants_1.C.USER_AGENT, + // Session parameters + noAnswerTimeout: 60, + // Hacks + hackViaTcp: false, + hackIpInContact: false, + hackWssInTransport: false, + hackAllowUnregisteredOptionTags: false, + // Session Description Handler Options + sessionDescriptionHandlerFactoryOptions: { + constraints: {}, + peerConnectionOptions: {} + }, + extraSupported: [], + contactName: Utils_1.Utils.createRandomToken(8), + contactTransport: "ws", + forceRport: false, + // autostarting + autostart: true, + autostop: true, + // Reliable Provisional Responses + rel100: Constants_1.C.supported.UNSUPPORTED, + // DTMF type: 'info' or 'rtp' (RFC 4733) + // RTP Payload Spec: https://tools.ietf.org/html/rfc4733 + // WebRTC Audio Spec: https://tools.ietf.org/html/rfc7874 + dtmfType: Constants_1.C.dtmfType.INFO, + // Replaces header (RFC 3891) + // http://tools.ietf.org/html/rfc3891 + replaces: Constants_1.C.supported.UNSUPPORTED, + sessionDescriptionHandlerFactory: SessionDescriptionHandler_1.SessionDescriptionHandler.defaultFactory, + authenticationFactory: this.checkAuthenticationFactory(function (ua) { + return new DigestAuthentication_1.DigestAuthentication(ua); + }), + allowLegacyNotifications: false, + allowOutOfDialogRefers: false, + experimentalFeatures: false + }; + var configCheck = this.getConfigurationCheck(); + // Check Mandatory parameters + for (var parameter in configCheck.mandatory) { + if (!configuration.hasOwnProperty(parameter)) { + throw new Exceptions_1.Exceptions.ConfigurationError(parameter); + } + else { + var value = configuration[parameter]; + var checkedValue = configCheck.mandatory[parameter](value); + if (checkedValue !== undefined) { + settings[parameter] = checkedValue; + } + else { + throw new Exceptions_1.Exceptions.ConfigurationError(parameter, value); + } + } + } + // Check Optional parameters + for (var parameter in configCheck.optional) { + if (configuration.hasOwnProperty(parameter)) { + var value = configuration[parameter]; + // If the parameter value is an empty array, but shouldn't be, apply its default value. + // If the parameter value is null, empty string, or undefined then apply its default value. + // If it's a number with NaN value then also apply its default value. + // NOTE: JS does not allow "value === NaN", the following does the work: + if ((value instanceof Array && value.length === 0) || + (value === null || value === "" || value === undefined) || + (typeof (value) === "number" && isNaN(value))) { + continue; + } + var checkedValue = configCheck.optional[parameter](value); + if (checkedValue !== undefined) { + settings[parameter] = checkedValue; + } + else { + throw new Exceptions_1.Exceptions.ConfigurationError(parameter, value); + } + } + } + // Post Configuration Process + // Allow passing 0 number as displayName. + if (settings.displayName === 0) { + settings.displayName = "0"; + } + // sipjsId instance parameter. Static random tag of length 5 + settings.sipjsId = Utils_1.Utils.createRandomToken(5); + // String containing settings.uri without scheme and user. + var hostportParams = settings.uri.clone(); + hostportParams.user = undefined; + settings.hostportParams = hostportParams.toRaw().replace(/^sip:/i, ""); + /* Check whether authorizationUser is explicitly defined. + * Take 'settings.uri.user' value if not. + */ + if (!settings.authorizationUser) { + settings.authorizationUser = settings.uri.user; + } + // User noAnswerTimeout + settings.noAnswerTimeout = settings.noAnswerTimeout * 1000; + // Via Host + if (settings.hackIpInContact) { + if (typeof settings.hackIpInContact === "boolean") { + var from = 1; + var to = 254; + var octet = Math.floor(Math.random() * (to - from + 1) + from); + // random Test-Net IP (http://tools.ietf.org/html/rfc5735) + settings.viaHost = "192.0.2." + octet; + } + else if (typeof settings.hackIpInContact === "string") { + settings.viaHost = settings.hackIpInContact; + } + } + // Contact transport parameter + if (settings.hackWssInTransport) { + settings.contactTransport = "wss"; + } + this.contact = { + pubGruu: undefined, + tempGruu: undefined, + uri: new URI_1.URI("sip", settings.contactName, settings.viaHost, undefined, { transport: settings.contactTransport }), + toString: function (options) { + if (options === void 0) { options = {}; } + var anonymous = options.anonymous || false; + var outbound = options.outbound || false; + var contact = "<"; + if (anonymous) { + contact += (_this.contact.tempGruu || + ("sip:anonymous@anonymous.invalid;transport=" + settings.contactTransport)).toString(); + } + else { + contact += (_this.contact.pubGruu || _this.contact.uri).toString(); + } + if (outbound) { + contact += ";ob"; + } + contact += ">"; + return contact; + } + }; + var skeleton = {}; + // Fill the value of the configuration_skeleton + for (var parameter in settings) { + if (settings.hasOwnProperty(parameter)) { + skeleton[parameter] = settings[parameter]; + } + } + Object.assign(this.configuration, skeleton); + this.logger.log("configuration parameters after validation:"); + for (var parameter in settings) { + if (settings.hasOwnProperty(parameter)) { + switch (parameter) { + case "uri": + case "sessionDescriptionHandlerFactory": + this.logger.log("· " + parameter + ": " + settings[parameter]); + break; + case "password": + this.logger.log("· " + parameter + ": " + "NOT SHOWN"); + break; + case "transportConstructor": + this.logger.log("· " + parameter + ": " + settings[parameter].name); + break; + default: + this.logger.log("· " + parameter + ": " + JSON.stringify(settings[parameter])); + } + } + } + return; + }; + /** + * Configuration checker. + * @return {Boolean} + */ + UA.prototype.getConfigurationCheck = function () { + return { + mandatory: {}, + optional: { + uri: function (uri) { + if (!(/^sip:/i).test(uri)) { + uri = Constants_1.C.SIP + ":" + uri; + } + var parsed = Grammar_1.Grammar.URIParse(uri); + if (!parsed || !parsed.user) { + return; + } + else { + return parsed; + } + }, + transportConstructor: function (transportConstructor) { + if (transportConstructor instanceof Function) { + return transportConstructor; + } + }, + transportOptions: function (transportOptions) { + if (typeof transportOptions === "object") { + return transportOptions; + } + }, + authorizationUser: function (authorizationUser) { + if (Grammar_1.Grammar.parse('"' + authorizationUser + '"', "quoted_string") === -1) { + return; + } + else { + return authorizationUser; + } + }, + displayName: function (displayName) { + if (Grammar_1.Grammar.parse('"' + displayName + '"', "displayName") === -1) { + return; + } + else { + return displayName; + } + }, + dtmfType: function (dtmfType) { + switch (dtmfType) { + case Constants_1.C.dtmfType.RTP: + return Constants_1.C.dtmfType.RTP; + case Constants_1.C.dtmfType.INFO: + // Fall through + default: + return Constants_1.C.dtmfType.INFO; + } + }, + hackViaTcp: function (hackViaTcp) { + if (typeof hackViaTcp === "boolean") { + return hackViaTcp; + } + }, + hackIpInContact: function (hackIpInContact) { + if (typeof hackIpInContact === "boolean") { + return hackIpInContact; + } + else if (typeof hackIpInContact === "string" && Grammar_1.Grammar.parse(hackIpInContact, "host") !== -1) { + return hackIpInContact; + } + }, + hackWssInTransport: function (hackWssInTransport) { + if (typeof hackWssInTransport === "boolean") { + return hackWssInTransport; + } + }, + hackAllowUnregisteredOptionTags: function (hackAllowUnregisteredOptionTags) { + if (typeof hackAllowUnregisteredOptionTags === "boolean") { + return hackAllowUnregisteredOptionTags; + } + }, + contactTransport: function (contactTransport) { + if (typeof contactTransport === "string") { + return contactTransport; + } + }, + extraSupported: function (optionTags) { + if (!(optionTags instanceof Array)) { + return; + } + for (var _i = 0, optionTags_1 = optionTags; _i < optionTags_1.length; _i++) { + var tag = optionTags_1[_i]; + if (typeof tag !== "string") { + return; + } + } + return optionTags; + }, + forceRport: function (forceRport) { + if (typeof forceRport === "boolean") { + return forceRport; + } + }, + noAnswerTimeout: function (noAnswerTimeout) { + if (Utils_1.Utils.isDecimal(noAnswerTimeout)) { + var value = Number(noAnswerTimeout); + if (value > 0) { + return value; + } + } + }, + password: function (password) { + return String(password); + }, + rel100: function (rel100) { + if (rel100 === Constants_1.C.supported.REQUIRED) { + return Constants_1.C.supported.REQUIRED; + } + else if (rel100 === Constants_1.C.supported.SUPPORTED) { + return Constants_1.C.supported.SUPPORTED; + } + else { + return Constants_1.C.supported.UNSUPPORTED; + } + }, + replaces: function (replaces) { + if (replaces === Constants_1.C.supported.REQUIRED) { + return Constants_1.C.supported.REQUIRED; + } + else if (replaces === Constants_1.C.supported.SUPPORTED) { + return Constants_1.C.supported.SUPPORTED; + } + else { + return Constants_1.C.supported.UNSUPPORTED; + } + }, + register: function (register) { + if (typeof register === "boolean") { + return register; + } + }, + registerOptions: function (registerOptions) { + if (typeof registerOptions === "object") { + return registerOptions; + } + }, + userAgentString: function (userAgentString) { + if (typeof userAgentString === "string") { + return userAgentString; + } + }, + autostart: function (autostart) { + if (typeof autostart === "boolean") { + return autostart; + } + }, + autostop: function (autostop) { + if (typeof autostop === "boolean") { + return autostop; + } + }, + sessionDescriptionHandlerFactory: function (sessionDescriptionHandlerFactory) { + if (sessionDescriptionHandlerFactory instanceof Function) { + return sessionDescriptionHandlerFactory; + } + }, + sessionDescriptionHandlerFactoryOptions: function (options) { + if (typeof options === "object") { + return options; + } + }, + authenticationFactory: this.checkAuthenticationFactory, + allowLegacyNotifications: function (allowLegacyNotifications) { + if (typeof allowLegacyNotifications === "boolean") { + return allowLegacyNotifications; + } + }, + custom: function (custom) { + if (typeof custom === "object") { + return custom; + } + }, + contactName: function (contactName) { + if (typeof contactName === "string") { + return contactName; + } + }, + experimentalFeatures: function (experimentalFeatures) { + if (typeof experimentalFeatures === "boolean") { + return experimentalFeatures; + } + }, + } + }; + }; + UA.C = { + // UA status codes + STATUS_INIT: 0, + STATUS_STARTING: 1, + STATUS_READY: 2, + STATUS_USER_CLOSED: 3, + STATUS_NOT_READY: 4, + // UA error codes + CONFIGURATION_ERROR: 1, + NETWORK_ERROR: 2, + ALLOWED_METHODS: [ + "ACK", + "CANCEL", + "INVITE", + "MESSAGE", + "BYE", + "OPTIONS", + "INFO", + "NOTIFY", + "REFER" + ], + ACCEPTED_BODY_TYPES: [ + "application/sdp", + "application/dtmf-relay" + ], + MAX_FORWARDS: 70, + TAG_LENGTH: 10 + }; + return UA; +}(events_1.EventEmitter)); +exports.UA = UA; +(function (UA) { + var DtmfType; + (function (DtmfType) { + DtmfType["RTP"] = "rtp"; + DtmfType["INFO"] = "info"; + })(DtmfType = UA.DtmfType || (UA.DtmfType = {})); +})(UA = exports.UA || (exports.UA = {})); +exports.UA = UA; diff --git a/lib/URI.d.ts b/lib/URI.d.ts new file mode 100644 index 000000000..1075bbf84 --- /dev/null +++ b/lib/URI.d.ts @@ -0,0 +1,57 @@ +import { TypeStrings } from "./Enums"; +export interface URIObject { + scheme: string; + user: string | undefined; + host: string; + port: number | undefined; +} +export declare class Parameters { + type: TypeStrings; + parameters: { + [name: string]: any; + }; + constructor(parameters: { + [name: string]: any; + }); + setParam(key: string, value: any): void; + getParam(key: string): any; + hasParam(key: string): boolean; + deleteParam(parameter: string): any; + clearParams(): void; +} +/** + * @class Class creating a SIP URI. + * + * @param {String} [scheme] + * @param {String} [user] + * @param {String} host + * @param {String} [port] + * @param {Object} [parameters] + * @param {Object} [headers] + * + */ +export declare class URI extends Parameters { + type: TypeStrings; + private headers; + private normal; + private raw; + constructor(scheme: string, user: string, host: string, port?: number, parameters?: any, headers?: any); + readonly _normal: URIObject; + readonly _raw: URIObject; + scheme: string; + user: string | undefined; + host: string; + readonly aor: string; + port: number | undefined; + setHeader(name: string, value: any): void; + getHeader(name: string): string | undefined; + hasHeader(name: string): boolean; + deleteHeader(header: string): any; + clearHeaders(): void; + clone(): URI; + toRaw(): string; + toString(): string; + private _toString; + private escapeUser; + private headerize; +} diff --git a/lib/URI.js b/lib/URI.js new file mode 100644 index 000000000..2d6b2b1d4 --- /dev/null +++ b/lib/URI.js @@ -0,0 +1,258 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Constants_1 = require("./Constants"); +var Enums_1 = require("./Enums"); +var Parameters = /** @class */ (function () { + function Parameters(parameters) { + this.parameters = {}; + this.type = Enums_1.TypeStrings.Parameters; + for (var param in parameters) { + if (parameters.hasOwnProperty(param)) { + this.setParam(param, parameters[param]); + } + } + } + Parameters.prototype.setParam = function (key, value) { + if (key) { + this.parameters[key.toLowerCase()] = (typeof value === "undefined" || value === null) ? null : value.toString(); + } + }; + Parameters.prototype.getParam = function (key) { + if (key) { + return this.parameters[key.toLowerCase()]; + } + }; + Parameters.prototype.hasParam = function (key) { + if (key) { + return !!this.parameters.hasOwnProperty(key.toLowerCase()); + } + return false; + }; + Parameters.prototype.deleteParam = function (parameter) { + parameter = parameter.toLowerCase(); + if (this.parameters.hasOwnProperty(parameter)) { + var value = this.parameters[parameter]; + delete this.parameters[parameter]; + return value; + } + }; + Parameters.prototype.clearParams = function () { + this.parameters = {}; + }; + return Parameters; +}()); +exports.Parameters = Parameters; +/** + * @class Class creating a SIP URI. + * + * @param {String} [scheme] + * @param {String} [user] + * @param {String} host + * @param {String} [port] + * @param {Object} [parameters] + * @param {Object} [headers] + * + */ +// tslint:disable-next-line:max-classes-per-file +var URI = /** @class */ (function (_super) { + __extends(URI, _super); + function URI(scheme, user, host, port, parameters, headers) { + var _this = _super.call(this, parameters) || this; + _this.headers = {}; + _this.type = Enums_1.TypeStrings.URI; + // Checks + if (!host) { + throw new TypeError('missing or invalid "host" parameter'); + } + // Initialize parameters + scheme = scheme || Constants_1.C.SIP; + for (var header in headers) { + if (headers.hasOwnProperty(header)) { + _this.setHeader(header, headers[header]); + } + } + // Raw URI + _this.raw = { + scheme: scheme, + user: user, + host: host, + port: port + }; + // Normalized URI + _this.normal = { + scheme: scheme.toLowerCase(), + user: user, + host: host.toLowerCase(), + port: port + }; + return _this; + } + Object.defineProperty(URI.prototype, "_normal", { + get: function () { return this.normal; }, + enumerable: true, + configurable: true + }); + Object.defineProperty(URI.prototype, "_raw", { + get: function () { return this.raw; }, + enumerable: true, + configurable: true + }); + Object.defineProperty(URI.prototype, "scheme", { + get: function () { return this.normal.scheme; }, + set: function (value) { + this.raw.scheme = value; + this.normal.scheme = value.toLowerCase(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(URI.prototype, "user", { + get: function () { return this.normal.user; }, + set: function (value) { + this.normal.user = this.raw.user = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(URI.prototype, "host", { + get: function () { return this.normal.host; }, + set: function (value) { + this.raw.host = value; + this.normal.host = value.toLowerCase(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(URI.prototype, "aor", { + get: function () { return this.normal.user + "@" + this.normal.host; }, + enumerable: true, + configurable: true + }); + Object.defineProperty(URI.prototype, "port", { + get: function () { return this.normal.port; }, + set: function (value) { + this.normal.port = this.raw.port = value === 0 ? value : value; + }, + enumerable: true, + configurable: true + }); + URI.prototype.setHeader = function (name, value) { + this.headers[this.headerize(name)] = (value instanceof Array) ? value : [value]; + }; + URI.prototype.getHeader = function (name) { + if (name) { + return this.headers[this.headerize(name)]; + } + }; + URI.prototype.hasHeader = function (name) { + return !!name && !!this.headers.hasOwnProperty(this.headerize(name)); + }; + URI.prototype.deleteHeader = function (header) { + header = this.headerize(header); + if (this.headers.hasOwnProperty(header)) { + var value = this.headers[header]; + delete this.headers[header]; + return value; + } + }; + URI.prototype.clearHeaders = function () { + this.headers = {}; + }; + URI.prototype.clone = function () { + return new URI(this._raw.scheme, this._raw.user || "", this._raw.host, this._raw.port, JSON.parse(JSON.stringify(this.parameters)), JSON.parse(JSON.stringify(this.headers))); + }; + URI.prototype.toRaw = function () { + return this._toString(this._raw); + }; + URI.prototype.toString = function () { + return this._toString(this._normal); + }; + URI.prototype._toString = function (uri) { + var uriString = uri.scheme + ":"; + // add slashes if it's not a sip(s) URI + if (!uri.scheme.toLowerCase().match("^sips?$")) { + uriString += "//"; + } + if (uri.user) { + uriString += this.escapeUser(uri.user) + "@"; + } + uriString += uri.host; + if (uri.port || uri.port === 0) { + uriString += ":" + uri.port; + } + for (var parameter in this.parameters) { + if (this.parameters.hasOwnProperty(parameter)) { + uriString += ";" + parameter; + if (this.parameters[parameter] !== null) { + uriString += "=" + this.parameters[parameter]; + } + } + } + var headers = []; + for (var header in this.headers) { + if (this.headers.hasOwnProperty(header)) { + for (var idx in this.headers[header]) { + if (this.headers[header].hasOwnProperty(idx)) { + headers.push(header + "=" + this.headers[header][idx]); + } + } + } + } + if (headers.length > 0) { + uriString += "?" + headers.join("&"); + } + return uriString; + }; + // The following two functions were copied from Utils to break a circular dependency + /* + * Hex-escape a SIP URI user. + * @private + * @param {String} user + */ + URI.prototype.escapeUser = function (user) { + // Don't hex-escape ':' (%3A), '+' (%2B), '?' (%3F"), '/' (%2F). + return encodeURIComponent(decodeURIComponent(user)) + .replace(/%3A/ig, ":") + .replace(/%2B/ig, "+") + .replace(/%3F/ig, "?") + .replace(/%2F/ig, "/"); + }; + URI.prototype.headerize = function (str) { + var exceptions = { + "Call-Id": "Call-ID", + "Cseq": "CSeq", + "Min-Se": "Min-SE", + "Rack": "RAck", + "Rseq": "RSeq", + "Www-Authenticate": "WWW-Authenticate", + }; + var name = str.toLowerCase().replace(/_/g, "-").split("-"); + var parts = name.length; + var hname = ""; + for (var part = 0; part < parts; part++) { + if (part !== 0) { + hname += "-"; + } + hname += name[part].charAt(0).toUpperCase() + name[part].substring(1); + } + if (exceptions[hname]) { + hname = exceptions[hname]; + } + return hname; + }; + return URI; +}(Parameters)); +exports.URI = URI; diff --git a/lib/Utils.d.ts b/lib/Utils.d.ts new file mode 100644 index 000000000..537858925 --- /dev/null +++ b/lib/Utils.d.ts @@ -0,0 +1,25 @@ +import { SessionDescriptionHandlerModifier } from "./session-description-handler"; +import { URI } from "./URI"; +export declare namespace Utils { + interface Deferred { + promise: Promise; + resolve: () => T; + reject: () => T; + } + function defer(): Deferred; + function reducePromises(arr: Array, val: any): Promise; + function str_utf8_length(str: string): number; + function generateFakeSDP(body: string): string | undefined; + function isDecimal(num: string): boolean; + function createRandomToken(size: number, base?: number): string; + function newTag(): string; + function newUUID(): string; + function normalizeTarget(target: string | URI, domain?: string): URI | undefined; + function escapeUser(user: string): string; + function headerize(str: string): string; + function sipErrorCause(statusCode: number): string; + function getReasonPhrase(code: number, specific?: string): string; + function getReasonHeaderValue(code: number, reason?: string): string; + function getCancelReason(code: number, reason: string): string | undefined; + function buildStatusLine(code: number, reason?: string): string; +} diff --git a/lib/Utils.js b/lib/Utils.js new file mode 100644 index 000000000..d5f3ad3c7 --- /dev/null +++ b/lib/Utils.js @@ -0,0 +1,202 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var Constants_1 = require("./Constants"); +var Enums_1 = require("./Enums"); +var Grammar_1 = require("./Grammar"); +var Utils; +(function (Utils) { + function defer() { + var deferred = {}; + deferred.promise = new Promise(function (resolve, reject) { + deferred.resolve = resolve; + deferred.reject = reject; + }); + return deferred; + } + Utils.defer = defer; + function reducePromises(arr, val) { + return arr.reduce(function (acc, fn) { + acc = acc.then(fn); + return acc; + }, Promise.resolve(val)); + } + Utils.reducePromises = reducePromises; + function str_utf8_length(str) { + return encodeURIComponent(str).replace(/%[A-F\d]{2}/g, "U").length; + } + Utils.str_utf8_length = str_utf8_length; + function generateFakeSDP(body) { + if (!body) { + return; + } + var start = body.indexOf("o="); + var end = body.indexOf("\r\n", start); + return "v=0\r\n" + body.slice(start, end) + "\r\ns=-\r\nt=0 0\r\nc=IN IP4 0.0.0.0"; + } + Utils.generateFakeSDP = generateFakeSDP; + function isDecimal(num) { + var numAsNum = parseInt(num, 10); + return !isNaN(numAsNum) && (parseFloat(num) === numAsNum); + } + Utils.isDecimal = isDecimal; + function createRandomToken(size, base) { + if (base === void 0) { base = 32; } + var token = ""; + for (var i = 0; i < size; i++) { + var r = Math.floor(Math.random() * base); + token += r.toString(base); + } + return token; + } + Utils.createRandomToken = createRandomToken; + function newTag() { + // used to use the constant in UA + return Utils.createRandomToken(10); + } + Utils.newTag = newTag; + // http://stackoverflow.com/users/109538/broofa + function newUUID() { + var UUID = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) { + var r = Math.floor(Math.random() * 16); + var v = c === "x" ? r : (r % 4 + 8); + return v.toString(16); + }); + return UUID; + } + Utils.newUUID = newUUID; + /* + * Normalize SIP URI. + * NOTE: It does not allow a SIP URI without username. + * Accepts 'sip', 'sips' and 'tel' URIs and convert them into 'sip'. + * Detects the domain part (if given) and properly hex-escapes the user portion. + * If the user portion has only 'tel' number symbols the user portion is clean of 'tel' visual separators. + * @private + * @param {String} target + * @param {String} [domain] + */ + function normalizeTarget(target, domain) { + // If no target is given then raise an error. + if (!target) { + return; + // If a SIP.URI instance is given then return it. + } + else if (target.type === Enums_1.TypeStrings.URI) { + return target; + // If a string is given split it by '@': + // - Last fragment is the desired domain. + // - Otherwise append the given domain argument. + } + else if (typeof target === "string") { + var targetArray = target.split("@"); + var targetUser = void 0; + var targetDomain = void 0; + switch (targetArray.length) { + case 1: + if (!domain) { + return; + } + targetUser = target; + targetDomain = domain; + break; + case 2: + targetUser = targetArray[0]; + targetDomain = targetArray[1]; + break; + default: + targetUser = targetArray.slice(0, targetArray.length - 1).join("@"); + targetDomain = targetArray[targetArray.length - 1]; + } + // Remove the URI scheme (if present). + targetUser = targetUser.replace(/^(sips?|tel):/i, ""); + // Remove 'tel' visual separators if the user portion just contains 'tel' number symbols. + if (/^[\-\.\(\)]*\+?[0-9\-\.\(\)]+$/.test(targetUser)) { + targetUser = targetUser.replace(/[\-\.\(\)]/g, ""); + } + // Build the complete SIP URI. + target = Constants_1.C.SIP + ":" + Utils.escapeUser(targetUser) + "@" + targetDomain; + // Finally parse the resulting URI. + return Grammar_1.Grammar.URIParse(target); + } + else { + return; + } + } + Utils.normalizeTarget = normalizeTarget; + /* + * Hex-escape a SIP URI user. + * @private + * @param {String} user + */ + function escapeUser(user) { + // Don't hex-escape ':' (%3A), '+' (%2B), '?' (%3F"), '/' (%2F). + return encodeURIComponent(decodeURIComponent(user)) + .replace(/%3A/ig, ":") + .replace(/%2B/ig, "+") + .replace(/%3F/ig, "?") + .replace(/%2F/ig, "/"); + } + Utils.escapeUser = escapeUser; + function headerize(str) { + var exceptions = { + "Call-Id": "Call-ID", + "Cseq": "CSeq", + "Min-Se": "Min-SE", + "Rack": "RAck", + "Rseq": "RSeq", + "Www-Authenticate": "WWW-Authenticate", + }; + var name = str.toLowerCase().replace(/_/g, "-").split("-"); + var parts = name.length; + var hname = ""; + for (var part = 0; part < parts; part++) { + if (part !== 0) { + hname += "-"; + } + hname += name[part].charAt(0).toUpperCase() + name[part].substring(1); + } + if (exceptions[hname]) { + hname = exceptions[hname]; + } + return hname; + } + Utils.headerize = headerize; + function sipErrorCause(statusCode) { + for (var cause in Constants_1.C.SIP_ERROR_CAUSES) { + if (Constants_1.C.SIP_ERROR_CAUSES[cause].indexOf(statusCode) !== -1) { + return Constants_1.C.causes[cause]; + } + } + return Constants_1.C.causes.SIP_FAILURE_CODE; + } + Utils.sipErrorCause = sipErrorCause; + function getReasonPhrase(code, specific) { + return specific || Constants_1.C.REASON_PHRASE[code] || ""; + } + Utils.getReasonPhrase = getReasonPhrase; + function getReasonHeaderValue(code, reason) { + reason = Utils.getReasonPhrase(code, reason); + return "SIP;cause=" + code + ';text="' + reason + '"'; + } + Utils.getReasonHeaderValue = getReasonHeaderValue; + function getCancelReason(code, reason) { + if (code && code < 200 || code > 699) { + throw new TypeError("Invalid statusCode: " + code); + } + else if (code) { + return Utils.getReasonHeaderValue(code, reason); + } + } + Utils.getCancelReason = getCancelReason; + function buildStatusLine(code, reason) { + // Validate code and reason values + if (!code || (code < 100 || code > 699)) { + throw new TypeError("Invalid statusCode: " + code); + } + else if (reason && typeof reason !== "string" && !(reason instanceof String)) { + throw new TypeError("Invalid reason: " + reason); + } + reason = Utils.getReasonPhrase(code, reason); + return "SIP/2.0 " + code + " " + reason + "\r\n"; + } + Utils.buildStatusLine = buildStatusLine; +})(Utils = exports.Utils || (exports.Utils = {})); diff --git a/lib/Web/Modifiers.d.ts b/lib/Web/Modifiers.d.ts new file mode 100644 index 000000000..124b2795a --- /dev/null +++ b/lib/Web/Modifiers.d.ts @@ -0,0 +1,8 @@ +import { SessionDescriptionHandlerModifier } from "../session-description-handler"; +export declare function stripTcpCandidates(description: RTCSessionDescriptionInit): Promise; +export declare function stripTelephoneEvent(description: RTCSessionDescriptionInit): Promise; +export declare function cleanJitsiSdpImageattr(description: RTCSessionDescriptionInit): Promise; +export declare function stripG722(description: RTCSessionDescriptionInit): Promise; +export declare function stripRtpPayload(payload: string): SessionDescriptionHandlerModifier; +export declare function stripVideo(description: RTCSessionDescriptionInit): Promise; +export declare function addMidLines(description: RTCSessionDescriptionInit): Promise; diff --git a/lib/Web/Modifiers.js b/lib/Web/Modifiers.js new file mode 100644 index 000000000..97d2ec179 --- /dev/null +++ b/lib/Web/Modifiers.js @@ -0,0 +1,121 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var stripPayload = function (sdp, payload) { + var mediaDescs = []; + var lines = sdp.split(/\r\n/); + var currentMediaDesc; + for (var i = 0; i < lines.length;) { + var line = lines[i]; + if (/^m=(?:audio|video)/.test(line)) { + currentMediaDesc = { + index: i, + stripped: [] + }; + mediaDescs.push(currentMediaDesc); + } + else if (currentMediaDesc) { + var rtpmap = /^a=rtpmap:(\d+) ([^/]+)\//.exec(line); + if (rtpmap && payload === rtpmap[2]) { + lines.splice(i, 1); + currentMediaDesc.stripped.push(rtpmap[1]); + continue; // Don't increment 'i' + } + } + i++; + } + for (var _i = 0, mediaDescs_1 = mediaDescs; _i < mediaDescs_1.length; _i++) { + var mediaDesc = mediaDescs_1[_i]; + var mline = lines[mediaDesc.index].split(" "); + // Ignore the first 3 parameters of the mline. The codec information is after that + for (var j = 3; j < mline.length;) { + if (mediaDesc.stripped.indexOf(mline[j]) !== -1) { + mline.splice(j, 1); + continue; + } + j++; + } + lines[mediaDesc.index] = mline.join(" "); + } + return lines.join("\r\n"); +}; +var stripMediaDescription = function (sdp, description) { + var descriptionRegExp = new RegExp("m=" + description + ".*$", "gm"); + var groupRegExp = new RegExp("^a=group:.*$", "gm"); + if (descriptionRegExp.test(sdp)) { + var midLineToRemove_1; + sdp = sdp.split(/^m=/gm).filter(function (section) { + if (section.substr(0, description.length) === description) { + midLineToRemove_1 = section.match(/^a=mid:.*$/gm); + if (midLineToRemove_1) { + var step = midLineToRemove_1[0].match(/:.+$/g); + if (step) { + midLineToRemove_1 = step[0].substr(1); + } + } + return false; + } + return true; + }).join("m="); + var groupLine = sdp.match(groupRegExp); + if (groupLine && groupLine.length === 1) { + var groupLinePortion = groupLine[0]; + var groupRegExpReplace = new RegExp("\ *" + midLineToRemove_1 + "[^\ ]*", "g"); + groupLinePortion = groupLinePortion.replace(groupRegExpReplace, ""); + sdp = sdp.split(groupRegExp).join(groupLinePortion); + } + } + return sdp; +}; +function stripTcpCandidates(description) { + description.sdp = (description.sdp || "").replace(/^a=candidate:\d+ \d+ tcp .*?\r\n/img, ""); + return Promise.resolve(description); +} +exports.stripTcpCandidates = stripTcpCandidates; +function stripTelephoneEvent(description) { + description.sdp = stripPayload(description.sdp || "", "telephone-event"); + return Promise.resolve(description); +} +exports.stripTelephoneEvent = stripTelephoneEvent; +function cleanJitsiSdpImageattr(description) { + description.sdp = (description.sdp || "").replace(/^(a=imageattr:.*?)(x|y)=\[0-/gm, "$1$2=[1:"); + return Promise.resolve(description); +} +exports.cleanJitsiSdpImageattr = cleanJitsiSdpImageattr; +function stripG722(description) { + description.sdp = stripPayload(description.sdp || "", "G722"); + return Promise.resolve(description); +} +exports.stripG722 = stripG722; +function stripRtpPayload(payload) { + return function (description) { + description.sdp = stripPayload(description.sdp || "", payload); + return Promise.resolve(description); + }; +} +exports.stripRtpPayload = stripRtpPayload; +function stripVideo(description) { + description.sdp = stripMediaDescription(description.sdp || "", "video"); + return Promise.resolve(description); +} +exports.stripVideo = stripVideo; +function addMidLines(description) { + var sdp = description.sdp || ""; + if (sdp.search(/^a=mid.*$/gm) === -1) { + var mlines_1 = sdp.match(/^m=.*$/gm); + var sdpArray_1 = sdp.split(/^m=.*$/gm); + if (mlines_1) { + mlines_1.forEach(function (elem, idx) { + mlines_1[idx] = elem + "\na=mid:" + idx; + }); + } + sdpArray_1.forEach(function (elem, idx) { + if (mlines_1 && mlines_1[idx]) { + sdpArray_1[idx] = elem + mlines_1[idx]; + } + }); + sdp = sdpArray_1.join(""); + description.sdp = sdp; + } + return Promise.resolve(description); +} +exports.addMidLines = addMidLines; diff --git a/lib/Web/SessionDescriptionHandler.d.ts b/lib/Web/SessionDescriptionHandler.d.ts new file mode 100644 index 000000000..5673ad5be --- /dev/null +++ b/lib/Web/SessionDescriptionHandler.d.ts @@ -0,0 +1,122 @@ +/// +import { EventEmitter } from "events"; +import { TypeStrings } from "../Enums"; +import { Logger } from "../LoggerFactory"; +import { InviteClientContext, InviteServerContext } from "../Session"; +import { BodyObj, SessionDescriptionHandler as SessionDescriptionHandlerDefinition, SessionDescriptionHandlerModifiers, SessionDescriptionHandlerOptions } from "../session-description-handler"; +import { SessionDescriptionHandlerObserver } from "./SessionDescriptionHandlerObserver"; +export interface WebSessionDescriptionHandlerOptions extends SessionDescriptionHandlerOptions { + peerConnectionOptions?: PeerConnectionOptions; + alwaysAcquireMediaFirst?: boolean; + disableAudioFallback?: boolean; + RTCOfferOptions?: any; + constraints?: any; +} +export interface PeerConnectionOptions { + iceCheckingTimeout?: number; + rtcConfiguration?: any; +} +export declare class SessionDescriptionHandler extends EventEmitter implements SessionDescriptionHandlerDefinition { + /** + * @param {SIP.Session} session + * @param {Object} [options] + */ + static defaultFactory(session: InviteClientContext | InviteServerContext, options: any): SessionDescriptionHandler; + type: TypeStrings; + peerConnection: RTCPeerConnection; + private options; + private logger; + private observer; + private dtmfSender; + private shouldAcquireMedia; + private CONTENT_TYPE; + private direction; + private C; + private modifiers; + private WebRTC; + private iceGatheringDeferred; + private iceGatheringTimeout; + private iceGatheringTimer; + private constraints; + constructor(logger: Logger, observer: SessionDescriptionHandlerObserver, options: any); + /** + * Destructor + */ + close(): void; + /** + * Gets the local description from the underlying media implementation + * @param {Object} [options] Options object to be used by getDescription + * @param {MediaStreamConstraints} [options.constraints] MediaStreamConstraints + * https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamConstraints + * @param {Object} [options.peerConnectionOptions] If this is set it will recreate the peer + * connection with the new options + * @param {Array} [modifiers] Array with one time use description modifiers + * @returns {Promise} Promise that resolves with the local description to be used for the session + */ + getDescription(options?: WebSessionDescriptionHandlerOptions, modifiers?: SessionDescriptionHandlerModifiers): Promise; + /** + * Check if the Session Description Handler can handle the Content-Type described by a SIP Message + * @param {String} contentType The content type that is in the SIP Message + * @returns {boolean} + */ + hasDescription(contentType: string): boolean; + /** + * The modifier that should be used when the session would like to place the call on hold + * @param {String} [sdp] The description that will be modified + * @returns {Promise} Promise that resolves with modified SDP + */ + holdModifier(description: RTCSessionDescriptionInit): Promise; + /** + * Set the remote description to the underlying media implementation + * @param {String} sessionDescription The description provided by a SIP message to be set on the media implementation + * @param {Object} [options] Options object to be used by getDescription + * @param {MediaStreamConstraints} [options.constraints] MediaStreamConstraints + * https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamConstraints + * @param {Object} [options.peerConnectionOptions] If this is set it will recreate the peer + * connection with the new options + * @param {Array} [modifiers] Array with one time use description modifiers + * @returns {Promise} Promise that resolves once the description is set + */ + setDescription(sessionDescription: string, options?: WebSessionDescriptionHandlerOptions, modifiers?: SessionDescriptionHandlerModifiers): Promise; + /** + * Send DTMF via RTP (RFC 4733) + * @param {String} tones A string containing DTMF digits + * @param {Object} [options] Options object to be used by sendDtmf + * @returns {boolean} true if DTMF send is successful, false otherwise + */ + sendDtmf(tones: string, options?: any): boolean; + /** + * Get the direction of the session description + * @returns {String} direction of the description + */ + getDirection(): string; + on(event: "getDescription" | "setDescription", listener: (description: RTCSessionDescriptionInit) => void): this; + on(event: "peerConnection-setRemoteDescriptionFailed", listener: (error: any) => void): this; + on(event: "setRemoteDescription", listener: (receivers: Array) => void): this; + on(event: "confirmed", listener: (sessionDescriptionHandler: SessionDescriptionHandler) => void): this; + on(event: "peerConnection-createAnswerFailed" | "peerConnection-createOfferFailed", listener: (error: any) => void): this; + on(event: "peerConnection-SetLocalDescriptionFailed", listener: (error: any) => void): this; + on(event: "addTrack", listener: (track: MediaStreamTrack) => void): this; + on(event: "addStream", listener: (track: MediaStream) => void): this; + on(event: "iceCandidate", listener: (candidate: RTCIceCandidate) => void): this; + on(event: "iceConnection" | "iceConnectionChecking" | "iceConnectionConnected" | "iceConnectionCompleted" | "iceConnectionFailed" | "iceConnectionDisconnected" | "iceConectionClosed", listener: (sessionDescriptionHandler: SessionDescriptionHandler) => void): this; + on(event: "iceGathering" | "iceGatheringComplete", listener: (sessionDescriptionHandler: SessionDescriptionHandler) => void): this; + on(event: "userMediaRequest", listener: (constraints: MediaStreamConstraints) => void): this; + on(event: "userMedia", listener: (streams: MediaStream) => void): this; + on(event: "userMediaFailed", listener: (error: any) => void): this; + private createOfferOrAnswer; + private createRTCSessionDescriptionInit; + private addDefaultIceCheckingTimeout; + private addDefaultIceServers; + private checkAndDefaultConstraints; + private hasBrowserTrackSupport; + private hasBrowserGetSenderSupport; + private initPeerConnection; + private acquire; + private hasOffer; + private isIceGatheringComplete; + private resetIceGatheringComplete; + private setDirection; + private triggerIceGatheringComplete; + private waitForIceGatheringComplete; +} diff --git a/lib/Web/SessionDescriptionHandler.js b/lib/Web/SessionDescriptionHandler.js new file mode 100644 index 000000000..9b15270ad --- /dev/null +++ b/lib/Web/SessionDescriptionHandler.js @@ -0,0 +1,638 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var events_1 = require("events"); +var Enums_1 = require("../Enums"); +var Exceptions_1 = require("../Exceptions"); +var Utils_1 = require("../Utils"); +var Modifiers = require("./Modifiers"); +var SessionDescriptionHandlerObserver_1 = require("./SessionDescriptionHandlerObserver"); +/* SessionDescriptionHandler + * @class PeerConnection helper Class. + * @param {SIP.Session} session + * @param {Object} [options] + */ +var SessionDescriptionHandler = /** @class */ (function (_super) { + __extends(SessionDescriptionHandler, _super); + function SessionDescriptionHandler(logger, observer, options) { + var _this = _super.call(this) || this; + _this.type = Enums_1.TypeStrings.SessionDescriptionHandler; + // TODO: Validate the options + _this.options = options || {}; + _this.logger = logger; + _this.observer = observer; + _this.dtmfSender = undefined; + _this.shouldAcquireMedia = true; + _this.CONTENT_TYPE = "application/sdp"; + _this.C = { + DIRECTION: { + NULL: null, + SENDRECV: "sendrecv", + SENDONLY: "sendonly", + RECVONLY: "recvonly", + INACTIVE: "inactive" + } + }; + _this.logger.log("SessionDescriptionHandlerOptions: " + JSON.stringify(_this.options)); + _this.direction = _this.C.DIRECTION.NULL; + _this.modifiers = _this.options.modifiers || []; + if (!Array.isArray(_this.modifiers)) { + _this.modifiers = [_this.modifiers]; + } + var environment = global.window || global; + _this.WebRTC = { + MediaStream: environment.MediaStream, + getUserMedia: environment.navigator.mediaDevices.getUserMedia.bind(environment.navigator.mediaDevices), + RTCPeerConnection: environment.RTCPeerConnection + }; + _this.iceGatheringTimeout = false; + _this.initPeerConnection(_this.options.peerConnectionOptions); + _this.constraints = _this.checkAndDefaultConstraints(_this.options.constraints); + return _this; + } + /** + * @param {SIP.Session} session + * @param {Object} [options] + */ + SessionDescriptionHandler.defaultFactory = function (session, options) { + var logger = session.ua.getLogger("sip.invitecontext.sessionDescriptionHandler", session.id); + var observer = new SessionDescriptionHandlerObserver_1.SessionDescriptionHandlerObserver(session, options); + return new SessionDescriptionHandler(logger, observer, options); + }; + // Functions the sesssion can use + /** + * Destructor + */ + SessionDescriptionHandler.prototype.close = function () { + this.logger.log("closing PeerConnection"); + // have to check signalingState since this.close() gets called multiple times + if (this.peerConnection && this.peerConnection.signalingState !== "closed") { + if (this.peerConnection.getSenders) { + this.peerConnection.getSenders().forEach(function (sender) { + if (sender.track) { + sender.track.stop(); + } + }); + } + else { + this.logger.warn("Using getLocalStreams which is deprecated"); + this.peerConnection.getLocalStreams().forEach(function (stream) { + stream.getTracks().forEach(function (track) { + track.stop(); + }); + }); + } + if (this.peerConnection.getReceivers) { + this.peerConnection.getReceivers().forEach(function (receiver) { + if (receiver.track) { + receiver.track.stop(); + } + }); + } + else { + this.logger.warn("Using getRemoteStreams which is deprecated"); + this.peerConnection.getRemoteStreams().forEach(function (stream) { + stream.getTracks().forEach(function (track) { + track.stop(); + }); + }); + } + this.resetIceGatheringComplete(); + this.peerConnection.close(); + } + }; + /** + * Gets the local description from the underlying media implementation + * @param {Object} [options] Options object to be used by getDescription + * @param {MediaStreamConstraints} [options.constraints] MediaStreamConstraints + * https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamConstraints + * @param {Object} [options.peerConnectionOptions] If this is set it will recreate the peer + * connection with the new options + * @param {Array} [modifiers] Array with one time use description modifiers + * @returns {Promise} Promise that resolves with the local description to be used for the session + */ + SessionDescriptionHandler.prototype.getDescription = function (options, modifiers) { + var _this = this; + if (options === void 0) { options = {}; } + if (modifiers === void 0) { modifiers = []; } + if (options.peerConnectionOptions) { + this.initPeerConnection(options.peerConnectionOptions); + } + // Merge passed constraints with saved constraints and save + var newConstraints = Object.assign({}, this.constraints, options.constraints); + newConstraints = this.checkAndDefaultConstraints(newConstraints); + if (JSON.stringify(newConstraints) !== JSON.stringify(this.constraints)) { + this.constraints = newConstraints; + this.shouldAcquireMedia = true; + } + if (!Array.isArray(modifiers)) { + modifiers = [modifiers]; + } + modifiers = modifiers.concat(this.modifiers); + return Promise.resolve().then(function () { + if (_this.shouldAcquireMedia) { + return _this.acquire(_this.constraints).then(function () { + _this.shouldAcquireMedia = false; + }); + } + }).then(function () { return _this.createOfferOrAnswer(options.RTCOfferOptions, modifiers); }) + .then(function (description) { + if (description.sdp === undefined) { + throw new Exceptions_1.Exceptions.SessionDescriptionHandlerError("getDescription", undefined, "SDP undefined"); + } + _this.emit("getDescription", description); + return { + body: description.sdp, + contentType: _this.CONTENT_TYPE + }; + }); + }; + /** + * Check if the Session Description Handler can handle the Content-Type described by a SIP Message + * @param {String} contentType The content type that is in the SIP Message + * @returns {boolean} + */ + SessionDescriptionHandler.prototype.hasDescription = function (contentType) { + return contentType === this.CONTENT_TYPE; + }; + /** + * The modifier that should be used when the session would like to place the call on hold + * @param {String} [sdp] The description that will be modified + * @returns {Promise} Promise that resolves with modified SDP + */ + SessionDescriptionHandler.prototype.holdModifier = function (description) { + if (!description.sdp) { + return Promise.resolve(description); + } + if (!(/a=(sendrecv|sendonly|recvonly|inactive)/).test(description.sdp)) { + description.sdp = description.sdp.replace(/(m=[^\r]*\r\n)/g, "$1a=sendonly\r\n"); + } + else { + description.sdp = description.sdp.replace(/a=sendrecv\r\n/g, "a=sendonly\r\n"); + description.sdp = description.sdp.replace(/a=recvonly\r\n/g, "a=inactive\r\n"); + } + return Promise.resolve(description); + }; + /** + * Set the remote description to the underlying media implementation + * @param {String} sessionDescription The description provided by a SIP message to be set on the media implementation + * @param {Object} [options] Options object to be used by getDescription + * @param {MediaStreamConstraints} [options.constraints] MediaStreamConstraints + * https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamConstraints + * @param {Object} [options.peerConnectionOptions] If this is set it will recreate the peer + * connection with the new options + * @param {Array} [modifiers] Array with one time use description modifiers + * @returns {Promise} Promise that resolves once the description is set + */ + SessionDescriptionHandler.prototype.setDescription = function (sessionDescription, options, modifiers) { + var _this = this; + if (options === void 0) { options = {}; } + if (modifiers === void 0) { modifiers = []; } + if (options.peerConnectionOptions) { + this.initPeerConnection(options.peerConnectionOptions); + } + if (!Array.isArray(modifiers)) { + modifiers = [modifiers]; + } + modifiers = modifiers.concat(this.modifiers); + var description = { + type: this.hasOffer("local") ? "answer" : "offer", + sdp: sessionDescription + }; + return Promise.resolve().then(function () { + // Media should be acquired in getDescription unless we need to do it sooner for some reason (FF61+) + if (_this.shouldAcquireMedia && _this.options.alwaysAcquireMediaFirst) { + return _this.acquire(_this.constraints).then(function () { + _this.shouldAcquireMedia = false; + }); + } + }).then(function () { return Utils_1.Utils.reducePromises(modifiers, description); }) + .catch(function (e) { + if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { + throw e; + } + var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("setDescription", e, "The modifiers did not resolve successfully"); + _this.logger.error(error.message); + _this.emit("peerConnection-setRemoteDescriptionFailed", error); + throw error; + }).then(function (modifiedDescription) { + _this.emit("setDescription", modifiedDescription); + return _this.peerConnection.setRemoteDescription(modifiedDescription); + }).catch(function (e) { + if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { + throw e; + } + // Check the original SDP for video, and ensure that we have want to do audio fallback + if ((/^m=video.+$/gm).test(sessionDescription) && !options.disableAudioFallback) { + // Do not try to audio fallback again + options.disableAudioFallback = true; + // Remove video first, then do the other modifiers + return _this.setDescription(sessionDescription, options, [Modifiers.stripVideo].concat(modifiers)); + } + var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("setDescription", e); + if (error.error) { + _this.logger.error(error.error); + } + _this.emit("peerConnection-setRemoteDescriptionFailed", error); + throw error; + }).then(function () { + if (_this.peerConnection.getReceivers) { + _this.emit("setRemoteDescription", _this.peerConnection.getReceivers()); + } + else { + _this.emit("setRemoteDescription", _this.peerConnection.getRemoteStreams()); + } + _this.emit("confirmed", _this); + }); + }; + /** + * Send DTMF via RTP (RFC 4733) + * @param {String} tones A string containing DTMF digits + * @param {Object} [options] Options object to be used by sendDtmf + * @returns {boolean} true if DTMF send is successful, false otherwise + */ + SessionDescriptionHandler.prototype.sendDtmf = function (tones, options) { + if (options === void 0) { options = {}; } + if (!this.dtmfSender && this.hasBrowserGetSenderSupport()) { + var senders = this.peerConnection.getSenders(); + if (senders.length > 0) { + this.dtmfSender = senders[0].dtmf; + } + } + if (!this.dtmfSender && this.hasBrowserTrackSupport()) { + var streams = this.peerConnection.getLocalStreams(); + if (streams.length > 0) { + var audioTracks = streams[0].getAudioTracks(); + if (audioTracks.length > 0) { + this.dtmfSender = this.peerConnection.createDTMFSender(audioTracks[0]); + } + } + } + if (!this.dtmfSender) { + return false; + } + try { + this.dtmfSender.insertDTMF(tones, options.duration, options.interToneGap); + } + catch (e) { + if (e.type === "InvalidStateError" || e.type === "InvalidCharacterError") { + this.logger.error(e); + return false; + } + else { + throw e; + } + } + this.logger.log("DTMF sent via RTP: " + tones.toString()); + return true; + }; + /** + * Get the direction of the session description + * @returns {String} direction of the description + */ + SessionDescriptionHandler.prototype.getDirection = function () { + return this.direction; + }; + SessionDescriptionHandler.prototype.on = function (name, callback) { return _super.prototype.on.call(this, name, callback); }; + // Internal functions + SessionDescriptionHandler.prototype.createOfferOrAnswer = function (RTCOfferOptions, modifiers) { + var _this = this; + if (RTCOfferOptions === void 0) { RTCOfferOptions = {}; } + if (modifiers === void 0) { modifiers = []; } + var methodName = this.hasOffer("remote") ? "createAnswer" : "createOffer"; + var pc = this.peerConnection; + this.logger.log(methodName); + var method = this.hasOffer("remote") ? pc.createAnswer : pc.createOffer; + return method(RTCOfferOptions).catch(function (e) { + if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { + throw e; + } + var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("createOfferOrAnswer", e, "peerConnection-" + methodName + "Failed"); + _this.emit("peerConnection-" + methodName + "Failed", error); + throw error; + }).then(function (sdp) { + return Utils_1.Utils.reducePromises(modifiers, _this.createRTCSessionDescriptionInit(sdp)); + }).then(function (sdp) { + _this.resetIceGatheringComplete(); + _this.logger.log("Setting local sdp."); + _this.logger.log("sdp is " + sdp.sdp || "undefined"); + return pc.setLocalDescription(sdp); + }).catch(function (e) { + if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { + throw e; + } + var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("createOfferOrAnswer", e, "peerConnection-SetLocalDescriptionFailed"); + _this.emit("peerConnection-SetLocalDescriptionFailed", error); + throw error; + }).then(function () { return _this.waitForIceGatheringComplete(); }) + .then(function () { + var localDescription = _this.createRTCSessionDescriptionInit(_this.peerConnection.localDescription); + return Utils_1.Utils.reducePromises(modifiers, localDescription); + }).then(function (localDescription) { + _this.setDirection(localDescription.sdp || ""); + return localDescription; + }).catch(function (e) { + if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { + throw e; + } + var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("createOfferOrAnswer", e); + _this.logger.error(error.toString()); + throw error; + }); + }; + // Creates an RTCSessionDescriptionInit from an RTCSessionDescription + SessionDescriptionHandler.prototype.createRTCSessionDescriptionInit = function (RTCSessionDescription) { + return { + type: RTCSessionDescription.type, + sdp: RTCSessionDescription.sdp + }; + }; + SessionDescriptionHandler.prototype.addDefaultIceCheckingTimeout = function (peerConnectionOptions) { + if (peerConnectionOptions.iceCheckingTimeout === undefined) { + peerConnectionOptions.iceCheckingTimeout = 5000; + } + return peerConnectionOptions; + }; + SessionDescriptionHandler.prototype.addDefaultIceServers = function (rtcConfiguration) { + if (!rtcConfiguration.iceServers) { + rtcConfiguration.iceServers = [{ urls: "stun:stun.l.google.com:19302" }]; + } + return rtcConfiguration; + }; + SessionDescriptionHandler.prototype.checkAndDefaultConstraints = function (constraints) { + var defaultConstraints = { audio: true, video: !this.options.alwaysAcquireMediaFirst }; + constraints = constraints || defaultConstraints; + // Empty object check + if (Object.keys(constraints).length === 0 && constraints.constructor === Object) { + return defaultConstraints; + } + return constraints; + }; + SessionDescriptionHandler.prototype.hasBrowserTrackSupport = function () { + return Boolean(this.peerConnection.addTrack); + }; + SessionDescriptionHandler.prototype.hasBrowserGetSenderSupport = function () { + return Boolean(this.peerConnection.getSenders); + }; + SessionDescriptionHandler.prototype.initPeerConnection = function (options) { + var _this = this; + if (options === void 0) { options = {}; } + options = this.addDefaultIceCheckingTimeout(options); + options.rtcConfiguration = options.rtcConfiguration || {}; + options.rtcConfiguration = this.addDefaultIceServers(options.rtcConfiguration); + this.logger.log("initPeerConnection"); + if (this.peerConnection) { + this.logger.log("Already have a peer connection for this session. Tearing down."); + this.resetIceGatheringComplete(); + this.peerConnection.close(); + } + this.peerConnection = new this.WebRTC.RTCPeerConnection(options.rtcConfiguration); + this.logger.log("New peer connection created"); + if ("ontrack" in this.peerConnection) { + this.peerConnection.addEventListener("track", function (e) { + _this.logger.log("track added"); + _this.observer.trackAdded(); + _this.emit("addTrack", e); + }); + } + else { + this.logger.warn("Using onaddstream which is deprecated"); + this.peerConnection.onaddstream = function (e) { + _this.logger.log("stream added"); + _this.emit("addStream", e); + }; + } + this.peerConnection.onicecandidate = function (e) { + _this.emit("iceCandidate", e); + if (e.candidate) { + _this.logger.log("ICE candidate received: " + + (e.candidate.candidate === null ? null : e.candidate.candidate.trim())); + } + else if (e.candidate === null) { + // indicates the end of candidate gathering + _this.logger.log("ICE candidate gathering complete"); + _this.triggerIceGatheringComplete(); + } + }; + this.peerConnection.onicegatheringstatechange = function () { + _this.logger.log("RTCIceGatheringState changed: " + _this.peerConnection.iceGatheringState); + switch (_this.peerConnection.iceGatheringState) { + case "gathering": + _this.emit("iceGathering", _this); + if (!_this.iceGatheringTimer && options.iceCheckingTimeout) { + _this.iceGatheringTimeout = false; + _this.iceGatheringTimer = setTimeout(function () { + _this.logger.log("RTCIceChecking Timeout Triggered after " + options.iceCheckingTimeout + " milliseconds"); + _this.iceGatheringTimeout = true; + _this.triggerIceGatheringComplete(); + }, options.iceCheckingTimeout); + } + break; + case "complete": + _this.triggerIceGatheringComplete(); + break; + } + }; + this.peerConnection.oniceconnectionstatechange = function () { + var stateEvent; + switch (_this.peerConnection.iceConnectionState) { + case "new": + stateEvent = "iceConnection"; + break; + case "checking": + stateEvent = "iceConnectionChecking"; + break; + case "connected": + stateEvent = "iceConnectionConnected"; + break; + case "completed": + stateEvent = "iceConnectionCompleted"; + break; + case "failed": + stateEvent = "iceConnectionFailed"; + break; + case "disconnected": + stateEvent = "iceConnectionDisconnected"; + break; + case "closed": + stateEvent = "iceConnectionClosed"; + break; + default: + _this.logger.warn("Unknown iceConnection state: " + _this.peerConnection.iceConnectionState); + return; + } + _this.logger.log("ICE Connection State changed to " + stateEvent); + _this.emit(stateEvent, _this); + }; + }; + SessionDescriptionHandler.prototype.acquire = function (constraints) { + var _this = this; + // Default audio & video to true + constraints = this.checkAndDefaultConstraints(constraints); + return new Promise(function (resolve, reject) { + /* + * Make the call asynchronous, so that ICCs have a chance + * to define callbacks to `userMediaRequest` + */ + _this.logger.log("acquiring local media"); + _this.emit("userMediaRequest", constraints); + if (constraints.audio || constraints.video) { + _this.WebRTC.getUserMedia(constraints).then(function (streams) { + _this.observer.trackAdded(); + _this.emit("userMedia", streams); + resolve(streams); + }).catch(function (e) { + _this.emit("userMediaFailed", e); + reject(e); + }); + } + else { + // Local streams were explicitly excluded. + resolve([]); + } + }).catch(function (e) { + if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { + throw e; + } + var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("acquire", e, "unable to acquire streams"); + _this.logger.error(error.message); + if (error.error) { + _this.logger.error(error.error); + } + throw error; + }).then(function (streams) { + _this.logger.log("acquired local media streams"); + try { + // Remove old tracks + if (_this.peerConnection.removeTrack) { + _this.peerConnection.getSenders().forEach(function (sender) { + _this.peerConnection.removeTrack(sender); + }); + } + return streams; + } + catch (e) { + return Promise.reject(e); + } + }).catch(function (e) { + if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { + throw e; + } + var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("acquire", e, "error removing streams"); + _this.logger.error(error.message); + if (error.error) { + _this.logger.error(error.error); + } + throw error; + }).then(function (streams) { + try { + streams = [].concat(streams); + streams.forEach(function (stream) { + if (_this.peerConnection.addTrack) { + stream.getTracks().forEach(function (track) { + _this.peerConnection.addTrack(track, stream); + }); + } + else { + // Chrome 59 does not support addTrack + _this.peerConnection.addStream(stream); + } + }); + } + catch (e) { + return Promise.reject(e); + } + return Promise.resolve(); + }).catch(function (e) { + if (e.type === Enums_1.TypeStrings.SessionDescriptionHandlerError) { + throw e; + } + var error = new Exceptions_1.Exceptions.SessionDescriptionHandlerError("acquire", e, "error adding stream"); + _this.logger.error(error.message); + if (error.error) { + _this.logger.error(error.error); + } + throw error; + }); + }; + SessionDescriptionHandler.prototype.hasOffer = function (where) { + var offerState = "have-" + where + "-offer"; + return this.peerConnection.signalingState === offerState; + }; + // ICE gathering state handling + SessionDescriptionHandler.prototype.isIceGatheringComplete = function () { + return this.peerConnection.iceGatheringState === "complete" || this.iceGatheringTimeout; + }; + SessionDescriptionHandler.prototype.resetIceGatheringComplete = function () { + this.iceGatheringTimeout = false; + this.logger.log("resetIceGatheringComplete"); + if (this.iceGatheringTimer) { + clearTimeout(this.iceGatheringTimer); + this.iceGatheringTimer = undefined; + } + if (this.iceGatheringDeferred) { + this.iceGatheringDeferred.reject(); + this.iceGatheringDeferred = undefined; + } + }; + SessionDescriptionHandler.prototype.setDirection = function (sdp) { + var match = sdp.match(/a=(sendrecv|sendonly|recvonly|inactive)/); + if (match === null) { + this.direction = this.C.DIRECTION.NULL; + this.observer.directionChanged(); + return; + } + var direction = match[1]; + switch (direction) { + case this.C.DIRECTION.SENDRECV: + case this.C.DIRECTION.SENDONLY: + case this.C.DIRECTION.RECVONLY: + case this.C.DIRECTION.INACTIVE: + this.direction = direction; + break; + default: + this.direction = this.C.DIRECTION.NULL; + break; + } + this.observer.directionChanged(); + }; + SessionDescriptionHandler.prototype.triggerIceGatheringComplete = function () { + if (this.isIceGatheringComplete()) { + this.emit("iceGatheringComplete", this); + if (this.iceGatheringTimer) { + clearTimeout(this.iceGatheringTimer); + this.iceGatheringTimer = undefined; + } + if (this.iceGatheringDeferred) { + this.iceGatheringDeferred.resolve(); + this.iceGatheringDeferred = undefined; + } + } + }; + SessionDescriptionHandler.prototype.waitForIceGatheringComplete = function () { + this.logger.log("waitForIceGatheringComplete"); + if (this.isIceGatheringComplete()) { + this.logger.log("ICE is already complete. Return resolved."); + return Promise.resolve(); + } + else if (!this.iceGatheringDeferred) { + this.iceGatheringDeferred = Utils_1.Utils.defer(); + } + this.logger.log("ICE is not complete. Returning promise"); + return this.iceGatheringDeferred ? this.iceGatheringDeferred.promise : Promise.resolve(); + }; + return SessionDescriptionHandler; +}(events_1.EventEmitter)); +exports.SessionDescriptionHandler = SessionDescriptionHandler; diff --git a/lib/Web/SessionDescriptionHandlerObserver.d.ts b/lib/Web/SessionDescriptionHandlerObserver.d.ts new file mode 100644 index 000000000..24b5b8187 --- /dev/null +++ b/lib/Web/SessionDescriptionHandlerObserver.d.ts @@ -0,0 +1,11 @@ +import { TypeStrings } from "../Enums"; +import { InviteClientContext, InviteServerContext } from "../Session"; +import { SessionDescriptionHandlerObserver as SessionDescriptionHandlerObserverDefinition } from "../session-description-handler-observer"; +export declare class SessionDescriptionHandlerObserver implements SessionDescriptionHandlerObserverDefinition { + type: TypeStrings; + private session; + private options; + constructor(session: InviteClientContext | InviteServerContext, options: any); + trackAdded(): void; + directionChanged(): void; +} diff --git a/lib/Web/SessionDescriptionHandlerObserver.js b/lib/Web/SessionDescriptionHandlerObserver.js new file mode 100644 index 000000000..d410c8968 --- /dev/null +++ b/lib/Web/SessionDescriptionHandlerObserver.js @@ -0,0 +1,23 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var Enums_1 = require("../Enums"); +/* SessionDescriptionHandlerObserver + * @class SessionDescriptionHandler Observer Class. + * @param {SIP.Session} session + * @param {Object} [options] + */ +var SessionDescriptionHandlerObserver = /** @class */ (function () { + function SessionDescriptionHandlerObserver(session, options) { + this.type = Enums_1.TypeStrings.SessionDescriptionHandlerObserver; + this.session = session; + this.options = options; + } + SessionDescriptionHandlerObserver.prototype.trackAdded = function () { + this.session.emit("trackAdded"); + }; + SessionDescriptionHandlerObserver.prototype.directionChanged = function () { + this.session.emit("directionChanged"); + }; + return SessionDescriptionHandlerObserver; +}()); +exports.SessionDescriptionHandlerObserver = SessionDescriptionHandlerObserver; diff --git a/lib/Web/Simple.d.ts b/lib/Web/Simple.d.ts new file mode 100644 index 000000000..f19a3ada2 --- /dev/null +++ b/lib/Web/Simple.d.ts @@ -0,0 +1,45 @@ +/// +import { EventEmitter } from "events"; +import { Logger } from "../LoggerFactory"; +import { InviteClientContext, InviteServerContext } from "../Session"; +import { UA } from "../UA"; +export declare enum SimpleStatus { + STATUS_NULL = 0, + STATUS_NEW = 1, + STATUS_CONNECTING = 2, + STATUS_CONNECTED = 3, + STATUS_COMPLETED = 4 +} +export declare class Simple extends EventEmitter { + static readonly C: typeof SimpleStatus; + video: boolean; + audio: boolean; + anonymous: boolean; + options: any; + ua: UA; + state: SimpleStatus; + logger: Logger; + session: InviteClientContext | InviteServerContext | undefined; + constructor(options: any); + call(destination: string): InviteClientContext | InviteServerContext | void; + answer(): InviteServerContext | void; + reject(): InviteServerContext | undefined; + hangup(): InviteClientContext | InviteServerContext | undefined; + hold(): InviteClientContext | InviteServerContext | void; + unhold(): InviteClientContext | InviteServerContext | void; + mute(): void; + unmute(): void; + sendDTMF(tone: string): void; + message(destination: string, message: string): void; + private checkRegistration; + private setupRemoteMedia; + private setupLocalMedia; + private cleanupMedia; + private setupSession; + private destroyMedia; + private toggleMute; + private onAccepted; + private onProgress; + private onFailed; + private onEnded; +} diff --git a/lib/Web/Simple.js b/lib/Web/Simple.js new file mode 100644 index 000000000..91ef1f4c9 --- /dev/null +++ b/lib/Web/Simple.js @@ -0,0 +1,423 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var events_1 = require("events"); +var UA_1 = require("../UA"); +var Modifiers = require("./Modifiers"); +/* Simple + * @class Simple + */ +var SimpleStatus; +(function (SimpleStatus) { + SimpleStatus[SimpleStatus["STATUS_NULL"] = 0] = "STATUS_NULL"; + SimpleStatus[SimpleStatus["STATUS_NEW"] = 1] = "STATUS_NEW"; + SimpleStatus[SimpleStatus["STATUS_CONNECTING"] = 2] = "STATUS_CONNECTING"; + SimpleStatus[SimpleStatus["STATUS_CONNECTED"] = 3] = "STATUS_CONNECTED"; + SimpleStatus[SimpleStatus["STATUS_COMPLETED"] = 4] = "STATUS_COMPLETED"; +})(SimpleStatus = exports.SimpleStatus || (exports.SimpleStatus = {})); +var Simple = /** @class */ (function (_super) { + __extends(Simple, _super); + function Simple(options) { + var _this = _super.call(this) || this; + /* + * { + * media: { + * remote: { + * audio: , + * video: + * }, + * local: { + * video: + * } + * }, + * ua: { + * + * } + * } + */ + if (options.media.remote.video) { + _this.video = true; + } + else { + _this.video = false; + } + if (options.media.remote.audio) { + _this.audio = true; + } + else { + _this.audio = false; + } + if (!_this.audio && !_this.video) { + // Need to do at least audio or video + // Error + throw new Error("At least one remote audio or video element is required for Simple."); + } + _this.options = options; + // https://stackoverflow.com/questions/7944460/detect-safari-browser + var browserUa = global.navigator.userAgent.toLowerCase(); + var isSafari = false; + var isFirefox = false; + if (browserUa.indexOf("safari") > -1 && browserUa.indexOf("chrome") < 0) { + isSafari = true; + } + else if (browserUa.indexOf("firefox") > -1 && browserUa.indexOf("chrome") < 0) { + isFirefox = true; + } + var sessionDescriptionHandlerFactoryOptions = {}; + if (isSafari) { + sessionDescriptionHandlerFactoryOptions.modifiers = [Modifiers.stripG722]; + } + if (isFirefox) { + sessionDescriptionHandlerFactoryOptions.alwaysAcquireMediaFirst = true; + } + if (!_this.options.ua.uri) { + _this.anonymous = true; + } + else { + _this.anonymous = false; + } + _this.ua = new UA_1.UA({ + // User Configurable Options + uri: _this.options.ua.uri, + authorizationUser: _this.options.ua.authorizationUser, + password: _this.options.ua.password, + displayName: _this.options.ua.displayName, + // Undocumented "Advanced" Options + userAgentString: _this.options.ua.userAgentString, + // Fixed Options + register: true, + sessionDescriptionHandlerFactoryOptions: sessionDescriptionHandlerFactoryOptions, + transportOptions: { + traceSip: _this.options.ua.traceSip, + wsServers: _this.options.ua.wsServers + } + }); + _this.state = SimpleStatus.STATUS_NULL; + _this.logger = _this.ua.getLogger("sip.simple"); + _this.ua.on("registered", function () { + _this.emit("registered", _this.ua); + }); + _this.ua.on("unregistered", function () { + _this.emit("unregistered", _this.ua); + }); + _this.ua.on("registrationFailed", function () { + _this.emit("unregistered", _this.ua); + }); + _this.ua.on("invite", function (session) { + // If there is already an active session reject the incoming session + if (_this.state !== SimpleStatus.STATUS_NULL && _this.state !== SimpleStatus.STATUS_COMPLETED) { + _this.logger.warn("Rejecting incoming call. Simple only supports 1 call at a time"); + session.reject(); + return; + } + _this.session = session; + _this.setupSession(); + _this.emit("ringing", _this.session); + }); + _this.ua.on("message", function (message) { + _this.emit("message", message); + }); + return _this; + } + Simple.prototype.call = function (destination) { + if (!this.ua || !this.checkRegistration()) { + this.logger.warn("A registered UA is required for calling"); + return; + } + if (this.state !== SimpleStatus.STATUS_NULL && this.state !== SimpleStatus.STATUS_COMPLETED) { + this.logger.warn("Cannot make more than a single call with Simple"); + return; + } + // Safari hack, because you cannot call .play() from a non user action + if (this.options.media.remote.audio) { + this.options.media.remote.audio.autoplay = true; + } + if (this.options.media.remote.video) { + this.options.media.remote.video.autoplay = true; + } + if (this.options.media.local && this.options.media.local.video) { + this.options.media.local.video.autoplay = true; + this.options.media.local.video.volume = 0; + } + this.session = this.ua.invite(destination, { + sessionDescriptionHandlerOptions: { + constraints: { + audio: this.audio, + video: this.video + } + } + }); + this.setupSession(); + return this.session; + }; + Simple.prototype.answer = function () { + if (this.state !== SimpleStatus.STATUS_NEW && this.state !== SimpleStatus.STATUS_CONNECTING) { + this.logger.warn("No call to answer"); + return; + } + // Safari hack, because you cannot call .play() from a non user action + if (this.options.media.remote.audio) { + this.options.media.remote.audio.autoplay = true; + } + if (this.options.media.remote.video) { + this.options.media.remote.video.autoplay = true; + } + return this.session.accept({ + sessionDescriptionHandlerOptions: { + constraints: { + audio: this.audio, + video: this.video + } + } + }); + // emit call is active + }; + Simple.prototype.reject = function () { + if (this.state !== SimpleStatus.STATUS_NEW && this.state !== SimpleStatus.STATUS_CONNECTING) { + this.logger.warn("Call is already answered"); + return; + } + return this.session.reject(); + }; + Simple.prototype.hangup = function () { + if (this.state !== SimpleStatus.STATUS_CONNECTED && + this.state !== SimpleStatus.STATUS_CONNECTING && + this.state !== SimpleStatus.STATUS_NEW) { + this.logger.warn("No active call to hang up on"); + return; + } + if (this.state !== SimpleStatus.STATUS_CONNECTED) { + return this.session.cancel(); + } + else if (this.session) { + return this.session.bye(); + } + }; + Simple.prototype.hold = function () { + if (this.state !== SimpleStatus.STATUS_CONNECTED || !this.session || this.session.localHold) { + this.logger.warn("Cannot put call on hold"); + return; + } + this.mute(); + this.logger.log("Placing session on hold"); + return this.session.hold(); + }; + Simple.prototype.unhold = function () { + if (this.state !== SimpleStatus.STATUS_CONNECTED || !this.session || !this.session.localHold) { + this.logger.warn("Cannot unhold a call that is not on hold"); + return; + } + this.unmute(); + this.logger.log("Placing call off hold"); + return this.session.unhold(); + }; + Simple.prototype.mute = function () { + if (this.state !== SimpleStatus.STATUS_CONNECTED) { + this.logger.warn("An acitve call is required to mute audio"); + return; + } + this.logger.log("Muting Audio"); + this.toggleMute(true); + this.emit("mute", this); + }; + Simple.prototype.unmute = function () { + if (this.state !== SimpleStatus.STATUS_CONNECTED) { + this.logger.warn("An active call is required to unmute audio"); + return; + } + this.logger.log("Unmuting Audio"); + this.toggleMute(false); + this.emit("unmute", this); + }; + Simple.prototype.sendDTMF = function (tone) { + if (this.state !== SimpleStatus.STATUS_CONNECTED || !this.session) { + this.logger.warn("An active call is required to send a DTMF tone"); + return; + } + this.logger.log("Sending DTMF tone: " + tone); + this.session.dtmf(tone); + }; + Simple.prototype.message = function (destination, message) { + if (!this.ua || !this.checkRegistration()) { + this.logger.warn("A registered UA is required to send a message"); + return; + } + if (!destination || !message) { + this.logger.warn("A destination and message are required to send a message"); + return; + } + this.ua.message(destination, message); + }; + // Private Helpers + Simple.prototype.checkRegistration = function () { + return (this.anonymous || (this.ua && this.ua.isRegistered())); + }; + Simple.prototype.setupRemoteMedia = function () { + var _this = this; + if (!this.session) { + this.logger.warn("No session to set remote media on"); + return; + } + // If there is a video track, it will attach the video and audio to the same element + var pc = this.session.sessionDescriptionHandler.peerConnection; + var remoteStream; + if (pc.getReceivers) { + remoteStream = new global.window.MediaStream(); + pc.getReceivers().forEach(function (receiver) { + var track = receiver.track; + if (track) { + remoteStream.addTrack(track); + } + }); + } + else { + remoteStream = pc.getRemoteStreams()[0]; + } + if (this.video) { + this.options.media.remote.video.srcObject = remoteStream; + this.options.media.remote.video.play().catch(function () { + _this.logger.log("play was rejected"); + }); + } + else if (this.audio) { + this.options.media.remote.audio.srcObject = remoteStream; + this.options.media.remote.audio.play().catch(function () { + _this.logger.log("play was rejected"); + }); + } + }; + Simple.prototype.setupLocalMedia = function () { + if (!this.session) { + this.logger.warn("No session to set local media on"); + return; + } + if (this.video && this.options.media.local && this.options.media.local.video) { + var pc = this.session.sessionDescriptionHandler.peerConnection; + var localStream_1; + if (pc.getSenders) { + localStream_1 = new global.window.MediaStream(); + pc.getSenders().forEach(function (sender) { + var track = sender.track; + if (track && track.kind === "video") { + localStream_1.addTrack(track); + } + }); + } + else { + localStream_1 = pc.getLocalStreams()[0]; + } + this.options.media.local.video.srcObject = localStream_1; + this.options.media.local.video.volume = 0; + this.options.media.local.video.play(); + } + }; + Simple.prototype.cleanupMedia = function () { + if (this.video) { + this.options.media.remote.video.srcObject = null; + this.options.media.remote.video.pause(); + if (this.options.media.local && this.options.media.local.video) { + this.options.media.local.video.srcObject = null; + this.options.media.local.video.pause(); + } + } + if (this.audio) { + this.options.media.remote.audio.srcObject = null; + this.options.media.remote.audio.pause(); + } + }; + Simple.prototype.setupSession = function () { + var _this = this; + if (!this.session) { + this.logger.warn("No session to set up"); + return; + } + this.state = SimpleStatus.STATUS_NEW; + this.emit("new", this.session); + this.session.on("progress", function () { return _this.onProgress(); }); + this.session.on("accepted", function () { return _this.onAccepted(); }); + this.session.on("rejected", function () { return _this.onEnded(); }); + this.session.on("failed", function () { return _this.onFailed(); }); + this.session.on("terminated", function () { return _this.onEnded(); }); + }; + Simple.prototype.destroyMedia = function () { + if (this.session && this.session.sessionDescriptionHandler) { + this.session.sessionDescriptionHandler.close(); + } + }; + Simple.prototype.toggleMute = function (mute) { + if (!this.session) { + this.logger.warn("No session to toggle mute"); + return; + } + var pc = this.session.sessionDescriptionHandler.peerConnection; + if (pc.getSenders) { + pc.getSenders().forEach(function (sender) { + if (sender.track) { + sender.track.enabled = !mute; + } + }); + } + else { + pc.getLocalStreams().forEach(function (stream) { + stream.getAudioTracks().forEach(function (track) { + track.enabled = !mute; + }); + stream.getVideoTracks().forEach(function (track) { + track.enabled = !mute; + }); + }); + } + }; + Simple.prototype.onAccepted = function () { + var _this = this; + if (!this.session) { + this.logger.warn("No session for accepting"); + return; + } + this.state = SimpleStatus.STATUS_CONNECTED; + this.emit("connected", this.session); + this.setupLocalMedia(); + this.setupRemoteMedia(); + if (this.session.sessionDescriptionHandler) { + this.session.sessionDescriptionHandler.on("addTrack", function () { + _this.logger.log("A track has been added, triggering new remoteMedia setup"); + _this.setupRemoteMedia(); + }); + this.session.sessionDescriptionHandler.on("addStream", function () { + _this.logger.log("A stream has been added, trigger new remoteMedia setup"); + _this.setupRemoteMedia(); + }); + } + this.session.on("dtmf", function (request, dtmf) { + _this.emit("dtmf", dtmf.tone); + }); + this.session.on("bye", function () { return _this.onEnded(); }); + }; + Simple.prototype.onProgress = function () { + this.state = SimpleStatus.STATUS_CONNECTING; + this.emit("connecting", this.session); + }; + Simple.prototype.onFailed = function () { + this.onEnded(); + }; + Simple.prototype.onEnded = function () { + this.state = SimpleStatus.STATUS_COMPLETED; + this.emit("ended", this.session); + this.cleanupMedia(); + }; + Simple.C = SimpleStatus; + return Simple; +}(events_1.EventEmitter)); +exports.Simple = Simple; diff --git a/lib/Web/Transport.d.ts b/lib/Web/Transport.d.ts new file mode 100644 index 000000000..f5d68f978 --- /dev/null +++ b/lib/Web/Transport.d.ts @@ -0,0 +1,160 @@ +import { TypeStrings } from "../Enums"; +import { Logger } from "../LoggerFactory"; +import { OutgoingRequest } from "../SIPMessage"; +import { Transport as TransportBase } from "../Transport"; +export declare enum TransportStatus { + STATUS_CONNECTING = 0, + STATUS_OPEN = 1, + STATUS_CLOSING = 2, + STATUS_CLOSED = 3 +} +export interface WsServer { + scheme: string; + sipUri: string; + wsUri: string; + weight: number; + isError: boolean; +} +export interface Configuration { + wsServers: Array; + connectionTimeout: number; + maxReconnectionAttempts: number; + reconnectionTimeout: number; + keepAliveInterval: number; + keepAliveDebounce: number; + traceSip: boolean; +} +/** + * @class Transport + * @param {Object} options + */ +export declare class Transport extends TransportBase { + static readonly C: typeof TransportStatus; + type: TypeStrings; + server: WsServer; + ws: any; + private WebSocket; + private connectionPromise; + private connectDeferredResolve; + private connectionTimeout; + private disconnectionPromise; + private disconnectDeferredResolve; + private reconnectionAttempts; + private reconnectTimer; + private keepAliveInterval; + private keepAliveDebounceTimeout; + private status; + private configuration; + private boundOnOpen; + private boundOnMessage; + private boundOnClose; + private boundOnError; + constructor(logger: Logger, options?: any); + /** + * @returns {Boolean} + */ + isConnected(): boolean; + /** + * Send a message. + * @param {SIP.OutgoingRequest|String} msg + * @param {Object} [options] + * @returns {Promise} + */ + protected sendPromise(msg: OutgoingRequest | string, options?: any): Promise<{ + msg: string; + }>; + /** + * Disconnect socket. + */ + protected disconnectPromise(options?: any): Promise; + /** + * Connect socket. + */ + protected connectPromise(options?: any): Promise; + /** + * @event + * @param {event} e + */ + protected onMessage(e: any): void; + /** + * @event + * @param {event} e + */ + private onOpen; + /** + * @event + * @param {event} e + */ + private onClose; + /** + * Removes event listeners and clears the instance ws + */ + private disposeWs; + /** + * @event + * @param {string} e + */ + private onError; + /** + * @event + * @private + */ + private onWebsocketError; + /** + * Reconnection attempt logic. + */ + private reconnect; + /** + * Resets the error state of all servers in the configuration + */ + private resetServerErrorStatus; + /** + * Retrieve the next server to which connect. + * @param {Boolean} force allows bypass of server error status checking + * @returns {Object} WsServer + */ + private getNextWsServer; + /** + * Checks all configuration servers, returns true if all of them have isError: true and false otherwise + * @returns {Boolean} + */ + private noAvailableServers; + /** + * Send a keep-alive (a double-CRLF sequence). + * @returns {Boolean} + */ + private sendKeepAlive; + private clearKeepAliveTimeout; + /** + * Start sending keep-alives. + */ + private startSendingKeepAlives; + /** + * Stop sending keep-alives. + */ + private stopSendingKeepAlives; + /** + * Checks given status against instance current status. Returns true if they match + * @param {Number} status + * @param {Boolean} [force] + * @returns {Boolean} + */ + private statusAssert; + /** + * Transitions the status. Checks for legal transition via assertion beforehand + * @param {Number} status + * @param {Boolean} [force] + * @returns {Boolean} + */ + private statusTransition; + /** + * Configuration load. + * returns {Configuration} + */ + private loadConfig; + /** + * Configuration checker. + * @return {Boolean} + */ + private getConfigurationCheck; +} diff --git a/lib/Web/Transport.js b/lib/Web/Transport.js new file mode 100644 index 000000000..4f29cb6d5 --- /dev/null +++ b/lib/Web/Transport.js @@ -0,0 +1,706 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var Enums_1 = require("../Enums"); +var Exceptions_1 = require("../Exceptions"); +var Grammar_1 = require("../Grammar"); +var Transport_1 = require("../Transport"); +var Utils_1 = require("../Utils"); +var TransportStatus; +(function (TransportStatus) { + TransportStatus[TransportStatus["STATUS_CONNECTING"] = 0] = "STATUS_CONNECTING"; + TransportStatus[TransportStatus["STATUS_OPEN"] = 1] = "STATUS_OPEN"; + TransportStatus[TransportStatus["STATUS_CLOSING"] = 2] = "STATUS_CLOSING"; + TransportStatus[TransportStatus["STATUS_CLOSED"] = 3] = "STATUS_CLOSED"; +})(TransportStatus = exports.TransportStatus || (exports.TransportStatus = {})); +/** + * Compute an amount of time in seconds to wait before sending another + * keep-alive. + * @returns {Number} + */ +var computeKeepAliveTimeout = function (upperBound) { + var lowerBound = upperBound * 0.8; + return 1000 * (Math.random() * (upperBound - lowerBound) + lowerBound); +}; +/** + * @class Transport + * @param {Object} options + */ +var Transport = /** @class */ (function (_super) { + __extends(Transport, _super); + function Transport(logger, options) { + if (options === void 0) { options = {}; } + var _this = _super.call(this, logger, options) || this; + _this.WebSocket = (global.window || global).WebSocket; + _this.type = Enums_1.TypeStrings.Transport; + _this.reconnectionAttempts = 0; + _this.status = TransportStatus.STATUS_CONNECTING; + _this.configuration = _this.loadConfig(options); + _this.server = _this.configuration.wsServers[0]; + return _this; + } + /** + * @returns {Boolean} + */ + Transport.prototype.isConnected = function () { + return this.status === TransportStatus.STATUS_OPEN; + }; + /** + * Send a message. + * @param {SIP.OutgoingRequest|String} msg + * @param {Object} [options] + * @returns {Promise} + */ + Transport.prototype.sendPromise = function (msg, options) { + if (options === void 0) { options = {}; } + if (!this.statusAssert(TransportStatus.STATUS_OPEN, options.force)) { + this.onError("unable to send message - WebSocket not open"); + return Promise.reject(); + } + var message = msg.toString(); + if (this.ws) { + if (this.configuration.traceSip === true) { + this.logger.log("sending WebSocket message:\n\n" + message + "\n"); + } + this.ws.send(message); + return Promise.resolve({ msg: message }); + } + else { + this.onError("unable to send message - WebSocket does not exist"); + return Promise.reject(); + } + }; + /** + * Disconnect socket. + */ + Transport.prototype.disconnectPromise = function (options) { + var _this = this; + if (options === void 0) { options = {}; } + if (this.disconnectionPromise) { // Already disconnecting. Just return this. + return this.disconnectionPromise; + } + options.code = options.code || 1000; + if (!this.statusTransition(TransportStatus.STATUS_CLOSING, options.force)) { + if (this.status === TransportStatus.STATUS_CLOSED) { // Websocket is already closed + return Promise.resolve({ overrideEvent: true }); + } + else if (this.connectionPromise) { // Websocket is connecting, cannot move to disconneting yet + return this.connectionPromise.then(function () { return Promise.reject("The websocket did not disconnect"); }) + .catch(function () { return Promise.resolve({ overrideEvent: true }); }); + } + else { + // Cannot move to disconnecting, but not in connecting state. + return Promise.reject("The websocket did not disconnect"); + } + } + this.emit("disconnecting"); + this.disconnectionPromise = new Promise(function (resolve, reject) { + _this.disconnectDeferredResolve = resolve; + if (_this.reconnectTimer) { + clearTimeout(_this.reconnectTimer); + _this.reconnectTimer = undefined; + } + if (_this.ws) { + _this.stopSendingKeepAlives(); + _this.logger.log("closing WebSocket " + _this.server.wsUri); + _this.ws.close(options.code, options.reason); + } + else { + reject("Attempted to disconnect but the websocket doesn't exist"); + } + }); + return this.disconnectionPromise; + }; + /** + * Connect socket. + */ + Transport.prototype.connectPromise = function (options) { + var _this = this; + if (options === void 0) { options = {}; } + if (this.status === TransportStatus.STATUS_CLOSING && !options.force) { + return Promise.reject("WebSocket " + this.server.wsUri + " is closing"); + } + if (this.connectionPromise) { + return this.connectionPromise; + } + this.server = this.server || this.getNextWsServer(options.force); + this.connectionPromise = new Promise(function (resolve, reject) { + if ((_this.status === TransportStatus.STATUS_OPEN || _this.status === TransportStatus.STATUS_CLOSING) + && !options.force) { + _this.logger.warn("WebSocket " + _this.server.wsUri + " is already connected"); + reject("Failed status check - attempted to open a connection but already open/closing"); + return; + } + _this.connectDeferredResolve = resolve; + _this.status = TransportStatus.STATUS_CONNECTING; + _this.emit("connecting"); + _this.logger.log("connecting to WebSocket " + _this.server.wsUri); + _this.disposeWs(); + try { + _this.ws = new WebSocket(_this.server.wsUri, "sip"); + } + catch (e) { + _this.ws = null; + _this.status = TransportStatus.STATUS_CLOSED; // force status to closed in error case + _this.onError("error connecting to WebSocket " + _this.server.wsUri + ":" + e); + reject("Failed to create a websocket"); + return; + } + if (!_this.ws) { + reject("Unexpected instance websocket not set"); + return; + } + _this.connectionTimeout = setTimeout(function () { + _this.statusTransition(TransportStatus.STATUS_CLOSED); + _this.logger.warn("took too long to connect - exceeded time set in configuration.connectionTimeout: " + + _this.configuration.connectionTimeout + "s"); + _this.emit("disconnected", { code: 1000 }); + _this.connectionPromise = undefined; + reject("Connection timeout"); + }, _this.configuration.connectionTimeout * 1000); + _this.boundOnOpen = _this.onOpen.bind(_this); + _this.boundOnMessage = _this.onMessage.bind(_this); + _this.boundOnClose = _this.onClose.bind(_this); + _this.boundOnError = _this.onWebsocketError.bind(_this); + _this.ws.addEventListener("open", _this.boundOnOpen); + _this.ws.addEventListener("message", _this.boundOnMessage); + _this.ws.addEventListener("close", _this.boundOnClose); + _this.ws.addEventListener("error", _this.boundOnError); + }); + return this.connectionPromise; + }; + /** + * @event + * @param {event} e + */ + Transport.prototype.onMessage = function (e) { + var data = e.data; + var finishedData; + // CRLF Keep Alive response from server. Clear our keep alive timeout. + if (/^(\r\n)+$/.test(data)) { + this.clearKeepAliveTimeout(); + if (this.configuration.traceSip === true) { + this.logger.log("received WebSocket message with CRLF Keep Alive response"); + } + return; + } + else if (!data) { + this.logger.warn("received empty message, message discarded"); + return; + } + else if (typeof data !== "string") { // WebSocket binary message. + try { + // the UInt8Data was here prior to types, and doesn't check + finishedData = String.fromCharCode.apply(null, new Uint8Array(data)); + } + catch (err) { + this.logger.warn("received WebSocket binary message failed to be converted into string, message discarded"); + return; + } + if (this.configuration.traceSip === true) { + this.logger.log("received WebSocket binary message:\n\n" + data + "\n"); + } + } + else { // WebSocket text message. + if (this.configuration.traceSip === true) { + this.logger.log("received WebSocket text message:\n\n" + data + "\n"); + } + finishedData = data; + } + this.emit("message", finishedData); + }; + // Transport Event Handlers + /** + * @event + * @param {event} e + */ + Transport.prototype.onOpen = function () { + if (this.status === TransportStatus.STATUS_CLOSED) { // Indicated that the transport thinks the ws is dead already + var ws = this.ws; + this.disposeWs(); + ws.close(1000); + return; + } + this.status = TransportStatus.STATUS_OPEN; // quietly force status to open + this.emit("connected"); + if (this.connectionTimeout) { + clearTimeout(this.connectionTimeout); + this.connectionTimeout = undefined; + } + this.logger.log("WebSocket " + this.server.wsUri + " connected"); + // Clear reconnectTimer since we are not disconnected + if (this.reconnectTimer !== undefined) { + clearTimeout(this.reconnectTimer); + this.reconnectTimer = undefined; + } + // Reset reconnectionAttempts + this.reconnectionAttempts = 0; + // Reset disconnection promise so we can disconnect from a fresh state + this.disconnectionPromise = undefined; + this.disconnectDeferredResolve = undefined; + // Start sending keep-alives + this.startSendingKeepAlives(); + if (this.connectDeferredResolve) { + this.connectDeferredResolve({ overrideEvent: true }); + } + else { + this.logger.warn("Unexpected websocket.onOpen with no connectDeferredResolve"); + } + }; + /** + * @event + * @param {event} e + */ + Transport.prototype.onClose = function (e) { + this.logger.log("WebSocket disconnected (code: " + e.code + (e.reason ? "| reason: " + e.reason : "") + ")"); + if (this.status !== TransportStatus.STATUS_CLOSING) { + this.logger.warn("WebSocket closed without SIP.js requesting it"); + this.emit("transportError"); + } + this.stopSendingKeepAlives(); + // Clean up connection variables so we can connect again from a fresh state + if (this.connectionTimeout) { + clearTimeout(this.connectionTimeout); + } + this.connectionTimeout = undefined; + this.connectionPromise = undefined; + this.connectDeferredResolve = undefined; + // Check whether the user requested to close. + if (this.disconnectDeferredResolve) { + this.disconnectDeferredResolve({ overrideEvent: true }); + this.statusTransition(TransportStatus.STATUS_CLOSED); + this.disconnectDeferredResolve = undefined; + return; + } + this.status = TransportStatus.STATUS_CLOSED; // quietly force status to closed + this.emit("disconnected", { code: e.code, reason: e.reason }); + this.reconnect(); + }; + /** + * Removes event listeners and clears the instance ws + */ + Transport.prototype.disposeWs = function () { + if (this.ws) { + this.ws.removeEventListener("open", this.boundOnOpen); + this.ws.removeEventListener("message", this.boundOnMessage); + this.ws.removeEventListener("close", this.boundOnClose); + this.ws.removeEventListener("error", this.boundOnError); + this.ws = undefined; + } + }; + /** + * @event + * @param {string} e + */ + Transport.prototype.onError = function (e) { + this.logger.warn("Transport error: " + e); + this.emit("transportError"); + }; + /** + * @event + * @private + */ + Transport.prototype.onWebsocketError = function () { + this.onError("The Websocket had an error"); + }; + /** + * Reconnection attempt logic. + */ + Transport.prototype.reconnect = function () { + var _this = this; + if (this.reconnectionAttempts > 0) { + this.logger.log("Reconnection attempt " + this.reconnectionAttempts + " failed"); + } + if (this.noAvailableServers()) { + this.logger.warn("attempted to get next ws server but there are no available ws servers left"); + this.logger.warn("no available ws servers left - going to closed state"); + this.status = TransportStatus.STATUS_CLOSED; + this.emit("closed"); + this.resetServerErrorStatus(); + return; + } + if (this.isConnected()) { + this.logger.warn("attempted to reconnect while connected - forcing disconnect"); + this.disconnect({ force: true }); + } + this.reconnectionAttempts += 1; + if (this.reconnectionAttempts > this.configuration.maxReconnectionAttempts) { + this.logger.warn("maximum reconnection attempts for WebSocket " + this.server.wsUri); + this.logger.log("transport " + this.server.wsUri + " failed | connection state set to 'error'"); + this.server.isError = true; + this.emit("transportError"); + if (!this.noAvailableServers()) { + this.server = this.getNextWsServer(); + } + // When there are no available servers, the reconnect function ends on the next recursive call + // after checking for no available servers again. + this.reconnectionAttempts = 0; + this.reconnect(); + } + else { + this.logger.log("trying to reconnect to WebSocket " + + this.server.wsUri + " (reconnection attempt " + this.reconnectionAttempts + ")"); + this.reconnectTimer = setTimeout(function () { + _this.connect(); + _this.reconnectTimer = undefined; + }, (this.reconnectionAttempts === 1) ? 0 : this.configuration.reconnectionTimeout * 1000); + } + }; + /** + * Resets the error state of all servers in the configuration + */ + Transport.prototype.resetServerErrorStatus = function () { + for (var _i = 0, _a = this.configuration.wsServers; _i < _a.length; _i++) { + var websocket = _a[_i]; + websocket.isError = false; + } + }; + /** + * Retrieve the next server to which connect. + * @param {Boolean} force allows bypass of server error status checking + * @returns {Object} WsServer + */ + Transport.prototype.getNextWsServer = function (force) { + if (force === void 0) { force = false; } + if (this.noAvailableServers()) { + this.logger.warn("attempted to get next ws server but there are no available ws servers left"); + throw new Error("Attempted to get next ws server, but there are no available ws servers left."); + } + // Order servers by weight + var candidates = []; + for (var _i = 0, _a = this.configuration.wsServers; _i < _a.length; _i++) { + var wsServer = _a[_i]; + if (wsServer.isError && !force) { + continue; + } + else if (candidates.length === 0) { + candidates.push(wsServer); + } + else if (wsServer.weight > candidates[0].weight) { + candidates = [wsServer]; + } + else if (wsServer.weight === candidates[0].weight) { + candidates.push(wsServer); + } + } + var idx = Math.floor(Math.random() * candidates.length); + return candidates[idx]; + }; + /** + * Checks all configuration servers, returns true if all of them have isError: true and false otherwise + * @returns {Boolean} + */ + Transport.prototype.noAvailableServers = function () { + for (var _i = 0, _a = this.configuration.wsServers; _i < _a.length; _i++) { + var server = _a[_i]; + if (!server.isError) { + return false; + } + } + return true; + }; + // ============================== + // KeepAlive Stuff + // ============================== + /** + * Send a keep-alive (a double-CRLF sequence). + * @returns {Boolean} + */ + Transport.prototype.sendKeepAlive = function () { + var _this = this; + if (this.keepAliveDebounceTimeout) { + // We already have an outstanding keep alive, do not send another. + return; + } + this.keepAliveDebounceTimeout = setTimeout(function () { + _this.emit("keepAliveDebounceTimeout"); + _this.clearKeepAliveTimeout(); + }, this.configuration.keepAliveDebounce * 1000); + return this.send("\r\n\r\n"); + }; + Transport.prototype.clearKeepAliveTimeout = function () { + if (this.keepAliveDebounceTimeout) { + clearTimeout(this.keepAliveDebounceTimeout); + } + this.keepAliveDebounceTimeout = undefined; + }; + /** + * Start sending keep-alives. + */ + Transport.prototype.startSendingKeepAlives = function () { + var _this = this; + if (this.configuration.keepAliveInterval && !this.keepAliveInterval) { + this.keepAliveInterval = setInterval(function () { + _this.sendKeepAlive(); + _this.startSendingKeepAlives(); + }, computeKeepAliveTimeout(this.configuration.keepAliveInterval)); + } + }; + /** + * Stop sending keep-alives. + */ + Transport.prototype.stopSendingKeepAlives = function () { + if (this.keepAliveInterval) { + clearInterval(this.keepAliveInterval); + } + if (this.keepAliveDebounceTimeout) { + clearTimeout(this.keepAliveDebounceTimeout); + } + this.keepAliveInterval = undefined; + this.keepAliveDebounceTimeout = undefined; + }; + // ============================== + // Status Stuff + // ============================== + /** + * Checks given status against instance current status. Returns true if they match + * @param {Number} status + * @param {Boolean} [force] + * @returns {Boolean} + */ + Transport.prototype.statusAssert = function (status, force) { + if (status === this.status) { + return true; + } + else { + if (force) { + this.logger.warn("Attempted to assert " + + Object.keys(TransportStatus)[this.status] + " as " + + Object.keys(TransportStatus)[status] + "- continuing with option: 'force'"); + return true; + } + else { + this.logger.warn("Tried to assert " + + Object.keys(TransportStatus)[status] + " but is currently " + + Object.keys(TransportStatus)[this.status]); + return false; + } + } + }; + /** + * Transitions the status. Checks for legal transition via assertion beforehand + * @param {Number} status + * @param {Boolean} [force] + * @returns {Boolean} + */ + Transport.prototype.statusTransition = function (status, force) { + if (force === void 0) { force = false; } + this.logger.log("Attempting to transition status from " + + Object.keys(TransportStatus)[this.status] + " to " + + Object.keys(TransportStatus)[status]); + if ((status === TransportStatus.STATUS_CONNECTING && this.statusAssert(TransportStatus.STATUS_CLOSED, force)) || + (status === TransportStatus.STATUS_OPEN && this.statusAssert(TransportStatus.STATUS_CONNECTING, force)) || + (status === TransportStatus.STATUS_CLOSING && this.statusAssert(TransportStatus.STATUS_OPEN, force)) || + (status === TransportStatus.STATUS_CLOSED)) { + this.status = status; + return true; + } + else { + this.logger.warn("Status transition failed - result: no-op - reason:" + + " either gave an nonexistent status or attempted illegal transition"); + return false; + } + }; + // ============================== + // Configuration Handling + // ============================== + /** + * Configuration load. + * returns {Configuration} + */ + Transport.prototype.loadConfig = function (configuration) { + var settings = { + wsServers: [{ + scheme: "WSS", + sipUri: "", + weight: 0, + wsUri: "wss://edge.sip.onsip.com", + isError: false + }], + connectionTimeout: 5, + maxReconnectionAttempts: 3, + reconnectionTimeout: 4, + keepAliveInterval: 0, + keepAliveDebounce: 10, + // Logging + traceSip: false + }; + var configCheck = this.getConfigurationCheck(); + // Check Mandatory parameters + for (var parameter in configCheck.mandatory) { + if (!configuration.hasOwnProperty(parameter)) { + throw new Exceptions_1.Exceptions.ConfigurationError(parameter); + } + else { + var value = configuration[parameter]; + var checkedValue = configCheck.mandatory[parameter](value); + if (checkedValue !== undefined) { + settings[parameter] = checkedValue; + } + else { + throw new Exceptions_1.Exceptions.ConfigurationError(parameter, value); + } + } + } + // Check Optional parameters + for (var parameter in configCheck.optional) { + if (configuration.hasOwnProperty(parameter)) { + var value = configuration[parameter]; + // If the parameter value is an empty array, but shouldn't be, apply its default value. + // If the parameter value is null, empty string, or undefined then apply its default value. + // If it's a number with NaN value then also apply its default value. + // NOTE: JS does not allow "value === NaN", the following does the work: + if ((value instanceof Array && value.length === 0) || + (value === null || value === "" || value === undefined) || + (typeof (value) === "number" && isNaN(value))) { + continue; + } + var checkedValue = configCheck.optional[parameter](value); + if (checkedValue !== undefined) { + settings[parameter] = checkedValue; + } + else { + throw new Exceptions_1.Exceptions.ConfigurationError(parameter, value); + } + } + } + var skeleton = {}; // Fill the value of the configuration_skeleton + for (var parameter in settings) { + if (settings.hasOwnProperty(parameter)) { + skeleton[parameter] = { + value: settings[parameter], + }; + } + } + var returnConfiguration = Object.defineProperties({}, skeleton); + this.logger.log("configuration parameters after validation:"); + for (var parameter in settings) { + if (settings.hasOwnProperty(parameter)) { + this.logger.log("· " + parameter + ": " + JSON.stringify(settings[parameter])); + } + } + return returnConfiguration; + }; + /** + * Configuration checker. + * @return {Boolean} + */ + Transport.prototype.getConfigurationCheck = function () { + return { + mandatory: {}, + optional: { + // Note: this function used to call 'this.logger.error' but calling 'this' with anything here is invalid + wsServers: function (wsServers) { + /* Allow defining wsServers parameter as: + * String: "host" + * Array of Strings: ["host1", "host2"] + * Array of Objects: [{wsUri:"host1", weight:1}, {wsUri:"host2", weight:0}] + * Array of Objects and Strings: [{wsUri:"host1"}, "host2"] + */ + if (typeof wsServers === "string") { + wsServers = [{ wsUri: wsServers }]; + } + else if (wsServers instanceof Array) { + for (var idx = 0; idx < wsServers.length; idx++) { + if (typeof wsServers[idx] === "string") { + wsServers[idx] = { wsUri: wsServers[idx] }; + } + } + } + else { + return; + } + if (wsServers.length === 0) { + return false; + } + for (var _i = 0, wsServers_1 = wsServers; _i < wsServers_1.length; _i++) { + var wsServer = wsServers_1[_i]; + if (!wsServer.wsUri) { + return; + } + if (wsServer.weight && !Number(wsServer.weight)) { + return; + } + var url = Grammar_1.Grammar.parse(wsServer.wsUri, "absoluteURI"); + if (url === -1) { + return; + } + else if (["wss", "ws", "udp"].indexOf(url.scheme) < 0) { + return; + } + else { + wsServer.sipUri = ""; + if (!wsServer.weight) { + wsServer.weight = 0; + } + wsServer.isError = false; + wsServer.scheme = url.scheme.toUpperCase(); + } + } + return wsServers; + }, + keepAliveInterval: function (keepAliveInterval) { + if (Utils_1.Utils.isDecimal(keepAliveInterval)) { + var value = Number(keepAliveInterval); + if (value > 0) { + return value; + } + } + }, + keepAliveDebounce: function (keepAliveDebounce) { + if (Utils_1.Utils.isDecimal(keepAliveDebounce)) { + var value = Number(keepAliveDebounce); + if (value > 0) { + return value; + } + } + }, + traceSip: function (traceSip) { + if (typeof traceSip === "boolean") { + return traceSip; + } + }, + connectionTimeout: function (connectionTimeout) { + if (Utils_1.Utils.isDecimal(connectionTimeout)) { + var value = Number(connectionTimeout); + if (value > 0) { + return value; + } + } + }, + maxReconnectionAttempts: function (maxReconnectionAttempts) { + if (Utils_1.Utils.isDecimal(maxReconnectionAttempts)) { + var value = Number(maxReconnectionAttempts); + if (value >= 0) { + return value; + } + } + }, + reconnectionTimeout: function (reconnectionTimeout) { + if (Utils_1.Utils.isDecimal(reconnectionTimeout)) { + var value = Number(reconnectionTimeout); + if (value > 0) { + return value; + } + } + } + } + }; + }; + Transport.C = TransportStatus; + return Transport; +}(Transport_1.Transport)); +exports.Transport = Transport; diff --git a/lib/Web/index.d.ts b/lib/Web/index.d.ts new file mode 100644 index 000000000..ffd3a7a3b --- /dev/null +++ b/lib/Web/index.d.ts @@ -0,0 +1,5 @@ +import * as Modifiers from "./Modifiers"; +export { Modifiers }; +export { Simple } from "./Simple"; +export { SessionDescriptionHandler } from "./SessionDescriptionHandler"; +export { Transport } from "./Transport"; diff --git a/lib/Web/index.js b/lib/Web/index.js new file mode 100644 index 000000000..2247b8ee5 --- /dev/null +++ b/lib/Web/index.js @@ -0,0 +1,10 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var Modifiers = require("./Modifiers"); +exports.Modifiers = Modifiers; +var Simple_1 = require("./Simple"); +exports.Simple = Simple_1.Simple; +var SessionDescriptionHandler_1 = require("./SessionDescriptionHandler"); +exports.SessionDescriptionHandler = SessionDescriptionHandler_1.SessionDescriptionHandler; +var Transport_1 = require("./Transport"); +exports.Transport = Transport_1.Transport; diff --git a/lib/index.d.ts b/lib/index.d.ts new file mode 100644 index 000000000..c7bec83d9 --- /dev/null +++ b/lib/index.d.ts @@ -0,0 +1,36 @@ +export { ClientContext } from "./ClientContext"; +export { C } from "./Constants"; +export { DigestAuthentication } from "./DigestAuthentication"; +export { DialogStatus, SessionStatus, TypeStrings, UAStatus } from "./Enums"; +export { Exceptions } from "./Exceptions"; +export { Grammar } from "./Grammar"; +export { LoggerFactory } from "./LoggerFactory"; +export { NameAddrHeader } from "./NameAddrHeader"; +export { Parser } from "./Parser"; +export { PublishContext } from "./PublishContext"; +export { ReferClientContext, ReferServerContext } from "./ReferContext"; +export { RegisterContext } from "./RegisterContext"; +export { ServerContext } from "./ServerContext"; +export { InviteClientContext, InviteServerContext, Session } from "./Session"; +export { SessionDescriptionHandlerFactory, SessionDescriptionHandlerFactoryOptions } from "./session-description-handler-factory"; +export { SessionDescriptionHandler, SessionDescriptionHandlerModifier, SessionDescriptionHandlerModifiers, SessionDescriptionHandlerOptions } from "./session-description-handler"; +export { IncomingRequest, IncomingResponse, OutgoingRequest } from "./SIPMessage"; +export { Subscription } from "./Subscription"; +export { Timers } from "./Timers"; +import { InviteClientTransaction, InviteServerTransaction, NonInviteClientTransaction, NonInviteServerTransaction } from "./Core/transactions"; +declare const Transactions: { + InviteClientTransaction: typeof InviteClientTransaction; + InviteServerTransaction: typeof InviteServerTransaction; + NonInviteClientTransaction: typeof NonInviteClientTransaction; + NonInviteServerTransaction: typeof NonInviteServerTransaction; +}; +export { Transactions }; +export { Transport } from "./Transport"; +export { UA } from "./UA"; +export { URI } from "./URI"; +export { Utils } from "./Utils"; +import * as Web from "./Web/index"; +export { Web }; +declare const name: any; +declare const version: any; +export { name, version }; diff --git a/lib/index.js b/lib/index.js new file mode 100644 index 000000000..3da7f9bc7 --- /dev/null +++ b/lib/index.js @@ -0,0 +1,68 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var ClientContext_1 = require("./ClientContext"); +exports.ClientContext = ClientContext_1.ClientContext; +var Constants_1 = require("./Constants"); +exports.C = Constants_1.C; +var DigestAuthentication_1 = require("./DigestAuthentication"); +exports.DigestAuthentication = DigestAuthentication_1.DigestAuthentication; +var Enums_1 = require("./Enums"); +exports.DialogStatus = Enums_1.DialogStatus; +exports.SessionStatus = Enums_1.SessionStatus; +exports.TypeStrings = Enums_1.TypeStrings; +exports.UAStatus = Enums_1.UAStatus; +var Exceptions_1 = require("./Exceptions"); +exports.Exceptions = Exceptions_1.Exceptions; +var Grammar_1 = require("./Grammar"); +exports.Grammar = Grammar_1.Grammar; +var LoggerFactory_1 = require("./LoggerFactory"); +exports.LoggerFactory = LoggerFactory_1.LoggerFactory; +var NameAddrHeader_1 = require("./NameAddrHeader"); +exports.NameAddrHeader = NameAddrHeader_1.NameAddrHeader; +var Parser_1 = require("./Parser"); +exports.Parser = Parser_1.Parser; +var PublishContext_1 = require("./PublishContext"); +exports.PublishContext = PublishContext_1.PublishContext; +var ReferContext_1 = require("./ReferContext"); +exports.ReferClientContext = ReferContext_1.ReferClientContext; +exports.ReferServerContext = ReferContext_1.ReferServerContext; +var RegisterContext_1 = require("./RegisterContext"); +exports.RegisterContext = RegisterContext_1.RegisterContext; +var ServerContext_1 = require("./ServerContext"); +exports.ServerContext = ServerContext_1.ServerContext; +var Session_1 = require("./Session"); +exports.InviteClientContext = Session_1.InviteClientContext; +exports.InviteServerContext = Session_1.InviteServerContext; +exports.Session = Session_1.Session; +var SIPMessage_1 = require("./SIPMessage"); +exports.IncomingRequest = SIPMessage_1.IncomingRequest; +exports.IncomingResponse = SIPMessage_1.IncomingResponse; +exports.OutgoingRequest = SIPMessage_1.OutgoingRequest; +var Subscription_1 = require("./Subscription"); +exports.Subscription = Subscription_1.Subscription; +var Timers_1 = require("./Timers"); +exports.Timers = Timers_1.Timers; +var transactions_1 = require("./Core/transactions"); +var Transactions = { + InviteClientTransaction: transactions_1.InviteClientTransaction, + InviteServerTransaction: transactions_1.InviteServerTransaction, + NonInviteClientTransaction: transactions_1.NonInviteClientTransaction, + NonInviteServerTransaction: transactions_1.NonInviteServerTransaction +}; +exports.Transactions = Transactions; +var Transport_1 = require("./Transport"); +exports.Transport = Transport_1.Transport; +var UA_1 = require("./UA"); +exports.UA = UA_1.UA; +var URI_1 = require("./URI"); +exports.URI = URI_1.URI; +var Utils_1 = require("./Utils"); +exports.Utils = Utils_1.Utils; +var Web = require("./Web/index"); +exports.Web = Web; +// tslint:disable-next-line:no-var-requires +var pkg = require("../package.json"); +var name = pkg.title; +exports.name = name; +var version = pkg.version; +exports.version = version; diff --git a/lib/session-description-handler-factory.d.ts b/lib/session-description-handler-factory.d.ts new file mode 100644 index 000000000..1190223b3 --- /dev/null +++ b/lib/session-description-handler-factory.d.ts @@ -0,0 +1,14 @@ +import { InviteClientContext, InviteServerContext } from "./Session"; +import { SessionDescriptionHandler } from "./session-description-handler"; +/** + * The SessionDescriptionHandlerFactory interface SIP.js is expecting. + */ +export interface SessionDescriptionHandlerFactory { + (session: InviteClientContext | InviteServerContext, options?: SessionDescriptionHandlerFactoryOptions): SessionDescriptionHandler; +} +/** + * SessionDescriptionHandlerFactory options. + * These options are provided as part of the UserAgent configuration + * and passed through on every call to SessionDescriptionHandlerFactory's constructor. + */ +export declare type SessionDescriptionHandlerFactoryOptions = object; diff --git a/lib/session-description-handler-factory.js b/lib/session-description-handler-factory.js new file mode 100644 index 000000000..c8ad2e549 --- /dev/null +++ b/lib/session-description-handler-factory.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/session-description-handler-observer.d.ts b/lib/session-description-handler-observer.d.ts new file mode 100644 index 000000000..335664627 --- /dev/null +++ b/lib/session-description-handler-observer.d.ts @@ -0,0 +1,8 @@ +import { TypeStrings } from "./Enums"; +import { InviteClientContext, InviteServerContext } from "./Session"; +export declare class SessionDescriptionHandlerObserver { + type: TypeStrings; + constructor(session: InviteClientContext | InviteServerContext, options: any); + trackAdded(): void; + directionChanged(): void; +} diff --git a/lib/session-description-handler-observer.js b/lib/session-description-handler-observer.js new file mode 100644 index 000000000..c8ad2e549 --- /dev/null +++ b/lib/session-description-handler-observer.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/session-description-handler.d.ts b/lib/session-description-handler.d.ts new file mode 100644 index 000000000..3f8464a7a --- /dev/null +++ b/lib/session-description-handler.d.ts @@ -0,0 +1,73 @@ +/** + * The SessionDescriptionHandler interface SIP.js is expecting. + */ +export interface SessionDescriptionHandler { + /** + * Destructor. + */ + close(): void; + /** + * Gets the local description from the underlying media implementation. + * @param options Options object to be used by getDescription. + * @param modifiers Array with one time use description modifiers. + * @returns Promise that resolves with the local description to be used for the session. + * @throws {ClosedSessionDescriptionHandlerError} When this method + * is called after close or when close occurs before complete. + */ + getDescription(options?: SessionDescriptionHandlerOptions, modifiers?: SessionDescriptionHandlerModifiers): Promise; + /** + * Returns true if the Session Description Handler can handle the Content-Type described by a SIP message. + * @param contentType The content type that is in the SIP Message. + * @returns True if the content type is handled by this session description handler. False otherwise. + */ + hasDescription(contentType: string): boolean; + /** + * The modifier that should be used when the session would like to place the call on hold. + * @param sessionDescription The description that will be modified. + * @returns Promise that resolves with modified SDP. + * @throws {ClosedSessionDescriptionHandlerError} When this method + * is called after close or when close occurs before complete. + */ + holdModifier(sessionDescription: RTCSessionDescriptionInit): Promise; + /** + * Sets the remote description to the underlying media implementation. + * @param sessionDescription The description provided by a SIP message to be set on the media implementation. + * @param options Options object to be used by setDescription. + * @param modifiers Array with one time use description modifiers. + * @returns Promise that resolves once the description is set. + * @throws {ClosedSessionDescriptionHandlerError} When this method + * is called after close or when close occurs before complete. + */ + setDescription(sdp: string, options?: SessionDescriptionHandlerOptions, modifiers?: SessionDescriptionHandlerModifiers): Promise; + /** + * Send DTMF via RTP (RFC 4733). + * Returns true if DTMF send is successful, false otherwise. + * @param tones A string containing DTMF digits. + * @param options Options object to be used by sendDtmf. + * @returns True if DTMF send is successful, false otherwise. + */ + sendDtmf(tones: string, options?: any): boolean; +} +export interface SessionDescriptionHandlerModifier { + (sessionDescription: RTCSessionDescriptionInit): Promise; +} +export declare type SessionDescriptionHandlerModifiers = Array; +/** + * SessionDescriptionHandler options. + * These options are provided to various UserAgent methods (invite() for example) + * and passed through on calls to getDescription() and setDescription(). + */ +export interface SessionDescriptionHandlerOptions { + modifiers?: SessionDescriptionHandlerModifiers; + constraints?: { + audio: boolean; + video: boolean; + }; +} +/** + * SIP message body and content type. + */ +export interface BodyObj { + body: string; + contentType: string; +} diff --git a/lib/session-description-handler.js b/lib/session-description-handler.js new file mode 100644 index 000000000..993644a62 --- /dev/null +++ b/lib/session-description-handler.js @@ -0,0 +1,3 @@ +"use strict"; +// tslint:disable:callable-types +Object.defineProperty(exports, "__esModule", { value: true });