socket_windows.odin 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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. @(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. _bound_endpoint :: proc(sock: Any_Socket) -> (ep: Endpoint, err: Network_Error) {
  103. sockaddr: win.SOCKADDR_STORAGE_LH
  104. sockaddrlen := c.int(size_of(sockaddr))
  105. if win.getsockname(win.SOCKET(any_socket_to_socket(sock)), &sockaddr, &sockaddrlen) == win.SOCKET_ERROR {
  106. err = Listen_Error(win.WSAGetLastError())
  107. return
  108. }
  109. ep = _sockaddr_to_endpoint(&sockaddr)
  110. return
  111. }
  112. @(private)
  113. _accept_tcp :: proc(sock: TCP_Socket, options := default_tcp_options) -> (client: TCP_Socket, source: Endpoint, err: Network_Error) {
  114. for {
  115. sockaddr: win.SOCKADDR_STORAGE_LH
  116. sockaddrlen := c.int(size_of(sockaddr))
  117. client_sock := win.accept(win.SOCKET(sock), &sockaddr, &sockaddrlen)
  118. if int(client_sock) == win.SOCKET_ERROR {
  119. e := win.WSAGetLastError()
  120. if e == win.WSAECONNRESET {
  121. // NOTE(tetra): Reset just means that a client that connection immediately lost the connection.
  122. // There's no need to concern the user with this, so we handle it for them.
  123. // On Linux, this error isn't possible in the first place according the man pages, so we also
  124. // can do this to match the behaviour.
  125. continue
  126. }
  127. err = Accept_Error(e)
  128. return
  129. }
  130. client = TCP_Socket(client_sock)
  131. source = _sockaddr_to_endpoint(&sockaddr)
  132. if options.no_delay {
  133. _ = set_option(client, .TCP_Nodelay, true) // NOTE(tetra): Not vital to succeed; error ignored
  134. }
  135. return
  136. }
  137. }
  138. @(private)
  139. _close :: proc(socket: Any_Socket) {
  140. if s := any_socket_to_socket(socket); s != {} {
  141. win.closesocket(win.SOCKET(s))
  142. }
  143. }
  144. @(private)
  145. _recv_tcp :: proc(socket: TCP_Socket, buf: []byte) -> (bytes_read: int, err: Network_Error) {
  146. if len(buf) <= 0 {
  147. return
  148. }
  149. res := win.recv(win.SOCKET(socket), raw_data(buf), c.int(len(buf)), 0)
  150. if res < 0 {
  151. err = TCP_Recv_Error(win.WSAGetLastError())
  152. return
  153. }
  154. return int(res), nil
  155. }
  156. @(private)
  157. _recv_udp :: proc(socket: UDP_Socket, buf: []byte) -> (bytes_read: int, remote_endpoint: Endpoint, err: Network_Error) {
  158. if len(buf) <= 0 {
  159. return
  160. }
  161. from: win.SOCKADDR_STORAGE_LH
  162. fromsize := c.int(size_of(from))
  163. res := win.recvfrom(win.SOCKET(socket), raw_data(buf), c.int(len(buf)), 0, &from, &fromsize)
  164. if res < 0 {
  165. err = UDP_Recv_Error(win.WSAGetLastError())
  166. return
  167. }
  168. bytes_read = int(res)
  169. remote_endpoint = _sockaddr_to_endpoint(&from)
  170. return
  171. }
  172. @(private)
  173. _send_tcp :: proc(socket: TCP_Socket, buf: []byte) -> (bytes_written: int, err: Network_Error) {
  174. for bytes_written < len(buf) {
  175. limit := min(int(max(i32)), len(buf) - bytes_written)
  176. remaining := buf[bytes_written:]
  177. res := win.send(win.SOCKET(socket), raw_data(remaining), c.int(limit), 0)
  178. if res < 0 {
  179. err = TCP_Send_Error(win.WSAGetLastError())
  180. return
  181. }
  182. bytes_written += int(res)
  183. }
  184. return
  185. }
  186. @(private)
  187. _send_udp :: proc(socket: UDP_Socket, buf: []byte, to: Endpoint) -> (bytes_written: int, err: Network_Error) {
  188. if len(buf) > int(max(c.int)) {
  189. // NOTE(tetra): If we don't guard this, we'll return (0, nil) instead, which is misleading.
  190. err = .Message_Too_Long
  191. return
  192. }
  193. toaddr := _endpoint_to_sockaddr(to)
  194. res := win.sendto(win.SOCKET(socket), raw_data(buf), c.int(len(buf)), 0, &toaddr, size_of(toaddr))
  195. if res < 0 {
  196. err = UDP_Send_Error(win.WSAGetLastError())
  197. return
  198. }
  199. bytes_written = int(res)
  200. return
  201. }
  202. @(private)
  203. _shutdown :: proc(socket: Any_Socket, manner: Shutdown_Manner) -> (err: Network_Error) {
  204. s := any_socket_to_socket(socket)
  205. res := win.shutdown(win.SOCKET(s), c.int(manner))
  206. if res < 0 {
  207. return Shutdown_Error(win.WSAGetLastError())
  208. }
  209. return
  210. }
  211. @(private)
  212. _set_option :: proc(s: Any_Socket, option: Socket_Option, value: any, loc := #caller_location) -> Network_Error {
  213. level := win.SOL_SOCKET if option != .TCP_Nodelay else win.IPPROTO_TCP
  214. bool_value: b32
  215. int_value: i32
  216. linger_value: win.LINGER
  217. ptr: rawptr
  218. len: c.int
  219. switch option {
  220. case
  221. .Reuse_Address,
  222. .Exclusive_Addr_Use,
  223. .Keep_Alive,
  224. .Out_Of_Bounds_Data_Inline,
  225. .TCP_Nodelay,
  226. .Broadcast,
  227. .Conditional_Accept,
  228. .Dont_Linger:
  229. switch x in value {
  230. case bool, b8:
  231. x2 := x
  232. bool_value = b32((^bool)(&x2)^)
  233. case b16:
  234. bool_value = b32(x)
  235. case b32:
  236. bool_value = b32(x)
  237. case b64:
  238. bool_value = b32(x)
  239. case:
  240. panic("set_option() value must be a boolean here", loc)
  241. }
  242. ptr = &bool_value
  243. len = size_of(bool_value)
  244. case .Linger:
  245. t := value.(time.Duration) or_else panic("set_option() value must be a time.Duration here", loc)
  246. num_secs := i64(time.duration_seconds(t))
  247. if time.Duration(num_secs * 1e9) != t {
  248. return .Linger_Only_Supports_Whole_Seconds
  249. }
  250. if num_secs > i64(max(u16)) {
  251. return .Value_Out_Of_Range
  252. }
  253. linger_value.l_onoff = 1
  254. linger_value.l_linger = c.ushort(num_secs)
  255. ptr = &linger_value
  256. len = size_of(linger_value)
  257. case
  258. .Receive_Timeout,
  259. .Send_Timeout:
  260. t := value.(time.Duration) or_else panic("set_option() value must be a time.Duration here", loc)
  261. int_value = i32(time.duration_milliseconds(t))
  262. ptr = &int_value
  263. len = size_of(int_value)
  264. case
  265. .Receive_Buffer_Size,
  266. .Send_Buffer_Size:
  267. switch i in value {
  268. case i8, u8: i2 := i; int_value = c.int((^u8)(&i2)^)
  269. case i16, u16: i2 := i; int_value = c.int((^u16)(&i2)^)
  270. case i32, u32: i2 := i; int_value = c.int((^u32)(&i2)^)
  271. case i64, u64: i2 := i; int_value = c.int((^u64)(&i2)^)
  272. case i128, u128: i2 := i; int_value = c.int((^u128)(&i2)^)
  273. case int, uint: i2 := i; int_value = c.int((^uint)(&i2)^)
  274. case:
  275. panic("set_option() value must be an integer here", loc)
  276. }
  277. ptr = &int_value
  278. len = size_of(int_value)
  279. }
  280. socket := any_socket_to_socket(s)
  281. res := win.setsockopt(win.SOCKET(socket), c.int(level), c.int(option), ptr, len)
  282. if res < 0 {
  283. return Socket_Option_Error(win.WSAGetLastError())
  284. }
  285. return nil
  286. }
  287. @(private)
  288. _set_blocking :: proc(socket: Any_Socket, should_block: bool) -> (err: Network_Error) {
  289. socket := any_socket_to_socket(socket)
  290. arg: win.DWORD = 0 if should_block else 1
  291. res := win.ioctlsocket(win.SOCKET(socket), transmute(win.c_long)win.FIONBIO, &arg)
  292. if res == win.SOCKET_ERROR {
  293. return Set_Blocking_Error(win.WSAGetLastError())
  294. }
  295. return nil
  296. }
  297. @(private)
  298. _endpoint_to_sockaddr :: proc(ep: Endpoint) -> (sockaddr: win.SOCKADDR_STORAGE_LH) {
  299. switch a in ep.address {
  300. case IP4_Address:
  301. (^win.sockaddr_in)(&sockaddr)^ = win.sockaddr_in {
  302. sin_port = u16be(win.USHORT(ep.port)),
  303. sin_addr = transmute(win.in_addr) a,
  304. sin_family = u16(win.AF_INET),
  305. }
  306. return
  307. case IP6_Address:
  308. (^win.sockaddr_in6)(&sockaddr)^ = win.sockaddr_in6 {
  309. sin6_port = u16be(win.USHORT(ep.port)),
  310. sin6_addr = transmute(win.in6_addr) a,
  311. sin6_family = u16(win.AF_INET6),
  312. }
  313. return
  314. }
  315. unreachable()
  316. }
  317. @(private)
  318. _sockaddr_to_endpoint :: proc(native_addr: ^win.SOCKADDR_STORAGE_LH) -> (ep: Endpoint) {
  319. switch native_addr.ss_family {
  320. case u16(win.AF_INET):
  321. addr := cast(^win.sockaddr_in) native_addr
  322. port := int(addr.sin_port)
  323. ep = Endpoint {
  324. address = IP4_Address(transmute([4]byte) addr.sin_addr),
  325. port = port,
  326. }
  327. case u16(win.AF_INET6):
  328. addr := cast(^win.sockaddr_in6) native_addr
  329. port := int(addr.sin6_port)
  330. ep = Endpoint {
  331. address = IP6_Address(transmute([8]u16be) addr.sin6_addr),
  332. port = port,
  333. }
  334. case:
  335. panic("native_addr is neither IP4 or IP6 address")
  336. }
  337. return
  338. }