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
;
149 struct hostent
*ent
= NULL
;
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
;
277 * Accept a client connection.
281 * Currently we always get back a different peer port number on successive
282 * connections, no matter what the client is doing. To test for resumable
283 * session support, force peer port = 0.
285 #define FORCE_ACCEPT_PEER_PORT_ZERO 1
287 OSStatus
AcceptClientConnection(
288 otSocket listenSock
, // obtained from ListenForClients
289 otSocket
*acceptSock
, // RETURNED
290 PeerSpec
*peer
) // RETURNED
292 struct sockaddr_in addr
;
296 len
= sizeof(struct sockaddr_in
);
298 sock
= accept((int)listenSock
, (struct sockaddr
*) &addr
, &len
);
300 if(errno
== EAGAIN
) {
301 /* nonblocking, no connection yet */
313 *acceptSock
= (otSocket
)sock
;
314 peer
->ipAddr
= addr
.sin_addr
.s_addr
;
315 #if FORCE_ACCEPT_PEER_PORT_ZERO
318 peer
->port
= ntohs(addr
.sin_port
);
320 return errSecSuccess
;
324 * Shut down a connection.
326 void endpointShutdown(
333 * R/W. Called out from SSL.
336 SSLConnectionRef connection
,
337 void *data
, /* owned by
340 size_t *dataLength
) /* IN/OUT */
342 size_t bytesToGo
= *dataLength
;
343 size_t initLen
= bytesToGo
;
344 UInt8
*currData
= (UInt8
*)data
;
345 int sock
= (int)((long)connection
);
346 OSStatus rtn
= errSecSuccess
;
352 /* paranoid check, ensure errno is getting written */
354 rrtn
= recv(sock
, currData
, bytesToGo
, 0);
358 rtn
= errSSLClosedGraceful
;
365 * Undocumented but I definitely see this.
366 * Non-blocking sockets only. Definitely retriable
367 * just like an EAGAIN.
369 dprintf(("SocketRead RETRYING on ENOENT, rrtn %d\n",
372 //rtn = errSSLWouldBlock;
373 /* ...for temp testing.... */
377 /* explicit peer abort */
378 rtn
= errSSLClosedAbort
;
381 /* nonblocking, no data */
382 rtn
= errSSLWouldBlock
;
385 dprintf(("SocketRead: read(%u) error %d, rrtn %d\n",
386 (unsigned)bytesToGo
, theErr
, (int)rrtn
));
390 /* in any case, we're done with this call if rrtn <= 0 */
397 /* filled buffer with incoming data, done */
401 *dataLength
= initLen
- bytesToGo
;
402 tprintf("SocketRead", initLen
, *dataLength
, (UInt8
*)data
);
404 #if SSL_OT_DOT || (SSL_OT_DEBUG && !SSL_OT_IO_TRACE)
405 if((rtn
== 0) && (*dataLength
== 0)) {
410 #if SSL_DISPL_WOULD_BLOCK
411 if(rtn
== errSSLWouldBlock
) {
412 printf("."); fflush(stdout
);
420 OSStatus
SocketWrite(
421 SSLConnectionRef connection
,
423 size_t *dataLength
) /* IN/OUT */
425 size_t bytesSent
= 0;
426 int sock
= (int)((long)connection
);
428 size_t dataLen
= *dataLength
;
429 const UInt8
*dataPtr
= (UInt8
*)data
;
432 if(oneAtATime
&& (*dataLength
> 1)) {
438 for(i
=0; i
<dataLen
; i
++) {
440 ortn
= SocketWrite(connection
, dataPtr
, &thisMove
);
447 return errSecSuccess
;
453 (char*)dataPtr
+ bytesSent
,
454 dataLen
- bytesSent
);
455 } while ((length
> 0) &&
456 ( (bytesSent
+= length
) < dataLen
) );
462 ortn
= errSSLWouldBlock
; break;
464 ortn
= errSSLClosedAbort
; break;
466 dprintf(("SocketWrite: write(%u) error %d\n",
467 (unsigned)(dataLen
- bytesSent
), theErr
));
473 ortn
= errSecSuccess
;
475 tprintf("SocketWrite", dataLen
, bytesSent
, dataPtr
);
476 *dataLength
= bytesSent
;