File: http_plugin_server_tests.cpp

package info (click to toggle)
pion 5.0.7%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 3,048 kB
  • ctags: 3,122
  • sloc: cpp: 14,237; perl: 269; pascal: 152; makefile: 145; sh: 70
file content (1194 lines) | stat: -rw-r--r-- 49,239 bytes parent folder | download
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
// ---------------------------------------------------------------------
// pion:  a Boost C++ framework for building lightweight HTTP interfaces
// ---------------------------------------------------------------------
// Copyright (C) 2007-2014 Splunk Inc.  (https://github.com/splunk/pion)
//
// Distributed under the Boost Software License, Version 1.0.
// See http://www.boost.org/LICENSE_1_0.txt
//


#include <pion/config.hpp>
#include <boost/asio.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/bind.hpp>
#include <boost/scoped_array.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/regex.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition.hpp>
#include <boost/filesystem.hpp>
#include <pion/plugin.hpp>
#include <pion/scheduler.hpp>
#include <pion/http/request.hpp>
#include <pion/http/response.hpp>
#include <pion/http/request_writer.hpp>
#include <pion/http/response_reader.hpp>
#include <pion/http/plugin_server.hpp>
#include <pion/user.hpp>
#include <pion/http/basic_auth.hpp>
#include <pion/http/cookie_auth.hpp>


using namespace std;
using namespace pion;

PION_DECLARE_PLUGIN(EchoService)
PION_DECLARE_PLUGIN(FileService)
PION_DECLARE_PLUGIN(HelloService)
PION_DECLARE_PLUGIN(LogService)
PION_DECLARE_PLUGIN(CookieService)

#if defined(PION_CMAKE_BUILD)
    #include "plugin_path.hpp"
#elif defined(PION_XCODE)
    static const std::string PATH_TO_PLUGINS("../bin/Debug");
    static const std::string SSL_PEM_FILE("../utils/sslkey.pem");
    static const std::string SERVICES_CONFIG_FILE("../tests/config/testservices.conf");
#else
    // same for Unix and Windows
    static const std::string PATH_TO_PLUGINS("../services/.libs");
    static const std::string SSL_PEM_FILE("../utils/sslkey.pem");
    static const std::string SERVICES_CONFIG_FILE("../tests/config/testservices.conf");
#endif


/// generates chunked POST requests for testing purposes
class ChunkedPostRequestSender : 
    public boost::enable_shared_from_this<ChunkedPostRequestSender>,
    private boost::noncopyable
{
public:
    /**
     * creates new ChunkedPostRequestSender objects
     *
     * @param tcp_conn TCP connection used to send the file
     * @param resource
     */
    static inline boost::shared_ptr<ChunkedPostRequestSender>
        create(const pion::tcp::connection_ptr& tcp_conn, const std::string& resource)
    {
        return boost::shared_ptr<ChunkedPostRequestSender>(new ChunkedPostRequestSender(tcp_conn, resource));
    }
    
    ~ChunkedPostRequestSender() {
        for (m_chunk_iterator = m_chunks.begin(); m_chunk_iterator != m_chunks.end(); ++m_chunk_iterator) {
            delete[] m_chunk_iterator->second;
        }
    }
    
    void send(void);

    void addChunk(size_t size, const char* ptr) {
        char* localCopy = new char[size];
        memcpy(localCopy, ptr, size);
        m_chunks.push_back(Chunk(size, localCopy));
        m_chunk_iterator = m_chunks.begin();
    }

protected:

    ChunkedPostRequestSender(const pion::tcp::connection_ptr& tcp_conn,
                             const std::string& resource);
    
    /**
     * handler called after a send operation has completed
     *
     * @param write_error error status from the last write operation
     * @param bytes_written number of bytes sent by the last write operation
     */
    void handle_write(const boost::system::error_code& write_error,
                     std::size_t bytes_written);

private:

    typedef std::pair<size_t, char*> Chunk;

    /// primary logging interface used by this class
    pion::logger                        m_logger;

    /// the chunks we are sending
    std::vector<Chunk>                      m_chunks;
    
    std::vector<Chunk>::const_iterator      m_chunk_iterator;

    /// the HTTP request writer we are using
    pion::http::request_writer_ptr         m_writer;
};

ChunkedPostRequestSender::ChunkedPostRequestSender(const pion::tcp::connection_ptr& tcp_conn,
                                                   const std::string& resource)
    : m_logger(PION_GET_LOGGER("pion.ChunkedPostRequestSender")),
    m_writer(pion::http::request_writer::create(tcp_conn))
{
    m_writer->get_request().set_method("POST");
    m_writer->get_request().set_resource(resource);
    m_writer->get_request().set_chunks_supported(true);
    m_chunk_iterator = m_chunks.begin();
}

void ChunkedPostRequestSender::send(void)
{
    if (m_chunk_iterator == m_chunks.end()) {
        m_writer->send_final_chunk(boost::bind(&ChunkedPostRequestSender::handle_write,
                                             shared_from_this(),
                                             boost::asio::placeholders::error,
                                             boost::asio::placeholders::bytes_transferred));
        return;
    }

    // write the current chunk
    m_writer->write_no_copy(m_chunk_iterator->second, m_chunk_iterator->first);
    
    if (++m_chunk_iterator == m_chunks.end()) {
        m_writer->send_final_chunk(boost::bind(&ChunkedPostRequestSender::handle_write,
                                             shared_from_this(),
                                             boost::asio::placeholders::error,
                                             boost::asio::placeholders::bytes_transferred));
    } else {
        m_writer->send_chunk(boost::bind(&ChunkedPostRequestSender::handle_write,
                                        shared_from_this(),
                                        boost::asio::placeholders::error,
                                        boost::asio::placeholders::bytes_transferred));
    }
}

void ChunkedPostRequestSender::handle_write(const boost::system::error_code& write_error,
                                           std::size_t bytes_written)
{
    if (write_error) {
        // encountered error sending request data
        m_writer->get_connection()->set_lifecycle(pion::tcp::connection::LIFECYCLE_CLOSE); // make sure it will get closed
        PION_LOG_ERROR(m_logger, "Error sending chunked request (" << write_error.message() << ')');
    } else {
        // request data sent OK
        
        if (m_chunk_iterator == m_chunks.end()) {
            PION_LOG_DEBUG(m_logger, "Sent " << bytes_written << " bytes (finished)");
        } else {
            PION_LOG_DEBUG(m_logger, "Sent " << bytes_written << " bytes");
            m_writer->clear();
            send();
        }
    }
}

