Debian Codegraph @

plugins/dm.gameconnection/clsocket/SimpleSocket.cpp

raw
1 /*---------------------------------------------------------------------------*/
2 /* */
3 /* CSimpleSocket.cpp - CSimpleSocket Implementation */
4 /* */
5 /* Author : Mark Carrier ([email protected]) */
6 /* */
7 /*---------------------------------------------------------------------------*/
8 /* Copyright (c) 2007-2009 CarrierLabs, LLC. All rights reserved.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 *
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 *
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in
19 * the documentation and/or other materials provided with the
20 * distribution.
21 *
22 * 3. The name of the author may not be used to endorse or promote products
23 * derived from this software without specific prior written permission.
24 *
25 * 4. The name "CarrierLabs" must not be used to
26 * endorse or promote products derived from this software without
27 * prior written permission. For written permission, please contact
28 * [email protected].
29 *
30 * THIS SOFTWARE IS PROVIDED BY MARK CARRIER ``AS IS'' AND ANY
31 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
32 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
33 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MARK CARRIER OR
34 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
35 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
36 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
37 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
38 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
39 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
40 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
41 * OF THE POSSIBILITY OF SUCH DAMAGE.
42 *----------------------------------------------------------------------------*/
43 #include "SimpleSocket.h"
44
45 CSimpleSocket::CSimpleSocket(CSocketType nType) :
46 m_socket(INVALID_SOCKET),
47 m_socketErrno(CSimpleSocket::SocketInvalidSocket),
48 m_pBuffer(NULL), m_nBufferSize(0), m_nSocketDomain(AF_INET),
49 m_nSocketType(SocketTypeInvalid), m_nBytesReceived(-1),
50 m_nBytesSent(-1), m_nFlags(0),
51 m_bIsBlocking(true)
52 {
53 SetConnectTimeout(1, 0);
54 memset(&m_stRecvTimeout, 0, sizeof(struct timeval));
55 memset(&m_stSendTimeout, 0, sizeof(struct timeval));
56 memset(&m_stLinger, 0, sizeof(struct linger));
57
58 switch(nType)
59 {
60 //----------------------------------------------------------------------
61 // Declare socket type stream - TCP
62 //----------------------------------------------------------------------
63 case CSimpleSocket::SocketTypeTcp:
64 {
65 m_nSocketDomain = AF_INET;
66 m_nSocketType = CSimpleSocket::SocketTypeTcp;
67 break;
68 }
69 case CSimpleSocket::SocketTypeTcp6:
70 {
71 m_nSocketDomain = AF_INET6;
72 m_nSocketType = CSimpleSocket::SocketTypeTcp6;
73 break;
74 }
75 //----------------------------------------------------------------------
76 // Declare socket type datagram - UDP
77 //----------------------------------------------------------------------
78 case CSimpleSocket::SocketTypeUdp:
79 {
80 m_nSocketDomain = AF_INET;
81 m_nSocketType = CSimpleSocket::SocketTypeUdp;
82 break;
83 }
84 case CSimpleSocket::SocketTypeUdp6:
85 {
86 m_nSocketDomain = AF_INET6;
87 m_nSocketType = CSimpleSocket::SocketTypeUdp6;
88 break;
89 }
90 //----------------------------------------------------------------------
91 // Declare socket type raw Ethernet - Ethernet
92 //----------------------------------------------------------------------
93 case CSimpleSocket::SocketTypeRaw:
94 {
95 #if defined(__linux__) && !defined(_DARWIN)
96 m_nSocketDomain = AF_PACKET;
97 m_nSocketType = CSimpleSocket::SocketTypeRaw;
98 #endif
99 #ifdef _WIN32
100 m_nSocketType = CSimpleSocket::SocketTypeInvalid;
101 #endif
102 break;
103 }
104 default:
105 m_nSocketType = CSimpleSocket::SocketTypeInvalid;
106 break;
107 }
108 }
109
110 CSimpleSocket::CSimpleSocket(CSimpleSocket &socket)
111 {
112 m_pBuffer = new uint8[socket.m_nBufferSize];
113 m_nBufferSize = socket.m_nBufferSize;
114 memcpy(m_pBuffer, socket.m_pBuffer, socket.m_nBufferSize);
115 }
116
117 CSimpleSocket *CSimpleSocket::operator=(CSimpleSocket &socket)
118 {
119 if (m_nBufferSize != socket.m_nBufferSize)
120 {
121 delete m_pBuffer;
122 m_pBuffer = new uint8[socket.m_nBufferSize];
123 m_nBufferSize = socket.m_nBufferSize;
124 memcpy(m_pBuffer, socket.m_pBuffer, socket.m_nBufferSize);
125 }
126
127 return this;
128 }
129
130
131 //------------------------------------------------------------------------------
132 //
133 // Initialize() - Initialize socket class
134 //
135 //------------------------------------------------------------------------------
136 bool CSimpleSocket::Initialize()
137 {
138 errno = CSimpleSocket::SocketSuccess;
139
140 #ifdef WIN32
141 //-------------------------------------------------------------------------
142 // Data structure containing general Windows Sockets Info
143 //-------------------------------------------------------------------------
144 memset(&m_hWSAData, 0, sizeof(m_hWSAData));
145 WSAStartup(MAKEWORD(2, 0), &m_hWSAData);
146 #endif
147
148 //-------------------------------------------------------------------------
149 // Create the basic Socket Handle
150 //-------------------------------------------------------------------------
151 m_timer.Initialize();
152 m_timer.SetStartTime();
153 m_socket = socket(m_nSocketDomain, m_nSocketType, 0);
154 m_timer.SetEndTime();
155
156 TranslateSocketError();
157
158 return (IsSocketValid());
159 }
160
161
162 //------------------------------------------------------------------------------
163 //
164 // BindInterface()
165 //
166 //------------------------------------------------------------------------------
167 bool CSimpleSocket::BindInterface(const char *pInterface)
168 {
169 bool bRetVal = false;
170 struct in_addr stInterfaceAddr;
171
172 if (GetMulticast() == true)
173 {
174 if (pInterface)
175 {
176 stInterfaceAddr.s_addr= inet_addr(pInterface);
177 if (SETSOCKOPT(m_socket, IPPROTO_IP, IP_MULTICAST_IF, &stInterfaceAddr, sizeof(stInterfaceAddr)) == SocketSuccess)
178 {
179 bRetVal = true;
180 }
181 }
182 }
183 else
184 {
185 SetSocketError(CSimpleSocket::SocketProtocolError);
186 }
187
188 return bRetVal;
189 }
190
191
192 //------------------------------------------------------------------------------
193 //
194 // SetMulticast()
195 //
196 //------------------------------------------------------------------------------
197 bool CSimpleSocket::SetMulticast(bool bEnable, uint8 multicastTTL)
198 {
199 bool bRetVal = false;
200
201 if (GetSocketType() == CSimpleSocket::SocketTypeUdp)
202 {
203 m_bIsMulticast = bEnable;
204 if (SETSOCKOPT(m_socket, IPPROTO_IP, IP_MULTICAST_TTL, (void *)&multicastTTL, sizeof(multicastTTL)) == SocketError)
205 {
206 TranslateSocketError();
207 bRetVal = false;
208 }
209 else
210 {
211 bRetVal = true;
212 }
213 }
214 else
215 {
216 m_socketErrno = CSimpleSocket::SocketProtocolError;
217 }
218
219 return bRetVal;
220 }
221
222
223 //------------------------------------------------------------------------------
224 //
225 // SetSocketDscp()
226 //
227 //------------------------------------------------------------------------------
228 bool CSimpleSocket::SetSocketDscp(int32 nDscp)
229 {
230 bool bRetVal = true;
231 int32 nTempVal = nDscp;
232
233 nTempVal <<= 4;
234 nTempVal /= 4;
235
236 if (IsSocketValid())
237 {
238 if (SETSOCKOPT(m_socket, IPPROTO_IP, IP_TOS, &nTempVal, sizeof(nTempVal)) == SocketError)
239 {
240 TranslateSocketError();
241 bRetVal = false;
242 }
243 }
244
245 return bRetVal;
246 }
247
248
249 //------------------------------------------------------------------------------
250 //
251 // GetSocketDscp()
252 //
253 //------------------------------------------------------------------------------
254 int32 CSimpleSocket::GetSocketDscp(void)
255 {
256 int32 nTempVal = 0;
257 socklen_t nLen = 0;
258
259 if (IsSocketValid())
260 {
261 if (GETSOCKOPT(m_socket, IPPROTO_IP, IP_TOS, &nTempVal, &nLen) == SocketError)
262 {
263 TranslateSocketError();
264 }
265
266 nTempVal *= 4;
267 nTempVal >>= 4;
268 }
269
270 return nTempVal;
271 }
272
273
274 //------------------------------------------------------------------------------
275 //
276 // GetWindowSize()
277 //
278 //------------------------------------------------------------------------------
279 uint32 CSimpleSocket::GetWindowSize(uint32 nOptionName)
280 {
281 uint32 nTcpWinSize = 0;
282
283 //-------------------------------------------------------------------------
284 // no socket given, return system default allocate our own new socket
285 //-------------------------------------------------------------------------
286 if (m_socket != CSimpleSocket::SocketError)
287 {
288 socklen_t nLen = sizeof(nTcpWinSize);
289
290 //---------------------------------------------------------------------
291 // query for buffer size
292 //---------------------------------------------------------------------
293 GETSOCKOPT(m_socket, SOL_SOCKET, nOptionName, &nTcpWinSize, &nLen);
294 TranslateSocketError();
295 }
296 else
297 {
298 SetSocketError(CSimpleSocket::SocketInvalidSocket);
299 }
300
301 return nTcpWinSize;
302 }
303
304
305 //------------------------------------------------------------------------------
306 //
307 // SetWindowSize()
308 //
309 //------------------------------------------------------------------------------
310 uint32 CSimpleSocket::SetWindowSize(uint32 nOptionName, uint32 nWindowSize)
311 {
312 //-------------------------------------------------------------------------
313 // no socket given, return system default allocate our own new socket
314 //-------------------------------------------------------------------------
315 if (m_socket != CSimpleSocket::SocketError)
316 {
317 SETSOCKOPT(m_socket, SOL_SOCKET, nOptionName, &nWindowSize, sizeof(nWindowSize));
318 TranslateSocketError();
319 }
320 else
321 {
322 SetSocketError(CSimpleSocket::SocketInvalidSocket);
323 }
324
325 return nWindowSize;
326 }
327
328
329 //------------------------------------------------------------------------------
330 //
331 // DisableNagleAlgorithm()
332 //
333 //------------------------------------------------------------------------------
334 bool CSimpleSocket::DisableNagleAlgoritm()
335 {
336 bool bRetVal = false;
337 int32 nTcpNoDelay = 1;
338
339 //----------------------------------------------------------------------
340 // Set TCP NoDelay flag to true
341 //----------------------------------------------------------------------
342 if (SETSOCKOPT(m_socket, IPPROTO_TCP, TCP_NODELAY, &nTcpNoDelay, sizeof(int32)) == 0)
343 {
344 bRetVal = true;
345 }
346
347 TranslateSocketError();
348
349 return bRetVal;
350 }
351
352
353 //------------------------------------------------------------------------------
354 //
355 // EnableNagleAlgorithm()
356 //
357 //------------------------------------------------------------------------------
358 bool CSimpleSocket::EnableNagleAlgoritm()
359 {
360 bool bRetVal = false;
361 int32 nTcpNoDelay = 0;
362
363 //----------------------------------------------------------------------
364 // Set TCP NoDelay flag to false
365 //----------------------------------------------------------------------
366 if (SETSOCKOPT(m_socket, IPPROTO_TCP, TCP_NODELAY, &nTcpNoDelay, sizeof(int32)) == 0)
367 {
368 bRetVal = true;
369 }
370
371 TranslateSocketError();
372
373 return bRetVal;
374 }
375
376
377 //------------------------------------------------------------------------------
378 //
379 // Send() - Send data on a valid socket
380 //
381 //------------------------------------------------------------------------------
382 int32 CSimpleSocket::Send(const uint8 *pBuf, size_t bytesToSend)
383 {
384 SetSocketError(SocketSuccess);
385 m_nBytesSent = 0;
386
387 switch(m_nSocketType)
388 {
389 case CSimpleSocket::SocketTypeTcp:
390 {
391 if (IsSocketValid())
392 {
393 if ((bytesToSend > 0) && (pBuf != NULL))
394 {
395 m_timer.Initialize();
396 m_timer.SetStartTime();
397
398 //---------------------------------------------------------
399 // Check error condition and attempt to resend if call
400 // was interrupted by a signal.
401 //---------------------------------------------------------
402 do
403 {
404 m_nBytesSent = SEND(m_socket, pBuf, bytesToSend, 0);
405 TranslateSocketError();
406 } while (GetSocketError() == CSimpleSocket::SocketInterrupted);
407
408 m_timer.SetEndTime();
409 }
410 }
411 break;
412 }
413 case CSimpleSocket::SocketTypeUdp:
414 {
415 if (IsSocketValid())
416 {
417 if ((bytesToSend > 0) && (pBuf != NULL))
418 {
419 m_timer.Initialize();
420 m_timer.SetStartTime();
421
422 //---------------------------------------------------------
423 // Check error condition and attempt to resend if call
424 // was interrupted by a signal.
425 //---------------------------------------------------------
426 // if (GetMulticast())
427 // {
428 // do
429 // {
430 // m_nBytesSent = SENDTO(m_socket, pBuf, bytesToSend, 0, (const sockaddr *)&m_stMulticastGroup,
431 // sizeof(m_stMulticastGroup));
432 // TranslateSocketError();
433 // } while (GetSocketError() == CSimpleSocket::SocketInterrupted);
434 // }
435 // else
436 {
437 do
438 {
439 m_nBytesSent = SENDTO(m_socket, pBuf, bytesToSend, 0, (const sockaddr *)&m_stServerSockaddr, sizeof(m_stServerSockaddr));
440 TranslateSocketError();
441 } while (GetSocketError() == CSimpleSocket::SocketInterrupted);
442 }
443
444 m_timer.SetEndTime();
445 }
446 }
447 break;
448 }
449 default:
450 break;
451 }
452
453 return m_nBytesSent;
454 }
455
456
457 //------------------------------------------------------------------------------
458 //
459 // Close() - Close socket and free up any memory allocated for the socket
460 //
461 //------------------------------------------------------------------------------
462 bool CSimpleSocket::Close(void)
463 {
464 bool bRetVal = false;
465
466 //--------------------------------------------------------------------------
467 // delete internal buffer
468 //--------------------------------------------------------------------------
469 if (m_pBuffer != NULL)
470 {
471 delete [] m_pBuffer;
472 m_pBuffer = NULL;
473 }
474
475 //--------------------------------------------------------------------------
476 // if socket handle is currently valid, close and then invalidate
477 //--------------------------------------------------------------------------
478 if (IsSocketValid())
479 {
480 if (CLOSE(m_socket) != CSimpleSocket::SocketError)
481 {
482 m_socket = INVALID_SOCKET;
483 bRetVal = true;
484 }
485 }
486
487 TranslateSocketError();
488
489 return bRetVal;
490 }
491
492
493 //------------------------------------------------------------------------------
494 //
495 // Shtudown()
496 //
497 //------------------------------------------------------------------------------
498 bool CSimpleSocket::Shutdown(CShutdownMode nShutdown)
499 {
500 CSocketError nRetVal = SocketEunknown;
501
502 nRetVal = (CSocketError)shutdown(m_socket, CSimpleSocket::Sends);
503 TranslateSocketError();
504
505 return (nRetVal == CSimpleSocket::SocketSuccess) ? true: false;
506 }
507
508
509 //------------------------------------------------------------------------------
510 //
511 // Flush()
512 //
513 //------------------------------------------------------------------------------
514 bool CSimpleSocket::Flush()
515 {
516 int32 nTcpNoDelay = 1;
517 int32 nCurFlags = 0;
518 uint8 tmpbuf = 0;
519 bool bRetVal = false;
520
521 //--------------------------------------------------------------------------
522 // Get the current setting of the TCP_NODELAY flag.
523 //--------------------------------------------------------------------------
524 if (GETSOCKOPT(m_socket, IPPROTO_TCP, TCP_NODELAY, &nCurFlags, sizeof(int32)) == 0)
525 {
526 //----------------------------------------------------------------------
527 // Set TCP NoDelay flag
528 //----------------------------------------------------------------------
529 if (SETSOCKOPT(m_socket, IPPROTO_TCP, TCP_NODELAY, &nTcpNoDelay, sizeof(int32)) == 0)
530 {
531 //------------------------------------------------------------------
532 // Send empty byte stream to flush the TCP send buffer
533 //------------------------------------------------------------------
534 if (Send(&tmpbuf, 0) != CSimpleSocket::SocketError)
535 {
536 bRetVal = true;
537 }
538
539 TranslateSocketError();
540 }
541
542 //----------------------------------------------------------------------
543 // Reset the TCP_NODELAY flag to original state.
544 //----------------------------------------------------------------------
545 SETSOCKOPT(m_socket, IPPROTO_TCP, TCP_NODELAY, &nCurFlags, sizeof(int32));
546 }
547
548 return bRetVal;
549 }
550
551
552 //------------------------------------------------------------------------------
553 //
554 // Writev -
555 //
556 //------------------------------------------------------------------------------
557 int32 CSimpleSocket::Writev(const struct iovec *pVector, size_t nCount)
558 {
559 int32 nBytes = 0;
560 int32 nBytesSent = 0;
561 int32 i = 0;
562
563 //--------------------------------------------------------------------------
564 // Send each buffer as a separate send, windows does not support this
565 // function call.
566 //--------------------------------------------------------------------------
567 for (i = 0; i < (int32)nCount; i++)
568 {
569 if ((nBytes = Send((uint8 *)pVector[i].iov_base, pVector[i].iov_len)) == CSimpleSocket::SocketError)
570 {
571 break;
572 }
573
574 nBytesSent += nBytes;
575 }
576
577 if (i > 0)
578 {
579 Flush();
580 }
581
582 return nBytesSent;
583 }
584
585
586 //------------------------------------------------------------------------------
587 //
588 // Send() - Send data on a valid socket via a vector of buffers.
589 //
590 //------------------------------------------------------------------------------
591 int32 CSimpleSocket::Send(const struct iovec *sendVector, int32 nNumItems)
592 {
593 SetSocketError(SocketSuccess);
594 m_nBytesSent = 0;
595
596 if ((m_nBytesSent = WRITEV(m_socket, sendVector, nNumItems)) == CSimpleSocket::SocketError)
597 {
598 TranslateSocketError();
599 }
600
601 return m_nBytesSent;
602 }
603
604
605 //------------------------------------------------------------------------------
606 //
607 // SetReceiveTimeout()
608 //
609 //------------------------------------------------------------------------------
610 bool CSimpleSocket::SetReceiveTimeout(int32 nRecvTimeoutSec, int32 nRecvTimeoutUsec)
611 {
612 bool bRetVal = true;
613
614 memset(&m_stRecvTimeout, 0, sizeof(struct timeval));
615
616 m_stRecvTimeout.tv_sec = nRecvTimeoutSec;
617 m_stRecvTimeout.tv_usec = nRecvTimeoutUsec;
618
619 //--------------------------------------------------------------------------
620 // Sanity check to make sure the options are supported!
621 //--------------------------------------------------------------------------
622 if (SETSOCKOPT(m_socket, SOL_SOCKET, SO_RCVTIMEO, &m_stRecvTimeout,
623 sizeof(struct timeval)) == CSimpleSocket::SocketError)
624 {
625 bRetVal = false;
626 TranslateSocketError();
627 }
628
629 return bRetVal;
630 }
631
632
633 //------------------------------------------------------------------------------
634 //
635 // SetSendTimeout()
636 //
637 //------------------------------------------------------------------------------
638 bool CSimpleSocket::SetSendTimeout(int32 nSendTimeoutSec, int32 nSendTimeoutUsec)
639 {
640 bool bRetVal = true;
641
642 memset(&m_stSendTimeout, 0, sizeof(struct timeval));
643 m_stSendTimeout.tv_sec = nSendTimeoutSec;
644 m_stSendTimeout.tv_usec = nSendTimeoutUsec;
645
646 //--------------------------------------------------------------------------
647 // Sanity check to make sure the options are supported!
648 //--------------------------------------------------------------------------
649 if (SETSOCKOPT(m_socket, SOL_SOCKET, SO_SNDTIMEO, &m_stSendTimeout,
650 sizeof(struct timeval)) == CSimpleSocket::SocketError)
651 {
652 bRetVal = false;
653 TranslateSocketError();
654 }
655
656 return bRetVal;
657 }
658
659
660 //------------------------------------------------------------------------------
661 //
662 // SetOptionReuseAddr()
663 //
664 //------------------------------------------------------------------------------
665 bool CSimpleSocket::SetOptionReuseAddr()
666 {
667 bool bRetVal = false;
668 int32 nReuse = IPTOS_LOWDELAY;
669
670 if (SETSOCKOPT(m_socket, SOL_SOCKET, SO_REUSEADDR, (char*)&nReuse, sizeof(int32)) == 0)
671 {
672 bRetVal = true;
673 }
674
675 TranslateSocketError();
676
677 return bRetVal;
678 }
679
680
681 //------------------------------------------------------------------------------
682 //
683 // SetOptionLinger()
684 //
685 //------------------------------------------------------------------------------
686 bool CSimpleSocket::SetOptionLinger(bool bEnable, uint16 nTime)
687 {
688 bool bRetVal = false;
689
690 m_stLinger.l_onoff = (bEnable == true) ? 1: 0;
691 m_stLinger.l_linger = nTime;
692
693 if (SETSOCKOPT(m_socket, SOL_SOCKET, SO_LINGER, &m_stLinger, sizeof(m_stLinger)) == 0)
694 {
695 bRetVal = true;
696 }
697
698 TranslateSocketError();
699
700 return bRetVal;
701 }
702
703
704 //------------------------------------------------------------------------------
705 //
706 // Receive() - Attempts to receive a block of data on an established
707 // connection. Data is received in an internal buffer managed
708 // by the class. This buffer is only valid until the next call
709 // to Receive(), a call to Close(), or until the object goes out
710 // of scope.
711 //
712 //------------------------------------------------------------------------------
713 int32 CSimpleSocket::Receive(int32 nMaxBytes, uint8 * pBuffer )
714 {
715 m_nBytesReceived = 0;
716
717 //--------------------------------------------------------------------------
718 // If the socket is invalid then return false.
719 //--------------------------------------------------------------------------
720 if (IsSocketValid() == false)
721 {
722 return m_nBytesReceived;
723 }
724
725 uint8 * pWorkBuffer = pBuffer;
726 if ( pBuffer == NULL )
727 {
728 //--------------------------------------------------------------------------
729 // Free existing buffer and allocate a new buffer the size of
730 // nMaxBytes.
731 //--------------------------------------------------------------------------
732 if ((m_pBuffer != NULL) && (nMaxBytes != m_nBufferSize))
733 {
734 delete [] m_pBuffer;
735 m_pBuffer = NULL;
736 }
737
738 //--------------------------------------------------------------------------
739 // Allocate a new internal buffer to receive data.
740 //--------------------------------------------------------------------------
741 if (m_pBuffer == NULL)
742 {
743 m_nBufferSize = nMaxBytes;
744 m_pBuffer = new uint8[nMaxBytes];
745 }
746
747 pWorkBuffer = m_pBuffer;
748 }
749
750 SetSocketError(SocketSuccess);
751
752 m_timer.Initialize();
753 m_timer.SetStartTime();
754
755 switch (m_nSocketType)
756 {
757 //----------------------------------------------------------------------
758 // If zero bytes are received, then return. If SocketERROR is
759 // received, free buffer and return CSocket::SocketError (-1) to caller.
760 //----------------------------------------------------------------------
761 case CSimpleSocket::SocketTypeTcp:
762 {
763 do
764 {
765 m_nBytesReceived = RECV(m_socket, (pWorkBuffer + m_nBytesReceived),
766 nMaxBytes, m_nFlags);
767 TranslateSocketError();
768 } while ((GetSocketError() == CSimpleSocket::SocketInterrupted));
769
770 break;
771 }
772 case CSimpleSocket::SocketTypeUdp:
773 {
774 uint32 srcSize;
775
776 srcSize = sizeof(struct sockaddr_in);
777
778 if (GetMulticast() == true)
779 {
780 do
781 {
782 m_nBytesReceived = RECVFROM(m_socket, pWorkBuffer, nMaxBytes, 0,
783 &m_stMulticastGroup, &srcSize);
784 TranslateSocketError();
785 } while (GetSocketError() == CSimpleSocket::SocketInterrupted);
786 }
787 else
788 {
789 do
790 {
791 m_nBytesReceived = RECVFROM(m_socket, pWorkBuffer, nMaxBytes, 0,
792 &m_stClientSockaddr, &srcSize);
793 TranslateSocketError();
794 } while (GetSocketError() == CSimpleSocket::SocketInterrupted);
795 }
796
797 break;
798 }
799 default:
800 break;
801 }
802
803 m_timer.SetEndTime();
804 TranslateSocketError();
805
806 //--------------------------------------------------------------------------
807 // If we encounter an error translate the error code and return. One
808 // possible error code could be EAGAIN (EWOULDBLOCK) if the socket is
809 // non-blocking. This does not mean there is an error, but no data is
810 // yet available on the socket.
811 //--------------------------------------------------------------------------
812 if (m_nBytesReceived == CSimpleSocket::SocketError)
813 {
814 if (m_pBuffer != NULL)
815 {
816 delete [] m_pBuffer;
817 m_pBuffer = NULL;
818 }
819 }
820
821 return m_nBytesReceived;
822 }
823
824
825 //------------------------------------------------------------------------------
826 //
827 // SetNonblocking()
828 //
829 //------------------------------------------------------------------------------
830 bool CSimpleSocket::SetNonblocking(void)
831 {
832 int32 nCurFlags;
833
834 #if WIN32
835 nCurFlags = 1;
836
837 if (ioctlsocket(m_socket, FIONBIO, (ULONG *)&nCurFlags) != 0)
838 {
839 TranslateSocketError();
840 return false;
841 }
842 #else
843 if ((nCurFlags = fcntl(m_socket, F_GETFL)) < 0)
844 {
845 TranslateSocketError();
846 return false;
847 }
848
849 nCurFlags |= O_NONBLOCK;
850
851 if (fcntl(m_socket, F_SETFL, nCurFlags) != 0)
852 {
853 TranslateSocketError();
854 return false;
855 }
856 #endif
857
858 m_bIsBlocking = false;
859
860 return true;
861 }
862
863
864 //------------------------------------------------------------------------------
865 //
866 // SetBlocking()
867 //
868 //------------------------------------------------------------------------------
869 bool CSimpleSocket::SetBlocking(void)
870 {
871 int32 nCurFlags;
872
873 #if WIN32
874 nCurFlags = 0;
875
876 if (ioctlsocket(m_socket, FIONBIO, (ULONG *)&nCurFlags) != 0)
877 {
878 return false;
879 }
880 #else
881 if ((nCurFlags = fcntl(m_socket, F_GETFL)) < 0)
882 {
883 TranslateSocketError();
884 return false;
885 }
886
887 nCurFlags &= (~O_NONBLOCK);
888
889 if (fcntl(m_socket, F_SETFL, nCurFlags) != 0)
890 {
891 TranslateSocketError();
892 return false;
893 }
894 #endif
895 m_bIsBlocking = true;
896
897 return true;
898 }
899
900
901 //------------------------------------------------------------------------------
902 //
903 // SendFile() - stands-in for system provided sendfile
904 //
905 //------------------------------------------------------------------------------
906 int32 CSimpleSocket::SendFile(int32 nOutFd, int32 nInFd, off_t *pOffset, int32 nCount)
907 {
908 int32 nOutCount = CSimpleSocket::SocketError;
909
910 static char szData[SOCKET_SENDFILE_BLOCKSIZE];
911 int32 nInCount = 0;
912
913 if (LSEEK(nInFd, *pOffset, SEEK_SET) == -1)
914 {
915 return -1;
916 }
917
918 while (nOutCount < nCount)
919 {
920 nInCount = (nCount - nOutCount) < SOCKET_SENDFILE_BLOCKSIZE ? (nCount - nOutCount) : SOCKET_SENDFILE_BLOCKSIZE;
921
922 if ((FREAD(nInFd, szData, nInCount)) != (int32)nInCount)
923 {
924 return -1;
925 }
926
927 if ((SEND(nOutFd, szData, nInCount, 0)) != (int32)nInCount)
928 {
929 return -1;
930 }
931
932 nOutCount += nInCount;
933 }
934
935 *pOffset += nOutCount;
936
937 TranslateSocketError();
938
939 return nOutCount;
940 }
941
942
943 //------------------------------------------------------------------------------
944 //
945 // TranslateSocketError() -
946 //
947 //------------------------------------------------------------------------------
948 void CSimpleSocket::TranslateSocketError(void)
949 {
950 #if defined(__linux__) || defined(_DARWIN)
951 switch (errno)
952 {
953 case EXIT_SUCCESS:
954 SetSocketError(CSimpleSocket::SocketSuccess);
955 break;
956 case ENOTCONN:
957 SetSocketError(CSimpleSocket::SocketNotconnected);
958 break;
959 case ENOTSOCK:
960 case EBADF:
961 case EACCES:
962 case EAFNOSUPPORT:
963 case EMFILE:
964 case ENFILE:
965 case ENOBUFS:
966 case ENOMEM:
967 case EPROTONOSUPPORT:
968 case EPIPE:
969 case EOPNOTSUPP:
970 SetSocketError(CSimpleSocket::SocketInvalidSocket);
971 break;
972 case ECONNREFUSED :
973 SetSocketError(CSimpleSocket::SocketConnectionRefused);
974 break;
975 case ETIMEDOUT:
976 SetSocketError(CSimpleSocket::SocketTimedout);
977 break;
978 case EINPROGRESS:
979 SetSocketError(CSimpleSocket::SocketEinprogress);
980 break;
981 case EWOULDBLOCK:
982 // case EAGAIN:
983 SetSocketError(CSimpleSocket::SocketEwouldblock);
984 break;
985 case EINTR:
986 SetSocketError(CSimpleSocket::SocketInterrupted);
987 break;
988 case ECONNABORTED:
989 SetSocketError(CSimpleSocket::SocketConnectionAborted);
990 break;
991 case EINVAL:
992 case EPROTO:
993 SetSocketError(CSimpleSocket::SocketProtocolError);
994 break;
995 case EPERM:
996 SetSocketError(CSimpleSocket::SocketFirewallError);
997 break;
998 case EFAULT:
999 SetSocketError(CSimpleSocket::SocketInvalidSocketBuffer);
1000 break;
1001 case ECONNRESET:
1002 case ENOPROTOOPT:
1003 SetSocketError(CSimpleSocket::SocketConnectionReset);
1004 break;
1005 case EADDRINUSE:
1006 SetSocketError(CSimpleSocket::SocketAddressInUse);
1007 break;
1008 default:
1009 SetSocketError(CSimpleSocket::SocketEunknown);
1010 break;
1011 }
1012 #endif
1013 #ifdef WIN32
1014 int32 nError = WSAGetLastError();
1015 switch (nError)
1016 {
1017 case EXIT_SUCCESS:
1018 SetSocketError(CSimpleSocket::SocketSuccess);
1019 break;
1020 case WSAEBADF:
1021 case WSAENOTCONN:
1022 SetSocketError(CSimpleSocket::SocketNotconnected);
1023 break;
1024 case WSAEINTR:
1025 SetSocketError(CSimpleSocket::SocketInterrupted);
1026 break;
1027 case WSAEACCES:
1028 case WSAEAFNOSUPPORT:
1029 case WSAEINVAL:
1030 case WSAEMFILE:
1031 case WSAENOBUFS:
1032 case WSAEPROTONOSUPPORT:
1033 SetSocketError(CSimpleSocket::SocketInvalidSocket);
1034 break;
1035 case WSAECONNREFUSED :
1036 SetSocketError(CSimpleSocket::SocketConnectionRefused);
1037 break;
1038 case WSAETIMEDOUT:
1039 SetSocketError(CSimpleSocket::SocketTimedout);
1040 break;
1041 case WSAEINPROGRESS:
1042 SetSocketError(CSimpleSocket::SocketEinprogress);
1043 break;
1044 case WSAECONNABORTED:
1045 SetSocketError(CSimpleSocket::SocketConnectionAborted);
1046 break;
1047 case WSAEWOULDBLOCK:
1048 SetSocketError(CSimpleSocket::SocketEwouldblock);
1049 break;
1050 case WSAENOTSOCK:
1051 SetSocketError(CSimpleSocket::SocketInvalidSocket);
1052 break;
1053 case WSAECONNRESET:
1054 SetSocketError(CSimpleSocket::SocketConnectionReset);
1055 break;
1056 case WSANO_DATA:
1057 SetSocketError(CSimpleSocket::SocketInvalidAddress);
1058 break;
1059 case WSAEADDRINUSE:
1060 SetSocketError(CSimpleSocket::SocketAddressInUse);
1061 break;
1062 case WSAEFAULT:
1063 SetSocketError(CSimpleSocket::SocketInvalidPointer);
1064 break;
1065 default:
1066 SetSocketError(CSimpleSocket::SocketEunknown);
1067 break;
1068 }
1069 #endif
1070 }
1071
1072 //------------------------------------------------------------------------------
1073 //
1074 // DescribeError()
1075 //
1076 //------------------------------------------------------------------------------
1077
1078 const char *CSimpleSocket::DescribeError(CSocketError err)
1079 {
1080 switch (err) {
1081 case CSimpleSocket::SocketError:
1082 return "Generic socket error translates to error below.";
1083 case CSimpleSocket::SocketSuccess:
1084 return "No socket error.";
1085 case CSimpleSocket::SocketInvalidSocket:
1086 return "Invalid socket handle.";
1087 case CSimpleSocket::SocketInvalidAddress:
1088 return "Invalid destination address specified.";
1089 case CSimpleSocket::SocketInvalidPort:
1090 return "Invalid destination port specified.";
1091 case CSimpleSocket::SocketConnectionRefused:
1092 return "No server is listening at remote address.";
1093 case CSimpleSocket::SocketTimedout:
1094 return "Timed out while attempting operation.";
1095 case CSimpleSocket::SocketEwouldblock:
1096 return "Operation would block if socket were blocking.";
1097 case CSimpleSocket::SocketNotconnected:
1098 return "Currently not connected.";
1099 case CSimpleSocket::SocketEinprogress:
1100 return "Socket is non-blocking and the connection cannot be completed immediately";
1101 case CSimpleSocket::SocketInterrupted:
1102 return "Call was interrupted by a signal that was caught before a valid connection arrived.";
1103 case CSimpleSocket::SocketConnectionAborted:
1104 return "The connection has been aborted.";
1105 case CSimpleSocket::SocketProtocolError:
1106 return "Invalid protocol for operation.";
1107 case CSimpleSocket::SocketFirewallError:
1108 return "Firewall rules forbid connection.";
1109 case CSimpleSocket::SocketInvalidSocketBuffer:
1110 return "The receive buffer point outside the process's address space.";
1111 case CSimpleSocket::SocketConnectionReset:
1112 return "Connection was forcibly closed by the remote host.";
1113 case CSimpleSocket::SocketAddressInUse:
1114 return "Address already in use.";
1115 case CSimpleSocket::SocketInvalidPointer:
1116 return "Pointer type supplied as argument is invalid.";
1117 case CSimpleSocket::SocketEunknown:
1118 return "Unknown error";
1119 default:
1120 return "No such CSimpleSocket error";
1121 }
1122 }
1123
1124 //------------------------------------------------------------------------------
1125 //
1126 // Select()
1127 //
1128 //------------------------------------------------------------------------------
1129 bool CSimpleSocket::Select(int32 nTimeoutSec, int32 nTimeoutUSec)
1130 {
1131 bool bRetVal = false;
1132 struct timeval *pTimeout = NULL;
1133 struct timeval timeout;
1134 int32 nNumDescriptors = -1;
1135 int32 nError = 0;
1136
1137 FD_ZERO(&m_errorFds);
1138 FD_ZERO(&m_readFds);
1139 FD_ZERO(&m_writeFds);
1140 FD_SET(m_socket, &m_errorFds);
1141 FD_SET(m_socket, &m_readFds);
1142 FD_SET(m_socket, &m_writeFds);
1143
1144 //---------------------------------------------------------------------
1145 // If timeout has been specified then set value, otherwise set timeout
1146 // to NULL which will block until a descriptor is ready for read/write
1147 // or an error has occurred.
1148 //---------------------------------------------------------------------
1149 if ((nTimeoutSec > 0) || (nTimeoutUSec > 0))
1150 {
1151 timeout.tv_sec = nTimeoutSec;
1152 timeout.tv_usec = nTimeoutUSec;
1153 pTimeout = &timeout;
1154 }
1155
1156 nNumDescriptors = SELECT(m_socket+1, &m_readFds, &m_writeFds, &m_errorFds, pTimeout);
1157 // nNumDescriptors = SELECT(m_socket+1, &m_readFds, NULL, NULL, pTimeout);
1158
1159 //----------------------------------------------------------------------
1160 // Handle timeout
1161 //----------------------------------------------------------------------
1162 if (nNumDescriptors == 0)
1163 {
1164 SetSocketError(CSimpleSocket::SocketTimedout);
1165 }
1166 //----------------------------------------------------------------------
1167 // If a file descriptor (read/write) is set then check the
1168 // socket error (SO_ERROR) to see if there is a pending error.
1169 //----------------------------------------------------------------------
1170 else if ((FD_ISSET(m_socket, &m_readFds)) || (FD_ISSET(m_socket, &m_writeFds)))
1171 {
1172 int32 nLen = sizeof(nError);
1173
1174 if (GETSOCKOPT(m_socket, SOL_SOCKET, SO_ERROR, &nError, &nLen) == 0)
1175 {
1176 errno = nError;
1177
1178 if (nError == 0)
1179 {
1180 bRetVal = true;
1181 }
1182 }
1183
1184 TranslateSocketError();
1185 }
1186
1187 return bRetVal;
1188 }
1189