示例#1
0
/*----------------------------------------------------------------------
|       TestHttpTimeouts
+---------------------------------------------------------------------*/
static void 
TestHttpTimeouts(const char* arg)
{
    NPT_HttpUrl url(arg);
    NPT_HttpRequest request(url, NPT_HTTP_METHOD_GET);
    NPT_HttpClient client;
    NPT_HttpResponse* response;

    NPT_Debug("### TIMEOUTS START ###\n");
    client.SetTimeouts(10000, 10000, 10000);
    NPT_TimeStamp before, after;
    NPT_System::GetCurrentTimeStamp(before);
    NPT_Result result = client.SendRequest(request, response);
    NPT_Debug("SendRequest returned %d (%s)\n", result, NPT_ResultText(result));
    NPT_System::GetCurrentTimeStamp(after);
    NPT_Debug("time elapsed: %d ms\n", (after-before).ToMillis());

    client.SetTimeouts(5000, 5000, 5000);
    NPT_System::GetCurrentTimeStamp(before);
    result = client.SendRequest(request, response);
    NPT_Debug("SendRequest returned %d (%s)\n", result, NPT_ResultText(result));
    NPT_System::GetCurrentTimeStamp(after);
    NPT_Debug("time elapsed: %d ms\n", (after-before).ToMillis());

    NPT_Debug("--- TIMEOUTS END ---\n");

    delete response;
}
示例#2
0
 void Run() {
     NPT_Console::Output("{02} waiting for connection on port 10000\n");
     NPT_SocketAddress address(NPT_IpAddress::Any, 10000);
     NPT_Result result = m_Socket.Bind(address, true);
     m_Ready.SetValue(1);
     if (NPT_FAILED(result)) {
         NPT_Console::OutputF("bind failed (%d) (%s)\n", result, NPT_ResultText(result));
         return;
     }
     NPT_Socket* client = NULL;
     result = m_Socket.WaitForNewClient(client);
     NPT_Console::Output("{02} client connected\n");
     for (;;) {
         NPT_System::Sleep(1.0);
         if (m_Interrupted) {
             NPT_Console::Output("{02} thread interrupted\n");
             break;
         }
     }
     delete client;
     NPT_Console::Output("{02} tcp server thread done\n");
 }
