Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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