BSocket.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. /**
  2. * @file BSocket.h
  3. * @author Ambroz Bizjak <ambrop7@gmail.com>
  4. *
  5. * @section LICENSE
  6. *
  7. * This file is part of BadVPN.
  8. *
  9. * BadVPN is free software: you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License version 2
  11. * as published by the Free Software Foundation.
  12. *
  13. * BadVPN is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License along
  19. * with this program; if not, write to the Free Software Foundation, Inc.,
  20. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  21. *
  22. * @section DESCRIPTION
  23. *
  24. * A wrapper around OS-specific socket functions, integrated into
  25. * the event system.
  26. */
  27. #ifndef BADVPN_SYSTEM_BSOCKET_H
  28. #define BADVPN_SYSTEM_BSOCKET_H
  29. #ifdef BADVPN_USE_WINAPI
  30. #include <winsock2.h>
  31. #include <misc/mswsock.h>
  32. #endif
  33. #include <misc/debug.h>
  34. #include <system/BAddr.h>
  35. #include <system/BReactor.h>
  36. #include <system/DebugObject.h>
  37. #include <system/BPending.h>
  38. // errors
  39. #define BSOCKET_ERROR_NONE 0
  40. #define BSOCKET_ERROR_UNKNOWN 1
  41. #define BSOCKET_ERROR_LATER 2
  42. #define BSOCKET_ERROR_IN_PROGRESS 3
  43. #define BSOCKET_ERROR_ACCESS_DENIED 4
  44. #define BSOCKET_ERROR_ADDRESS_NOT_AVAILABLE 5
  45. #define BSOCKET_ERROR_ADDRESS_IN_USE 6
  46. #define BSOCKET_ERROR_CONNECTION_REFUSED 7
  47. #define BSOCKET_ERROR_CONNECTION_TIMED_OUT 8
  48. #define BSOCKET_ERROR_CONNECTION_RESET 9
  49. #define BSOCKET_ERROR_NETWORK_UNREACHABLE 10
  50. #define BSOCKET_ERROR_NO_MEMORY 11
  51. // socket types
  52. #define BSOCKET_TYPE_STREAM 1
  53. #define BSOCKET_TYPE_DGRAM 2
  54. // socket events
  55. #define BSOCKET_READ (1 << 0)
  56. #define BSOCKET_WRITE (1 << 1)
  57. #define BSOCKET_ACCEPT (1 << 2)
  58. #define BSOCKET_CONNECT (1 << 3)
  59. #define BSOCKET_ERROR (1 << 4)
  60. #define BSOCKET_NUM_EVENTS 5
  61. // default backlog if backlog is <0
  62. #define BSOCKET_DEFAULT_BACKLOG 128
  63. // default limit for number of consecutive receive operations
  64. // must be -1 (no limit) or >0
  65. #define BSOCKET_DEFAULT_RECV_MAX 2
  66. struct BSocket_t;
  67. /**
  68. * Handler function called when an event is detected on the socket.
  69. *
  70. * If the socket does not have a global event handler registered:
  71. * The event parameter is the event that was detected.
  72. * It is guaranteed that that the corresponding event handler is registered
  73. * and the event is enabled.
  74. *
  75. * If the socket has a global event handler registered:
  76. * The event parameter is a bitmask of detected events. It is guaranteed
  77. * that it is a subset of enabled events, and contains at least one event.
  78. *
  79. * It is guaranteed that the handler returns control to the reactor immediately.
  80. *
  81. * @param user as in {@link BSocket_AddEventHandler} or {@link BSocket_AddGlobalEventHandler}
  82. * @param event events that were detected, see above
  83. */
  84. typedef void (*BSocket_handler) (void *user, int event);
  85. /**
  86. * A wrapper around OS-specific socket functions, integrated into
  87. * the event system.
  88. *
  89. * To simplify implementation, most functions just call the corresponding
  90. * socket function. Only required and most common errors are translated.
  91. */
  92. typedef struct BSocket_t {
  93. DebugObject d_obj;
  94. BReactor *bsys;
  95. int type;
  96. int domain;
  97. int socket;
  98. int error;
  99. BSocket_handler global_handler;
  100. void *global_handler_user;
  101. BSocket_handler handlers[BSOCKET_NUM_EVENTS];
  102. void *handlers_user[BSOCKET_NUM_EVENTS];
  103. uint8_t waitEvents;
  104. int connecting_status; // 0 not connecting, 1 connecting, 2 finished
  105. int connecting_result;
  106. int recv_max;
  107. int recv_num;
  108. // event dispatching
  109. int ready_events;
  110. int current_event_index;
  111. BPending job;
  112. BPending connect_job;
  113. #ifdef BADVPN_USE_WINAPI
  114. WSAEVENT event;
  115. BHandle bhandle;
  116. LPFN_WSASENDMSG WSASendMsg;
  117. LPFN_WSARECVMSG WSARecvMsg;
  118. #else
  119. BFileDescriptor fd;
  120. #endif
  121. } BSocket;
  122. /**
  123. * Initializes global socket data.
  124. * This must be called once in program before sockets are used.
  125. *
  126. * @return 0 for success, -1 for failure
  127. */
  128. int BSocket_GlobalInit (void) WARN_UNUSED;
  129. /**
  130. * Initializes a socket.
  131. *
  132. * @param bs the object
  133. * @param bsys {@link BReactor} to operate in
  134. * @param domain domain (same as address type). Must be one of BADDR_TYPE_IPV4, BADDR_TYPE_IPV6
  135. * and BADDR_TYPE_UNIX (non-Windows only).
  136. * @param type socket type. Must be one of BSOCKET_TYPE_STREAM and BSOCKET_TYPE_DGRAM.
  137. * @return 0 for success,
  138. * -1 for failure
  139. */
  140. int BSocket_Init (BSocket *bs, BReactor *bsys, int domain, int type) WARN_UNUSED;
  141. /**
  142. * Frees a socket.
  143. *
  144. * @param bs the object
  145. */
  146. void BSocket_Free (BSocket *bs);
  147. /**
  148. * Sets the maximum number of consecutive receive operations.
  149. * This limit prevents starvation that might occur when data is being
  150. * received on a socket faster than in can be processed.
  151. * The default limit is BSOCKET_DEFAULT_RECV_MAX.
  152. *
  153. * @param bs the object
  154. * @param max number of consecutive receive operations allowed. Muse be >0,
  155. * or -1 for no limit.
  156. */
  157. void BSocket_SetRecvMax (BSocket *bs, int max);
  158. /**
  159. * Returns the socket's current error code.
  160. *
  161. * @param bs the object
  162. */
  163. int BSocket_GetError (BSocket *bs);
  164. /**
  165. * Registers a socket-global event handler.
  166. * The socket-global event handler must not be registered.
  167. * No event-specific handlers must be registered.
  168. * When the handler is invoked, it is passed a bitmask of events
  169. * that occured, instead of a single event.
  170. *
  171. * @param bs the object
  172. * @param handler event handler
  173. * @param user value to be passed to event handler
  174. */
  175. void BSocket_AddGlobalEventHandler (BSocket *bs, BSocket_handler handler, void *user);
  176. /**
  177. * Unregisters the socket-global event handler.
  178. * The socket-global event handler must be registered.
  179. *
  180. * @param bs the object
  181. * @param handler event handler
  182. * @param user value to be passed to event handler
  183. */
  184. void BSocket_RemoveGlobalEventHandler (BSocket *bs);
  185. /**
  186. * Sets events for the socket-global event handler.
  187. * The socket-global event handler must be registered.
  188. *
  189. * @param bs the object
  190. * @param events bitmask containing socket events the user is interested in
  191. */
  192. void BSocket_SetGlobalEvents (BSocket *bs, int events);
  193. /**
  194. * Registers an event handler for a socket event.
  195. * When the handler is registered, the corresponding event will
  196. * initially be disabled.
  197. * The event must be valid and must not have a handler.
  198. * The socket-global event handler must not be registered.
  199. *
  200. * @param bs the object
  201. * @param event event to register handler for
  202. * @param handler event handler
  203. * @param user value to be passed to event handler
  204. */
  205. void BSocket_AddEventHandler (BSocket *bs, uint8_t event, BSocket_handler handler, void *user);
  206. /**
  207. * Unregisters an event handler for a socket event.
  208. * The event must be valid and must have a handler.
  209. *
  210. * @param bs the object
  211. * @param event event to unregister handler for
  212. */
  213. void BSocket_RemoveEventHandler (BSocket *bs, uint8_t event);
  214. /**
  215. * Enables a socket event.
  216. * The event must be valid, must not be enabled, and must have a handler.
  217. *
  218. * @param bs the object
  219. * @param event event to enable
  220. */
  221. void BSocket_EnableEvent (BSocket *bs, uint8_t event);
  222. /**
  223. * Disables a socket event.
  224. * The event must be valid, must be enabled, and must have a handler.
  225. *
  226. * @param bs the object
  227. * @param event event to enable
  228. */
  229. void BSocket_DisableEvent (BSocket *bs, uint8_t event);
  230. /**
  231. * Connects the socket to the specifed address, or starts a connection attempt.
  232. *
  233. * There must be no pending connection attempt.
  234. *
  235. * For stream sockets, the user will have to wait for the connection result. See the
  236. * BSOCKET_ERROR_IN_PROGRESS error for details.
  237. *
  238. * Datagram sockets can be connected at any time, since connecting such a socket only means
  239. * specifying an addres where datagrams will be sent and received from.
  240. * An associated address can be removed by specifying a BADDR_TYPE_NONE address.
  241. *
  242. * @param bs the object
  243. * @param addr remote address. Must not be an invalid address.
  244. * @param later if true, even if the connection succeeded right away, fail with BSOCKET_ERROR_IN_PROGRESS,
  245. * and report success in the handler. Must be 0 or 1.
  246. * @return 0 for immediate success,
  247. * -1 for failure, where the error code can be:
  248. * - BSOCKET_ERROR_IN_PROGRESS the socket is a stream socket and the connection attempt has started.
  249. * The user should wait for the BSOCKET_CONNECT event and obtain the
  250. * result of attempt with {@link BSocket_GetConnectResult}.
  251. * - BSOCKET_ERROR_UNKNOWN unhandled error
  252. */
  253. int BSocket_Connect (BSocket *bs, BAddr *addr, int later) WARN_UNUSED;
  254. /**
  255. * Retreives the result of a connection attempt.
  256. * The socket must have completed a connection attempt whose result has not yet been retrieved.
  257. *
  258. * @param bs the object
  259. * @return connection attempt result. Possible values:
  260. * - 0 connection successful
  261. * - BSOCKET_ERROR_CONNECTION_TIMED_OUT timeout while attempting connection
  262. * - BSOCKET_ERROR_CONNECTION_REFUSED no one is listening on the remote address
  263. * - BSOCKET_ERROR_UNKNOWN unhandled error
  264. */
  265. int BSocket_GetConnectResult (BSocket *bs);
  266. /**
  267. * Binds the socket to the specified address.
  268. *
  269. * @param bs the object
  270. * @param addr local address. Must not be an invalid address.
  271. * @return 0 for success,
  272. * -1 for failure, where the error code can be:
  273. * - BSOCKET_ERROR_ADDRESS_NOT_AVAILABLE the address is not a local address
  274. * - BSOCKET_ERROR_ADDRESS_IN_USE the address is already in use
  275. * - BSOCKET_ERROR_ACCESS_DENIED the address is protected
  276. * - BSOCKET_ERROR_UNKNOWN unhandled error
  277. */
  278. int BSocket_Bind (BSocket *bs, BAddr *addr) WARN_UNUSED;
  279. /**
  280. * Marks the socket as a listening socket.
  281. *
  282. * @param bs the object. Must be a BSOCKET_TYPE_STREAM socket.
  283. * @param backlog whatever this means in the system's listen() function. If it's
  284. * negative, BSOCKET_DEFAULT_BACKLOG will be used.
  285. * @return 0 for success,
  286. * -1 for failure, where the error code can be:
  287. * - BSOCKET_ERROR_ADDRESS_IN_USE the address is already in use
  288. * - BSOCKET_ERROR_UNKNOWN unhandled error
  289. */
  290. int BSocket_Listen (BSocket *bs, int backlog) WARN_UNUSED;
  291. /**
  292. * Accepts a connection on a listening socket.
  293. *
  294. * @param bs the object. Must be a BSOCKET_TYPE_STREAM socket.
  295. * @param newsock on success, the new socket will be stored here. If it is NULL and a connection
  296. * was accepted, it is closed immediately (but the function succeeds). The resulting
  297. * socket will have the same domain and type as the listening socket.
  298. * @param addr if not NULL, the client address will be stored here on success.
  299. * The returned address may be an invalid address.
  300. * @return 0 for success,
  301. * -1 for failure, where the error code can be:
  302. * - BSOCKET_ERROR_LATER a connection cannot be accepted at the moment
  303. * - BSOCKET_ERROR_UNKNOWN unhandled error
  304. */
  305. int BSocket_Accept (BSocket *bs, BSocket *newsock, BAddr *addr) WARN_UNUSED;
  306. /**
  307. * Sends data on a stream socket.
  308. *
  309. * @param bs the object. Must be a BSOCKET_TYPE_STREAM socket.
  310. * @param data buffer to read data from
  311. * @param len amount of data. Must be >=0.
  312. * @return non-negative value for amount of data sent,
  313. * -1 for failure, where the error code can be:
  314. * - BSOCKET_ERROR_LATER no data can be sent at the moment
  315. * - BSOCKET_ERROR_CONNECTION_REFUSED the remote host refused to allow the network connection.
  316. * For UDP sockets, this means the remote sent an ICMP Port Unreachable packet.
  317. * - BSOCKET_ERROR_CONNECTION_RESET connection was reset by the remote peer
  318. * - BSOCKET_ERROR_UNKNOWN unhandled error
  319. */
  320. int BSocket_Send (BSocket *bs, uint8_t *data, int len) WARN_UNUSED;
  321. /**
  322. * Receives data on a stream socket.
  323. *
  324. * @param bs the object. Must be a BSOCKET_TYPE_STREAM socket.
  325. * @param data buffer to write data to
  326. * @param len maximum amount of data to read. Must be >=0.
  327. * @return - non-negative value for amount of data read; on stream sockets the value 0
  328. * means that the peer has shutdown the connection gracefully
  329. * - -1 for failure, where the error code can be:
  330. * - BSOCKET_ERROR_LATER no data can be read at the moment
  331. * - BSOCKET_ERROR_CONNECTION_REFUSED the remote host refused to allow the network connection.
  332. * For UDP sockets, this means the remote sent an ICMP Port Unreachable packet.
  333. * - BSOCKET_ERROR_CONNECTION_RESET connection was reset by the remote peer
  334. * - BSOCKET_ERROR_UNKNOWN unhandled error
  335. */
  336. int BSocket_Recv (BSocket *bs, uint8_t *data, int len) WARN_UNUSED;
  337. /**
  338. * Sends a datagram on a datagram socket to the specified address
  339. * from the specified local source address.
  340. *
  341. * @param bs the object. Must be a BSOCKET_TYPE_DGRAM socket.
  342. * @param data buffer to read data from
  343. * @param len amount of data. Must be >=0.
  344. * @param addr remote address. Must be valid.
  345. * @param local_addr source address. Must not be NULL, but may be invalid.
  346. * @return non-negative value for amount of data sent,
  347. * -1 for failure, where the error code can be:
  348. * - BSOCKET_ERROR_LATER no data can be sent at the moment
  349. * - BSOCKET_ERROR_CONNECTION_REFUSED the remote host refused to allow the network connection.
  350. * For UDP sockets, this means the remote sent an ICMP Port Unreachable packet.
  351. * - BSOCKET_ERROR_CONNECTION_RESET connection was reset by the remote peer
  352. * - BSOCKET_ERROR_UNKNOWN unhandled error
  353. */
  354. int BSocket_SendToFrom (BSocket *bs, uint8_t *data, int len, BAddr *addr, BIPAddr *local_addr) WARN_UNUSED;
  355. /**
  356. * Receives a datagram on a datagram socket and returns the sender address
  357. * and the local destination address.
  358. *
  359. * @param bs the object. Must be a BSOCKET_TYPE_DGRAM socket.
  360. * @param data buffer to write data to
  361. * @param len maximum amount of data to read. Must be >=0.
  362. * @param addr the sender address will be stored here on success. Must not be NULL.
  363. * The returned address may be an invalid address.
  364. * @param local_addr the destination address will be stored here on success. Must not be NULL.
  365. * Returned address will be invalid if it could not be determined.
  366. * @return - non-negative value for amount of data read; on stream sockets the value 0
  367. * means that the peer has shutdown the connection gracefully
  368. * - -1 for failure, where the error code can be:
  369. * - BSOCKET_ERROR_LATER no data can be read at the moment
  370. * - BSOCKET_ERROR_CONNECTION_REFUSED a remote host refused to allow the network connection.
  371. * For UDP sockets, this means the remote sent an ICMP Port Unreachable packet.
  372. * - BSOCKET_ERROR_CONNECTION_RESET connection was reset by the remote peer
  373. * - BSOCKET_ERROR_UNKNOWN unhandled error
  374. */
  375. int BSocket_RecvFromTo (BSocket *bs, uint8_t *data, int len, BAddr *addr, BIPAddr *local_addr) WARN_UNUSED;
  376. /**
  377. * Returns the address of the remote peer.
  378. *
  379. * @param bs the object
  380. * @param addr where to store address. Must not be NULL.
  381. * The returned address may be an invalid address.
  382. * @return 0 for success, -1 for failure
  383. */
  384. int BSocket_GetPeerName (BSocket *bs, BAddr *addr) WARN_UNUSED;
  385. #ifndef BADVPN_USE_WINAPI
  386. /**
  387. * Binds the unix socket to the specified path.
  388. *
  389. * @param bs the object
  390. * @param path path to bind to
  391. * @return 0 for success, -1 for failure
  392. */
  393. int BSocket_BindUnix (BSocket *bs, const char *path) WARN_UNUSED;
  394. /**
  395. * Connects the unix socket to the specified path.
  396. *
  397. * @param bs the object
  398. * @param path path to connect to
  399. * @return 0 for success, -1 for failure
  400. */
  401. int BSocket_ConnectUnix (BSocket *bs, const char *path) WARN_UNUSED;
  402. #endif
  403. /**
  404. * Returns the {@link BReactor} of this socket.
  405. *
  406. * @param bs the object
  407. * @return {@link BReactor} of this socket
  408. */
  409. BReactor * BSocket_Reactor (BSocket *bs);
  410. /**
  411. * Returns the underlying file descriptor of the socket.
  412. *
  413. * @param bs the object
  414. * @return file descriptor
  415. */
  416. int BSocket_SockFd (BSocket *bs);
  417. #endif