socket_darwin.odin 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. package net
  2. // +build darwin
  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 "core:os"
  19. import "core:time"
  20. Socket_Option :: enum c.int {
  21. Reuse_Address = c.int(os.SO_REUSEADDR),
  22. Keep_Alive = c.int(os.SO_KEEPALIVE),
  23. Out_Of_Bounds_Data_Inline = c.int(os.SO_OOBINLINE),
  24. TCP_Nodelay = c.int(os.TCP_NODELAY),
  25. Linger = c.int(os.SO_LINGER),
  26. Receive_Buffer_Size = c.int(os.SO_RCVBUF),
  27. Send_Buffer_Size = c.int(os.SO_SNDBUF),
  28. Receive_Timeout = c.int(os.SO_RCVTIMEO),
  29. Send_Timeout = c.int(os.SO_SNDTIMEO),
  30. }
  31. @(private)
  32. _create_socket :: proc(family: Address_Family, protocol: Socket_Protocol) -> (socket: Any_Socket, err: Network_Error) {
  33. c_type, c_protocol, c_family: int
  34. switch family {
  35. case .IP4: c_family = os.AF_INET
  36. case .IP6: c_family = os.AF_INET6
  37. case:
  38. unreachable()
  39. }
  40. switch protocol {
  41. case .TCP: c_type = os.SOCK_STREAM; c_protocol = os.IPPROTO_TCP
  42. case .UDP: c_type = os.SOCK_DGRAM; c_protocol = os.IPPROTO_UDP
  43. case:
  44. unreachable()
  45. }
  46. sock, ok := os.socket(c_family, c_type, c_protocol)
  47. if ok != os.ERROR_NONE {
  48. err = Create_Socket_Error(ok)
  49. return
  50. }
  51. switch protocol {
  52. case .TCP: return TCP_Socket(sock), nil
  53. case .UDP: return UDP_Socket(sock), nil
  54. case:
  55. unreachable()
  56. }
  57. }
  58. @(private)
  59. _dial_tcp_from_endpoint :: proc(endpoint: Endpoint, options := default_tcp_options) -> (skt: TCP_Socket, err: Network_Error) {
  60. if endpoint.port == 0 {
  61. return 0, .Port_Required
  62. }
  63. family := family_from_endpoint(endpoint)
  64. sock := create_socket(family, .TCP) or_return
  65. skt = sock.(TCP_Socket)
  66. // NOTE(tetra): This is so that if we crash while the socket is open, we can
  67. // bypass the cooldown period, and allow the next run of the program to
  68. // use the same address immediately.
  69. _ = set_option(skt, .Reuse_Address, true)
  70. sockaddr := _endpoint_to_sockaddr(endpoint)
  71. res := os.connect(os.Socket(skt), (^os.SOCKADDR)(&sockaddr), i32(sockaddr.len))
  72. if res != os.ERROR_NONE {
  73. err = Dial_Error(res)
  74. return
  75. }
  76. return
  77. }
  78. @(private)
  79. _bind :: proc(skt: Any_Socket, ep: Endpoint) -> (err: Network_Error) {
  80. sockaddr := _endpoint_to_sockaddr(ep)
  81. s := any_socket_to_socket(skt)
  82. res := os.bind(os.Socket(s), (^os.SOCKADDR)(&sockaddr), i32(sockaddr.len))
  83. if res != os.ERROR_NONE {
  84. err = Bind_Error(res)
  85. }
  86. return
  87. }
  88. @(private)
  89. _listen_tcp :: proc(interface_endpoint: Endpoint, backlog := 1000) -> (skt: TCP_Socket, err: Network_Error) {
  90. assert(backlog > 0 && i32(backlog) < max(i32))
  91. family := family_from_endpoint(interface_endpoint)
  92. sock := create_socket(family, .TCP) or_return
  93. skt = sock.(TCP_Socket)
  94. // NOTE(tetra): This is so that if we crash while the socket is open, we can
  95. // bypass the cooldown period, and allow the next run of the program to
  96. // use the same address immediately.
  97. //
  98. // TODO(tetra, 2022-02-15): Confirm that this doesn't mean other processes can hijack the address!
  99. set_option(sock, .Reuse_Address, true) or_return
  100. bind(sock, interface_endpoint) or_return
  101. res := os.listen(os.Socket(skt), backlog)
  102. if res != os.ERROR_NONE {
  103. err = Listen_Error(res)
  104. return
  105. }
  106. return
  107. }
  108. @(private)
  109. _accept_tcp :: proc(sock: TCP_Socket, options := default_tcp_options) -> (client: TCP_Socket, source: Endpoint, err: Network_Error) {
  110. sockaddr: os.SOCKADDR_STORAGE_LH
  111. sockaddrlen := c.int(size_of(sockaddr))
  112. client_sock, ok := os.accept(os.Socket(sock), cast(^os.SOCKADDR) &sockaddr, &sockaddrlen)
  113. if ok != os.ERROR_NONE {
  114. err = Accept_Error(ok)
  115. return
  116. }
  117. client = TCP_Socket(client_sock)
  118. source = _sockaddr_to_endpoint(&sockaddr)
  119. return
  120. }
  121. @(private)
  122. _close :: proc(skt: Any_Socket) {
  123. s := any_socket_to_socket(skt)
  124. os.close(os.Handle(os.Socket(s)))
  125. }
  126. @(private)
  127. _recv_tcp :: proc(skt: TCP_Socket, buf: []byte) -> (bytes_read: int, err: Network_Error) {
  128. if len(buf) <= 0 {
  129. return
  130. }
  131. res, ok := os.recv(os.Socket(skt), buf, 0)
  132. if ok != os.ERROR_NONE {
  133. err = TCP_Recv_Error(ok)
  134. return
  135. }
  136. return int(res), nil
  137. }
  138. @(private)
  139. _recv_udp :: proc(skt: UDP_Socket, buf: []byte) -> (bytes_read: int, remote_endpoint: Endpoint, err: Network_Error) {
  140. if len(buf) <= 0 {
  141. return
  142. }
  143. from: os.SOCKADDR_STORAGE_LH
  144. fromsize := c.int(size_of(from))
  145. res, ok := os.recvfrom(os.Socket(skt), buf, 0, cast(^os.SOCKADDR) &from, &fromsize)
  146. if ok != os.ERROR_NONE {
  147. err = UDP_Recv_Error(ok)
  148. return
  149. }
  150. bytes_read = int(res)
  151. remote_endpoint = _sockaddr_to_endpoint(&from)
  152. return
  153. }
  154. @(private)
  155. _send_tcp :: proc(skt: TCP_Socket, buf: []byte) -> (bytes_written: int, err: Network_Error) {
  156. for bytes_written < len(buf) {
  157. limit := min(int(max(i32)), len(buf) - bytes_written)
  158. remaining := buf[bytes_written:][:limit]
  159. res, ok := os.send(os.Socket(skt), remaining, 0)
  160. if ok != os.ERROR_NONE {
  161. err = TCP_Send_Error(ok)
  162. return
  163. }
  164. bytes_written += int(res)
  165. }
  166. return
  167. }
  168. @(private)
  169. _send_udp :: proc(skt: UDP_Socket, buf: []byte, to: Endpoint) -> (bytes_written: int, err: Network_Error) {
  170. toaddr := _endpoint_to_sockaddr(to)
  171. for bytes_written < len(buf) {
  172. limit := min(1<<31, len(buf) - bytes_written)
  173. remaining := buf[bytes_written:][:limit]
  174. res, ok := os.sendto(os.Socket(skt), remaining, 0, cast(^os.SOCKADDR)&toaddr, i32(toaddr.len))
  175. if ok != os.ERROR_NONE {
  176. err = UDP_Send_Error(ok)
  177. return
  178. }
  179. bytes_written += int(res)
  180. }
  181. return
  182. }
  183. @(private)
  184. _shutdown :: proc(skt: Any_Socket, manner: Shutdown_Manner) -> (err: Network_Error) {
  185. s := any_socket_to_socket(skt)
  186. res := os.shutdown(os.Socket(s), int(manner))
  187. if res != os.ERROR_NONE {
  188. return Shutdown_Error(res)
  189. }
  190. return
  191. }
  192. @(private)
  193. _set_option :: proc(s: Any_Socket, option: Socket_Option, value: any, loc := #caller_location) -> Network_Error {
  194. level := os.SOL_SOCKET if option != .TCP_Nodelay else os.IPPROTO_TCP
  195. // NOTE(tetra, 2022-02-15): On Linux, you cannot merely give a single byte for a bool;
  196. // it _has_ to be a b32.
  197. // I haven't tested if you can give more than that.
  198. bool_value: b32
  199. int_value: i32
  200. timeval_value: os.Timeval
  201. ptr: rawptr
  202. len: os.socklen_t
  203. switch option {
  204. case
  205. .Reuse_Address,
  206. .Keep_Alive,
  207. .Out_Of_Bounds_Data_Inline,
  208. .TCP_Nodelay:
  209. // TODO: verify whether these are options or not on Linux
  210. // .Broadcast,
  211. // .Conditional_Accept,
  212. // .Dont_Linger:
  213. switch x in value {
  214. case bool, b8:
  215. x2 := x
  216. bool_value = b32((^bool)(&x2)^)
  217. case b16:
  218. bool_value = b32(x)
  219. case b32:
  220. bool_value = b32(x)
  221. case b64:
  222. bool_value = b32(x)
  223. case:
  224. panic("set_option() value must be a boolean here", loc)
  225. }
  226. ptr = &bool_value
  227. len = size_of(bool_value)
  228. case
  229. .Linger,
  230. .Send_Timeout,
  231. .Receive_Timeout:
  232. t, ok := value.(time.Duration)
  233. if !ok do panic("set_option() value must be a time.Duration here", loc)
  234. nanos := time.duration_nanoseconds(t)
  235. timeval_value.nanoseconds = int(nanos % 1e9)
  236. timeval_value.seconds = (nanos - i64(timeval_value.nanoseconds)) / 1e9
  237. ptr = &timeval_value
  238. len = size_of(timeval_value)
  239. case
  240. .Receive_Buffer_Size,
  241. .Send_Buffer_Size:
  242. // TODO: check for out of range values and return .Value_Out_Of_Range?
  243. switch i in value {
  244. case i8, u8: i2 := i; int_value = os.socklen_t((^u8)(&i2)^)
  245. case i16, u16: i2 := i; int_value = os.socklen_t((^u16)(&i2)^)
  246. case i32, u32: i2 := i; int_value = os.socklen_t((^u32)(&i2)^)
  247. case i64, u64: i2 := i; int_value = os.socklen_t((^u64)(&i2)^)
  248. case i128, u128: i2 := i; int_value = os.socklen_t((^u128)(&i2)^)
  249. case int, uint: i2 := i; int_value = os.socklen_t((^uint)(&i2)^)
  250. case:
  251. panic("set_option() value must be an integer here", loc)
  252. }
  253. ptr = &int_value
  254. len = size_of(int_value)
  255. }
  256. skt := any_socket_to_socket(s)
  257. res := os.setsockopt(os.Socket(skt), int(level), int(option), ptr, len)
  258. if res != os.ERROR_NONE {
  259. return Socket_Option_Error(res)
  260. }
  261. return nil
  262. }
  263. @(private)
  264. _set_blocking :: proc(socket: Any_Socket, should_block: bool) -> (err: Network_Error) {
  265. // TODO: Implement
  266. unimplemented()
  267. }
  268. @private
  269. _endpoint_to_sockaddr :: proc(ep: Endpoint) -> (sockaddr: os.SOCKADDR_STORAGE_LH) {
  270. switch a in ep.address {
  271. case IP4_Address:
  272. (^os.sockaddr_in)(&sockaddr)^ = os.sockaddr_in {
  273. sin_port = u16be(ep.port),
  274. sin_addr = transmute(os.in_addr) a,
  275. sin_family = u8(os.AF_INET),
  276. sin_len = size_of(os.sockaddr_in),
  277. }
  278. return
  279. case IP6_Address:
  280. (^os.sockaddr_in6)(&sockaddr)^ = os.sockaddr_in6 {
  281. sin6_port = u16be(ep.port),
  282. sin6_addr = transmute(os.in6_addr) a,
  283. sin6_family = u8(os.AF_INET6),
  284. sin6_len = size_of(os.sockaddr_in6),
  285. }
  286. return
  287. }
  288. unreachable()
  289. }
  290. @private
  291. _sockaddr_to_endpoint :: proc(native_addr: ^os.SOCKADDR_STORAGE_LH) -> (ep: Endpoint) {
  292. switch native_addr.family {
  293. case u8(os.AF_INET):
  294. addr := cast(^os.sockaddr_in) native_addr
  295. port := int(addr.sin_port)
  296. ep = Endpoint {
  297. address = IP4_Address(transmute([4]byte) addr.sin_addr),
  298. port = port,
  299. }
  300. case u8(os.AF_INET6):
  301. addr := cast(^os.sockaddr_in6) native_addr
  302. port := int(addr.sin6_port)
  303. ep = Endpoint {
  304. address = IP6_Address(transmute([8]u16be) addr.sin6_addr),
  305. port = port,
  306. }
  307. case:
  308. panic("native_addr is neither IP4 or IP6 address")
  309. }
  310. return
  311. }