forked from darrenjs/openssl_examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ssl_server_nonblock.c
103 lines (77 loc) · 2.47 KB
/
ssl_server_nonblock.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/*
Copyright (c) 2017 Darren Smith
ssl_examples is free software; you can redistribute it and/or modify
it under the terms of the MIT license. See LICENSE for details.
*/
#include "common.h"
int main(int argc, char **argv)
{
char str[INET_ADDRSTRLEN];
int port = (argc>1)? atoi(argv[1]):55555;
int servfd = socket(AF_INET, SOCK_STREAM, 0);
if (servfd < 0)
die("socket()");
int enable = 1;
if (setsockopt(servfd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)) < 0)
die("setsockopt(SO_REUSEADDR)");
/* Specify socket address */
struct sockaddr_in servaddr;
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(port);
if (bind(servfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0)
die("bind()");
if (listen(servfd, 128) < 0)
die("listen()");
int clientfd;
struct sockaddr_in peeraddr;
socklen_t peeraddr_len = sizeof(peeraddr);
struct pollfd fdset[2];
memset(&fdset, 0, sizeof(fdset));
fdset[0].fd = STDIN_FILENO;
fdset[0].events = POLLIN;
ssl_init("server.crt", "server.key"); // see README to create these files
while (1) {
printf("waiting for next connection on port %d\n", port);
clientfd = accept(servfd, (struct sockaddr *)&peeraddr, &peeraddr_len);
if (clientfd < 0)
die("accept()");
ssl_client_init(&client, clientfd, SSLMODE_SERVER);
inet_ntop(peeraddr.sin_family, &peeraddr.sin_addr, str, INET_ADDRSTRLEN);
printf("new connection from %s:%d\n", str, ntohs(peeraddr.sin_port));
fdset[1].fd = clientfd;
/* event loop */
fdset[1].events = POLLERR | POLLHUP | POLLNVAL | POLLIN;
#ifdef POLLRDHUP
fdset[1].events |= POLLRDHUP;
#endif
while (1) {
fdset[1].events &= ~POLLOUT;
fdset[1].events |= (ssl_client_want_write(&client)? POLLOUT : 0);
int nready = poll(&fdset[0], 2, -1);
if (nready == 0)
continue; /* no fd ready */
int revents = fdset[1].revents;
if (revents & POLLIN)
if (do_sock_read() == -1)
break;
if (revents & POLLOUT)
if (do_sock_write() == -1)
break;
if (revents & (POLLERR | POLLHUP | POLLNVAL))
break;
#ifdef POLLRDHUP
if (revents & POLLRDHUP)
break;
#endif
if (fdset[0].revents & POLLIN)
do_stdin_read();
if (client.encrypt_len>0)
do_encrypt();
}
close(fdset[1].fd);
ssl_client_cleanup(&client);
}
return 0;
}