Debian Codegraph @

protolib/include/protoSocket.h

raw
1 #ifndef _PROTO_SOCKET
2 #define _PROTO_SOCKET
3
4 #include "protoAddress.h"
5 #include "protoDebug.h" // temp
6 #include "protoNotify.h"
7
8 #ifdef WIN32
9 /*#ifdef _WIN32_WCE
10 #ifndef LPGUID
11 #include <guiddef.h>
12 #endif // !LPGUID
13 #endif // _WIN32_WCE*/
14 #ifndef __LPGUID_DEFINED__
15 #define __LPGUID_DEFINED__
16 typedef GUID *LPGUID;
17 #endif
18 #include <winsock2.h> // for SOCKET type, etc
19 #include <MswSock.h> // for WSARecvMsg() stuff
20 #else // !WIN32
21 #include <errno.h> // for errno
22 #include <net/if.h> // for struct ifconf
23 #include <unistd.h> // for read()
24 #include <stdio.h>
25 #endif // if/else WIN32/UNIX
26 // "RAW" is predefined IOCTL macro in Gnu/Hurd Linux
27 // so this deconflicts it for the ProtoSocket::Protocol enum
28 #ifdef RAW
29 #undef RAW
30 #endif // RAW
31 /**
32 * @class ProtoSocket
33 *
34 * @brief Network socket container class that provides
35 * consistent interface for use of operating
36 * system (or simulation environment) transport
37 * sockets. Provides support for asynchronous
38 * notification to ProtoSocket::Listeners.
39 * The ProtoSocket class may be used stand-alone, or
40 * with other classes described below. A
41 * ProtoSocket may be instantiated as either a
42 * UDP or TCP socket.
43 */
44
45 class ProtoSocket : public ProtoNotify
46 {
47 public:
48 // Type definitions
49 enum Domain
50 {
51 LOCAL,
52 IPv4,
53 IPv6
54 #ifdef SIMULATE
55 ,SIM
56 #endif // SIMULATE
57 };
58 enum Protocol {INVALID_PROTOCOL, UDP, TCP, RAW, ZMQ};
59 enum State {CLOSED, IDLE, CONNECTING, LISTENING, CONNECTED};
60
61 enum EcnStatus
62 {
63 ECN_NONE = 0x00, // not ECN-Capable
64 ECN_ECT1 = 0x01, // ECN-Capable Transport 1
65 ECN_ECT0 = 0x02, // ECN-Capable Transport 0 (old ECT)
66 ECN_CE = 0x03 // ECN "Congestion Experienced" (old CE)
67 };
68
69 enum IPv6SupportStatus
70 {
71 IPV6_UNKNOWN,
72 IPV6_UNSUPPORTED,
73 IPV6_SUPPORTED
74 };
75
76 #ifdef SIMULATE
77 class Proxy {};
78 typedef Proxy* Handle;
79 bool GetEcnStatus() const;
80 #else
81 #ifdef WIN32
82 typedef SOCKET Handle;
83 #else
84 typedef int Handle;
85 #endif // if/else WIN32/UNIX
86 #endif // if/else SIMULATE
87 static const Handle INVALID_HANDLE;
88
89 ProtoSocket(Protocol theProtocol);
90 virtual ~ProtoSocket();
91
92 // Control methods
93 bool Open(UINT16 thePort = 0,
94 ProtoAddress::Type addrType = ProtoAddress::IPv4,
95 bool bindOnOpen = true);
96 bool Bind(UINT16 thePort = 0, const ProtoAddress* localAddr = NULL);
97 bool Connect(const ProtoAddress& theAddress);
98 void Disconnect();
99 bool Listen(UINT16 thePort = 0);
100 void Ignore();
101 bool Accept(ProtoSocket* theSocket = NULL);
102 bool Shutdown();
103 void Close();
104
105 // First cut at IGMPv3 SSM support (TBD - refine this and expand platform support)
106 // On Mac OSX, only version 10.7 and later support IGMPv3
107 // and the "MCAST_JOIN_GROUP" macro definition is a "tell" for this
108 // (we _reallly_ need to go to a more sophisticated build system!)
109 #if (!defined(WIN32) && !defined(ANDROID) && (!defined(MACOSX))) || (defined(MACOSX) && defined(MCAST_JOIN_GROUP))
110 #define _PROTOSOCKET_IGMPV3_SSM
111 #endif // !WIN32 && !ANDROID && (!MACOSX || MCAST_JOIN_GROUP)
112
113 bool JoinGroup(const ProtoAddress& groupAddress,
114 const char* interfaceName = NULL,
115 const ProtoAddress* sourceAddress = NULL);
116 bool LeaveGroup(const ProtoAddress& groupAddress,
117 const char* interfaceName = NULL,
118 const ProtoAddress* sourceAddress = NULL);
119
120 bool SetRawProtocol(Protocol theProtocol);
121
122 void SetState(State st){state = st;} // JPH 7/14/06 - for tcp development testing
123 #ifdef WIN32
124 void SetClosing(bool status) {closing = status;}
125 bool IsClosing() const {return closing;}
126 #endif // WIN32
127 // Status methods
128 Domain GetDomain() const {return domain;}
129 ProtoAddress::Type GetAddressType();
130 Protocol GetProtocol() const {return protocol;}
131 State GetState() const {return state;}
132 Handle GetHandle() const {return handle;}
133 UINT16 GetPort() const {return port < 0 ? 0 : port;}
134 bool IsOpen() const {return (CLOSED != state);}
135 bool IsBound() const {return (IsOpen() ? (port >= 0) : false);}
136 bool IsConnected() const {return (CONNECTED == state);}
137 bool IsConnecting() const {return (CONNECTING == state);}
138 bool IsIdle() const {return (IDLE == state);}
139 bool IsClosed() const {return (CLOSED == state);}
140 bool IsListening() const {return (LISTENING == state);}
141 #ifdef OPNET
142 ProtoAddress& GetDestination() {return destination;}
143 #else
144 // These are valid for connected sockets only
145 const ProtoAddress& GetSourceAddr() const {return source_addr;}
146 const ProtoAddress& GetDestination() const {return destination;}
147 // I.T. helper method to set the destination on a socket after an ACCEPT.
148 void SetDestination(const ProtoAddress& theDestination)
149 {destination = theDestination;}
150 #endif // OPNET
151 #ifdef WIN32
152 HANDLE GetInputEventHandle() {return input_event_handle;}
153 HANDLE GetOutputEventHandle() {return output_event_handle;}
154 bool IsOutputReady() {return output_ready;}
155 bool IsInputReady() {return input_ready;}
156 bool IsReady() {return (input_ready || output_ready);}
157 #endif // WIN32
158 static const char* GetErrorString()
159 {
160 #ifdef WIN32
161 static char errorString[256];
162 errorString[255] = '\0';
163 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
164 FORMAT_MESSAGE_IGNORE_INSERTS,
165 NULL,
166 WSAGetLastError(),
167 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
168 (LPTSTR) errorString, 255, NULL);
169 return errorString;
170 #else
171 return strerror(errno);
172 #endif // if/else WIN32/UNIX
173 }
174
175 // Read/Write methods
176 bool SendTo(const char* buffer, unsigned int &buflen, const ProtoAddress& dstAddr);
177 bool RecvFrom(char* buffer, unsigned int& numBytes, ProtoAddress& srcAddr);
178 bool RecvFrom(char* buffer, unsigned int& numBytes, ProtoAddress& srcAddr, ProtoAddress& dstAddr);
179 bool Send(const char* buffer, unsigned int& numBytes);
180 bool Recv(char* buffer, unsigned int& numBytes);
181 #if !defined(WIN32) && !defined(SIMULATE)
182 // This was for debugging?? Remove??
183 bool Read(char* buffer, unsigned int &numBytes)
184 {
185 ssize_t result = read(handle, buffer, numBytes);
186 if (result < 0)
187 {
188 perror("read() error");
189 numBytes = 0;
190 switch (errno)
191 {
192 case EAGAIN:
193 return true;
194 default:
195 return false;
196 }
197 }
198 else
199 {
200 numBytes = (unsigned int)result;
201 return true;
202 }
203 }
204 #endif // !WIN32
205 // Attributes
206 bool SetTTL(unsigned char ttl);
207 bool SetUnicastTTL(unsigned char ttl);
208 bool SetLoopback(bool loopback);
209 bool SetBroadcast(bool broadcast);
210 bool SetFragmentation(bool enable);
211 bool SetReuse(bool reuse);
212 bool SetBindInterface(const char* interfaceName);
213 bool SetMulticastInterface(const char* interfaceName);
214 bool SetTOS(unsigned char tos);
215 bool SetEcnCapable(bool status);
216 bool SetTxBufferSize(unsigned int bufferSize);
217 unsigned int GetTxBufferSize();
218 bool SetRxBufferSize(unsigned int bufferSize);
219 unsigned int GetRxBufferSize();
220
221 void EnableRecvDstAddr();
222
223 // Helper methods
224 #ifdef HAVE_IPV6
225 static bool HostIsIPv6Capable();
226 // Temporarily retained for backward compatability
227 static bool SetHostIPv6Capable() {return true;}
228 bool SetFlowLabel(UINT32 label);
229 #endif //HAVE_IPV6
230
231 // These are some static network "helper" functions that get information
232 // about the system network devices (interfaces), addresses, etc
233 //
234 // Note that the "ProtoSocket" implementation of this is being replaced
235 // by implementation in the "ProtoNet" namespace (see "protoNet.h") and
236 // the implementations here will eventually be removed _and_ the ProtoSocket
237 // static method declarations themselves will be eventually deprecated
238 //
239 // This appends addresses of type "addrType" to the "addrList"
240 static bool GetHostAddressList(ProtoAddress::Type addrType,
241 ProtoAddressList& addrList);
242
243 static bool GetInterfaceAddressList(const char* ifName,
244 ProtoAddress::Type addrType,
245 ProtoAddressList& addrList,
246 unsigned int* ifIndex = NULL);
247
248 static bool GetInterfaceAddress(const char* ifName,
249 ProtoAddress::Type addrType,
250 ProtoAddress& theAddress,
251 unsigned int* ifIndex = NULL);
252
253 static unsigned int GetInterfaceIndices(unsigned int* indexArray, unsigned int indexArraySize);
254 static unsigned int GetInterfaceIndex(const char* interfaceName);
255 static bool FindLocalAddress(ProtoAddress::Type addrType, ProtoAddress& theAddress);
256 static bool GetInterfaceName(unsigned int index, char* buffer, unsigned int buflen);
257 static bool GetInterfaceName(const ProtoAddress& ifAddr, char* buffer, unsigned int buflen);
258
259 class Notifier
260 {
261 public:
262 virtual ~Notifier() {}
263 virtual bool UpdateSocketNotification(ProtoSocket& theSocket,
264 int notifyFlags) {return true;}
265 };
266 bool SetNotifier(ProtoSocket::Notifier* theNotifier);
267 Notifier* GetNotifier() const {return notifier;}
268
269 bool StartInputNotification();
270 void StopInputNotification();
271 bool InputNotification() const
272 {return notify_input;}
273 bool StartOutputNotification();
274 void StopOutputNotification();
275 bool OutputNotification() const
276 {return notify_output;}
277 bool StartExceptionNotification();
278 void StopExceptionNotification();
279 bool ExceptionNotification() const
280 {return notify_exception;}
281
282 void OnNotify(ProtoNotify::NotifyFlag theFlag);
283
284 enum Event {INVALID_EVENT, CONNECT, ACCEPT, SEND, RECV, DISCONNECT, ERROR_, EXCEPTION};
285
286 // NOTE: For VC++ 6.0 Debug builds, you _cannot_ use pre-compiled
287 // headers with this template code. Also, "/ZI" or "/Z7" compile options
288 // must NOT be specified. (or else VC++ 6.0 experiences an "internal compiler error")
289 // (Later Visual Studio versions have fixed this error)
290 template <class listenerType>
291 bool SetListener(listenerType* theListener, void(listenerType::*eventHandler)(ProtoSocket&, Event))
292 {
293 bool doUpdate = ((NULL != theListener) || (NULL != listener));
294 if (NULL != listener) delete listener;
295 listener = (NULL != theListener) ? new LISTENER_TYPE<listenerType>(theListener, eventHandler) : NULL;
296 bool result = (NULL != theListener) ? (NULL != listener) : true;
297 return result ? (doUpdate ? UpdateNotification() : true) : false;
298 }
299
300
301 bool HasListener()
302 {return (NULL != listener);}
303 void SetUserData(const void* userData) {user_data = userData;}
304 const void* GetUserData() {return user_data;}
305
306 /**
307 * @class List
308 *
309 * @brief A helper linked list class
310 */
311 class List
312 {
313 public:
314 List();
315 ~List();
316 void Destroy(); // deletes list Items _and_ their socket
317
318 bool AddSocket(ProtoSocket& theSocket);
319 void RemoveSocket(ProtoSocket& theSocket);
320
321 class Item;
322 Item* FindItem(const ProtoSocket& theSocket) const;
323
324 public:
325 /**
326 * @class Iterator
327 *
328 * @brief List Iterator
329 */
330 class Iterator
331 {
332 public:
333 Iterator(const List& theList);
334 const Item* GetNextItem()
335 {
336 const Item* current = next;
337 next = current ? current->GetNext() : current;
338 return current;
339 }
340 ProtoSocket* GetNextSocket()
341 {
342 const Item* nextItem = GetNextItem();
343 return nextItem ? nextItem->GetSocket() : NULL;
344 }
345
346
347 private:
348 const class Item* next;
349
350 }; // end class ProtoSocketList::Iterator
351 friend class List::Iterator;
352 /**
353 * @class Item
354 *
355 * @brief List Item
356 */
357 class Item
358 {
359 friend class List;
360 friend class Iterator;
361 public:
362 Item(ProtoSocket* theSocket);
363 ProtoSocket* GetSocket() const {return socket;}
364 const void* GetUserData() {return user_data;}
365 void SetUserData(const void* userData)
366 {user_data = userData;}
367 private:
368 Item* GetPrev() const {return prev;}
369 void SetPrev(Item* item) {prev = item;}
370 Item* GetNext() const {return next;}
371 void SetNext(Item* item) {next = item;}
372
373 ProtoSocket* socket;
374 const void* user_data;
375 Item* prev;
376 Item* next;
377 }; // end class ProtoSocketList::Item
378
379 Item* head;
380 }; // end class ProtoSocketList
381
382
383 protected:
384 /**
385 * @class Listener
386 *
387 * @brief Listens for socket activity and invokes socket event handler.
388 */
389 class Listener
390 {
391 public:
392 virtual ~Listener() {}
393 virtual void on_event(ProtoSocket& theSocket, Event theEvent) = 0;
394 virtual Listener* duplicate() = 0;
395 };
396
397 /**
398 * @class LISTENER_TYPE
399 *
400 * @brief Listener template
401 */
402 template <class listenerType>
403 class LISTENER_TYPE : public Listener
404 {
405 public:
406 LISTENER_TYPE(listenerType* theListener,
407 void(listenerType::*eventHandler)(ProtoSocket&, Event))
408 : listener(theListener), event_handler(eventHandler) {}
409 void on_event(ProtoSocket& theSocket, Event theEvent)
410 {(listener->*event_handler)(theSocket, theEvent);}
411 Listener* duplicate()
412 {return (static_cast<Listener*>(new LISTENER_TYPE<listenerType>(listener, event_handler)));}
413 private:
414 listenerType* listener;
415 void(listenerType::*event_handler)(ProtoSocket&, Event);
416 };
417 virtual bool SetBlocking(bool blocking);
418 bool UpdateNotification();
419
420 Domain domain;
421 Protocol protocol;
422 Protocol raw_protocol; // only applies to raw sockets
423 State state;
424 Handle handle;
425 int port;
426 UINT8 tos; // IPv4 TOS or IPv6 traffic class
427 bool ecn_capable;
428 bool ip_recvdstaddr; // set "true" if RecvFrom() w/ destAddr is invoked
429 #ifdef HAVE_IPV6
430 UINT32 flow_label; // IPv6 flow label
431 #endif // HAVE_IPV6
432 // These cache the "getsockname()" source/dest for connected/accepted sockets
433 // TBD - perhaps should have "GetLocalAddress()" and "GetRemoteAddress()" methods instead?
434 // althought the cached information is useful for post-mortem (closure) purposes
435 ProtoAddress source_addr; // connected/accepted local address/port
436 ProtoAddress destination; // connected/accepted destination address/port
437
438 Notifier* notifier;
439 bool notify_output;
440 bool notify_input;
441 bool notify_exception;
442 #ifdef WIN32
443 HANDLE input_event_handle;
444 HANDLE output_event_handle;
445 bool output_ready; // used to morph edge triggered Win32 sockets to level-triggered behavior
446 bool input_ready; // used to morph edge triggered Win32 sockets to level-triggered behavior
447 bool closing;
448 #endif // WIN32
449 Listener* listener;
450
451 const void* user_data;
452
453 private:
454 static const int IFBUFSIZ = 256; // for GetHostAddressList
455 static const int IFIDXSIZ = 256; // "
456 #ifdef WIN32
457 static LPFN_WSARECVMSG WSARecvMsg;
458 #else
459 static int GetInterfaceList(struct ifconf& conf); // helper fn
460 #endif // if/else WIN32
461
462 static IPv6SupportStatus ipv6_support_status;
463
464 }; // end class ProtoSocket
465
466 #endif // _PROTO_SOCKET