forked from BetterVoice/iOS-SIP.js
-
Notifications
You must be signed in to change notification settings - Fork 1
/
sip-0.6.4.js
11106 lines (9549 loc) · 336 KB
/
sip-0.6.4.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.6.4
* Copyright (c) 2014-2014 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){
module.exports={
"name": "sip.js",
"title": "SIP.js",
"description": "A simple, intuitive, and powerful JavaScript signaling library",
"version": "0.6.4",
"main": "src/SIP.js",
"homepage": "http://sipjs.com",
"author": "Will Mitchell <[email protected]>",
"contributors": [
{
"url": "http://sipjs.com/authors/"
}
],
"repository": {
"type": "git",
"url": "https://github.com/onsip/SIP.js.git"
},
"keywords": [
"sip",
"websocket",
"webrtc",
"library",
"javascript"
],
"devDependencies": {
"grunt": "~0.4.0",
"grunt-cli": "~0.1.6",
"grunt-contrib-jasmine": "~0.6.0",
"grunt-contrib-jshint": ">0.5.0",
"grunt-contrib-uglify": "~0.2.0",
"grunt-peg": "~1.3.1",
"grunt-trimtrailingspaces": "^0.4.0",
"node-minify": "~0.7.2",
"pegjs": "0.8.0",
"sdp-transform": "~0.4.0",
"grunt-contrib-copy": "^0.5.0",
"browserify": "^4.1.8",
"grunt-browserify": "^2.1.0"
},
"engines": {
"node": ">=0.8"
},
"license": "MIT",
"scripts": {
"test": "grunt travis --verbose"
}
}
},{}],2:[function(_dereq_,module,exports){
module.exports = function (SIP) {
var ClientContext;
ClientContext = function (ua, method, target, options) {
var params, extraHeaders,
originalTarget = target,
events = [
'progress',
'accepted',
'rejected',
'failed',
'cancel'
];
if (target === undefined) {
throw new TypeError('Not enough arguments');
}
// Check target validity
target = ua.normalizeTarget(target);
if (!target) {
throw new TypeError('Invalid target: ' + originalTarget);
}
this.ua = ua;
this.logger = ua.getLogger('sip.clientcontext');
this.method = method;
params = options && options.params;
extraHeaders = (options && options.extraHeaders || []).slice();
if (options && options.body) {
this.body = options.body;
}
if (options && options.contentType) {
this.contentType = options.contentType;
extraHeaders.push('Content-Type: ' + this.contentType);
}
this.request = new SIP.OutgoingRequest(this.method, target, this.ua, params, extraHeaders);
this.localIdentity = this.request.from;
this.remoteIdentity = this.request.to;
if (this.body) {
this.request.body = this.body;
}
this.data = {};
this.initEvents(events);
};
ClientContext.prototype = new SIP.EventEmitter();
ClientContext.prototype.send = function () {
(new SIP.RequestSender(this, this.ua)).send();
return this;
};
ClientContext.prototype.cancel = function (options) {
options = options || {};
var
status_code = options.status_code,
reason_phrase = options.reason_phrase,
cancel_reason;
if (status_code && status_code < 200 || status_code > 699) {
throw new TypeError('Invalid status_code: ' + status_code);
} else if (status_code) {
reason_phrase = reason_phrase || SIP.C.REASON_PHRASE[status_code] || '';
cancel_reason = 'SIP ;cause=' + status_code + ' ;text="' + reason_phrase + '"';
}
this.request.cancel(cancel_reason);
this.emit('cancel');
};
ClientContext.prototype.receiveResponse = function (response) {
var cause = SIP.C.REASON_PHRASE[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;
};
},{}],3:[function(_dereq_,module,exports){
/**
* @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'
}
};
};
},{}],4:[function(_dereq_,module,exports){
/**
* @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.off('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;
};
},{}],5:[function(_dereq_,module,exports){
/**
* @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, RequestSender) {
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'));
};
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.off('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;
},
/**
* @param {SIP.IncomingRequest} request
*/
receiveRequest: function(request) {
//Check in-dialog request
if(!this.checkInDialogRequest(request)) {
return;
}
this.owner.receiveRequest(request);
}
};
Dialog.C = C;
SIP.Dialog = Dialog;
};
},{}],6:[function(_dereq_,module,exports){
/**
* @fileoverview SIP Digest Authentication
*/
/**
* SIP Digest Authentication.
* @augments SIP.
* @function Digest Authentication
* @param {SIP.UA} ua
*/
module.exports = function (Utils) {
var DigestAuthentication;
DigestAuthentication = function(ua) {
this.logger = ua.getLogger('sipjs.digestauthentication');
this.username = ua.configuration.authorizationUser;
this.password = ua.configuration.password;
this.cnonce = null;
this.nc = 0;
this.ncHex = '00000000';
this.response = null;
};
/**
* Performs Digest authentication given a SIP request and the challenge
* received in a response to that request.
* Returns true if credentials were successfully generated, false otherwise.
*
* @param {SIP.OutgoingRequest} request
* @param {Object} challenge
*/
DigestAuthentication.prototype.authenticate = function(request, challenge) {
// Inspect and validate the challenge.
this.algorithm = challenge.algorithm;
this.realm = challenge.realm;
this.nonce = challenge.nonce;
this.opaque = challenge.opaque;
this.stale = challenge.stale;
if (this.algorithm) {
if (this.algorithm !== 'MD5') {
this.logger.warn('challenge with Digest algorithm different than "MD5", authentication aborted');
return false;
}
} else {
this.algorithm = 'MD5';
}
if (! this.realm) {
this.logger.warn('challenge without Digest realm, authentication aborted');
return false;
}
if (! this.nonce) {
this.logger.warn('challenge without Digest nonce, authentication aborted');
return false;
}
// 'qop' can contain a list of values (Array). Let's choose just one.
if (challenge.qop) {
if (challenge.qop.indexOf('auth') > -1) {
this.qop = 'auth';
} else if (challenge.qop.indexOf('auth-int') > -1) {
this.qop = 'auth-int';
} else {
// Otherwise 'qop' is present but does not contain 'auth' or 'auth-int', so abort here.
this.logger.warn('challenge without Digest qop different than "auth" or "auth-int", authentication aborted');
return false;
}
} else {
this.qop = null;
}
// Fill other attributes.
this.method = request.method;
this.uri = request.ruri;
this.cnonce = Utils.createRandomToken(12);
this.nc += 1;
this.updateNcHex();
// nc-value = 8LHEX. Max value = 'FFFFFFFF'.
if (this.nc === 4294967296) {
this.nc = 1;
this.ncHex = '00000001';
}
// Calculate the Digest "response" value.
this.calculateResponse();
return true;
};
/**
* Generate Digest 'response' value.
* @private
*/
DigestAuthentication.prototype.calculateResponse = function() {
var ha1, ha2;
// HA1 = MD5(A1) = MD5(username:realm:password)
ha1 = Utils.calculateMD5(this.username + ":" + this.realm + ":" + this.password);
if (this.qop === 'auth') {
// HA2 = MD5(A2) = MD5(method:digestURI)
ha2 = Utils.calculateMD5(this.method + ":" + this.uri);
// response = MD5(HA1:nonce:nonceCount:credentialsNonce:qop:HA2)
this.response = Utils.calculateMD5(ha1 + ":" + this.nonce + ":" + this.ncHex + ":" + this.cnonce + ":auth:" + ha2);
} else if (this.qop === 'auth-int') {
// HA2 = MD5(A2) = MD5(method:digestURI:MD5(entityBody))
ha2 = Utils.calculateMD5(this.method + ":" + this.uri + ":" + Utils.calculateMD5(this.body ? this.body : ""));
// response = MD5(HA1:nonce:nonceCount:credentialsNonce:qop:HA2)
this.response = Utils.calculateMD5(ha1 + ":" + this.nonce + ":" + this.ncHex + ":" + this.cnonce + ":auth-int:" + ha2);
} else if (this.qop === null) {
// HA2 = MD5(A2) = MD5(method:digestURI)
ha2 = Utils.calculateMD5(this.method + ":" + this.uri);
// response = MD5(HA1:nonce:HA2)
this.response = Utils.calculateMD5(ha1 + ":" + this.nonce + ":" + ha2);
}
};
/**
* Return the Proxy-Authorization or WWW-Authorization header value.
*/
DigestAuthentication.prototype.toString = function() {
var auth_params = [];
if (! this.response) {
throw new Error('response field does not exist, cannot generate Authorization header');
}
auth_params.push('algorithm=' + this.algorithm);
auth_params.push('username="' + this.username + '"');
auth_params.push('realm="' + this.realm + '"');
auth_params.push('nonce="' + this.nonce + '"');
auth_params.push('uri="' + this.uri + '"');
auth_params.push('response="' + this.response + '"');
if (this.opaque) {
auth_params.push('opaque="' + this.opaque + '"');
}
if (this.qop) {
auth_params.push('qop=' + this.qop);
auth_params.push('cnonce="' + this.cnonce + '"');
auth_params.push('nc=' + this.ncHex);
}
return 'Digest ' + auth_params.join(', ');
};
/**
* Generate the 'nc' value as required by Digest in this.ncHex by reading this.nc.
* @private
*/
DigestAuthentication.prototype.updateNcHex = function() {
var hex = Number(this.nc).toString(16);
this.ncHex = '00000000'.substr(0, 8-hex.length) + hex;
};
return DigestAuthentication;
};
},{}],7:[function(_dereq_,module,exports){
/**
* @fileoverview EventEmitter
*/
/**
* @augments SIP
* @class Class creating an event emitter.
*/
module.exports = function (SIP) {
var
EventEmitter,
Event,
logger = new SIP.LoggerFactory().getLogger('sip.eventemitter'),
C = {
MAX_LISTENERS: 10
};
EventEmitter = function(){};
EventEmitter.prototype = {
/**
* Initialize events dictionaries.
* @param {Array} events
*/
initEvents: function(events) {
this.events = {};
return this.initMoreEvents(events);
},
initMoreEvents: function(events) {
var idx;
if (!this.logger) {
this.logger = logger;
}
this.maxListeners = C.MAX_LISTENERS;
for (idx = 0; idx < events.length; idx++) {
if (!this.events[events[idx]]) {
this.logger.log('adding event '+ events[idx]);
this.events[events[idx]] = [];
} else {
this.logger.log('skipping event '+ events[idx]+ ' - Event exists');
}
}
return this;
},
/**
* Check whether an event exists or not.
* @param {String} event
* @returns {Boolean}
*/
checkEvent: function(event) {
return !!(this.events && this.events[event]);
},
/**
* Check whether an event exists and has at least one listener or not.
* @param {String} event
* @returns {Boolean}
*/
checkListener: function(event) {
return this.checkEvent(event) && this.events[event].length > 0;
},
/**
* Add a listener to the end of the listeners array for the specified event.
* @param {String} event
* @param {Function} listener
*/
on: function(event, listener, bindTarget) {
if (listener === undefined) {
return this;
} else if (typeof listener !== 'function') {
this.logger.error('listener must be a function');
return this;
} else if (!this.checkEvent(event)) {
this.logger.error('unable to add a listener to a nonexistent event '+ event);
throw new TypeError('Invalid or uninitialized event: ' + event);
}
var listenerObj = { listener: listener };
if (bindTarget) {
listenerObj.bindTarget = bindTarget;
}
if (this.events[event].length >= this.maxListeners) {
this.logger.warn('max listeners exceeded for event '+ event);
return this;
}
this.events[event].push(listenerObj);
this.logger.log('new listener added to event '+ event);
return this;
},
/**
* Add a one time listener for the specified event.
* The listener is invoked only the next time the event is fired, then it is removed.
* @param {String} event
* @param {Function} listener
*/
once: function(event, listener, bindTarget) {
var self = this;
function listenOnce () {
listener.apply(this, arguments);
self.off(event, listenOnce, bindTarget);
}
return this.on(event, listenOnce, bindTarget);
},
/**
* Remove a listener from the listener array for the specified event.