// sample passwords and corresponding hashes
static const std::string PASSWORD_1 = "Whatever";
static const std::string SHA_1_HASH_OF_PASSWORD_1 = "c916e71d733d06cb77a4775de5f77fd0b480a7e8";
static const std::string SHA_256_HASH_OF_PASSWORD_1 = "e497135e5c9481c39bc35e62927bc53b7cad4ed3193f1831e63ee66973b970b1";
static const std::string PASSWORD_2 = "Open, Sesame!";
static const std::string SHA_1_HASH_OF_PASSWORD_2 = "a46a5895a829d1fedc9bd4ef1801a2c99fd4f044";
static const std::string SHA_256_HASH_OF_PASSWORD_2 = "b620fa9f74d0173f84c8f27116766ef426d9beb0f38534555655a9e80a03a8c5";

///
/// WebServerTests_F: fixture used for running web server tests
/// 
class WebServerTests_F {
public:
    
    // default constructor & destructor
    WebServerTests_F() : m_scheduler(), m_server(m_scheduler) {
        // initialize the list of directories in which to look for plug-ins
        plugin::reset_plugin_directories();
#ifndef PION_STATIC_LINKING
        plugin::add_plugin_directory(PATH_TO_PLUGINS);
#endif
    }
    ~WebServerTests_F() {
        m_server.stop();
        m_scheduler.shutdown();
    }
    
    /**
     * sends a request to the local HTTP server
     *
     * @param http_stream open stream to send the request via
     * @param resource name of the HTTP resource to request
     * @param content_length bytes available in the response, if successful
     */
    inline unsigned int sendRequest(boost::asio::ip::tcp::iostream& http_stream,
                                    const std::string& resource,
                                    unsigned long& content_length)
    {
        const boost::regex regex_get_response_code("^HTTP/1\\.1\\s(\\d+)\\s.*");
        const boost::regex regex_response_header("^[A-Za-z0-9_-]+:\\s.*");
        const boost::regex regex_content_length_header("^Content-Length:\\s(\\d+).*", boost::regex::icase);
        const boost::regex regex_response_end("^\\s*$");

        // send HTTP request to the server
        http_stream << "GET " << resource << " HTTP/1.1" << http::types::STRING_CRLF << http::types::STRING_CRLF;
        http_stream.flush();
                
        // receive response from the server
        std::string rsp_line;
        boost::smatch rx_matches;
        unsigned int response_code = 0;
        BOOST_REQUIRE(std::getline(http_stream, rsp_line));
        BOOST_REQUIRE(boost::regex_match(rsp_line, rx_matches, regex_get_response_code));
        BOOST_REQUIRE(rx_matches.size() == 2);

        // extract response status code
        response_code = boost::lexical_cast<unsigned int>(rx_matches[1]);
        BOOST_REQUIRE(response_code != 0);
        
        // read response headers
        content_length = 0;
        while (true) {
            BOOST_REQUIRE(std::getline(http_stream, rsp_line));
            // check for end of response headers (empty line)
            if (boost::regex_match(rsp_line, rx_matches, regex_response_end))
                break;
            // check validity of response header
            BOOST_REQUIRE(boost::regex_match(rsp_line, rx_matches, regex_response_header));
            // check for content-length response header
            if (boost::regex_match(rsp_line, rx_matches, regex_content_length_header)) {
                if (rx_matches.size() == 2)
                    content_length = boost::lexical_cast<unsigned long>(rx_matches[1]);
            }
        }
        
        return response_code;
    }
    
    /**
     * checks the local HTTP server's response code & validity using HelloService
     */
    inline void checkWebServerResponseCode(void) {
        // load simple Hello service and start the server
        m_server.load_service("/hello", "HelloService");
        m_server.start();
        
        // open a connection
        boost::asio::ip::tcp::endpoint http_endpoint(boost::asio::ip::address::from_string("127.0.0.1"), m_server.get_port());
        boost::asio::ip::tcp::iostream http_stream(http_endpoint);
        
        // send valid request to the server
        unsigned int response_code;
        unsigned long content_length = 0;
        response_code = sendRequest(http_stream, "/hello", content_length);
        BOOST_CHECK(response_code == 200);
        BOOST_CHECK(content_length > 0);
        if (content_length > 0) {
            boost::scoped_array<char> content_buf(new char[content_length+1]);
            BOOST_CHECK(http_stream.read(content_buf.get(), content_length));
        }
        
        // send invalid request to the server
        response_code = sendRequest(http_stream, "/doesnotexist", content_length);
        BOOST_CHECK(response_code == 404);
    }
    
    /**
     * checks response content validity for the local HTTP server
     *
     * @param http_stream open stream to send the request via
     * @param resource name of the HTTP resource to request
     * @param content_regex regex that the response content should match
     */
    inline void checkWebServerResponseContent(boost::asio::ip::tcp::iostream& http_stream,
                                              const std::string& resource,
                                              const boost::regex& content_regex,
                                              unsigned int expectedResponseCode = 200)
    {
        // send valid request to the server
        unsigned int response_code;
        unsigned long content_length = 0;
        response_code = sendRequest(http_stream, resource, content_length);
        BOOST_CHECK(response_code == expectedResponseCode);
        BOOST_REQUIRE(content_length > 0);
        
        // read in the response content
        boost::scoped_array<char> content_buf(new char[content_length+1]);
        BOOST_CHECK(http_stream.read(content_buf.get(), content_length));
        content_buf[content_length] = '\0';
        
        // check the response content
        BOOST_CHECK(boost::regex_match(content_buf.get(), content_regex));
    }

    /**
     * checks response content validity for the local HTTP server
     *
     * @param service name of the web service to load and query
     * @param resource name of the HTTP resource to request
     * @param content_regex regex that the response content should match
     */
    inline void checkWebServerResponseContent(const std::string& service,
                                              const std::string& resource,
                                              const boost::regex& content_regex,
                                              unsigned int expectedResponseCode = 200)
    {
        // load specified service and start the server
        m_server.load_service(resource, service);
        m_server.start();
        
        // open a connection
        boost::asio::ip::tcp::endpoint http_endpoint(boost::asio::ip::address::from_string("127.0.0.1"), m_server.get_port());
        boost::asio::ip::tcp::iostream http_stream(http_endpoint);

        // send request and check response
        checkWebServerResponseContent(http_stream, resource, content_regex, expectedResponseCode);
    }
    
