コード例 #1
0
void CThreadedServerApp::Init(void)
{
    CORE_SetLOG(LOG_cxx2c());
    CORE_SetLOCK(MT_LOCK_cxx2c());

    auto_ptr<CArgDescriptions> arg_desc(new CArgDescriptions);
    arg_desc->SetUsageContext(GetArguments().GetProgramBasename(),
                             "sample server using thread pools");

    arg_desc->AddKey("port", "N", "TCP port number on which to listen",
                     CArgDescriptions::eInteger);
    arg_desc->SetConstraint("port", new CArgAllow_Integers(0, 0xFFFF));

    arg_desc->AddDefaultKey("threads", "N", "Number of initial threads",
                            CArgDescriptions::eInteger, "5");
    
    arg_desc->AddDefaultKey("maxThreads", "N",
                            "Maximum number of simultaneous threads",
                            CArgDescriptions::eInteger, "10");
    
    arg_desc->AddDefaultKey("queue", "N", "Maximum size of request queue",
                            CArgDescriptions::eInteger, "20");

    {{
        CArgAllow* constraint = new CArgAllow_Integers(1, 999);
        arg_desc->SetConstraint("threads",    constraint);
        arg_desc->SetConstraint("maxThreads", constraint);
        arg_desc->SetConstraint("queue",      constraint);        
    }}

    SetupArgDescriptions(arg_desc.release());
}
コード例 #2
0
int main(void)
{
    static STimeout timeout/* = 0 */;
    CONNECTOR       connector;
    FILE*           data_file;

    /* Log and data-log streams */
    CORE_SetLOGFormatFlags(fLOG_None          | fLOG_Level   |
                           fLOG_OmitNoteLevel | fLOG_DateTime);
    CORE_SetLOGFILE(stderr, 0/*false*/);
    data_file = fopen("test_ncbi_memory_connector.log", "wb");
    assert(data_file);

     /* Run the tests */
    connector = MEMORY_CreateConnector();
    CONN_TestConnector(connector, &timeout, data_file, fTC_SingleBounceCheck);

    connector = MEMORY_CreateConnectorEx(0, 0);
    CONN_TestConnector(connector, &timeout, data_file, fTC_Everything);

    /* Cleanup and Exit */
    fclose(data_file);
    CORE_LOG(eLOG_Note, "TEST completed successfully");
    CORE_SetLOG(0);
    return 0;
}
コード例 #3
0
void CServerTestApp::Init(void)
{
    CORE_SetLOCK(MT_LOCK_cxx2c());
    CORE_SetLOG(LOG_cxx2c());

    auto_ptr<CArgDescriptions> arg_desc(new CArgDescriptions);

    arg_desc->SetUsageContext(GetArguments().GetProgramBasename(),
                              "CServer test application");

    arg_desc->AddDefaultKey("srvthreads", "N",
                            "Initial number of server threads",
                            CArgDescriptions::eInteger, "5");

    arg_desc->AddDefaultKey("maxsrvthreads", "N",
                            "Maximum number of server threads",
                            CArgDescriptions::eInteger, "10");

    arg_desc->AddDefaultKey("clthreads", "N",
                            "Initial number of client threads",
                            CArgDescriptions::eInteger, "5");

    arg_desc->AddDefaultKey("maxclthreads", "N",
                            "Maximum number of client threads",
                            CArgDescriptions::eInteger, "10");

    arg_desc->AddDefaultKey("requests", "N",
                            "Number of requests to make",
                            CArgDescriptions::eInteger, "100");

    CArgAllow* constraint = new CArgAllow_Integers(1, 999);

    arg_desc->SetConstraint("srvthreads", constraint);
    arg_desc->SetConstraint("maxsrvthreads", constraint);

    arg_desc->SetConstraint("clthreads", constraint);
    arg_desc->SetConstraint("maxclthreads", constraint);
    arg_desc->SetConstraint("requests", constraint);

    arg_desc->AddDefaultKey("maxdelay", "N",
                            "Maximum delay in milliseconds",
                            CArgDescriptions::eInteger, "1000");

    SetupArgDescriptions(arg_desc.release());
}
コード例 #4
0
int main(void)
{
    g_NCBI_ConnectRandomSeed = (int) time(0) ^ NCBI_CONNECT_SRAND_ADDEND;
    srand(g_NCBI_ConnectRandomSeed);

    CORE_SetLOGFormatFlags(fLOG_None          | fLOG_Level   |
                           fLOG_OmitNoteLevel | fLOG_DateTime);
    CORE_SetLOGFILE(stderr, 0/*false*/);

    CORE_LOG(eLOG_Note, "Miscellaneous tests started");

    TEST_URL_Encoding();
    TEST_MIME();
    TEST_ConnNetInfo();

    CORE_LOG(eLOG_Note, "All tests completed successfully");
    CORE_SetLOG(0);
    return 0;
}
コード例 #5
0
    int Run(void)
    {
        CONNECT_Init(&CNcbiApplication::Instance()->GetConfig());
        
        const CNcbiArguments& app_args = GetArguments();
        m_Seed = app_args.Size() > 1 ?
                (unsigned int)atoi(app_args[1].c_str()) : (unsigned int)time(0);
        // Set error posting and tracing on maximum
        SetDiagTrace(eDT_Enable);
        SetDiagPostLevel(eDiag_Info);
        SetDiagPostAllFlags(SetDiagPostAllFlags(eDPF_Default)
            | eDPF_All | eDPF_OmitInfoSev);
        UnsetDiagPostFlag(eDPF_Line);
        UnsetDiagPostFlag(eDPF_File);
        UnsetDiagPostFlag(eDPF_Location);
        UnsetDiagPostFlag(eDPF_LongFilename);
        SetDiagTraceAllFlags(SetDiagPostAllFlags(eDPF_Default));

        string host = "www.ncbi.nlm.nih.gov";
        string path = "/Service/bounce.cgi";
        string args = kEmptyStr;
        string uhdr = kEmptyStr;

        ERR_POST(Info << "Seed = " << m_Seed);
        srand(m_Seed);

        ERR_POST(Info << "Creating HTTP connection to "
            "http://" + host + path + &"?"[args.empty() ? 1 : 0] + args);
        CConn_HttpStream ios(host, path, args, uhdr);

        int n = TEST_StreamPushback(ios, false/*no rewind*/);

        // Manual CONNECT_UnInit (for implicit CONNECT_Init() by HTTP stream ctor)
        CORE_SetREG(0);
        CORE_SetLOG(0);
        CORE_SetLOCK(0);

        return n;
    }
コード例 #6
0
int main(int argc, const char* argv[])
{
    CONN        conn;
    CONNECTOR   connector;
    EIO_Status  status;
    const char* inp_file;

    /* cmd.-line args */
    if (argc != 2) {
        Usage(argv[0], "Must specify the input file name");
    }
    inp_file = argv[1];

    /* log and data log streams */
    CORE_SetLOGFormatFlags(fLOG_None          | fLOG_Level   |
                           fLOG_OmitNoteLevel | fLOG_DateTime);
    CORE_SetLOGFILE(stderr, 0/*false*/);

    /* run the test */
    fprintf(stderr,
            "Starting the FILE CONNECTOR test...\n"
            "Copy data from file \"%s\" to file \"%s\".\n\n",
            inp_file, OUT_FILE);

    /* create connector, and bind it to the connection */
    connector = FILE_CreateConnector(inp_file, OUT_FILE);
    if ( !connector ) {
        Usage(argv[0], "Failed to create FILE connector");
    }

    verify(CONN_Create(connector, &conn) == eIO_Success);
 
    /* pump the data from one file to another */
    for (;;) {
        char buf[100];
        size_t n_read, n_written;

        /* read */
        status = CONN_Read(conn, buf, sizeof(buf), &n_read, eIO_ReadPlain);
        if (status != eIO_Success) {
            fprintf(stderr, "CONN_Read() failed (status: %s)\n",
                    IO_StatusStr(status));
            break;
        }
        fprintf(stderr, "READ: %ld  bytes\n", (long) n_read);

        /* write */
        status = CONN_Write(conn, buf, n_read, &n_written, eIO_WritePersist);
        if (status != eIO_Success) {
            fprintf(stderr, "CONN_Write() failed (status: %s)\n",
                    IO_StatusStr(status));
            assert(0);
            break;
        }
        assert(n_written == n_read);
    }
    assert(status == eIO_Closed);
    
    /* cleanup, exit */
    verify(CONN_Close(conn) == eIO_Success);
    CORE_LOG(eLOG_Note, "TEST completed successfully");
    CORE_SetLOG(0);
    return 0;
}
コード例 #7
0
/* Main function
 * Parse command-line options, initialize and cleanup API internals;
 * run client or server test
 */
