Panel użytkownika
Nazwa użytkownika:
Hasło:
Nie masz jeszcze konta?

C++ ssl socket serwer wiele połączeń z openssl

Ostatnio zmodyfikowano 2017-11-13 20:19
Autor Wiadomość
mateczek
» 2017-08-28 12:57:35
zobacz, jak gościu pisze programy (server) tcp w Qt
https://www.youtube.com/watch?v=BSdKkZNEKlQ
P-164348
Breakermind
Temat założony przez niniejszego użytkownika
» 2017-08-28 13:36:36
Jeżeli jest gdzieś jakiś fajny przykład c++ ssl z multi users na QSSLSocket chętnie zobaczę.
Ten przykład działa na debianie a inny znaleziony w sieci z QSSLSockets nie działa.



P-164350
mateczek
» 2017-08-28 17:02:16
jeden przykład jest w przykładach (zakładka qtCreatora o nazwie przykłady(example)) masz i serwer i klienta. Klikasz zieloną strzałkę i działa (testowałem na msys2 windows). Serwer odpowiadał klijentowi. Bardziej się nie wgłębiałem tylko odpaliłem przykład i skompilowałem oba programy
P-164352
Breakermind
Temat założony przez niniejszego użytkownika
» 2017-08-29 11:02:25
Link do classy C++ servera ssl multiple users, metoda odpowiadająca za wysyłanie i odbieranie danych ServerLoop(SSL *ssl)
https://github.com/breakermind/CppLinux/tree/master/QtSslServerClass
P-164360
Breakermind
Temat założony przez niniejszego użytkownika
» 2017-08-31 21:06:41
Wysyłanie danych w pętli do znacznika [end]:

C/C++
// Send HTML
SSL_write( ssl, reply_html, strlen( reply_html ) );
std::string html = "";
if( received > 0 )
{
    html += std::string( buffer );
    TotalReceived += received;
    while( 1 ) {
        received = SSL_read( ssl, buffer, readSize );
        html += buffer;
        TotalReceived += received;
        // printf("PID %i Buffsize - %i - %.*s \n", getpid(), received, received, buffer);
        cout << "MAIL FROM <<< " << std::string( buffer ) << endl;
        string xx = "";
        string en = "[end]";
        xx = std::string( buffer );
        // if(x.find(std::string("[end]")) != std::string::npos){
        if( strstr( xx.c_str(), en.c_str() ) ) {
            cout << "SHOW HTML " << html;
            // Clear buffer
            memset( buffer, 0, sizeof buffer );
            break;
        }
        // check ssl error and destroy connection
        sslError( ssl, received );
    }
}

// Check ssl error
void SslServer::sslError( SSL * ssl, int received ) {
    const int err = SSL_get_error( ssl, received );
    // const int st = ERR_get_error();
    if( err == SSL_ERROR_NONE ) {
        std::cout << "SSL_ERROR_NONE:" << SSL_ERROR_NONE << std::endl;
    } else if( err == SSL_ERROR_WANT_READ ) {
        std::cout << "SSL_ERROR_WANT_READ:" << SSL_ERROR_WANT_READ << std::endl;
        SSL_shutdown( ssl );
        kill( getpid(), SIGKILL );
    } else if( SSL_ERROR_SYSCALL ) {
        std::cout << "SSL_ERROR_SYSCALL:" << SSL_ERROR_SYSCALL << std::endl;
        SSL_shutdown( ssl );
        kill( getpid(), SIGKILL );
    }
}
P-164481
Breakermind
Temat założony przez niniejszego użytkownika
» 2017-09-07 21:04:22
Link do przykładu klasy serwera ssl multiple threads connection z tredami pthreads:
https://github.com/breakermind​/CppLinux/tree/master​/QtSslServerThreads
P-164701
Breakermind
Temat założony przez niniejszego użytkownika
» 2017-11-08 15:29:57
No i timeout socketu (Dodać po wykonaniu funkcji fork() w procesie dziecku):

C/C++
void socket_timeout( int sec, int sock ) {
    struct timeval timeout;
    timeout.tv_sec = sec;
    timeout.tv_usec = 0;
    // (const char*)
    if( setsockopt( sock, SOL_SOCKET, SO_RCVTIMEO,( char * ) & timeout, sizeof( timeout ) ) < 0 ) {
        cout << "Timeout set failed" << endl;
    }
   
    if( setsockopt( sock, SOL_SOCKET, SO_SNDTIMEO,( char * ) & timeout, sizeof( timeout ) ) < 0 ) {
        cout << "Timeout set failed" << endl;
    }
}

fork() return:
1) W rodzicu: zwraca wartość PID procesu dziecka
2) W dziecku PID == 0 (pobranie numeru procesu w dziecku przez funkcje getpid() )
3) Unicestwienie procesu dziecka:
C/C++
PID = fork();

if( PID == - 1 ) {
    cout << "Error create child" << endl;
} else {
    cout << "Child proccess created" << endl;
}

// Process pochodny (child)
if( PID == 0 ) {
    cout << "Proces pochodny" << endl;
    // Unicestwia process dziecka po fork
    kill( getpid(), SIGTERM ); // można przechwycić
    kill( getpid(), SIGKILL ); // unicestwia bez możliwości przechwycenia
}

// Process parent
if( PID > 0 ) {
    cout << "Working parent" << endl;
}
P-166591
Breakermind
Temat założony przez niniejszego użytkownika
» 2017-11-08 20:25:56
Dodam jeszcze połączenie do mysql dla przypomnienia:

C/C++
#include <iostream>
#include <vector>
#include <string>

// time
#include <time.h>
#include <stdio.h>

#include "mysql.h"
#include <errno.h>

using namespace std;

// conection
MYSQL * connect = NULL;


// Connect to database
bool Connect( string host = "localhost", string port = "3306", string user = "root", string pass = "toor", string db = "dbname" ) {
    try {
       
        connect = mysql_init( connect );
       
        // init mysql  
        connect = mysql_init( NULL );
        mysql_options( connect, MYSQL_SET_CHARSET_NAME, "utf8mb4" );
        mysql_options( connect, MYSQL_INIT_COMMAND, "SET NAMES utf8mb4" );
        // Allow reconnections
        my_bool recon = true;
        mysql_options( connect, MYSQL_OPT_RECONNECT, & recon );
        // Connection time out
        // mysql_options(connect, MYSQL_OPT_CONNECT_TIMEOUT, "600");
        if( !connect ) {
            cout << "[ERROR_MYSQL_INIT] MySQL Initialization failed" << std::strerror( errno ) << endl;
            return 0;
        }
        connect = mysql_real_connect( connect, host.c_str(), user.c_str(), pass.c_str(), db.c_str(), atoi( port.c_str() ), NULL, 0 );
        if( connect ) {
            cout << "[NOTICE] MySQL Connection Succeeded\n";
            //mysql_query(connect, "set global max_connections = 1000;");
            return 1;
        } else {
            cout << "[ERROR_MYSQL_CONN] MySQL Connection failed (Restarting threads...wait)\n";
            return 0;
        }
    } catch( std::exception & e ) {
        cout << "# ERR: Mysql Exception in " << __FILE__;
        cout << "(" << __FUNCTION__ << ") on line " << __LINE__ << endl;
        cout << "# ERR: " << e.what();
        return 0;
    }
}

Pobieranie:
C/C++
vector < string > getDKIM( std::string email ) {
    vector < string > dkim;
    try {
        MYSQL_RES * res_set;
        MYSQL_ROW row;
       
        vector < string > ema = splitDelimiter( email, "@" );
        if( ema.size() != 2 ) { return dkim; }
        std::string domain = ema.at( ema.size() - 1 );
       
        // Select user
        char query[ 200 ];
        sprintf( query, "SELECT dkim_key,dkim_selector,dkim_active,domainname FROM domain_dkim WHERE domainname = '%s' AND active = 1;", domain.c_str() );
        int err = mysql_query( connect, query );
        if( err ) {
            cout << mysql_error( connect );
            return dkim;
        }
        res_set = mysql_store_result( connect );
        while((( row = mysql_fetch_row( res_set ) ) != NULL ) ) {
            dkim.push_back( row[ 0 ] );
            dkim.push_back( row[ 1 ] );
            dkim.push_back( row[ 2 ] );
            dkim.push_back( row[ 3 ] );
        }
    } catch( std::exception & e ) {
        cout << "# ERR: Mysql in " << __FILE__;
        cout << "(" << __FUNCTION__ << ") on line " << __LINE__ << endl;
        cout << mysql_error( connect ) << endl;
        return dkim;
    }
    return dkim;
}

Dodawanie i aktualizacja
C/C++
unsigned long long InsertMsgSMTP( string efrom, string eto, string subject, string data, string msgid, int spf ) {
    try {
        unsigned long long id = 0;
        // stream
        std::ostringstream sql;
        sql << "INSERT INTO messages(email_from,email_to,email_replyto,email_subject,email_content,email_file,spf,size,uid,send) VALUES('";
        sql << Quotes( efrom ) << "','";
        sql << Quotes( eto ) << "','";
        sql << Quotes( efrom ) << "','";
        sql << Quotes( subject ) << "','";
        sql << Quotes( data ) << "','";
        sql << Quotes( msgid ) << "',";
        sql << spf << ",";
        sql << data.size() << ",";
        sql << "0,0);";
        //cout << "Query 0x... " << sql << " txt " << reQuotes(sql.str()) << endl;
        int err = mysql_query( connect,( sql.str().c_str() ) );
        if( err ) {
            cout << mysql_error( connect );
            return 0;
        }
        id = LastInsertID();
        if( id > 0 ) {
            char sql[ 250 ];
            sprintf( sql, "UPDATE messages SET email_content=CONCAT('Date: %s +0000\r\nContent-ID: <ID_%i@msg> \r\n',email_content) WHERE id=%i;", currentDateTimeSMTP(),( int ) id,( int ) id );
            mysql_query( connect, sql );
        }
        return id;
    } catch( std::exception & e ) {
        cout << "# ERR: Mysql Exception in " << __FILE__;
        cout << "(" << __FUNCTION__ << ") on line " << __LINE__ << endl;
        cout << "# ERR: " << e.what();
        return 0;
    } catch(...) {
        cout << "# ERR: (...) " << __FILE__ << " " << __FUNCTION__ << ") on line " << __LINE__ << endl;
        return 0;
    }
}


Last insert id
C/C++
unsigned long long LastInsertID() {
   
    try {
        MYSQL_RES * res_set;
        MYSQL_ROW row;
        // Select id
        int err = mysql_query( connect, "SELECT LAST_INSERT_ID() as id" );
        if( err ) {
            cout << mysql_error( connect );
            return 0;
        }
        res_set = mysql_store_result( connect );
        while((( row = mysql_fetch_row( res_set ) ) != NULL ) ) {
            return( unsigned long long ) std::stoi( row[ 0 ] ); // cntall
        }
        return 0;
    } catch( std::exception & e ) {
        cout << "# ERR: Mysql in " << __FILE__;
        cout << "(" << __FUNCTION__ << ") on line " << __LINE__ << endl;
        cout << mysql_error( connect ) << endl;
        return 0;
    }
}

Quotes
C/C++
string reQuotes( string str ) {
    string subs[] = { "#semi#", "#amp#", "#quot#", "#apos#", "#lt#", "#gt#", "#colon#", "#equals#", "#excl#", "#slash#" };
    string reps[] = { ";", "&", "\"", "'", "<", ">", ":", "=", "!", "\\" };
    size_t found;
    for( int j = 0; j < 9; j++ ) {
        do {
            found = str.find( subs[ j ] );
            if( found != string::npos ) {
                str.replace( found, subs[ j ].length(), reps[ j ] );
            }
        } while( found != string::npos );
       
    }
    return str;
}

string Quotes( string str ) {
    string subs[] = { ";", "&", "\"", "'", "<", ">", ":", "=", "!", "\\" };
    string reps[] = { "#semi#", "#amp#", "#quot#", "#apos#", "#lt#", "#gt#", "#colon#", "#equals#", "#excl#", "#slash#" };
    size_t found;
    for( int j = 0; j < 9; j++ ) {
        do {
            found = str.find( subs[ j ] );
            if( found != string::npos ) {
                str.replace( found, subs[ j ].length(), reps[ j ] );
            }
        } while( found != string::npos );
       
    }
    return str;
}

Pozdrawiam
P-166596
1 « 2 » 3
Poprzednia strona Strona 2 z 3 Następna strona