File: testSipStackNetNs.cxx

package info (click to toggle)
resiprocate 1%3A1.11.0~beta1-3%2Bdeb9u1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 37,944 kB
  • sloc: cpp: 206,325; xml: 12,515; sh: 12,418; ansic: 6,973; makefile: 2,315; php: 1,150; python: 355; sql: 142; objc: 91; perl: 21; csh: 5
file content (392 lines) | stat: -rw-r--r-- 15,568 bytes parent folder | download | duplicates (2)
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
#include <memory>

#include <cassert>
#include <sys/types.h>
#include <ifaddrs.h>

#include "rutil/Log.hxx"
#include "rutil/NetNs.hxx"
#include "rutil/HashMap.hxx"
#include "rutil/DnsUtil.hxx"
#include "resip/stack/EventStackThread.hxx"
#include "resip/stack/TransactionUser.hxx"
#include "resip/stack/SipStack.hxx"
#include "resip/stack/Helper.hxx"

using namespace resip;
using namespace std;

#ifdef USE_NETNS

typedef vector<Data> DataVector;

class WakeUpMessage : public Message
{
public:
    WakeUpMessage(){};
    virtual ~WakeUpMessage(){};

    virtual resip::Message* clone() const {return(new WakeUpMessage());};
    virtual std::ostream& encode(std::ostream& s) const {return(s);};
    virtual std::ostream& encodeBrief(std::ostream& s) const {return(s);};
};

class TestTransactionConsumer : public TransactionUser
{
private:
    static Data sName;

public:
    TestTransactionConsumer()
    {
    };

    ~TestTransactionConsumer()
    {
    };

    Data& name() const
    {
        return(sName);
    };

    Message* getMessage()
    {
        return(mFifo.getNext(3000));
    };

    void sendWakeUp()
    {
        WakeUpMessage* wakeUp = new WakeUpMessage();
        mFifo.add(wakeUp, TimeLimitFifo<Message>::InternalElement);
    };
};
Data TestTransactionConsumer::sName;

int getInterfaces(HashMap<Data, DataVector> & interfaces)
{
   int interfaceCount = 0;
   struct ifaddrs* interfaceList = NULL;

   getifaddrs(&interfaceList);
   struct ifaddrs* interface = interfaceList;
   while(interface)
   {
      if(interface->ifa_flags)
      {
         Data address = 
            inet_ntoa(((struct sockaddr_in*)interface->ifa_addr)->sin_addr);

         if(address.find(".0.0.0") == Data::npos)
         {
            interfaces[interface->ifa_name].push_back(address);
            //resipCerr << interface->ifa_name << "=" << address
            //    << "(" << interface->ifa_flags << ")" << std::endl;
            interfaceCount++;
         }
      }

      interface = interface->ifa_next;
   }

   return(interfaceCount);
}

