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

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