    /**
     * checks if we can successfully send and receive HTTP messages
     * 
     * @param tcp_conn open TCP connection to use for the tests
     */
    inline void checkSendAndReceiveMessages(pion::tcp::connection& tcp_conn) {
        // send valid request to the server
        http::request http_request("/hello");
        boost::system::error_code error_code;
        http_request.send(tcp_conn, error_code);
        BOOST_REQUIRE(! error_code);

        // receive the response from the server
        http::response http_response(http_request);
        http_response.receive(tcp_conn, error_code);
        BOOST_REQUIRE(! error_code);
        
        // check that the response is OK
        boost::regex hello_regex(".*Hello\\sWorld.*");
        BOOST_REQUIRE(http_response.get_status_code() == 200);
        BOOST_REQUIRE(http_response.get_content_length() > 0);
        BOOST_REQUIRE(boost::regex_match(http_response.get_content(), hello_regex));
                
        // send invalid request to the server
        http_request.set_resource("/doesnotexist");
        http_request.send(tcp_conn, error_code);
        BOOST_REQUIRE(! error_code);
        http_response.receive(tcp_conn, error_code);
        BOOST_REQUIRE(! error_code);
        BOOST_CHECK_EQUAL(http_response.get_status_code(), 404U);
    }
    
    inline boost::asio::io_service& get_io_service(void) { return m_scheduler.get_io_service(); }
    
    single_service_scheduler	m_scheduler;
	http::plugin_server			m_server;
};


// plugin_server Test Cases

BOOST_FIXTURE_TEST_SUITE(WebServerTests_S, WebServerTests_F)

BOOST_AUTO_TEST_CASE(checkWebServerIsListening) {
    BOOST_CHECK(! m_server.is_listening());
    m_server.start();
    BOOST_CHECK(m_server.is_listening());
    m_server.stop();
    BOOST_CHECK(! m_server.is_listening());
}

BOOST_AUTO_TEST_CASE(checkWebServerRespondsProperly) {
    checkWebServerResponseCode();
}

BOOST_AUTO_TEST_CASE(checkSendRequestsAndReceiveResponses) {
    // load simple Hello service and start the server
    m_server.load_service("/hello", "HelloService");
    m_server.start();
    
    // open a connection
    pion::tcp::connection tcp_conn(get_io_service());
    tcp_conn.set_lifecycle(pion::tcp::connection::LIFECYCLE_KEEPALIVE);
    boost::system::error_code error_code;
    error_code = tcp_conn.connect(boost::asio::ip::address::from_string("127.0.0.1"), m_server.get_port());
    BOOST_REQUIRE(! error_code);
    
    checkSendAndReceiveMessages(tcp_conn);
}

BOOST_AUTO_TEST_CASE(checkSendRequestsAndReceiveResponseLeftoverConnection) {
    // load simple Hello service and start the server
    m_server.load_service("/hello", "HelloService");
    m_server.start();
    
    // open a connection
    pion::tcp::connection tcp_conn(get_io_service());
    tcp_conn.set_lifecycle(pion::tcp::connection::LIFECYCLE_KEEPALIVE);
    boost::system::error_code error_code;
    error_code = tcp_conn.connect(boost::asio::ip::address::from_string("127.0.0.1"), m_server.get_port());
    BOOST_REQUIRE(! error_code);
    
    // send valid request to the server
    http::request http_request("/hello");
    http_request.send(tcp_conn, error_code);
    BOOST_REQUIRE(! error_code);
    
    // receive the response from the server
    http::response http_response(http_request);
    http_response.receive(tcp_conn, error_code);
    BOOST_REQUIRE(! error_code);
    BOOST_CHECK_EQUAL(http_response.get_header(http::types::HEADER_CONNECTION), "Keep-Alive");
    
    // check that the response is OK
    boost::regex hello_regex(".*Hello\\sWorld.*");
    BOOST_REQUIRE(http_response.get_status_code() == 200);
    BOOST_REQUIRE(http_response.get_content_length() > 0);
    BOOST_REQUIRE(boost::regex_match(http_response.get_content(), hello_regex));
    
    // shut down the server while the connection is still alive and waiting for data
    m_server.stop();
}

BOOST_AUTO_TEST_CASE(checkSendRequestAndReceiveResponseFromEchoService) {
    m_server.load_service("/echo", "EchoService");
    m_server.start();

    // open a connection
    tcp::connection_ptr tcp_conn(new pion::tcp::connection(get_io_service()));
    tcp_conn->set_lifecycle(pion::tcp::connection::LIFECYCLE_KEEPALIVE);
    boost::system::error_code error_code;
    error_code = tcp_conn->connect(boost::asio::ip::address::from_string("127.0.0.1"), m_server.get_port());
    BOOST_REQUIRE(!error_code);

    pion::http::request_writer_ptr writer(pion::http::request_writer::create(tcp_conn));
    writer->get_request().set_method("POST");
    writer->get_request().set_resource("/echo");

    writer << "junk";
    writer->send();

    // receive the response from the server
    http::response http_response(writer->get_request());
    http_response.receive(*tcp_conn, error_code);
    BOOST_CHECK(!error_code);

    // check that the response is OK
    BOOST_CHECK(http_response.get_status_code() == 200);
    BOOST_CHECK(http_response.get_content_length() > 0);

    // check the post content of the request, by parsing it out of the post content of the response
    boost::regex post_content(".*\\[POST Content]\\s*junk.*");
    BOOST_CHECK(boost::regex_match(http_response.get_content(), post_content));
}

BOOST_AUTO_TEST_CASE(checkRedirectHelloServiceToEchoService) {
    m_server.load_service("/hello", "HelloService");
    m_server.load_service("/echo", "EchoService");
    m_server.start();

    // open a connection
    boost::asio::ip::tcp::endpoint http_endpoint(boost::asio::ip::address::from_string("127.0.0.1"), m_server.get_port());
    boost::asio::ip::tcp::iostream http_stream(http_endpoint);

    // send a request to /hello and check that the response is from HelloService
    checkWebServerResponseContent(http_stream, "/hello", boost::regex(".*Hello\\sWorld.*"));

    m_server.add_redirect("/hello", "/echo");

    // send a request to /hello and check that the response is from EchoService
    checkWebServerResponseContent(http_stream, "/hello", boost::regex(".*\\[Request\\sEcho\\].*"));
}

