socket_windows.odin 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. package net
  2. // +build windows
  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. @(init, private)
  23. ensure_winsock_initialized :: proc() {
  24. win.ensure_winsock_initialized()
  25. }
  26. @(private)
  27. _create_socket :: proc(family: Address_Family, protocol: Socket_Protocol) -> (socket: Any_Socket, err: Network_Error) {
  28. c_type, c_protocol, c_family: c.int
  29. switch family {
  30. case .IP4: c_family = win.AF_INET
  31. case .IP6: c_family = win.AF_INET6
  32. case:
  33. unreachable()
  34. }
  35. switch protocol {
  36. case .TCP: c_type = win.SOCK_STREAM; c_protocol = win.IPPROTO_TCP
  37. case .UDP: c_type = win.SOCK_DGRAM; c_protocol = win.IPPROTO_UDP
  38. case:
  39. unreachable()
  40. }
  41. sock := win.socket(c_family, c_type, c_protocol)
  42. if sock == win.INVALID_SOCKET {
  43. err = Create_Socket_Error(win.WSAGetLastError())
  44. return
  45. }
  46. switch protocol {
  47. case .TCP: return TCP_Socket(sock), nil
  48. case .UDP: return UDP_Socket(sock), nil
  49. case:
  50. unreachable()
  51. }
  52. }
  53. @(private)
  54. _dial_tcp_from_endpoint :: proc(endpoint: Endpoint, options := default_tcp_options) -> (socket: TCP_Socket, err: Network_Error) {
  55. if endpoint.port == 0 {
  56. err = .Port_Required
  57. return
  58. }
  59. family := family_from_endpoint(endpoint)
  60. sock := create_socket(family, .TCP) or_return
  61. socket = sock.(TCP_Socket)
  62. // NOTE(tetra): This is so that if we crash while the socket is open, we can
  63. // bypass the cooldown period, and allow the next run of the program to
  64. // use the same address immediately.
  65. _ = set_option(socket, .Reuse_Address, true)
  66. sockaddr := _endpoint_to_sockaddr(endpoint)
  67. res := win.connect(win.SOCKET(socket), &sockaddr, size_of(sockaddr))
  68. if res < 0 {
  69. err = Dial_Error(win.WSAGetLastError())
  70. return
  71. }
  72. if options.no_delay {
  73. _ = set_option(sock, .TCP_Nodelay, true) // NOTE(tetra): Not vital to succeed; error ignored
  74. }
  75. return
  76. }
  77. @(private)
  78. _bind :: proc(socket: Any_Socket, ep: Endpoint) -> (err: Network_Error) {
  79. sockaddr := _endpoint_to_sockaddr(ep)
  80. sock := any_socket_to_socket(socket)
  81. res := win.bind(win.SOCKET(sock), &sockaddr, size_of(sockaddr))
  82. if res < 0 {
  83. err = Bind_Error(win.WSAGetLastError())
  84. }
  85. return
  86. }
  87. @(private)
  88. _listen_tcp :: proc(interface_endpoint: Endpoint, backlog := 1000) -> (socket: TCP_Socket, err: Network_Error) {
  89. family := family_from_endpoint(interface_endpoint)
  90. sock := create_socket(family, .TCP) or_return
  91. socket = sock.(TCP_Socket)
  92. // NOTE(tetra): While I'm not 100% clear on it, my understanding is that this will
  93. // prevent hijacking of the server's endpoint by other applications.
  94. set_option(socket, .Exclusive_Addr_Use, true) or_return
  95. bind(sock, interface_endpoint) or_return
  96. if res := win.listen(win.SOCKET(socket), i32(backlog)); res == win.SOCKET_ERROR {
  97. err = Listen_Error(win.WSAGetLastError())
  98. }
  99. return
  100. }
  101. @(private)
  102. _accept_tcp :: proc(sock: TCP_Socket, options := default_tcp_options) -> (client: TCP_Socket, source: Endpoint, err: Network_Error) {
  103. for {
  104. sockaddr: win.SOCKADDR_STORAGE_LH
  105. sockaddrlen := c.int(size_of(sockaddr))
  106. client_sock := win.accept(win.SOCKET(sock), &sockaddr, &sockaddrlen)
  107. if int(client_sock) == win.SOCKET_ERROR {
  108. e := win.WSAGetLastError()
  109. if e == win.WSAECONNRESET {
  110. // NOTE(tetra): Reset just means that a client that connection immediately lost the connection.
  111. // There's no need to concern the user with this, so we handle it for them.
  112. // On Linux, this error isn't possible in the first place according the man pages, so we also
  113. // can do this to match the behaviour.
  114. continue
  115. }
  116. err = Accept_Error(e)
  117. return
  118. }
  119. client = TCP_Socket(client_sock)
  120. source = _sockaddr_to_endpoint(&sockaddr)
  121. if options.no_delay {
  122. _ = set_option(client, .TCP_Nodelay, true) // NOTE(tetra): Not vital to succeed; error ignored
  123. }
  124. return
  125. }
  126. }
  127. @(private)
  128. _close :: proc(socket: Any_Socket) {
  129. if s := any_socket_to_socket(socket); s != {} {
  130. win.closesocket(win.SOCKET(s))
  131. }
  132. }
  133. @(private)
  134. _recv_tcp :: proc(socket: TCP_Socket, buf: []byte) -> (bytes_read: int, err: Network_Error) {
  135. if len(buf) <= 0 {
  136. return
  137. }
  138. res := win.recv(win.SOCKET(socket), raw_data(buf), c.int(len(buf)), 0)
  139. if res < 0 {
  140. err = TCP_Recv_Error(win.WSAGetLastError())
  141. return
  142. }
  143. return int(res), nil
  144. }
  145. @(private)
  146. _recv_udp :: proc(socket: UDP_Socket, buf: []byte) -> (bytes_read: int, remote_endpoint: Endpoint, err: Network_Error) {
  147. if len(buf) <= 0 {
  148. return
  149. }
  150. from: win.SOCKADDR_STORAGE_LH
  151. fromsize := c.int(size_of(from))
  152. res := win.recvfrom(win.SOCKET(socket), raw_data(buf), c.int(len(buf)), 0, &from, &fromsize)
  153. if res < 0 {
  154. err = UDP_Recv_Error(win.WSAGetLastError())
  155. return
  156. }
  157. bytes_read = int(res)
  158. remote_endpoint = _sockaddr_to_endpoint(&from)
  159. return
  160. }
  161. @(private)
  162. _send_tcp :: proc(socket: TCP_Socket, buf: []byte) -> (bytes_written: int, err: Network_Error) {
  163. for bytes_written < len(buf) {
  164. limit := min(int(max(i32)), len(buf) - bytes_written)
  165. remaining := buf[bytes_written:]
  166. res := win.send(win.SOCKET(socket), raw_data(remaining), c.int(limit), 0)
  167. if res < 0 {
  168. err = TCP_Send_Error(win.WSAGetLastError())
  169. return
  170. }
  171. bytes_written += int(res)
  172. }
  173. return
  174. }
  175. @(private)
  176. _send_udp :: proc(socket: UDP_Socket, buf: []byte, to: Endpoint) -> (bytes_written: int, err: Network_Error) {
  177. if len(buf) > int(max(c.int)) {
  178. // NOTE(tetra): If we don't guard this, we'll return (0, nil) instead, which is misleading.
  179. err = .Message_Too_Long
  180. return
  181. }
  182. toaddr := _endpoint_to_sockaddr(to)
  183. res := win.sendto(win.SOCKET(socket), raw_data(buf), c.int(len(buf)), 0, &toaddr, size_of(toaddr))
  184. if res < 0 {
  185. err = UDP_Send_Error(win.WSAGetLastError())
  186. return
  187. }
  188. bytes_written = int(res)
  189. return
  190. }
  191. @(private)
  192. _shutdown :: proc(socket: Any_Socket, manner: Shutdown_Manner) -> (err: Network_Error) {
  193. s := any_socket_to_socket(socket)
  194. res := win.shutdown(win.SOCKET(s), c.int(manner))
  195. if res < 0 {
  196. return Shutdown_Error(win.WSAGetLastError())
  197. }
  198. return
  199. }
  200. @(private)
  201. _set_option :: proc(s: Any_Socket, option: Socket_Option, value: any, loc := #caller_location) -> Network_Error {
  202. level := win.SOL_SOCKET if option != .TCP_Nodelay else win.IPPROTO_TCP
  203. bool_value: b32
  204. int_value: i32
  205. linger_value: win.LINGER
  206. ptr: rawptr
  207. len: c.int
  208. switch option {
  209. case
  210. .Reuse_Address,
  211. .Exclusive_Addr_Use,
  212. .Keep_Alive,
  213. .Out_Of_Bounds_Data_Inline,
  214. .TCP_Nodelay,
  215. .Broadcast,
  216. .Conditional_Accept,
  217. .Dont_Linger:
  218. switch x in value {
  219. case bool, b8:
  220. x2 := x
  221. bool_value = b32((^bool)(&x2)^)
  222. case b16:
  223. bool_value = b32(x)
  224. case b32:
  225. bool_value = b32(x)
  226. case b64:
  227. bool_value = b32(x)
  228. case:
  229. panic("set_option() value must be a boolean here", loc)
  230. }
  231. ptr = &bool_value
  232. len = size_of(bool_value)
  233. case .Linger:
  234. t := value.(time.Duration) or_else panic("set_option() value must be a time.Duration here", loc)
  235. num_secs := i64(time.duration_seconds(t))
  236. if time.Duration(num_secs * 1e9) != t {
  237. return .Linger_Only_Supports_Whole_Seconds
  238. }
  239. if num_secs > i64(max(u16)) {
  240. return .Value_Out_Of_Range
  241. }
  242. linger_value.l_onoff = 1
  243. linger_value.l_linger = c.ushort(num_secs)
  244. ptr = &linger_value
  245. len = size_of(linger_value)
  246. case
  247. .Receive_Timeout,
  248. .Send_Timeout:
  249. t := value.(time.Duration) or_else panic("set_option() value must be a time.Duration here", loc)
  250. int_value = i32(time.duration_milliseconds(t))
  251. ptr = &int_value
  252. len = size_of(int_value)
  253. case
  254. .Receive_Buffer_Size,
  255. .Send_Buffer_Size:
  256. switch i in value {
  257. case i8, u8: i2 := i; int_value = c.int((^u8)(&i2)^)
  258. case i16, u16: i2 := i; int_value = c.int((^u16)(&i2)^)
  259. case i32, u32: i2 := i; int_value = c.int((^u32)(&i2)^)
  260. case i64, u64: i2 := i; int_value = c.int((^u64)(&i2)^)
  261. case i128, u128: i2 := i; int_value = c.int((^u128)(&i2)^)
  262. case int, uint: i2 := i; int_value = c.int((^uint)(&i2)^)
  263. case:
  264. panic("set_option() value must be an integer here", loc)
  265. }
  266. ptr = &int_value
  267. len = size_of(int_value)
  268. }
  269. socket := any_socket_to_socket(s)
  270. res := win.setsockopt(win.SOCKET(socket), c.int(level), c.int(option), ptr, len)
  271. if res < 0 {
  272. return Socket_Option_Error(win.WSAGetLastError())
  273. }
  274. return nil
  275. }
  276. @(private)
  277. _set_blocking :: proc(socket: Any_Socket, should_block: bool) -> (err: Network_Error) {
  278. socket := any_socket_to_socket(socket)
  279. arg: win.DWORD = 0 if should_block else 1
  280. res := win.ioctlsocket(win.SOCKET(socket), transmute(win.c_long)win.FIONBIO, &arg)
  281. if res == win.SOCKET_ERROR {
  282. return Set_Blocking_Error(win.WSAGetLastError())
  283. }
  284. return nil
  285. }
  286. @(private)
  287. _endpoint_to_sockaddr :: proc(ep: Endpoint) -> (sockaddr: win.SOCKADDR_STORAGE_LH) {
  288. switch a in ep.address {
  289. case IP4_Address:
  290. (^win.sockaddr_in)(&sockaddr)^ = win.sockaddr_in {
  291. sin_port = u16be(win.USHORT(ep.port)),
  292. sin_addr = transmute(win.in_addr) a,
  293. sin_family = u16(win.AF_INET),
  294. }
  295. return
  296. case IP6_Address:
  297. (^win.sockaddr_in6)(&sockaddr)^ = win.sockaddr_in6 {
  298. sin6_port = u16be(win.USHORT(ep.port)),
  299. sin6_addr = transmute(win.in6_addr) a,
  300. sin6_family = u16(win.AF_INET6),
  301. }
  302. return
  303. }
  304. unreachable()
  305. }
  306. @(private)
  307. _sockaddr_to_endpoint :: proc(native_addr: ^win.SOCKADDR_STORAGE_LH) -> (ep: Endpoint) {
  308. switch native_addr.ss_family {
  309. case u16(win.AF_INET):
  310. addr := cast(^win.sockaddr_in) native_addr
  311. port := int(addr.sin_port)
  312. ep = Endpoint {
  313. address = IP4_Address(transmute([4]byte) addr.sin_addr),
  314. port = port,
  315. }
  316. case u16(win.AF_INET6):
  317. addr := cast(^win.sockaddr_in6) native_addr
  318. port := int(addr.sin6_port)
  319. ep = Endpoint {
  320. address = IP6_Address(transmute([8]u16be) addr.sin6_addr),
  321. port = port,
  322. }
  323. case:
  324. panic("native_addr is neither IP4 or IP6 address")
  325. }
  326. return
  327. }