/
TransportSelector.cxx
1745 lines (1581 loc) · 58.1 KB
/
TransportSelector.cxx
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
#if defined(HAVE_CONFIG_H)
#include "config.h"
#endif
#ifdef WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#include <wspiapi.h> // Required for freeaddrinfo implementation in Windows 2000, NT, Me/95/98
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
#endif
#include "resip/stack/NameAddr.hxx"
#include "resip/stack/Uri.hxx"
#include "resip/stack/ExtensionParameter.hxx"
#include "resip/stack/Compression.hxx"
#include "resip/stack/SipMessage.hxx"
#include "resip/stack/TransactionState.hxx"
#include "resip/stack/TransportFailure.hxx"
#include "resip/stack/TransportSelector.hxx"
#include "resip/stack/InternalTransport.hxx"
#include "resip/stack/TcpBaseTransport.hxx"
#include "resip/stack/TcpTransport.hxx"
#include "resip/stack/UdpTransport.hxx"
#include "resip/stack/WsTransport.hxx"
#include "resip/stack/Uri.hxx"
#include "rutil/DataStream.hxx"
#include "rutil/DnsUtil.hxx"
#include "rutil/Inserter.hxx"
#include "rutil/Logger.hxx"
#include "rutil/Socket.hxx"
#include "rutil/FdPoll.hxx"
#include "rutil/WinLeakCheck.hxx"
#include "rutil/dns/DnsStub.hxx"
#ifdef USE_NETNS
# include "rutil/NetNs.hxx"
#endif
#ifdef USE_SIGCOMP
#include <osc/Stack.h>
#include <osc/SigcompMessage.h>
#endif
#ifdef USE_SSL
#include "resip/stack/ssl/DtlsTransport.hxx"
#include "resip/stack/ssl/Security.hxx"
#include "resip/stack/ssl/TlsTransport.hxx"
#include "resip/stack/ssl/WssTransport.hxx"
#endif
#ifdef WIN32
#include "rutil/WinCompat.hxx"
#endif
#ifdef __MINGW32__
#define gai_strerror strerror
#endif
#include <sys/types.h>
using namespace resip;
#define RESIPROCATE_SUBSYSTEM Subsystem::TRANSPORT
TransportSelector::TransportSelector(Fifo<TransactionMessage>& fifo, Security* security, DnsStub& dnsStub, Compression &compression) :
mDns(dnsStub),
mStateMacFifo(fifo),
mSecurity(security),
mCompression(compression),
mSigcompStack (0),
mPollGrp(0),
mAvgBufferSize(1024),
mInterruptorHandle(0)
{
memset(&mUnspecified.v4Address, 0, sizeof(sockaddr_in));
mUnspecified.v4Address.sin_family = AF_UNSPEC;
#ifdef USE_IPV6
memset(&mUnspecified6.v6Address, 0, sizeof(sockaddr_in6));
mUnspecified6.v6Address.sin6_family = AF_UNSPEC;
#endif
#ifdef USE_SIGCOMP
if (mCompression.isEnabled())
{
DebugLog (<< "Compression enabled for Transport Selector");
mSigcompStack = new osc::Stack(mCompression.getStateHandler());
mCompression.addCompressorsToStack(mSigcompStack);
}
else
{
DebugLog (<< "Compression disabled for Transport Selector");
}
#else
DebugLog (<< "No compression library available");
#endif
}
TransportSelector::~TransportSelector()
{
mExactTransports.clear();
mAnyInterfaceTransports.clear();
mAnyPortTransports.clear();
mAnyPortAnyInterfaceTransports.clear();
mTlsTransports.clear();
mSharedProcessTransports.clear();
mHasOwnProcessTransports.clear();
mTypeToTransportMap.clear();
for(TransportKeyMap::iterator it = mTransports.begin(); it != mTransports.end(); it++)
{
delete it->second;
}
#ifdef USE_SIGCOMP
delete mSigcompStack;
#endif
for(HashMap<Data, Socket>::iterator socketIterator = mSockets.begin();
socketIterator != mSockets.end(); socketIterator++)
{
if (socketIterator->second != INVALID_SOCKET)
{
closeSocket(socketIterator->second);
DebugLog(<< "Closing TransportSelector::mSocket[" << socketIterator->first << "]");
}
}
for(HashMap<Data, Socket>::iterator socketIterator = mSocket6s.begin();
socketIterator != mSocket6s.end(); socketIterator++)
{
if (socketIterator->second != INVALID_SOCKET)
{
closeSocket(socketIterator->second);
DebugLog(<< "Closing TransportSelector::mSocket6[" << socketIterator->first << "]");
}
}
setPollGrp(0);
}
void
TransportSelector::shutdown()
{
for(TransportKeyMap::iterator it = mTransports.begin(); it != mTransports.end(); it++)
{
it->second->shutdown();
}
}
bool
TransportSelector::isFinished() const
{
for(TransportKeyMap::const_iterator it = mTransports.begin(); it != mTransports.end(); it++)
{
if (!it->second->isFinished())
{
return false;
}
}
return true;
}
void
TransportSelector::addTransport(std::auto_ptr<Transport> autoTransport, bool isStackRunning)
{
Transport* transport = autoTransport.release();
// !bwc! This is a multimap from TransportType/IpVersion to Transport*.
// Make _extra_ sure that no garbage goes in here.
if(transport->transport()==TCP)
{
resip_assert(dynamic_cast<TcpTransport*>(transport));
}
#ifdef USE_SSL
else if(transport->transport()==TLS)
{
resip_assert(dynamic_cast<TlsTransport*>(transport));
}
#endif
else if(transport->transport()==UDP)
{
resip_assert(dynamic_cast<UdpTransport*>(transport));
}
#ifdef USE_DTLS
#ifdef USE_SSL
else if(transport->transport()==DTLS)
{
resip_assert(dynamic_cast<DtlsTransport*>(transport));
}
#endif
#endif
else if(transport->transport()==WS)
{
resip_assert(dynamic_cast<WsTransport*>(transport));
}
#ifdef USE_SSL
else if(transport->transport()==WSS)
{
resip_assert(dynamic_cast<WssTransport*>(transport));
}
#endif
else
{
resip_assert(0);
}
Tuple tuple(transport->interfaceName(), transport->port(),
transport->ipVersion(), transport->transport(),
Data::Empty, // Domain
transport->netNs());
tuple.mTransportKey = transport->getKey();
if(!isSecure(transport->transport()))
{
if(mExactTransports.find(tuple) == mExactTransports.end() &&
mAnyInterfaceTransports.find(tuple) == mAnyInterfaceTransports.end())
{
DebugLog (<< "Adding transport: " << tuple);
// Store the transport in the ANY interface maps if the tuple specifies ANY
// interface. Store the transport in the specific interface maps if the tuple
// specifies an interface. See TransportSelector::findTransport.
if (transport->interfaceName().empty() ||
transport->getTuple().isAnyInterface() ||
transport->hasSpecificContact() )
{
mAnyInterfaceTransports[tuple] = transport;
mAnyPortAnyInterfaceTransports[tuple] = transport;
}
else
{
mExactTransports[tuple] = transport;
mAnyPortTransports[tuple] = transport;
}
}
else
{
WarningLog (<< "Can't add transport, overlapping properties with existing transport: " << tuple);
resip_assert(false); // should never get here - checked in SipStack first
return;
}
}
else
{
tuple.setTargetDomain(transport->tlsDomain());
TlsTransportKey key(tuple);
if(mTlsTransports.find(key) == mTlsTransports.end())
{
mTlsTransports[key] = transport;
}
else
{
WarningLog (<< "Can't add transport, overlapping properties with existing transport: " << tuple);
resip_assert(false); // should never get here - checked in SipStack first
return;
}
}
if (transport->shareStackProcessAndSelect())
{
if ( mPollGrp )
{
transport->setPollGrp(mPollGrp);
}
if(isStackRunning)
{
// When stack is running we need to add to mSharedProcessTransports from
// within TransportSelectorThread in order to be thread safe
mTransportsToAddRemove.add(transport);
}
else
{
// Stack isn't running yet - just add to mSharedProcess directly - this
// ensures the mSharedProcessTransports list is propulated when the stack
// starts to run. When in multi-threaded stack mode the TransportSelectorThread
// will assume ownership (FdPollGrp control) of all the transports using this list.
mSharedProcessTransports.push_back(transport);
}
}
else
{
mHasOwnProcessTransports.push_back(transport);
mHasOwnProcessTransports.back()->startOwnProcessing();
}
mTypeToTransportMap.insert(TypeToTransportMap::value_type(tuple,transport));
mDns.addTransportType(transport->transport(), transport->ipVersion());
mTransports[transport->getKey()] = transport;
InfoLog(<< "TransportSelector::addTransport: added transport for tuple=" << tuple << ", key=" << transport->getKey());
}
void
TransportSelector::removeTransport(unsigned int transportKey)
{
Transport* transportToRemove = 0;
// Find transport in global map and remove it
// Note: it is important that this is map is removed from before rebuildAnyPortTransportMaps is called,
// since it uses this map.
TransportKeyMap::iterator it = mTransports.find(transportKey);
if(it != mTransports.end())
{
transportToRemove = it->second;
mTransports.erase(it);
}
// If we found the transport - continue removal from other maps
if(transportToRemove)
{
// notify transport to shutdown
transportToRemove->shutdown();
if(!isSecure(transportToRemove->transport()))
{
// Ensure transport is removed from all containers
mExactTransports.erase(transportToRemove->getTuple());
mAnyInterfaceTransports.erase(transportToRemove->getTuple());
// In the AnyPort maps 2 transports can end up overwriting each other in these maps - then when we remove one, there may be none left - even though we should have an
// entry. The rebuilt method will dig through all transports again and rebuild these maps.
rebuildAnyPortTransportMaps();
}
else
{
Tuple tlsRemoveTuple = transportToRemove->getTuple();
tlsRemoveTuple.setTargetDomain(transportToRemove->tlsDomain());
TlsTransportKey tlsKey(tlsRemoveTuple);
mTlsTransports.erase(tlsKey);
}
// mTypeToTransportMap is a multimap - make sure to delete only this instance by looking up transportKey, instead of using
// mTypeToTransportMap.erase(transportToRemove->getTuple()); which might end up deleting more than 1 transport
for (TypeToTransportMap::iterator itTypeToTransport = mTypeToTransportMap.begin(); itTypeToTransport != mTypeToTransportMap.end(); itTypeToTransport++)
{
if (itTypeToTransport->second->getKey() == transportKey)
{
mTypeToTransportMap.erase(itTypeToTransport);
break;
}
}
// Remove transport types from Dns list of supported protocols
// Note: DNS tracks use counts so that we will only remove this transport type if this is the last of the type to be removed
mDns.removeTransportType(transportToRemove->transport(), transportToRemove->ipVersion());
if (transportToRemove->shareStackProcessAndSelect())
{
// Note: We called shutdown above, therefor the TransportSelectorThread can tell this
// is a remove transpot request vs an addTransport request, by calling isShuttingDown().
mTransportsToAddRemove.add(transportToRemove); // Need to add to mSharedProcessTransports from within TransportSelectorThread
// Note: Transport will be deleted from mTransportsToAddRemove handler (see checkTransportAddRemoveQueue)
}
else
{
for(TransportList::iterator it = mHasOwnProcessTransports.begin(); it != mHasOwnProcessTransports.end(); it++)
{
if((*it)->getKey() == transportKey)
{
mHasOwnProcessTransports.erase(it);
break;
}
}
// Delete transport
delete transportToRemove;
}
}
}
void
TransportSelector::rebuildAnyPortTransportMaps()
{
// These maps may contain less transports than what exist in the mTransports map, due to the fact that multiple transports can
// match their index. In these cases the last transport added that matchs the map compare function is the only one that ends
// up in these maps. Therefor we cannot just simply remove items and expect transprot selection to work as expects.
// We will clear these maps here. Iterate through the master transport list and rebuilt them back up. This isn't very efficient,
// but it only occurs when a transport is removed.
mAnyPortTransports.clear();
mAnyPortAnyInterfaceTransports.clear();
for (TransportKeyMap::iterator it = mTransports.begin(); it != mTransports.end(); it++)
{
if (!isSecure(it->second->transport()))
{
// Store the transport in the ANY interface maps if the tuple specifies ANY
// interface. Store the transport in the specific interface maps if the tuple
// specifies an interface. See TransportSelector::findTransport.
if (it->second->interfaceName().empty() ||
it->second->getTuple().isAnyInterface() ||
it->second->hasSpecificContact())
{
mAnyPortAnyInterfaceTransports[it->second->getTuple()] = it->second;
}
else
{
mAnyPortTransports[it->second->getTuple()] = it->second;
}
}
}
}
void
TransportSelector::setPollGrp(FdPollGrp *grp)
{
if(mPollGrp && mInterruptorHandle)
{
// unregister our select interruptor
mPollGrp->delPollItem(mInterruptorHandle);
mInterruptorHandle=0;
}
mPollGrp = grp;
if(mPollGrp && mSelectInterruptor.get())
{
mInterruptorHandle = mPollGrp->addPollItem(mSelectInterruptor->getReadSocket(), FPEM_Read, mSelectInterruptor.get());
}
for(TransportList::iterator t=mSharedProcessTransports.begin(); t!=mSharedProcessTransports.end(); ++t)
{
(*t)->setPollGrp(mPollGrp);
}
}
void
TransportSelector::createSelectInterruptor()
{
if(!mSelectInterruptor.get())
{
mSelectInterruptor.reset(new SelectInterruptor);
if(mPollGrp)
{
mInterruptorHandle = mPollGrp->addPollItem(mSelectInterruptor->getReadSocket(), FPEM_Read, mSelectInterruptor.get());
}
}
}
void
TransportSelector::buildFdSet(FdSet& fdset)
{
for(TransportList::iterator it = mSharedProcessTransports.begin(); it != mSharedProcessTransports.end(); it++)
{
(*it)->buildFdSet(fdset);
}
if(mSelectInterruptor.get())
{
mSelectInterruptor->buildFdSet(fdset);
}
}
void
TransportSelector::process(FdSet& fdset)
{
checkTransportAddRemoveQueue();
for(TransportList::iterator it = mSharedProcessTransports.begin(); it != mSharedProcessTransports.end(); it++)
{
try
{
(*it)->process(fdset);
}
catch (BaseException& e)
{
ErrLog (<< "Exception thrown from Transport::process: " << e);
}
}
if(mSelectInterruptor.get())
{
mSelectInterruptor->process(fdset);
}
}
void
TransportSelector::process()
{
// This function will only be sufficient if these Transports are hooked into a FdPollGrp.
checkTransportAddRemoveQueue();
for(TransportList::iterator it = mSharedProcessTransports.begin(); it != mSharedProcessTransports.end(); it++)
{
try
{
(*it)->process();
}
catch (BaseException& e)
{
ErrLog (<< "Exception thrown from Transport::process: " << e);
}
}
}
void
TransportSelector::checkTransportAddRemoveQueue()
{
// This method ensures we add/remove from/to the mSharedProcessTransports
// list from the TransportSelectorThread
Transport* t(mTransportsToAddRemove.getNext(-1));
while(t)
{
if(!t->isShuttingDown())
{
// If not shutting down then this is an addTransport request
mSharedProcessTransports.push_back(t);
}
else
{
// If shutting down then this is a removeTransport request
for(TransportList::iterator it = mSharedProcessTransports.begin(); it != mSharedProcessTransports.end(); it++)
{
if((*it)->getKey() == t->getKey())
{
mSharedProcessTransports.erase(it);
break;
}
}
// Now delete the transport
delete t;
}
t = mTransportsToAddRemove.getNext(-1);
}
}
void
TransportSelector::poke()
{
for(TransportList::iterator it = mHasOwnProcessTransports.begin(); it != mHasOwnProcessTransports.end(); it++)
{
try
{
(*it)->poke();
}
catch (BaseException& e)
{
ErrLog (<< "Exception thrown from Transport::process: " << e);
}
}
if(mSelectInterruptor.get() /* && hasDataToSend() */) // removed hasDataToSend call since it is not thread safe
{
mSelectInterruptor->handleProcessNotification();
}
}
bool
TransportSelector::hasDataToSend() const
{
for(TransportList::const_iterator it = mSharedProcessTransports.begin(); it != mSharedProcessTransports.end(); it++)
{
if ((*it)->hasDataToSend())
{
return true;
}
}
return false;
}
//!jf! the problem here is that DnsResult is returned after looking
//mDns.lookup() but this can result in a synchronous call to handle() which
//assumes that dnsresult has been assigned to the TransactionState
//!dcm! -- now 2-phase to fix this
DnsResult*
TransportSelector::createDnsResult(DnsHandler* handler)
{
return mDns.createDnsResult(handler);
}
void
TransportSelector::dnsResolve(DnsResult* result,
SipMessage* msg)
{
// Picking the target destination:
// - for request, use forced target if set
// otherwise use loose routing behaviour (route or, if none, request-uri)
// - for response, use forced target if set, otherwise look at via
if (msg->isRequest())
{
// If this is an ACK we need to fix the tid to reflect that
if (msg->hasForceTarget())
{
//DebugLog(<< "!ah! RESOLVING request with force target : " << msg->getForceTarget() );
mDns.lookup(result, msg->getForceTarget());
}
else if (msg->exists(h_Routes) && !msg->const_header(h_Routes).empty())
{
// put this into the target, in case the send later fails, so we don't
// lose the target
msg->setForceTarget(msg->const_header(h_Routes).front().uri());
DebugLog (<< "Looking up dns entries (from route) for " << msg->getForceTarget());
mDns.lookup(result, msg->getForceTarget());
}
else
{
DebugLog (<< "Looking up dns entries for " << msg->const_header(h_RequestLine).uri());
mDns.lookup(result, msg->const_header(h_RequestLine).uri());
}
}
else if (msg->isResponse())
{
ErrLog(<<"unimplemented response dns");
resip_assert(0);
}
else
{
resip_assert(0);
}
}
// FIXME: maybe this should move to rutil/TransportType?
bool isDgramTransport (TransportType type)
{
static const bool unknown_transport = false;
switch(type)
{
case UDP:
case DTLS:
case DCCP:
case SCTP:
return true;
case TCP:
case TLS:
case WS:
case WSS:
return false;
default:
resip_assert(unknown_transport);
return unknown_transport; // !kh! just to make it compile wo/warning.
}
}
Tuple
TransportSelector::getFirstInterface(bool is_v4, TransportType type)
{
// !kh! both getaddrinfo() and IPv6 are not supported by cygwin, yet.
#ifdef __CYGWIN__
resip_assert(0);
return Tuple();
#else
// !kh!
// 1. Query local hostname.
char hostname[256] = "";
if(gethostname(hostname, sizeof(hostname)) != 0)
{
int e = getErrno();
Transport::error( e );
InfoLog(<< "Can't query local hostname : [" << e << "] " << strerror(e) );
throw Transport::Exception("Can't query local hostname", __FILE__, __LINE__);
}
InfoLog(<< "Local hostname is [" << hostname << "]");
// !kh!
// 2. Resolve address(es) of local hostname for specified transport.
const bool is_dgram = isDgramTransport(type);
addrinfo hint;
memset(&hint, 0, sizeof(hint));
hint.ai_family = is_v4 ? PF_INET : PF_INET6;
hint.ai_flags = AI_PASSIVE;
hint.ai_socktype = is_dgram ? SOCK_DGRAM : SOCK_STREAM;
addrinfo* results;
int ret = getaddrinfo(
hostname,
0,
&hint,
&results);
if(ret != 0)
{
Transport::error( ret ); // !kh! is this the correct sematics? ret is not errno.
InfoLog(<< "Can't resolve " << hostname << "'s address : [" << ret << "] " << gai_strerror(ret) );
throw Transport::Exception("Can't resolve hostname", __FILE__,__LINE__);
}
// !kh!
// 3. Use first address resolved if there are more than one.
// What should I do if there are more than one address?
// i.e. results->ai_next != 0.
Tuple source(*(results->ai_addr), type);
InfoLog(<< "Local address is " << source);
addrinfo* ai = results->ai_next;
for(; ai; ai = ai->ai_next)
{
Tuple addr(*(ai->ai_addr), type);
InfoLog(<<"Additional address " << addr);
}
freeaddrinfo(results);
return source;
#endif
}
/**
Check the msg's top Via header for a source host&port that indicates a particular Transport.
Do NOT do this for a response, as it would allow malicious downstream to insert bogus host
in via header that we would then use.
**/
Transport*
TransportSelector::findTransportByVia(SipMessage* msg, const Tuple& target, Tuple& source) const
{
resip_assert(msg->exists(h_Vias));
resip_assert(!msg->const_header(h_Vias).empty());
const Via& via = msg->const_header(h_Vias).front();
if (via.sentHost().empty() && via.transport().empty())
{
return 0;
}
// XXX: Is there better way to do below (without the copy)?
source = Tuple(via.sentHost(), via.sentPort(), target.ipVersion(),
via.transport().empty() ? target.getType() : toTransportType(via.transport()), // Transport type is pre-populated in via, lock to it
Data::Empty, target.getNetNs());
DebugLog(<< "TransportSelector::findTransportByVia: source: " << source);
if ( target.mFlowKey!=0 && (source.getPort()==0 || source.isAnyInterface()) )
{
WarningLog(<< "Sending request with incomplete Via header and FlowKey."
<<" This code no smart enough to pick the correct Transport."
<<" Via=" << via);
resip_assert(0);
}
if ( source.isAnyInterface() )
{
// INADDR_ANY cannot go out on the wire, so remove it from
// via header now.
// transmit() will later use determineSourceInterface() to
// get the actual interface to populate the Contact & Via headers.
// Not sure if we should support this case or just assert.
// .gh. This should be supported, in case only the transport part of the Via is set
msg->header(h_Vias).front().sentHost().clear();
}
Transport *trans;
if ( (trans = findTransportBySource(source, msg)) == NULL )
{
return NULL;
}
if(source.getPort()==0)
{
source.setPort(trans->port());
}
return trans;
}
Tuple
TransportSelector::determineSourceInterface(SipMessage* msg, const Tuple& target) const
{
resip_assert(msg->exists(h_Vias));
resip_assert(!msg->header(h_Vias).empty());
const Via& via = msg->header(h_Vias).front();
// this case should be handled already for UDP and TCP targets
resip_assert((!(msg->isRequest() && !via.sentHost().empty())) || isSecure(target.getType()));
if (1)
{
Tuple source(target);
#if defined(WIN32) && !defined(NO_IPHLPAPI)
try
{
GenericIPAddress addr = WinCompat::determineSourceInterface(target.toGenericIPAddress());
source.setSockaddr(addr);
}
catch (WinCompat::Exception& ex)
{
ErrLog (<< "Can't find source interface to use: " << ex);
throw Transport::Exception("Can't find source interface", __FILE__, __LINE__);
}
#else
// !kh!
// The connected UDP technique doesn't work all the time.
// 1. Might not work on all implementaions as stated in UNP vol.1 8.14.
// 2. Might not work under unspecified condition on Windows,
// search "getsockname" in MSDN library.
// 3. We've experienced this issue on our production software.
// this process will determine which interface the kernel would use to
// send a packet to the target by making a connect call on a udp socket.
Socket tmp = INVALID_SOCKET;
Data netNs = target.getNetNs();
// One IPV4 and IPV6 socket per namespace. Even if we do not support netns,
// we still have the default namespace of "" (empty string).
if (target.isV4())
{
// If socket does not exist for namespace, create one
if (mSockets.find(netNs) == mSockets.end() || mSockets[netNs] == INVALID_SOCKET)
{
#ifdef USE_NETNS
NetNs::setNs(netNs);
#endif
mSockets[netNs] = InternalTransport::socket(UDP, V4); // may throw
}
tmp = mSockets[netNs];
}
else
{
// If socket does not exist for namespace, create one
if (mSocket6s.find(netNs) == mSocket6s.end() || mSocket6s[netNs] == INVALID_SOCKET)
{
#ifdef USE_NETNS
NetNs::setNs(netNs);
#endif
mSocket6s[netNs] = InternalTransport::socket(UDP, V6); // may throw
}
tmp = mSocket6s[netNs];
}
#ifdef USE_NETNS
// Not sure if connect has to be done in netns context or just the socket create
NetNs::setNs(netNs);
#endif
int ret = connect(tmp,&target.getSockaddr(), target.length());
if (ret < 0)
{
int e = getErrno();
Transport::error( e );
InfoLog(<< "Unable to route to " << target << " : [" << e << "] " << strerror(e) );
throw Transport::Exception("Can't find source address for Via", __FILE__,__LINE__);
}
socklen_t len = source.length();
ret = getsockname(tmp,&source.getMutableSockaddr(), &len);
if (ret < 0)
{
int e = getErrno();
Transport::error(e);
InfoLog(<< "Can't determine name of socket " << target << " : " << strerror(e) );
throw Transport::Exception("Can't find source address for Via", __FILE__,__LINE__);
}
// !kh! test if connected UDP technique results INADDR_ANY, i.e. 0.0.0.0.
// if it does, assume the first avaiable interface.
if(source.isV4())
{
long src = (reinterpret_cast<const sockaddr_in*>(&source.getSockaddr())->sin_addr.s_addr);
if(src == INADDR_ANY)
{
InfoLog(<< "Connected UDP failed to determine source address, use first address instaed.");
source = getFirstInterface(true, target.getType());
}
}
else // IPv6
{
//should never reach here in WIN32 w/ V6 support
#if defined(USE_IPV6) && !defined(WIN32)
if (source.isAnyInterface()) //!dcm! -- when could this happen?
{
source = getFirstInterface(false, target.getType());
}
# endif
}
// Unconnect.
// !jf! This is necessary, but I am not sure what we can do if this
// fails. I'm not sure the stack can recover from this error condition.
if (target.isV4())
{
ret = connect(mSockets[netNs],
(struct sockaddr*)&mUnspecified.v4Address,
sizeof(mUnspecified.v4Address));
}
#ifdef USE_IPV6
else
{
ret = connect(mSocket6s[netNs],
(struct sockaddr*)&mUnspecified6.v6Address,
sizeof(mUnspecified6.v6Address));
}
#else
else
{
resip_assert(0);
}
#endif
if ( ret<0 )
{
int e = getErrno();
//.dcm. OS X 10.5 workaround, we could #ifdef for specific OS X version.
if (!(e ==EAFNOSUPPORT || e == EADDRNOTAVAIL))
{
ErrLog(<< "Can't disconnect socket : " << strerror(e) );
Transport::error(e);
throw Transport::Exception("Can't disconnect socket", __FILE__,__LINE__);
}
}
#endif
// This is the port that the request will get sent out from. By default,
// this value will be 0, since the Helper that creates the request will not
// assign it. In this case, the stack will pick an arbitrary (but appropriate)
// transport. If it is non-zero, it will only match transports that are bound to
// the specified port (and fail if none are available)
if(msg->isRequest())
{
source.setPort(via.sentPort());
}
else
{
source.setPort(0);
}
DebugLog (<< "Looked up source for destination: " << target
<< " -> " << source
<< " sent-by=" << via.sentHost()
<< " sent-port=" << via.sentPort());
return source;
}
}
// !jf! there may be an extra copy of a tuple here. can probably get rid of it
// but there are some const issues.
TransportSelector::TransmitState
TransportSelector::transmit(SipMessage* msg, Tuple& target, SendData* sendData)
{
resip_assert(msg);
if(msg->mIsDecorated)
{
msg->rollbackOutboundDecorators();
}
try
{
TransportFailure::FailureReason transportFailureReason = TransportFailure::NoTransport;
// !ah! You NEED to do this for responses too -- the transport doesn't
// !ah! know it's IP addres(es) in all cases, AND it's function of the dest.
// (imagine a synthetic message...)
Tuple source;
// .bwc. We need 3 things here:
// 1) A Transport* to call send() on.
// 2) A complete Tuple to pass in this call (target).
// 3) A host, port, and protocol for filling out the topmost via, and
// possibly stuff like Contact, Referred-By, and other headers that
// must specify a hostname that the TU was unable to supply, because
// it didn't know what interface/port the message would be sent on.
// (source)
/*
Our Transport* might be found in target. If so, we can skip this block
of stuff.
Alternatively, we might not have the transport to start with. However,
given a connection id, we will be able to find the Connection we
should use, we can get the Transport we want. If we have no connection
id, but we know we are using TLS, DTLS or WSS and have a tls hostname, we
can use the hostname to find the appropriate transport. If all else
fails, we must resort to the connected UDP trick to fill out source,
which in turn is used to look up a matching transport.
Given the transport, it is always possible to get the port/protocol,
and usually possible to get the host (if it is bound to INADDR_ANY, we
can't tell). However, if we had to fill out source in order to find
the transport in the first place, this is not an issue.
*/
Data remoteSigcompId;
Transport* transport=0;
if (msg->isRequest())
{
transport = findTransportByVia(msg, target, source);
if (!transport)
{
if ((transport = findTransportByDest(target)) != NULL)
{
source = transport->getTuple();
DebugLog(<< "Found transport: " << source);
}
}
else
{
DebugLog(<< "Found transport: " << source);
}
if(!transport && target.mFlowKey && target.onlyUseExistingConnection)
{
// .bwc. Connection info was specified, and use of this connection
// was mandatory, but connection is no longer around. We fail.
transportFailureReason = TransportFailure::TransportNoExistConn;
}
else if (transport)// .bwc. Here we use transport to find source.
{
resip_assert( source.getType()!=0 );
// .bwc. If the transport has an ambiguous interface, we need to