BOOST_AUTO_TEST_CASE(checkOriginalResourceAvailableAfterRedirect) {
    m_server.load_service("/hello", "HelloService");
    m_server.load_service("/echo", "EchoService");
    m_server.start();

    // open a connection
    boost::asio::ip::tcp::endpoint http_endpoint(boost::asio::ip::address::from_string("127.0.0.1"), m_server.get_port());
    boost::asio::ip::tcp::iostream http_stream(http_endpoint);

    m_server.add_redirect("/hello", "/echo");

    // send a request to /hello and check the reported values of the original resource and the delivered resource
    boost::regex regex_expected_content(".*Resource\\soriginally\\srequested:\\s/hello.*Resource\\sdelivered:\\s/echo.*");
    checkWebServerResponseContent(http_stream, "/hello", regex_expected_content);
}

BOOST_AUTO_TEST_CASE(checkRecursiveRedirect) {
    m_server.load_service("/hello", "HelloService");
    m_server.load_service("/echo", "EchoService");
    m_server.load_service("/cookie", "CookieService");
    m_server.start();

    // open a connection
    boost::asio::ip::tcp::endpoint http_endpoint(boost::asio::ip::address::from_string("127.0.0.1"), m_server.get_port());
    boost::asio::ip::tcp::iostream http_stream(http_endpoint);

    m_server.add_redirect("/hello", "/echo");
    m_server.add_redirect("/echo", "/cookie");

    // send a request to /hello and check that the response is from CookieService
    checkWebServerResponseContent(http_stream, "/hello", boost::regex(".*<html>.*Cookie\\sService.*</html>.*"));
}

BOOST_AUTO_TEST_CASE(checkCircularRedirect) {
    m_server.load_service("/hello", "HelloService");
    m_server.load_service("/cookie", "CookieService");
    m_server.load_service("/echo", "EchoService");
    m_server.start();

    // open a connection
    boost::asio::ip::tcp::endpoint http_endpoint(boost::asio::ip::address::from_string("127.0.0.1"), m_server.get_port());
    boost::asio::ip::tcp::iostream http_stream(http_endpoint);

    // set up a circular set of redirects
    m_server.add_redirect("/hello", "/echo");
    m_server.add_redirect("/echo", "/cookie");
    m_server.add_redirect("/cookie", "/hello");

    // send request and check that server returns expected status code and error message
    checkWebServerResponseContent(http_stream, "/hello",
                                  boost::regex(".*Maximum number of redirects.*exceeded.*"),
                                  http::types::RESPONSE_CODE_SERVER_ERROR);
}

BOOST_AUTO_TEST_CASE(checkSendChunkedRequestAndReceiveResponse) {
    m_server.load_service("/echo", "EchoService");
    m_server.start();

    // open a connection
    tcp::connection_ptr tcp_conn(new pion::tcp::connection(get_io_service()));
    tcp_conn->set_lifecycle(pion::tcp::connection::LIFECYCLE_KEEPALIVE);
    boost::system::error_code error_code;
    error_code = tcp_conn->connect(boost::asio::ip::address::from_string("127.0.0.1"), m_server.get_port());
    BOOST_REQUIRE(!error_code);

    boost::shared_ptr<ChunkedPostRequestSender> sender = ChunkedPostRequestSender::create(tcp_conn, "/echo");
    sender->addChunk(5, "klmno");
    sender->addChunk(4, "1234");
    sender->addChunk(10, "abcdefghij");
    sender->send();

    // receive the response from the server
    http::response http_response("GET");
    http_response.receive(*tcp_conn, error_code);
    BOOST_CHECK(!error_code);

    // check that the response is OK
    BOOST_CHECK(http_response.get_status_code() == 200);
    BOOST_CHECK(http_response.get_content_length() > 0);

    // check the content length of the request, by parsing it out of the post content of the response
    boost::regex content_length_of_request(".*Content length\\: 19.*");
    BOOST_CHECK(boost::regex_match(http_response.get_content(), content_length_of_request));

    // check the post content of the request, by parsing it out of the post content of the response
    boost::regex post_content_of_request(".*\\[POST Content]\\s*klmno1234abcdefghij.*");
    BOOST_CHECK(boost::regex_match(http_response.get_content(), post_content_of_request));
}

BOOST_AUTO_TEST_CASE(checkSendChunkedRequestWithOneChunkAndReceiveResponse) {
    m_server.load_service("/echo", "EchoService");
    m_server.start();

    // open a connection
    tcp::connection_ptr tcp_conn(new pion::tcp::connection(get_io_service()));
    tcp_conn->set_lifecycle(pion::tcp::connection::LIFECYCLE_KEEPALIVE);
    boost::system::error_code error_code;
    error_code = tcp_conn->connect(boost::asio::ip::address::from_string("127.0.0.1"), m_server.get_port());
    BOOST_REQUIRE(!error_code);

    boost::shared_ptr<ChunkedPostRequestSender> sender = ChunkedPostRequestSender::create(tcp_conn, "/echo");
    sender->addChunk(10, "abcdefghij");
    sender->send();

    // receive the response from the server
    http::response http_response("GET");
    http_response.receive(*tcp_conn, error_code);
    BOOST_CHECK(!error_code);

    // check that the response is OK
    BOOST_CHECK(http_response.get_status_code() == 200);
    BOOST_CHECK(http_response.get_content_length() > 0);

    // check the post content of the request, by parsing it out of the post content of the response
    boost::regex post_content(".*\\[POST Content]\\s*abcdefghij.*");
    BOOST_CHECK(boost::regex_match(http_response.get_content(), post_content));
}

BOOST_AUTO_TEST_CASE(checkSendChunkedRequestWithNoChunksAndReceiveResponse) {
    m_server.load_service("/echo", "EchoService");
    m_server.start();

    // open a connection
    tcp::connection_ptr tcp_conn(new pion::tcp::connection(get_io_service()));
    tcp_conn->set_lifecycle(pion::tcp::connection::LIFECYCLE_KEEPALIVE);
    boost::system::error_code error_code;
    error_code = tcp_conn->connect(boost::asio::ip::address::from_string("127.0.0.1"), m_server.get_port());
    BOOST_REQUIRE(!error_code);

    boost::shared_ptr<ChunkedPostRequestSender> sender = ChunkedPostRequestSender::create(tcp_conn, "/echo");
    sender->send();

    // receive the response from the server
    http::response http_response("GET");
    http_response.receive(*tcp_conn, error_code);
    BOOST_CHECK(!error_code);

    // check that the response is OK
    BOOST_CHECK(http_response.get_status_code() == 200);
    BOOST_CHECK(http_response.get_content_length() > 0);

    // check the content length of the request, by parsing it out of the post content of the response
    boost::regex content_length_of_request(".*Content length\\: 0.*");
    BOOST_CHECK(boost::regex_match(http_response.get_content(), content_length_of_request));
}

