socket_windows.odin 10 KB

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