-
Notifications
You must be signed in to change notification settings - Fork 792
Expand file tree
/
Copy pathRegistrator.js
More file actions
415 lines (336 loc) · 10.1 KB
/
Registrator.js
File metadata and controls
415 lines (336 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
const Logger = require('./Logger');
const Utils = require('./Utils');
const JsSIP_C = require('./Constants');
const SIPMessage = require('./SIPMessage');
const RequestSender = require('./RequestSender');
const logger = new Logger('Registrator');
const MIN_REGISTER_EXPIRES = 10; // In seconds.
module.exports = class Registrator {
constructor(ua, transport) {
// Force reg_id to 1.
this._reg_id = 1;
this._ua = ua;
this._transport = transport;
this._registrar = ua.configuration.registrar_server;
this._expires = ua.configuration.register_expires;
// Call-ID and CSeq values RFC3261 10.2.
this._call_id = Utils.createRandomToken(22);
this._cseq = 0;
this._to_uri = ua.configuration.uri;
this._registrationTimer = null;
// Ongoing Register request.
this._registering = false;
// Set status.
this._registered = false;
// Contact header.
this._contact = this._ua.contact.toString();
// Sip.ice media feature tag (RFC 5768).
this._contact += ';+sip.ice';
// Custom headers for REGISTER and un-REGISTER.
this._extraHeaders = [];
// Custom Contact header params for REGISTER and un-REGISTER.
this._extraContactParams = '';
// Contents of the sip.instance Contact header parameter.
this._sipInstance = `"<urn:uuid:${this._ua.configuration.instance_id}>"`;
this._contact += `;reg-id=${this._reg_id}`;
this._contact += `;+sip.instance=${this._sipInstance}`;
}
get registered() {
return this._registered;
}
setExtraHeaders(extraHeaders) {
if (!Array.isArray(extraHeaders)) {
extraHeaders = [];
}
this._extraHeaders = extraHeaders.slice();
}
setExtraContactParams(extraContactParams) {
if (!(extraContactParams instanceof Object)) {
extraContactParams = {};
}
// Reset it.
this._extraContactParams = '';
for (const param_key in extraContactParams) {
if (Object.prototype.hasOwnProperty.call(extraContactParams, param_key)) {
const param_value = extraContactParams[param_key];
this._extraContactParams += `;${param_key}`;
if (param_value) {
this._extraContactParams += `=${param_value}`;
}
}
}
}
register() {
if (this._registering) {
logger.debug('Register request in progress...');
return;
}
const extraHeaders = Utils.cloneArray(this._extraHeaders);
let contactValue;
// Proactive Authorization: Authorization header will be added automatically
// by RequestSender if cached credentials are available from previous auth challenges.
if (this._expires) {
contactValue = `${this._contact};expires=${this._expires}${this._extraContactParams}`;
extraHeaders.push(`Expires: ${this._expires}`);
} else {
contactValue = `${this._contact}${this._extraContactParams}`;
}
extraHeaders.push(`Contact: ${contactValue}`);
let fromTag = Utils.newTag();
if (this._ua.configuration.register_from_tag_trail) {
if (
typeof this._ua.configuration.register_from_tag_trail === 'function'
) {
fromTag += this._ua.configuration.register_from_tag_trail();
} else {
fromTag += this._ua.configuration.register_from_tag_trail;
}
}
const request = new SIPMessage.OutgoingRequest(
JsSIP_C.REGISTER,
this._registrar,
this._ua,
{
to_uri: this._to_uri,
call_id: this._call_id,
cseq: (this._cseq += 1),
from_tag: fromTag,
},
extraHeaders
);
const request_sender = new RequestSender(this._ua, request, {
onRequestTimeout: () => {
this._registrationFailure(null, JsSIP_C.causes.REQUEST_TIMEOUT);
},
onTransportError: () => {
this._registrationFailure(null, JsSIP_C.causes.CONNECTION_ERROR);
},
// Increase the CSeq on authentication.
onAuthenticated: () => {
this._cseq += 1;
},
onReceiveResponse: response => {
// Discard responses to older REGISTER/un-REGISTER requests.
if (response.cseq !== this._cseq) {
return;
}
// Clear registration timer.
if (this._registrationTimer !== null) {
clearTimeout(this._registrationTimer);
this._registrationTimer = null;
}
switch (true) {
case /^1[0-9]{2}$/.test(response.status_code): {
// Ignore provisional responses.
break;
}
case /^2[0-9]{2}$/.test(response.status_code): {
this._registering = false;
if (!response.hasHeader('Contact')) {
logger.debug(
'no Contact header in response to REGISTER, response ignored'
);
break;
}
const contacts = response.headers['Contact'].reduce(
(a, b) => a.concat(b.parsed),
[]
);
// Get the Contact pointing to us and update the expires value accordingly.
// Try to find a matching Contact using sip.instance and reg-id.
let contact = contacts.find(
element =>
this._sipInstance === element.getParam('+sip.instance') &&
this._reg_id === parseInt(element.getParam('reg-id'))
);
// If no match was found using the sip.instance try comparing the URIs.
if (!contact) {
contact = contacts.find(
element => element.uri.user === this._ua.contact.uri.user
);
}
if (!contact) {
logger.debug(
'no Contact header pointing to us, response ignored'
);
break;
}
let expires = contact.getParam('expires');
if (!expires && response.hasHeader('expires')) {
expires = response.getHeader('expires');
}
if (!expires) {
expires = this._expires;
}
expires = Number(expires);
if (expires < MIN_REGISTER_EXPIRES) {
expires = MIN_REGISTER_EXPIRES;
}
const timeout =
expires > 64
? (expires * 1000) / 2 +
Math.floor((expires / 2 - 32) * 1000 * Math.random())
: expires * 1000 - 5000;
// Re-Register or emit an event before the expiration interval has elapsed.
// For that, decrease the expires value. ie: 3 seconds.
this._registrationTimer = setTimeout(() => {
this._registrationTimer = null;
// If there are no listeners for registrationExpiring, renew registration.
// If there are listeners, let the function listening do the register call.
if (this._ua.listeners('registrationExpiring').length === 0) {
this.register();
} else {
this._ua.emit('registrationExpiring');
}
}, timeout);
// Save gruu values.
if (contact.hasParam('temp-gruu')) {
this._ua.contact.temp_gruu = contact
.getParam('temp-gruu')
.replace(/"/g, '');
}
if (contact.hasParam('pub-gruu')) {
this._ua.contact.pub_gruu = contact
.getParam('pub-gruu')
.replace(/"/g, '');
}
if (!this._registered) {
this._registered = true;
this._ua.registered({ response });
}
break;
}
// Interval too brief RFC3261 10.2.8.
case /^423$/.test(response.status_code): {
if (response.hasHeader('min-expires')) {
// Increase our registration interval to the suggested minimum.
this._expires = Number(response.getHeader('min-expires'));
if (this._expires < MIN_REGISTER_EXPIRES) {
this._expires = MIN_REGISTER_EXPIRES;
}
// Assure register re-try with new expire.
this._registering = false;
// Attempt the registration again immediately.
this.register();
} else {
// This response MUST contain a Min-Expires header field.
logger.debug(
'423 response received for REGISTER without Min-Expires'
);
this._registrationFailure(
response,
JsSIP_C.causes.SIP_FAILURE_CODE
);
}
break;
}
default: {
const cause = Utils.sipErrorCause(response.status_code);
this._registrationFailure(response, cause);
}
}
},
});
this._registering = true;
request_sender.send();
}
unregister(options = {}) {
if (!this._registered) {
logger.debug('already unregistered');
return;
}
this._registered = false;
// Clear the registration timer.
if (this._registrationTimer !== null) {
clearTimeout(this._registrationTimer);
this._registrationTimer = null;
}
const extraHeaders = Utils.cloneArray(this._extraHeaders);
if (options.all) {
extraHeaders.push(`Contact: *${this._extraContactParams}`);
} else {
extraHeaders.push(
`Contact: ${this._contact};expires=0${this._extraContactParams}`
);
}
extraHeaders.push('Expires: 0');
const request = new SIPMessage.OutgoingRequest(
JsSIP_C.REGISTER,
this._registrar,
this._ua,
{
to_uri: this._to_uri,
call_id: this._call_id,
cseq: (this._cseq += 1),
},
extraHeaders
);
const request_sender = new RequestSender(this._ua, request, {
onRequestTimeout: () => {
this._unregistered(null, JsSIP_C.causes.REQUEST_TIMEOUT);
},
onTransportError: () => {
this._unregistered(null, JsSIP_C.causes.CONNECTION_ERROR);
},
// Increase the CSeq on authentication.
onAuthenticated: () => {
this._cseq += 1;
},
onReceiveResponse: response => {
switch (true) {
case /^1[0-9]{2}$/.test(response.status_code): {
// Ignore provisional responses.
break;
}
case /^2[0-9]{2}$/.test(response.status_code): {
this._unregistered(response);
break;
}
default: {
const cause = Utils.sipErrorCause(response.status_code);
this._unregistered(response, cause);
}
}
},
});
request_sender.send();
}
close() {
if (this._registered) {
this.unregister();
}
}
onTransportClosed() {
this._registering = false;
if (this._registrationTimer !== null) {
clearTimeout(this._registrationTimer);
this._registrationTimer = null;
}
if (this._registered) {
this._registered = false;
this._ua.unregistered({});
}
}
_registrationFailure(response, cause) {
this._registering = false;
this._ua.registrationFailed({
response: response || null,
cause,
});
if (this._registered) {
this._registered = false;
this._ua.unregistered({
response: response || null,
cause,
});
}
}
_unregistered(response, cause) {
this._registering = false;
this._registered = false;
this._ua.unregistered({
response: response || null,
cause: cause || null,
});
}
};