Commit 12ca21a for jssip.net
commit 12ca21a86b54b9ea0fa25b387ffb25ca17a1eb9c
Author: José Luis Millán <jmillan@aliax.net>
Date: Tue Dec 1 17:09:43 2026 +0100
TS: Dialog and Dialog/RequestSender (#1002)
diff --git a/src/Dialog.js b/src/Dialog.js
deleted file mode 100644
index e2d2596..0000000
--- a/src/Dialog.js
+++ /dev/null
@@ -1,310 +0,0 @@
-const { Logger } = require('./Logger');
-const SIPMessage = require('./SIPMessage');
-const JsSIP_C = require('./Constants');
-const Transactions = require('./Transactions');
-const Dialog_RequestSender = require('./Dialog/RequestSender');
-const Utils = require('./Utils');
-
-const logger = new Logger('Dialog');
-
-const C = {
- // Dialog states.
- STATUS_EARLY: 1,
- STATUS_CONFIRMED: 2,
- STATUS_TERMINATED: 3,
-};
-
-// RFC 3261 12.1.
-module.exports = class Dialog {
- // Expose C object.
- static get C() {
- return C;
- }
-
- constructor(owner, message, type, state = C.STATUS_CONFIRMED) {
- this._owner = owner;
- this._ua = owner._ua;
-
- this._uac_pending_reply = false;
- this._uas_pending_reply = false;
-
- if (!message.hasHeader('contact')) {
- return {
- error: 'unable to create a Dialog without Contact header field',
- };
- }
-
- if (message instanceof SIPMessage.IncomingResponse) {
- state = message.status_code < 200 ? C.STATUS_EARLY : C.STATUS_CONFIRMED;
- }
-
- const contact = message.parseHeader('contact');
-
- // RFC 3261 12.1.1.
- if (type === 'UAS') {
- this._id = {
- call_id: message.call_id,
- local_tag: message.to_tag,
- remote_tag: message.from_tag,
- toString() {
- return this.call_id + this.local_tag + this.remote_tag;
- },
- };
- this._state = state;
- this._remote_seqnum = message.cseq;
- this._local_uri = message.parseHeader('to').uri;
- this._remote_uri = message.parseHeader('from').uri;
- this._remote_target = contact.uri;
- this._route_set = message.getHeaders('record-route');
- this._incoming_ack_seqnum = message.cseq;
- this._outgoing_ack_seqnum = null;
- }
- // RFC 3261 12.1.2.
- else if (type === 'UAC') {
- this._id = {
- call_id: message.call_id,
- local_tag: message.from_tag,
- remote_tag: message.to_tag,
- toString() {
- return this.call_id + this.local_tag + this.remote_tag;
- },
- };
- this._state = state;
- this._local_seqnum = message.cseq;
- this._local_uri = message.parseHeader('from').uri;
- this._remote_uri = message.parseHeader('to').uri;
- this._remote_target = contact.uri;
- this._route_set = message.getHeaders('record-route').reverse();
- this._incoming_ack_seqnum = null;
- this._outgoing_ack_seqnum = this._local_seqnum;
- }
-
- this._ua.newDialog(this);
- logger.debug(
- `new ${type} dialog created with status ${this._state === C.STATUS_EARLY ? 'EARLY' : 'CONFIRMED'}`
- );
- }
-
- get id() {
- return this._id;
- }
-
- get local_seqnum() {
- return this._local_seqnum;
- }
-
- set local_seqnum(num) {
- this._local_seqnum = num;
- }
-
- get owner() {
- return this._owner;
- }
-
- get uac_pending_reply() {
- return this._uac_pending_reply;
- }
-
- set uac_pending_reply(pending) {
- this._uac_pending_reply = pending;
- }
-
- get uas_pending_reply() {
- return this._uas_pending_reply;
- }
-
- isTerminated() {
- return this._state === C.STATUS_TERMINATED;
- }
-
- update(message, type) {
- this._state = C.STATUS_CONFIRMED;
-
- logger.debug(`dialog ${this._id.toString()} changed to CONFIRMED state`);
-
- if (type === 'UAC') {
- // RFC 3261 13.2.2.4.
- this._route_set = message.getHeaders('record-route').reverse();
- }
- }
-
- terminate() {
- logger.debug(`dialog ${this._id.toString()} deleted`);
-
- this._ua.destroyDialog(this);
- this._state = C.STATUS_TERMINATED;
- }
-
- sendRequest(method, options = {}) {
- const extraHeaders = Utils.cloneArray(options.extraHeaders);
- const eventHandlers = Utils.cloneObject(options.eventHandlers);
- const body = options.body || null;
- const request = this._createRequest(method, extraHeaders, body);
-
- // Some usages may need to know about authentication.
- const onAuthenticated = eventHandlers.onAuthenticated || (() => {});
-
- // Increase the local CSeq on authentication.
- eventHandlers.onAuthenticated = _request => {
- this._local_seqnum += 1;
-
- // In case of re-INVITE store outgoing ack_seqnum for its CANCEL or ACK.
- if (request.method === JsSIP_C.INVITE) {
- this._outgoing_ack_seqnum = this._local_seqnum;
- }
-
- onAuthenticated(_request);
- };
-
- const request_sender = new Dialog_RequestSender(
- this,
- request,
- eventHandlers
- );
-
- request_sender.send();
-
- // Return the instance of OutgoingRequest.
- return request;
- }
-
- receiveRequest(request) {
- // Check in-dialog request.
- if (!this._checkInDialogRequest(request)) {
- return;
- }
-
- // ACK received. Cleanup this._ack_seqnum.
- if (request.method === JsSIP_C.ACK && this._incoming_ack_seqnum !== null) {
- this._incoming_ack_seqnum = null;
- }
- // INVITE received. Set this._ack_seqnum.
- else if (request.method === JsSIP_C.INVITE) {
- this._incoming_ack_seqnum = request.cseq;
- }
-
- this._owner.receiveRequest(request);
- }
-
- // RFC 3261 12.2.1.1.
- _createRequest(method, extraHeaders, body) {
- extraHeaders = Utils.cloneArray(extraHeaders);
-
- if (!this._local_seqnum) {
- this._local_seqnum = Math.floor(Math.random() * 10000);
- }
-
- // CANCEL and ACK must use the same sequence number as the INVITE.
- const cseq =
- method === JsSIP_C.CANCEL || method === JsSIP_C.ACK
- ? this._outgoing_ack_seqnum
- : (this._local_seqnum += 1);
-
- // In case of re-INVITE store ack_seqnum for future CANCEL or ACK.
- if (method === JsSIP_C.INVITE) {
- this._outgoing_ack_seqnum = cseq;
- }
-
- const request = new SIPMessage.OutgoingRequest(
- method,
- this._remote_target,
- this._ua,
- {
- cseq: cseq,
- call_id: this._id.call_id,
- from_uri: this._local_uri,
- from_tag: this._id.local_tag,
- to_uri: this._remote_uri,
- to_tag: this._id.remote_tag,
- route_set: this._route_set,
- },
- extraHeaders,
- body
- );
-
- return request;
- }
-
- // RFC 3261 12.2.2.
- _checkInDialogRequest(request) {
- if (!this._remote_seqnum) {
- this._remote_seqnum = request.cseq;
- } else if (request.cseq < this._remote_seqnum) {
- if (request.method === JsSIP_C.ACK) {
- // We are not expecting any ACK with lower seqnum than the current one.
- // Or this is not the ACK we are waiting for.
- if (
- this._incoming_ack_seqnum === null ||
- request.cseq !== this._incoming_ack_seqnum
- ) {
- return false;
- }
- } else {
- request.reply(500);
-
- return false;
- }
- } else if (request.cseq > this._remote_seqnum) {
- this._remote_seqnum = request.cseq;
- }
-
- // RFC3261 14.2 Modifying an Existing Session -UAS BEHAVIOR-.
- if (
- request.method === JsSIP_C.INVITE ||
- (request.method === JsSIP_C.UPDATE && request.body)
- ) {
- if (this._uac_pending_reply === true) {
- request.reply(491);
- } else if (this._uas_pending_reply === true) {
- const retryAfter = ((Math.random() * 10) | 0) + 1;
-
- request.reply(500, null, [`Retry-After:${retryAfter}`]);
-
- return false;
- } else {
- this._uas_pending_reply = true;
-
- const stateChanged = () => {
- if (
- request.server_transaction.state === Transactions.Status.ACCEPTED ||
- request.server_transaction.state ===
- Transactions.Status.COMPLETED ||
- request.server_transaction.state === Transactions.Status.TERMINATED
- ) {
- request.server_transaction.removeListener(
- 'stateChanged',
- stateChanged
- );
- this._uas_pending_reply = false;
- }
- };
-
- request.server_transaction.on('stateChanged', stateChanged);
- }
-
- // RFC3261 12.2.2 Replace the dialog`s remote target URI if the request is accepted.
- if (request.hasHeader('contact')) {
- request.server_transaction.on('stateChanged', () => {
- if (
- request.server_transaction.state === Transactions.Status.ACCEPTED
- ) {
- this._remote_target = request.parseHeader('contact').uri;
- }
- });
- }
- } else if (request.method === JsSIP_C.NOTIFY) {
- // RFC6665 3.2 Replace the dialog`s remote target URI if the request is accepted.
- if (request.hasHeader('contact')) {
- request.server_transaction.on('stateChanged', () => {
- if (
- request.server_transaction.state === Transactions.Status.COMPLETED
- ) {
- this._remote_target = request.parseHeader('contact').uri;
- }
- });
- }
- }
-
- return true;
- }
-};
diff --git a/src/Dialog.ts b/src/Dialog.ts
new file mode 100644
index 0000000..60c7d2b
--- /dev/null
+++ b/src/Dialog.ts
@@ -0,0 +1,470 @@
+import * as JsSIP_C from './Constants';
+import { DialogRequestSender } from './Dialog/RequestSender';
+import type { DialogRequestSenderEventHandlers } from './Dialog/RequestSender';
+import { Logger } from './Logger';
+import type { RequestSenderUA } from './RequestSender';
+import * as SIPMessage from './SIPMessage';
+import type { IncomingMessage, IncomingRequest } from './SIPMessage';
+import * as Transactions from './Transactions';
+import * as Utils from './Utils';
+import NameAddrHeader = require('./NameAddrHeader');
+import URI = require('./URI');
+
+const logger = new Logger('Dialog');
+
+/**
+ * Dialog states.
+ */
+export enum Status {
+ EARLY = 1,
+ CONFIRMED = 2,
+ TERMINATED = 3,
+}
+
+/**
+ * Why a dialog could not be created. Reported by the `DialogError` carrying
+ * it, both as its `reason` and as its `message`.
+ */
+export enum DialogErrorReason {
+ NO_CONTACT = 'missing Contact header field',
+ NO_ID = 'missing Call-ID or tags',
+}
+
+/**
+ * Thrown by `Dialog.Create()` when the message cannot establish a dialog.
+ */
+export class DialogError extends Error {
+ override name = 'DIALOG_ERROR';
+ readonly reason: DialogErrorReason;
+
+ constructor(reason: DialogErrorReason) {
+ super(reason);
+
+ this.reason = reason;
+ }
+}
+
+/**
+ * Which side of the dialog the local peer is on. RFC 3261 12.1.1 and 12.1.2.
+ */
+export type DialogType = 'UAS' | 'UAC';
+
+/**
+ * RFC 3261 12.1 dialog id. Its `toString()` is the key the `UA` indexes
+ * dialogs by.
+ *
+ */
+export type DialogId = {
+ call_id: string;
+ local_tag: string;
+ remote_tag: string;
+ toString(): string;
+};
+
+/**
+ * The `UA` surface a dialog depends on.
+ *
+ * TODO: Replace with `import type { UA } from './UA'` once `UA` is ported to
+ * TypeScript.
+ */
+export interface DialogUA extends RequestSenderUA {
+ newDialog(dialog: Dialog): void;
+ destroyDialog(dialog: Dialog): void;
+}
+
+/**
+ * The dialog usage that owns the dialog and gets its in-dialog requests.
+ *
+ * TODO: Replace with a `RTCSession | Subscriber | Notifier` union once those
+ * modules are ported to TypeScript.
+ */
+export interface DialogOwner {
+ readonly _ua: DialogUA;
+
+ receiveRequest(request: IncomingRequest): void;
+}
+
+/**
+ * Options accepted by `sendRequest()`.
+ */
+export type DialogSendRequestOptions = {
+ extraHeaders?: string[] | null;
+ eventHandlers?: Partial<DialogRequestSenderEventHandlers> | null;
+ body?: string | null;
+};
+
+// RFC 3261 12.1.
+export class Dialog {
+ /**
+ * Create a dialog out of the given message.
+ *
+ * -throws {DialogError} if the message cannot establish a dialog.
+ */
+ static Create(
+ owner: DialogOwner,
+ message: IncomingMessage,
+ type: DialogType,
+ state: Status = Status.CONFIRMED
+ ): Dialog {
+ if (!message.hasHeader('contact')) {
+ const error = new DialogError(DialogErrorReason.NO_CONTACT);
+
+ logger.warn(
+ 'Create() | cannot create %s dialog [reason:%s]',
+ type,
+ error.reason
+ );
+
+ throw error;
+ }
+
+ // RFC 3261 12.1.1 and 12.1.2.
+ const call_id = message.call_id;
+ const local_tag = type === 'UAS' ? message.to_tag : message.from_tag;
+ const remote_tag = type === 'UAS' ? message.from_tag : message.to_tag;
+
+ if (!call_id || !local_tag || !remote_tag) {
+ const error = new DialogError(DialogErrorReason.NO_ID);
+
+ logger.warn(
+ 'Create() | cannot create %s dialog [reason:%s]',
+ type,
+ error.reason
+ );
+
+ throw error;
+ }
+
+ const id: DialogId = {
+ call_id,
+ local_tag,
+ remote_tag,
+ toString() {
+ return this.call_id + this.local_tag + this.remote_tag;
+ },
+ };
+
+ return new Dialog(owner, message, type, state, id);
+ }
+
+ #owner: DialogOwner;
+ #ua: DialogUA;
+
+ #uac_pending_reply = false;
+ #uas_pending_reply = false;
+
+ #incoming_ack_seqnum: number | null = null;
+ #outgoing_ack_seqnum: number | null = null;
+
+ /* NOTE: Only set while there is a sequence number to remember.
+ * `#local_seqnum` is lazily initialized by `#createRequest()` on dialogs
+ * created by an incoming request.
+ */
+ #local_seqnum?: number;
+ #remote_seqnum?: number;
+
+ #id: DialogId;
+ #state: Status;
+ #local_uri: URI;
+ #remote_uri: URI;
+ #remote_target: URI;
+ #route_set: string[];
+
+ /**
+ * NOTE: Private so that a dialog can only be built through `Create()`, which
+ * is the one that rejects a message that cannot establish one. That is what
+ * lets every field above be definitely assigned.
+ */
+ private constructor(
+ owner: DialogOwner,
+ message: IncomingMessage,
+ type: DialogType,
+ state: Status,
+ id: DialogId
+ ) {
+ this.#owner = owner;
+ this.#ua = owner._ua;
+ this.#id = id;
+
+ if (message instanceof SIPMessage.IncomingResponse) {
+ state = message.status_code < 200 ? Status.EARLY : Status.CONFIRMED;
+ }
+
+ /* NOTE: The non-null assertions below mirror the original implementation,
+ * which throws if a mandatory header field is missing or unparseable.
+ */
+ const contact = message.parseHeader<NameAddrHeader>('contact')!;
+
+ // RFC 3261 12.1.1.
+ if (type === 'UAS') {
+ this.#state = state;
+ this.#remote_seqnum = message.cseq;
+ this.#local_uri = message.parseHeader<NameAddrHeader>('to')!.uri;
+ this.#remote_uri = message.parseHeader<NameAddrHeader>('from')!.uri;
+ this.#remote_target = contact.uri;
+ this.#route_set = message.getHeaders('record-route');
+ this.#incoming_ack_seqnum = message.cseq ?? null;
+ this.#outgoing_ack_seqnum = null;
+ }
+ // RFC 3261 12.1.2.
+ else {
+ this.#state = state;
+ this.#local_seqnum = message.cseq;
+ this.#local_uri = message.parseHeader<NameAddrHeader>('from')!.uri;
+ this.#remote_uri = message.parseHeader<NameAddrHeader>('to')!.uri;
+ this.#remote_target = contact.uri;
+ this.#route_set = message.getHeaders('record-route').reverse();
+ this.#incoming_ack_seqnum = null;
+ this.#outgoing_ack_seqnum = this.#local_seqnum ?? null;
+ }
+
+ this.#ua.newDialog(this);
+ logger.debug(
+ `new ${type} dialog created with status ${this.#state === Status.EARLY ? 'EARLY' : 'CONFIRMED'}`
+ );
+ }
+
+ get id(): DialogId {
+ return this.#id;
+ }
+
+ /**
+ * NOTE: `Dialog/RequestSender` reads it.
+ */
+ get ua(): DialogUA {
+ return this.#ua;
+ }
+
+ get local_seqnum(): number | undefined {
+ return this.#local_seqnum;
+ }
+
+ set local_seqnum(num: number | undefined) {
+ this.#local_seqnum = num;
+ }
+
+ get owner(): DialogOwner {
+ return this.#owner;
+ }
+
+ get uac_pending_reply(): boolean {
+ return this.#uac_pending_reply;
+ }
+
+ set uac_pending_reply(pending: boolean) {
+ this.#uac_pending_reply = pending;
+ }
+
+ get uas_pending_reply(): boolean {
+ return this.#uas_pending_reply;
+ }
+
+ isTerminated(): boolean {
+ return this.#state === Status.TERMINATED;
+ }
+
+ update(message: IncomingMessage, type: DialogType): void {
+ this.#state = Status.CONFIRMED;
+
+ logger.debug(`dialog ${this.#id.toString()} changed to CONFIRMED state`);
+
+ if (type === 'UAC') {
+ // RFC 3261 13.2.2.4.
+ this.#route_set = message.getHeaders('record-route').reverse();
+ }
+ }
+
+ terminate(): void {
+ logger.debug(`dialog ${this.#id.toString()} deleted`);
+
+ this.#ua.destroyDialog(this);
+ this.#state = Status.TERMINATED;
+ }
+
+ sendRequest(
+ method: string,
+ options: DialogSendRequestOptions = {}
+ ): SIPMessage.OutgoingRequest {
+ const extraHeaders = Utils.cloneArray(options.extraHeaders);
+ const eventHandlers = Utils.cloneObject(options.eventHandlers);
+ const body = options.body || undefined;
+ const request = this.#createRequest(method, extraHeaders, body);
+
+ // Some usages may need to know about authentication.
+ const onAuthenticated = eventHandlers.onAuthenticated || (() => {});
+
+ // Increase the local CSeq on authentication.
+ eventHandlers.onAuthenticated = _request => {
+ /* NOTE: `#createRequest()` above made sure there is a local sequence
+ * number.
+ */
+ this.#local_seqnum = (this.#local_seqnum ?? 0) + 1;
+
+ // In case of re-INVITE store outgoing ack_seqnum for its CANCEL or ACK.
+ if (request.method === JsSIP_C.INVITE) {
+ this.#outgoing_ack_seqnum = this.#local_seqnum;
+ }
+
+ onAuthenticated(_request);
+ };
+
+ const request_sender = new DialogRequestSender(
+ this,
+ request,
+ eventHandlers
+ );
+
+ request_sender.send();
+
+ // Return the instance of OutgoingRequest.
+ return request;
+ }
+
+ receiveRequest(request: IncomingRequest): void {
+ // Check in-dialog request.
+ if (!this.#checkInDialogRequest(request)) {
+ return;
+ }
+
+ // ACK received. Cleanup this.#incoming_ack_seqnum.
+ if (request.method === JsSIP_C.ACK && this.#incoming_ack_seqnum !== null) {
+ this.#incoming_ack_seqnum = null;
+ }
+ // INVITE received. Set this.#incoming_ack_seqnum.
+ else if (request.method === JsSIP_C.INVITE) {
+ this.#incoming_ack_seqnum = request.cseq ?? null;
+ }
+
+ this.#owner.receiveRequest(request);
+ }
+
+ // RFC 3261 12.2.1.1.
+ #createRequest(
+ method: string,
+ extraHeaders: string[],
+ body?: string
+ ): SIPMessage.OutgoingRequest {
+ extraHeaders = Utils.cloneArray(extraHeaders);
+
+ if (!this.#local_seqnum) {
+ this.#local_seqnum = Math.floor(Math.random() * 10000);
+ }
+
+ // CANCEL and ACK must use the same sequence number as the INVITE.
+ const cseq =
+ method === JsSIP_C.CANCEL || method === JsSIP_C.ACK
+ ? this.#outgoing_ack_seqnum
+ : (this.#local_seqnum += 1);
+
+ // In case of re-INVITE store ack_seqnum for future CANCEL or ACK.
+ if (method === JsSIP_C.INVITE) {
+ this.#outgoing_ack_seqnum = cseq;
+ }
+
+ const request = new SIPMessage.OutgoingRequest(
+ method,
+ this.#remote_target,
+ this.#ua,
+ {
+ cseq: cseq ?? undefined,
+ call_id: this.#id.call_id,
+ from_uri: this.#local_uri,
+ from_tag: this.#id.local_tag,
+ to_uri: this.#remote_uri,
+ to_tag: this.#id.remote_tag,
+ route_set: this.#route_set,
+ },
+ extraHeaders,
+ body
+ );
+
+ return request;
+ }
+
+ // RFC 3261 12.2.2.
+ #checkInDialogRequest(request: IncomingRequest): boolean {
+ /* NOTE: CSeq is a mandatory header field, so `sanityCheck` already dropped
+ * the request if it had none.
+ */
+ const cseq = request.cseq!;
+
+ if (!this.#remote_seqnum) {
+ this.#remote_seqnum = cseq;
+ } else if (cseq < this.#remote_seqnum) {
+ if (request.method === JsSIP_C.ACK) {
+ // We are not expecting any ACK with lower seqnum than the current one.
+ // Or this is not the ACK we are waiting for.
+ if (
+ this.#incoming_ack_seqnum === null ||
+ cseq !== this.#incoming_ack_seqnum
+ ) {
+ return false;
+ }
+ } else {
+ request.reply(500);
+
+ return false;
+ }
+ } else if (cseq > this.#remote_seqnum) {
+ this.#remote_seqnum = cseq;
+ }
+
+ /* NOTE: An in-dialog request always reaches the dialog through its server
+ * transaction, which the `UA` creates before routing it.
+ */
+ const server_transaction = request.server_transaction!;
+
+ // RFC3261 14.2 Modifying an Existing Session -UAS BEHAVIOR-.
+ if (
+ request.method === JsSIP_C.INVITE ||
+ (request.method === JsSIP_C.UPDATE && request.body)
+ ) {
+ if (this.#uac_pending_reply === true) {
+ request.reply(491);
+ } else if (this.#uas_pending_reply === true) {
+ const retryAfter = ((Math.random() * 10) | 0) + 1;
+
+ request.reply(500, null, [`Retry-After:${retryAfter}`]);
+
+ return false;
+ } else {
+ this.#uas_pending_reply = true;
+
+ const stateChanged = (): void => {
+ if (
+ server_transaction.state === Transactions.Status.ACCEPTED ||
+ server_transaction.state === Transactions.Status.COMPLETED ||
+ server_transaction.state === Transactions.Status.TERMINATED
+ ) {
+ server_transaction.removeListener('stateChanged', stateChanged);
+ this.#uas_pending_reply = false;
+ }
+ };
+
+ server_transaction.on('stateChanged', stateChanged);
+ }
+
+ // RFC3261 12.2.2 Replace the dialog`s remote target URI if the request is accepted.
+ if (request.hasHeader('contact')) {
+ server_transaction.on('stateChanged', () => {
+ if (server_transaction.state === Transactions.Status.ACCEPTED) {
+ this.#remote_target =
+ request.parseHeader<NameAddrHeader>('contact')!.uri;
+ }
+ });
+ }
+ } else if (request.method === JsSIP_C.NOTIFY) {
+ // RFC6665 3.2 Replace the dialog`s remote target URI if the request is accepted.
+ if (request.hasHeader('contact')) {
+ server_transaction.on('stateChanged', () => {
+ if (server_transaction.state === Transactions.Status.COMPLETED) {
+ this.#remote_target =
+ request.parseHeader<NameAddrHeader>('contact')!.uri;
+ }
+ });
+ }
+ }
+
+ return true;
+ }
+}
diff --git a/src/Dialog/RequestSender.js b/src/Dialog/RequestSender.js
deleted file mode 100644
index d846302..0000000
--- a/src/Dialog/RequestSender.js
+++ /dev/null
@@ -1,112 +0,0 @@
-const JsSIP_C = require('../Constants');
-const Transactions = require('../Transactions');
-const { RequestSender } = require('../RequestSender');
-
-// Default event handlers.
-const EventHandlers = {
- onRequestTimeout: () => {},
- onTransportError: () => {},
- onSuccessResponse: () => {},
- onErrorResponse: () => {},
- onAuthenticated: () => {},
- onDialogError: () => {},
-};
-
-module.exports = class DialogRequestSender {
- constructor(dialog, request, eventHandlers) {
- this._dialog = dialog;
- this._ua = dialog._ua;
- this._request = request;
- this._eventHandlers = eventHandlers;
-
- // RFC3261 14.1 Modifying an Existing Session. UAC Behavior.
- this._reattempt = false;
- this._reattemptTimer = null;
-
- // Define the undefined handlers.
- for (const handler in EventHandlers) {
- if (Object.prototype.hasOwnProperty.call(EventHandlers, handler)) {
- if (!this._eventHandlers[handler]) {
- this._eventHandlers[handler] = EventHandlers[handler];
- }
- }
- }
- }
-
- get request() {
- return this._request;
- }
-
- send() {
- const request_sender = new RequestSender(this._ua, this._request, {
- onRequestTimeout: () => {
- this._eventHandlers.onRequestTimeout();
- },
- onTransportError: () => {
- this._eventHandlers.onTransportError();
- },
- onAuthenticated: request => {
- this._eventHandlers.onAuthenticated(request);
- },
- onReceiveResponse: response => {
- this._receiveResponse(response);
- },
- });
-
- request_sender.send();
-
- // RFC3261 14.2 Modifying an Existing Session -UAC BEHAVIOR-.
- if (
- (this._request.method === JsSIP_C.INVITE ||
- (this._request.method === JsSIP_C.UPDATE && this._request.body)) &&
- request_sender.clientTransaction.state !== Transactions.Status.TERMINATED
- ) {
- this._dialog.uac_pending_reply = true;
-
- const stateChanged = () => {
- if (
- request_sender.clientTransaction.state ===
- Transactions.Status.ACCEPTED ||
- request_sender.clientTransaction.state ===
- Transactions.Status.COMPLETED ||
- request_sender.clientTransaction.state ===
- Transactions.Status.TERMINATED
- ) {
- request_sender.clientTransaction.removeListener(
- 'stateChanged',
- stateChanged
- );
- this._dialog.uac_pending_reply = false;
- }
- };
-
- request_sender.clientTransaction.on('stateChanged', stateChanged);
- }
- }
-
- _receiveResponse(response) {
- // RFC3261 12.2.1.2 408 or 481 is received for a request within a dialog.
- if (response.status_code === 408 || response.status_code === 481) {
- this._eventHandlers.onDialogError(response);
- } else if (
- response.method === JsSIP_C.INVITE &&
- response.status_code === 491
- ) {
- if (this._reattempt) {
- this._eventHandlers.onErrorResponse(response);
- } else {
- this._request.cseq = this._dialog.local_seqnum += 1;
- this._reattemptTimer = setTimeout(() => {
- if (!this._dialog.isTerminated()) {
- this._reattempt = true;
- this.send();
- }
- }, 1000);
- }
- } else if (response.status_code >= 200 && response.status_code < 300) {
- this._eventHandlers.onSuccessResponse(response);
- } else if (response.status_code >= 300) {
- this._eventHandlers.onErrorResponse(response);
- }
- }
-};
diff --git a/src/Dialog/RequestSender.ts b/src/Dialog/RequestSender.ts
new file mode 100644
index 0000000..4728d60
--- /dev/null
+++ b/src/Dialog/RequestSender.ts
@@ -0,0 +1,155 @@
+import * as JsSIP_C from '../Constants';
+import type { Dialog, DialogUA } from '../Dialog';
+import { RequestSender } from '../RequestSender';
+import type { IncomingResponse, OutgoingRequest } from '../SIPMessage';
+import * as Transactions from '../Transactions';
+
+/**
+ * The callbacks a dialog request sender reports to the applicant. Every one of
+ * them is optional; the ones left out fall back to `DEFAULT_EVENT_HANDLERS`.
+ */
+export interface DialogRequestSenderEventHandlers {
+ onRequestTimeout(): void;
+ onTransportError(): void;
+ onSuccessResponse(response: IncomingResponse): void;
+ onErrorResponse(response: IncomingResponse): void;
+ onAuthenticated(request: OutgoingRequest): void;
+ onDialogError(response: IncomingResponse): void;
+}
+
+// Default event handlers.
+const DEFAULT_EVENT_HANDLERS: DialogRequestSenderEventHandlers = {
+ onRequestTimeout: () => {},
+ onTransportError: () => {},
+ onSuccessResponse: () => {},
+ onErrorResponse: () => {},
+ onAuthenticated: () => {},
+ onDialogError: () => {},
+};
+
+export class DialogRequestSender {
+ #dialog: Dialog;
+ #ua: DialogUA;
+ #request: OutgoingRequest;
+ #eventHandlers: DialogRequestSenderEventHandlers;
+
+ /**
+ * RFC3261 14.1 Modifying an Existing Session. UAC Behavior.
+ */
+ #reattempt = false;
+
+ constructor(
+ dialog: Dialog,
+ request: OutgoingRequest,
+ eventHandlers: Partial<DialogRequestSenderEventHandlers>
+ ) {
+ this.#dialog = dialog;
+ this.#ua = dialog.ua;
+ this.#request = request;
+
+ this.#eventHandlers = Object.assign(eventHandlers, {
+ onRequestTimeout:
+ eventHandlers.onRequestTimeout ||
+ DEFAULT_EVENT_HANDLERS.onRequestTimeout,
+ onTransportError:
+ eventHandlers.onTransportError ||
+ DEFAULT_EVENT_HANDLERS.onTransportError,
+ onSuccessResponse:
+ eventHandlers.onSuccessResponse ||
+ DEFAULT_EVENT_HANDLERS.onSuccessResponse,
+ onErrorResponse:
+ eventHandlers.onErrorResponse || DEFAULT_EVENT_HANDLERS.onErrorResponse,
+ onAuthenticated:
+ eventHandlers.onAuthenticated || DEFAULT_EVENT_HANDLERS.onAuthenticated,
+ onDialogError:
+ eventHandlers.onDialogError || DEFAULT_EVENT_HANDLERS.onDialogError,
+ });
+ }
+
+ get request(): OutgoingRequest {
+ return this.#request;
+ }
+
+ send(): void {
+ const request_sender = new RequestSender(this.#ua, this.#request, {
+ onRequestTimeout: () => {
+ this.#eventHandlers.onRequestTimeout();
+ },
+ onTransportError: () => {
+ this.#eventHandlers.onTransportError();
+ },
+ onAuthenticated: request => {
+ this.#eventHandlers.onAuthenticated(request);
+ },
+ onReceiveResponse: response => {
+ this.#receiveResponse(response);
+ },
+ });
+
+ request_sender.send();
+
+ const clientTransaction = request_sender.clientTransaction;
+
+ /* RFC3261 14.2 Modifying an Existing Session -UAC BEHAVIOR-.
+ *
+ * NOTE: `send()` always creates the client transaction, and the `'state'
+ * in` check just narrows out `AckClientTransaction` (the only one with no
+ * state), which the method check already makes impossible here.
+ */
+ if (
+ (this.#request.method === JsSIP_C.INVITE ||
+ (this.#request.method === JsSIP_C.UPDATE && this.#request.body)) &&
+ clientTransaction &&
+ 'state' in clientTransaction &&
+ clientTransaction.state !== Transactions.Status.TERMINATED
+ ) {
+ this.#dialog.uac_pending_reply = true;
+
+ const stateChanged = (): void => {
+ if (
+ clientTransaction.state === Transactions.Status.ACCEPTED ||
+ clientTransaction.state === Transactions.Status.COMPLETED ||
+ clientTransaction.state === Transactions.Status.TERMINATED
+ ) {
+ clientTransaction.removeListener('stateChanged', stateChanged);
+ this.#dialog.uac_pending_reply = false;
+ }
+ };
+
+ clientTransaction.on('stateChanged', stateChanged);
+ }
+ }
+
+ #receiveResponse(response: IncomingResponse): void {
+ // RFC3261 12.2.1.2 408 or 481 is received for a request within a dialog.
+ if (response.status_code === 408 || response.status_code === 481) {
+ this.#eventHandlers.onDialogError(response);
+ } else if (
+ response.method === JsSIP_C.INVITE &&
+ response.status_code === 491
+ ) {
+ if (this.#reattempt) {
+ this.#eventHandlers.onErrorResponse(response);
+ } else {
+ /* NOTE: The dialog always has a local sequence number here, since
+ * `Dialog.sendRequest()` created the request being retried.
+ */
+ const local_seqnum = (this.#dialog.local_seqnum ?? 0) + 1;
+
+ this.#dialog.local_seqnum = local_seqnum;
+ this.#request.cseq = local_seqnum;
+
+ setTimeout(() => {
+ if (!this.#dialog.isTerminated()) {
+ this.#reattempt = true;
+ this.send();
+ }
+ }, 1000);
+ }
+ } else if (response.status_code >= 200 && response.status_code < 300) {
+ this.#eventHandlers.onSuccessResponse(response);
+ } else if (response.status_code >= 300) {
+ this.#eventHandlers.onErrorResponse(response);
+ }
+ }
+}
diff --git a/src/Notifier.js b/src/Notifier.js
index 0596533..716fa70 100644
--- a/src/Notifier.js
+++ b/src/Notifier.js
@@ -3,7 +3,7 @@ const Exceptions = require('./Exceptions');
const { Logger } = require('./Logger');
const JsSIP_C = require('./Constants');
const Utils = require('./Utils');
-const Dialog = require('./Dialog');
+const { Dialog } = require('./Dialog');
const logger = new Logger('Notifier');
@@ -186,7 +186,14 @@ module.exports = class Notifier extends EventEmitter {
// Create dialog for normal and fetch-subscribe.
if (!this._dialog) {
- this._dialog = new Dialog(this, request, 'UAS');
+ try {
+ this._dialog = Dialog.Create(this, request, 'UAS');
+ } catch {
+ // The SUBSCRIBE cannot establish a dialog.
+ request.reply(400);
+
+ return;
+ }
}
request.reply(200, null, [`Expires: ${this._expires}`, `${this._contact}`]);
diff --git a/src/RTCSession.js b/src/RTCSession.js
index 654976e..4dc6b9d 100644
--- a/src/RTCSession.js
+++ b/src/RTCSession.js
@@ -10,7 +10,7 @@ const Transactions = require('./Transactions');
const Utils = require('./Utils');
const Timers = require('./Timers');
const SIPMessage = require('./SIPMessage');
-const Dialog = require('./Dialog');
+const { Dialog, Status: DialogStatus } = require('./Dialog');
const { RequestSender } = require('./RequestSender');
const RTCSession_DTMF = require('./RTCSession/DTMF');
const RTCSession_Info = require('./RTCSession/Info');
@@ -416,7 +416,7 @@ module.exports = class RTCSession extends EventEmitter {
// An error on dialog creation will fire 'failed' event.
if (!this._createDialog(request, 'UAS', true)) {
- request.reply(500, 'Missing Contact header field');
+ request.reply(500, 'Error creating dialog');
return;
}
@@ -1911,19 +1911,18 @@ module.exports = class RTCSession extends EventEmitter {
if (early_dialog) {
return true;
} else {
- early_dialog = new Dialog(this, message, type, Dialog.C.STATUS_EARLY);
-
- // Dialog has been successfully created.
- if (early_dialog.error) {
- logger.debug(early_dialog.error);
+ try {
+ early_dialog = Dialog.Create(this, message, type, DialogStatus.EARLY);
+ } catch {
this._failed('remote', message, JsSIP_C.causes.INTERNAL_ERROR);
return false;
- } else {
- this._earlyDialogs[id] = early_dialog;
-
- return true;
}
+
+ // Dialog has been successfully created.
+ this._earlyDialogs[id] = early_dialog;
+
+ return true;
}
}
@@ -1942,18 +1941,19 @@ module.exports = class RTCSession extends EventEmitter {
}
// Otherwise, create a _confirmed_ dialog.
- const dialog = new Dialog(this, message, type);
+ let dialog;
- if (dialog.error) {
- logger.debug(dialog.error);
+ try {
+ dialog = Dialog.Create(this, message, type);
+ } catch {
this._failed('remote', message, JsSIP_C.causes.INTERNAL_ERROR);
return false;
- } else {
- this._dialog = dialog;
-
- return true;
}
+
+ this._dialog = dialog;
+
+ return true;
}
}
@@ -2560,11 +2560,9 @@ module.exports = class RTCSession extends EventEmitter {
// If not, send an ACK and terminate.
else {
- const dialog = new Dialog(this, response, 'UAC');
-
- if (dialog.error !== undefined) {
- logger.debug(dialog.error);
-
+ try {
+ Dialog.Create(this, response, 'UAC');
+ } catch {
return;
}
diff --git a/src/SIPMessage.ts b/src/SIPMessage.ts
index 3f0ee99..6bbb12f 100644
--- a/src/SIPMessage.ts
+++ b/src/SIPMessage.ts
@@ -3,6 +3,7 @@ import type { EventEmitter } from 'events';
import * as JsSIP_C from './Constants';
import { Logger } from './Logger';
import * as Grammar from './Grammar';
+import type { Status as TransactionStatus } from './Transactions';
import type { Transport } from './Transport';
import {
cloneArray,
@@ -98,11 +99,13 @@ export interface ClientTransactionLike {
/**
* The server transaction an incoming request is bound to.
*
- * TODO: Replace with the server transaction types from './Transactions' once
- * that module is ported to TypeScript.
+ * TODO: Replace with the `NonInviteServerTransaction | InviteServerTransaction`
+ * union from './Transactions'. Only `state` is typed from there for now, since
+ * importing the classes themselves (and not just their types) would create a
+ * runtime require cycle.
*/
export interface ServerTransactionLike extends EventEmitter {
- state: number;
+ state: TransactionStatus;
receiveResponse(
code: number,
diff --git a/src/Subscriber.js b/src/Subscriber.js
index 088ef9f..aa197c4 100644
--- a/src/Subscriber.js
+++ b/src/Subscriber.js
@@ -6,7 +6,7 @@ const Utils = require('./Utils');
const Grammar = require('./Grammar');
const SIPMessage = require('./SIPMessage');
const { RequestSender } = require('./RequestSender');
-const Dialog = require('./Dialog');
+const { Dialog } = require('./Dialog');
const logger = new Logger('Subscriber');
@@ -239,11 +239,12 @@ module.exports = class Subscriber extends EventEmitter {
* 4.1.2.4).
*/
receiveEarlyNotify(request) {
- const dialog = new Dialog(this, request, 'UAS');
+ let dialog;
- if (dialog.error) {
+ try {
+ dialog = Dialog.Create(this, request, 'UAS');
+ } catch {
// NOTIFY without Contact.
- logger.warn(dialog.error);
request.reply(400);
return;
@@ -554,11 +555,12 @@ module.exports = class Subscriber extends EventEmitter {
if (response.status_code >= 200 && response.status_code < 300) {
// Create dialog, unless an early NOTIFY already created it.
if (this._dialog === null) {
- const dialog = new Dialog(this, response, 'UAC');
+ let dialog;
- if (dialog.error) {
+ try {
+ dialog = Dialog.Create(this, response, 'UAC');
+ } catch {
// OK response without Contact.
- logger.warn(dialog.error);
this._terminateDialog(
C.SUBSCRIBE_WRONG_OK_RESPONSE,
undefined,
diff --git a/src/test/test-Dialog.ts b/src/test/test-Dialog.ts
new file mode 100644
index 0000000..c406929
--- /dev/null
+++ b/src/test/test-Dialog.ts
@@ -0,0 +1,179 @@
+import { setTimeout as delay } from 'timers/promises';
+
+import './include/common';
+import * as consts from './include/consts';
+import { buildRequest, buildResponse } from './include/sipMessage';
+import TestSocket from './include/TestSocket';
+import { startUA, stopUA } from './include/ua';
+
+import { Dialog, DialogError, DialogErrorReason } from '../Dialog';
+import type { DialogOwner } from '../Dialog';
+import { UA, WebSocketInterface } from '../JsSIP';
+import type { Notifier } from '../Notifier';
+import * as Parser from '../Parser';
+import type { IncomingMessage, UALike } from '../SIPMessage';
+
+const AOR = 'sip:alice@example.com';
+const REMOTE = '<sip:bob@example.com>';
+const CONTACT = 'Contact: <sip:bob@abcdefabcdef.invalid;transport=ws>';
+
+describe('Dialog.Create()', () => {
+ /* The dialogs below are never used, so the owner only has to carry the `ua`
+ * that `Create()` registers them with.
+ */
+ const dialogs: Dialog[] = [];
+
+ const owner = {
+ _ua: {
+ newDialog: (dialog: Dialog) => dialogs.push(dialog),
+ },
+ receiveRequest: () => {},
+ } as unknown as DialogOwner;
+
+ let ua: UA;
+
+ beforeAll(() => {
+ ua = new UA(
+ consts.uaConfiguration({
+ sockets: new WebSocketInterface(consts.SOCKET_DESCRIPTION.url),
+ })
+ );
+ });
+
+ /**
+ * A SUBSCRIBE as it arrives from the wire, so that the dialog is built out
+ * of a real `IncomingMessage` rather than a stub.
+ */
+ function subscribe(fields: string[]): IncomingMessage {
+ const data = buildRequest('SUBSCRIBE', AOR, {
+ from: REMOTE,
+ to: `<${AOR}>;tag=localtag`,
+ callId: 'the-call-id',
+ cseq: 1,
+ extraHeaders: ['Event: weather', 'Expires: 3600', ...fields],
+ });
+
+ /* A started UA does satisfy UALike, but no exported type says so: see
+ * the TODO on 'Configuration', which UA mutates after loading it.
+ */
+ const message = Parser.parseMessage(data, ua as unknown as UALike);
+
+ if (!message) {
+ throw new Error('parseMessage() did not return a message');
+ }
+
+ return message;
+ }
+
+ test('rejects a message with no Contact', () => {
+ const message = subscribe([`From: ${REMOTE};tag=remotetag`]);
+ const create = (): Dialog => Dialog.Create(owner, message, 'UAS');
+
+ expect(create).toThrow(DialogError);
+ expect(create).toThrow(DialogErrorReason.NO_CONTACT);
+ });
+
+ test('rejects a message that cannot identify a dialog', () => {
+ // No From tag, so there is no remote tag to build the dialog id with.
+ const message = subscribe([`From: ${REMOTE}`, CONTACT]);
+ const create = (): Dialog => Dialog.Create(owner, message, 'UAS');
+
+ expect(create).toThrow(DialogError);
+ expect(create).toThrow(DialogErrorReason.NO_ID);
+ });
+
+ test('builds the dialog id out of the Call-ID and both tags', () => {
+ const message = subscribe([`From: ${REMOTE};tag=remotetag`, CONTACT]);
+ const dialog = Dialog.Create(owner, message, 'UAS');
+
+ // RFC 3261 12.1.1: the local tag of a UAS dialog is the To tag.
+ expect(dialog.id).toMatchObject({
+ call_id: 'the-call-id',
+ local_tag: 'localtag',
+ remote_tag: 'remotetag',
+ });
+
+ // The key the UA indexes dialogs by.
+ expect(dialog.id.toString()).toBe('the-call-idlocaltagremotetag');
+
+ expect(dialog.isTerminated()).toBe(false);
+ });
+});
+
+/**
+ * Answers every request the UA sends with a 200, so that terminating the
+ * notifier does not leave a transaction pending when the UA stops.
+ */
+class PlainSocket extends TestSocket {
+ protected override onRequest(request: string): void {
+ this.receive(buildResponse(request, 200, { toTag: 'remotetag' }));
+ }
+}
+
+/**
+ * Feeds a UA with a notifier an initial SUBSCRIBE carrying the given header
+ * fields and returns the status code it is answered with.
+ */
+async function subscribeStatus(fields: string[]): Promise<number | undefined> {
+ const callId = 'the-call-id';
+ const socket = new PlainSocket();
+ const ua = new UA({ sockets: socket, uri: AOR, register: false });
+
+ let notifier: Notifier | undefined;
+
+ ua.on('newSubscribe', ({ request }) => {
+ notifier = ua.notify(request, 'text/plain', { pending: false });
+ notifier.start();
+ });
+
+ await startUA(ua);
+
+ socket.receive(
+ buildRequest('SUBSCRIBE', AOR, {
+ from: REMOTE,
+ to: `<${AOR}>`,
+ callId,
+ cseq: 1,
+ extraHeaders: ['Event: weather', 'Expires: 3600', ...fields],
+ })
+ );
+
+ await delay(50);
+
+ /* A notifier that got its dialog arms an expires timer, and `UA.stop()`
+ * does not terminate notifiers the way it does sessions and subscribers,
+ * so the timer would outlive the test.
+ */
+ if (notifier?.id) {
+ notifier.terminate();
+ }
+
+ await stopUA(ua);
+
+ return socket.statusFor(callId);
+}
+
+describe('notifier receiving a SUBSCRIBE that cannot establish a dialog', () => {
+ /* Not 400: `Notifier.checkSubscribe()` rejects a SUBSCRIBE with no Contact
+ * before the UA even emits 'newSubscribe', so `Dialog.Create()` never sees
+ * it. Asserted so that the earlier gate is not removed unnoticed.
+ */
+ test('answers a SUBSCRIBE with no Contact', async () => {
+ await expect(
+ subscribeStatus([`From: ${REMOTE};tag=remotetag`])
+ ).resolves.toBe(405);
+ });
+
+ test('answers a SUBSCRIBE with no From tag', async () => {
+ await expect(subscribeStatus([`From: ${REMOTE}`, CONTACT])).resolves.toBe(
+ 400
+ );
+ });
+
+ // The control: the very same SUBSCRIBE, only well formed, is accepted.
+ test('accepts a well formed SUBSCRIBE', async () => {
+ await expect(
+ subscribeStatus([`From: ${REMOTE};tag=remotetag`, CONTACT])
+ ).resolves.toBe(200);
+ });
+});