#ifdef PION_HAVE_SSL
BOOST_AUTO_TEST_CASE(checkSendRequestsAndReceiveResponsesUsingSSL) {
    // load simple Hello service and start the server
    m_server.set_ssl_key_file(SSL_PEM_FILE);
    m_server.load_service("/hello", "HelloService");
    m_server.start();

    // open a connection
    pion::tcp::connection tcp_conn(get_io_service(), true);
    tcp_conn.set_lifecycle(pion::tcp::connection::LIFECYCLE_KEEPALIVE);
    boost::system::error_code error_code;
    error_code = tcp_conn.connect(boost::asio::ip::address::from_string("127.0.0.1"), m_server.get_port());
    BOOST_REQUIRE(! error_code);
    error_code = tcp_conn.handshake_client();
    BOOST_REQUIRE(! error_code);

    checkSendAndReceiveMessages(tcp_conn);
}

BOOST_AUTO_TEST_CASE(checkSendRequestsAndReceiveResponseLeftoverConnectionUsingSSL) {
    // load simple Hello service and start the server
    m_server.set_ssl_key_file(SSL_PEM_FILE);
    m_server.load_service("/hello", "HelloService");
    m_server.start();
    
    // open a connection
    pion::tcp::connection tcp_conn(get_io_service(), true);
    tcp_conn.set_lifecycle(pion::tcp::connection::LIFECYCLE_KEEPALIVE);
    boost::system::error_code error_code;
    error_code = tcp_conn.connect(boost::asio::ip::address::from_string("127.0.0.1"), m_server.get_port());
    BOOST_REQUIRE(! error_code);
    error_code = tcp_conn.handshake_client();
    BOOST_REQUIRE(! error_code);
    
    // send valid request to the server
    http::request http_request("/hello");
    http_request.send(tcp_conn, error_code);
    BOOST_REQUIRE(! error_code);
    
    // receive the response from the server
    http::response http_response(http_request);
    http_response.receive(tcp_conn, error_code);
    BOOST_REQUIRE(! error_code);
    BOOST_CHECK_EQUAL(http_response.get_header(http::types::HEADER_CONNECTION), "Keep-Alive");
    
    // check that the response is OK
    boost::regex hello_regex(".*Hello\\sWorld.*");
    BOOST_REQUIRE(http_response.get_status_code() == 200);
    BOOST_REQUIRE(http_response.get_content_length() > 0);
    BOOST_REQUIRE(boost::regex_match(http_response.get_content(), hello_regex));
    
    // shut down the server while the connection is still alive and waiting for data
    m_server.stop();
}
#endif

BOOST_AUTO_TEST_CASE(checkHelloServiceResponseContent) {
    checkWebServerResponseContent("HelloService", "/hello",
                                  boost::regex(".*Hello\\sWorld.*"));
}

BOOST_AUTO_TEST_CASE(checkCookieServiceResponseContent) {
    checkWebServerResponseContent("CookieService", "/cookie",
                                  boost::regex(".*<html>.*Cookie\\sService.*</html>.*"));
}

BOOST_AUTO_TEST_CASE(checkEchoServiceResponseContent) {
    checkWebServerResponseContent("EchoService", "/echo",
                                  boost::regex(".*\\[Request\\sEcho\\].*\\[POST\\sContent\\].*"));
}

BOOST_AUTO_TEST_CASE(checkLogServiceResponseContent) {
#if defined(PION_USE_LOG4CXX) || defined(PION_USE_LOG4CPLUS) || defined(PION_USE_LOG4CPP)
    // make sure that the log level is high enough so that the entry will be recorded
    pion::logger log_ptr = PION_GET_LOGGER("pion");
    PION_LOG_SETLEVEL_INFO(log_ptr);
    // make sure that the log service includes an entry for loading itself
    checkWebServerResponseContent("LogService", "/log",
                                  boost::regex(".*Loaded.*plug-in.*\\(/log\\):\\sLogService.*"));
    // bump the log level back down when we are done with the test
    PION_LOG_SETLEVEL_WARN(log_ptr);
#elif defined(PION_DISABLE_LOGGING)
    checkWebServerResponseContent("LogService", "/log",
                                  boost::regex(".*Logging\\sis\\sdisabled.*"));
#else
    checkWebServerResponseContent("LogService", "/log",
                                  boost::regex(".*Using\\sostream\\slogging.*"));
#endif
}

#if defined(PION_USE_LOG4CPLUS)
BOOST_AUTO_TEST_CASE(checkCircularBufferAppender) {
	// Create a circular buffer appender and add it:
	pion::log_appender_ptr appender(new pion::circular_buffer_appender);
	appender->setName("CircularBufferAppender");
	pion::logger::getRoot().addAppender(appender);

	// Log an error so we can check if it gets appended:
	pion::logger log_ptr = PION_GET_LOGGER("pion");
	PION_LOG_ERROR(log_ptr, "X happened");

	// Get a reference to the log event buffer.
	pion::log_appender_ptr cba_ptr = pion::logger::getRoot().getAppender("CircularBufferAppender");
	const pion::circular_buffer_appender& cba = dynamic_cast<const pion::circular_buffer_appender&>(*cba_ptr.get());
	const pion::circular_buffer_appender::LogEventBuffer& events = cba.getLogIterator();
	pion::circular_buffer_appender::LogEventBuffer::const_iterator it;

	// Check that the log event buffer has exactly one event, with the expected message:
	it = events.begin();
	BOOST_REQUIRE(it != events.end());
	BOOST_CHECK_EQUAL(it->getMessage(), "X happened");
	BOOST_CHECK(++it == events.end());

	// Log a second error:
	PION_LOG_ERROR(log_ptr, "Y happened");

	// Check that the log event buffer has exactly two events, with the expected messages:
	it = events.begin();
	BOOST_REQUIRE(it != events.end());
	BOOST_CHECK_EQUAL(it->getMessage(), "X happened");
	BOOST_REQUIRE((++it) != events.end());
	BOOST_CHECK_EQUAL(it->getMessage(), "Y happened");
	BOOST_CHECK(++it == events.end());

	// Now remove the appender and log a third error:
	pion::logger::getRoot().removeAppender(appender);
	PION_LOG_ERROR(log_ptr, "Z happened");

	// Check that the log event buffer still has only the same two events:
	it = events.begin();
	BOOST_REQUIRE(it != events.end());
	BOOST_CHECK_EQUAL(it->getMessage(), "X happened");
	BOOST_REQUIRE((++it) != events.end());
	BOOST_CHECK_EQUAL(it->getMessage(), "Y happened");
	BOOST_CHECK(++it == events.end());
}
#endif

