libmicrohttpd

HTTP/1.x server C library (MHD 1.x, stable)
Log | Files | Refs | Submodules | README | LICENSE

commit 40ad3037f98315bfa7e647098151b857059c37ac
parent 771c844be474916b8b29888a7214f0ca20fef557
Author: Christian Grothoff <christian@grothoff.org>
Date:   Sun,  5 May 2013 19:26:15 +0000

add testcases

Diffstat:
Asrc/testspdy/Makefile.am | 93+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/testspdy/common.c | 61+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/testspdy/common.h | 38++++++++++++++++++++++++++++++++++++++
Asrc/testspdy/test_daemon_start_stop.c | 49+++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/testspdy/test_daemon_start_stop_many.c | 66++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/testspdy/test_misc.c | 273+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/testspdy/test_new_connection.c | 981+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/testspdy/test_request_response.c | 990+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/testspdy/test_request_response_with_callback.c | 305++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/testspdy/test_requests_with_assets.c | 291++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/testspdy/test_session_timeout.c | 275+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/testspdy/test_struct_namevalue.c | 340+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
12 files changed, 3762 insertions(+), 0 deletions(-)

diff --git a/src/testspdy/Makefile.am b/src/testspdy/Makefile.am @@ -0,0 +1,93 @@ +SUBDIRS = . + +AM_CFLAGS = -DDATADIR=\"$(top_srcdir)/src/datadir/\" + +if USE_COVERAGE + AM_CFLAGS += -fprofile-arcs -ftest-coverage +endif + +if USE_PRIVATE_PLIBC_H + PLIBC_INCLUDE = -I$(top_srcdir)/src/include/plibc +endif + +AM_CPPFLAGS = \ + $(PLIBC_INCLUDE) \ + -I$(top_srcdir) \ + -I$(top_srcdir)/src/include \ + -I$(top_srcdir)/src/applicationlayer \ +$(LIBCURL_CPPFLAGS) + +if !HAVE_W32 +PERF_GET_CONCURRENT=perf_get_concurrent +endif + +check_PROGRAMS = \ + test_daemon_start_stop \ + test_daemon_start_stop_many \ + test_struct_namevalue \ + test_new_connection \ + test_request_response \ + test_request_response_with_callback \ + test_requests_with_assets \ + test_misc \ + test_session_timeout + +TESTS = $(check_PROGRAMS) + +SPDY_SOURCES= \ + common.h common.c + +SPDY_LDADD= \ + $(top_builddir)/src/microspdy/libmicrospdy.la \ + -lssl \ + -lcrypto \ + -lz \ + -ldl + +test_daemon_start_stop_SOURCES = \ + test_daemon_start_stop.c \ + $(SPDY_SOURCES) +test_daemon_start_stop_LDADD = $(SPDY_LDADD) + +test_daemon_start_stop_many_SOURCES = \ + test_daemon_start_stop_many.c \ + $(SPDY_SOURCES) +test_daemon_start_stop_many_LDADD = $(SPDY_LDADD) + +test_struct_namevalue_SOURCES = \ + test_struct_namevalue.c \ + $(SPDY_SOURCES) +test_struct_namevalue_LDADD = $(SPDY_LDADD) + +test_new_connection_SOURCES = \ + test_new_connection.c \ + $(SPDY_SOURCES) +test_new_connection_LDADD = $(SPDY_LDADD) \ + -lspdylay + +test_request_response_SOURCES = \ + test_request_response.c \ + $(SPDY_SOURCES) +test_request_response_LDADD = $(SPDY_LDADD) \ + -lspdylay + +test_request_response_with_callback_SOURCES = \ + test_request_response_with_callback.c \ + $(SPDY_SOURCES) +test_request_response_with_callback_LDADD = $(SPDY_LDADD) + +test_requests_with_assets_SOURCES = \ + test_requests_with_assets.c \ + $(SPDY_SOURCES) +test_requests_with_assets_LDADD = $(SPDY_LDADD) + +test_misc_SOURCES = \ + test_misc.c \ + $(SPDY_SOURCES) +test_misc_LDADD = $(SPDY_LDADD) + +test_session_timeout_SOURCES = \ + test_session_timeout.c \ + $(SPDY_SOURCES) +test_session_timeout_LDADD = $(SPDY_LDADD) + diff --git a/src/testspdy/common.c b/src/testspdy/common.c @@ -0,0 +1,61 @@ +/* + This file is part of libmicrospdy + Copyright (C) 2013 Andrey Uzunov + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +/** + * @file common.c + * @brief Common functions used by the tests. + * @author Andrey Uzunov + */ + + +#include "common.h" +#include <sys/time.h> + +#ifdef __GNUC__ +#define ATTRIBUTE_CONSTRUCTOR __attribute__ ((constructor)) +#define ATTRIBUTE_DESTRUCTOR __attribute__ ((destructor)) +#else // !__GNUC__ +#define ATTRIBUTE_CONSTRUCTOR +#define ATTRIBUTE_DESTRUCTOR +#endif // __GNUC__ + +void ATTRIBUTE_CONSTRUCTOR +constructor() +{ + printf("\nTEST START -------------------------------------------------------\n"); +} + +void ATTRIBUTE_DESTRUCTOR +destructor() +{ + printf("------------------------------------------------------- TEST END\n"); +} + +uint16_t +get_port(uint16_t min) +{ + struct timeval tv; + gettimeofday(&tv, NULL); + if(2 > min) min=2; + uint16_t port = min + (tv.tv_usec+10) % ((1 << 16) - min); + + //port = 12345; + printf("Port used: %i\n", port); + + return port; +} diff --git a/src/testspdy/common.h b/src/testspdy/common.h @@ -0,0 +1,38 @@ +/* + This file is part of libmicrospdy + Copyright (C) 2013 Andrey Uzunov + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +/** + * @file common.h + * @brief Common functions used by the tests. + * @author Andrey Uzunov + */ + +#include <stdlib.h> +#include <unistd.h> +#include <stdint.h> +#include <stdio.h> + +#define FAIL_TEST(msg) do{\ + printf("%i:%s\n", __LINE__, msg);\ + fflush(stdout);\ + exit(-10);\ + }\ + while(0) + +uint16_t +get_port(uint16_t min); diff --git a/src/testspdy/test_daemon_start_stop.c b/src/testspdy/test_daemon_start_stop.c @@ -0,0 +1,49 @@ +/* + This file is part of libmicrospdy + Copyright (C) 2012 Andrey Uzunov + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +/** + * @file daemon_start_stop.c + * @brief starts and stops a SPDY daemon + * @author Andrey Uzunov + */ + +#include "platform.h" +#include "microspdy.h" +#include "common.h" + +int +main() +{ + SPDY_init(); + + struct SPDY_Daemon *daemon = SPDY_start_daemon(get_port(16123), + DATADIR "cert-and-key.pem", + DATADIR "cert-and-key.pem", + NULL,NULL,NULL,NULL,NULL,SPDY_DAEMON_OPTION_END); + + if(NULL==daemon){ + printf("no daemon\n"); + return 1; + } + + SPDY_stop_daemon(daemon); + + SPDY_deinit(); + + return 0; +} diff --git a/src/testspdy/test_daemon_start_stop_many.c b/src/testspdy/test_daemon_start_stop_many.c @@ -0,0 +1,66 @@ +/* + This file is part of libmicrospdy + Copyright (C) 2012 Andrey Uzunov + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +/** + * @file daemon_start_stop_many.c + * @brief starts and stops several SPDY daemons, reusing port numbers + * @author Andrey Uzunov + */ + +#include "platform.h" +#include "microspdy.h" +#include "common.h" + +int +main() +{ + int i; + int j; + int num_daemons = 3; + int num_tries = 5; + int port = get_port(15123); + struct SPDY_Daemon *daemon[num_daemons]; + + SPDY_init(); + + for(i=0; i<num_tries; ++i) + { + for(j=0;j<num_daemons;++j) + { + daemon[j] = SPDY_start_daemon(port + j, + DATADIR "cert-and-key.pem", + DATADIR "cert-and-key.pem", + NULL,NULL,NULL,NULL,NULL,SPDY_DAEMON_OPTION_END); + + if(NULL==daemon[j]){ + printf("no daemon\n"); + return 1; + } + } + + + for(j=0;j<num_daemons;++j) + { + SPDY_stop_daemon(daemon[j]); + } + } + + SPDY_deinit(); + + return 0; +} diff --git a/src/testspdy/test_misc.c b/src/testspdy/test_misc.c @@ -0,0 +1,273 @@ +/* + This file is part of libmicrospdy + Copyright (C) 2013 Andrey Uzunov + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +/** + * @file misc.c + * @brief tests a lot of small calls and callbacks. TODO mention what + * @author Andrey Uzunov + */ + +#include "platform.h" +#include "microspdy.h" +#include "stdio.h" +#include <sys/wait.h> +#include "common.h" + +int port; + +#define HTML "<html><head>\ +<link href=\"main.css\" rel=\"stylesheet\" type=\"text/css\" />\ +</head><body>This is libmicrospdy</body></html>" + +#define CSS "body{font-size:15px}" + +#define SESSION_CLS "1234567890" + +#define REQUEST_CLS "1234567890REQ" + +pid_t parent; +pid_t child; + +struct SPDY_Session *session1; +struct SPDY_Session *session2; + +void +killchild() +{ + kill(child, SIGKILL); + exit(1); +} + +void +killparent() +{ + kill(parent, SIGKILL); + _exit(1); +} + + +void +create_child() +{ + parent = getpid(); + + child = fork(); + if (-1 == child) + { + fprintf(stderr, "can't fork, error %d\n", errno); + exit(EXIT_FAILURE); + } + + if (child == 0) + { + int devnull; + char *uri; + fflush(stdout); + devnull = open("/dev/null", O_WRONLY); + if (1 != devnull) + { + dup2(devnull, 1); + close(devnull); + } + asprintf(&uri,"https://127.0.0.1:%i/",port); + execlp("spdycat", "spdycat","-anv",uri,NULL ); + printf("execlp failed\n"); + killparent(); + } +} + +void +response_done_callback(void *cls, + struct SPDY_Response *response, + struct SPDY_Request *request, + bool streamopened) +{ + if(strcmp(cls,"/main.css")) + { + session1 = SPDY_get_session_for_request(request); + if(NULL == session1) + { + printf("SPDY_get_session_for_request failed\n"); + killchild(); + } + + char *session_cls = strdup(SESSION_CLS); + SPDY_set_cls_to_session(session1,session_cls); + } + else + { + session2 = SPDY_get_session_for_request(request); + if(session1 != session2) + { + printf("SPDY_get_session_for_request failed the second time\n"); + killchild(); + } + printf("SPDY_get_session_for_request tested...\n"); + + void *session_cls = SPDY_get_cls_from_session(session2); + if(NULL == session_cls || strcmp(session_cls, SESSION_CLS)) + { + printf("SPDY_get_cls_from_session failed\n"); + killchild(); + } + printf("SPDY_set_cls_to_session tested...\n"); + printf("SPDY_get_cls_from_session tested...\n"); + + void *request_cls = SPDY_get_cls_from_request(request); + if(NULL == request_cls || strcmp(request_cls, REQUEST_CLS)) + { + printf("SPDY_get_cls_from_request failed\n"); + killchild(); + } + printf("SPDY_set_cls_to_request tested...\n"); + printf("SPDY_get_cls_from_request tested...\n"); + } + + SPDY_destroy_request(request); + SPDY_destroy_response(response); + free(cls); +} + +void +standard_request_handler(void *cls, + struct SPDY_Request * request, + uint8_t priority, + const char *method, + const char *path, + const char *version, + const char *host, + const char *scheme, + struct SPDY_NameValue * headers) +{ + struct SPDY_Response *response=NULL; + char *cls_path = strdup(path); + + if(strcmp(path,"/main.css")==0) + { + char *request_cls = strdup(REQUEST_CLS); + SPDY_set_cls_to_request(request,request_cls); + response = SPDY_build_response(200,NULL,SPDY_HTTP_VERSION_1_1,NULL,CSS,strlen(CSS)); + } + else + { + response = SPDY_build_response(200,NULL,SPDY_HTTP_VERSION_1_1,NULL,HTML,strlen(HTML)); + } + + if(NULL==response){ + fprintf(stdout,"no response obj\n"); + killchild(); + } + + if(SPDY_queue_response(request,response,true,false,&response_done_callback,cls_path)!=SPDY_YES) + { + fprintf(stdout,"queue\n"); + killchild(); + } +} + +int +parentproc() +{ + int childstatus; + unsigned long long timeoutlong=0; + struct timeval timeout; + int ret; + fd_set read_fd_set; + fd_set write_fd_set; + fd_set except_fd_set; + int maxfd = -1; + struct SPDY_Daemon *daemon; + + SPDY_init(); + + daemon = SPDY_start_daemon(port, + DATADIR "cert-and-key.pem", + DATADIR "cert-and-key.pem", + NULL, + NULL, + &standard_request_handler, + NULL, + NULL, + SPDY_DAEMON_OPTION_SESSION_TIMEOUT, + 1800, + SPDY_DAEMON_OPTION_END); + + if(NULL==daemon){ + printf("no daemon\n"); + return 1; + } + + timeout.tv_usec = 0; + create_child(); + + do + { + FD_ZERO(&read_fd_set); + FD_ZERO(&write_fd_set); + FD_ZERO(&except_fd_set); + + ret = SPDY_get_timeout(daemon, &timeoutlong); + if(SPDY_NO == ret || timeoutlong > 1) + { + timeout.tv_sec = 1; + } + else + { + timeout.tv_sec = timeoutlong; + } + + maxfd = SPDY_get_fdset (daemon, + &read_fd_set, + &write_fd_set, + &except_fd_set); + + ret = select(maxfd+1, &read_fd_set, &write_fd_set, &except_fd_set, &timeout); + + switch(ret) { + case -1: + printf("select error: %i\n", errno); + break; + case 0: + + break; + default: + SPDY_run(daemon); + + break; + } + } + while(waitpid(child,&childstatus,WNOHANG) != child); + + SPDY_stop_daemon(daemon); + + return WEXITSTATUS(childstatus); +} + + +int +main(int argc, char **argv) +{ + port = get_port(13123); + SPDY_init(); + + int ret = parentproc(); + + SPDY_deinit(); + + return ret; +} diff --git a/src/testspdy/test_new_connection.c b/src/testspdy/test_new_connection.c @@ -0,0 +1,981 @@ +/* + This file is part of libmicrospdy + Copyright (C) 2012 Andrey Uzunov + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +/** + * @file request_response.c + * @brief tests new connection callback. spdycli.c + * code is reused here + * @author Andrey Uzunov + * @author Tatsuhiro Tsujikawa + */ + + //TODO child exits with ret val 1 sometimes + +#include "platform.h" +#include "microspdy.h" +#include <sys/wait.h> +#include "common.h" + +#define RESPONSE_BODY "<html><body><b>Hi, this is libmicrospdy!</b></body></html>" + +#define CLS "anything" + +int port; +int loop = 1; + +pid_t parent; +pid_t child; + +int +spdylay_printf(const char *format, ...) +{ + return 0; +} + +int +spdylay_fprintf(FILE *stream, const char *format, ...) +{ + return 0; +} + +void +killchild(int pid, char *message) +{ + printf("%s\n",message); + kill(pid, SIGKILL); + exit(1); +} + +void +killparent(int pid, char *message) +{ + printf("%s\n",message); + kill(pid, SIGKILL); + _exit(2); +} + + +/***** + * start of code needed to utilize spdylay + */ + +#include <stdint.h> +#include <stdlib.h> +#include <unistd.h> +#include <fcntl.h> +#include <sys/types.h> +#include <sys/socket.h> +#include <netdb.h> +#include <netinet/in.h> +#include <netinet/tcp.h> +#include <poll.h> +#include <signal.h> +#include <stdio.h> +#include <assert.h> + +#include <spdylay/spdylay.h> + +#include <openssl/ssl.h> +#include <openssl/err.h> + +enum { + IO_NONE, + WANT_READ, + WANT_WRITE +}; + +struct Connection { + SSL *ssl; + spdylay_session *session; + /* WANT_READ if SSL connection needs more input; or WANT_WRITE if it + needs more output; or IO_NONE. This is necessary because SSL/TLS + re-negotiation is possible at any time. Spdylay API offers + similar functions like spdylay_session_want_read() and + spdylay_session_want_write() but they do not take into account + SSL connection. */ + int want_io; +}; + +struct Request { + char *host; + uint16_t port; + /* In this program, path contains query component as well. */ + char *path; + /* This is the concatenation of host and port with ":" in + between. */ + char *hostport; + /* Stream ID for this request. */ + int32_t stream_id; + /* The gzip stream inflater for the compressed response. */ + spdylay_gzip *inflater; +}; + +struct URI { + const char *host; + size_t hostlen; + uint16_t port; + /* In this program, path contains query component as well. */ + const char *path; + size_t pathlen; + const char *hostport; + size_t hostportlen; +}; + +/* + * Returns copy of string |s| with the length |len|. The returned + * string is NULL-terminated. + */ +static char* strcopy(const char *s, size_t len) +{ + char *dst; + dst = malloc(len+1); + memcpy(dst, s, len); + dst[len] = '\0'; + return dst; +} + +/* + * Prints error message |msg| and exit. + */ +static void die(const char *msg) +{ + fprintf(stderr, "FATAL: %s\n", msg); + exit(EXIT_FAILURE); +} + +/* + * Prints error containing the function name |func| and message |msg| + * and exit. + */ +static void dief(const char *func, const char *msg) +{ + fprintf(stderr, "FATAL: %s: %s\n", func, msg); + exit(EXIT_FAILURE); +} + +/* + * Prints error containing the function name |func| and error code + * |error_code| and exit. + */ +static void diec(const char *func, int error_code) +{ + fprintf(stderr, "FATAL: %s: error_code=%d, msg=%s\n", func, error_code, + spdylay_strerror(error_code)); + exit(EXIT_FAILURE); +} + +/* + * Check response is content-encoding: gzip. We need this because SPDY + * client is required to support gzip. + */ +static void check_gzip(struct Request *req, char **nv) +{ + int gzip = 0; + size_t i; + for(i = 0; nv[i]; i += 2) { + if(strcmp("content-encoding", nv[i]) == 0) { + gzip = strcmp("gzip", nv[i+1]) == 0; + break; + } + } + if(gzip) { + int rv; + if(req->inflater) { + return; + } + rv = spdylay_gzip_inflate_new(&req->inflater); + if(rv != 0) { + die("Can't allocate inflate stream."); + } + } +} + +/* + * The implementation of spdylay_send_callback type. Here we write + * |data| with size |length| to the network and return the number of + * bytes actually written. See the documentation of + * spdylay_send_callback for the details. + */ +static ssize_t send_callback(spdylay_session *session, + const uint8_t *data, size_t length, int flags, + void *user_data) +{ + struct Connection *connection; + ssize_t rv; + connection = (struct Connection*)user_data; + connection->want_io = IO_NONE; + ERR_clear_error(); + rv = SSL_write(connection->ssl, data, length); + if(rv < 0) { + int err = SSL_get_error(connection->ssl, rv); + if(err == SSL_ERROR_WANT_WRITE || err == SSL_ERROR_WANT_READ) { + connection->want_io = (err == SSL_ERROR_WANT_READ ? + WANT_READ : WANT_WRITE); + rv = SPDYLAY_ERR_WOULDBLOCK; + } else { + rv = SPDYLAY_ERR_CALLBACK_FAILURE; + } + } + return rv; +} + +/* + * The implementation of spdylay_recv_callback type. Here we read data + * from the network and write them in |buf|. The capacity of |buf| is + * |length| bytes. Returns the number of bytes stored in |buf|. See + * the documentation of spdylay_recv_callback for the details. + */ +static ssize_t recv_callback(spdylay_session *session, + uint8_t *buf, size_t length, int flags, + void *user_data) +{ + struct Connection *connection; + ssize_t rv; + connection = (struct Connection*)user_data; + connection->want_io = IO_NONE; + ERR_clear_error(); + rv = SSL_read(connection->ssl, buf, length); + if(rv < 0) { + int err = SSL_get_error(connection->ssl, rv); + if(err == SSL_ERROR_WANT_WRITE || err == SSL_ERROR_WANT_READ) { + connection->want_io = (err == SSL_ERROR_WANT_READ ? + WANT_READ : WANT_WRITE); + rv = SPDYLAY_ERR_WOULDBLOCK; + } else { + rv = SPDYLAY_ERR_CALLBACK_FAILURE; + } + } else if(rv == 0) { + rv = SPDYLAY_ERR_EOF; + } + return rv; +} + +/* + * The implementation of spdylay_before_ctrl_send_callback type. We + * use this function to get stream ID of the request. This is because + * stream ID is not known when we submit the request + * (spdylay_submit_request). + */ +static void before_ctrl_send_callback(spdylay_session *session, + spdylay_frame_type type, + spdylay_frame *frame, + void *user_data) +{ + if(type == SPDYLAY_SYN_STREAM) { + struct Request *req; + int stream_id = frame->syn_stream.stream_id; + req = spdylay_session_get_stream_user_data(session, stream_id); + if(req && req->stream_id == -1) { + req->stream_id = stream_id; + spdylay_printf("[INFO] Stream ID = %d\n", stream_id); + } + } +} + +static void on_ctrl_send_callback(spdylay_session *session, + spdylay_frame_type type, + spdylay_frame *frame, void *user_data) +{ + char **nv; + const char *name = NULL; + int32_t stream_id; + size_t i; + switch(type) { + case SPDYLAY_SYN_STREAM: + nv = frame->syn_stream.nv; + name = "SYN_STREAM"; + stream_id = frame->syn_stream.stream_id; + break; + default: + break; + } + if(name && spdylay_session_get_stream_user_data(session, stream_id)) { + spdylay_printf("[INFO] C ----------------------------> S (%s)\n", name); + for(i = 0; nv[i]; i += 2) { + spdylay_printf(" %s: %s\n", nv[i], nv[i+1]); + } + } +} + +static void on_ctrl_recv_callback(spdylay_session *session, + spdylay_frame_type type, + spdylay_frame *frame, void *user_data) +{ + struct Request *req; + char **nv; + const char *name = NULL; + int32_t stream_id; + size_t i; + switch(type) { + case SPDYLAY_SYN_REPLY: + nv = frame->syn_reply.nv; + name = "SYN_REPLY"; + stream_id = frame->syn_reply.stream_id; + break; + case SPDYLAY_HEADERS: + nv = frame->headers.nv; + name = "HEADERS"; + stream_id = frame->headers.stream_id; + break; + default: + break; + } + if(!name) { + return; + } + req = spdylay_session_get_stream_user_data(session, stream_id); + if(req) { + check_gzip(req, nv); + spdylay_printf("[INFO] C <---------------------------- S (%s)\n", name); + for(i = 0; nv[i]; i += 2) { + spdylay_printf(" %s: %s\n", nv[i], nv[i+1]); + } + } +} + +/* + * The implementation of spdylay_on_stream_close_callback type. We use + * this function to know the response is fully received. Since we just + * fetch 1 resource in this program, after reception of the response, + * we submit GOAWAY and close the session. + */ +static void on_stream_close_callback(spdylay_session *session, + int32_t stream_id, + spdylay_status_code status_code, + void *user_data) +{ + struct Request *req; + req = spdylay_session_get_stream_user_data(session, stream_id); + if(req) { + int rv; + rv = spdylay_submit_goaway(session, SPDYLAY_GOAWAY_OK); + if(rv != 0) { + diec("spdylay_submit_goaway", rv); + } + } +} + +#define MAX_OUTLEN 4096 + +/* + * The implementation of spdylay_on_data_chunk_recv_callback type. We + * use this function to print the received response body. + */ +static void on_data_chunk_recv_callback(spdylay_session *session, uint8_t flags, + int32_t stream_id, + const uint8_t *data, size_t len, + void *user_data) +{ + struct Request *req; + req = spdylay_session_get_stream_user_data(session, stream_id); + if(req) { + spdylay_printf("[INFO] C <---------------------------- S (DATA)\n"); + spdylay_printf(" %lu bytes\n", (unsigned long int)len); + if(req->inflater) { + while(len > 0) { + uint8_t out[MAX_OUTLEN]; + size_t outlen = MAX_OUTLEN; + size_t tlen = len; + int rv; + rv = spdylay_gzip_inflate(req->inflater, out, &outlen, data, &tlen); + if(rv == -1) { + spdylay_submit_rst_stream(session, stream_id, SPDYLAY_INTERNAL_ERROR); + break; + } + fwrite(out, 1, outlen, stdout); + data += tlen; + len -= tlen; + } + } else { + /* TODO add support gzip */ + fwrite(data, 1, len, stdout); + + //check if the data is correct + if(strcmp(RESPONSE_BODY, (char *)data) != 0) + killparent(parent, "\nreceived data is not the same"); + } + spdylay_printf("\n"); + } +} + +/* + * Setup callback functions. Spdylay API offers many callback + * functions, but most of them are optional. The send_callback is + * always required. Since we use spdylay_session_recv(), the + * recv_callback is also required. + */ +static void setup_spdylay_callbacks(spdylay_session_callbacks *callbacks) +{ + memset(callbacks, 0, sizeof(spdylay_session_callbacks)); + callbacks->send_callback = send_callback; + callbacks->recv_callback = recv_callback; + callbacks->before_ctrl_send_callback = before_ctrl_send_callback; + callbacks->on_ctrl_send_callback = on_ctrl_send_callback; + callbacks->on_ctrl_recv_callback = on_ctrl_recv_callback; + callbacks->on_stream_close_callback = on_stream_close_callback; + callbacks->on_data_chunk_recv_callback = on_data_chunk_recv_callback; +} + +/* + * Callback function for SSL/TLS NPN. Since this program only supports + * SPDY protocol, if server does not offer SPDY protocol the Spdylay + * library supports, we terminate program. + */ +static int select_next_proto_cb(SSL* ssl, + unsigned char **out, unsigned char *outlen, + const unsigned char *in, unsigned int inlen, + void *arg) +{ + int rv; + uint16_t *spdy_proto_version; + /* spdylay_select_next_protocol() selects SPDY protocol version the + Spdylay library supports. */ + rv = spdylay_select_next_protocol(out, outlen, in, inlen); + if(rv <= 0) { + die("Server did not advertise spdy/2 or spdy/3 protocol."); + } + spdy_proto_version = (uint16_t*)arg; + *spdy_proto_version = rv; + return SSL_TLSEXT_ERR_OK; +} + +/* + * Setup SSL context. We pass |spdy_proto_version| to get negotiated + * SPDY protocol version in NPN callback. + */ +static void init_ssl_ctx(SSL_CTX *ssl_ctx, uint16_t *spdy_proto_version) +{ + /* Disable SSLv2 and enable all workarounds for buggy servers */ + SSL_CTX_set_options(ssl_ctx, SSL_OP_ALL|SSL_OP_NO_SSLv2); + SSL_CTX_set_mode(ssl_ctx, SSL_MODE_AUTO_RETRY); + SSL_CTX_set_mode(ssl_ctx, SSL_MODE_RELEASE_BUFFERS); + /* Set NPN callback */ + SSL_CTX_set_next_proto_select_cb(ssl_ctx, select_next_proto_cb, + spdy_proto_version); +} + +static void ssl_handshake(SSL *ssl, int fd) +{ + int rv; + if(SSL_set_fd(ssl, fd) == 0) { + dief("SSL_set_fd", ERR_error_string(ERR_get_error(), NULL)); + } + ERR_clear_error(); + rv = SSL_connect(ssl); + if(rv <= 0) { + dief("SSL_connect", ERR_error_string(ERR_get_error(), NULL)); + } +} + +/* + * Connects to the host |host| and port |port|. This function returns + * the file descriptor of the client socket. + */ +static int connect_to(const char *host, uint16_t port) +{ + struct addrinfo hints; + int fd = -1; + int rv; + char service[NI_MAXSERV]; + struct addrinfo *res, *rp; + snprintf(service, sizeof(service), "%u", port); + memset(&hints, 0, sizeof(struct addrinfo)); + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_STREAM; + rv = getaddrinfo(host, service, &hints, &res); + if(rv != 0) { + dief("getaddrinfo", gai_strerror(rv)); + } + for(rp = res; rp; rp = rp->ai_next) { + fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); + if(fd == -1) { + continue; + } + while((rv = connect(fd, rp->ai_addr, rp->ai_addrlen)) == -1 && + errno == EINTR); + if(rv == 0) { + break; + } + close(fd); + fd = -1; + } + freeaddrinfo(res); + return fd; +} + +static void make_non_block(int fd) +{ + int flags, rv; + while((flags = fcntl(fd, F_GETFL, 0)) == -1 && errno == EINTR); + if(flags == -1) { + dief("fcntl", strerror(errno)); + } + while((rv = fcntl(fd, F_SETFL, flags | O_NONBLOCK)) == -1 && errno == EINTR); + if(rv == -1) { + dief("fcntl", strerror(errno)); + } +} + +/* + * Setting TCP_NODELAY is not mandatory for the SPDY protocol. + */ +static void set_tcp_nodelay(int fd) +{ + int val = 1; + int rv; + rv = setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &val, (socklen_t)sizeof(val)); + if(rv == -1) { + dief("setsockopt", strerror(errno)); + } +} + +/* + * Update |pollfd| based on the state of |connection|. + */ +static void ctl_poll(struct pollfd *pollfd, struct Connection *connection) +{ + pollfd->events = 0; + if(spdylay_session_want_read(connection->session) || + connection->want_io == WANT_READ) { + pollfd->events |= POLLIN; + } + if(spdylay_session_want_write(connection->session) || + connection->want_io == WANT_WRITE) { + pollfd->events |= POLLOUT; + } +} + +/* + * Submits the request |req| to the connection |connection|. This + * function does not send packets; just append the request to the + * internal queue in |connection->session|. + */ +static void submit_request(struct Connection *connection, struct Request *req) +{ + int pri = 0; + int rv; + const char *nv[15]; + /* We always use SPDY/3 style header even if the negotiated protocol + version is SPDY/2. The library translates the header name as + necessary. Make sure that the last item is NULL! */ + nv[0] = ":method"; nv[1] = "GET"; + nv[2] = ":path"; nv[3] = req->path; + nv[4] = ":version"; nv[5] = "HTTP/1.1"; + nv[6] = ":scheme"; nv[7] = "https"; + nv[8] = ":host"; nv[9] = req->hostport; + nv[10] = "accept"; nv[11] = "*/*"; + nv[12] = "user-agent"; nv[13] = "spdylay/"SPDYLAY_VERSION; + nv[14] = NULL; + rv = spdylay_submit_request(connection->session, pri, nv, NULL, req); + if(rv != 0) { + diec("spdylay_submit_request", rv); + } +} + +/* + * Performs the network I/O. + */ +static void exec_io(struct Connection *connection) +{ + int rv; + rv = spdylay_session_recv(connection->session); + if(rv != 0) { + diec("spdylay_session_recv", rv); + } + rv = spdylay_session_send(connection->session); + if(rv != 0) { + diec("spdylay_session_send", rv); + } +} + +static void request_init(struct Request *req, const struct URI *uri) +{ + req->host = strcopy(uri->host, uri->hostlen); + req->port = uri->port; + req->path = strcopy(uri->path, uri->pathlen); + req->hostport = strcopy(uri->hostport, uri->hostportlen); + req->stream_id = -1; + req->inflater = NULL; +} + +static void request_free(struct Request *req) +{ + free(req->host); + free(req->path); + free(req->hostport); + spdylay_gzip_inflate_del(req->inflater); +} + +/* + * Fetches the resource denoted by |uri|. + */ +static void fetch_uri(const struct URI *uri) +{ + spdylay_session_callbacks callbacks; + int fd; + SSL_CTX *ssl_ctx; + SSL *ssl; + struct Request req; + struct Connection connection; + int rv; + nfds_t npollfds = 1; + struct pollfd pollfds[1]; + uint16_t spdy_proto_version; + + request_init(&req, uri); + + setup_spdylay_callbacks(&callbacks); + + /* Establish connection and setup SSL */ + fd = connect_to(req.host, req.port); + ssl_ctx = SSL_CTX_new(SSLv23_client_method()); + if(ssl_ctx == NULL) { + dief("SSL_CTX_new", ERR_error_string(ERR_get_error(), NULL)); + } + init_ssl_ctx(ssl_ctx, &spdy_proto_version); + ssl = SSL_new(ssl_ctx); + if(ssl == NULL) { + dief("SSL_new", ERR_error_string(ERR_get_error(), NULL)); + } + /* To simplify the program, we perform SSL/TLS handshake in blocking + I/O. */ + ssl_handshake(ssl, fd); + + connection.ssl = ssl; + connection.want_io = IO_NONE; + + /* Here make file descriptor non-block */ + make_non_block(fd); + set_tcp_nodelay(fd); + + spdylay_printf("[INFO] SPDY protocol version = %d\n", spdy_proto_version); + rv = spdylay_session_client_new(&connection.session, spdy_proto_version, + &callbacks, &connection); + if(rv != 0) { + diec("spdylay_session_client_new", rv); + } + + /* Submit the HTTP request to the outbound queue. */ + submit_request(&connection, &req); + + pollfds[0].fd = fd; + ctl_poll(pollfds, &connection); + + /* Event loop */ + while(spdylay_session_want_read(connection.session) || + spdylay_session_want_write(connection.session)) { + int nfds = poll(pollfds, npollfds, -1); + if(nfds == -1) { + dief("poll", strerror(errno)); + } + if(pollfds[0].revents & (POLLIN | POLLOUT)) { + exec_io(&connection); + } + if((pollfds[0].revents & POLLHUP) || (pollfds[0].revents & POLLERR)) { + die("Connection error"); + } + ctl_poll(pollfds, &connection); + } + + /* Resource cleanup */ + spdylay_session_del(connection.session); + SSL_shutdown(ssl); + SSL_free(ssl); + SSL_CTX_free(ssl_ctx); + shutdown(fd, SHUT_WR); + close(fd); + request_free(&req); +} + +static int parse_uri(struct URI *res, const char *uri) +{ + /* We only interested in https */ + size_t len, i, offset; + memset(res, 0, sizeof(struct URI)); + len = strlen(uri); + if(len < 9 || memcmp("https://", uri, 8) != 0) { + return -1; + } + offset = 8; + res->host = res->hostport = &uri[offset]; + res->hostlen = 0; + if(uri[offset] == '[') { + /* IPv6 literal address */ + ++offset; + ++res->host; + for(i = offset; i < len; ++i) { + if(uri[i] == ']') { + res->hostlen = i-offset; + offset = i+1; + break; + } + } + } else { + const char delims[] = ":/?#"; + for(i = offset; i < len; ++i) { + if(strchr(delims, uri[i]) != NULL) { + break; + } + } + res->hostlen = i-offset; + offset = i; + } + if(res->hostlen == 0) { + return -1; + } + /* Assuming https */ + res->port = 443; + if(offset < len) { + if(uri[offset] == ':') { + /* port */ + const char delims[] = "/?#"; + int port = 0; + ++offset; + for(i = offset; i < len; ++i) { + if(strchr(delims, uri[i]) != NULL) { + break; + } + if('0' <= uri[i] && uri[i] <= '9') { + port *= 10; + port += uri[i]-'0'; + if(port > 65535) { + return -1; + } + } else { + return -1; + } + } + if(port == 0) { + return -1; + } + offset = i; + res->port = port; + } + } + res->hostportlen = uri+offset-res->host; + for(i = offset; i < len; ++i) { + if(uri[i] == '#') { + break; + } + } + if(i-offset == 0) { + res->path = "/"; + res->pathlen = 1; + } else { + res->path = &uri[offset]; + res->pathlen = i-offset; + } + return 0; +} + + +/***** + * end of code needed to utilize spdylay + */ + + +/***** + * start of code needed to utilize microspdy + */ + +void +new_session_callback (void *cls, + struct SPDY_Session * session) +{ + char ipstr[1024]; + + const struct sockaddr *addr; + socklen_t addr_len = SPDY_get_remote_addr(session, &addr); + + if(!addr_len) + { + printf("SPDY_get_remote_addr"); + abort(); + } + + if(strcmp(CLS,cls)!=0) + { + killchild(child,"wrong cls"); + } + + if(AF_INET == addr->sa_family) + { + struct sockaddr_in * addr4 = (struct sockaddr_in *) addr; + if(NULL == inet_ntop(AF_INET, &(addr4->sin_addr), ipstr, sizeof(ipstr))) + { + killchild(child,"inet_ntop"); + } + printf("New connection from: %s:%i\n", ipstr, ntohs(addr4->sin_port)); + + loop = 0; + } +#if HAVE_INET6 + else if(AF_INET6 == addr->sa_family) + { + struct sockaddr_in6 * addr6 = (struct sockaddr_in6 *) addr; + if(NULL == inet_ntop(AF_INET6, &(addr6->sin6_addr), ipstr, sizeof(ipstr))) + { + killchild(child,"inet_ntop"); + } + printf("New connection from: %s:%i\n", ipstr, ntohs(addr6->sin6_port)); + + loop = 0; + } +#endif + else + { + killchild(child,"wrong family"); + } +} + +/***** + * end of code needed to utilize microspdy + */ + +//child process +void +childproc(int parent) +{ + struct URI uri; + struct sigaction act; + int rv; + char *uristr; + + memset(&act, 0, sizeof(struct sigaction)); + act.sa_handler = SIG_IGN; + sigaction(SIGPIPE, &act, 0); + + asprintf(&uristr, "https://127.0.0.1:%i/",port); + + SSL_load_error_strings(); + SSL_library_init(); + + rv = parse_uri(&uri, uristr); + if(rv != 0) { + killparent(parent,"parse_uri failed"); + } + fetch_uri(&uri); +} + +//parent proc +int +parentproc(int child) +{ + int childstatus = 0; + unsigned long long timeoutlong=0; + struct timeval timeout; + int ret; + fd_set read_fd_set; + fd_set write_fd_set; + fd_set except_fd_set; + int maxfd = -1; + struct SPDY_Daemon *daemon; + + SPDY_init(); + + daemon = SPDY_start_daemon(port, + DATADIR "cert-and-key.pem", + DATADIR "cert-and-key.pem", + &new_session_callback,NULL,NULL,NULL,CLS,SPDY_DAEMON_OPTION_END); + + if(NULL==daemon){ + printf("no daemon\n"); + return 1; + } + + timeout.tv_usec = 0; + + do + { + FD_ZERO(&read_fd_set); + FD_ZERO(&write_fd_set); + FD_ZERO(&except_fd_set); + + ret = SPDY_get_timeout(daemon, &timeoutlong); + if(SPDY_NO == ret || timeoutlong > 1) + { + timeout.tv_sec = 1; + } + else + { + timeout.tv_sec = timeoutlong; + } + + maxfd = SPDY_get_fdset (daemon, + &read_fd_set, + &write_fd_set, + &except_fd_set); + + ret = select(maxfd+1, &read_fd_set, &write_fd_set, &except_fd_set, &timeout); + + switch(ret) { + case -1: + printf("select error: %i\n", errno); + killchild(child, "select error"); + break; + case 0: + + break; + default: + SPDY_run(daemon); + + break; + } + } + while(loop && waitpid(child,&childstatus,WNOHANG) != child); + + SPDY_stop_daemon(daemon); + + SPDY_deinit(); + + if(loop) + return WEXITSTATUS(childstatus); + if(waitpid(child,&childstatus,WNOHANG) == child) + return WEXITSTATUS(childstatus); + + kill(child,SIGKILL); + + waitpid(child,&childstatus,0); + + return 0; +} + +int main(int argc, char **argv) +{ + port = get_port(14123); + parent = getpid(); + + child = fork(); + if (child == -1) + { + fprintf(stderr, "can't fork, error %d\n", errno); + exit(EXIT_FAILURE); + } + + if (child == 0) + { + childproc(parent); + _exit(0); + } + else + { + int ret = parentproc(child); + exit(ret); + } + return 1; +} diff --git a/src/testspdy/test_request_response.c b/src/testspdy/test_request_response.c @@ -0,0 +1,990 @@ +/* + This file is part of libmicrospdy + Copyright (C) 2012 Andrey Uzunov + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +/** + * @file request_response.c + * @brief tests receiving request and sending response. spdycli.c (spdylay) + * code is reused here + * @author Andrey Uzunov + * @author Tatsuhiro Tsujikawa + */ + +#include "platform.h" +#include "microspdy.h" +#include <sys/wait.h> +#include "common.h" + +#define RESPONSE_BODY "<html><body><b>Hi, this is libmicrospdy!</b></body></html>" + +#define CLS "anything" + +pid_t parent; +pid_t child; +char *rcvbuf; +int rcvbuf_c = 0; + +int session_closed_called = 0; + +void +killchild(int pid, char *message) +{ + printf("%s\n",message); + kill(pid, SIGKILL); + exit(1); +} + +void +killparent(int pid, char *message) +{ + printf("%s\n",message); + kill(pid, SIGKILL); + _exit(1); +} + + +/***** + * start of code needed to utilize spdylay + */ + +#include <stdint.h> +#include <stdlib.h> +#include <unistd.h> +#include <fcntl.h> +#include <sys/types.h> +#include <sys/socket.h> +#include <netdb.h> +#include <netinet/in.h> +#include <netinet/tcp.h> +#include <poll.h> +#include <signal.h> +#include <stdio.h> +#include <assert.h> + +#include <spdylay/spdylay.h> + +#include <openssl/ssl.h> +#include <openssl/err.h> + +enum { + IO_NONE, + WANT_READ, + WANT_WRITE +}; + +struct Connection { + SSL *ssl; + spdylay_session *session; + /* WANT_READ if SSL connection needs more input; or WANT_WRITE if it + needs more output; or IO_NONE. This is necessary because SSL/TLS + re-negotiation is possible at any time. Spdylay API offers + similar functions like spdylay_session_want_read() and + spdylay_session_want_write() but they do not take into account + SSL connection. */ + int want_io; +}; + +struct Request { + char *host; + uint16_t port; + /* In this program, path contains query component as well. */ + char *path; + /* This is the concatenation of host and port with ":" in + between. */ + char *hostport; + /* Stream ID for this request. */ + int32_t stream_id; + /* The gzip stream inflater for the compressed response. */ + spdylay_gzip *inflater; +}; + +struct URI { + const char *host; + size_t hostlen; + uint16_t port; + /* In this program, path contains query component as well. */ + const char *path; + size_t pathlen; + const char *hostport; + size_t hostportlen; +}; + +/* + * Returns copy of string |s| with the length |len|. The returned + * string is NULL-terminated. + */ +static char* strcopy(const char *s, size_t len) +{ + char *dst; + dst = malloc(len+1); + memcpy(dst, s, len); + dst[len] = '\0'; + return dst; +} + +/* + * Prints error message |msg| and exit. + */ +static void die(const char *msg) +{ + fprintf(stderr, "FATAL: %s\n", msg); + exit(EXIT_FAILURE); +} + +/* + * Prints error containing the function name |func| and message |msg| + * and exit. + */ +static void dief(const char *func, const char *msg) +{ + fprintf(stderr, "FATAL: %s: %s\n", func, msg); + exit(EXIT_FAILURE); +} + +/* + * Prints error containing the function name |func| and error code + * |error_code| and exit. + */ +static void diec(const char *func, int error_code) +{ + fprintf(stderr, "FATAL: %s: error_code=%d, msg=%s\n", func, error_code, + spdylay_strerror(error_code)); + exit(EXIT_FAILURE); +} + +/* + * Check response is content-encoding: gzip. We need this because SPDY + * client is required to support gzip. + */ +static void check_gzip(struct Request *req, char **nv) +{ + int gzip = 0; + size_t i; + for(i = 0; nv[i]; i += 2) { + if(strcmp("content-encoding", nv[i]) == 0) { + gzip = strcmp("gzip", nv[i+1]) == 0; + break; + } + } + if(gzip) { + int rv; + if(req->inflater) { + return; + } + rv = spdylay_gzip_inflate_new(&req->inflater); + if(rv != 0) { + die("Can't allocate inflate stream."); + } + } +} + +/* + * The implementation of spdylay_send_callback type. Here we write + * |data| with size |length| to the network and return the number of + * bytes actually written. See the documentation of + * spdylay_send_callback for the details. + */ +static ssize_t send_callback(spdylay_session *session, + const uint8_t *data, size_t length, int flags, + void *user_data) +{ + struct Connection *connection; + ssize_t rv; + connection = (struct Connection*)user_data; + connection->want_io = IO_NONE; + ERR_clear_error(); + rv = SSL_write(connection->ssl, data, length); + if(rv < 0) { + int err = SSL_get_error(connection->ssl, rv); + if(err == SSL_ERROR_WANT_WRITE || err == SSL_ERROR_WANT_READ) { + connection->want_io = (err == SSL_ERROR_WANT_READ ? + WANT_READ : WANT_WRITE); + rv = SPDYLAY_ERR_WOULDBLOCK; + } else { + rv = SPDYLAY_ERR_CALLBACK_FAILURE; + } + } + return rv; +} + +/* + * The implementation of spdylay_recv_callback type. Here we read data + * from the network and write them in |buf|. The capacity of |buf| is + * |length| bytes. Returns the number of bytes stored in |buf|. See + * the documentation of spdylay_recv_callback for the details. + */ +static ssize_t recv_callback(spdylay_session *session, + uint8_t *buf, size_t length, int flags, + void *user_data) +{ + struct Connection *connection; + ssize_t rv; + connection = (struct Connection*)user_data; + connection->want_io = IO_NONE; + ERR_clear_error(); + rv = SSL_read(connection->ssl, buf, length); + if(rv < 0) { + int err = SSL_get_error(connection->ssl, rv); + if(err == SSL_ERROR_WANT_WRITE || err == SSL_ERROR_WANT_READ) { + connection->want_io = (err == SSL_ERROR_WANT_READ ? + WANT_READ : WANT_WRITE); + rv = SPDYLAY_ERR_WOULDBLOCK; + } else { + rv = SPDYLAY_ERR_CALLBACK_FAILURE; + } + } else if(rv == 0) { + rv = SPDYLAY_ERR_EOF; + } + return rv; +} + +/* + * The implementation of spdylay_before_ctrl_send_callback type. We + * use this function to get stream ID of the request. This is because + * stream ID is not known when we submit the request + * (spdylay_submit_request). + */ +static void before_ctrl_send_callback(spdylay_session *session, + spdylay_frame_type type, + spdylay_frame *frame, + void *user_data) +{ + if(type == SPDYLAY_SYN_STREAM) { + struct Request *req; + int stream_id = frame->syn_stream.stream_id; + req = spdylay_session_get_stream_user_data(session, stream_id); + if(req && req->stream_id == -1) { + req->stream_id = stream_id; + printf("[INFO] Stream ID = %d\n", stream_id); + } + } +} + +static void on_ctrl_send_callback(spdylay_session *session, + spdylay_frame_type type, + spdylay_frame *frame, void *user_data) +{ + char **nv; + const char *name = NULL; + int32_t stream_id; + size_t i; + switch(type) { + case SPDYLAY_SYN_STREAM: + nv = frame->syn_stream.nv; + name = "SYN_STREAM"; + stream_id = frame->syn_stream.stream_id; + break; + default: + break; + } + if(name && spdylay_session_get_stream_user_data(session, stream_id)) { + printf("[INFO] C ----------------------------> S (%s)\n", name); + for(i = 0; nv[i]; i += 2) { + printf(" %s: %s\n", nv[i], nv[i+1]); + } + } +} + +static void on_ctrl_recv_callback(spdylay_session *session, + spdylay_frame_type type, + spdylay_frame *frame, void *user_data) +{ + struct Request *req; + char **nv; + const char *name = NULL; + int32_t stream_id; + size_t i; + switch(type) { + case SPDYLAY_SYN_REPLY: + nv = frame->syn_reply.nv; + name = "SYN_REPLY"; + stream_id = frame->syn_reply.stream_id; + break; + case SPDYLAY_HEADERS: + nv = frame->headers.nv; + name = "HEADERS"; + stream_id = frame->headers.stream_id; + break; + default: + break; + } + if(!name) { + return; + } + req = spdylay_session_get_stream_user_data(session, stream_id); + if(req) { + check_gzip(req, nv); + printf("[INFO] C <---------------------------- S (%s)\n", name); + for(i = 0; nv[i]; i += 2) { + printf(" %s: %s\n", nv[i], nv[i+1]); + } + } +} + +/* + * The implementation of spdylay_on_stream_close_callback type. We use + * this function to know the response is fully received. Since we just + * fetch 1 resource in this program, after reception of the response, + * we submit GOAWAY and close the session. + */ +static void on_stream_close_callback(spdylay_session *session, + int32_t stream_id, + spdylay_status_code status_code, + void *user_data) +{ + struct Request *req; + req = spdylay_session_get_stream_user_data(session, stream_id); + if(req) { + int rv; + rv = spdylay_submit_goaway(session, SPDYLAY_GOAWAY_OK); + if(rv != 0) { + diec("spdylay_submit_goaway", rv); + } + } +} + +#define MAX_OUTLEN 4096 + +/* + * The implementation of spdylay_on_data_chunk_recv_callback type. We + * use this function to print the received response body. + */ +static void on_data_chunk_recv_callback(spdylay_session *session, uint8_t flags, + int32_t stream_id, + const uint8_t *data, size_t len, + void *user_data) +{ + struct Request *req; + req = spdylay_session_get_stream_user_data(session, stream_id); + if(req) { + printf("[INFO] C <---------------------------- S (DATA)\n"); + printf(" %lu bytes\n", (unsigned long int)len); + if(req->inflater) { + while(len > 0) { + uint8_t out[MAX_OUTLEN]; + size_t outlen = MAX_OUTLEN; + size_t tlen = len; + int rv; + rv = spdylay_gzip_inflate(req->inflater, out, &outlen, data, &tlen); + if(rv == -1) { + spdylay_submit_rst_stream(session, stream_id, SPDYLAY_INTERNAL_ERROR); + break; + } + fwrite(out, 1, outlen, stdout); + data += tlen; + len -= tlen; + } + } else { + /* TODO add support gzip */ + fwrite(data, 1, len, stdout); + + //check if the data is correct + //if(strcmp(RESPONSE_BODY, data) != 0) + //killparent(parent, "\nreceived data is not the same"); + if(len + rcvbuf_c > strlen(RESPONSE_BODY)) + killparent(parent, "\nreceived data is not the same"); + + strcpy(rcvbuf + rcvbuf_c,(char*)data); + rcvbuf_c+=len; + } + printf("\n"); + } +} + +/* + * Setup callback functions. Spdylay API offers many callback + * functions, but most of them are optional. The send_callback is + * always required. Since we use spdylay_session_recv(), the + * recv_callback is also required. + */ +static void setup_spdylay_callbacks(spdylay_session_callbacks *callbacks) +{ + memset(callbacks, 0, sizeof(spdylay_session_callbacks)); + callbacks->send_callback = send_callback; + callbacks->recv_callback = recv_callback; + callbacks->before_ctrl_send_callback = before_ctrl_send_callback; + callbacks->on_ctrl_send_callback = on_ctrl_send_callback; + callbacks->on_ctrl_recv_callback = on_ctrl_recv_callback; + callbacks->on_stream_close_callback = on_stream_close_callback; + callbacks->on_data_chunk_recv_callback = on_data_chunk_recv_callback; +} + +/* + * Callback function for SSL/TLS NPN. Since this program only supports + * SPDY protocol, if server does not offer SPDY protocol the Spdylay + * library supports, we terminate program. + */ +static int select_next_proto_cb(SSL* ssl, + unsigned char **out, unsigned char *outlen, + const unsigned char *in, unsigned int inlen, + void *arg) +{ + int rv; + uint16_t *spdy_proto_version; + /* spdylay_select_next_protocol() selects SPDY protocol version the + Spdylay library supports. */ + rv = spdylay_select_next_protocol(out, outlen, in, inlen); + if(rv <= 0) { + die("Server did not advertise spdy/2 or spdy/3 protocol."); + } + spdy_proto_version = (uint16_t*)arg; + *spdy_proto_version = rv; + return SSL_TLSEXT_ERR_OK; +} + +/* + * Setup SSL context. We pass |spdy_proto_version| to get negotiated + * SPDY protocol version in NPN callback. + */ +static void init_ssl_ctx(SSL_CTX *ssl_ctx, uint16_t *spdy_proto_version) +{ + /* Disable SSLv2 and enable all workarounds for buggy servers */ + SSL_CTX_set_options(ssl_ctx, SSL_OP_ALL|SSL_OP_NO_SSLv2); + SSL_CTX_set_mode(ssl_ctx, SSL_MODE_AUTO_RETRY); + SSL_CTX_set_mode(ssl_ctx, SSL_MODE_RELEASE_BUFFERS); + /* Set NPN callback */ + SSL_CTX_set_next_proto_select_cb(ssl_ctx, select_next_proto_cb, + spdy_proto_version); +} + +static void ssl_handshake(SSL *ssl, int fd) +{ + int rv; + if(SSL_set_fd(ssl, fd) == 0) { + dief("SSL_set_fd", ERR_error_string(ERR_get_error(), NULL)); + } + ERR_clear_error(); + rv = SSL_connect(ssl); + if(rv <= 0) { + dief("SSL_connect", ERR_error_string(ERR_get_error(), NULL)); + } +} + +/* + * Connects to the host |host| and port |port|. This function returns + * the file descriptor of the client socket. + */ +static int connect_to(const char *host, uint16_t port) +{ + struct addrinfo hints; + int fd = -1; + int rv; + char service[NI_MAXSERV]; + struct addrinfo *res, *rp; + snprintf(service, sizeof(service), "%u", port); + memset(&hints, 0, sizeof(struct addrinfo)); + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_STREAM; + rv = getaddrinfo(host, service, &hints, &res); + if(rv != 0) { + dief("getaddrinfo", gai_strerror(rv)); + } + for(rp = res; rp; rp = rp->ai_next) { + fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); + if(fd == -1) { + continue; + } + while((rv = connect(fd, rp->ai_addr, rp->ai_addrlen)) == -1 && + errno == EINTR); + if(rv == 0) { + break; + } + close(fd); + fd = -1; + } + freeaddrinfo(res); + return fd; +} + +static void make_non_block(int fd) +{ + int flags, rv; + while((flags = fcntl(fd, F_GETFL, 0)) == -1 && errno == EINTR); + if(flags == -1) { + dief("fcntl", strerror(errno)); + } + while((rv = fcntl(fd, F_SETFL, flags | O_NONBLOCK)) == -1 && errno == EINTR); + if(rv == -1) { + dief("fcntl", strerror(errno)); + } +} + +/* + * Setting TCP_NODELAY is not mandatory for the SPDY protocol. + */ +static void set_tcp_nodelay(int fd) +{ + int val = 1; + int rv; + rv = setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &val, (socklen_t)sizeof(val)); + if(rv == -1) { + dief("setsockopt", strerror(errno)); + } +} + +/* + * Update |pollfd| based on the state of |connection|. + */ +static void ctl_poll(struct pollfd *pollfd, struct Connection *connection) +{ + pollfd->events = 0; + if(spdylay_session_want_read(connection->session) || + connection->want_io == WANT_READ) { + pollfd->events |= POLLIN; + } + if(spdylay_session_want_write(connection->session) || + connection->want_io == WANT_WRITE) { + pollfd->events |= POLLOUT; + } +} + +/* + * Submits the request |req| to the connection |connection|. This + * function does not send packets; just append the request to the + * internal queue in |connection->session|. + */ +static void submit_request(struct Connection *connection, struct Request *req) +{ + int pri = 0; + int rv; + const char *nv[15]; + /* We always use SPDY/3 style header even if the negotiated protocol + version is SPDY/2. The library translates the header name as + necessary. Make sure that the last item is NULL! */ + nv[0] = ":method"; nv[1] = "GET"; + nv[2] = ":path"; nv[3] = req->path; + nv[4] = ":version"; nv[5] = "HTTP/1.1"; + nv[6] = ":scheme"; nv[7] = "https"; + nv[8] = ":host"; nv[9] = req->hostport; + nv[10] = "accept"; nv[11] = "*/*"; + nv[12] = "user-agent"; nv[13] = "spdylay/"SPDYLAY_VERSION; + nv[14] = NULL; + rv = spdylay_submit_request(connection->session, pri, nv, NULL, req); + if(rv != 0) { + diec("spdylay_submit_request", rv); + } +} + +/* + * Performs the network I/O. + */ +static void exec_io(struct Connection *connection) +{ + int rv; + rv = spdylay_session_recv(connection->session); + if(rv != 0) { + diec("spdylay_session_recv", rv); + } + rv = spdylay_session_send(connection->session); + if(rv != 0) { + diec("spdylay_session_send", rv); + } +} + +static void request_init(struct Request *req, const struct URI *uri) +{ + req->host = strcopy(uri->host, uri->hostlen); + req->port = uri->port; + req->path = strcopy(uri->path, uri->pathlen); + req->hostport = strcopy(uri->hostport, uri->hostportlen); + req->stream_id = -1; + req->inflater = NULL; +} + +static void request_free(struct Request *req) +{ + free(req->host); + free(req->path); + free(req->hostport); + spdylay_gzip_inflate_del(req->inflater); +} + +/* + * Fetches the resource denoted by |uri|. + */ +static void fetch_uri(const struct URI *uri) +{ + spdylay_session_callbacks callbacks; + int fd; + SSL_CTX *ssl_ctx; + SSL *ssl; + struct Request req; + struct Connection connection; + int rv; + nfds_t npollfds = 1; + struct pollfd pollfds[1]; + uint16_t spdy_proto_version; + + request_init(&req, uri); + + setup_spdylay_callbacks(&callbacks); + + /* Establish connection and setup SSL */ + fd = connect_to(req.host, req.port); + ssl_ctx = SSL_CTX_new(SSLv23_client_method()); + if(ssl_ctx == NULL) { + dief("SSL_CTX_new", ERR_error_string(ERR_get_error(), NULL)); + } + init_ssl_ctx(ssl_ctx, &spdy_proto_version); + ssl = SSL_new(ssl_ctx); + if(ssl == NULL) { + dief("SSL_new", ERR_error_string(ERR_get_error(), NULL)); + } + /* To simplify the program, we perform SSL/TLS handshake in blocking + I/O. */ + ssl_handshake(ssl, fd); + + connection.ssl = ssl; + connection.want_io = IO_NONE; + + /* Here make file descriptor non-block */ + make_non_block(fd); + set_tcp_nodelay(fd); + + printf("[INFO] SPDY protocol version = %d\n", spdy_proto_version); + rv = spdylay_session_client_new(&connection.session, spdy_proto_version, + &callbacks, &connection); + if(rv != 0) { + diec("spdylay_session_client_new", rv); + } + + /* Submit the HTTP request to the outbound queue. */ + submit_request(&connection, &req); + + pollfds[0].fd = fd; + ctl_poll(pollfds, &connection); + + /* Event loop */ + while(spdylay_session_want_read(connection.session) || + spdylay_session_want_write(connection.session)) { + int nfds = poll(pollfds, npollfds, -1); + if(nfds == -1) { + dief("poll", strerror(errno)); + } + if(pollfds[0].revents & (POLLIN | POLLOUT)) { + exec_io(&connection); + } + if((pollfds[0].revents & POLLHUP) || (pollfds[0].revents & POLLERR)) { + die("Connection error"); + } + ctl_poll(pollfds, &connection); + } + + /* Resource cleanup */ + spdylay_session_del(connection.session); + SSL_shutdown(ssl); + SSL_free(ssl); + SSL_CTX_free(ssl_ctx); + shutdown(fd, SHUT_WR); + close(fd); + request_free(&req); +} + +static int parse_uri(struct URI *res, const char *uri) +{ + /* We only interested in https */ + size_t len, i, offset; + memset(res, 0, sizeof(struct URI)); + len = strlen(uri); + if(len < 9 || memcmp("https://", uri, 8) != 0) { + return -1; + } + offset = 8; + res->host = res->hostport = &uri[offset]; + res->hostlen = 0; + if(uri[offset] == '[') { + /* IPv6 literal address */ + ++offset; + ++res->host; + for(i = offset; i < len; ++i) { + if(uri[i] == ']') { + res->hostlen = i-offset; + offset = i+1; + break; + } + } + } else { + const char delims[] = ":/?#"; + for(i = offset; i < len; ++i) { + if(strchr(delims, uri[i]) != NULL) { + break; + } + } + res->hostlen = i-offset; + offset = i; + } + if(res->hostlen == 0) { + return -1; + } + /* Assuming https */ + res->port = 443; + if(offset < len) { + if(uri[offset] == ':') { + /* port */ + const char delims[] = "/?#"; + int port = 0; + ++offset; + for(i = offset; i < len; ++i) { + if(strchr(delims, uri[i]) != NULL) { + break; + } + if('0' <= uri[i] && uri[i] <= '9') { + port *= 10; + port += uri[i]-'0'; + if(port > 65535) { + return -1; + } + } else { + return -1; + } + } + if(port == 0) { + return -1; + } + offset = i; + res->port = port; + } + } + res->hostportlen = uri+offset-res->host; + for(i = offset; i < len; ++i) { + if(uri[i] == '#') { + break; + } + } + if(i-offset == 0) { + res->path = "/"; + res->pathlen = 1; + } else { + res->path = &uri[offset]; + res->pathlen = i-offset; + } + return 0; +} + + +/***** + * end of code needed to utilize spdylay + */ + + +/***** + * start of code needed to utilize microspdy + */ + + +void +standard_request_handler(void *cls, + struct SPDY_Request * request, + uint8_t priority, + const char *method, + const char *path, + const char *version, + const char *host, + const char *scheme, + struct SPDY_NameValue * headers) +{ + struct SPDY_Response *response=NULL; + + if(strcmp(CLS,cls)!=0) + { + killchild(child,"wrong cls"); + } + + response = SPDY_build_response(200,NULL,SPDY_HTTP_VERSION_1_1,NULL,RESPONSE_BODY,strlen(RESPONSE_BODY)); + + if(NULL==response){ + fprintf(stdout,"no response obj\n"); + exit(3); + } + + if(SPDY_queue_response(request,response,true,false,NULL,(void*)strdup(path))!=SPDY_YES) + { + fprintf(stdout,"queue\n"); + exit(4); + } +} + +void +session_closed_handler (void *cls, + struct SPDY_Session * session, + int by_client) +{ + printf("session_closed_handler called\n"); + + if(strcmp(CLS,cls)!=0) + { + killchild(child,"wrong cls"); + } + + if(SPDY_YES != by_client) + { + //killchild(child,"wrong by_client"); + printf("session closed by server\n"); + } + else + { + printf("session closed by client\n"); + } + + if(NULL == session) + { + killchild(child,"session is NULL"); + } + + session_closed_called = 1; +} + + +/***** + * end of code needed to utilize microspdy + */ + +//child process +void +childproc(int port) +{ + struct URI uri; + struct sigaction act; + int rv; + char *uristr; + + memset(&act, 0, sizeof(struct sigaction)); + act.sa_handler = SIG_IGN; + sigaction(SIGPIPE, &act, 0); + + asprintf(&uristr, "https://127.0.0.1:%i/",port); + if(NULL == (rcvbuf = malloc(strlen(RESPONSE_BODY)+1))) + killparent(parent,"no memory"); + + SSL_load_error_strings(); + SSL_library_init(); + + rv = parse_uri(&uri, uristr); + if(rv != 0) { + killparent(parent,"parse_uri failed"); + } + fetch_uri(&uri); + + if(strcmp(rcvbuf, RESPONSE_BODY)) + killparent(parent,"received data is different"); +} + +//parent proc +int +parentproc( int port) +{ + int childstatus; + unsigned long long timeoutlong=0; + struct timeval timeout; + int ret; + fd_set read_fd_set; + fd_set write_fd_set; + fd_set except_fd_set; + int maxfd = -1; + struct SPDY_Daemon *daemon; + + SPDY_init(); + + daemon = SPDY_start_daemon(port, + DATADIR "cert-and-key.pem", + DATADIR "cert-and-key.pem", + NULL,&session_closed_handler,&standard_request_handler,NULL,CLS,SPDY_DAEMON_OPTION_END); + + if(NULL==daemon){ + printf("no daemon\n"); + return 1; + } + + timeout.tv_usec = 0; + + do + { + FD_ZERO(&read_fd_set); + FD_ZERO(&write_fd_set); + FD_ZERO(&except_fd_set); + + ret = SPDY_get_timeout(daemon, &timeoutlong); + if(SPDY_NO == ret || timeoutlong > 1) + { + timeout.tv_sec = 1; + } + else + { + timeout.tv_sec = timeoutlong; + } + + maxfd = SPDY_get_fdset (daemon, + &read_fd_set, + &write_fd_set, + &except_fd_set); + + ret = select(maxfd+1, &read_fd_set, &write_fd_set, &except_fd_set, &timeout); + + switch(ret) { + case -1: + printf("select error: %i\n", errno); + killchild(child, "select error"); + break; + case 0: + + break; + default: + SPDY_run(daemon); + + break; + } + } + while(waitpid(child,&childstatus,WNOHANG) != child); + + //give chance to the client to close socket and handle this in run + usleep(100000); + SPDY_run(daemon); + + SPDY_stop_daemon(daemon); + + SPDY_deinit(); + + return WEXITSTATUS(childstatus); +} + +int main(int argc, char **argv) +{ + int port = get_port(12123); + parent = getpid(); + + child = fork(); + if (child == -1) + { + fprintf(stderr, "can't fork, error %d\n", errno); + exit(EXIT_FAILURE); + } + + if (child == 0) + { + childproc(port); + _exit(0); + } + else + { + int ret = parentproc(port); + if(1 == session_closed_called && 0 == ret) + exit(0); + else + exit(ret ? ret : 21); + } + return 1; +} diff --git a/src/testspdy/test_request_response_with_callback.c b/src/testspdy/test_request_response_with_callback.c @@ -0,0 +1,305 @@ +/* + This file is part of libmicrospdy + Copyright (C) 2013 Andrey Uzunov + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +/** + * @file request_response_with_callback.c + * @brief tests responses with callbacks + * @author Andrey Uzunov + */ + +#include "platform.h" +#include "microspdy.h" +#include "stdio.h" +#include <sys/wait.h> +#include <ctype.h> +#include "common.h" +#include <sys/time.h> +#include <sys/stat.h> + +int port; + +pid_t parent; +pid_t child; + +int run = 1; +int chunk_size=1; + +void +killchild() +{ + kill(child, SIGKILL); + exit(1); +} + +void +killparent() +{ + kill(parent, SIGKILL); + _exit(1); +} + +ssize_t +response_callback (void *cls, + void *buffer, + size_t max, + bool *more) +{ + FILE *fd =(FILE*)cls; + + size_t n; + if(chunk_size % 2) + n = chunk_size; + else + n = max - chunk_size; + + if(n < 1) n = 1; + else if (n > max) n=max; + chunk_size++; + + int ret = fread(buffer,1,n,fd); + *more = feof(fd) == 0; + + //printf("more is %i\n",*more); + + if(!(*more)) + fclose(fd); + + return ret; +} + + +void +response_done_callback(void *cls, + struct SPDY_Response *response, + struct SPDY_Request *request, + bool streamopened) +{ + printf("answer for %s was sent\n", (char*)cls); + + SPDY_destroy_request(request); + SPDY_destroy_response(response); + free(cls); + + run = 0; +} + +void +standard_request_handler(void *cls, + struct SPDY_Request * request, + uint8_t priority, + const char *method, + const char *path, + const char *version, + const char *host, + const char *scheme, + struct SPDY_NameValue * headers) +{ + struct SPDY_Response *response=NULL; + struct SPDY_NameValue *resp_headers; + + printf("received request for '%s %s %s'\n", method, path, version); + + FILE *fd = fopen(DATADIR "spdy-draft.txt","r"); + + if(NULL == (resp_headers = SPDY_name_value_create())) + { + fprintf(stdout,"SPDY_name_value_create failed\n"); + killchild(); + } + if(SPDY_YES != SPDY_name_value_add(resp_headers,SPDY_HTTP_HEADER_CONTENT_TYPE,"text/plain")) + { + fprintf(stdout,"SPDY_name_value_add failed\n"); + killchild(); + } + + response = SPDY_build_response_with_callback(200,NULL, + SPDY_HTTP_VERSION_1_1,resp_headers,&response_callback,fd,SPDY_MAX_SUPPORTED_FRAME_SIZE); + SPDY_name_value_destroy(resp_headers); + + if(NULL==response){ + fprintf(stdout,"no response obj\n"); + killchild(); + } + + void *clspath = strdup(path); + + if(SPDY_queue_response(request,response,true,false,&response_done_callback,clspath)!=SPDY_YES) + { + fprintf(stdout,"queue\n"); + killchild(); + } +} + +int +parentproc() +{ + int childstatus; + unsigned long long timeoutlong=0; + struct timeval timeout; + int ret; + fd_set read_fd_set; + fd_set write_fd_set; + fd_set except_fd_set; + int maxfd = -1; + struct SPDY_Daemon *daemon; + + SPDY_init(); + + daemon = SPDY_start_daemon(port, + DATADIR "cert-and-key.pem", + DATADIR "cert-and-key.pem", + NULL, + NULL, + &standard_request_handler, + NULL, + NULL, + SPDY_DAEMON_OPTION_SESSION_TIMEOUT, + 1800, + SPDY_DAEMON_OPTION_END); + + if(NULL==daemon){ + printf("no daemon\n"); + return 1; + } + + timeout.tv_usec = 0; + + do + { + FD_ZERO(&read_fd_set); + FD_ZERO(&write_fd_set); + FD_ZERO(&except_fd_set); + + ret = SPDY_get_timeout(daemon, &timeoutlong); + if(SPDY_NO == ret || timeoutlong > 1) + { + timeout.tv_sec = 1; + } + else + { + timeout.tv_sec = timeoutlong; + } + + maxfd = SPDY_get_fdset (daemon, + &read_fd_set, + &write_fd_set, + &except_fd_set); + + ret = select(maxfd+1, &read_fd_set, &write_fd_set, &except_fd_set, &timeout); + + switch(ret) { + case -1: + printf("select error: %i\n", errno); + break; + case 0: + + break; + default: + SPDY_run(daemon); + + break; + } + } + while(waitpid(child,&childstatus,WNOHANG) != child); + + SPDY_stop_daemon(daemon); + + SPDY_deinit(); + + return WEXITSTATUS(childstatus); +} + +#define MD5_LEN 32 + +int +md5(char *cmd, char *md5_sum) +{ + FILE *p = popen(cmd, "r"); + if (p == NULL) return 0; + + int i, ch; + for (i = 0; i < MD5_LEN && isxdigit(ch = fgetc(p)); i++) { + *md5_sum++ = ch; + } + + *md5_sum = '\0'; + pclose(p); + return i == MD5_LEN; +} + +int +childproc() +{ + char *cmd1; + char *cmd2; + char md5_sum1[33]; + char md5_sum2[33]; + int ret; + struct timeval tv1; + struct timeval tv2; + struct stat st; + //int secs; + uint64_t usecs; + + asprintf(&cmd1, "spdycat https://127.0.0.1:%i/ | md5sum",port); + asprintf(&cmd2, "md5sum " DATADIR "spdy-draft.txt"); + + gettimeofday(&tv1, NULL); + md5(cmd1,md5_sum1); + gettimeofday(&tv2, NULL); + md5(cmd2,md5_sum2); + + printf("downloaded file md5: %s\n", md5_sum1); + printf("original file md5: %s\n", md5_sum2); + ret = strcmp(md5_sum1, md5_sum2); + + if(0 == ret && 0 == stat(DATADIR "spdy-draft.txt", &st)) + { + usecs = (uint64_t)1000000 * (uint64_t)(tv2.tv_sec - tv1.tv_sec) + tv2.tv_usec - tv1.tv_usec; + printf("%i bytes read in %i usecs\n", st.st_size, usecs); + } + + return ret; +} + + +int +main(int argc, char **argv) +{ + port = get_port(11123); + parent = getpid(); + + child = fork(); + if (-1 == child) + { + fprintf(stderr, "can't fork, error %d\n", errno); + exit(EXIT_FAILURE); + } + + if (child == 0) + { + int ret = childproc(); + _exit(ret); + } + else + { + int ret = parentproc(); + exit(ret); + } + return 1; +} diff --git a/src/testspdy/test_requests_with_assets.c b/src/testspdy/test_requests_with_assets.c @@ -0,0 +1,291 @@ +/* + This file is part of libmicrospdy + Copyright (C) 2012 Andrey Uzunov + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +/** + * @file requests_with_assets.c + * @brief tests several requests for an HTML and all its assets. For + * client spdycat (from spdylay) is used. The latter uses + * libxml2. + * @author Andrey Uzunov + */ + +#include "platform.h" +#include "microspdy.h" +#include "common.h" +#include <sys/wait.h> +#include <stdio.h> /* printf, stderr, fprintf */ +#include <sys/types.h> /* pid_t */ +#include <unistd.h> /* _exit, fork */ +#include <stdlib.h> /* exit */ +#include <errno.h> /* errno */ +#include <sys/wait.h> /* pid_t */ +#include "common.h" + +#define HTML "<html>\ +<head>\ +<link href=\"file1.css\" rel=\"stylesheet\" type=\"text/css\" />\ +<link href=\"file2.css\" rel=\"stylesheet\" type=\"text/css\" />\ +<link href=\"file3.css\" rel=\"stylesheet\" type=\"text/css\" />\ +</head>\ +<body><b>Hi, this is libmicrospdy!</b>\ +</body></html>" + +#define CSS "@media all{body{font-family:verdana,arial;color:#333;background-color:#fff;margin:0;padding:0}#navcontainer ul{padding-left:0;background:#005cb9 url(http://cdn.computerhope.com/backbar.jpg) repeat-x left top;padding-bottom:0;padding-top:0;color:#fff;float:right;font-weight:700;width:100%;border-top:1px solid #333;border-bottom:1px solid #333;margin:0}#navcontainer ul li a{color:#fff;text-decoration:none;float:left;border-top:1px solid #fff;border-right:1px solid #333;border-left:1px solid #fff;border-bottom:1px solid #333;padding:.2em 1em}#navcontainer ul li a:hover{background:url(http://cdn.computerhope.com/backbar2.jpg) repeat-x left top;background-color:#9fcfff;color:#333;border-top:1px solid #333;border-right:1px solid #fff;border-left:1px solid #333;border-bottom:1px solid #fff}a:visited{color:#636}a{color:#2a70d0}#content a{text-decoration:none;border-bottom:1px solid #DBDBDB}#content a:hover,a:active,a:focus{color:#c33;border-bottom:1px solid #c33}img{border:0}#content-container1{float:left;width:100%;background:#fff url(http://cdn.computerhope.com/back.jpg) repeat-y 0}.print,.email,.edit,.share,.up,.down,.book,.folder,.issue,.driver,.history,.news,.btips,.tips,.warn,.phone,.forum,.question{background:url(chs.png) no-repeat top left}#container{padding-left:150px;padding-right:265px}#container .column{position:relative;float:left}#content{width:100%;padding:20px}#left-bar{width:150px;margin-left:-100%;left:225px;padding:10px}#container > #left-bar{left:-190px}#right-bar{width:205px;margin-right:-265px;padding:0 10px}#topad{background:#9fcfff;text-align:center;padding:35px 0 4px}#leftad{clear:both;background:inherit;height:auto;margin:15px 0 0}#content ul{position:relative;margin:10px 0 10px 10px;padding:0}#content ul li{list-style-type:none;background:url(http://cdn.computerhope.com/arrow.png) no-repeat top left;background-position:0 5px;line-height:1.5625;padding:0 0 8px 23px}ol li{margin-bottom:8px;line-height:1.5625}.print,.email,.edit,.share{padding-left:23px}.print{background-position:0 -868px;width:16px;height:16px}.email{background-position:0 -469px;width:16px;height:16px}.edit{background-position:0 -403px;width:16px;height:16px}.share{background-position:0 -1002px;width:16px;height:16px}#left-bar li.title{color:#005cb9;font-weight:700;margin:1em 0}#right-box{width:180px;border:1px solid #005cb9;border-radius:15px 15px 15px 15px;background:#ebebeb;margin:90px 0 0;padding:10px}#right-box ul.poll{margin-top:15px;font-weight:700;margin-bottom:10px}.up,.down{padding-left:20px;text-decoration:none;color:#333}.up{background-position:0 -1068px;width:16px;height:16px}.down{background-position:0 -269px;width:16px;height:16px}#right-box li.title{color:#333;font-weight:700;margin:1em 0 0}#header{background:#9fcfff}#containercol2{background-color:#d0e8ff;width:700px;overflow:hidden;margin:0 auto}#containercol2 ul.col2{width:700px;list-style:none;float:left;padding:0}#containercol2 ul.col2 li h2{border:1px solid #005cb9;background:url(http://cdn.computerhope.com/backbar.jpg) repeat-x left top;color:#fff;font-size:large;text-align:center}#containercol2 ul.col2 li{float:left;width:340px;padding:5px}#containercol2 ul li.headline{border-bottom:1px solid #327dac;background:gray}#bottomad{margin:14px 0 0}input.btn,input.bbtn{color:#333;background:#9fcfff;font-weight:700;border:1px solid #005cb9;border-top:1px solid #eee;border-left:1px solid #eee;cursor:pointer;margin:4px 0 0}input.sbar,input.bsbar{color:#333;width:110px;background:#fff}input.btn{width:115px;font-size:medium}input.sbar{font-size:medium}input.bbtn{width:110px;font-size:large}input.bsbar{width:350px;font-size:18px;margin-right:5px}h1{font-size:175%;margin-bottom:25px;border-bottom:1px solid #dadada;padding-bottom:.17em;letter-spacing:-.05em;font-weight:700}.ce{text-align:center}.tab{margin-left:40px}p{line-height:1.5625}.tabb{margin-left:40px;font-weight:700;line-height:1.4}.dtab{margin-left:80px}.dd{font-weight:700;margin-left:7px}.lb{margin-left:5px}.bld{font-weight:700}.bb{font-size:14pt;color:#005cb9;font-weight:700}.bbl{font-size:14pt;font-weight:700}.nb{color:#005cb9;font-weight:700}.rg{color:gray;font-weight:700}.sg{font-size:10pt;color:gray}.sm{font-size:small}.rb{color:#fff;font-weight:700;text-indent:.3cm}.wt{color:#fff;font-weight:700}.bwt{color:#fff;font-weight:700;font-size:14pt}.large{font-size:x-large}.red{color:red}table{clear:both}.mtable,.mtable2{border:0 solid silver;background-color:#e5e5e5;border-spacing:2px 1px;width:98%;margin-left:auto;margin-right:auto}table.mtable td,table.mtable2 td{border-spacing:5px 10px;padding:9px}table.mtable th,table.mtable2 th{background:#005cb9 url(http://cdn.computerhope.com/backbar.jpg) repeat-x left top;color:#fff;font-weight:700;padding:5px}table.mtable a{border-bottom:0!important}table.mtable tr:hover td{background-color:#eee;cursor:pointer}td{vertical-align:top}.tcb{background:#005cb9 url(http://cdn.computerhope.com/backbar.jpg) repeat-x left top}.tclb{background-color:#9fcfff}.tcllb{background-color:#d0e8ff}.tcw{background-color:#fff}.tcg{background-color:#ebebeb}.tcbl{background-color:#333}.tcy{border:1px solid #005cb9;background-color:#f1f5f9;overflow:auto;padding:15px}.icell{padding-left:15px;padding-bottom:3px}.mlb{background-color:#9fcfff;padding-left:15px;padding-bottom:3px;white-space:nowrap;width:120px;vertical-align:top}#footer{background:url(http://cdn.computerhope.com/footback.jpg) repeat-x left top;background-color:#d0e8ff;clear:both;padding:5px}#footer ul li{list-style-type:none;display:inline;background:inherit;margin:0}#footer li a{float:left;text-decoration:none;width:300px;border-bottom:1px dotted #327dac;padding:0 0 10px 10px}#footer li a:hover{background:#005cb9;color:#fff}#creditfooter{display:none}.legal{text-align:center;font-size:11px}.legal a{text-decoration:none;color:#333}.floatLeft{float:left;clear:left;margin-right:20px;margin-bottom:10px}.floatRight{float:right;margin-left:20px;margin-bottom:10px}.floatRightClear{float:right;clear:right;margin-left:20px}:first-child + html #container{overflow:hidden}.book,.folder,.issue,.driver,.history,.news,.btips,.tips,.warn,.phone,.forum,.question{padding-left:22px;font-weight:700}.book{background-position:0 0;width:17px;height:18px}.tips{background-position:0 -68px;width:17px;height:17px}.btips{background-position:0 -135px;width:17px;height:17px}.history{background-position:0 -202px;width:17px;height:17px}.driver{background-position:0 -335px;width:17px;height:18px}.folder{background-position:0 -535px;width:17px;height:16px}.issue{background-position:0 -601px;width:17px;height:18px}.news{background-position:0 -669px;width:17px;height:14px}.forum{background-position:0 -733px;width:17px;height:18px}.phone{background-position:0 -801px;width:17px;height:17px}.question{background-position:0 -934px;width:17px;height:18px}.warn{background-position:0 -1134px;width:16px;height:16px}textarea,input{border:1px solid #ccc;border-top:1px solid #8d8e90;border-left:1px solid #8d8e90}textarea:focus,input:focus{border:1px solid #005cb9}#left-bar ul,#right-box ul,#footer ul{margin:0;padding:0}#right-box li.poll,#navcontainer ul li{display:inline}#noprint{margin:1px 0 0}#left-bar ul li,#right-box ul li{margin-left:10px;list-style-type:none;padding:0}#right-box a,#left-bar a{color:#333}}@media print{#header,#navcontainer,#topad,#left-bar,#right-bar,#bottomad,#footer,#search,#buttons,#noprint{display:none!important}#content a{text-decoration:none;color:#000}#content,#container{font-family:\"Times New Roman\",Times;background:transparent!important;text-indent:0!important;width:100%!important;border:0!important;float:none!important;position:static!important;overflow:visible!important;line-height:1;margin:0!important;padding:0!important}h1{font-size:14pt;margin-bottom:5px;border-bottom:0;padding-bottom:0;letter-spacing:-.05em;font-weight:700}h2{font-size:13pt}.bb{font-size:13pt;color:#005cb9;font-weight:700}#content ul li:before{content:\"\00bb \0020\"}#content .nb,.bb{font-weight:700;color:#000}table{margin-top:30px;margin-bottom:30px;border-collapse:collapse}th,td{border:1px solid #333}}" + +#define JS "var _gaq = _gaq || [];\ +_gaq.push(['_setAccount', 'UA-222222222222222222222222-1']);\ +_gaq.push(['_trackPageview']);\ +(function() {\ +var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;\ +//ga.src = ('https:' == document.location.protocol ? 'ZZZhttps://ssl' : 'ZZZhttp://www') + '.google-analytics.com/ga.js';\ +var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);\ +})();" + +int port; + +#define NUM_CLIENTS 50 + +pid_t parent; +int html_req_count; +int html_resp_count; + +int child_c; +int children_pid[NUM_CLIENTS]; +int children_status[NUM_CLIENTS]; + +int session_closed_called; + +void +new_child(pid_t pid) +{ + //todo ids overflow + children_pid[child_c] = pid; + children_status[child_c++] = 1; +} + +int +alive_children() +{ + int i; + int dead; + int status; + int ret = 0; + + for(i=NUM_CLIENTS-1;i>=0;--i) + { + if (1 != children_status[i]) + continue; + dead = waitpid(children_pid[i], &status, WNOHANG); + if (0 == dead) + { + ret = 1; + continue; + } + if (WEXITSTATUS(status) != 0) + { + for (i=NUM_CLIENTS-1;i>=0;--i) + if (1 == children_status[i]) + kill (children_pid[i], SIGKILL); + exit (WEXITSTATUS(status)); + } + children_status[i] = 2; + } + return ret; +} + +void +killchild(int pid, char *message) +{ + printf("%s\nkilling %i\n",message,pid); + kill(pid, SIGKILL); + exit(1); +} + +void +killparent(int pid, const char *message) +{ + printf("%s\nkilling %i\n",message,pid); + kill(pid, SIGKILL); + _exit(1); +} + +void +standard_request_handler(void *cls, + struct SPDY_Request * request, + uint8_t priority, + const char *method, + const char *path, + const char *version, + const char *host, + const char *scheme, + struct SPDY_NameValue * headers) +{ + struct SPDY_Response *response; + + if(NULL != strstr(path,".css")) + { + response = SPDY_build_response(200,NULL,SPDY_HTTP_VERSION_1_1,NULL,CSS,strlen(CSS)); + if(strcmp("/file3.css",path)==0)++html_resp_count; + } + /*else if(NULL != strstr(path,".js")) + { + response = SPDY_build_response(200,NULL,SPDY_HTTP_VERSION_1_1,NULL,JS,strlen(JS)); + }*/ + else + { + response = SPDY_build_response(200,NULL,SPDY_HTTP_VERSION_1_1,NULL,HTML,strlen(HTML)); + } + + if(NULL==response){ + fprintf(stdout,"no response obj\n"); + exit(3); + } + + if(SPDY_queue_response(request,response,true,false,NULL,(void*)strdup(path))!=SPDY_YES) + { + fprintf(stdout,"queue\n"); + exit(4); + } + + +} + +void +run_spdycat() +{ + pid_t child; + ++html_req_count; + child = fork(); + if (child == -1) + { + killparent(parent,"fork failed\n"); + } + + if (child == 0) + { + int devnull; + + close(1); + devnull = open("/dev/null", O_WRONLY); + if (1 != devnull) + { + dup2(devnull, 1); + close(devnull); + } + char *uri; + asprintf (&uri, "https://127.0.0.1:%i/%i.html", port, html_req_count); + execlp ("spdycat", "spdycat", "-anv", uri, NULL); + killparent (parent, "executing spdycat failed"); + } + else + { + new_child(child); + } +} + +int +parentproc() +{ + unsigned long long timeoutlong=0; + struct timeval timeout; + int ret; + fd_set read_fd_set; + fd_set write_fd_set; + fd_set except_fd_set; + int maxfd = -1; + struct SPDY_Daemon *daemon; + + SPDY_init(); + + daemon = SPDY_start_daemon(port, + DATADIR "cert-and-key.pem", + DATADIR "cert-and-key.pem", + NULL, + NULL, + &standard_request_handler, + NULL, + NULL, + SPDY_DAEMON_OPTION_END); + + if(NULL==daemon){ + printf("no daemon\n"); + return 1; + } + + timeout.tv_usec = 0; + + do + { + if(NUM_CLIENTS > html_req_count) + { + run_spdycat(); + } + + FD_ZERO(&read_fd_set); + FD_ZERO(&write_fd_set); + FD_ZERO(&except_fd_set); + + ret = SPDY_get_timeout(daemon, &timeoutlong); + if(SPDY_NO == ret || timeoutlong > 1) + { + timeout.tv_sec = 1; + } + else + { + timeout.tv_sec = timeoutlong; + } + + maxfd = SPDY_get_fdset (daemon, + &read_fd_set, + &write_fd_set, + &except_fd_set); + + ret = select(maxfd+1, &read_fd_set, &write_fd_set, &except_fd_set, &timeout); + + switch(ret) { + case -1: + printf("select error: %i\n", errno); + break; + case 0: + + break; + default: + SPDY_run(daemon); + + break; + } + } + while(alive_children()); + + SPDY_stop_daemon(daemon); + + SPDY_deinit(); + + return html_resp_count != html_req_count; +} + +int main(int argc, char **argv) +{ + parent = getpid(); + port = get_port(10123); + + int ret = parentproc(); + exit(ret); + + return 1; +} diff --git a/src/testspdy/test_session_timeout.c b/src/testspdy/test_session_timeout.c @@ -0,0 +1,275 @@ +/* + This file is part of libmicrospdy + Copyright (C) 2013 Andrey Uzunov + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +/** + * @file session_timeout.c + * @brief tests closing sessions after set timeout. Openssl is used for + * client + * @author Andrey Uzunov + */ + +#include "platform.h" +#include "microspdy.h" +#include "stdio.h" +#include <sys/wait.h> +#include <ctype.h> +#include "common.h" +#include <sys/time.h> +#include <sys/stat.h> + +#define TIMEOUT 2 + +int port; + +pid_t parent; +pid_t child; + +int run = 1; +int chunk_size=1; +int new_session; +int closed_session; +int do_sleep; + +void +killchild(char *msg) +{ + printf("%s\n",msg); + kill(child, SIGKILL); + exit(1); +} + +void +killparent(char *msg) +{ + printf("%s\n",msg); + kill(parent, SIGKILL); + _exit(1); +} + +void +new_session_cb (void *cls, + struct SPDY_Session * session) +{ + if(!new_session)do_sleep = 1; + new_session = 1; + printf("new session\n"); +} + +void +closed_session_cb (void *cls, + struct SPDY_Session * session, + int by_client) +{ + printf("closed_session_cb called\n"); + + if(SPDY_YES == by_client) + { + killchild("closed by the client"); + } + if(closed_session) + { + killchild("closed_session_cb called twice"); + } + + closed_session = 1; +} + +int +parentproc() +{ + int childstatus; + unsigned long long timeoutlong=0; + struct timeval timeout; + int ret; + fd_set read_fd_set; + fd_set write_fd_set; + fd_set except_fd_set; + int maxfd = -1; + struct SPDY_Daemon *daemon; + + SPDY_init(); + + daemon = SPDY_start_daemon(port, + DATADIR "cert-and-key.pem", + DATADIR "cert-and-key.pem", + &new_session_cb, + &closed_session_cb, + NULL, + NULL, + NULL, + SPDY_DAEMON_OPTION_SESSION_TIMEOUT, + TIMEOUT, + SPDY_DAEMON_OPTION_END); + + if(NULL==daemon){ + printf("no daemon\n"); + return 1; + } + + timeout.tv_usec = 0; + + do + { + do_sleep=0; + FD_ZERO(&read_fd_set); + FD_ZERO(&write_fd_set); + FD_ZERO(&except_fd_set); + + ret = SPDY_get_timeout(daemon, &timeoutlong); + + if(new_session && !closed_session) + { + if(SPDY_NO == ret) + { + killchild("SPDY_get_timeout returned wrong SPDY_NO"); + } + if(timeoutlong) + { + killchild("SPDY_get_timeout returned wrong timeout"); + } + } + else + { + if(SPDY_YES == ret) + { + killchild("SPDY_get_timeout returned wrong SPDY_YES"); + } + } + + if(SPDY_NO == ret || timeoutlong > 1) + { + timeout.tv_sec = 1; + } + else + { + timeout.tv_sec = timeoutlong; + } + + maxfd = SPDY_get_fdset (daemon, + &read_fd_set, + &write_fd_set, + &except_fd_set); + + ret = select(maxfd+1, &read_fd_set, &write_fd_set, &except_fd_set, &timeout); + + switch(ret) { + case -1: + printf("select error: %i\n", errno); + break; + case 0: + /*if(new_session) + { + killchild("select returned wrong number"); + }*/ + break; + default: + SPDY_run(daemon); + if(do_sleep) + { + sleep(TIMEOUT); + do_sleep = 0; + } + + break; + } + } + while(waitpid(child,&childstatus,WNOHANG) != child); + + if(!new_session || !closed_session) + { + killchild("child is dead, callback wasn't called"); + } + + ret = SPDY_get_timeout(daemon, &timeoutlong); + + if(SPDY_YES == ret) + { + killchild("SPDY_get_timeout returned wrong SPDY_YES after child died"); + } + + SPDY_stop_daemon(daemon); + + SPDY_deinit(); + + return 0; +} + +int +childproc() +{ + pid_t devnull; + pid_t out; + + out=dup(1); + //close(0); + close(1); + close(2); + /*devnull = open("/dev/null", O_RDONLY); + if (0 != devnull) + { + dup2(devnull, 0); + close(devnull); + }*/ + devnull = open("/dev/null", O_WRONLY); + if (1 != devnull) + { + dup2(devnull, 1); + close(devnull); + } + devnull = open("/dev/null", O_WRONLY); + if (2 != devnull) + { + dup2(devnull, 2); + close(devnull); + } + char *uri; + asprintf (&uri, "127.0.0.1:%i", port); + execlp ("openssl", "openssl", "s_client", "-connect", uri, NULL); + close(1); + dup2(out,1); + close(out); + killparent ("executing openssl failed"); + return 1; +} + + +int +main(int argc, char **argv) +{ + port = get_port(11123); + parent = getpid(); + + child = fork(); + if (-1 == child) + { + fprintf(stderr, "can't fork, error %d\n", errno); + exit(EXIT_FAILURE); + } + + if (child == 0) + { + int ret = childproc(); + _exit(ret); + } + else + { + int ret = parentproc(); + exit(ret); + } + return 1; +} diff --git a/src/testspdy/test_struct_namevalue.c b/src/testspdy/test_struct_namevalue.c @@ -0,0 +1,340 @@ +/* + This file is part of libmicrospdy + Copyright (C) 2012 Andrey Uzunov + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +/** + * @file struct_namevalue.c + * @brief tests all the API functions for handling struct SPDY_NameValue + * @author Andrey Uzunov + */ + +#include "platform.h" +#include "microspdy.h" +#include "common.h" +#include "../microspdy/structures.h" +#include "../microspdy/alstructures.h" + +char *pairs[] = {"one","1","two","2","three","3","four","4","five","5"}; +char *pairs_with_dups[] = {"one","1","two","2","one","11","two","22","three","3","two","222","two","2222","four","","five","5"};//82 +char *pairs_with_empty[] = {"name","","name","value"}; +char *pairs_different[] = {"30","thirty","40","fouthy"}; +int size; +int size2; +int brake_at = 3; +bool flag; + +int +iterate_cb (void *cls, const char *name, const char * const * value, int num_values) +{ + int *c = (int*)cls; + + if(*c < 0 || *c > size) + exit(11); + + if(strcmp(name,pairs[*c]) != 0) + { + FAIL_TEST("name is wrong\n"); + } + + if(1 != num_values) + { + FAIL_TEST("num_values is wrong\n"); + } + + if(strcmp(value[0],pairs[(*c)+1]) != 0) + { + FAIL_TEST("value is wrong\n"); + } + + (*c)+=2; + + return SPDY_YES; +} + +int +iterate_brake_cb (void *cls, const char *name, const char * const *value, int num_values) +{ + int *c = (int*)cls; + + if(*c < 0 || *c >= brake_at) + { + FAIL_TEST("iteration was not interrupted\n"); + } + + (*c)++; + + if(*c == brake_at) return SPDY_NO; + + return SPDY_YES; +} + +int +main() +{ + SPDY_init(); + + const char *const*value; + const char *const*value2; + int i; + int j; + int cls = 0; + int ret; + int ret2; + void *ob1; + void *ob2; + void *ob3; + void *stream; + char data[] = "anything"; + struct SPDY_NameValue *container; + struct SPDY_NameValue *container2; + struct SPDY_NameValue *container3; + struct SPDY_NameValue *container_arr[1]; + + size = sizeof(pairs)/sizeof(pairs[0]); + + if(NULL == (container = SPDY_name_value_create ())) + { + FAIL_TEST("SPDY_name_value_create failed\n"); + } + + if(NULL != SPDY_name_value_lookup (container, "anything", &ret)) + { + FAIL_TEST("SPDY_name_value_lookup failed\n"); + } + + if(SPDY_name_value_iterate (container, NULL, NULL) != 0) + { + FAIL_TEST("SPDY_name_value_iterate failed\n"); + } + + for(i=0;i<size; i+=2) + { + if(SPDY_YES != SPDY_name_value_add(container,pairs[i],pairs[i+1])) + { + FAIL_TEST("SPDY_name_value_add failed\n"); + } + + if(SPDY_name_value_iterate (container, NULL, NULL) != ((i / 2) + 1)) + { + FAIL_TEST("SPDY_name_value_iterate failed\n"); + } + } + + if(NULL != SPDY_name_value_lookup (container, "anything", &ret)) + { + FAIL_TEST("SPDY_name_value_lookup failed\n"); + } + + for(i=size - 2; i >= 0; i-=2) + { + value = SPDY_name_value_lookup(container,pairs[i], &ret); + if(NULL == value || 1 !=ret || strcmp(value[0], pairs[i+1]) != 0) + { + printf("%i; %i; %i\n", value, ret, strcmp(value[0], pairs[i+1])); + FAIL_TEST("SPDY_name_value_lookup failed\n"); + } + } + + SPDY_name_value_iterate (container, &iterate_cb, &cls); + + cls = 0; + if(SPDY_name_value_iterate (container, &iterate_brake_cb, &cls) != brake_at) + { + FAIL_TEST("SPDY_name_value_iterate with brake failed\n"); + } + + SPDY_name_value_destroy(container); + + //check everything with NULL values + for(i=0; i<6; ++i) + { + printf("%i ",i); + ob1 = (i & 4) ? data : NULL; + ob2 = (i & 2) ? data : NULL; + ob3 = (i & 1) ? data : NULL; + if(SPDY_INPUT_ERROR != SPDY_name_value_add(ob1,ob2,ob3)) + { + FAIL_TEST("SPDY_name_value_add with NULLs failed\n"); + } + } + printf("\n"); + fflush(stdout); + + if(SPDY_INPUT_ERROR != SPDY_name_value_iterate(NULL,NULL,NULL)) + { + FAIL_TEST("SPDY_name_value_iterate with NULLs failed\n"); + } + + for(i=0; i<7; ++i) + { + printf("%i ",i); + ob1 = (i & 4) ? data : NULL; + ob2 = (i & 2) ? data : NULL; + ob3 = (i & 1) ? data : NULL; + if(NULL != SPDY_name_value_lookup(ob1,ob2,ob3)) + { + FAIL_TEST("SPDY_name_value_lookup with NULLs failed\n"); + } + } + printf("\n"); + SPDY_name_value_destroy(NULL); + + if(NULL == (container = SPDY_name_value_create ())) + { + FAIL_TEST("SPDY_name_value_create failed\n"); + } + + size = sizeof(pairs_with_dups)/sizeof(pairs_with_dups[0]); + + for(i=0;i<size; i+=2) + { + if(SPDY_YES != SPDY_name_value_add(container,pairs_with_dups[i],pairs_with_dups[i+1])) + { + FAIL_TEST("SPDY_name_value_add failed\n"); + } + } + if(SPDY_name_value_iterate (container, NULL, NULL) != atoi(pairs_with_dups[size - 1])) + { + FAIL_TEST("SPDY_name_value_iterate failed\n"); + } + for(i=size - 2; i >= 0; i-=2) + { + value = SPDY_name_value_lookup(container,pairs_with_dups[i], &ret); + if(NULL == value) + { + FAIL_TEST("SPDY_name_value_lookup failed\n"); + } + flag = false; + for(j=0; j<ret; ++j) + if(0 == strcmp(pairs_with_dups[i + 1], value[j])) + { + if(flag) + FAIL_TEST("SPDY_name_value_lookup failed\n"); + flag=true; + } + + if(!flag) + FAIL_TEST("SPDY_name_value_lookup failed\n"); + } + if(SPDY_NO != SPDY_name_value_add(container,pairs_with_dups[0],pairs_with_dups[1])) + FAIL_TEST("SPDY_name_value_add failed\n"); + + SPDY_name_value_destroy(container); + + if(NULL == (container = SPDY_name_value_create ())) + { + FAIL_TEST("SPDY_name_value_create failed\n"); + } + + size = sizeof(pairs_with_empty)/sizeof(pairs_with_empty[0]); + + for(i=0;i<size; i+=2) + { + if(SPDY_YES != SPDY_name_value_add(container,pairs_with_empty[i],pairs_with_empty[i+1])) + { + FAIL_TEST("SPDY_name_value_add failed\n"); + } + value = SPDY_name_value_lookup(container,pairs_with_empty[i], &ret); + if(NULL == value || 1 != ret) + { + printf("%i; %i\n", value, ret); + FAIL_TEST("SPDY_name_value_lookup failed\n"); + } + } + + ret = SPDY_name_value_iterate(container, NULL, NULL); + if(SPDY_INPUT_ERROR != SPDY_name_value_add(container, "capitalLeter","anything") + || SPDY_name_value_iterate(container, NULL, NULL) != ret) + { + FAIL_TEST("SPDY_name_value_add failed\n"); + } + + SPDY_name_value_destroy(container); + + if(NULL == (container = SPDY_name_value_create ())) + { + FAIL_TEST("SPDY_name_value_create failed\n"); + } + + size = sizeof(pairs_with_dups)/sizeof(pairs_with_dups[0]); + + for(i=0;i<size; i+=2) + { + if(SPDY_YES != SPDY_name_value_add(container,pairs_with_dups[i],pairs_with_dups[i+1])) + { + FAIL_TEST("SPDY_name_value_add failed\n"); + } + } + + if(NULL == (container2 = SPDY_name_value_create ())) + { + FAIL_TEST("SPDY_name_value_create failed\n"); + } + + size2 = sizeof(pairs_different)/sizeof(pairs_different[0]); + + for(i=0;i<size2; i+=2) + { + if(SPDY_YES != SPDY_name_value_add(container2,pairs_different[i],pairs_different[i+1])) + { + FAIL_TEST("SPDY_name_value_add failed\n"); + } + } + + container_arr[0] = container; + container_arr[1] = container2; + if(0 > (ret = SPDYF_name_value_to_stream(container_arr, 2, &stream)) || NULL == stream) + FAIL_TEST("SPDYF_name_value_to_stream failed\n"); + ret = SPDYF_name_value_from_stream(stream, ret, &container3); + if(SPDY_YES != ret) + FAIL_TEST("SPDYF_name_value_from_stream failed\n"); + + if(SPDY_name_value_iterate(container3, NULL, NULL) + != (SPDY_name_value_iterate(container, NULL, NULL) + SPDY_name_value_iterate(container2, NULL, NULL))) + FAIL_TEST("SPDYF_name_value_from_stream failed\n"); + + for(i=size - 2; i >= 0; i-=2) + { + value = SPDY_name_value_lookup(container,pairs_with_dups[i], &ret); + if(NULL == value) + FAIL_TEST("SPDY_name_value_lookup failed\n"); + value2 = SPDY_name_value_lookup(container3,pairs_with_dups[i], &ret2); + if(NULL == value2) + FAIL_TEST("SPDY_name_value_lookup failed\n"); + + for(j=0; j<ret; ++j) + if(0 != strcmp(value2[j], value[j])) + FAIL_TEST("SPDY_name_value_lookup failed\n"); + } + for(i=size2 - 2; i >= 0; i-=2) + { + value = SPDY_name_value_lookup(container2,pairs_different[i], &ret); + if(NULL == value) + FAIL_TEST("SPDY_name_value_lookup failed\n"); + value2 = SPDY_name_value_lookup(container3,pairs_different[i], &ret2); + if(NULL == value2) + FAIL_TEST("SPDY_name_value_lookup failed\n"); + + for(j=0; j<ret; ++j) + if(0 != strcmp(value2[j], value[j])) + FAIL_TEST("SPDY_name_value_lookup failed\n"); + } + + SPDY_deinit(); + + return 0; +}