socket_windows.odin 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. #+build windows
  2. package net
  3. /*
  4. Package net implements cross-platform Berkeley Sockets, DNS resolution and associated procedures.
  5. For other protocols and their features, see subdirectories of this package.
  6. */
  7. /*
  8. Copyright 2022 Tetralux <[email protected]>
  9. Copyright 2022 Colin Davidson <[email protected]>
  10. Copyright 2022 Jeroen van Rijn <[email protected]>.
  11. Copyright 2024 Feoramund <[email protected]>.
  12. Made available under Odin's BSD-3 license.
  13. List of contributors:
  14. Tetralux: Initial implementation
  15. Colin Davidson: Linux platform code, OSX platform code, Odin-native DNS resolver
  16. Jeroen van Rijn: Cross platform unification, code style, documentation
  17. Feoramund: FreeBSD platform code
  18. */
  19. import "core:c"
  20. import win "core:sys/windows"
  21. import "core:time"
  22. Socket_Option :: enum c.int {
  23. // bool: Whether the address that this socket is bound to can be reused by other sockets.
  24. // This allows you to bypass the cooldown period if a program dies while the socket is bound.
  25. Reuse_Address = win.SO_REUSEADDR,
  26. // bool: Whether other programs will be inhibited from binding the same endpoint as this socket.
  27. Exclusive_Addr_Use = win.SO_EXCLUSIVEADDRUSE,
  28. // bool: When true, keepalive packets will be automatically be sent for this connection. TODO: verify this understanding
  29. Keep_Alive = win.SO_KEEPALIVE,
  30. // bool: When true, client connections will immediately be sent a TCP/IP RST response, rather than being accepted.
  31. Conditional_Accept = win.SO_CONDITIONAL_ACCEPT,
  32. // bool: If true, when the socket is closed, but data is still waiting to be sent, discard that data.
  33. Dont_Linger = win.SO_DONTLINGER,
  34. // bool: When true, 'out-of-band' data sent over the socket will be read by a normal net.recv() call, the same as normal 'in-band' data.
  35. Out_Of_Bounds_Data_Inline = win.SO_OOBINLINE,
  36. // bool: When true, disables send-coalescing, therefore reducing latency.
  37. TCP_Nodelay = win.TCP_NODELAY,
  38. // win.LINGER: Customizes how long (if at all) the socket will remain open when there
  39. // is some remaining data waiting to be sent, and net.close() is called.
  40. Linger = win.SO_LINGER,
  41. // win.DWORD: The size, in bytes, of the OS-managed receive-buffer for this socket.
  42. Receive_Buffer_Size = win.SO_RCVBUF,
  43. // win.DWORD: The size, in bytes, of the OS-managed send-buffer for this socket.
  44. Send_Buffer_Size = win.SO_SNDBUF,
  45. // win.DWORD: For blocking sockets, the time in milliseconds to wait for incoming data to be received, before giving up and returning .Timeout.
  46. // For non-blocking sockets, ignored.
  47. // Use a value of zero to potentially wait forever.
  48. Receive_Timeout = win.SO_RCVTIMEO,
  49. // win.DWORD: For blocking sockets, the time in milliseconds to wait for outgoing data to be sent, before giving up and returning .Timeout.
  50. // For non-blocking sockets, ignored.
  51. // Use a value of zero to potentially wait forever.
  52. Send_Timeout = win.SO_SNDTIMEO,
  53. // bool: Allow sending to, receiving from, and binding to, a broadcast address.
  54. Broadcast = win.SO_BROADCAST,
  55. }
  56. Shutdown_Manner :: enum c.int {
  57. Receive = win.SD_RECEIVE,
  58. Send = win.SD_SEND,
  59. Both = win.SD_BOTH,
  60. }
  61. @(init, private)
  62. ensure_winsock_initialized :: proc "contextless" () {
  63. win.ensure_winsock_initialized()
  64. }
  65. @(private)
  66. _create_socket :: proc(family: Address_Family, protocol: Socket_Protocol) -> (socket: Any_Socket, err: Create_Socket_Error) {
  67. c_type, c_protocol, c_family: c.int
  68. switch family {
  69. case .IP4: c_family = win.AF_INET
  70. case .IP6: c_family = win.AF_INET6
  71. case:
  72. unreachable()
  73. }
  74. switch protocol {
  75. case .TCP: c_type = win.SOCK_STREAM; c_protocol = win.IPPROTO_TCP
  76. case .UDP: c_type = win.SOCK_DGRAM; c_protocol = win.IPPROTO_UDP
  77. case:
  78. unreachable()
  79. }
  80. sock := win.socket(c_family, c_type, c_protocol)
  81. if sock == win.INVALID_SOCKET {
  82. err = _create_socket_error()
  83. return
  84. }
  85. switch protocol {
  86. case .TCP: return TCP_Socket(sock), nil
  87. case .UDP: return UDP_Socket(sock), nil
  88. case:
  89. unreachable()
  90. }
  91. }
  92. @(private)
  93. _dial_tcp_from_endpoint :: proc(endpoint: Endpoint, options := DEFAULT_TCP_OPTIONS) -> (socket: TCP_Socket, err: Network_Error) {
  94. if endpoint.port == 0 {
  95. err = .Port_Required
  96. return
  97. }
  98. family := family_from_endpoint(endpoint)
  99. sock := create_socket(family, .TCP) or_return
  100. socket = sock.(TCP_Socket)
  101. // NOTE(tetra): This is so that if we crash while the socket is open, we can
  102. // bypass the cooldown period, and allow the next run of the program to
  103. // use the same address immediately.
  104. _ = set_option(socket, .Reuse_Address, true)
  105. sockaddr := _endpoint_to_sockaddr(endpoint)
  106. res := win.connect(win.SOCKET(socket), &sockaddr, size_of(sockaddr))
  107. if res < 0 {
  108. err = _dial_error()
  109. close(socket)
  110. return {}, err
  111. }
  112. if options.no_delay {
  113. _ = set_option(sock, .TCP_Nodelay, true) // NOTE(tetra): Not vital to succeed; error ignored
  114. }
  115. return
  116. }
  117. @(private)
  118. _bind :: proc(socket: Any_Socket, ep: Endpoint) -> (err: Bind_Error) {
  119. sockaddr := _endpoint_to_sockaddr(ep)
  120. sock := any_socket_to_socket(socket)
  121. res := win.bind(win.SOCKET(sock), &sockaddr, size_of(sockaddr))
  122. if res < 0 {
  123. err = _bind_error()
  124. }
  125. return
  126. }
  127. @(private)
  128. _listen_tcp :: proc(interface_endpoint: Endpoint, backlog := 1000) -> (socket: TCP_Socket, err: Network_Error) {
  129. family := family_from_endpoint(interface_endpoint)
  130. sock := create_socket(family, .TCP) or_return
  131. socket = sock.(TCP_Socket)
  132. defer if err != nil { close(socket) }
  133. // NOTE(tetra): While I'm not 100% clear on it, my understanding is that this will
  134. // prevent hijacking of the server's endpoint by other applications.
  135. set_option(socket, .Exclusive_Addr_Use, true) or_return
  136. bind(sock, interface_endpoint) or_return
  137. if res := win.listen(win.SOCKET(socket), i32(backlog)); res == win.SOCKET_ERROR {
  138. err = _listen_error()
  139. }
  140. return
  141. }
  142. @(private)
  143. _bound_endpoint :: proc(sock: Any_Socket) -> (ep: Endpoint, err: Socket_Info_Error) {
  144. sockaddr: win.SOCKADDR_STORAGE_LH
  145. sockaddrlen := c.int(size_of(sockaddr))
  146. if win.getsockname(win.SOCKET(any_socket_to_socket(sock)), &sockaddr, &sockaddrlen) == win.SOCKET_ERROR {
  147. err = _socket_info_error()
  148. return
  149. }
  150. ep = _sockaddr_to_endpoint(&sockaddr)
  151. return
  152. }
  153. @(private)
  154. _peer_endpoint :: proc(sock: Any_Socket) -> (ep: Endpoint, err: Socket_Info_Error) {
  155. sockaddr: win.SOCKADDR_STORAGE_LH
  156. sockaddrlen := c.int(size_of(sockaddr))
  157. res := win.getpeername(win.SOCKET(any_socket_to_socket(sock)), &sockaddr, &sockaddrlen)
  158. if res < 0 {
  159. err = _socket_info_error()
  160. return
  161. }
  162. ep = _sockaddr_to_endpoint(&sockaddr)
  163. return
  164. }
  165. @(private)
  166. _accept_tcp :: proc(sock: TCP_Socket, options := DEFAULT_TCP_OPTIONS) -> (client: TCP_Socket, source: Endpoint, err: Accept_Error) {
  167. for {
  168. sockaddr: win.SOCKADDR_STORAGE_LH
  169. sockaddrlen := c.int(size_of(sockaddr))
  170. client_sock := win.accept(win.SOCKET(sock), &sockaddr, &sockaddrlen)
  171. if int(client_sock) == win.SOCKET_ERROR {
  172. e := win.WSAGetLastError()
  173. if e == win.WSAECONNRESET {
  174. // NOTE(tetra): Reset just means that a client that connection immediately lost the connection.
  175. // There's no need to concern the user with this, so we handle it for them.
  176. // On Linux, this error isn't possible in the first place according the man pages, so we also
  177. // can do this to match the behaviour.
  178. continue
  179. }
  180. err = _accept_error()
  181. return
  182. }
  183. client = TCP_Socket(client_sock)
  184. source = _sockaddr_to_endpoint(&sockaddr)
  185. if options.no_delay {
  186. _ = set_option(client, .TCP_Nodelay, true) // NOTE(tetra): Not vital to succeed; error ignored
  187. }
  188. return
  189. }
  190. }
  191. @(private)
  192. _close :: proc(socket: Any_Socket) {
  193. if s := any_socket_to_socket(socket); s != {} {
  194. win.closesocket(win.SOCKET(s))
  195. }
  196. }
  197. @(private)
  198. _recv_tcp :: proc(socket: TCP_Socket, buf: []byte) -> (bytes_read: int, err: TCP_Recv_Error) {
  199. if len(buf) <= 0 {
  200. return
  201. }
  202. res := win.recv(win.SOCKET(socket), raw_data(buf), c.int(len(buf)), 0)
  203. if res < 0 {
  204. err = _tcp_recv_error()
  205. return
  206. }
  207. return int(res), nil
  208. }
  209. @(private)
  210. _recv_udp :: proc(socket: UDP_Socket, buf: []byte) -> (bytes_read: int, remote_endpoint: Endpoint, err: UDP_Recv_Error) {
  211. if len(buf) <= 0 {
  212. return
  213. }
  214. from: win.SOCKADDR_STORAGE_LH
  215. fromsize := c.int(size_of(from))
  216. res := win.recvfrom(win.SOCKET(socket), raw_data(buf), c.int(len(buf)), 0, &from, &fromsize)
  217. if res < 0 {
  218. err = _udp_recv_error()
  219. return
  220. }
  221. bytes_read = int(res)
  222. remote_endpoint = _sockaddr_to_endpoint(&from)
  223. return
  224. }
  225. @(private)
  226. _send_tcp :: proc(socket: TCP_Socket, buf: []byte) -> (bytes_written: int, err: TCP_Send_Error) {
  227. for bytes_written < len(buf) {
  228. limit := min(int(max(i32)), len(buf) - bytes_written)
  229. remaining := buf[bytes_written:]
  230. res := win.send(win.SOCKET(socket), raw_data(remaining), c.int(limit), 0)
  231. if res < 0 {
  232. err = _tcp_send_error()
  233. return
  234. }
  235. bytes_written += int(res)
  236. }
  237. return
  238. }
  239. @(private)
  240. _send_udp :: proc(socket: UDP_Socket, buf: []byte, to: Endpoint) -> (bytes_written: int, err: UDP_Send_Error) {
  241. toaddr := _endpoint_to_sockaddr(to)
  242. for bytes_written < len(buf) {
  243. limit := min(int(max(i32)), len(buf) - bytes_written)
  244. remaining := buf[bytes_written:]
  245. res := win.sendto(win.SOCKET(socket), raw_data(remaining), c.int(limit), 0, &toaddr, size_of(toaddr))
  246. if res < 0 {
  247. err = _udp_send_error()
  248. return
  249. }
  250. bytes_written += int(res)
  251. }
  252. return
  253. }
  254. @(private)
  255. _shutdown :: proc(socket: Any_Socket, manner: Shutdown_Manner) -> (err: Shutdown_Error) {
  256. s := any_socket_to_socket(socket)
  257. res := win.shutdown(win.SOCKET(s), c.int(manner))
  258. if res < 0 {
  259. return _shutdown_error()
  260. }
  261. return
  262. }
  263. @(private)
  264. _set_option :: proc(s: Any_Socket, option: Socket_Option, value: any, loc := #caller_location) -> Socket_Option_Error {
  265. level := win.SOL_SOCKET if option != .TCP_Nodelay else win.IPPROTO_TCP
  266. bool_value: b32
  267. int_value: i32
  268. linger_value: win.LINGER
  269. ptr: rawptr
  270. len: c.int
  271. switch option {
  272. case
  273. .Reuse_Address,
  274. .Exclusive_Addr_Use,
  275. .Keep_Alive,
  276. .Out_Of_Bounds_Data_Inline,
  277. .TCP_Nodelay,
  278. .Broadcast,
  279. .Conditional_Accept,
  280. .Dont_Linger:
  281. switch x in value {
  282. case bool, b8:
  283. x2 := x
  284. bool_value = b32((^bool)(&x2)^)
  285. case b16:
  286. bool_value = b32(x)
  287. case b32:
  288. bool_value = b32(x)
  289. case b64:
  290. bool_value = b32(x)
  291. case:
  292. panic("set_option() value must be a boolean here", loc)
  293. }
  294. ptr = &bool_value
  295. len = size_of(bool_value)
  296. case .Linger:
  297. t := value.(time.Duration) or_else panic("set_option() value must be a time.Duration here", loc)
  298. num_secs := i64(time.duration_seconds(t))
  299. if num_secs > i64(max(u16)) {
  300. return .Invalid_Value
  301. }
  302. linger_value.l_onoff = 1
  303. linger_value.l_linger = c.ushort(num_secs)
  304. ptr = &linger_value
  305. len = size_of(linger_value)
  306. case
  307. .Receive_Timeout,
  308. .Send_Timeout:
  309. t := value.(time.Duration) or_else panic("set_option() value must be a time.Duration here", loc)
  310. int_value = i32(time.duration_milliseconds(t))
  311. ptr = &int_value
  312. len = size_of(int_value)
  313. case
  314. .Receive_Buffer_Size,
  315. .Send_Buffer_Size:
  316. switch i in value {
  317. case i8, u8: i2 := i; int_value = c.int((^u8)(&i2)^)
  318. case i16, u16: i2 := i; int_value = c.int((^u16)(&i2)^)
  319. case i32, u32: i2 := i; int_value = c.int((^u32)(&i2)^)
  320. case i64, u64: i2 := i; int_value = c.int((^u64)(&i2)^)
  321. case i128, u128: i2 := i; int_value = c.int((^u128)(&i2)^)
  322. case int, uint: i2 := i; int_value = c.int((^uint)(&i2)^)
  323. case:
  324. panic("set_option() value must be an integer here", loc)
  325. }
  326. ptr = &int_value
  327. len = size_of(int_value)
  328. }
  329. socket := any_socket_to_socket(s)
  330. res := win.setsockopt(win.SOCKET(socket), c.int(level), c.int(option), ptr, len)
  331. if res < 0 {
  332. return _socket_option_error()
  333. }
  334. return nil
  335. }
  336. @(private)
  337. _set_blocking :: proc(socket: Any_Socket, should_block: bool) -> (err: Set_Blocking_Error) {
  338. socket := any_socket_to_socket(socket)
  339. arg: win.DWORD = 0 if should_block else 1
  340. res := win.ioctlsocket(win.SOCKET(socket), transmute(win.c_long)win.FIONBIO, &arg)
  341. if res == win.SOCKET_ERROR {
  342. return _set_blocking_error()
  343. }
  344. return nil
  345. }
  346. @(private)
  347. _endpoint_to_sockaddr :: proc(ep: Endpoint) -> (sockaddr: win.SOCKADDR_STORAGE_LH) {
  348. switch a in ep.address {
  349. case IP4_Address:
  350. (^win.sockaddr_in)(&sockaddr)^ = win.sockaddr_in {
  351. sin_port = u16be(win.USHORT(ep.port)),
  352. sin_addr = transmute(win.in_addr) a,
  353. sin_family = u16(win.AF_INET),
  354. }
  355. return
  356. case IP6_Address:
  357. (^win.sockaddr_in6)(&sockaddr)^ = win.sockaddr_in6 {
  358. sin6_port = u16be(win.USHORT(ep.port)),
  359. sin6_addr = transmute(win.in6_addr) a,
  360. sin6_family = u16(win.AF_INET6),
  361. }
  362. return
  363. }
  364. unreachable()
  365. }
  366. @(private)
  367. _sockaddr_to_endpoint :: proc(native_addr: ^win.SOCKADDR_STORAGE_LH) -> (ep: Endpoint) {
  368. switch native_addr.ss_family {
  369. case u16(win.AF_INET):
  370. addr := cast(^win.sockaddr_in) native_addr
  371. port := int(addr.sin_port)
  372. ep = Endpoint {
  373. address = IP4_Address(transmute([4]byte) addr.sin_addr),
  374. port = port,
  375. }
  376. case u16(win.AF_INET6):
  377. addr := cast(^win.sockaddr_in6) native_addr
  378. port := int(addr.sin6_port)
  379. ep = Endpoint {
  380. address = IP6_Address(transmute([8]u16be) addr.sin6_addr),
  381. port = port,
  382. }
  383. case:
  384. panic("native_addr is neither IP4 or IP6 address")
  385. }
  386. return
  387. }