Debian Codegraph @

3rdparty/xspublic/xstypes/xssocket.c

raw
1
2 // Copyright (c) 2003-2019 Xsens Technologies B.V. or subsidiaries worldwide.
3 // All rights reserved.
4 //
5 // Redistribution and use in source and binary forms, with or without modification,
6 // are permitted provided that the following conditions are met:
7 //
8 // 1. Redistributions of source code must retain the above copyright notice,
9 // this list of conditions, and the following disclaimer.
10 //
11 // 2. Redistributions in binary form must reproduce the above copyright notice,
12 // this list of conditions, and the following disclaimer in the documentation
13 // and/or other materials provided with the distribution.
14 //
15 // 3. Neither the names of the copyright holders nor the names of their contributors
16 // may be used to endorse or promote products derived from this software without
17 // specific prior written permission.
18 //
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
20 // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
21 // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
22 // THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
24 // OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25 // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY OR
26 // TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27 // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.THE LAWS OF THE NETHERLANDS
28 // SHALL BE EXCLUSIVELY APPLICABLE AND ANY DISPUTES SHALL BE FINALLY SETTLED UNDER THE RULES
29 // OF ARBITRATION OF THE INTERNATIONAL CHAMBER OF COMMERCE IN THE HAGUE BY ONE OR MORE
30 // ARBITRATORS APPOINTED IN ACCORDANCE WITH SAID RULES.
31 //
32
33 #ifdef _WIN32
34 #include <winsock2.h>
35 #include <winerror.h>
36 #include <ws2tcpip.h>
37 #include <stdio.h>
38 #include <iphlpapi.h>
39
40 #pragma comment(lib, "ws2_32.lib")
41 #else
42 #include <unistd.h>
43 #include <stdio.h>
44 #include <stdlib.h>
45 #include <ctype.h>
46 #include <sys/types.h>
47 #include <sys/socket.h>
48 #include <sys/time.h>
49 #include <netdb.h>
50 #include <arpa/inet.h>
51 #define SOCKET int32_t
52 #define SOCKET_ERROR -1
53 #define INVALID_SOCKET ((int32_t)-1)
54
55 /* capture the fact that windows has a specific closesocket function */
56 static int closesocket(SOCKET s)
57 {
58 close(s);
59 return 0;
60 }
61 #endif
62 #if defined(__FreeBSD__) || defined(BSD) || defined(__APPLE__) || defined(__linux__)
63 # define USE_GETIFADDRS 1
64 # include <ifaddrs.h>
65 #endif
66 #include <errno.h>
67
68 // MSG_NOSIGNAL is linux stuff
69 #ifndef MSG_NOSIGNAL
70 #define MSG_NOSIGNAL 0
71 #endif
72
73 #include "xssocket.h"
74
75 #ifndef PEEKBUFSIZE
76 #define PEEKBUFSIZE 32768
77 #endif
78
79 /* the socket data */
80 struct XsSocketPrivate
81 {
82 SOCKET m_sd;
83
84 enum NetworkLayerProtocol m_ipVersion;
85 enum IpProtocol m_ipProtocol;
86
87 struct sockaddr_storage m_remoteAddr;
88 socklen_t m_remoteAddrLen;
89
90 XsResultValue m_lastResult;
91 int m_lastSystemError;
92
93 XsDataFlags m_flags;
94 char m_peekBuf[PEEKBUFSIZE];
95
96 #ifdef _WIN32
97 WSADATA m_sockData;
98 #endif
99 };
100
101 /* Return non-zero if the native socket s is usable */
102 static int socketIsUsable(SOCKET s)
103 {
104 return (s != INVALID_SOCKET && s > 0);
105 }
106
107
108 /*!
109 * \brief Get the IP address of \a remote.
110 * \param[in] remote the socket address info of the remote peer
111 * \param[in,out] address XsString to return the host IP address in.
112 */
113 static void getRemoteHostAddress(const struct sockaddr_storage *remote, XsString *address)
114 {
115 void *src;
116 socklen_t length;
117
118 switch (remote->ss_family)
119 {
120 case AF_INET:
121 default:
122 src = &(((struct sockaddr_in*)remote)->sin_addr);
123 length = INET_ADDRSTRLEN;
124 break;
125 case AF_INET6:
126 src = &(((struct sockaddr_in6*)remote)->sin6_addr);
127 length = INET6_ADDRSTRLEN;
128 break;
129 }
130 XsString_resize(address, (XsSize)(ptrdiff_t) length);
131 if (inet_ntop(remote->ss_family, src, address->m_data, (size_t)(ptrdiff_t) length) == NULL)
132 XsString_erase(address, 0, address->m_size);
133 }
134
135 /* Update the last result of thisPtr to retval, if thisPtr is non-null
136
137 Returns retval for easy use in return statements.
138 */
139 static XsResultValue setLastResult(XsSocket* thisPtr, XsResultValue retval, int systemError)
140 {
141 if (thisPtr && thisPtr->d)
142 {
143 thisPtr->d->m_lastResult = retval;
144 thisPtr->d->m_lastSystemError = systemError;
145 }
146 return retval;
147 }
148
149 /* Translate a platform error into an XsResultValue
150
151 If thisPtr is non-null, the socket's last result will be updated.
152 */
153 static XsResultValue translateAndReturnSocketError(XsSocket* thisPtr, int functionResult)
154 {
155 XsResultValue result;
156 int err;
157 if (functionResult == 0)
158 return setLastResult(thisPtr, XRV_OK, 0);
159 #ifdef _WIN32
160 err = WSAGetLastError();
161 switch (err)
162 {
163 case WSA_INVALID_HANDLE:
164 case WSA_INVALID_PARAMETER:
165 case WSAEINVAL:
166 result = XRV_INVALIDPARAM;
167 break;
168 case WSA_NOT_ENOUGH_MEMORY:
169 result = XRV_OUTOFMEMORY;
170 break;
171 case WSA_OPERATION_ABORTED:
172 result = XRV_ABORTED;
173 break;
174 case WSAEMSGSIZE:
175 result = XRV_BUFFEROVERFLOW;
176 break;
177 case WSAETIMEDOUT:
178 result = XRV_TIMEOUTNODATA;
179 break;
180 case WSA_IO_INCOMPLETE:
181 case WSA_IO_PENDING:
182 case WSAEINTR:
183 case WSAEBADF:
184 case WSAEACCES:
185 case WSAEFAULT:
186 case WSAEMFILE:
187 case WSAEWOULDBLOCK:
188 case WSAEINPROGRESS:
189 case WSAEALREADY:
190 case WSAENOTSOCK:
191 case WSAEDESTADDRREQ:
192 case WSAEPROTOTYPE:
193 case WSAENOPROTOOPT:
194 case WSAEPROTONOSUPPORT:
195 case WSAESOCKTNOSUPPORT:
196 case WSAEOPNOTSUPP:
197 case WSAEPFNOSUPPORT:
198 case WSAEAFNOSUPPORT:
199 case WSAEADDRINUSE:
200 case WSAEADDRNOTAVAIL:
201 case WSAENETDOWN:
202 case WSAENETUNREACH:
203 case WSAENETRESET:
204 case WSAECONNABORTED:
205 case WSAECONNRESET:
206 case WSAENOBUFS:
207 case WSAEISCONN:
208 case WSAENOTCONN:
209 case WSAESHUTDOWN:
210 case WSAETOOMANYREFS:
211 case WSAECONNREFUSED:
212 case WSAELOOP:
213 case WSAENAMETOOLONG:
214 case WSAEHOSTDOWN:
215 case WSAEHOSTUNREACH:
216 case WSAENOTEMPTY:
217 case WSAEPROCLIM:
218 case WSAEUSERS:
219 case WSAEDQUOT:
220 case WSAESTALE:
221 case WSAEREMOTE:
222 case WSASYSNOTREADY:
223 case WSAVERNOTSUPPORTED:
224 case WSANOTINITIALISED:
225 case WSAEDISCON:
226 case WSAENOMORE:
227 case WSAECANCELLED:
228 case WSAEINVALIDPROCTABLE:
229 case WSAEINVALIDPROVIDER:
230 case WSAEPROVIDERFAILEDINIT:
231 case WSASYSCALLFAILURE:
232 case WSASERVICE_NOT_FOUND:
233 case WSATYPE_NOT_FOUND:
234 case WSA_E_NO_MORE:
235 case WSA_E_CANCELLED:
236 case WSAEREFUSED:
237 case WSAHOST_NOT_FOUND:
238 case WSATRY_AGAIN:
239 case WSANO_RECOVERY:
240 case WSANO_DATA:
241 default:
242 result = XRV_OTHER;
243 break;
244 }
245 #else
246 err = errno;
247 switch (err)
248 {
249 case EROFS:
250 result = XRV_READONLY;
251 break;
252 case EACCES:
253 result = XRV_INPUTCANNOTBEOPENED;
254 break;
255 case EADDRINUSE:
256 result = XRV_ALREADYOPEN;
257 break;
258 case EBADF:
259 case EINVAL:
260 case ENOTDIR:
261 case EFAULT:
262 result = XRV_INVALIDPARAM;
263 break;
264 case ENAMETOOLONG:
265 result = XRV_DATAOVERFLOW;
266 break;
267 case ENOTSOCK:
268 result = XRV_UNSUPPORTED;
269 break;
270 case EADDRNOTAVAIL:
271 case ENOENT:
272 result = XRV_NOTFOUND;
273 break;
274 case ELOOP:
275 case ENOMEM:
276 result = XRV_OUTOFMEMORY;
277 break;
278 case ETIME:
279 case ETIMEDOUT:
280 result = XRV_TIMEOUTNODATA;
281 break;
282 default:
283 result = XRV_OTHER;
284 break;
285 }
286 #endif
287 return setLastResult(thisPtr, result, err);
288 }
289
290 static void translateSocketError(XsSocket* thisPtr, int functionResult)
291 {
292 (void)translateAndReturnSocketError(thisPtr, functionResult);
293 }
294
295 /* Initialize the socket
296
297 This function performs some basic initialization on the socket
298 */
299 static void XsSocket_initialize(XsSocket* thisPtr, XsDataFlags flags)
300 {
301 thisPtr->d = (struct XsSocketPrivate*)malloc(sizeof(struct XsSocketPrivate));
302 memset(thisPtr->d, 0, sizeof(*thisPtr->d));
303 thisPtr->d->m_sd = INVALID_SOCKET;
304 thisPtr->d->m_flags = flags;
305 #ifdef _WIN32
306 (void)WSAStartup(MAKEWORD(2,0), &thisPtr->d->m_sockData);
307 #endif
308 }
309
310 /*! \brief Create socket \a thisPtr for IP version \a ip with protocol \a protocol
311
312 \param[in] ip the IP version
313 \param[in] protocol the protocol. Currently supported are TCP and UDP
314 \relates XsSocket
315 */
316 void XsSocket_create(XsSocket* thisPtr, enum NetworkLayerProtocol ip, enum IpProtocol protocol)
317 {
318 XsSocket_initialize(thisPtr, XSDF_Managed);
319
320 thisPtr->d->m_sd = socket(
321 (ip == NLP_IPV4) ? PF_INET : PF_INET6,
322 (protocol == IP_UDP) ? SOCK_DGRAM : SOCK_STREAM,
323 (protocol == IP_UDP) ? IPPROTO_UDP : IPPROTO_TCP);
324
325 thisPtr->d->m_ipVersion = ip;
326 thisPtr->d->m_ipProtocol = protocol;
327 }
328
329 /* Create a socket from a native socket
330
331 Usually we expect that theirinfo and infolen are filled in. If theirInfo is NULL though,
332 we will fetch the information from the socket. Doing so by default would add a possible
333 extra point of failure.
334 */
335 void XsSocket_createFromNativeSocket(XsSocket* thisPtr, SOCKET nativeSocket, struct sockaddr const *theirInfo, socklen_t infolen, XsDataFlags flags)
336 {
337 XsSocket_initialize(thisPtr, flags);
338 thisPtr->d->m_sd = nativeSocket;
339
340 if (theirInfo)
341 {
342 memcpy(&thisPtr->d->m_remoteAddr, theirInfo, (size_t)(ptrdiff_t) infolen);
343 thisPtr->d->m_remoteAddrLen = infolen;
344 }
345 else
346 {
347 int rv;
348 thisPtr->d->m_remoteAddrLen = sizeof(thisPtr->d->m_remoteAddr);
349 rv = getpeername(thisPtr->d->m_sd, (struct sockaddr*)&thisPtr->d->m_remoteAddr, &thisPtr->d->m_remoteAddrLen);
350 translateSocketError(thisPtr, rv);
351 }
352
353 switch (thisPtr->d->m_remoteAddr.ss_family)
354 {
355 case PF_INET6:
356 thisPtr->d->m_ipVersion = NLP_IPV6;
357 break;
358 case PF_INET:
359 thisPtr->d->m_ipVersion = NLP_IPV4;
360 break;
361 default:
362 // IRDA and the likes. do we need it?
363 break;
364 }
365 }
366
367 /*!
368 * \brief Create a socket from a native file descriptor.
369 * \param[in] sockfd the file descriptor of the underlying socket
370 * \param[in] flags flags to inicate if the underlying socket should be managed by this object
371 * \relates XsSocket
372 *
373 * If the socket should be closed when this XsSocket is destroyed then the flags
374 * should be set to XSDF_Managed.
375 */
376 void XsSocket_createFromFileDescriptor(XsSocket* thisPtr, int sockfd, XsDataFlags flags)
377 {
378 XsSocket_createFromNativeSocket(thisPtr, sockfd, NULL, 0, flags);
379 }
380
381 /*! \brief Return the native file descriptor
382 *
383 * The native socket descriptor returned from this function should only be
384 * passed to third party libraries. However, it is possible to select, read and
385 * write on it, if you know what you're doing. Do remember that this object
386 * still manages the lifetime of the file descriptor.
387 */
388 XSOCKET XsSocket_nativeDescriptor(XsSocket const* thisPtr)
389 {
390 return thisPtr->d->m_sd;
391 }
392
393 /*! \brief Close a socket
394 \details This function closes the socket. The XsSocket object is reusable after this, but this is
395 not recommended.
396 \return XRV_OK if the socket was already closed or is now closed, XRV_ERROR if some error occurred while closing the socket
397 \relates XsSocket
398 */
399 XsResultValue XsSocket_close(XsSocket* thisPtr)
400 {
401 if (thisPtr->d->m_sd == INVALID_SOCKET)
402 return XRV_OK;
403
404 if (closesocket(thisPtr->d->m_sd) == SOCKET_ERROR)
405 return XRV_ERROR;
406
407 thisPtr->d->m_sd = INVALID_SOCKET;
408 return XRV_OK;
409 }
410
411 /*! \brief Destroy the given socket
412
413 After calling this function, the XsSocket will no longer be usable for socket communications.
414
415 It is safe to call this function twice on the same XsSocket.
416
417 If the socket was created from a file descriptor using
418 XsSocket_createFromFileDescriptor and had the XSDF_Managed flag set then
419 the underlying socket will be closed.
420
421 \relates XsSocket
422 */
423 void XsSocket_destroy(XsSocket* thisPtr)
424 {
425 if (thisPtr->d)
426 {
427 if ((thisPtr->d->m_flags & XSDF_Managed) != 0)
428 {
429 (void)XsSocket_close(thisPtr);
430 }
431 free(thisPtr->d);
432 thisPtr->d = NULL;
433 #ifdef _WIN32
434 // decrease ref counter and possibly clean up socket dll
435 // http://msdn.microsoft.com/en-us/library/windows/desktop/ms741549%28v=vs.85%29.aspx
436 (void)WSACleanup();
437 #endif
438 }
439 }
440
441 /*! \brief Wait for read or write for mstimeout milliseconds on socket thisPtr
442 \param[in] mstimeout timeout in milliseconds, set to a negative value to do a blocking call
443 \param[in,out] canRead if not null will be set to non-zero if the socket has data to read
444 \param[in,out] canWrite if not null will be set to non-zero if the socket can be written to
445 \returns -1 on error, 0 when no data is available, a positive number otherwise
446 \relates XsSocket
447
448 Use canRead and canWrite to determine whether you can read from or write to the socket.
449 They will be set to non-zero if you can write, zero if you can't.
450 If only one of canRead or canWrite points to non-null, a positive non-zero return value
451 already indicates the filled in value is set to non-zero.
452 */
453 int XsSocket_select(XsSocket* thisPtr, int mstimeout, int *canRead, int *canWrite)
454 {
455 fd_set readfd;
456 fd_set writefd;
457 fd_set errorfd;
458 struct timeval timeout;
459 int rv;
460 FD_ZERO(&readfd);
461 FD_ZERO(&writefd);
462 FD_ZERO(&errorfd);
463 FD_SET(thisPtr->d->m_sd, &readfd);
464 FD_SET(thisPtr->d->m_sd, &writefd);
465 FD_SET(thisPtr->d->m_sd, &errorfd);
466
467 if (canRead)
468 *canRead = 0;
469 if (canWrite)
470 *canWrite = 0;
471
472 timeout.tv_sec = mstimeout/1000;
473 timeout.tv_usec = (mstimeout%1000) * 1000;
474
475 rv = select(FD_SETSIZE, (canRead ? &readfd : NULL),
476 (canWrite ? &writefd : NULL),
477 &errorfd, mstimeout >= 0 ? &timeout : NULL);
478
479 switch (rv)
480 {
481 case -1:
482 translateSocketError(thisPtr, rv);
483 break;
484 case 0:
485 (void)setLastResult(thisPtr, XRV_TIMEOUT, 0);
486 break;
487 default:
488 if (FD_ISSET(thisPtr->d->m_sd, &errorfd))
489 {
490 (void)setLastResult(thisPtr, XRV_ERROR, 0);
491 rv = -1;
492 break;
493 }
494
495 if (canRead)
496 *canRead = FD_ISSET(thisPtr->d->m_sd, &readfd);
497 if (canWrite)
498 *canWrite = FD_ISSET(thisPtr->d->m_sd, &writefd);
499 break;
500 }
501 return rv;
502 }
503
504 /*! \brief Read \a size data into \a dest
505
506 \param[in,out] dest a pointer to a data buffer
507 \param[in] size the size of the buffer \a dest points to
508 \param[in] timeout the amount of time in milliseconds to wait for data
509
510 \returns the size of the data read from the socket, -1 on error.
511 \relates XsSocket
512 */
513 int XsSocket_read(XsSocket* thisPtr, void* dest, XsSize size, int timeout)
514 {
515 return XsSocket_readFrom(thisPtr, dest, size, NULL, NULL, timeout);
516 }
517
518 /* peek at the size of the incoming data */
519 static int peekPendingDataSize(XsSocket* thisPtr)
520 {
521 int rv = recvfrom(thisPtr->d->m_sd, thisPtr->d->m_peekBuf, PEEKBUFSIZE, MSG_PEEK, NULL, NULL);
522 if (rv < 0)
523 {
524 translateSocketError(thisPtr, rv);
525 if (thisPtr->d->m_lastResult == XRV_BUFFEROVERFLOW)
526 return PEEKBUFSIZE;
527 }
528 return rv;
529 }
530
531 /*! \brief Read \a size data into \a dest
532
533 \param[in,out] dest a pointer to a data buffer, may be NULL, in which case only the size of the pending data is reported.
534 \param[in] size the size of the buffer \a dest points to
535 \param[in,out] hostname a pointer to a string that contains the hostname of the sender after returning from this function. May be NULL.
536 \param[in,out] port a pointer that will contain the port of the sender after returning from this function. May be NULL.
537 \param[in] timeout the amount of time in milliseconds to wait for data
538
539 \returns the size of the data read from the socket, -1 on error.
540 \relates XsSocket
541 */
542 int XsSocket_readFrom(XsSocket* thisPtr, void* dest, XsSize size, XsString* hostname, uint16_t* port, int timeout)
543 {
544 int rv;
545 int canRead;
546 struct sockaddr_storage sender;
547 socklen_t l = sizeof(sender);
548
549 rv = XsSocket_select(thisPtr, timeout, &canRead, NULL);
550 (void) canRead;
551 if (rv <= 0)
552 return rv;
553
554 if (!dest)
555 return peekPendingDataSize(thisPtr);
556
557 rv = recvfrom(thisPtr->d->m_sd, dest, (int)size, 0, (struct sockaddr *)&sender, &l);
558
559 if (hostname)
560 getRemoteHostAddress(&sender, hostname);
561
562 if (port)
563 *port = ntohs(((struct sockaddr_in*)&sender)->sin_port);
564
565 translateSocketError(thisPtr, rv);
566 return rv;
567 }
568
569 /*! \brief Read \a size data into \a dest
570
571 \param[in,out] dest a pointer to a data buffer XsByteArray, may be NULL, in which case only the size of the pending data is reported.
572 \param[in] timeout the amount of time in milliseconds to wait for data
573
574 \returns the size of the data read from the socket, -1 on error.
575 \relates XsSocket
576 */
577 int XsSocket_read2ByteArray(XsSocket* thisPtr, XsByteArray* dest, int timeout)
578 {
579 return XsSocket_readFrom2ByteArray(thisPtr, dest, NULL, NULL, timeout);
580 }
581
582 /*! \brief Read \a size data into \a dest
583
584 \param[in,out] dest a pointer to a data buffer XsByteArray, may be NULL, in which case only the size of the pending data is reported.
585 \param[in,out] hostname a pointer to a string that contains the hostname of the sender after returning from this function. May be NULL.
586 \param[in,out] port a pointer that will contain the port of the sender after returning from this function. May be NULL.
587 \param[in] timeout the amount of time in milliseconds to wait for data
588
589 \returns the size of the data read from the socket, -1 on error.
590 \relates XsSocket
591 */
592 int XsSocket_readFrom2ByteArray(XsSocket* thisPtr, XsByteArray* dest, XsString* hostname, uint16_t* port, int timeout)
593 {
594 int rv;
595 int canRead;
596 struct sockaddr_storage sender;
597 socklen_t l = sizeof(sender);
598
599 rv = XsSocket_select(thisPtr, timeout, &canRead, NULL);
600 (void) canRead;
601 if (rv <= 0)
602 return rv;
603
604 if (!dest)
605 return peekPendingDataSize(thisPtr);
606
607 rv = recvfrom(thisPtr->d->m_sd, thisPtr->d->m_peekBuf, PEEKBUFSIZE, 0, (struct sockaddr *)&sender, &l);
608 if (rv <= 0)
609 return rv;
610 XsByteArray_assign(dest, (XsSize)(ptrdiff_t) rv, thisPtr->d->m_peekBuf);
611
612 if (hostname)
613 getRemoteHostAddress(&sender, hostname);
614
615 if (port)
616 *port = ntohs(((struct sockaddr_in*)&sender)->sin_port);
617
618 translateSocketError(thisPtr, rv);
619 return rv;
620 }
621
622 /*! \brief Write data to the socket
623
624 \param[in] data a pointer to the data to write
625 \param[in] size the size of the data to write
626
627 \returns the number of bytes written, -1 or 0 on error
628 \relates XsSocket
629 */
630 int XsSocket_write(XsSocket* thisPtr, const void* data, XsSize size)
631 {
632 int canWrite;
633 int rv = XsSocket_select(thisPtr, 0, NULL, &canWrite);
634 (void) canWrite;
635 if (rv <= 0)
636 return rv;
637
638 return send(thisPtr->d->m_sd, data, (int)(ptrdiff_t)size, MSG_NOSIGNAL);
639 }
640
641 /* Return non-zero if the hostname is actually an IPv4 address */
642 int isIPv4Address(XsString const* hostname)
643 {
644 char *c;
645 int expectNum = 1;
646 int expectDot = 0;
647 int numbersFound = 0;
648
649 if (!hostname || !hostname->m_data)
650 return 0;
651
652 for (c = hostname->m_data; *c != '\0'; c++)
653 {
654 if (*c == '.')
655 {
656 if (!expectDot)
657 return 0;
658 expectNum = 1;
659 numbersFound = 0;
660 expectDot = 0;
661 }
662 else if (isdigit(*c))
663 {
664 if (!expectNum)
665 return 0;
666 expectDot = 1;
667 ++numbersFound;
668 if (numbersFound == 3)
669 expectNum = 0;
670 }
671 else
672 {
673 return 0;
674 }
675 }
676 return 1;
677 }
678
679 /* Prefix the hostname with ::ffff: if we're on ipv6 and hostname looks like a ipv4 address */
680 void XsSocket_fixupHostname(XsSocket const* thisPtr, XsString* hostname)
681 {
682 if (!hostname || !hostname->m_data)
683 return;
684
685 if (thisPtr->d->m_ipVersion == NLP_IPV4)
686 return;
687
688 if (isIPv4Address(hostname))
689 {
690 const char prefix[] = "::ffff:";
691 XsArray_insert(hostname, 0, (XsSize)strlen(prefix), prefix);
692 }
693 }
694
695 typedef int (*lookupTestFunction)(XsSocket* thisPtr, SOCKET currentSocket, struct addrinfo const* info);
696
697 /* Do a lookup of the given hostname and port
698
699 This is an internal function that centralizes the lookup code.
700
701 thisPtr - the socket to use information from
702 hostname - the hostname to look up
703 port - the port to check the connection on
704 hints_flags - the flags we should put into the lookup hints, e.g. AI_PASSIVE
705 tester - a function that performs some sanity checks on the passed info
706 info - a pointer to a sockaddr buffer. Should be at least as big as sockaddr, preferably be sockaddr_storage
707 addrlen - the size of info. This function will change addrlen based on the actual size of info if necessary
708
709 return OK or NOTFOUND
710 */
711 static XsResultValue XsSocket_internalLookup(XsSocket* thisPtr, const XsString* hostname, uint16_t port,
712 int hints_flags, lookupTestFunction tester,
713 struct sockaddr* info, socklen_t* addrlen)
714 {
715 struct addrinfo *lookupInfo, *p;
716 SOCKET s;
717 char gaport[7];
718 struct addrinfo hints;
719 int ret;
720 memset(&hints, 0, sizeof(hints));
721
722 switch (thisPtr->d->m_ipVersion)
723 {
724 case NLP_IPV6: hints.ai_family = AF_INET6; break;
725 case NLP_IPV4: hints.ai_family = AF_INET; break;
726 case NLP_IPVX: hints.ai_family = AF_UNSPEC; break;
727 }
728 hints.ai_socktype = (thisPtr->d->m_ipProtocol == IP_UDP) ? SOCK_DGRAM : SOCK_STREAM;
729 hints.ai_flags = hints_flags;
730
731 sprintf(gaport, "%u", (unsigned int) port);
732 if (hostname)
733 {
734 XsString host;
735
736 XsString_construct(&host);
737 XsArray_copy(&host, hostname);
738
739 XsSocket_fixupHostname(thisPtr, &host);
740
741 ret = getaddrinfo(host.m_data, gaport, &hints, &lookupInfo);
742
743 XsString_destruct(&host);
744 }
745 else
746 {
747 ret = getaddrinfo(NULL, gaport, &hints, &lookupInfo);
748 }
749
750 if (ret)
751 {
752 switch (ret)
753 {
754 case EAI_BADFLAGS:
755 return setLastResult(thisPtr, XRV_INVALIDPARAM, -1);
756 case EAI_AGAIN:
757 return translateAndReturnSocketError(thisPtr, EAGAIN);
758 case EAI_FAIL:
759 return setLastResult(thisPtr, XRV_ERROR, -1);
760 case EAI_MEMORY:
761 return setLastResult(thisPtr, XRV_INSUFFICIENTSPACE, -1);
762 //case EAI_NODATA:
763 // return setLastResult(thisPtr, XRV_TIMEOUTNODATA, -1);
764 case EAI_NONAME:
765 return setLastResult(thisPtr, XRV_INSUFFICIENTDATA, -1);
766 //case EAI_ADDRFAMILY:
767 case EAI_SERVICE:
768 case EAI_FAMILY:
769 case EAI_SOCKTYPE:
770 return setLastResult(thisPtr, XRV_UNSUPPORTED, -1);
771 default:
772 return translateAndReturnSocketError(thisPtr, ret);
773 }
774 }
775
776 setLastResult(thisPtr, XRV_NOTFOUND, -1);
777 for (p = lookupInfo; p != NULL; p = p->ai_next)
778 {
779 s = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
780 if (!socketIsUsable(s))
781 continue;
782
783 ret = tester(thisPtr, s, p);
784 if (ret == 0)
785 {
786 (void)closesocket(s);
787 if (info && addrlen)
788 {
789 if ((socklen_t)p->ai_addrlen < *addrlen)
790 *addrlen = (socklen_t)p->ai_addrlen;
791 memcpy(info, p->ai_addr, (size_t)(ptrdiff_t) *addrlen);
792 }
793 break;
794 }
795 (void)closesocket(s);
796 }
797 freeaddrinfo(lookupInfo);
798 return setLastResult(thisPtr, (ret == 0) ? XRV_OK : thisPtr->d->m_lastResult, ret);
799 }
800
801 /* try and see if we can connect on currentSocket to the remote host */
802 static int defaultLookupTest(XsSocket* thisPtr, SOCKET currentSocket, struct addrinfo const* info)
803 {
804 (void)thisPtr;
805 return connect(currentSocket, info->ai_addr, (int) info->ai_addrlen);
806 }
807
808 /*! \brief Perform a lookup */
809 static XsResultValue XsSocket_lookup(XsSocket* thisPtr, const XsString* hostname, uint16_t port, struct sockaddr* info, socklen_t* addrlen)
810 {
811 return XsSocket_internalLookup(thisPtr, hostname, port, 0, defaultLookupTest, info, addrlen);
812 }
813
814 /*! \brief Write data to the socket to the host indicated by \a hostname, \a port
815
816 \param[in] data the data to write
817 \param[in] size the size of the data
818 \param[in] hostname the name of the host to send data to
819 \param[in] port the port to send data to
820
821 \returns the number of bytes written, -1 on error.
822 \relates XsSocket
823 */
824 int XsSocket_writeTo(XsSocket* thisPtr, const void* data, XsSize size, const XsString* hostname, uint16_t port)
825 {
826 struct sockaddr_storage storage;
827 struct sockaddr* addr = NULL;
828 socklen_t addrlen = 0;
829 int sent;
830 int canWrite;
831 int rv;
832
833 rv = XsSocket_select(thisPtr, 0, NULL, &canWrite);
834 (void) canWrite;
835 if (rv <= 0)
836 return rv;
837
838 if (thisPtr->d->m_ipProtocol == IP_UDP)
839 {
840 addr = (struct sockaddr*)&storage;
841 addrlen = sizeof(storage);
842
843 if (XsSocket_lookup(thisPtr, hostname, port, addr, &addrlen) != XRV_OK)
844 return -1;
845 }
846
847 sent = sendto(thisPtr->d->m_sd, data, (int)size, MSG_NOSIGNAL, addr, addrlen);
848 translateSocketError(thisPtr, sent);
849 return sent;
850 }
851
852 /*! \brief Enable sending and receiving broadcasts on this socket
853 \details By default sockets do not receive broadcasts and can't send them. This function can enable this option.
854 \param enable Set to 1 to enable broadcasts, 0 to disable them again
855 \return 1 if successful, 0 if a failure occurred
856 \relates XsSocket
857 */
858 int XsSocket_enableBroadcasts(XsSocket* thisPtr, int enable)
859 {
860 int broadcast = enable ? 1 : 0;
861 int res = setsockopt(thisPtr->d->m_sd, SOL_SOCKET, SO_BROADCAST, (char*)&broadcast, sizeof(broadcast));
862 if (res != 0)
863 {
864 thisPtr->d->m_lastResult = translateAndReturnSocketError(thisPtr, res);
865 return 0;
866 }
867 thisPtr->d->m_lastResult = XRV_OK;
868 return 1;
869 }
870
871 #ifdef USE_GETIFADDRS
872 static uint32_t SockAddrToUint32(struct sockaddr * a)
873 {
874 return ((a)&&(a->sa_family == AF_INET)) ? ntohl(((struct sockaddr_in *)a)->sin_addr.s_addr) : 0;
875 }
876 #endif
877
878 /*! \brief Broadcast data over the socket to the port indicated by \a port
879
880 \param[in] data the data to write
881 \param[in] size the size of the data
882 \param[in] port the port to send data to
883
884 \returns the number of bytes written, -1 on error, depending on whether the majority of sub broadcasts succeeded or failed.
885 \relates XsSocket
886 */
887 int XsSocket_broadcast(XsSocket* thisPtr, const void* data, XsSize size, uint16_t port)
888 {
889 struct sockaddr_in addr;
890 int sent = 0;
891 int failed = 0;
892 int ok = 0;
893 int canWrite;
894 int rv;
895
896 rv = XsSocket_select(thisPtr, 0, NULL, &canWrite);
897 (void) canWrite;
898 if (rv <= 0)
899 return rv;
900
901 if (thisPtr->d->m_ipProtocol == IP_UDP)
902 {
903 addr.sin_family = AF_INET;
904 addr.sin_port = htons(port);
905 addr.sin_addr.s_addr = INADDR_BROADCAST; // this is equiv to 255.255.255.255 and won't work!
906
907 #ifdef _WIN32
908 do
909 {
910 // Windows XP style implementation
911 MIB_IPADDRTABLE * ipTable = NULL;
912 {
913 ULONG bufLen = 0;
914 for (int i=0; i<5; i++)
915 {
916 DWORD ipRet = GetIpAddrTable(ipTable, &bufLen, FALSE);
917 if (ipRet == ERROR_INSUFFICIENT_BUFFER)
918 {
919 free(ipTable); // in case we had previously allocated it
920 ipTable = (MIB_IPADDRTABLE *) malloc(bufLen);
921 }
922 else if (ipRet == NO_ERROR)
923 break;
924 else
925 {
926 free(ipTable);
927 ipTable = NULL;
928 break;
929 }
930 }
931 }
932
933 if (ipTable)
934 {
935 IP_ADAPTER_INFO * pAdapterInfo = NULL;
936 {
937 ULONG bufLen = 0;
938 for (int i=0; i<5; i++)
939 {
940 DWORD apRet = GetAdaptersInfo(pAdapterInfo, &bufLen);
941 if (apRet == ERROR_BUFFER_OVERFLOW)
942 {
943 free(pAdapterInfo); // in case we had previously allocated it
944 pAdapterInfo = (IP_ADAPTER_INFO *) malloc(bufLen);
945 }
946 else if (apRet == ERROR_SUCCESS)
947 break;
948 else
949 {
950 free(pAdapterInfo);
951 pAdapterInfo = NULL;
952 break;
953 }
954 }
955 }
956
957 for (DWORD i=0; i<ipTable->dwNumEntries; i++)
958 {
959 const MIB_IPADDRROW* row = &ipTable->table[i];
960 uint32_t ad = ntohl(row->dwAddr) | ~ntohl(row->dwMask);
961 char bcastAddr[32];
962 sprintf(bcastAddr, "%u.%u.%u.%u", (ad >> 24)&0xFF, (ad >> 16) & 0xFF, (ad >> 8) & 0xFF, ad & 0xFF);
963 inet_pton(AF_INET, bcastAddr, &addr.sin_addr);
964 sent = sendto(thisPtr->d->m_sd, data, (int)size, MSG_NOSIGNAL, (struct sockaddr const*) &addr, sizeof(addr));
965 if (sent < 0)
966 {
967 ++failed;
968 translateSocketError(thisPtr, sent);
969 }
970 else if (sent > 0)
971 ++ok;
972 }
973
974 free(pAdapterInfo);
975 free(ipTable);
976 }
977 }
978 while (0);
979 #elif defined(USE_GETIFADDRS)
980 // BSD-style implementation
981 struct ifaddrs * ifap;
982 if (getifaddrs(&ifap) == 0)
983 {
984 struct ifaddrs * p = ifap;
985 while (p)
986 {
987 uint32_t bcastAddr = (uint32_t)SockAddrToUint32(p->ifa_dstaddr);
988 if (bcastAddr > 0)
989 {
990 char bcastAddrStr[32];
991 sprintf(bcastAddrStr, "%u.%u.%u.%u", (bcastAddr >> 24)&0xFF, (bcastAddr >> 16) & 0xFF, (bcastAddr >> 8) & 0xFF, bcastAddr & 0xFF);
992 inet_pton(AF_INET, bcastAddrStr, &addr.sin_addr);
993 sent = (int)sendto(thisPtr->d->m_sd, data, size, MSG_NOSIGNAL, (struct sockaddr const*) &addr, sizeof(addr));
994 if (sent < 0)
995 {
996 ++failed;
997 translateSocketError(thisPtr, sent);
998 }
999 else if (sent > 0)
1000 ++ok;
1001 }
1002 p = p->ifa_next;
1003 }
1004 freeifaddrs(ifap);
1005 }
1006 #else
1007 // just use direct local broadcast, this may or may not work depending on the system configuration
1008 sent = sendto(thisPtr->d->m_sd, data, (int)size, MSG_NOSIGNAL, (struct sockaddr const*) &addr, sizeof(addr));
1009 if (sent < 0)
1010 ++failed;
1011 else
1012 ++ok;
1013 #endif
1014 }
1015 if (failed >= ok)
1016 return -1;
1017 translateSocketError(thisPtr, sent);
1018 return sent;
1019 }
1020
1021 /*! \brief Flush the incoming data
1022
1023 Flush all data from the incoming buffer.
1024
1025 \relates XsSocket
1026 */
1027 void XsSocket_flush(XsSocket* thisPtr)
1028 {
1029 char buf[512];
1030
1031 while (XsSocket_read(thisPtr, buf, sizeof(buf), 0) > 0)
1032 {
1033 /* nop */
1034 }
1035 }
1036
1037 /*! \brief Accept an incoming connection
1038
1039 This function requires that XsSocket_listen() has already been called.
1040
1041 The returned pointer should be freed using XsSocket_freeAcceptedSocket().
1042
1043 \param[in] mstimeout the timeout in milliseconds
1044
1045 \returns a pointer to a newly created socket for the new connection. NULL on error.
1046 \relates XsSocket
1047 */
1048 XsSocket* XsSocket_accept(XsSocket* thisPtr, int mstimeout)
1049 {
1050 XsSocket *ns;
1051 struct sockaddr_storage theirInfo;
1052 socklen_t infoLength = sizeof(struct sockaddr_storage);
1053 SOCKET sd;
1054
1055 if (mstimeout >= 0)
1056 {
1057 int read;
1058 int rv = XsSocket_select(thisPtr, mstimeout, &read, NULL);
1059 (void) read;
1060 if (rv == 0)
1061 {
1062 (void)setLastResult(thisPtr, XRV_TIMEOUTNODATA, 0);
1063 return NULL;
1064 }
1065 else if (rv == -1)
1066 {
1067 translateSocketError(thisPtr, rv);
1068 return NULL;
1069 }
1070 }
1071
1072 sd = accept(thisPtr->d->m_sd, (struct sockaddr *)&theirInfo, &infoLength);
1073 if (!socketIsUsable(sd))
1074 return NULL;
1075
1076 ns = XsSocket_allocate();
1077 XsSocket_createFromNativeSocket(ns, sd, (struct sockaddr*)&theirInfo, infoLength, XSDF_Managed);
1078 return ns;
1079 }
1080
1081 /*! \brief Dynamically allocate an XsSocket
1082
1083 After calling this function, it is still required to call
1084 XsSocket_create or the internal function XsSocket_createFromNativeSocket
1085
1086 Use XsSocket_free to safely free the returned XsSocket.
1087
1088 \returns a pointer to a newly allocated XsSocket, or NULL on error
1089 */
1090 XsSocket* XsSocket_allocate()
1091 {
1092 return (XsSocket*)malloc(sizeof(XsSocket));
1093 }
1094
1095 /*! \brief Free a socket returned from XsSocket_accept() or XsSocket_allocate()
1096
1097 Use this function only on sockets returned from XsSocket_accept().
1098
1099 This function calls XsSocket_destroy() before freeing the memory.
1100
1101 \see XsSocket_destroy
1102 \relates XsSocket
1103 */
1104 void XsSocket_free(XsSocket* thisPtr)
1105 {
1106 XsSocket_destroy(thisPtr);
1107 free(thisPtr);
1108 }
1109
1110 /*! \brief Changes the value of a socket option
1111 * \param[in] option the socket option to change
1112 * \param[in] valuePtr poins to the value the option must be set to
1113 * \param[in] valueSize the size of the value \a valuePtr points to
1114 * \return an XsResultValue indicating the result of the operation, possibly pointing towards a cause
1115 * \relates XsSocket
1116 */
1117 XsResultValue XsSocket_setSocketOption(XsSocket *thisPtr, enum XsSocketOption option, void* valuePtr, int valueSize)
1118 {
1119 int res;
1120 int nativeOption;
1121 #ifdef _WIN32
1122 const char *valPtr = (const char*)valuePtr;
1123 #else
1124 const void *valPtr = valuePtr;
1125 #endif
1126
1127 switch(option)
1128 {
1129 case XSO_ReuseAddress:
1130 nativeOption = SO_REUSEADDR;
1131 break;
1132
1133 #if !defined(_WIN32) && !defined(__ANDROID__) && defined(SO_REUSEPORT)
1134 case XSO_ReusePort:
1135 nativeOption = SO_REUSEPORT;
1136 break;
1137 #endif
1138
1139 default:
1140 return XRV_OK;
1141 }
1142
1143 res = setsockopt(thisPtr->d->m_sd, SOL_SOCKET, nativeOption, valPtr, valueSize);
1144 return translateAndReturnSocketError(thisPtr, res);
1145 }
1146
1147
1148 /* test if we can bind to info
1149
1150 keeps the bind alive after leaving the function
1151 */
1152 static int binder(XsSocket* thisPtr, SOCKET currentSocket, struct addrinfo const* info)
1153 {
1154 int res;
1155 int yesval = 1;
1156 #ifdef _WIN32
1157 const char *yes = (const char*)&yesval;
1158 #else
1159 const void *yes = &yesval;
1160 #endif
1161
1162 (void)currentSocket;
1163
1164 res = setsockopt(thisPtr->d->m_sd, SOL_SOCKET, SO_REUSEADDR, yes, sizeof(yesval));
1165 if (res)
1166 return res;
1167
1168 return bind(thisPtr->d->m_sd, info->ai_addr, (int)info->ai_addrlen);
1169 }
1170
1171 /*! \brief Bind to the \a hostname and \a port combination
1172
1173 \param[in] hostname the hostname to bind to, may be NULL, in which we will bind to any address
1174 \param[in] port the port to bind to. Must be a value above 1023, unless we have elevated privileges
1175
1176 \return an XsResultValue indicating the result of the operation, possibly pointing towards a cause
1177 \relates XsSocket
1178 */
1179 XsResultValue XsSocket_bind(XsSocket* thisPtr, const XsString* hostname, uint16_t port)
1180 {
1181 int rv;
1182 struct sockaddr_storage s;
1183 socklen_t addrlen;
1184
1185 if (hostname)
1186 return XsSocket_internalLookup(thisPtr, hostname, port, AI_PASSIVE, binder, NULL, NULL);
1187
1188 memset(&s, 0, sizeof(s));
1189
1190 if (thisPtr->d->m_ipVersion == NLP_IPV4)
1191 {
1192 struct sockaddr_in *sin = (struct sockaddr_in*)&s;
1193 sin->sin_family = AF_INET;
1194 sin->sin_port = htons(port);
1195 sin->sin_addr.s_addr = INADDR_ANY;
1196 addrlen = sizeof(*sin);
1197 }
1198 else
1199 {
1200 struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)&s;
1201 sin6->sin6_family = AF_INET6;
1202 sin6->sin6_port = htons(port);
1203 sin6->sin6_addr = in6addr_any;
1204 addrlen = sizeof(*sin6);
1205 }
1206
1207 rv = bind(thisPtr->d->m_sd, (struct sockaddr*)&s, addrlen);
1208 return translateAndReturnSocketError(thisPtr, rv);
1209 }
1210
1211 /*! \brief Start listening for incoming connections on this socket
1212
1213 \param[in] maxPending the maximum amount of pending connections
1214
1215 \return an XsResultValue indicating the result of the operation
1216 \relates XsSocket
1217 */
1218 XsResultValue XsSocket_listen(XsSocket* thisPtr, int maxPending)
1219 {
1220 int r = listen(thisPtr->d->m_sd, maxPending);
1221 return translateAndReturnSocketError(thisPtr, r);
1222 }
1223
1224 /* Connect to info
1225
1226 Keep the connection alive
1227 */
1228 static int connector(XsSocket* thisPtr, SOCKET currentSocket, struct addrinfo const* info)
1229 {
1230 int ret;
1231 (void)currentSocket;
1232
1233 ret = connect(thisPtr->d->m_sd, info->ai_addr, (int)info->ai_addrlen);
1234
1235 if (ret == 0)
1236 {
1237 thisPtr->d->m_ipVersion = (info->ai_family == AF_INET ? NLP_IPV4 : NLP_IPV6);
1238 memcpy(&thisPtr->d->m_remoteAddr, info->ai_addr, info->ai_addrlen);
1239 thisPtr->d->m_remoteAddrLen = (socklen_t)(info->ai_addrlen);
1240 }
1241 else
1242 translateSocketError(thisPtr, ret);
1243
1244 return ret;
1245 }
1246
1247 /*! \brief Connect to \a hostame on \a port
1248
1249 \param[in] host the hostname to connect to
1250 \param[in] port the port to connect to
1251
1252 \returns an XsResultValue indicating the result of the operation
1253 \relates XsSocket
1254 */
1255 XsResultValue XsSocket_connect(XsSocket* thisPtr, const XsString* host, uint16_t port)
1256 {
1257 return XsSocket_internalLookup(thisPtr, host, port, 0, connector, NULL, NULL);
1258 }
1259
1260 /*! \brief Return non-zero if the socket is usable for reading and writing data
1261
1262 \returns non-zero if the socket is usable for reading and writing data, zero otherwise
1263 \relates XsSocket
1264 */
1265 int XsSocket_isUsable(const XsSocket* thisPtr)
1266 {
1267 return socketIsUsable(thisPtr->d->m_sd);
1268 }
1269
1270 /*!
1271 * \brief Get the numeric IP address of remote host of this socket.
1272 * \param[in,out] address XsString to return the remote host IP address in
1273 */
1274 void XsSocket_getRemoteAddress(const XsSocket* thisPtr, XsString *address)
1275 {
1276 getRemoteHostAddress(&thisPtr->d->m_remoteAddr, address);
1277 }
1278
1279 /*!
1280 * \brief Return the system error code of the last socket operation
1281 * \return The error code
1282 */
1283 int XsSocket_getLastSystemError(const XsSocket* thisPtr)
1284 {
1285 return thisPtr->d->m_lastSystemError;
1286 }