示例#3
0
/*----------------------------------------------------------------------
|   PLT_HttpListenTask::DoRun
+---------------------------------------------------------------------*/
void 
PLT_HttpListenTask::DoRun() 
{
    while (!IsAborting(0)) {
        NPT_Socket* client = NULL;
        NPT_Result  result = m_Socket->WaitForNewClient(client, 5000, NPT_SOCKET_FLAG_CANCELLABLE);
        if (NPT_FAILED(result)) {
            // cleanup just in case
            if (client) delete client;
            
            // normal error
            if (result == NPT_ERROR_TIMEOUT) continue;
            
            // exit on other errors ?
            NPT_LOG_WARNING_2("PLT_HttpListenTask exiting with %d (%s)", result, NPT_ResultText(result));
            break;
        } else {
            PLT_ThreadTask* task = new PLT_HttpServerTask(m_Handler, client);
            m_TaskManager->StartTask(task);
        }
    }
}
示例#4
0
/*----------------------------------------------------------------------
|   PLT_HttpServerSocketTask::SendResponseBody
+---------------------------------------------------------------------*/
NPT_Result
PLT_HttpServerSocketTask::SendResponseBody(NPT_HttpResponse* response,
                                           NPT_OutputStream& output_stream)
{
    NPT_HttpEntity* entity = response->GetEntity();
    if (!entity) return NPT_SUCCESS;

    NPT_InputStreamReference body_stream;
    entity->GetInputStream(body_stream);
    if (body_stream.IsNull()) return NPT_SUCCESS;

    // check for chunked transfer encoding
    NPT_OutputStream* dest = &output_stream;
    if (entity->GetTransferEncoding() == NPT_HTTP_TRANSFER_ENCODING_CHUNKED) {
        dest = new NPT_HttpChunkedOutputStream(output_stream);
    }

    // send body
    NPT_LOG_FINE_1("sending body stream, %lld bytes", entity->GetContentLength());
    NPT_LargeSize bytes_written = 0;
    NPT_Result result = NPT_StreamToStreamCopy(*body_stream, *dest, 0, entity->GetContentLength(), &bytes_written); /* passing 0 if content length is unknown will read until nothing is left */
    if (NPT_FAILED(result)) {
        NPT_LOG_FINE_3("body stream only partially sent, %lld bytes (%d:%s)",
                       bytes_written,
                       result,
                       NPT_ResultText(result));
    }

    // flush to write out any buffered data left in chunked output if used
    dest->Flush();

    // cleanup (this will send zero size chunk followed by CRLF)
    if (dest != &output_stream) delete dest;

    return result;
}
void
TlsTestServer::Run()
{
    printf("@@@ starting TLS server\n");
    NPT_TcpServerSocket socket;
    NPT_SocketAddress address(NPT_IpAddress::Any, 0);
    NPT_Result result = socket.Bind(address);
    if (NPT_FAILED(result)) {
        fprintf(stderr, "@@@ Bind failed (%d)\n", result);
        return;
    }
    result = socket.GetInfo(m_SocketInfo);
    if (NPT_FAILED(result)) {
        fprintf(stderr, "@@@ GetInfo failed (%d)\n", result);
        return;
    }
    m_Ready.SetValue(1);
    
    printf("@@@ Waiting for connection\n");
    NPT_Socket* client = NULL;
    socket.WaitForNewClient(client);
    printf("@@@ Client connected\n");
    
    NPT_TlsContextReference tls_context;
    if (m_Mode == 0) {
        tls_context = new NPT_TlsContext();
    } else if (m_Mode == 1) {
        /* require client authentication */
        tls_context = new NPT_TlsContext(NPT_TLS_CONTEXT_OPTION_REQUIRE_CLIENT_CERTIFICATE | NPT_TLS_CONTEXT_OPTION_VERIFY_LATER);
    }
    /* self-signed cert */
    result = tls_context->LoadKey(NPT_TLS_KEY_FORMAT_PKCS8, TestClient_p8_1, TestClient_p8_1_len, "neptune");
    CHECK(result == NPT_SUCCESS);
    result = tls_context->SelfSignCertificate("MyServerCommonName", "MyServerOrganization", "MyServerOrganizationalName");
    
    NPT_InputStreamReference  socket_input;
    NPT_OutputStreamReference socket_output;
    client->GetInputStream(socket_input);
    client->GetOutputStream(socket_output);
    NPT_TlsServerSession session(tls_context, socket_input, socket_output);
    delete client;
    
    result = session.Handshake();
    if (m_Mode == 1) {
        /* expect a self-signed client cert */
        result = session.VerifyPeerCertificate();
        printf("@@@ Certificate Verification Result = %d (%s)\n", result, NPT_ResultText(result));
        if (result != NPT_ERROR_TLS_CERTIFICATE_SELF_SIGNED) {
            printf("!ERROR, cert verification expected %d, got %d\n", NPT_ERROR_TLS_CERTIFICATE_SELF_SIGNED, result);
            return;
        }

        NPT_TlsCertificateInfo cert_info;
        result = session.GetPeerCertificateInfo(cert_info);
        CHECK(result == NPT_SUCCESS);
        PrintCertificateInfo(cert_info);
    } else {
        if (NPT_FAILED(result)) {
            fprintf(stderr, "@@@ Handshake failed (%d : %s)\n", result, NPT_ResultText(result));
            return;
        }
    }
    
    NPT_OutputStreamReference tls_output;
    session.GetOutputStream(tls_output);
    tls_output->WriteString("Hello, Client\n");
    
    printf("@@@ TLS server done\n");
    //NPT_System::Sleep(1.0);
}
static int
TestRemoteServer(const char* hostname, unsigned int port, bool verify_cert, NPT_Result expected_cert_verif_result)
{
    printf("[1] Connecting to %s...\n", hostname);
    NPT_Socket* client_socket = new NPT_TcpClientSocket();
    NPT_IpAddress server_ip;
    NPT_Result result = server_ip.ResolveName(hostname);
    if (NPT_FAILED(result)) {
        printf("!ERROR cannot resolve hostname\n");
        return 1;
    }
    NPT_SocketAddress server_addr(server_ip, port);
    result = client_socket->Connect(server_addr);
    printf("[2] Connection result = %d (%s)\n", result, NPT_ResultText(result));
    if (NPT_FAILED(result)) {
        printf("!ERROR\n");
        return 1;
    }
    
    NPT_InputStreamReference input;
    NPT_OutputStreamReference output;
    client_socket->GetInputStream(input);
    client_socket->GetOutputStream(output);
    delete client_socket;
    NPT_TlsContextReference context(new NPT_TlsContext(NPT_TLS_CONTEXT_OPTION_VERIFY_LATER));
    
    /* self-signed cert */
    result = context->LoadKey(NPT_TLS_KEY_FORMAT_PKCS8, TestClient_p8_1, TestClient_p8_1_len, "neptune");
    CHECK(result == NPT_SUCCESS);
    result = context->SelfSignCertificate("MyClientCommonName", "MyClientOrganization", "MyClientOrganizationalName");

    NPT_DataBuffer ta_data;
    NPT_Base64::Decode(EquifaxCA, NPT_StringLength(EquifaxCA), ta_data);
    result = context->AddTrustAnchor(ta_data.GetData(), ta_data.GetDataSize());
    if (NPT_FAILED(result)) {
        printf("!ERROR: context->AddTrustAnchor() \n");
        return 1;
    }
    result = context->AddTrustAnchors(NptTlsDefaultTrustAnchors);
    if (NPT_FAILED(result)) {
        printf("!ERROR: context->AddTrustAnchors() \n");
        return 1;
    }
    NPT_TlsClientSession session(context, input, output);
    printf("[3] Performing Handshake\n");
    result = session.Handshake();
    printf("[4] Handshake Result = %d (%s)\n", result, NPT_ResultText(result));
    if (NPT_FAILED(result)) {
        printf("!ERROR\n");
        return 1;
    }

    PrintSessionInfo(session);
    if (verify_cert) {
        result = session.VerifyPeerCertificate();
        printf("[9] Certificate Verification Result = %d (%s)\n", result, NPT_ResultText(result));
        if (result != expected_cert_verif_result) {
            printf("!ERROR, cert verification expected %d, got %d\n", expected_cert_verif_result, result);
            return 1;
        }
    }
    
    NPT_InputStreamReference  ssl_input;
    NPT_OutputStreamReference ssl_output;
    session.GetInputStream(ssl_input);
    session.GetOutputStream(ssl_output);
    
    printf("[10] Getting / Document\n");
    ssl_output->WriteString("GET / HTTP/1.0\n\n");
    for (;;) {
        unsigned char buffer[1];
        NPT_Size bytes_read = 0;
        result = ssl_input->Read(&buffer[0], 1, &bytes_read);
        if (NPT_SUCCEEDED(result)) {
            CHECK(bytes_read == 1);
            printf("%c", buffer[0]);
        } else {
            if (result != NPT_ERROR_EOS && result != NPT_ERROR_CONNECTION_ABORTED) {
                printf("!ERROR: Read() returned %d (%s)\n", result, NPT_ResultText(result)); 
            }
            break;
        }
    }
    printf("[9] SUCCESS\n");
    
    return 0;
}
/*----------------------------------------------------------------------
|       main
+---------------------------------------------------------------------*/
int
main(int argc, char** argv)
{
    // check command line
    if (argc < 2) {
        PrintUsageAndExit();
    }

    // init endpoints
    EndPoint in_endpoint;
    in_endpoint.direction = ENDPOINT_DIRECTION_IN;
    EndPoint out_endpoint;
    out_endpoint.direction = ENDPOINT_DIRECTION_OUT;
    EndPoint* current_endpoint = &in_endpoint;

    // init other parameters
    unsigned int packet_size = PUMP_DEFAULT_PACKET_SIZE;

    // init options
    Options.verbose       = false;
    Options.show_progress = false;

    // parse command line
    argv++;
    char* arg;
    while ((arg = *argv++)) {
        if (current_endpoint == NULL) {
            printf("ERROR: unexpected argument (%s)\n", arg);
            exit(1);    
        }
                 
        if (NPT_StringsEqual(arg, "--packet-size")) {
            packet_size = strtoul(*argv++, NULL, 10);
            continue;
        } else if (NPT_StringsEqual(arg, "--verbose")) {
            Options.verbose = true;
            continue;
        } else if (NPT_StringsEqual(arg, "--show-progress")) {
            Options.show_progress = true;
            continue;
        } else if (NPT_StringsEqual(arg, "udp")) {
            if (argv[0] && argv[1]) {
                if (NPT_StringsEqual(argv[0], "server")) {
                    if (current_endpoint->direction == ENDPOINT_DIRECTION_OUT){
                        printf("ERROR: cannot use 'udp server' as output\n");
                        exit(1);
                    }
                    current_endpoint->type = ENDPOINT_TYPE_UDP_SERVER;
                    current_endpoint->info.udp_server.port = strtoul(argv[1], NULL, 10);
                    argv += 2;
                    if (argv[0] && NPT_StringsEqual(argv[0], "-r")) {
                        current_endpoint->info.udp_server.reuse_addr = false;
                        ++argv;
                    } else {
                        current_endpoint->info.udp_server.reuse_addr = true;
                    }
                } else if (NPT_StringsEqual(argv[0], "client")) {
                    if (current_endpoint->direction == ENDPOINT_DIRECTION_IN) {
                        printf("ERROR: cannot use 'udp client' as input\n");
                        exit(1);
                    }
                    if (argv[2]) {
                        current_endpoint->type = ENDPOINT_TYPE_UDP_CLIENT;
                        current_endpoint->info.udp_client.hostname = argv[1];
                        current_endpoint->info.udp_client.port = strtoul(argv[2], NULL, 10);
                        argv += 3;                        
                    } else {
                        printf("ERROR: missing argument for 'udp client'\n");
                        exit(1);
                    }
                }
            } else {
                printf("ERROR: missing argument for 'udp' endpoint\n");
                exit(1);
            }
         } else if (NPT_StringsEqual(arg, "multicast")) {
            if (argv[0] && argv[1]) {
                if (NPT_StringsEqual(argv[0], "server")) {
                    if (current_endpoint->direction == ENDPOINT_DIRECTION_OUT){
                        printf("ERROR: cannot use 'multicast server' as output\n");
                        exit(1);
                    }
                    if (argv[2]) {
                        current_endpoint->type = ENDPOINT_TYPE_MULTICAST_SERVER;
                        current_endpoint->info.multicast_server.groupname = argv[1];
                        current_endpoint->info.multicast_server.port = strtoul(argv[2], NULL, 10);
                        argv += 3;                        
                    } else {
                        printf("ERROR: missing argument for 'multicast server'\n");
                        exit(1);
                    }
                    if (argv[0] && NPT_StringsEqual(argv[0], "-r")) {
                        current_endpoint->info.multicast_server.reuse_addr = false;
                        ++argv;
                    } else {
                        current_endpoint->info.multicast_server.reuse_addr = true;
                    }
                } else if (NPT_StringsEqual(argv[0], "client")) {
                    if (current_endpoint->direction == ENDPOINT_DIRECTION_IN) {
                        printf("ERROR: cannot use 'udp client' as input\n");
                        exit(1);
                    }
                    if (argv[2] && argv[3]) {
                        current_endpoint->type = ENDPOINT_TYPE_MULTICAST_CLIENT;
                        current_endpoint->info.multicast_client.groupname = argv[1];
                        current_endpoint->info.multicast_client.port = strtoul(argv[2], NULL, 10);
                        current_endpoint->info.multicast_client.ttl = strtoul(argv[3], NULL, 10);
                        argv += 4;                        
                    } else {
                        printf("ERROR: missing argument for 'multicast client'\n");
                        exit(1);
                    }
                }
            } else {
                printf("ERROR: missing argument for 'multicast' endpoint\n");
                exit(1);
            }
        } else if (NPT_StringsEqual(arg, "tcp")) {
            if (argv[0] && argv[1]) {
                if (NPT_StringsEqual(argv[0], "server")) {
                    current_endpoint->type = ENDPOINT_TYPE_TCP_SERVER;
                    current_endpoint->info.tcp_server.port = strtoul(argv[1], NULL, 10);
                    argv += 2;
                    if (argv[0] && NPT_StringsEqual(argv[0], "-r")) {
                        current_endpoint->info.tcp_server.reuse_addr = false;
                        ++argv;
                    } else {
                        current_endpoint->info.tcp_server.reuse_addr = true;
                    }
                } else if (NPT_StringsEqual(argv[0], "client")) {
                    if (argv[2]) {
                        current_endpoint->type = ENDPOINT_TYPE_TCP_CLIENT;
                        current_endpoint->info.tcp_client.hostname = argv[1];
                        current_endpoint->info.tcp_client.port = strtoul(argv[2], NULL, 10);
                        argv += 3;                        
                    } else {
                        printf("ERROR: missing argument for 'tcp client'\n");
                        exit(1);
                    }
                }
            } else {
                printf("ERROR: missing argument for 'tcp' endpoint\n");
                exit(1);
            }
        } else if (NPT_StringsEqual(arg, "file")) {
            if (argv[0]) {
                current_endpoint->type = ENDPOINT_TYPE_FILE;
                current_endpoint->info.file.name = *argv++;
            } else {
                printf("ERROR: missing argument for 'file' endpoint\n");
                exit(1);
            }
        } else if (NPT_StringsEqual(arg, "serial")) {
            if (argv[0]) {
                current_endpoint->type = ENDPOINT_TYPE_SERIAL_PORT;
                current_endpoint->info.serial_port.name = *argv++;
            } else {
                printf("ERROR: missing argument for 'serial' endpoint\n");
                exit(1);
            }
            if (argv[0]) {
                int speed = 0;
                if (NPT_FAILED(NPT_ParseInteger(*argv++, speed))) {
                    printf("ERROR: invalid speed for 'serial' endpoint\n");
                    exit(1);
                } 
                current_endpoint->info.serial_port.speed = (unsigned int)speed;
            } else {
                printf("ERROR: missing argument for 'serial' endpoint\n");
                exit(1);
            }
        } else {
            printf("ERROR: invalid argument (%s)\n", arg);
            exit(1);
        }

        if (current_endpoint == &in_endpoint) {
            current_endpoint = &out_endpoint;
        } else {
            current_endpoint = NULL;
        }
    }

    if (current_endpoint) {
        printf("ERROR: missing endpoint specification\n");
        exit(1);
    }

    // data pump
    NPT_Result result;

    // allocate buffer
    unsigned char* buffer;
    buffer = (unsigned char*)malloc(packet_size);
    if (buffer == NULL) {
        printf("ERROR: out of memory\n");
        exit(1);
    }

    // get output stream
    NPT_OutputStreamReference out;
    result = GetEndPointStreams(&out_endpoint, NULL, &out);
    if (NPT_FAILED(result)) {
        printf("ERROR: failed to get stream for output (%d)\n", result);
        exit(1);
    }

    unsigned long offset = 0;
    unsigned long total  = 0;
    if (in_endpoint.type == ENDPOINT_TYPE_UDP_SERVER ||
        in_endpoint.type == ENDPOINT_TYPE_MULTICAST_SERVER) {
        NPT_UdpSocket* udp_socket;
        result = GetEndPointUdpSocket(&in_endpoint, udp_socket);
        if (NPT_FAILED(result)) {
            printf("ERROR: failed to create UDP socket (%d : %s)\n", result, NPT_ResultText(result));
            exit(1);
        }

        // packet loop
        NPT_DataBuffer packet(32768);
        NPT_SocketAddress address;

        do {
            result = udp_socket->Receive(packet, &address);
            if (NPT_SUCCEEDED(result)) {
                if (Options.verbose) {
                    NPT_String ip = address.GetIpAddress().ToString();
                    printf("Received %d bytes from %s\n", (int)packet.GetDataSize(), ip.GetChars());
                }
                result = out->Write(packet.GetData(), packet.GetDataSize(), NULL);
                offset += packet.GetDataSize();
                total  += packet.GetDataSize();
            }
        } while (NPT_SUCCEEDED(result));
    } else {
        // get the input stream
        NPT_InputStreamReference in;
        result = GetEndPointStreams(&in_endpoint, &in, NULL);
        if (NPT_FAILED(result)) {
            printf("ERROR: failed to get stream for input (%d : %s)\n", result, NPT_ResultText(result));
            exit(1);
        }

        // stream loop 
        do {
            NPT_Size bytes_read;
            NPT_Size bytes_written;

            // send 
            result = in->Read(buffer, packet_size, &bytes_read);
            if (Options.show_progress) {
                printf("[%d]\r", (int)total);
            }
            if (NPT_SUCCEEDED(result) && bytes_read) {
                result = out->Write(buffer, bytes_read, &bytes_written);
                if (Options.show_progress) {
                    printf("[%d]\r", (int)total);
                }
                offset += bytes_written;
                total  += bytes_written;
            } else {
                break;
            }
        } while (NPT_SUCCEEDED(result));
    }

    if (NPT_FAILED(result)) {
        printf("[%d] *******************\n", result);
        exit(1);
    }
    
    delete buffer;
    return 0;
}
示例#8
0
文件: TlsTest1.cpp 项目: AWilco/xbmc
int 
main(int /*argc*/, char** /*argv*/)
{
    TestPrivateKeys();
    
    /* test a connection */
    const char* hostname = "koala.bok.net";
    printf("[1] Connecting to %s...\n", hostname);
    NPT_Socket* client_socket = new NPT_TcpClientSocket();
    NPT_IpAddress server_ip;
    server_ip.ResolveName(hostname);
    NPT_SocketAddress server_addr(server_ip, 443);
    NPT_Result result = client_socket->Connect(server_addr);
    printf("[2] Connection result = %d (%s)\n", result, NPT_ResultText(result));
    if (NPT_FAILED(result)) {
        printf("!ERROR\n");
        return 1;
    }
    
    NPT_InputStreamReference input;
    NPT_OutputStreamReference output;
    client_socket->GetInputStream(input);
    client_socket->GetOutputStream(output);
    NPT_TlsContextReference context(new NPT_TlsContext());
    NPT_TlsClientSession session(context, input, output);
    printf("[3] Performing Handshake\n");
    result = session.Handshake();
    printf("[4] Handshake Result = %d (%s)\n", result, NPT_ResultText(result));
    if (NPT_FAILED(result)) {
        printf("!ERROR\n");
        return 1;
    }
    NPT_DataBuffer session_id;
    result = session.GetSessionId(session_id);
    CHECK(result == NPT_SUCCESS);
    CHECK(session_id.GetDataSize() > 0);
    printf("[5] Session ID: ");
    printf(NPT_HexString(session_id.GetData(), session_id.GetDataSize()).GetChars());
    printf("\n");
    
    NPT_TlsCertificateInfo cert_info;
    result = session.GetPeerCertificateInfo(cert_info);
    CHECK(result == NPT_SUCCESS);
    printf("[6] Fingerprints:\n");
    printf("MD5: %s\n", NPT_HexString(cert_info.fingerprint.md5, sizeof(cert_info.fingerprint.md5), ":").GetChars());
    printf("SHA1: %s\n", NPT_HexString(cert_info.fingerprint.sha1, sizeof(cert_info.fingerprint.sha1), ":").GetChars());
    printf("Subject Certificate:\n");
    printf("  Common Name         = %s\n", cert_info.subject.common_name.GetChars());
    printf("  Organization        = %s\n", cert_info.subject.organization.GetChars());
    printf("  Organizational Name = %s\n", cert_info.subject.organizational_name.GetChars());
    printf("Issuer Certificate:\n");
    printf("  Common Name         = %s\n", cert_info.issuer.common_name.GetChars());
    printf("  Organization        = %s\n", cert_info.issuer.organization.GetChars());
    printf("  Organizational Name = %s\n", cert_info.issuer.organizational_name.GetChars());
    printf("\n");
    printf("[7] Cipher Type = %d (%s)\n", session.GetCipherSuiteId(), GetCipherSuiteName(session.GetCipherSuiteId()));
    
    NPT_InputStreamReference  ssl_input;
    NPT_OutputStreamReference ssl_output;
    session.GetInputStream(ssl_input);
    session.GetOutputStream(ssl_output);
    
    printf("[8] Getting / Document\n");
    ssl_output->WriteString("GET / HTTP/1.0\n\n");
    for (;;) {
        unsigned char buffer[1];
        NPT_Size bytes_read = 0;
        result = ssl_input->Read(&buffer[0], 1, &bytes_read);
        if (NPT_SUCCEEDED(result)) {
            CHECK(bytes_read == 1);
            printf("%c", buffer[0]);
        } else {
            if (result != NPT_ERROR_EOS) {
                printf("!ERROR: Read() returned %d (%s)\n", result, NPT_ResultText(result)); 
            }
            break;
        }
    }
    printf("[9] SUCCESS\n");
}
/*----------------------------------------------------------------------
|       TestHttp
+---------------------------------------------------------------------*/
static NPT_Result 
TestHttp()
{
    NPT_HttpServer            server(1234);
    NPT_InputStreamReference  input;
    NPT_OutputStreamReference output;
    NPT_HttpRequestContext    context;

    NPT_HttpStaticRequestHandler* static_handler = new NPT_HttpStaticRequestHandler(
        "<html><body>"
        "<h1>Neptune HTTP Server Test 1</h1>"
        "<a href='/files-autodir'>List files working directory (autodir)</a><br>"
        "<a href='/files'>List files working directory (no autodir)</a><br>"
        "<a href='/test1'>Test 1</a><br>"
        "<a href='/test2'>Test 2</a><br>"
        "<a href='/chunked1'>Chunked 1</a><br>"
        "<a href='/chunked2'>Chunked 2</a><br>"
        "<a href='/kill'>Kill Test Server</a><br>"
        "</body></html>", 
        "text/html");
    server.AddRequestHandler(static_handler, "/", false);

    KillHandler* kill_handler = new KillHandler();
    server.AddRequestHandler(kill_handler, "/kill", false);

    TestHandler1* test_handler1 = new TestHandler1();
    server.AddRequestHandler(test_handler1, "/test1", false);

    TestHandler2* test_handler2 = new TestHandler2();
    server.AddRequestHandler(test_handler2, "/test2", false);

    ChunkedHandler* chunked_handler1 = new ChunkedHandler();
    server.AddRequestHandler(chunked_handler1, "/chunked1", false);

    TestHandler1* chunked_handler2 = new TestHandler1(true);
    server.AddRequestHandler(chunked_handler2, "/chunked2", false);

    NPT_String cwd;
    NPT_File::GetWorkingDir(cwd);
    NPT_HttpFileRequestHandler* file_handler_autodir = new NPT_HttpFileRequestHandler("/files-autodir", cwd.GetChars(), true);
    server.AddRequestHandler(file_handler_autodir, "/files-autodir", true);
    NPT_HttpFileRequestHandler* file_handler_noautodir = new NPT_HttpFileRequestHandler("/files", cwd.GetChars(), false);
    server.AddRequestHandler(file_handler_noautodir, "/files", true);

    do {
        NPT_Console::Output("Test HTTP server waiting for connection on port 1234...\n");
        NPT_Result result = server.WaitForNewClient(input, 
                                                    output,
                                                    &context);
        NPT_Console::OutputF("WaitForNewClient returned %d (%s)\n", result, NPT_ResultText(result));
        if (NPT_FAILED(result)) return result;

        result = server.RespondToClient(input, output, context);
        NPT_Console::OutputF("RespondToClient returned %d (%s)\n", result, NPT_ResultText(result));
        
        input = NULL;
        output = NULL;
    } while (!KillRequest);

    NPT_Console::OutputF("Killing Server\n");
    
    delete static_handler;
    delete test_handler1;
    delete test_handler2;
    delete file_handler_autodir;
    delete file_handler_noautodir;
    
    return NPT_SUCCESS;
}
示例#10
0
/*----------------------------------------------------------------------
|       main
+---------------------------------------------------------------------*/
int
main(int /*argc*/, char** /*argv*/)
{
    // setup debugging
#if defined(WIN32) && defined(_DEBUG)
    int flags = _crtDbgFlag       | 
        _CRTDBG_ALLOC_MEM_DF      |
        _CRTDBG_DELAY_FREE_MEM_DF |
        _CRTDBG_CHECK_ALWAYS_DF;

    _CrtSetDbgFlag(flags);
    //AllocConsole();
    //freopen("CONOUT$", "w", stdout);
#endif 
    
    NPT_Result result;
    TcpServerThread*     server_thread = NULL;
    NPT_TcpClientSocket* tcp_client = NULL;
    NPT_TcpServerSocket* tcp_server = NULL;
    CancellerThread*     canceller  = NULL;
    
	NPT_SocketAddress address(NPT_IpAddress(127,0,0,1), 10000);
#if 0
    result = RemoteIpAddress.ResolveName("www.google.com");
    CHECK(result == NPT_SUCCESS);

    NPT_Console::Output("--- test for immediate connection\n");
    NPT_Console::Output("[01] starting write server thread\n");
    server_thread = new TcpServerThread();
    server_thread->Start();
    NPT_Console::Output("[01] waiting for server to be ready...\n");
    server_thread->m_Ready.WaitUntilEquals(1);
    NPT_Console::Output("[01] server thread ready\n");
    NPT_Console::Output("[01] waiting a while...\n");
    NPT_System::Sleep(3.0);
    tcp_client = new NPT_TcpClientSocket();
    NPT_Console::Output("[01] connection to 127.0.0.1:10000\n");
    result = tcp_client->Connect(address);
    NPT_Console::OutputF("[01] connect returns %d : %s\n", result, NPT_ResultText(result));
    CHECK(result == NPT_SUCCESS);
    delete tcp_client;
    NPT_Console::Output("[01] terminating server\n");
    server_thread->m_Interrupted = true;
    server_thread->Wait();
    delete server_thread;
    
    NPT_Console::Output("\n--- test for refused local connection\n");
    address.SetPort(89);
    tcp_client = new NPT_TcpClientSocket();
    NPT_Console::Output("[01] connecting to 127.0.0.1:89\n");
    result = tcp_client->Connect(address);
    NPT_Console::OutputF("[01] connect returns %d : %s\n", result, NPT_ResultText(result));
    CHECK(result == NPT_ERROR_CONNECTION_REFUSED);
    delete tcp_client;

    /*NPT_Console::Output("\n--- test for refused remote connection\n");
    address.SetIpAddress(RemoteIpAddress);
    address.SetPort(81);
    tcp_client = new NPT_TcpClientSocket();
    NPT_Console::Output("[01] connecting to www.google.com:81\n");
    result = tcp_client->Connect(address);
    NPT_Console::OutputF("[01] connect returns %d : %s\n", result, NPT_ResultText(result));
    CHECK(result == NPT_ERROR_CONNECTION_REFUSED);
    delete tcp_client;*/

    NPT_Console::Output("\n--- test for connection timeout\n");
    address.SetIpAddress(NPT_IpAddress(1,1,1,1));
    NPT_Console::Output("[01] connecting to 1.1.1.1:89\n");
    tcp_client = new NPT_TcpClientSocket();
    result = tcp_client->Connect(address, 3000);
    NPT_Console::OutputF("[01] connect returns %d : %s\n", result, NPT_ResultText(result));
    CHECK(result == NPT_ERROR_TIMEOUT);
    delete tcp_client;
    
    NPT_Console::Output("\n--- test for remote connection\n");
    address.SetIpAddress(RemoteIpAddress);
    address.SetPort(80);
    NPT_Console::Output("[01] connecting to www.google.com:80\n");
    tcp_client = new NPT_TcpClientSocket();
    result = tcp_client->Connect(address);
    NPT_Console::OutputF("[01] connect returns %d : %s\n", result, NPT_ResultText(result));
    CHECK(result == NPT_SUCCESS);
    delete tcp_client;
#endif

    for (int i=0; i<2; i++) {
        NPT_Console::OutputF("\n--- test for cancelled connection, shutdown=%d\n", i);
        address.SetIpAddress(NPT_IpAddress(1,1,1,1));
        address.SetPort(89);
        NPT_Console::Output("[01] connecting to 1.1.1.1:89\n");
        tcp_client = new NPT_TcpClientSocket(NPT_SOCKET_FLAG_CANCELLABLE);
        canceller = new CancellerThread(tcp_client, 3.0f, i==1);
        result = tcp_client->Connect(address);
        NPT_Console::OutputF("[01] connect returns %d : %s\n", result, NPT_ResultText(result));
        CHECK(result == NPT_ERROR_CANCELLED);
        canceller->Wait();
        delete canceller;
        delete tcp_client;
    }
    
    for (int i=0; i<2; i++) {
        NPT_Console::OutputF("\n--- testing read cancellation, shutdown=%d\n", i);
        address.SetIpAddress(RemoteIpAddress);
        address.SetPort(80);
        NPT_Console::Output("[01] connecting to www.google.com:80\n");
        tcp_client = new NPT_TcpClientSocket(NPT_SOCKET_FLAG_CANCELLABLE);
        result = tcp_client->Connect(address);
        NPT_Console::OutputF("[01] connect returns %d : %s\n", result, NPT_ResultText(result));
        CHECK(result == NPT_SUCCESS);    
        canceller = new CancellerThread(tcp_client, 3.0f, i==1);
        NPT_InputStreamReference input;
        tcp_client->GetInputStream(input);
        unsigned char buffer[4096];
        NPT_SetMemory(buffer, 0, sizeof(buffer));
        result = input->Read(buffer, 4096);
        NPT_Console::OutputF("{00} read returned %d (%s)\n", result, NPT_ResultText(result));
        CHECK(result == NPT_ERROR_CANCELLED);
        delete tcp_client;
        canceller->Wait();
        delete canceller;
    }
    
    for (int i=0; i<2; i++) {
        NPT_Console::OutputF("\n--- testing write cancellation, shutdown=%d\n", i);
        server_thread = new TcpServerThread();
        server_thread->Start();
        NPT_Console::Output("[01] waiting for server to be ready...\n");
        server_thread->m_Ready.WaitUntilEquals(1);
        NPT_Console::Output("[01] server thread ready\n");
        NPT_Console::Output("[01] waiting a while...\n");
        NPT_System::Sleep(3.0);
        address.SetIpAddress(NPT_IpAddress(127,0,0,1));
        address.SetPort(10000);
        NPT_Console::Output("[01] connecting to localhost:10000\n");
        tcp_client = new NPT_TcpClientSocket(NPT_SOCKET_FLAG_CANCELLABLE);
        result = tcp_client->Connect(address);
        NPT_Console::OutputF("[01] connect returns %d : %s\n", result, NPT_ResultText(result));
        CHECK(result == NPT_SUCCESS);    
        canceller = new CancellerThread(tcp_client, 3.0f, i==1);
        NPT_OutputStreamReference output;
        tcp_client->GetOutputStream(output);
        NPT_Size total_written = 0;
        unsigned char buffer[4096];
        NPT_SetMemory(buffer, 0, sizeof(buffer));
        do {
            NPT_Size bytes_written = 0;
            result = output->Write(buffer, 4096, &bytes_written);
            if (NPT_SUCCEEDED(result)) {
                total_written += bytes_written;
            }
        } while (NPT_SUCCEEDED(result));
        output = NULL;
        NPT_Console::OutputF("{01} write returned %d (%s)\n", result, NPT_ResultText(result));
        NPT_Console::OutputF("{01} wrote %d bytes total\n", total_written);
        CHECK(result == NPT_ERROR_CANCELLED);
        delete tcp_client;
        canceller->Wait();
        delete canceller;
        server_thread->m_Interrupted = true;
        server_thread->Wait();
        delete server_thread;
    }

    for (int i=0; i<2; i++) {
        NPT_Console::OutputF("\n--- testing accept cancellation, shutdown=%d\n", i);
        NPT_Console::Output("{03} waiting for connection on port 10000\n");
        address.SetIpAddress(NPT_IpAddress(127,0,0,1));
        address.SetPort(10000);
        tcp_server = new NPT_TcpServerSocket(NPT_SOCKET_FLAG_CANCELLABLE);
        result = tcp_server->Bind(address, true);
        CHECK(result == NPT_SUCCESS);
        canceller = new CancellerThread(tcp_server, 3.0f, i==1);
        NPT_Socket* new_client = NULL;
        result = tcp_server->WaitForNewClient(new_client);
        NPT_Console::OutputF("{03} WaitForNewClient returned %d (%s)\n", result, NPT_ResultText(result));
        CHECK(result == NPT_ERROR_CANCELLED);
        canceller->Wait();
        delete canceller;
        delete tcp_server;
    }

    NPT_Console::Output("------------\n");
    NPT_Console::Output("bye bye\n");

#if defined(WIN32) && defined(_DEBUG)
    _CrtDumpMemoryLeaks();
#endif

    return 0;
}