Debian Codegraph @

protolib/src/common/protoSocket.cpp

raw
1
2 /**
3 * @file protoSocket.cpp
4 *
5 * @brief Network socket container class that provides consistent interface for use of operating system (or simulation environment) transport sockets.
6 */
7
8
9
10 #ifdef UNIX
11
12 #include <unistd.h>
13 #include <stdlib.h> // for atoi()
14 #ifdef HAVE_IPV6
15 #ifdef MACOSX
16 #define __APPLE_USE_RFC_3542 1 // needed to invoke IPV6_PKTINFO
17 #endif // MACOSX
18 #include <netinet/in.h>
19 #endif // HAVE_IPV6
20 #include <sys/ioctl.h>
21 #include <arpa/inet.h>
22 #include <net/if.h>
23 #include <ifaddrs.h>
24 #include <errno.h>
25 #include <fcntl.h>
26
27 #ifndef SIOCGIFHWADDR
28 #if defined(SOLARIS) || defined(IRIX)
29 #include <sys/sockio.h> // for SIOCGIFADDR ioctl
30 #include <netdb.h> // for res_init()
31 #include <sys/dlpi.h>
32 #include <stropts.h>
33 #else
34 #include <net/if.h>
35 #include <net/if_dl.h>
36 #include <net/if_types.h>
37 #include <ifaddrs.h>
38 #endif // if/else (SOLARIS || IRIX)
39 #endif // !SIOCGIFHWADDR
40
41 #endif // UNIX
42
43 #ifdef WIN32
44 #include <Winsock2.h>
45 #include <Ws2def.h>
46 #include <WS2tcpip.h> // for extra socket options
47 #include <Mswsock.h> // for even more
48 #include <Windows.h>
49 #include <Iphlpapi.h>
50 #include <Iptypes.h>
51 #include <BaseTsd.h>
52 typedef SSIZE_T ssize_t;
53 typedef UINT32 in_addr_t;
54 #endif // WIN32
55
56 // NOTE: This value should be confirmed. It's the apparently Linux-only approach we currently
57 // use to set the IPv6 flow info header fields. Other approaches are under investigation
58 // (We seem to be only able to affect the "traffic class" bits at this time)
59 #ifndef IPV6_FLOWINFO_SEND
60 #define IPV6_FLOWINFO_SEND 33 // from linux/in6.h
61 #endif // !IPV6_FLOWINFO_SEND
62
63 #include <stdio.h>
64 #include <string.h>
65
66 #include "protoSocket.h"
67 #include "protoNet.h"
68 #include "protoDebug.h"
69
70 // Hack for using with NRL IPSEC implementation
71 #ifdef HAVE_NETSEC
72 #include <net/security.h>
73 extern void* netsec_request;
74 extern int netsec_requestlen;
75 #endif // HAVE_NETSEC
76
77 // Use this macro (-DSOCKLEN_T=X) in your system's Makefile if the type socklen_t is
78 // not defined for your system (use "man getsockname" to see what type is required).
79
80 #ifdef SOCKLEN_T
81 #define socklen_t SOCKLEN_T
82 #else
83 #ifdef WIN32
84 //#define socklen_t int
85 #endif // WIN32
86 #endif // if/else SOCKLEN_T
87
88 #include "protoDispatcher.h"
89
90 #ifdef WIN32
91 const ProtoSocket::Handle ProtoSocket::INVALID_HANDLE = INVALID_SOCKET;
92 LPFN_WSARECVMSG ProtoSocket::WSARecvMsg = NULL;
93 #else
94 const ProtoSocket::Handle ProtoSocket::INVALID_HANDLE = -1;
95 #endif // if/else WIN32
96
97 ProtoSocket::IPv6SupportStatus ProtoSocket::ipv6_support_status = IPV6_UNKNOWN;
98
99 ProtoSocket::ProtoSocket(ProtoSocket::Protocol theProtocol)
100 : domain(IPv4), protocol(theProtocol), raw_protocol(RAW), state(CLOSED),
101 handle(INVALID_HANDLE), port(-1), tos(0), ecn_capable(false), ip_recvdstaddr(false),
102 #ifdef HAVE_IPV6
103 flow_label(0),
104 #endif // HAVE_IPV6
105 notifier(NULL), notify_output(false), notify_input(true), notify_exception(false),
106 #ifdef WIN32
107 input_event_handle(NULL), output_event_handle(NULL),
108 input_ready(false), output_ready(false), closing(false),
109 #endif // WIN32
110 listener(NULL), user_data(NULL)
111 {
112
113 }
114
115 ProtoSocket::~ProtoSocket()
116 {
117 Close();
118 if (NULL != listener)
119 {
120 delete listener;
121 listener = NULL;
122 }
123 }
124
125 bool ProtoSocket::SetBlocking(bool blocking)
126 {
127 #ifdef UNIX
128 if (blocking)
129 {
130 if(-1 == fcntl(handle, F_SETFL, fcntl(handle, F_GETFL, 0) & ~O_NONBLOCK))
131 {
132 PLOG(PL_ERROR, "ProtoSocket::SetBlocking() fcntl(F_SETFL(~O_NONBLOCK)) error: %s\n", GetErrorString());
133 return false;
134 }
135 }
136 else
137 {
138 if(-1 == fcntl(handle, F_SETFL, fcntl(handle, F_GETFL, 0) | O_NONBLOCK))
139 {
140 PLOG(PL_ERROR, "ProtoSocket::SetBlocking() fcntl(F_SETFL(O_NONBLOCK)) error: %s\n", GetErrorString());
141 return false;
142 }
143 }
144 #endif // UNIX
145 return true; //Note: taken care automatically under Win32 by WSAAsyncSelect(), etc
146 } // end ProtoSocket::SetBlocking(bool blocking)
147
148 bool ProtoSocket::StartInputNotification()
149 {
150 if (!notify_input)
151 {
152 notify_input = true;
153 notify_input = UpdateNotification();
154 }
155 return notify_input;
156 } // end ProtoSocket::StartInputNotification()
157
158 void ProtoSocket::StopInputNotification()
159 {
160 if (notify_input)
161 {
162 notify_input = false;
163 UpdateNotification();
164 }
165 } // end ProtoSocket::StopInputNotification()
166
167 bool ProtoSocket::StartOutputNotification()
168 {
169 if (!notify_output)
170 {
171 notify_output = true;
172 notify_output = UpdateNotification();
173 }
174 return notify_output;
175 } // end ProtoSocket::StartOutputNotification()
176
177 void ProtoSocket::StopOutputNotification()
178 {
179 if (notify_output)
180 {
181 notify_output = false;
182 UpdateNotification();
183 }
184 } // end ProtoSocket::StopOutputNotification()
185
186 bool ProtoSocket::StartExceptionNotification()
187 {
188 notify_exception = true;
189 notify_exception = UpdateNotification();
190 return notify_exception;
191 } // end ProtoSocket::StartExceptionNotification()
192
193 void ProtoSocket::StopExceptionNotification()
194 {
195 notify_exception = false;
196 UpdateNotification();
197 } // ProtoSocket::StopExceptionNotification()
198
199 bool ProtoSocket::SetNotifier(ProtoSocket::Notifier* theNotifier)
200 {
201 if (notifier != theNotifier)
202 {
203 if (IsOpen())
204 {
205 // 1) Detach old notifier, if any
206 if (NULL != notifier)
207 {
208 notifier->UpdateSocketNotification(*this, 0);
209 if (NULL == theNotifier)
210 {
211 // Reset socket to "blocking"
212 if(!SetBlocking(true))
213 PLOG(PL_ERROR, "ProtoSocket::SetNotifier() SetBlocking(true) error\n", GetErrorString());
214 }
215 }
216 else
217 {
218 // Set socket to "non-blocking"
219 if(!SetBlocking(false))
220 {
221 PLOG(PL_ERROR, "ProtoSocket::SetNotifier() SetBlocking(false) error\n", GetErrorString());
222 return false;
223 }
224 #ifdef WIN32
225 // Reset input/output ready to initial state?
226 input_ready = false;
227 output_ready = true;
228 #endif // WIN32
229 }
230 // 2) Set and update new notifier (if applicable)
231 notifier = theNotifier;
232 if (!UpdateNotification())
233 {
234 notifier = NULL;
235 return false;
236 }
237 }
238 else
239 {
240 notifier = theNotifier;
241 }
242 }
243 return true;
244 } // end ProtoSocket::SetNotifier()
245
246 ProtoAddress::Type ProtoSocket::GetAddressType()
247 {
248 switch (domain)
249 {
250 case LOCAL:
251 return ProtoAddress::INVALID;
252 case IPv4:
253 return ProtoAddress::IPv4;
254 #ifdef HAVE_IPV6
255 case IPv6:
256 return ProtoAddress::IPv6;
257 #endif // HAVE_IPV6
258 #ifdef SIMULATE
259 case SIM:
260 return ProtoAddress::SIM;
261 #endif // SIMULATE
262 default:
263 return ProtoAddress::INVALID;
264 }
265 } // end ProtoSocket::GetAddressType()
266
267 /**
268 * WIN32 needs the address type determine IPv6 _or_ IPv4 socket domain
269 * @note WIN32 can't do IPv4 on an IPV6 socket!
270 * Vista and above support dual stack sockets
271 */
272 bool ProtoSocket::Open(UINT16 thePort,
273 ProtoAddress::Type addrType,
274 bool bindOnOpen)
275 {
276 if (IsOpen()) Close();
277 #ifdef HAVE_IPV6
278 if(addrType == ProtoAddress::IPv6)
279 {
280 if (!HostIsIPv6Capable())
281 {
282 PLOG(PL_ERROR,"ProtoSocket::Open() system not IPv6 capable?\n");
283 return false;
284 }
285 domain = IPv6;
286 }
287 else
288 #endif // HAVE_IPV6
289 {
290 domain = IPv4;
291 }
292
293 int socketType = 0;
294 switch (protocol)
295 {
296 case UDP:
297 socketType = SOCK_DGRAM;
298 break;
299 case TCP:
300 socketType = SOCK_STREAM;
301 break;
302 case RAW:
303 socketType = SOCK_RAW;
304 break;
305 default:
306 PLOG(PL_ERROR,"ProtoSocket::Open() error: Unsupported protocol\n");
307 return false;
308 }
309
310 #ifdef WIN32
311 #ifdef HAVE_IPV6
312 int family = (IPv6 == domain) ? AF_INET6: AF_INET;
313 #else
314 int family = AF_INET;
315 #endif // if/else HAVE_IPV6
316 // Startup WinSock
317 if (!ProtoAddress::Win32Startup())
318 {
319 PLOG(PL_ERROR, "ProtoSocket::Open() WSAStartup() error: %s\n", GetErrorString());
320 return false;
321 }
322 // Since we're might want QoS, we need find a QoS-capable UDP service provider
323 WSAPROTOCOL_INFO* infoPtr = NULL;
324 WSAPROTOCOL_INFO* protocolInfo = NULL;
325 DWORD buflen = 0;
326 // Query to properly size protocolInfo buffer
327 WSAEnumProtocols(NULL, protocolInfo, &buflen);
328 if (buflen)
329 {
330 int protocolType;
331 switch (protocol)
332 {
333 case UDP:
334 protocolType = IPPROTO_UDP;
335 break;
336 case TCP:
337 protocolType = IPPROTO_TCP;
338 break;
339 case RAW:
340 switch (raw_protocol)
341 {
342 case RAW:
343 protocolType = IPPROTO_RAW;
344 break;
345 case UDP:
346 protocolType = IPPROTO_UDP;
347 break;
348 case TCP:
349 protocolType = IPPROTO_TCP;
350 break;
351 default:
352 protocolType = IPPROTO_RAW;
353 }
354 break;
355 }
356
357 // Enumerate, try to find multipoint _AND_ QOS-capable UDP, and create a socket
358 if ((protocolInfo = (WSAPROTOCOL_INFO*) new char[buflen]))
359 {
360 int count = WSAEnumProtocols(NULL, protocolInfo, &buflen);
361 if (SOCKET_ERROR != count)
362 {
363 for (int i = 0; i < count; i++)
364 {
365 switch (protocol)
366 {
367 // This code tries to find a multicast-capable UDP/TCP socket
368 // providers _without_ QoS support, if possible (but note will
369 // use one with QoS support if this is not possible. The reason
370 // for this is that, ironically, it appears that a socket _without_
371 // QoS support allows for more flexible control of IP TOS setting
372 // by the app?! (Note that this may be revisited if we someday
373 // again dabble with Win32 RSVP support (if it still exists) in future
374 // Protolib apps)
375 case UDP:
376 if ((IPPROTO_UDP == protocolInfo[i].iProtocol) &&
377 (0 != (XP1_SUPPORT_MULTIPOINT & protocolInfo[i].dwServiceFlags1)))
378 {
379
380 if ((NULL == infoPtr) ||
381 (0 == (XP1_QOS_SUPPORTED & protocolInfo[i].dwServiceFlags1)))
382 {
383 infoPtr = protocolInfo + i;
384 }
385 }
386 break;
387 case TCP:
388 if (IPPROTO_TCP == protocolInfo[i].iProtocol)
389 {
390 if ((NULL == infoPtr) ||
391 (0 == (XP1_QOS_SUPPORTED & protocolInfo[i].dwServiceFlags1)))
392 {
393 infoPtr = protocolInfo + i;
394 }
395 }
396 break;
397 default:
398 break;
399 }
400 } // end for (i=0..count)
401 }
402 else
403 {
404 PLOG(PL_ERROR, "ProtoSocket: WSAEnumProtocols() error2!\n");
405 delete[] protocolInfo;
406 ProtoAddress::Win32Cleanup();
407 return false;
408 }
409 }
410 else
411 {
412 PLOG(PL_ERROR, "ProtoSocket: Error allocating memory!\n");
413 ProtoAddress::Win32Cleanup();
414 return false;
415 }
416 }
417 else
418 {
419 PLOG(PL_WARN, "ProtoSocket::Open() WSAEnumProtocols() error1!\n");
420 }
421
422 // Use WSASocket() to open right kind of socket
423 // (Just a regular socket if infoPtr == NULL
424 DWORD flags = WSA_FLAG_OVERLAPPED;
425 #ifndef _WIN32_WCE
426 if (UDP == protocol) flags |= (WSA_FLAG_MULTIPOINT_C_LEAF | WSA_FLAG_MULTIPOINT_D_LEAF);
427 #endif // !_WIN32_WCE
428 handle = WSASocket(family, socketType, 0, infoPtr, 0, flags);
429 if (NULL != protocolInfo) delete[] protocolInfo;
430 if (INVALID_HANDLE == handle)
431 {
432 PLOG(PL_ERROR, "ProtoSocket::Open() WSASocket() error: %s\n", GetErrorString());
433 ProtoAddress::Win32Cleanup();
434 return false;
435 }
436 if (NULL == (input_event_handle = WSACreateEvent()))
437 {
438 PLOG(PL_ERROR, "ProtoSocket::Open() WSACreateEvent() error: %s\n", GetErrorString());
439 Close();
440 return false;
441 }
442 input_ready = false;
443 output_ready = true;
444 #else
445 #ifdef HAVE_IPV6
446 int family = (IPv6 == domain) ? AF_INET6: AF_INET;
447 #else
448 int family = AF_INET;
449 #endif // if/else HAVE_IPV6
450
451 /*if (AF_INET6 == family)
452 TRACE("opening an IPV6 socket\n");
453 else
454 TRACE("opening an IPV4 socket\n");*/
455 int socketProtocol = 0; // use default socket protocol type if not RAW
456 if (SOCK_RAW == socketType)
457 {
458 switch (raw_protocol)
459 {
460 case RAW:
461 socketProtocol = IPPROTO_RAW;
462 break;
463 case UDP:
464 socketProtocol = IPPROTO_UDP;
465 break;
466 case TCP:
467 socketProtocol = IPPROTO_TCP;
468 break;
469 default:
470 socketProtocol = IPPROTO_RAW;
471 }
472 }
473 if (INVALID_HANDLE == (handle = socket(family, socketType, socketProtocol)))
474 {
475 PLOG(PL_ERROR, "ProtoSocket::Open() socket() error: %s\n", GetErrorString());
476 return false;
477 }
478 // (TBD) set IP_HDRINCL option for raw socket
479 #endif // if/else WIN32
480 state = IDLE;
481 #ifdef NETSEC
482 if (net_security_setrequest(handle, 0, netsec_request, netsec_requestlen))
483 {
484 PLOG(PL_ERROR, "ProtoSocket::Open() net_security_setrequest() error: %s\n",
485 GetErrorString());
486 Close();
487 return false;
488 }
489 #endif // NETSEC
490
491 #ifdef UNIX
492 // Don't pass descriptor to child processes
493 if(-1 == fcntl(handle, F_SETFD, FD_CLOEXEC))
494 PLOG(PL_ERROR, "ProtoSocket::Open() fcntl(FD_CLOEXEC) warning: %s\n", GetErrorString());
495 // Make the socket non-blocking
496 if (notifier)
497 {
498 if(-1 == fcntl(handle, F_SETFL, fcntl(handle, F_GETFL, 0) | O_NONBLOCK))
499 {
500 PLOG(PL_ERROR, "ProtoSocket::Open() fcntl(F_SETFL(O_NONBLOCK)) error: %s\n",
501 GetErrorString());
502 Close();
503 return false;
504 }
505 }
506 #endif // UNIX
507 if (bindOnOpen)
508 {
509 if (!Bind(thePort))
510 {
511 Close();
512 return false;
513 }
514 }
515 else
516 {
517 port = -1;
518 // TBD - the UpdateNotification() call here may be unnecessary???
519 // (newly opened, unbound socket needs no notification?)
520 if (!UpdateNotification())
521 {
522 PLOG(PL_ERROR, "ProtoSocket::Open() error installing async notification\n");
523 Close();
524 return false;
525 }
526 }
527 // Do the following in case TOS or "ecn_capable" was set _before_
528 // ProtoSocket::Open() was called. Note that the "IPv6" flow label
529 // "traffic class" is also updated as needed for IPv6 sockets
530 if ((0 != tos) || (ecn_capable)) SetTOS(tos);
531 #ifdef WIN32
532 closing = false;
533 #endif //WIN32
534 ip_recvdstaddr = false; // make sure this is reset
535 return true;
536 } // end ProtoSocket::Open()
537
538 bool ProtoSocket::SetRawProtocol(Protocol theProtocol)
539 {
540 bool wasOpen = false;
541 UINT16 portSave = 0;
542 if (IsOpen())
543 {
544 portSave = GetPort();
545 Close();
546 wasOpen = true;
547 }
548 protocol = RAW;
549 raw_protocol = theProtocol;
550 if (wasOpen)
551 return Open(portSave);
552 else
553 return true;
554 } // end ProtoSocket::SetRawProtocol()
555
556 bool ProtoSocket::UpdateNotification()
557 {
558 if (NULL != notifier)
559 {
560 if (IsOpen() && !SetBlocking(false))
561 {
562 PLOG(PL_ERROR, "ProtoSocket::UpdateNotification() SetBlocking() error\n");
563 return false;
564 }
565 int notifyFlags = NOTIFY_NONE;
566 if (NULL != listener)
567 {
568 switch (protocol)
569 {
570 case UDP:
571 case RAW:
572 switch (state)
573 {
574 case CLOSED:
575 break;
576 default:
577 if (notify_input && IsBound())
578 notifyFlags = NOTIFY_INPUT;
579 else
580 notifyFlags = NOTIFY_NONE;
581 if (notify_output)
582 notifyFlags |= NOTIFY_OUTPUT;
583 if (IsOpen() && notify_exception)
584 notifyFlags |= NOTIFY_EXCEPTION;
585 break;
586 }
587 break;
588
589 case TCP:
590 switch(state)
591 {
592 case CLOSED:
593 case IDLE:
594 break;
595 case CONNECTING:
596 notifyFlags = NOTIFY_OUTPUT;
597 break;
598 case LISTENING:
599 notifyFlags = NOTIFY_INPUT;
600 break;
601 case CONNECTED:
602 if (notify_input)
603 notifyFlags = NOTIFY_INPUT;
604 if (notify_output)
605 notifyFlags |= NOTIFY_OUTPUT;
606 break;
607 } // end switch(state)
608 break;
609 case ZMQ:
610 switch (state)
611 {
612 case CONNECTED:
613 if (notify_input)
614 notifyFlags = NOTIFY_INPUT;
615 break;
616 default:
617 break;
618 }
619 break;
620 default:
621 PLOG(PL_ERROR,"ProtoSocket::UpdateNotification Error: Unsupported protocol: %d.\n", protocol);
622 break;
623 } // end switch(protocol)
624 } // end if(listener)
625 return notifier->UpdateSocketNotification(*this, notifyFlags);
626 }
627 else
628 {
629 return true;
630 }
631 } // end ProtoSocket::UpdateNotification()
632
633 void ProtoSocket::OnNotify(NotifyFlag theFlag)
634 {
635 ProtoSocket::Event event = INVALID_EVENT;
636 if (NOTIFY_INPUT == theFlag)
637 {
638 switch (state)
639 {
640 case CLOSED:
641 break;
642 case IDLE:
643 event = RECV;
644 break;
645 case CONNECTING:
646 break;
647 case LISTENING:
648 // (TBD) check for error
649 event = ACCEPT;
650 break;
651 case CONNECTED:
652 event = RECV;
653 break;
654 }
655 }
656 else if (NOTIFY_OUTPUT == theFlag)
657 {
658 switch (state)
659 {
660 case CLOSED:
661 break;
662 case IDLE:
663 event = SEND;
664 break;
665 case CONNECTING:
666 {
667 #ifdef WIN32
668 event = CONNECT;
669 state = CONNECTED;
670 UpdateNotification();
671 #else
672 int err;
673 socklen_t errsize = sizeof(err);
674 if (getsockopt(handle, SOL_SOCKET, SO_ERROR, (char*)&err, &errsize))
675 {
676 PLOG(PL_ERROR, "ProtoSocket::OnNotify() getsockopt() error: %s\n", GetErrorString());
677
678 }
679 else if (0 != err)
680 {
681 PLOG(PL_DEBUG, "ProtoSocket::OnNotify() getsockopt() error: %s\n", GetErrorString());
682 Disconnect();
683 event = ERROR_; // TBD - should this be DISCONNECT instead?
684 }
685 else
686 {
687 event = CONNECT;
688 state = CONNECTED;
689 UpdateNotification();
690 }
691 #endif // if/else WIN32
692 break;
693 }
694 case LISTENING:
695 break;
696 case CONNECTED:
697 event = SEND;
698 break;
699 }
700 }
701 else if (NOTIFY_EXCEPTION == theFlag)
702 {
703 event = EXCEPTION;
704 }
705 else if (NOTIFY_ERROR == theFlag)
706 {
707 //TRACE("ProtoSocket NOTIFY_ERROR notification\n");
708 switch(state)
709 {
710 case CONNECTING:
711 case CONNECTED:
712 Disconnect();
713 default:
714 event = ProtoSocket::ERROR_;
715 break;
716 }
717 }
718 else // NOTIFY_NONE (connection was purposefully ended)
719 {
720 switch(state)
721 {
722 case CONNECTING:
723 //PLOG(PL_ERROR, "ProtoSocket::OnNotify() Connect() error: %s\n", GetErrorString());
724 case CONNECTED:
725 Disconnect();
726 event = DISCONNECT;
727 break;
728 default:
729 break;
730 }
731 }
732 ASSERT(INVALID_EVENT != event);
733 if (listener) listener->on_event(*this, event);
734 } // end ProtoSocket::OnNotify()
735
736 bool ProtoSocket::Bind(UINT16 thePort, const ProtoAddress* localAddress)
737 {
738 if (IsBound()) Close();
739 if (IsOpen() && (NULL != localAddress) && (GetAddressType() != localAddress->GetType()))
740 {
741 Close(); // requires a different address family, so close for reopen
742 }
743 if (!IsOpen())
744 {
745 ProtoAddress::Type addrType = localAddress ? localAddress->GetType() : ProtoAddress::IPv4;
746 if(!Open(thePort, addrType, false))
747 {
748 PLOG(PL_ERROR,"ProtoSocket::Bind() error opening socket on port %d\n",thePort);
749 return false;
750 }
751 }
752 #ifdef HAVE_IPV6
753 struct sockaddr_storage socketAddr;
754 socklen_t addrSize;
755 if (IPv6 == domain)
756 {
757 addrSize = sizeof(struct sockaddr_in6);
758 memset((char*)&socketAddr, 0, sizeof(struct sockaddr_in6));
759 ((struct sockaddr_in6*)&socketAddr)->sin6_family = AF_INET6;
760 ((struct sockaddr_in6*)&socketAddr)->sin6_port = htons(thePort);
761 ((struct sockaddr_in6*)&socketAddr)->sin6_flowinfo = 0;
762 if (NULL != localAddress)
763 {
764 ((struct sockaddr_in6*)&socketAddr)->sin6_addr =
765 ((const struct sockaddr_in6*)(&localAddress->GetSockAddrStorage()))->sin6_addr;
766 }
767 else
768 {
769 ((struct sockaddr_in6*)&socketAddr)->sin6_addr = in6addr_any;
770 }
771 }
772 else
773 {
774 addrSize = sizeof(struct sockaddr_in);
775 memset((char*)&socketAddr, 0, sizeof(struct sockaddr_in));
776 ((struct sockaddr_in*)&socketAddr)->sin_family = AF_INET;
777 ((struct sockaddr_in*)&socketAddr)->sin_port = htons(thePort);
778 if (NULL != localAddress)
779 {
780 ((struct sockaddr_in*)&socketAddr)->sin_addr =
781 ((const struct sockaddr_in*)(&localAddress->GetSockAddrStorage()))->sin_addr;
782 }
783 else
784 {
785 struct in_addr inAddr;
786 inAddr.s_addr = htonl(INADDR_ANY);
787 ((struct sockaddr_in*)&socketAddr)->sin_addr = inAddr;
788 }
789 }
790 #else
791 struct sockaddr socketAddr;
792 socklen_t addrSize = sizeof(struct sockaddr_in);
793 memset((char*)&socketAddr, 0, sizeof(struct sockaddr_in));
794 ((struct sockaddr_in*)&socketAddr)->sin_family = AF_INET;
795 ((struct sockaddr_in*)&socketAddr)->sin_port = htons(thePort);
796 if (NULL != localAddress)
797 {
798 ((struct sockaddr_in*)&socketAddr)->sin_addr =
799 ((struct sockaddr_in*)(&localAddress->GetSockAddr()))->sin_addr;
800 }
801 else
802 {
803 struct in_addr inAddr;
804 inAddr.s_addr = htonl(INADDR_ANY);
805 ((struct sockaddr_in*)&socketAddr)->sin_addr = inAddr;
806 }
807 #endif // if/else HAVE_IPV6
808
809 #ifdef UNIX
810 #ifdef HAVE_IPV6
811 if ((IPv6 == domain) && (0 != flow_label))
812 ((struct sockaddr_in6*)&socketAddr)->sin6_flowinfo = flow_label;
813 #endif // HAVE_IPV6
814 #endif // UNIX
815
816 #ifdef HAVE_IPV6
817 #ifdef WIN32
818 OSVERSIONINFO osvi;
819 BOOL osVistaOrLater;
820 ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
821 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
822 GetVersionEx(&osvi);
823 osVistaOrLater = osvi.dwMajorVersion > 5;
824 if (osVistaOrLater)
825 {
826 // On Windows Vista & above dual stack sockets are supported so
827 // disable ipv6_v6only so we can listen to both ipv4 & ipv6 connections
828 // simultaneously
829 int ipv6only = 0;
830 if (setsockopt(handle, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&ipv6only, sizeof(ipv6only)) < 0)
831 {
832 PLOG(PL_ERROR, "ProtoSocket::Bind() setsockopt(!IPV6_V6ONLY) error: %s\n", GetErrorString());
833 return false;
834 }
835 }
836 #endif // WIN32
837 #endif // HAVE_IPV6
838 // Bind the socket to the given port
839 if (bind(handle, (struct sockaddr*)&socketAddr, addrSize) < 0)
840 {
841 PLOG(PL_ERROR, "ProtoSocket::Bind(%hu) bind() error: %s\n", thePort, GetErrorString());
842 return false;
843 }
844
845 // Get socket name so we know our port number
846 socklen_t sockLen = addrSize;
847 if (getsockname(handle, (struct sockaddr*)&socketAddr, &sockLen) < 0)
848 {
849 PLOG(PL_ERROR, "ProtoSocket::Bind() getsockname() error: %s\n", GetErrorString());
850 return false;
851 }
852 source_addr.SetSockAddr((struct sockaddr&)socketAddr);
853 switch(((struct sockaddr*)&socketAddr)->sa_family)
854 {
855 case AF_INET:
856 source_addr.SetSockAddr((struct sockaddr&)socketAddr);
857 port = ntohs(((struct sockaddr_in*)&socketAddr)->sin_port);
858 break;
859 #ifdef HAVE_IPV6
860 case AF_INET6:
861 source_addr.SetSockAddr((struct sockaddr&)socketAddr);
862 port = ntohs(((struct sockaddr_in6*)&socketAddr)->sin6_port);
863 break;
864 #endif // HAVE_IPV6
865 default:
866 PLOG(PL_ERROR, "ProtoSocket::Bind() error: getsockname() returned unknown address type\n");
867 return false;
868 }
869 #ifdef WIN32
870 // reset input/output readiness since it is a newly bound socket
871 input_ready = false;
872 output_ready = true;
873 #endif // WIN32
874 return UpdateNotification();
875 } // end ProtoSocket::Bind()
876
877 bool ProtoSocket::Shutdown()
878 {
879 #ifdef WIN32
880 if (TCP == protocol)
881 #else
882 if (IsConnected() && TCP == protocol)
883 #endif // WIN32
884 {
885 bool notifyOutput = notify_output;
886 if (notifyOutput)
887 {
888 notify_output = false;
889 UpdateNotification();
890 }
891 #ifdef WIN32
892 if (SOCKET_ERROR == shutdown(handle, SD_SEND))
893 #else
894 if (0 != shutdown(handle, SHUT_WR))
895 #endif // if/else WIN32/UNIX
896 {
897 // TBD - should we not bother to re-enable output notification here?
898 // (i.e. since the user intended to shutdown the socket?!)
899 if (notifyOutput)
900 {
901 notify_output = true;
902 UpdateNotification();
903 }
904 PLOG(PL_ERROR, "ProtoSocket::Shutdown() error: %s\n", GetErrorString());
905 return false;
906 }
907 else
908 {
909 return true;
910 }
911 }
912 else
913 {
914 PLOG(PL_ERROR, "ProtoSocket::Shutdown() error: socket not connected\n");
915 return false;
916 }
917 } // end ProtoSocket::Shutdown()
918
919 void ProtoSocket::Close()
920 {
921 if (IsOpen())
922 {
923 if (IsConnected()) Disconnect();
924 state = CLOSED;
925 UpdateNotification();
926 #ifdef WIN32
927 if (NULL != input_event_handle)
928 {
929 WSACloseEvent(input_event_handle);
930 input_event_handle = NULL;
931 }
932 #endif // if WIN32
933 if (INVALID_HANDLE != handle)
934 {
935 #ifdef WIN32
936 if (SOCKET_ERROR == closesocket(handle))
937 PLOG(PL_WARN, "ProtoSocket::Close() warning: closesocket() error: %s\n", GetErrorString());
938 ProtoAddress::Win32Cleanup();
939 input_ready = output_ready = false;
940 #else
941 close(handle);
942 #endif // if/else WIN32/UNIX
943 handle = INVALID_HANDLE;
944 }
945 port = -1;
946 }
947 } // end Close()
948
949 bool ProtoSocket::Connect(const ProtoAddress& theAddress)
950 {
951 TRACE("enter ProtoSocket::Connect() ...\n");
952 if (IsConnected()) Disconnect();
953 if (!IsOpen() && !Open(0, theAddress.GetType()))
954 {
955 PLOG(PL_ERROR, "ProtoSocket::Connect() error opening socket!\n");
956 return false;
957 }
958 #ifdef HAVE_IPV6
959 socklen_t addrSize = (IPv6 == domain) ? sizeof(sockaddr_storage) :
960 sizeof(struct sockaddr_in);
961 #else
962 socklen_t addrSize = sizeof(struct sockaddr_in);
963 #endif // if/else HAVE_IPV6
964 #ifdef WIN32
965 //int result = WSAConnect(handle, &theAddress.GetSockAddr(), addrSize,
966 // NULL, NULL, NULL, NULL);
967 int result = connect(handle, &theAddress.GetSockAddr(), addrSize);
968 if (SOCKET_ERROR == result)
969 {
970 if (WSAEWOULDBLOCK != WSAGetLastError())
971 {
972 PLOG(PL_ERROR, "ProtoSocket::Connect() WSAConnect() error: (%s)\n", GetErrorString());
973 return false;
974 }
975 output_ready = false; // not yet connected
976 state = CONNECTING;
977 }
978 #else // UNIX
979 #ifdef HAVE_IPV6
980 if (flow_label && (ProtoAddress::IPv6 == theAddress.GetType()))
981 ((struct sockaddr_in6*)(&theAddress.GetSockAddrStorage()))->sin6_flowinfo = flow_label;
982 #endif // HAVE_IPV6
983 int result = connect(handle, &theAddress.GetSockAddr(), addrSize);
984 if (0 != result)
985 {
986 if (EINPROGRESS != errno)
987 {
988 PLOG(PL_ERROR, "ProtoSocket::Connect() connect() error: %s\n", GetErrorString());
989 return false;
990 }
991 state = CONNECTING;
992 }
993 #endif // if/else WIN32/UNIX
994 else
995 {
996 state = CONNECTED;
997 }
998 if (!UpdateNotification())
999 {
1000 PLOG(PL_ERROR, "ProtoSocket::Connect() error updating notification\n");
1001 state = IDLE;
1002 UpdateNotification();
1003 return false;
1004 }
1005 // Use getsockname() to get local "port" and "source_addr"
1006 #ifdef HAVE_IPV6
1007 struct sockaddr_in6 socketAddr;
1008 #else
1009 struct sockaddr socketAddr;
1010 #endif // if/else HAVE_IPV6
1011 socklen_t addrLen = sizeof(socketAddr);
1012 if (getsockname(handle, (struct sockaddr*)&socketAddr, &addrLen) < 0)
1013 {
1014 // getsockname() failed, so issue a warning
1015 PLOG(PL_ERROR, "ProtoSocket::Connect() getsockname() error: %s\n", GetErrorString());
1016 source_addr.Invalidate();
1017 }
1018 else
1019 {
1020 switch(((struct sockaddr*)&socketAddr)->sa_family)
1021 {
1022 case AF_INET:
1023 source_addr.SetSockAddr((struct sockaddr&)socketAddr);
1024 port = ntohs(((struct sockaddr_in*)&socketAddr)->sin_port);
1025 break;
1026 #ifdef HAVE_IPV6
1027 case AF_INET6:
1028 source_addr.SetSockAddr((struct sockaddr&)socketAddr);
1029 port = ntohs(((struct sockaddr_in6*)&socketAddr)->sin6_port);
1030 break;
1031 #endif // HAVE_IPV6
1032 #ifndef WIN32
1033 case AF_UNIX:
1034 source_addr.Invalidate();
1035 port = -1;
1036 break;
1037 #endif // !WIN32
1038 default:
1039 PLOG(PL_ERROR, "ProtoSocket::Connect() error: getsockname() returned unknown address type");
1040 break;
1041 } // end switch()
1042 }
1043 destination = theAddress; // cache the destination address
1044 return true;
1045 } // end bool ProtoSocket::Connect()
1046
1047 void ProtoSocket::Disconnect()
1048 {
1049 if (IsConnected() || IsConnecting())
1050 {
1051 state = IDLE;
1052 UpdateNotification();
1053 //source_addr.Invalidate();
1054 //destination.Invalidate();
1055 struct sockaddr nullAddr;
1056 memset(&nullAddr, 0 , sizeof(struct sockaddr));
1057 #ifdef UNIX
1058 if (TCP != protocol)
1059 {
1060 nullAddr.sa_family = AF_UNSPEC;
1061 if (connect(handle, &nullAddr, sizeof(struct sockaddr)))
1062 {
1063 if (EAFNOSUPPORT != errno)
1064 PLOG(PL_WARN, "ProtoSocket::Disconnect() connect() error: %s)\n", GetErrorString());
1065 // (TBD) should we Close() and re-Open() the socket here?
1066 }
1067 }
1068 else
1069 {
1070 // TCP doesn't like the connect(nullAddr) trick, best to just close
1071 // (TBD) should we Close() and re-Open() the socket here?
1072 // (but can't easily recall all socket options, so best not I guess)
1073 //UINT16 savePort = GetPort();
1074
1075 // MACOSX & LINUX trigger server resets differently...
1076 #ifdef MACOSX
1077 Close();
1078 #else
1079 nullAddr.sa_family = AF_UNSPEC;
1080 if (connect(handle,&nullAddr,sizeof(struct sockaddr)))
1081 {
1082 if (EAFNOSUPPORT != errno)
1083 PLOG(PL_WARN, "ProtoSocket::Disconnect() connect() error (%s)\n", GetErrorString());
1084 Close();
1085 }
1086 #endif
1087 //Open(savePort);
1088 }
1089 #else
1090 if (SOCKET_ERROR == WSAConnect(handle, &nullAddr, sizeof(struct sockaddr),
1091 NULL, NULL, NULL, NULL))
1092 {
1093 //PLOG(PL_WARN, "ProtoSocket::Disconnect() WSAConnect() error: %s\n", GetErrorString());
1094 Close(); // if windows doesn't like the null-connect disconnect trick either
1095 }
1096 #endif // WIN32
1097 }
1098 } // end ProtoSocket::Disconnect()
1099
1100 bool ProtoSocket::Listen(UINT16 thePort)
1101 {
1102 if (IsBound())
1103 {
1104 if ((0 != thePort) && (thePort != port))
1105 {
1106 PLOG(PL_ERROR, "ProtoSocket::Listen() error: socket bound to different port.\n");
1107 return false;
1108 }
1109 }
1110 else
1111 {
1112 if (!Bind(thePort))
1113 {
1114 PLOG(PL_ERROR, "ProtoSocket::Listen() error binding socket.\n");
1115 return false;
1116 }
1117 }
1118 if (TCP == protocol)
1119 state = LISTENING;
1120 else
1121 return true; // UDP sockets don't "listen"
1122 if (!UpdateNotification())
1123 {
1124 state = IDLE;
1125 PLOG(PL_ERROR, "ProtoSocket::Listen() error updating notification\n");
1126 return false;
1127 }
1128 #ifdef WIN32
1129 if (SOCKET_ERROR == listen(handle, 5))
1130 #else
1131 if (listen(handle, 5) < 0)
1132 #endif // if/else WIN32/UNIX
1133 {
1134 PLOG(PL_ERROR, "ProtoSocket: listen() error: %s\n", GetErrorString());
1135 return false;
1136 }
1137 return true;
1138 } // end ProtoSocket::Listen()
1139
1140 bool ProtoSocket::Accept(ProtoSocket* newSocket)
1141 {
1142 if (TCP != protocol)
1143 {
1144 PLOG(PL_ERROR, "ProtoSocket::Accept() error non-TCP socket!\n");
1145 return false;
1146 }
1147 ProtoSocket& theSocket = (NULL != newSocket) ? *newSocket : *this;
1148 // Clone server socket
1149 if (this != &theSocket)
1150 {
1151 // TBD - should override ProtoSocket copy operator to delete old listener???
1152 if (NULL != theSocket.listener) delete theSocket.listener;
1153 theSocket = *this;
1154 theSocket.listener = NULL; // this->listener is duplicated later (or should we save our old one?)
1155 }
1156 #ifdef HAVE_IPV6
1157 struct sockaddr_in6 socketAddr;
1158 #else
1159 struct sockaddr socketAddr;
1160 #endif // if/else HAVE_IPV6
1161 socklen_t addrLen = sizeof(socketAddr);
1162 #ifdef WIN32
1163 if (this != &theSocket)
1164 {
1165 if (!ProtoAddress::Win32Startup())
1166 {
1167 PLOG(PL_ERROR, "ProtoSocket::Accept() WSAStartup() error: %s\n", GetErrorString());
1168 return false;
1169 }
1170 }
1171 Handle theHandle = WSAAccept(handle, (struct sockaddr*)&socketAddr, &addrLen, NULL, NULL);
1172 #else
1173 Handle theHandle = accept(handle, (struct sockaddr*)&socketAddr, &addrLen);
1174 #endif // if/else WIN32/UNIX
1175 if (INVALID_HANDLE == theHandle)
1176 {
1177 #ifdef WIN32
1178 switch (WSAGetLastError())
1179 {
1180 case WSAEWOULDBLOCK:
1181 if (input_ready)
1182 {
1183 input_ready = false;
1184 UpdateNotification();
1185 }
1186 break;
1187 default:
1188 PLOG(PL_ERROR, "ProtoSocket::Accept() accept() error: %s\n", GetErrorString());
1189 break;
1190 }
1191 #endif
1192 PLOG(PL_ERROR, "ProtoSocket::Accept() accept() error: %s\n", GetErrorString());
1193 if (this != &theSocket)
1194 {
1195 #ifdef WIN32
1196 ProtoAddress::Win32Cleanup();
1197 #endif // WIN32
1198 theSocket.handle = INVALID_HANDLE;
1199 theSocket.state = CLOSED;
1200 }
1201 return false;
1202 }
1203 // Don't think we need make "input_ready" true on accept?
1204 if (LOCAL != domain)
1205 theSocket.destination.SetSockAddr((struct sockaddr&)socketAddr);
1206 // Get the socket name so we know our port number
1207 addrLen = sizeof(socketAddr);
1208 if (getsockname(theHandle, (struct sockaddr*)&socketAddr, &addrLen) < 0)
1209 {
1210 PLOG(PL_ERROR, "ProtoSocket::Accept() getsockname() error: %s\n", GetErrorString());
1211 if (this != &theSocket)
1212 {
1213 #ifdef WIN32
1214 closesocket(theHandle);
1215 ProtoAddress::Win32Cleanup();
1216 #endif // WIN32
1217 theSocket.handle = INVALID_HANDLE;
1218 theSocket.state = CLOSED;
1219 }
1220 return false;
1221 }
1222 switch(((struct sockaddr*)&socketAddr)->sa_family)
1223 {
1224 case AF_INET:
1225 theSocket.source_addr.SetSockAddr((struct sockaddr&)socketAddr);
1226 theSocket.port = ntohs(((struct sockaddr_in*)&socketAddr)->sin_port);
1227 break;
1228 #ifdef HAVE_IPV6
1229 case AF_INET6:
1230 theSocket.source_addr.SetSockAddr((struct sockaddr&)socketAddr);
1231 theSocket.port = ntohs(((struct sockaddr_in6*)&socketAddr)->sin6_port);
1232 break;
1233 #endif // HAVE_IPV6
1234 #ifndef WIN32
1235 case AF_UNIX:
1236 theSocket.source_addr.Invalidate();
1237 theSocket.port = -1;
1238 break;
1239 #endif // !WIN32
1240 default:
1241 PLOG(PL_ERROR, "ProtoSocket::Accept() error: getsockname() returned unknown address type");
1242 if (this != &theSocket)
1243 {
1244 #ifdef WIN32
1245 closesocket(theHandle);
1246 ProtoAddress::Win32Cleanup();
1247 #endif // WIN32
1248 theSocket.handle = INVALID_HANDLE;
1249 theSocket.state = CLOSED;
1250 }
1251 return false;
1252 } // end switch()
1253 if (this == &theSocket)
1254 {
1255 state = CLOSED;
1256 UpdateNotification();
1257 #ifdef WIN32
1258 closesocket(theSocket.handle);
1259 input_ready = false; // will be notified when there's something to read
1260 output_ready = true; // assume new socket ready for writing
1261 #else
1262 close(theSocket.handle);
1263 #endif // if/else WIN32/UNIX
1264 }
1265 else
1266 {
1267 #ifdef WIN32
1268 // Need a new event handle for this new, unopened socket
1269 if (NULL == (theSocket.input_event_handle = WSACreateEvent()))
1270 {
1271 PLOG(PL_ERROR, "ProtoSocket::Accept() WSACreateEvent error: %s\n", GetErrorString());
1272 theSocket.Close();
1273 return false;
1274 }
1275 theSocket.input_ready = false; // will be notified when there's something to read
1276 theSocket.output_ready = true; // assume new socket ready for writing
1277 #endif // WIN32
1278 // TBD - keep old listener / notifier and just do an UpdateNotification() here
1279 if (NULL != listener)
1280 {
1281 if (NULL == (theSocket.listener = listener->duplicate()))
1282 {
1283 PLOG(PL_ERROR, "ProtoSocket::Accept() listener duplication error: %s\n", ::GetErrorString());
1284 theSocket.Close();
1285 return false;
1286 }
1287 }
1288 if (NULL != notifier)
1289 {
1290 theSocket.handle = theHandle;
1291 if(!theSocket.SetBlocking(false))
1292 {
1293 PLOG(PL_ERROR, "ProtoSocket::Accept() SetBlocking(false) error\n");
1294 theSocket.Close();
1295 return false;
1296 }
1297 }
1298 } // end if/else (this == &theSocket)
1299 theSocket.handle = theHandle; // the socket gets the new handle/descriptor from accept()
1300 theSocket.state = CONNECTED;
1301 theSocket.UpdateNotification();
1302 return true;
1303 } // end ProtoSocket::Accept()
1304
1305 bool ProtoSocket::Send(const char* buffer,
1306 unsigned int& numBytes)
1307 {
1308 if (IsConnected())
1309 {
1310 #ifdef WIN32
1311 WSABUF sendBuf;
1312 sendBuf.buf = (char*)buffer;
1313 sendBuf.len = numBytes;
1314 DWORD bytesSent;
1315 if (SOCKET_ERROR == WSASend(handle, &sendBuf, 1, &bytesSent, 0, NULL, NULL))
1316 {
1317 numBytes = 0;
1318 switch (WSAGetLastError())
1319 {
1320 case WSAEINTR:
1321 return true;
1322 case WSAEWOULDBLOCK:
1323 if (output_ready)
1324 {
1325 output_ready = false;
1326 UpdateNotification(); // because no longer "output ready"
1327 }
1328 return true;
1329 case WSAENETRESET:
1330 case WSAECONNABORTED:
1331 case WSAECONNRESET:
1332 case WSAESHUTDOWN:
1333 case WSAENOTCONN:
1334 if (output_ready)
1335 {
1336 output_ready = false;
1337 UpdateNotification(); // because no longer "output ready"
1338 }
1339 OnNotify(NOTIFY_ERROR);
1340 break;
1341 default:
1342 PLOG(PL_ERROR, "ProtoSocket::Send() WSASend() error: %s\n", GetErrorString());
1343 break;
1344 }
1345 return false;
1346 }
1347 else
1348 {
1349 if (bytesSent < numBytes)
1350 {
1351 if (output_ready)
1352 {
1353 output_ready = false;
1354 UpdateNotification(); // because no longer "output ready"
1355 }
1356 }
1357 else if (!output_ready)
1358 {
1359 output_ready = true;
1360 UpdateNotification();
1361 }
1362 numBytes = (unsigned int)bytesSent;
1363 return true;
1364 }
1365 #else
1366 ssize_t result = send(handle, buffer, (size_t)numBytes, 0);
1367 if (result < 0)
1368 {
1369 numBytes = 0;
1370 switch (errno)
1371 {
1372 case EINTR:
1373 case EAGAIN:
1374 return true;
1375 case ENETRESET:
1376 case ECONNABORTED:
1377 case ECONNRESET:
1378 case ESHUTDOWN:
1379 case ENOTCONN:
1380 case EPIPE:
1381 OnNotify(NOTIFY_ERROR);
1382 break;
1383 case ENOBUFS:
1384 PLOG(PL_DEBUG, "ProtoSocket::Send() send() error: %s\n", GetErrorString());
1385 return false;
1386 default:
1387 PLOG(PL_ERROR, "ProtoSocket::Send() send() error: %s\n", GetErrorString());
1388 break;
1389 }
1390 return false;
1391 }
1392 else
1393 {
1394 numBytes = (unsigned int)result;
1395 return true;
1396 }
1397 #endif // if/else WIN32/UNIX
1398 }
1399 else
1400 {
1401 PLOG(PL_ERROR, "ProtoSocket::Send() error unconnected socket\n");
1402 numBytes = 0;
1403 return false;
1404 }
1405 } // end ProtoSocket::Send()
1406
1407 bool ProtoSocket::Recv(char* buffer,
1408 unsigned int& numBytes)
1409 {
1410 #ifdef WIN32
1411 WSABUF recvBuf;
1412 recvBuf.buf = buffer;
1413 recvBuf.len = numBytes;
1414 DWORD bytesReceived;
1415 DWORD flags = 0;
1416 if (SOCKET_ERROR == WSARecv(handle, &recvBuf, 1, &bytesReceived, &flags, NULL, NULL))
1417 {
1418 numBytes = 0;
1419 switch (WSAGetLastError())
1420 {
1421 case WSAEINTR:
1422 case WSAEWOULDBLOCK:
1423 if (input_ready)
1424 {
1425 input_ready = false;
1426 UpdateNotification(); // because no longer "input ready"
1427 }
1428 return true; // not really an error, just no bytes read
1429 break;
1430 case WSAENETRESET:
1431 case WSAECONNABORTED:
1432 case WSAECONNRESET:
1433 case WSAESHUTDOWN:
1434 case WSAENOTCONN:
1435 PLOG(PL_ERROR, "ProtoSocket::Recv() recv() error: %s\n", GetErrorString());
1436 OnNotify(NOTIFY_ERROR);
1437 break;
1438 default:
1439 PLOG(PL_ERROR, "ProtoSocket::Recv() recv() error: %s\n", GetErrorString());
1440 break;
1441 }
1442 return false;
1443 }
1444 else
1445 {
1446 if ((bytesReceived < numBytes) && (TCP == protocol))
1447 {
1448 input_ready = false;
1449 UpdateNotification(); // because no longer "input ready"
1450 }
1451 else if (!input_ready)
1452 {
1453 input_ready = true;
1454 UpdateNotification();
1455 }
1456 numBytes = bytesReceived;
1457 // TBD - Should we do a NOTIFY_NONE here like we do for UNIX?
1458 return true;
1459 }
1460 #else
1461 ssize_t result = recv(handle, buffer, numBytes, 0);
1462 if (result < 0)
1463 {
1464 numBytes = 0;
1465 switch (errno)
1466 {
1467 case EINTR:
1468 case EAGAIN:
1469 PLOG(PL_WARN, "ProtoSocket::Recv() recv() error: %s\n", GetErrorString());
1470 return true;
1471 break;
1472 case ENETRESET:
1473 case ECONNABORTED:
1474 case ECONNRESET:
1475 case ESHUTDOWN:
1476 case ENOTCONN:
1477 OnNotify(NOTIFY_ERROR);
1478 break;
1479 default:
1480 PLOG(PL_ERROR, "ProtoSocket::Recv() recv() error: %s\n", GetErrorString());
1481 break;
1482 }
1483 return false;
1484 }
1485 else
1486 {
1487 numBytes = (unsigned int)result;
1488 if (0 == result) OnNotify(NOTIFY_NONE);
1489 return true;
1490 }
1491 #endif // if/else WIN32/UNIX
1492 } // end ProtoSocket::Recv()
1493
1494 // Note the function prototype and behavior here is changing slightly
1495 // from the prior / original ProtoSocket::SendTo() behavior such that
1496 // the EWOULDBLOCK condition no longer returns "false" but instead returns
1497 // "true", but with setting the referenced "buflen" value to zero.
1498 // This lets us differentiate this condition, mainly as a cue for when
1499 // (and when not to) enable socket output notification for async i/o mgmnt.s
1500 bool ProtoSocket::SendTo(const char* buffer,
1501 unsigned int& buflen,
1502 const ProtoAddress& dstAddr)
1503 {
1504 if (!IsOpen())
1505 {
1506 if (!Open(0, dstAddr.GetType()))
1507 {
1508 PLOG(PL_ERROR, "ProtoSocket::SendTo() error: socket not open\n");
1509 return false;
1510 }
1511 }
1512 if (IsConnected())
1513 {
1514 unsigned int numBytes = buflen;
1515 if (!Send(buffer, numBytes))
1516 {
1517
1518 PLOG(PL_DEBUG, "ProtoSocket::SendTo() error: Send() error\n");
1519 buflen = 0;
1520 return false;
1521 }
1522 if (numBytes != buflen)
1523 {
1524 PLOG(PL_DEBUG, "ProtoSocket::SendTo() error: Send() incomplete\n");
1525 buflen = 0;
1526 return true;
1527 }
1528 else
1529 {
1530 return true;
1531 }
1532 }
1533 else
1534 {
1535 socklen_t addrSize;
1536 #ifdef HAVE_IPV6
1537 if (flow_label && (ProtoAddress::IPv6 == dstAddr.GetType()))
1538 ((struct sockaddr_in6*)(&dstAddr.GetSockAddrStorage()))->sin6_flowinfo = flow_label;
1539 if (ProtoAddress::IPv6 == dstAddr.GetType())
1540 addrSize = sizeof(struct sockaddr_in6);
1541 else
1542 #endif //HAVE_IPV6
1543 addrSize = sizeof(struct sockaddr_in);
1544 #ifdef WIN32
1545 WSABUF wsaBuf;
1546 wsaBuf.len = buflen;
1547 wsaBuf.buf = (char*)buffer;
1548 DWORD numBytes;
1549 if (SOCKET_ERROR == WSASendTo(handle, &wsaBuf, 1, &numBytes, 0,
1550 &dstAddr.GetSockAddr(), addrSize, NULL, NULL))
1551 {
1552 buflen = 0;
1553 switch (WSAGetLastError())
1554 {
1555 case WSAEINTR:
1556 return true;
1557 case WSAEWOULDBLOCK:
1558 output_ready = false;
1559 return true;
1560 default:
1561 break;
1562 }
1563 PLOG(PL_ERROR, "ProtoSocket::SendTo() WSASendTo() error: %s\n", GetErrorString());
1564 return false;
1565 }
1566 else
1567 {
1568 //ASSERT(numBytes == buflen);
1569 return true;
1570 }
1571 #else
1572 ssize_t result = sendto(handle, buffer, (size_t)buflen, 0, &dstAddr.GetSockAddr(), addrSize);
1573 if (result < 0)
1574 {
1575 buflen = 0;
1576 switch (errno)
1577 {
1578 case EINTR:
1579 case EAGAIN:
1580 return true;
1581 case ENOBUFS:
1582 PLOG(PL_DEBUG, "ProtoSocket::SendTo() sendto() error: %s\n", GetErrorString());
1583 return false;
1584 default:
1585 break;
1586 }
1587 PLOG(PL_ERROR, "ProtoSocket::SendTo() sendto() error: %s\n", GetErrorString());
1588 return false;
1589 }
1590 else
1591 {
1592 //ASSERT(result == buflen);
1593 return true;
1594 }
1595 #endif // if/else WIN32/UNIX
1596 }
1597 } // end ProtoSocket::SendTo()
1598
1599 bool ProtoSocket::RecvFrom(char* buffer,
1600 unsigned int& numBytes,
1601 ProtoAddress& sourceAddr)
1602 {
1603 if (!IsBound())
1604 {
1605 PLOG(PL_ERROR, "ProtoSocket::RecvFrom() error: socket not bound\n");
1606 numBytes = 0;
1607 }
1608 #ifdef HAVE_IPV6
1609 struct sockaddr_storage sockAddr;
1610 #else
1611 struct sockaddr sockAddr;
1612 #endif // if/else HAVE_IPV6
1613 socklen_t addrLen = sizeof(sockAddr);
1614 // Just do a regular recvfrom() (TBD - for Win32, should we be using WSARecvFrom()???)
1615 ssize_t result = recvfrom(handle, buffer, (size_t)numBytes, 0, (struct sockaddr*)&sockAddr, &addrLen);
1616 if (result < 0)
1617 {
1618 numBytes = 0;
1619 #ifdef WIN32
1620 switch (WSAGetLastError())
1621 {
1622 case WSAEINTR:
1623 case WSAEWOULDBLOCK:
1624 if (input_ready)
1625 {
1626 input_ready = false;
1627 UpdateNotification(); // because no longer "input ready"
1628 }
1629 return true;
1630 break;
1631 default:
1632 PLOG(PL_ERROR, "ProtoSocket::RecvFrom() recvfrom() error: %s\n", GetErrorString());
1633 break;
1634 }
1635 #else
1636 switch (errno)
1637 {
1638 case EINTR:
1639 case EAGAIN:
1640 //PLOG(PL_WARN, "ProtoSocket::Recv() recv() error: %s\n", GetErrorString());
1641 return true;
1642 break;
1643 default:
1644 PLOG(PL_ERROR, "ProtoSocket::Recv() recv() error: %s\n", GetErrorString());
1645 break;
1646 }
1647 #endif // UNIX
1648 return false;
1649 }
1650 else
1651 {
1652 #ifdef WIN32
1653 if (!input_ready)
1654 {
1655 input_ready = true;
1656 UpdateNotification();
1657 }
1658 #endif // WIN32
1659 numBytes = (unsigned int)result;
1660 sourceAddr.SetSockAddr(*((struct sockaddr*)&sockAddr));
1661 if (!sourceAddr.IsValid())
1662 {
1663 PLOG(PL_ERROR, "ProtoSocket::RecvFrom() Unsupported address type!\n");
1664 return false;
1665 }
1666 return true;
1667 }
1668 } // end ProtoSocket::RecvFrom()
1669
1670 void ProtoSocket::EnableRecvDstAddr()
1671 {
1672 if (!ip_recvdstaddr)
1673 {
1674 int enable = 1;
1675 #ifdef IP_RECVDSTADDR
1676 if (setsockopt(handle, IPPROTO_IP, IP_RECVDSTADDR, (char*)&enable, sizeof(enable)) < 0)
1677 PLOG(PL_WARN, "ProtoSocket::EnableRecvDstAddr() setsocktopt(IP_RECVDSTADDR) error: %s\n", GetErrorString());
1678 #else
1679 if (setsockopt(handle, IPPROTO_IP, IP_PKTINFO, (char*)&enable, sizeof(enable)) < 0)
1680 PLOG(PL_WARN, "ProtoSocket::EnableRecvDstAddr() setsocktopt(IP_PKTINFO) error: %s\n", GetErrorString());
1681 #endif // if/else IP_RECVDSTADDR
1682 #ifdef HAVE_IPV6
1683 #ifdef IPV6_RECVDSTADDR
1684 if (setsockopt(handle, IPPROTO_IPV6, IPV6_RECVDSTADDR, (char*)&enable, sizeof(enable)) < 0)
1685 PLOG(PL_WARN, "ProtoSocket::EnableRecvDstAddr() setsocktopt(IPV6_RECVDSTADDR) error: %s\n", GetErrorString());
1686 #else
1687 if (setsockopt(handle, IPPROTO_IPV6, IPV6_RECVPKTINFO, (char*)&enable, sizeof(enable)) < 0)
1688 PLOG(PL_WARN, "ProtoSocket::EnableRecvDstAddr() setsocktopt(IPV6_PKTINFO) error: %s\n", GetErrorString());
1689 #endif // if/else IPV6_RECVDSTADDR
1690 #endif // HAVE_IPV6
1691 ip_recvdstaddr = true;
1692 }
1693 #ifdef WIN32
1694 // On Windows, you have to "load" the WsaRecvMsg() function pointer
1695 if (NULL == WSARecvMsg)
1696 {
1697 // On first call, we need to fetch the WSARecvMsg() function pointer
1698 GUID WSARecvMsg_GUID = WSAID_WSARECVMSG;
1699 DWORD NumberOfBytes;
1700 if (SOCKET_ERROR == WSAIoctl(handle, SIO_GET_EXTENSION_FUNCTION_POINTER,
1701 &WSARecvMsg_GUID, sizeof(WSARecvMsg_GUID),
1702 &WSARecvMsg, sizeof WSARecvMsg,
1703 &NumberOfBytes, NULL, NULL))
1704 {
1705 PLOG(PL_ERROR, "ProtoSocket::EnableRecvDstAddr() error: WSARecvMsg() not supported on this platform!\n");
1706 WSARecvMsg = NULL;
1707 }
1708 }
1709 #endif // WIN32
1710 } // end ProtoSocket::EnableRecvDstAddr()
1711
1712 #ifndef WIN32
1713 // Variant RecvFrom() that uses recvmsg() to get destAddr information
1714 bool ProtoSocket::RecvFrom(char* buffer,
1715 unsigned int& numBytes,
1716 ProtoAddress& sourceAddr,
1717 ProtoAddress& destAddr)
1718 {
1719 if (!IsBound())
1720 {
1721 PLOG(PL_ERROR, "ProtoSocket::RecvFrom() error: socket not bound\n");
1722 numBytes = 0;
1723 }
1724 if (!ip_recvdstaddr) EnableRecvDstAddr(); // should enable ahead of time to make sure you don't miss any
1725
1726 #ifdef HAVE_IPV6
1727 struct sockaddr_storage sockAddr;
1728 #else
1729 struct sockaddr sockAddr;
1730 #endif // if/else HAVE_IPV6
1731 socklen_t addrLen = sizeof(sockAddr);
1732
1733 char cdata[64];
1734 struct msghdr msg; // TBD - should we bzero() our "cdata" and "msg" here???
1735 struct iovec iov[1];
1736 iov[0].iov_base = buffer;
1737 iov[0].iov_len = numBytes;
1738 msg.msg_name = &sockAddr;
1739 msg.msg_namelen = addrLen;
1740 msg.msg_iov = iov;
1741 msg.msg_iovlen = 1;
1742 msg.msg_control = cdata;
1743 msg.msg_controllen = 64;//sizeof(cdata);
1744 msg.msg_flags = 0;
1745 destAddr.Invalidate();
1746 ssize_t result = recvmsg(handle, &msg, 0);
1747 if (result < 0)
1748 {
1749 numBytes = 0;
1750 #ifdef WIN32
1751 switch (WSAGetLastError())
1752 {
1753 case WSAEINTR:
1754 case WSAEWOULDBLOCK:
1755 //PLOG(PL_WARN, "ProtoSocket::RecvFrom() recvmsg() error: %s\n", GetErrorString());
1756 input_ready = false;
1757 return true;
1758 break;
1759 default:
1760 PLOG(PL_ERROR, "ProtoSocket::RecvFrom() recvmsg() error: %s\n", GetErrorString());
1761 break;
1762 }
1763 #else
1764 switch (errno)
1765 {
1766 case EINTR:
1767 case EAGAIN:
1768 //PLOG(PL_WARN, "ProtoSocket::Recv() recv() error: %s\n", GetErrorString());
1769 return true;
1770 break;
1771 default:
1772 PLOG(PL_ERROR, "ProtoSocket::Recv() recv() error: %s\n", GetErrorString());
1773 break;
1774 }
1775 #endif // UNIX
1776 return false;
1777 }
1778 else
1779 {
1780 numBytes = (unsigned int)result;
1781 sourceAddr.SetSockAddr(*((struct sockaddr*)&sockAddr));
1782 if (!sourceAddr.IsValid())
1783 {
1784 PLOG(PL_ERROR, "ProtoSocket::RecvFrom() Unsupported address type!\n");
1785 return false;
1786 }
1787 // Get destAddr info
1788 for (struct cmsghdr* cmptr = CMSG_FIRSTHDR(&msg); cmptr != NULL; cmptr = CMSG_NXTHDR(&msg, cmptr))
1789 {
1790 if (cmptr->cmsg_level == IPPROTO_IP)
1791 {
1792 #ifdef IP_RECVDSTADDR
1793 if ((cmptr->cmsg_level == IPPROTO_IP) && (cmptr->cmsg_type == IP_RECVDSTADDR))
1794 {
1795 destAddr.SetRawHostAddress(ProtoAddress::IPv4, (char*)CMSG_DATA(cmptr), 4);
1796 }
1797 #else
1798 if (cmptr->cmsg_type == IP_PKTINFO)
1799 {
1800 struct in_pktinfo* pktInfo = (struct in_pktinfo*)((void*)CMSG_DATA(cmptr));
1801 destAddr.SetRawHostAddress(ProtoAddress::IPv4, (char*)(&pktInfo->ipi_addr), 4);
1802 }
1803 #endif // if/else IP_RECVDSTADDR
1804 }
1805 #ifdef HAVE_IPV6
1806 if (cmptr->cmsg_level == IPPROTO_IPV6)
1807 {
1808 #ifdef IPV6_RECVDSTADDR
1809 if (cmptr->cmsg_type == IPV6_RECVDSTADDR)
1810 {
1811 destAddr.SetRawHostAddress(ProtoAddress::IPv6, (char*)CMSG_DATA(cmptr), 16);
1812 }
1813 #else
1814 if (cmptr->cmsg_type == IPV6_PKTINFO)
1815 {
1816 struct in6_pktinfo* pktInfo = (struct in6_pktinfo*)((void*)CMSG_DATA(cmptr));
1817 destAddr.SetRawHostAddress(ProtoAddress::IPv6, (char*)(&pktInfo->ipi6_addr), 16);
1818 }
1819 #endif // if/else IPV6_RECVDSTADDR
1820 }
1821 #endif // HAVE_IPV6
1822 }
1823 return true;
1824 }
1825 } // end ProtoSocket::RecvFrom(w/ destAddr)
1826 #else
1827 // WIN32 implementation
1828 bool ProtoSocket::RecvFrom(char* buffer,
1829 unsigned int& numBytes,
1830 ProtoAddress& sourceAddr,
1831 ProtoAddress& destAddr)
1832 {
1833 if (!IsBound())
1834 {
1835 PLOG(PL_ERROR, "ProtoSocket::RecvFrom() error: socket not bound\n");
1836 numBytes = 0;
1837 }
1838 if (!ip_recvdstaddr) EnableRecvDstAddr(); // should enable ahead of time to make sure you don't miss any
1839 destAddr.Invalidate(); // will be filled in if possible
1840
1841 if (NULL == WSARecvMsg)
1842 {
1843 PLOG(PL_WARN, "ProtoSocket::RecvFrom() warning: WSARecvMsg() not supported\n");
1844 return RecvFrom(buffer, numBytes, sourceAddr);
1845 }
1846 struct sockaddr sockAddr;
1847 socklen_t addrLen = sizeof(sockAddr);
1848
1849 // Buffer to receive control data (destAddr info)
1850 char cdata[256];
1851 // Buffer to receive data
1852 WSABUF dbuf[1];
1853 dbuf[0].len = numBytes;
1854 dbuf[0].buf = buffer;
1855
1856 WSAMSG msg;
1857 msg.name = &sockAddr;
1858 msg.namelen = addrLen;
1859 msg.lpBuffers = dbuf;
1860 msg.dwBufferCount = 1;
1861 msg.Control.len = 64;
1862 msg.Control.buf = cdata;
1863 msg.dwFlags = 0;
1864 destAddr.Invalidate();
1865
1866 DWORD bytesRecvd;
1867 if (SOCKET_ERROR == WSARecvMsg(handle, &msg, &bytesRecvd, NULL, NULL))
1868 {
1869 numBytes = 0;
1870 switch (WSAGetLastError())
1871 {
1872 case WSAEINTR:
1873 case WSAEWOULDBLOCK:
1874 //PLOG(PL_WARN, "ProtoSocket::RecvFrom() WSARecvMsg() error: %s\n", GetErrorString());
1875 input_ready = false;
1876 return true;
1877 break;
1878 default:
1879 PLOG(PL_ERROR, "ProtoSocket::RecvFrom() WSARecvMsg() error: %s\n", GetErrorString());
1880 break;
1881 }
1882 return false;
1883 }
1884 else
1885 {
1886 numBytes = bytesRecvd;
1887 sourceAddr.SetSockAddr(*((struct sockaddr*)&sockAddr));
1888 if (!sourceAddr.IsValid())
1889 {
1890 PLOG(PL_ERROR, "ProtoSocket::RecvFrom() error: Unsupported address type!\n");
1891 return false;
1892 }
1893 // Get destAddr info
1894 for (WSACMSGHDR* cmptr = WSA_CMSG_FIRSTHDR(&msg); cmptr != NULL; cmptr = WSA_CMSG_NXTHDR(&msg, cmptr))
1895 {
1896 if (cmptr->cmsg_level == IPPROTO_IP)
1897 {
1898 #ifdef IP_RECVDSTADDR
1899 if ((cmptr->cmsg_level == IPPROTO_IP) && (cmptr->cmsg_type == IP_RECVDSTADDR))
1900 {
1901 destAddr.SetRawHostAddress(ProtoAddress::IPv4, (char*)WSA_CMSG_DATA(cmptr), 4);
1902 }
1903 #else
1904 if (cmptr->cmsg_type == IP_PKTINFO)
1905 {
1906 struct in_pktinfo* pktInfo = (struct in_pktinfo*)((void*)WSA_CMSG_DATA(cmptr));
1907 destAddr.SetRawHostAddress(ProtoAddress::IPv4, (char*)(&pktInfo->ipi_addr), 4);
1908 }
1909 #endif // if/else IP_RECVDSTADDR
1910 }
1911 #ifdef HAVE_IPV6
1912 if (cmptr->cmsg_level == IPPROTO_IPV6)
1913 {
1914 #ifdef IPV6_RECVDSTADDR
1915 if (cmptr->cmsg_type == IPV6_RECVDSTADDR)
1916 {
1917 destAddr.SetRawHostAddress(ProtoAddress::IPv6, (char*)WSA_CMSG_DATA(cmptr), 16);
1918 }
1919 #else
1920 if (cmptr->cmsg_type == IPV6_PKTINFO)
1921 {
1922 struct in6_pktinfo* pktInfo = (struct in6_pktinfo*)((void*)WSA_CMSG_DATA(cmptr));
1923 destAddr.SetRawHostAddress(ProtoAddress::IPv6, (char*)(&pktInfo->ipi6_addr), 16);
1924 }
1925 #endif // if/else IPV6_RECVDSTADDR
1926 }
1927 #endif // HAVE_IPV6
1928 }
1929 return true;
1930 }
1931 } // end ProtoSocket::RecvFrom(w/ destAddr) [WIN32]
1932
1933 #endif // if/else !WIN32
1934
1935 #ifdef HAVE_IPV6
1936 #ifndef IPV6_ADD_MEMBERSHIP
1937 #define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
1938 #define IPV6_DROP_MEMBERSHIP IPV6_LEAVE_GROUP
1939 #endif // !IPV6_ADD_MEMBERSHIP
1940 #endif // HAVE_IPV6
1941
1942 /**
1943 * @note On WinNT 4.0 (or earlier?), we seem to need WSAJoinLeaf() for multicast to work
1944 * Thus NT 4.0 probably doesn't support IPv6 multicast???
1945 * So, here we use WSAJoinLeaf() iff the OS is NT and version 4.0 or earlier.
1946 */
1947 // Full SSM support is still work in progress (only supported on Linux and Mac OSX for moment)
1948 bool ProtoSocket::JoinGroup(const ProtoAddress& groupAddress,
1949 const char* interfaceName, // optional interface name for group join
1950 const ProtoAddress* sourceAddress) // optional source address for SSM support
1951 {
1952 if (!IsOpen() && !Open(0, groupAddress.GetType(), false))
1953 {
1954 PLOG(PL_ERROR, "ProtoSocket::JoinGroup() error: unable to open socket\n");
1955 return false;
1956 }
1957 #ifdef WIN32
1958 if (NULL != sourceAddress)
1959 {
1960 // WIN32 SSM support will be added in near future
1961 PLOG(PL_ERROR, "ProtoSocket::JoinGroup() error: Source-specific Multicast (SSM) for WIN32 not yet supported\n");
1962 return false;
1963 }
1964 // on WinNT 4.0 (or earlier?), we seem to need WSAJoinLeaf() for multicast to work
1965 // Thus NT 4.0 probably doesn't support IPv6 multicast???
1966 // So, here we use WSAJoinLeaf() iff the OS is NT and version 4.0 or earlier.
1967 bool useJoinLeaf = false;
1968 OSVERSIONINFO vinfo;
1969 vinfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1970 GetVersionEx(&vinfo);
1971 if ((VER_PLATFORM_WIN32_NT == vinfo.dwPlatformId) &&
1972 ((vinfo.dwMajorVersion < 4) ||
1973 ((vinfo.dwMajorVersion == 4) && (vinfo.dwMinorVersion == 0))))
1974 useJoinLeaf = true;
1975 if (useJoinLeaf)
1976 {
1977 if (interfaceName && !SetMulticastInterface(interfaceName))
1978 PLOG(PL_ERROR, "ProtoSocket::JoinGroup() warning: error setting socket multicast interface\n");
1979 SOCKET result = WSAJoinLeaf(handle, &groupAddress.GetSockAddr(), sizeof(struct sockaddr),
1980 NULL, NULL, NULL, NULL, JL_BOTH);
1981 if (INVALID_SOCKET == result)
1982 {
1983 PLOG(PL_ERROR, "WSAJoinLeaf() error: %d\n", WSAGetLastError());
1984 return false;
1985 }
1986 else
1987 {
1988 return true;
1989 }
1990 } // end if (useJoinLeaf)
1991 #endif // WIN32
1992 int result;
1993 #ifdef HAVE_IPV6
1994 if (ProtoAddress::IPv6 == groupAddress.GetType())
1995 {
1996 if (NULL != sourceAddress)
1997 {
1998 // IPv6 SSM support will be added in near future
1999 PLOG(PL_ERROR, "ProtoSocket::JoinGroup() error: Source-specific Multicast (SSM) for IPv6 not yet supported\n");
2000 return false;
2001 }
2002 if (IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6*)&groupAddress.GetSockAddrStorage())->sin6_addr))
2003 {
2004 struct ip_mreq mreq;
2005 mreq.imr_multiaddr.s_addr =
2006 (in_addr_t)IN6_V4MAPPED_ADDR(&(((struct sockaddr_in6*)&groupAddress.GetSockAddrStorage())->sin6_addr));
2007 if (NULL != interfaceName)
2008 {
2009 ProtoAddress interfaceAddress;
2010 #if defined(WIN32) && (WINVER < 0x0500)
2011 if (interfaceAddress.ResolveFromString(interfaceName))
2012 {
2013 mreq.imr_interface.s_addr = htonl(interfaceAddress.IPv4GetAddress());
2014 }
2015 else if (GetInterfaceAddress(interfaceName, ProtoAddress::IPv4, interfaceAddress))
2016 #else
2017 if (GetInterfaceAddress(interfaceName, ProtoAddress::IPv4, interfaceAddress))
2018 #endif // if/else defined(WIN32) && (WINVER < 0x0500)
2019 {
2020 mreq.imr_interface.s_addr = htonl(interfaceAddress.IPv4GetAddress());
2021 }
2022 else
2023 {
2024 PLOG(PL_ERROR, "ProtoSocket::JoinGroup() invalid interface name\n");
2025 return false;
2026 }
2027 }
2028 else
2029 {
2030 mreq.imr_interface.s_addr = INADDR_ANY;
2031 }
2032 result = setsockopt(handle, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char*)&mreq, sizeof(mreq));
2033 }
2034 else
2035 {
2036 struct ipv6_mreq mreq;
2037 mreq.ipv6mr_multiaddr = ((struct sockaddr_in6*)&groupAddress.GetSockAddrStorage())->sin6_addr;
2038 if (NULL != interfaceName)
2039 mreq.ipv6mr_interface = GetInterfaceIndex(interfaceName);
2040 else
2041 mreq.ipv6mr_interface = 0;
2042 result = setsockopt(handle, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, (char*)&mreq, sizeof(mreq));
2043 }
2044 }
2045 else
2046 #endif // HAVE_IPV6
2047 {
2048 // IPv4 group join
2049 if (NULL == sourceAddress)
2050 {
2051 // non-SSM
2052
2053 struct ip_mreq mreq;
2054 #ifdef HAVE_IPV6
2055 mreq.imr_multiaddr = ((struct sockaddr_in*)&groupAddress.GetSockAddrStorage())->sin_addr;
2056 #else
2057 mreq.imr_multiaddr = ((struct sockaddr_in*)&groupAddress.GetSockAddr())->sin_addr;
2058 #endif // end if/else HAVE_IPV6
2059 if (NULL != interfaceName)
2060 {
2061 ProtoAddress interfaceAddress;
2062 #if defined(WIN32) && (WINVER < 0x0500)
2063 if (interfaceAddress.ResolveFromString(interfaceName))
2064 {
2065 mreq.imr_interface.s_addr = htonl(interfaceAddress.IPv4GetAddress());
2066 }
2067 else if (GetInterfaceAddress(interfaceName, ProtoAddress::IPv4, interfaceAddress))
2068 #else
2069 if (GetInterfaceAddress(interfaceName, ProtoAddress::IPv4, interfaceAddress))
2070 #endif // if/else defined(WIN32) && (WINVER < 0x0500)
2071 {
2072 mreq.imr_interface.s_addr = htonl(interfaceAddress.IPv4GetAddress());
2073 }
2074 else
2075 {
2076 PLOG(PL_ERROR, "ProtoSocket::JoinGroup() error: invalid interface name\n");
2077 return false;
2078 }
2079 }
2080 else
2081 {
2082 mreq.imr_interface.s_addr = INADDR_ANY;
2083 }
2084 result = setsockopt(handle, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char*)&mreq, sizeof(mreq));
2085 }
2086 else
2087 {
2088 // SSM join
2089 #if defined(_PROTOSOCKET_IGMPV3_SSM) && defined(IP_ADD_SOURCE_MEMBERSHIP)
2090 struct ip_mreq_source mreq;
2091 #ifdef HAVE_IPV6
2092 mreq.imr_multiaddr = ((struct sockaddr_in*)&groupAddress.GetSockAddrStorage())->sin_addr;
2093 mreq.imr_sourceaddr = ((struct sockaddr_in*)&sourceAddress->GetSockAddrStorage())->sin_addr;
2094 #else
2095 mreq.imr_multiaddr = ((struct sockaddr_in*)&groupAddress.GetSockAddr())->sin_addr;
2096 mreq.imr_sourceaddr = ((struct sockaddr_in*)&sourceAddress->GetSockAddr())->sin_addr;
2097 #endif // if/else HAVE_IPV6
2098 if (NULL != interfaceName)
2099 {
2100 ProtoAddress interfaceAddress;
2101 if (GetInterfaceAddress(interfaceName, ProtoAddress::IPv4, interfaceAddress))
2102 {
2103 mreq.imr_interface.s_addr = htonl(interfaceAddress.IPv4GetAddress());
2104 }
2105 else
2106 {
2107 PLOG(PL_ERROR, "ProtoSocket::JoinGroup() invalid interface name\n");
2108 return false;
2109 }
2110 }
2111 else
2112 {
2113 mreq.imr_interface.s_addr = INADDR_ANY;
2114 }
2115 result = setsockopt(handle, IPPROTO_IP, IP_ADD_SOURCE_MEMBERSHIP, (char*)&mreq, sizeof(mreq));
2116 if (result < 0)
2117 {
2118 PLOG(PL_ERROR, "ProtoSocket::JoinGroup() setsockopt(IP_ADD_SOURCE_MEMBERSHIP) error: %s\n", strerror( errno ));
2119 return false;
2120 }
2121 return true;
2122 #else
2123 PLOG(PL_ERROR, "ProtoSocket:JoinGroup() error: SSM support not included in this build\n");
2124 return false;
2125 #endif // end if/else _PROTOSOCKET_IGMPV3_SSM && IP_ADD_SOURCE_MEMBERSHIP
2126 }
2127 }
2128 if (result < 0)
2129 {
2130 PLOG(PL_ERROR, "ProtoSocket:JoinGroup() setsockopt(add membership) error: %s\n", GetErrorString());
2131 return false;
2132 }
2133 return true;
2134 } // end ProtoSocket::JoinGroup()
2135
2136 bool ProtoSocket::LeaveGroup(const ProtoAddress& groupAddress,
2137 const char* interfaceName,
2138 const ProtoAddress* sourceAddress)
2139 {
2140 if (!IsOpen()) return true;
2141 int result;
2142 #ifdef HAVE_IPV6
2143 if (ProtoAddress::IPv6 == groupAddress.GetType())
2144 {
2145 // IPv6 leave
2146 if (NULL != sourceAddress)
2147 {
2148 // IPv6 SSM support will be added in near future
2149 PLOG(PL_ERROR, "ProtoSocket::LeaveGroup() error: Source-specific Multicast (SSM) for IPv6 not yet supported\n");
2150 return false;
2151 }
2152 if (IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6*)&groupAddress.GetSockAddrStorage())->sin6_addr))
2153 {
2154 struct ip_mreq mreq;
2155 mreq.imr_multiaddr.s_addr =
2156 (in_addr_t)IN6_V4MAPPED_ADDR(&(((struct sockaddr_in6*)&groupAddress.GetSockAddrStorage())->sin6_addr));
2157 if (interfaceName)
2158 {
2159 ProtoAddress interfaceAddress;
2160 if (GetInterfaceAddress(interfaceName, ProtoAddress::IPv4, interfaceAddress))
2161 {
2162 mreq.imr_interface.s_addr = htonl(interfaceAddress.IPv4GetAddress());
2163 }
2164 else
2165 {
2166 PLOG(PL_ERROR, "ProtoSocket::LeaveGroup() invalid interface name\n");
2167 return false;
2168 }
2169 }
2170 else
2171 {
2172 mreq.imr_interface.s_addr = INADDR_ANY;
2173 }
2174 result = setsockopt(handle, IPPROTO_IP, IP_DROP_MEMBERSHIP, (char*)&mreq, sizeof(mreq));
2175 }
2176 else
2177 {
2178 struct ipv6_mreq mreq;
2179 mreq.ipv6mr_multiaddr = ((struct sockaddr_in6*)&groupAddress.GetSockAddrStorage())->sin6_addr;
2180 if (interfaceName)
2181 mreq.ipv6mr_interface = GetInterfaceIndex(interfaceName);
2182 else
2183 mreq.ipv6mr_interface = 0;
2184 result = setsockopt(handle, IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, (char*)&mreq, sizeof(mreq));
2185 }
2186 }
2187 else
2188 #endif // HAVE_IPV6
2189 {
2190 // IPv4 leave
2191 if (NULL == sourceAddress)
2192 {
2193 // non-SSM
2194 struct ip_mreq mreq;
2195 #ifdef HAVE_IPV6
2196 mreq.imr_multiaddr = ((struct sockaddr_in*)&groupAddress.GetSockAddrStorage())->sin_addr;
2197 #else
2198 mreq.imr_multiaddr = ((struct sockaddr_in*)&groupAddress.GetSockAddr())->sin_addr;
2199 #endif // end if/else HAVE_IPV6
2200 if (NULL != interfaceName)
2201 {
2202 ProtoAddress interfaceAddress;
2203 if (GetInterfaceAddress(interfaceName, ProtoAddress::IPv4,
2204 interfaceAddress))
2205 {
2206 mreq.imr_interface.s_addr = htonl(interfaceAddress.IPv4GetAddress());
2207 }
2208 else
2209 {
2210 PLOG(PL_ERROR, "ProtoSocket::LeaveGroup() invalid interface name\n");
2211 return false;
2212 }
2213 }
2214 else
2215 {
2216 mreq.imr_interface.s_addr = INADDR_ANY;
2217 }
2218 result = setsockopt(handle, IPPROTO_IP, IP_DROP_MEMBERSHIP, (char*)&mreq, sizeof(mreq));
2219 }
2220 else
2221 {
2222 // SSM Leave
2223 #if defined(_PROTOSOCKET_IGMPV3_SSM) && defined(IP_DROP_SOURCE_MEMBERSHIP)
2224 struct ip_mreq_source mreq;
2225 #ifdef HAVE_IPV6
2226 mreq.imr_multiaddr = ((struct sockaddr_in*)&groupAddress.GetSockAddrStorage())->sin_addr;
2227 mreq.imr_sourceaddr = ((struct sockaddr_in*)&sourceAddress->GetSockAddrStorage())->sin_addr;
2228 #else
2229 mreq.imr_multiaddr = ((struct sockaddr_in*)&groupAddress.GetSockAddr())->sin_addr;
2230 mreq.imr_sourceaddr = ((struct sockaddr_in*)&sourceAddress->GetSockAddr())->sin_addr;
2231 #endif // if/else HAVE_IPV6
2232 if (interfaceName)
2233 {
2234 ProtoAddress interfaceAddress;
2235 if (GetInterfaceAddress(interfaceName, ProtoAddress::IPv4,
2236 interfaceAddress))
2237 {
2238 mreq.imr_interface.s_addr = htonl(interfaceAddress.IPv4GetAddress());
2239 }
2240 else
2241 {
2242 PLOG(PL_ERROR, "ProtoSocket::LeaveGroup() invalid interface name\n");
2243 return false;
2244 }
2245 }
2246 else
2247 {
2248 mreq.imr_interface.s_addr = INADDR_ANY;
2249 }
2250 result = setsockopt(handle, IPPROTO_IP, IP_DROP_SOURCE_MEMBERSHIP, (char*)&mreq, sizeof(mreq));
2251 #else
2252 PLOG(PL_ERROR, "ProtoSocket:LeaveGroup() error: SSM support not included in this build\n");
2253 return false;
2254 #endif // end if/else _PROTOSOCKET_IGMPV3_SSM && IP_DROP_SOURCE_MEMBERSHIP
2255 }
2256 }
2257 if (result < 0)
2258 {
2259 PLOG(PL_ERROR, "ProtoSocket::LeaveGroup() error leaving multicast group: %s\n", GetErrorString());
2260 return false;
2261 }
2262 else
2263 {
2264 return true;
2265 }
2266 } // end ProtoSocket::LeaveGroup()
2267
2268 // Set MulticastTTL Function name retained for backwards compatability
2269 // See new ProtoSocket::SetUnicastTTL
2270 bool ProtoSocket::SetTTL(unsigned char ttl)
2271 {
2272 #if defined(WIN32) && !defined(_WIN32_WCE)
2273 DWORD dwTTL = (DWORD)ttl;
2274 DWORD dwBytesXfer;
2275 int optVal = ttl;
2276 int optLen = sizeof(int);
2277 if (WSAIoctl(handle, SIO_MULTICAST_SCOPE, &dwTTL, sizeof(dwTTL),
2278 NULL, 0, &dwBytesXfer, NULL, NULL))
2279
2280 #else
2281 int result = 0;
2282 #ifdef HAVE_IPV6
2283 if (IPv6 == domain)
2284 {
2285 #ifdef MACOSX
2286 // v6 multicast TTL socket option must be an int
2287 int hops = (int) ttl;
2288
2289 if (protocol != ProtoSocket::TCP)
2290 result = setsockopt(handle, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
2291 &hops, sizeof(hops));
2292
2293 if (result == 0)
2294 result = setsockopt(handle, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
2295 &hops, sizeof(hops));
2296 #else
2297
2298 socklen_t hops = (socklen_t) ttl;
2299
2300 if (protocol != ProtoSocket::TCP)
2301 result = setsockopt(handle, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
2302 &hops, sizeof(hops));
2303
2304 if (result == 0)
2305 result = setsockopt(handle, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
2306 &hops, sizeof(hops));
2307 #endif // MACOSX
2308 }
2309 else
2310 #endif // HAVE_IPV6
2311 {
2312 #ifdef _WIN32_WCE
2313 int hops = (int)ttl;
2314 #else
2315 socklen_t hops = (socklen_t)ttl;
2316 #endif // if/else _WIN32_WCE/UNIX
2317 #ifdef MACOSX
2318 if (protocol != ProtoSocket::TCP)
2319 result = setsockopt(handle, IPPROTO_IP, IP_MULTICAST_TTL,
2320 (char*)&hops, sizeof(hops));
2321
2322 if (result == 0)
2323 result = setsockopt(handle,IPPROTO_IP, IP_TTL,
2324 (char*)&hops, sizeof(hops));
2325
2326 #else
2327 if (protocol != ProtoSocket::TCP)
2328 result = setsockopt(handle, IPPROTO_IP, IP_MULTICAST_TTL,
2329 (char*)&hops, sizeof(hops));
2330 #endif
2331 }
2332 if (result < 0)
2333 #endif // if/else WIN32/UNIX | _WIN32_WCE
2334 {
2335
2336 PLOG(PL_ERROR, "ProtoSocket: setsockopt(IP_MULTICAST_TTL) error: %s\n", GetErrorString());
2337 return false;
2338 }
2339 else
2340 {
2341 return true;
2342 }
2343 } // end ProtoSocket::SetTTL()
2344
2345 bool ProtoSocket::SetUnicastTTL(unsigned char ttl)
2346 {
2347 #if defined(WIN32) && !defined(_WIN32_WCE)
2348 DWORD dwTTL = (DWORD)ttl;
2349 DWORD dwBytesXfer;
2350 int optVal = ttl;
2351 int optLen = sizeof(int);
2352 if (setsockopt(handle,IPPROTO_IP,IP_TTL,(char*)&optVal,optLen) == SOCKET_ERROR)
2353 {
2354 PLOG(PL_ERROR, "ProtoSocket: setsockopt(IP_TTL) error: %s\n", GetErrorString());
2355 return false;
2356 }
2357 #else
2358 int result = 0;
2359 #ifdef HAVE_IPV6
2360 if (IPv6 == domain)
2361 {
2362 socklen_t hops = (socklen_t) ttl;
2363
2364 #ifdef MACOSX
2365 result = setsockopt(handle, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
2366 &hops, sizeof(&hops));
2367 #else
2368 result = setsockopt(handle, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
2369 &hops, sizeof(hops));
2370 #endif // MACOSX
2371 }
2372 else
2373 #endif // HAVE_IPV6
2374 {
2375 #ifdef _WIN32_WCE
2376 int hops = (int)ttl;
2377 #else
2378 socklen_t hops = (socklen_t)ttl;
2379 #endif // if/else _WIN32_WCE/UNIX
2380 #ifdef MACOSX
2381 result = setsockopt(handle,IPPROTO_IP, IP_TTL,
2382 (char*)&hops, sizeof(&hops));
2383
2384 #else
2385 result = setsockopt(handle,IPPROTO_IP, IP_TTL,
2386 (char*)&hops, sizeof(hops));
2387 #endif
2388 }
2389 if (result < 0)
2390 {
2391
2392 PLOG(PL_ERROR, "ProtoSocket: setsockopt(IP_MULTICAST_TTL) error: %s\n", GetErrorString());
2393 return false;
2394 }
2395 #endif // if/else WIN32/UNIX | _WIN32_WCE
2396 else
2397 {
2398 return true;
2399 }
2400 } // end ProtoSocket::SetUnicastTTL()
2401
2402 bool ProtoSocket::SetTOS(UINT8 theTOS)
2403 {
2404 if (!IsOpen())
2405 {
2406 tos = theTOS;
2407 return true;
2408 }
2409 if (ecn_capable)
2410 {
2411 theTOS |= ((UINT8)ECN_ECT0); // set ECT0 bit
2412 theTOS &= ~((UINT8)ECN_ECT1); // clear ECT1 bit
2413 }
2414 #ifdef NEVER_EVER // (for older LINUX?)
2415 int precedence = IPTOS_PREC(theTOS);
2416 if (setsockopt(handle, SOL_SOCKET, SO_PRIORITY, (char*)&precedence, sizeof(precedence)) < 0)
2417 {
2418 PLOG(PL_ERROR, "ProtoSocket: setsockopt(SO_PRIORITY) error: %s\n", GetErrorString());
2419 return false;
2420 }
2421 int tosBits = IPTOS_TOS(theTOS);
2422 if (setsockopt(handle, SOL_IP, IP_TOS, (char*)&tosBits, sizeof(tosBits)) < 0)
2423 #else
2424 int tosBits = theTOS;
2425 int result = -1;
2426 #ifdef HAVE_IPV6
2427 if (IPv6 == domain)
2428 {
2429 #ifdef IPV6_TCLASS
2430 result = setsockopt(handle, IPPROTO_IPV6, IPV6_TCLASS, (char*)&tosBits, sizeof(tosBits));
2431 if (result < 0)
2432 #endif // IPV6_TCLASS
2433 {
2434 result = setsockopt(handle, IPPROTO_IPV6, IP_TOS, (char*)&tosBits, sizeof(tosBits));
2435 if (result < 0)
2436 PLOG(PL_ERROR,"ProtoSocket::SetTOS() Error setting IPV6 tos/tclass %s",GetErrorString());
2437 }
2438 SetFlowLabel(((UINT32)theTOS) << 20); // set flow label "traffic class" to "tos" value
2439 }
2440 else
2441 #endif // HAVE_IPV6
2442 {
2443 result = setsockopt(handle, IPPROTO_IP, IP_TOS, (char*)&tosBits, sizeof(tosBits));
2444 }
2445 #endif // if/else NEVER_EVER
2446 if (result < 0)
2447 {
2448 PLOG(PL_ERROR, "ProtoSocket: setsockopt(IP_TOS) error\n");
2449 return false;
2450 }
2451 tos = theTOS;
2452 return true;
2453 } // end ProtoSocket::SetTOS()
2454
2455 /**
2456 * (TBD) add mechanism to dither ECN ECT0/ECT1 1-bit "nonce"
2457 * of RFC3168 (e.g. RFC3540). For now we set ECT0 bit only.
2458 */
2459 bool ProtoSocket::SetEcnCapable(bool state)
2460 {
2461 if (state)
2462 {
2463 if (!ecn_capable)
2464 {
2465 ecn_capable = true;
2466 bool result = SetTOS(tos); // will update saved "tos" value accordingly
2467 if (!result) ecn_capable = false;
2468 return result;
2469 }
2470 }
2471 else if (ecn_capable)
2472 {
2473 ecn_capable = false;
2474 bool result = SetTOS(tos);
2475 if (!result) ecn_capable = true;
2476 return result;
2477 }
2478 return true;
2479 } // end ProtoSocket::SetEcnCapable()
2480
2481 bool ProtoSocket::SetBroadcast(bool broadcast)
2482 {
2483 #ifdef SO_BROADCAST
2484 #ifdef WIN32
2485 BOOL state = broadcast ? TRUE : FALSE;
2486 #else
2487 int state = broadcast ? 1 : 0;
2488 #endif // if/else WIN32
2489 if (setsockopt(handle, SOL_SOCKET, SO_BROADCAST, (char*)&state, sizeof(state)) < 0)
2490 {
2491 PLOG(PL_ERROR, "ProtoSocket::SetBroadcast(): setsockopt(SO_BROADCAST) error: %s\n",
2492 GetErrorString());
2493 return false;
2494 }
2495 #endif // SO_BROADCAST
2496 return true;
2497 } // end ProtoSocket::SetBroadcast()
2498
2499
2500 bool ProtoSocket::SetFragmentation(bool enable)
2501 {
2502 #ifdef WIN32
2503 DWORD df = enable ? FALSE : TRUE;
2504 if (setsockopt(handle, IPPROTO_IP, IP_DONTFRAGMENT, (char*)&df, sizeof(df)) < 0)
2505 {
2506 PLOG(PL_ERROR, "ProtoSocket::SetFragmentation() setsockopt(IP_DONTFRAGMENT) error: %s\n", GetErrorString());
2507 return false;
2508 }
2509 #else // UNIX
2510 #if defined(IP_MTU_DISCOVER)
2511 // Note PMTUDISC_DONT clears DF flag while PMTUDISC_DO sets DF flag for MTU discovery
2512 // (thus, IP_PMTUDISC_DONT allows fragmentation to occur)
2513 int val = enable ? IP_PMTUDISC_DONT : IP_PMTUDISC_DO;
2514 if (setsockopt(handle, IPPROTO_IP, IP_MTU_DISCOVER, &val, sizeof(val)) < 0)
2515 {
2516 #if defined(HAVE_IPV6) && defined(IPV6_DONTFRAG)
2517 if (IPv6 == domain)
2518 {
2519 // For IPv6 sockets, we can try "IPV6_DONTFRAG" as a backup
2520 // (clear DF to allow fragmenation to occur)
2521 int df = enable ? 0 : 1;
2522 if (setsockopt(handle, IPPROTO_IPV6, IPV6_DONTFRAG, &df, sizeof(df)) < 0)
2523 {
2524 PLOG(PL_ERROR, "ProtoSocket::SetFragmentation() setsockopt(IPV6_DONTFRAG) error: %s\n", GetErrorString());
2525 return false;
2526 }
2527 }
2528 else
2529 #endif // HAVE_IPV6 && IPV6_DONTFRAG
2530 {
2531 PLOG(PL_ERROR, "ProtoSocket::SetFragmentation() setsockopt(IP_MTU_DISCOVER) error: %s\n", GetErrorString());
2532 return false;
2533 }
2534 }
2535 #elif defined(IP_DONTFRAG)
2536 int df = enable ? 0 : 1;
2537 int result;
2538 #if defined(HAVE_IPV6) && defined(IPV6_DONTFRAG)
2539 if (IPv6 == domain)
2540 result = setsockopt(handle, IPPROTO_IP, IPV6_DONTFRAG, (char*)&df, sizeof(df));
2541 else
2542 #endif
2543 result = setsockopt(handle, IPPROTO_IP, IP_DONTFRAG, (char*)&df, sizeof(df));
2544 if (result < 0)
2545 {
2546 PLOG(PL_ERROR, "ProtoSocket::SetFragmentation() setsockopt(IP_DONTFRAG) error: %s\n", GetErrorString());
2547 return false;
2548 }
2549 #else
2550 PLOG(PL_WARN, "ProtoSocket::SetFragmentation() warning: IP_MTU_DISCOVER or IP_DONTFRAG socket option not supported!\n");
2551 return false;
2552 #endif // if/else IP_MTU_DISCOVER / IP_DONTFRAG / none
2553 #endif // if/else WIN32 / UNIX
2554 return true;
2555 } // end ProtoSocket::SetFragmentation()
2556
2557 bool ProtoSocket::SetLoopback(bool loopback)
2558 {
2559 ASSERT(IsOpen());
2560 #ifdef WIN32
2561 DWORD dwLoop = loopback ? TRUE: FALSE;
2562 DWORD dwBytesXfer;
2563 if (WSAIoctl(handle, SIO_MULTIPOINT_LOOPBACK , &dwLoop, sizeof(dwLoop),
2564 NULL, 0, &dwBytesXfer, NULL, NULL))
2565 #else
2566 int result;
2567 char loop = loopback ? 1 : 0;
2568 #ifdef HAVE_IPV6
2569 unsigned int loop6 = loopback ? 1 : 0; // this is needed at least for FreeBSD
2570 if (IPv6 == domain)
2571 result = setsockopt(handle, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
2572 (char*)&loop6, sizeof(loop6));
2573 else
2574 #endif // HAVE_IPV6
2575 result = setsockopt(handle, IPPROTO_IP, IP_MULTICAST_LOOP,
2576 (char*)&loop, sizeof(loop));
2577 if (result < 0)
2578 #endif // if/else WIN32
2579 {
2580 #ifdef WIN32
2581 // On NT, this the SIO_MULTIPOINT_LOOPBACK always seems to return an error
2582 // so we'll ignore the error and return success on NT4 and earlier
2583 OSVERSIONINFO vinfo;
2584 vinfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
2585 GetVersionEx(&vinfo);
2586 if ((VER_PLATFORM_WIN32_NT == vinfo.dwPlatformId) &&
2587 ((vinfo.dwMajorVersion < 4) ||
2588 ((vinfo.dwMajorVersion == 4) && (vinfo.dwMinorVersion == 0))))
2589 return true;
2590 #endif // WIN32
2591 PLOG(PL_ERROR, "ProtoSocket: setsockopt(IP_MULTICAST_LOOP) error: %s\n", GetErrorString());
2592 return false;
2593 }
2594 else
2595 {
2596 return true;
2597 }
2598 } // end ProtoSocket::SetLoopback()
2599
2600 bool ProtoSocket::SetBindInterface(const char* ifaceName)
2601 {
2602 #ifdef SO_BINDTODEVICE
2603 size_t nameSize = strlen(ifaceName) + 1; // includes NULL termination
2604 if (setsockopt(handle, SOL_SOCKET, SO_BINDTODEVICE, ifaceName, nameSize) < 0)
2605 {
2606 PLOG(PL_ERROR, "ProtoSocket::SetBindInterface() error: %s\n", GetErrorString());
2607 return false;
2608 }
2609 return true;
2610 #else
2611 // TBD - For MacOS/BSD, we can use the IP_RECVIF socket options and recvmsg() calls
2612 // (under the hood) and filter incoming datagrams for a specific interface
2613 // to _simulate_ the behavior of SO_BINDTODEVICE. Not yet sure what to do
2614 // here for WIN32 systems.
2615
2616 PLOG(PL_ERROR, "ProtoSocket::SetBindInterface() error: SO_BINDTODEVICE socket option not supported!\n", GetErrorString());
2617 return false;
2618 #endif // if/else SO_BINDTODEVICE
2619 } // end ProtoSocket::SetBindInterface()
2620
2621 bool ProtoSocket::SetMulticastInterface(const char* interfaceName)
2622 {
2623 if (interfaceName)
2624 {
2625 int result;
2626 #ifdef HAVE_IPV6
2627 if (IPv6 == domain)
2628 {
2629 #ifdef WIN32
2630 // (TBD) figure out Win32 IPv6 multicast interface
2631 PLOG(PL_ERROR, "ProtoSocket::SetMulticastInterface() not yet supported for IPv6 on WIN32?!\n");
2632 return false;
2633 #else
2634 unsigned int interfaceIndex = GetInterfaceIndex(interfaceName);
2635 result = setsockopt(handle, IPPROTO_IPV6, IPV6_MULTICAST_IF,
2636 (char*)&interfaceIndex, sizeof(interfaceIndex));
2637 #endif // if/else WIN32
2638 }
2639 else
2640 #endif // HAVE_IPV6
2641 {
2642 struct in_addr localAddr;
2643 ProtoAddress interfaceAddress;
2644 #if defined(WIN32) && (WINVER < 0x0500)
2645 // First check to see if "interfaceName" is the IP address on older Win32 versions
2646 // since there seem to be issues with iphlpapi.lib (and hence GetInterfaceAddress()) on those platforms
2647 if (interfaceAddress.ResolveFromString(interfaceName))
2648 {
2649 localAddr.s_addr = htonl(interfaceAddress.IPv4GetAddress());
2650 }
2651 else if (GetInterfaceAddress(interfaceName, ProtoAddress::IPv4, interfaceAddress))
2652 #else
2653 if (GetInterfaceAddress(interfaceName, ProtoAddress::IPv4, interfaceAddress))
2654 #endif // if/else WIN32 && (WINVER < 0x0500)
2655 {
2656 localAddr.s_addr = htonl(interfaceAddress.IPv4GetAddress());
2657 }
2658 else
2659 {
2660 PLOG(PL_ERROR, "ProtoSocket::SetMulticastInterface() invalid interface name: %s\n", interfaceName);
2661 return false;
2662 }
2663 result = setsockopt(handle, IPPROTO_IP, IP_MULTICAST_IF, (char*)&localAddr,
2664 sizeof(localAddr));
2665 }
2666 if (result < 0)
2667 {
2668 PLOG(PL_ERROR, "ProtoSocket: setsockopt(IP_MULTICAST_IF) error: %s\n", GetErrorString());
2669 return false;
2670 }
2671 }
2672 return true;
2673 } // end ProtoSocket::SetMulticastInterface()
2674
2675 bool ProtoSocket::SetReuse(bool state)
2676 {
2677 #if defined(SO_REUSEADDR) || defined(SO_REUSEPORT)
2678 bool success = true;
2679 #else
2680 return false;
2681 #endif
2682 int reuse = state ? 1 : 0;
2683 #ifdef SO_REUSEADDR
2684 #ifdef WIN32
2685 BOOL reuseAddr = (BOOL)reuse;
2686 if (setsockopt(handle, SOL_SOCKET, SO_REUSEADDR, (char*)&reuseAddr, sizeof(reuseAddr)) < 0)
2687 #else
2688 if (setsockopt(handle, SOL_SOCKET, SO_REUSEADDR, (char*)&reuse, sizeof(reuse)) < 0)
2689 #endif // if/else WIN32
2690 {
2691 PLOG(PL_ERROR, "ProtoSocket: setsockopt(REUSE_ADDR) error: %s\n", GetErrorString());
2692 success = false;
2693 }
2694 #endif // SO_REUSEADDR
2695
2696 #ifdef SO_REUSEPORT // not defined on Linux for some reason?
2697 #ifdef WIN32
2698 BOOL reusePort = (BOOL)reuse;
2699 if (setsockopt(handle, SOL_SOCKET, SO_REUSEPORT, (char*)&reusePort, sizeof(reusePort)) < 0)
2700 #else
2701 if (setsockopt(handle, SOL_SOCKET, SO_REUSEPORT, (char*)&reuse, sizeof(reuse)) < 0)
2702 #endif // if/else WIN32
2703 {
2704 PLOG(PL_ERROR, "ProtoSocket: setsockopt(SO_REUSEPORT) error: %s\n", GetErrorString());
2705 success = false;
2706 }
2707 #endif // SO_REUSEPORT
2708 return success;
2709 } // end ProtoSocketError::SetReuse()
2710
2711 #ifdef HAVE_IPV6
2712 bool ProtoSocket::HostIsIPv6Capable()
2713 {
2714 #ifdef WIN32
2715 if (!ProtoAddress::Win32Startup())
2716 {
2717 PLOG(PL_ERROR, "ProtoSocket::HostIsIPv6Capable() WSAStartup() error: %s\n", GetErrorString());
2718 return false;
2719 }
2720 SOCKET handle = socket(AF_INET6, SOCK_DGRAM, 0);
2721 closesocket(handle);
2722 ProtoAddress::Win32Cleanup();
2723 if(INVALID_SOCKET == handle)
2724 return false;
2725 else
2726 return true;
2727 #else
2728 if (IPV6_UNKNOWN == ipv6_support_status)
2729 {
2730 ProtoAddressList addrList;
2731 ProtoNet::GetHostAddressList(ProtoAddress::IPv6, addrList);
2732 if (addrList.IsEmpty())
2733 {
2734 ipv6_support_status = IPV6_UNSUPPORTED;
2735 }
2736 else
2737 {
2738 ipv6_support_status = IPV6_SUPPORTED;
2739 }
2740 }
2741 return (IPV6_SUPPORTED == ipv6_support_status);
2742 #endif // if/else WIN32
2743 } // end ProtoSocket::HostIsIPv6Capable()
2744
2745 #endif // HAVE_IPV6
2746
2747
2748 bool ProtoSocket::SetTxBufferSize(unsigned int bufferSize)
2749 {
2750 if (!IsOpen())
2751 {
2752 PLOG(PL_ERROR, "ProtoSocket::SetTxBufferSize() error: socket closed\n");
2753 return false;
2754 }
2755 unsigned int oldBufferSize = GetTxBufferSize();
2756 if (setsockopt(handle, SOL_SOCKET, SO_SNDBUF, (char*)&bufferSize, sizeof(bufferSize)) < 0)
2757 {
2758 setsockopt(handle, SOL_SOCKET, SO_SNDBUF, (char*)&oldBufferSize, sizeof(oldBufferSize));
2759 PLOG(PL_ERROR, "ProtoSocket::SetTxBufferSize() setsockopt(SO_SNDBUF) error: %s\n",
2760 GetErrorString());
2761 return false;
2762 }
2763 return true;
2764 } // end ProtoSocket::SetTxBufferSize()
2765
2766 unsigned int ProtoSocket::GetTxBufferSize()
2767 {
2768 if (!IsOpen()) return 0;
2769 unsigned int txBufferSize = 0;
2770 socklen_t len = sizeof(txBufferSize);
2771 if (getsockopt(handle, SOL_SOCKET, SO_SNDBUF, (char*)&txBufferSize, &len) < 0)
2772 {
2773 PLOG(PL_ERROR, "ProtoSocket::GetTxBufferSize() getsockopt(SO_SNDBUF) error: %s\n",
2774 GetErrorString());
2775 return 0;
2776 }
2777 return ((unsigned int)txBufferSize);
2778 } // end ProtoSocket::GetTxBufferSize()
2779
2780 bool ProtoSocket::SetRxBufferSize(unsigned int bufferSize)
2781 {
2782 if (!IsOpen())
2783 {
2784 PLOG(PL_ERROR, "ProtoSocket::SetRxBufferSize() error: socket closed\n");
2785 return false;
2786 }
2787 unsigned int oldBufferSize = GetRxBufferSize();
2788 if (setsockopt(handle, SOL_SOCKET, SO_RCVBUF, (char*)&bufferSize, sizeof(bufferSize)) < 0)
2789 {
2790 setsockopt(handle, SOL_SOCKET, SO_RCVBUF, (char*)&oldBufferSize, sizeof(oldBufferSize));
2791 PLOG(PL_ERROR, "ProtoSocket::SetRxBufferSize() setsockopt(SO_RCVBUF) error: %s\n",
2792 GetErrorString());
2793 return false;
2794 }
2795 return true;
2796 } // end ProtoSocket::SetRxBufferSize()
2797
2798 unsigned int ProtoSocket::GetRxBufferSize()
2799 {
2800 if (!IsOpen()) return 0;
2801 unsigned int rxBufferSize = 0;
2802 socklen_t len = sizeof(rxBufferSize);
2803 if (getsockopt(handle, SOL_SOCKET, SO_RCVBUF, (char*)&rxBufferSize, &len) < 0)
2804 {
2805 PLOG(PL_ERROR, "ProtoSocket::GetRxBufferSize() getsockopt(SO_RCVBUF) error: %s\n",
2806 GetErrorString());
2807 return 0;
2808 }
2809 return ((unsigned int)rxBufferSize);
2810 } // end ProtoSocket::GetRxBufferSize()
2811
2812 #ifdef HAVE_IPV6
2813 bool ProtoSocket::SetFlowLabel(UINT32 label)
2814 {
2815 int result = 0;
2816 #ifdef SOL_IPV6
2817 if (label && !flow_label)
2818 {
2819 int on = 1;
2820 result = setsockopt(handle, SOL_IPV6, IPV6_FLOWINFO_SEND, (void*)&on, sizeof(on));
2821 }
2822 else if (!label && flow_label)
2823 {
2824 int off = 0;
2825 result = setsockopt(handle, SOL_IPV6, IPV6_FLOWINFO_SEND, (void*)&off, sizeof(off));
2826 }
2827 #endif // SOL_IPV6
2828 if (0 == result)
2829 {
2830 if (ecn_capable)
2831 {
2832 label |= (((UINT32)ECN_ECT0) << 20); // set ECN_ECT0 bit
2833 label &= ~(((UINT32)ECN_ECT1) << 20); // clear ECN_ECT1 bit
2834 }
2835 flow_label = htonl(label);
2836 return true;
2837 }
2838 else
2839 {
2840 PLOG(PL_ERROR, "ProtoSocket::SetFlowLabel() setsockopt(SOL_IPV6) error\n");
2841 return false;
2842 }
2843 } // end ProtoSocket::SetFlowLabel()
2844 #endif //HAVE_IPV6
2845
2846
2847
2848 ProtoSocket::List::List()
2849 : head(NULL)
2850 {
2851 }
2852
2853 ProtoSocket::List::~List()
2854 {
2855 Destroy();
2856 }
2857
2858 void ProtoSocket::List::Destroy()
2859 {
2860 Item* next = head;
2861 while (next)
2862 {
2863 Item* current = next;
2864 next = next->GetNext();
2865 delete current->GetSocket();
2866 delete current;
2867 }
2868 head = NULL;
2869 } // end ProtoSocket::List::Destroy()
2870
2871 bool ProtoSocket::List::AddSocket(ProtoSocket& theSocket)
2872 {
2873 Item* item = new Item(&theSocket);
2874 if (item)
2875 {
2876 item->SetPrev(NULL);
2877 item->SetNext(head);
2878 head = item;
2879 return true;
2880 }
2881 else
2882 {
2883 PLOG(PL_ERROR, "ProtoSocket::List::AddSocket() new Item error: %s\n", GetErrorString());
2884 return false;
2885 }
2886 } // end ProtoSocket::List::AddSocket()
2887
2888 void ProtoSocket::List::RemoveSocket(ProtoSocket& theSocket)
2889 {
2890 Item* item = head;
2891 while (item)
2892 {
2893 if (&theSocket == item->GetSocket())
2894 {
2895 Item* prev = item->GetPrev();
2896 Item* next = item->GetNext();
2897 if (prev)
2898 prev->SetNext(next);
2899 else
2900 head = next;
2901 if (next) next->SetPrev(prev);
2902 delete item;
2903 break;
2904 }
2905 item = item->GetNext();
2906 }
2907 } // end ProtoSocket::List::RemoveSocket()
2908
2909 ProtoSocket::List::Item* ProtoSocket::List::FindItem(const ProtoSocket& theSocket) const
2910 {
2911 Item* item = head;
2912 while (item)
2913 {
2914 if (&theSocket == item->GetSocket())
2915 return item;
2916 else
2917 item = item->GetNext();
2918 }
2919 return NULL;
2920 } // end ProtoSocket::List::FindItem()
2921
2922 ProtoSocket::List::Item::Item(ProtoSocket* theSocket)
2923 : socket(theSocket), prev(NULL), next(NULL)
2924 {
2925 }
2926
2927 ProtoSocket::List::Iterator::Iterator(const ProtoSocket::List& theList)
2928 : next(theList.head)
2929 {
2930 }
2931
2932
2933 ////////////////////////////////////////////////////////////////////
2934 // These are some network "helper" functions that get information
2935 // about the system network devices (interfaces), addresses, etc
2936 //
2937 // Note that the "ProtoSocket" implementation of this is being replaced
2938 // by implementation in the "ProtoNet" namespace (see "protoNet.h") and
2939 // the implementations here will eventually be removed _and_ the ProtoSocket
2940 // static method declarations themselves will be eventually deprecated
2941
2942 #include "protoNet.h"
2943
2944 bool ProtoSocket::GetHostAddressList(ProtoAddress::Type addrType,
2945 ProtoAddressList& addrList)
2946 {
2947 return ProtoNet::GetHostAddressList(addrType, addrList);
2948 } // end ProtoSocket::GetHostAddressList()
2949
2950
2951 bool ProtoSocket::GetInterfaceAddress(const char* ifName,
2952 ProtoAddress::Type addrType,
2953 ProtoAddress& theAddress,
2954 unsigned int* ifIndex)
2955 {
2956 return ProtoNet::GetInterfaceAddress(ifName, addrType, theAddress, ifIndex);
2957 } // end ProtoSocket::GetInterfaceAddress()
2958
2959 bool ProtoSocket::GetInterfaceAddressList(const char* interfaceName,
2960 ProtoAddress::Type addressType,
2961 ProtoAddressList& addrList,
2962 unsigned int* interfaceIndex)
2963
2964 {
2965 return ProtoNet::GetInterfaceAddressList(interfaceName, addressType, addrList, interfaceIndex);
2966 } // end ProtoSocket::GetInterfaceAddressList()
2967
2968
2969 bool ProtoSocket::FindLocalAddress(ProtoAddress::Type addrType, ProtoAddress& theAddress)
2970 {
2971 return ProtoNet::FindLocalAddress(addrType, theAddress);
2972 } // end ProtoSocket::FindLocalAddress()
2973
2974 unsigned int ProtoSocket::GetInterfaceIndex(const char* interfaceName)
2975 {
2976 return ProtoNet::GetInterfaceIndex(interfaceName);
2977 } // end ProtoSocket::GetInterfaceIndex()
2978
2979 unsigned int ProtoSocket::GetInterfaceIndices(unsigned int* indexArray, unsigned int indexArraySize)
2980 {
2981 return ProtoNet::GetInterfaceIndices(indexArray, indexArraySize);
2982 } // end ProtoSocket::GetInterfaceIndices()
2983
2984
2985 bool ProtoSocket::GetInterfaceName(unsigned int index, char* buffer, unsigned int buflen)
2986 {
2987 return (0 != ProtoNet::GetInterfaceName(index, buffer, buflen));
2988 } // end ProtoSocket::GetInterfaceName(by index)
2989
2990
2991 bool ProtoSocket::GetInterfaceName(const ProtoAddress& ifAddr, char* buffer, unsigned int buflen)
2992 {
2993 return (0 != ProtoNet::GetInterfaceName(ifAddr, buffer, buflen));
2994 } // end ProtoSocket::GetInterfaceName(by address)
2995