1 /*-------------------------------------------------------------------------
2 * drawElements Utility Library
3 * ----------------------------
5 * Copyright 2014 The Android Open Source Project
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
21 * \brief Socket abstraction.
22 *//*--------------------------------------------------------------------*/
28 #if (DE_OS == DE_OS_WIN32)
29 # define DE_USE_WINSOCK
30 #elif (DE_OS == DE_OS_UNIX) || (DE_OS == DE_OS_OSX) || (DE_OS == DE_OS_IOS) || (DE_OS == DE_OS_ANDROID) || (DE_OS == DE_OS_SYMBIAN)
31 # define DE_USE_BERKELEY_SOCKETS
33 # error Implement deSocket for your OS.
36 /* Common utilities. */
38 const char* deGetSocketResultName (deSocketResult result)
42 case DE_SOCKETRESULT_SUCCESS: return "DE_SOCKETRESULT_SUCCESS";
43 case DE_SOCKETRESULT_WOULD_BLOCK: return "DE_SOCKETRESULT_WOULD_BLOCK";
44 case DE_SOCKETRESULT_CONNECTION_CLOSED: return "DE_SOCKETRESULT_CONNECTION_CLOSED";
45 case DE_SOCKETRESULT_CONNECTION_TERMINATED: return "DE_SOCKETRESULT_CONNECTION_TERMINATED";
46 case DE_SOCKETRESULT_ERROR: return "DE_SOCKETRESULT_ERROR";
47 default: return DE_NULL;
51 const char* deGetSocketFamilyName (deSocketFamily family)
55 case DE_SOCKETFAMILY_INET4: return "DE_SOCKETFAMILY_INET4";
56 case DE_SOCKETFAMILY_INET6: return "DE_SOCKETFAMILY_INET6";
57 default: return DE_NULL;
61 #if defined(DE_USE_WINSOCK) || defined(DE_USE_BERKELEY_SOCKETS)
63 /* Common deSocketAddress implementation. */
65 struct deSocketAddress_s
69 deSocketFamily family;
71 deSocketProtocol protocol;
74 deSocketAddress* deSocketAddress_create (void)
76 deSocketAddress* addr = (deSocketAddress*)deCalloc(sizeof(deSocketAddress));
81 addr->family = DE_SOCKETFAMILY_INET4;
82 addr->type = DE_SOCKETTYPE_STREAM;
83 addr->protocol = DE_SOCKETPROTOCOL_TCP;
88 deBool deSocketAddress_setFamily (deSocketAddress* address, deSocketFamily family)
90 address->family = family;
94 deSocketFamily deSocketAddress_getFamily (const deSocketAddress* address)
96 return address->family;
99 void deSocketAddress_destroy (deSocketAddress* address)
101 deFree(address->host);
105 deBool deSocketAddress_setPort (deSocketAddress* address, int port)
107 address->port = port;
111 int deSocketAddress_getPort (const deSocketAddress* address)
113 return address->port;
116 deBool deSocketAddress_setHost (deSocketAddress* address, const char* host)
120 deFree(address->host);
121 address->host = DE_NULL;
124 address->host = deStrdup(host);
125 return address->host != DE_NULL;
128 const char* deSocketAddress_getHost (const deSocketAddress* address)
130 return address->host;
134 deBool deSocketAddress_setType (deSocketAddress* address, deSocketType type)
136 address->type = type;
140 deSocketType deSocketAddress_getType (const deSocketAddress* address)
142 return address->type;
145 deBool deSocketAddress_setProtocol (deSocketAddress* address, deSocketProtocol protocol)
147 address->protocol = protocol;
151 deSocketProtocol deSocketAddress_getProtocol (const deSocketAddress* address)
153 return address->protocol;
158 #if defined(DE_USE_WINSOCK)
160 /* WinSock spesific. */
161 # include <WinSock2.h>
162 # include <WS2tcpip.h>
165 static deBool initWinsock (void)
168 if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
174 #elif defined(DE_USE_BERKELEY_SOCKETS)
176 /* Berkeley Socket includes. */
177 # include <sys/socket.h>
178 # include <netinet/in.h>
179 # include <netinet/tcp.h>
180 # include <arpa/inet.h>
189 #if defined(DE_USE_WINSOCK)
190 /* \note SOCKET is unsigned type! */
191 typedef SOCKET deSocketHandle;
192 # define DE_INVALID_SOCKET_HANDLE INVALID_SOCKET
194 typedef int deSocketHandle;
195 # define DE_INVALID_SOCKET_HANDLE -1
198 DE_INLINE deBool deSocketHandleIsValid (deSocketHandle handle)
200 return handle != DE_INVALID_SOCKET_HANDLE;
203 #if defined(DE_USE_WINSOCK) || defined(DE_USE_BERKELEY_SOCKETS)
205 /* Shared berkeley and winsock implementation. */
209 deSocketHandle handle;
212 volatile deSocketState state;
213 volatile deUint32 openChannels;
216 /* Common socket functions. */
218 static int deSocketFamilyToBsdFamily (deSocketFamily family)
222 case DE_SOCKETFAMILY_INET4: return AF_INET;
223 case DE_SOCKETFAMILY_INET6: return AF_INET6;
230 static int deSocketTypeToBsdType (deSocketType type)
234 case DE_SOCKETTYPE_STREAM: return SOCK_STREAM;
235 case DE_SOCKETTYPE_DATAGRAM: return SOCK_DGRAM;
242 static int deSocketProtocolToBsdProtocol (deSocketProtocol protocol)
246 case DE_SOCKETPROTOCOL_TCP: return IPPROTO_TCP;
247 case DE_SOCKETPROTOCOL_UDP: return IPPROTO_UDP;
254 static deBool deSocketAddressToBsdAddress (const deSocketAddress* address, int bsdAddrBufSize, struct sockaddr* bsdAddr, int* bsdAddrLen)
256 deMemset(bsdAddr, 0, bsdAddrBufSize);
259 if (address->host != DE_NULL)
261 struct addrinfo* result = DE_NULL;
262 struct addrinfo hints;
264 deMemset(&hints, 0, sizeof(hints));
265 hints.ai_family = deSocketFamilyToBsdFamily(address->family);
266 hints.ai_socktype = deSocketTypeToBsdType(address->type);
267 hints.ai_protocol = deSocketProtocolToBsdProtocol(address->protocol);
269 if (getaddrinfo(address->host, DE_NULL, &hints, &result) != 0 || !result)
272 freeaddrinfo(result);
276 /* \note Always uses first address. */
278 if (bsdAddrBufSize < (int)result->ai_addrlen)
280 DE_ASSERT(!"Too small bsdAddr buffer");
281 freeaddrinfo(result);
285 *bsdAddrLen = (int)result->ai_addrlen;
287 deMemcpy(bsdAddr, result->ai_addr, (int)result->ai_addrlen);
288 freeaddrinfo(result);
291 if (bsdAddr->sa_family == AF_INET)
293 if (*bsdAddrLen < (int)sizeof(struct sockaddr_in))
295 ((struct sockaddr_in*)bsdAddr)->sin_port = htons((deUint16)address->port);
297 else if (bsdAddr->sa_family == AF_INET6)
299 if (*bsdAddrLen < (int)sizeof(struct sockaddr_in6))
301 ((struct sockaddr_in6*)bsdAddr)->sin6_port = htons((deUint16)address->port);
308 else if (address->family == DE_SOCKETFAMILY_INET4)
310 struct sockaddr_in* addr4 = (struct sockaddr_in*)bsdAddr;
312 if (bsdAddrBufSize < (int)sizeof(struct sockaddr_in))
314 DE_ASSERT(!"Too small bsdAddr buffer");
318 addr4->sin_port = htons((deUint16)address->port);
319 addr4->sin_family = AF_INET;
320 addr4->sin_addr.s_addr = INADDR_ANY;
322 *bsdAddrLen = sizeof(struct sockaddr_in);
326 else if (address->family == DE_SOCKETFAMILY_INET6)
328 struct sockaddr_in6* addr6 = (struct sockaddr_in6*)bsdAddr;
330 if (bsdAddrBufSize < (int)sizeof(struct sockaddr_in6))
332 DE_ASSERT(!"Too small bsdAddr buffer");
336 addr6->sin6_port = htons((deUint16)address->port);
337 addr6->sin6_family = AF_INET6;
339 *bsdAddrLen = sizeof(struct sockaddr_in6);
347 void deBsdAddressToSocketAddress (deSocketAddress* address, const struct sockaddr* bsdAddr, int addrLen)
349 /* Decode client address info. */
350 if (bsdAddr->sa_family == AF_INET)
352 const struct sockaddr_in* addr4 = (const struct sockaddr_in*)bsdAddr;
353 DE_ASSERT(addrLen >= (int)sizeof(struct sockaddr_in));
356 deSocketAddress_setFamily(address, DE_SOCKETFAMILY_INET4);
357 deSocketAddress_setPort(address, ntohs(addr4->sin_port));
360 char buf[16]; /* Max valid address takes 3*4 + 3 = 15 chars */
361 inet_ntop(AF_INET, (void*)&addr4->sin_addr, buf, sizeof(buf));
362 deSocketAddress_setHost(address, buf);
365 else if (bsdAddr->sa_family == AF_INET6)
367 const struct sockaddr_in6* addr6 = (const struct sockaddr_in6*)bsdAddr;
368 DE_ASSERT(addrLen >= (int)sizeof(struct sockaddr_in6));
371 deSocketAddress_setFamily(address, DE_SOCKETFAMILY_INET6);
372 deSocketAddress_setPort(address, ntohs(addr6->sin6_port));
375 char buf[40]; /* Max valid address takes 8*4 + 7 = 39 chars */
376 inet_ntop(AF_INET6, (void*)&addr6->sin6_addr, buf, sizeof(buf));
377 deSocketAddress_setHost(address, buf);
384 deSocket* deSocket_create (void)
386 deSocket* sock = (deSocket*)deCalloc(sizeof(deSocket));
390 #if defined(DE_USE_WINSOCK)
391 /* Make sure WSA is up. */
396 sock->stateLock = deMutex_create(0);
397 sock->handle = DE_INVALID_SOCKET_HANDLE;
398 sock->state = DE_SOCKETSTATE_CLOSED;
403 void deSocket_destroy (deSocket* sock)
405 if (sock->state != DE_SOCKETSTATE_CLOSED)
406 deSocket_close(sock);
408 deMutex_destroy(sock->stateLock);
412 deSocketState deSocket_getState (const deSocket* sock)
417 deUint32 deSocket_getOpenChannels (const deSocket* sock)
419 return sock->openChannels;
422 deBool deSocket_setFlags (deSocket* sock, deUint32 flags)
424 deSocketHandle fd = sock->handle;
426 if (sock->state == DE_SOCKETSTATE_CLOSED)
431 int mode = (flags & DE_SOCKET_KEEPALIVE) ? 1 : 0;
432 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (const char*)&mode, sizeof(mode)) != 0)
438 int mode = (flags & DE_SOCKET_NODELAY) ? 1 : 0;
439 if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (const char*)&mode, sizeof(mode)) != 0)
445 #if defined(DE_USE_WINSOCK)
446 u_long mode = (flags & DE_SOCKET_NONBLOCKING) ? 1 : 0;
447 if (ioctlsocket(fd, FIONBIO, &mode) != 0)
450 int oldFlags = fcntl(fd, F_GETFL, 0);
451 int newFlags = (flags & DE_SOCKET_NONBLOCKING) ? (oldFlags | O_NONBLOCK) : (oldFlags & ~O_NONBLOCK);
452 if (fcntl(fd, F_SETFL, newFlags) != 0)
459 #if defined(DE_USE_BERKELEY_SOCKETS)
460 int oldFlags = fcntl(fd, F_GETFD, 0);
461 int newFlags = (flags & DE_SOCKET_CLOSE_ON_EXEC) ? (oldFlags | FD_CLOEXEC) : (oldFlags & ~FD_CLOEXEC);
462 if (fcntl(fd, F_SETFD, newFlags) != 0)
470 deBool deSocket_listen (deSocket* sock, const deSocketAddress* address)
472 const int backlogSize = 4;
473 deUint8 bsdAddrBuf[sizeof(struct sockaddr_in6)];
474 struct sockaddr* bsdAddr = (struct sockaddr*)&bsdAddrBuf[0];
477 if (sock->state != DE_SOCKETSTATE_CLOSED)
480 /* Resolve address. */
481 if (!deSocketAddressToBsdAddress(address, (int)sizeof(bsdAddrBuf), bsdAddr, &bsdAddrLen))
485 sock->handle = socket(bsdAddr->sa_family, deSocketTypeToBsdType(address->type), deSocketProtocolToBsdProtocol(address->protocol));
486 if (!deSocketHandleIsValid(sock->handle))
489 sock->state = DE_SOCKETSTATE_DISCONNECTED;
491 /* Allow re-using address. */
494 setsockopt(sock->handle, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuseVal, (int)sizeof(reuseVal));
497 /* Bind to address. */
498 if (bind(sock->handle, bsdAddr, bsdAddrLen) != 0)
500 deSocket_close(sock);
504 /* Start listening. */
505 if (listen(sock->handle, backlogSize) != 0)
507 deSocket_close(sock);
511 sock->state = DE_SOCKETSTATE_LISTENING;
516 deSocket* deSocket_accept (deSocket* sock, deSocketAddress* clientAddress)
518 deSocketHandle newFd = DE_INVALID_SOCKET_HANDLE;
519 deSocket* newSock = DE_NULL;
520 deUint8 bsdAddrBuf[sizeof(struct sockaddr_in6)];
521 struct sockaddr* bsdAddr = (struct sockaddr*)&bsdAddrBuf[0];
522 #if defined(DE_USE_WINSOCK)
523 int bsdAddrLen = (int)sizeof(bsdAddrBuf);
525 socklen_t bsdAddrLen = (socklen_t)sizeof(bsdAddrBuf);
528 deMemset(bsdAddr, 0, (int)bsdAddrLen);
530 #if defined(DE_USE_WINSOCK)
531 newFd = accept(sock->handle, bsdAddr, &bsdAddrLen);
533 newFd = accept(sock->handle, bsdAddr, (socklen_t*)&bsdAddrLen);
535 if (!deSocketHandleIsValid(newFd))
538 newSock = (deSocket*)deCalloc(sizeof(deSocket));
541 #if defined(DE_USE_WINSOCK)
549 newSock->stateLock = deMutex_create(0);
550 newSock->handle = newFd;
551 newSock->state = DE_SOCKETSTATE_CONNECTED;
552 newSock->openChannels = DE_SOCKETCHANNEL_BOTH;
555 deBsdAddressToSocketAddress(clientAddress, bsdAddr, (int)bsdAddrLen);
560 deBool deSocket_connect (deSocket* sock, const deSocketAddress* address)
562 deUint8 bsdAddrBuf[sizeof(struct sockaddr_in6)];
563 struct sockaddr* bsdAddr = (struct sockaddr*)&bsdAddrBuf[0];
566 /* Resolve address. */
567 if (!deSocketAddressToBsdAddress(address, (int)sizeof(bsdAddrBuf), bsdAddr, &bsdAddrLen))
571 sock->handle = socket(bsdAddr->sa_family, deSocketTypeToBsdType(address->type), deSocketProtocolToBsdProtocol(address->protocol));
572 if (!deSocketHandleIsValid(sock->handle))
576 if (connect(sock->handle, bsdAddr, bsdAddrLen) != 0)
578 #if defined(DE_USE_WINSOCK)
579 closesocket(sock->handle);
583 sock->handle = DE_INVALID_SOCKET_HANDLE;
587 sock->state = DE_SOCKETSTATE_CONNECTED;
588 sock->openChannels = DE_SOCKETCHANNEL_BOTH;
593 deBool deSocket_shutdown (deSocket* sock, deUint32 channels)
595 deUint32 closedChannels = 0;
597 deMutex_lock(sock->stateLock);
599 if (sock->state == DE_SOCKETSTATE_DISCONNECTED ||
600 sock->state == DE_SOCKETSTATE_CLOSED)
602 deMutex_unlock(sock->stateLock);
606 DE_ASSERT(channels != 0 && (channels & ~DE_SOCKETCHANNEL_BOTH) == 0);
608 /* Don't attempt to close already closed channels on partially open socket. */
609 channels &= sock->openChannels;
613 deMutex_unlock(sock->stateLock);
617 #if defined(DE_USE_WINSOCK)
621 if ((channels & DE_SOCKETCHANNEL_BOTH) == DE_SOCKETCHANNEL_BOTH)
623 else if (channels & DE_SOCKETCHANNEL_SEND)
625 else if (channels & DE_SOCKETCHANNEL_RECEIVE)
628 if (shutdown(sock->handle, how) == 0)
629 closedChannels = channels;
632 int err = WSAGetLastError();
634 /* \note Due to asynchronous behavior certain errors are perfectly ok. */
635 if (err == WSAECONNABORTED || err == WSAECONNRESET || err == WSAENOTCONN)
636 closedChannels = DE_SOCKETCHANNEL_BOTH;
639 deMutex_unlock(sock->stateLock);
648 if ((channels & DE_SOCKETCHANNEL_BOTH) == DE_SOCKETCHANNEL_BOTH)
650 else if (channels & DE_SOCKETCHANNEL_SEND)
652 else if (channels & DE_SOCKETCHANNEL_RECEIVE)
655 if (shutdown(sock->handle, how) == 0)
656 closedChannels = channels;
659 if (errno == ENOTCONN)
660 closedChannels = DE_SOCKETCHANNEL_BOTH;
663 deMutex_unlock(sock->stateLock);
670 sock->openChannels &= ~closedChannels;
671 if (sock->openChannels == 0)
672 sock->state = DE_SOCKETSTATE_DISCONNECTED;
674 deMutex_unlock(sock->stateLock);
678 deBool deSocket_close (deSocket* sock)
680 deMutex_lock(sock->stateLock);
682 if (sock->state == DE_SOCKETSTATE_CLOSED)
684 deMutex_unlock(sock->stateLock);
688 #if !defined(DE_USE_WINSOCK)
689 if (sock->state == DE_SOCKETSTATE_LISTENING)
691 /* There can be a thread blockin in accept(). Release it by calling shutdown. */
692 shutdown(sock->handle, SHUT_RDWR);
696 #if defined(DE_USE_WINSOCK)
697 if (closesocket(sock->handle) != 0)
700 if (close(sock->handle) != 0)
703 sock->state = DE_SOCKETSTATE_CLOSED;
704 sock->handle = DE_INVALID_SOCKET_HANDLE;
705 sock->openChannels = 0;
707 deMutex_unlock(sock->stateLock);
711 static deSocketResult mapSendRecvResult (int numBytes)
714 return DE_SOCKETRESULT_SUCCESS;
715 else if (numBytes == 0)
716 return DE_SOCKETRESULT_CONNECTION_CLOSED;
720 #if defined(DE_USE_WINSOCK)
721 int error = WSAGetLastError();
724 case WSAEWOULDBLOCK: return DE_SOCKETRESULT_WOULD_BLOCK;
727 case WSAECONNABORTED:
728 case WSAECONNRESET: return DE_SOCKETRESULT_CONNECTION_TERMINATED;
729 default: return DE_SOCKETRESULT_ERROR;
734 case EAGAIN: return DE_SOCKETRESULT_WOULD_BLOCK;
736 case ECONNRESET: return DE_SOCKETRESULT_CONNECTION_TERMINATED;
737 default: return DE_SOCKETRESULT_ERROR;
743 DE_INLINE void deSocket_setChannelsClosed (deSocket* sock, deUint32 channels)
745 deMutex_lock(sock->stateLock);
747 sock->openChannels &= ~channels;
748 if (sock->openChannels == 0)
749 sock->state = DE_SOCKETSTATE_DISCONNECTED;
751 deMutex_unlock(sock->stateLock);
754 deSocketResult deSocket_send (deSocket* sock, const void* buf, int bufSize, int* numSentPtr)
756 int numSent = (int)send(sock->handle, (const char*)buf, bufSize, 0);
757 deSocketResult result = mapSendRecvResult(numSent);
760 *numSentPtr = numSent;
763 if (result == DE_SOCKETRESULT_CONNECTION_CLOSED)
764 deSocket_setChannelsClosed(sock, DE_SOCKETCHANNEL_SEND);
765 else if (result == DE_SOCKETRESULT_CONNECTION_TERMINATED)
766 deSocket_setChannelsClosed(sock, DE_SOCKETCHANNEL_BOTH);
771 deSocketResult deSocket_receive (deSocket* sock, void* buf, int bufSize, int* numReceivedPtr)
773 int numRecv = (int)recv(sock->handle, (char*)buf, bufSize, 0);
774 deSocketResult result = mapSendRecvResult(numRecv);
777 *numReceivedPtr = numRecv;
780 if (result == DE_SOCKETRESULT_CONNECTION_CLOSED)
781 deSocket_setChannelsClosed(sock, DE_SOCKETCHANNEL_RECEIVE);
782 else if (result == DE_SOCKETRESULT_CONNECTION_TERMINATED)
783 deSocket_setChannelsClosed(sock, DE_SOCKETCHANNEL_BOTH);