extern int main(int argc, const char* argv[])
{
    /* Setup log stream */
    CORE_SetLOGFormatFlags(fLOG_None          | fLOG_Level   |
                           fLOG_OmitNoteLevel | fLOG_DateTime);
    CORE_SetLOGFILE(stderr, 0/*false*/);

    /* Parse cmd.-line args and decide whether it's a client or a server
     */
    switch ( argc ) {
    case 1:
        /*** Try to set various fake MT safety locks ***/
        CORE_SetLOCK( MT_LOCK_Create(0,
                                     TEST_LockHandler, TEST_LockCleanup) );
        CORE_SetLOCK(0);
        CORE_SetLOCK(0);
        CORE_SetLOCK( MT_LOCK_Create(&TEST_LockUserData,
                                     TEST_LockHandler, TEST_LockCleanup) );

        SOCK_SetDataLoggingAPI(eOn);
        assert(SOCK_InitializeAPI() == eIO_Success);
        SOCK_SetDataLoggingAPI(eOff);

        {{
            char local_host[64];
            assert(SOCK_gethostname(local_host, sizeof(local_host)) == 0);
            CORE_LOGF(eLOG_Note,
                      ("Running NCBISOCK test on host \"%s\"", local_host));
        }}

        TEST_gethostby();

        TEST_SOCK_isip();

        assert(SOCK_ShutdownAPI() == eIO_Success);

        CORE_SetLOCK(0);
        break;

    case 2: {
        /*** SERVER ***/
        TEST__server(argv[1]);
        assert(SOCK_ShutdownAPI() == eIO_Success);
        CORE_SetLOG(0);
        return 0;
    }

    case 3: case 4: {
        /*** CLIENT ***/
        const char*    host;
        unsigned short port;
        STimeout*      tmo;
        STimeout     x_tmo;

        /* host */
        host = argv[1];

        /* port */
        if (sscanf(argv[2], "%hu", &port) != 1)
            break;

        /* timeout */
        if (argc == 4) {
            double v;
            char*  e = (char*) argv[3];
            if (!*e  ||  (v = NCBI_simple_atof(e, &e)) < 0.0  ||  errno  || *e)
                break;
            x_tmo.sec  = (unsigned int)  v;
            x_tmo.usec = (unsigned int)((v - x_tmo.sec) * 1000000.0);
            tmo        = &x_tmo;
        } else
            tmo = 0/*infinite*/;

        TEST__client(host, port, tmo);
        assert(SOCK_ShutdownAPI() == eIO_Success);
        CORE_SetLOG(0);
        return 0;
    }
    } /* switch */

    /* USAGE */
    fprintf(stderr,
            "\nClient/Server USAGE:\n"
            "Client: %s <host> <port> [timeout]\n"
            "Server: %s <port>\n\n",
            argv[0], argv[0]);
    CORE_SetLOG(0);
    return argc == 1 ? 0 : 1;
}
コード例 #8
0
int main(int argc, char** argv)
{
    /* Prepare to connect:  parse and check cmd.-line args, etc. */
    const char*    host        = argc > 1 ? argv[1]       : "";
    unsigned short port        = argc > 2 ? atoi(argv[2]) : CONN_PORT_HTTP;
    const char*    path        = argc > 3 ? argv[3]       : "";
    const char*    args        = argc > 4 ? argv[4]       : "";
    const char*    inp_file    = argc > 5 ? argv[5]       : "";
    const char*    user_header = argc > 6 ? argv[6]       : "";

    size_t   content_length;
    STimeout timeout;

    SOCK sock;
    EIO_Status status;
    char buffer[10000];

    CORE_SetLOGFormatFlags(fLOG_None          | fLOG_Level   |
                           fLOG_OmitNoteLevel | fLOG_DateTime);
    CORE_SetLOGFILE(stderr, 0/*false*/);

    SOCK_SetupSSL(NcbiSetupTls);

    fprintf(stderr, "Running...\n"
            "  Executable:      '%s'\n"
            "  URL host:        '%s'\n"
            "  URL port:         %hu\n"
            "  URL path:        '%s'\n"
            "  URL args:        '%s'\n"
            "  Input data file: '%s'\n"
            "  User header:     '%s'\n"
            "Response(if any) from the hit URL goes to standard output.\n\n",
            argv[0], host, port, path, args, inp_file, user_header);

    if ( argc < 4 ) {
        fprintf(stderr,
                "Usage:   %s host port path args inp_file [user_header]\n",
                argv[0]);
        CORE_LOG(eLOG_Fatal, "Two few arguments");
        return 1;
    }

    {{
        FILE *fp = fopen(inp_file, "rb");
        long offset;

        if ( !fp ) {
            CORE_LOGF(eLOG_Fatal, ("Non-existent file '%s'", inp_file));
            return 2;
        }
        if ( fseek(fp, 0, SEEK_END) != 0  ||  (offset = ftell(fp)) < 0 ) {
            CORE_LOGF(eLOG_Fatal,
                      ("Cannot obtain size of file '%s'", inp_file));
            return 2;
        }
        fclose(fp);
        content_length = (size_t) offset;
    }}

    timeout.sec  = 10;
    timeout.usec = 0;
    
    /* Connect */
    sock = URL_Connect(host, port, path, args, /*NCBI_FAKE_WARNING*/
                       eReqMethod_Any, content_length,
                       &timeout, &timeout, user_header, 1/*true*/,
                       port == CONN_PORT_HTTPS
                       ? fSOCK_LogDefault | fSOCK_Secure
                       : fSOCK_LogDefault);
    if ( !sock )
        return 3;

    {{ /* Pump data from the input file to socket */
        FILE* fp = fopen(inp_file, "rb");
        if ( !fp ) {
            CORE_LOGF(eLOG_Fatal, 
                      ("Cannot open file '%s' for reading", inp_file));
            return 4;
        }

        for (;;) {
            size_t n_written;
            size_t n_read = fread(buffer, 1, sizeof(buffer), fp);
            if ( n_read <= 0 ) {
                if ( content_length ) {
                    CORE_LOGF(eLOG_Fatal,
                              ("Cannot read last %lu bytes from file '%s'",
                               (unsigned long) content_length, inp_file));
                    return 5;
                }
                break;
            }

            assert(content_length >= n_read);
            content_length -= n_read;
            status = SOCK_Write(sock, buffer, n_read,
                                &n_written, eIO_WritePersist);
            if ( status != eIO_Success ) {
                CORE_LOGF(eLOG_Fatal,
                          ("Error writing to socket: %s",
                           IO_StatusStr(status)));
                return 6;
            }
        }

        fclose(fp);
    }}

    /* Read reply from socket, write it to STDOUT */
    {{
        size_t n_read;
        for (;;) {
            status = SOCK_Read(sock, buffer, sizeof(buffer), &n_read,
                               eIO_ReadPlain);
            if (status != eIO_Success)
                break;

            fwrite(buffer, 1, n_read, stdout);
        }

        if ( status != eIO_Closed ) {
            CORE_LOGF(eLOG_Error,
                      ("Read error after %ld byte(s) from socket: %s",
                       (long) content_length, IO_StatusStr(status)));
        }
        fprintf(stdout, "\n");
    }}

    /* Success:  close the socket, cleanup, and exit */
    SOCK_Close(sock);

    CORE_LOG(eLOG_Note, "TEST completed successfully");
    CORE_SetLOG(0);
    return 0;
}
コード例 #9
0
ファイル: test_ncbi_namerd.c プロジェクト: svn2github/ncbi_tk
int main(int argc, const char *argv[])
{
    const char  *retmsg = "";
    const char  *svc = "";
    const char  *test_nums = "";
    int         retval = 1;
    int         live = 0;

    int i;
    for (i=1; i < argc; ++i) {
        if (strcmp(argv[i], "-f") == 0  &&  i < argc-1) {
            ++i;
            s_json_file = argv[i];
        } else if (strcmp(argv[i], "-l") == 0) {
            live = 1;
        } else if (strcmp(argv[i], "-n") == 0  &&  i < argc-1) {
            ++i;
            test_nums = argv[i];
            retmsg = "Not all tests run.";
        } else if (strcmp(argv[i], "-s") == 0  &&  i < argc-1) {
            ++i;
            svc = argv[i];
            retmsg = "Run for a given service instead of standard tests.";
        } else if (strcmp(argv[i], "-u") == 0  &&  i < argc-1) {
            ++i;
            s_user_header = argv[i];
            retmsg = "User header overridden.";
        } else {
            fprintf(stderr, "USAGE:  %s [OPTIONS...]\n", argv[0]);
            fprintf(stderr,
                "    [-h]       help\n"
                "    [-f ARG]   test file\n"
                "    [-l]       live test data (default is mock data)\n"
                "    [-n ARG]   comma-separated test selections (eg 1,2,5)\n"
                "    [-s ARG]   service\n"
                "    [-u ARG]   user header\n");
            goto out;
        }
    }

    CORE_SetLOGFormatFlags(fLOG_None | fLOG_Level | fLOG_OmitNoteLevel);
    CORE_SetLOGFILE(stderr, 0/*false*/);

    if (*svc) {
        test_service(live, svc);
    } else {
        if ( ! run_tests(live, test_nums)  &&  ! *retmsg)
            retmsg = "Not all tests passed.";
    }

out:
    CORE_LOG(eLOG_Note, "");
    if (strcmp(retmsg, "") == 0) {
        /* The only successful condition is a run of all tests. */
        CORE_LOG(eLOG_Note, "SUCCESS - All tests passed.");
        retval = 0;
    } else {
        CORE_LOGF(eLOG_Note, ("FAIL - %s", retmsg));
    }
    CORE_SetLOG(0);
    return retval;
}
コード例 #10
0
int main(int argc, const char* argv[])
{
    const char* service = argc > 1 && *argv[1] ? argv[1] : "bounce";
    static char obuf[8192 + 2];
    SConnNetInfo* net_info;
    CONNECTOR connector;
    EIO_Status status;
    char ibuf[1024];
    CONN conn;
    size_t n;

    setlocale(LC_ALL, "");
    g_NCBI_ConnectRandomSeed = (int) time(0) ^ NCBI_CONNECT_SRAND_ADDEND;
    srand(g_NCBI_ConnectRandomSeed);

    CORE_SetLOGFormatFlags(fLOG_None          | fLOG_Level   |
                           fLOG_OmitNoteLevel | fLOG_DateTime);
    CORE_SetLOGFILE(stderr, 0/*false*/);

    net_info = ConnNetInfo_Create(service);
    ConnNetInfo_AppendArg(net_info, "testarg",  "val");
    ConnNetInfo_AppendArg(net_info, "service",  "none");
    ConnNetInfo_AppendArg(net_info, "platform", "none");
    ConnNetInfo_AppendArg(net_info, "address",  "2010");
    ConnNetInfo_Log(net_info, eLOG_Note, CORE_GetLOG());

    connector = SERVICE_CreateConnectorEx(service, fSERV_Any, net_info, 0);

    if (!connector)
        CORE_LOG(eLOG_Fatal, "Failed to create service connector");

    if (CONN_Create(connector, &conn) != eIO_Success)
        CORE_LOG(eLOG_Fatal, "Failed to create connection");

    if (argc > 2) {
        strncpy0(obuf, argv[2], sizeof(obuf) - 2);
        obuf[n = strlen(obuf)] = '\n';
        obuf[++n]              = '\0';
        if (CONN_Write(conn, obuf, strlen(obuf), &n, eIO_WritePersist)
            != eIO_Success) {
            CONN_Close(conn);
            CORE_LOG(eLOG_Fatal, "Cannot write to connection");
        }
        assert(n == strlen(obuf));
    } else {
        for (n = 0; n < 10; n++) {
            size_t m;
            for (m = 0; m < sizeof(obuf) - 2; m++)
                obuf[m] = "0123456789\n"[rand() % 11];
            obuf[m++] = '\n';
            obuf[m]   = '\0';

            if (CONN_Write(conn, obuf, strlen(obuf), &m, eIO_WritePersist)
                != eIO_Success) {
                if (!n) {
                    CONN_Close(conn);
                    CORE_LOG(eLOG_Fatal, "Cannot write to connection");
                } else
                    break;
            }
            assert(m == strlen(obuf));
        }
    }

    for (;;) {
       if (CONN_Wait(conn, eIO_Read, net_info->timeout) != eIO_Success) {
            CONN_Close(conn);
            CORE_LOG(eLOG_Fatal, "Failed to wait for reading");
        }

        status = CONN_Read(conn, ibuf, sizeof(ibuf), &n, eIO_ReadPersist);
        if (n) {
            char* descr = CONN_Description(conn);
            CORE_DATAF(eLOG_Note, ibuf, n,
                       ("%lu bytes read from service (%s%s%s):",
                        (unsigned long) n, CONN_GetType(conn),
                        descr ? ", " : "", descr ? descr : ""));
            if (descr)
                free(descr);
        }
        if (status != eIO_Success) {
            if (status != eIO_Closed)
                CORE_LOGF(n ? eLOG_Error : eLOG_Fatal,
                          ("Read error: %s", IO_StatusStr(status)));
            break;
        }
    }

    ConnNetInfo_Destroy(net_info);
    CONN_Close(conn);

#if 0
    CORE_LOG(eLOG_Note, "Trying ID1 service");

    net_info = ConnNetInfo_Create(service);
    connector = SERVICE_CreateConnectorEx("ID1", fSERV_Any, net_info);
    ConnNetInfo_Destroy(net_info);

    if (!connector)
        CORE_LOG(eLOG_Fatal, "Service ID1 not available");

    if (CONN_Create(connector, &conn) != eIO_Success)
        CORE_LOG(eLOG_Fatal, "Failed to create connection");

    if (CONN_Write(conn, "\xA4\x80\x02\x01\x02\x00", 7, &n, eIO_WritePersist)
        != eIO_Success) {
        CONN_Close(conn);
        CORE_LOG(eLOG_Fatal, "Cannot write to service ID1");
    }
    assert(n == 7);

    if (CONN_Read(conn, ibuf, sizeof(ibuf), &n, eIO_ReadPlain) != eIO_Success){
        CONN_Close(conn);
        CORE_LOG(eLOG_Fatal, "Cannot read from service ID1");
    }

    CORE_LOGF(eLOG_Note, ("%d bytes read from service ID1", n));
    CONN_Close(conn);
#endif

    CORE_LOG(eLOG_Note, "TEST completed successfully");
    CORE_SetLOG(0);
    return 0/*okay*/;
}
コード例 #11
0
int main(int argc, char* argv[])
{
    char*       user_header = 0;
    CONNECTOR   connector;
    FILE*       data_file;
    STimeout    timeout;
    THTTP_Flags flags;

    /* Log and data-log streams */
    CORE_SetLOGFormatFlags(fLOG_None          | fLOG_Level   |
                           fLOG_OmitNoteLevel | fLOG_DateTime);
    CORE_SetLOGFILE(stderr, 0/*false*/);

    data_file = fopen("test_ncbi_http_connector.log", "ab");
    assert(data_file);

    /* Tune to the test URL using hard-coded pseudo-registry */
    CORE_SetREG( REG_Create(0, s_REG_Get, 0, 0, 0) );

    /* Connection timeout */
    timeout.sec  = 5;
    timeout.usec = 123456;

    if (argc > 1) {
        /* Generate user header and check graceful failure with
         * bad request status if the header ends up too large. */
        static const char kHttpHeader[] = "My-Header: ";
        size_t n, header_size = (size_t) atoi(argv[1]);
        user_header = (char*) malloc(sizeof(kHttpHeader) + header_size);
        if (user_header) {
            header_size += sizeof(kHttpHeader)-1;
            memcpy(user_header, kHttpHeader, sizeof(kHttpHeader)-1);
            for (n = sizeof(kHttpHeader)-1;  n < header_size;  n++)
                user_header[n] = '.';
            user_header[n] = '\0';
        }
    }

    /* Run the tests */
    flags = fHTTP_KeepHeader | (fHCC_UrlCodec|fHCC_UrlEncodeArgs)/*obsolete*/;
    connector = HTTP_CreateConnector(0, user_header, flags);
    CONN_TestConnector(connector, &timeout, data_file, fTC_SingleBouncePrint);

    flags = 0;
    connector = HTTP_CreateConnector(0, user_header, flags);
    CONN_TestConnector(connector, &timeout, data_file, fTC_SingleBounceCheck);

    flags = fHTTP_AutoReconnect;
    connector = HTTP_CreateConnector(0, user_header, flags);
    CONN_TestConnector(connector, &timeout, data_file, fTC_Everything);

    flags = fHTTP_AutoReconnect | fHCC_UrlCodec/*obsolete*/;
    connector = HTTP_CreateConnector(0, user_header, flags);
    CONN_TestConnector(connector, &timeout, data_file, fTC_Everything);

    /* Cleanup and Exit */
    CORE_SetREG(0);
    fclose(data_file);

    if (user_header)
        free(user_header);

    CORE_LOG(eLOG_Note, "TEST completed successfully");
    CORE_SetLOG(0);
    return 0;
}
コード例 #12
0
ファイル: test_ncbi_socket.c プロジェクト: hsptools/hsp-wrap
/* Main function
 * Parse command-line options, initialize and cleanup API internals;
 * run client or server test
 */
