aboutsummaryrefslogtreecommitdiffstats
path: root/src/net/java/sip/communicator/impl/protocol/sip/SipStackSharing.java
blob: 2e714b5d393c100810cf77625f71c98e31daa88c (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
/*
 * Jitsi, the OpenSource Java VoIP and Instant Messaging client.
 *
 * Copyright @ 2015 Atlassian Pty Ltd
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.java.sip.communicator.impl.protocol.sip;

import gov.nist.javax.sip.*;
import gov.nist.javax.sip.header.*;
import gov.nist.javax.sip.stack.*;

import java.io.*;
import java.util.*;

import javax.sip.*;
import javax.sip.address.*;
import javax.sip.header.*;
import javax.sip.message.*;

import net.java.sip.communicator.service.netaddr.event.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.protocol.event.*;
import net.java.sip.communicator.util.*;
import net.java.sip.communicator.util.Logger;

import org.jitsi.util.*;

/**
 * This class is the <tt>SipListener</tt> for all JAIN-SIP
 * <tt>SipProvider</tt>s. It is in charge of dispatching the received messages
 * to the suitable <tt>ProtocolProviderServiceSipImpl</tt>s registered with
 * <tt>addSipListener</tt>. It also contains the JAIN-SIP pieces which are
 * common between all <tt>ProtocolProviderServiceSipImpl</tt>s (namely 1
 * <tt>SipStack</tt>, 2 <tt>SipProvider</tt>s, 3 <tt>ListeningPoint</tt>s).
 *
 * @author Emil Ivov
 * @author Lubomir Marinov
 * @author Alan Kelly
 * @author Sebastien Mazy
 */
public class SipStackSharing
    implements SipListener,
               NetworkConfigurationChangeListener
{
    /**
     * We set a custom parameter in the contact address for registrar accounts,
     * so as to ease dispatching of incoming requests in case several accounts
     * have the same username in their contact address, eg:
     * sip:username@192.168.0.1:5060;transport=udp;registering_acc=example_com
     */
    public static final String CONTACT_ADDRESS_CUSTOM_PARAM_NAME
        = "registering_acc";

    /**
     * Logger for this class.
     */
    private static final Logger logger
        = Logger.getLogger(SipStackSharing.class);

    /**
     * Our SIP stack (provided by JAIN-SIP).
     */
    private final SipStack stack;

    /**
     * The JAIN-SIP provider that we use for clear UDP/TCP.
     */
    private SipProvider clearJainSipProvider = null;
    /**
     *
     * The JAIN-SIP provider that we use for TLS.
     */
    private SipProvider secureJainSipProvider = null;

    /**
     * The candidate recipients to choose from when dispatching messages
     * received from one the JAIN-SIP <tt>SipProvider</tt>-s. for thread safety
     * issues reasons, better iterate on a copy of that set using
     * <tt>getSipListeners()</tt>.
     */
    private final Set<ProtocolProviderServiceSipImpl> listeners
        = new HashSet<ProtocolProviderServiceSipImpl>();

    /**
     * The property indicating the preferred UDP and TCP
     * port to bind to for clear communications.
     */
    private static final String PREFERRED_CLEAR_PORT_PROPERTY_NAME
        = "net.java.sip.communicator.SIP_PREFERRED_CLEAR_PORT";

    /**
     * The property indicating the preferred TLS (TCP)
     * port to bind to for secure communications.
     */
    private static final String PREFERRED_SECURE_PORT_PROPERTY_NAME
        = "net.java.sip.communicator.SIP_PREFERRED_SECURE_PORT";

    /**
     * Constructor for this class. Creates the JAIN-SIP stack.
     *
     * @throws OperationFailedException if creating the stack fails.
     */
    SipStackSharing()
        throws OperationFailedException
    {
        // init of the stack
        try
        {
            SipFactory sipFactory = SipFactory.getInstance();

            /**
             * In android jsip libs exist in core android devices and
             * use different version as the one used in jitsi
             * We change jsip package name in order to use our libs.
             */
            if(OSUtils.IS_ANDROID)
                sipFactory.setPathName("org.jitsi.gov.nist");
            else
                sipFactory.setPathName("gov.nist");

            Properties sipStackProperties = new SipStackProperties();

            // Create SipStack object
            this.stack = sipFactory.createSipStack(sipStackProperties);
            if (logger.isTraceEnabled())
                logger.trace("Created stack: " + this.stack);

            // set our custom address resolver managing SRV records
            AddressResolverImpl addressResolver =
                new AddressResolverImpl();
            ((SIPTransactionStack) this.stack)
                .setAddressResolver(addressResolver);

            SipActivator.getNetworkAddressManagerService()
                .addNetworkConfigurationChangeListener(this);
        }
        catch(Exception ex)
        {
            logger.fatal("Failed to get SIP Factory.", ex);
            throw new OperationFailedException("Failed to get SIP Factory"
                    , OperationFailedException.INTERNAL_ERROR
                    , ex);
        }
    }

    /**
     * Adds this <tt>listener</tt> as a candidate recipient for the dispatching
     * of new messages received from the JAIN-SIP <tt>SipProvider</tt>s.
     *
     * @param listener a new possible target for the dispatching process.
     *
     * @throws OperationFailedException if creating one of the underlying
     * <tt>SipProvider</tt>s fails for whatever reason.
     */
    public void addSipListener(ProtocolProviderServiceSipImpl listener)
        throws OperationFailedException
    {
        synchronized(this.listeners)
        {
            if(this.listeners.size() == 0)
                startListening();
            this.listeners.add(listener);
            if (logger.isTraceEnabled())
                logger.trace(this.listeners.size() + " listeners now");
        }
    }

    /**
     * This <tt>listener</tt> will no longer be a candidate recipient for the
     * dispatching of new messages received from the JAIN-SIP
     * <tt>SipProvider</tt>s.
     *
     * @param listener possible target to remove for the dispatching process.
     */
    public void removeSipListener(ProtocolProviderServiceSipImpl listener)
    {
        synchronized(this.listeners)
        {
            this.listeners.remove(listener);

            int listenerCount = listeners.size();
            if (logger.isTraceEnabled())
                logger.trace(listenerCount + " listeners left");
            if(listenerCount == 0)
                stopListening();
        }
    }

    /**
     * Returns a copy of the <tt>listeners</tt> (= candidate recipients) set.
     *
     * @return a copy of the <tt>listeners</tt> set.
     */
    private Set<ProtocolProviderServiceSipImpl> getSipListeners()
    {
        synchronized(this.listeners)
        {
            return new HashSet<ProtocolProviderServiceSipImpl>(this.listeners);
        }
    }

    /**
     * Returns the JAIN-SIP <tt>ListeningPoint</tt> associated to the given
     * transport string.
     *
     * @param transport a string like "UDP", "TCP" or "TLS".
     * @return the LP associated to the given transport.
     */
    @SuppressWarnings("unchecked") //jain-sip legacy code
    public ListeningPoint getLP(String transport)
    {
        ListeningPoint lp;
        Iterator<ListeningPoint> it = this.stack.getListeningPoints();

        while(it.hasNext())
        {
            lp = it.next();
            // FIXME: JAIN-SIP stack is not consistent with case
            // (reported upstream)
            if(lp.getTransport().toLowerCase().equals(transport.toLowerCase()))
                return lp;
        }

        throw new IllegalArgumentException("Invalid transport: " + transport);
    }

    /**
     * Put the stack in a state where it can receive data on three UDP/TCP ports
     * (2 for clear communication, 1 for TLS). That is to say create the related
     * JAIN-SIP <tt>ListeningPoint</tt>s and <tt>SipProvider</tt>s.
     *
     * @throws OperationFailedException if creating one of the underlying
     * <tt>SipProvider</tt>s fails for whatever reason.
     */
    private void startListening()
        throws OperationFailedException
    {
        try
        {
            int bindRetriesValue = getBindRetriesValue();

            this.createProvider(this.getPreferredClearPort(),
                            bindRetriesValue, false);
            this.createProvider(this.getPreferredSecurePort(),
                            bindRetriesValue, true);
            this.stack.start();
            if (logger.isTraceEnabled())
                logger.trace("started listening");
        }
        catch(Exception ex)
        {
            logger.error("An unexpected error happened while creating the"
                    + "SipProviders and ListeningPoints.");
            throw new OperationFailedException("An unexpected error hapenned"
                    + "while initializing the SIP stack"
                    , OperationFailedException.INTERNAL_ERROR
                    , ex);
        }
    }

    /**
     * Attach JAIN-SIP <tt>SipProvider</tt> and <tt>ListeningPoint</tt> to the
     * stack either for clear communications or TLS. Clear UDP and TCP
     * <tt>ListeningPoint</tt>s are not handled separately as the former is a
     * fallback for the latter (depending on the size of the data transmitted).
     * Both <tt>ListeningPoint</tt>s must be bound to the same address and port
     * in order for the related <tt>SipProvider</tt> to be created. If a UDP or
     * TCP <tt>ListeningPoint</tt> cannot bind, retry for both on another port.
     *
     * @param preferredPort which port to try first to bind.
     * @param retries how many times should we try to find a free port to bind
     * @param secure whether to create the TLS SipProvider.
     * or the clear UDP/TCP one.
     *
     * @throws TransportNotSupportedException in case we try to create a
     * provider for a transport not currently supported by jain-sip
     * @throws InvalidArgumentException if we try binding to an illegal port
     * (which we won't)
     * @throws ObjectInUseException if another <tt>SipProvider</tt> is already
     * associated with this <tt>ListeningPoint</tt>.
     * @throws TransportAlreadySupportedException if there is already a
     * ListeningPoint associated to this <tt>SipProvider</tt> with the same
     * transport of the <tt>ListeningPoint</tt>.
     * @throws TooManyListenersException if we try to add a new
     * <tt>SipListener</tt> with a <tt>SipProvider</tt> when one was already
     * registered.
     *
     */
    private void createProvider(int preferredPort, int retries, boolean secure)
        throws TransportNotSupportedException,
        InvalidArgumentException,
        ObjectInUseException,
        TransportAlreadySupportedException,
        TooManyListenersException
    {
        String context = (secure ? "TLS: " : "clear UDP/TCP: ");

        if(retries < 0)
        {
            // very unlikely to happen with the default 50 retries
            logger.error(context + "couldn't find free ports to listen on.");
            return;
        }

        ListeningPoint tlsLP = null;
        ListeningPoint udpLP = null;
        ListeningPoint tcpLP = null;

        try
        {
            if(secure)
            {
                tlsLP = this.stack.createListeningPoint(
                        NetworkUtils.IN_ADDR_ANY
                        , preferredPort
                        , ListeningPoint.TLS);
                if (logger.isTraceEnabled())
                    logger.trace("TLS secure ListeningPoint has been created.");

                this.secureJainSipProvider =
                    this.stack.createSipProvider(tlsLP);
                this.secureJainSipProvider.addSipListener(this);
            }
            else
            {
                udpLP = this.stack.createListeningPoint(
                        NetworkUtils.IN_ADDR_ANY
                        , preferredPort
                        , ListeningPoint.UDP);
                tcpLP = this.stack.createListeningPoint(
                        NetworkUtils.IN_ADDR_ANY
                        , preferredPort
                        , ListeningPoint.TCP);
                if (logger.isTraceEnabled())
                    logger.trace("UDP and TCP clear ListeningPoints have "
                            + "been created.");

                this.clearJainSipProvider =
                    this.stack.createSipProvider(udpLP);
                this.clearJainSipProvider.
                    addListeningPoint(tcpLP);
                this.clearJainSipProvider.addSipListener(this);
            }

            if (logger.isTraceEnabled())
                logger.trace(context + "SipProvider has been created.");
        }
        catch(InvalidArgumentException ex)
        {
            // The TLS lp tries to bind to the socket after the lp is created
            // and added to the list. So despite being invalid and not
            // returned from createLP, it still lingers around. Search it
            // by obtaining all LPs and then destroy it.
            if(secure)
            {
                if (tlsLP != null)
                    this.stack.deleteListeningPoint(tlsLP);

                Set<ListeningPoint> lpsToDelete = new HashSet<ListeningPoint>();

                @SuppressWarnings("rawtypes")
                Iterator lps = this.stack.getListeningPoints();
                while (lps.hasNext())
                {
                    ListeningPoint lp = (ListeningPoint) lps.next();
                    if (ListeningPoint.TLS.equalsIgnoreCase(lp.getTransport())
                        && lp.getPort() == preferredPort)
                    {
                        lpsToDelete.add(lp);
                    }
                }

                for (ListeningPoint lp : lpsToDelete)
                {
                    this.stack.deleteListeningPoint(lp);
                }
            }

            // makes sure we didn't leave an open listener
            // as both UDP and TCP listener have to bind to the same port
            if(udpLP != null)
                this.stack.deleteListeningPoint(udpLP);
            if(tcpLP != null)
                this.stack.deleteListeningPoint(tcpLP);

            // FIXME: "Address already in use" is not working
            // as ex.getMessage() displays in the locale language in SC
            // (getMessage() is always supposed to be English though)
            // this should be a temporary workaround
            //if (ex.getMessage().indexOf("Address already in use") != -1)
            // another software is probably using the port
            if(ex.getCause() instanceof java.io.IOException)
            {
                if (logger.isDebugEnabled())
                    logger.debug("Port " + preferredPort
                            + " seems in use for either TCP or UDP.");

                // tries again on a new random port
                int currentlyTriedPort = NetworkUtils.getRandomPortNumber();
                if (logger.isDebugEnabled())
                    logger.debug("Retrying bind on port " + currentlyTriedPort);
                this.createProvider(currentlyTriedPort, retries-1, secure);
            }
            else
                throw ex;
        }
    }

    /**
     * Put the JAIN-SIP stack in a state where it cannot receive any data and
     * frees the network ports used. That is to say remove JAIN-SIP
     * <tt>ListeningPoint</tt>s and <tt>SipProvider</tt>s.
     */
    @SuppressWarnings("unchecked") //jain-sip legacy code
    private void stopListening()
    {
        try
        {
            if (this.secureJainSipProvider != null)
            {
                this.secureJainSipProvider.removeSipListener(this);
                this.stack.deleteSipProvider(this.secureJainSipProvider);
                this.secureJainSipProvider = null;
            }

            if (this.clearJainSipProvider != null)
            {
                this.clearJainSipProvider.removeSipListener(this);
                this.stack.deleteSipProvider(this.clearJainSipProvider);
                this.clearJainSipProvider = null;
            }

            Iterator<ListeningPoint> it = this.stack.getListeningPoints();
            Vector<ListeningPoint> lpointsToRemove = new Vector<ListeningPoint>();
            while(it.hasNext())
            {
                lpointsToRemove.add(it.next());
            }

            it = lpointsToRemove.iterator();
            while (it.hasNext())
            {
                this.stack.deleteListeningPoint(it.next());
            }

            this.stack.stop();
            if (logger.isTraceEnabled())
                logger.trace("stopped listening");
        }
        catch(ObjectInUseException ex)
        {
            logger.fatal("Failed to stop listening", ex);
        }
    }

    /**
     * Returns the JAIN-SIP <tt>SipProvider</tt> in charge of this
     * <tt>transport</tt>.
     *
     * @param transport a <tt>String</tt> like "TCP", "UDP" or "TLS"
     * @return the corresponding <tt>SipProvider</tt>
     */
    public SipProvider getJainSipProvider(String transport)
    {
        SipProvider sp = null;
        if(transport.equalsIgnoreCase(ListeningPoint.UDP)
                || transport.equalsIgnoreCase(ListeningPoint.TCP))
            sp = this.clearJainSipProvider;
        else if(transport.equalsIgnoreCase(ListeningPoint.TLS))
            sp = this.secureJainSipProvider;

        if(sp == null)
            throw new IllegalArgumentException("invalid transport");
        return sp;
    }

    /**
     * Fetches the preferred UDP and TCP port for clear communications in the
     * user preferences or search is default value set in settings or
     * fallback on a default value.
     *
     * @return the preferred network port for clear communications.
     */
    private int getPreferredClearPort()
    {

        int preferredPort =  SipActivator.getConfigurationService().getInt(
            PREFERRED_CLEAR_PORT_PROPERTY_NAME, -1);

        if(preferredPort <= 1)
        {
            // check for default value
            preferredPort =  SipActivator.getResources().getSettingsInt(
                PREFERRED_CLEAR_PORT_PROPERTY_NAME);
        }

        if(preferredPort <= 1)
            return ListeningPoint.PORT_5060;
        else
            return preferredPort;
    }

    /**
     * Fetches the preferred TLS (TCP) port for secure communications in the
     * user preferences or search is default value set in settings or
     * fallback on a default value.
     *
     * @return the preferred network port for secure communications.
     */
    private int getPreferredSecurePort()
    {
        int preferredPort =  SipActivator.getConfigurationService().getInt(
            PREFERRED_SECURE_PORT_PROPERTY_NAME, -1);

        if(preferredPort <= 1)
        {
            // check for default value
            preferredPort =  SipActivator.getResources().getSettingsInt(
                PREFERRED_SECURE_PORT_PROPERTY_NAME);
        }

        if(preferredPort <= 1)
            return ListeningPoint.PORT_5061;
        else
            return preferredPort;
    }

    /**
     * Fetches the number of times to retry when the binding of a JAIN-SIP
     * <tt>ListeningPoint</tt> fails. Looks in the user preferences or
     * fallbacks on a default value.
     *
     * @return the number of times to retry a failed bind.
     */
    private int getBindRetriesValue()
    {
        return SipActivator.getConfigurationService().getInt(
            ProtocolProviderService.BIND_RETRIES_PROPERTY_NAME,
            ProtocolProviderService.BIND_RETRIES_DEFAULT_VALUE);
    }

    /**
     * Dispatches the event received from a JAIN-SIP <tt>SipProvider</tt> to one
     * of our "candidate recipient" listeners.
     *
     * @param event the event received for a
     * <tt>SipProvider</tt>.
     */
    public void processDialogTerminated(DialogTerminatedEvent event)
    {
        try
        {
            ProtocolProviderServiceSipImpl recipient
                = (ProtocolProviderServiceSipImpl) SipApplicationData
                    .getApplicationData(event.getDialog(),
                                        SipApplicationData.KEY_SERVICE);
            if(recipient == null)
            {
                logger.error("Dialog wasn't marked, please report this to "
                                + "dev@jitsi.org");
            }
            else
            {
                if (logger.isTraceEnabled())
                    logger.trace("service was found with dialog data");
                recipient.processDialogTerminated(event);
            }
        }
        catch(Throwable exc)
        {
            //any exception thrown within our code should be caught here
            //so that we could log it rather than interrupt stack activity with
            //it.
            this.logApplicationException(DialogTerminatedEvent.class, exc);
        }
    }

    /**
     * Dispatches the event received from a JAIN-SIP <tt>SipProvider</tt> to one
     * of our "candidate recipient" listeners.
     *
     * @param event the event received for a <tt>SipProvider</tt>.
     */
    public void processIOException(IOExceptionEvent event)
    {
        try
        {
            if (logger.isTraceEnabled())
                logger.trace(event);

            // impossible to dispatch, log here
            if (logger.isDebugEnabled())
                logger.debug("@todo implement processIOException()");
        }
        catch(Throwable exc)
        {
            //any exception thrown within our code should be caught here
            //so that we could log it rather than interrupt stack activity with
            //it.
            this.logApplicationException(DialogTerminatedEvent.class, exc);
        }
    }

    /**
     * Dispatches the event received from a JAIN-SIP <tt>SipProvider</tt> to one
     * of our "candidate recipient" listeners.
     *
     * @param event the event received for a <tt>SipProvider</tt>.
     */
    public void processRequest(RequestEvent event)
    {
        try
        {
            Request request = event.getRequest();
            if (logger.isTraceEnabled())
                logger.trace("received request: " + request.getMethod());

            /*
             * Create the transaction if it doesn't exist yet. If it is a
             * dialog-creating request, the dialog will also be automatically
             * created by the stack.
             */
            if (event.getServerTransaction() == null)
            {
                try
                {
                    // apply some hacks if needed on incoming request
                    // to be compliant with some servers/clients
                    // if needed stop further processing.
                    if(applyNonConformanceHacks(event))
                        return;

                    SipProvider source = (SipProvider) event.getSource();
                    ServerTransaction transaction
                        = source.getNewServerTransaction(request);

                    /*
                     * Update the event, otherwise getServerTransaction() and
                     * getDialog() will still return their previous value.
                     */
                    event
                        = new RequestEvent(
                                source,
                                transaction,
                                transaction.getDialog(),
                                request);
                }
                catch (SipException ex)
                {
                    logger.error(
                        "couldn't create transaction, please report "
                            + "this to dev@jitsi.org",
                        ex);
                }
            }

            ProtocolProviderServiceSipImpl service
                = getServiceData(event.getServerTransaction());
            if (service != null)
            {
                service.processRequest(event);
            }
            else
            {
                service = findTargetFor(request);
                if (service == null)
                {
                    logger.error(
                        "couldn't find a ProtocolProviderServiceSipImpl "
                            + "to dispatch to");
                    if (event.getServerTransaction() != null)
                        event.getServerTransaction().terminate();
                }
                else
                {

                    /*
                     * Mark the dialog for the dispatching of later in-dialog
                     * requests. If there is no dialog, we need to mark the
                     * request to dispatch a possible timeout when sending the
                     * response.
                     */
                    Object container = event.getDialog();
                    if (container == null)
                        container = request;
                    SipApplicationData.setApplicationData(
                        container,
                        SipApplicationData.KEY_SERVICE,
                        service);

                    service.processRequest(event);
                }
            }
        }
        catch(Throwable exc)
        {

            /*
             * Any exception thrown within our code should be caught here so
             * that we could log it rather than interrupt stack activity with
             * it.
             */
            this.logApplicationException(DialogTerminatedEvent.class, exc);

            // Unfortunately, death can hardly be ignored.
            if (exc instanceof ThreadDeath)
                throw (ThreadDeath) exc;
        }
    }

    /**
     * Dispatches the event received from a JAIN-SIP <tt>SipProvider</tt> to one
     * of our "candidate recipient" listeners.
     *
     * @param event the event received for a <tt>SipProvider</tt>.
     */
    public void processResponse(ResponseEvent event)
    {
        try
        {
            // we don't have to accept the transaction since we
            //created the request
            ClientTransaction transaction = event.getClientTransaction();
            if (logger.isTraceEnabled())
                logger.trace("received response: "
                        + event.getResponse().getStatusCode()
                        + " " + event.getResponse().getReasonPhrase());

            if(transaction == null)
            {
                logger.warn("Transaction is null, probably already expired! "
                    + "Status=" + event.getResponse().getStatusCode());
                return;
            }

            ProtocolProviderServiceSipImpl service
                = getServiceData(transaction);
            if (service != null)
            {
                // Mark the dialog for the dispatching of later in-dialog
                // responses. If there is no dialog then the initial request
                // sure is marked otherwise we won't have found the service with
                // getServiceData(). The request has to be marked in case we
                // receive one more response in an out-of-dialog transaction.
                if (event.getDialog() != null)
                {
                    SipApplicationData.setApplicationData(event.getDialog(),
                                    SipApplicationData.KEY_SERVICE, service);
                }
                service.processResponse(event);
            }
            else
            {
                logger.error("We received a response which "
                                + "wasn't marked, please report this to "
                                + "dev@jitsi.org");
            }
        }
        catch(Throwable exc)
        {
            //any exception thrown within our code should be caught here
            //so that we could log it rather than interrupt stack activity with
            //it.
            this.logApplicationException(DialogTerminatedEvent.class, exc);
        }
    }

    /**
     * Dispatches the event received from a JAIN-SIP <tt>SipProvider</tt> to one
     * of our "candidate recipient" listeners.
     *
     * @param event the event received for a <tt>SipProvider</tt>.
     */
    public void processTimeout(TimeoutEvent event)
    {
        try
        {
            Transaction transaction;
            if (event.isServerTransaction())
            {
                transaction = event.getServerTransaction();
            }
            else
            {
                transaction = event.getClientTransaction();
            }

            ProtocolProviderServiceSipImpl recipient
                = getServiceData(transaction);
            if (recipient == null)
            {
                logger.error("We received a timeout which wasn't "
                                + "marked, please report this to "
                                + "dev@jitsi.org");
            }
            else
            {
                recipient.processTimeout(event);
            }
        }
        catch(Throwable exc)
        {
            //any exception thrown within our code should be caught here
            //so that we could log it rather than interrupt stack activity with
            //it.
            this.logApplicationException(DialogTerminatedEvent.class, exc);
        }
    }

    /**
     * Dispatches the event received from a JAIN-SIP <tt>SipProvider</tt> to one
     * of our "candidate recipient" listeners.
     *
     * @param event the event received for a
     * <tt>SipProvider</tt>.
     */
    public void processTransactionTerminated(TransactionTerminatedEvent event)
    {
        try
        {
            Transaction transaction;
            if (event.isServerTransaction())
                transaction = event.getServerTransaction();
            else
                transaction = event.getClientTransaction();

            ProtocolProviderServiceSipImpl recipient
                = getServiceData(transaction);

            if (recipient == null)
            {
                logger.error("We received a transaction terminated which wasn't"
                                + " marked, please report this to"
                                + " dev@jitsi.org");
            }
            else
            {
                recipient.processTransactionTerminated(event);
            }
        }
        catch(Throwable exc)
        {
            //any exception thrown within our code should be caught here
            //so that we could log it rather than interrupt stack activity with
            //it.
            this.logApplicationException(DialogTerminatedEvent.class, exc);
        }
    }

    /**
     * Find the <tt>ProtocolProviderServiceSipImpl</tt> (one of our
     * "candidate recipient" listeners) which this <tt>request</tt> should be
     * dispatched to. The strategy is to look first at the request URI, and
     * then at the To field to find a matching candidate for dispatching.
     * Note that this method takes a <tt>Request</tt> as param, and not a
     * <tt>ServerTransaction</tt>, because sometimes <tt>RequestEvent</tt>s
     * have no associated <tt>ServerTransaction</tt>.
     *
     * @param request the <tt>Request</tt> to find a recipient for.
     * @return a suitable <tt>ProtocolProviderServiceSipImpl</tt>.
     */
    private ProtocolProviderServiceSipImpl findTargetFor(Request request)
    {
        if(request == null)
        {
            logger.error("request shouldn't be null.");
            return null;
        }

        List<ProtocolProviderServiceSipImpl> currentListenersCopy
            = new ArrayList<ProtocolProviderServiceSipImpl>(
                                this.getSipListeners());

        // Let's first narrow down candidate choice by comparing
        // addresses and ports (no point in delivering to a provider with a
        // non matching IP address  since they will reject it anyway).
        filterByAddress(currentListenersCopy, request);

        if(currentListenersCopy.size() == 0)
        {
            logger.error("no listeners");
            return null;
        }

        URI requestURI = request.getRequestURI();

        if(requestURI.isSipURI())
        {
            String requestUser = ((SipURI) requestURI).getUser();

            List<ProtocolProviderServiceSipImpl> candidates =
                new ArrayList<ProtocolProviderServiceSipImpl>();

            // check if the Request-URI username is
            // one of ours usernames
            for(ProtocolProviderServiceSipImpl listener : currentListenersCopy)
            {
                String ourUserID = listener.getAccountID().getUserID();
                //logger.trace(ourUserID + " *** " + requestUser);
                if(ourUserID.equals(requestUser))
                {
                    if (logger.isTraceEnabled())
                        logger.trace("suitable candidate found: "
                                + listener.getAccountID());
                    candidates.add(listener);
                }
            }

            // the perfect match
            // every other case is approximation
            if(candidates.size() == 1)
            {
                ProtocolProviderServiceSipImpl perfectMatch = candidates.get(0);

                if (logger.isTraceEnabled())
                    logger.trace("Will dispatch to \""
                            + perfectMatch.getAccountID() + "\"");
                return perfectMatch;
            }

            // more than one account match
            if(candidates.size() > 1)
            {
                // check if a custom param exists in the contact
                // address (set for registrar accounts)
                for (ProtocolProviderServiceSipImpl candidate : candidates)
                {
                    String hostValue = ((SipURI) requestURI).getParameter(
                            SipStackSharing.CONTACT_ADDRESS_CUSTOM_PARAM_NAME);
                    if (hostValue == null)
                        continue;
                    if (hostValue.equals(candidate
                                .getContactAddressCustomParamValue()))
                    {
                        if (logger.isTraceEnabled())
                            logger.trace("Will dispatch to \""
                                    + candidate.getAccountID() + "\" because "
                                    + "\" the custom param was set");
                        return candidate;
                    }
                }

                // Past this point, our guess is not reliable. We try to find
                // the "least worst" match based on parameters like the To field

                // check if the To header field host part
                // matches any of our SIP hosts
                for(ProtocolProviderServiceSipImpl candidate : candidates)
                {
                    URI fromURI = ((FromHeader) request
                            .getHeader(FromHeader.NAME)).getAddress().getURI();
                    if(fromURI.isSipURI() == false)
                        continue;
                    SipURI ourURI = (SipURI) candidate
                        .getOurSipAddress((SipURI) fromURI).getURI();
                    String ourHost = ourURI.getHost();

                    URI toURI = ((ToHeader) request
                            .getHeader(ToHeader.NAME)).getAddress().getURI();
                    if(toURI.isSipURI() == false)
                        continue;
                    String toHost = ((SipURI) toURI).getHost();

                    //logger.trace(toHost + "***" + ourHost);
                    if(toHost.equals(ourHost))
                    {
                        if (logger.isTraceEnabled())
                            logger.trace("Will dispatch to \""
                                    + candidate.getAccountID() + "\" because "
                                    + "host in the To: is the same as in our AOR");
                        return candidate;
                    }
                }

                // fallback on the first candidate
                ProtocolProviderServiceSipImpl target =
                    candidates.iterator().next();
                logger.info("Will randomly dispatch to \""
                        + target.getAccountID()
                        + "\" because there is ambiguity on the username from"
                        + " the Request-URI");
                if (logger.isTraceEnabled())
                    logger.trace("\n" + request);
                return target;
            }

            // fallback on any account
            ProtocolProviderServiceSipImpl target =
                currentListenersCopy.iterator().next();
            if (logger.isDebugEnabled())
                logger.debug("Will randomly dispatch to \"" + target
                        .getAccountID()
                        + "\" because the username in the Request-URI "
                        + "is unknown or empty");
            if (logger.isTraceEnabled())
                logger.trace("\n" + request);
            return target;
        }
        else
        {
            logger.error("Request-URI is not a SIP URI, dropping");
        }
        return null;
    }

    /**
     * Removes from the specified list of candidates providers connected to a
     * registrar that does not match the IP address that we are receiving a
     * request from.
     *
     * @param candidates the list of providers we've like to filter.
     * @param request the request that we are currently dispatching
     */
    private void filterByAddress(
                    List<ProtocolProviderServiceSipImpl> candidates,
                    Request                              request)
    {
        Iterator<ProtocolProviderServiceSipImpl> iterPP =
            candidates.iterator();
        while (iterPP.hasNext())
        {
            ProtocolProviderServiceSipImpl candidate = iterPP.next();
            boolean forceProxyBypass
                = candidate.getAccountID()
                    .getAccountPropertyBoolean(
                        ProtocolProviderFactory.FORCE_PROXY_BYPASS, false);
            if(forceProxyBypass)
            {
                // Proxy check is disabled all connections are
                // ok (HA sipXecs, sipXcom, ...)
                continue;
            } 
            if(candidate.getRegistrarConnection() == null)
            {
                //RegistrarLess connections are ok
                continue;
            }

            if (   !candidate.getRegistrarConnection().isRegistrarless()
                && !candidate.getRegistrarConnection()
                        .isRequestFromSameConnection(request))
            {
                iterPP.remove();
            }
        }

    }

    /**
     * Retrieves and returns that ProtocolProviderService that this transaction
     * belongs to, or <tt>null</tt> if we couldn't associate it with a provider
     * based on neither the request nor the transaction itself.
     *
     * @param transaction the transaction that we'd like to determine a provider
     * for.
     *
     * @return a reference to the <tt>ProtocolProviderServiceSipImpl</tt> that
     * <tt>transaction</tt> was associated with or <tt>null</tt> if we couldn't
     * determine which one it is.
     */
    private ProtocolProviderServiceSipImpl
        getServiceData(Transaction transaction)
    {
        ProtocolProviderServiceSipImpl service
            = (ProtocolProviderServiceSipImpl) SipApplicationData
            .getApplicationData(transaction.getRequest(),
                    SipApplicationData.KEY_SERVICE);

        if (service != null)
        {
            if (logger.isTraceEnabled())
                logger.trace("service was found in request data");
            return service;
        }

        service = (ProtocolProviderServiceSipImpl) SipApplicationData
            .getApplicationData(transaction.getDialog(),
                    SipApplicationData.KEY_SERVICE);
        if (service != null)
        {
            if (logger.isTraceEnabled())
                logger.trace("service was found in dialog data");
        }

        return service;
    }

    /**
     * Logs exceptions that have occurred in the application while processing
     * events originating from the stack.
     *
     * @param eventClass the class of the jain-sip event that we were handling
     * when the exception was thrown.
     * @param exc the exception that we need to log.
     */
    private void logApplicationException(
        Class<DialogTerminatedEvent> eventClass,
        Throwable exc)
    {
        String message
            = "An error occurred while processing event of type: "
                + eventClass.getName();

        logger.error(message, exc);
        if (logger.isDebugEnabled())
            logger.debug(message, exc);
    }

    /**
     * Safely returns the transaction from the event if already exists.
     * If not a new transaction is created.
     *
     * @param event the request event
     * @return the server transaction
     * @throws javax.sip.TransactionAlreadyExistsException if transaction exists
     * @throws javax.sip.TransactionUnavailableException if unavailable
     */
    public static ServerTransaction getOrCreateServerTransaction(
                                                            RequestEvent event)
        throws TransactionAlreadyExistsException,
               TransactionUnavailableException
    {
        ServerTransaction serverTransaction = event.getServerTransaction();

        if(serverTransaction == null)
        {
            SipProvider jainSipProvider = (SipProvider) event.getSource();

            serverTransaction
                = jainSipProvider
                    .getNewServerTransaction(event.getRequest());
        }
        return serverTransaction;
    }

    /**
     * Returns a local address to use with the specified TCP destination.
     * The method forces the JAIN-SIP stack to create
     * s and binds (if necessary)
     * and return a socket connected to the specified destination address and
     * port and then return its local address.
     *
     * @param dst the destination address that the socket would need to connect
     *            to.
     * @param dstPort the port number that the connection would be established
     * with.
     * @param localAddress the address that we would like to bind on
     * (null for the "any" address).
     * @param transport the transport that will be used TCP ot TLS
     *
     * @return the SocketAddress that this handler would use when connecting to
     * the specified destination address and port.
     *
     * @throws IOException  if we fail binding the local socket
     */
    public java.net.InetSocketAddress getLocalAddressForDestination(
                    java.net.InetAddress dst,
                    int                  dstPort,
                    java.net.InetAddress localAddress,
                    String transport)
        throws IOException
    {
        if(ListeningPoint.TLS.equalsIgnoreCase(transport))
            return (java.net.InetSocketAddress)(((SipStackImpl)this.stack)
                .getLocalAddressForTlsDst(dst, dstPort, localAddress));
        else
            return (java.net.InetSocketAddress)(((SipStackImpl)this.stack)
            .getLocalAddressForTcpDst(dst, dstPort, localAddress, 0));
    }

    /**
     * Place to put some hacks if needed on incoming requests.
     *
     * @param event the incoming request event.
     * @return status <code>true</code> if we don't need to process this
     * message, just discard it and <code>false</code> otherwise.
     */
    private boolean applyNonConformanceHacks(RequestEvent event)
    {
        Request request = event.getRequest();
        try
        {
            /*
             * Max-Forwards is required, yet there are UAs which do not
             * place it. SipProvider#getNewServerTransaction(Request)
             * will throw an exception in the case of a missing
             * Max-Forwards header and this method will eventually just
             * log it thus ignoring the whole event.
             */
            if (request.getHeader(MaxForwardsHeader.NAME) == null)
            {
                // it appears that some buggy providers do send requests
                // with no Max-Forwards headers, as we are at application level
                // and we know there will be no endless loops
                // there is no problem of adding headers and process normally
                // this messages
                MaxForwardsHeader maxForwards = SipFactory
                    .getInstance().createHeaderFactory()
                        .createMaxForwardsHeader(70);
                request.setHeader(maxForwards);
            }
        }
        catch(Throwable ex)
        {
            logger.warn("Cannot apply incoming request modification!", ex);
        }

        try
        {
            // using asterisk voice mail initial notify for messages
            // is ok, but on the fly received messages their notify comes
            // without subscription-state, so we add it in order to be able to
            // process message.
            if(request.getMethod().equals(Request.NOTIFY)
               && request.getHeader(EventHeader.NAME) != null
               && ((EventHeader)request.getHeader(EventHeader.NAME))
                    .getEventType().equals(
                        OperationSetMessageWaitingSipImpl.EVENT_PACKAGE)
               && request.getHeader(SubscriptionStateHeader.NAME)
                    == null)
            {
                request.addHeader(
                        new HeaderFactoryImpl()
                            .createSubscriptionStateHeader(
                                SubscriptionStateHeader.ACTIVE));
            }
        }
        catch(Throwable ex)
        {
            logger.warn("Cannot apply incoming request modification!", ex);
        }

        try
        {
            // receiving notify message without subscription state
            // used for keep-alive pings, they have done their job
            // and are no more need. Skip processing them to avoid
            // filling logs with unneeded exceptions.
            if(request.getMethod().equals(Request.NOTIFY)
               && request.getHeader(SubscriptionStateHeader.NAME) == null)
            {
                return true;
            }
        }
        catch(Throwable ex)
        {
            logger.warn("Cannot apply incoming request modification!", ex);
        }

        return false;
    }

    /**
     * List of currently waiting timers that will monitor the protocol provider
     *
     */
    Map<String, TimerTask> resetListeningPointsTimers
            = new HashMap<String, TimerTask>();

    /**
     * Listens for network changes and if we have a down interface
     * and we have a tcp/tls provider which is staying for 20 seconds in
     * unregistering state, it cannot unregister cause its using the old
     * address which is currently down, and we must recreate its listening
     * points so it can further reconnect.
     *
     * @param event the change event.
     */
    public void configurationChanged(ChangeEvent event)
    {
        if(event.isInitial())
            return;

        if(event.getType() == ChangeEvent.ADDRESS_DOWN)
        {
            for(final ProtocolProviderServiceSipImpl pp : listeners)
            {
                if(pp.getRegistrarConnection().getTransport() != null
                   && (pp.getRegistrarConnection().getTransport()
                            .equals(ListeningPoint.TCP)
                        || pp.getRegistrarConnection().getTransport()
                            .equals(ListeningPoint.TLS)))
                {
                    ResetListeningPoint reseter;
                    synchronized(resetListeningPointsTimers)
                    {
                        // we do this only once for transport
                        if(resetListeningPointsTimers.containsKey(
                                pp.getRegistrarConnection().getTransport()))
                            continue;

                        reseter = new ResetListeningPoint(pp);
                        resetListeningPointsTimers.put(
                            pp.getRegistrarConnection().getTransport(),
                            reseter);
                    }
                    pp.addRegistrationStateChangeListener(reseter);
                }
            }
        }
    }

    /**
     * If a tcp(tls) provider stays unregistering for a long time after
     * connection changed most probably it won't get registered after
     * unregistering fails, cause underlying listening point are conncted
     * to wrong interfaces. So we will replace them.
     */
    private class ResetListeningPoint
            extends TimerTask
            implements RegistrationStateChangeListener
    {
        /**
         * The time we wait before checking is the provider still unregistering.
         */
        private static final int TIME_FOR_PP_TO_UNREGISTER = 20000;

        /**
         * The protocol provider we are checking.
         */
        private final ProtocolProviderServiceSipImpl protocolProvider;

        /**
         * Constructs this task.
         * @param pp
         */
        ResetListeningPoint(ProtocolProviderServiceSipImpl pp)
        {
            this.protocolProvider = pp;
        }

        /**
         * Notified when registration state changed for a provider.
         * @param evt
         */
        public void registrationStateChanged(RegistrationStateChangeEvent evt)
        {
            if(evt.getNewState() == RegistrationState.UNREGISTERING)
            {
                new Timer().schedule(this, TIME_FOR_PP_TO_UNREGISTER);
            }
            else
            {
                protocolProvider.removeRegistrationStateChangeListener(this);
                resetListeningPointsTimers.remove(
                    protocolProvider.getRegistrarConnection().getTransport());
            }
        }

        /**
         * The real task work, replace listening point.
         */
        @Override
        public void run()
        {
            // if the provider is still unregistering it most probably won't
            // successes until we re-init the LP
            if(protocolProvider.getRegistrationState()
                == RegistrationState.UNREGISTERING)
            {
                String transport = protocolProvider.getRegistrarConnection()
                    .getTransport();

                ListeningPoint old = getLP(transport);

                try
                {
                    stack.deleteListeningPoint(old);
                }
                catch(Throwable t)
                {
                    logger.warn("Error replacing ListeningPoint for "
                            + transport, t);
                }

                try
                {
                    ListeningPoint tcpLP =
                        stack.createListeningPoint(
                            NetworkUtils.IN_ADDR_ANY
                            , transport.equals(ListeningPoint.TCP)?
                                getPreferredClearPort(): getPreferredSecurePort()
                            , transport);
                    clearJainSipProvider.addListeningPoint(tcpLP);
                }
                catch(Throwable t)
                {
                    logger.warn("Error replacing ListeningPoint for " +
                        protocolProvider.getRegistrarConnection().getTransport(),
                            t);
                }
            }

            resetListeningPointsTimers.remove(
                    protocolProvider.getRegistrarConnection().getTransport());
        }
    }
}