2 * Copyright (c) 2006-2008,2010,2012-2013 Apple Inc. All Rights Reserved.
4 * io_sock.c - SecureTransport sample I/O module, X sockets version
10 #include <Security/SecBase.h>
12 #include <sys/types.h>
13 #include <netinet/in.h>
14 #include <sys/socket.h>
16 #include <arpa/inet.h>
19 #include <Security/SecBase.h>
24 /* debugging for this module */
25 #define SSL_OT_DEBUG 1
27 /* log errors to stdout */
28 #define SSL_OT_ERRLOG 1
30 /* trace all low-level network I/O */
31 #define SSL_OT_IO_TRACE 0
33 /* if SSL_OT_IO_TRACE, only log non-zero length transfers */
34 #define SSL_OT_IO_TRACE_NZ 1
36 /* pause after each I/O (only meaningful if SSL_OT_IO_TRACE == 1) */
37 #define SSL_OT_IO_PAUSE 0
39 /* print a stream of dots while I/O pending */
42 /* dump some bytes of each I/O (only meaningful if SSL_OT_IO_TRACE == 1) */
43 #define SSL_OT_IO_DUMP 0
44 #define SSL_OT_IO_DUMP_SIZE 256
46 /* indicate errSSLWouldBlock with a '.' */
47 #define SSL_DISPL_WOULD_BLOCK 0
49 /* general, not-too-verbose debugging */
51 #define dprintf(s) printf s
56 /* errors --> stdout */
58 #define eprintf(s) printf s
63 /* trace completion of every r/w */
71 #if SSL_OT_IO_TRACE_NZ
76 printf("%s(%u): moved (%u) bytes\n", str
, (unsigned)req
, (unsigned)act
);
81 for(i
=0; i
<act
; i
++) {
82 printf("%02X ", buf
[i
]);
83 if(i
>= (SSL_OT_IO_DUMP_SIZE
- 1)) {
93 printf("CR to continue: ");
100 #define tprintf(str, req, act, buf)
101 #endif /* SSL_OT_IO_TRACE */
104 * If SSL_OT_DOT, output a '.' every so often while waiting for
105 * connection. This gives user a chance to do something else with the
111 static time_t lastTime
= (time_t)0;
112 #define TIME_INTERVAL 3
114 static void outputDot()
116 time_t thisTime
= time(0);
118 if((thisTime
- lastTime
) >= TIME_INTERVAL
) {
119 printf("."); fflush(stdout
);
129 * One-time only init.
139 #define GETHOST_RETRIES 3
141 OSStatus
MakeServerConnection(
142 const char *hostName
,
144 int nonBlocking
, // 0 or 1
145 otSocket
*socketNo
, // RETURNED
146 PeerSpec
*peer
) // RETURNED
148 struct sockaddr_in addr
;
154 if (hostName
[0] >= '0' && hostName
[0] <= '9')
156 host
.s_addr
= inet_addr(hostName
);
160 /* seeing a lot of soft failures here that I really don't want to track down */
161 for(dex
=0; dex
<GETHOST_RETRIES
; dex
++) {
163 printf("\n...retrying gethostbyname(%s)", hostName
);
165 ent
= gethostbyname(hostName
);
171 printf("\n***gethostbyname(%s) returned: %s\n", hostName
, hstrerror(h_errno
));
174 memcpy(&host
, ent
->h_addr
, sizeof(struct in_addr
));
176 sock
= socket(AF_INET
, SOCK_STREAM
, 0);
177 addr
.sin_addr
= host
;
178 addr
.sin_port
= htons((u_short
)port
);
180 addr
.sin_family
= AF_INET
;
181 if (connect(sock
, (struct sockaddr
*) &addr
, sizeof(struct sockaddr_in
)) != 0)
183 perror("connect returned error");
188 /* OK to do this after connect? */
189 int rtn
= fcntl(sock
, F_SETFL
, O_NONBLOCK
);
191 perror("fctnl(O_NONBLOCK)");
196 peer
->ipAddr
= addr
.sin_addr
.s_addr
;
197 peer
->port
= htons((u_short
)port
);
198 *socketNo
= (otSocket
)sock
;
199 return errSecSuccess
;
203 * Set up an otSocket to listen for client connections. Call once, then
204 * use multiple AcceptClientConnection calls.
206 OSStatus
ListenForClients(
208 int nonBlocking
, // 0 or 1
209 otSocket
*socketNo
) // RETURNED
211 struct sockaddr_in addr
;
216 sock
= socket(AF_INET
, SOCK_STREAM
, 0);
223 int err
= setsockopt(sock
, SOL_SOCKET
, SO_REUSEADDR
, &reuse
, sizeof(reuse
));
225 perror("setsockopt");
229 ent
= gethostbyname("localhost");
231 perror("gethostbyname");
234 memcpy(&addr
.sin_addr
, ent
->h_addr
, sizeof(struct in_addr
));
236 addr
.sin_port
= htons((u_short
)port
);
237 addr
.sin_addr
.s_addr
= INADDR_ANY
;
238 addr
.sin_family
= AF_INET
;
239 len
= sizeof(struct sockaddr_in
);
240 if (bind(sock
, (struct sockaddr
*) &addr
, len
)) {
243 if(theErr
== EADDRINUSE
) {
251 int rtn
= fcntl(sock
, F_SETFL
, O_NONBLOCK
);
253 perror("fctnl(O_NONBLOCK)");
259 int rtn
= listen(sock
, 1);
262 *socketNo
= (otSocket
)sock
;
279 * Accept a client connection.
283 * Currently we always get back a different peer port number on successive
284 * connections, no matter what the client is doing. To test for resumable
285 * session support, force peer port = 0.
287 #define FORCE_ACCEPT_PEER_PORT_ZERO 1
289 OSStatus
AcceptClientConnection(
290 otSocket listenSock
, // obtained from ListenForClients
291 otSocket
*acceptSock
, // RETURNED
292 PeerSpec
*peer
) // RETURNED
294 struct sockaddr_in addr
;
298 len
= sizeof(struct sockaddr_in
);
300 sock
= accept((int)listenSock
, (struct sockaddr
*) &addr
, &len
);
302 if(errno
== EAGAIN
) {
303 /* nonblocking, no connection yet */
315 *acceptSock
= (otSocket
)sock
;
316 peer
->ipAddr
= addr
.sin_addr
.s_addr
;
317 #if FORCE_ACCEPT_PEER_PORT_ZERO
320 peer
->port
= ntohs(addr
.sin_port
);
322 return errSecSuccess
;
326 * Shut down a connection.
328 void endpointShutdown(
335 * R/W. Called out from SSL.
338 SSLConnectionRef connection
,
339 void *data
, /* owned by
342 size_t *dataLength
) /* IN/OUT */
344 size_t bytesToGo
= *dataLength
;
345 size_t initLen
= bytesToGo
;
346 UInt8
*currData
= (UInt8
*)data
;
347 int sock
= (int)((long)connection
);
348 OSStatus rtn
= errSecSuccess
;
349 size_t bytesRead
= 0;
355 /* paranoid check, ensure errno is getting written */
357 rrtn
= recv(sock
, currData
, bytesToGo
, 0);
361 rtn
= errSSLClosedGraceful
;
368 * Undocumented but I definitely see this.
369 * Non-blocking sockets only. Definitely retriable
370 * just like an EAGAIN.
372 dprintf(("SocketRead RETRYING on ENOENT, rrtn %d\n",
375 //rtn = errSSLWouldBlock;
376 /* ...for temp testing.... */
380 /* explicit peer abort */
381 rtn
= errSSLClosedAbort
;
384 /* nonblocking, no data */
385 rtn
= errSSLWouldBlock
;
388 dprintf(("SocketRead: read(%u) error %d, rrtn %d\n",
389 (unsigned)bytesToGo
, theErr
, (int)rrtn
));
393 /* in any case, we're done with this call if rrtn <= 0 */
397 bytesToGo
-= bytesRead
;
398 currData
+= bytesRead
;
401 /* filled buffer with incoming data, done */
405 *dataLength
= initLen
- bytesToGo
;
406 tprintf("SocketRead", initLen
, *dataLength
, (UInt8
*)data
);
408 #if SSL_OT_DOT || (SSL_OT_DEBUG && !SSL_OT_IO_TRACE)
409 if((rtn
== 0) && (*dataLength
== 0)) {
414 #if SSL_DISPL_WOULD_BLOCK
415 if(rtn
== errSSLWouldBlock
) {
416 printf("."); fflush(stdout
);
424 OSStatus
SocketWrite(
425 SSLConnectionRef connection
,
427 size_t *dataLength
) /* IN/OUT */
429 size_t bytesSent
= 0;
430 int sock
= (int)((long)connection
);
432 size_t dataLen
= *dataLength
;
433 const UInt8
*dataPtr
= (UInt8
*)data
;
436 if(oneAtATime
&& (*dataLength
> 1)) {
442 for(i
=0; i
<dataLen
; i
++) {
444 ortn
= SocketWrite(connection
, dataPtr
, &thisMove
);
451 return errSecSuccess
;
457 (char*)dataPtr
+ bytesSent
,
458 dataLen
- bytesSent
);
459 } while ((length
> 0) &&
460 ( (bytesSent
+= length
) < dataLen
) );
466 ortn
= errSSLWouldBlock
; break;
468 ortn
= errSSLClosedAbort
; break;
470 dprintf(("SocketWrite: write(%u) error %d\n",
471 (unsigned)(dataLen
- bytesSent
), theErr
));
477 ortn
= errSecSuccess
;
479 tprintf("SocketWrite", dataLen
, bytesSent
, dataPtr
);
480 *dataLength
= bytesSent
;