extern int main(int argc, char** argv)
{
    /* Setup log stream */
    CORE_SetLOGFormatFlags(fLOG_None          | fLOG_Level   |
                           fLOG_OmitNoteLevel | fLOG_DateTime);
    CORE_SetLOGFILE(stderr, 0/*false*/);

    /* Test client or server using hard-coded parameters */
#if   defined(DO_SERVER)
    argc = 2;
#elif defined(DO_CLIENT)
    argc = 3;
#endif

    /* Parse cmd.-line args and decide whether it's a client or a server
     */
    switch ( argc ) {
    case 1:
        /*** Try to set various fake MT safety locks ***/
        CORE_SetLOCK( MT_LOCK_Create(0,
                                     TEST_LockHandler, TEST_LockCleanup) );
        CORE_SetLOCK(0);
        CORE_SetLOCK(0);
        CORE_SetLOCK( MT_LOCK_Create(&TEST_LockUserData,
                                     TEST_LockHandler, TEST_LockCleanup) );

        SOCK_SetDataLoggingAPI(eOn);
        assert(SOCK_InitializeAPI() == eIO_Success);
        SOCK_SetDataLoggingAPI(eOff);

        {{
            char local_host[64];
            assert(SOCK_gethostname(local_host, sizeof(local_host)) == 0);
            CORE_LOGF(eLOG_Note,
                      ("Running NCBISOCK test on host \"%s\"", local_host));
        }}

        TEST_gethostby();

        TEST_SOCK_isip();

        assert(SOCK_ShutdownAPI() == eIO_Success);

        CORE_SetLOCK(0);
        break;

    case 2: {
        /*** SERVER ***/
        int port;

#if defined(DO_SERVER)
        port = DEF_PORT;
#else
        if (sscanf(argv[1], "%d", &port) != 1  ||  port < MIN_PORT)
            break;
#endif /* DO_SERVER */

        TEST__server((unsigned short) port);
        assert(SOCK_ShutdownAPI() == eIO_Success);
        CORE_SetLOG(0);
        return 0;
    }

    case 3: case 4: {
        /*** CLIENT ***/
        const char* host;
        int         port;
        STimeout*   tmo;

#if defined(DO_CLIENT)
        host = DEF_HOST;
        port = DEF_PORT;
        tmo  = 0/*infinite*/;
#else
        STimeout    x_tmo;
        /* host */
        host = argv[1];

        /* port */
        if (sscanf(argv[2], "%d", &port) != 1  ||  port < MIN_PORT)
            break;

        /* timeout */
        if (argc == 4) {
            double val = atof(argv[3]);
            if (val < 0)
                break;
            x_tmo.sec  = (unsigned int)  val;
            x_tmo.usec = (unsigned int)((val - x_tmo.sec) * 1000000);
            tmo = &x_tmo;
        } else
            tmo = 0/*infinite*/;
#endif /* DO_CLIENT */

        TEST__client(host, (unsigned short) port, tmo);
        assert(SOCK_ShutdownAPI() == eIO_Success);
        CORE_SetLOG(0);
        return 0;
    }
    } /* switch */

    /* USAGE */
    fprintf(stderr,
            "\nClient/Server USAGE:\n"
            "Client: %s <host> <port> [timeout]\n"
            "Server: %s <port>\n"
            "where <port> is greater than %d, and [timeout] is a double\n\n",
            argv[0], argv[0], MIN_PORT);
    CORE_SetLOG(0);
    return argc == 1 ? 0 : 1;
}
コード例 #13
0
void CServerTestApp::Exit(void)
{
    CORE_SetLOG(0);
    CORE_SetLOCK(0);
}
コード例 #14
0
ファイル: test_ncbi_disp.c プロジェクト: fbtestrepo/hw
/* One can define env.var. 'service'_CONN_HOST to reroute dispatching
 * information to particular dispatching host (instead of default).
 */
