diff --git a/src/Notifier.ts b/src/Notifier.ts index bb3af7e2..e7c669f4 100644 --- a/src/Notifier.ts +++ b/src/Notifier.ts @@ -123,6 +123,9 @@ export interface NotifierUA extends DialogUA { readonly contact: DialogUA['contact'] & { toString(): string; }; + + newNotifier(notifier: Notifier): void; + destroyNotifier(notifier: Notifier): void; } /** @@ -146,7 +149,7 @@ export class Notifier * @remarks * - Called by the `UA`. The application must not call it. * - A SUBSCRIBE that does not pass {@link Notifier.checkSubscribe} is - * answered 405 and the callback is not invoked. + * answered 400 and the callback is not invoked. */ static init_incoming(request: IncomingRequest, callback: () => void): void { try { @@ -157,7 +160,7 @@ export class Notifier (error as Error).message ); - request.reply(405); + request.reply(400); return; } @@ -388,6 +391,12 @@ export class Notifier } this.receiveRequest(this.#initial_subscribe); + + // receiveRequest() leaves no dialog when the SUBSCRIBE is a fetch + // (Expires: 0), already over, or when it could not establish one. + if (this.#dialog) { + this.ua.newNotifier(this); + } } /** @@ -499,6 +508,7 @@ export class Notifier this.#dialog.terminate(); this.#dialog = null; } + this.ua.destroyNotifier(this); logger.debug(`emit "terminated" code=${termination_code}`); this.emit('terminated', termination_code); diff --git a/src/UA.ts b/src/UA.ts index 28f7a1d1..6d418f72 100644 --- a/src/UA.ts +++ b/src/UA.ts @@ -402,6 +402,9 @@ export class UA extends EventEmitter { // Subscriber instances with a subscription sent or established. #subscribers: Set = new Set(); + // Notifier instances with an established subscription. + #notifiers: Set = new Set(); + #transport!: Transport; #contact!: UAContact; #status: Status = Status.INIT; @@ -711,6 +714,16 @@ export class UA extends EventEmitter { } catch (error) {} } + // End every subscription we serve with a final NOTIFY, sent before the + // UA is closed: the subscribers would otherwise wait for the + // subscription to expire. + for (const notifier of this.#notifiers) { + logger.debug('closing notifier'); + try { + notifier.terminate(); + } catch (error) {} + } + // Close every applicant. // // NOTE: Neither `Message` nor `Options` exposes a `close()`, so every @@ -946,6 +959,20 @@ export class UA extends EventEmitter { this.#subscribers.delete(subscriber); } + /** + * @internal + */ + newNotifier(notifier: Notifier): void { + this.#notifiers.add(notifier); + } + + /** + * @internal + */ + destroyNotifier(notifier: Notifier): void { + this.#notifiers.delete(notifier); + } + /** * @internal */ @@ -1065,8 +1092,10 @@ export class UA extends EventEmitter { message.init_incoming(request); } else if (method === JsSIP_C.SUBSCRIBE) { + // SUBSCRIBE is an allowed method: without a listener it is the event + // package that is not supported (RFC 6665 4.2.1.1). if (this.listeners('newSubscribe').length === 0) { - request.reply(405); + request.reply(489); return; } diff --git a/src/test/test-Dialog.ts b/src/test/test-Dialog.ts index c8d9fdf4..2687e886 100644 --- a/src/test/test-Dialog.ts +++ b/src/test/test-Dialog.ts @@ -9,7 +9,6 @@ import { startUA, stopUA } from './include/ua'; import { Dialog, DialogError, DialogErrorReason } from '../Dialog'; import type { DialogOwner, DialogUA } from '../Dialog'; import { UA, WebSocketInterface } from '../JsSIP'; -import type { Notifier } from '../Notifier'; import * as Parser from '../Parser'; import type { IncomingMessage, UALike } from '../SIPMessage'; @@ -120,11 +119,8 @@ async function subscribeStatus(fields: string[]): Promise { 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(); + ua.notify(request, 'text/plain', { pending: false }).start(); }); await startUA(ua); @@ -141,26 +137,18 @@ async function subscribeStatus(fields: string[]): Promise { 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. + // `Notifier.checkSubscribe()` rejects a SUBSCRIBE with no Contact before + // the UA even emits 'newSubscribe', so `Dialog.Create()` never sees it. test('answers a SUBSCRIBE with no Contact', async () => { await expect( subscribeStatus([`From: ${REMOTE};tag=remotetag`]) - ).resolves.toBe(405); + ).resolves.toBe(400); }); test('answers a SUBSCRIBE with no From tag', async () => { diff --git a/src/test/test-SubscriberNotifier.ts b/src/test/test-SubscriberNotifier.ts index 87bcdf49..a543823c 100644 --- a/src/test/test-SubscriberNotifier.ts +++ b/src/test/test-SubscriberNotifier.ts @@ -398,6 +398,164 @@ describe('subscriber/notifier communication', () => { expect(sentOnStop).toEqual([`${EXPIRES}`, '0']); expect(terminationCode).toBe(subscriber.C.UA_STOPPED); }); + + test('notifier answers 489 when nobody listens to "newSubscribe"', async () => { + const socket = new LoopSocket(); + + const ua = new UA({ + sockets: socket, + uri: 'sip:ikq@example.com', + register: false, + }); + + await startUA(ua); + + const subscriber = ua.subscribe('ikq', 'weather', 'text/plain', {}); + + let terminationCode: number | undefined; + + subscriber.on('terminated', code => { + terminationCode = code; + + ua.stop(); + }); + + subscriber.subscribe(); + + await untilDisconnected(ua); + + expect(terminationCode).toBe(subscriber.C.SUBSCRIBE_NON_OK_RESPONSE); + expect(socket.responses('SUBSCRIBE').map(startLine)).toEqual([ + 'SIP/2.0 489 Bad Event', + ]); + }); + + test('notifier answers 400 to a SUBSCRIBE without Event header', async () => { + // The Event header is removed from the SUBSCRIBE on its way. + class NoEventSocket extends LoopSocket { + protected override onRequest(message: string): void { + super.onRequest(message.replace(/\r\nEvent:[^\r]*/i, '')); + } + } + + const socket = new NoEventSocket(); + + const ua = new UA({ + sockets: socket, + uri: 'sip:ikq@example.com', + register: false, + }); + + const newSubscribe = jest.fn(); + + ua.on('newSubscribe', newSubscribe); + + await startUA(ua); + + const subscriber = ua.subscribe('ikq', 'weather', 'text/plain', {}); + + let terminationCode: number | undefined; + + subscriber.on('terminated', code => { + terminationCode = code; + + ua.stop(); + }); + + subscriber.subscribe(); + + await untilDisconnected(ua); + + expect(terminationCode).toBe(subscriber.C.SUBSCRIBE_NON_OK_RESPONSE); + expect(socket.responses('SUBSCRIBE').map(startLine)).toEqual([ + 'SIP/2.0 400 Bad Request', + ]); + // A malformed SUBSCRIBE does not reach the application. + expect(newSubscribe).not.toHaveBeenCalled(); + }); + + test('UA.stop() sends the final NOTIFY', async () => { + // A stopped UA drops incoming requests, so it cannot be its own + // subscriber: the subscriber and the notifier are two UAs. + const [subscriberSocket, notifierSocket] = LoopSocket.pair(); + + const subscriberUA = new UA({ + sockets: subscriberSocket, + uri: 'sip:alice@example.com', + contact_uri: 'sip:alice@abcdefabcdef.invalid;transport=ws', + register: false, + }); + + const notifierUA = new UA({ + sockets: notifierSocket, + uri: 'sip:ikq@example.com', + contact_uri: 'sip:ikq@abcdefabcdef.invalid;transport=ws', + register: false, + }); + + const terminated: string[] = []; + let notifierTerminationCode: number | undefined; + let finalNotifyCode: number | undefined; + + notifierUA.on('newSubscribe', e => { + const notifier = notifierUA.notify(e.request, 'text/plain', { + pending: false, + }); + + notifier.on('subscribe', isUnsubscribe => { + if (!isUnsubscribe) { + notifier.notify(); + } + }); + + notifier.on('terminated', code => { + terminated.push('notifier'); + notifierTerminationCode = code; + finalNotifyCode = notifier.C.FINAL_NOTIFY_SENT; + }); + + notifier.start(); + }); + + await Promise.all([startUA(notifierUA), startUA(subscriberUA)]); + + const subscriber = subscriberUA.subscribe( + 'sip:ikq@example.com', + 'weather', + 'text/plain', + { expires: EXPIRES } + ); + + let subscriberTerminationCode: number | undefined; + + subscriber.on('active', () => { + notifierUA.stop(); + }); + + subscriber.on('terminated', code => { + terminated.push('subscriber'); + subscriberTerminationCode = code; + + subscriberUA.stop(); + }); + + subscriber.subscribe(); + + await Promise.all([ + untilDisconnected(subscriberUA), + untilDisconnected(notifierUA), + ]); + + expect(terminated).toEqual(['notifier', 'subscriber']); + expect(notifierTerminationCode).toBe(finalNotifyCode); + expect(subscriberTerminationCode).toBe(subscriber.C.FINAL_NOTIFY_RECEIVED); + expect( + notifierSocket + .requests('NOTIFY') + .map(message => header(message, 'Subscription-State')) + .at(-1) + ).toMatch(/^terminated/); + }); }); // RFC 6665 4.1.2.4: the NOTIFY that creates the subscription dialog may reach