socket_darwin.odin 11 KB

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