Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions src/Notifier.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,9 @@ export interface NotifierUA extends DialogUA {
readonly contact: DialogUA['contact'] & {
toString(): string;
};

newNotifier(notifier: Notifier): void;
destroyNotifier(notifier: Notifier): void;
}

/**
Expand All @@ -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 {
Expand All @@ -157,7 +160,7 @@ export class Notifier
(error as Error).message
);

request.reply(405);
request.reply(400);

return;
}
Expand Down Expand Up @@ -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);
}
}

/**
Expand Down Expand Up @@ -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);
Expand Down
31 changes: 30 additions & 1 deletion src/UA.ts
Original file line number Diff line number Diff line change
Expand Up @@ -402,6 +402,9 @@ export class UA extends EventEmitter<UAEventMap> {
// Subscriber instances with a subscription sent or established.
#subscribers: Set<Subscriber> = new Set();

// Notifier instances with an established subscription.
#notifiers: Set<Notifier> = new Set();

#transport!: Transport;
#contact!: UAContact;
#status: Status = Status.INIT;
Expand Down Expand Up @@ -711,6 +714,16 @@ export class UA extends EventEmitter<UAEventMap> {
} 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
Expand Down Expand Up @@ -946,6 +959,20 @@ export class UA extends EventEmitter<UAEventMap> {
this.#subscribers.delete(subscriber);
}

/**
* @internal
*/
newNotifier(notifier: Notifier): void {
this.#notifiers.add(notifier);
}

/**
* @internal
*/
destroyNotifier(notifier: Notifier): void {
this.#notifiers.delete(notifier);
}

/**
* @internal
*/
Expand Down Expand Up @@ -1065,8 +1092,10 @@ export class UA extends EventEmitter<UAEventMap> {

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;
}
Expand Down
20 changes: 4 additions & 16 deletions src/test/test-Dialog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -120,11 +119,8 @@ async function subscribeStatus(fields: string[]): Promise<number | undefined> {
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);
Expand All @@ -141,26 +137,18 @@ async function subscribeStatus(fields: string[]): Promise<number | undefined> {

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 () => {
Expand Down
158 changes: 158 additions & 0 deletions src/test/test-SubscriberNotifier.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading