LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
	int wmId, wmEvent;
	LPMINMAXINFO minInfo;
	static SOCKET serverSocket;
	static SOCKET clientSocket;

	switch (message) {
	case WM_CREATE:
		serverSocket = CreateSocket(hWnd);
		connectionStatus = statusNotConnected;
		EnableMenuItem(GetMenu(hWnd), IDM_DISCONNECT, MF_BYCOMMAND | MF_GRAYED);
		ListAddresses();
		break;
	case WM_NETWORK:
		switch (WSAGETSELECTEVENT(lParam)) {
		case FD_ACCEPT:
			clientSocket = AcceptSocket(hWnd, serverSocket);
			break;
		case FD_CLOSE:
			if (connectionStatus == statusConnected)
				CloseSocket(hWnd, clientSocket);
			break;
		}
		break;
	case WM_COMMAND:
		wmId = LOWORD(wParam);
		wmEvent = HIWORD(wParam);
		switch (wmId) {
		case IDM_ABOUT:
			DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
			break;
		case IDM_EXIT:
			Shell_NotifyIcon(NIM_DELETE, &trayIcon[trayIconNotConnected]);
			DestroyWindow(hWnd);
			break;
		case IDM_TRAY:
			HideInTray(hWnd, TRUE);
			break;
		case IDM_DISCONNECT:
			if (connectionStatus == statusConnected)
				CloseSocket(hWnd, clientSocket);
			break;
		case IDM_OPEN:
			HideInTray(hWnd, FALSE);
			break;
		default:
			return DefWindowProc(hWnd, message, wParam, lParam);
		}
		break;
	case WM_GETMINMAXINFO:
		minInfo = (LPMINMAXINFO)lParam;
		minInfo->ptMinTrackSize.x = kWidthMin;
		minInfo->ptMinTrackSize.y = kHeightMin;
		break;
	case WM_PAINT:
		DisplayWindow(hWnd);
		break;
	case WM_SYSCOMMAND:
		if (wParam == SC_MINIMIZE)
			HideInTray(hWnd, TRUE);
		else
			return DefWindowProc(hWnd, message, wParam, lParam);
		break;
	case WM_CLOSE:
		HideInTray(hWnd, TRUE);
		break;
	case WM_DESTROY:
		PostQuitMessage(0);
		break;
	case WM_TRAYMENU:
		if (wParam == kTrayId) {
			switch (lParam) {
			case WM_RBUTTONDOWN:
				DisplayTrayMenu(hWnd);
				break;
			case WM_LBUTTONDBLCLK:
				HideInTray(hWnd, !bInTray);
				break;
			default:
				break;
			}
		}
		break;
	default:
		return DefWindowProc(hWnd, message, wParam, lParam);
	}
	return 0;
}
Beispiel #2
0
/** void connect_server()
 *  Attempts to connect to all configured servers.
 */
int connect_server(int initial_id)
{
    int attempts = 2;
    int rc = initial_id;


    /* Checking if the initial is zero, meaning we have to rotate to the
     * beginning.
     */
    if(agt->rip[initial_id] == NULL)
    {
        rc = 0;
        initial_id = 0;
    }


    /* Closing socket if available. */
    if(agt->sock >= 0)
    {
        sleep(1);
        CloseSocket(agt->sock);
        agt->sock = -1;

        if(agt->rip[1])
        {
            verbose("%s: INFO: Closing connection to server (%s:%d).",
                    ARGV0,
                    agt->rip[rc],
                    agt->port);
        }

    }


    while(agt->rip[rc])
    {
        char *tmp_str;

        /* Checking if we have a hostname. */
        tmp_str = strchr(agt->rip[rc], '/');
        if(tmp_str)
        {
            char *f_ip;
            *tmp_str = '\0';

            f_ip = OS_GetHost(agt->rip[rc], 5);
            if(f_ip)
            {
                char ip_str[128];
                ip_str[127] = '\0';

                snprintf(ip_str, 127, "%s/%s", agt->rip[rc], f_ip);

                free(f_ip);
                free(agt->rip[rc]);

                os_strdup(ip_str, agt->rip[rc]);
                tmp_str = strchr(agt->rip[rc], '/');
                tmp_str++;
            }
            else
            {
                merror("%s: WARN: Unable to get hostname for '%s'.",
                       ARGV0, agt->rip[rc]);
                *tmp_str = '/';
                tmp_str++;
            }
        }
        else
        {
            tmp_str = agt->rip[rc];
        }


        verbose("%s: INFO: Trying to connect to server (%s:%d).", ARGV0,
                agt->rip[rc],
                agt->port);

        /* IPv6 address: */
        if(strchr(tmp_str,':') != NULL)
        {
            verbose("%s: INFO: Using IPv6 for: %s .", ARGV0, tmp_str);
            agt->sock = OS_ConnectUDP(agt->port, tmp_str, 1);
        }
        else
        {
            verbose("%s: INFO: Using IPv4 for: %s .", ARGV0, tmp_str);
            agt->sock = OS_ConnectUDP(agt->port, tmp_str, 0);
        }

        if(agt->sock < 0)
        {
            agt->sock = -1;
            merror(CONNS_ERROR, ARGV0, tmp_str);
            rc++;

            if(agt->rip[rc] == NULL)
            {
                attempts += 10;

                /* Only log that if we have more than 1 server configured. */
                if(agt->rip[1])
                    merror("%s: ERROR: Unable to connect to any server.",ARGV0);

                sleep(attempts);
                rc = 0;
            }
        }
        else
        {
            /* Setting socket non-blocking on HPUX */
            #ifdef HPUX
            //fcntl(agt->sock, O_NONBLOCK);
            #endif

            #ifdef WIN32
            int bmode = 1;

            /* Setting socket to non-blocking */
            ioctlsocket(agt->sock, FIONBIO, (u_long FAR*) &bmode);
            #endif

            agt->rip_id = rc;
            return(1);
        }
    }

    return(0);
}
Beispiel #3
0
void XLCDproc::Stop()
{
  CloseSocket();
  m_bStop = true;
}
Beispiel #4
0
THREAD_RETURN CYASSL_THREAD server_test(void* args)
{
    SOCKET_T sockfd   = 0;
    int      clientfd = 0;

    SSL_METHOD* method = 0;
    SSL_CTX*    ctx    = 0;
    SSL*        ssl    = 0;

    char   msg[] = "I hear you fa shizzle!";
    char   input[80];
    int    idx;
    int    ch;
    int    version = SERVER_DEFAULT_VERSION;
    int    doCliCertCheck = 1;
    int    useAnyAddr = 0;
    int    port = yasslPort;
    int    usePsk = 0;
    int    doDTLS = 0;
    int    useNtruKey = 0;
    int    nonBlocking = 0;
    int    trackMemory = 0;
    char*  cipherList = NULL;
    char*  verifyCert = (char*)cliCert;
    char*  ourCert    = (char*)svrCert;
    char*  ourKey     = (char*)svrKey;
    int    argc = ((func_args*)args)->argc;
    char** argv = ((func_args*)args)->argv;

    ((func_args*)args)->return_code = -1; /* error state */

#ifdef NO_RSA
    verifyCert = (char*)cliEccCert;
    ourCert    = (char*)eccCert;
    ourKey     = (char*)eccKey;
#endif
    (void)trackMemory;

    while ((ch = mygetopt(argc, argv, "?dbstnNup:v:l:A:c:k:")) != -1) {
        switch (ch) {
            case '?' :
                Usage();
                exit(EXIT_SUCCESS);

            case 'd' :
                doCliCertCheck = 0;
                break;

            case 'b' :
                useAnyAddr = 1;
                break;

            case 's' :
                usePsk = 1;
                break;

            case 't' :
            #ifdef USE_CYASSL_MEMORY
                trackMemory = 1;
            #endif
                break;

            case 'n' :
                useNtruKey = 1;
                break;

            case 'u' :
                doDTLS  = 1;
                break;

            case 'p' :
                port = atoi(myoptarg);
                #if !defined(NO_MAIN_DRIVER) || defined(USE_WINDOWS_API)
                    if (port == 0)
                        err_sys("port number cannot be 0");
                #endif
                break;

            case 'v' :
                version = atoi(myoptarg);
                if (version < 0 || version > 3) {
                    Usage();
                    exit(MY_EX_USAGE);
                }
                break;

            case 'l' :
                cipherList = myoptarg;
                break;

            case 'A' :
                verifyCert = myoptarg;
                break;

            case 'c' :
                ourCert = myoptarg;
                break;

            case 'k' :
                ourKey = myoptarg;
                break;

            case 'N':
                nonBlocking = 1;
                break;

            default:
                Usage();
                exit(MY_EX_USAGE);
        }
    }

    myoptind = 0;      /* reset for test cases */

    /* sort out DTLS versus TLS versions */
    if (version == CLIENT_INVALID_VERSION) {
        if (doDTLS)
            version = CLIENT_DTLS_DEFAULT_VERSION;
        else
            version = CLIENT_DEFAULT_VERSION;
    }
    else {
        if (doDTLS) {
            if (version == 3)
                version = -2;
            else
                version = -1;
        }
    }

#ifdef USE_CYASSL_MEMORY
    if (trackMemory)
        InitMemoryTracker(); 
#endif

    switch (version) {
#ifndef NO_OLD_TLS
        case 0:
            method = SSLv3_server_method();
            break;

        case 1:
            method = TLSv1_server_method();
            break;

        case 2:
            method = TLSv1_1_server_method();
            break;
#endif

        case 3:
            method = TLSv1_2_server_method();
            break;

#ifdef CYASSL_DTLS
        case -1:
            method = DTLSv1_server_method();
            break;

        case -2:
            method = DTLSv1_2_server_method();
            break;
#endif

        default:
            err_sys("Bad SSL version");
    }

    if (method == NULL)
        err_sys("unable to get method");

    ctx = SSL_CTX_new(method);
    if (ctx == NULL)
        err_sys("unable to get ctx");

    if (cipherList)
        if (SSL_CTX_set_cipher_list(ctx, cipherList) != SSL_SUCCESS)
            err_sys("server can't set cipher list 1");

#ifdef CYASSL_LEANPSK
    usePsk = 1;
#endif

#if defined(NO_RSA) && !defined(HAVE_ECC)
    usePsk = 1;
#endif

#if !defined(NO_FILESYSTEM) && !defined(NO_CERTS)
    if (!usePsk) {
        if (SSL_CTX_use_certificate_file(ctx, ourCert, SSL_FILETYPE_PEM)
                                         != SSL_SUCCESS)
            err_sys("can't load server cert file, check file and run from"
                    " CyaSSL home dir");
    }
#endif

#ifdef HAVE_NTRU
    if (useNtruKey) {
        if (CyaSSL_CTX_use_NTRUPrivateKey_file(ctx, ourKey)
                                               != SSL_SUCCESS)
            err_sys("can't load ntru key file, "
                    "Please run from CyaSSL home dir");
    }
#endif

#if !defined(NO_FILESYSTEM) && !defined(NO_CERTS)
    if (!useNtruKey && !usePsk) {
        if (SSL_CTX_use_PrivateKey_file(ctx, ourKey, SSL_FILETYPE_PEM)
                                         != SSL_SUCCESS)
            err_sys("can't load server cert file, check file and run from"
                " CyaSSL home dir");
    }
#endif

    if (usePsk) {
#ifndef NO_PSK
        SSL_CTX_set_psk_server_callback(ctx, my_psk_server_cb);
        SSL_CTX_use_psk_identity_hint(ctx, "cyassl server");
        if (cipherList == NULL) {
            const char *defaultCipherList;
            #ifdef HAVE_NULL_CIPHER
                defaultCipherList = "PSK-NULL-SHA256";
            #else
                defaultCipherList = "PSK-AES128-CBC-SHA256";
            #endif
            if (SSL_CTX_set_cipher_list(ctx, defaultCipherList) != SSL_SUCCESS)
                err_sys("server can't set cipher list 2");
        }
#endif
    }

#if !defined(NO_FILESYSTEM) && !defined(NO_CERTS)
    /* if not using PSK, verify peer with certs */
    if (doCliCertCheck && usePsk == 0) {
        SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER |
                                SSL_VERIFY_FAIL_IF_NO_PEER_CERT,0);
        if (SSL_CTX_load_verify_locations(ctx, verifyCert, 0) != SSL_SUCCESS)
            err_sys("can't load ca file, Please run from CyaSSL home dir");
    }
#endif

#ifdef OPENSSL_EXTRA
    SSL_CTX_set_default_passwd_cb(ctx, PasswordCallBack);
#endif

#if defined(CYASSL_SNIFFER) && !defined(HAVE_NTRU) && !defined(HAVE_ECC)
    /* don't use EDH, can't sniff tmp keys */
    if (cipherList == NULL) {
        if (SSL_CTX_set_cipher_list(ctx, "AES256-SHA256") != SSL_SUCCESS)
            err_sys("server can't set cipher list 3");
    }
#endif

    ssl = SSL_new(ctx);
    if (ssl == NULL)
        err_sys("unable to get SSL");

#ifdef HAVE_CRL
    CyaSSL_EnableCRL(ssl, 0);
    CyaSSL_LoadCRL(ssl, crlPemDir, SSL_FILETYPE_PEM, CYASSL_CRL_MONITOR |
                                                     CYASSL_CRL_START_MON);
    CyaSSL_SetCRL_Cb(ssl, CRL_CallBack);
#endif
    tcp_accept(&sockfd, &clientfd, (func_args*)args, port, useAnyAddr, doDTLS);
    if (!doDTLS) 
        CloseSocket(sockfd);

    SSL_set_fd(ssl, clientfd);
    if (usePsk == 0) {
        #if !defined(NO_FILESYSTEM) && defined(OPENSSL_EXTRA)
            CyaSSL_SetTmpDH_file(ssl, dhParam, SSL_FILETYPE_PEM);
        #elif !defined(NO_CERTS)
            SetDH(ssl);  /* repick suites with DHE, higher priority than PSK */
        #endif
    }

#ifndef CYASSL_CALLBACKS
    if (nonBlocking) {
        CyaSSL_set_using_nonblock(ssl, 1);
        tcp_set_nonblocking(&clientfd);
        NonBlockingSSL_Accept(ssl);
    } else if (SSL_accept(ssl) != SSL_SUCCESS) {
        int err = SSL_get_error(ssl, 0);
        char buffer[80];
        printf("error = %d, %s\n", err, ERR_error_string(err, buffer));
        err_sys("SSL_accept failed");
    }
#else
    NonBlockingSSL_Accept(ssl);
#endif
    showPeer(ssl);

    idx = SSL_read(ssl, input, sizeof(input)-1);
    if (idx > 0) {
        input[idx] = 0;
        printf("Client message: %s\n", input);

    }
    else if (idx < 0) {
        int readErr = SSL_get_error(ssl, 0);
        if (readErr != SSL_ERROR_WANT_READ)
            err_sys("SSL_read failed");
    }

    if (SSL_write(ssl, msg, sizeof(msg)) != sizeof(msg))
        err_sys("SSL_write failed");

    SSL_shutdown(ssl);
    SSL_free(ssl);
    SSL_CTX_free(ctx);
    
    CloseSocket(clientfd);
    ((func_args*)args)->return_code = 0;

#ifdef USE_CYASSL_MEMORY
    if (trackMemory)
        ShowMemoryTracker();
#endif /* USE_CYASSL_MEMORY */

    return 0;
}
Beispiel #5
0
void RecvFinish(int32_t bytestransfer,struct connection *c,uint32_t err_code)
{
	uint32_t recv_size;
	uint32_t free_buffer_size;
	buffer_t buf;
	uint32_t pos;
	int32_t i = 0;
	do{
		if(bytestransfer == 0)
			return;
		else if(bytestransfer < 0 && err_code != EAGAIN){
			//printf("recv close\n");
            if(c->status != SCLOSE){
                c->status = SCLOSE;
                CloseSocket(c->socket);
                //被动关闭
                c->cb_disconnect(c,err_code);
			}
			return;
		}else if(bytestransfer > 0){
			int32_t total_size = 0;
			do{
				c->last_recv = GetSystemMs64();
				update_next_recv_pos(c,bytestransfer);
				c->unpack_size += bytestransfer;
				total_size += bytestransfer;
				if(!unpack(c)) return;
				buf = c->next_recv_buf;
				pos = c->next_recv_pos;
				recv_size = BUFFER_SIZE;
				i = 0;
				do
				{
					free_buffer_size = buf->capacity - pos;
					free_buffer_size = recv_size > free_buffer_size ? free_buffer_size:recv_size;
					c->wrecvbuf[i].iov_len = free_buffer_size;
					c->wrecvbuf[i].iov_base = buf->buf + pos;
					recv_size -= free_buffer_size;
					pos += free_buffer_size;
					if(recv_size && pos >= buf->capacity)
					{
						pos = 0;
						if(!buf->next)
							buf->next = buffer_create_and_acquire(NULL,BUFFER_SIZE);
						buf = buf->next;
					}
					++i;
				}while(recv_size);
				c->recv_overlap.m_super.iovec_count = i;
				c->recv_overlap.m_super.iovec = c->wrecvbuf;
				if(total_size >= BUFFER_SIZE)
				{
					Post_Recv(c->socket,&c->recv_overlap.m_super);
					return;
				}
				else
					bytestransfer = Recv(c->socket,&c->recv_overlap.m_super,&err_code);
			}while(bytestransfer > 0);
		}
	}while(1);
}
void SocketManager::MainLoop() {
    // remove evironment values passed by systemd
    sd_listen_fds(1);

    // Daemon is ready to work.
    sd_notify(0, "READY=1");

    m_working = true;
    while(m_working) {
        fd_set readSet = m_readSet;
        fd_set writeSet = m_writeSet;

        timeval localTempTimeout;
        timeval *ptrTimeout = &localTempTimeout;

        // I need to extract timeout from priority_queue.
        // Timeout in priority_queue may be deprecated.
        // I need to find some actual one.
        while(!m_timeoutQueue.empty()) {
            auto &top = m_timeoutQueue.top();
            auto &desc = m_socketDescriptionVector[top.sock];

            if (top.time == desc.timeout) {
                // This timeout matches timeout from socket.
                // It can be used.
                break;
            } else {
                // This socket was used after timeout in priority queue was set up.
                // We need to update timeout and find some useable one.
                Timeout tm = { desc.timeout , top.sock};
                m_timeoutQueue.pop();
                m_timeoutQueue.push(tm);
            }
        }

        if (m_timeoutQueue.empty()) {
            LogDebug("No usaable timeout found.");
            ptrTimeout = NULL; // select will wait without timeout
        } else {
            time_t currentTime = time(NULL);
            auto &pqTimeout = m_timeoutQueue.top();

            // 0 means that select won't block and socket will be closed ;-)
            ptrTimeout->tv_sec =
              currentTime < pqTimeout.time ? pqTimeout.time - currentTime : 0;
            ptrTimeout->tv_usec = 0;
//            LogDebug("Set up timeout: " << (int)ptrTimeout->tv_sec
//                << " seconds. Socket: " << pqTimeout.sock);
        }

        int ret = select(m_maxDesc+1, &readSet, &writeSet, NULL, ptrTimeout);

        if (0 == ret) { // timeout
            Assert(!m_timeoutQueue.empty());

            Timeout pqTimeout = m_timeoutQueue.top();
            m_timeoutQueue.pop();

            auto &desc = m_socketDescriptionVector[pqTimeout.sock];

            if (!desc.isTimeout || !desc.isOpen) {
                // Connection was closed. Timeout is useless...
                desc.isTimeout = false;
                continue;
            }

            if (pqTimeout.time < desc.timeout) {
                // Is it possible?
                // This socket was used after timeout. We need to update timeout.
                pqTimeout.time = desc.timeout;
                m_timeoutQueue.push(pqTimeout);
                continue;
            }

            // timeout from m_timeoutQueue matches with socket.timeout
            // and connection is open. Time to close it!
            // Putting new timeout in queue here is pointless.
            desc.isTimeout = false;
            CloseSocket(pqTimeout.sock);

            // All done. Now we should process next select ;-)
            continue;
        }

        if (-1 == ret) {
            switch(errno) {
            case EINTR:
                LogDebug("EINTR in select");
                break;
            default:
                int err = errno;
                LogError("Error in select: " << strerror(err));
                return;
            }
            continue;
        }
        for(int i = 0; i<m_maxDesc+1 && ret; ++i) {
            if (FD_ISSET(i, &readSet)) {
                ReadyForRead(i);
                --ret;
            }
            if (FD_ISSET(i, &writeSet)) {
                ReadyForWrite(i);
                --ret;
            }
        }
        ProcessQueue();
    }
}
void Sys_Net_DeleteSocket(struct SysNetData *netdata, struct SysSocket *socket)
{
	CloseSocket(socket->s);
	FreeVec(socket);
}
Beispiel #8
0
void client_test(void* args)
{
    SOCKET_T sockfd = 0;

    CYASSL_METHOD*  method  = 0;
    CYASSL_CTX*     ctx     = 0;
    CYASSL*         ssl     = 0;
    
#ifdef TEST_RESUME
    CYASSL*         sslResume = 0;
    CYASSL_SESSION* session = 0;
    char         resumeMsg[] = "resuming cyassl!";
    int          resumeSz    = sizeof(resumeMsg);
#endif

    char msg[64] = "hello cyassl!";
    char reply[1024];
    int  input;
    int  msgSz = strlen(msg);

    int   port   = yasslPort;
    char* host   = (char*)yasslIP;
    char* domain = "www.yassl.com";

    int    ch;
    int    version = CLIENT_DEFAULT_VERSION;
    int    usePsk   = 0;
    int    sendGET  = 0;
    int    benchmark = 0;
    int    doDTLS    = 0;
    int    matchName = 0;
    int    doPeerCheck = 1;
    char*  cipherList = NULL;
    char*  verifyCert = (char*)caCert;
    char*  ourCert    = (char*)cliCert;
    char*  ourKey     = (char*)cliKey;

    int     argc = ((func_args*)args)->argc;
    char**  argv = ((func_args*)args)->argv;

    ((func_args*)args)->return_code = -1; /* error state */

    while ((ch = mygetopt(argc, argv, "?gdusmh:p:v:l:A:c:k:b:")) != -1) {
        switch (ch) {
            case '?' :
                Usage();
                exit(EXIT_SUCCESS);

            case 'g' :
                sendGET = 1;
                break;

            case 'd' :
                doPeerCheck = 0;
                break;

            case 'u' :
                doDTLS  = 1;
                version = -1;  /* DTLS flag */
                break;

            case 's' :
                usePsk = 1;
                break;

            case 'm' :
                matchName = 1;
                break;

            case 'h' :
                host   = myoptarg;
                domain = myoptarg;
                break;

            case 'p' :
                port = atoi(myoptarg);
                break;

            case 'v' :
                version = atoi(myoptarg);
                if (version < 0 || version > 3) {
                    Usage();
                    exit(MY_EX_USAGE);
                }
                if (doDTLS)
                    version = -1;   /* DTLS flag */
                break;

            case 'l' :
                cipherList = myoptarg;
                break;

            case 'A' :
                verifyCert = myoptarg;
                break;

            case 'c' :
                ourCert = myoptarg;
                break;

            case 'k' :
                ourKey = myoptarg;
                break;

            case 'b' :
                benchmark = atoi(myoptarg);
                if (benchmark < 0 || benchmark > 1000000) {
                    Usage();
                    exit(MY_EX_USAGE);
                }
                break;

            default:
                Usage();
                exit(MY_EX_USAGE);
        }
    }

    argc -= myoptind;
    argv += myoptind;
    myoptind = 0;      /* reset for test cases */

    switch (version) {
        case 0:
            method = CyaSSLv3_client_method();
            break;

        case 1:
            method = CyaTLSv1_client_method();
            break;

        case 2:
            method = CyaTLSv1_1_client_method();
            break;

        case 3:
            method = CyaTLSv1_2_client_method();
            break;

#ifdef CYASSL_DTLS
        case -1:
            method = CyaDTLSv1_client_method();
            break;
#endif

        default:
            err_sys("Bad SSL version");
    }

    if (method == NULL)
        err_sys("unable to get method");

    ctx = CyaSSL_CTX_new(method);
    if (ctx == NULL)
        err_sys("unable to get ctx");

    if (cipherList)
        if (CyaSSL_CTX_set_cipher_list(ctx, cipherList) != SSL_SUCCESS)
            err_sys("can't set cipher list");

#ifndef NO_PSK
    if (usePsk)
        CyaSSL_CTX_set_psk_client_callback(ctx, my_psk_client_cb);
#endif

#ifdef OPENSSL_EXTRA
    CyaSSL_CTX_set_default_passwd_cb(ctx, PasswordCallBack);
#endif

#if defined(CYASSL_SNIFFER) && !defined(HAVE_NTRU) && !defined(HAVE_ECC)
    /* don't use EDH, can't sniff tmp keys */
    if (cipherList == NULL)
        if (CyaSSL_CTX_set_cipher_list(ctx, "AES256-SHA") != SSL_SUCCESS)
            err_sys("can't set cipher list");
#endif

#ifdef USER_CA_CB
    CyaSSL_CTX_SetCACb(ctx, CaCb);
#endif

#ifdef VERIFY_CALLBACK
    CyaSSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, myVerify);
#endif

    if (CyaSSL_CTX_use_certificate_file(ctx, ourCert, SSL_FILETYPE_PEM)
                                     != SSL_SUCCESS)
        err_sys("can't load client cert file, check file and run from"
                " CyaSSL home dir");

    if (CyaSSL_CTX_use_PrivateKey_file(ctx, ourKey, SSL_FILETYPE_PEM)
                                     != SSL_SUCCESS)
        err_sys("can't load client cert file, check file and run from"
                " CyaSSL home dir");    

    if (CyaSSL_CTX_load_verify_locations(ctx, verifyCert, 0) != SSL_SUCCESS)
            err_sys("can't load ca file, Please run from CyaSSL home dir");

    if (doPeerCheck == 0)
        CyaSSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, 0);

    if (benchmark) {
        /* time passed in number of connects give average */
        int times = benchmark;
        int i = 0;

        double start = current_time(), avg;

        for (i = 0; i < times; i++) {
            tcp_connect(&sockfd, host, port, doDTLS);
            ssl = CyaSSL_new(ctx);
            CyaSSL_set_fd(ssl, sockfd);
            if (CyaSSL_connect(ssl) != SSL_SUCCESS)
                err_sys("SSL_connect failed");

            CyaSSL_shutdown(ssl);
            CyaSSL_free(ssl);
            CloseSocket(sockfd);
        }
        avg = current_time() - start;
        avg /= times;
        avg *= 1000;   /* milliseconds */
        printf("CyaSSL_connect avg took: %8.3f milliseconds\n", avg);

        CyaSSL_CTX_free(ctx);
        ((func_args*)args)->return_code = 0;

        exit(EXIT_SUCCESS);
    }

    tcp_connect(&sockfd, host, port, doDTLS);
    ssl = CyaSSL_new(ctx);
    if (ssl == NULL)
        err_sys("unable to get SSL object");
    CyaSSL_set_fd(ssl, sockfd);
#ifdef HAVE_CRL
    if (CyaSSL_EnableCRL(ssl, CYASSL_CRL_CHECKALL) != SSL_SUCCESS)
        err_sys("can't enable crl check");
    if (CyaSSL_LoadCRL(ssl, crlPemDir, SSL_FILETYPE_PEM, 0) != SSL_SUCCESS)
        err_sys("can't load crl, check crlfile and date validity");
    if (CyaSSL_SetCRL_Cb(ssl, CRL_CallBack) != SSL_SUCCESS)
        err_sys("can't set crl callback");
#endif
    if (matchName && doPeerCheck)
        CyaSSL_check_domain_name(ssl, domain);
#ifdef NON_BLOCKING
    tcp_set_nonblocking(&sockfd);
    NonBlockingSSL_Connect(ssl);
#else
    #ifndef CYASSL_CALLBACKS
        if (CyaSSL_connect(ssl) != SSL_SUCCESS) {/* see note at top of README */
            int  err = CyaSSL_get_error(ssl, 0);
            char buffer[80];
            printf("err = %d, %s\n", err, CyaSSL_ERR_error_string(err, buffer));
            err_sys("SSL_connect failed");/* if you're getting an error here  */
        }
    #else
        timeout.tv_sec  = 2;
        timeout.tv_usec = 0;
        NonBlockingSSL_Connect(ssl);  /* will keep retrying on timeout */
    #endif
#endif
    showPeer(ssl);

    if (sendGET) {
        printf("SSL connect ok, sending GET...\n");
        msgSz = 28;
        strncpy(msg, "GET /index.html HTTP/1.0\r\n\r\n", msgSz);
    }
    if (CyaSSL_write(ssl, msg, msgSz) != msgSz)
        err_sys("SSL_write failed");

    input = CyaSSL_read(ssl, reply, sizeof(reply));
    if (input > 0) {
        reply[input] = 0;
        printf("Server response: %s\n", reply);

        if (sendGET) {  /* get html */
            while (1) {
                input = CyaSSL_read(ssl, reply, sizeof(reply));
                if (input > 0) {
                    reply[input] = 0;
                    printf("%s\n", reply);
                }
                else
                    break;
            }
        }
    }
  
#ifdef TEST_RESUME
    if (doDTLS) {
        strncpy(msg, "break", 6);
        msgSz = (int)strlen(msg);
        /* try to send session close */
        CyaSSL_write(ssl, msg, msgSz);
    }
    session   = CyaSSL_get_session(ssl);
    sslResume = CyaSSL_new(ctx);
#endif

    if (doDTLS == 0)            /* don't send alert after "break" command */
        CyaSSL_shutdown(ssl);  /* echoserver will interpret as new conn */
    CyaSSL_free(ssl);
    CloseSocket(sockfd);

#ifdef TEST_RESUME
    if (doDTLS) {
        #ifdef USE_WINDOWS_API 
            Sleep(500);
        #else
            sleep(1);
        #endif
    }
    tcp_connect(&sockfd, host, port, doDTLS);
    CyaSSL_set_fd(sslResume, sockfd);
    CyaSSL_set_session(sslResume, session);
   
    showPeer(sslResume);
#ifdef NON_BLOCKING
    tcp_set_nonblocking(&sockfd);
    NonBlockingSSL_Connect(sslResume);
#else
    #ifndef CYASSL_CALLBACKS
        if (CyaSSL_connect(sslResume) != SSL_SUCCESS)
            err_sys("SSL resume failed");
    #else
        timeout.tv_sec  = 2;
        timeout.tv_usec = 0;
        NonBlockingSSL_Connect(ssl);  /* will keep retrying on timeout */
    #endif
#endif

#ifdef OPENSSL_EXTRA
    if (CyaSSL_session_reused(sslResume))
        printf("reused session id\n");
    else
        printf("didn't reuse session id!!!\n");
#endif
  
    if (CyaSSL_write(sslResume, resumeMsg, resumeSz) != resumeSz)
        err_sys("SSL_write failed");

#ifdef NON_BLOCKING
    /* need to give server a chance to bounce a message back to client */
    #ifdef USE_WINDOWS_API
        Sleep(500);
    #else
        sleep(1);
    #endif
#endif

    input = CyaSSL_read(sslResume, reply, sizeof(reply));
    if (input > 0) {
        reply[input] = 0;
        printf("Server resume response: %s\n", reply);
    }

    /* try to send session break */
    CyaSSL_write(sslResume, msg, msgSz); 

    CyaSSL_shutdown(sslResume);
    CyaSSL_free(sslResume);
#endif /* TEST_RESUME */

    CyaSSL_CTX_free(ctx);
    CloseSocket(sockfd);

    ((func_args*)args)->return_code = 0;
}
Beispiel #9
0
int testserver(void) {
    unsigned int sockaddr;
    unsigned char mysocket;
    unsigned int rsize;

    mysocket = 0; // magic number! declare the socket number we will use (0-3)
    sockaddr = 0x400;//W5100_SKT_BASE(mysocket); // calc address of W5100 register set for this socket

    /*
     *  The main loop.  Control stays in this loop forever, processing any received packets
     *  and sending any requested data.
     */
    while (1) {
        LATAbits.LATA0 ^= 1;
        int x = w5100_read(sockaddr + W5100_SR_OFFSET);
        switch (x) // based on current status of socket...
        {
            case W5100_SKT_SR_CLOSED: // if socket is closed...
                LATBbits.LATB8 = 0;
                if (OpenSocket(mysocket, W5100_SKT_MR_TCP, HTTP_PORT) == mysocket) // if successful opening a socket...
                {
                    Listen(mysocket);
                    __delay_ms(1);
                }
                break;

            case W5100_SKT_SR_ESTABLISHED: // if socket connection is established...
                LATBbits.LATB8 = 1;
                rsize = ReceivedSize(mysocket); // find out how many bytes
                if (rsize > 0) {
                    if (Receive(mysocket, buf, rsize) != W5100_OK) break; // if we had problems, all done
                    /*
                     *  Add code here to process the payload from the packet.
                     *
                     *  For now, we just ignore the payload and send a canned HTML page so the client at least
                     *  knows we are alive.
                     */
                    strcpy((char *) buf, "HTTP/1.0 200 OK\r\nContent-Type: text/html\r\nPragma: no-cache\r\n\r\n");
                    strcat((char *) buf, "<html>\r\n<body>\r\n");
                    strcat((char *) buf, "<title>Phil's W5100 web server (ATmega644p)</title>\r\n");
                    strcat((char *) buf, "<h2>Phil's ATmega644p web server using Wiznet W5100 chip</h2>\r\n");
                    strcat((char *) buf, "<br /><hr>\r\n");
                    if (Send(mysocket, buf, strlen((char *) buf)) == W5100_FAIL) break; // just throw out the packet for now

                    strcpy((char *) buf, "This is part 2 of the page.");
                    strcat((char *) buf, "</body>\r\n</html>\r\n");
                    if (Send(mysocket, buf, strlen((char *) buf)) == W5100_FAIL) break; // just throw out the packet for now

                    DisconnectSocket(mysocket);
                } else // no data yet...
                {
                    __delay_us(10);
                }
                break;

            case W5100_SKT_SR_FIN_WAIT:
            case W5100_SKT_SR_CLOSING:
            case W5100_SKT_SR_TIME_WAIT:
            case W5100_SKT_SR_CLOSE_WAIT:
            case W5100_SKT_SR_LAST_ACK:
                CloseSocket(mysocket);
                break;
        }
    }

    return 0;
}
Beispiel #10
0
int network::start()
{
	int count = 0;
	for (int i=0; i<3; i++) {
		SOCKET sock = socket(AF_INETX, SOCK_STREAM, IPPROTO_TCP);
		if (sock == INVALID_SOCKET) {
#ifdef WIN32
			DEBUG("%s (%i) :: Could not create socket (%d)\n", __FILE__, __LINE__, WSAGetLastError());
#else
			DEBUG("%s (%i) :: Could not create socket (%d)\n", __FILE__, __LINE__, errno);
#endif
			continue;
		}

		struct sockaddr_in sa;
		sa.sin_family = AF_INET;
		ushort port = 0;
		switch (i) {
			case 2 :
				port = Sharun->Settings.Net.Ports.Bridge;
				break;
			case 1 :
				port = Sharun->Settings.Net.Ports.Httpd;
				if (port == Sharun->Settings.Net.Ports.Game)
					port = 0;
				break;
			default :
				port = Sharun->Settings.Net.Ports.Game;
		}
		if (!port) {
			CloseSocket(&sock);
			continue;
		}
		sa.sin_port = htons(port);
		if (Sharun->Settings.Net.localhost)
			sa.sin_addr.s_addr = inet_addr("127.0.0.1");
		else
			sa.sin_addr.s_addr = INADDR_ANY;

		int sockopt = 1;
		setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)&sockopt, sizeof(int));

		if (bind(sock, (SOCKADDR *)&sa, sizeof(sa)) == SOCKET_ERROR) {
#ifdef WIN32
			DEBUG("%s (%i) :: Could not bind socket (%i - %d)\n", __FILE__, __LINE__, port, WSAGetLastError());
#else
			DEBUG("%s (%i) :: Could not bind socket (%i - %d)\n", __FILE__, __LINE__, port, errno);
#endif
			CloseSocket(&sock);
			continue;
		}

		if (listen(sock, 100) == SOCKET_ERROR) {
#ifdef WIN32
			DEBUG("%s (%i) :: Could not listen socket (%i - %d)\n", __FILE__, __LINE__, port, WSAGetLastError());
#else
			DEBUG("%s (%i) :: Could not listen socket (%i - %d)\n", __FILE__, __LINE__, port, errno);
#endif
			CloseSocket(&sock);
			continue;
		}

		count++;
		new connexion_list(sock, (port_type)i);
		DEBUG("%s (%i) :: Network Started (%s : %i).\n", __FILE__, __LINE__, Sharun->Settings.Net.localhost ? "localhost" : "ANY", port);
	}
	for (int i=0; count && Sharun->Settings.Thread.Httpd > 1 && i < Sharun->Settings.Thread.Httpd; i++) {
		thread_list *thread = new thread_list();
		if (!thread->start((void*)HttpD_Thread, thread))
			DEBUG("%s (%i) :: Could not start Httpd thread %i !\n", __FILE__, __LINE__, i);
		else
			DEBUG("%s (%i) :: Httpd thread %i started.\n", __FILE__, __LINE__, i);
	}
	return count;
}
void UrRealtimeCommunication::run() {
	uint8_t buf[2048];
	int bytes_read;
	memset(buf, 0, 2048);
	struct timeval timeout;
	fd_set readfds;
	FD_ZERO(&readfds);
	FD_SET(sockfd_, &readfds);
	print_debug("Realtime port: Got connection");
	connected_ = true;
	while (keepalive_) {
		while (connected_ && keepalive_) {
			timeout.tv_sec = 0; //do this each loop as selects modifies timeout
			timeout.tv_usec = 500000; // timeout of 0.5 sec
			select(sockfd_ + 1, &readfds, NULL, NULL, &timeout);
			bytes_read = recv(sockfd_, (char*) buf, 2048, 0);
			if (bytes_read > 0) {
				setsockopt(sockfd_, IPPROTO_TCP, TCP_NODELAY, (char *) &flag_, sizeof(int));
				robot_state_->unpack(buf);
				if (safety_count_ == safety_count_max_) {
					setSpeed(0., 0., 0., 0., 0., 0.);
				}
				safety_count_ += 1;
			} else {
				connected_ = false;
				CloseSocket(sockfd_);
			}
		}
		if (keepalive_) {
			//reconnect
            ofLog()<<"Realtime port: No connection. Is controller crashed? Will try to reconnect in 10 seconds..."<<endl;
			sockfd_ = socket(AF_INET, SOCK_STREAM, 0);
			if (sockfd_ < 0) {
				print_fatal("ERROR opening socket");
			}
			flag_ = 1;
			setsockopt(sockfd_, IPPROTO_TCP, TCP_NODELAY, (char *) &flag_,
					sizeof(int));
			setsockopt(sockfd_, IPPROTO_TCP, TCP_NODELAY, (char *) &flag_, 
					sizeof(int));
	
			setsockopt(sockfd_, SOL_SOCKET, SO_REUSEADDR, (char *) &flag_,
					sizeof(int));
			SetNonBlocking(sockfd_, true);
			while (keepalive_ && !connected_) {
				std::this_thread::sleep_for(std::chrono::seconds(10));
				fd_set writefds;

				connect(sockfd_, (struct sockaddr *) &serv_addr_,
						sizeof(serv_addr_));
				FD_ZERO(&writefds);
				FD_SET(sockfd_, &writefds);
				select(sockfd_ + 1, NULL, &writefds, NULL, NULL);
				int flag_len;
				getsockopt(sockfd_, SOL_SOCKET, SO_ERROR, (char*)&flag_, &flag_len);
				if (flag_ < 0) {
					print_error("Error re-connecting to RT port 30003. Is controller started? Will try to reconnect in 10 seconds...");
				} else {
					connected_ = true;
					print_info("Realtime port: Reconnected");
				}
			}
		}
	}
	setSpeed(0., 0., 0., 0., 0., 0.);
	CloseSocket(sockfd_);
}
Beispiel #12
0
THREAD_RETURN WOLFSSL_THREAD client_test(void* args)
{
    SOCKET_T sockfd = 0;

    WOLFSSL_METHOD*  method  = 0;
    WOLFSSL_CTX*     ctx     = 0;
    WOLFSSL*         ssl     = 0;
    
    WOLFSSL*         sslResume = 0;
    WOLFSSL_SESSION* session = 0;
    char         resumeMsg[] = "resuming wolfssl!";
    int          resumeSz    = sizeof(resumeMsg);

    char msg[32] = "hello wolfssl!";   /* GET may make bigger */
    char reply[80];
    int  input;
    int  msgSz = (int)strlen(msg);

    word16 port   = yasslPort;
    char* host   = (char*)yasslIP;
    const char* domain = "www.yassl.com";

    int    ch;
    int    version = CLIENT_INVALID_VERSION;
    int    usePsk   = 0;
    int    useAnon  = 0;
    int    sendGET  = 0;
    int    benchmark = 0;
    int    doDTLS    = 0;
    int    matchName = 0;
    int    doPeerCheck = 1;
    int    nonBlocking = 0;
    int    resumeSession = 0;
    int    scr           = 0;    /* allow secure renegotiation */
    int    forceScr      = 0;    /* force client initiaed scr */
    int    trackMemory   = 0;
    int    useClientCert = 1;
    int    fewerPackets  = 0;
    int    atomicUser    = 0;
    int    pkCallbacks   = 0;
    int    overrideDateErrors = 0;
    char*  cipherList = NULL;
    const char* verifyCert = caCert;
    const char* ourCert    = cliCert;
    const char* ourKey     = cliKey;

#ifdef HAVE_SNI
    char*  sniHostName = NULL;
#endif
#ifdef HAVE_MAX_FRAGMENT
    byte maxFragment = 0;
#endif
#ifdef HAVE_TRUNCATED_HMAC
    byte  truncatedHMAC = 0;
#endif


#ifdef HAVE_OCSP
    int    useOcsp  = 0;
    char*  ocspUrl  = NULL;
#endif

    int     argc = ((func_args*)args)->argc;
    char**  argv = ((func_args*)args)->argv;

    ((func_args*)args)->return_code = -1; /* error state */

#ifdef NO_RSA
    verifyCert = (char*)eccCert;
    ourCert    = (char*)cliEccCert;
    ourKey     = (char*)cliEccKey;
#endif
    (void)resumeSz;
    (void)session;
    (void)sslResume;
    (void)trackMemory;
    (void)atomicUser;
    (void)pkCallbacks;
    (void)scr;
    (void)forceScr;

    StackTrap();

    while ((ch = mygetopt(argc, argv,
                          "?gdDusmNrRitfxUPh:p:v:l:A:c:k:b:zS:L:ToO:a")) != -1) {
        switch (ch) {
            case '?' :
                Usage();
                exit(EXIT_SUCCESS);

            case 'g' :
                sendGET = 1;
                break;

            case 'd' :
                doPeerCheck = 0;
                break;

            case 'D' :
                overrideDateErrors = 1;
                break;

            case 'u' :
                doDTLS  = 1;
                break;

            case 's' :
                usePsk = 1;
                break;

            case 't' :
            #ifdef USE_WOLFSSL_MEMORY
                trackMemory = 1;
            #endif
                break;

            case 'm' :
                matchName = 1;
                break;

            case 'x' :
                useClientCert = 0;
                break;

            case 'f' :
                fewerPackets = 1;
                break;

            case 'U' :
            #ifdef ATOMIC_USER
                atomicUser = 1;
            #endif
                break;

            case 'P' :
            #ifdef HAVE_PK_CALLBACKS 
                pkCallbacks = 1;
            #endif
                break;

            case 'h' :
                host   = myoptarg;
                domain = myoptarg;
                break;

            case 'p' :
                port = (word16)atoi(myoptarg);
                #if !defined(NO_MAIN_DRIVER) || defined(USE_WINDOWS_API)
                    if (port == 0)
                        err_sys("port number cannot be 0");
                #endif
                break;

            case 'v' :
                version = atoi(myoptarg);
                if (version < 0 || version > 3) {
                    Usage();
                    exit(MY_EX_USAGE);
                }
                break;

            case 'l' :
                cipherList = myoptarg;
                break;

            case 'A' :
                verifyCert = myoptarg;
                break;

            case 'c' :
                ourCert = myoptarg;
                break;

            case 'k' :
                ourKey = myoptarg;
                break;

            case 'b' :
                benchmark = atoi(myoptarg);
                if (benchmark < 0 || benchmark > 1000000) {
                    Usage();
                    exit(MY_EX_USAGE);
                }
                break;

            case 'N' :
                nonBlocking = 1;
                break;

            case 'r' :
                resumeSession = 1;
                break;

            case 'R' :
                #ifdef HAVE_SECURE_RENEGOTIATION
                    scr = 1;
                #endif
                break;

            case 'i' :
                #ifdef HAVE_SECURE_RENEGOTIATION
                    scr      = 1;
                    forceScr = 1;
                #endif
                break;

            case 'z' :
                #ifndef WOLFSSL_LEANPSK
                    wolfSSL_GetObjectSize();
                #endif
                break;

            case 'S' :
                #ifdef HAVE_SNI
                    sniHostName = myoptarg;
                #endif
                break;

            case 'L' :
                #ifdef HAVE_MAX_FRAGMENT
                    maxFragment = atoi(myoptarg);
                    if (maxFragment < WOLFSSL_MFL_2_9 ||
                                                maxFragment > WOLFSSL_MFL_2_13) {
                        Usage();
                        exit(MY_EX_USAGE);
                    }
                #endif
                break;

            case 'T' :
                #ifdef HAVE_TRUNCATED_HMAC
                    truncatedHMAC = 1;
                #endif
                break;

            case 'o' :
                #ifdef HAVE_OCSP
                    useOcsp = 1;
                #endif
                break;

            case 'O' :
                #ifdef HAVE_OCSP
                    useOcsp = 1;
                    ocspUrl = myoptarg;
                #endif
                break;

            case 'a' :
                #ifdef HAVE_ANON
                    useAnon = 1;
                #endif
                break;

            default:
                Usage();
                exit(MY_EX_USAGE);
        }
    }

    myoptind = 0;      /* reset for test cases */

    /* sort out DTLS versus TLS versions */
    if (version == CLIENT_INVALID_VERSION) {
        if (doDTLS)
            version = CLIENT_DTLS_DEFAULT_VERSION;
        else
            version = CLIENT_DEFAULT_VERSION;
    }
    else {
        if (doDTLS) {
            if (version == 3)
                version = -2;
            else
                version = -1;
        }
    }

#ifdef USE_WOLFSSL_MEMORY
    if (trackMemory)
        InitMemoryTracker(); 
#endif

    switch (version) {
#ifndef NO_OLD_TLS
        case 0:
            method = wolfSSLv3_client_method();
            break;
                
                
    #ifndef NO_TLS
        case 1:
            method = wolfTLSv1_client_method();
            break;

        case 2:
            method = wolfTLSv1_1_client_method();
            break;
    #endif /* NO_TLS */
                
#endif  /* NO_OLD_TLS */
                
#ifndef NO_TLS
        case 3:
            method = wolfTLSv1_2_client_method();
            break;
#endif

#ifdef WOLFSSL_DTLS
        case -1:
            method = wolfDTLSv1_client_method();
            break;

        case -2:
            method = wolfDTLSv1_2_client_method();
            break;
#endif

        default:
            err_sys("Bad SSL version");
            break;
    }

    if (method == NULL)
        err_sys("unable to get method");

    ctx = wolfSSL_CTX_new(method);
    if (ctx == NULL)
        err_sys("unable to get ctx");

    if (cipherList)
        if (wolfSSL_CTX_set_cipher_list(ctx, cipherList) != SSL_SUCCESS)
            err_sys("client can't set cipher list 1");

#ifdef WOLFSSL_LEANPSK
    usePsk = 1;
#endif

#if defined(NO_RSA) && !defined(HAVE_ECC)
    usePsk = 1;
#endif

    if (fewerPackets)
        wolfSSL_CTX_set_group_messages(ctx);

    if (usePsk) {
#ifndef NO_PSK
        wolfSSL_CTX_set_psk_client_callback(ctx, my_psk_client_cb);
        if (cipherList == NULL) {
            const char *defaultCipherList;
            #ifdef HAVE_NULL_CIPHER
                defaultCipherList = "PSK-NULL-SHA256";
            #else
                defaultCipherList = "PSK-AES128-CBC-SHA256";
            #endif
            if (wolfSSL_CTX_set_cipher_list(ctx,defaultCipherList) !=SSL_SUCCESS)
                err_sys("client can't set cipher list 2");
        }
#endif
        useClientCert = 0;
    }

    if (useAnon) {
#ifdef HAVE_ANON
        if (cipherList == NULL) {
            wolfSSL_CTX_allow_anon_cipher(ctx);
            if (wolfSSL_CTX_set_cipher_list(ctx,"ADH-AES128-SHA") != SSL_SUCCESS)
                err_sys("client can't set cipher list 4");
        }
#endif
        useClientCert = 0;
    }

#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER)
    wolfSSL_CTX_set_default_passwd_cb(ctx, PasswordCallBack);
#endif

#if defined(WOLFSSL_SNIFFER) && !defined(HAVE_NTRU) && !defined(HAVE_ECC)
    if (cipherList == NULL) {
        /* don't use EDH, can't sniff tmp keys */
        if (wolfSSL_CTX_set_cipher_list(ctx, "AES256-SHA256") != SSL_SUCCESS) {
            err_sys("client can't set cipher list 3");
        }
    }
#endif

#ifdef HAVE_OCSP
    if (useOcsp) {
        if (ocspUrl != NULL) {
            wolfSSL_CTX_SetOCSP_OverrideURL(ctx, ocspUrl);
            wolfSSL_CTX_EnableOCSP(ctx, WOLFSSL_OCSP_NO_NONCE
                                                    | WOLFSSL_OCSP_URL_OVERRIDE);
        }
        else
            wolfSSL_CTX_EnableOCSP(ctx, WOLFSSL_OCSP_NO_NONCE);
    }
#endif

#ifdef USER_CA_CB
    wolfSSL_CTX_SetCACb(ctx, CaCb);
#endif

#ifdef VERIFY_CALLBACK
    wolfSSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, myVerify);
#endif
#if !defined(NO_FILESYSTEM) && !defined(NO_CERTS)
    if (useClientCert){
        if (wolfSSL_CTX_use_certificate_chain_file(ctx, ourCert) != SSL_SUCCESS)
            err_sys("can't load client cert file, check file and run from"
                    " wolfSSL home dir");

        if (wolfSSL_CTX_use_PrivateKey_file(ctx, ourKey, SSL_FILETYPE_PEM)
                                         != SSL_SUCCESS)
            err_sys("can't load client private key file, check file and run "
                    "from wolfSSL home dir");
    }

    if (!usePsk && !useAnon) {
        if (wolfSSL_CTX_load_verify_locations(ctx, verifyCert, 0) != SSL_SUCCESS)
                err_sys("can't load ca file, Please run from wolfSSL home dir");
    }
#endif
#if !defined(NO_CERTS)
    if (!usePsk && !useAnon && doPeerCheck == 0)
        wolfSSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, 0);
    if (!usePsk && !useAnon && overrideDateErrors == 1)
        wolfSSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, myDateCb);
#endif

#ifdef HAVE_CAVIUM
    wolfSSL_CTX_UseCavium(ctx, CAVIUM_DEV_ID);
#endif

#ifdef HAVE_SNI
    if (sniHostName)
        if (wolfSSL_CTX_UseSNI(ctx, 0, sniHostName, XSTRLEN(sniHostName))
                                                                 != SSL_SUCCESS)
            err_sys("UseSNI failed");
#endif
#ifdef HAVE_MAX_FRAGMENT
    if (maxFragment)
        if (wolfSSL_CTX_UseMaxFragment(ctx, maxFragment) != SSL_SUCCESS)
            err_sys("UseMaxFragment failed");
#endif
#ifdef HAVE_TRUNCATED_HMAC
    if (truncatedHMAC)
        if (wolfSSL_CTX_UseTruncatedHMAC(ctx) != SSL_SUCCESS)
            err_sys("UseTruncatedHMAC failed");
#endif
#ifdef HAVE_SESSION_TICKET
    if (wolfSSL_CTX_UseSessionTicket(ctx) != SSL_SUCCESS)
        err_sys("UseSessionTicket failed");
#endif

    if (benchmark) {
        /* time passed in number of connects give average */
        int times = benchmark;
        int i = 0;

        double start = current_time(), avg;

        for (i = 0; i < times; i++) {
            tcp_connect(&sockfd, host, port, doDTLS);

            ssl = wolfSSL_new(ctx);
            wolfSSL_set_fd(ssl, sockfd);
            if (wolfSSL_connect(ssl) != SSL_SUCCESS)
                err_sys("SSL_connect failed");

            wolfSSL_shutdown(ssl);
            wolfSSL_free(ssl);
            CloseSocket(sockfd);
        }
        avg = current_time() - start;
        avg /= times;
        avg *= 1000;   /* milliseconds */
        printf("wolfSSL_connect avg took: %8.3f milliseconds\n", avg);

        wolfSSL_CTX_free(ctx);
        ((func_args*)args)->return_code = 0;

        exit(EXIT_SUCCESS);
    }
    
    #if defined(WOLFSSL_MDK_ARM)
    wolfSSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, 0);
    #endif
    
    ssl = wolfSSL_new(ctx);
    if (ssl == NULL)
        err_sys("unable to get SSL object");
    #ifdef HAVE_SESSION_TICKET
    wolfSSL_set_SessionTicket_cb(ssl, sessionTicketCB, (void*)"initial session");
    #endif
    if (doDTLS) {
        SOCKADDR_IN_T addr;
        build_addr(&addr, host, port, 1);
        wolfSSL_dtls_set_peer(ssl, &addr, sizeof(addr));
        tcp_socket(&sockfd, 1);
    }
    else {
        tcp_connect(&sockfd, host, port, 0);
    }

#ifdef HAVE_POLY1305
    /* use old poly to connect with google server */
    if (!XSTRNCMP(domain, "www.google.com", 14)) {
        if (wolfSSL_use_old_poly(ssl, 1) != 0)
            err_sys("unable to set to old poly");
    }
#endif

    wolfSSL_set_fd(ssl, sockfd);
#ifdef HAVE_CRL
    if (wolfSSL_EnableCRL(ssl, WOLFSSL_CRL_CHECKALL) != SSL_SUCCESS)
        err_sys("can't enable crl check");
    if (wolfSSL_LoadCRL(ssl, crlPemDir, SSL_FILETYPE_PEM, 0) != SSL_SUCCESS)
        err_sys("can't load crl, check crlfile and date validity");
    if (wolfSSL_SetCRL_Cb(ssl, CRL_CallBack) != SSL_SUCCESS)
        err_sys("can't set crl callback");
#endif
#ifdef HAVE_SECURE_RENEGOTIATION
    if (scr) {
        if (wolfSSL_UseSecureRenegotiation(ssl) != SSL_SUCCESS)
            err_sys("can't enable secure renegotiation");
    }
#endif
#ifdef ATOMIC_USER
    if (atomicUser)
        SetupAtomicUser(ctx, ssl);
#endif
#ifdef HAVE_PK_CALLBACKS
    if (pkCallbacks)
        SetupPkCallbacks(ctx, ssl);
#endif
    if (matchName && doPeerCheck)
        wolfSSL_check_domain_name(ssl, domain);
#ifndef WOLFSSL_CALLBACKS
    if (nonBlocking) {
        wolfSSL_set_using_nonblock(ssl, 1);
        tcp_set_nonblocking(&sockfd);
        NonBlockingSSL_Connect(ssl);
    }
    else if (wolfSSL_connect(ssl) != SSL_SUCCESS) {
        /* see note at top of README */
        int  err = wolfSSL_get_error(ssl, 0);
        char buffer[WOLFSSL_MAX_ERROR_SZ];
        printf("err = %d, %s\n", err,
                                wolfSSL_ERR_error_string(err, buffer));
        err_sys("SSL_connect failed");
        /* if you're getting an error here  */
    }
#else
    timeout.tv_sec  = 2;
    timeout.tv_usec = 0;
    NonBlockingSSL_Connect(ssl);  /* will keep retrying on timeout */
#endif
    showPeer(ssl);

#ifdef HAVE_SECURE_RENEGOTIATION
    if (scr && forceScr) {
        if (nonBlocking) {
            printf("not doing secure renegotiation on example with"
                   " nonblocking yet");
        } else {
            #ifndef NO_SESSION_CACHE
                if (resumeSession) {
                    session = wolfSSL_get_session(ssl);
                    wolfSSL_set_session(ssl, session);
                    resumeSession = 0;  /* only resume once */
                }
            #endif
            if (wolfSSL_Rehandshake(ssl) != SSL_SUCCESS) {
                int  err = wolfSSL_get_error(ssl, 0);
                char buffer[WOLFSSL_MAX_ERROR_SZ];
                printf("err = %d, %s\n", err,
                                wolfSSL_ERR_error_string(err, buffer));
                err_sys("wolfSSL_Rehandshake failed");
            }
        }
    }
#endif /* HAVE_SECURE_RENEGOTIATION */

    if (sendGET) {
        printf("SSL connect ok, sending GET...\n");
        msgSz = 28;
        strncpy(msg, "GET /index.html HTTP/1.0\r\n\r\n", msgSz);
        msg[msgSz] = '\0';
    }
    if (wolfSSL_write(ssl, msg, msgSz) != msgSz)
        err_sys("SSL_write failed");

    input = wolfSSL_read(ssl, reply, sizeof(reply)-1);
    if (input > 0) {
        reply[input] = 0;
        printf("Server response: %s\n", reply);

        if (sendGET) {  /* get html */
            while (1) {
                input = wolfSSL_read(ssl, reply, sizeof(reply)-1);
                if (input > 0) {
                    reply[input] = 0;
                    printf("%s\n", reply);
                }
                else
                    break;
            }
        }
    }
    else if (input < 0) {
        int readErr = wolfSSL_get_error(ssl, 0);
        if (readErr != SSL_ERROR_WANT_READ)
            err_sys("wolfSSL_read failed");
    }

#ifndef NO_SESSION_CACHE
    if (resumeSession) {
        if (doDTLS) {
            strncpy(msg, "break", 6);
            msgSz = (int)strlen(msg);
            /* try to send session close */
            wolfSSL_write(ssl, msg, msgSz);
        }
        session   = wolfSSL_get_session(ssl);
        sslResume = wolfSSL_new(ctx);
    }
#endif

    if (doDTLS == 0)            /* don't send alert after "break" command */
        wolfSSL_shutdown(ssl);  /* echoserver will interpret as new conn */
#ifdef ATOMIC_USER
    if (atomicUser)
        FreeAtomicUser(ssl);
#endif
    wolfSSL_free(ssl);
    CloseSocket(sockfd);

#ifndef NO_SESSION_CACHE
    if (resumeSession) {
        if (doDTLS) {
            SOCKADDR_IN_T addr;
            #ifdef USE_WINDOWS_API 
                Sleep(500);
            #elif defined(WOLFSSL_TIRTOS)
                Task_sleep(1);
            #else
                sleep(1);
            #endif
            build_addr(&addr, host, port, 1);
            wolfSSL_dtls_set_peer(sslResume, &addr, sizeof(addr));
            tcp_socket(&sockfd, 1);
        }
        else {
            tcp_connect(&sockfd, host, port, 0);
        }
        wolfSSL_set_fd(sslResume, sockfd);
        wolfSSL_set_session(sslResume, session);
#ifdef HAVE_SESSION_TICKET
        wolfSSL_set_SessionTicket_cb(sslResume, sessionTicketCB,
                                    (void*)"resumed session");
#endif
       
        showPeer(sslResume);
#ifndef WOLFSSL_CALLBACKS
        if (nonBlocking) {
            wolfSSL_set_using_nonblock(sslResume, 1);
            tcp_set_nonblocking(&sockfd);
            NonBlockingSSL_Connect(sslResume);
        }
        else if (wolfSSL_connect(sslResume) != SSL_SUCCESS)
            err_sys("SSL resume failed");
#else
        timeout.tv_sec  = 2;
        timeout.tv_usec = 0;
        NonBlockingSSL_Connect(ssl);  /* will keep retrying on timeout */
#endif

        if (wolfSSL_session_reused(sslResume))
            printf("reused session id\n");
        else
            printf("didn't reuse session id!!!\n");

        if (wolfSSL_write(sslResume, resumeMsg, resumeSz) != resumeSz)
            err_sys("SSL_write failed");

        if (nonBlocking) {
            /* give server a chance to bounce a message back to client */
            #ifdef USE_WINDOWS_API
                Sleep(500);
            #elif defined(WOLFSSL_TIRTOS)
                Task_sleep(1);
            #else
                sleep(1);
            #endif
        }

        input = wolfSSL_read(sslResume, reply, sizeof(reply)-1);
        if (input > 0) {
            reply[input] = 0;
            printf("Server resume response: %s\n", reply);
        }

        /* try to send session break */
        wolfSSL_write(sslResume, msg, msgSz); 

        wolfSSL_shutdown(sslResume);
        wolfSSL_free(sslResume);
        CloseSocket(sockfd);
    }
#endif /* NO_SESSION_CACHE */

    wolfSSL_CTX_free(ctx);

    ((func_args*)args)->return_code = 0;

#ifdef USE_WOLFSSL_MEMORY
    if (trackMemory)
        ShowMemoryTracker();
#endif /* USE_WOLFSSL_MEMORY */

#if !defined(WOLFSSL_TIRTOS)
    return 0;
#endif
}
Beispiel #13
0
int OnDoorRequest(char *host_name, int host_port, char *pData, int nDataSize)
{
	/*
	SOCKADDR_IN		saServer;
	LPHOSTENT		lphostent;
	WSADATA			wsadata;
	SOCKET			hsocket;
	*/
	char             		ipaddr[16];
    int                     rsocket = -1;
    struct sockaddr_in      daddr;
    struct timeval          TimeOut;
    int 					nFlag;

	int						nRet;

	memset( ipaddr, 0x00, 16 );


#if	1
    //nRet = GetDnsIp( host_name, ipaddr );
	//Textout("Server = [%s], IPADDR = [%s]", host_name, ipaddr);
	
	//ipaddr[0] = 0;
#else
	strcpy(ipaddr, "183.232.25.234");
#endif

	if(jpush_address[0] != 0){
		strcpy(ipaddr, jpush_address);
	}
	else
	{
		strcpy(ipaddr, "183.232.25.234");
	}
	Textout("jpush ipaddr:%s",ipaddr);
	
    rsocket = InitSocket( 0, 1, NULL );             //tcp
    nFlag = 1;
    setsockopt( rsocket, IPPROTO_TCP, TCP_NODELAY, ( void* )&nFlag, sizeof( int ) );
    TimeOut.tv_sec = 30;
    TimeOut.tv_usec = 0;
    setsockopt( rsocket, SOL_SOCKET, SO_RCVTIMEO, ( char* )&TimeOut, sizeof( TimeOut ) );
    TimeOut.tv_sec = 30;
    TimeOut.tv_usec = 0;
    setsockopt( rsocket, SOL_SOCKET, SO_SNDTIMEO, ( char* )&TimeOut, sizeof( TimeOut ) );
    bzero( &daddr, sizeof( struct sockaddr_in ) );

	daddr.sin_family        = AF_INET;
    daddr.sin_port          = htons(host_port);
    daddr.sin_addr.s_addr   = inet_addr( ipaddr );


	nRet = connect( rsocket, ( struct sockaddr* )&daddr, sizeof( struct sockaddr ) );
	if(nRet == -1)	//SOCKET_ERROR)
	{
		Textout( "Can't connect %s",host_name);
        CloseSocket( rsocket );
		return -1;
	}
	else
	{

		Textout("connected   with host %s",host_name);
	}

	nRet = send(rsocket, pData, nDataSize, 0);
	if(nRet == -1)	//SOCKET_ERROR)
	{
		Textout( "Can't Send");
        CloseSocket( rsocket );
		return -1;
	}
	else
	{
		Textout("send() OK");
		//Textout("pData:%s",pData);
	}

	char   dest[1024];
	nRet=0;
	
	nRet=recv(rsocket,(char *)dest,sizeof(dest),0);
	
	if(nRet>0)
	{
		dest[nRet]=0;

		

		if(strstr(dest,"Succeed") == NULL )
		{
			nRet = -1;
			Textout("Received bytes:%d",nRet);
			printf("Result:%s\n",dest);
		}
		else
		{
			printf("jPush send Succeed!\n");
			nRet = 0;
		}
	}
	else
	{
		printf("jPush not recv data! ");
		dest[0]=0;
		nRet = -1;
	}

	CloseSocket(rsocket);
	return nRet;
}
Beispiel #14
0
int WebRequest::Request
(
    int request_type
    , std::string url_host
    , int url_port
    , std::string url_path
    , std::string data
)
{
	bool secure = false;
	
    mMessageHeader = "";
	mMessageBody.clear();
    // temp fix for POST recognition
    data = "_start_=1&" + data + "&_end_=1";
    
    mReadSize = 1024;
    mError = 0;
	
	if(request_type == HTTPS_GET
	   || request_type == HTTPS_POST
	   || request_type == HTTPS_PUT
	   || request_type == HTTPS_DELETE)
	{
		secure = true;		
	}

    #ifdef WIN32
    WSADATA wsa;
	// startup winsock
    mError = WSAStartup(MAKEWORD(2,0),&wsa);
	if(mError)
	{
	  printf("Error in Startup = %d\n", mError);
      return -1;
	}
    #endif

	// socket 
	int socket = 0;

    // struct for socket
	struct sockaddr_in host_addr = {0};

	// information about host
	struct hostent *host = {0};

	// request of client
    std::string request;
    
	// SSL context
	SSL_CTX *sslContext = NULL;

	// SSL socket
	SSL *sslSocket = NULL;

	// get IP from name host
	host = gethostbyname(url_host.c_str());

	if (host == NULL) 
	{
	  printf("Unknown Host %s\n", url_host.c_str());
	  return -1;
	}

	// create socket TCP
	socket = ::socket(PF_INET, SOCK_STREAM, 0);

	if (socket < 0) 
	{
	  printf("Socket Error\n");
	  return -1;
	}

	// create host struct
	host_addr.sin_family = AF_INET;
	// set IP addres
	host_addr.sin_addr = *((struct in_addr *)host->h_addr);
	// set HTTP port
	host_addr.sin_port = htons(url_port);

    // connect
    mError = connect(socket, (struct sockaddr *)&host_addr, sizeof(host_addr));
	
	if (mError == -1) 
	{
	  CloseSocket(socket);
	  printf("Connection Error\n");
	  return -1;
	}

    if(secure)
    {
        // init OpenSSL
	    SSL_load_error_strings();
	    SSL_library_init();

	    // create context 
	    sslContext = SSL_CTX_new(SSLv23_client_method());

	    //create ssl socket
	    sslSocket = SSL_new(sslContext);
	    if(!sslSocket) 
	    {
	      CloseSocket(socket);
	      printf("SSL creation error\n");
	      return -1;
	    }

        // join sslSocket and socket
	    SSL_set_fd(sslSocket, socket);

	    // conect sslSocket
	    mError = SSL_connect(sslSocket);

	    if(!mError) 
	    {
	      CloseSocket(socket);
	      printf("SSL connect error = %d\n", mError);
	      mError = SSL_get_error(sslSocket, mError);
	      printf("SSL error: %d\n", mError);
          //std::cin.get();
	      return -1;
	    }
    }

    if(request_type == HTTP_GET || request_type == HTTPS_GET)
    {
	    //create get request
        request = "GET " + url_path + " HTTP/1.0\nHost: " + url_host + " \r\n\r\n";	  
    }
    else if(request_type == HTTP_POST || request_type == HTTPS_POST)
    {
	    //create get request
	    request = "POST " + url_path + " HTTP/1.0\nHost: " + url_host + "\nContent-Length: " + to_string(data.length()) + "\nContent-Type: application/x-www-form-urlencoded\n" + "\r\n\r\n" + data + "\r\n";	  
    }
    // TODO add DELETE and PUT
    // send data to server

    if(secure)
    {
        mError = SSL_write(sslSocket, request.c_str(), strlen(request.c_str()));
    }
    else
    {
        mError = send(socket, request.c_str(), strlen(request.c_str()), 0);
    }

	

    // read in header and body

    char bufferHeader[1];
    int readHeader;
    int lineLength;
    bool loop = true;
    bool bHeader = false;

    // header
    
    mMessageHeader = "";

    while(loop) {
        if(secure)
            readHeader = SSL_read(sslSocket, bufferHeader, 1);
        else
            readHeader = recv(socket, bufferHeader, 1, 0);
        if(readHeader < 0) loop = false;
        if(bufferHeader[0]=='\n') {
           if(lineLength == 0) loop = false;

           lineLength = 0;
           if(mMessageHeader.find("200") != std::string::npos)
               bHeader = true;

        }
        else if(bufferHeader[0]!='\r') lineLength++;

        mMessageHeader += bufferHeader[0];
    }

    // body

    mMessageBody.clear();

    if(bHeader) {
        unsigned char bufferBody[1024];
        if(secure)
        {
            while((readHeader = SSL_read(sslSocket, bufferBody, sizeof(bufferBody))) > 0)  
            {
				mMessageBody.insert(mMessageBody.end(), bufferBody, bufferBody + readHeader);
            }
        }
        else
        {
            while((readHeader = recv(socket, (char*)bufferBody, sizeof(bufferBody), 0)) > 0)  
            {
				mMessageBody.insert(mMessageBody.end(), bufferBody, bufferBody + readHeader);
            }
        }
    }

    if(secure)
    {
        switch(SSL_get_error( sslSocket, mReadSize ))
        {
	        case SSL_ERROR_ZERO_RETURN: printf( "\n\nSSL::ZERO\n\n" );  break;
            case SSL_ERROR_NONE:        printf( "\n\nSSL::No Error\n\n" );	break;
            case SSL_ERROR_SSL:         printf( "\n\nSSL::SSL ERROR\n\n" ); break;
        }
    }

    #if WIN32
 	    Sleep(1);   
    #else
 	    sleep(1); 
    #endif

    if(secure)
    {
	    //close SSLsocket
        SSL_shutdown(sslSocket);
	    //free memory
        SSL_free(sslSocket);
	    // free context
        SSL_CTX_free(sslContext);
    }

    //close scoket
    CloseSocket(socket);

    return 0;
}
Beispiel #15
0
void * ClientRecevier::run(void * arg)
{
	if (NULL == arg) {
		return reinterpret_cast<void *>(-error::INVALIDSOCKARG);
	}
	SockClientRecviveParams * scr = (SockClientRecviveParams *)arg;
	/* Dump */
	int sockfd = scr->sockfd();
	ClientHandler * clientHandler = scr->clientHandler();
	SockDidFinish fb;
	fb.fd = sockfd;/* Fill FI sockfd */
	bool teminate = clientHandler->shouldTeminateRecv(sockfd);
	uint8_t * buf = new uint8_t[4096];
	SockRecved rcv;
	rcv.fd = sockfd;
	memcpy(&(rcv.info), scr->from(), sizeof(NetProtocol));
	int ret;
	while (0 == teminate) {
		memset(buf, 0, 4096);
		ret = RecvFromSockfd(
			sockfd, buf, 0, 4096, 15 * 1e6, 15 * 1e6);
		if ((ret < 0) && (ret > -1000)) {
			fb.code = ret;/* Fail */
			ShutdownSocket(sockfd, shutdownhow::RDWR);
			CloseSocket(sockfd);
			clientHandler->didFinish(fb);
			goto end;
		} else if (0 == ret) {
			/* disconnected */
			fb.code = 0;
			ShutdownSocket(sockfd, shutdownhow::RDWR);
			CloseSocket(sockfd);
			clientHandler->didFinish(fb);
			goto end;
		} else if (ret > 0) {
			/* success */
			rcv.data = buf;
			rcv.count = ret;
			clientHandler->didReceive(rcv);
		} else {
			/* < -1000 timeout */
		}
		teminate = clientHandler->shouldTeminateRecv(sockfd);
	}
	fb.code = 1;/* user terminate */
	ShutdownSocket(sockfd, shutdownhow::RDWR);
	CloseSocket(sockfd);
	clientHandler->didFinish(fb);
end:
	if (NULL != scr) {
		delete scr;
		scr = NULL;
	}
	if (NULL != buf) {
		delete[] buf;
		buf = NULL;
	}
	if (NULL != clientHandler) {
		if (NULL != clientHandler->gc()) {
			clientHandler->gc()->gc(clientHandler);
		}
		/* else has released */
		clientHandler = NULL;
	}

	return (void *)0;/* success */
}
Beispiel #16
0
void
NfcConsumer::OnConnectError()
{
    CHROMIUM_LOG("NFC: %s\n", __FUNCTION__);
    CloseSocket();
}
Beispiel #17
0
/*
 * NAME
 *   run - connect thread routine
 * DESC
 *  - When success: delete arg
 *  - When fail: arg valid => delete arg, clientHandler valid => delete clientHandler
 */
void * ConnectToServerBySockfd::run(void * arg)
{
	/* Check */
	if (NULL == arg) {
		return (void *)-error::INVALIDSOCKARG;
	}
	/* Dump */
	SockConnParams * cps = static_cast<SockConnParams *>(arg);
	ClientHandler * clientHandler = cps->clientHandler();
	if (NULL == clientHandler) {
		delete cps;
		cps = NULL;
		return (void *)-error::NOCLICB;
	}
	/* Real dump*/
	ConnectHandler conHandler;
	int sockfd;
	NetProtocol target;
	if (0x00000001 != this->ver()) {
		sockfd = cps->sockfd();
		memcpy(&target, cps->target(), sizeof(NetProtocol));
		memcpy(&(conHandler.info), &target, sizeof(NetProtocol));
		conHandler.sockfd = sockfd;
	} else {
		sockfd = -1;
	}
	uint32_t timeout = cps->timeout();
	conHandler.code = 0;
	int code = 0;
	char msg[128];
	std::string ip;
	struct timeval tv_select;
	int ret;
	fd_set fdwrite;
	SockClientRecviveParams * rcvparams = NULL;
	do {
		if (0x00000001 == this->ver()) {
			ip = cps->ip();
			strncpy(target.ip, ip.c_str(), OYWS_MAXIPLEN);
			target.port = cps->port();
			snprintf(msg, 127, "To connect server: %s:%u", target.ip,
				target.port);
			msg[127] = '\0';
			OYWL_INFOSTR(msg);
			/* FIXME valid ip first */
			sockfd = GetSockfdByHost(target);
			if (sockfd < 0) {
				goto retry_later;
			} else {
				memcpy(&(conHandler.info), &target, sizeof(NetProtocol));
				conHandler.sockfd = sockfd;
			}
		}
		/* Wait(select) writeable */
		FD_ZERO(&fdwrite);
		FD_SET(sockfd, &fdwrite);
		tv_select.tv_sec = timeout;
		tv_select.tv_usec = 0;
		ret = select(sockfd + 1, NULL, &fdwrite, NULL, &tv_select);
		/* FIXME: handle EINTR here and other .. (block)
		 * or EAGAIN of noneblock */
		if (ret < 0) {
			ret = errno;
			code = -ret;
			if (0x00000001 == this->ver()) {
				goto retry_later;
			} else {
				goto select_fail;
			}
		} else if (0 == ret) {
			/* timeout */
			code = -ETIMEDOUT;
			if (0x00000001 == this->ver()) {
				goto retry_later;
			} else {
				goto select_to;
			}
		} else {
			/* final check sokcet error */
			int errlen = sizeof(ret);
#			if !defined(WIN32)
			getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &ret,
				(socklen_t *)&errlen);
#			else
			getsockopt(sockfd, SOL_SOCKET, SO_ERROR,
				reinterpret_cast<char *>(&ret),
				(socklen_t *)&errlen);
#			endif

			if (0 != ret) {
				/* connect fail */
				errno = ret;
				code = -ret;
				snprintf(msg, 127, "FAIL: select: %s", strerror(ret));
				msg[127] = '\0';
				if (0x00000001 == this->ver()) {
					goto retry_later;
				} else {
					goto select_fail;
				}
			}
		}
		break;/* ok */
retry_later:
		if (sockfd > 0) {
			CloseSocket(sockfd);
			sockfd = -1;
		}
		usleep(10 * 1e6);
		usleep(10 * 1e6);
		usleep(10 * 1e6);
	} while(true);
	/* Final ok */
#	if defined(__APPLE__)
	{
	int set = 1;
	setsockopt(sockfd, SOL_SOCKET, SO_NOSIGPIPE, (void *)&set, sizeof(int));
	}