#ifndef PION_STATIC_LINKING
BOOST_AUTO_TEST_CASE(checkAllowNothingServiceResponseContent) {
    checkWebServerResponseContent("AllowNothingService", "/deny",
                                  boost::regex(".*No, you can't.*"),
                                  http::types::RESPONSE_CODE_METHOD_NOT_ALLOWED);
}
#endif // PION_STATIC_LINKING

BOOST_AUTO_TEST_CASE(checkFileServiceResponseContent) {
    // load multiple services and start the server
    try {
        m_server.load_service_config(SERVICES_CONFIG_FILE);
    } catch (error::directory_not_found&) {}
    m_server.start();
    
    // open a connection
    boost::asio::ip::tcp::endpoint http_endpoint(boost::asio::ip::address::from_string("127.0.0.1"), m_server.get_port());
    boost::asio::ip::tcp::iostream http_stream(http_endpoint);
    
    // send request and check response (index page)
    const boost::regex index_page_regex(".*<html>.*Test\\sWebsite.*</html>.*");
    checkWebServerResponseContent(http_stream, "/" , index_page_regex);
    checkWebServerResponseContent(http_stream, "/index.html" , index_page_regex);

    // send request and check response (copy of docs index page generated by doxygen)
    const boost::regex doc_index_regex(".*<html>.*pion-.*Documentation.*</html>.*");
    checkWebServerResponseContent(http_stream, "/doc/index.html" , doc_index_regex);
}

BOOST_AUTO_TEST_CASE(checkPionUserPasswordSanity) {
    const std::string clear_pw("deadmeat");
    user u("test-user");
    u.set_password(clear_pw);
    BOOST_CHECK(u.match_password(clear_pw));

#ifdef PION_HAVE_SSL
    std::string encrypted_pw = u.get_password();
    BOOST_CHECK_EQUAL(encrypted_pw.size(), static_cast<unsigned int>(SHA256_DIGEST_LENGTH * 2));
    BOOST_CHECK(clear_pw != encrypted_pw);
    
    u.set_password_hash(encrypted_pw);
    BOOST_CHECK_EQUAL(encrypted_pw, u.get_password());   // should still be identical
    BOOST_CHECK(u.match_password(clear_pw));
#endif
}

BOOST_AUTO_TEST_CASE(checkMatchPassword) {
    user u("test-user", PASSWORD_1);
    BOOST_CHECK(u.match_password(PASSWORD_1));
    BOOST_CHECK(! u.match_password(PASSWORD_2));
}

#ifdef PION_HAVE_SSL
BOOST_AUTO_TEST_CASE(checkSetPasswordCreatesSha256PasswordHash) {
    user u("test-user");
    u.set_password(PASSWORD_1);
    BOOST_CHECK_EQUAL(u.get_password(), SHA_256_HASH_OF_PASSWORD_1);
}

BOOST_AUTO_TEST_CASE(checkNewUserGetsSha256PasswordHash) {
    user u("test-user", PASSWORD_1);
    BOOST_CHECK_EQUAL(u.get_password(), SHA_256_HASH_OF_PASSWORD_1);
}

BOOST_AUTO_TEST_CASE(checkAddUserCreatesSha256PasswordHash) {
    user_manager userManager;
    BOOST_CHECK(userManager.add_user("test-user", PASSWORD_1));
    user_ptr u = userManager.get_user("test-user");
    BOOST_CHECK_EQUAL(u->get_password(), SHA_256_HASH_OF_PASSWORD_1);
}

BOOST_AUTO_TEST_CASE(checkUpdateUserCreatesSha256PasswordHash) {
    user_manager userManager;
    BOOST_REQUIRE(userManager.add_user("test-user", PASSWORD_1));

    BOOST_CHECK(userManager.update_user("test-user", PASSWORD_2));
    user_ptr u = userManager.get_user("test-user");
    BOOST_CHECK_EQUAL(u->get_password(), SHA_256_HASH_OF_PASSWORD_2);
}

BOOST_AUTO_TEST_CASE(checkAddUserHashWorksWithSha256PasswordHash) {
    user_manager userManager;
    BOOST_CHECK(userManager.add_user_hash("test-user", SHA_256_HASH_OF_PASSWORD_1));
    user_ptr u = userManager.get_user("test-user");
    BOOST_CHECK(u->match_password(PASSWORD_1));
}

// Check that SHA-1 (legacy) password hashes still work.
BOOST_AUTO_TEST_CASE(checkSha1PasswordHashStillWorks) {
    user u("test-user");
    u.set_password_hash(SHA_1_HASH_OF_PASSWORD_1);
    BOOST_CHECK(u.match_password(PASSWORD_1));
}

BOOST_AUTO_TEST_CASE(checkAddUserHashWorksWithLegacySha1PasswordHash) {
    user_manager userManager;
    BOOST_CHECK(userManager.add_user_hash("test-user", SHA_1_HASH_OF_PASSWORD_2));
    user_ptr u = userManager.get_user("test-user");
    BOOST_CHECK(u->match_password(PASSWORD_2));
}
#endif

