Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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