#	endif /* defined(__APPLE__) */
	{
	rcvparams = new SockClientRecviveParams(sockfd, clientHandler, target);
	/* start on received thread */
	ret = ClientHelper::startReceiveFromPeer(rcvparams);
	if (0 != ret) {
		OYWL_ERRSN("startReceiveFromPeer() fail", ret);
		code = ret;
		delete rcvparams;
		rcvparams = NULL;
	} else {
		/* success */
		code = 0;
	}
	rcvparams = NULL;
	}
	/* Feedback */
	conHandler.code = code;
	clientHandler->didConnect(conHandler);
	if (0 != code) {
		OYWL_SN0("Will delete clientHandler by code", code);
		delete clientHandler;
		clientHandler = NULL;
	}
	/* Final delete */
	if (NULL != cps) {
		OYWL_S0("Will delete cps");
		delete cps;
		cps = NULL;
	}
	return reinterpret_cast<void *>(0);/* Success */
select_to:
select_fail:
	if (NULL != clientHandler) {
		conHandler.code = code;
		clientHandler->didConnect(conHandler);
		OYWL_S0("Will delete clientHandler by not nil");
		delete clientHandler;
		clientHandler = NULL;
	}
	if (NULL != rcvparams) {
		delete rcvparams;
		rcvparams = NULL;
	}
	/* Final delete */
	if (NULL != cps) {
		OYWL_S0("Will delete cps");
		delete cps;
		cps = NULL;
	}
	return (void *)-1;
}
Beispiel #18
0
void echoclient_test(void* args)
{
    SOCKET_T sockfd = 0;

    FILE* fin  = stdin;
    FILE* fout = stdout;

    int inCreated  = 0;
    int outCreated = 0;

    char send[1024];
    char reply[1024];

    SSL_METHOD* method = 0;
    SSL_CTX*    ctx    = 0;
    SSL*        ssl    = 0;

    int sendSz;
    int argc    = 0;
    char** argv = 0;

    ((func_args*)args)->return_code = -1; /* error state */
    argc = ((func_args*)args)->argc;
    argv = ((func_args*)args)->argv;

    if (argc >= 2) {
        fin  = fopen(argv[1], "r"); 
        inCreated = 1;
    }
    if (argc >= 3) {
        fout = fopen(argv[2], "w");
        outCreated = 1;
    }

    if (!fin)  err_sys("can't open input file");
    if (!fout) err_sys("can't open output file");

    tcp_connect(&sockfd, yasslIP, yasslPort);

#if defined(CYASSL_DTLS)
    method  = DTLSv1_client_method();
#elif  !defined(NO_TLS)
    method = TLSv1_client_method();
#else
    method = SSLv3_client_method();
#endif
    ctx    = SSL_CTX_new(method);

#ifndef NO_FILESYSTEM
    if (SSL_CTX_load_verify_locations(ctx, caCert, 0) != SSL_SUCCESS)
        err_sys("can't load ca file");
    #ifdef HAVE_ECC
        if (SSL_CTX_load_verify_locations(ctx, eccCert, 0) != SSL_SUCCESS)
            err_sys("can't load ca file");
    #endif
#else
    load_buffer(ctx, caCert, CYASSL_CA);
#endif

#ifdef OPENSSL_EXTRA
    SSL_CTX_set_default_passwd_cb(ctx, PasswordCallBack);
#endif
    ssl = SSL_new(ctx);

    SSL_set_fd(ssl, sockfd);
#if defined(USE_WINDOWS_API) && defined(CYASSL_DTLS) && defined(NO_MAIN_DRIVER)
    /* let echoserver bind first, TODO: add Windows signal like pthreads does */
    Sleep(100);
#endif
    if (SSL_connect(ssl) != SSL_SUCCESS) err_sys("SSL_connect failed");

    while (fgets(send, sizeof(send), fin)) {

        sendSz = (int)strlen(send) + 1;

        if (SSL_write(ssl, send, sendSz) != sendSz)
            err_sys("SSL_write failed");

        if (strncmp(send, "quit", 4) == 0) {
            fputs("sending server shutdown command: quit!\n", fout);
            break;
        }

        if (strncmp(send, "break", 4) == 0) {
            fputs("sending server session close: break!\n", fout);
            break;
        }

        while (sendSz) {
            int got;
            if ( (got = SSL_read(ssl, reply, sizeof(reply))) > 0) {
                fputs(reply, fout);
                sendSz -= got;
            }
            else
                break;
        }
    }

#ifdef CYASSL_DTLS
    strncpy(send, "break", 6);
    sendSz = (int)strlen(send);
    /* try to tell server done */
    SSL_write(ssl, send, sendSz);
#else
    SSL_shutdown(ssl);
#endif

    SSL_free(ssl);
    SSL_CTX_free(ctx);

    fflush(fout);
    if (inCreated)  fclose(fin);
    if (outCreated) fclose(fout);

    CloseSocket(sockfd);
    ((func_args*)args)->return_code = 0; 
}
void SocketManager::ProcessQueue() {
    WriteBuffer buffer;
    WriteData data;
    {
        std::lock_guard<std::mutex> ulock(m_eventQueueMutex);
        while (!m_writeBufferQueue.empty()) {
            buffer = m_writeBufferQueue.front();
            m_writeBufferQueue.pop();

            auto &desc = m_socketDescriptionVector[buffer.connectionID.sock];

            if (!desc.isOpen) {
                LogDebug("Received packet for write but connection is closed. Packet ignored!");
                continue;
            }

            if (desc.counter != buffer.connectionID.counter)
            {
                LogDebug("Received packet for write but counter is broken. Packet ignored!");
                continue;
            }

            if (desc.useSendMsg) {
                LogError("Some service tried to push rawdata to socket that usees sendmsg!");
                continue;
            }

            std::copy(
                buffer.rawBuffer.begin(),
                buffer.rawBuffer.end(),
                std::back_inserter(desc.rawBuffer));

            FD_SET(buffer.connectionID.sock, &m_writeSet);
        }

        while(!m_writeDataQueue.empty()) {
            data = m_writeDataQueue.front();
            m_writeDataQueue.pop();

            auto &desc = m_socketDescriptionVector[data.connectionID.sock];

            if (!desc.isOpen) {
                LogDebug("Received packet for sendmsg but connection is closed. Packet ignored!");
                continue;
            }

            if (desc.counter != data.connectionID.counter)
            {
                LogDebug("Received packet for write but counter is broken. Packet ignored!");
                continue;
            }

            if (!desc.useSendMsg) {
                LogError("Some service tries to push SendMsgData to socket that uses write!");
                continue;
            }

            desc.sendMsgDataQueue.push(data.sendMsgData);

            FD_SET(data.connectionID.sock, &m_writeSet);
        }
    }

    while (1) {
        ConnectionID connection;
        {
            std::lock_guard<std::mutex> ulock(m_eventQueueMutex);
            if (m_closeQueue.empty())
                return;
            connection = m_closeQueue.front();
            m_closeQueue.pop();
        }

        if (!m_socketDescriptionVector[connection.sock].isOpen)
            continue;

        if (connection.counter != m_socketDescriptionVector[connection.sock].counter)
            continue;

        CloseSocket(connection.sock);
    }
}
Beispiel #20
0
/*==========================================================================*/
SLPDSocket* SLPDSocketCreateConnected(struct in_addr* addr)
/*                                                                          */
/* addr - (IN) the address of the peer to connect to                        */
/*                                                                          */
/* Returns: A connected socket or a socket in the process of being connected*/
/*          if the socket was connected the SLPDSocket->state will be set   */
/*          to writable.  If the connect would block, SLPDSocket->state will*/
/*          be set to connect.  Return NULL on error                        */
/*==========================================================================*/
{
#ifdef WIN32
    char                lowat;
    u_long              fdflags;
#else
    int                 lowat;
    int                 fdflags;
#endif
    SLPDSocket*         sock = 0;

    sock = SLPDSocketAlloc();
    if(sock == 0)
    {
        goto FAILURE;
    }

    /* create the stream socket */
    sock->fd = socket(PF_INET,SOCK_STREAM,0);
    if(sock->fd < 0)
    {
        goto FAILURE;                        
    }

    /* set the socket to non-blocking */
#ifdef WIN32
    fdflags = 1;
    ioctlsocket(sock->fd, FIONBIO, &fdflags);
#else
    fdflags = fcntl(sock->fd, F_GETFL, 0);
    fcntl(sock->fd,F_SETFL, fdflags | O_NONBLOCK);
#endif  

    /* zero then set peeraddr to connect to */
    sock->peeraddr.sin_family = AF_INET;
    sock->peeraddr.sin_port = htons(SLP_RESERVED_PORT);
    sock->peeraddr.sin_addr = *addr;

    /* set the receive and send buffer low water mark to 18 bytes 
    (the length of the smallest slpv2 message) */
    lowat = 18;
    setsockopt(sock->fd,SOL_SOCKET,SO_RCVLOWAT,&lowat,sizeof(lowat));
    setsockopt(sock->fd,SOL_SOCKET,SO_SNDLOWAT,&lowat,sizeof(lowat));

    /* non-blocking connect */
    if(connect(sock->fd, 
               (struct sockaddr *) &(sock->peeraddr), 
               sizeof(sock->peeraddr)) == 0)
    {
        /* Connection occured immediately */
        sock->state = STREAM_CONNECT_IDLE;
    }
    else
    {
#ifdef WIN32
        if(WSAEWOULDBLOCK == WSAGetLastError())
#else
        if(errno == EINPROGRESS)
#endif
        {
            /* Connect would have blocked */
            sock->state = STREAM_CONNECT_BLOCK;
        }
        else
        {
            goto FAILURE;
        }                                
    }                   

    return sock;

    /* cleanup on failure */
    FAILURE:
    if(sock)
    {
        CloseSocket(sock->fd);
        xfree(sock);
        sock = 0;
    }

    return sock;
}
void EndSignal(int sig){
	DB(fprintf(stderr,"EndSignal()\n"));
	CloseSocket();
	exit(0);
}
Beispiel #22
0
//接收完成函数
bool CServerSocketItem::OnRecvCompleted(COverLappedRecv * pOverLappedRecv, DWORD dwThancferred)
{
	//效验数据
	ASSERT(m_bRecvIng==true);

	//设置变量
	m_bRecvIng=false;
	m_dwRecvTickCount=GetTickCount();

	//判断关闭
	if (m_hSocket==INVALID_SOCKET)
	{
		CloseSocket(m_wRountID);
		return true;
	}

	//接收数据
	int iRetCode=recv(m_hSocket,(char *)m_cbRecvBuf+m_wRecvSize,sizeof(m_cbRecvBuf)-m_wRecvSize,0);
	if (iRetCode<=0)
	{
		CloseSocket(m_wRountID);
		return true;
	}

	//接收完成
	m_wRecvSize+=iRetCode;
	BYTE cbBuffer[SOCKET_BUFFER];
	CMD_Head * pHead=(CMD_Head *)m_cbRecvBuf;

	//处理数据
	try
	{
		while (m_wRecvSize>=sizeof(CMD_Head))
		{
			//效验数据
			WORD wPacketSize=pHead->CmdInfo.wPacketSize;
			if (wPacketSize>SOCKET_BUFFER) throw TEXT("数据包超长");
			if (wPacketSize<sizeof(CMD_Head)) throw TEXT("数据包非法");
			if (pHead->CmdInfo.cbVersion!=SOCKET_VER) throw TEXT("数据包版本错误");
			if (m_wRecvSize<wPacketSize) break;

			//提取数据
			CopyMemory(cbBuffer,m_cbRecvBuf,wPacketSize);
			WORD wRealySize=CrevasseBuffer(cbBuffer,wPacketSize);
			ASSERT(wRealySize>=sizeof(CMD_Head));
			m_dwRecvPacketCount++;

			//解释数据
			WORD wDataSize=wRealySize-sizeof(CMD_Head);
			void * pDataBuffer=cbBuffer+sizeof(CMD_Head);
			CMD_Command Command=((CMD_Head *)cbBuffer)->CommandInfo;

			//内核命令
			if (Command.wMainCmdID==MDM_KN_COMMAND)
			{
				switch (Command.wSubCmdID)
				{
				case SUB_KN_DETECT_SOCKET:	//网络检测
					{
						break;
					}
				default: throw TEXT("非法命令码");
				}
			}
			else 
			{
				//消息处理
				m_pIServerSocketItemSink->OnSocketReadEvent(Command,pDataBuffer,wDataSize,this);			
			}

			//删除缓存数据
			m_wRecvSize-=wPacketSize;
			MoveMemory(m_cbRecvBuf,m_cbRecvBuf+wPacketSize,m_wRecvSize);
		}
	}
	catch (...)
	{ 
		CloseSocket(m_wRountID);
		return false;
	}

	return RecvData();
}
void SampleSocketPort::pending(void)
{
//cerr << "Pending called " << endl;
	if(!m_bOpen)
		return;

	// Read all available bytes into our buffer
	int nBytesAvail = peek(m_pBuf, MAX_RXBUF);
//cerr << "Pending .. " << nBytesAvail << endl;

	if(!m_bReceptionStarted)
	{	//Start the receive timer
		ResetReadTimeout(MAX_RXTIMEOUT);	//Got 'n' seconds to get all the data else we timeout
		m_bReceptionStarted = true;
	}
	else
	{
		if(m_bTimedOut)	//The receive timer has expired...this is a timeout condition
		{
			ResetReadTimeout(MAX_RXTIMEOUT); //Clear the timeout flag
			m_nLastBytesAvail = 0;		//Reset the flags
			m_bReceptionStarted = false;
			OnRxTimeout();	//Do whatever 'we' do for a timeout (probably a flush or disconnect)...
			return;
		}
	}

	if(m_nLastBytesAvail == nBytesAvail)	//Check if any more data has been received since last time
	{										//No point in parsing unless this has changed!
		//Maybe yield in here!
		//Thread::yield();
		if(nBytesAvail == 0)		//If we have been called with 0 bytes available (twice now)
		{							//a disconnection has occurred
			if(!m_bDoDisconnect)
			{
				CloseSocket();	//Force the close
			}
		}
		return;
	}

	//Depending on your application you may want to attempt to process the extra data 
	//(or change your MAX_RXBUF).
	//
	//Here I just flush the whole lot, because I assume a 'legal' client wont send more than
	//we can receive....maybe someone is trying to flood / overrun us!
	if(nBytesAvail > MAX_RXBUF)	
	{
		cerr << "TCP/IP overflow..." << endl;
		FlushRxData();
		m_nLastBytesAvail = 0;
		m_bReceptionStarted = false;
		return;
	}
	m_nLastBytesAvail = nBytesAvail;

	//In this loop you may parse the received data to determine whether a whole
	//'packet' has arrived. What you do in here depends on what data you are sending.
	//Here we will just look for a /r/n terminator sequence.
	for(int i=0; i < nBytesAvail; i++)
	{

/***************************SHOULD BE CUSTOMISED*******************/

		if(m_pBuf[i] == '\r')
		{
			if(i+1 < nBytesAvail)
			{
				if(m_pBuf[i+1] == '\n')
				{	//Terminator sequence found

					/**************************************************************/
					// COMPULSORY ... Clear the flag and count..
					// do this when you have received a good packet
					m_nLastBytesAvail = 0;
					m_bReceptionStarted = false;
					/**************************************************************/

					// Now receive the data into a buffer and call our receive function
					int nLen = i+2;
					char *pszRxData = new char[nLen+1];	//Allow space for terminator
					receive(pszRxData, nLen);		//Receive the data
					pszRxData[nLen] = '\0';		//Terminate it
					OnDataReceived(pszRxData, nLen);
					delete [] pszRxData;
					return;
				}
			}
		}
/***************************END CUSTOMISATION*******************/

	}
}
Beispiel #24
0
int Logger(LISTE *plcs)
{
	int res=0,Comm_err=0,Read_Something=0;
	if (TEST)
	{
		ListePlc(plcs);
		//return(0);
	}
	int now=time(NULL);
	res=BuildSockets(plcs);
	while (!Terminated)
	{
		ELEMENT *elt=GetFirst(plcs);
		while (elt!=NULL)  // PLCs
		{
			PLC *plc=elt->Data;
			/* Something to do ? */
			if (plc->Next_Time>time(NULL))
			{
				elt=GetNext(plcs,elt);			
				continue;
			}
			/* Test Socket */
			if (plc->socket<0)
			{
				if (BuildSocket(plc)<0)
				{
					Log(LOG_WARNING,"Socket unavailable for : %s\n",plc->PlcName);
					plc->Next_Time=now+WAIT_FOR_RECONNECT;
					elt=GetNext(plcs,elt);
					continue;
				} else Log(LOG_INFO,"Socket build for : %s\n",plc->PlcName);
			}
			now=time(NULL);
			Read_Something=0;
			Comm_err=1;
			//plc->Next_Time=now+0.95*MAX_SAMPLE/1000;
			plc->Next_Time=now+MAX_SAMPLE;
			Log(LOG_DEBUG,"Set plc->Next_Time in %d seconds (MAX_SAMPLE : %d)\n",plc->Next_Time-now,MAX_SAMPLE);
			/* Read Tags */
			ELEMENT *elt2=GetFirst(&(plc->Tags));
			while (elt2!=NULL)
			{
				TAG *tag=elt2->Data;
				if ((now-tag->Time_Value)>(1.5*tag->Time_Sample))
					Log(LOG_WARNING,"Time Sample exceed on tag : %s (%s)\n",tag->TagName,plc->PlcName);
				if ((now-tag->Time_Value)>=tag->Time_Sample)
				{
					//Log(LOG_DEBUG,"Reading tag : %s (%s) (%d - %d > %d)\n",tag->TagName,plc->PlcName,now,tag->Time_Value,tag->Time_Sample);
					Read_Something=1;
					res=ReadTag(plc,tag);
					if (res==0) Comm_err=0; // At least one tag is Ok
					if (mb_errno==EPIPE) CloseSocket(plc->socket,plcs);
				}
				if ((tag->Time_Value+tag->Time_Sample)<(plc->Next_Time))
				{
					plc->Next_Time=tag->Time_Value+tag->Time_Sample;
					Log(LOG_DEBUG,"plc->Next_Time in %d seconds*\n",plc->Next_Time-now);
				}
				elt2=GetNext(&(plc->Tags),elt2);
			}
			/* Read Packets */
			elt2=GetFirst(&(plc->Packets));
			while (elt2!=NULL)
			{
				PACKET *packet=elt2->Data;
				if ((now-packet->Time_Value)>(1.5*packet->Time_Sample))
					Log(LOG_WARNING,"Time Sample exceed on packet : %s (%s)\n",packet->BaseAddress,plc->PlcName);
				if ((now-packet->Time_Value)>=packet->Time_Sample)
				{
					Read_Something=1;
					res=ReadPacket(plc,packet);
					if (res>=0) Comm_err=0; // At least one tag is Ok
					if (mb_errno==EPIPE) CloseSocket(plc->socket,plcs);
				}
				if ((packet->Time_Value+packet->Time_Sample)<(plc->Next_Time))
				{
					plc->Next_Time=packet->Time_Value+packet->Time_Sample;
					Log(LOG_DEBUG,"plc->Next_Time in %d seconds\n",plc->Next_Time-now);
				}
				elt2=GetNext(&(plc->Packets),elt2);
			}
			/* Check Plc */
			if (Comm_err && Read_Something) // All Tags & packets are in error
			{
				Log(LOG_WARNING,"All tags in error for : %s suspending for %d seconds\n",plc->PlcName,WAIT_FOR_RECONNECT);
				plc->Next_Time=now+WAIT_FOR_RECONNECT;
			}
			if (plc->Next_Time>0.8*(time(NULL)+MODBUS_SOCK_TIMEOUT))
			{
				close(plc->socket);
				plc->socket=-1;
				Log(LOG_DEBUG,"Closing socket for plc : %s \n",plc->PlcName);
			}			
			elt=GetNext(plcs,elt);
		}
		sleep(1);
	}
	Log(LOG_NOTICE,"Killing Connections\n");
	KillAll(plcs);
	FreeAll(plcs);
	return(0);
}
THREAD_RETURN CYASSL_THREAD echoserver_test(void* args)
{
    SOCKET_T       sockfd = 0;
    CYASSL_METHOD* method = 0;
    CYASSL_CTX*    ctx    = 0;

    int    doDTLS = 0;
    int    doPSK = 0;
    int    outCreated = 0;
    int    shutDown = 0;
    int    useAnyAddr = 0;
    word16 port = yasslPort;
    int    argc = ((func_args*)args)->argc;
    char** argv = ((func_args*)args)->argv;

#ifdef ECHO_OUT
    FILE* fout = stdout;
    if (argc >= 2) {
        fout = fopen(argv[1], "w");
        outCreated = 1;
    }
    if (!fout) err_sys("can't open output file");
#endif
    (void)outCreated;
    (void)argc;
    (void)argv;

    ((func_args*)args)->return_code = -1; /* error state */

#ifdef CYASSL_DTLS
    doDTLS  = 1;
#endif

#ifdef CYASSL_LEANPSK
    doPSK = 1;
#endif

#if defined(NO_RSA) && !defined(HAVE_ECC)
    doPSK = 1;
#endif

    #if defined(NO_MAIN_DRIVER) && !defined(USE_WINDOWS_API) && \
        !defined(CYASSL_SNIFFER) && !defined(CYASSL_MDK_SHELL) && \
        !defined(CYASSL_TIRTOS)
        port = 0;
    #endif
    #if defined(USE_ANY_ADDR)
        useAnyAddr = 1;
    #endif

#ifdef CYASSL_TIRTOS
    fdOpenSession(Task_self());
#endif

    tcp_listen(&sockfd, &port, useAnyAddr, doDTLS);

#if defined(CYASSL_DTLS)
    method  = CyaDTLSv1_server_method();
#elif  !defined(NO_TLS)
    method = CyaSSLv23_server_method();
#else
    method = CyaSSLv3_server_method();
#endif
    ctx    = CyaSSL_CTX_new(method);
    /* CyaSSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF); */

#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER)
    CyaSSL_CTX_set_default_passwd_cb(ctx, PasswordCallBack);
#endif

#ifndef NO_FILESYSTEM
    if (doPSK == 0) {
    #ifdef HAVE_NTRU
        /* ntru */
        if (CyaSSL_CTX_use_certificate_file(ctx, ntruCert, SSL_FILETYPE_PEM)
                != SSL_SUCCESS)
            err_sys("can't load ntru cert file, "
                    "Please run from CyaSSL home dir");

        if (CyaSSL_CTX_use_NTRUPrivateKey_file(ctx, ntruKey)
                != SSL_SUCCESS)
            err_sys("can't load ntru key file, "
                    "Please run from CyaSSL home dir");
    #elif defined(HAVE_ECC)
        /* ecc */
        if (CyaSSL_CTX_use_certificate_file(ctx, eccCert, SSL_FILETYPE_PEM)
                != SSL_SUCCESS)
            err_sys("can't load server cert file, "
                    "Please run from CyaSSL home dir");

        if (CyaSSL_CTX_use_PrivateKey_file(ctx, eccKey, SSL_FILETYPE_PEM)
                != SSL_SUCCESS)
            err_sys("can't load server key file, "
                    "Please run from CyaSSL home dir");
    #elif defined(NO_CERTS)
        /* do nothing, just don't load cert files */
    #else
        /* normal */
        if (CyaSSL_CTX_use_certificate_file(ctx, svrCert, SSL_FILETYPE_PEM)
                != SSL_SUCCESS)
            err_sys("can't load server cert file, "
                    "Please run from CyaSSL home dir");

        if (CyaSSL_CTX_use_PrivateKey_file(ctx, svrKey, SSL_FILETYPE_PEM)
                != SSL_SUCCESS)
            err_sys("can't load server key file, "
                    "Please run from CyaSSL home dir");
    #endif
    } /* doPSK */
#elif !defined(NO_CERTS)
    if (!doPSK) {
        load_buffer(ctx, svrCert, CYASSL_CERT);
        load_buffer(ctx, svrKey,  CYASSL_KEY);
    }
#endif

#if defined(CYASSL_SNIFFER) && !defined(HAVE_NTRU) && !defined(HAVE_ECC)
    /* don't use EDH, can't sniff tmp keys */
    CyaSSL_CTX_set_cipher_list(ctx, "AES256-SHA");
#endif

    if (doPSK) {
#ifndef NO_PSK
        const char *defaultCipherList;

        CyaSSL_CTX_set_psk_server_callback(ctx, my_psk_server_cb);
        CyaSSL_CTX_use_psk_identity_hint(ctx, "cyassl server");
        #ifdef HAVE_NULL_CIPHER
            defaultCipherList = "PSK-NULL-SHA256";
        #else
            defaultCipherList = "PSK-AES128-CBC-SHA256";
        #endif
        if (CyaSSL_CTX_set_cipher_list(ctx, defaultCipherList) != SSL_SUCCESS)
            err_sys("server can't set cipher list 2");
#endif
    }

    SignalReady(args, port);

    while (!shutDown) {
        CYASSL* ssl = 0;
        char    command[SVR_COMMAND_SIZE+1];
        int     echoSz = 0;
        int     clientfd;
        int     firstRead = 1;
        int     gotFirstG = 0;
                
#ifndef CYASSL_DTLS 
        SOCKADDR_IN_T client;
        socklen_t     client_len = sizeof(client);
        clientfd = accept(sockfd, (struct sockaddr*)&client,
                         (ACCEPT_THIRD_T)&client_len);
#else
        clientfd = udp_read_connect(sockfd);
#endif
        if (clientfd == -1) err_sys("tcp accept failed");

        ssl = CyaSSL_new(ctx);
        if (ssl == NULL) err_sys("SSL_new failed");
        CyaSSL_set_fd(ssl, clientfd);
        #ifdef __MORPHOS__
            CyaSSL_set_socketbase(ssl, SocketBase);
        #endif
        #if !defined(NO_FILESYSTEM) && !defined(NO_DH)
            CyaSSL_SetTmpDH_file(ssl, dhParam, SSL_FILETYPE_PEM);
        #elif !defined(NO_DH)
            SetDH(ssl);  /* will repick suites with DHE, higher than PSK */
        #endif
        if (CyaSSL_accept(ssl) != SSL_SUCCESS) {
            printf("SSL_accept failed\n");
            CyaSSL_free(ssl);
            CloseSocket(clientfd);
            continue;
        }
#if defined(PEER_INFO)
        showPeer(ssl);
#endif

        while ( (echoSz = CyaSSL_read(ssl, command, sizeof(command)-1)) > 0) {

            if (firstRead == 1) {
                firstRead = 0;  /* browser may send 1 byte 'G' to start */
                if (echoSz == 1 && command[0] == 'G') {
                    gotFirstG = 1;
                    continue;
                }
            }
            else if (gotFirstG == 1 && strncmp(command, "ET /", 4) == 0) {
                strncpy(command, "GET", 4);
                /* fall through to normal GET */
            }
           
            if ( strncmp(command, "quit", 4) == 0) {
                printf("client sent quit command: shutting down!\n");
                shutDown = 1;
                break;
            }
            if ( strncmp(command, "break", 5) == 0) {
                printf("client sent break command: closing session!\n");
                break;
            }
#ifdef SESSION_STATS
            if ( strncmp(command, "printstats", 10) == 0) {
                PrintSessionStats();
                break;
            }
#endif
            if ( strncmp(command, "GET", 3) == 0) {
                char type[]   = "HTTP/1.0 200 ok\r\nContent-type:"
                                " text/html\r\n\r\n";
                char header[] = "<html><body BGCOLOR=\"#ffffff\">\n<pre>\n";
                char body[]   = "greetings from CyaSSL\n";
                char footer[] = "</body></html>\r\n\r\n";
            
                strncpy(command, type, sizeof(type));
                echoSz = sizeof(type) - 1;

                strncpy(&command[echoSz], header, sizeof(header));
                echoSz += (int)sizeof(header) - 1;
                strncpy(&command[echoSz], body, sizeof(body));
                echoSz += (int)sizeof(body) - 1;
                strncpy(&command[echoSz], footer, sizeof(footer));
                echoSz += (int)sizeof(footer);

                if (CyaSSL_write(ssl, command, echoSz) != echoSz)
                    err_sys("SSL_write failed");
                break;
            }
            command[echoSz] = 0;

            #ifdef ECHO_OUT
                fputs(command, fout);
            #endif

            if (CyaSSL_write(ssl, command, echoSz) != echoSz)
                err_sys("SSL_write failed");
        }
#ifndef CYASSL_DTLS
        CyaSSL_shutdown(ssl);
#endif
        CyaSSL_free(ssl);
        CloseSocket(clientfd);
#ifdef CYASSL_DTLS
        tcp_listen(&sockfd, &port, useAnyAddr, doDTLS);
        SignalReady(args, port);
#endif
    }

    CloseSocket(sockfd);
    CyaSSL_CTX_free(ctx);

#ifdef ECHO_OUT
    if (outCreated)
        fclose(fout);
#endif

    ((func_args*)args)->return_code = 0;

#if defined(NO_MAIN_DRIVER) && defined(HAVE_ECC) && defined(FP_ECC) \
                            && defined(HAVE_THREAD_LS)
    ecc_fp_free();  /* free per thread cache */
#endif

#ifdef CYASSL_TIRTOS
    fdCloseSession(Task_self());
#endif

#ifndef CYASSL_TIRTOS
    return 0;
#endif
}
Beispiel #26
0
THREAD_RETURN CYASSL_THREAD client_test(void* args)
{
    SOCKET_T sockfd = 0;

    CYASSL_METHOD*  method  = 0;
    CYASSL_CTX*     ctx     = 0;
    CYASSL*         ssl     = 0;
    
    CYASSL*         sslResume = 0;
    CYASSL_SESSION* session = 0;
    char         resumeMsg[] = "resuming cyassl!";
    int          resumeSz    = sizeof(resumeMsg);

    char msg[32] = "hello cyassl!";   /* GET may make bigger */
    char reply[80];
    int  input;
    int  msgSz = (int)strlen(msg);

    int   port   = yasslPort;
    char* host   = (char*)yasslIP;
    char* domain = (char*)"www.yassl.com";

    int    ch;
    int    version = CLIENT_INVALID_VERSION;
    int    usePsk   = 0;
    int    sendGET  = 0;
    int    benchmark = 0;
    int    doDTLS    = 0;
    int    matchName = 0;
    int    doPeerCheck = 1;
    int    nonBlocking = 0;
    int    resumeSession = 0;
    int    trackMemory   = 0;
    int    useClientCert = 1;
    int    fewerPackets  = 0;
    char*  cipherList = NULL;
    char*  verifyCert = (char*)caCert;
    char*  ourCert    = (char*)cliCert;
    char*  ourKey     = (char*)cliKey;

#ifdef HAVE_SNI
    char*  sniHostName = NULL;
#endif

    int     argc = ((func_args*)args)->argc;
    char**  argv = ((func_args*)args)->argv;

    ((func_args*)args)->return_code = -1; /* error state */

#ifdef NO_RSA
    verifyCert = (char*)eccCert;
    ourCert    = (char*)cliEccCert;
    ourKey     = (char*)cliEccKey;
#endif
    (void)resumeSz;
    (void)session;
    (void)sslResume;
    (void)trackMemory;

    while ((ch = mygetopt(argc, argv, "?gdusmNrtfxh:p:v:l:A:c:k:b:zS:")) != -1){
        switch (ch) {
            case '?' :
                Usage();
                exit(EXIT_SUCCESS);

            case 'g' :
                sendGET = 1;
                break;

            case 'd' :
                doPeerCheck = 0;
                break;

            case 'u' :
                doDTLS  = 1;
                break;

            case 's' :
                usePsk = 1;
                break;

            case 't' :
            #ifdef USE_CYASSL_MEMORY
                trackMemory = 1;
            #endif
                break;

            case 'm' :
                matchName = 1;
                break;

            case 'x' :
                useClientCert = 0;
                break;

            case 'f' :
                fewerPackets = 1;
                break;

            case 'h' :
                host   = myoptarg;
                domain = myoptarg;
                break;

            case 'p' :
                port = atoi(myoptarg);
                #if !defined(NO_MAIN_DRIVER) || defined(USE_WINDOWS_API)
                    if (port == 0)
                        err_sys("port number cannot be 0");
                #endif
                break;

            case 'v' :
                version = atoi(myoptarg);
                if (version < 0 || version > 3) {
                    Usage();
                    exit(MY_EX_USAGE);
                }
                break;

            case 'l' :
                cipherList = myoptarg;
                break;

            case 'A' :
                verifyCert = myoptarg;
                break;

            case 'c' :
                ourCert = myoptarg;
                break;

            case 'k' :
                ourKey = myoptarg;
                break;

            case 'b' :
                benchmark = atoi(myoptarg);
                if (benchmark < 0 || benchmark > 1000000) {
                    Usage();
                    exit(MY_EX_USAGE);
                }
                break;

            case 'N' :
                nonBlocking = 1;
                break;

            case 'r' :
                resumeSession = 1;
                break;

            case 'z' :
                #ifndef CYASSL_LEANPSK
                    CyaSSL_GetObjectSize();
                #endif
                break;

            case 'S' :
                #ifdef HAVE_SNI
                    sniHostName = myoptarg;
                #endif
                break;

            default:
                Usage();
                exit(MY_EX_USAGE);
        }
    }

    myoptind = 0;      /* reset for test cases */

    /* sort out DTLS versus TLS versions */
    if (version == CLIENT_INVALID_VERSION) {
        if (doDTLS)
            version = CLIENT_DTLS_DEFAULT_VERSION;
        else
            version = CLIENT_DEFAULT_VERSION;
    }
    else {
        if (doDTLS) {
            if (version == 3)
                version = -2;
            else
                version = -1;
        }
    }

#ifdef USE_CYASSL_MEMORY
    if (trackMemory)
        InitMemoryTracker(); 
#endif

    switch (version) {
#ifndef NO_OLD_TLS
        case 0:
            method = CyaSSLv3_client_method();
            break;
                
                
    #ifndef NO_TLS
        case 1:
            method = CyaTLSv1_client_method();
            break;

        case 2:
            method = CyaTLSv1_1_client_method();
            break;
    #endif /* NO_TLS */
                
#endif  /* NO_OLD_TLS */
                
#ifndef NO_TLS
        case 3:
            method = CyaTLSv1_2_client_method();
            break;
#endif

#ifdef CYASSL_DTLS
        case -1:
            method = CyaDTLSv1_client_method();
            break;

        case -2:
            method = CyaDTLSv1_2_client_method();
            break;
#endif

        default:
            err_sys("Bad SSL version");
            break;
    }

    if (method == NULL)
        err_sys("unable to get method");

    ctx = CyaSSL_CTX_new(method);
    if (ctx == NULL)
        err_sys("unable to get ctx");
		
    if (cipherList)
        if (CyaSSL_CTX_set_cipher_list(ctx, cipherList) != SSL_SUCCESS)
            err_sys("client can't set cipher list 1");

#ifdef CYASSL_LEANPSK
    usePsk = 1;
#endif

#if defined(NO_RSA) && !defined(HAVE_ECC)
    usePsk = 1;
#endif

    if (fewerPackets)
        CyaSSL_CTX_set_group_messages(ctx);

    if (usePsk) {
#ifndef NO_PSK
        CyaSSL_CTX_set_psk_client_callback(ctx, my_psk_client_cb);
        if (cipherList == NULL) {
            const char *defaultCipherList;
            #ifdef HAVE_NULL_CIPHER
                defaultCipherList = "PSK-NULL-SHA256";
            #else
                defaultCipherList = "PSK-AES128-CBC-SHA256";
            #endif
            if (CyaSSL_CTX_set_cipher_list(ctx,defaultCipherList) !=SSL_SUCCESS)
                err_sys("client can't set cipher list 2");
        }
#endif
        useClientCert = 0;
    }

#ifdef OPENSSL_EXTRA
    CyaSSL_CTX_set_default_passwd_cb(ctx, PasswordCallBack);
#endif

#if defined(CYASSL_SNIFFER) && !defined(HAVE_NTRU) && !defined(HAVE_ECC)
    if (cipherList == NULL) {
        /* don't use EDH, can't sniff tmp keys */
        if (CyaSSL_CTX_set_cipher_list(ctx, "AES256-SHA256") != SSL_SUCCESS) {
            err_sys("client can't set cipher list 3");
        }
    }
#endif

#ifdef USER_CA_CB
    CyaSSL_CTX_SetCACb(ctx, CaCb);
#endif

#ifdef VERIFY_CALLBACK
    CyaSSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, myVerify);
#endif
#if !defined(NO_FILESYSTEM) && !defined(NO_CERTS)
    if (useClientCert){
        if (CyaSSL_CTX_use_certificate_chain_file(ctx, ourCert) != SSL_SUCCESS)
            err_sys("can't load client cert file, check file and run from"
                    " CyaSSL home dir");

        if (CyaSSL_CTX_use_PrivateKey_file(ctx, ourKey, SSL_FILETYPE_PEM)
                                         != SSL_SUCCESS)
            err_sys("can't load client private key file, check file and run "
                    "from CyaSSL home dir");
    }

    if (!usePsk) {
        if (CyaSSL_CTX_load_verify_locations(ctx, verifyCert, 0) != SSL_SUCCESS)
                err_sys("can't load ca file, Please run from CyaSSL home dir");
    }
#endif
#if !defined(NO_CERTS)
    if (!usePsk && doPeerCheck == 0)
        CyaSSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, 0);
#endif

#ifdef HAVE_CAVIUM
    CyaSSL_CTX_UseCavium(ctx, CAVIUM_DEV_ID);
#endif

#ifdef HAVE_SNI
    if (sniHostName)
        if (CyaSSL_CTX_UseSNI(ctx, 0, sniHostName, XSTRLEN(sniHostName))
                                                                 != SSL_SUCCESS)
            err_sys("UseSNI failed");
#endif

    if (benchmark) {
        /* time passed in number of connects give average */
        int times = benchmark;
        int i = 0;

        double start = current_time(), avg;

        for (i = 0; i < times; i++) {
            tcp_connect(&sockfd, host, port, doDTLS);

            ssl = CyaSSL_new(ctx);
            CyaSSL_set_fd(ssl, sockfd);
            if (CyaSSL_connect(ssl) != SSL_SUCCESS)
                err_sys("SSL_connect failed");

            CyaSSL_shutdown(ssl);
            CyaSSL_free(ssl);
            CloseSocket(sockfd);
        }
        avg = current_time() - start;
        avg /= times;
        avg *= 1000;   /* milliseconds */
        printf("CyaSSL_connect avg took: %8.3f milliseconds\n", avg);

        CyaSSL_CTX_free(ctx);
        ((func_args*)args)->return_code = 0;

        exit(EXIT_SUCCESS);
    }
    
    #if defined(CYASSL_MDK_ARM)
    CyaSSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, 0);
    #endif
    
    ssl = CyaSSL_new(ctx);
    if (ssl == NULL)
        err_sys("unable to get SSL object");

    CyaSSL_set_quiet_shutdown(ssl, 1) ;

    if (doDTLS) {
        SOCKADDR_IN_T addr;
        build_addr(&addr, host, port, 1);
        CyaSSL_dtls_set_peer(ssl, &addr, sizeof(addr));
        tcp_socket(&sockfd, 1);
    }
    else {
        tcp_connect(&sockfd, host, port, 0);
    }
    CyaSSL_set_fd(ssl, sockfd);
#ifdef HAVE_CRL
    if (CyaSSL_EnableCRL(ssl, CYASSL_CRL_CHECKALL) != SSL_SUCCESS)
        err_sys("can't enable crl check");
    if (CyaSSL_LoadCRL(ssl, crlPemDir, SSL_FILETYPE_PEM, 0) != SSL_SUCCESS)
        err_sys("can't load crl, check crlfile and date validity");
    if (CyaSSL_SetCRL_Cb(ssl, CRL_CallBack) != SSL_SUCCESS)
        err_sys("can't set crl callback");
#endif
    if (matchName && doPeerCheck)
        CyaSSL_check_domain_name(ssl, domain);
#ifndef CYASSL_CALLBACKS
    if (nonBlocking) {
        CyaSSL_set_using_nonblock(ssl, 1);
        tcp_set_nonblocking(&sockfd);
        NonBlockingSSL_Connect(ssl);
    }
    else if (CyaSSL_connect(ssl) != SSL_SUCCESS) {
        /* see note at top of README */
        int  err = CyaSSL_get_error(ssl, 0);
        char buffer[80];
        printf("err = %d, %s\n", err,
                                CyaSSL_ERR_error_string(err, buffer));
        err_sys("SSL_connect failed");
        /* if you're getting an error here  */
    }
#else
    timeout.tv_sec  = 2;
    timeout.tv_usec = 0;
    NonBlockingSSL_Connect(ssl);  /* will keep retrying on timeout */
#endif
    showPeer(ssl);

    if (sendGET) {
        printf("SSL connect ok, sending GET...\n");
        msgSz = 28;
        strncpy(msg, "GET /index.html HTTP/1.0\r\n\r\n", msgSz);
        msg[msgSz] = '\0';
    }
    if (CyaSSL_write(ssl, msg, msgSz) != msgSz)
        err_sys("SSL_write failed");

    input = CyaSSL_read(ssl, reply, sizeof(reply)-1);
    if (input > 0) {
        reply[input] = 0;
        printf("Server response: %s", reply);

        if (sendGET && (input == (sizeof(reply)-1))) {  /* get html */
            while (1) {
                input = CyaSSL_read(ssl, reply, sizeof(reply)-1);
                if (input > 0) {
                    reply[input] = 0;
                    printf("%s", reply);
                    if(input < sizeof(reply)-1)
                        break ;
                }
                else
                    break;
            }
        }
        printf("\n");
    }
    else if (input < 0) {
        int readErr = CyaSSL_get_error(ssl, 0);
        if (readErr != SSL_ERROR_WANT_READ)
            err_sys("CyaSSL_read failed");
    }
    
#ifdef CYASSL_CMSIS_RTOS
    osDelay(5000) ;
#endif

#ifndef NO_SESSION_CACHE
    if (resumeSession) {
        if (doDTLS) {
            strncpy(msg, "break", 6);
            msgSz = (int)strlen(msg);
            /* try to send session close */
            CyaSSL_write(ssl, msg, msgSz);
        }
        session   = CyaSSL_get_session(ssl);
        sslResume = CyaSSL_new(ctx);
    }
#endif

    if (doDTLS == 0)            /* don't send alert after "break" command */
        CyaSSL_shutdown(ssl);  /* echoserver will interpret as new conn */
    CyaSSL_free(ssl);
    CloseSocket(sockfd);

#ifndef NO_SESSION_CACHE
    if (resumeSession) {
        if (doDTLS) {
            SOCKADDR_IN_T addr;
            #ifdef USE_WINDOWS_API 
                Sleep(500);
            #else
                sleep(1);
            #endif
            build_addr(&addr, host, port, 1);
            CyaSSL_dtls_set_peer(sslResume, &addr, sizeof(addr));
            tcp_socket(&sockfd, 1);
        }
        else {
            tcp_connect(&sockfd, host, port, 0);
        }
        CyaSSL_set_fd(sslResume, sockfd);
        CyaSSL_set_session(sslResume, session);
       
        showPeer(sslResume);
#ifndef CYASSL_CALLBACKS
        if (nonBlocking) {
            CyaSSL_set_using_nonblock(sslResume, 1);
            tcp_set_nonblocking(&sockfd);
            NonBlockingSSL_Connect(sslResume);
        }
        else if (CyaSSL_connect(sslResume) != SSL_SUCCESS)
            err_sys("SSL resume failed");
#else
        timeout.tv_sec  = 2;
        timeout.tv_usec = 0;
        NonBlockingSSL_Connect(ssl);  /* will keep retrying on timeout */
#endif

        if (CyaSSL_session_reused(sslResume))
            printf("reused session id\n");
        else
            printf("didn't reuse session id!!!\n");

        if (CyaSSL_write(sslResume, resumeMsg, resumeSz) != resumeSz)
            err_sys("SSL_write failed");

        if (nonBlocking) {
            /* give server a chance to bounce a message back to client */
            #ifdef USE_WINDOWS_API
                Sleep(500);
            #else
                sleep(1);
            #endif
        }

        input = CyaSSL_read(sslResume, reply, sizeof(reply)-1);
        if (input > 0) {
            reply[input] = 0;
            printf("Server resume response: %s\n", reply);
        }

        /* try to send session break */
        CyaSSL_write(sslResume, msg, msgSz); 

        CyaSSL_shutdown(sslResume);
        CyaSSL_free(sslResume);
        CloseSocket(sockfd);
    }
#endif /* NO_SESSION_CACHE */

    CyaSSL_CTX_free(ctx);

    ((func_args*)args)->return_code = 0;

#ifdef USE_CYASSL_MEMORY
    if (trackMemory)
        ShowMemoryTracker();
#endif /* USE_CYASSL_MEMORY */

    return 0;
}
Beispiel #27
0
nsUDPSocket::~nsUDPSocket()
{
  CloseSocket();
  MOZ_COUNT_DTOR(nsUDPSocket);
}
Beispiel #28
0
void echoclient_test(void* args)
{
    SOCKET_T sockfd = 0;

    FILE* fin  = stdin;
    FILE* fout = stdout;

    int inCreated  = 0;
    int outCreated = 0;

    char msg[1024];
    char reply[1024+1];

    SSL_METHOD* method = 0;
    SSL_CTX*    ctx    = 0;
    SSL*        ssl    = 0;

    int doDTLS = 0;
    int doPSK = 0;
    int sendSz;
    int argc    = 0;
    char** argv = 0;

    ((func_args*)args)->return_code = -1; /* error state */
    argc = ((func_args*)args)->argc;
    argv = ((func_args*)args)->argv;

    if (argc >= 2) {
        fin  = fopen(argv[1], "r"); 
        inCreated = 1;
    }
    if (argc >= 3) {
        fout = fopen(argv[2], "w");
        outCreated = 1;
    }

    if (!fin)  err_sys("can't open input file");
    if (!fout) err_sys("can't open output file");

#ifdef CYASSL_DTLS
    doDTLS  = 1;
#endif

#ifdef CYASSL_LEANPSK 
    doPSK = 1;
#endif

#if defined(NO_RSA) && !defined(HAVE_ECC)
    doPSK = 1;
#endif

#if defined(CYASSL_DTLS)
    method  = DTLSv1_client_method();
#elif  !defined(NO_TLS)
    method = CyaSSLv23_client_method();
#else
    method = SSLv3_client_method();
#endif
    ctx    = SSL_CTX_new(method);

#ifndef NO_FILESYSTEM
    #ifndef NO_RSA
    if (SSL_CTX_load_verify_locations(ctx, caCert, 0) != SSL_SUCCESS)
        err_sys("can't load ca file, Please run from CyaSSL home dir");
    #endif
    #ifdef HAVE_ECC
        if (SSL_CTX_load_verify_locations(ctx, eccCert, 0) != SSL_SUCCESS)
            err_sys("can't load ca file, Please run from CyaSSL home dir");
    #endif
#elif !defined(NO_CERTS)
    if (!doPSK)
        load_buffer(ctx, caCert, CYASSL_CA);
#endif

#if defined(CYASSL_SNIFFER) && !defined(HAVE_NTRU) && !defined(HAVE_ECC)
    /* don't use EDH, can't sniff tmp keys */
    SSL_CTX_set_cipher_list(ctx, "AES256-SHA");
#endif
    if (doPSK) {
#ifndef NO_PSK
        const char *defaultCipherList;

        CyaSSL_CTX_set_psk_client_callback(ctx, my_psk_client_cb);
        #ifdef HAVE_NULL_CIPHER
            defaultCipherList = "PSK-NULL-SHA256";
        #else
            defaultCipherList = "PSK-AES128-CBC-SHA256";
        #endif
        if (CyaSSL_CTX_set_cipher_list(ctx,defaultCipherList) !=SSL_SUCCESS)
            err_sys("client can't set cipher list 2");
#endif
    }

#ifdef OPENSSL_EXTRA
    SSL_CTX_set_default_passwd_cb(ctx, PasswordCallBack);
#endif
    ssl = SSL_new(ctx);

    if (doDTLS) {
        SOCKADDR_IN_T addr;
        build_addr(&addr, yasslIP, yasslPort);
        CyaSSL_dtls_set_peer(ssl, &addr, sizeof(addr));
        tcp_socket(&sockfd, 1);
    }
    else {
        tcp_connect(&sockfd, yasslIP, yasslPort, 0);
    }

    SSL_set_fd(ssl, sockfd);
#if defined(USE_WINDOWS_API) && defined(CYASSL_DTLS) && defined(NO_MAIN_DRIVER)
    /* let echoserver bind first, TODO: add Windows signal like pthreads does */
    Sleep(100);
#endif
    if (SSL_connect(ssl) != SSL_SUCCESS) err_sys("SSL_connect failed");

    while (fgets(msg, sizeof(msg), fin)) {

        sendSz = (int)strlen(msg);

        if (SSL_write(ssl, msg, sendSz) != sendSz)
            err_sys("SSL_write failed");

        if (strncmp(msg, "quit", 4) == 0) {
            fputs("sending server shutdown command: quit!\n", fout);
            break;
        }

        if (strncmp(msg, "break", 5) == 0) {
            fputs("sending server session close: break!\n", fout);
            break;
        }

        while (sendSz) {
            int got;
            if ( (got = SSL_read(ssl, reply, sizeof(reply)-1)) > 0) {
                reply[got] = 0;
                fputs(reply, fout);
                sendSz -= got;
            }
            else
                break;
        }
    }

#ifdef CYASSL_DTLS
    strncpy(msg, "break", 6);
    sendSz = (int)strlen(msg);
    /* try to tell server done */
    SSL_write(ssl, msg, sendSz);
#else
    SSL_shutdown(ssl);
#endif

    SSL_free(ssl);
    SSL_CTX_free(ctx);

    fflush(fout);
    if (inCreated)  fclose(fin);
    if (outCreated) fclose(fout);

    CloseSocket(sockfd);
    ((func_args*)args)->return_code = 0; 
}
Beispiel #29
0
bool XLCDproc::Connect()
{
  CloseSocket();

  struct hostent *server;
  server = gethostbyname(g_advancedSettings.m_lcdHostName);
  if (server == NULL)
  {
     CLog::Log(LOGERROR, "XLCDproc::%s - Unable to resolve LCDd host.", __FUNCTION__);
     return false;
  }

  m_sockfd = socket(AF_INET, SOCK_STREAM, 0);
  if (m_sockfd == -1)
  {
    CLog::Log(LOGERROR, "XLCDproc::%s - Unable to create socket.", __FUNCTION__);
    return false;
  }

  struct sockaddr_in serv_addr = {};
  serv_addr.sin_family = AF_INET;
  memmove(&serv_addr.sin_addr, server->h_addr_list[0], server->h_length);
  //Connect to default LCDd port, hard coded for now.
  serv_addr.sin_port = htons(13666);

  if (connect(m_sockfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr)) == -1)
  {
    CLog::Log(LOGERROR, "XLCDproc::%s - Unable to connect to host, LCDd not running?", __FUNCTION__);
    return false;
  }

  // Start a new session
  CStdString hello;
  hello = "hello\n";

  if (write(m_sockfd,hello.c_str(),hello.size()) == -1)
  {
    CLog::Log(LOGERROR, "XLCDproc::%s - Unable to write to socket", __FUNCTION__);
    return false;
  }

  // Receive LCDproc data to determine row and column information
  char reply[1024];
  if (read(m_sockfd,reply,1024) == -1)
  {
    CLog::Log(LOGERROR, "XLCDproc::%s - Unable to read from socket", __FUNCTION__);
    return false;
  }

  unsigned int i=0;
  while ((strncmp("lcd",reply + i,3) != 0 ) && (i < (strlen(reply) - 5))) i++;
  if(sscanf(reply+i,"lcd wid %u hgt %u", &m_iColumns, &m_iRows))
    CLog::Log(LOGDEBUG, "XLCDproc::%s - LCDproc data: Columns %i - Rows %i.", __FUNCTION__, m_iColumns, m_iRows);

  //Build command to setup screen
  CStdString cmd;
  cmd = "screen_add xbmc\n";
  if (!g_advancedSettings.m_lcdHeartbeat)
    cmd.append("screen_set xbmc -heartbeat off\n");
  if (g_advancedSettings.m_lcdScrolldelay != 0)
  {
    cmd.append("widget_add xbmc line1 scroller\n");
    cmd.append("widget_add xbmc line2 scroller\n");
    cmd.append("widget_add xbmc line3 scroller\n");
    cmd.append("widget_add xbmc line4 scroller\n");
  }
  else
  {
    cmd.append("widget_add xbmc line1 string\n");
    cmd.append("widget_add xbmc line2 string\n");
    cmd.append("widget_add xbmc line3 string\n");
    cmd.append("widget_add xbmc line4 string\n");
  }

  //Send to server
  if (write(m_sockfd,cmd.c_str(),cmd.size()) == -1)
  {
    CLog::Log(LOGERROR, "XLCDproc::%s - Unable to write to socket", __FUNCTION__);
    return false;
  }

  return true;
}
Beispiel #30
0
THREAD_RETURN CYASSL_THREAD server_test(void* args)
{
    SOCKET_T sockfd   = WOLFSSL_SOCKET_INVALID;
    SOCKET_T clientfd = WOLFSSL_SOCKET_INVALID;

    SSL_METHOD* method = 0;
    SSL_CTX*    ctx    = 0;
    SSL*        ssl    = 0;

    const char msg[] = "I hear you fa shizzle!";
    char   input[80];
    int    ch;
    int    version = SERVER_DEFAULT_VERSION;
    int    doCliCertCheck = 1;
    int    useAnyAddr = 0;
    word16 port = wolfSSLPort;
    int    usePsk = 0;
    int    usePskPlus = 0;
    int    useAnon = 0;
    int    doDTLS = 0;
    int    needDH = 0;
    int    useNtruKey   = 0;
    int    nonBlocking  = 0;
    int    trackMemory  = 0;
    int    fewerPackets = 0;
    int    pkCallbacks  = 0;
    int    wc_shutdown     = 0;
    int    resume = 0;
    int    resumeCount = 0;
    int    loopIndefinitely = 0;
    int    echoData = 0;
    int    throughput = 0;
    int    minDhKeyBits  = DEFAULT_MIN_DHKEY_BITS;
    short  minRsaKeyBits = DEFAULT_MIN_RSAKEY_BITS;
    short  minEccKeyBits = DEFAULT_MIN_ECCKEY_BITS;
    int    doListen = 1;
    int    crlFlags = 0;
    int    ret;
    int    err = 0;
    char*  serverReadyFile = NULL;
    char*  alpnList = NULL;
    unsigned char alpn_opt = 0;
    char*  cipherList = NULL;
    const char* verifyCert = cliCert;
    const char* ourCert    = svrCert;
    const char* ourKey     = svrKey;
    const char* ourDhParam = dhParam;
    tcp_ready*  readySignal = NULL;
    int    argc = ((func_args*)args)->argc;
    char** argv = ((func_args*)args)->argv;

#ifdef WOLFSSL_TRUST_PEER_CERT
    const char* trustCert  = NULL;
#endif

#ifndef NO_PSK
    int sendPskIdentityHint = 1;
#endif

#ifdef HAVE_SNI
    char*  sniHostName = NULL;
#endif

#ifdef HAVE_OCSP
    int    useOcsp  = 0;
    char*  ocspUrl  = NULL;
#endif

    ((func_args*)args)->return_code = -1; /* error state */

#ifdef NO_RSA
    verifyCert = (char*)cliEccCert;
    ourCert    = (char*)eccCert;
    ourKey     = (char*)eccKey;
#endif
    (void)trackMemory;
    (void)pkCallbacks;
    (void)needDH;
    (void)ourKey;
    (void)ourCert;
    (void)ourDhParam;
    (void)verifyCert;
    (void)useNtruKey;
    (void)doCliCertCheck;
    (void)minDhKeyBits;
    (void)minRsaKeyBits;
    (void)minEccKeyBits;
    (void)alpnList;
    (void)alpn_opt;
    (void)crlFlags;
    (void)readySignal;

#ifdef CYASSL_TIRTOS
    fdOpenSession(Task_self());
#endif

#ifdef WOLFSSL_VXWORKS
    useAnyAddr = 1;
#else
    while ((ch = mygetopt(argc, argv, "?jdbstnNufrawPIR:p:v:l:A:c:k:Z:S:oO:D:L:ieB:E:"))
                         != -1) {
        switch (ch) {
            case '?' :
                Usage();
                exit(EXIT_SUCCESS);

            case 'd' :
                doCliCertCheck = 0;
                break;

            case 'b' :
                useAnyAddr = 1;
                break;

            case 's' :
                usePsk = 1;
                break;

            case 'j' :
                usePskPlus = 1;
                break;

            case 't' :
            #ifdef USE_WOLFSSL_MEMORY
                trackMemory = 1;
            #endif
                break;

            case 'n' :
                useNtruKey = 1;
                break;

            case 'u' :
                doDTLS  = 1;
                break;

            case 'f' :
                fewerPackets = 1;
                break;

            case 'R' :
                serverReadyFile = myoptarg;
                break;

            case 'r' :
                #ifndef NO_SESSION_CACHE
                    resume = 1;
                #endif
                break;

            case 'P' :
            #ifdef HAVE_PK_CALLBACKS
                pkCallbacks = 1;
            #endif
                break;

            case 'p' :
                port = (word16)atoi(myoptarg);
                break;

            case 'w' :
                wc_shutdown = 1;
                break;

            case 'v' :
                version = atoi(myoptarg);
                if (version < 0 || version > 3) {
                    Usage();
                    exit(MY_EX_USAGE);
                }
                break;

            case 'l' :
                cipherList = myoptarg;
                break;

            case 'A' :
                verifyCert = myoptarg;
                break;

            case 'c' :
                ourCert = myoptarg;
                break;

            case 'k' :
                ourKey = myoptarg;
                break;

            case 'D' :
                #ifndef NO_DH
                    ourDhParam = myoptarg;
                #endif
                break;

            case 'Z' :
                #ifndef NO_DH
                    minDhKeyBits = atoi(myoptarg);
                    if (minDhKeyBits <= 0 || minDhKeyBits > 16000) {
                        Usage();
                        exit(MY_EX_USAGE);
                    }
                #endif
                break;

            case 'N':
                nonBlocking = 1;
                break;

            case 'S' :
                #ifdef HAVE_SNI
                    sniHostName = myoptarg;
                #endif
                break;

            case 'o' :
                #ifdef HAVE_OCSP
                    useOcsp = 1;
                #endif
                break;

            case 'O' :
                #ifdef HAVE_OCSP
                    useOcsp = 1;
                    ocspUrl = myoptarg;
                #endif
                break;

            case 'a' :
                #ifdef HAVE_ANON
                    useAnon = 1;
                #endif
                break;
            case 'I':
                #ifndef NO_PSK
                    sendPskIdentityHint = 0;
                #endif
                break;

            case 'L' :
                #ifdef HAVE_ALPN
                    alpnList = myoptarg;

                    if (alpnList[0] == 'C' && alpnList[1] == ':')
                        alpn_opt = WOLFSSL_ALPN_CONTINUE_ON_MISMATCH;
                    else if (alpnList[0] == 'F' && alpnList[1] == ':')
                        alpn_opt = WOLFSSL_ALPN_FAILED_ON_MISMATCH;
                    else {
                        Usage();
                        exit(MY_EX_USAGE);
                    }

                    alpnList += 2;

                #endif
                break;

            case 'i' :
                loopIndefinitely = 1;
                break;

            case 'e' :
                echoData = 1;
                break;

            case 'B':
                throughput = atoi(myoptarg);
                if (throughput <= 0) {
                    Usage();
                    exit(MY_EX_USAGE);
                }
                break;

            #ifdef WOLFSSL_TRUST_PEER_CERT
            case 'E' :
                 trustCert = myoptarg;
                break;
            #endif

            default:
                Usage();
                exit(MY_EX_USAGE);
        }
    }

    myoptind = 0;      /* reset for test cases */
#endif /* !WOLFSSL_VXWORKS */

    /* sort out DTLS versus TLS versions */
    if (version == CLIENT_INVALID_VERSION) {
        if (doDTLS)
            version = CLIENT_DTLS_DEFAULT_VERSION;
        else
            version = CLIENT_DEFAULT_VERSION;
    }
    else {
        if (doDTLS) {
            if (version == 3)
                version = -2;
            else
                version = -1;
        }
    }

#ifdef USE_CYASSL_MEMORY
    if (trackMemory)
        InitMemoryTracker();
#endif

    switch (version) {
#ifndef NO_OLD_TLS
    #ifdef WOLFSSL_ALLOW_SSLV3
        case 0:
            method = SSLv3_server_method();
            break;
    #endif

    #ifndef NO_TLS
        case 1:
            method = TLSv1_server_method();
            break;


        case 2:
            method = TLSv1_1_server_method();
            break;

        #endif
#endif

#ifndef NO_TLS
        case 3:
            method = TLSv1_2_server_method();
            break;
#endif

#ifdef CYASSL_DTLS
    #ifndef NO_OLD_TLS
        case -1:
            method = DTLSv1_server_method();
            break;
    #endif

        case -2:
            method = DTLSv1_2_server_method();
            break;
#endif

        default:
            err_sys("Bad SSL version");
    }

    if (method == NULL)
        err_sys("unable to get method");

    ctx = SSL_CTX_new(method);
    if (ctx == NULL)
        err_sys("unable to get ctx");

#if defined(HAVE_SESSION_TICKET) && defined(HAVE_CHACHA) && \
                                    defined(HAVE_POLY1305)
    if (TicketInit() != 0)
        err_sys("unable to setup Session Ticket Key context");
    wolfSSL_CTX_set_TicketEncCb(ctx, myTicketEncCb);
#endif

    if (cipherList)
        if (SSL_CTX_set_cipher_list(ctx, cipherList) != SSL_SUCCESS)
            err_sys("server can't set cipher list 1");

#ifdef CYASSL_LEANPSK
    if (!usePsk) {
        usePsk = 1;
    }
#endif

#if defined(NO_RSA) && !defined(HAVE_ECC)
    if (!usePsk) {
        usePsk = 1;
    }
#endif

    if (fewerPackets)
        CyaSSL_CTX_set_group_messages(ctx);

#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER)
    SSL_CTX_set_default_passwd_cb(ctx, PasswordCallBack);
#endif

#if !defined(NO_FILESYSTEM) && !defined(NO_CERTS)
    if ((!usePsk || usePskPlus) && !useAnon) {
        if (SSL_CTX_use_certificate_chain_file(ctx, ourCert)
                                         != SSL_SUCCESS)
            err_sys("can't load server cert file, check file and run from"
                    " wolfSSL home dir");
    }
#endif

#ifndef NO_DH
    if (wolfSSL_CTX_SetMinDhKey_Sz(ctx, (word16)minDhKeyBits) != SSL_SUCCESS) {
        err_sys("Error setting minimum DH key size");
    }
#endif
#ifndef NO_RSA
    if (wolfSSL_CTX_SetMinRsaKey_Sz(ctx, minRsaKeyBits) != SSL_SUCCESS){
        err_sys("Error setting minimum RSA key size");
    }
#endif
#ifdef HAVE_ECC
    if (wolfSSL_CTX_SetMinEccKey_Sz(ctx, minEccKeyBits) != SSL_SUCCESS){
        err_sys("Error setting minimum ECC key size");
    }
#endif

#ifdef HAVE_NTRU
    if (useNtruKey) {
        if (CyaSSL_CTX_use_NTRUPrivateKey_file(ctx, ourKey)
                                != SSL_SUCCESS)
            err_sys("can't load ntru key file, "
                    "Please run from wolfSSL home dir");
    }
#endif
#if !defined(NO_FILESYSTEM) && !defined(NO_CERTS)
    if (!useNtruKey && (!usePsk || usePskPlus) && !useAnon) {
        if (SSL_CTX_use_PrivateKey_file(ctx, ourKey, SSL_FILETYPE_PEM)
                                         != SSL_SUCCESS)
            err_sys("can't load server private key file, check file and run "
                "from wolfSSL home dir");
    }
#endif

    if (usePsk || usePskPlus) {
#ifndef NO_PSK
        SSL_CTX_set_psk_server_callback(ctx, my_psk_server_cb);

        if (sendPskIdentityHint == 1)
            SSL_CTX_use_psk_identity_hint(ctx, "cyassl server");

        if (cipherList == NULL && !usePskPlus) {
            const char *defaultCipherList;
            #if defined(HAVE_AESGCM) && !defined(NO_DH)
                defaultCipherList = "DHE-PSK-AES128-GCM-SHA256";
                needDH = 1;
            #elif defined(HAVE_NULL_CIPHER)
                defaultCipherList = "PSK-NULL-SHA256";
            #else
                defaultCipherList = "PSK-AES128-CBC-SHA256";
            #endif
            if (SSL_CTX_set_cipher_list(ctx, defaultCipherList) != SSL_SUCCESS)
                err_sys("server can't set cipher list 2");
        }
#endif
    }

    if (useAnon) {
#ifdef HAVE_ANON
        CyaSSL_CTX_allow_anon_cipher(ctx);
        if (cipherList == NULL) {
            if (SSL_CTX_set_cipher_list(ctx, "ADH-AES128-SHA") != SSL_SUCCESS)
                err_sys("server can't set cipher list 4");
        }
#endif
    }

#if !defined(NO_FILESYSTEM) && !defined(NO_CERTS)
    /* if not using PSK, verify peer with certs
       if using PSK Plus then verify peer certs except PSK suites */
    if (doCliCertCheck && (usePsk == 0 || usePskPlus) && useAnon == 0) {
        SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER |
                                ((usePskPlus)? SSL_VERIFY_FAIL_EXCEPT_PSK :
                                SSL_VERIFY_FAIL_IF_NO_PEER_CERT),0);
        if (SSL_CTX_load_verify_locations(ctx, verifyCert, 0) != SSL_SUCCESS)
            err_sys("can't load ca file, Please run from wolfSSL home dir");
        #ifdef WOLFSSL_TRUST_PEER_CERT
        if (trustCert) {
            if ((ret = wolfSSL_CTX_trust_peer_cert(ctx, trustCert,
                                            SSL_FILETYPE_PEM)) != SSL_SUCCESS) {
                err_sys("can't load trusted peer cert file");
            }
        }
        #endif /* WOLFSSL_TRUST_PEER_CERT */
   }
#endif

#if defined(CYASSL_SNIFFER)
    /* don't use EDH, can't sniff tmp keys */
    if (cipherList == NULL) {
        if (SSL_CTX_set_cipher_list(ctx, "AES128-SHA") != SSL_SUCCESS)
            err_sys("server can't set cipher list 3");
    }
#endif

#ifdef HAVE_SNI
    if (sniHostName)
        if (CyaSSL_CTX_UseSNI(ctx, CYASSL_SNI_HOST_NAME, sniHostName,
                                           XSTRLEN(sniHostName)) != SSL_SUCCESS)
            err_sys("UseSNI failed");
#endif

#ifdef USE_WINDOWS_API
    if (port == 0) {
        /* Generate random port for testing */
        port = GetRandomPort();
    }
#endif /* USE_WINDOWS_API */

    while (1) {
        /* allow resume option */
        if(resumeCount > 1) {
            if (doDTLS == 0) {
                SOCKADDR_IN_T client;
                socklen_t client_len = sizeof(client);
                clientfd = accept(sockfd, (struct sockaddr*)&client,
                                 (ACCEPT_THIRD_T)&client_len);
            } else {
                tcp_listen(&sockfd, &port, useAnyAddr, doDTLS);
                clientfd = sockfd;
            }
            if(WOLFSSL_SOCKET_IS_INVALID(clientfd)) {
                err_sys("tcp accept failed");
            }
        }

        ssl = SSL_new(ctx);
        if (ssl == NULL)
            err_sys("unable to get SSL");

#ifndef NO_HANDSHAKE_DONE_CB
        wolfSSL_SetHsDoneCb(ssl, myHsDoneCb, NULL);
#endif
#ifdef HAVE_CRL
#ifdef HAVE_CRL_MONITOR
        crlFlags = CYASSL_CRL_MONITOR | CYASSL_CRL_START_MON;
#endif
        if (CyaSSL_EnableCRL(ssl, 0) != SSL_SUCCESS)
            err_sys("unable to enable CRL");
        if (CyaSSL_LoadCRL(ssl, crlPemDir, SSL_FILETYPE_PEM, crlFlags)
                                                                 != SSL_SUCCESS)
            err_sys("unable to load CRL");
        if (CyaSSL_SetCRL_Cb(ssl, CRL_CallBack) != SSL_SUCCESS)
            err_sys("unable to set CRL callback url");
#endif
#ifdef HAVE_OCSP
        if (useOcsp) {
            if (ocspUrl != NULL) {
                CyaSSL_CTX_SetOCSP_OverrideURL(ctx, ocspUrl);
                CyaSSL_CTX_EnableOCSP(ctx, CYASSL_OCSP_NO_NONCE
                                                        | CYASSL_OCSP_URL_OVERRIDE);
            }
            else
                CyaSSL_CTX_EnableOCSP(ctx, CYASSL_OCSP_NO_NONCE);
        }
#endif
#if defined(HAVE_CERTIFICATE_STATUS_REQUEST) \
 || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
        if (wolfSSL_CTX_EnableOCSPStapling(ctx) != SSL_SUCCESS)
            err_sys("can't enable OCSP Stapling Certificate Manager");
        if (SSL_CTX_load_verify_locations(ctx, "certs/ocsp/intermediate1-ca-cert.pem", 0) != SSL_SUCCESS)
            err_sys("can't load ca file, Please run from wolfSSL home dir");
        if (SSL_CTX_load_verify_locations(ctx, "certs/ocsp/intermediate2-ca-cert.pem", 0) != SSL_SUCCESS)
            err_sys("can't load ca file, Please run from wolfSSL home dir");
        if (SSL_CTX_load_verify_locations(ctx, "certs/ocsp/intermediate3-ca-cert.pem", 0) != SSL_SUCCESS)
            err_sys("can't load ca file, Please run from wolfSSL home dir");
#endif
#ifdef HAVE_PK_CALLBACKS
        if (pkCallbacks)
            SetupPkCallbacks(ctx, ssl);
#endif

        /* do accept */
        readySignal = ((func_args*)args)->signal;
        if (readySignal) {
            readySignal->srfName = serverReadyFile;
        }
        tcp_accept(&sockfd, &clientfd, (func_args*)args, port, useAnyAddr,
                       doDTLS, serverReadyFile ? 1 : 0, doListen);
        doListen = 0; /* Don't listen next time */

        if (SSL_set_fd(ssl, clientfd) != SSL_SUCCESS) {
            err_sys("error in setting fd");
        }

#ifdef HAVE_ALPN
        if (alpnList != NULL) {
            printf("ALPN accepted protocols list : %s\n", alpnList);
            wolfSSL_UseALPN(ssl, alpnList, (word32)XSTRLEN(alpnList), alpn_opt);
        }
#endif

#ifdef WOLFSSL_DTLS
        if (doDTLS) {
            SOCKADDR_IN_T cliaddr;
            byte          b[1500];
            int           n;
            socklen_t     len = sizeof(cliaddr);

            /* For DTLS, peek at the next datagram so we can get the client's
             * address and set it into the ssl object later to generate the
             * cookie. */
            n = (int)recvfrom(sockfd, (char*)b, sizeof(b), MSG_PEEK,
                              (struct sockaddr*)&cliaddr, &len);
            if (n <= 0)
                err_sys("recvfrom failed");

            wolfSSL_dtls_set_peer(ssl, &cliaddr, len);
        }
#endif
        if ((usePsk == 0 || usePskPlus) || useAnon == 1 || cipherList != NULL
                                                               || needDH == 1) {
            #if !defined(NO_FILESYSTEM) && !defined(NO_DH) && !defined(NO_ASN)
                CyaSSL_SetTmpDH_file(ssl, ourDhParam, SSL_FILETYPE_PEM);
            #elif !defined(NO_DH)
                SetDH(ssl);  /* repick suites with DHE, higher priority than PSK */
            #endif
        }

#ifndef CYASSL_CALLBACKS
        if (nonBlocking) {
            CyaSSL_set_using_nonblock(ssl, 1);
            tcp_set_nonblocking(&clientfd);
        }
#endif

        do {
#ifdef WOLFSSL_ASYNC_CRYPT
            if (err == WC_PENDING_E) {
                ret = AsyncCryptPoll(ssl);
                if (ret < 0) { break; } else if (ret == 0) { continue; }
            }
#endif

            err = 0; /* Reset error */
#ifndef CYASSL_CALLBACKS
            if (nonBlocking) {
                ret = NonBlockingSSL_Accept(ssl);
            }
            else {
                ret = SSL_accept(ssl);
            }
#else
            ret = NonBlockingSSL_Accept(ssl);
#endif
            if (ret != SSL_SUCCESS) {
                err = SSL_get_error(ssl, 0);
            }
        } while (ret != SSL_SUCCESS && err == WC_PENDING_E);

        if (ret != SSL_SUCCESS) {
            char buffer[CYASSL_MAX_ERROR_SZ];
            err = SSL_get_error(ssl, 0);
            printf("error = %d, %s\n", err, ERR_error_string(err, buffer));
            err_sys("SSL_accept failed");
        }

        showPeer(ssl);

#ifdef HAVE_ALPN
        if (alpnList != NULL) {
            char *protocol_name = NULL, *list = NULL;
            word16 protocol_nameSz = 0, listSz = 0;

            err = wolfSSL_ALPN_GetProtocol(ssl, &protocol_name, &protocol_nameSz);
            if (err == SSL_SUCCESS)
                printf("Sent ALPN protocol : %s (%d)\n",
                       protocol_name, protocol_nameSz);
            else if (err == SSL_ALPN_NOT_FOUND)
                printf("No ALPN response sent (no match)\n");
            else
                printf("Getting ALPN protocol name failed\n");

            err = wolfSSL_ALPN_GetPeerProtocol(ssl, &list, &listSz);
            if (err == SSL_SUCCESS)
                printf("List of protocol names sent by Client: %s (%d)\n",
                       list, listSz);
            else
                printf("Get list of client's protocol name failed\n");

            free(list);
        }
#endif
        if(echoData == 0 && throughput == 0) {
            ret = SSL_read(ssl, input, sizeof(input)-1);
            if (ret > 0) {
                input[ret] = 0;
                printf("Client message: %s\n", input);

            }
            else if (ret < 0) {
                int readErr = SSL_get_error(ssl, 0);
                if (readErr != SSL_ERROR_WANT_READ)
                    err_sys("SSL_read failed");
            }

            if (SSL_write(ssl, msg, sizeof(msg)) != sizeof(msg))
                err_sys("SSL_write failed");
        }
        else {
            ServerEchoData(ssl, clientfd, echoData, throughput);
        }

#if defined(WOLFSSL_MDK_SHELL) && defined(HAVE_MDK_RTX)
        os_dly_wait(500) ;
#elif defined (CYASSL_TIRTOS)
        Task_yield();
#endif

        if (doDTLS == 0) {
            ret = SSL_shutdown(ssl);
            if (wc_shutdown && ret == SSL_SHUTDOWN_NOT_DONE)
                SSL_shutdown(ssl);    /* bidirectional shutdown */
        }
        SSL_free(ssl);

        CloseSocket(clientfd);

        if (resume == 1 && resumeCount == 0) {
            resumeCount++;           /* only do one resume for testing */
            continue;
        }
        resumeCount = 0;

        if(!loopIndefinitely) {
            break;  /* out of while loop, done with normal and resume option */
        }
    } /* while(1) */

    CloseSocket(sockfd);
    SSL_CTX_free(ctx);

    ((func_args*)args)->return_code = 0;


#if defined(NO_MAIN_DRIVER) && defined(HAVE_ECC) && defined(FP_ECC) \
                            && defined(HAVE_THREAD_LS)
    ecc_fp_free();  /* free per thread cache */
#endif

#ifdef USE_WOLFSSL_MEMORY
    if (trackMemory)
        ShowMemoryTracker();
#endif

#ifdef CYASSL_TIRTOS
    fdCloseSession(Task_self());
#endif

#if defined(HAVE_SESSION_TICKET) && defined(HAVE_CHACHA) && \
                                    defined(HAVE_POLY1305)
    TicketCleanup();
#endif

    /* There are use cases  when these assignments are not read. To avoid
     * potential confusion those warnings have been handled here.
     */
    (void) ourKey;
    (void) verifyCert;
    (void) doCliCertCheck;
    (void) useNtruKey;
    (void) ourDhParam;
    (void) ourCert;
#ifndef CYASSL_TIRTOS
    return 0;
#endif
}