http_client: Test a stray event while connecting #215

Open
koolkhel wants to merge 4 commits from koolkhel/vitastor:http-connect-stray-event-test into master

View File

@@ -4,6 +4,11 @@
#undef NDEBUG
#include <assert.h>
#include <stdio.h>
#include <poll.h>
#include <unistd.h>
#include <netinet/in.h>
#include <sys/epoll.h>
#include <sys/socket.h>
#include "http_client.h"
#include "timerfd_manager.h"
@@ -66,10 +71,67 @@ static void test_sync_error_leaves_no_timer(int mode)
printf("test_sync_error_leaves_no_timer %d passed\n", mode);
}
// An event without EPOLLOUT or EPOLLERR while connect() is in progress must not spin the event loop
static void test_stray_event_while_connecting()
{
printf("test_stray_event_while_connecting\n");
timerfd_manager_t tfd(nullptr);
std::function<void(int, int)> fd_cb;
int cb_fd = -1;
tfd.set_fd_handler = [&](int fd, bool, std::function<void(int, int)> cb)
{
if (cb)
{
cb_fd = fd;
fd_cb = cb;
}
};
int listen_fd = socket(AF_INET, SOCK_STREAM, 0);
sockaddr_in addr = {};
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
socklen_t addr_len = sizeof(addr);
assert(listen_fd >= 0);
assert(bind(listen_fd, (sockaddr*)&addr, addr_len) == 0);
assert(listen(listen_fd, 1) == 0);
assert(getsockname(listen_fd, (sockaddr*)&addr, &addr_len) == 0);
std::string err;
http_context_t *ctx = http_context_init(&tfd, "", "", "", false, err);
assert(ctx && err == "");
http_co_t *cli = http_init(ctx);
bool done = false;
http_request(cli, "127.0.0.1:"+std::to_string(ntohs(addr.sin_port)), request, { .timeout = 5000, .keepalive = true }, [&](http_message_t *)
{
done = true;
});
assert(fd_cb);
fd_cb(cb_fd, EPOLLIN);
fd_cb(cb_fd, EPOLLRDHUP);
assert(!done);
// The connect still completes, and the stray EPOLLRDHUP does not end the connection
struct pollfd pfd = { .fd = cb_fd, .events = POLLOUT };
assert(poll(&pfd, 1, 1000) == 1);
fd_cb(cb_fd, EPOLLOUT);
assert(!done);
int peer_fd = accept(listen_fd, NULL, NULL);
assert(peer_fd >= 0);
struct pollfd rfd = { .fd = peer_fd, .events = POLLIN };
assert(poll(&rfd, 1, 1000) == 1);
char buf[4];
assert(read(peer_fd, buf, 4) == 4 && std::string(buf, 4) == "GET ");
close(peer_fd);
http_close(cli);
http_destroy(cli);
http_context_destroy(ctx);
close(listen_fd);
printf("test_stray_event_while_connecting passed\n");
}
int main(int narg, char *args[])
{
test_sync_error_leaves_no_timer(FAIL_REQUEST);
test_sync_error_leaves_no_timer(FAIL_REQUEST_NEXT_IN_CB);
test_sync_error_leaves_no_timer(FAIL_WEBSOCKET);
test_stray_event_while_connecting();
return 0;
}