BOOST_AUTO_TEST_CASE(checkBasicAuthServiceFailure) {
    m_server.load_service("/auth", "EchoService");
    user_manager_ptr userManager(new user_manager());
    http::auth_ptr my_auth_ptr(new http::basic_auth(userManager));
    m_server.set_authentication(my_auth_ptr);
    my_auth_ptr->add_restrict("/auth");
    my_auth_ptr->add_user("mike", "123456");
    m_server.start();
    
    // open a connection
    tcp::connection_ptr tcp_conn(new pion::tcp::connection(get_io_service()));
    tcp_conn->set_lifecycle(pion::tcp::connection::LIFECYCLE_KEEPALIVE);
    boost::system::error_code error_code;
    error_code = tcp_conn->connect(boost::asio::ip::address::from_string("127.0.0.1"), m_server.get_port());
    BOOST_REQUIRE(!error_code);
    
    pion::http::request_writer_ptr writer(pion::http::request_writer::create(tcp_conn));
    writer->get_request().set_method("POST");
    writer->get_request().set_resource("/auth/something/somewhere");
    
    writer << "junk";
    writer->send();
    
    // receive the response from the server
    http::response http_response(writer->get_request());
    http_response.receive(*tcp_conn, error_code);
    BOOST_CHECK(!error_code);
    
    // check that the response is RESPONSE_CODE_UNAUTHORIZED
    BOOST_CHECK(http_response.get_status_code() == http::types::RESPONSE_CODE_UNAUTHORIZED);
    BOOST_CHECK(http_response.get_content_length() > 0);
    
    // check the post content of the request, by parsing it out of the post content of the response
    boost::regex post_content(".*\\[POST Content]\\s*junk.*");
    BOOST_CHECK(!boost::regex_match(http_response.get_content(), post_content));
}

BOOST_AUTO_TEST_CASE(checkBasicAuthServiceLogin) {
    m_server.load_service("/auth", "EchoService");
    user_manager_ptr userManager(new user_manager());
    http::auth_ptr my_auth_ptr(new http::basic_auth(userManager));
    m_server.set_authentication(my_auth_ptr);
    my_auth_ptr->add_restrict("/auth");
    my_auth_ptr->add_user("mike", "123456");
    m_server.start();
    
    // open a connection
    tcp::connection_ptr tcp_conn(new pion::tcp::connection(get_io_service()));
    tcp_conn->set_lifecycle(pion::tcp::connection::LIFECYCLE_KEEPALIVE);
    boost::system::error_code error_code;
    error_code = tcp_conn->connect(boost::asio::ip::address::from_string("127.0.0.1"), m_server.get_port());
    BOOST_REQUIRE(!error_code);
    
    pion::http::request_writer_ptr writer(pion::http::request_writer::create(tcp_conn));
    writer->get_request().set_method("POST");
    writer->get_request().set_resource("/auth/something/somewhere");
    // add an authentication for "mike:123456"
    writer->get_request().add_header(http::types::HEADER_AUTHORIZATION, "Basic bWlrZToxMjM0NTY=");
    
    writer << "junk";
    writer->send();
    
    // receive the response from the server
    http::response http_response(writer->get_request());
    http_response.receive(*tcp_conn, error_code);
    BOOST_CHECK(!error_code);
    
    // check that the response is OK
    BOOST_CHECK(http_response.get_status_code() == 200);
    BOOST_CHECK(http_response.get_content_length() > 0);
    
    // check the post content of the request, by parsing it out of the post content of the response
    boost::regex post_content(".*\\[POST Content]\\s*junk.*");
    BOOST_CHECK(boost::regex_match(http_response.get_content(), post_content));
}

BOOST_AUTO_TEST_CASE(checkCookieAuthServiceFailure) {
    m_server.load_service("/auth", "EchoService");
    user_manager_ptr userManager(new user_manager());
    http::auth_ptr my_auth_ptr(new http::cookie_auth(userManager));
    m_server.set_authentication(my_auth_ptr);
    my_auth_ptr->add_restrict("/auth");
    my_auth_ptr->add_user("mike", "123456");
    m_server.start();

    // open a connection
    tcp::connection_ptr tcp_conn(new pion::tcp::connection(get_io_service()));
    tcp_conn->set_lifecycle(pion::tcp::connection::LIFECYCLE_KEEPALIVE);
    boost::system::error_code error_code;
    error_code = tcp_conn->connect(boost::asio::ip::address::from_string("127.0.0.1"), m_server.get_port());
    BOOST_REQUIRE(!error_code);

    pion::http::request_writer_ptr writer(pion::http::request_writer::create(tcp_conn));
    writer->get_request().set_method("POST");
    writer->get_request().set_resource("/auth/something/somewhere");

    writer << "junk";
    writer->send();

    // receive the response from the server
    http::response http_response(writer->get_request());
    http_response.receive(*tcp_conn, error_code);
    BOOST_CHECK(!error_code);

    // check that the response is RESPONSE_CODE_UNAUTHORIZED
    BOOST_CHECK(http_response.get_status_code() == http::types::RESPONSE_CODE_UNAUTHORIZED);
    BOOST_CHECK(http_response.get_content_length() > 0);

    // check the post content of the request, by parsing it out of the post content of the response
    boost::regex post_content(".*\\[POST Content]\\s*junk.*");
    BOOST_CHECK(!boost::regex_match(http_response.get_content(), post_content));
}

BOOST_AUTO_TEST_CASE(checkCookieAuthServiceLogin) {
    m_server.load_service("/auth", "EchoService");
    user_manager_ptr userManager(new user_manager());
    http::auth_ptr my_auth_ptr(new http::cookie_auth(userManager));
    m_server.set_authentication(my_auth_ptr);
    my_auth_ptr->add_restrict("/auth");
    my_auth_ptr->add_user("mike", "123456");
    m_server.start();

    // open a login connection
    tcp::connection_ptr tcp_conn(new pion::tcp::connection(get_io_service()));
    tcp_conn->set_lifecycle(pion::tcp::connection::LIFECYCLE_KEEPALIVE);
    boost::system::error_code error_code;
    error_code = tcp_conn->connect(boost::asio::ip::address::from_string("127.0.0.1"), m_server.get_port());
    BOOST_REQUIRE(!error_code);

    pion::http::request_writer_ptr writer(pion::http::request_writer::create(tcp_conn));
    writer->get_request().set_method("GET");
    // login as "mike:123456"
    writer->get_request().set_resource("/login?user=mike&pass=123456");

    //writer << "junk";
    writer->send();

    // receive the response from the server
    http::response http_response(writer->get_request());
    http_response.receive(*tcp_conn, error_code);
    BOOST_CHECK(!error_code);

    // check that the response is OK
    BOOST_CHECK(http_response.get_status_code() == 204);
    BOOST_CHECK(http_response.get_content_length() == 0);
    BOOST_CHECK(http_response.has_header(http::types::HEADER_SET_COOKIE));
    // get Cookies
    std::string cookie = http_response.get_header(http::types::HEADER_SET_COOKIE);

    // now try to connect to protected area using login cookie

    pion::http::request_writer_ptr writer2(pion::http::request_writer::create(tcp_conn));
    writer2->get_request().set_method("POST");
    writer2->get_request().set_resource("/auth/something/somewhere");
    // add an authentications for "mike:123456"
    writer2->get_request().add_header(http::types::HEADER_COOKIE,cookie);

    writer2 << "junk";
    writer2->send();

    // receive the response from the server
    http::response http_response2(writer2->get_request());
    http_response2.receive(*tcp_conn, error_code);
    BOOST_CHECK(!error_code);

    // check that the response is OK
    BOOST_CHECK(http_response2.get_status_code() == 200);
    BOOST_CHECK(http_response2.get_content_length() > 0);

    // check the post content of the request, by parsing it out of the post content of the response
    boost::regex post_content(".*\\[POST Content]\\s*junk.*");
    BOOST_CHECK(boost::regex_match(http_response2.get_content(), post_content));
}

