Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

networking.hpp 28KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. // networking.hpp
  2. // Copyright (C) 2006-2009 MicroNeil Research Corporation.
  3. //
  4. // This program is part of the MicroNeil Research Open Library Project. For
  5. // more information go to http://www.microneil.com/OpenLibrary/index.html
  6. //
  7. // This program is free software; you can redistribute it and/or modify it
  8. // under the terms of the GNU General Public License as published by the
  9. // Free Software Foundation; either version 2 of the License, or (at your
  10. // option) any later version.
  11. //
  12. // This program is distributed in the hope that it will be useful, but WITHOUT
  13. // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  14. // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  15. // more details.
  16. //
  17. // You should have received a copy of the GNU General Public License along with
  18. // this program; if not, write to the Free Software Foundation, Inc., 59 Temple
  19. // Place, Suite 330, Boston, MA 02111-1307 USA
  20. //==============================================================================
  21. // The networking module abstracts network communications and provides a set
  22. // of objects for handling most tasks.
  23. // 20080313 _M Refactored to throw proper runtime_error exceptions.
  24. // Include only once...
  25. #ifndef M_Networking
  26. #define M_Networking
  27. #include <stdexcept>
  28. #include <iostream>
  29. #include <string>
  30. #include <sstream>
  31. #include <cstring>
  32. using namespace std;
  33. #include <cstdlib>
  34. #include <cstdio>
  35. #include <cerrno>
  36. //// Platform specific includes...
  37. #if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64)
  38. //// Windows headers...
  39. #include <winsock2.h>
  40. typedef int socklen_t; // Posix uses socklen_t so we mimic it.
  41. typedef SOCKET hSocket; // Winx handles Socket is opaque.
  42. #else
  43. //// GNU Headers...
  44. #include <netdb.h>
  45. #include <sys/socket.h>
  46. #include <netinet/in.h>
  47. #include <sys/file.h>
  48. #include <arpa/inet.h>
  49. #include <unistd.h>
  50. #include <fcntl.h>
  51. typedef int hSocket; // *nix uses int to handle a Socket.
  52. const hSocket INVALID_SOCKET = -1; // -1 is the invalid Socket.
  53. #endif
  54. //// Handling SIGPIPE //////////////////////////////////////////////////////////
  55. #ifndef MSG_NOSIGNAL
  56. const int MSG_NOSIGNAL = 0; // Fake this if it isn't defined.
  57. #endif
  58. #ifndef SO_NOSIGPIPE
  59. const int SO_NOSIGPIPE = 0; // Fake this if it isn't defined.
  60. #endif
  61. //// Tuning and Constants //////////////////////////////////////////////////////
  62. const unsigned long LOCALHOST = 0x7F000001; // 127.0.0.1 as an integer.
  63. const int DefaultMaxPending = 5; // Default connection queue size.
  64. const int TCPClientBufferSize = 4096; // TCP Client buffer size.
  65. const int TCPHostBufferSize = 4096; // TCP Host buffer size.
  66. const int NOFLAGS = 0; // Magic number for no flags.
  67. ////////////////////////////////////////////////////////////////////////////////
  68. // IP4address class
  69. //
  70. // The IP4address class makes it easy to manipulate IPs.
  71. class IP4Address { // IP4Address manipulator.
  72. private:
  73. unsigned long int IP; // The actual data.
  74. public:
  75. IP4Address(); // Blank constructor IP = 0.0.0.0
  76. IP4Address(const unsigned long int newIP); // Constructor given unsigned long
  77. IP4Address(const IP4Address&); // Constructor given an IP4Address
  78. IP4Address(const char* newIP); // Construcing with a cstring.
  79. IP4Address(const string& newIP); // Constructing with a cppstring.
  80. IP4Address& operator=(const unsigned long int Right); // Convert from unsigned long int.
  81. IP4Address& operator=(const char* Right); // Convert from c string.
  82. IP4Address& operator=(const string& Right); // Convert from cpp string.
  83. operator unsigned long int() const;
  84. operator string() const;
  85. bool operator<(const IP4Address Right) const; // < Comparison.
  86. bool operator>(const IP4Address Right) const; // > Comparison.
  87. bool operator==(const IP4Address Right) const; // == Comparison.
  88. bool operator!=(const IP4Address Right) const; // != Comparison.
  89. bool operator<=(const IP4Address Right) const; // <= Comparison.
  90. bool operator>=(const IP4Address Right) const; // >= Comparison.
  91. };
  92. /* static unsigned long int&
  93. operator=(unsigned long int& Out, const IP4Address& In); // Assign to unsigned long
  94. static string&
  95. operator=(string& Out, const IP4Address& In); // Assign to cpp string
  96. */
  97. ////////////////////////////////////////////////////////////////////////////////
  98. // Network Core class
  99. //
  100. // The Networking class acts as a central point for setup, cleanup, and access
  101. // to network services. For example, when using WinSock, the DLL initialization
  102. // must occur once when the program starts up and the shutdown must occur once
  103. // as the program shuts down. The constructor and destructor of the "Network"
  104. // instances of this class handles that work. There should only be one instance
  105. // of this class anywhere in the program and that instance is created when this
  106. // module is included. DON'T MAKE MORE INSTANCES OF THIS :-)
  107. //
  108. // Part of the reason for this class is to handle all of the cross-platform
  109. // weirdness involved in handling sockets and conversions. This way all of the
  110. // ifdef switched code can be consolidated into this utility class and the
  111. // code for the remaining classes can remain nice and clean by using this
  112. // class to handle those tasks.
  113. class Networking {
  114. private:
  115. public:
  116. class NotSupportedError : public runtime_error { // Thrown when something can't be done.
  117. public: NotSupportedError(const string& w):runtime_error(w) {}
  118. };
  119. class InitializationError : public runtime_error { // Thrown if initialization fails.
  120. public: InitializationError(const string& w):runtime_error(w) {}
  121. };
  122. class ControlError : public runtime_error { // Thrown if control functions fail.
  123. public: ControlError(const string& w):runtime_error(w) {}
  124. };
  125. class SocketCreationError : public runtime_error { // Thrown if a call to socket() fails.
  126. public: SocketCreationError(const string& w):runtime_error(w) {}
  127. };
  128. class SocketSetSockOptError : public runtime_error {
  129. public: SocketSetSockOptError(const string& w):runtime_error(w) {} // Thrown if a call to setsockopt() fails.
  130. };
  131. class SocketBindError : public runtime_error { // Thrown if a call to bind() fails.
  132. public: SocketBindError(const string& w):runtime_error(w) {}
  133. };
  134. class SocketListenError : public runtime_error { // Thrown if a call to listen() fails.
  135. public: SocketListenError(const string& w):runtime_error(w) {}
  136. };
  137. class SocketConnectError : public runtime_error { // Thrown if a call to connect() fails.
  138. public: SocketConnectError(const string& w):runtime_error(w) {}
  139. };
  140. class SocketAcceptError : public runtime_error { // Thrown if a call to accept() fails.
  141. public: SocketAcceptError(const string& w):runtime_error(w) {}
  142. };
  143. class SocketReadError : public runtime_error { // Thrown if a socket read call fails.
  144. public: SocketReadError(const string& w):runtime_error(w) {}
  145. };
  146. class SocketWriteError : public runtime_error { // Thrown if a socket write call fails.
  147. public: SocketWriteError(const string& w):runtime_error(w) {}
  148. };
  149. static string DescriptiveError(string Msg, int Errno); // Form a descriptive error w/ errno.
  150. Networking();
  151. ~Networking();
  152. int getLastError(); // WSAGetLastError or errno
  153. int setNonBlocking(hSocket socket); // Set socket to non-blocking.
  154. int closeSocket(hSocket socket); // closesocket() or close()
  155. bool WouldBlock(int ErrorCode); // ErrorCode matches [WSA]EWOULDBLOCK
  156. bool InProgress(int ErrorCode); // ErrorCode matches [WSA]EINPROGRESS
  157. bool IsConnected(int ErrorCode); // ErrorCode matches [WSA]EISCONN
  158. };
  159. extern Networking Network; // There is ONE Network object ;-)
  160. // End of Network Core Class
  161. ////////////////////////////////////////////////////////////////////////////////
  162. ////////////////////////////////////////////////////////////////////////////////
  163. // SocketName class
  164. // This class represents a communications end-point on a TCP/IP network. All
  165. // conversions from/to strings and for byte orders are handled in this class
  166. // as well as lookups for ports/services and IPaddresses/host-names.
  167. //
  168. // Note that the cstring conversions expect the buffer to be large enough.
  169. const int IPStringBufferSize = 40; // Safe size for IP as text conversion.
  170. const int PortStringBufferSize = 20; // Safe size for Port as text conversion.
  171. class SocketAddress {
  172. private:
  173. struct sockaddr_in Address; // Socket address structure.
  174. char IPStringBuffer[IPStringBufferSize]; // Handy conversion buffer.
  175. char PortStringBuffer[PortStringBufferSize]; // Handy conversion buffer.
  176. public:
  177. SocketAddress(); // Constructor sets ANY address.
  178. struct sockaddr_in* getPtr_sockaddr_in(); // Returns a pointer to sockaddr_in.
  179. struct sockaddr* getPtr_sockaddr(); // Returns a pointer to sockaddr.
  180. socklen_t getAddressSize(); // How big is that structure anyway?
  181. void setAddress(unsigned long ipAddress); // Set the IP address from an unsigned int
  182. void setAddress(char* ipString); // Set the IP address from a cstring
  183. unsigned long getAddress(); // Get the IP address as an unsigned int
  184. const char* getAddress(char* str); // Get the IP address into a cstring
  185. void getAddress(int& a0, int& a1, int& a2, int& a3); // Get the IP address into 4 ints
  186. void setPort(unsigned short port); // Set the port address from an int
  187. void setPort(char* port); // Set the port address from a cstring
  188. unsigned short getPort(); // Get the port address as an unsigned int
  189. const char* getPort(char* str); // Get the port address into a cstring
  190. void clear(); // Initialize the address.
  191. };
  192. // End of SocketName class
  193. ////////////////////////////////////////////////////////////////////////////////
  194. ////////////////////////////////////////////////////////////////////////////////
  195. // Socket class
  196. // This class abstracts the underlying socket and adds some functionality
  197. // for this module. The derived class is expected to setup the socket before
  198. // it can be opened. In fact, the derivative class must provide the open()
  199. // function :-) Open is expected to call socket, bind it, and set the socket
  200. // into the appropriate mode for it's use in the derived object.
  201. class Socket {
  202. protected:
  203. hSocket Handle; // Our socket handle.
  204. bool NonBlocking; // True if the socket is NonBlocking.
  205. bool ReuseAddress; // True if SO_REUSEADDR should be used.
  206. bool OpenSucceeded; // Successful open occurred.
  207. int LastError; // Last error result for this socket.
  208. SocketAddress LocalAddress; // Our local address data.
  209. SocketAddress RemoteAddress; // Our remote address data.
  210. public:
  211. Socket(); // Constructor sets initial state.
  212. virtual ~Socket(); // Destructor closes Socket if open.
  213. hSocket getHandle(); // Returns the current SocketId.
  214. bool isNonBlocking(); // Returns true if socket is NonBlocking
  215. void makeNonBlocking(); // Sets the socket to NonBlocking mode.
  216. bool isReuseAddress(); // True if socket is set SO_REUSEADDR.
  217. bool isReuseAddress(bool set); // Changes SO_REUSEADDR setting.
  218. bool isOpen(); // True if the socket is open.
  219. int getLastError(); // Returns the last error for this socket.
  220. virtual void open() = 0; // Derived class specifies open();
  221. void close(); // Close politely.
  222. };
  223. // End of Socket class
  224. ////////////////////////////////////////////////////////////////////////////////
  225. ////////////////////////////////////////////////////////////////////////////////
  226. // MessagePort class
  227. // Interface that Sends and Receives messages - possibly a bit at a time. This
  228. // interface standardizes things so that multiple technologies can go beneith
  229. // such as UNIX domain pipes or named pipes or sockets etc. There is also a
  230. // special function to improve the efficiency of delimited transfers (such as
  231. // email). The function checks for the delimited byte inside an optimized loop
  232. // so that the port doesn't have to be read one byte at a time by the caller.
  233. // In the case of non-blocking ports, these methods may return before all of
  234. // the data has been transferred. In these cases the caller is expected to know
  235. // if it's got the complete message and is expected to repeat it's call until
  236. // it does.
  237. class MessagePort {
  238. public:
  239. virtual bool isNonBlocking() = 0; // True if we should expect partial xfrs.
  240. virtual int transmit(const char* bfr, int size) = 0; // How to send a buffer of data.
  241. virtual int receive(char* bfr, int size) = 0; // How to receive a buffer of data.
  242. virtual int delimited_receive(char* bfr, int size, char delimiter) = 0; // How to receive delimited data.
  243. };
  244. ////////////////////////////////////////////////////////////////////////////////
  245. // Message class
  246. // This is a base class for representing messages that are sent to or received
  247. // from MessagePorts. The basic Message has 3 modes. Unfixed width, fixed width,
  248. // or delimeted. More complex messaging schemes can be built up from these
  249. // basics. A message must know how to send and recieve itself using the
  250. // MessagePort API and must be able to indicate if the latest transfer request
  251. // is complete or needs to be continued. The MessagePort may be blocking or
  252. // non-blocking. If it is blocking then a writeTo() or readFrom() operation
  253. // should not return until the transfer is completed. If the MessagePort is in
  254. // a non-blocking mode then writeTo() and readFrom() will do as much as they
  255. // can before returning but if the transfer was not completed then the app
  256. // lication may need to transferMore().
  257. class Message {
  258. char* Data; // Pointer to message data.
  259. int DataBufferSize; // Size of buffer to hold data.
  260. int DataSize; // Size of Data.
  261. char* RWPointer; // RW position in buffer.
  262. bool TransferInProgress; // True if read or write is not complete.
  263. bool Delimited; // Delimited Message Flag.
  264. char Delimiter; // Delimiter character.
  265. public:
  266. /** All of this is yet to be built! **/
  267. Message(const Message& M); // Copy constructor.
  268. Message(int Size); // Construct empty of Size.
  269. Message(int Size, char Delimiter); // Construct empty with delimiter.
  270. Message(char* NewData, int Size); // Construct non-delimited message.
  271. Message(char* NewData, int Size, char Delimiter); // Construct delimited message.
  272. void writeTo(MessagePort &P); // Initiate an outbound transfer.
  273. void readFrom(MessagePort &P); // Initiate an inbound transfer.
  274. bool isBusy(); // True if the transfer isn't complete.
  275. void transferMore(); // Do more of the transfer.
  276. void abortTransfer(); // Forget about the transfer.
  277. bool isDelimited(); // True if the message is delimited.
  278. char getDelimiter(); // Read the delimiter cahracter.
  279. char* getData(); // Access the data buffer.
  280. int getDataSize(); // How much data is there.
  281. };
  282. // End of Message class
  283. ////////////////////////////////////////////////////////////////////////////////
  284. ////////////////////////////////////////////////////////////////////////////////
  285. // TCPListener class
  286. // This class represents a local socket used to listen for new connections. The
  287. // application can poll this object for new inbound connections which are then
  288. // delivered as TCPClient objects.
  289. class TCPClient; // Hint about the coming client class.
  290. class TCPListener : public Socket {
  291. private:
  292. bool OpenStage1Complete; // First stage of open() complete.
  293. bool OpenStage2Complete; // Second stage of open() complete.
  294. public:
  295. TCPListener(unsigned short Port); // Set up localhost on this Port.
  296. TCPListener(SocketAddress& WhereToBind); // Set up specific "name" for listening.
  297. ~TCPListener(); // Close when destructing.
  298. int MaxPending; // Maximum inbound connection queue.
  299. virtual void open(); // Open when ready.
  300. TCPClient* acceptClient(); // Accept a client connection.
  301. };
  302. // End of TCPListener class
  303. ////////////////////////////////////////////////////////////////////////////////
  304. ////////////////////////////////////////////////////////////////////////////////
  305. // TCPClient class
  306. // This class represents a TCP network client connection. It is created by
  307. // a TCPListener object if/when a TCP connection is made to the Listener and
  308. // accepted by the application.
  309. class TCPClient : public Socket, public MessagePort {
  310. private:
  311. TCPListener& MyListener;
  312. char ReadBuffer[TCPClientBufferSize]; // Buffer for delimited reading.
  313. char* ReadPointer; // Read position.
  314. int DataLength; // Length of data in buffer.
  315. bool ReadBufferIsEmpty(); // True if DataLength is zero.
  316. void fillReadBuffer(); // Fill the ReadBuffer from the socket.
  317. public:
  318. TCPClient(TCPListener& L, hSocket H, SocketAddress& A); // How to create a TCPClient.
  319. ~TCPClient(); // Destructor for cleanup.
  320. TCPListener& getMyListener(); // Where did I come from?
  321. bool isNonBlocking(); // Provided for MessagePort.
  322. virtual int transmit(const char* bfr, int size); // How to send a buffer of data.
  323. virtual int receive(char* bfr, int size); // How to receive a buffer of data.
  324. virtual int delimited_receive(char* bfr, int size, char delimiter); // How to receive delimited data.
  325. virtual void open(); // We provide open() as unsupported.
  326. unsigned long getRemoteIP(); // Get remote IP as long.
  327. const char* getRemoteIP(char* str); // Get IP as string.
  328. unsigned short getRemotePort(); // Get remote Port as unsigned short.
  329. const char* getRemotePort(char* str); // Get Port as string.
  330. };
  331. // End of TCPClient class
  332. ////////////////////////////////////////////////////////////////////////////////
  333. ////////////////////////////////////////////////////////////////////////////////
  334. // TCPHost class
  335. // This class represents a TCP network server connection. A client application
  336. // creates this object when it wants to connect to a given TCP service.
  337. class TCPHost : public Socket, public MessagePort {
  338. private:
  339. char ReadBuffer[TCPHostBufferSize]; // Buffer for delimited reading.
  340. char* ReadPointer; // Read position.
  341. int DataLength; // Length of data in buffer.
  342. bool ReadBufferIsEmpty(); // True if DataLength is zero.
  343. void fillReadBuffer(); // Fill the ReadBuffer from the socket.
  344. bool OpenStage1Complete; // Skip stage 1 of open() after done.
  345. public:
  346. TCPHost(unsigned short Port); // Will connect to localhost on Port.
  347. TCPHost(SocketAddress& Remote); // Will connect to Remote address/port.
  348. // TCPHost(SocketAddress& Local, SocketAddress& Remote); // Will connect to Remote from Local.
  349. ~TCPHost(); // Clean up when we go away.
  350. bool isNonBlocking(); // Provided for MessagePort.
  351. virtual int transmit(const char* bfr, int size); // How to send a buffer of data.
  352. virtual int receive(char* bfr, int size); // How to receive a buffer of data.
  353. virtual int delimited_receive(char* bfr, int size, char delimiter); // How to receive delimited data.
  354. virtual void open(); // We provide open().
  355. };
  356. // End of TCPHost class
  357. ////////////////////////////////////////////////////////////////////////////////
  358. ////////////////////////////////////////////////////////////////////////////////
  359. // UDPListener class
  360. // This class represents a local UPD port set up to listen for UDP requests. In
  361. // this case, each UDP packet that arrives is assumed to be a single request so
  362. // for each a UDPRequest object is created that links back to this Listener.
  363. // The application can then use that UDPRequest to .respond() with a Message.
  364. // the response is sent back to the original requester and the UDPRequest is
  365. // considered satisfied.
  366. class UDPListener : public Socket {
  367. };
  368. // End of UDPListener class
  369. ////////////////////////////////////////////////////////////////////////////////
  370. ////////////////////////////////////////////////////////////////////////////////
  371. // UDPRequest class
  372. // This class is created by a UDPListener when a packet is received. The object
  373. // contains all of the necessary information about the source for the request
  374. // so that the application can .respond() to them through this object. The
  375. // response UDP packtes are sent through the UDPListener socket.
  376. class UDPRequest : public MessagePort {
  377. };
  378. // End of UDPRequest class
  379. ////////////////////////////////////////////////////////////////////////////////
  380. ////////////////////////////////////////////////////////////////////////////////
  381. // UDPHost class
  382. // This class represents a server/host on the network that uses the UDP
  383. // protocol. The application can use this object to send a .request() Message
  384. // and getReply(). Each request becomes a UDP packet. Each received UDP packet
  385. // from the specified UDPHost becomes a reply Message. (Connected UDP socket).
  386. class UDPHost : public Socket, public MessagePort {
  387. };
  388. // End of UDPHost class
  389. ////////////////////////////////////////////////////////////////////////////////
  390. ////////////////////////////////////////////////////////////////////////////////
  391. // UDPReceiver class
  392. // This class is used to receive UDP packets on a particular port, but does not
  393. // create UDPRequest objects from them - they are considered to be simply
  394. // Messages. A UDPReceiver is most likely to be used in ad-hoc networking and
  395. // to receive advertisements and/or broadcasts from other peers.
  396. class UDPReceiver : public Socket, public MessagePort {
  397. };
  398. // End of UDPReceiver class
  399. ////////////////////////////////////////////////////////////////////////////////
  400. ////////////////////////////////////////////////////////////////////////////////
  401. // UDPBroadcaster class
  402. // This class is used to advertise / broadcast Messages using UDP.
  403. class UDPBroadcaster : public Socket, public MessagePort {
  404. };
  405. // End of UDPBroadcaster class
  406. ////////////////////////////////////////////////////////////////////////////////
  407. //// Include Inline methods and functions...
  408. #include "networking.inline.hpp"
  409. #endif
  410. // End include Networking.hpp only once...