summaryrefslogtreecommitdiffstats
path: root/test/xmpp_dummy_server.cpp
blob: 9316f37dd365220c14acb172e72a1f19a3793637 (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
///////////////////////////////////////////////////////////////////////////////
//
// Copyright 2015 Intel Mobile Communications GmbH All Rights Reserved.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//
// 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.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//
//
///////////////////////////////////////////////////////////////////////////////

/// @file xmpp_tests.cpp

#include "stdafx.h"
#include <gtest/gtest.h>

#include <common/buffers.h>
#include <xml/portabledom.h>
#include <common/str_helpers.h>
#include <xmpp/xmppclient.h>
#include <xmpp/sasl.h>
#include <common/bufferencrypt.h>
#include <connect/connecterror.h>

#include "xmpp_dummy_server.h"



#if !defined(__GNUC__) || __GNUC__>4 || (__GNUC__==4 && __GNUC_MINOR__>9)
#include <regex>
#define REGEX_SUPPORTED
#endif

extern "C"
{
#if !defined(_WIN32)
#include <safe_mem_lib.h>
#include <safe_str_lib.h>
#endif
}



using namespace std;
using namespace Iotivity;
using namespace Iotivity::Xmpp;
using namespace Iotivity::XML;


#ifndef DISABLE_SUPPORT_NATIVE_XMPP_CLIENT


void DummyTCPConnect::close() {}
void DummyTCPConnect::connect(std::chrono::milliseconds &&timeout) {}
void DummyTCPConnect::send(const ByteBuffer &buf) {}
size_t DummyTCPConnect::receive(ByteBuffer &buf, asio::error_code &errorCode) { return 0; }
void DummyTCPConnect::async_receive(std::shared_ptr<ByteBuffer> buffer, ReceiveCallback f)
{
    if (!buffer)
    {
        throw connect_error(LocalError(LocalError::ecInvalidParameter));
    }
    f(connect_error::SUCCESS, buffer->size());
}

//////////
SegmentedDummyTCPConnect::SegmentedDummyTCPConnect(const SegmentArray &segments):
    m_segments(segments), m_currentIndex(0), m_matchFailures(0),
    m_promiseClosed(), m_closed(m_promiseClosed.get_future()), m_captures()
{}

void SegmentedDummyTCPConnect::close()
{
    m_promiseClosed.set_value();
}

void SegmentedDummyTCPConnect::send(const ByteBuffer &buf)
{
    static const char CLOSE_BUFFER_STR[] = "</stream:stream>";
    static const ByteBuffer CLOSE_BUFFER(CLOSE_BUFFER_STR, sizeof(CLOSE_BUFFER_STR) - 1);
    if (currentAction() == Segment::WaitForSend)
    {
        const string &currentData = m_segments.at(m_currentIndex).m_data;

        nextAction();

        // Allow "" to match any send data.
        if (currentData.size() != 0)
        {
            string tempStr((const char *)buf.get(), buf.size());
            if (tempStr != currentData)
            {
                ++m_matchFailures;
                cout << "SEND Failed to Match. Expected:" << endl;
                cout << currentData << endl;
                cout << "Received: " << endl;
                cout << tempStr << endl;
                EXPECT_NO_THROW(throw runtime_error("Expected Send Missing"));
            }
        }
    }
    else if (currentAction() == Segment::WaitForSendCapture)
    {
        const string &currentData = m_segments.at(m_currentIndex).m_data;

        nextAction();

        m_captures[currentData] = string((const char *)buf.get(), buf.size());
        cout << "CAPTURED: " << currentData << ":" << m_captures[currentData] << endl;
    }
    else if (buf != CLOSE_BUFFER && currentAction() != Segment::OutOfActions)
    {
        ++m_matchFailures;
        throw runtime_error("Data sent outside of WaitForSend segment");
    }
}

void SegmentedDummyTCPConnect::async_send(std::shared_ptr<ByteBuffer> buffer, SendCallback f)
{
    if (buffer)
    {
        send(*buffer);
        f(connect_error::SUCCESS, buffer->size());
    }
    else
    {
        f(connect_error(LocalError(LocalError::ecInvalidParameter)), 0);
    }
}

size_t SegmentedDummyTCPConnect::receive(ByteBuffer &, asio::error_code &)
{
    cout << "SIM READ" << endl;
    return 0;
}

void SegmentedDummyTCPConnect::async_receive(std::shared_ptr<ByteBuffer> buffer,
        ReceiveCallback f)
{
    if (!buffer)
    {
        throw connect_error(LocalError(LocalError::ecInvalidParameter));
    }

    if (currentAction() == Segment::PlayDataNow)
    {
        const string &currentData = m_segments.at(m_currentIndex).m_data;
        //cout<< "ASYNC_RECEIVE"<< currentData<< endl;
        if (buffer->size() < currentData.size())
        {
            // NOTE: This is not an issue with the tcp connection; the test simulation
            //       just needs to be able to fit its segments into the read buffers.
            //       If the read buffers get smaller, the segments will need to be
            //       smaller too, but this should not affect normal operation.
            throw runtime_error("Insufficient buffer for simulated read request");
        }
        memcpy_s(buffer->get(), buffer->size(), currentData.c_str(), currentData.size());
        nextAction();
        f(connect_error::SUCCESS, currentData.size());
    }
    else if (currentAction() == Segment::ServerSubstitution)
    {

#ifdef REGEX_SUPPORTED
        string currentData = m_segments.at(m_currentIndex).m_data, copyData = currentData;
        const static regex s_substitutionFilter("\\$\\{([^\\}]+)\\}");

        for (auto i = sregex_iterator(copyData.begin(), copyData.end(), s_substitutionFilter);
             i != sregex_iterator(); ++i)
        {
            auto match = *i;
            bool foundExpression = false;
            auto fullMatchStr = match.str(), replaceStr = fullMatchStr;

            auto splitV = str_helper::split(match[1].str(), '.');
            list<string> split;
            copy(splitV.begin(), splitV.end(), back_inserter(split));

            if (!split.empty())
            {
                string tag = split.front();
                split.pop_front();

                const auto f = m_captures.find(tag);
                if (f != m_captures.end())
                {
                    string tagStanza = m_captures[tag];

                    auto doc = XMLDocument::createEmptyDocument();
                    doc->parse(tagStanza);
                    auto element = doc->documentElement();

                    if (element)
                    {
                        while (!split.empty())
                        {
                            if (element->name() == split.front())
                            {
                                split.pop_front();
                                if (split.empty()) break;
                            }

                            string attrTest;
                            if (element->getAttribute(split.front(), attrTest))
                            {
                                string last = split.front();
                                split.pop_front();
                                if (split.empty())
                                {
                                    // This is the attribute we are looking for
                                    foundExpression = true;
                                    replaceStr = attrTest;
                                    break;
                                }
                                else
                                {
                                    // Must not be an attribute. Keep looking
                                    split.push_front(last);
                                }
                            }

                            for (auto &i : element->elements())
                            {
                                if (i->name() == split.front())
                                {
                                    split.pop_front();
                                    element.reset(i.release());
                                    break;
                                }
                            }

                            if (split.empty()) break;
                            split.pop_front();
                        }
                    }

                    if (foundExpression)
                    {
                        auto f = currentData.find(fullMatchStr);
                        if (f != string::npos)
                        {
                            currentData.erase(f, fullMatchStr.size());
                            currentData.insert(f, replaceStr);
                        }
                    }

                }
                else
                {
                    cout << "WARNING: Test substitution variable " << tag <<
                         " did not match known parameters" << endl;
                }
            }
        }

        if (buffer->size() < currentData.size())
        {
            throw runtime_error("Insufficient buffer for simulated read request");
        }
        memcpy_s(buffer->get(), buffer->size(), currentData.c_str(), currentData.size());
        nextAction();
        f(connect_error::SUCCESS, currentData.size());
#else
        cout << "WARNING: TEST UNUSABLE ON THIS PLATFORM; REGEX IS NOT SUPPORTED" << endl;
#endif

    }
    else
    {
        //cout<< "INVALID STREAM CURRENT STATE: "<< currentAction()<< endl;
        f(connect_error::ecInvalidStream, 0);
    }
}

void SegmentedDummyTCPConnect::negotiateTLS(TLSCallback callback)
{
    if (callback) callback(connect_error::SUCCESS);
}

Segment::Action SegmentedDummyTCPConnect::currentAction() const
{
    return m_currentIndex < m_segments.size() ?
           m_segments[m_currentIndex].m_action :
           Segment::OutOfActions;
}

void SegmentedDummyTCPConnect::nextAction()
{
    do
    {
        ++m_currentIndex;
    }
    while (currentAction() > Segment::FirstConfigAction &&
           currentAction() < Segment::LastConfigAction);
}



void SegmentRunner::run(const SegmentArray &segments)
{
    try
    {
        bool willCompleteNegotiation = true, willCompleteBind = false, exitWithStateIntact = false;
        list<string> SASLPreferences;
        for (const auto &s : segments)
        {
            switch (s.m_action)
            {
                case Segment::UpdateSASLPreferences:
                    SASLPreferences.push_back(s.m_data);
                    break;
                case Segment::IncompleteNegotation:
                    willCompleteNegotiation = false;
                    break;
                case Segment::WillCompleteBind:
                    willCompleteBind = true;
                    break;
                case Segment::ExitWithStateIntact:
                    exitWithStateIntact = true;
                    break;
                default:
                    break;
            }
        }

        auto remoteTcp = make_shared<SegmentedDummyTCPConnect>(segments);

        auto xmlConnection = make_shared<XmppConnection>(
                                 static_pointer_cast<IStreamConnection>(remoteTcp));

        auto streamPromise = make_shared<promise<shared_ptr<IXmppStream>>>();
        auto streamFuture = streamPromise->get_future();

        m_config.overrideSASLOrder(SASLPreferences);

        m_client = XmppClient::create();
        ASSERT_NO_THROW(m_client->initiateXMPP(m_config, xmlConnection, streamPromise));

        m_stream = streamFuture.get();
        EXPECT_NE(m_stream, nullptr);

        if (m_stream)
        {
            if (willCompleteNegotiation)
            {
                auto status = m_stream->whenNegotiated().wait_for(chrono::seconds(5));
                EXPECT_EQ(status, future_status::ready);

                if (willCompleteBind)
                {
                    auto status = m_stream->whenBound().wait_for(chrono::seconds(5));
                    EXPECT_EQ(status, future_status::ready);
                }
            }
            size_t sleepCount = 0;
            while (!remoteTcp->lastSegmentRan() && sleepCount < 1000)
            {
                ++sleepCount;
                this_thread::sleep_for(chrono::milliseconds(1));
            }

            if (!exitWithStateIntact)
            {
                EXPECT_NO_THROW(m_stream->close());

                remoteTcp->closed().wait();
            }
            EXPECT_EQ(remoteTcp->expressionMatchFailures(), 0);

            m_captures = remoteTcp->captures();
        }
    }
    catch (const enum Segment::Action &state)
    {
        if (state == Segment::ExitWithStateIntact)
        {
            cout << "EXIT WITH STATE INTACT" << endl;
        }
        else
        {
            EXPECT_NO_THROW(throw state);
        }
    }
    catch (const connect_error &ce)
    {
        EXPECT_NO_THROW(throw ce);
    }
    catch (const runtime_error &re)
    {
        EXPECT_NO_THROW(throw re);
    }
}

#endif // ifndef DISABLE_SUPPORT_NATIVE_XMPP_CLIENT