int main(int argc, const char* argv[])
{
    static const char kParameter[] = "test_parameter";
    const char* service = argc > 1 ? argv[1] : "bounce";
    SConnNetInfo* net_info;
    const SSERV_Info* info;
    const char* value;
    int n_found = 0;
    SERV_ITER iter;

    CORE_SetLOGFormatFlags(fLOG_None          | fLOG_Level   |
                           fLOG_OmitNoteLevel | fLOG_DateTime);
    CORE_SetLOGFILE(stderr, 0/*false*/);
    if (argc > 2) {
        if (strcasecmp(argv[2],"heap") == 0 || strcasecmp(argv[2],"all") == 0){
            HEAP_Options(eOff, eDefault);
            CORE_LOG(eLOG_Note, "Using slow heap access (w/checks)");
        }
        if (strcasecmp(argv[2],"lbsm") == 0 || strcasecmp(argv[2],"all") == 0){
#ifdef NCBI_OS_MSWIN
            if (strcasecmp(argv[2],"lbsm") == 0) {
                CORE_LOG(eLOG_Warning,
                         "Option \"lbsm\" has no useful effect on MS-Windows");
            }
#else
            LBSMD_FastHeapAccess(eOn);
            CORE_LOG(eLOG_Note, "Using live (faster) LBSM heap access");
#endif /*NCBI_OS_MSWIN*/
        }
        if (strcasecmp(argv[2],"lbsm") != 0  &&
            strcasecmp(argv[2],"heap") != 0  &&
            strcasecmp(argv[2],"all")  != 0)
            CORE_LOGF(eLOG_Fatal, ("Unknown option `%s'", argv[2]));
    }

    value = LBSMD_GetHostParameter(SERV_LOCALHOST, kParameter);
    CORE_LOGF(eLOG_Note, ("Querying host parameter `%s': %s%s%s", kParameter,
                          "`" + !value,
                          value ? value : "Not found",
                          "'" + !value));
    if (value)
        free((void*) value);

    CORE_LOGF(eLOG_Note, ("Looking for service `%s'", service));
    net_info = ConnNetInfo_Create(service);
    CORE_LOG(eLOG_Trace, "Opening service mapper");
    iter = SERV_OpenP(service, (fSERV_All & ~fSERV_Firewall) |
                      (strpbrk(service, "?*") ? fSERV_Promiscuous : 0),
                      SERV_LOCALHOST, 0/*port*/, 0.0/*preference*/,
                      net_info, 0/*skip*/, 0/*n_skip*/,
                      0/*external*/, 0/*arg*/, 0/*val*/);
    ConnNetInfo_Destroy(net_info);
    if (iter) {
        HOST_INFO hinfo;
        CORE_LOGF(eLOG_Trace,("%s service mapper has been successfully opened",
                              SERV_MapperName(iter)));
        while ((info = SERV_GetNextInfoEx(iter, &hinfo)) != 0) {
            char* info_str = SERV_WriteInfo(info);
            CORE_LOGF(eLOG_Note, ("Server #%d `%s' = %s", ++n_found,
                                  SERV_CurrentName(iter), info_str));
            if (hinfo) {
                static const char kTimeFormat[] = "%m/%d/%y %H:%M:%S";
                time_t t;
                char buf[80];
                double array[5];
                SHINFO_Params params;
                const char* e = HINFO_Environment(hinfo);
                const char* a = HINFO_AffinityArgument(hinfo);
                const char* v = HINFO_AffinityArgvalue(hinfo);
                CORE_LOG(eLOG_Note, "  Host info available:");
                CORE_LOGF(eLOG_Note, ("    Number of CPUs:      %d",
                                      HINFO_CpuCount(hinfo)));
                CORE_LOGF(eLOG_Note, ("    Number of CPU units: %d @ %.0fMHz",
                                      HINFO_CpuUnits(hinfo),
                                      HINFO_CpuClock(hinfo)));
                CORE_LOGF(eLOG_Note, ("    Number of tasks:     %d",
                                      HINFO_TaskCount(hinfo)));
                if (HINFO_MachineParams(hinfo, &params)) {
                    CORE_LOGF(eLOG_Note, ("    Arch:       %d",
                                          params.arch));
                    CORE_LOGF(eLOG_Note, ("    OSType:     %d",
                                          params.ostype));
                    t = (time_t) params.bootup;
                    strftime(buf, sizeof(buf), kTimeFormat, localtime(&t));
                    CORE_LOGF(eLOG_Note, ("    Kernel:     %hu.%hu.%hu @ %s",
                                          params.kernel.major,
                                          params.kernel.minor,
                                          params.kernel.patch, buf));
                    CORE_LOGF(eLOG_Note, ("    Bits:       %hu",
                                          params.bits));
                    CORE_LOGF(eLOG_Note, ("    Page size:  %lu",
                                          (unsigned long) params.pgsize));
                    t = (time_t) params.start;
                    strftime(buf, sizeof(buf), kTimeFormat, localtime(&t));
                    CORE_LOGF(eLOG_Note, ("    LBSMD:      %hu.%hu.%hu @ %s",
                                          params.daemon.major,
                                          params.daemon.minor,
                                          params.daemon.patch, buf));
                } else
                    CORE_LOG (eLOG_Note,  "    Machine params: unavailable");
                if (HINFO_Memusage(hinfo, array)) {
                    CORE_LOGF(eLOG_Note, ("    Total RAM:  %.2fMB", array[0]));
                    CORE_LOGF(eLOG_Note, ("    Cache RAM:  %.2fMB", array[1]));
                    CORE_LOGF(eLOG_Note, ("    Free  RAM:  %.2fMB", array[2]));
                    CORE_LOGF(eLOG_Note, ("    Total Swap: %.2fMB", array[3]));
                    CORE_LOGF(eLOG_Note, ("    Free  Swap: %.2fMB", array[4]));
                } else
                    CORE_LOG (eLOG_Note,  "    Memory usage: unavailable");
                if (HINFO_LoadAverage(hinfo, array)) {
                    CORE_LOGF(eLOG_Note, ("    Load averages: %f, %f (BLAST)",
                                          array[0], array[1]));
                } else
                    CORE_LOG (eLOG_Note,  "    Load averages: unavailable");
                if (a) {
                    assert(*a);
                    CORE_LOGF(eLOG_Note, ("    Affinity argument: %s", a));
                }
                if (a  &&  v)
                    CORE_LOGF(eLOG_Note, ("    Affinity value:    %s%s%s",
                                          *v ? "" : "\"", v, *v ? "" : "\""));
                CORE_LOGF(eLOG_Note, ("    Host environment: %s%s%s",
                                      e? "\"": "", e? e: "NULL", e? "\"": ""));
                free(hinfo);
            }
            free(info_str);
        }
        CORE_LOG(eLOG_Trace, "Resetting service mapper");
        SERV_Reset(iter);
        CORE_LOG(eLOG_Trace, "Service mapper has been reset");
        if (n_found && !(info = SERV_GetNextInfo(iter)))
            CORE_LOG(eLOG_Fatal, "Service not found after reset");
        CORE_LOG(eLOG_Trace, "Closing service mapper");
        SERV_Close(iter);
    }

    if (n_found != 0)
        CORE_LOGF(eLOG_Note, ("%d server(s) found", n_found));
    else
        CORE_LOG(eLOG_Fatal, "Requested service not found");

#if 0
    {{
        SConnNetInfo* net_info;
        net_info = ConnNetInfo_Create(service);
        iter = SERV_Open(service, fSERV_Http, SERV_LOCALHOST, net_info);
        ConnNetInfo_Destroy(net_info);
    }}

    if (iter != 0) {
        while ((info = SERV_GetNextInfo(iter)) != 0) {
            char* info_str = SERV_WriteInfo(info);
            CORE_LOGF(eLOG_Note, ("Service `%s' = %s", service, info_str));
            free(info_str);
            n_found++;
        }
        SERV_Close(iter);
    }
#endif

    CORE_LOG(eLOG_Note, "TEST completed successfully");
    CORE_SetLOG(0);
    return 0;
}
コード例 #15
0
int main(int argc, const char* argv[])
{
    SHEAP_Block* blk;
    int r, j, i, n;
    HEAP heap;
    char* c;

    /* CORE_SetLOGFormatFlags(fLOG_None | fLOG_Level | fLOG_OmitNoteLevel); */
    CORE_SetLOGFILE(stderr, 0/*false*/);
    if (argc > 1)
        g_NCBI_ConnectRandomSeed = atoi(argv[1]);
    else
        g_NCBI_ConnectRandomSeed = (int) time(0) ^ NCBI_CONNECT_SRAND_ADDEND;
    CORE_LOGF(eLOG_Note, ("Using seed %d", g_NCBI_ConnectRandomSeed));
    HEAP_Options(eOff/*slow*/, eOn/*newalk*/);
    srand(g_NCBI_ConnectRandomSeed);
    for (j = 1;  j <= 3;  j++) {
        CORE_LOGF(eLOG_Note, ("Creating heap %d", j));
        if (!(heap = HEAP_Create(0, 0, 4096, s_Expand, 0)))
            CORE_LOG(eLOG_Error, "Cannot create heap");
        for (n = 0; n < 1000 && (rand() & 0xFFFF) != 0x1234; n++) {
            r = rand() & 7;
            if (r == 1  ||  r == 3) {
                int/*bool*/ fast = rand() & 1;
                i = rand() & 0xFF;
                if (i) {
                    CORE_LOGF(eLOG_Note,
                              ("Allocating%s data size %d",
                               fast ? " fast" : "", i));
                    blk = fast ? HEAP_AllocFast(heap, i) : HEAP_Alloc(heap, i);
                    if (blk) {
                        CORE_LOGF(eLOG_Note,
                                  ("Done @%u, size %u",
                                   HEAP_ADDR(blk, heap), blk->size));
                    } else
                        CORE_LOG(eLOG_Error, "Allocation failed");
                    c = (char*) blk + sizeof(*blk);
                    while (i--)
                        *c++ = rand();
                    s_Walk(heap, 0);
                } else {
                    assert(!(fast
                             ? HEAP_AllocFast(heap, i)
                             : HEAP_Alloc(heap, i)));
                }
            } else if (r == 2  ||  r == 4) {
                blk = 0;
                do {
                    if (!(blk = HEAP_Walk(heap, blk)))
                        break;
                } while (rand() & 7);
                if (blk  &&  (short) blk->flag) {
                    unsigned size = blk->size;
                    unsigned data_size = size - sizeof(*blk);
                    CORE_LOGF(eLOG_Note,
                              ("Freeing @%u, size %u, data size %u",
                               HEAP_ADDR(blk, heap), size, data_size));
                    assert(data_size);
                    HEAP_Free(heap, blk);
                    CORE_LOG(eLOG_Note, "Done");
                    s_Walk(heap, 0);
                }
            } else if (r == 5) {
                const SHEAP_Block* prev = 0;
                unsigned ok = 0;
                blk = 0;
                for (;;) {
                    if (!(blk = HEAP_Walk(heap, blk)))
                        break;
                    if ((short) blk->flag  &&  (rand() & 7)) {
                        char buf[32];
                        unsigned size = blk->size;
                        int/*bool*/ fast = rand() & 1;
                        unsigned data_size = size - sizeof(*blk);
                        if (!fast  ||  !prev)
                            *buf = '\0';
                        else
                            sprintf(buf, ", prev @%u", HEAP_ADDR(prev, heap));
                        CORE_LOGF(eLOG_Note,
                                  ("Freeing%s%s @%u%s in walk,"
                                   " size %u, data size %u",
                                   fast ? " fast" : "", ok ? " more" : "",
                                   HEAP_ADDR(blk,heap), buf, size, data_size));
                        assert(data_size);
                        if (fast)
                            HEAP_FreeFast(heap, blk, prev);
                        else
                            HEAP_Free(heap, blk);
                        CORE_LOG(eLOG_Note, "Done");
                        s_Walk(heap, 0);
                        ok = 1;
                        if (prev  &&  !((short) prev->flag))
                            continue;
                    }
                    prev = blk;
                }
                if (!ok)
                    s_Walk(heap, "the");
                else
                    CORE_LOG(eLOG_Note, "Done with freeing while walking");
            } else if (r == 6  ||  r == 7) {
                HEAP newheap;

                if (r == 6) {
                    int/*bool*/ fast = rand() & 1;
                    if (fast) {
                        CORE_LOG(eLOG_Note, "Attaching heap fast");
                        newheap = HEAP_AttachFast(HEAP_Base(heap),
                                                  HEAP_Size(heap), 0);
                    } else {
                        CORE_LOG(eLOG_Note, "Attaching heap");
                        newheap = HEAP_Attach(HEAP_Base(heap), 0);
                    }
                } else {
                    CORE_LOG(eLOG_Note, "Copying heap");
                    newheap = HEAP_Copy(heap, 0, 0);
                }

                if (!newheap) {
                    CORE_LOGF(eLOG_Error,
                              ("%s failed", r == 6 ? "Attach" : "Copy"));
                } else
                    s_Walk(newheap, r == 6 ? "attached" : "copied");
                HEAP_Detach(newheap);
            } else {
                TNCBI_Size size = HEAP_Size(heap);
                HEAP newheap;

                CORE_LOG(eLOG_Note, "Trimming heap");
                newheap = HEAP_Trim(heap);
                CORE_LOGF(eLOG_Note,
                          ("Heap %strimmed: %u -> %u", newheap ? "" : "NOT ",
                           size, HEAP_Size(newheap)));
                if (newheap) {
                    heap = newheap;
                    s_Walk(heap, "trimmed");
                }
            }
        }
        HEAP_Destroy(heap);
        CORE_LOGF(eLOG_Note, ("Heap %d done", j));
    }
    CORE_LOG(eLOG_Note, "Test completed");
    CORE_SetLOG(0);
    return 0;
}
コード例 #16
0
int main(int argc, const char* argv[])
{
    const char custom_body[] =
        "Subject: Custom sized body\n"
        "\n"
        "Custom sized body\n"
        "0123456789\n"; /* these 11 chars to ignore */
    const char* body[] = {
        "This is a simple test",
        "This is a test with\n.",
        0,
        ".",
        "\n.\n",
        ".\n",
        "",
        "a\nb\nc\nd\n.",
        "a\r\n\rb\r\nc\r\nd\r\n.",
        ".\na"
    };
    const char* subject[] = {
        0,
        "CORE_SendMail Test",
        "",
    };
    const char* to[] = {
        "lavr",
        "lavr@pavo",
        " \"Anton Lavrentiev\"   <lavr@pavo>  , lavr, <lavr>   ",
    };
    size_t i, j, k, n, m;
    const char* mx_host;
    SSendMailInfo info;
    const char* retval;
    STimeout mx_tmo;
    char* huge_body;
    short mx_port;
    char val[32];
    FILE* fp;

    g_NCBI_ConnectRandomSeed = (int) time(0) ^ NCBI_CONNECT_SRAND_ADDEND;
    srand(g_NCBI_ConnectRandomSeed);

    CORE_SetLOGFormatFlags(fLOG_None          | fLOG_Level   |
                           fLOG_OmitNoteLevel | fLOG_DateTime);
    CORE_SetLOGFILE(stderr, 0/*false*/);

    ConnNetInfo_GetValue(0, REG_CONN_DEBUG_PRINTOUT, val, sizeof(val),
                         DEF_CONN_DEBUG_PRINTOUT);
    if (ConnNetInfo_Boolean(val)
        ||  (*val  &&  (strcasecmp(val, "all")  == 0  ||
                        strcasecmp(val, "some") == 0  ||
                        strcasecmp(val, "data") == 0))) {
        SOCK_SetDataLoggingAPI(eOn);
    }

    strcpy(val, "@");
    SendMailInfo_InitEx(&info, val, eCORE_UsernameCurrent);
    CORE_LOGF(eLOG_Note, ("@ - <%s>", info.from));

    strcpy(info.from, "user0");
    SendMailInfo_InitEx(&info, info.from, eCORE_UsernameCurrent);
    CORE_LOGF(eLOG_Note, ("user0 - <%s>", info.from));

    strcpy(info.from, "user1@");
    SendMailInfo_InitEx(&info, info.from, eCORE_UsernameCurrent);
    CORE_LOGF(eLOG_Note, ("user1@ - <%s>", info.from));

    strcpy(val, "@host2.net");
    SendMailInfo_InitEx(&info, val, eCORE_UsernameLogin);
    CORE_LOGF(eLOG_Note, ("@host2.net - <%s>", info.from));

    strcpy(val, "*****@*****.**");
    SendMailInfo_InitEx(&info, val, eCORE_UsernameReal);
    CORE_LOGF(eLOG_Note, ("[email protected] - <%s>", info.from));

    strcpy(info.from, "*****@*****.**");
    SendMailInfo_InitEx(&info, info.from, eCORE_UsernameReal);
    CORE_LOGF(eLOG_Note, ("[email protected] - <%s>", info.from));

    SendMailInfo_InitEx(&info, 0, eCORE_UsernameReal);
    CORE_LOGF(eLOG_Note, ("NULL - <%s>", info.from));

    if ((huge_body = malloc(TEST_HUGE_BODY_SIZE)) != 0) {

        strcpy(huge_body, "user5@");
        for (i = 0;  i < TEST_HUGE_BODY_SIZE - 6;  i++)
            huge_body[i + 6] = "abcdefghijklmnopqrstuvwxyz."[rand() % 27];
        huge_body[TEST_HUGE_BODY_SIZE - 1] = '\0';
        SendMailInfo_InitEx(&info, huge_body, eCORE_UsernameCurrent);
        CORE_LOGF(eLOG_Note, ("HUGE user5@host - <%s>", info.from));

        SendMailInfo_InitEx(&info, huge_body + 5, eCORE_UsernameLogin);
        CORE_LOGF(eLOG_Note, ("HUGE @host - <%s>", info.from));

        huge_body[4] = '6';
        huge_body[5] = '_';
        for (i = 6;  i < sizeof(info.from) + 1;  i++) {
            if (huge_body[i] == '.')
                huge_body[i]  = '_';
        }
        huge_body[sizeof(info.from) + 1] = '@';
        SendMailInfo_InitEx(&info, huge_body, eCORE_UsernameReal);
        CORE_LOGF(eLOG_Note, ("HUGE user6 - <%s>", info.from));

        huge_body[4] = '7';
        huge_body[sizeof(info.from) - 10]  = '@';
        SendMailInfo_InitEx(&info, huge_body, eCORE_UsernameReal);
        CORE_LOGF(eLOG_Note, ("LONG user7 - <%s>", info.from));

        memcpy(huge_body + sizeof(info.from) - 10, "user8", 5);
        huge_body[sizeof(info.from) << 1] = '\0';
        SendMailInfo_InitEx(&info, huge_body + sizeof(info.from) - 10,
                            eCORE_UsernameReal);
        CORE_LOGF(eLOG_Note, ("LONG user8 - <%s>", info.from));

        SendMailInfo_InitEx(&info, huge_body + sizeof(info.from) + 1,
                            eCORE_UsernameReal);
        CORE_LOGF(eLOG_Note, ("LONG @host - <%s>", info.from));

        free(huge_body);
    }

    if (argc > 1) {
        CORE_LOG(eLOG_Note, "Special test requested");
        if ((fp = fopen(argv[1], "rb")) != 0          &&
            fseek(fp, 0, SEEK_END) == 0               &&
            (m = ftell(fp)) != (size_t)(-1)           &&
            fseek(fp, 0, SEEK_SET) == 0               &&
            (huge_body = (char*) malloc(m + 1)) != 0  &&
            fread(huge_body, m, 1, fp) == 1) {
            huge_body[m] = '\0';
            CORE_LOGF(eLOG_Note, ("Sending file (%lu bytes)",
                                  (unsigned long) m));
            retval = CORE_SendMail("lavr", "File", huge_body);
            if (retval) {
                CORE_LOGF(eLOG_Fatal, ("Test failed: %s", retval));
            } else {
                CORE_LOG(eLOG_Note, "Test passed");
            }
        } else
            CORE_LOG_ERRNO(eLOG_Error, errno, "Test failed");
        return 0;
    }

#if 1
    CORE_LOG(eLOG_Note, "Phase 1 of 2: Testing CORE_SendMail");

    n = (sizeof(to)/sizeof(to[0]))*
        (sizeof(subject)/sizeof(subject[0]))*
        (sizeof(body)/sizeof(body[0]));
    m = 0;
    for (i = 0; i < sizeof(to)/sizeof(to[0]); i++) {
        for (j = 0; j < sizeof(subject)/sizeof(subject[0]); j++)
            for (k = 0; k < sizeof(body)/sizeof(body[0]); k++) {
                CORE_LOGF(eLOG_Note, ("Test %u of %u",
                                      (unsigned)(++m), (unsigned)n));
                retval = CORE_SendMail(to[i], subject[j], body[k]);
                if (retval != 0)
                    CORE_LOGF(eLOG_Fatal, ("Test failed: %s", retval));
            }
    }
#else
    CORE_LOG(eLOG_Note, "Phase 1 of 2: Skipping CORE_SendMail tests");
#endif

    CORE_LOG(eLOG_Note, "Phase 2 of 2: Testing CORE_SendMailEx");

    SendMailInfo_Init(&info);
    mx_host = info.mx_host;
    mx_port = info.mx_port;
    mx_tmo  = info.mx_timeout;

    info.mx_host = "localhost";

    CORE_LOG(eLOG_Note, "Testing bad port");
    info.mx_port = 10/*BAD*/;
    retval = CORE_SendMailEx("lavr", "CORE_SendMailEx", "Bad port", &info);
    if (!retval)
        CORE_LOG(eLOG_Fatal, "Test failed");
    CORE_LOGF(eLOG_Note, ("Test passed: %s", retval));

    CORE_LOG(eLOG_Note, "Testing bad protocol");
    info.mx_port = CONN_PORT_FTP;
    retval = CORE_SendMailEx("lavr", "CORE_SendMailEx", "Protocol", &info);
    if (!retval)
        CORE_LOG(eLOG_Fatal, "Test failed");
    CORE_LOGF(eLOG_Note, ("Test passed: %s", retval));

    CORE_LOG(eLOG_Note, "Testing timeout");
    info.mx_host = "www.ncbi.nlm.nih.gov";
    info.mx_timeout.sec = 5;
    info.mx_port = CONN_PORT_HTTP;
    retval = CORE_SendMailEx("lavr", "CORE_SendMailEx", "Timeout", &info);
    if (!retval)
        CORE_LOG(eLOG_Error, "Test failed");
    else
        CORE_LOGF(eLOG_Note, ("Test passed: %s", retval));

    info.mx_port = mx_port;
    info.mx_timeout = mx_tmo;

    CORE_LOG(eLOG_Note, "Testing bad host");
    info.mx_host = "abrakadabra";
    retval = CORE_SendMailEx("lavr", "CORE_SendMailEx", "Bad host", &info);
    if (!retval)
        CORE_LOG(eLOG_Fatal, "Test failed");
    CORE_LOGF(eLOG_Note, ("Test passed: %s", retval));

    info.mx_host = "localhost";

    CORE_LOG(eLOG_Note, "Testing cc");
    info.cc = "vakatov";
    retval = CORE_SendMailEx("", "CORE_SendMailEx", "CC", &info);
    if (retval)
        CORE_LOGF(eLOG_Fatal, ("Test failed: %s", retval));
    CORE_LOG(eLOG_Note, "Test passed");

    CORE_LOG(eLOG_Note, "Testing bcc");
    info.cc = 0;
    info.bcc = "vakatov";
    retval = CORE_SendMailEx(0, "CORE_SendMailEx", "Bcc", &info);
    if (retval)
        CORE_LOGF(eLOG_Fatal, ("Test failed: %s", retval));
    CORE_LOG(eLOG_Note, "Test passed");

    CORE_LOG(eLOG_Note, "Testing huge body");
    info.cc = 0;
    info.bcc = 0;
    if (!(huge_body = (char*) malloc(TEST_HUGE_BODY_SIZE)))
        CORE_LOG(eLOG_Fatal, "Test failed: Cannot allocate memory");
    for (i = 0; i < TEST_HUGE_BODY_SIZE - 1; i++)
        huge_body[i] = "0123456789\nABCDEFGHIJKLMNOPQRSTUVWXYZ ."[rand() % 39];
    huge_body[i] = 0;
    retval = CORE_SendMailEx("lavr", "CORE_SendMailEx", huge_body, &info);
    if (retval)
        CORE_LOGF(eLOG_Fatal, ("Test failed: %s", retval));
    if (!(fp = fopen("test_ncbi_sendmail.out", "w")) ||
        fwrite(huge_body, TEST_HUGE_BODY_SIZE - 1, 1, fp) != 1) {
        CORE_LOG(eLOG_Error, "Test failed: Cannot store huge body to file");
    } else {
        fclose(fp);
        CORE_LOG(eLOG_Note, "Success: Check test_ncbi_sendmail.out");
    }
    free(huge_body);

    CORE_LOG(eLOG_Note, "Testing custom headers");
    info.header = "Organization: NCBI/NLM/NIH\nReference: abcdefghijk";
    retval = CORE_SendMailEx("lavr", "CORE_SendMailEx", "Custom header",&info);
    if (retval)
        CORE_LOGF(eLOG_Fatal, ("Test failed: %s", retval));
    CORE_LOG(eLOG_Note, "Test passed");

    CORE_LOG(eLOG_Note, "Testing no recipients");
    retval = CORE_SendMailEx(0, "CORE_SendMailEx", "No recipients", &info);
    if (!retval)
        CORE_LOG(eLOG_Fatal, "Test failed");
    CORE_LOGF(eLOG_Note, ("Test passed: %s", retval));

    CORE_LOG(eLOG_Note, "Testing AS-IS message");
    info.mx_options = fSendMail_NoMxHeader;
    retval = CORE_SendMailEx("lavr",
                             "BAD SUBJECT SHOULD NOT APPEAR BUT IGNORED",
                             "From: yourself\n"
                             "To: yourself\n"
                             "Subject: AS-IS message\n"
                             "\n"
                             "AS-IS",
                             &info);
    if (retval)
        CORE_LOGF(eLOG_Fatal, ("Test failed: %s", retval));
    CORE_LOG(eLOG_Note, "Test passed");

    CORE_LOG(eLOG_Note, "Testing AS-IS custom sized message");
    info.body_size = strlen(custom_body) - 11/*to ignore*/;
    retval = CORE_SendMailEx("<lavr@pavo>",
                             "BAD SUBJECT SHOULD NOT APPEAR BUT IGNORED",
                             custom_body,
                             &info);
    if (retval)
        CORE_LOGF(eLOG_Fatal, ("Test failed: %s", retval));
    CORE_LOG(eLOG_Note, "Test passed");

    info.body_size = 0;
    info.mx_options = 0;
    info.mx_host = mx_host;

    CORE_LOG(eLOG_Note, "Testing bad from");
    strcpy(info.from, "blahblah@blahblah");
    retval = CORE_SendMailEx("lavr", "CORE_SendMailEx", "Bad from",&info);
    if (!retval)
        CORE_LOG(eLOG_Error, "Test failed");
    else
        CORE_LOGF(eLOG_Note, ("Test passed: %s", retval));

    SendMailInfo_Init(&info);
    CORE_LOG(eLOG_Note, "Testing drop no FQDN option");
    info.mx_options |= fSendMail_StripNonFQDNHost;
    retval = CORE_SendMailEx("lavr", "CORE_SendMailEx", "No FQDN", &info);
    if (retval)
        CORE_LOGF(eLOG_Error, ("Test failed: %s", retval));
    else
        CORE_LOG(eLOG_Note, "Test passed");

    CORE_LOG(eLOG_Note, "Testing bad magic");
    info.magic_cookie = 0;
    retval = CORE_SendMailEx("lavr", "CORE_SendMailEx", "Bad Magic", &info);
    if (!retval)
        CORE_LOG(eLOG_Fatal, "Test failed");
    CORE_LOGF(eLOG_Note, ("Test passed: %s", retval));

    CORE_LOG(eLOG_Note, "TEST completed successfully");
    CORE_SetLOG(0);
    return 0;
}
コード例 #17
0
int main(int argc, const char* argv[])
{
    const char* inp_file    = (argc > 5) ? argv[5] : "";
    const char* user_header = (argc > 6) ? argv[6] : "";

    SConnNetInfo* net_info;
    CONNECTOR     connector;
    CONN          conn;
    EIO_Status    status;

    char   buffer[100];
    size_t n_read, n_written;

    /* Prepare to connect:  parse and check cmd.-line args, etc. */
    s_Args.host         = (argc > 1) ? argv[1] : "";
    s_Args.port         = (argc > 2) ? argv[2] : "";
    s_Args.path         = (argc > 3) ? argv[3] : "";
    s_Args.args         = (argc > 4) ? argv[4] : "";

    fprintf(stderr, "Running '%s':\n"
            "  URL host:        '%s'\n"
            "  URL port:        '%s'\n"
            "  URL path:        '%s'\n"
            "  URL args:        '%s'\n"
            "  Input data file: '%s'\n"
            "  User header:     '%s'\n"
            "Reply(if any) from the hit URL goes to the standard output.\n\n",
            argv[0],
            s_Args.host, s_Args.port, s_Args.path, s_Args.args,
            inp_file, user_header);

    /* Log stream */
    CORE_SetLOGFormatFlags(fLOG_None          | fLOG_Level   |
                           fLOG_OmitNoteLevel | fLOG_DateTime);
    CORE_SetLOGFILE(stderr, 0/*false*/);

    /* Tune to the test URL using hard-coded pseudo-registry */
    CORE_SetREG( REG_Create(0, s_REG_Get, 0, 0, 0) );

    SOCK_SetupSSL(NcbiSetupTls);

    /* Usage */
    if (argc < 4) {
        fprintf(stderr,
                "Usage:   %s host port path [args] [inp_file] [user_header]\n"
                "Example: %s www.ncbi.nlm.nih.gov 80 "
                "/Service/bounce.cgi 'arg1+arg2+arg3'\n",
                argv[0], argv[0]);
        CORE_LOG(eLOG_Fatal, "Too few arguments");
        return 1;
    }

    /* Connect */
    if (atoi(s_Args.port) == CONN_PORT_HTTPS) {
        verify((net_info = ConnNetInfo_Create(0)) != 0);
        net_info->scheme = eURL_Https;
    } else
        net_info = 0;

    connector = HTTP_CreateConnector(net_info, user_header, 0);
    assert(connector);
    verify(CONN_Create(connector, &conn) == eIO_Success);

    ConnNetInfo_Destroy(net_info);

    /* If input file specified, then send its content (as HTTP request body) */
    if (*inp_file) {
        FILE* inp_fp;

        if (strcmp(inp_file, "-") != 0) {
            static const char kDevNull[] =
#ifdef NCBI_OS_MSWIN
                "NUL"
#else
                "/dev/null"
#endif /*NCBI_OS_MSWIN*/
                ;
            if (strcmp(inp_file, "+") == 0)
                inp_file = kDevNull;
            if (!(inp_fp = fopen(inp_file, "rb"))) {
                CORE_LOGF(eLOG_Fatal,
                          ("Cannot open file '%s' for reading", inp_file));
            }
        } else
            inp_fp = stdin;

        for (;;) {
            n_read = fread(buffer, 1, sizeof(buffer), inp_fp);
            if (n_read <= 0) {
                assert(feof(inp_fp));
                break; /* EOF */
            }

            status = CONN_Write(conn, buffer, n_read,
                                &n_written, eIO_WritePersist);
            if (status != eIO_Success) {
                CORE_LOGF(eLOG_Fatal,
                          ("Unable to write to URL: %s",IO_StatusStr(status)));
            }
            assert(n_written == n_read);
        }
        fclose(inp_fp);
    }

    /* Read reply from connection, write it to standard output */
    for (;;) {
        status = CONN_Read(conn,buffer,sizeof(buffer),&n_read,eIO_ReadPlain);
        if (status != eIO_Success)
            break;
        if (connector)
            puts("----- [BEGIN] HTTP Content -----");
        fwrite(buffer, 1, n_read, stdout);
        fflush(stdout);
        connector = 0;
    }
    if (!connector) {
        puts("\n----- [END] HTTP Content -----");
        fclose(stdout);
    }

    if (status != eIO_Closed) {
        CORE_LOGF(eLOG_Fatal,
                  ("Unable to read from URL: %s", IO_StatusStr(status)));
    }

    /* Success:  close the connection, cleanup, and exit */
    CONN_Close(conn);
    CORE_SetREG(0);
    CORE_LOG(eLOG_Note, "TEST completed successfully");
    CORE_SetLOG(0);
    return 0;
}