BSocket.h 17 KB

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