Skip to content

Commit cc67208

Browse files
committed
fix bug on SSL_read() blocking
1 parent f5eb4f0 commit cc67208

File tree

1 file changed

+23
-4
lines changed

1 file changed

+23
-4
lines changed

chap09/tls_client.c

+23-4
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,18 @@ int main(int argc, char *argv[]) {
131131
X509_free(cert);
132132

133133

134+
//Set to non-blocking. This is needed to for the SSL functions.
135+
//Without this, SSL_read() might block.
136+
#if defined(_WIN32)
137+
unsigned long nonblock = 1;
138+
ioctlsocket(socket_peer, FIONBIO, &nonblock);
139+
#else
140+
int flags;
141+
flags = fcntl(socket_peer, F_GETFL, 0);
142+
fcntl(socket_peer, F_SETFL, flags | O_NONBLOCK);
143+
#endif
144+
145+
134146

135147
printf("Connected.\n");
136148
printf("To send data, enter text followed by enter.\n");
@@ -157,11 +169,18 @@ int main(int argc, char *argv[]) {
157169
char read[4096];
158170
int bytes_received = SSL_read(ssl, read, 4096);
159171
if (bytes_received < 1) {
160-
printf("Connection closed by peer.\n");
161-
break;
172+
int err;
173+
if ((err = SSL_get_error(ssl, bytes_received)) &&
174+
(err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE)) {
175+
//Just waiting on SSL, nothing to do.
176+
} else {
177+
printf("Connection closed by peer.\n");
178+
break;
179+
}
180+
} else {
181+
printf("Received (%d bytes): %.*s",
182+
bytes_received, bytes_received, read);
162183
}
163-
printf("Received (%d bytes): %.*s",
164-
bytes_received, bytes_received, read);
165184
}
166185

167186
#if defined(_WIN32)

0 commit comments

Comments
 (0)