BOOST_AUTO_TEST_SUITE_END()


#define BIG_BUF_SIZE (12 * 1024)

///
/// ContentResponseWithoutLengthTests_F: 
/// this uses a "big content buffer" to make sure that reading the response
/// content works across multiple packets (and asio_read_some() calls)
/// and when no content-length is specified (it should read through the end)
/// 
class ContentResponseWithoutLengthTests_F
    : public WebServerTests_F
{
public:
    // default constructor and destructor
    ContentResponseWithoutLengthTests_F() {
        // fill the buffer with non-random characters
        for (unsigned long n = 0; n < BIG_BUF_SIZE; ++n) {
            m_big_buf[n] = char(n);
        }
    }
    virtual ~ContentResponseWithoutLengthTests_F() {}
    
    /**
     * sends an HTTP response with content, but not content-length provided
     *
     * @param http_request_ptr the HTTP request to respond to
     * @param tcp_conn the TCP connection to send the response over
     */
    void sendResponseWithContentButNoLength(const http::request_ptr& http_request_ptr,
                                            const tcp::connection_ptr& tcp_conn)
    {
        // make sure it will get closed when finished
        tcp_conn->set_lifecycle(pion::tcp::connection::LIFECYCLE_CLOSE);
        
        // prepare the response headers
        http::response http_response(*http_request_ptr);
        http_response.set_do_not_send_content_length();
        
        // send the response headers
        boost::system::error_code error_code;
        http_response.send(*tcp_conn, error_code);
        BOOST_REQUIRE(! error_code);
        
        // send the content buffer
        tcp_conn->write(boost::asio::buffer(m_big_buf, BIG_BUF_SIZE), error_code);
        BOOST_REQUIRE(! error_code);
        
        // finish (and close) the connection
        tcp_conn->finish();
    }
    
    /// reads in a HTTP response asynchronously
    void readAsyncResponse(const tcp::connection_ptr& tcp_conn)
    {
        http::request http_request("GET");
		http::response_reader_ptr my_reader_ptr(http::response_reader::create(tcp_conn, http_request,
                                                                    boost::bind(&ContentResponseWithoutLengthTests_F::checkResponse,
                                                                    this, _1, _2, _3)));
        my_reader_ptr->receive();
    }

    /// checks the validity of the HTTP response
    void checkResponse(const http::response& http_response)
    {
        BOOST_REQUIRE(http_response.get_status_code() == 200);
        BOOST_CHECK(! http_response.has_header(http::types::HEADER_CONTENT_LENGTH));
        BOOST_REQUIRE(http_response.get_content_length() == BIG_BUF_SIZE);
        BOOST_CHECK_EQUAL(memcmp(http_response.get_content(), m_big_buf, BIG_BUF_SIZE), 0);
    }
    
    /// checks the validity of the HTTP response
    void checkResponse(const http::response_ptr http_response_ptr,
        tcp::connection_ptr conn_ptr, const boost::system::error_code& ec)
    {
        checkResponse(*http_response_ptr);
        boost::mutex::scoped_lock async_lock(m_mutex);
        m_async_test_finished.notify_one();
    }

    /// big data buffer used for the tests
    char                m_big_buf[BIG_BUF_SIZE];
    
    /// signaled after the async response check has finished
    boost::condition    m_async_test_finished;

    /// used to protect the asynchronous operations
    boost::mutex        m_mutex;
};


// ContentResponseWithoutLengthTests_F Test Cases

BOOST_FIXTURE_TEST_SUITE(ContentResponseWithoutLengthTests_S, ContentResponseWithoutLengthTests_F)

BOOST_AUTO_TEST_CASE(checkSendContentWithoutLengthAndReceiveSyncResponse) {
    // startup the server 
    m_server.add_resource("/big", boost::bind(&ContentResponseWithoutLengthTests_F::sendResponseWithContentButNoLength,
                                             this, _1, _2));
    m_server.start();
    
    // open a connection
    tcp::connection_ptr tcp_conn(new pion::tcp::connection(get_io_service()));
    boost::system::error_code error_code;
    error_code = tcp_conn->connect(boost::asio::ip::address::from_string("127.0.0.1"), m_server.get_port());
    BOOST_REQUIRE(!error_code);

    // send an HTTP request
    http::request http_request("/big");
    http_request.send(*tcp_conn, error_code);
    BOOST_REQUIRE(! error_code);
    
    // receive the response from the server
    http::response http_response(http_request);
    http_response.receive(*tcp_conn, error_code);
    BOOST_REQUIRE(! error_code);
    
    // check that the response is OK
    checkResponse(http_response);
}

BOOST_AUTO_TEST_CASE(checkSendContentWithoutLengthAndReceiveAsyncResponse) {
    // startup the server 
    m_server.add_resource("/big", boost::bind(&ContentResponseWithoutLengthTests_F::sendResponseWithContentButNoLength,
                                             this, _1, _2));
    m_server.start();
    
    // open a connection
    tcp::connection_ptr tcp_conn(new pion::tcp::connection(get_io_service()));
    boost::system::error_code error_code;
    error_code = tcp_conn->connect(boost::asio::ip::address::from_string("127.0.0.1"), m_server.get_port());
    BOOST_REQUIRE(!error_code);
    
    // send an HTTP request
    boost::mutex::scoped_lock async_lock(m_mutex);
    pion::http::request_writer_ptr writer_ptr(pion::http::request_writer::create(tcp_conn,
                                     boost::bind(&ContentResponseWithoutLengthTests_F::readAsyncResponse,
                                                 this, tcp_conn)));
    writer_ptr->get_request().set_resource("/big");
    writer_ptr->send();
    
    // wait until the test is finished (and async calls have finished)
    m_async_test_finished.wait(async_lock);
}

BOOST_AUTO_TEST_SUITE_END()