socket_freebsd.odin 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. #+build freebsd
  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 "core:sys/freebsd"
  21. import "core:time"
  22. Fd :: freebsd.Fd
  23. Socket_Option :: enum c.int {
  24. // TODO: Test and implement more socket options.
  25. // DEBUG
  26. Reuse_Address = cast(c.int)freebsd.Socket_Option.REUSEADDR,
  27. Keep_Alive = cast(c.int)freebsd.Socket_Option.KEEPALIVE,
  28. // DONTROUTE
  29. Broadcast = cast(c.int)freebsd.Socket_Option.BROADCAST,
  30. Use_Loopback = cast(c.int)freebsd.Socket_Option.USELOOPBACK,
  31. Linger = cast(c.int)freebsd.Socket_Option.LINGER,
  32. Out_Of_Bounds_Data_Inline = cast(c.int)freebsd.Socket_Option.OOBINLINE,
  33. Reuse_Port = cast(c.int)freebsd.Socket_Option.REUSEPORT,
  34. // TIMESTAMP
  35. No_SIGPIPE_From_EPIPE = cast(c.int)freebsd.Socket_Option.NOSIGPIPE,
  36. // ACCEPTFILTER
  37. // BINTIME
  38. // NO_OFFLOAD
  39. // NO_DDP
  40. Reuse_Port_Load_Balancing = cast(c.int)freebsd.Socket_Option.REUSEPORT_LB,
  41. // RERROR
  42. Send_Buffer_Size = cast(c.int)freebsd.Socket_Option.SNDBUF,
  43. Receive_Buffer_Size = cast(c.int)freebsd.Socket_Option.RCVBUF,
  44. // SNDLOWAT
  45. // RCVLOWAT
  46. Send_Timeout = cast(c.int)freebsd.Socket_Option.SNDTIMEO,
  47. Receive_Timeout = cast(c.int)freebsd.Socket_Option.RCVTIMEO,
  48. }
  49. @(private)
  50. _create_socket :: proc(family: Address_Family, protocol: Socket_Protocol) -> (socket: Any_Socket, err: Network_Error) {
  51. sys_family: freebsd.Protocol_Family = ---
  52. sys_protocol: freebsd.Protocol = ---
  53. sys_socket_type: freebsd.Socket_Type = ---
  54. switch family {
  55. case .IP4: sys_family = .INET
  56. case .IP6: sys_family = .INET6
  57. }
  58. switch protocol {
  59. case .TCP: sys_protocol = .TCP; sys_socket_type = .STREAM
  60. case .UDP: sys_protocol = .UDP; sys_socket_type = .DGRAM
  61. }
  62. new_socket, errno := freebsd.socket(sys_family, sys_socket_type, sys_protocol)
  63. if errno != nil {
  64. err = cast(Create_Socket_Error)errno
  65. return
  66. }
  67. // NOTE(Feoramund): By default, FreeBSD will generate SIGPIPE if an EPIPE
  68. // error is raised during the writing of a socket that may be closed.
  69. // This behavior is unlikely to be expected by general users.
  70. //
  71. // There are two workarounds. One is to apply the .NOSIGNAL flag when using
  72. // the `sendto` syscall. However, that would prevent users of this library
  73. // from re-enabling the SIGPIPE-raising functionality, if they really
  74. // wanted it.
  75. //
  76. // So I have disabled it here with this socket option for all sockets.
  77. truth: b32 = true
  78. errno = freebsd.setsockopt(new_socket, .SOCKET, .NOSIGPIPE, &truth, size_of(truth))
  79. if errno != nil {
  80. err = cast(Socket_Option_Error)errno
  81. return
  82. }
  83. switch protocol {
  84. case .TCP: return cast(TCP_Socket)new_socket, nil
  85. case .UDP: return cast(UDP_Socket)new_socket, nil
  86. }
  87. return
  88. }
  89. @(private)
  90. _dial_tcp_from_endpoint :: proc(endpoint: Endpoint, options := default_tcp_options) -> (socket: TCP_Socket, err: Network_Error) {
  91. if endpoint.port == 0 {
  92. return 0, .Port_Required
  93. }
  94. family := family_from_endpoint(endpoint)
  95. new_socket := create_socket(family, .TCP) or_return
  96. socket = new_socket.(TCP_Socket)
  97. sockaddr := _endpoint_to_sockaddr(endpoint)
  98. errno := freebsd.connect(cast(Fd)socket, &sockaddr, cast(freebsd.socklen_t)sockaddr.len)
  99. if errno != nil {
  100. close(socket)
  101. return {}, cast(Dial_Error)errno
  102. }
  103. return
  104. }
  105. @(private)
  106. _bind :: proc(socket: Any_Socket, ep: Endpoint) -> (err: Network_Error) {
  107. sockaddr := _endpoint_to_sockaddr(ep)
  108. real_socket := any_socket_to_socket(socket)
  109. errno := freebsd.bind(cast(Fd)real_socket, &sockaddr, cast(freebsd.socklen_t)sockaddr.len)
  110. if errno != nil {
  111. err = cast(Bind_Error)errno
  112. }
  113. return
  114. }
  115. @(private)
  116. _listen_tcp :: proc(interface_endpoint: Endpoint, backlog := 1000) -> (socket: TCP_Socket, err: Network_Error) {
  117. family := family_from_endpoint(interface_endpoint)
  118. new_socket := create_socket(family, .TCP) or_return
  119. socket = new_socket.(TCP_Socket)
  120. defer if err != nil { close(socket) }
  121. bind(socket, interface_endpoint) or_return
  122. errno := freebsd.listen(cast(Fd)socket, backlog)
  123. if errno != nil {
  124. err = cast(Listen_Error)errno
  125. return
  126. }
  127. return
  128. }
  129. @(private)
  130. _bound_endpoint :: proc(sock: Any_Socket) -> (ep: Endpoint, err: Network_Error) {
  131. sockaddr: freebsd.Socket_Address_Storage
  132. errno := freebsd.getsockname(cast(Fd)any_socket_to_socket(sock), &sockaddr)
  133. if errno != nil {
  134. err = cast(Listen_Error)errno
  135. return
  136. }
  137. ep = _sockaddr_to_endpoint(&sockaddr)
  138. return
  139. }
  140. @(private)
  141. _accept_tcp :: proc(sock: TCP_Socket, options := default_tcp_options) -> (client: TCP_Socket, source: Endpoint, err: Network_Error) {
  142. sockaddr: freebsd.Socket_Address_Storage
  143. result, errno := freebsd.accept(cast(Fd)sock, &sockaddr)
  144. if errno != nil {
  145. err = cast(Accept_Error)errno
  146. return
  147. }
  148. client = cast(TCP_Socket)result
  149. source = _sockaddr_to_endpoint(&sockaddr)
  150. return
  151. }
  152. @(private)
  153. _close :: proc(socket: Any_Socket) {
  154. real_socket := cast(Fd)any_socket_to_socket(socket)
  155. // TODO: This returns an error number, but the `core:net` interface does not handle it.
  156. _ = freebsd.close(real_socket)
  157. }
  158. @(private)
  159. _recv_tcp :: proc(socket: TCP_Socket, buf: []byte) -> (bytes_read: int, err: Network_Error) {
  160. if len(buf) == 0 {
  161. return
  162. }
  163. result, errno := freebsd.recv(cast(Fd)socket, buf, .NONE)
  164. if errno != nil {
  165. err = cast(TCP_Recv_Error)errno
  166. return
  167. }
  168. return result, nil
  169. }
  170. @(private)
  171. _recv_udp :: proc(socket: UDP_Socket, buf: []byte) -> (bytes_read: int, remote_endpoint: Endpoint, err: Network_Error) {
  172. if len(buf) == 0 {
  173. return
  174. }
  175. from: freebsd.Socket_Address_Storage
  176. result, errno := freebsd.recvfrom(cast(Fd)socket, buf, .NONE, &from)
  177. if errno != nil {
  178. err = cast(UDP_Recv_Error)errno
  179. return
  180. }
  181. return result, _sockaddr_to_endpoint(&from), nil
  182. }
  183. @(private)
  184. _send_tcp :: proc(socket: TCP_Socket, buf: []byte) -> (bytes_written: int, err: Network_Error) {
  185. for bytes_written < len(buf) {
  186. limit := min(int(max(i32)), len(buf) - bytes_written)
  187. remaining := buf[bytes_written:][:limit]
  188. result, errno := freebsd.send(cast(Fd)socket, remaining, .NONE)
  189. if errno != nil {
  190. err = cast(TCP_Send_Error)errno
  191. return
  192. }
  193. bytes_written += result
  194. }
  195. return
  196. }
  197. @(private)
  198. _send_udp :: proc(socket: UDP_Socket, buf: []byte, to: Endpoint) -> (bytes_written: int, err: Network_Error) {
  199. toaddr := _endpoint_to_sockaddr(to)
  200. for bytes_written < len(buf) {
  201. limit := min(int(max(i32)), len(buf) - bytes_written)
  202. remaining := buf[bytes_written:][:limit]
  203. result, errno := freebsd.sendto(cast(Fd)socket, remaining, .NONE, &toaddr)
  204. if errno != nil {
  205. err = cast(UDP_Send_Error)errno
  206. return
  207. }
  208. bytes_written += result
  209. }
  210. return
  211. }
  212. @(private)
  213. _shutdown :: proc(socket: Any_Socket, manner: Shutdown_Manner) -> (err: Network_Error) {
  214. real_socket := cast(Fd)any_socket_to_socket(socket)
  215. errno := freebsd.shutdown(real_socket, cast(freebsd.Shutdown_Method)manner)
  216. if errno != nil {
  217. return cast(Shutdown_Error)errno
  218. }
  219. return
  220. }
  221. @(private)
  222. _set_option :: proc(socket: Any_Socket, option: Socket_Option, value: any, loc := #caller_location) -> Network_Error {
  223. // NOTE(Feoramund): I found that FreeBSD, like Linux, requires at least 32
  224. // bits for a boolean socket option value. Nothing less will work.
  225. bool_value: b32
  226. // TODO: Assuming no larger than i32, but the system may accept i64.
  227. int_value: i32
  228. timeval_value: freebsd.timeval
  229. ptr: rawptr
  230. len: freebsd.socklen_t
  231. switch option {
  232. case
  233. .Reuse_Address,
  234. .Keep_Alive,
  235. .Broadcast,
  236. .Use_Loopback,
  237. .Out_Of_Bounds_Data_Inline,
  238. .Reuse_Port,
  239. .No_SIGPIPE_From_EPIPE,
  240. .Reuse_Port_Load_Balancing:
  241. switch real in value {
  242. case bool: bool_value = cast(b32)real
  243. case b8: bool_value = cast(b32)real
  244. case b16: bool_value = cast(b32)real
  245. case b32: bool_value = real
  246. case b64: bool_value = cast(b32)real
  247. case:
  248. panic("set_option() value must be a boolean here", loc)
  249. }
  250. ptr = &bool_value
  251. len = size_of(bool_value)
  252. case
  253. .Linger,
  254. .Send_Timeout,
  255. .Receive_Timeout:
  256. t, ok := value.(time.Duration)
  257. if !ok {
  258. panic("set_option() value must be a time.Duration here", loc)
  259. }
  260. micros := cast(freebsd.time_t)time.duration_microseconds(t)
  261. timeval_value.usec = cast(freebsd.suseconds_t)micros % 1e6
  262. timeval_value.sec = (micros - cast(freebsd.time_t)timeval_value.usec) / 1e6
  263. ptr = &timeval_value
  264. len = size_of(timeval_value)
  265. case
  266. .Receive_Buffer_Size,
  267. .Send_Buffer_Size:
  268. switch real in value {
  269. case i8: int_value = cast(i32)real
  270. case u8: int_value = cast(i32)real
  271. case i16: int_value = cast(i32)real
  272. case u16: int_value = cast(i32)real
  273. case i32: int_value = real
  274. case u32:
  275. if real > u32(max(i32)) { return .Value_Out_Of_Range }
  276. int_value = cast(i32)real
  277. case i64:
  278. if real > i64(max(i32)) || real < i64(min(i32)) { return .Value_Out_Of_Range }
  279. int_value = cast(i32)real
  280. case u64:
  281. if real > u64(max(i32)) { return .Value_Out_Of_Range }
  282. int_value = cast(i32)real
  283. case i128:
  284. if real > i128(max(i32)) || real < i128(min(i32)) { return .Value_Out_Of_Range }
  285. int_value = cast(i32)real
  286. case u128:
  287. if real > u128(max(i32)) { return .Value_Out_Of_Range }
  288. int_value = cast(i32)real
  289. case int:
  290. if real > int(max(i32)) || real < int(min(i32)) { return .Value_Out_Of_Range }
  291. int_value = cast(i32)real
  292. case uint:
  293. if real > uint(max(i32)) { return .Value_Out_Of_Range }
  294. int_value = cast(i32)real
  295. case:
  296. panic("set_option() value must be an integer here", loc)
  297. }
  298. ptr = &int_value
  299. len = size_of(int_value)
  300. case:
  301. unimplemented("set_option() option not yet implemented", loc)
  302. }
  303. real_socket := any_socket_to_socket(socket)
  304. errno := freebsd.setsockopt(cast(Fd)real_socket, .SOCKET, cast(freebsd.Socket_Option)option, ptr, len)
  305. if errno != nil {
  306. return cast(Socket_Option_Error)errno
  307. }
  308. return nil
  309. }
  310. @(private)
  311. _set_blocking :: proc(socket: Any_Socket, should_block: bool) -> (err: Network_Error) {
  312. real_socket := any_socket_to_socket(socket)
  313. flags, errno := freebsd.fcntl_getfl(cast(freebsd.Fd)real_socket)
  314. if errno != nil {
  315. return cast(Set_Blocking_Error)errno
  316. }
  317. if should_block {
  318. flags &= ~{ .NONBLOCK }
  319. } else {
  320. flags |= { .NONBLOCK }
  321. }
  322. errno = freebsd.fcntl_setfl(cast(freebsd.Fd)real_socket, flags)
  323. if errno != nil {
  324. return cast(Set_Blocking_Error)errno
  325. }
  326. return
  327. }
  328. @(private)
  329. _endpoint_to_sockaddr :: proc(ep: Endpoint) -> (sockaddr: freebsd.Socket_Address_Storage) {
  330. switch addr in ep.address {
  331. case IP4_Address:
  332. (cast(^freebsd.Socket_Address_Internet)(&sockaddr))^ = {
  333. len = size_of(freebsd.Socket_Address_Internet),
  334. family = .INET,
  335. port = cast(freebsd.in_port_t)ep.port,
  336. addr = transmute(freebsd.IP4_Address)addr,
  337. }
  338. case IP6_Address:
  339. (cast(^freebsd.Socket_Address_Internet6)(&sockaddr))^ = {
  340. len = size_of(freebsd.Socket_Address_Internet),
  341. family = .INET6,
  342. port = cast(freebsd.in_port_t)ep.port,
  343. addr = transmute(freebsd.IP6_Address)addr,
  344. }
  345. }
  346. return
  347. }
  348. @(private)
  349. _sockaddr_to_endpoint :: proc(native_addr: ^freebsd.Socket_Address_Storage) -> (ep: Endpoint) {
  350. #partial switch native_addr.family {
  351. case .INET:
  352. addr := cast(^freebsd.Socket_Address_Internet)native_addr
  353. ep = {
  354. address = cast(IP4_Address)addr.addr.addr8,
  355. port = cast(int)addr.port,
  356. }
  357. case .INET6:
  358. addr := cast(^freebsd.Socket_Address_Internet6)native_addr
  359. ep = {
  360. address = cast(IP6_Address)addr.addr.addr16,
  361. port = cast(int)addr.port,
  362. }
  363. case:
  364. panic("native_addr is neither an IP4 or IP6 address")
  365. }
  366. return
  367. }