選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

networking.hpp 28KB

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