forked from BetterVoice/iOS-SIP.js
-
Notifications
You must be signed in to change notification settings - Fork 1
/
sip.js
11401 lines (9807 loc) · 350 KB
/
sip.js
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* SIP version 0.7.0
* Copyright (c) 2014-2015 Junction Networks, Inc <http://www.onsip.com>
* Homepage: http://sipjs.com
* License: http://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 <http://www.versatica.com>
*
* 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(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.SIP=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
// 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.
function EventEmitter() {
this._events = this._events || {};
this._maxListeners = this._maxListeners || undefined;
}
module.exports = EventEmitter;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
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.
EventEmitter.defaultMaxListeners = 10;
// 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(n) {
if (!isNumber(n) || n < 0 || isNaN(n))
throw TypeError('n must be a positive number');
this._maxListeners = n;
return this;
};
EventEmitter.prototype.emit = function(type) {
var er, handler, len, args, i, listeners;
if (!this._events)
this._events = {};
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._events.error ||
(isObject(this._events.error) && !this._events.error.length)) {
er = arguments[1];
if (er instanceof Error) {
throw er; // Unhandled 'error' event
}
throw TypeError('Uncaught, unspecified "error" event.');
}
}
handler = this._events[type];
if (isUndefined(handler))
return false;
if (isFunction(handler)) {
switch (arguments.length) {
// fast cases
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
len = arguments.length;
args = new Array(len - 1);
for (i = 1; i < len; i++)
args[i - 1] = arguments[i];
handler.apply(this, args);
}
} else if (isObject(handler)) {
len = arguments.length;
args = new Array(len - 1);
for (i = 1; i < len; i++)
args[i - 1] = arguments[i];
listeners = handler.slice();
len = listeners.length;
for (i = 0; i < len; i++)
listeners[i].apply(this, args);
}
return true;
};
EventEmitter.prototype.addListener = function(type, listener) {
var m;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events)
this._events = {};
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (this._events.newListener)
this.emit('newListener', type,
isFunction(listener.listener) ?
listener.listener : listener);
if (!this._events[type])
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
else if (isObject(this._events[type]))
// If we've already got an array, just append.
this._events[type].push(listener);
else
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
// Check for listener leak
if (isObject(this._events[type]) && !this._events[type].warned) {
var m;
if (!isUndefined(this._maxListeners)) {
m = this._maxListeners;
} else {
m = EventEmitter.defaultMaxListeners;
}
if (m && m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
if (typeof console.trace === 'function') {
// not supported in IE 10
console.trace();
}
}
}
return this;
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) {
if (!isFunction(listener))
throw TypeError('listener must be a function');
var fired = false;
function g() {
this.removeListener(type, g);
if (!fired) {
fired = true;
listener.apply(this, arguments);
}
}
g.listener = listener;
this.on(type, g);
return this;
};
// emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener = function(type, listener) {
var list, position, length, i;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events || !this._events[type])
return this;
list = this._events[type];
length = list.length;
position = -1;
if (list === listener ||
(isFunction(list.listener) && list.listener === listener)) {
delete this._events[type];
if (this._events.removeListener)
this.emit('removeListener', type, listener);
} else if (isObject(list)) {
for (i = length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
position = i;
break;
}
}
if (position < 0)
return this;
if (list.length === 1) {
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
}
if (this._events.removeListener)
this.emit('removeListener', type, listener);
}
return this;
};
EventEmitter.prototype.removeAllListeners = function(type) {
var key, listeners;
if (!this._events)
return this;
// not listening for removeListener, no need to emit
if (!this._events.removeListener) {
if (arguments.length === 0)
this._events = {};
else if (this._events[type])
delete this._events[type];
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
for (key in this._events) {
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = {};
return this;
}
listeners = this._events[type];
if (isFunction(listeners)) {
this.removeListener(type, listeners);
} else {
// LIFO order
while (listeners.length)
this.removeListener(type, listeners[listeners.length - 1]);
}
delete this._events[type];
return this;
};
EventEmitter.prototype.listeners = function(type) {
var ret;
if (!this._events || !this._events[type])
ret = [];
else if (isFunction(this._events[type]))
ret = [this._events[type]];
else
ret = this._events[type].slice();
return ret;
};
EventEmitter.listenerCount = function(emitter, type) {
var ret;
if (!emitter._events || !emitter._events[type])
ret = 0;
else if (isFunction(emitter._events[type]))
ret = 1;
else
ret = emitter._events[type].length;
return ret;
};
function isFunction(arg) {
return typeof arg === 'function';
}
function isNumber(arg) {
return typeof arg === 'number';
}
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
function isUndefined(arg) {
return arg === void 0;
}
},{}],2:[function(_dereq_,module,exports){
module.exports={
"name": "sip.js",
"title": "SIP.js",
"description": "A simple, intuitive, and powerful JavaScript signaling library",
"version": "0.7.0",
"main": "src/index.js",
"browser": {
"./src/environment.js": "./src/environment_browser.js"
},
"homepage": "http://sipjs.com",
"author": "Will Mitchell <will@onsip.com>",
"contributors": [
{
"url": "http://sipjs.com/authors/"
}
],
"repository": {
"type": "git",
"url": "https://github.com/onsip/SIP.js.git"
},
"keywords": [
"sip",
"websocket",
"webrtc",
"library",
"javascript"
],
"devDependencies": {
"browserify": "^4.1.8",
"grunt": "~0.4.0",
"grunt-browserify": "^2.1.0",
"grunt-cli": "~0.1.6",
"grunt-contrib-copy": "^0.5.0",
"grunt-contrib-jasmine": "~0.8.0",
"grunt-contrib-jshint": ">0.5.0",
"grunt-contrib-uglify": "~0.2.0",
"grunt-peg": "~1.3.1",
"grunt-trimtrailingspaces": "^0.4.0",
"pegjs": "^0.8.0"
},
"engines": {
"node": ">=0.8"
},
"license": "MIT",
"scripts": {
"prepublish": "cd src/Grammar && mkdir -p dist && pegjs --extra-options-file peg.json src/Grammar.pegjs dist/Grammar.js",
"test": "grunt travis --verbose"
},
"dependencies": {
"ws": "^0.6.4"
},
"optionalDependencies": {
"promiscuous": "^0.6.0"
}
}
},{}],3:[function(_dereq_,module,exports){
"use strict";
module.exports = function (SIP) {
var ClientContext;
ClientContext = function (ua, method, target, options) {
var originalTarget = target;
// Validate arguments
if (target === undefined) {
throw new TypeError('Not enough arguments');
}
this.ua = ua;
this.logger = ua.getLogger('sip.clientcontext');
this.method = method;
target = ua.normalizeTarget(target);
if (!target) {
throw new TypeError('Invalid target: ' + originalTarget);
}
/* Options
* - extraHeaders
* - params
* - contentType
* - body
*/
options = Object.create(options || Object.prototype);
options.extraHeaders = (options.extraHeaders || []).slice();
if (options.contentType) {
this.contentType = options.contentType;
options.extraHeaders.push('Content-Type: ' + this.contentType);
}
// Build the request
this.request = new SIP.OutgoingRequest(this.method,
target,
this.ua,
options.params,
options.extraHeaders);
if (options.body) {
this.body = options.body;
this.request.body = this.body;
}
/* Set other properties from the request */
this.localIdentity = this.request.from;
this.remoteIdentity = this.request.to;
this.data = {};
};
ClientContext.prototype = Object.create(SIP.EventEmitter.prototype);
ClientContext.prototype.send = function () {
(new SIP.RequestSender(this, this.ua)).send();
return this;
};
ClientContext.prototype.cancel = function (options) {
options = options || {};
var cancel_reason = SIP.Utils.getCancelReason(options.status_code, options.reason_phrase);
this.request.cancel(cancel_reason);
this.emit('cancel');
};
ClientContext.prototype.receiveResponse = function (response) {
var cause = SIP.Utils.getReasonPhrase(response.status_code);
switch(true) {
case /^1[0-9]{2}$/.test(response.status_code):
this.emit('progress', response, cause);
break;
case /^2[0-9]{2}$/.test(response.status_code):
if(this.ua.applicants[this]) {
delete this.ua.applicants[this];
}
this.emit('accepted', response, cause);
break;
default:
if(this.ua.applicants[this]) {
delete this.ua.applicants[this];
}
this.emit('rejected', response, cause);
this.emit('failed', response, cause);
break;
}
};
ClientContext.prototype.onRequestTimeout = function () {
this.emit('failed', null, SIP.C.causes.REQUEST_TIMEOUT);
};
ClientContext.prototype.onTransportError = function () {
this.emit('failed', null, SIP.C.causes.CONNECTION_ERROR);
};
SIP.ClientContext = ClientContext;
};
},{}],4:[function(_dereq_,module,exports){
"use strict";
/**
* @fileoverview SIP Constants
*/
/**
* SIP Constants.
* @augments SIP
*/
module.exports = function (name, version) {
return {
USER_AGENT: name +'/'+ version,
// SIP scheme
SIP: 'sip',
SIPS: 'sips',
// End and Failure causes
causes: {
// Generic error causes
CONNECTION_ERROR: 'Connection Error',
REQUEST_TIMEOUT: 'Request Timeout',
SIP_FAILURE_CODE: 'SIP Failure Code',
INTERNAL_ERROR: 'Internal Error',
// SIP error causes
BUSY: 'Busy',
REJECTED: 'Rejected',
REDIRECTED: 'Redirected',
UNAVAILABLE: 'Unavailable',
NOT_FOUND: 'Not Found',
ADDRESS_INCOMPLETE: 'Address Incomplete',
INCOMPATIBLE_SDP: 'Incompatible SDP',
AUTHENTICATION_ERROR: 'Authentication Error',
DIALOG_ERROR: 'Dialog Error',
// Session error causes
WEBRTC_NOT_SUPPORTED: 'WebRTC Not Supported',
WEBRTC_ERROR: 'WebRTC Error',
CANCELED: 'Canceled',
NO_ANSWER: 'No Answer',
EXPIRES: 'Expires',
NO_ACK: 'No ACK',
NO_PRACK: 'No PRACK',
USER_DENIED_MEDIA_ACCESS: 'User Denied Media Access',
BAD_MEDIA_DESCRIPTION: 'Bad Media Description',
RTP_TIMEOUT: 'RTP Timeout'
},
supported: {
UNSUPPORTED: 'none',
SUPPORTED: 'supported',
REQUIRED: 'required'
},
SIP_ERROR_CAUSES: {
REDIRECTED: [300,301,302,305,380],
BUSY: [486,600],
REJECTED: [403,603],
NOT_FOUND: [404,604],
UNAVAILABLE: [480,410,408,430],
ADDRESS_INCOMPLETE: [484],
INCOMPATIBLE_SDP: [488,606],
AUTHENTICATION_ERROR:[401,407]
},
// SIP Methods
ACK: 'ACK',
BYE: 'BYE',
CANCEL: 'CANCEL',
INFO: 'INFO',
INVITE: 'INVITE',
MESSAGE: 'MESSAGE',
NOTIFY: 'NOTIFY',
OPTIONS: 'OPTIONS',
REGISTER: 'REGISTER',
UPDATE: 'UPDATE',
SUBSCRIBE: 'SUBSCRIBE',
REFER: 'REFER',
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
*/
REASON_PHRASE: {
100: 'Trying',
180: 'Ringing',
181: 'Call Is Being Forwarded',
182: 'Queued',
183: 'Session Progress',
199: 'Early Dialog Terminated', // draft-ietf-sipcore-199
200: 'OK',
202: 'Accepted', // RFC 3265
204: 'No Notification', //RFC 5839
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', // RFC 3903
413: 'Request Entity Too Large',
414: 'Request-URI Too Long',
415: 'Unsupported Media Type',
416: 'Unsupported URI Scheme',
417: 'Unknown Resource-Priority', // RFC 4412
420: 'Bad Extension',
421: 'Extension Required',
422: 'Session Interval Too Small', // RFC 4028
423: 'Interval Too Brief',
428: 'Use Identity Header', // RFC 4474
429: 'Provide Referrer Identity', // RFC 3892
430: 'Flow Failed', // RFC 5626
433: 'Anonymity Disallowed', // RFC 5079
436: 'Bad Identity-Info', // RFC 4474
437: 'Unsupported Certificate', // RFC 4744
438: 'Invalid Identity Header', // RFC 4744
439: 'First Hop Lacks Outbound Support', // RFC 5626
440: 'Max-Breadth Exceeded', // RFC 5393
469: 'Bad Info Package', // draft-ietf-sipcore-info-events
470: 'Consent Needed', // RFC 5360
478: 'Unresolvable Destination', // Custom code copied from Kamailio.
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', // RFC 3265
491: 'Request Pending',
493: 'Undecipherable',
494: 'Security Agreement Required', // RFC 3329
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', // RFC 3312
600: 'Busy Everywhere',
603: 'Decline',
604: 'Does Not Exist Anywhere',
606: 'Not Acceptable'
}
};
};
},{}],5:[function(_dereq_,module,exports){
"use strict";
/**
* @fileoverview In-Dialog Request Sender
*/
/**
* @augments SIP.Dialog
* @class Class creating an In-dialog request sender.
* @param {SIP.Dialog} dialog
* @param {Object} applicant
* @param {SIP.OutgoingRequest} request
*/
/**
* @fileoverview in-Dialog Request Sender
*/
module.exports = function (SIP) {
var RequestSender;
RequestSender = function(dialog, applicant, request) {
this.dialog = dialog;
this.applicant = applicant;
this.request = request;
// RFC3261 14.1 Modifying an Existing Session. UAC Behavior.
this.reattempt = false;
this.reattemptTimer = null;
};
RequestSender.prototype = {
send: function() {
var self = this,
request_sender = new SIP.RequestSender(this, this.dialog.owner.ua);
request_sender.send();
// RFC3261 14.2 Modifying an Existing Session -UAC BEHAVIOR-
if (this.request.method === SIP.C.INVITE && request_sender.clientTransaction.state !== SIP.Transactions.C.STATUS_TERMINATED) {
this.dialog.uac_pending_reply = true;
request_sender.clientTransaction.on('stateChanged', function stateChanged(){
if (this.state === SIP.Transactions.C.STATUS_ACCEPTED ||
this.state === SIP.Transactions.C.STATUS_COMPLETED ||
this.state === SIP.Transactions.C.STATUS_TERMINATED) {
this.removeListener('stateChanged', stateChanged);
self.dialog.uac_pending_reply = false;
if (self.dialog.uas_pending_reply === false) {
self.dialog.owner.onReadyToReinvite();
}
}
});
}
},
onRequestTimeout: function() {
this.applicant.onRequestTimeout();
},
onTransportError: function() {
this.applicant.onTransportError();
},
receiveResponse: function(response) {
var self = this;
// 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.applicant.onDialogError(response);
} else if (response.method === SIP.C.INVITE && response.status_code === 491) {
if (this.reattempt) {
this.applicant.receiveResponse(response);
} else {
this.request.cseq.value = this.dialog.local_seqnum += 1;
this.reattemptTimer = SIP.Timers.setTimeout(
function() {
if (self.applicant.owner.status !== SIP.Session.C.STATUS_TERMINATED) {
self.reattempt = true;
self.request_sender.send();
}
},
this.getReattemptTimeout()
);
}
} else {
this.applicant.receiveResponse(response);
}
}
};
return RequestSender;
};
},{}],6:[function(_dereq_,module,exports){
"use strict";
/**
* @fileoverview SIP Dialog
*/
/**
* @augments SIP
* @class Class creating a SIP dialog.
* @param {SIP.RTCSession} owner
* @param {SIP.IncomingRequest|SIP.IncomingResponse} message
* @param {Enum} type UAC / UAS
* @param {Enum} state SIP.Dialog.C.STATUS_EARLY / SIP.Dialog.C.STATUS_CONFIRMED
*/
module.exports = function (SIP) {
var RequestSender = _dereq_('./Dialog/RequestSender')(SIP);
var Dialog,
C = {
// Dialog states
STATUS_EARLY: 1,
STATUS_CONFIRMED: 2
};
// RFC 3261 12.1
Dialog = function(owner, message, type, state) {
var contact;
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 SIP.IncomingResponse) {
state = (message.status_code < 200) ? C.STATUS_EARLY : C.STATUS_CONFIRMED;
} else {
// Create confirmed dialog if state is not defined
state = state || C.STATUS_CONFIRMED;
}
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: function() {
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.invite_seqnum = message.cseq;
this.local_seqnum = message.cseq;
}
// 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: function() {
return this.call_id + this.local_tag + this.remote_tag;
}
};
this.state = state;
this.invite_seqnum = message.cseq;
this.local_seqnum = message.cseq;
this.local_uri = message.parseHeader('from').uri;
this.pracked = [];
this.remote_uri = message.parseHeader('to').uri;
this.remote_target = contact.uri;
this.route_set = message.getHeaders('record-route').reverse();
//RENDERBODY
if (this.state === C.STATUS_EARLY && (!owner.hasOffer)) {
this.mediaHandler = owner.mediaHandlerFactory(owner);
}
}
this.logger = owner.ua.getLogger('sip.dialog', this.id.toString());
this.owner = owner;
owner.ua.dialogs[this.id.toString()] = this;
this.logger.log('new ' + type + ' dialog created with status ' + (this.state === C.STATUS_EARLY ? 'EARLY': 'CONFIRMED'));
owner.emit('dialog', this);
};
Dialog.prototype = {
/**
* @param {SIP.IncomingMessage} message
* @param {Enum} UAC/UAS
*/
update: function(message, type) {
this.state = C.STATUS_CONFIRMED;
this.logger.log('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: function() {
this.logger.log('dialog ' + this.id.toString() + ' deleted');
if (this.mediaHandler && this.state !== C.STATUS_CONFIRMED) {
this.mediaHandler.peerConnection.close();
}
delete this.owner.ua.dialogs[this.id.toString()];
},
/**
* @param {String} method request method
* @param {Object} extraHeaders extra headers
* @returns {SIP.OutgoingRequest}
*/
// RFC 3261 12.2.1.1
createRequest: function(method, extraHeaders, body) {
var cseq, request;
extraHeaders = (extraHeaders || []).slice();
if(!this.local_seqnum) { this.local_seqnum = Math.floor(Math.random() * 10000); }
cseq = (method === SIP.C.CANCEL || method === SIP.C.ACK) ? this.invite_seqnum : this.local_seqnum += 1;
request = new SIP.OutgoingRequest(
method,
this.remote_target,
this.owner.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);
request.dialog = this;
return request;
},
/**
* @param {SIP.IncomingRequest} request
* @returns {Boolean}
*/
// RFC 3261 12.2.2
checkInDialogRequest: function(request) {
var self = this;
if(!this.remote_seqnum) {
this.remote_seqnum = request.cseq;
} else if(request.cseq < this.remote_seqnum) {
//Do not try to reply to an ACK request.
if (request.method !== SIP.C.ACK) {
request.reply(500);
}
if (request.cseq === this.invite_seqnum) {
return true;
}
return false;
} else if(request.cseq > this.remote_seqnum) {
this.remote_seqnum = request.cseq;
}
switch(request.method) {
// RFC3261 14.2 Modifying an Existing Session -UAS BEHAVIOR-
case SIP.C.INVITE:
if (this.uac_pending_reply === true) {
request.reply(491);
} else if (this.uas_pending_reply === true) {
var retryAfter = (Math.random() * 10 | 0) + 1;
request.reply(500, null, ['Retry-After:' + retryAfter]);
return false;
} else {
this.uas_pending_reply = true;
request.server_transaction.on('stateChanged', function stateChanged(){
if (this.state === SIP.Transactions.C.STATUS_ACCEPTED ||
this.state === SIP.Transactions.C.STATUS_COMPLETED ||
this.state === SIP.Transactions.C.STATUS_TERMINATED) {
this.removeListener('stateChanged', stateChanged);
self.uas_pending_reply = false;
if (self.uac_pending_reply === false) {
self.owner.onReadyToReinvite();
}
}
});
}
// 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', function(){
if (this.state === SIP.Transactions.C.STATUS_ACCEPTED) {
self.remote_target = request.parseHeader('contact').uri;
}
});
}
break;
case SIP.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', function(){
if (this.state === SIP.Transactions.C.STATUS_COMPLETED) {
self.remote_target = request.parseHeader('contact').uri;
}
});
}
break;
}
return true;
},
sendRequest: function(applicant, method, options) {
options = options || {};
var
extraHeaders = (options.extraHeaders || []).slice(),
body = options.body || null,
request = this.createRequest(method, extraHeaders, body),
request_sender = new RequestSender(this, applicant, request);
request_sender.send();
return request;
},