-
Notifications
You must be signed in to change notification settings - Fork 164
Expand file tree
/
Copy pathSIPTransactionImpl.java
More file actions
1737 lines (1499 loc) · 59.6 KB
/
Copy pathSIPTransactionImpl.java
File metadata and controls
1737 lines (1499 loc) · 59.6 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
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
/*
* Conditions Of Use
*
* This software was developed by employees of the National Institute of
* Standards and Technology (NIST), an agency of the Federal Government.
* Pursuant to title 15 Untied States Code Section 105, works of NIST
* employees are not subject to copyright protection in the United States
* and are considered to be in the public domain. As a result, a formal
* license is not needed to use the software.
*
* This software is provided by NIST as a service and is expressly
* provided "AS IS." NIST MAKES NO WARRANTY OF ANY KIND, EXPRESS, IMPLIED
* OR STATUTORY, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTY OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT
* AND DATA ACCURACY. NIST does not warrant or make any representations
* regarding the use of the software or the results thereof, including but
* not limited to the correctness, accuracy, reliability or usefulness of
* the software.
*
* Permission to use this software is contingent upon your acceptance
* of the terms of this agreement
*
* .
*
*/
package gov.nist.javax.sip.stack;
import gov.nist.core.CommonLogger;
import gov.nist.core.InternalErrorHandler;
import gov.nist.core.LogLevels;
import gov.nist.core.LogWriter;
import gov.nist.core.ServerLogger;
import gov.nist.core.StackLogger;
import gov.nist.javax.sip.ReleaseReferencesStrategy;
import gov.nist.javax.sip.SIPConstants;
import gov.nist.javax.sip.SipProviderImpl;
import gov.nist.javax.sip.SipStackImpl;
import gov.nist.javax.sip.address.AddressFactoryImpl;
import gov.nist.javax.sip.header.Via;
import gov.nist.javax.sip.message.SIPMessage;
import gov.nist.javax.sip.message.SIPRequest;
import gov.nist.javax.sip.message.SIPResponse;
import gov.nist.javax.sip.stack.SIPClientTransactionImpl.ExpiresTimerTask;
import java.io.IOException;
import java.net.InetAddress;
import java.security.cert.Certificate;
import java.security.cert.CertificateParsingException;
import java.security.cert.X509Certificate;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.ReentrantLock;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.sip.Dialog;
import javax.sip.IOExceptionEvent;
import javax.sip.TransactionState;
import javax.sip.address.SipURI;
import javax.sip.message.Request;
import javax.sip.message.Response;
/*
* Modifications for TLS Support added by Daniel J. Martinez Manzano
* <dani@dif.um.es> Bug fixes by Jeroen van Bemmel (JvB) and others.
*/
/**
* Abstract class to support both client and server transactions. Provides an
* encapsulation of a message channel, handles timer events, and creation of the
* Via header for a message.
*
* @author Jeff Keyser
* @author M. Ranganathan
*
*
* @version 1.2 $Revision: 1.100 $ $Date: 2010-12-02 22:04:13 $
*/
public abstract class SIPTransactionImpl implements SIPTransaction {
private static StackLogger logger = CommonLogger.getLogger(SIPTransaction.class);
// Contribution on http://java.net/jira/browse/JSIP-417 from Alexander Saveliev
private static final Pattern EXTRACT_CN = Pattern.compile(".*CN\\s*=\\s*([\\w*\\.\\-_]+).*");
protected boolean toListener; // Flag to indicate that the listener gets
// to see the event.
protected int baseTimerInterval = SIPTransactionStack.BASE_TIMER_INTERVAL;
/**
* 5 sec Maximum duration a message will remain in the network
*/
protected int T4 = 5000 / baseTimerInterval;
/**
* The maximum retransmit interval for non-INVITE requests and INVITE
* responses
*/
protected int T2 = 4000 / baseTimerInterval;
protected int timerI = T4;
protected int timerK = T4;
protected int timerD = 32000 / baseTimerInterval;
protected int timerB = 32000 / baseTimerInterval;
// Proposed feature for next release.
protected transient Object applicationData;
protected SIPResponse lastResponse;
// private SIPDialog dialog;
protected boolean isMapped;
private transient TransactionSemaphore semaphore;
// protected boolean eventPending; // indicate that an event is pending
// here.
protected String transactionId; // Transaction Id.
// Audit tag used by the SIP Stack audit
protected long auditTag = 0;
// Parent stack for this transaction
protected transient SIPTransactionStack sipStack;
// Original request that is being handled by this transaction
protected SIPRequest originalRequest;
//jeand we nullify the originalRequest fast to save on mem and help GC
// so we keep only those data instead
protected byte[] originalRequestBytes;
protected long originalRequestCSeqNumber;
protected String originalRequestBranch;
protected boolean originalRequestHasPort;
// Underlying channel being used to send messages for this transaction
protected transient MessageChannel encapsulatedChannel;
protected AtomicBoolean transactionTimerStarted = new AtomicBoolean(false);
// Transaction branch ID
private String branch;
// Method of the Request used to create the transaction.
private String method;
// Current transaction state
private int currentState = -1;
// Number of ticks the retransmission timer was set to last
private transient int retransmissionTimerLastTickCount;
// Number of ticks before the message is retransmitted
private transient int retransmissionTimerTicksLeft;
// Number of ticks before the transaction times out
protected int timeoutTimerTicksLeft;
// List of event listeners for this transaction
private transient Set<SIPTransactionEventListener> eventListeners;
// Counter for caching of connections.
// Connection lingers for collectionTime
// after the Transaction goes to terminated state.
protected int collectionTime;
private boolean terminatedEventDelivered;
// aggressive flag to optimize eagerly
private ReleaseReferencesStrategy releaseReferencesStrategy;
// caching flags
private Boolean inviteTransaction = null;
private Boolean dialogCreatingTransaction = null;
// caching fork id
private String forkId = null;
protected String mergeId = null;
public ExpiresTimerTask expiresTimerTask;
// http://java.net/jira/browse/JSIP-420
private MaxTxLifeTimeListener maxTxLifeTimeListener;
/**
* @see gov.nist.javax.sip.stack.SIPTransaction#getBranchId()
*/
@Override
public String getBranchId() {
return this.branch;
}
// [Issue 284] https://jain-sip.dev.java.net/issues/show_bug.cgi?id=284
// JAIN SIP drops 200 OK due to race condition
// Wrapper that uses a semaphore for non reentrant listener
// and a lock for reetrant listener to avoid race conditions
// when 2 responses 180/200 OK arrives at the same time
class TransactionSemaphore {
private static final long serialVersionUID = -1634100711669020804L;
Semaphore sem = null;
ReentrantLock lock = null;
public TransactionSemaphore() {
if(((SipStackImpl)sipStack).isReEntrantListener()) {
lock = new ReentrantLock();
} else {
sem = new Semaphore(1, true);
}
}
public boolean acquire() {
try {
if(((SipStackImpl)sipStack).isReEntrantListener()) {
lock.lock();
} else {
sem.acquire();
}
return true;
} catch (Exception ex) {
logger.logError("Unexpected exception acquiring sem",
ex);
InternalErrorHandler.handleException(ex);
return false;
}
}
public boolean tryAcquire() {
try {
if(((SipStackImpl)sipStack).isReEntrantListener()) {
return lock.tryLock(sipStack.maxListenerResponseTime, TimeUnit.SECONDS);
} else {
return sem.tryAcquire(sipStack.maxListenerResponseTime, TimeUnit.SECONDS);
}
} catch (Exception ex) {
logger.logError("Unexpected exception trying acquiring sem",
ex);
InternalErrorHandler.handleException(ex);
return false;
}
}
public void release() {
try {
if(((SipStackImpl)sipStack).isReEntrantListener()) {
if(lock.isHeldByCurrentThread()) {
lock.unlock();
}
} else {
sem.release();
}
} catch (Exception ex) {
logger.logError("Unexpected exception releasing sem",
ex);
}
}
}
/**
* The linger timer is used to remove the transaction from the transaction
* table after it goes into terminated state. This allows connection caching
* and also takes care of race conditins.
*
*
*/
class LingerTimer extends SIPStackTimerTask {
public LingerTimer() {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
SIPTransaction sipTransaction = SIPTransactionImpl.this;
logger.logDebug("LingerTimer : "
+ sipTransaction.getTransactionId());
}
}
public void runTask() {
cleanUp();
}
}
/**
* http://java.net/jira/browse/JSIP-420
* This timer task will terminate the transaction after a configurable time
*
*/
class MaxTxLifeTimeListener extends SIPStackTimerTask {
SIPTransaction sipTransaction = SIPTransactionImpl.this;
public void runTask() {
try {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug("Fired MaxTxLifeTimeListener for tx " + sipTransaction + " , tx id "+ sipTransaction.getTransactionId() + " , state " + sipTransaction.getState());
}
raiseErrorEvent(SIPTransactionErrorEvent.TIMEOUT_ERROR);
SIPStackTimerTask myTimer = new LingerTimer();
if(sipStack.getConnectionLingerTimer() != 0) {
sipStack.getTimer().schedule(myTimer, sipStack.getConnectionLingerTimer() * 1000);
} else {
myTimer.runTask();
}
maxTxLifeTimeListener = null;
} catch (Exception ex) {
logger.logError("unexpected exception", ex);
}
}
}
/**
* Transaction constructor.
*
* @param newParentStack
* Parent stack for this transaction.
* @param newEncapsulatedChannel
* Underlying channel for this transaction.
*/
protected SIPTransactionImpl(SIPTransactionStack newParentStack,
MessageChannel newEncapsulatedChannel) {
sipStack = newParentStack;
this.semaphore = new TransactionSemaphore();
encapsulatedChannel = newEncapsulatedChannel;
if (this.isReliable()) {
encapsulatedChannel.useCount++;
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG))
logger
.logDebug("use count for encapsulated channel"
+ this
+ " "
+ encapsulatedChannel.useCount );
}
this.currentState = -1;
disableRetransmissionTimer();
disableTimeoutTimer();
eventListeners = new CopyOnWriteArraySet<SIPTransactionEventListener>();
// Always add the parent stack as a listener
// of this transaction
addEventListener(newParentStack);
releaseReferencesStrategy = sipStack.getReleaseReferencesStrategy();
}
/**
* @see gov.nist.javax.sip.stack.SIPTransaction#cleanUp()
*/
@Override
public abstract void cleanUp();
/**
* @see gov.nist.javax.sip.stack.SIPTransaction#setOriginalRequest(gov.nist.javax.sip.message.SIPRequest)
*/
@Override
public void setOriginalRequest(SIPRequest newOriginalRequest) {
// Branch value of topmost Via header
String newBranch;
final String newTransactionId = newOriginalRequest.getTransactionId();
if (this.originalRequest != null
&& (!this.originalRequest.getTransactionId().equals(
newTransactionId))) {
sipStack.removeTransactionHash(this);
}
// This will be cleared later.
this.originalRequest = newOriginalRequest;
this.originalRequestCSeqNumber = newOriginalRequest.getCSeq().getSeqNumber();
final Via topmostVia = newOriginalRequest.getTopmostVia();
this.originalRequestBranch = topmostVia.getBranch();
this.originalRequestHasPort = topmostVia.hasPort();
int originalRequestViaPort = topmostVia.getPort();
if ( originalRequestViaPort == -1 ) {
if (topmostVia.getTransport().equalsIgnoreCase("TLS") ) {
originalRequestViaPort = 5061;
} else {
originalRequestViaPort = 5060;
}
}
// just cache the control information so the
// original request can be released later.
this.method = newOriginalRequest.getMethod();
this.transactionId = newTransactionId;
originalRequest.setTransaction(this);
// If the message has an explicit branch value set,
newBranch = topmostVia.getBranch();
if (newBranch != null) {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG))
logger.logDebug("Setting Branch id : " + newBranch);
// Override the default branch with the one
// set by the message
setBranch(newBranch);
} else {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG))
logger.logDebug("Branch id is null - compute TID!"
+ newOriginalRequest.encode());
setBranch(newTransactionId);
}
}
/**
* @see gov.nist.javax.sip.stack.SIPTransaction#getOriginalRequest()
*/
@Override
public SIPRequest getOriginalRequest() {
return this.originalRequest;
}
/**
* @see gov.nist.javax.sip.stack.SIPTransaction#getRequest()
*/
@Override
public Request getRequest() {
if(getReleaseReferencesStrategy() != ReleaseReferencesStrategy.None && originalRequest == null && originalRequestBytes != null) {
if(logger.isLoggingEnabled(StackLogger.TRACE_WARN)) {
logger.logWarning("reparsing original request " + originalRequestBytes + " since it was eagerly cleaned up, but beware this is not efficient with the aggressive flag set !");
}
try {
originalRequest = (SIPRequest) sipStack.getMessageParserFactory().createMessageParser(sipStack).parseSIPMessage(originalRequestBytes, true, false, null);
// originalRequestBytes = null;
} catch (ParseException e) {
logger.logError("message " + originalRequestBytes + " could not be reparsed !");
}
}
return (Request) originalRequest;
}
/**
* @see gov.nist.javax.sip.stack.SIPTransaction#isDialogCreatingTransaction()
*/
@Override
public boolean isDialogCreatingTransaction() {
if (dialogCreatingTransaction == null) {
dialogCreatingTransaction = Boolean.valueOf(isInviteTransaction() || getMethod().equals(Request.SUBSCRIBE) || getMethod().equals(Request.REFER));
}
return dialogCreatingTransaction.booleanValue();
}
/**
* @see gov.nist.javax.sip.stack.SIPTransaction#isInviteTransaction()
*/
@Override
public boolean isInviteTransaction() {
if (inviteTransaction == null) {
inviteTransaction = Boolean.valueOf(getMethod().equals(Request.INVITE));
}
return inviteTransaction.booleanValue();
}
/**
* @see gov.nist.javax.sip.stack.SIPTransaction#isCancelTransaction()
*/
@Override
public boolean isCancelTransaction() {
return getMethod().equals(Request.CANCEL);
}
/**
* @see gov.nist.javax.sip.stack.SIPTransaction#isByeTransaction()
*/
@Override
public boolean isByeTransaction() {
return getMethod().equals(Request.BYE);
}
/**
* @see gov.nist.javax.sip.stack.SIPTransaction#getMessageChannel()
*/
@Override
public MessageChannel getMessageChannel() {
return encapsulatedChannel;
}
/**
* @see gov.nist.javax.sip.stack.SIPTransaction#setBranch(java.lang.String)
*/
@Override
public void setBranch(String newBranch) {
branch = newBranch;
}
/**
* @see gov.nist.javax.sip.stack.SIPTransaction#getBranch()
*/
@Override
public String getBranch() {
if (this.branch == null) {
this.branch = originalRequestBranch;
}
return branch;
}
/**
* @see gov.nist.javax.sip.stack.SIPTransaction#getMethod()
*/
@Override
public String getMethod() {
return this.method;
}
/**
* @see gov.nist.javax.sip.stack.SIPTransaction#getCSeq()
*/
@Override
public long getCSeq() {
return this.originalRequestCSeqNumber;
}
/**
* @see gov.nist.javax.sip.stack.SIPTransaction#setState(int)
*/
@Override
public void setState(int newState) {
// PATCH submitted by sribeyron
if (currentState == TransactionState._COMPLETED) {
if (newState != TransactionState._TERMINATED
&& newState != TransactionState._CONFIRMED)
newState = TransactionState._COMPLETED;
}
if (currentState == TransactionState._CONFIRMED) {
if (newState != TransactionState._TERMINATED)
newState = TransactionState._CONFIRMED;
}
if (currentState != TransactionState._TERMINATED) {
currentState = newState;
}
else
newState = currentState;
// END OF PATCH
if(newState == TransactionState._COMPLETED) {
enableTimeoutTimer(TIMER_H); // timer H must be started around now
}
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug("Transaction:setState " + newState
+ " " + this + " branchID = " + this.getBranch()
+ " isClient = " + (this instanceof SIPClientTransaction));
logger.logStackTrace();
}
}
/**
* @see gov.nist.javax.sip.stack.SIPTransaction#getInternalState()
*/
@Override
public int getInternalState() {
return this.currentState;
}
/**
* @see gov.nist.javax.sip.stack.SIPTransaction#getState()
*/
@Override
public TransactionState getState() {
if(currentState < 0) {
return null;
}
return TransactionState.getObject(this.currentState);
}
/**
* Enables retransmission timer events for this transaction to begin in one
* tick.
*/
protected void enableRetransmissionTimer() {
enableRetransmissionTimer(1);
}
/**
* Enables retransmission timer events for this transaction to begin after
* the number of ticks passed to this routine.
*
* @param tickCount
* Number of ticks before the next retransmission timer event
* occurs.
*/
protected void enableRetransmissionTimer(int tickCount) {
// For INVITE Client transactions, double interval each time
if (isInviteTransaction() && (this instanceof SIPClientTransaction)) {
retransmissionTimerTicksLeft = tickCount;
} else {
// non-INVITE transactions and 3xx-6xx responses are capped at T2
retransmissionTimerTicksLeft = Math.min(tickCount,
getTimerT2());
}
retransmissionTimerLastTickCount = retransmissionTimerTicksLeft;
}
/**
* @see gov.nist.javax.sip.stack.SIPTransaction#disableRetransmissionTimer()
*/
@Override
public void disableRetransmissionTimer() {
retransmissionTimerTicksLeft = -1;
}
/**
* Enables a timeout event to occur for this transaction after the number of
* ticks passed to this method.
*
* @param tickCount
* Number of ticks before this transaction times out.
*/
protected void enableTimeoutTimer(int tickCount) {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG))
logger.logDebug("enableTimeoutTimer " + this
+ " tickCount " + tickCount + " currentTickCount = "
+ timeoutTimerTicksLeft);
timeoutTimerTicksLeft = tickCount;
}
/**
* @see gov.nist.javax.sip.stack.SIPTransaction#disableTimeoutTimer()
*/
@Override
public void disableTimeoutTimer() {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) logger.logDebug("disableTimeoutTimer " + this);
timeoutTimerTicksLeft = -1;
}
/**
* @see gov.nist.javax.sip.stack.SIPTransaction#fireTimer()
*/
@Override
public void fireTimer() {
// If the timeout timer is enabled,
if (timeoutTimerTicksLeft != -1) {
// Count down the timer, and if it has run out,
if (--timeoutTimerTicksLeft == 0) {
fireTimeoutTimer();
}
}
// If the retransmission timer is enabled,
if (retransmissionTimerTicksLeft != -1) {
// Count down the timer, and if it has run out,
if (--retransmissionTimerTicksLeft == 0) {
// Enable this timer to fire again after
// twice the original time
enableRetransmissionTimer(retransmissionTimerLastTickCount * 2);
// Fire the timeout timer
fireRetransmissionTimer();
}
}
}
/**
* @see gov.nist.javax.sip.stack.SIPTransaction#isTerminated()
*/
@Override
public boolean isTerminated() {
return currentState == TransactionState._TERMINATED;
}
/**
* @see gov.nist.javax.sip.stack.SIPTransaction#getHost()
*/
@Override
public String getHost() {
return encapsulatedChannel.getHost();
}
/**
* @see gov.nist.javax.sip.stack.SIPTransaction#getKey()
*/
@Override
public String getKey() {
return encapsulatedChannel.getKey();
}
/**
* @see gov.nist.javax.sip.stack.SIPTransaction#getPort()
*/
@Override
public int getPort() {
return encapsulatedChannel.getPort();
}
/**
* @see gov.nist.javax.sip.stack.SIPTransaction#getSIPStack()
*/
@Override
public SIPTransactionStack getSIPStack() {
return (SIPTransactionStack) sipStack;
}
/**
* @see gov.nist.javax.sip.stack.SIPTransaction#getPeerAddress()
*/
@Override
public String getPeerAddress() {
return this.encapsulatedChannel.getPeerAddress();
}
/**
* @see gov.nist.javax.sip.stack.SIPTransaction#getPeerPort()
*/
@Override
public int getPeerPort() {
return this.encapsulatedChannel.getPeerPort();
}
// @@@ hagai
/**
* @see gov.nist.javax.sip.stack.SIPTransaction#getPeerPacketSourcePort()
*/
@Override
public int getPeerPacketSourcePort() {
return this.encapsulatedChannel.getPeerPacketSourcePort();
}
/**
* @see gov.nist.javax.sip.stack.SIPTransaction#getPeerPacketSourceAddress()
*/
@Override
public InetAddress getPeerPacketSourceAddress() {
return this.encapsulatedChannel.getPeerPacketSourceAddress();
}
public InetAddress getPeerInetAddress() {
return this.encapsulatedChannel.getPeerInetAddress();
}
public String getPeerProtocol() {
return this.encapsulatedChannel.getPeerProtocol();
}
/**
* @see gov.nist.javax.sip.stack.SIPTransaction#getTransport()
*/
@Override
public String getTransport() {
return encapsulatedChannel.getTransport();
}
/**
* @see gov.nist.javax.sip.stack.SIPTransaction#isReliable()
*/
@Override
public boolean isReliable() {
return encapsulatedChannel.isReliable();
}
/**
* @see gov.nist.javax.sip.stack.SIPTransaction#getViaHeader()
*/
@Override
public Via getViaHeader() {
// Via header of the encapulated channel
Via channelViaHeader;
// Add the branch parameter to the underlying
// channel's Via header
channelViaHeader = encapsulatedChannel.getViaHeader();
try {
channelViaHeader.setBranch(branch);
} catch (java.text.ParseException ex) {
}
return channelViaHeader;
}
/**
* @see gov.nist.javax.sip.stack.SIPTransaction#sendMessage(gov.nist.javax.sip.message.SIPMessage)
*/
@Override
public void sendMessage(final SIPMessage messageToSend) throws IOException {
// Use the peer address, port and transport
// that was specified when the transaction was
// created. Bug was noted by Bruce Evangelder
// soleo communications.
try {
final RawMessageChannel channel = (RawMessageChannel) encapsulatedChannel;
for (MessageProcessor messageProcessor : sipStack
.getMessageProcessors()) {
boolean addrmatch = messageProcessor.getIpAddress().getHostAddress().toString().equals(this.getPeerAddress());
if (addrmatch
&& messageProcessor.getPort() == this.getPeerPort()
&& messageProcessor.getTransport().equalsIgnoreCase(
this.getPeerProtocol())) {
if (channel instanceof TCPMessageChannel) {
try {
Runnable processMessageTask = new Runnable() {
public void run() {
try {
((TCPMessageChannel) channel)
.processMessage((SIPMessage) messageToSend.clone(), getPeerInetAddress());
} catch (Exception ex) {
if (logger.isLoggingEnabled(ServerLogger.TRACE_ERROR)) {
logger.logError("Error self routing TCP message cause by: ", ex);
}
}
}
};
getSIPStack().getSelfRoutingThreadpoolExecutor().execute(processMessageTask);
} catch (Exception e) {
logger.logError("Error passing message in self routing TCP", e);
}
if (logger.isLoggingEnabled(LogLevels.TRACE_DEBUG))
logger.logDebug("Self routing message TCP");
return;
}
if (channel instanceof TLSMessageChannel) {
try {
Runnable processMessageTask = new Runnable() {
public void run() {
try {
((TLSMessageChannel) channel)
.processMessage((SIPMessage) messageToSend.clone(), getPeerInetAddress());
} catch (Exception ex) {
if (logger.isLoggingEnabled(ServerLogger.TRACE_ERROR)) {
logger.logError("Error self routing TLS message cause by: ", ex);
}
}
}
};
getSIPStack().getSelfRoutingThreadpoolExecutor().execute(processMessageTask);
} catch (Exception e) {
logger.logError("Error passing message in TLS self routing", e);
}
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG))
logger.logDebug("Self routing message TLS");
return;
}
if (channel instanceof RawMessageChannel) {
try {
Runnable processMessageTask = new Runnable() {
public void run() {
try {
((RawMessageChannel) channel).processMessage((SIPMessage) messageToSend.clone());
} catch (Exception ex) {
if (logger.isLoggingEnabled(ServerLogger.TRACE_ERROR)) {
logger.logError("Error self routing message cause by: ", ex);
}
}
}
};
getSIPStack().getSelfRoutingThreadpoolExecutor().execute(processMessageTask);
} catch (Exception e) {
logger.logError("Error passing message in self routing", e);
}
if (logger.isLoggingEnabled(LogLevels.TRACE_DEBUG))
logger.logDebug("Self routing message");
return;
}
}
}
encapsulatedChannel.sendMessage(messageToSend,
this.getPeerInetAddress(), this.getPeerPort());
} finally {
this.startTransactionTimer();
}
}
/**
* Parse the byte array as a message, process it through the transaction,
* and send it to the SIP peer. This is just a placeholder method -- calling
* it will result in an IO exception.
*
* @param messageBytes
* Bytes of the message to send.
* @param receiverAddress
* Address of the target peer.
* @param receiverPort
* Network port of the target peer.
*
* @throws IOException
* If called.
*/
public void sendMessage(byte[] messageBytes,
InetAddress receiverAddress, int receiverPort, boolean retry)
throws IOException {
throw new IOException(
"Cannot send unparsed message through Transaction Channel!");
}
/**
* @see gov.nist.javax.sip.stack.SIPTransaction#addEventListener(gov.nist.javax.sip.stack.SIPTransactionEventListener)
*/
@Override
public void addEventListener(SIPTransactionEventListener newListener) {
eventListeners.add(newListener);
}
/**
* @see gov.nist.javax.sip.stack.SIPTransaction#removeEventListener(gov.nist.javax.sip.stack.SIPTransactionEventListener)
*/
@Override
public void removeEventListener(SIPTransactionEventListener oldListener) {
eventListeners.remove(oldListener);
}
/**
* @see gov.nist.javax.sip.stack.SIPTransaction#raiseErrorEvent(int)
*/
@Override
public void raiseErrorEvent(int errorEventID) {
// Error event to send to all listeners
SIPTransactionErrorEvent newErrorEvent;
// Iterator through the list of listeners
Iterator<SIPTransactionEventListener> listenerIterator;
// Next listener in the list
SIPTransactionEventListener nextListener;
// Create the error event
newErrorEvent = new SIPTransactionErrorEvent(this, errorEventID);
// Loop through all listeners of this transaction
synchronized (eventListeners) {
listenerIterator = eventListeners.iterator();
while (listenerIterator.hasNext()) {
// Send the event to the next listener
nextListener = (SIPTransactionEventListener) listenerIterator
.next();
nextListener.transactionErrorEvent(newErrorEvent);
}
}
// Clear the event listeners after propagating the error.
// Retransmit notifications are just an alert to the
// application (they are not an error).
if (errorEventID != SIPTransactionErrorEvent.TIMEOUT_RETRANSMIT) {
eventListeners.clear();
// Errors always terminate a transaction
this.setState(TransactionState._TERMINATED);
if (this instanceof SIPServerTransaction && this.isByeTransaction()
&& this.getDialog() != null)
((SIPDialog) this.getDialog())
.setState(SIPDialog.TERMINATED_STATE);
}
}
/**
* @see gov.nist.javax.sip.stack.SIPTransaction#isServerTransaction()
*/
@Override
public boolean isServerTransaction() {
return this instanceof SIPServerTransaction;
}
/**
* @see gov.nist.javax.sip.stack.SIPTransaction#getDialog()
*/
@Override
public abstract Dialog getDialog();
/**
* @see gov.nist.javax.sip.stack.SIPTransaction#setDialog(gov.nist.javax.sip.stack.SIPDialog, java.lang.String)
*/
@Override
public abstract void setDialog(SIPDialog sipDialog, String dialogId);