bool testSendReceiveOnAllInterfaces()
{
   int sendPort = 15060;
   int receivePort = 25060;

   // Create a stack to send message from
   FdPollGrp* sendFdPollGroup = FdPollGrp::create();
   EventThreadInterruptor* sendResipStackInteruptor = new EventThreadInterruptor(*sendFdPollGroup);

   SipStackOptions sendSipStackOptions;
   sendSipStackOptions.mAsyncProcessHandler = sendResipStackInteruptor;
   sendSipStackOptions.mStateless = false;
   sendSipStackOptions.mPollGrp = sendFdPollGroup;

   SipStack* sendSipStack = new SipStack(sendSipStackOptions);
   
   EventStackThread* sendMainSipStackThread =  
       new EventStackThread(*sendSipStack,
                            *sendResipStackInteruptor,
                            *sendFdPollGroup);

   // Register a consumer for SIP transactions
   TestTransactionConsumer* sendSipTransactionConsumer = new TestTransactionConsumer();
   sendSipStack->registerTransactionUser(*sendSipTransactionConsumer);

   // Start the sender stack
   sendSipStack->run();
   sendMainSipStackThread->run();


   // Create a stack to receive message from
   FdPollGrp* receiveFdPollGroup = FdPollGrp::create();
   EventThreadInterruptor* receiveResipStackInteruptor = new EventThreadInterruptor(*receiveFdPollGroup);

   SipStackOptions receiveSipStackOptions;
   receiveSipStackOptions.mAsyncProcessHandler = receiveResipStackInteruptor;
   receiveSipStackOptions.mStateless = false;
   receiveSipStackOptions.mPollGrp = receiveFdPollGroup;

   SipStack* receiveSipStack = new SipStack(receiveSipStackOptions);
   
   EventStackThread* receiveMainSipStackThread =  
       new EventStackThread(*receiveSipStack,
                            *receiveResipStackInteruptor,
                            *receiveFdPollGroup);

   // Register a consumer for SIP transactions
   TestTransactionConsumer* receiveSipTransactionConsumer = new TestTransactionConsumer();
   receiveSipStack->registerTransactionUser(*receiveSipTransactionConsumer);

   // Start the receiver stack
   receiveSipStack->run();
   receiveMainSipStackThread->run();


   vector<Data> publicNetNs;
   int netnsCount = NetNs::getPublicNetNs(publicNetNs);
   //resipCerr << "netns count: " << netnsCount <<std::endl;
   //resipCerr << "vector size: " << publicNetNs.size() <<std::endl;
   int sentMessageCount = 0;
   int receivedMessageCount = 0;

   assert(netnsCount);
   assert(netnsCount == (int) publicNetNs.size());
   for(unsigned int netNsIndex = 0; netNsIndex < publicNetNs.size(); netNsIndex++)
   {
      HashMap<Data, DataVector> currentInterfaces;

      resipCerr << "Found netns: \"" << publicNetNs[netNsIndex] << "\"" << std::endl;

      // Switch the current netns
      NetNs::setNs(publicNetNs[netNsIndex]);

      // Get the interfaces in the current netns
      getInterfaces(currentInterfaces);

      // Reset back to the default namespace
      // This is to be sure that addTransport uses the specified netns as opposed to
      // just getting lucky and using the current netns
      NetNs::setNs("");

      for(HashMap<Data, DataVector>::iterator interfaceItr = currentInterfaces.begin();
              interfaceItr != currentInterfaces.end(); ++ interfaceItr)
      {
         for(size_t addressIndex = 0; addressIndex < interfaceItr->second.size(); addressIndex++)
         {
            resipCerr << interfaceItr->first << "=" << interfaceItr->second[addressIndex] << std::endl;
            Data ipAddress = interfaceItr->second[addressIndex];
            bool isIpV6 = resip::DnsUtil::isIpV6Address(ipAddress);

            try
            {
                Transport* transport =
                    sendSipStack->addTransport(TCP,
                                               0, // any port available
                                               isIpV6 ? resip::V6 : resip::V4,
                                               StunDisabled,
                                               ipAddress,
                                               Data::Empty, // TLD domain
                                               Data::Empty, // private key pass phrase
                                               SecurityTypes::TLSv1,
                                               0, // transport flags
                                               Data::Empty, // cert filename
                                               Data::Empty, // private key filename
                                               SecurityTypes::None,
                                               false, // use email as SIP
                                               SharedPtr<resip::WsConnectionValidator>(),
                                               SharedPtr<resip::WsCookieContextFactory>(),
                                               publicNetNs[netNsIndex]);
                assert(transport);
                sendPort = transport->getTuple().getPort();
                cout << "Sending from port: " << sendPort << endl;

            }
            catch(resip::BaseException& e)
            {
                resipCerr << "Failed to bind TCP " << ipAddress << ":" << sendPort << "\n"
                        << e << std::endl;
                assert(0);
            }


            try
            {
                Transport* transport =
                    receiveSipStack->addTransport(TCP,
                                               0, // any port available
                                               isIpV6 ? resip::V6 : resip::V4,
                                               StunDisabled,
                                               ipAddress,
                                               Data::Empty, // TLD domain
                                               Data::Empty, // private key pass phrase
                                               SecurityTypes::TLSv1,
                                               0, // transport flags
                                               Data::Empty, // cert filename
                                               Data::Empty, // private key filename
                                               SecurityTypes::None,
                                               false, // use email as SIP
                                               SharedPtr<resip::WsConnectionValidator>(),
                                               SharedPtr<resip::WsCookieContextFactory>(),
                                               publicNetNs[netNsIndex]);
                assert(transport);
                receivePort = transport->getTuple().getPort();
                cout << "Receiving on port: " << receivePort << endl;

            }
            catch(resip::BaseException& e)
            {
                resipCerr << "Failed to bind TCP " << ipAddress << ":" << receivePort << "\n"
                        << e << std::endl;
                assert(0);
            }

            NameAddr from;
            from.uri().scheme() = "sip";
            from.uri().user() = "sender";
            from.uri().host() = ipAddress;
            from.uri().port() = sendPort;
            NameAddr target;
            target.uri().scheme() = "sip";
            target.uri().user() = "receiver";
            target.uri().host() = ipAddress;
            target.uri().port() = receivePort;
            target.uri().param(p_transport) = "tcp";
            target.uri().netNs() = publicNetNs[netNsIndex];
            MethodTypes method = OPTIONS;
            cout << "From: " << from << " To: " << target << endl;
            auto_ptr<SipMessage> sipRequest = auto_ptr<SipMessage>(Helper::makeRequest(target, from, method));
            assert(sipRequest->header(h_RequestLine).uri().netNs() == publicNetNs[netNsIndex]);

            // Send a message
            sendSipStack->send(sipRequest, sendSipTransactionConsumer);
            sentMessageCount++;

            // Receive request
            Message* message = receiveSipTransactionConsumer->getMessage();
            SipMessage* receivedRequest = static_cast<SipMessage*>(message);
            if(receivedRequest)
            {
               receivedMessageCount++;

               // Send back a response to stop resends
               // TODO
               auto_ptr<SipMessage> sipResponse(Helper::makeResponse(*receivedRequest, 200, "Got it"));
               receiveSipStack->send(sipResponse, receiveSipTransactionConsumer);
               
               // Assert we received it on the right interface
               Tuple receivedInterface = receivedRequest->getReceivedTransportTuple();
               cout << "Received request source netns: " << publicNetNs[netNsIndex] << " " << ipAddress << ":" << receivedInterface.getPort() << endl;
               assert(receivedInterface.getPort() == receivePort);
               assert(receivedInterface.getType() == resip::TCP);
               assert(Tuple::inet_ntop(receivedInterface) == ipAddress);
               assert(receivedInterface.getNetNs() == publicNetNs[netNsIndex]);
               Tuple receivedSourceTuple = receivedRequest->getSource();
               // TCP port of source will be actual client port, not server/listener port
               assert(receivedSourceTuple.getType() == resip::TCP);
               assert(Tuple::inet_ntop(receivedSourceTuple) == ipAddress);
               assert(receivedSourceTuple.getNetNs() == publicNetNs[netNsIndex]);
            }
            else
            {
               cout << "No message Received from netns: " << publicNetNs[netNsIndex] << " " << ipAddress << endl;
               assert(receivedRequest);
            }

            // Receive response
            message = sendSipTransactionConsumer->getMessage();
            assert(message);
            cout << "Message: " << message << endl;
            SipMessage* receivedResponse = static_cast<SipMessage*>(message);
            if(receivedResponse)
            {
               // Verify response came back on right IP address and netns
               Tuple receivedResponseInterface = receivedResponse->getReceivedTransportTuple();
               cout << "Received response source netns: " << publicNetNs[netNsIndex] << " " << ipAddress << ":" << receivedResponseInterface.getPort() << endl;
               assert(receivedResponseInterface.getType() == resip::TCP);
               assert(Tuple::inet_ntop(receivedResponseInterface) == ipAddress);
               assert(receivedResponseInterface.getPort() == sendPort);
               assert(receivedResponseInterface.getNetNs() == publicNetNs[netNsIndex]);
               Tuple receivedResponseSourceTuple = receivedResponse->getSource();
               // TCP port of source will be actual client port, not server/listener port
               assert(receivedResponseSourceTuple.getType() == resip::TCP);
               assert(Tuple::inet_ntop(receivedResponseSourceTuple) == ipAddress);
               assert(receivedResponseSourceTuple.getNetNs() == publicNetNs[netNsIndex]);
            }
            else if(message)
            {
               cout << "Non-SIP message: " << *message << endl;
            }
            else
            {
               cout << "No response Received from netns: " << publicNetNs[netNsIndex] << " " << ipAddress << endl;
               assert(receivedResponse);
            }
         }
      }

   }
   cout << "Received " << receivedMessageCount << " of " << sentMessageCount << " messages" << endl;

   return(false);
}

int main(int argc, const char* argv[])
{
    //Log::setLevel(Log::Stack);
    assert(!testSendReceiveOnAllInterfaces());

    resipCerr << "ALL OK" << std::endl;
    return(0);
}

#else

int main(int argc, const char* argv[])
{
    resipCerr << "USE_NETNS not set." << std::endl;
    return(0);
}

#endif

/* ====================================================================
 *
 * Copyright (c) 2014 Daniel Petrie, SIPez LLC  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. Neither the name of the author(s) nor the names of any contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR(S) OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * ====================================================================
 *
 */
 // vi: set shiftwidth=3 expandtab: