static http2_session_data* create_http2_session_data(app_context *app_ctx, int fd, struct sockaddr *addr, int addrlen) { int rv; http2_session_data *session_data; SSL *ssl; char host[NI_MAXHOST]; int val = 1; ssl = create_ssl(app_ctx->ssl_ctx); session_data = malloc(sizeof(http2_session_data)); memset(session_data, 0, sizeof(http2_session_data)); session_data->app_ctx = app_ctx; setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val)); session_data->bev = bufferevent_openssl_socket_new (app_ctx->evbase, fd, ssl, BUFFEREVENT_SSL_ACCEPTING, BEV_OPT_CLOSE_ON_FREE | BEV_OPT_DEFER_CALLBACKS); session_data->handshake_leftlen = NGHTTP2_CLIENT_CONNECTION_HEADER_LEN; rv = getnameinfo(addr, addrlen, host, sizeof(host), NULL, 0, NI_NUMERICHOST); if(rv != 0) { session_data->client_addr = strdup("(unknown)"); } else { session_data->client_addr = strdup(host); } return session_data; }
static void perform_ssl_connection (void) { struct evhttp_connection *con; struct evhttp_request *req; struct bufferevent *bev; SSL_CTX *sctx; SSL *ssl; sctx = SSL_CTX_new (SSLv23_client_method ()); assert (sctx); SSL_CTX_set_options (sctx, SSL_OP_NO_TLSv1_2); //SSL_CTX_set_options (sctx, SSL_OP_ALL); SSL_CTX_set_timeout (sctx, 3000); SSL_CTX_set_verify (sctx, SSL_VERIFY_PEER, SSLX_CTX_verify_callback); SSL_CTX_set_default_verify_paths (sctx); SSL_CTX_set_cipher_list (sctx, "RC4-MD5"); ssl = SSL_new (sctx); assert (ssl); bev = bufferevent_openssl_socket_new (evbase, -1, ssl, BUFFEREVENT_SSL_CONNECTING , BEV_OPT_CLOSE_ON_FREE); //bev = bufferevent_socket_new (evbase, -1, BEV_OPT_CLOSE_ON_FREE); assert (bev); con = evhttp_connection_base_bufferevent_new (evbase, dnsbase, bev, HOST, PORT); evhttp_connection_set_closecb (con, on_connection_close, NULL); evhttp_connection_set_timeout (con, 10); req = evhttp_request_new (on_response_cb, NULL); evhttp_add_header (req->output_headers, "Host", HOST); // evhttp_add_header (req->output_headers, "Connection", "Keep-Alive"); evhttp_make_request (con, req, EVHTTP_REQ_GET, "/index.html"); }
static void lev_cb(struct evconnlistener *evlistener, evutil_socket_t fd, struct sockaddr *address, int socklen, void *levws_ptr) { struct evwsconnlistener* levws = (struct evwsconnlistener *)levws_ptr; struct event_base *base = evconnlistener_get_base(levws->lev); struct evwspendingconn *pending = (struct evwspendingconn *)malloc(sizeof(struct evwspendingconn)); pending->levws = levws; if (levws->server_ctx == NULL) { pending->bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE); } else { SSL *client_ctx = SSL_new(levws->server_ctx); if (client_ctx == NULL) { fprintf(stderr, "Unable to get client_ctx\n"); exit(-1); } pending->bev = bufferevent_openssl_socket_new(base, fd, client_ctx, BUFFEREVENT_SSL_ACCEPTING, BEV_OPT_CLOSE_ON_FREE); } bufferevent_setcb(pending->bev, pending_read, NULL, pending_event, pending); bufferevent_enable(pending->bev, EV_READ); pending->address = (struct sockaddr *)malloc(socklen); memcpy(pending->address, address, socklen); pending->socklen = socklen; pending->next = levws->head; levws->head = pending; }
static void accept_cb(struct evconnlistener *listener, evutil_socket_t fd, struct sockaddr *a, int slen, void *p) { struct bufferevent *b_out, *b_in; /* Create two linked bufferevent objects: one to connect, one for the * new connection */ b_in = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE|BEV_OPT_DEFER_CALLBACKS); if (!ssl_ctx || use_wrapper) b_out = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE|BEV_OPT_DEFER_CALLBACKS); else { SSL *ssl = SSL_new(ssl_ctx); b_out = bufferevent_openssl_socket_new(base, -1, ssl, BUFFEREVENT_SSL_CONNECTING, BEV_OPT_CLOSE_ON_FREE|BEV_OPT_DEFER_CALLBACKS); } assert(b_in && b_out); if (bufferevent_socket_connect(b_out, (struct sockaddr*)&connect_to_addr, connect_to_addrlen)<0) { perror("bufferevent_socket_connect"); bufferevent_free(b_out); bufferevent_free(b_in); return; } if (ssl_ctx && use_wrapper) { struct bufferevent *b_ssl; SSL *ssl = SSL_new(ssl_ctx); b_ssl = bufferevent_openssl_filter_new(base, b_out, ssl, BUFFEREVENT_SSL_CONNECTING, BEV_OPT_CLOSE_ON_FREE|BEV_OPT_DEFER_CALLBACKS); if (!b_ssl) { perror("Bufferevent_openssl_new"); bufferevent_free(b_out); bufferevent_free(b_in); } b_out = b_ssl; } bufferevent_setcb(b_in, readcb, NULL, eventcb, b_out); bufferevent_setcb(b_out, readcb, NULL, eventcb, b_in); bufferevent_enable(b_in, EV_READ|EV_WRITE); bufferevent_enable(b_out, EV_READ|EV_WRITE); }
static void open_ssl_bufevs(struct bufferevent **bev1_out, struct bufferevent **bev2_out, struct event_base *base, int is_open, int flags, SSL *ssl1, SSL *ssl2, evutil_socket_t *fd_pair, struct bufferevent **underlying_pair) { int state1 = is_open ? BUFFEREVENT_SSL_OPEN :BUFFEREVENT_SSL_CONNECTING; int state2 = is_open ? BUFFEREVENT_SSL_OPEN :BUFFEREVENT_SSL_ACCEPTING; if (fd_pair) { *bev1_out = bufferevent_openssl_socket_new( base, fd_pair[0], ssl1, state1, flags); *bev2_out = bufferevent_openssl_socket_new( base, fd_pair[1], ssl2, state2, flags); } else { *bev1_out = bufferevent_openssl_filter_new( base, underlying_pair[0], ssl1, state1, flags); *bev2_out = bufferevent_openssl_filter_new( base, underlying_pair[1], ssl2, state2, flags); } bufferevent_setcb(*bev1_out, respond_to_number, done_writing_cb, eventcb, (void*)"client"); bufferevent_setcb(*bev2_out, respond_to_number, done_writing_cb, eventcb, (void*)"server"); }
static void ssl_acceptcb(struct evconnlistener *serv, int sock, struct sockaddr *sa, int sa_len, void *arg) { struct event_base *evbase; struct bufferevent *bev; SSL_CTX *server_ctx; SSL *client_ctx; server_ctx = (SSL_CTX *)arg; client_ctx = SSL_new(server_ctx); evbase = evconnlistener_get_base(serv); bev = bufferevent_openssl_socket_new(evbase, sock, client_ctx, BUFFEREVENT_SSL_ACCEPTING, BEV_OPT_CLOSE_ON_FREE); bufferevent_enable(bev, EV_READ); bufferevent_setcb(bev, ssl_readcb, NULL, NULL, NULL); }
/* Start connecting to the remote peer |host:port| */ static void initiate_connection(struct event_base *evbase, SSL_CTX *ssl_ctx, const char *host, uint16_t port, http2_session_data *session_data) { int rv; struct bufferevent *bev; SSL *ssl; ssl = create_ssl(ssl_ctx); bev = bufferevent_openssl_socket_new( evbase, -1, ssl, BUFFEREVENT_SSL_CONNECTING, BEV_OPT_DEFER_CALLBACKS | BEV_OPT_CLOSE_ON_FREE); bufferevent_enable(bev, EV_READ | EV_WRITE); bufferevent_setcb(bev, readcb, writecb, eventcb, session_data); rv = bufferevent_socket_connect_hostname(bev, session_data->dnsbase, AF_UNSPEC, host, port); if (rv != 0) { errx(1, "Could not connect to the remote host %s", host); } session_data->bev = bev; }
static void listener_cb(struct evconnlistener *listener, evutil_socket_t socket, struct sockaddr *sockaddr, int socklen, void *userdata) { DEBUG("New connection."); ad_server_t *server = (ad_server_t *)userdata; // Create a new buffer. struct bufferevent *buffer = NULL; if (server->sslctx) { buffer = bufferevent_openssl_socket_new(server->evbase, socket, SSL_new(server->sslctx), BUFFEREVENT_SSL_ACCEPTING, BEV_OPT_CLOSE_ON_FREE); } else { buffer = bufferevent_socket_new(server->evbase, socket, BEV_OPT_CLOSE_ON_FREE); } if (buffer == NULL) goto error; // Set read timeout. int timeout = ad_server_get_option_int(server, "server.timeout"); if (timeout > 0) { struct timeval tm; bzero((void *)&tm, sizeof(struct timeval)); tm.tv_sec = timeout; bufferevent_set_timeouts(buffer, &tm, NULL); } // Create a connection. void *conn = conn_new(server, buffer); if (! conn) goto error; return; error: if (buffer) bufferevent_free(buffer); ERROR("Failed to create a connection handler."); event_base_loopbreak(server->evbase); server->errcode = ENOMEM; }
void libwebsock_handle_accept_ssl(evutil_socket_t listener, short event, void *arg) { libwebsock_ssl_event_data *evdata = arg; libwebsock_context *ctx = evdata->ctx; SSL_CTX *ssl_ctx = evdata->ssl_ctx; libwebsock_client_state *client_state; struct bufferevent *bev; struct sockaddr_storage ss; socklen_t slen = sizeof(ss); int fd = accept(listener, (struct sockaddr *) &ss, &slen); if (fd < 0) { fprintf(stderr, "Error accepting new connection.\n"); } else { client_state = (libwebsock_client_state *) lws_calloc(sizeof(libwebsock_client_state)); client_state->sockfd = fd; client_state->flags |= STATE_CONNECTING | STATE_IS_SSL; client_state->control_callback = ctx->control_callback; client_state->onopen = ctx->onopen; client_state->onmessage = ctx->onmessage; client_state->onclose = ctx->onclose; client_state->onpong = ctx->onpong; client_state->sa = (struct sockaddr_storage *) lws_malloc(sizeof(struct sockaddr_storage)); memcpy(client_state->sa, &ss, sizeof(struct sockaddr_storage)); client_state->ssl = SSL_new(ssl_ctx); SSL_set_fd(client_state->ssl, fd); if (SSL_accept(client_state->ssl) <= 0) { fprintf(stderr, "error during ssl handshake.\n"); } client_state->ctx = (void *) ctx; evutil_make_socket_nonblocking(fd); bev = bufferevent_openssl_socket_new(ctx->base, -1, client_state->ssl, BUFFEREVENT_SSL_OPEN, BEV_OPT_CLOSE_ON_FREE | BEV_OPT_THREADSAFE); client_state->bev = bev; bufferevent_setcb(bev, libwebsock_handshake, NULL, libwebsock_do_event, (void *) client_state); bufferevent_enable(bev, EV_READ | EV_WRITE); } }
static int _evhtp_connection_accept(evbase_t * evbase, evhtp_connection_t * connection) { if (connection->htp->ssl_ctx != NULL) { connection->ssl = SSL_new(connection->htp->ssl_ctx); connection->bev = bufferevent_openssl_socket_new(evbase, connection->sock, connection->ssl, BUFFEREVENT_SSL_ACCEPTING, BEV_OPT_CLOSE_ON_FREE | BEV_OPT_DEFER_CALLBACKS); SSL_set_app_data(connection->ssl, connection); goto end; } //创建一个socket-based bufferevent connection->bev = bufferevent_socket_new(evbase, connection->sock, BEV_OPT_CLOSE_ON_FREE | BEV_OPT_DEFER_CALLBACKS); end: bufferevent_set_timeouts(connection->bev, connection->htp->recv_timeo, connection->htp->send_timeo); connection->resume_ev = event_new(evbase, -1, EV_READ | EV_PERSIST, _evhtp_connection_resumecb, connection); event_add(connection->resume_ev, NULL); bufferevent_enable(connection->bev, EV_READ); bufferevent_setcb(connection->bev, _evhtp_connection_readcb, _evhtp_connection_writecb, _evhtp_connection_eventcb, connection); return 0; } /* _evhtp_connection_accept */
int main(int argc, char **argv) { int r; struct evhttp_uri *http_uri = NULL; const char *url = NULL, *data_file = NULL; const char *crt = "/etc/ssl/certs/ca-certificates.crt"; const char *scheme, *host, *path, *query; char uri[256]; int port; int retries = 0; int timeout = -1; SSL_CTX *ssl_ctx = NULL; SSL *ssl = NULL; struct bufferevent *bev; struct evhttp_connection *evcon = NULL; struct evhttp_request *req; struct evkeyvalq *output_headers; struct evbuffer *output_buffer; int i; int ret = 0; enum { HTTP, HTTPS } type = HTTP; for (i = 1; i < argc; i++) { if (!strcmp("-url", argv[i])) { if (i < argc - 1) { url = argv[i + 1]; } else { syntax(); goto error; } } else if (!strcmp("-crt", argv[i])) { if (i < argc - 1) { crt = argv[i + 1]; } else { syntax(); goto error; } } else if (!strcmp("-ignore-cert", argv[i])) { ignore_cert = 1; } else if (!strcmp("-data", argv[i])) { if (i < argc - 1) { data_file = argv[i + 1]; } else { syntax(); goto error; } } else if (!strcmp("-retries", argv[i])) { if (i < argc - 1) { retries = atoi(argv[i + 1]); } else { syntax(); goto error; } } else if (!strcmp("-timeout", argv[i])) { if (i < argc - 1) { timeout = atoi(argv[i + 1]); } else { syntax(); goto error; } } else if (!strcmp("-help", argv[i])) { syntax(); goto error; } } if (!url) { syntax(); goto error; } #ifdef _WIN32 { WORD wVersionRequested; WSADATA wsaData; int err; wVersionRequested = MAKEWORD(2, 2); err = WSAStartup(wVersionRequested, &wsaData); if (err != 0) { printf("WSAStartup failed with error: %d\n", err); goto error; } } #endif // _WIN32 http_uri = evhttp_uri_parse(url); if (http_uri == NULL) { err("malformed url"); goto error; } scheme = evhttp_uri_get_scheme(http_uri); if (scheme == NULL || (strcasecmp(scheme, "https") != 0 && strcasecmp(scheme, "http") != 0)) { err("url must be http or https"); goto error; } host = evhttp_uri_get_host(http_uri); if (host == NULL) { err("url must have a host"); goto error; } port = evhttp_uri_get_port(http_uri); if (port == -1) { port = (strcasecmp(scheme, "http") == 0) ? 80 : 443; } path = evhttp_uri_get_path(http_uri); if (strlen(path) == 0) { path = "/"; } query = evhttp_uri_get_query(http_uri); if (query == NULL) { snprintf(uri, sizeof(uri) - 1, "%s", path); } else { snprintf(uri, sizeof(uri) - 1, "%s?%s", path, query); } uri[sizeof(uri) - 1] = '\0'; #if OPENSSL_VERSION_NUMBER < 0x10100000L // Initialize OpenSSL SSL_library_init(); ERR_load_crypto_strings(); SSL_load_error_strings(); OpenSSL_add_all_algorithms(); #endif /* This isn't strictly necessary... OpenSSL performs RAND_poll * automatically on first use of random number generator. */ r = RAND_poll(); if (r == 0) { err_openssl("RAND_poll"); goto error; } /* Create a new OpenSSL context */ ssl_ctx = SSL_CTX_new(SSLv23_method()); if (!ssl_ctx) { err_openssl("SSL_CTX_new"); goto error; } #ifndef _WIN32 /* TODO: Add certificate loading on Windows as well */ /* Attempt to use the system's trusted root certificates. * (This path is only valid for Debian-based systems.) */ if (1 != SSL_CTX_load_verify_locations(ssl_ctx, crt, NULL)) { err_openssl("SSL_CTX_load_verify_locations"); goto error; } /* Ask OpenSSL to verify the server certificate. Note that this * does NOT include verifying that the hostname is correct. * So, by itself, this means anyone with any legitimate * CA-issued certificate for any website, can impersonate any * other website in the world. This is not good. See "The * Most Dangerous Code in the World" article at * https://crypto.stanford.edu/~dabo/pubs/abstracts/ssl-client-bugs.html */ SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, NULL); /* This is how we solve the problem mentioned in the previous * comment. We "wrap" OpenSSL's validation routine in our * own routine, which also validates the hostname by calling * the code provided by iSECPartners. Note that even though * the "Everything You've Always Wanted to Know About * Certificate Validation With OpenSSL (But Were Afraid to * Ask)" paper from iSECPartners says very explicitly not to * call SSL_CTX_set_cert_verify_callback (at the bottom of * page 2), what we're doing here is safe because our * cert_verify_callback() calls X509_verify_cert(), which is * OpenSSL's built-in routine which would have been called if * we hadn't set the callback. Therefore, we're just * "wrapping" OpenSSL's routine, not replacing it. */ SSL_CTX_set_cert_verify_callback(ssl_ctx, cert_verify_callback, (void *) host); #else // _WIN32 (void)crt; #endif // _WIN32 // Create event base base = event_base_new(); if (!base) { perror("event_base_new()"); goto error; } // Create OpenSSL bufferevent and stack evhttp on top of it ssl = SSL_new(ssl_ctx); if (ssl == NULL) { err_openssl("SSL_new()"); goto error; } #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME // Set hostname for SNI extension SSL_set_tlsext_host_name(ssl, host); #endif if (strcasecmp(scheme, "http") == 0) { bev = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE); } else { type = HTTPS; bev = bufferevent_openssl_socket_new(base, -1, ssl, BUFFEREVENT_SSL_CONNECTING, BEV_OPT_CLOSE_ON_FREE|BEV_OPT_DEFER_CALLBACKS); } if (bev == NULL) { fprintf(stderr, "bufferevent_openssl_socket_new() failed\n"); goto error; } bufferevent_openssl_set_allow_dirty_shutdown(bev, 1); // For simplicity, we let DNS resolution block. Everything else should be // asynchronous though. evcon = evhttp_connection_base_bufferevent_new(base, NULL, bev, host, port); if (evcon == NULL) { fprintf(stderr, "evhttp_connection_base_bufferevent_new() failed\n"); goto error; } if (retries > 0) { evhttp_connection_set_retries(evcon, retries); } if (timeout >= 0) { evhttp_connection_set_timeout(evcon, timeout); } // Fire off the request req = evhttp_request_new(http_request_done, bev); if (req == NULL) { fprintf(stderr, "evhttp_request_new() failed\n"); goto error; } output_headers = evhttp_request_get_output_headers(req); evhttp_add_header(output_headers, "Host", host); evhttp_add_header(output_headers, "Connection", "close"); if (data_file) { /* NOTE: In production code, you'd probably want to use * evbuffer_add_file() or evbuffer_add_file_segment(), to * avoid needless copying. */ FILE * f = fopen(data_file, "rb"); char buf[1024]; size_t s; size_t bytes = 0; if (!f) { syntax(); goto error; } output_buffer = evhttp_request_get_output_buffer(req); while ((s = fread(buf, 1, sizeof(buf), f)) > 0) { evbuffer_add(output_buffer, buf, s); bytes += s; } evutil_snprintf(buf, sizeof(buf)-1, "%lu", (unsigned long)bytes); evhttp_add_header(output_headers, "Content-Length", buf); fclose(f); } r = evhttp_make_request(evcon, req, data_file ? EVHTTP_REQ_POST : EVHTTP_REQ_GET, uri); if (r != 0) { fprintf(stderr, "evhttp_make_request() failed\n"); goto error; } event_base_dispatch(base); goto cleanup; error: ret = 1; cleanup: if (evcon) evhttp_connection_free(evcon); if (http_uri) evhttp_uri_free(http_uri); event_base_free(base); if (ssl_ctx) SSL_CTX_free(ssl_ctx); if (type == HTTP && ssl) SSL_free(ssl); #if OPENSSL_VERSION_NUMBER < 0x10100000L EVP_cleanup(); ERR_free_strings(); #ifdef EVENT__HAVE_ERR_REMOVE_THREAD_STATE ERR_remove_thread_state(NULL); #else ERR_remove_state(0); #endif CRYPTO_cleanup_all_ex_data(); sk_SSL_COMP_free(SSL_COMP_get_compression_methods()); #endif /*OPENSSL_VERSION_NUMBER < 0x10100000L */ #ifdef _WIN32 WSACleanup(); #endif return ret; }
static int new_peer() { int flag = 1; int fd = -1; struct sockaddr_in sin; SSL_CTX *ctx; SSL *ssl; memset(&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_addr.s_addr = htonl(0); sin.sin_port = htons(9093); if ((fd = socket(sin.sin_family, SOCK_STREAM, IPPROTO_TCP)) < 0) { jlog(L_ERROR, "socket failed"); goto out; } if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &flag, sizeof(flag)) < 0 || setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &flag, sizeof(flag)) < 0) { jlog(L_ERROR, "setsockopt failed"); goto out; } if (evutil_make_socket_nonblocking(fd) < 0) { jlog(L_ERROR, "evutil_make_socket_nonblocking failed"); goto out; } if ((ctx = evssl_init()) == NULL) { jlog(L_ERROR, "evssl_init failed"); goto out; } if ((ssl = SSL_new(ctx)) == NULL) { jlog(L_ERROR, "SSL_new failed"); goto out; } if ((bufev_sock = bufferevent_openssl_socket_new(base, fd, ssl, BUFFEREVENT_SSL_CONNECTING, BEV_OPT_CLOSE_ON_FREE)) == NULL) { jlog(L_ERROR, "bufferevent_socket_new failed"); goto out; } bufferevent_enable(bufev_sock, EV_READ|EV_WRITE); bufferevent_setcb(bufev_sock, on_read_cb, NULL, on_event_cb, NULL); if (bufferevent_socket_connect(bufev_sock, (struct sockaddr *)&sin, sizeof(sin)) < 0) { jlog(L_ERROR, "bufferevent_socket_connected failed"); goto out; } return 0; out: if (bufev_sock != NULL) bufferevent_free(bufev_sock); return -1; }
struct bufferevent* Listener::createBufferEvent(evutil_socket_t fd) { if (_ssl_ctx != NULL) return bufferevent_openssl_socket_new(GetEventBase(), fd, SSL_new(_ssl_ctx) ,BUFFEREVENT_SSL_ACCEPTING, BEV_OPT_CLOSE_ON_FREE|BEV_OPT_THREADSAFE); return bufferevent_socket_new(GetEventBase(), fd, BEV_OPT_CLOSE_ON_FREE|BEV_OPT_THREADSAFE); };
struct bufferevent* SSLListener::createBufferEvent(int fd) { return bufferevent_openssl_socket_new(Global::Get()->GetEventBase(), fd, SSL_new(ssl_ctx) ,BUFFEREVENT_SSL_ACCEPTING, BEV_OPT_CLOSE_ON_FREE|BEV_OPT_THREADSAFE); };